我正在尝试制作游戏,但你可以继续发送垃圾邮件" w" (跳跃)无限高度,当你试图制作一个平台游戏时非常糟糕。这是我的全部代码:
GRAVITY = .2
diedorgameover = False
while not diedorgameover:
for event in pygame.event.get():
if event.type == pygame.QUIT:
diedorgameover = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
x_change = -5
elif event.key == pygame.K_d:
x_change = 5
elif event.key == pygame.K_s:
y_change = 5
elif event.key == pygame.K_w:
y_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
x_change = 0
if event.key == pygame.K_s or event.key == pygame.K_w:
y_change = 0
#adding gravity to y_value
y_change += GRAVITY
x += x_change
y += y_change
if y >= gameDisplay.get_height() - 68:
y = gameDisplay.get_height() - 68
y_change = 0
#draw everything
gameDisplay.blit(background_image,(0,0))
red(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
如果您对此问题有任何见解,我将非常感激。
答案 0 :(得分:0)
如果玩家触地,您可以定义设置为on_ground
的{{1}}变量。当用户想要跳转时(按'w'),您首先检查True
,然后更改if on_ground:
并将y_change
设置为on_ground
。
False
同时删除这些行,否则如果释放该键,播放器可以在空中停止:
import pygame
pygame.init()
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
GRAVITY = .5
player_img = pygame.Surface((30, 50))
player_img.fill((40, 120, 200))
x = 100
y = 500
x_change = 0
y_change = 0
on_ground = False
diedorgameover = False
while not diedorgameover:
for event in pygame.event.get():
if event.type == pygame.QUIT:
diedorgameover = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
x_change = -5
elif event.key == pygame.K_d:
x_change = 5
elif event.key == pygame.K_s:
y_change = 5
elif event.key == pygame.K_w:
# Only jump if the player is on the ground.
if on_ground:
y_change = -12
on_ground = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
x_change = 0
y_change += GRAVITY
x += x_change
y += y_change
# If the player is on the ground.
if y >= gameDisplay.get_height() - 68:
y = gameDisplay.get_height() - 68
y_change = 0
on_ground = True
gameDisplay.fill((30, 30, 30))
gameDisplay.blit(player_img, (x, y))
pygame.display.update()
clock.tick(60)
pygame.quit()