Learn to Code via Tutorials on Repl.it!

← Back to all posts
🚀 A Starter Guide to Pygame 📀
eankeen (1209)

🚀 A Starter Guide to Pygame 📀

Pygame is an open-source library for making graphical applications with Python. Learn more about it on the official website.

This tutorial is intended to help you setup a very basic Pygame interface. It's for Python beginners or people who want to quickly bootstrap a Pygame project. Find more about Repl.it's GFX public beta announcement here. So let's get started!

We're going to be building a simple screen saver. The final result will look like the following

Starting out

When creating a new project, be sure to select "PyGame" when creating a project.

Now we're ready to start writing some code!

Painting the Screen Red 🎨

First, we're importing Pygame and initializing all the imported pygame modules with pygame.init().

Second, we're declaring width and height variables that represent the size of the screen.
Third, we're setting backgroundColor to a tuple of 3 elements that represent the RGB numbers.

Fourth, screen is a display Surface, or an initialized window or screen for display with the set_mode() method.

Lastly, in the infinite loop, we're filling the screen to the backGroundColor and updatiang the display Surface to the screen. In other words pygame.display.flip() "refreshes" the screen with changes you made to the grahpics.

import pygame

width, height = 800,  600
backgroundColor = 255,  0,  0

screen = pygame.display.set_mode((width, height))

while True:

So, we get a red background!

Adding the DVD

Right before you while loop, import an image of your DVD. Feel free to use the same image I used, in the repl below.

dvdLogo = pygame.image.load("dvd-logo-white.png")

Then, create a rectangle from the Surface, or from the image you just loaded with get_rect()

dvdLogoRect = dvdLogo.get_rect()

Now, inside of the while loop (after filling the background color), "map" the imported image to the dvdLogoRect rectangle using the blit() method. That way, the image stays inside of the invisible dvdLogoRect rectangle.

screen.blit(dvdLogo, dvdLogoRect)

Now, we get a DVD!

Moving the DVD Logo

To move the DVD logo, simply use move() by a speed:

dvdLogoRect = dvdLogoRect.move(dvdLogoSpeed)

Make sure you also declare and initialie dvdLogoSpeed at the top of the file. dvdLogoSpeed[0] represents the speed in the x direction.

dvdLogoSpeed = [1,  1]

Finally, I added a time.sleep(10 / 1000) so the logo moves slower.

So my code ended up looking like

The DVD logo will move off the screen because there is no bouncing.
To implement a check for bouncing, add the following:

if dvdLogoRect.left < 0  or dvdLogoRect.right > width:
	dvdLogoSpeed[0] = -dvdLogoSpeed[0]
if dvdLogoRect.top < 0  or dvdLogoRect.bottom > height:
	dvdLogoSpeed[1] = -dvdLogoSpeed[1]

The .left and .right properties don't seem to be documented, but it's implied that .left measures the distance from the left part of the dvdLogoRect Rect (rectangle) to the left part of the screen. And so on and so fourth for .right, .top, and .bottom.

Here is the final result

Now let me know when the logo hits the corner!

RishabhDey (8)

no avaiable video device what

Traceback (most recent call last):
File "main.py", line 11, in <module>
screen = pygame.display.set_mode((width, height))
pygame.error: No available video device

eankeen (1209)

Hmm. I'll have to check this error out. Do you get the error when forking the project?

Neo_ (5)

@RishabhDey make sure you made a repl under "pygame" and not "python" category when you create a new repl. That was my problem.

eankeen (1209)

@Neo_ Oh! Thanks for finding the problem - I'll add that to this guide.

Neo_ (5)

@eankeen also by the way, in the code box under the section "painting the screen red" you misspelled display on the last line. I couldn't figure out what was wrong and it was that.

eankeen (1209)

@Neo_ Sorry about that! Not sure how I glossed over that when checking everything over - fixed now.

adobadobe (4)

File "main.py", line 10, in <module>
dvdLogo = pygame.image.load("dvd-logo-white.png")
pygame.error: Couldn't open dvd-logo-white.png

WikingGaffa (39)

The example works when I open it in your repl, but when I fork to my own it doens't work :-(
I wanted to test it because I find pygame and love2d kind of slow responding/ laggy when I move a picture around (with keyboard input)
Some of the error code:
Display is not capable of DPMS
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM default
^CTraceback (most recent call last):
File "main.py", line 25, in <module>
time.sleep(10 / 1000)
XIO: fatal IO error 11 (Resource temporarily unavailable) on X server ":0"
after 123 requests (123 known processed) with 12 events remaining.
exit status 1

emotionbot (8)

@WikingGaffa This happens to me when I try and run Tkinter. Try running it on a IDE such as atom and see if it works.

SkyyCivil (98)

i always wanted to get into pygame!

GrandMoff100 (5)

doesn't work when i fork it
exit status -1 bash -c polygott-x11-vnc q && DISPLAY=:0 run-project
nohup: redirecting stderr to stdout
xset: unable to open display ":0"
Keyboard Control:
auto repeat: on key click percent: 0 LED mask: 00000000
XKB indicators:
00: Caps Lock: off 01: Num Lock: off 02: ScrollLock: off
03: Shift Lock: off 04: Group 2: off 05: Mouse Keys: off
auto repeat delay: 660 repeat rate: 25
auto repeating keys: 00feffffdffffbbf
bell percent: 50 bell pitch: 400 bell duration: 100
Pointer Control:
acceleration: 2/1 threshold: 4
Screen Saver:
prefer blanking: yes allow exposures: yes
timeout: 600 cycle: 600
default colormap: 0x20 BlackPixel: 0x0 WhitePixel: 0xffffff
Font Path:
DPMS (Energy Star):
Display is not capable of DPMS
nohup: ignoring input and appending output to 'nohup.out'
nohup: appending output to 'nohup.out'
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4528:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5007:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM default

FilipH (20)

It gives me the error message couldn't open dvd-logo-white.png when I run the program I don't know why.

ctnimmo (6)

@FilipH I had the same issue. The filename is case-sensitive (the code was looking for "dvd-logo-white.png" but my file uploaded as "dvd-logo-white.PNG").

themaka (181)

Get in the corner!

zyl0c (4)

Great tutorial, very easy for a beginner like me to follow!

Sam_philipsen (3)

I don't know if anyone else had this issue, but when I run the program it gives the message:
nohup: redirecting stderr to stdout
and then doesn't run it further.

jordancampbell5 (1)

@Sam_philipsen I found that this happens to me sometimes if I push the stop button before it finishes loading. Try copying the code to a new file and run it again

AidanCashman (3)

How do you adjust the size of the image

lgrocks11 (1)


JosephSanthosh (86)

Yo dude I got a problem when I run the first strings of code it just shows this and I've no idea what's wrong with this:
Repl.it: Package operation failed.

yanovsky (8)

Wait.....is pygame the same as python but with an interface? Could somebody please clarify?

JamieDurow1 (0)

hi, how would i make the pygame screen be 1920x1080, because when set that as the width and height, the screen stays the saame dimensions but the dvd moves off the screen?

SreeramTheBest (11)

Pygame just shows a blank screen for me!

IjjouAmejal (0)

i like this tutorial

futuremom (0)

my thing wont work

AtriDey (88)


DanielSchumache (26)

What can I change to allow it to hit the corner periodically?

LukeShomper (49)

Thanks, I'm good with Pygame but still have much to learn, this taught me about blitting so thanks!

codyg28_11 (0)

Works well, thank you. Was wondering if there was anyway to make the logo move more fluidly, it looks like it's running at 3fps rn

eankeen (1209)


on my screen it looks to be moving at ~20fps. i think purchasing hacker plan would improve the speed, but i dont think that should matter in this context. a better internet connection might help if your consistently getting 2fps - but it could also be some sort of bug? as you can probably tell, im not too sure :P

SteelCityCity (0)

how do you add a link in pygame?

codyg28_11 (0)

@SteelCityCity If you're talking about the image, click on the three dots next to the add file buttons on the left and upload the image. Then you just run the dvdLogo = pygame.image.load("dvd-logo-white.png") part of the code and replace the image name with yours

RogerHaegg (0)

New to Python and Pygame. I tried this with my students, but ended up getting message that it "Couldn't open dvd-logo-white.png ".
I saw a similar post that was commented to change png to PNG, but got same message. Below is what I believe is what the tutorial told us to use.
Any ideas?

import pygame
width, height = 800, 600
backgroundColor = 255, 0, 0

screen = pygame.display.set_mode((width, height))
dvdLogo = pygame.image.load("dvd-logo-white.PNG")
dvdLogoRect = dvdLogo.get_rect()
while True:
screen.blit(dvdLogo, dvdLogoRect)

eankeen (1209)

@RogerHaegg Hmm. That's kind of strange

On my project, if I write the following, my program works.

dvdLogo = pygame.image.load("dvd-logo-white.png")

However, if I convert 'png' to 'PNG', then it stops working (since it can't find the file).

Are you trying to use a different file? Maybe you downloaded a JPEG, renamed it to 'dvd-logo-white.png' and it didn't work because it tried to read the PNG (even though it is a JPEG file). Other than that, I'm not sure what the error might be.

RogerHaegg (0)

So, what I didn't realize, is that I had to go to the sample code in the repl at bottom of tutorial, save that image, and then upload the pic into my repl.
Now it does work. Thank you

eankeen (1209)

@RogerHaegg Ohh, gotchia
Glad you figured it out! 🙂

DavonteEvans (0)

this is so coooooooooooooooooooooooooollllll!!

ChristianGlacet (2)

There is a bug in this code, the logo doesn't change color.

eankeen (1209)

@ChristianGlacet Hm. Well the logo was not supposed to change color. I put the other color in there just in case you wanted to use a white background. 🙂

ChristianGlacet (2)

@eankeen Ah don't worry that was just a joke as the typical bouncing DVD logo changes color :p

ChristianGlacet (2)

@eankeen A neat trick you could try to implement is to make sure it can't hit any corner but still have it to bounce all around with kind of uniform probability, that'd be super cool. Note sure if that's hard or not tho :p

eankeen (1209)

@ChristianGlacet yeah that sounds pretty cool. heh, sometimes I have trouble detecting jokes myself.

boohoo (3)

if dvdLogoRect.left < 0 or dvdLogoRect.right > width:
dvdLogoSpeed[0] = -dvdLogoSpeed[0]
if dvdLogoRect.top < 0 or dvdLogoRect.bottom > height:
dvdLogoSpeed[1] = -dvdLogoSpeed[1]

can anyone explain this part for me

Deacon_Cronin (67)

@boohoo If it's touching the edge of the screen, invert its speed