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

如何实现井字棋(Tic Tac Toe)游戏的重启功能?

解决井字棋游戏重启失效的问题

兄弟,我仔细扒了你的代码,重启功能没生效的原因其实挺明确的,主要是踩了这几个小坑:

问题根源

  • 局部变量覆盖全局变量:你的restart()函数里定义的board是局部变量,根本没碰着全局作用域里的那个棋盘数组,所以旧棋盘状态完全没变化
  • 核心状态未重置:游戏的关键状态(game_is_on、current_player、winner)在重启时完全没被重置,就算棋盘改了,游戏逻辑还是停在结束状态
  • 未重新触发游戏循环:现在的代码只是调用了restart(),但没重新启动play_game(),所以游戏不会进入新的回合

修复方案

1. 重构restart()函数

让它真正重置所有游戏状态,并且重新启动游戏:

def restart():
    # 声明要修改全局变量
    global board, game_is_on, current_player, winner
    print("\n***********Let's play our game again!**********\n")
    # 重置棋盘为初始状态
    board = ['-','-','-',
             '-','-','-',
             '-','-','-']
    # 重置所有游戏状态
    game_is_on = True
    current_player = 'x'
    winner = None
    # 显示重置后的新棋盘
    display_board()
    # 重新启动游戏循环
    play_game()

2. 修正重启交互的逻辑

你之前的lower()用错地方了,应该把用户输入转成小写再判断:

run_again = input("Do you want to restart it: ").lower()
if run_again == 'yes':
    restart()
elif run_again == 'no':
    print("Player doesn't want to play anymore.")
else:
    print("Invalid input, game exits.")

3. 优化play_game()的结束逻辑

原来的代码会在胜负分出后继续执行flip_player(),导致结果打印时玩家显示错误,调整后让游戏结束直接跳出循环:

def play_game():
    while game_is_on:
        handle_turn(current_player)
        check_if_game_over()
        # 游戏结束就立刻跳出循环,不再切换玩家
        if not game_is_on:
            break
        flip_player()
    
    # 统一在循环外打印最终结果
    if winner == 'x' or winner == 'o':
        print(f"{winner} won the match! Better luck next time, {current_player}!")
    else:
        print("Match Draw!")

小提示:修正拼写错误

你代码里的cheak应该是check(比如cheak_if_game_over),虽然不影响运行,但规范的命名能让代码更易读~

现在重启功能就能正常工作了——每次选择重启后,棋盘会回到初始状态,游戏状态全部重置,并且自动进入新的游戏循环。

内容的提问来源于stack exchange,提问作者Deependra Rout

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:25:47