Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Pygame黑屏和向移动玩家添加代码时出错_Python_Pygame - Fatal编程技术网

Python Pygame黑屏和向移动玩家添加代码时出错

Python Pygame黑屏和向移动玩家添加代码时出错,python,pygame,Python,Pygame,我试图让我的球员在一个程序中移动,但我一直收到这个错误,我不承认。 以下是错误: 回溯(最近一次呼叫最后一次): 文件“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行 图像

我试图让我的球员在一个程序中移动,但我一直收到这个错误,我不承认。 以下是错误:

回溯(最近一次呼叫最后一次): 文件“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行 图像_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)

这是因为您从未初始化过变量

def main(self, screen):
    clock = pygame.time.Clock()

    image = pygame.image.load('Sprite-01.png')

    # initialize variables
    image_x = 0
    image_y = 0
在使用它们之前,需要使用一些初始值初始化
image\u x
image\u y

此外,为了移动图像,您需要在图像x,图像y坐标处实际显示图像:

因此,不是:

screen.blit(image, (320, 240))
您需要使用:

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

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

需要设置哪些值?玩家仍然不会移动。您没有使用image_x或image_y。可以使用
screen.blit(image,(320,240))
,而不是
screen.blit(image,(image,image,y))