Python井字棋项目:字典键值对无法更新的问题求助
问题解决:井字棋字典无法更新+棋盘不刷新
你的代码存在两个关键问题,直接导致字典值不更新、棋盘显示无变化:
1. 赋值运算符使用错误
在reassign函数中,你误用了比较运算符==,它的作用是判断两边值是否相等,而非赋值。正确的赋值应该用单等号=:
# 错误写法 boardPos[pos] == val # 正确写法 boardPos[pos] = val
2. 棋盘行变量未实时刷新
你在全局作用域定义的row1、row2、row3只会在程序启动时读取一次boardPos的初始值,后续字典更新后这些变量不会自动同步最新数据。解决办法是把行的生成逻辑移到print_board函数内部,每次打印时重新从字典读取最新值。
修正后的完整代码
#Board Positions boardPos = { "a1" : " ", "a2" : " ", "a3" : " ", "b1" : " ", "b2" : " ", "b3" : " ", "c1" : " ", "c2" : " ", "c3" : " " } #winning combinations #Function for printing the current game board def print_board() : colLab = " 1 2 3" # 每次打印时重新读取字典最新值生成行 row1 = "A " + boardPos.get("a1") + "|" + boardPos.get("a2") + "|" + boardPos.get("a3") row2 = "B " + boardPos.get("b1") + "|" + boardPos.get("b2") + "|" + boardPos.get("b3") row3 = "C " + boardPos.get("c1") + "|" + boardPos.get("c2") + "|" + boardPos.get("c3") print(colLab) print("\x1B[4m" + row1 + "\x1b[0m") print("\x1B[4m" + row2 + "\x1b[0m") print(row3) def reassign(pos, val) : boardPos[pos] = val print(boardPos[pos]) print("Welcome to Tic-Tac-Toe \nThis game requires two players. \nThe rules are simple. One player is X and the other O. \nTo win, position your X or O three in a row either horizontally, vertically or diagonally.") print("To start, reference the A B C 1 2 3 on the border of the board to make your first move. \nFor example: if you want to place your character in the top left corner, you will type A1.") print_board() i = 1 # number of turns lastTurn = "" while i < 9 : print("It is player 1's Turn") # 将用户输入转为小写,匹配字典的键格式 reassign(input().lower(), "x") i += 1 print_board() print("It is player 2's Turn") reassign(input().lower(), "o") i += 1 print_board()
额外优化说明:用户输入可能是大写的A1,通过input().lower()将输入转为小写,避免因键格式不匹配导致的错误。
内容的提问来源于stack exchange,提问作者Aaronstran
相关产品推荐
相关产品推荐

