我是Python新手,我一直在尝试做一个简单的游戏,你可以向左移动一个正方形,向右移动,让它跳跃。在过去的几天里,我一直在尝试做跳跃运动,但没有成功。有人能帮助我吗?
import pygame
pygame.init()
xscreen, yscreen = 1000, 500
screen = pygame.display.set_mode((xscreen, yscreen))
pygame.display.set_caption("Pygame")
width, height = 50, 50
x, y = 950, 200
vel, jumping_points = 10, 10
run = True
while run:
pygame.time.delay(100)
# Checks if the player wants to quit the game.
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Checks if a key was pressed and moves the square accordingly.
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] and x + width < xscreen:
x += vel
if keys[pygame.K_LEFT] and x > 0:
x -= vel
# Unfinished jump movement.
if keys[pygame.K_SPACE] and y > 0:
while True:
if jumping_points >= -10:
y -= (jumping_points ** 2) / 5
jumping_points -= 1
animation()
else:
jumping_points = 10
break
# Updates the screen surface.
animation()
pygame.quit()
编辑:删除,对问题不重要。
1条答案
按热度按时间8hhllhi21#
不要尝试在应用程序循环中实现控制游戏的循环。使用应用程序循环。添加一个变量
jump = False
。当按下空格键时设置该变量。使用KEYDOWN
事件而不是pygame.key.get_pressed()
。在应用程序循环中实现跳转算法,而不是额外的循环:此外,你需要改变计算跳跃的公式。
(jump_points ** 2)
的结果总是一个正值,玩家永远不会下来:y -= (jumping_points ** 2) / 5
或
使用
pygame.time.Clock
控制每秒帧数,从而控制游戏速度。pygame.time.Clock
对象的方法tick()
以这种方式延迟游戏,即循环的每次迭代都消耗相同的时间。参见pygame.time.Clock.tick()
:此方法应每帧调用一次。
这意味着循环:
每秒运行60次。
最小示例: