【问题标题】:Blackjack style python (computer) game looping incorrectly二十一点风格的python(计算机)游戏循环不正确
【发布时间】:2013-12-27 04:27:11
【问题描述】:

我遇到的主要问题是当我在hand_one 上选择stay,然后在hand_two 上选择hit 时会发生什么。

当我已经选择留在 hand_one 上时,它没有让我再次在 hand_two 上联系 hit or stay,而是让我回到 hit or stay hand_one所以 hand_one 应该没有更多选择强>。这会导致出现多个打印语句和不正确的游戏玩法的问题。

我的代码有什么问题,就像导致它循环回hand_one
完整代码在这里:http://labs.codecademy.com/Bjaf/2#:workspace

这是可能导致问题的部分。

def hit_or_stay(person):
    hit_or_stay = raw_input("Do you want to hit or stay? You can type h or s.")
    if hit_or_stay == 'h' or hit_or_stay == 'hit':
        deal_one_card(person)
        value_of_current_cards(person)
        number_value_of_hand()
    elif hit_or_stay == 's'or hit_or_stay == 'stay':
        print "You stayed"
        return
    else:
        hit_or_stay(person)

def number_value_of_hand():
    if number_of_hands > 0:
        value_of_hand_one = value_of_current_cards(hand_one)
        if value_of_hand_one < 18:
            print "\n" "You have %i" % (value_of_hand_one)
            hit_or_stay(hand_one)
        elif value_of_hand_one > 18:
            print "You Lose"
            return
        elif value_of_hand_one == 18:
            print "You hit HOT 18!!!"
            return
        if number_of_hands > 1:
            value_of_hand_two = value_of_current_cards(hand_two)
            if value_of_hand_two < 18:
                print "\n" "Your second hand has %i" % (value_of_hand_two)
                hit_or_stay(hand_two)
            elif value_of_hand_two > 18:
                print "You Lose"
                return
            elif value_of_hand_two == 18:
                print "You hit HOT 18!!!"
                return

number_value_of_hand()

谁能明白为什么它会循环返回给 hand_one 另一个选项?可能我该如何解决?非常感谢!

【问题讨论】:

  • hit_or_stay 调用 number_value_of_hand,它将执行行放回到 number_value_of_hand 的开头。
  • 这似乎是一个在类中更容易实现的经典代码示例
  • 在 hit_or_call 函数中。为hand1\hand2 添加一个参数。将其传回 number_value_of_hand 并使用它来检查继续使用哪只手。
  • 你在哪里定义手数?如果您有一个定义手数及其初始值的方法,那么最好在其中调用这两个方法,并将更新的值传回给它。这会将每只手的值视为伪全局并且更容易循环。另外,请包含 deal_one_card() 和 value_of_current_cards() 方法

标签: python if-statement blackjack


【解决方案1】:

你的问题出现在这一步:

hit_or_stay(hand_two)

当您点击 hand_two 时,您的代码会执行以下操作:

deal_one_card(person)
value_of_current_cards(person)
number_value_of_hand()

问题就在这里,因为number_value_of_hand() 将您带回到该函数的开头,并再次检查hand_one 选项。

您可能必须重写 number_value_of_hand() 函数以包含一个参数,告诉它从哪里开始(hand_one、hand_two 等)

我可能会做一个list 的手,然后遍历列表。然后,你可以打电话给number_of_hands(hands[i]) 来参与i

【讨论】:

    猜你喜欢
    • 2015-06-18
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2012-09-21
    • 2021-04-25
    • 1970-01-01
    • 2023-03-21
    • 2020-05-18
    相关资源
    最近更新 更多