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

140 lines
3.1 KiB
Ruby

class GamesController < ApplicationController
before_action :set_game, only: [:show, :edit, :update, :destroy, :play_hand, :join, :start, :my_inventory]
respond_to :html, :json
def index
@games = Game.all.order :id
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: move this logic out of controller maybe to model(s) ?
# validate player's turn
if current_user.soft_token == @game.controlling_player.soft_token
# Player action: pass
# TODO: wtf do we need game params for? And why nest hand_type in it?
if params[:game]
if params[:game][:hand_type] == 'pass'
@game.set_controlling_player 'next'
flash[:notice] = 'Successfully passed.'
@game.save
end
end
# Player action: play_hand
if params[:player_card_ids]
@cards_to_play = @game.controlling_player.try(:player_cards).order(:value).find(params[:player_card_ids])
# Instantiate the play
@play = @game.controlling_player.plays.new
@play.game_id = @game.id
@play.player_cards << @cards_to_play
if @play.save
@game.set_controlling_player 'next'
@game.save
else
# TODO: Does anything need to happen here?
#
# 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.errors.messages.each do |key, msg|
flash[key] = msg.join
end
else
# No cards are played
@cards_to_play = []
end
else
flash[:notice] = 'It is not your turn.'
end
respond_to do |format|
format.html { redirect_to(@game) }
## TODO: Return status message of attempt to play_hand
format.json { render json: @game }
end
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 play_now
# First joinable game or create new game
@game = Game.play_now(current_user)
@game.add_player_from_user current_user
redirect_to @game
end
def join
@game.add_player_from_user(current_user)
flash[:notice] = 'Successfully joined game...'
redirect_to(@game)
end
def start
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
@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