When i try to run this simple game. it says:
screen.blit(plumbers,(50 + M ,337 + N))
UnboundLocalError: local variable 'M' referenced before assignment
this is from the bellow code:
import pygame
import os, sys
import itertools
import pygame
from pygame.sprite import Sprite
cloud_background = pygame.image.load('clouds.bmp')
brick_tile = pygame.image.load('brick_tile.png')
plumbers = pygame.image.load('Mario_sideways_sprite_2xL.png')
pink = (255, 64, 64)
w = 640
h = 480
screen = pygame.display.set_mode((w, h))
running = 1
def setup_background():
screen.fill((pink))
screen.blit(cloud_background,(0,0))
brick_width, brick_height = brick_tile.get_width(), brick_tile.get_height()
for x,y in itertools.product(range(0,640,brick_width),
range(390,480,brick_height)):
# print(x,y)
screen.blit(brick_tile, (x,y))
def show_sprites():
screen.blit(plumbers,(50 + M ,337 + N))
if event.key == pygame.K_UP:
M = 1
N = 0
while running:
setup_background()
show_sprites()
move()
event = pygame.event.poll()
if event.type == pygame.QUIT: sys.exit()
But when i add the variable above “screen.blit” so it looks like this:
def show_sprites():
if event.key == pygame.K_UP:
M = 1
N = 0
screen.blit(plumbers,(50 + M ,337 + N))
I get this error:
Traceback (most recent call last):
File "C:\Users\Enrique\Dropbox\GAMEZ_PYGAME\gamez.py", line 36, in <module>
show_sprites()
File "C:\Users\Enrique\Dropbox\GAMEZ_PYGAME\gamez.py", line 28, in show_sprites
if event.key == pygame.K_UP:
NameError: global name 'event' is not defined
What do i have to add/ change to get these simple controls to work?
That means you have two problems. Python sees the first one and stops with an exception.
In :
M and N still don’t exist when called.
Try for example:
In
neither
eventhas been defined.You should check a tutorial about function arguments/parameters and local variables.
your function should looks like this (for example):
or most likely:
with:
Finally, this code will send all kind of events to your function so you should filter them:
check this for example