Learn to Code via Tutorials on Repl.it!

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

🚀 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

pygame.init()
width, height = 800,  600
backgroundColor = 255,  0,  0

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

while True:
	screen.fill(backgroundColor)
	pygame.display.flip()

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!

Commentshotnewtop
RishabhDey (12)

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 (1339)

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

Neo_ (6)

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

eankeen (1339)

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

Neo_ (6)

@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 (1339)

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

JordanDixon1 (355)

@eankeen I've figured out that you can enable the video screen on a normal python repl by pressing ctrl + shift + s then type in python. Once the python is open type in help() then modules. After a little while, you'll find the screen open.

adobadobe (5)

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

hello1964 (23)

@adobadobe you have to download to to the project files

WikingGaffa (49)

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)
KeyboardInterrupt
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 (9)

@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.

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").

SkyyCivil (119)

Thxxxx
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
fadfffffffdfe5ef
ffffffffffffffff
ffffffffffffffff
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
Colors:
default colormap: 0x20 BlackPixel: 0x0 WhitePixel: 0xffffff
Font Path:
/usr/share/fonts/X11/misc,built-ins
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

themaka (184)

Get in the corner!

zyl0c (4)

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

AidanCashman (3)

How do you adjust the size of the image

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

JUSTINCHEN22 (0)

How to randomize the "spawn" location? Like how to make the DVD or wtvr image spawn from a different spot of the program?

dominicl645 (30)

is there a way to make an idle game using pygame?

ninjutsu808 (0)

Its not loading the dvd logo i don't know why
and when i add the code to add the dvd logo it shows a white screen .
it is nice

NidhiSinha (0)

why do I keep getting this error

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
Traceback (most recent call last):

octopyBot (263)

I used this to make it a bit more random which direction the HULU goes:

import pygame, time
import random

hlsxcor = random.randint(1, 4)
hlsycor = random.randint(1, 4)
pygame.init()

bgColor = 0, 0, 0
huluspeed = [hlsxcor, hlsycor]
width, height = 800, 600
screen = pygame.display.set_mode((width, height))

hulu = pygame.image.load("hulu_logo.png")
hulurect = hulu.get_rect()
while True:
  screen.fill(bgColor)
  screen.blit(hulu, hulurect)
  hulurect = hulurect.move(huluspeed)
  if hulurect.left < 0 or hulurect.right > width:
    huluspeed[0] = -huluspeed[0]
  if hulurect.top < 0 or hulurect.bottom > height:
    huluspeed[1] = -huluspeed[1]
  pygame.display.flip()
  time.sleep(10 / 1000)
NidhiSinha (0)

@octopyBot I am new to this coding thingy. I was wondering how do we import images. I mean there needs to be a source file from where the program can pick up the images. Can you please help me with this

octopyBot (263)

@NidhiSinha sure. download the image you want to your computer's image files, then click the three buttons on top of your files like so:

then click add file and choose your image. then refer to the image by it's file name, + png or jpg.

NidhiSinha (0)

Hey, That I had figured already, but I was actually getting this problem of ALSA, and I am not sure why I was getting that. it said cannot find directory. So I needed help with that @octopyBot . If you have enough experience with pygame. Can you please tutor me on Pygame. I need some extensive help on designing something which needs images to be presented systematically for n number of time followed by a response

octopyBot (263)

@NidhiSinha no. next time, either be more specific or go to the ask board. I am experienced in pygame, but I'm not going to tutor you.

octopyBot (263)

@NidhiSinha well there are worries. next time, if you want pygame help, then there's the ask board. don't go asking random people to tutor you.

NidhiSinha (0)

Well. I have a question for you: what happened in your life that made you so cold. Like really! I mean, you were very cold while also replying to my request to tutor you. I gave you the benefit of the doubt and politely said no worries, and then there goes this comment of yours. If you think you can comment like a rude person, and no one is going to reply back then dude you are highly mistaken. Also, read my above comment, where I said I am new to this pygame and so I didn't know where to ask questions related to this if I had one. So as a nice person, you should have politely directed to me where I was supposed to be directed. But no, you have to be a loser here. I guess you like when people thrash you back, and yes, you were right about the point that there are worries because we have people like you in this world who don't know how to be kind and considerate and only know how to be selfish. I hope to not meet another one like you on this platform @octopyBot

octopyBot (263)

@NidhiSinha try to look at it from my point of view. you ask a question, not on the ask board. I assume you're new, and give you the benefit of the doubt, answering it. you respond saying it got you an error and asking me to tutor you?! now I'm mad. you tell me I didn't give you the correct answer and tell me you wanted to `know about an error you mentioned nothing about in the first question. I can't tutor anyone on repl just cause they ask me to. so you were completely disrespectful and immature in your rude comment back to me. I wasn't being cold, you thought I was being cold and lashed back for no reason. I expect an apology, and I don't want to see you hating on my comments again.

JosephSanthosh (1192)

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?

octopyBot (263)

@yanovsky not really, it's a python library, it's just that when you make a pygame repl, it starts with all the packager files and interface. that's just repl.

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?

octopyBot (263)

@JamieDurow1 the screen is 1920x1080, it's just the window isn't zoomed out. so it's going out of the window and bouncing off the window you set, outside of 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 (170)

IT HIT THE CORNER!!!!!!