lvndsky
lvndsky

Reputation: 159

Pygame - local variable referenced before assignment

I've been struggling with a problem that says: "Local variable 'snake' referenced before assignment" in gameLoop(). It pops up when I press a key to move the snake... I have no idea how to solve it - I thought that "global snake" would be enough. Please let me know if you have any solution - thanks a lot in advance! :)

import pygame
import sys
black = (0, 0, 0)
white = (255, 255, 255)

def displayElements():
    global snake
    snake = pygame.Rect(360, 200, 30, 10) 
    pygame.draw.rect(screen, white, snake)

def gameSetup():
    global screen, window, fps, step
    pygame.init()
    screen = pygame.display.set_mode((720, 400))
    window = screen.get_rect()
    pygame.key.set_repeat(15, 15)
    fps = pygame.time.Clock()
    step = 5
    displayElements()

def gameLoop():
    while True:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    snake = snake.move(0,-step)
                if event.key == pygame.K_DOWN:
                    snake = snake.move(0,step)

        fps.tick(120)
        pygame.display.flip()

def main():
    gameSetup()
    gameLoop()

main()

Upvotes: 1

Views: 164

Answers (1)

CJR
CJR

Reputation: 3985

global snake just tells displayElements() to use snake in the global namespace.

Nothing is telling gameLoop() to look in the global namespace to find snake, though.

As a rule, you should not use global. There are rare exceptions to this rule, and this is absolutely not one of those exceptions - you should rewrite this to pass references in and out of functions. Something like this, for example.

def displayElements():
    snake = pygame.Rect(360, 200, 30, 10) 
    pygame.draw.rect(screen, white, snake)
    return snake

def gameSetup():
    ...
    return displayElements()

def gameLoop(snake):
    ...

def main():
    snake = gameSetup()
    gameLoop(snake)

Upvotes: 1

Related Questions