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

133 lines
2.8 KiB
Ruby

class GamesController < ApplicationController
before_action :set_game, only: [:show, :edit, :update, :destroy, :play_hand]
respond_to :html, :json
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 play_hand
# TODO: validate player's turn, current_user == @game.current_player.user
# TODO: move this logic out of controller maybe to model(s)
if params[:game]
if params[:game][:hand_type] == 'pass'
@game.set_active_player 'next'
flash[:notice] = 'Successfully passed.'
@game.save
end
end
# If cards are played
if params[:player_card_ids]
@cards_to_play = @game.current_player.player_cards.order(:value).find(params[:player_card_ids])
# Instantiate the play
@play = @game.current_player.plays.new
@play.game_id = @game.id
@play.player_cards << @cards_to_play
if @play.save
# TODO: Ensure active player only changes when valid hand is played
@game.set_active_player 'next'
@game.save
else
# If play is invalid, remove the cards from the play
#@play.player_cards.map {|card| card.play_id = nil; card.save}
# Delete play
#@play.destroy
end
#@play.save
@play.errors.messages.each do |key, msg|
flash[key] = msg.join
end
else
# No cards are played
@cards_to_play = []
end
#@cards_to_play.each do |card|
#@play.player_cards << card
#end
redirect_to(@game)
# TODO: add current_hand logic
# @hand > @game.hand_to_beat
#redirect_to @game
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])
begin
@game.start
rescue StandardError => e
@game.errors.messages.each do |key, msg|
flash[key] = msg.join
end
redirect_to(@game)
return
end
flash[:notice] = 'Game started.'
redirect_to(@game)
end
def my_inventory
@game = Game.find(params[:game_id])
@player = @game.players.find_by(user_id: current_user.id)
end
private
def set_game
@game = Game.find(params[:id])
end
def game_params
params.require(:game).permit(:title, player_ids: [])
end
end