How do I blit an image on a keypressed event in pygame

旧街凉风 提交于 2020-06-18 08:40:34

问题


I'm trying to blit an image to the screen when the event K_SPACE is triggered. However, when I press space nothing happens. I've tried moving where the screen is updated or flipped, but i've hit a brick wall.

Here is my code:

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()

回答1:


Your image is being displayed, but only 1 time, and then it is washed away by the background. Slow down your loop using clock.tick() and see if it is being displayed.




回答2:


Since you have spacePressed, use that to draw the bullet like this:

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

You can use spacePressed for any key as well.



来源:https://stackoverflow.com/questions/19731385/how-do-i-blit-an-image-on-a-keypressed-event-in-pygame

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!