[英]Pygame Black screen and error when adding code to move player
我试图让我的播放器进入程序,但是我一直收到我不认识的错误。 这是错误:
追溯(最近一次通话最近):文件“ C:\\ Users \\ 1234 \\ AppData \\ Local \\ Programs \\ Python \\ Python36-32 \\ My First game ERROR.py”,第39行,位于Game()。main(屏幕)文件中主图像_x + = 1中的“ C:\\ Users \\ 1234 \\ AppData \\ Local \\ Programs \\ Python \\ Python36-32 \\我的第一个游戏ERROR.py”,第19行+ UnboundLocalError:分配前引用了局部变量“ image_x”
这是代码:
# This just imports all the Pygame modules
import pygame
class Game(object):
def main(self, screen):
clock = pygame.time.Clock()
image = pygame.image.load('Sprite-01.png')
while 1:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
image_x += 1
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
image_x -= 10
if key[pygame.K_RIGHT]:
image_x += 10
if key[pygame.K_UP]:
image_y -= 10
if key[pygame.K_DOWN]:
image_y += 10
screen.fill((200, 200, 200))
screen.blit(image, (320, 240))
pygame.display.flip()
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((640, 480))
Game().main(screen)
那是因为您从未初始化变量。
def main(self, screen):
clock = pygame.time.Clock()
image = pygame.image.load('Sprite-01.png')
# initialize variables
image_x = 0
image_y = 0
使用它们之前,您需要使用一些初始值初始化image_x
和image_y
。
另外,为了移动图像,您需要实际在image_x,image_y坐标处显示图像:
因此,代替:
screen.blit(image, (320, 240))
您需要使用:
screen.blit(image, (image_x, image_y))
最后,应用上述更改后,图像会在每个事件(包括鼠标单击和移动)上移动,因为无论事件如何,您总是将image_x增加1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.