【问题标题】:Pygame Black screen and error when adding code to move playerPygame添加代码移动播放器时出现黑屏和错误
【发布时间】:2018-06-24 10:47:52
【问题描述】:

我正在尝试让我的播放器在程序中移动,但我不断收到这个我无法识别的错误。 这是错误:

Traceback(最近一次调用最后一次): 文件“C:\Users\1234\AppData\Local\Programs\Python\Python36-32\My First game ERROR.py”,第 39 行,在 游戏()。主(屏幕) 文件“C:\Users\1234\AppData\Local\Programs\Python\Python36-32\My First game ERROR.py”,第 19 行,在 main 图像_x += 1 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)

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    那是因为你从来没有初始化过这个变量。

    def main(self, screen):
        clock = pygame.time.Clock()
    
        image = pygame.image.load('Sprite-01.png')
    
        # initialize variables
        image_x = 0
        image_y = 0
    

    在使用image_ximage_y 之前,需要使用它们初始化一些初始值。

    另外,为了移动图像,你需要在image_x,image_y坐标处实际显示图像:

    所以,而不是:

    screen.blit(image, (320, 240))
    

    你需要使用:

    screen.blit(image, (image_x, image_y))
    

    最后,在应用上述更改后,您的图像会随着每个事件移动,包括鼠标点击和移动,因为无论发生什么事件,您总是将 image_x 增加 1。

    【讨论】:

    • 需要设置哪些值?
    • 玩家仍然不会移动。
    • 您没有使用 image_x 或 image_y。可以用screen.blit(image, (image_x, image_y)) 代替screen.blit(image, (320, 240))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2019-11-05
    • 1970-01-01
    • 2012-06-23
    • 2014-10-10
    相关资源
    最近更新 更多