Skip to content

Instantly share code, notes, and snippets.

@AlexTalker
Created August 4, 2014 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexTalker/b13e2000e272a34d5208 to your computer and use it in GitHub Desktop.
Save AlexTalker/b13e2000e272a34d5208 to your computer and use it in GitHub Desktop.
class GamesController < ApplicationController
Vertical = 'v'
Horizontal = 'h'
def new
@game = Game.new
@game.field = new_field
@player = auth
@game.vscore = 0 # default scores
@game.hscore = 0
@game.way = Vertical
@game.range = 0
if @game.valid? and @game.save
redirect_to game_path(@game)
else
redirect_to "/404.html"
end
end
def show
@game = Game.find(params[:id])
@length = Math.sqrt(@game.field.length).to_i
@player = auth
@cells = cells_availble
case @player
when :Vertical
@user = "a player by vertical"
if @game.way == Vertical
flash[:status] = "Make you move!"
else
flash[:status] = "Wait move player by horizontal!"
end
when :Horizontal
@user = "a player by horizontal"
if @game.way == Horizontal
flash[:status] = "Make you move!"
else
flash[:status] = "Wait move player by vertical!"
end
else
@user = "a spectator"
end
end
def move
@game = Game.find(params[:id])
@player = auth
@cells = cells_availble
n = params[:n]
if n >= 0 and @cells.member? n
value = @game.field[n].to_i
case @player
when :Vertical
@game.vscore = @game.vscore + value
when :Horizontal
@game.hscore = @game.hscore + value
else
@game.field[n] = 0
flash[:save_error] = "Can't save your move!" unless @game.save
end
end
end
private
def new_field
return Array.new(64).map{ rand(1..8) }.join
end
def auth
if session[:client].nil? or session[:client].length != 32
session[:client] = SecureRandom.hex(16)
end
if @game.vplayer.nil?
@game.vplayer = session[:client]
elsif @game.hplayer.nil?
if session[:client] != @game.vplayer
@game.hplayer = session[:client]
@game.save
end
end
case session[:client]
when @game.vplayer
return :Vertical
when @game.hplayer
return :Horizontal
else
return :Spectator
end
end
def cells_availble
if @player == :Vertical and @game.way == Vertical
(@game.range..@game.field.length).step @length
elsif @player == :Horizontal and @game.way == Horizontal
i = @length*@game.range
i..(i+@length)
else
-1..-1
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment