A
A
Alexey Romanov2020-06-02 11:51:15
Python
Alexey Romanov, 2020-06-02 11:51:15

Why does it throw an error File "obrazew.py", line 41, in update if not (jump): UnboundLocalError: local variable 'jump' referenced before assignment?

import pygame

WIDTH = 1280
HEIGHT = 700
FPS = 60
jump = False
jumpcount = 10
# Задаем цвета
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)

# Создаем игру и окно
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Game!")
clock = pygame.time.Clock()

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((50, 40))
        self.image.fill(GREEN)
        self.rect = self.image.get_rect()
        self.rect.centerx = WIDTH / 2
        self.rect.bottom = HEIGHT - 10
        self.speedx = 0

    def update(self):
        self.speedx = 0
        keystate = pygame.key.get_pressed()
        if keystate[pygame.K_LEFT]:
            self.speedx = -5
        if keystate[pygame.K_RIGHT]:
            self.speedx = 5
        if not (jump):
            if keystate[pygame.K_SPACE]:
                jump = True
        else:
            if jumpcount>= -10:
                if jumpcount < 0:
                    y+= (jumpcount ** 2) / 2
                else:
                    y-= (jumpcount ** 2) / 2
                jumpcount -= 1
            else:
                jump = False
                jumpcount = 10

        self.rect.x += self.speedx
        if self.rect.right > WIDTH:
            self.rect.right = WIDTH
        if self.rect.left < 0:
            self.rect.left = 0

all_sprites = pygame.sprite.Group() 
player = Player()
all_sprites.add(player)

# Цикл игры
running = True
while running:
    # Держим цикл на правильной скорости
    clock.tick(FPS)
    # Ввод процесса (события)
    for event in pygame.event.get():
        # проверка для закрытия окна
        if event.type == pygame.QUIT:
            running = False

    # Обновление
    all_sprites.update()
    
    # Рендеринг
    screen.fill(BLACK)
    all_sprites.draw(screen)
    # После отрисовки всего, переворачиваем экран
    pygame.display.flip()

pygame.quit()

gives the following error:
File "obrazew.py", line 41, in update
if not (jump):
UnboundLocalError: local variable 'jump' referenced before assignment

Explain why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-06-02
@bacon

Because you don’t need to use global variables like that, why do you need them when you have an object where you can store all states.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question