0

Hey I've been trying to call the pygame events in a function to reduce the clutter of my code. But I am unable to perform the process due to an error with global variables. Any help would be appreciated.

from pygame.locals import *
import pygame, sys
def color():
    screen.fill((85,163,48)) 

def events():
for event in pygame.event.get():
    if event.type == QUIT:
        pygame.quit()
    if event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT:
        print "left"
#sets the game map variables
tilesize = 100
map_width = 600
map_height = 300
#initialises the game screen setting it up with the game map variables
pygame.init()
screen = pygame.display.set_mode((map_width,map_height))

while True:
    color()
    events()
    pygame.display.update()
1
  • 1
    Well the code is improperly indented, so that would be the first thing to fix. Beyond that, can you give us your specific error? Commented May 4, 2016 at 2:49

1 Answer 1

1

If you're unable to access a value locally from within a function, the answer is to simply pass the value into the function. Something simple like this should suffice:

def events(ev_list):
    for event in ev_list:
        if event.type == QUIT:
            pygame.quit()

within your game loop you'd call it with:

event_list = pygame.event.get()
events(event_list)

alternatively (less desirable) you can import a library from within the function or declare a variable global

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.