0
import pygame, os, random, time # Packages that I will use
from spritesheet import SpriteSheet

pygame.init() # Little pygame function to initiate all the modules

WHITE = (255,255,255)

# Window basic information
WIDTH, HEIGHT = 1280, 720
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("The zombies are COMING!!")

# Sprites
size = (70,70)

environment = pygame.transform.scale(pygame.image.load(os.path.join('Assets','Graveyard.png')),(WIDTH, HEIGHT))
heart = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'Heart.png')), (size))
bullet = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'Bullet.png')), (size))
sword = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'Sword.png')), (size))
rocketLauncher = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'Rocket Launcher.png')), (size))
shotgun = pygame.transform.scale(pygame.image.load(os.path.join('Assets', 'Shotgun.png')), (size))

# Sprite Sheet

spritesheet = SpriteSheet(r'Assets/Ninja Idle.png')
sprite1 = spritesheet.get_sprite(0,0,16,16)
sprite1 = pygame.transform.scale((sprite1),(100,100))
sprite2 = spritesheet.get_sprite(16,0,16,16)
sprite2 = pygame.transform.scale((sprite2),(100,100))
spriteIdle = [sprite1,sprite2]

index = 0

class Player:
    def __init__(self, x, y, lives, ammunition):
        self.lives = lives
        self.ammunition = ammunition
        self.x = x
        self.y = y
    
    def drawPlayer(self, win):
        #pygame.draw.rect(win, (255,0,0), (self.x, self.y, 50, 50))
        win.blit(spriteIdle[index])

def main(): # Main loop
    run = True
    FPS = 60
    clock = pygame.time.Clock()
    wave = 1
    lives = 5
    ammunition = 1
    velocity = 5
    player = Player(WIDTH/2, HEIGHT/2, lives, ammunition)

    def windowRenderer (): # Func to update the screen according the events
        win.blit(environment, (0,0))
        main_font = pygame.font.SysFont("comicsans", 50)
        lives_label = main_font.render(f"{lives}", 1, (WHITE))
        wave_label = main_font.render(f"Wave: {wave}", 1, (WHITE))
        ammunition_label = main_font.render(f"{ammunition}", 1, (WHITE))
        player.drawPlayer(win)
        win.blit(heart, (WIDTH - 150, 0))
        win.blit(bullet,(WIDTH - 150, 70))
        win.blit(lives_label, (WIDTH - 50, 20))
        win.blit(wave_label, (WIDTH/2-70, 20))
        win.blit(ammunition_label, (WIDTH - 50, 95))
        pygame.display.update()

    while run:
        clock.tick(240)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
        
        key = pygame.key.get_pressed()

        if key[pygame.K_a] and player.x > 0:
            player.x -= velocity
        if key[pygame.K_d] and player.x + velocity < WIDTH - 49:
            player.x += velocity
        if key[pygame.K_w] and player.y > 0:
            player.y -= velocity
        if key[pygame.K_s] and player.y + velocity < HEIGHT - 49:
            player.y += velocity
        else:
            index = (index + 1) % len(spriteIdle)
        windowRenderer()
        
main()

If you try to run the code, it replies saying that a local variable was reference before de assignment. But the "index" variable, is in global form.

I also tried the nonlocal form, but, well... no results either.

I also tried moving the index variable to the "main()" function. But if I try that, I don't have a lot of control about the character by itself.

If I remove global, the same error happens.

To specify, the error happens on the line 86. And the index variable is on the line 32.

And the error message is "UnboundLocalError: local variable 'index' referenced before assignment"

I'm using pygame, but you don't need to worry a lot about that.

furas
  • 134,197
  • 12
  • 106
  • 148
  • 3
    Global is used inside a function. If you want to use a global variable inside a function, then use the global keyword. https://www.programiz.com/python-programming/global-keyword – Vkreddy Apr 01 '21 at 04:40
  • Which variable on which line is causing you a problem? Please supply the error messages. – Nayuki Apr 01 '21 at 04:45
  • Nayuki, the line 86 and 32, "index" variable – Calvin Ogata Apr 01 '21 at 04:49
  • you should put this information in question when you created this question. But problem is Stackoverflow doesn't show line numbers - so your numbers are useless for us. – furas Apr 01 '21 at 05:45
  • aalways put full error message (starting at word "Traceback") in question (not comment) as text (not screenshot, not link to external portal). There are other useful information. – furas Apr 01 '21 at 05:45
  • you have to use `global index` inside `main()` to inform function that you want to assign `index = ...` to external/global variable. Without `global index` it will try to create local variable `index = ...` but to create it it has to first calculate `... = (index + 1) % len(spriteIdle)` so it has to get value from local `index` which still doesn't exist - `index =... ` will be created after calculating `... = (index + 1) % len(spriteIdle)` - and this makes conflict: it refer local variable `index` before assignment - it want to get value from local variable before it is created. – furas Apr 01 '21 at 05:50
  • Because you modify the value of `index`. For more detail about global and local variable, see https://stackoverflow.com/a/24572187/10315163. – Ynjxsjmh Apr 01 '21 at 06:18
  • Another option (other than making it `global`) is to box it in a mutable container -- do `index = [0]` at the outer scope, and then access `index[0]` inside your functions. – Samwise Apr 02 '21 at 14:49

0 Answers0