Skip to main content
 首页 » 编程设计

python之NIM 游戏之重新运行游戏

2025年05月04日9davidwang456

我要做一个叫NIM的小游戏。该游戏是一种人机对战游戏,每个玩家移除一些吸管(1,2 或 3),移除最后一根吸管的玩家松散。我让游戏正常运行,但问题是如果玩家想再次玩游戏,它不想重新运行。任何帮助将不胜感激。 :)

import random 
print("""************ NIM GAME   *********** 
************ Game Start *********** 
************ The rules  *********** 
----------------------------------------------------- 
You need to remove from 1 to 3 straws from the pile. 
The player that removes the final straw is the loser. 
-----------------------------------------------------""") 
 
player1=str(input("Enter your name. ")) 
player2="Computer" 
howMany=0 
gameover=False 
strawsNumber=random.randint(10,20) 
 
if (strawsNumber%4)==1: 
    strawsNumber+=1 
 
def removingStrawsComputer(): 
    removedNumber=random.randint(1,3) 
    global strawsNumber 
    while removedNumber>strawsNumber: 
    removedNumber=random.randint(1,3) 
    strawsNumber-=removedNumber 
    return strawsNumber 
 
def removingStrawsHuman(): 
    global strawsNumber 
    strawsNumber-=howMany 
    return strawsNumber 
 
def humanLegalMove(): 
    global howMany 
    legalMove=False 
    while not legalMove: 
        print("It's your turn, ",player1) 
        howMany=int(input("How many straws do you want to remove?(from 1 to 3) ")) 
        if  howMany>3 or howMany<1: 
            print("Enter a number between 1 and 3.") 
        else: 
            legalMove=True 
    while howMany>strawsNumber: 
        print("The entered number is greater than a number of straws remained.") 
        howMany=int(input("How many straws do you want to remove?")) 
    return howMany 
 
def checkWinner(player): 
    if strawsNumber==0: 
        print(player," wins.") 
        global gameover 
        gameover=True 
        return gameover 
 
def resetGameover(): 
    global gameover 
    gameover=False 
    return gameover 
 
def game(): 
    while gameover==False: 
        print("It's ",player2,"turn. The number of straws left: ",removingStrawsComputer()) 
        checkWinner(player1) 
        if gameover==True: 
            break 
        humanLegalMove()         
        print("The number of straws left: ",removingStrawsHuman()) 
        checkWinner(player2) 
 
def playAgain(): 
    answer=input("Do you want to play again?(y/n)") 
    resetGameover() 
    while answer=="y": 
        game() 
    else: 
        print("Thanks for playing the game") 
 
game() 
playAgain() 

请您参考如下方法:

您忘记在每场比赛开始时重置吸管数量。在 def game(): 之后,您应该插入:

global strawsNumber 
strawsNumber=random.randint(10,20) 

注意:您还需要在 while answer=="y ": 循环。这将要求用户每次重播,而不是在第一场比赛之后。