thirteen-tien-len/app/controllers/games_controller.rb

89 lines
1.6 KiB
Ruby

class GamesController < ApplicationController
before_action :set_game, only: [:show, :edit, :update, :destroy]
respond_to :html
def index
@games = Game.all
respond_with(@games)
end
def show
respond_with(@game)
end
def new
@game = Game.new
respond_with(@game)
end
def edit
end
def create
@game = Game.new(title: game_params[:title])
if game_params[:player_ids]
game_params[:player_ids].each do |user_id|
@game.players.new(user_id: user_id)
end
end
@game.save
respond_with(@game)
end
def update
@game.update(game_params)
respond_with(@game)
end
def destroy
@game.destroy
respond_with(@game)
end
def join
@game = Game.find(params[:game_id])
@game.add_player_from_user(current_user)
flash[:notice] = "Successfully joined game..."
redirect_to(@game)
end
def start
@game = Game.find(params[:game_id])
# If game is already started, simply return
if @game.status == 'Game Started'
flash[:notice] = "Game already started..."
return redirect_to(@game)
end
@game.status = 'Game Started' if @game.startable?
@game.save
# Create a deck
d = Deck.new
# Shuffle the deck
d.cards.shuffle!
# Deal the cards
@game.players.each do |player|
13.times do
card = d.cards.shift
player.player_cards.new(card.instance_values)
end
player.save
end
redirect_to(@game)
end
private
def set_game
@game = Game.find(params[:id])
end
def game_params
params.require(:game).permit(:title, player_ids: [])
end
end