【问题标题】:Ending a while loop结束一个while循环
【发布时间】:2019-03-15 17:52:18
【问题描述】:

我目前正在用 Python 3.6 为骰子游戏编写代码,我知道我的代码在这方面有点偏离,但是,我真的只是想知道如何开始我的 while 循环。游戏说明如下...

  • 人类玩家与计算机对战。

  • 玩家 1 掷骰,直到他们获胜、决定保住或掷出 1。玩家 2 也是如此。

  • 他们轮流掷两个骰子,骰子的总数相加,除非掷出 1。

  • 如果掷出一个 1,则不会增加分数,轮到下一个人。如果掷出两个 1,您将失去所有分数,轮到下一个人。

  • 第一个达到 100 分的玩家获胜。

我的游戏运行良好,直到玩家 1 和玩家 2 都按“y”来保持背靠背。然后游戏退出玩家之间的切换,直到“n”再次被击中。知道为什么吗? 有人告诉我我需要变量来决定轮到谁,但我不确定如何将它们合并到我的代码中。 任何帮助将不胜感激。

import random
def main():

    print("Welcome to the Two Dice Pig Game. You are Player 1!")

    Player1 = 0
    Player2 = 0

    while(Player1<100 and Player2<100):

        p1dice=random.randrange(1,7)
        p1dice2=random.randrange(1,7)
        Player1+=p1dice+p1dice2
        print("Player 1 dice 1 =",p1dice)
        print("Player 1 dice 2 =",p1dice2)
        print("Player 1 dice total =",Player1)
        print("Does player 1 want to hold?")
        choose1 = input("Enter y for yes or n for no.")
        if(choose1=="n"):
            p1dice=random.randrange(1,7)
            p1dice2=random.randrange(1,7)
            Player1+=p1dice+p1dice2
            print("Player 1 dice 1 =",p1dice)
            print("Player 1 dice 2 =",p1dice2)
            print("Player 1 dice total =",Player1)
            if(Player1>=100):
                print("Player 1 wins!")
            else:
                print("Does player 1 want to hold?")
                choose1 = input("Enter y for yes or n for no.")
        while(choose1=="y"):

            print("It's player 2's turn.")
            p2dice=random.randrange(1,7)
            p2dice2=random.randrange(1,7)
            Player2+=p2dice+p2dice2
            print("Player 2 dice 2 =",p2dice)
            print("Player 2 dice 2 =",p2dice2)
            print("Player 2 dice total =",Player2)
            print("Does player 2 want to hold?")
            choose2 = input("Enter y for yes or n for no.")
            while(choose2=="n"):
                p2dice=random.randrange(1,7)
                p2dice2=random.randrange(1,7)
                Player2+=p2dice+p2dice2
                print("Player 2 dice 2 =",p2dice)
                print("Player 2 dice 2 =",p2dice2)
                print("Player 2 dice total =",Player2)
                print("Does player 2 want to hold?")
                choose2 = input("Enter y for yes or n for no.")
            while(choose2=="y"):
                print("It's player 1's turn.")
                p1dice=random.randrange(1,7)
                p1dice2=random.randrange(1,7)
                Player1+=p1dice+p1dice2
                print("Player 1 dice 2 =",p1dice)
                print("Player 1 dice 2 =",p1dice2)
                print("Player 1 dice total =",Player1)
                print("Does player 1 want to hold?")
                choose2 = input("Enter y for yes or n for no.")

main()

【问题讨论】:

  • 一旦进入while(choose1=="y") 循环,choose1 将无法改变,因此它永远不会退出该循环。您可能想尝试修复这部分逻辑,看看是否还有问题。

标签: python while-loop


【解决方案1】:

您可能希望通过执行以下操作来简化代码:

# Keep track of whose turn it is
player = 1

# Keep a dictionary of scores for each player (1 or 2)
scores = {1: 0, 2: 0}
choice = 'n'

# While neither player has > 100
while max(d.values()) < 100:

    # Roll until current player decides to keep roll
    while choice == 'n':
        print('Player', player, 'turn')
        roll = random.randrange(1,7) + random.randrange(1,7)
        print('You rolled', roll)
        choice = input('Keep roll? y/n')

    # Increment that player's score
    scores[player] += roll
    choice = 'n'

    # Change to other player
    player = (player % 2) + 1

【讨论】:

    【解决方案2】:

    因为一旦您为choose1 设置了一个选项,它就再也不会被设置了。解决此问题的快速方法是在 choose2 的两个 while 循环之后添加一个输入,尽管您可能希望通过为通用逻辑创建函数来使代码更整洁

    while(choose2=="y"):
         ....
    choose1 = input("Enter y for yes or n for no.")
    

    【讨论】:

      【解决方案3】:

      使用字典来记录每个玩家姓名的分数,切换turn 来保存当前投掷骰子的玩家。

      实现了一些逻辑,例如何时将turn 从一个更改为另一个:

      import random
      
      def score(players):
          for k in players:
              print("{} has {} points".format(k,players[k]))
      
      def hold(player):
          if input("Does {} want to hold? [y or anything]".format(player)).lower().strip() == "y":
              return "y"
          return "n"
      
      
      def main():
      
          dice = range(1,7)
          players = {"p1":0, "p2":0}
          turn = ""
          change_player = "y"
      
          print("Welcome to the Two Dice Pig Game. You are Player 1!")
      
          while all(x < 100 for x in players.values()):
              # initially changePlayer is 
              if change_player == "y":
                  # print both scores on player changed
                  score(players)
                  turn = "p1" if turn != "p1" else "p2"
      
              dice1, dice2 = random.choices(dice,k=2)
              print("{} threw {} and {} for a total of {}".format(turn,d1,d2,d1+d2))
      
              if dice1 + dice2 == 2:
                  players[turn] = 0
                  print("Two 1 - you're done for now. Your points go back to 0.")
                  change_player = "y"
              elif dice1 == 1 or dice2 == 1:
                  print("One 1 - you're done for now.")
                  change_player  = "y"
              else:
                  # only case where we need to add values and print new score
                  players[turn] += dice1 + dice2
                  print("Your score: {}".format(players[turn]))
                  if turn == "p1":
                      change_player = hold(turn)
                  else:
                      change_player = "n" # computer is greedy, never stops
      
          winner, points = max(players.items(),key=lambda x: x[1])
          print("The winner is {} with {} points.".format(winner,points))
      
      
      main() 
      

      输出:

      Welcome to the Two Dice Pig Game. You are Player 1!
      p1 has 0 points
      p2 has 0 points
      p1 threw 5 and 1 for a total of 6
      One 1 - you're done for now.
      p1 has 0 points
      p2 has 0 points
      p2 threw 3 and 6 for a total of 9
      Your score: 9
      p2 threw 6 and 2 for a total of 8
      Your score: 17
      p2 threw 4 and 1 for a total of 5
      One 1 - you're done for now.
      p1 has 0 points
      p2 has 17 points
      p1 threw 4 and 5 for a total of 9
      Your score: 9
      Does p1 want to hold? [y or anything]
      p1 threw 2 and 6 for a total of 8
      Your score: 17
      Does p1 want to hold? [y or anything]
      p1 threw 4 and 6 for a total of 10
      Your score: 27
      
      [snipp]
      
      One 1 - you're done for now.
      p1 has 91 points
      p2 has 51 points
      p1 threw 6 and 4 for a total of 10
      Your score: 101
      Does p1 want to hold? [y or anything]
      The winner is p1 with 101 points. 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-20
        • 2014-10-31
        • 2016-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多