我正在学习Ruby和Sinatra的指南,让我为纸牌游戏编写以下代码(基于Play Your Cards Right)。
这是代码
enable :sessions
get '/' do
session[:deck] = []
suits = %w[ Hearts Diamonds Clubs Spades ]
values = %w[ Ace 2 3 4 5 6 7 8 9 10 Jack Queen King ]
suits.each do |suit|
values.each do |value|
session[:deck] << "#{value} of #{suit}"
end
end
session[:deck].shuffle!
session[:guesses] = -1
redirect to('/play')
end
get '/:guess' do
card = session[:deck].pop
value = case card[0]
when "J" then 11
when "Q" then 12
when "K" then 13
else card.to_i
end
if (params[:guess] == 'higher' and value < session[:value]) or (params[:guess] == 'lower' and value > session[:value])
"Game Over! The card was the #{card} (value #{value}), and you had #{session[:value]}. You managed to make #{session[:guesses]} correct guess#{'es' unless session[:guesses] == 1}. <a href='/'>Play Again</a>"
else
session[:guesses] += 1
session[:value] = value
"The card is the #{card} (value of #{value}). Do you think the next card will be <a href='/higher'>Higher</a> or <a href='/lower'>Lower</a>?"
end
end
游戏似乎在某些时候玩得很好,但是,出于某种原因,会话变量value
似乎在IF语句执行之前被新值覆盖。
我不知道上面的代码可能出现什么问题,以及value
会话变量为什么不随意更改为新值。
请查看我的代码(或尝试自己运行代码)并告诉我可能出现的问题。
我的config.ru
文件:
require 'rubygems'
require 'sinatra'
set :environment, ENV['RACK_ENV'].to_sym
disable :run, :reload
require './play_your_cards_right.rb'
run Sinatra::Application