This video shows you how to create an entire endless runner game in python using Pygame! Start to finish this tutorial goes line by line and teaches you everything you need to know whether you are a total Pygame novice or just looking to hone your skills!
We start by defining the game screen and creating dimensions and game variables, setting rgb color values and drawing the game floor. Then we draw the player onto the screen, and create the controls for jumping and lateral back and forth movement using the space key and left and right arrow keys. Then we create a list of obstacles and randomly generate spawn locations for an infinite loop, then we handle restart tracking and score counting!
Once you complete this game check out the rest of the channel for tons of other tutorials and instructional videos on a wide variety of subjects!
what's going on you guys welcome back to
the channel and today we're going to
learn how to build this infinite runner
game in python using pygame
[Music]
so
as always with a python pie game game
first thing you want to do is import
pygame in the very beginning
um a ton of what we do for the game
functionality is built into the pi game
module and so you just first thing you
want to do is import the package
and we'll see why later but if you're
going to have any kind of rng in your
game which is pretty common some sort of
randomly generated
difficulty or enemy spawning or anything
like that i always import the random
module as well
you certainly can hold off on that until
you actually need it and do it on a
case-by-case basis but if you include it
as kind of part of your standard package
it'll usually benefit you in the long
run
um so then the next thing to do is just
initialize pygame this is saying
anything that's inside of the
um inside of the pie game module now
it's up and running so the init
is the next thing to do and then um i
like to just create some like uh game
constants
and so this is where i'll put like
colors because a lot of the colors in
pie game are rgb fashion and so if you
just want to be able to call white or
black instead of rgbe typing it out
every time you would just put those here
so for now i'll just throw a few down um
and if we decide later on in the game
that we want more we can come in and add
them and then i'll just make a section
here for game variables also so things
like score
player positions enemy positions things
like that we'll put those in here
and if you're following along line by
line you want to make this exact game go
ahead and make player x player y 50 and
200 for now um those will change during
the game but for now that's where we're
gonna start them and then two more
variables i'm gonna make and i'm gonna
or they're not really gonna be variables
they're gonna be constants are gonna be
screen width and screen height and
because they're pretty much going to
stay constant i'm going to make them all
caps that's kind of a normal python
standard but you can play around with it
if you don't like it
and so let's go ahead and use those
variables we just made width and height
and let's go ahead and my indentation is
kind of funky let's define our screen so
it's going to be this pie game built in
pie game
dot display
dot set mode and then we just give it a
size inside of these brackets and so we
will do width
by height
and you could just type in 450 and 300
there if you weren't going to use it
anywhere else like you didn't need that
as a variable then you could just type
them in there that's fine
i prefer to do it this way and if we
ever want to reference something that's
exactly the width of the screen then you
can do it right there
and then uh
python.display.setcaption this isn't
something you have to do but uh it gives
a title to your window when you open it
up and so since this is just kind of an
infinite runner we will call it infinite
runner i like that call it whatever you
want
and then i always create a variable for
my background
so later on when we do a fill command
i just reference the background that way
if you do want to load an image in here
later
or anything like that you can just come
and edit your background variable
then you always want to define a frame
rate and we'll get into this when we get
into the game loop but you want a speed
at the beginning of your game
that it will run at on any device and so
we're saying 60 frames per second
and the last thing that i do
initializing everything before actually
starting the game loop is i'll define a
font because almost every game will
include some text so in this case we're
going to use one of the
built-in fonts that comes with your
install so we'll do freesandbold.ttf
and then we'll give it a size of 16.
that looks pretty good when i was making
this before
and then we'll define a timer
pie game dot time dot clock okay
and these are the things basically what
you're looking at on your screen right
now i
make this although i'll play around with
the width and the height depending on
what game i'm making and these variables
will obviously change to pan the game
but i basically this is the frame of
every game that you're going to create
and you start
you'll use almost everything you see on
the screen here in any pi game game
and now we'll actually get into the game
functionality so we'll set this variable
running equals true and then we're going
to create this is called the main game
loop and it's just any time we're
running so while running equals true
didn't need a column there
but while running equals true and then
now we're going to start seeing
timer.tick at our frame rate so this is
what's actually going to control the
speed at which it runs and we'll do
screen dot fill
with the background
and so you'll see i kind of defined all
the variables knowing i was going to
need them later if you were just kind of
muddling through this you'd be jumping
back and forth into the loop realizing
you need another variable going back up
and creating it
okay but now we'll get into
just kind of the quickest way to get the
screen to pop up and so for event
handling we're going to create for event
in
pygame.event.get
and that's the code to get anything
going on your computer clicks mouse
position um buttons that are pressed on
the keyboard anything that's pi guy
pygame.event.get
and then we are going to
check and see if the if the game is
exited out so it's
event.type
is equal to
pi game and then the built-in quit which
is gonna be the the uh x in the top
right screen
then we just wanna set running
equal to false and so that's going to
make sure we don't have an infinite loop
if you start this game up and you don't
have any conditions that could end
running
then your computer is basically going to
error out python is going to error out
because that's called an infinite loop
and that will totally bring your
computer down
um there's there's no processing uh
power capable of doing something
infinite yet
uh okay so let's get out of the event
handler later inside of this event um
code this for event in pi game that's
also where we'll put conditions for like
jumping and moving the player character
but for now we just want the screen to
open and so the last thing we're going
to throw in here is going to be
pygame.display.flip
to kind of throw everything onto the
screen
and then we'll throw pie game.quit as
this very last screen and we're going to
go ahead and run this and i want to see
if i missed anything we should just get
our
rectangular screen
it closed right away has no attribute
time
aha
that is supposed to be time not time
all right so there we go we just got
this boring uh screen nothing going on
but uh we created a window so let's go
ahead and start getting some stuff in
the window first thing i'm going to do
is i'm going to create the floor so
that's going to be just below
where we fill the screen with the
background
i'm going to just draw a rectangular
floor
that will kind of consider the base of
the game
so i'm going to just call it a variable
floor and it's going to be
pygame.draw.rect
that's the built-in
instruction for drawing a rectangle on
screen you could do it as a line and
mess around with line thickness if you
want i think rectangles are kind of
easier
but
if you don't like how i do it do it your
own way
so then we'll go for the rectangle we
give it a
x starting position y starting position
and then width and then height and here
you can see because i had a
width variable for the width of the
screen that if i start at 0 and i make
it width long it should span the entire
screen so let's go ahead and run that
again
and you can see we just get a big
rectangle across the bottom of the
screen but i'm going to go ahead and
call that the floor i think that looks
pretty good let's go ahead and draw the
player next
so i'll call it player
and we will make it equal to
again pygame.draw.rect
and now this one's going to be a little
different we're going to put on the
screen we'll make him green so it's
really easy to see and then for those
variables
we actually want him to be at player x
and player y
so
those are going to be things that change
right player y is going to change when
the player jumps and player x will
change with the arrow keys if you decide
to go left and right
so we're going to make those variables
rather than constants
but we'll make the size constant so
we'll make him a 20 by 20 rectangle
and i can touch on briefly at the end of
the video how to pull in an image if you
do want that to be like an 8-bit
character rather than
a rectangle it's pretty easy but we're
going to do it with just built-in shapes
because i don't want to assume for this
video
that you've gone out and pulled in
images or anything
okay so we can't do anything with him
yet but we do have a little rectangle
and he's sitting on a runway and so
right there that's pretty cool we got
start of our game
let's go ahead and put in the jumping
code because it's kind of simple but
it's actually
it can get a little confusing so
let's go ahead we're going to need a new
section in here if event.type equals and
now instead of checking if it's been
quit we're checking for something called
key down which is a key press
and later on we'll also get into key up
which is key release but we'll start
with key down
and we'll check if event dot key so now
we're looking to see that the actual key
that was pressed
is equal to
pygame.k
underscore space so that's the built-in
for the space bar and then we'll check
something else
we're going to check that and
y change is equal to
zero and the reason for this is when we
do jump we're going to add a variable to
the player's y condition called y change
and we want to kind of work like jumping
in real life where gravity is going to
have a progressive effect
um so we're only going to let the space
bar do anything
if you're not actively jumping so we'll
go back up into game variables
and we'll call y change equal to zero
initially saying you know you will be
able to jump right when the game starts
up
um okay so what we're gonna do is we're
gonna set y change equal to
a value and i've messed around with this
a little bit i made the game already and
i found 18 worked pretty good but um you
can you can modify it if you want um i
like 18 and for now that's what i'm
going to go with and so now let's put in
the actual jump logic and it's going to
go like this it's going to
um we're going to start by checking to
see
if y change is
greater than zero
so now we're checking to see if we have
just jumped essentially
or
the player is less than 200 and less
than might seem weird here but the
actual pie game coordinate system i'll
open the oh it's not gonna let me yet
um
let me just throw a pass in here
because i want to pull the window up
real quick to talk about this
the
less than is not
oh
player y is less than 200 okay there we
go
um i want to talk about this real quick
this point where my mouse is right now
in pi games coordinate system is 0 0 so
as you go further right your x
coordinate gets larger but as you go
down your y coordinate gets larger so it
actually might seem counter-intuitive
but if you want this guy to essentially
jump you need to subtract values from
the
player y so when we say we're checking
to see if the player y is less than 200
we're checking to see if he's above the
floor basically
so that took me a while to get that
window open but hopefully that makes
sense and it should make sense once we
get this code in there
but basically what we're going to say
this means that y change is positive
we're going to have the
player y
minus equal to
y change so
when you jump i'm saying 18 we could
make this um a negative 18 and then you
could do plus equals
it doesn't matter either way that you do
it you just have to be aware
um
of how the coordinate system is going to
equal
is is going to work but then the next
thing we're going to do is we're going
to add gravity so that's another game
variable i want to have in here i'm just
going to make it equal to 1 but if you
want to see the effects of different
of different gravity you can play around
with that on your own time
so this is saying that while you're
actively jumping and going upward we're
going to subtract gravity so every scan
of it so 60 times per second we're going
to take one away from your jump um and
we're going to subtract gravity and then
this second piece is saying even while
you're still in the air so when y change
is no longer positive which means now
you're coming back down
um
we are still going to keep subtracting
gravity so you'll progressively fall
faster and faster
so hopefully that makes sense but
then the next thing we want to check is
if somehow because
it could happen if the player
y ever goes greater than 200 meaning
it's gone past the floor um we're just
gonna force it back to the floor so this
is just kind of checking for weird
conditions where like gravity is going
so fast that you're falling 10 or 15
pixels a second it might for one scan
take you below the floor
and if we don't put this line in your
block might just get stuck below the
floor so
include that
and if you don't believe me you can
remove it and see what happens
but then we'll do this other piece where
we reset y change so now we're saying
okay the player's back on the floor but
y change is still negative
and then we're going to
set our y change back equal to zero so
that's basically reinitializing you and
giving you the ability to jump again
you could also use an intermediate
variable called like jumping set equal
to false initially when you price press
space set equal to true
once you land back on the ground set it
back equal to false
um that would be another valid way to do
the jump logic but let's just run this
and see if we have a good looking uh
jump animation
so yeah you can see i can do it once
um but i can't do it over and over again
so what is going on
if player is oh i keep doing player it's
gotta be player y
there we go
that's why it's important to run your
program
fairly often while you're coding it and
make sure there we go
make sure that
it behaves as you'd expect it to that
far into your routine because you catch
a lot of little things like that and if
you don't test it fairly frequently
while you're writing it you'll end up at
the end of a fairly large program with
12 things to debug so
all right let's go ahead and add left
and right motion using the left and
right arrow keys
um so again this is going to use more in
our key down space we're also going to
now add conditions for
if event dot key is equal to pi game
dot k
and then this will be k right and k left
okay
right
okay and if it's equal to k right then
we're going to do something called x
change right we have our y change now
we're going to do x change if it's right
we want to go to 2
and i'll just copy this whole thing and
we'll just tweak it for left
and if it's left
we are gonna want it
to go minus two and this is kind of an
easy way of handling
left and right with one variable so now
i'm gonna get rid of the space in here
but we're gonna add a new section called
pie game key up so we're checking for
the release and if the left or right key
is released it doesn't matter if it's
left or right
we want the character to stop moving at
that point
so
what we're going to do is down here
where we have the
player x and player y changing
currently we just have the y change
we're going to add a section for the
player x change
and we're going to use some limit
conditions because we don't want the
player to be able to move off the screen
so we're going to say as long as the
player x is greater than uh or equal to
0 and less than or equal to 430
right which are the boundaries because
the block is 20 wide so if he's
currently at 430 that means the right
edge of it is going to be equal to 450
just a little math for you there
but in that case we're going to do plus
equals
exchange
and one thing before i forget we do want
to come up into our game variables and
we want to create exchange as well and
we want to be equal to 0 when the game
starts so you don't start off sliding
one way or another
and now we're just going to add some
stuff as well
just on the off chance that you do slide
too far off screen to the left
we are just going to put you back to
zero and we'll do the same thing
on the right so there are i mean you
could tweak this statement get rid of
the equals and do
greater than zero less than 430 but then
you can get a problem with uh
like going back to the right going back
to the left
um so what if if you can get working for
you that's great i always add these
because the number of times weird stuff
happens where you end up one pixel too
far to the right and your game just
freezes you can't move
so i like adding these boundary
conditions just saying if somehow you go
beyond the boundaries we're gonna bring
you back into the screen
okay
so let's go ahead and see i believe
that's all we need for our left and
right arrow keys to get us moving yep
and we can jump and move left and right
let's see if we can get off screen we
can't to the left
and honestly like if you're following
along just once you get to the point
where you have a little rectangle that
can jump around and move left and right
like it's already kind of fun
um maybe that's just me
but uh okay so um that's pretty good the
next mechanic i want to add is going to
be the obstacles and i've waited till
this point because it kind of seems
complicated to have like
infinite um obstacles coming at you and
there's a whole bunch of ways that you
could do this so before anyone gets in
my comments and says like oh well you
should have done this you should have
done that there are so many ways that
you could do
spawned enemies you could
constantly be creating a list and
tracking like new ones
whatever you want
because the game i created
really would be too jumbled if it ever
had more than three obstacles on the
screen at one time
i'm gonna create three obstacles i'm
gonna have them start in a set position
and move from right to left and then
once they get off screen left i'm going
to have them randomly select a position
somewhere to the right of the screen to
spawn in at
and i'm going to have them continually
in a loop where if they make it off
screen to the left
pick a new position on the right and
spawn back in and i'm just going to use
three obstacles so that's what we're
going to do here
i'm going to create another couple
colors because i i kind of like the idea
of these guys being like red orange and
yellow so
i'm going to put those three colors up
in here as well you can grab any rgb
values you want
if you want to follow along i looked
these up ahead of time
and they all look pretty good
red orange and yellow are good bad guy
colors if you've ever seen tron
okay
all right and so uh one more thing i'm
gonna put in my game variables is i'm
going to make a list of obstacles
positions
and you'll see why we need this in a
second but this is also going to be
where they'll spawn in at so
we'll just go with 300 450 and
that works pretty good for the size we
created i'm going to create another
variable and i'm going to call it
obstacle if i can spell it right uh you
could maybe call them
enemies too if you want because uh
obstacle is kind of hard to spell and i
would just give obstacle speed
of two to start
and let's see that may be all we need
for this so okay let's go down into
where we draw everything
and uh let's go ahead and draw
underneath the player obstacle
obstacle
actually this is the easiest way to do
it let's do 4i in
obstacles there we go and we will just
say
pie game dot draw dot wrecked
and we'll put it on the screen
now then my then my uh theory about
three colors will
not look as sweet so let's go ahead and
just do it do it this way sorry i'm
making game time decision
obstacle zero is going to be equal to
pygame.draw.rec
just like the player
we're gonna put it on the screen
and we are going to make this guy red
and let's start giving him the
coordinates
0 is going to be at position obstacles
index value zero
and then uh
we're gonna put it at 200 20 and 20 and
those three can be constants because
we're not going to make the enemies jump
and then i will go ahead and copy this
guy in copy this and we'll do obstacle
zero one and two i started numbering
zero one and two so that their values
would match the indexes
because a list always starts from zero
if you don't know that now you know
but we're going to make them red orange
and yellow and all we need to modify is
where they start in their x positions
and so this will get them to draw in
when we run it but they're not going to
be moving yet so you can see you can
only see red because um orange and
yellow are over here
so let's go ahead and handle the
obstacle movement
and this is kind of the best like
python programming bit in this game
pretty much everything else is just
a little bit of style a little bit of
knowledge of object oriented programming
but here we're going to be using a for
loop and we're going to say 4i in range
and the range is going to be the length
of our list of
obstacles
so some people say you can do 4i in
obstacles and that should work as well
that's true but i want to be real clear
about what i'm checking
and then let's create a new variable and
say if active because we want to plan
for if you collide with an enemy the
game ends
and so at the beginning
game variables we'll say active equals
true
okay and then what we'll say is if you
hit an enemy active is going to become
equal to false so
let's go ahead here
if active what do we want to do we want
obstacles at position i so this is going
to
update every obstacle in our lists
position
and how much do we want to change it by
well we want to move it left
at obstacle speed
okay
and so
uh
that's it for moving them but then we
also want if
obstacles
i
is
less than
negative 20. so at that point the object
has moved completely off screen to the
left
well what do we want to do i think it's
actually easier
so there are two ways you could do it
you could delete it from your list and
then add a new value to the list or you
can just overwrite it like there's no
there's not going to be some funny
business where the object looks really
weird going back across the screen to
the right
if we just overwrite that entry with a
new position
so what we're going to do is we're going
to reuse that value obstacles i at
whatever index just finished and we're
going to set it equal to random
dot rand in so this is kind of our our
rng
piece to the game
and i'm just going to use this range 470
to 570 because that's off screen to the
right
um and so this is going to kind of
affect the spacing a little bit so they
could in theory
progressively get closer and closer
together further and further apart um it
could get a little goofy looking but uh
we'll see when we play it these are the
sort of variables
you can modify as much as you want
and then this is also going to be where
we increment the score so i know we're
not displaying that anywhere yet um
but
uh this is once we draw that onto the
screen this is gonna be how we handle
that so okay
so let's do one last thing because we
are inside the if active loop
and um
if player dot collide wrecked
and uh here's where it maybe if i had
drawn them in a for loop this would be a
little easier but we're going to say if
player collide wrecked with obstacle
zero and this collide rect is a built-in
pie game function
that
is uh automatically checking two
rectangles to see if they collide with
each other so because the player and the
enemies are both currently rectangles
we can just use it if you were to pull
in an image you would have to also use
the pygame.getrect function to get a
rectangular
set of coordinates for your image it's
really easy to do but since we just are
drawing rectangles for everything then
we can just do it like this
okay so if player.collide
obstacle zero one or two
um so that's saying the player just
collided with one of the enemies we're
just gonna set active equal to false and
so all i think that this will do now is
it'll get stuff moving from right to
left i'll try to jump a few here
yep
and you can see the red guy
spawns back in orange yellow they're
spawning back in and the spacing is
changing a little bit and we hit and uh
i can still jump but you can see the
um the enemies aren't moving anymore and
the game is
stopped so uh that's pretty cool let's
go ahead and draw
the score onto the screen as well
i think now is a good time to do that
so
underneath the screen dot fill
background and make sure everything's
after screen dot fill background because
this is as you see it kind of the order
that's going to go in if you had
screened up fill after all of this stuff
um this is all getting drawn before they
it fills the screen with the color black
so you're not going to see anything
okay so that was a little tangent but
we're gonna say score text is equal to
and this is going to be if you're not
familiar with pi game fonts if this is
the first time you've made a pie game
game
just kind of follow along
you have to do this font dot render
before you can actually draw it onto the
screen it's one extra step
but score text is going to be equal to
just score
and then
also the string of our score variable so
i'm going to make this an f string
if you put that f before your string
that makes it a formatted string and you
can use these curly brackets inside your
string
um to display a variable
so a little python hack for you
and then we're gonna make it white and
with a black background not that you'll
really see the background because the
screen is black
and then we are going to
screen
dot blit so this is saying onto the
screen do a it's block transfer but dot
blit is the pi game
draw something instruction
and what do we want to draw we want to
draw score text we want to draw it at
about 160 and 250 if you're following
along with my dimensions
it looks pretty good there it'll be
about in the center of the screen
underneath the floor so let's go ahead
and see if that came up
there we go
and let's see as yeah so you can see as
blocks do make it off the screen
my score does go up let's see if i can
get a few here
oh okay
but one thing you'll notice we don't
have any way of
restarting or resetting so if i hit
something
um the score is not going to go back to
zero but there's also there's no way to
restart so we'll add that in now
um
and we'll add we'll just make it to
where when the game starts active is
actually equal to false and we will
check
if
active is equal to false and you press
the space bar
then we'll start the game and that way
spacebar will also be how you restart it
if you lost so what we have to do though
is we have to add some conditions here
so we'll say all of this is going to be
true
if
active
is true
but we'll add something new that says if
event
dot type is
pygame dot key down and you actually
could do that active
you could do that active check on just
this rung if you wanted but i'm going to
do it here
and what we'll say is if it's key down
and not active and they press the space
bar then what'll we do
we'll set active equal to true but we
want to do a few other things because if
the player's out of position or the
obstacles are out of position this could
get a little goofy
so we are gonna go ahead and
where are we active equals true
we're also going to reinitialize our
obstacles and we're also going to put
the player's x back to 50.
and this is just going to put everyone
back in their starting positions and
then one last thing we'll do is we'll
set the score equal to zero
so there are a few ways we can pretty
this up we can add some instructions and
we can actually display what they need
to know onto the screen
but let's go ahead and see if we got the
functionality working first so i'm going
to press space
and the game starts that's pretty sweet
and i die
unintentionally
and you can see i hit space once
and i reset the game and then i can play
it again and the score is resetting
all right so i mean really this is the
end of the video i mean we have an
infinite runner
um where
uh you know the game
uh can be played and restarted and it
keeps track of score a few cool things
just off the
top of my head that i think would take
this game the next level you would want
to track high score um which
you would just check at every time that
you died essentially every time you had
that collide with the rectangle right
there you check if your current score
was higher than whatever your previously
stored highest was
and you would move the value into that
highest score before you cleared out
current score
um let's go ahead and do one last thing
just when it's not active let's go ahead
and draw a few things on the screen
we'll draw so we'll take this
text that we have here the score text
and
we'll say
if not active
we're also going to call this one
instruction text
and we'll just have it say
spacebar to start
and this guy we're not going to want it
1
62 50 we'll put this guy
a little bit higher and a little bit to
the left because he's a
different length and let's do one more
we'll just call it instruction text 2.
you got to change it in here as well
instruction text and instruction text
two
and the second one will have
spacebar
jumps
left
right
moves
okay
and we'll put this guy just a little bit
below so that was at 50 we'll put this
guy down at 90. let's take a look how
that looks
so we started up
so uh you can see that doesn't look
great we'll move it to the left a fair
bit here maybe over to 80.
um clearly going off script now
but let's run it like that
okay i like that spacebar to start
spacebar jumps left right moves so we're
not just throwing the player in there
with no instructions
and then
you can play you can get a few points
you could get millions of points if you
wanted because the game
doesn't get progressively more difficult
one thing that you could do i've done it
in a few other videos
is progressive difficulty where you kind
of use the score
as a multiplier for the speed so for
example you could do score divided by 10
equals
obstacle speed and that way like every
time you hit
a new increment of 10 or 20 whatever
increment you wanted you could make it
to where the
objects actually get faster and faster
and faster and that would be a good way
of making it difficult as you got higher
scores
for me i just think it's one of those
like you're going to lose focus at some
point so this is uh good for me and good
for the tutorial um
but that really is uh the entire
instructions i mean if you followed
along i hope you're having fun playing
this game because honestly i just made
it to make an instructional video but i
have a blast playing this now it's kind
of addictive
and
if you did decide to make it and you did
take it another step further and do
something unique with yours let me know
in the comments below what you did to
improve it because i'd love to hear your
thoughts on what makes this really an
even better game
and i hope you found it useful if
there's anything in particular you have
questions on just let me know about that
in the comments below as well and i'll
get back to you as soon as i can
and uh be sure to check out the channel
for a ton of other python tutorials
we've done apps using kivy we've done
applications using tkinter
we've done a ton of just python
tutorials where you don't need a
graphical user interface an hmi portion
um
so be sure to check out the channel if
you're looking for more content and if
there's an idea that you want to see in
a future video let me know about that
one as well in the comments and maybe
you'll see it on the channel pretty soon
if you do like the channel be sure to
leave a like and subscribe to the
channel it helps me a ton we're a pretty
new channel and i really appreciate all
the support and as always good luck with
your code and thanks for watching thanks
bye