i'm sorry
i'm sorry

Reputation: 49

pixel index out of range: snake game

I am trying to code an snake game and use collision to make the snake eat the food. well I am having error as it is saying there's

index error: pixel index our of range

Here's some code that could help show the problem.

collision_colour = YELLOW
colour = screen.get_at((400,300))

if dx > 0:
        collision_x = playerRect.right + 1
        collision_y = playerRect.centery
        collision_colour = screen.get_at((collision_x,collision_y))

elif dx < 0:
        collision_x = playerRect.left - 1
        collision_y = playerRect.centery
        collision_colour = screen.get_at((collision_x,collision_y))
elif dy > 0:
        collision_x = playerRect.bottom + 1
        collision_y = playerRect.centerx
        collision_colour = screen.get_at((collision_x,collision_y))
elif dy < 0:
        collision_x = playerRect.top - 1
        collision_y = playerRect.centerx
        collision_colour = screen.get_at((collision_x,collision_y))

if collision_colour == BLUE:
        screen.fill(BLACK)
        startX = screenCentreX
        startY = screenCentreY
        dx = 0
        dy = 0
        main = False
        gameover = True
        elapsedTime = int(time.perf_counter() - startTime)

Upvotes: 1

Views: 167

Answers (1)

Rabbid76
Rabbid76

Reputation: 210978

You have to ensure that the pixel coordinates are in range of the Surface when you call set_at(). Ensure that 0 <= collision_x < screen.get_width() and 0 <= collision_y < screen.get_height():

collision_colour = YELLOW
if dx != 0 or dy != 0:
    collision_colour = BLUE

if dx > 0 and playerRect.right + 1 + 1 < screen.get_width():
    collision_x = playerRect.right + 1
    collision_y = playerRect.centery
    collision_colour = screen.get_at((collision_x, collision_y))
elif dx < 0 and playerRect.left - 1 >= 0
    collision_x = playerRect.left - 1
    collision_y = playerRect.centery
    collision_colour = screen.get_at((collision_x, collision_y))
elif dy > 0 and playerRect.bottom + 1 < screen.get_height():
    collision_x = playerRect.bottom + 1
    collision_y = playerRect.centerx
    collision_colour = screen.get_at((collision_x, collision_y))
elif dy < 0 and playerRect.top - 1 >= 0
    collision_x = playerRect.top - 1
    collision_y = playerRect.centerx
    collision_colour = screen.get_at((collision_x, collision_y))

if collision_colour == BLUE:
    dx = 0
    dy = 0
    # [...]

Upvotes: 1

Related Questions