I am making game in pygame, but when I call update() function for zombie class it says UnboundLocalError: local variable 'x' referenced before assignment but x is = 0, and if I call update from Zombie init function it says NameError: name 'update' is not defined
class Zombie:
x = 0
y = 0
movX = 0
def movStop(self):
movX = 0
def update(self):
x += movX
def movX(self):
movX = -2
def __init__(self, _x, _y):
x, y = _x, _y
image = pygame.image.load('zombie.png')
win.blit(image, (x, y))
def main():
# init window
pygame.display.set_caption(title)
pygame.init()
clock = pygame.time.Clock()
# game loop and user input
isClosed = False
while not isClosed:
for event in pygame.event.get():
if event.type == pygame.QUIT: # check if exit button is pressed
isClosed = True
# user input
# render
win.fill(green)
zomb = Zombie(50,50)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
zomb.movX()
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
movStop()
zomb.update()
geWrite('health', 40, 20, 20)
# redisplay
pygame.display.update()
clock.tick(120)
pygame.quit()
quit()
x
is local variable. You have to use self.x
, self.y
, self.movX
in class method.
Your class could look like this
class Zombie:
def __init__(self, x=0, y=0):
self.mov_x = 0
self.image = pygame.image.load('zombie.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# or in one line
# self.rect = self.image.get_rect(x=x, y=y)
def draw(self, surface)
surface.blit(self.image, self.rect)
def movStop(self):
self.mov_x = 0
def update(self):
self.x += self.mov_x
def movX(self):
self.mov_x = -2
I use rect
( pygame.Rect()
) because it useful - you can get rect.center
, rect.right
and some pygame classes need it to draw elements - see pygame.sprite.Group.draw .
You can't have variable movX
and method movX
at the same time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.