【发布时间】:2020-06-14 09:18:50
【问题描述】:
我正在尝试添加两个功能:第一个是当玩家按下 x 时,它会显示分数,第二个是当玩家按下 q 时退出游戏。
我想将x => ':SCORE' 添加到ENTRY_TO_SYM 哈希中,但是当玩家按下x 时,我不希望计算机选择某些内容。
ENTRY_TO_SYM = { 'p'=>:PAPER, 'r'=>:ROCK, 's'=>:SCISSORS, 'x' => :SCORE , 'q' => :QUIT}
VALID_ENTRIES = ENTRY_TO_SYM.keys
COMPUTER_CHOICES = ENTRY_TO_SYM.values
# WINNERS and LOSERS from the player's perspective, the first value of each
# pair being the player's choice, the second, the computer's choice.
WINNERS = [[:SCISSORS, :PAPER], [:PAPER, :ROCK], [:ROCK, :SCISSORS]]
LOSERS = WINNERS.map { |i,j| [j,i] }
class RockPaperScissors
def initialize
@player_score = @computer_score = @ties = 0
end
def play(winning_score)
while @player_score < winning_score && @computer_score < winning_score
puts "Player score: #{@player_score}, " +
"Computer score: #{@computer_score}, Ties: #{@ties}"
player = player_choice
computer = COMPUTER_CHOICES.sample
puts "\nPlayer chooses #{player.to_s}"
puts "Computer chooses #{computer.to_s}"
case player_outcome [player, computer]
when :WIN
puts "#{player.to_s} beats #{computer.to_s}, player wins the round"
@player_score += 1
when :LOSE
puts "#{computer.to_s} beats #{player.to_s}, computer wins the round"
@computer_score += 1
else
puts "Tie, choose again"
@ties += 1
end
end
puts "\nFinal score: player: #{@player_score}, " +
"computer: #{@computer_score} (ties: #{@ties})"
puts (@player_score == 2) ? "Player wins!" : "Yea! Computer wins!"
end
private
def player_choice
loop do
print "Choose rock (r), paper (p) or scissors (s) || OPTION choose (x) if you want to display the score and (q) to quit the game : "
choice = gets.chomp.downcase
return ENTRY_TO_SYM[choice] if ENTRY_TO_SYM.key?(choice)
puts "That entry is invalid. Please re-enter"
end
end
def player_outcome(plays)
return :WIN if WINNERS.include?(plays)
return :LOSE if LOSERS.include?(plays)
:TIE
end
end
RockPaperScissors.new.play(3)
【问题讨论】:
-
考虑写
WINNERS = { 's'=>'p', 'p'=>'r', 'r'=>'s' }。那么如果变量player和computer各有'r'、'p'或's',则如果WINNERS[player] == computer #=> true,则玩家获胜,如果WINNERS[computer] == player #=> true,则计算机获胜;否则他们会再次抛出。你看到这如何简化你的问题吗?您不需要符号:ROCK、:PAPER和:SCISSORS。 -
我很困惑,您是否将ruby-on-rails 与sinatra 结合使用?您的问题与这两者有何关系?
标签: ruby-on-rails ruby sinatra