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

Python井字棋代码精简优化及占位重复输入判断失效问题求助

Fixing and Refactoring Your Tic Tac Toe Code

Hey Kumar, let's tackle your Tic Tac Toe code issues step by step—we'll fix the input validation bug and slim down the redundant code while making it easier to maintain.

What's Going Wrong in Your Original Code?

  • Redundant Logic: You repeat the same input-checking code for each player multiple times, which makes the code bloated and hard to update.
  • Incomplete Validation: When a player enters a taken spot the second time, there's no loop to keep asking for a valid input—your code just tries once and moves on, leading to unexpected behavior.
  • Typo: Player 2's move accidentally sets X instead of O in one section, breaking the turn-based gameplay.

Refactored, Robust Version of Your Code

board = [" " for _ in range(9)]

def print_board():
    """Show the current state of the Tic Tac Toe board"""
    rows = [
        "|{}|{}|{}|".format(board[i], board[i+1], board[i+2])
        for i in range(0, 9, 3)
    ]
    print("\n" + "\n".join(rows) + "\n")

def get_valid_move(player_name, board):
    """Prompt the player until they enter a valid, unused position"""
    while True:
        try:
            choice = int(input(f"Enter your choice, {player_name}: ").strip())
            # Check if input is within the valid 1-9 range
            if 1 <= choice <= 9:
                index = choice - 1
                if board[index] == " ":
                    return index
                else:
                    print("Place is already taken. Try again.")
            else:
                print("Please enter a number between 1 and 9.")
        except ValueError:
            print("That's not a valid number. Try again.")

# Main game loop
current_player = ("Player 1", "X")
while True:
    print_board()
    player_name, symbol = current_player
    move_index = get_valid_move(player_name, board)
    board[move_index] = symbol
    
    # Switch players for the next turn
    current_player = ("Player 2", "O") if current_player[0] == "Player 1" else ("Player 1", "X")

Key Improvements Explained

1. Extract Repeated Logic into Functions

  • print_board(): We streamlined the row creation with a list comprehension to avoid repeating the same format line three times, and added a docstring to clarify its purpose.
  • get_valid_move(): This is the biggest win—we moved all input validation into one function. It handles:
    • Non-numeric inputs (with a try-except block to catch invalid number entries).
    • Numbers outside the 1-9 range.
    • Already taken positions.
    • It loops until the player enters a valid move, so no more skipped checks when someone repeats a taken spot.

2. Simplified Turn Management

Instead of writing separate code blocks for Player 1 and Player 2, we use a tuple to track the current player's name and symbol. After each valid move, we switch the player—this cuts out duplicate code and makes the loop easy to extend (like adding win/tie checks later).

3. Robust Input Handling

The original code only checked for taken spots once per input attempt. The new function uses a while True loop to keep prompting until it gets a valid input, so players can't break the game with bad entries.

4. Fixed Typo

Player 2 now correctly places an O instead of an X, keeping the turn-based logic intact.

Optional Next Steps to Expand the Game

If you want to take this further, you could add:

  • A win condition check (after each move, verify if the current player has 3 symbols in a row).
  • A tie condition check (trigger when the board is full with no winner).
  • A restart prompt after the game ends.

内容的提问来源于stack exchange,提问作者Kumar Katariya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:00:56