首页 > 解决方案 > Pygame精灵穿越屏幕

问题描述

问题是当我按下左键或右键时,精灵会穿过屏幕的左右边界。但是当我点击它时,只有当我持续按住键时它才会交叉

这是人类的课程

class Human:

y = display_height * 0.8
x = display_width * 0.45
width = 120
image = pygame.image.load('yasin/alien1.png')

def run(self):
    gameDisplay.blit(Human.image, (Human.x, Human.y))

这是贯穿整个游戏的主循环

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        gameExit = True
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            if human.x > 0:
                x_change = -8
            else:
                x_change = 0
        elif event.key == pygame.K_RIGHT:
            if human.x < display_width - human.width:
                x_change = 8
            else:
                x_change = 0
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
            x_change = 0
human.x += x_change
human.run()

标签: pythonpygame

解决方案


if human.x > 0:andif human.x < display_width - human.width:移出事件循环,因为它们只会在事件队列中的每个事件中执行一次。如果玩家仍在游戏区域内,请检查主 while 循环,否则将其停止。

我还更改了一些其他内容:属性应该在__init__方法中定义,以使它们成为实例属性而不是类属性。在课堂上使用self.x而不是。Human.x和变量属于人类对象,所以它们也应该是属性x_changey_change然后你可以添加一个update方法来进行Human边界检查和移动。

import pygame


display_width, display_height = 640, 480

class Human:

    def __init__(self):
        self.image = pygame.image.load('yasin/alien1.png')
        self.y = display_height * 0.8
        self.x = display_width * 0.45
        self.x_change = 0
        self.y_change = 0
        self.width = 120

    def run(self, gameDisplay):
        gameDisplay.blit(self.image, (self.x, self.y))

    def update(self):
        self.x += self.x_change
        # Check if the human is outside of the game area.
        if self.x < 0:
            self.x_change = 0  # Stop it.
            self.x = 0  # Reset the position, so that we can move again.
        elif self.x > display_width - self.width:
            self.x_change = 0
            self.x = display_width - self.width


def main():
    pygame.init()
    gameDisplay = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()
    human = Human()

    gameExit = False

    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    human.x_change = -8
                elif event.key == pygame.K_RIGHT:
                    human.x_change = 8
            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    human.x_change = 0

        human.update()

        gameDisplay.fill((30, 30, 30))
        human.run(gameDisplay)
        pygame.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pygame.quit()

推荐阅读