What's wrong with this loop?
class GameController < ApplicationController
def index
@games = Game.all
respond_to do |format|
format.html
end
end
def start_game
session[:round] ||= 1
session[:points] ||= 0
@round = session[:round]
@points = session[:points]
end
def next_round
session[:round] += 1
session[:points] += 1200
@round = session[:round]
@points = session[:points]
end
def generate_round
numbers = Array.new(6){rand(9)}
@addition = []
@display = numbers
numbers.inject do |s, i|
@addition << s + i
@addition.last
end
end
def new
if @round == nil
start_game
generate_round
else
generate_round
end
if session[:addition]
if not session[:addition].index(params[:guess].to_i).nil?
puts "Correct."
next_round
else
puts 'Game over.'
end
end
session[:addition] = @addition
respond_to do |format|
format.html
end
end
end
Hey guys, I`m trying to put together this mini game in ruby that depends on guessing numbers. After ev开发者_开发百科ery guess points are added and the level is increased by one.
However with the current code, I`m getting stuck at round 2. Most likely something is resetting those variables for some reason but I can seem to pin point what it is.
Would be grateful for any kind of help.
::Edit::
Code updated. Problem solved! Thanks for the help @blackbird07, @robertodecurnex and @fl00r!
Controller is stateless so of course all variables are reseted each time you call it.
You should use some datastorage (database, filesystem) to store your current state.
And another your problem is that all this code shouldn't belong to controller at all.
You do not increase the counters for session[:round] and session[:points] in your next_round action. Do this and it should work.
session[:round] += 1
session[:points] += 1200
@round = session[:round]
@points = session[:points]
Since you are keeping the round on the session you should use the session value instead of the instance variable or at least create a filter to set this variable on every request.
Using the filter:
before_filter :set_round
private
def set_round
@round = session[:round]
end
The new method (action) is making the following:
if @round = 0 then
It's assigning 0
to @round
instead of compare it.
Try if @round == 0
or just if @round.zero?
You will need also to increase the session value and not just the @round
variable one.
Remember:
= #=> Assignation
== #=> Equality, usually overwritten by the classes to return true base on the equality of the state/attributes of two objects.
=== #=> Equality, usually defined to compare the identity of two objects (to return true only if both objects are actually the same object).
精彩评论