让我的角色在Pygame中流畅地移动

时间:2019-05-24 23:52:58

标签: python pygame

我正在尝试为com sci final创建一个pygame,但是我的老师在解释pygame的工作方式方面做得并不出色。我的麻烦是我需要使我的角色(我创建的自定义精灵)在按住四个箭头键中的任意一个时流畅地移动。到目前为止,我所能做的就是让每个按键都能移动它,而我不知道该如何解决。

我不确定我的代码是否最有效,但实际上取决于您所按的键,不仅X和Y坐标会更改,而且png图像也会更改以面向适当的方向。这都是使用blit进行平局。

import pygame

pygame.init()

def redraw_game_window(texture):
    screen = pygame.display.set_mode(size)
    background_image = pygame.image.load("lava.jpg").convert()
    background_image = pygame.transform.scale(background_image, (size))
    screen.blit(background_image, [0, 0])
    texture= pygame.transform.scale(texture, (65,64))
    texture=texture.convert_alpha()
    screen.blit(texture,(EarlX,EarlY))

size=1200,600
EarlWidth=65
EarlLength=64
texture = pygame.image.load("UpFacingEarl.png")
EarlX=500
EarlY=150
speed=50

inPlay= True
while inPlay:
    redraw_game_window(texture)
    pygame.time.delay(20)

    keys = pygame.key.get_pressed()
    if keys[pygame.K_ESCAPE]:
        inPlay = False
    if keys[pygame.K_LEFT]:
        texture = pygame.image.load("LeftFacingEarl.png")
        EarlX-=speed
    if keys[pygame.K_RIGHT]:
       texture = pygame.image.load("RightFacingEarl.png")
       EarlX+=speed
    if keys[pygame.K_UP]:
        texture = pygame.image.load("UpFacingEarl.png")
        EarlY-=speed
    if keys[pygame.K_DOWN]:
       texture = pygame.image.load("DownFacingEarl.png")
       EarlY+=speed

    pygame.display.flip()

我们将不胜感激任何改进我的代码的帮助,我知道我不包括png,但是我在那儿无能为力。

1 个答案:

答案 0 :(得分:3)

首先,您不需要将代码加倍。现在我们已经解决了这个问题:

screen = pygame.display.set_mode(size)

应仅在程序开始时调用。并非每次!这就是您的程序无法运行的原因。 以下是一些其他不重要的问题可以解决:

这也应该只在开始时调用:

background_image = pygame.image.load("lava.jpg").convert()
background_image = pygame.transform.scale(background_image, (size))

总而言之,您的redraw_game_window函数应如下所示:

def redraw_game_window(texture, EarlX, EarlY, screen): #you should pass all the variables you are using to the function. Python doesn't work well with global variables. if you really want to use global variables like you did here, use the global keyword
    screen.fill((0,0,0)) #clear the screen

    screen.blit(background_image, [0, 0]) #draw new background

    texture = pygame.transform.scale(texture, (65,64))
    texture = texture.convert_alpha()
    screen.blit(texture,(EarlX,EarlY)) #draw earl

此事件循环很好:

for event in pygame.event.get():
    if event.type == pygame.QUIT: #you need this or else pressing the red "x" on the window won't close it
        quit()

keys = pygame.key.get_pressed()

if keys[pygame.K_ESCAPE]: #press esc to exit program
    quit()

if keys[pygame.K_UP]:
    EarlY -= 1

if keys[pygame.K_DOWN]:
    EarlY -= -1

if keys[pygame.K_LEFT]:
    EarlX += -1

if keys[pygame.K_RIGHT]:
    EarlX += 1