我试图记录按下空格键的次数,以便我可以限制在一定时间内按下空格键的次数,以避免垃圾邮件,从而消除游戏的意义。我通过每次按下空格键时向 keypress_count 变量添加一 (+1) 来尝试此操作,但是,一旦释放空格键,该值就会返回到 0。
class Player():
def __init__(self, x, y):
self.image = aru
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_y = 0
self.jumped = False
def update(self):
δx = 0
δy = 0
keypress_count = 0
# Player controls
kei = pygame.key.get_pressed()
if kei[pygame.K_SPACE] and self.jumped == False:
self.vel_y = -15
self.jumped = True
keypress_count += 1
print(keypress_count)
if kei[pygame.K_SPACE] == False:
self.jumped = False
print(keypress_count)
if kei[pygame.K_a]:
δx -= 10
if kei[pygame.K_d]:
δx += 10
如何才能使释放空格键后该值保持不变?
您的代码只是每次通过更新方法重置计数。您应该创建另一个实例变量:
class Player():
def __init__(self, x, y):
self.image = aru
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.vel_y = 0
self.jumped = False
self.keypress_count = 0
def update(self):
δx = 0
δy = 0
# Player controls
kei = pygame.key.get_pressed()
if kei[pygame.K_SPACE] and self.jumped == False:
self.vel_y = -15
self.jumped = True
self.keypress_count += 1
print(self.keypress_count)
if kei[pygame.K_SPACE] == False:
self.jumped = False
print(self.keypress_count)
if kei[pygame.K_a]:
δx -= 10
if kei[pygame.K_d]:
δx += 10