我如何在pygame中的按键事件上进行blit和image

时间:2013-11-01 16:50:52

标签: python animation pygame render blit

我正在尝试在按下事件K_SPACE时将图像blit到屏幕。 但是当我按空间时没有任何反应。我已经尝试过移动屏幕更新或翻转的地方,但我碰到了一堵砖墙。

感谢您的帮助。

def Play():

background  = pygame.image.load(bifPlay).convert() 
char = pygame.image.load(mif).convert_alpha()
bullet = pygame.image.load(bulletLoad).convert()
zombie = pygame.image.load(zombieLoad).convert_alpha()
#converting images needed so pygame can use them
x,y = 115,350
movex, movey = 0,0
zombieX = 1100
zombieY = random.randint(0,675)
bulletX = x+90
bulletY = y+37.5
clock = pygame.time.Clock()
zombieSpeed = 100
bulletSpeed = 200
while True:

    milli = clock.tick()
    seconds = milli/1000.
    zomMovement = seconds*zombieSpeed
    bulletMovement = seconds*bulletSpeed
    zombieX-=zomMovement
    bulletX+=bulletMovement
    x += movex
    y += movey
    screen.blit(background,(0,0))
    screen.blit(char,(x,y))
    screen.blit(zombie,(zombieX,zombieY))
    spacePressed = pygame.key.get_pressed()

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
#code above allows the user to exit - while program is running if event is exit
#allows user to exit program.
        if event.type == KEYDOWN:
            if event.key == K_UP:
                movey =-1
            elif event.key == K_DOWN:
                movey =+1
            elif event.key == K_SPACE:
                screen.blit(bullet,(bulletX,bulletY))
        if event.type == KEYUP:
            if event.key == K_UP:
                movey =0
            elif event.key == K_DOWN:
                movey =0

    if y == 675: 
        y -= 1
    if y == 0: 
        y +=1
    pygame.display.update()

2 个答案:

答案 0 :(得分:1)

您的图像正在显示,但只显示一次,然后被背景冲走。使用clock.tick()减慢循环,看看它是否正在显示。

答案 1 :(得分:1)

由于你有spacePressed,用它来画这样的子弹:

if spacePressed[K_SPACE]:
    screen.blit(bullet, (bulletx, bullety))

您也可以将spacePressed用于任何键。