【问题标题】:IndexError: index 3 is out of bounds for axis 0 with size 3 pygameIndexError:索引 3 超出轴 0 的范围,大小为 3 pygame
【发布时间】:2021-10-30 10:35:08
【问题描述】:

从事井字游戏,因为我是 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()

【问题讨论】:

    标签: python python-3.x pygame tic-tac-toe


    【解决方案1】:

    clicked_rowclicked_col 的计算错误。问题是如果点击窗口右侧,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:
    

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 2019-08-26
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      • 2021-05-16
      • 2020-08-12
      • 2020-04-24
      • 2020-12-26
      相关资源
      最近更新 更多