🚀 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()
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)
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
.
Now let me know when the logo hits the corner!
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
im having the same problem! @jgunn
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
@SeamusDonahue I a not an expert or anything but it might be the version you are using
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
File "main.py", line 10, in <module>
dvdLogo = pygame.image.load("dvd-logo-white.png")
pygame.error: Couldn't open dvd-logo-white.png
@adobadobe you have to download to to the project files
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
@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.
It gives me the error message couldn't open dvd-logo-white.png when I run the program I don't know why.
@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").
Get in the corner!
Thxxxx
i always wanted to get into pygame!
How do you adjust the size of the image
Great tutorial, very easy for a beginner like me to follow!
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.
@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
IT HIT THE CORNER
Great tutorial!
File "main.py", line 10, in <module>
dvdLogo = pygame.image.load("dvd-logo-white.png")
FileNotFoundError: No such file or directory.
the code works in the post, but not in my own IDE.Is there a solution to this?
how do you do
get_rect() loll get rekt
@eankeen Hi,
The screen fill is not working for me.
Would you mind if I invited you to my Repl.
Thanks!
Oh wow @eankeen this is from so long ago xD. Do you have any og Repl stories? (°▽°)
I have no idea what I did wrong but after adding the movement code my pygame window doesn't load anything. It's just grayed out but I'm not getting an error message.
Lol I watched the DVD for just 15 and then it hit the corner :)
something keeps going wrong... it keeps giving me error messages... help pls
I wrote something, but after running and then stopping for program fixes, the screen's cursor freezes permanently…
import pygame
pygame.init()
screen = pygame.display.set_mode(flags = pygame.FULLSCREEN)
width, height = pygame.display.get_surface().get_size()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((255, 0, 0))
pygame.draw.circle(screen, (0, 0, 255), (width/2, height/2), 75)
pygame.display.flip()
pygame.quit()
How to randomize the "spawn" location? Like how to make the DVD or wtvr image spawn from a different spot of the program?
is there a way to make an idle game using pygame?
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
amzing!
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):
@NidhiSinha I am getting the same error
I don't get it
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
Hmm. I'll have to check this error out. Do you get the error when forking the project?
@RishabhDey make sure you made a repl under "pygame" and not "python" category when you create a new repl. That was my problem.
@Neo_ Oh! Thanks for finding the problem - I'll add that to this guide.
@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.
@Neo_ Sorry about that! Not sure how I glossed over that when checking everything over - fixed now.
@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.