Python NIM游戏:如何添加新游戏(y)或(n)

2024-04-26 00:02:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题:我如何将新游戏放入代码或重新播放(y)或(n) 这是我的学校项目。我一直在试图找到一个解决办法,但它只会重复问题“再次播放”或错误。你知道吗

    import random

    player1 = input("Enter your real name: ")
    player2 = "Computer"

    state = random.randint(12,15)
    print("The number of sticks is " , state)
    while(True):
        print(player1)
        while(True):
            move = int(input("Enter your move: "))
            if move in (1,2,3) and move <= state:
                break
            print("Illegal move") 
        state = state - move
        print("The number of sticks is now " , state)
        if state == 0:
            print(player1 , "wins")
            break
        print(player2)
        move = random.randint(1,3)
        if state in (1,2,3):
            move = state
        print("My move is " , move)
        state = state - move
        print("The number of sticks is now " , state)
        if state == 0:
            print("Computer wins")
            break

Tags: ofthenumberinputyourmoveifis
1条回答
网友
1楼 · 发布于 2024-04-26 00:02:10

循环条件总是True。这就是需要调整的地方。相反,您只希望在用户希望继续时循环

choice = 'y'  # so that we run at least once
while choice == 'y':
    ...
    choice = input("Play again? (y/n):")

每次开始新游戏时,您都必须确保重置状态。你知道吗

由于游戏可以在多个点结束,因此需要重构代码或替换break

if state == 0:
    print(player1 , "wins")
    choice = input("Play again? (y/n):")
    continue

或者更容易的是将游戏放入一个内部循环

choice = 'y'
while choice == 'y':
  while True:
    ...
    if state == 0:
      print(player1, "wins")
      break
    ...
  choice = input("Play again? (y/n):")

在那一点上,如果我是你的话,我会开始把东西分解成函数

相关问题 更多 >