0

我是 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
4

1 回答 1

1

我认为问题在于,如果玩家 1 和玩家 2 都拥有一张价值为“12”的牌,那么另一个人永远不会达到 52。

12's 将被放回每个玩家的牌组中。当出现平局时,一名球员需要获胜。

更新

这是一个工作示例

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
        player1_war_cars = player1.pop(3)
        player2_war_cars = player2.pop(3)

        if player1_war_cars.first < player2_war_cars.first
            player1.unshift(player1_war_cars)
            player1.unshift(player2_war_cars)

            player1 = player1.flatten
            puts "Player 2 won hand #{hand_count}"
        elsif player1_war_cars.first > player2_war_cars.first
            player2.unshift(player1_war_cars)
            player2.unshift(player2_war_cars)

            player2 = player2.flatten
            puts "Player 1 won hand #{hand_count}"
        else
            player1.unshift(player1_war_cars)
            player2.unshift(player2_war_cars)

            player1 = player1.flatten
            player2 = player2.flatten
            puts "It's a tie"
        end
     end
 end


puts "Player 1 wins" if player1.length == 52
puts "Player 2 wins" if player2.length == 52
于 2014-05-04T06:24:51.827 回答