python - 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()
解决方案
将if human.x > 0:
andif human.x < display_width - human.width:
移出事件循环,因为它们只会在事件队列中的每个事件中执行一次。如果玩家仍在游戏区域内,请检查主 while 循环,否则将其停止。
我还更改了一些其他内容:属性应该在__init__
方法中定义,以使它们成为实例属性而不是类属性。在课堂上使用self.x
而不是。Human.x
和变量属于人类对象,所以它们也应该是属性x_change
。y_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()
推荐阅读
- postgresql - 无法在基于 ubuntu 的发行版中安装 pgadmin4
- typescript - 'awaited T' 类型的参数不能分配给'T' 类型的参数
- python - 迭代一个数据帧以计算新特征 - Python
- javascript - 如何在 CRA 应用程序中进行代码拆分
- python - VS2019 中没有自动变量调试 Python
- html - How can I reuse the same piece of HTML/CSS across multiple files?
- c# - File.AppendAllText is outputting different text than what the sting is
- excel - 需要在数据透视表中找到所有值的平均值
- ajax - CFML 如何从 ajax 响应中获取状态码
- reactjs - React 路由器私有路由正在访问它不应该访问的路由