我是 Ruby 的新手,几周前才开始。我正在尝试创建一个模拟游戏玩法的算法,但我陷入了无限循环。我的控制流出了点问题,我只是没有看到。现在,我没有为战争部分添加循环,只是试图将卡片从数组的末尾取出并放回开头。另外,请注意,我不使用 .shuffle!因为我们被告知不要这样做。这是我的算法课的一部分。另外,我没有作弊,我们被告知要使用 Stack Overflow 和其他资源。
有人可以帮助我了解我哪里出错了吗?谢谢!
deck = (2..14).to_a*4
deck.sort! {|a, b| rand <=> rand}
player1 = deck.values_at(0..25)
player2 = deck.values_at(26..51)
print "Player 1's cards: #{player1}"
print "Player 2's cards: #{player2}"
hand_count = 0
until player1.count == 52 || player2.count == 52
hand_count += 1
state = player1[-1] <=> player2[-1]
if state == -1
player2.unshift(player2.pop)
player2.unshift(player1.pop)
puts "Player 2 won hand #{hand_count}"
elsif state == 1
player1.unshift(player1.pop)
player1.unshift(player2.pop)
puts "Player 1 won hand #{hand_count}"
else
player2.unshift(player2.pop)
player1.unshift(player1.pop)
puts "It's a tie"
end
end
puts "Player 1 wins" if player1.length == 52
puts "Player 2 wins" if player2.length == 52