Sky Hopper: a one-button flyer
Tap to flap and guide the bird through gaps between scrolling pillars. Simple to play, a great first physics project.
- Difficulty
- Beginner
- Source size
- 182 lines, 1 file
- Requires
- Python 3.10+, pygame-ce or pygame
- Assets
- None (drawn in code)
Controls
- Space Up click Flap
- Space Restart after landing
On this page
What you'll learn#
- Gravity and impulse-based jumping
- Spawning and removing scrolling obstacles
- Scoring when passing an object
- Rotating a sprite to match its velocity
- Forgiving hit boxes
Run it on your computer#
- Install Python 3.10 or newer and Pygame:
python -m pip install pygame-ce(orpygame). See the installation guides. - Download flappy_style.py into any folder.
- Open a terminal in that folder and run
python flappy_style.py.
No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.
How it works#
Gravity and flapping#
Every frame the bird's vertical speed grows by GRAVITY * dt, and its position changes by that speed. A flap sets the speed to a fixed upward value instead of adding to it, so rapid tapping doesn't launch the bird into space. That one choice is what makes this kind of game feel controllable.
Scrolling pillars#
The bird never moves horizontally. The pillars move left at PIPE_SPEED, new ones appear every PIPE_EVERY seconds with a random gap height, and pillars that leave the screen are dropped from the list.
Scoring#
Each pillar remembers whether it has been scored. When its right edge passes the bird it's marked and the score goes up, exactly once.
Juice#
The bird image is rotated with pygame.transform.rotate according to its speed: nose up while rising, diving while falling. The hit box is slightly smaller than the drawing, so near misses feel fair.
This is an original game inspired by the one-button flying genre, with its own art and name.
Complete source code#
"""Sky Hopper - a Pygame.net game project (a one-button flying game).
Tap to flap and steer the bird through the gaps between the pillars.
Every pillar you pass is a point; touching a pillar or the ground ends the run.
Run it: pip install pygame-ce (or: pip install pygame)
python flappy_style.py
Controls: Space, Up or a mouse click to flap. Same key to restart.
License: MIT - https://pygame.net/licenses/
"""
import asyncio
import random
import pygame
WIDTH, HEIGHT = 640, 480
FPS = 60
GROUND = HEIGHT - 50
GRAVITY = 1500 # pixels per second squared
FLAP = -440 # upward speed after a flap
PIPE_W, GAP = 70, 150
PIPE_SPEED = 170
PIPE_EVERY = 1.45 # seconds between pillars
SKY = (186, 214, 247)
PIPE = (72, 160, 100)
PIPE_DARK = (48, 120, 72)
GROUND_C = (222, 196, 130)
BIRD = (244, 197, 49)
INK = (21, 35, 63)
class Bird:
def __init__(self):
self.x = 150
self.y = HEIGHT / 2
self.vy = 0.0
self.radius = 14
@property
def rect(self):
r = self.radius - 2 # forgiving hit box
return pygame.Rect(self.x - r, self.y - r, r * 2, r * 2)
def flap(self):
self.vy = FLAP
def update(self, dt):
self.vy = min(self.vy + GRAVITY * dt, 700)
self.y += self.vy * dt
class Game:
def __init__(self, seed=None):
self.rng = random.Random(seed)
self.font = pygame.font.Font(None, 72)
self.small = pygame.font.Font(None, 30)
self.best = 0
self.clouds = [(self.rng.randrange(WIDTH), self.rng.randrange(40, 220)) for _ in range(5)]
self.reset()
def reset(self):
self.bird = Bird()
self.pipes = [] # list of [x, gap_top, scored]
self.timer = 0.0
self.score = 0
self.state = "ready" # ready, playing, over
def add_pipe(self):
gap_top = self.rng.randint(70, GROUND - GAP - 50)
self.pipes.append([float(WIDTH), gap_top, False])
def pipe_rects(self, pipe):
x, gap_top, _ = pipe
top = pygame.Rect(round(x), 0, PIPE_W, gap_top)
bottom = pygame.Rect(round(x), gap_top + GAP, PIPE_W, GROUND - gap_top - GAP)
return top, bottom
def press(self):
if self.state == "ready":
self.state = "playing"
self.bird.flap()
elif self.state == "playing":
self.bird.flap()
elif self.state == "over" and self.bird.y >= GROUND - self.bird.radius:
self.reset()
def handle_event(self, event):
if event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP, pygame.K_w):
self.press()
elif event.type == pygame.MOUSEBUTTONDOWN:
self.press()
def update(self, dt):
if self.state == "ready":
return
self.bird.update(dt)
if self.bird.y >= GROUND - self.bird.radius:
self.bird.y = GROUND - self.bird.radius
self.bird.vy = 0
self.end()
if self.state != "playing":
return
self.timer += dt
if self.timer >= PIPE_EVERY:
self.timer -= PIPE_EVERY
self.add_pipe()
for pipe in self.pipes:
pipe[0] -= PIPE_SPEED * dt
if not pipe[2] and pipe[0] + PIPE_W < self.bird.x:
pipe[2] = True
self.score += 1
if any(self.bird.rect.colliderect(r) for r in self.pipe_rects(pipe)):
self.end()
self.pipes = [p for p in self.pipes if p[0] > -PIPE_W]
if self.bird.y < -40:
self.end()
def end(self):
if self.state == "playing":
self.state = "over"
self.best = max(self.best, self.score)
def draw(self, surface):
surface.fill(SKY)
for cx, cy in self.clouds:
pygame.draw.ellipse(surface, (232, 241, 252), (cx, cy, 90, 30))
pygame.draw.ellipse(surface, (232, 241, 252), (cx + 25, cy - 14, 60, 34))
for pipe in self.pipes:
for r in self.pipe_rects(pipe):
pygame.draw.rect(surface, PIPE, r)
pygame.draw.rect(surface, PIPE_DARK, r, 3)
top, bottom = self.pipe_rects(pipe)
pygame.draw.rect(surface, PIPE_DARK, (top.x - 6, top.bottom - 22, PIPE_W + 12, 22))
pygame.draw.rect(surface, PIPE_DARK, (bottom.x - 6, bottom.top, PIPE_W + 12, 22))
pygame.draw.rect(surface, GROUND_C, (0, GROUND, WIDTH, HEIGHT - GROUND))
pygame.draw.line(surface, (160, 130, 70), (0, GROUND), (WIDTH, GROUND), 3)
b = self.bird
tilt = max(-25, min(70, b.vy / 8))
body = pygame.Surface((40, 32), pygame.SRCALPHA)
pygame.draw.ellipse(body, BIRD, (4, 4, 30, 24))
pygame.draw.ellipse(body, (230, 160, 30), (6, 14, 16, 10)) # wing
pygame.draw.circle(body, (255, 255, 255), (26, 12), 6)
pygame.draw.circle(body, INK, (28, 12), 3)
pygame.draw.polygon(body, (240, 120, 50), [(32, 16), (40, 19), (32, 22)])
rotated = pygame.transform.rotate(body, -tilt)
surface.blit(rotated, rotated.get_rect(center=(b.x, round(b.y))))
score = self.font.render(str(self.score), True, (255, 255, 255))
surface.blit(score, score.get_rect(midtop=(WIDTH // 2, 24)))
if self.state == "ready":
t = self.small.render("Press Space or click to flap", True, INK)
surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 70)))
elif self.state == "over":
t = self.small.render(f"Score {self.score} Best {self.best} - Space to retry", True, INK)
surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2)))
async def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Sky Hopper - Pygame.net")
clock = pygame.time.Clock()
game = Game()
running = True
while running:
dt = min(clock.tick(FPS) / 1000, 0.03)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
else:
game.handle_event(event)
game.update(dt)
game.draw(screen)
pygame.display.flip()
await asyncio.sleep(0)
pygame.quit()
if __name__ == "__main__":
asyncio.run(main())The code is released under the MIT license: use it, change it and build on it. See licenses.
Ideas to extend it#
- Shrink the gap slowly as the score rises.
- Add a parallax background of hills that scrolls slower than the pillars.
- Add a medal screen for scores of 10, 20 and 40.
- Use a sprite sheet to animate the wings (sprite animation).
- Save the best score between sessions.