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

基于If-then语句的双人Python井字棋代码优化咨询

Refactoring Your Tic-Tac-Toe Code for Cleanliness & Efficiency

Hey there! The main issue with your original code is that using 9 separate global variables leads to tons of repetition and makes the code hard to maintain. Let's refactor this into a much cleaner, more efficient version using lists and modular functions—here's how:

Key Optimizations We'll Make

  • Replace individual position variables with a single list to store the board state
  • Split logic into reusable functions (drawing the board, checking wins, handling input)
  • Remove global variables to avoid side effects
  • Simplify win-checking with pre-defined winning combinations instead of endless if-then statements

Full Refactored Code

def print_board(board):
    """Draw the 3x3 Tic-Tac-Toe board"""
    print(f" {board[0]} | {board[1]} | {board[2]} ")
    print("---+---+---")
    print(f" {board[3]} | {board[4]} | {board[5]} ")
    print("---+---+---")
    print(f" {board[6]} | {board[7]} | {board[8]} ")

def check_win(board):
    """Check if there's a winner or tie, return the result (X/O/Tie/None)"""
    # All possible winning combinations (rows, columns, diagonals)
    win_combinations = [
        [0,1,2], [3,4,5], [6,7,8],  # Horizontal
        [0,3,6], [1,4,7], [2,5,8],  # Vertical
        [0,4,8], [2,4,6]             # Diagonal
    ]
    # Check for a winner
    for combo in win_combinations:
        if board[combo[0]] == board[combo[1]] == board[combo[2]] != ' ':
            return board[combo[0]]
    # Check for a tie (board is full with no winner)
    if ' ' not in board:
        return 'Tie'
    # Game is still ongoing
    return None

def get_valid_input(board, current_player):
    """Get a valid move from the player (1-9, unused position)"""
    while True:
        try:
            # Convert input to 0-indexed for the list
            position = int(input(f"Player {current_player}, enter your move (1-9): ")) - 1
            if 0 <= position < 9 and board[position] == ' ':
                return position
            else:
                print("Oops! That position is either taken or out of range. Try again.")
        except ValueError:
            print("Please enter a valid number between 1 and 9.")

def play_tic_tac_toe():
    """Main game loop"""
    # Initialize empty board (indexes 0-8 map to positions 1-9)
    board = [' ' for _ in range(9)]
    current_player = 'X'
    
    print("Welcome to Tic-Tac-Toe!")
    print("Position numbering:")
    print(" 1 | 2 | 3 ")
    print("---+---+---")
    print(" 4 | 5 | 6 ")
    print("---+---+---")
    print(" 7 | 8 | 9 ")
    
    while True:
        print_board(board)
        move = get_valid_input(board, current_player)
        board[move] = current_player
        
        # Check if game has ended
        game_result = check_win(board)
        if game_result:
            print_board(board)
            if game_result == 'Tie':
                print("It's a tie!")
            else:
                print(f"Player {game_result} wins!")
            break
        
        # Switch players
        current_player = 'O' if current_player == 'X' else 'X'

if __name__ == "__main__":
    play_tic_tac_toe()

Why This Works Better

  1. Single Board State: Instead of z1 to z9, we use a list where each index represents a board position. This makes updating and checking positions far less repetitive.
  2. Modular Functions: Each function handles one specific task—this makes the code easier to read, debug, and modify (e.g., you can tweak the board layout without touching win-checking logic).
  3. Simplified Win Check: Instead of writing dozens of if-then statements for every possible win, we loop through a list of winning combinations. This is scalable and way cleaner.
  4. Input Validation: The get_valid_input function ensures players can't enter invalid moves, which makes the game more robust.
  5. No Global Variables: All game state is contained within the play_tic_tac_toe function, avoiding unexpected side effects from global variables.

内容的提问来源于stack exchange,提问作者Christopher Rapkoch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:56:32