Learn to Code via Tutorials on Repl.it!

← Back to all posts
Pygame Tutorial!
CodingElf66

Pygame Tutorial!

Intro

Hello, guys! This tutorial is based on Pygame, a module in Python that is used for the development of games! Pygame is very fun and simple to learn, maybe you should try learning it!

Why

Well, you might be thinking: Why should I learn Pygame? To answer that question, maybe you should go look on the projects people have made with Pygame; you can blit images, text with fonts, all sorts of shapes, lines, sprites, and way more! Pygame lets you create games simply, with its built-in functions and more! So, let's start learning Pygame!

Important

Note: All of the examples below are just only examples! You do not have to follow them, they are just to help you understand! And, all the examples are like dominoes; you have to keep reading to understand the previous.

Importing It

Of course, what we always need to start with, is importing pygame!

Now that we've got the Pygame module imported, we can start learning Pygame!

Initializing The Pygame Window

We need to initialize the Pygame window before we use it. Pygame has a function for that!

Setting The Dimensions Of The Pygame Window

We need to set the size of the Pygame window first also, before we use it, or the dimensions would be undefined.

If we do this, Pygame would create a window that has a width of 400 and a height of 400. The dimensions (width and height) could be anything (that is nonnegative).

Output

Note: Notice that the dimensions is a tuple of two parameters, not two individual parameters

Warning: The dimensions cannot be negative

Setting The Window Captions

If you look at the output in the previous example, you'll probably notice that on top of the window, it says "pygame window". If you want to name it, you can caption it!

Output:

Updating The Pygame Window

Now, maybe you won't see how this would do anything yet, but in the next parts, this will be used! To update the window, do:

This function updates the window, and use it when you need to update it!

Filling The Pygame Window With Color

Now, this part will be slightly more tricky. We will go over something maybe you heard of but don't know, RGB color code!

First, we need to assign a variable to the window settings (pygame.display.set_mode((400,400)). Let's call it screen.

To fill it, we just do screen.fill(color), such that parameter color is a tuple in RGB code.

Output:

Note: If you don't get RGB color code, this may help! A RGB color picker to help you find your colors in RGB code! https://www.google.com/search?q=rgb+color+picker&rlz=1CASFKO_enUS934&oq=rgb+color+picker&aqs=chrome..69i57j0i512l9.2085j0j7&sourceid=chrome&ie=UTF-8

Drawing Lines

Drawing lines can be quite a useful thing! However, it may be complicated. Now, x and y coordinates will start to be used!

pygame.draw.line() is the way to draw a line, but hold on; it has lots of parameters, so let's learn them!

That's a lot there, so let's explain its parameters one by one.

The first parameter, surface, is basically the window settings.

The second parameter is color (in RGB code).

The third parameter is start_pos, which is where the line starts from. start_pos is a x and y tuple.

The fourth parameter, end_pos, is where the line ends. It is also a x and y tuple.

The fifth and final parameter, width, is how thick the line is.

Now, let's test it out!

That's a lot there, too! So let's explain it.

In this part, we are drawing a line that is black, starts at (50,50) and ends at (350,350). It's thickness is 5. The background is white.

Output:

Note: The width parameter will be 1 as default.

Warning: The width parameter cannot be below 1, or it would return nothing!

Warning: The x and y axis in Pygame is different then the normal one. The left side of the window is still 0, and the right side of the window is the width of the window. The top side of the window is actually 0! But the bottom side isn't negative; it is the height of the window!

Drawing Circles

Drawing circles are also quite tricky. Let's review it's parameters.

The first parameter, surface, is the window settings.

The second parameter, color, is a color in RGB code.

The third parameter, center, is where the circle's center is, in x and y coordinates.

The fourth parameter, radius, is the radius of the circle.

The last four parameters are basically for drawing the circle partially. For example, if you set draw_bottom_left to True, then it would only blit the bottom left part of the circle. Anyways, you get the idea...

Now, let's do an example!

Here, we have the background as white, the circle color as black, the center of the circle at (200,200), the radius of the circle as 100, and we only draw the bottom right part of the circle. Let's see what it looks like!

Output:

Super weird, right? Haha. Let's move on!

Drawing Rectangles

Drawing rectangles are similar, like the previous. We'll go over the parameters first.

Drawing rectangles in Pygame has lots of parameters.

The first parameter is surface, the window settings.

The second parameter is color, the color of the rectangle.

The third parameter, rect, is quite confusing. It is a tuple, consisting four parameter in it. The first two parameters is the top-left coordinate of the rectangle. The remaining two parameters are the width (moving right) and the height (moving down) of the rectangle.

The fourth parameter, border_radius, has a defualt value of 0. The meaning of this parameter is that it makes the rectangle's corners bented like the circle, given the radius.

The remaining four parameters are for individual corner radiuses.

Now, let's get some practice!

This time, we draw a rectangle, that has a red color, has a top-left corner at (100,100), with a width and height at 200, and with a rectangle corner radius of 5.

Output:

That is the three main parts of pygame.draw, let's move on to image bliting!

Bliting Images

Bliting images are way way easier than the previous things we've done.

Let's say we have a image file.

earth.webp

To blit it, we do the code below:

We need to load the image first, so we use pygame.image.load(filename) to load it. Then, we use screen.blit(file, (x,y)) to blit the image. Note that the second parameter of screen.blit is the top-left coordinate of the image.

So, the top-left coordinate of the image is (100,100). Now, let's see what this looks like!

Output:

Now, let's learn about the next part, delaying time.

Delaying Movement

If you ever want to delay movement of the window, you are in luck! There is something for that, it is pygame.time.delay()! It holds only one parameter, how much you delay it! It is basically delaying the number of milliseconds you put in.

We have nothing to delay, but it will be useful in animations!

Turning A Image Into A Rect-Like Object

Let's say we have the earth image again.

earth.webp

To turn it into a Rect-Like object, we can use the .get_rect() function.

Now that we've turned it into a Rect-Like object, we can do lots of things with it, such as assigning it's center.

Assigning Rect-Like Object Centers

To assign a center to a Rect-Like object, we can use the .center to assign it to a coordinate!

For example, if we have the earth image again.

earth.webp

Then, we can assign it's center, which is way easier than finding the "top-left" corner of the image.

Output:

This is a very simple way of bliting the earth image! As same result, we also get the earth image in the same position.

Rendering Text With Font

Now, this is one of the best parts in Pygame, rendering text, with the font as a style!

To do this part, you can go to https://fonts.google.com. You can just keep scrolling for fonts, or you can just directly search it. After you found the font of your choice, you can click on it! When you click on it, you should see a button that says "Download Family". If you are using a Chromebook, find the font that you downloaded and press it in your Downloads. Then, you should find your font file on the left bar on your files. If you are using some other computer, you can just download the font and search for it too to make sure you successfully downloaded the font, then you can go to your coding workspace and download it. Make sure that the font ends with a 'ttf' or an 'otf'. Then, you're off to go!

Let's do an example here!

font.ttf

Now, let's learn how to render text with a certain font in Pygame!

Output:

First, we initialize the font, with pygame.font.init().

Next, we define variable font by using pygame.font.Font("font.ttf", 20). Notice that font.ttf is the font name, and 20 is the size.

Then, we start rendering the text, by using font.render("Hello, world!", True, (0,0,0)). "Hello, world!" is the text, and (0,0,0) is the color in RGB code.

We transfer text into a Rect-Like object, then we blit the text onto the screen! Big part there! To make it easier, I usually make a function.

This function makes all of it easier, you just need to add pygame.display.update() to update the window, or otherwise it's good!

Detecting Mouse Click

Now, we've entered a new part in Pygame! In this part, you will learn about Pygame tracking all sorts of user events, such as keyboard events, mouse clicks, mouse position, and everything else!

This part can be a little tricky, so listen up!

This may all sound unfamiliar, but that's ok! Pygame has event storage that stores all events, that is pygame.event.get()! The first if-statement inside the for loop is to check if the user is unresponsive, such like if offline (then the program would end). The second if-statement is for checking if the user clicked on the Pygame window. If that is true, "You pressed the Pygame window." would be printed on the Python output screen.

Output:

Detecting Keyboard Activity

Pygame supports tracking keyboard activity, such as detecting if you pressed the 'h' key, or if you pressed the 'space' key, for example. Below is an example.

First, we use pygame.event.get() to get all possible user events. We then use an if-statement to detect offline activity. The second if-statement can be confusing; pygame.KEYDOWN is for detecting keyboard activity, so we need to check if that's happening before we detect individual keyboard activity. In the final if-statement, we detect if the user pressed the 'a' key. Pygame can also detect every keyboard key, here's a table of them below!

Output:

Pygame ConstantASCIIDescription
K_BACKSPACE\bbackspace
K_TAB\ttab
K_CLEARclear
K_RETURN\rreturn
K_PAUSEpause
K_ESCAPE^[escape
K_SPACEspace
K_EXCLAIM!exclaim
K_QUOTEDBL"quotedbl
K_HASH#hash
K_DOLLAR$dollar
K_AMPERSAND&ampersand
K_QUOTEquote
K_LEFTPAREN(left parenthesis
K_RIGHTPAREN)right parenthesis
K_ASTERISK*asterisk
K_PLUS+plus sign
K_COMMA,comma
K_MINUS-minus sign
K_PERIOD.period
K_SLASH/forward slash
K_000
K_111
K_222
K_333
K_444
K_555
K_666
K_777
K_888
K_999
K_COLON:colon
K_SEMICOLON;semicolon
K_LESS<less-than sign
K_EQUALS=equals sign
K_GREATER>greater-than sign
K_QUESTION?question mark
K_AT@at
K_LEFTBRACKET[left bracket
K_BACKSLASH\ backslash
K_RIGHTBRACKET]right bracket
K_CARET^caret
K_UNDERSCORE_underscore
K_BACKQUOTE` | grave
K_aaa
K_bbb
K_ccc
K_ddd
K_eee
K_fff
K_ggg
K_hhh
K_iii
K_jjj
K_kkk
K_lll
K_mmm
K_nnn
K_ooo
K_ppp
K_qqq
K_rrr
K_sss
K_ttt
K_uuu
K_vvv
K_www
K_xxx
K_yyy
K_zzz
K_DELETEdelete
K_KP0keypad 0
K_KP1keypad 1
K_KP2keypad 2
K_KP3keypad 3
K_KP4keypad 4
K_KP5keypad 5
K_KP6keypad 6
K_KP7keypad 7
K_KP8keypad 8
K_KP9keypad 9
K_KP_PERIOD.keypad period
K_KP_DIVIDE/keypad divide
K_KP_MULTIPLY*keypad multiply
K_KP_MINUS-keypad minus
K_KP_PLUS+keypad plus
K_KP_ENTER\rkeypad enter
K_KP_EQUALS=keypad equals
K_UPup arrow
K_DOWNdown arrow
K_RIGHTright arrow
K_LEFTleft arrow
K_INSERTinsert
K_HOMEhome
K_ENDend
K_PAGEUPpage up
K_PAGEDOWNpage down
K_F1F1
K_F2F2
K_F3F3
K_F4F4
K_F5F5
K_F6F6
K_F7F7
K_F8F8
K_F9F9
K_F10F10
K_F11F11
K_F12F12
K_F13F13
K_F14F14
K_F15F15
K_NUMLOCKnumlock
K_CAPSLOCKcapslock
K_SCROLLOCKscrollock
K_RSHIFTright shift
K_LSHIFTleft shift
K_RCTRLright control
K_LCTRLleft control
K_RALTright alt
K_LALTleft alt
K_RMETAright meta
K_LMETAleft meta
K_LSUPERleft Windows key
K_RSUPERright Windows key
K_MODEmode shift
K_HELPhelp
K_PRINTprint screen
K_SYSREQsysrq
K_BREAKbreak
K_MENUmenu
K_POWERpower
K_EUROEuro

Detecting Mouse Position

Maybe you are thinking about buttons in Pygame! Well, this will help! If you want to make a button, you need the mouse position! Unlike HTML, making a button is not that easy. Read on to learn more!

To get the mouse position, we just put pygame.mouse.get_pos() in our code. However, if you want it in terms of x and y, you can do x,y = pygame.mouse.get_pos(), because it returns a coordinate tuple. We can only get the mouse position when we get all events. Let's try an example!

This will print the coordinates of your mouse (based on the Pygame window). (It will do it very fast, so if you want to look at the output, keep sharp eyes on it)!

Output:

Making A Button

To make a button, we can combine the Detecting Mouse Click part and the Detecting Mouse Position part.

The first few lines I hope you get the idea... setting up the window size and captioning it. Then, we make a loop and we fill it with white. We get a list of every event, then we first check if the user clicked on the window. If the user did, then it would check the mouse position (based on the window). We split the coordinates so we can use an if statement to check if it is on the button. If it is, we print "You clicked the button.", and the loop repeats again.

Output:

Detecting User Input

If we want to detect user input, we wouldn't just check if the user pressed every key and append it on some variable, wouldn't we? Well, remember that Pygame has pygame.event.get() as a storage for all the events? We can do event.unicode to get the user input. However, it only works if it is keyboard activity, so you need to remember pygame.KEYDOWN! Alright, let's get started.

Let's test it out!

Output:

Extra: I actually made a project on that before, it was a Typing Game! It is a good idea, maybe you can try!

Closing

Whew, that was a big tutorial! I hope you improved your knowledge in Pygame. If you ever make a Pygame project, feel free to just comment below and share me a repl, I'll help you! If you feel like sharing any Pygame related things or basically anything related to this post, please consider saying it below in the chat! That also applies if you have any questions, concerns, compliments, feedback, etc.. I wish you good luck on your future Pygame projects, and good luck and have fun with Pygame!

P.S. Thanks for all the people who upvoted this post for reaching me my goal of 100 upvotes, thanks!

Voters
SilentFoxy78
EncryptedUser
mollthecoder
Sant600
BryannaJohnson
NFadhlurrahman
DillonB07
RithvikKasam
imoveslowguy
365DaysOfCode
Comments
hotnewtop
SilentFoxy78

@JeffreyChen13, This is all amazing :D but do you know how to make a shape like solid? because I create shapes that go through each other...

CodingElf66
CodingElf66

@LavernieChen They go through each other, you can't make it transparent like an image.

SilentFoxy78

@JeffreyChen13 like your ping pong post. you hit ther ball and the ball doesn't go through

CodingElf66

@LavernieChen Oh you can use the .move(x,y) function in Pygame, it works for a rect-like object.

SilentFoxy78

@JeffreyChen13 Does it work for circles?

CodingElf66

@LavernieChen Oh lol that is for images. If you are talking about circles, you can just literally change the center coordinates

SilentFoxy78

@JeffreyChen13 TELL MY HOW THAT WORKS PLZ I"M DESPREATE

SilentFoxy78

I think i spelled it wrong
...

CodingElf66

@LavernieChen Fine I'll try to get a clear explanation of this. You can also view this on top at the Drawing Circles part. Pygame let's you draw circles. It goes like this:

I'm just ignoring the rest of the parameters because I'm assuming you won't need it.

If you want to move it, you can just change the coordinates of the center. So if it was (50,50) before, if you want it to move up, it would now be (50,49), then (50,48), (50,47), and so on and so on...

So you would just put this all in a For Loop. I'll do an example.

SilentFoxy78

@JeffreyChen13 The problem is...
Nvm I will share my repl with you ok?

CodingElf66
SilentFoxy78

@JeffreyChen13 Ok, look for the notification :D

CodingElf66
CodingElf66

@LavernieChen Need any help?

CodingElf66

@LavernieChen Wait who upvoted all the comments??

Dunce

@LavernieChen If you're talking about collision I recommend looking into the pygame.sprite.collide_circle, pygame.sprite.spritecollide and the other collision functions on the Pygame documentation

CodingElf66

@Dunce Good idea

Kristinase

Pygame Tutorial with Pygame, Pygame Installation, Install Pygame in Mac, Pygame Surface, Pygame Clock, Pygame Adding Image, Pygame Rec.

https://www.tellpopeyes.biz/

CodingElf66

I switched my username, so don't think somebody hacked my account, I changed it to a (in my opinion), a better name lol

CodingElf66

Please do not spam upvote the comments below, guys. That is one of the Replit rules, and make sure we don't break it

CodingElf66

Thanks for all the upvotes! Thanks, I would love to get this on Trending or something like that for big tutorials, thanks for all your support Replit!