IndexError: index 3 is out of bounds for axis 0 with size 3 pygame

IndexError: index 3 is out of bounds for axis 0 with size 3 pygame

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

我得到的错误是;

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()

clicked_rowclicked_col计算错误。问题是,如果点击window右边的,mouseX // 160的结果可能是3.

网格有 3 行和 3 列。宽度为550,高度为450。计算clicked_rowclicked_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.

转换结果

此外,您不小心在 available_square 函数中交换了 row col。变化:

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

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