You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python开发的NIM取石子游戏中实现重启或结束游戏功能

NIM取石子游戏代码问题修正

现有代码疏漏

  • 重启判断逻辑错误:if answer == "y" or "yes":语法逻辑有误,or右侧的非空字符串"yes"布尔值恒为真,导致无论用户输入什么内容,条件都会成立,游戏永远无法正常退出。
  • 电脑取石子策略错误:当前规则为每次可取1-3颗、取走最后一颗者获胜,正确的必胜策略是每轮取完后让剩余石子数为4的倍数,现有按模3计算的逻辑完全错误,大量场景下会主动让对手获胜。
  • 取数验证逻辑冗余:当前玩家取石子时,分两次循环分别验证1-3范围、是否超过剩余石子数,可合并优化减少重复代码。
  • 无异常输入兼容逻辑:用户输入非数字内容时,int(input())会直接抛出异常导致程序崩溃。

修正后完整代码

print("NIM: The Python Game")
print("Hello! My name is AI (the clever computer). \nIn this game, 2 other players will play against me and each other. \nThe player to go first will randomly choose between 30 and 50 stones in a pile to start the game.")
print("She\He will also be the first to remove the first stones. \nPlayers will then take turns at removing between 1 and 3 stones from the pile until a player removes the final stone. \nThe player to remove the final stone is the winner.")
player1=str(input("\nPlayer 1, what is your name and MIT ID? "))
print("Hello, " + player1.capitalize())

player2=str(input("\nPlayer 2, what is your name and MIT ID? "))
print("Hello, " + player2.capitalize())

player3="The computer"

howMany=0
stonesNumber=0

while True:
    # 初始石子数输入验证
    while True:
        try:
            stonesNumber=int(input("\nNEW GAME \nHow many stones do you want to start with (between 30 and 50), " + player1.capitalize() + "? "))
            if 30 <= stonesNumber <=50:
                print("The number of stones is ", stonesNumber)
                break
            print("The number must be between 30 and 50!")
        except ValueError:
            print("Please enter a valid integer!")

    while True:
        print("\nIt's your turn, ",player1.capitalize())
        # 合并取数验证逻辑
        while True:
            try:
                howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
                if 1<= howMany <=3 and howMany <= stonesNumber:
                    break
                elif howMany <1 or howMany>3:
                    print("Enter a number between 1 and 3.")
                else:
                    print("The entered number is greater than a number of stones remaining.")
            except ValueError:
                print("Please enter a valid integer!")
    
        stonesNumber=stonesNumber-(howMany)
        print("Numbers of stones left: " + str(stonesNumber))
        if stonesNumber==0:
            print(player1.capitalize()," wins.")
            break

        print("\nIt's your turn, ",player2.capitalize())
        while True:
            try:
                howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
                if 1<= howMany <=3 and howMany <= stonesNumber:
                    break
                elif howMany <1 or howMany>3:
                    print("Enter a number between 1 and 3.")
                else:
                    print("The entered number is greater than a number of stones remaining.")
            except ValueError:
                print("Please enter a valid integer!")
    
        stonesNumber=stonesNumber-(howMany)
        if stonesNumber==0:
            print(player2.capitalize()," wins.")
            break
        print("Numbers of stones left: " + str(stonesNumber))

        print("\nIt's my turn!")
        # 修正电脑必胜策略
        remainder = stonesNumber %4
        howMany = remainder if remainder !=0 else 1
        stonesNumber=stonesNumber-(howMany)
        print(f"The computer has taken {howMany} counter{'s' if howMany>1 else ''}")

        if stonesNumber==0:
            print(player3," wins.")
            break
        print("Numbers of stones left: " + str(stonesNumber))

    print("\nThe game is over!")
    
    # 修正重启判断逻辑,兼容大小写
    answer=str(input("\nDo you want to play again?(y/n)")).strip().lower()
    if answer in ("y", "yes"):
        print("\nRestarting the game")
    else:
        break
print("\nThanks for playing the game!")

内容的提问来源于stack exchange,提问作者Alain Khanh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:54:07