IndexError:像素索引超出范围(Pygame)

时间:2018-05-28 12:47:01

标签: python pygame project maze

我能够制作一个相当容易的迷宫游戏,但似乎在第二级碰撞时难以接受,如果我遇到第二级别的东西,它会崩溃,从而导致像素索引的误差超出范围。

这是我的代码:

import pygame, sys
from pygame.locals import *
from random import * 

pygame.init()

FPS = 30
fpsClock = pygame.time.Clock()

width = 1080
height = 720

DISPLAYSURF = pygame.display.set_mode((width, height))
pygame.display.set_caption('Maze Game')
level1 = pygame.image.load('maze.png')
level2 = pygame.image.load('maze2.png')
clevel = 1

UP = 'up'
LEFT = 'left'
RIGHT = 'right'
DOWN = 'down'

sprite = pygame.image.load('marble.png')
sprite2 = pygame.image.load('marble2.png')
dot = pygame.image.load('dot.png')
dot_x = (randrange(0, 1080))
dot_y = (randrange(0, 720))
spritex = 7
spritey = 520
#sprite2x = 505
#sprite2y = 4

while True:

    if clevel == 1:
        level = DISPLAYSURF.blit(level1, (0, 0))
        DISPLAYSURF.blit(sprite, (spritex, spritey,))

    elif clevel == 2:
        level = DISPLAYSURF.blit(level2, (0,0))
        DISPLAYSURF.blit(sprite2, (spritex, spritey))

    #if tuple(DISPLAYSURF.get_at((dot_x, dot_y))) == (255, 255, 255, 255) or tuple(DISPLAYSURF.get_at((dot_x + 20 , dot_y + 20))) == (255, 255, 255,255):
        #DISPLAYSURF.blit(dot, (dot_x, dot_y))

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

        elif event.type == KEYDOWN:
            if event.key == K_LEFT:
                sprite

            elif event.key == K_RIGHT:
                sprite

            elif event.key == K_UP:
                sprite

            elif event.key == K_DOWN:
                sprite

            elif event.key == K_t:
                sprite

    keys_pressed = pygame.key.get_pressed()
    if keys_pressed[K_LEFT]:
        spritex -= 5

    elif keys_pressed[K_RIGHT]:
        spritex += 5

    elif keys_pressed[K_UP]:
        spritey -= 5

    elif keys_pressed[K_DOWN]:
        spritey += 5

    elif keys_pressed[K_t]:
        spritex = 950
        spritey = 20

    if clevel == 1:
        if tuple(DISPLAYSURF.get_at((spritex, spritey))) == (0, 0, 0, 255) or tuple(DISPLAYSURF.get_at(((spritex + 30), (spritey + 30)))) == (0, 0, 0, 255):
            spritex = 7
            spritey = 520
    if clevel == 2:
        if tuple(DISPLAYSURF.get_at((spritex, spritey))) == (0, 0, 0, 255) or tuple(DISPLAYSURF.get_at(((spritex + 10), (spritey + 12)))) == (0, 0, 0, 255):
            spritex = 505
            spritey = 4

    if tuple(DISPLAYSURF.get_at((spritex, spritey))) == (255, 8, 0, 255) or tuple(DISPLAYSURF.get_at(((spritex + 32), (spritey + 33)))) == (255, 8, 0, 255):
        clevel = 2
        sprite = sprite2
        spritex = 505
        spritey = 4

    pygame.display.update()
    fpsClock.tick(FPS)

我不知道为什么这会崩溃,但它真的很烦人。我知道这段代码看起来像垃圾,但我是python的新手。

1 个答案:

答案 0 :(得分:0)

在致电(spritex, spritey)之前,您必须确保点pygame.Surface.get_at在表面上,或者使用try: ... except IndexError:来捕获例外。