Python井字棋(Tic-Tac-Toe)程序胜负判定无输出问题求助
修复Python井字棋胜负判断失效问题
问题根源分析
这段代码的核心问题出在move_chck函数,而非main里的pass语句:
- 棋子位置收集错误:原代码收集的是棋子值('X'/'O')而非位置编号,导致无法用赢的条件集合判断胜负
- 循环逻辑错误:原函数在第一次遍历赢的条件时,只要当前条件不满足就直接返回'Continue',根本没检查所有赢的条件,平局判断也被错误嵌套在循环内
修复后的完整代码
import random def show_board(board): print(f''' +-------+-------+-------+ | | | | | {board[1]} | {board[2]} | {board[3]} | | | | | +-------+-------+-------+ | | | | | {board[4]} | {board[5]} | {board[6]} | | | | | +-------+-------+-------+ | | | | | {board[7]} | {board[8]} | {board[9]} | | | | | +-------+-------+-------+ ''') def player_move(board): while True: try: x = int(input("What is your move? ")) except: continue if x < 1 or x > 9: # 修正范围判断,棋盘只有1-9位置 continue if board[x] in ['O', 'X']: continue else: board[x] = 'O' break def comp_move(board): available = [k for k,v in board.items() if v != 'O' and v != 'X'] board[random.choice(available)] = 'X' def move_chck(board): win_conditions = [{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, {2,5,8}, {3,6,9}, {1,5,9}, {3,5,7}] # 修正:收集位置编号而非棋子值 comp_moves = {k for k, v in board.items() if v == 'X'} player_moves = {k for k, v in board.items() if v == 'O'} # 遍历所有赢的条件 for condition in win_conditions: if comp_moves.issuperset(condition): return "Computer won" if player_moves.issuperset(condition): return 'Player won' # 所有赢条件都不满足,再判断平局 if len(comp_moves) + len(player_moves) == 9: return 'Draw' # 都不满足则继续游戏 return 'Continue' def main(): board = {1:1, 2:2, 3:3, 4:4, 5:'X', 6:6, 7:7, 8:8, 9:9} while True: show_board(board) player_move(board) r = move_chck(board) if r != 'Continue': print(r) break comp_move(board) r = move_chck(board) if r != 'Continue': print(r) break if __name__ == "__main__": main()
关键修复说明
- 修正棋子位置收集:将
comp_moves和player_moves改为收集棋盘的位置编号(键),这样才能和赢的条件集合(位置编号集合)匹配 - 重构胜负判断逻辑:先遍历所有赢的条件,确认没有玩家或电脑获胜后,再判断是否平局,最后才返回'Continue',确保所有情况都被检查到
- 优化玩家输入判断:原代码的范围判断是
x <0 or x>10,修正为x<1 or x>9,符合棋盘1-9的位置范围 - 简化main函数逻辑:将
if r == 'Continue': pass改为直接判断if r != 'Continue',代码更简洁
内容的提问来源于stack exchange,提问作者7203f400-11
相关产品推荐
相关产品推荐

