class GameController < ApplicationController
def index
@games = Game.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @games }
end
end
def start_game
session[:round] = 1
session[:points] = 0
@round = session[:round]
@points = session[:points]
end
def next_round
@round += 1
@points += 1200
end
def game_over
puts "Game Over."
end
def highscore
puts "Leaderboard action here."
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
start_game
generate_round
puts @points
puts @round
if session[:addition]
if not session[:addition].index(params[:guess].to_i).nil?
puts "Correct."
next_round
else
game_over
puts "Wrong anwser."
highscore
end
end
session[:addition] = @addition
respond_to do |format|
format.html
end
end
end
Hey guys, So Im trying to build a simple game in rails. Its premise is to add all the numbers up in your memory and type in the highest sum you can within a predefined time limit. Right now I able to generate the numbers and check for correct answers, however I don`t know how to loop the method in a way that points are added after each successful round.
I`m assuming the problem is that for each instance of "new" it sets the start_game开发者_如何学C method again, thus zeroing the points and round again?
You are correct, every time you hit the 'new' action it will start your game over again. You could do something like below to get it to keep over multiple requests to 'new'
def start_game
session[:round] ||= 1
session[:points] ||= 0
@round = session[:round]
@points = session[:points]
end
def game_over
session[:round] = nil
session[:points] = nil
puts "Game Over."
end
精彩评论