Advertisement
ZEdKasat

Flappy Bird

May 14th, 2022
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. import pygame, random
  2.  
  3. WIDTH = 600
  4. HEIGHT = 800
  5. GRAVITY = 1
  6. JUMP_POWER = 20
  7. GAME_SPEED = 5
  8.  
  9. class Pipe(pygame.sprite.Sprite):
  10.     def __init__(self, category):
  11.         super().__init__()    
  12.         self.height = random.randrange(HEIGHT/4, HEIGHT/2-50)
  13.         self.image = pygame.Surface((90, self.height))
  14.         self.image.fill((255,0,255))
  15.         self.rect = self.image.get_rect()
  16.         self.rect.left = WIDTH
  17.         if category == 0:
  18.             self.rect.top = 0
  19.         else:
  20.             self.rect.bottom = HEIGHT
  21.    
  22.     def update(self):
  23.         self.rect.centerx -= GAME_SPEED
  24.  
  25. class Bird(pygame.sprite.Sprite): # inheritance
  26.     def __init__(self):
  27.         super().__init__()
  28.         self.image = pygame.Surface((35,35))
  29.         self.image.fill((209, 0, 0))
  30.         self.rect = self.image.get_rect()
  31.         self.rect.center = (100, 50)
  32.         self.yspeed = 0  # the speed with which the bird is going down
  33.    
  34.     def update(self):
  35.         self.yspeed += GRAVITY
  36.         self.rect.move_ip(0, self.yspeed)
  37.        
  38.     def jump(self):
  39.         self.yspeed = -JUMP_POWER
  40.        
  41. pygame.init()
  42. window = pygame.display.set_mode((WIDTH, HEIGHT))
  43. run = True
  44. elements = pygame.sprite.Group()
  45. pipes = pygame.sprite.Group()
  46. clock = pygame.time.Clock() # helps us control the frame rate
  47. event_make_pipe = pygame.USEREVENT + 1
  48. pygame.time.set_timer(event_make_pipe, 1500)
  49. player = Bird()
  50. elements.add(player)
  51. while run:
  52.     clock.tick(60) # frame rate
  53.     window.fill((0,0,0))
  54.     for event in pygame.event.get():
  55.         if event.type == pygame.QUIT:
  56.             run = False
  57.         if event.type == pygame.KEYDOWN:
  58.             if event.key == pygame.K_SPACE:
  59.                 player.jump()
  60.         if event.type == pygame.MOUSEBUTTONDOWN:
  61.             player.jump()
  62.         if event.type == event_make_pipe:
  63.             p = Pipe(0)
  64.             elements.add(p)
  65.             pipes.add(p)
  66.             p = Pipe(1)
  67.             elements.add(p)
  68.             pipes.add(p)
  69.     if pygame.sprite.spritecollideany(player, pipes) or player.rect.bottom > HEIGHT or player.rect.top < 0:
  70.         run = False
  71.     elements.update()
  72.     elements.draw(window)
  73.     pygame.display.update()
  74.  
  75. pygame.quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement