Reputation: 9
I am trying to make a background show up but it keeps coming with a error??? Here is the code..
import pygame, sys
# == (1) Create 'global' variables ==
# These are variables that every part of your
# code can 'see' and change
global screen, current_keys
# == (2) Define the functions for each task first ==
# == GameInit ==
# Put initialisation stuff here
# it is called just once
# at the beginning of our game
def GameInit():
global screen
pygame.init()
screen = pygame.display.set_mode((1024,640))
spaceship = pygame.image.load("Space Ship.png")
Background = pygame.image.load("Space Background.png")
backrect = Background.get_rect()
shiprect = spaceship.get_rect()
shiprect = shiprect.move(448, 240)
# == GameLoop ==
# Put things that have to occur repeatedly
# here. It is called every frame
def GameLoop():
global current_keys
# Lock the timing to 60 frames per second
pygame.time.Clock().tick(60)
# Check for exit
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pressed_keys = pygame.key.get_pressed()
# update our key states
current_keys = pygame.key.get_pressed()
#if up or down move the Space Ship
if pressed_keys[pygame.K_UP]:
shiprect = shiprect.move(0, -20)
if pressed_keys[pygame.K_DOWN]:
shiprect = shiprect.move(0, 20)
if pressed_keys[pygame.K_LEFT]:
shiprect = shiprect.move(-20, 0)
if pressed_keys[pygame.K_RIGHT]:
shiprect = shiprect.move(20, 0)
# GameUpdate functions will go here
# GameDraw functions will go here
#Drawing the characters & Background
screen.blit(Background, backrect)
screen.blit(spaceship, shiprect)
# flip the screen
pygame.display.flip()
# == (3) Call the functions to run the game ==
# We have only *defined* our functions above.
# Here we actually call them to make them happen
GameInit()
while True:
GameLoop()`
and here is the error
libpng warning: iCCP: known incorrect sRGB profile
Traceback (most recent call last):
File "C:\Users\Naeem\Desktop\Python Subline Games\Space Game.py", line 70, in <module>
GameLoop()
File "C:\Users\Naeem\Desktop\Python Subline Games\Space Game.py", line 60, in GameLoop
screen.blit(spaceship, shiprect)
UnboundLocalError: local variable 'shiprect' referenced before assignment
[Finished in 7.2s]
Upvotes: 0
Views: 106
Reputation: 102842
If you define a value outside of a function, and want to use it inside a function, pass it to the function as a parameter:
foo = 1
def bar(foo):
foo += 1
return foo
So, in your case, pass shiprect
to your GameLoop()
function:
...
shiprect = shiprect.move(448, 240)
def GameLoop(shiprect):
...
if pressed_keys[pygame.K_UP]:
shiprect = shiprect.move(0, -20)
...
while True:
GameLoop(shiprect)
Upvotes: -1
Reputation: 473
shiprect
is not defined as global within GameLoop()
.
Try adding global shiprect
to the beginning of that function.
(Edit: this is generally considered bad practice for many reasons: How to avoid global variables)
Upvotes: 2