首页 > 解决方案 > IndexError:索引 3 超出轴 0 的范围,大小为 3 pygame

问题描述

从事井字游戏,因为我是pygame的新手,所以我知道的不多,所以我使用这个项目作为了解pygame的一种方式,无论如何我随机得到这个错误并且不知道如何修复它,我尝试在谷歌上查找,但没有找到我真正理解的任何内容。

我得到的错误是;

IndexError: index 3 is out of bounds for axis 0 with size 3
import pygame, sys
import numpy as np
pygame.init()

screen_color = (28, 170, 156)
line_color = (23, 140, 135)
line_width = 9

screen = pygame.display.set_mode((550, 450))
pygame.display.set_caption("Tic Tac Toe")
screen.fill(screen_color)
board = np.zeros((3, 3))


def draw_lines():
    #1st horizontal
    pygame.draw.line(screen, line_color, (0, 135), (550, 135), line_width)
    #2nd horizontal
    pygame.draw.line(screen, line_color, (0, 300), (550, 300), line_width)
    #1st vertical
    pygame.draw.line(screen, line_color, (175, 0), (175, 450), line_width)
    #2nd vertical
    pygame.draw.line(screen, line_color, (370, 0), (370, 450), line_width)

def mark_square(row, col, player):
    board[row][col] = player

def available_square(row, col):
    if board[col][row] == 0:
        return True

    else:
        return False

def is_board_full():
    for row in range(3):
        for col in range(3):
            if board[row][col] == 0:
                return False

print(is_board_full())
print(board)
draw_lines()

player = 1

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouseX = event.pos[0] #X coordinate
            mouseY = event.pos[1] #Y coordinate

            clicked_row = int(mouseY // 180)
            clicked_col = int(mouseX // 160)

            #print(clicked_col)
            #print(clicked_row)

            if available_square(clicked_row, clicked_col):
                if player == 1:
                    mark_square(clicked_row, clicked_col, 1)
                    player = 2
                
                elif player == 2:
                    mark_square(clicked_row, clicked_col, 2)
                    player = 1

                print(board)

    pygame.display.update()

标签: pythonpython-3.xpygametic-tac-toe

解决方案


clicked_row和的计算clicked_col是错误的。问题是,如果你点击窗口右侧,结果mouseX // 160可能是 3。

网格有 3 行 3 列。宽550,高450。计算clicked_row如下clicked_col

clicked_row = mouseY * 3 // 450
clicked_col = mouseX * 3 // 550

甚至更好:

clicked_row = mouseY * 3 // screen.get_height()
clicked_col = mouseX * 3 // screen.get_width()

//操作员是楼层划分操作员。所以你不需要用int.


此外,您不小心在函数中交换了row和。改变: colavailable_square

if board[col][row] == 0:

if board[row][col] == 0:

推荐阅读