Pygame新手在这里,我正在尝试制作Flappy Bird克隆。我想设置控件,以便按住跳键不会让鸟跳。与原始游戏一样,玩家必须继续点击跳跃以保持鸟类漂浮。我尝试使用pygame.key.set_repeat()来关闭键重复,但它似乎没有工作。通过回顾关于同一主题的其他帖子,我开始认为它可能是我的事件循环中的一个问题。
谢谢你的帮助!
我的代码:
import pygame
class Bird(pygame.sprite.Sprite):
def __init__(self):
#load pic of bird
self.image = pygame.image.load('ball.png')
#sets bird pic as a rectangle object and moves position to centre
self.rect = pygame.rect.Rect((320, 240), self.image.get_size())
#default value for gravity
self.dy = 0 #how much to add to current player position
def update(self, dt, game):
pygame.key.set_repeat()
key = pygame.key.get_pressed()
if key[pygame.K_UP]:
print "jump!!!"
self.dy = -400
#apply gravity
self.dy = min(400, self.dy + 40)
self.rect.y += self.dy * dt
#collision detection
if(self.rect.top <= 0): #top
self.rect.y = 0
self.dy = -4
elif(self.rect.bottom >= 480): #ground
self.rect.y = (480-self.rect.width)
#blit image to screen
screen.blit(self.image, (320, self.rect.y))
pygame.display.flip()
print self.rect.center
print self.dy
class Ground(pygame.sprite.Sprite):
def __init__(self):
self.image = pygame.image.load('ground.png')
self.rect = pygame.rect.Rect((0, 480-self.image.get_width()), self.image.get_size())
class Game(object):
def main(self, screen):
clock = pygame.time.Clock()
#create background and player object
background = pygame.image.load('background.png')
#instantiate bird object
self.bird = Bird()
self.ground = Ground()
while 1:
dt = clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
screen.blit(background, (0, 0))
pygame.display.flip()
self.bird.update(dt / 1000., self) #for some reason, update must go last
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((640, 480))
Game().main(screen)
pygame.quit()
答案 0 :(得分:2)
pygame.key.set_repeat()在这里没有任何改变,因为默认情况下禁用了键重复。
你的错误很简单:你的程序检查&#34; update()&#34;方法,如果K_UP 当前按下 - 但您应该只检查事件,因为按钮被事件拦截。
简而言之:事件告诉您是否按下了键并且&#34; get_pressed()&#34;告诉我是否按下键。
所以你必须编写类似&#34; jump()&#34;的方法。当你按下K_UP接收事件时执行它 - 不检查内部的键状态&#34;更新()&#34;方法。并且不要忘记从&#34; update()&#34;删除跳转代码方法!
class Bird(pygame.sprite.Sprite):
def jump(self):
print "jump!!!"
self.dy = -400
(...)
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
return
if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
self.bird.jump()