【发布时间】:2017-09-03 04:44:44
【问题描述】:
设置了以下代码,因此当头像被移动到屏幕上并且点击空格键或向上键时,它会移动一次,但当它被按住时,它不会一直向上移动(在空中)。我需要更改我的代码,以便在按住键时移动是恒定的。
import pygame, sys, time, random
from pygame.locals import *
class Player(Duck):
"""The player controlled Duck"""
def __init__(self, x, y, width, height):
super(Player, self).__init__(x, y, width, height)
# How many pixels the Player duck should move on a given frame.
self.y_change = 0
# How many pixels the spaceship should move each frame a key is pressed.
self.y_dist = 50
def MoveKeyDown(self, key):
"""Responds to a key-down event and moves accordingly"""
if (key == pygame.K_UP or key == K_SPACE):
self.rect.y -= self.y_dist
def MoveKeyUp(self, key):
"""Responds to a key-up event and stops movement accordingly"""
if (key == pygame.K_UP or key == K_SPACE):
self.rect.y -= self.y_dist
def update(self):
"""
Moves the Spaceship while ensuring it stays in bounds
"""
# Moves it relative to its current location.
self.rect.move_ip(self.y_change, 0)
# If the Spaceship moves off the screen, put it back on.
if self.rect.y <= 0:
self.rect.y = 0
elif self.rect.y > window_width:
self.rect.y = window_width
while True: # the main game loop
for event in pygame.event.get(): #Closes game
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYUP:
player.MoveKeyUp(event.key)
elif event.type == pygame.KEYDOWN:
player.MoveKeyDown(event.key)
【问题讨论】:
-
即使它被关闭为题外话,答案应该是有帮助的:stackoverflow.com/questions/43154793/…
-
请提供complete but minimal example。我们想要无需调整即可运行的示例。
标签: pygame python-3.5