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

Tic Tac Toe脚本在VSCode运行报IndexError问题求助

Tic Tac Toe游戏报错修复指导

问题描述

根据Udemy课程编写了简易Tic Tac Toe(井字棋)游戏,该程序在Jupyter Notebook中可正常运行,但在VSCode中执行脚本时出现索引越界错误,需修复指导。

错误信息

Traceback (most recent call last):
  File "x:\Python\Python_Bootcamp\Complete-Python-3-Bootcamp-master\04-Milestone Project - 1\TIC_TAC_TOE.py", line 105, in <module>   
    display_board(board)
  File "x:\Python\Python_Bootcamp\Complete-Python-3-Bootcamp-master\04-Milestone Project - 1\TIC_TAC_TOE.py", line 8, in display_board
    print(board[1] + '|' + board[2] + '|' + board[3])
          ~~~~~^^^
IndexError: list index out of range

原代码

import random

def display_board(board):
    # print('\n'*100) # Lets you only see one version of the board
    print(board[1] + '|' + board[2] + '|' + board[3])
    print('-----')
    print(board[4] + '|' + board[5] + '|' + board[6])
    print('-----')
    print(board[7] + '|' + board[8] + '|' + board[9])

def player_input():
    marker = ''

    while marker != 'X' and marker != 'O':
        marker = input('Player 1 choose X or O: ')
        
        player1 = marker.upper()

        if player1 == 'X':
            player2 = 'O'
        else:
            player2 = 'X'

    return(player1, player2)

def place_marker(board,marker,position):
    board[position] = marker

def win_check(board, mark):
    return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the bottom
    (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle
    (board[1] == mark and board[2] == mark and board[3] == mark) or # across the top
    (board[7] == mark and board[4] == mark and board[1] == mark) or # down the left column
    (board[2] == mark and board[5] == mark and board[8] == mark) or # down the middle
    (board[3] == mark and board[6] == mark and board[9] == mark) or # down the right side
    (board[3] == mark and board[5] == mark and board[7] == mark) or # diagonal
    (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal

def choose_first():
    flip = random.randint(0,1)

    if flip == 0:
        return ('Player 1')
    else:
        return ('Player 2')

def space_check(board, position):
    return board[position] == ' ' # If space is empty the return value will be True

def full_board_check(board):
    for i in range(1,10):
        if space_check(board,i):
            return False # False meaning the space is empty of marker
        else:
            return True # True meaning the board is full

def player_choice(board):
    position = 0

    while position not in [1,2,3,4,5,6,7,8,9]:
        position = int(input('Choose your position: '))

    return position

def replay():
    
    choice = input('Do you want to play again?')

    return choice == 'Yes'

# GAME SETUP
print('Welcome to Tic Tac Toe!')

while True:
    board = [' '*10]
    player1_marker,player2_marker = player_input()
    turn = choose_first()
    print(turn + ' will go first')
    game_on = ''
    
    play_game = input('Are you ready to play Yes or No?: ')

    if play_game.lower()[0] == 'y':
        game_on == True
    else:
        game_on == False

        # Player 1 Turn
    if turn == 'Player 1':

        # Show board

        display_board(board)

        # Choose a position

        position = player_choice(board)

        # Place marker on chosen position

        place_marker(board,player1_marker,position)

        # Check if they won

        if win_check(board,player1_marker) == True:
            display_board(board)
            print('Player 1 has won the game!')
            game_on = False

        # Check to see if Tie
        else: 
            if full_board_check(board):
                display_board(board)
                print('TIE GAME')
                break

    # If there's no tie turn to Player 2        
    else:
        turn = 'Player 2'

        # Player2's turn.
    if turn == 'Player 2':

        # Show board
        # display_board(board)

        # Show position
        position = player_choice(board)

        #Place marker on position
        place_marker(board,player2_marker,position)

        # Check to see if win
        if win_check(board,player2_marker) == True:
            display_board(board)
            print('Player 2 has won the game!')
            game_on = False
        
        # Check to see if Tie
        else:
            full_board_check(board)
            display_board(board)
            print('TIE GAME')
            break
    else:
        turn = 'Player 1'
    
    # If players do not want to play again, quit
    if not replay():
        break

修复方案

1. 修复棋盘初始化错误

原代码board = [' '*10]创建了仅包含1个元素的列表(该元素是10个空格的字符串),导致索引1-9不存在,直接引发IndexError。
修复后代码:

board = [' '] * 10

此代码创建包含10个独立空格元素的列表,索引0闲置不用,1-9对应棋盘的9个位置。

2. 修复赋值运算符错误

原代码中game_on == True和game_on == False使用了比较运算符==,实际应为赋值运算符=,否则game_on始终为空字符串,游戏逻辑无法正常触发。
修复后代码:

if play_game.lower()[0] == 'y':
    game_on = True
else:
    game_on = False

3. 修复full_board_check函数逻辑错误

原函数仅检查第一个位置(i=1)就返回结果,无法正确判断整个棋盘是否填满。需遍历所有位置,确认无空位置后才返回True。
修复后代码:

def full_board_check(board):
    for i in range(1,10):
        if space_check(board,i):
            return False  # 存在空位置,返回False
    return True  # 所有位置都被占用,返回True

4. 修复主游戏循环结构错误

原代码仅执行一次玩家回合就终止,未实现持续游戏直到分出胜负或平局。需将玩家回合逻辑放入while game_on:循环中,确保游戏流程正常推进。
修复后主循环代码:

print('Welcome to Tic Tac Toe!')

while True:
    board = [' '] * 10
    player1_marker,player2_marker = player_input()
    turn = choose_first()
    print(turn + ' will go first')
    game_on = False
    
    play_game = input('Are you ready to play Yes or No?: ')

    if play_game.lower()[0] == 'y':
        game_on = True
    else:
        game_on = False

    while game_on:
        # Player 1 Turn
        if turn == 'Player 1':
            # Show board
            display_board(board)
            # Choose a position
            position = player_choice(board)
            # Place marker on chosen position
            place_marker(board,player1_marker,position)
            # Check if they won
            if win_check(board,player1_marker):
                display_board(board)
                print('Player 1 has won the game!')
                game_on = False
            else:
                # Check to see if Tie
                if full_board_check(board):
                    display_board(board)
                    print('TIE GAME')
                    game_on = False
                else:
                    turn = 'Player 2'
        # Player2's turn.
        else:
            # Show board
            display_board(board)
            # Choose position
            position = player_choice(board)
            # Place marker on position
            place_marker(board,player2_marker,position)
            # Check to see if win
            if win_check(board,player2_marker):
                display_board(board)
                print('Player 2 has won the game!')
                game_on = False
            else:
                # Check to see if Tie
                if full_board_check(board):
                    display_board(board)
                    print('TIE GAME')
                    game_on = False
                else:
                    turn = 'Player 1'
    
    # If players do not want to play again, quit
    if not replay():
        break

5. 修复player_choice函数缺失位置可用性检查

原函数仅验证输入是否为1-9,但未检查位置是否已被占用,导致玩家可重复选择已被占据的位置。
修复后代码:

def player_choice(board):
    position = 0
    while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):
        position = int(input('Choose your position (1-9): '))
    return position

6. 修复replay函数大小写不兼容问题

原函数仅判断输入为严格的'Yes',导致用户输入小写'yes'时会直接退出游戏,优化后支持大小写无关的判断。
修复后代码:

def replay():
    choice = input('Do you want to play again? (Yes/No): ')
    return choice.lower() == 'yes'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 06:55:22