这有什么问题?Python鳕鱼

2024-10-02 10:21:25 发布

您现在位置: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]

Tags: thegetmoveifherespacekeysfunctions
2条回答

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

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)

shiprect未在GameLoop()内定义为全局。你知道吗

尝试将global shiprect添加到该函数的开头。你知道吗

(编辑:这通常被认为是不好的做法,原因很多:How to avoid global variables

相关问题 更多 >

    热门问题