Untitled
unknown
plain_text
3 years ago
2.5 kB
9
Indexable
import pygame
import random
pygame.init()
# set up the game window
win_width = 400
win_height = 600
win = pygame.display.set_mode((win_width, win_height))
pygame.display.set_caption("Flappy Bird")
# define colors
white = (255, 255, 255)
black = (0, 0, 0)
# set up the bird
bird_width = 50
bird_height = 50
bird_x = 50
bird_y = 250
bird_vel = 0
bird_accel = 0.5
bird_jump_vel = -10
bird_img = pygame.Surface((bird_width, bird_height))
bird_img.fill(white)
# set up the pipes
pipe_width = 50
pipe_gap = 150
pipe_vel = -5
pipe_img = pygame.Surface((pipe_width, win_height))
pipe_img.fill(white)
pipes = []
for i in range(3):
pipes.append(pygame.Rect(win_width + (i * (pipe_width + pipe_gap)), 0, pipe_width, random.randint(50, win_height - 50 - pipe_gap)))
pipes.append(pygame.Rect(win_width + (i * (pipe_width + pipe_gap)), pipes[-1].bottom + pipe_gap, pipe_width, win_height - pipes[-1].bottom - pipe_gap))
# set up the score
score = 0
font = pygame.font.SysFont(None, 50)
# main game loop
while True:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bird_vel = bird_jump_vel
# update bird position and velocity
bird_vel += bird_accel
bird_y += bird_vel
# update pipe positions
for p in pipes:
p.x += pipe_vel
if p.right < 0:
p.x += 3 * (pipe_width + pipe_gap)
p.height = random.randint(50, win_height - 50 - pipe_gap)
p.bottom = pipes[pipes.index(p) - 2].bottom + pipe_gap
# check for collision with pipes
if p.colliderect(pygame.Rect(bird_x, bird_y, bird_width, bird_height)):
pygame.quit()
quit()
# increment score when bird passes through gap in pipe
if p.right < bird_x and p.right + pipe_vel >= bird_x:
score += 1
# draw everything
win.fill(black)
for p in pipes:
pygame.draw.rect(win, white, p)
win.blit(bird_img, (bird_x, bird_y))
score_text = font.render(str(score), True, white)
win.blit(score_text, (win_width // 2 - score_text.get_width() // 2, 50))
pygame.display.update()
# check for game over
if bird_y < 0 or bird_y + bird_height > win_height:
pygame.quit()
quit()Editor is loading...