Python井字棋函数无法正常打印问题求助
Fix for Tic-Tac-Toe Board Not Printing Correctly
The core issue in your code is that you're printing the function board itself rather than invoking it. When you write print(board), Python outputs the function's reference instead of executing the code inside it.
Corrected Code
AA=0;AB=0;AC=0;BA=0;BB=0;BC=0;CA=0;CB=0;CC=0 AAtext="AA";ABtext="AB";ACtext="AC";BAtext="BA";BBtext="BB";BCtext="BC";CAtext="CA";CBtext="CB"; CCtext="CC" def board(): def lines(A, B, C): print("|",A,"|",B,"|",C,"|") print("________________") lines(AAtext, ABtext, ACtext) print("|______________|") lines(BAtext, BBtext, BCtext) print("|______________|") lines(CAtext, CBtext, CCtext) print("|______________|") board() # Call the function instead of printing it
Key Change
Replace print(board) with board(). This tells Python to execute the function's code, which will print your board as expected.
Additional Suggestions
Using individual variables for each board cell (like AA, AAtext) is cumbersome. A better approach is to use a 2D list to represent the board, which makes updates and maintenance easier. For example:
board_state = [["AA", "AB", "AC"], ["BA", "BB", "BC"], ["CA", "CB", "CC"]] def print_board(): print("________________") for row in board_state: print(f"| {row[0]} | {row[1]} | {row[2]} |") print("|______________|") print_board()
This version is cleaner, easier to modify, and scales better if you ever want to adjust the board size.
内容的提问来源于stack exchange,提问作者Joey Jin
相关产品推荐
相关产品推荐

