这有什么问题? Python代码

时间:2015-01-22 20:09:52

标签: python

我正在尝试制作一个背景,但它会一直出现错误??? 这是代码..

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()`

这是错误

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]

2 个答案:

答案 0 :(得分:2)

shiprect未在GameLoop()中定义为全局。

尝试将global shiprect添加到该功能的开头。

(编辑:由于多种原因,这通常被视为不良做法:How to avoid global variables

答案 1 :(得分:-1)

如果在函数外部定义一个值,并希望在函数内部使用它,则将其作为参数传递给函数:

foo = 1

def bar(foo):
    foo += 1
    return foo

因此,在您的情况下,将shiprect传递给您的GameLoop()函数:

...
shiprect = shiprect.move(448, 240)

def GameLoop(shiprect):
    ...
    if pressed_keys[pygame.K_UP]:
        shiprect = shiprect.move(0, -20)

...
while True:
    GameLoop(shiprect)