class NimController < ApplicationController def first_time session[:sticks]=nil session[:computer_choice]=nil session[:user_choice]=nil session[:state]= :starting what_next end def get_sticks session[:sticks] ||= 7 + rand(10) # logger.info("#{session[:sticks]} left") session[:sticks] end def start_choices %w{1 2 3} end def extras logger.info "session in nim #{session.inspect}" case session[:state] when :computer_won session[:state]=:starting @displayed=translate( 'you lost. the computer and you take turns '+ 'to pick 1,2 or 3 sticks. If you pick the'+ ' last stick, you lose') when :user_won session[:state]=:starting passstring= 'you won! Click smiley to play again' @displayed=translate(passstring) when :starting session[:state]= :playing passstring= 'welcome to the game of Nim' @displayed=translate(passstring) session[:sticks]=nil when :playing passstring1 = 'you took' passstring2 = 'I took' @returned1 = translate(passstring1) @returned2 = translate(passstring2) @displayed= (session[:user_choice]? @returned1 + "#{session[:user_choice]}. ": '')+ (session[:computer_choice]? @returned2 + "#{session[:computer_choice]}": '') else passstring= 'should not happen' @displayed=translate(passstring) end @sticks=get_sticks passstring = 'sticks left' @returned = translate(passstring) logger.info @returned.inspect @title="#{@sticks} " + @returned # session.delete # session[:displayed]=nil # if @sticks <= 0 #for new game to start # session[:sticks]=nil # end end def selected(user_choice) if (s = get_sticks) == 0 session[:state]=:starting session[:sticks]=nil else u = user_choice.to_i if u <= s #we have a legal move logger.info "move: #{s} - #{u} sticks" session[:user_choice]=u s -= u session[:sticks]=s if s <= 0 #computer has won logger.info "c won" session[:state]= :computer_won else #computer makes move c= (s-1) % 4 #since 1,5,9,.. is a series of losing positions, #we try to get the opponent to one of them if c == 0 #we are losing, #because sticks=4n+1, a losing position c = 1+ rand(3) #doesn't matter what we pick here, long as it #isn't more than the sticks available. end if c > s c=s end session[:sticks] = s-c session[:computer_choice]=c if session[:sticks] == 0 #user has won session[:state] = :user_won # session[:choices]=[] end end end end nil end def backspace what_next "first_time" end end