Today, we're going to start laying a foundation for one of the most important objects in our game, the bird. This bird will have to update each frame and be drawn on top of the canvas we have thus far.
import pygame
import os
class Background:
image = pygame.image.load(os.path.join("assets", "background.png"))
PANNING_VELOCITY = 60
def __init__(self, width, height):
self.width = width
self.height = height
self.image_width = self.image.get_width()
self.image_height = self.image.get_height()
self.x_offset = 0
def update(self, dt):
self.x_offset = (self.x_offset - self.PANNING_VELOCITY * dt) % self.image_width
def draw(self, screen):
screen.blit(self.image, (self.x_offset, 0))
screen.blit(self.image, (self.x_offset - self.image_width, 0))
def main():
run = True
# Define a Pygame clock
clock = pygame.time.Clock()
# Initialize the background
**bg = Background(SCREEN_WIDTH, SCREEN_HEIGHT)**
while run:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
# Updating and drawing
**dt = 1/60 # time between frames**
SCREEN.fill((255, 255, 255)) # Clear background
**bg.update(dt)
bg.draw(SCREEN)**
pygame.display.update()
clock.tick(60)
Step 1: Creating the Bird
GRAVITY
and JUMP_VELOCITY
are going to help us later when we want to characterize how the bird flies.COLORS
contains all the different bird colors (we'll see how this is useful in a few weeks).IMAGES
is a dictionary mapping the color to the preloaded bird image of that color so that we don’t have to load them for every single bird. We also scale each image by 3 (since they were a little small just as 16x17 pixel images).birds
is going to be an array of the current birds.x
, y
) and color
. Within the constructor, we'll set initial values for color
, image
, and vy
. We'll also define an instance variable rect
which stores the bird's position, height, and width.Step 2: Implementing game physics.
<aside> 💡 Many games wouldn't be fun without movement, collisions, and other interactions. This is where game physics comes in. Wikipedia defines game physics as: "the introduction of the laws of physics into a simulation or game engine". Unlike real life, computation for our game only occurs in discrete intervals (i.e. our computation occurs once per game loop iteration). As a result, our game physics is only an approximation of real-life physics, but we can get pretty close.
For our game, the physics aren't too complicated since we're mostly dealing with the bird's movement (this week) and collisions (next week).
<aside> ⚙ Physics Review - Kinematics Kinematics deals with the motion of objects. From physics, we might remember the relationships between position, velocity, and acceleration: $x=vt$ and $v=at$.
We also have our four kinematic equations:
</aside>
</aside>