Skip to content
← Back to Community
πŸš€ A Starter Guide to Pygame πŸ“€
Profile icon
hyperupcall

πŸš€ 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
programProgress4

Starting out

When creating a new project, be sure to select "PyGame" when creating a project.
This file cannot be displayed: https://storage.googleapis.com/replit/images/1552705106070_4aa0e807cd3fb5197a7251222d74d724.pn
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!
This file cannot be displayed: https://storage.googleapis.com/replit/images/1552448696584_73e029d5335f2d2a06c92a180e7103be.pn

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!
This file cannot be displayed: https://storage.googleapis.com/replit/images/1552449702561_27872d2c7a30d4d9dbb53d3c908851d9.pn

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
programProgress3

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
programProgress4

Now let me know when the logo hits the corner!

Voters
Profile icon
audr5930audr593
Profile icon
vinic9
Profile icon
Nayr94
Profile icon
sheilm
Profile icon
cmiles287
Profile icon
testaccontim
Profile icon
ARJPEG
Profile icon
akimbojenai1
Profile icon
KarenTao2
Profile icon
cornellgwc
Comments
hotnewtop
Profile icon
RishabhDey

no avaiable video device what

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

Profile icon
hyperupcall

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

Profile icon
Neo_

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

Profile icon
hyperupcall

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

Profile icon
Neo_

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

Profile icon
hyperupcall

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

Profile icon
JordanDixon1

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

Profile icon
awesomel

@RishabhDey,

I think you don't have a compatible console and preview for your editor please share the editor your using. If your using replit.com's editor, then this should not happen.

Thanking you in advance.

Regards,
@awesomel

Profile icon
AFragileStick

@JordanDixon1 It just tells me "bash: modules: command not found" when I do this

Profile icon
JordanDixon1

@AFragileStick did you do python then help() and at the help screen you typed in modules if that does not work then do help(β€œmodules”)

Profile icon
GrandMoff100

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

Profile icon
adobadobe

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

Profile icon
Henslo

@adobadobe you have to download to to the project files

Profile icon
WikingGaffa

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

Profile icon
emotionbot

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

Profile icon
[deleted]

How do you adjust the size of the image

Profile icon
FilipH

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

Profile icon
ctnimmo

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

Profile icon
themaka

Get in the corner!

Profile icon
SkyyCivil

Thxxxx
i always wanted to get into pygame!

Profile icon
SreeramTheBest

Pygame just shows a blank screen for me!

Profile icon
zyl0c

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

Profile icon
Whippingdot
Profile icon
adamgadd99
Profile icon
Whippingdot
Profile icon
AlphaComputer

@Whippingdot I was wondering about that! XD

Profile icon
awesomel

@Whippingdot

Why is restoring to the old version?
An update means it should go to the new version.
I think there's a problem.

Profile icon
Whippingdot

I am pretty sure that happened because this is an old program and it uses the older version @awesomel

Profile icon
jgunn

This works when I run it as is, or when I fork it, but when I copy and paste the same code into a new pygame file (including an appropriate image file in the project) it doesn't work. Has something been deprecated or something? Here's the error I get:
bash -c polygott-x11-vnc q && DISPLAY=:0 run-project
.....pygame 2.0.0 (SDL 2.0.12, python 3.8.5)
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
ξΊ§ bash -c polygott-x11-vnc q && DISPLAY=:0 run-project
.....pygame 2.0.0 (SDL 2.0.12, python 3.8.5)
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
X Error of failed request: BadMatch (invalid parameter attributes)
Major opcode of failed request: 42 (X_SetInputFocus)
Serial number of failed request: 191
Current serial number in output stream: 192
exit status 1

Profile icon
SeamusDonahue

im having the same problem! @jgunn

Profile icon
SeamusDonahue

I managed to sort of fix it? I added a print statement after pygame.init() and hit the x on the window rather than stopping the repl. @jgunn

Profile icon
CreeperCraft1

@SeamusDonahue I a not an expert or anything but it might be the version you are using

Profile icon
Sam_philipsen

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.

Profile icon
jordancampbell5

@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

Profile icon
evanzimmerman

Great tutorial!

Profile icon
lgrocks11

IT HIT THE CORNER

Profile icon
Soulpanton

File "main.py", line 10, in
dvdLogo = pygame.image.load("dvd-logo-white.png")
FileNotFoundError: No such file or directory.

Profile icon
olliegroth

@Soulpanton I had a similar issue, try downloading you image, and then dropping it into the Files tab on repl.it. It should then appear as an image under main.py, meaning you can call it as described.

Profile icon
Dominicl645

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

Profile icon
NidhiSinha

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):

Profile icon
camgrover

@NidhiSinha I am getting the same error

Profile icon
testaccontim

you should change the resolution to 800x400 so you can fully see it on the replit page

Profile icon
CodingElf66

How come this gets in the homepage and my more detailed Pygame tutorial gets nowhere? https://replit.com/talk/learn/Pygame-Tutorial/143782. Nice tutorial, but try to provide more content next time, btw.

Profile icon
AnirudhKarthik

wow! so cool!

Profile icon
DSARobert20

doesn't work. import pygame, time

pygame.init()
width, height = 800, 600
dvdLogoSpeed = [1, 1]
backgroundColor = 0, 0, 0

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

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

while True:
screen.fill(backgroundColor)

screen.blit(dvdLogo, dvdLogoRect) dvdLogoRect = dvdLogoRect.move(dvdLogoSpeed) if dvdLogoRect.left < 0 or dvdLogoRect.right > width: dvdLogoSpeed[0] = -dvdLogoSpeed[0] if dvdLogoRect.top < 0 or dvdLogoRect.bottom > height: dvdLogoSpeed[1] = -dvdLogoSpeed[1] pygame.display.flip() time.sleep(10 / 1000)
Profile icon
awesomel

Hi, eankeen,

It is showing that there is an error:
Traceback (most recent call last):
File "main.py", line 10, in <module>
dvdLogo = pygame.image.load("dvd-logo-white.png")
FileNotFoundError: No such file or directory.
The error type is "dvd-logo-white.png" file is not found.
I think there's an error in your code.
Please fix it and share it again.

Thanking you in advance.

Regards,
@awesomel
(Not my real name. (My profile name.))

Profile icon
ZEG111

I tried creating a empty python window for a game but it isn't working. can you help me? I put my code below.
import sys
import pygame
class AlienInvasion:

def init(self):
pygame.init()

self.screen = pygame.display.set_mode((1200,800)) pygame.display.set_caption("Alien Invasion") self.bg_color = (230,230,230)

def run_game(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
self.screen.fill(self.bg_color)
pygame.display.flip()

if name == 'main':
ai = AlienInvasion()
ai.run_game()

Profile icon
Pikachushon

it doesn't show anything, I think I need a code to put in the shell for pygame.

Profile icon
cannonthepom123

how do i change the size of an image?

Profile icon
[deleted]

It’s Good

Profile icon
Mozyyoo

When i attempt i recieve a FileNotFound error, i also recieved it in another repl i did, do files just not work on here?

Profile icon
MetadataX

I'm having just ONE problem;
Traceback (most recent call last):
File "main.py", line 10, in
dvdLogo = pygame.image.load("dvd-logo-white.png")
FileNotFoundError: No such file or directory.

Profile icon
ShajeenthShan

I just like that it says dvdlogo get rect