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

请求协助完善Python井字棋游戏:实现电脑落子及修复报错

Hey there! Let's tackle your Tic Tac Toe issues step by step—we'll fix that ValueError when choosing position 1, improve the computer's move logic, and get your game loop running smoothly. Here's what we need to adjust:

1. Fixing the ValueError for Position 1

The error happens because your Computer list tracks position numbers (1-9), but when you select position 1, you try to remove the index 0 (from board.index(1)) from Computer—and 0 isn't in that list. Instead, we should directly map the position number to its board index (position 1 = index 0, position 2 = index 1, etc.) and only remove the chosen number from Computer.

Here's the revised ChooseNum function:

def ChooseNum():
    while True:
        print('Where do you want to place your X? Enter a number 1-9:')
        choice = input().strip()
        try:
            choice = int(choice)
            # Validate the choice is available and within range
            if choice not in Computer:
                print("That spot's already taken! Pick another one.")
                continue
            if choice < 1 or choice > 9:
                print("Please enter a number between 1 and 9.")
                continue
        except ValueError:
            print("Oops, that's not a valid number—try again!")
            continue
        
        # Convert position number to board index
        board_index = choice - 1
        # Update board and track player moves
        board[board_index] = 'X'
        player.append(choice)
        Computer.remove(choice)
        draw()
        
        # Check if player won after their move
        if WinCheck(player, "You"):
            break
        # Check for a tie
        if not Computer:
            print("It's a tie! Resetting the board in 5 seconds.")
            reset()
            break
        # Let the computer take its turn
        CompChoice()

2. Improving Computer Move Logic

Your original CompChoice function could pick non-number values (like 'X') from the board, which would cause errors. Instead, we'll use the Computer list (which tracks available positions) to pick a valid random move:

def CompChoice():
    print("Computer's turn...")
    # Pick a random available position
    comp_choice = random.choice(Computer)
    board_index = comp_choice - 1
    # Update board and track computer moves
    board[board_index] = 'O'
    pc.append(comp_choice)
    Computer.remove(comp_choice)
    draw()
    
    # Check if computer won
    if WinCheck(pc, "Computer"):
        reset()

3. Rewriting the WinCheck Function

Your original WinCheck had syntax errors (like player.count[i] instead of player.count(i)) and inefficient logic. We'll make it reusable for both players and check if any winning combination is fully contained in the player's moves:

def WinCheck(player_positions, winner_name):
    # All possible winning position combinations (1-9)
    winning_combinations = [
        [1,2,3], [4,5,6], [7,8,9],  # Rows
        [1,4,7], [2,5,8], [3,6,9],  # Columns
        [1,5,9], [3,5,7]             # Diagonals
    ]
    # Check if any combo is entirely in the player's positions
    for combo in winning_combinations:
        if all(pos in player_positions for pos in combo):
            print(f"{winner_name} Win! The board will reset in 5 seconds!")
            return True
    return False

4. Fixing the Reset Function & Adding a Main Game Loop

Your reset function used a local board variable (which wouldn't update the global one) and missed importing the time module. We'll also add a main loop to restart the game automatically:

import time  # Don't forget to import this!

def reset():
    global board, Computer, player, pc
    # Reset all game state variables
    board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    Computer = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    player = []
    pc = []
    time.sleep(5)
    # Restart the game
    main_game()

def main_game():
    print("Welcome to Tic Tac Toe!")
    draw()
    ChooseNum()

# Start the game when the script runs
if __name__ == "__main__":
    main_game()

Full Working Code

Here's the complete, fixed version of your game:

import random
import time

board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Computer = [1, 2, 3, 4, 5, 6, 7, 8, 9]
player = []
pc = []

def WinCheck(player_positions, winner_name):
    winning_combinations = [
        [1,2,3], [4,5,6], [7,8,9],
        [1,4,7], [2,5,8], [3,6,9],
        [1,5,9], [3,5,7]
    ]
    for combo in winning_combinations:
        if all(pos in player_positions for pos in combo):
            print(f"{winner_name} Win! The board will reset in 5 seconds!")
            return True
    return False

def draw():
    print(f"\n | {board[0]} | {board[1]} | {board[2]} |")
    print("\n --------")
    print(f"\n | {board[3]} | {board[4]} | {board[5]} |")
    print("\n --------")
    print(f"\n | {board[6]} | {board[7]} | {board[8]} | \n")

def reset():
    global board, Computer, player, pc
    board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    Computer = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    player = []
    pc = []
    time.sleep(5)
    main_game()

def ChooseNum():
    while True:
        print('Where do you want to place your X? Enter a number 1-9:')
        choice = input().strip()
        try:
            choice = int(choice)
            if choice not in Computer:
                print("That spot's already taken! Pick another one.")
                continue
            if choice < 1 or choice > 9:
                print("Please enter a number between 1 and 9.")
                continue
        except ValueError:
            print("Oops, that's not a valid number—try again!")
            continue
        
        board_index = choice - 1
        board[board_index] = 'X'
        player.append(choice)
        Computer.remove(choice)
        draw()
        
        if WinCheck(player, "You"):
            reset()
            break
        if not Computer:
            print("It's a tie! Resetting the board in 5 seconds.")
            reset()
            break
        CompChoice()

def CompChoice():
    print("Computer's turn...")
    comp_choice = random.choice(Computer)
    board_index = comp_choice - 1
    board[board_index] = 'O'
    pc.append(comp_choice)
    Computer.remove(comp_choice)
    draw()
    
    if WinCheck(pc, "Computer"):
        reset()

def main_game():
    print("Welcome to Tic Tac Toe!")
    draw()
    ChooseNum()

if __name__ == "__main__":
    main_game()

This version fixes all your reported issues: no more ValueError when choosing position 1, the computer makes valid random moves, the game resets automatically after a win/tie, and the win detection works reliably.

内容的提问来源于stack exchange,提问作者Nick Damore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:02:17