1

I am trying to make a clone of flappy bird to learn pygame and I'm a beginner. Just doing the basics, and I want the image to jump whenever the user presses space button or else the image keeps falling down. The problem I'm getting is that if I keep the space button pressed, it will keep flying upwards rather than just a single jump at a time. How do I fix this? (Someone explain the basic physics required to apply for the jump in flappy bird)

import pygame
pygame.init()

screen = pygame.display.set_mode((500,500))
c = pygame.image.load('cookie.png')

run = True
x,y = 50,50

while run:
    screen.fill((255,255,255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        y -= 1
    else:
        y += 0.2

    screen.blit(c, (x,y))
    pygame.display.update()

pygame.quit()

Rabbid76
  • 177,135
  • 25
  • 101
  • 146
Ali Ahmed
  • 87
  • 10

2 Answers2

1

Try using the KEYDOWN event instead of get_pressed(). get_pressed() returns an array containing the state of every key on the keyboard, and you're calling it every time your loop runs - so if you hold the key down, it's going to fire repeatedly.

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        run = False
    elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
        y -= 1
    else:
        y += 0.2

Something along those lines should work for you.

diplodorkus
  • 160
  • 1
  • 13
1

The states which are returned by pygame.key.get_pressed() as long a key is hold down. The KEYDOWN occurs only once when the key is pressed.
Use the event to lift the bird. But the position of the bird has to be computed in the main loop, to keep the bird falling down continuously.
Furthermore use pygame.time.Clock respectively .tick() to c ontrol the flops per second:

import pygame
pygame.init()

screen = pygame.display.set_mode((500,500))
clock = pygame.time.Clock()

c = pygame.image.load('cookie.png')
run = True
x,y = 50,50

while run:
    clock.tick(60)

    fly = False
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        elif event.type == pygame.KEYDOWN:
           fly = event.key == pygame.K_SPACE

    if fly:
        y -= 20
    else:
        y += 1

    screen.fill((255,255,255))
    screen.blit(c, (x,y))
    pygame.display.update()

pygame.quit()
Rabbid76
  • 177,135
  • 25
  • 101
  • 146