如果我重复其他人之前的要求,请道歉。我已经在 stackoverflow 上完成了其他 RSP 游戏问题。大多数是关于播放器与计算机的。可能我需要阅读更多理论以更好地理解并修改代码以适合我的目的,即玩家一与玩家二。
我正在尝试玩家一与玩家二 - Ruby 中的石头剪刀和纸游戏。我对以下代码有以下疑问。- 如何隐藏每个玩家条目?- 代码中有很多重复,因此违反了 DRY 原则。我应该如何重构这个?- 类方法是玩这个游戏的最好方法吗(最有效)?- 目前,此游戏仅适用于石头剪刀布。如果我想稍后添加蜥蜴 spock,我应该如何证明这一点?或以最有效的方式添加它?提前致谢!
options = ["rock", "scissors", "paper"]
while true
print <<TEXT
1 - rock
2 - scissors
3 - paper
9 - end game
TEXT
puts "Player 1, choose rock(1), scissors(2), paper(3). To end the game, enter 9."
player1_val = gets.to_i
puts "Player 2, choose rock(1), scissors(2), paper(3). To end the game, enter 9."
player2_val = gets.to_i
if player1_val == 9 # I am repeating the same condition for player2. How should I combine?
puts "End"
exit
end
if player2_val == 9
puts "End"
exit
end
player1 = options[player1_val-1]
player2 = options[player2_val-1]
if player1 == player2
puts "Tie, next throw please"
redo
end
if player1 == 1 and player2 == 2
puts "Rock blunts scissors, you win"
elsif player1 == 2 and player2 == 1
puts "Rock blunts scissors, you loose"
elsif player1 == 2 and player2 == 3
puts "Scissors cut paper, you win"
elsif player1 == 3 and player2 == 2
puts "Scissors cut paper, you loose"
elsif player1 == 3 and player2 == 1
puts "Paper covers rock, you win"
elsif player1 == 1 and player2 == 3
puts "Paper covers rock, you loose"
end
end