Learn to Code via Tutorials on Repl.it!

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

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

So, we get a red background!
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.

Then, create a rectangle from the Surface, or from the image you just loaded with 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.

Now, we get a DVD!
https://storage.googleapis.com/replit/images/1552449702561_27872d2c7a30d4d9dbb53d3c908851d9.pn

Moving the DVD Logo

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

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

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:

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!

Voters
Ren7328
fnajarro
maxina
brayyyy
simfonia2
KimmyJongyYay
KaiserFranz
YonathanS
tankerguy1917
astrophile12
Comments
hotnewtop
AnirudhKarthik

wow! so cool!

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)

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

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

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

Pikachushon

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

cannonthepom123

how do i change the size of an image?

[deleted]

It’s Good

DrHalloween

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

MetadataX

I'm having just ONE problem;
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.

ShajeenthShan

I just like that it says dvdlogo get rect

AhmadHamrah1

The example works when I open it in your repl, but when I fork to my own it doens't work :-(

Whippingdot

noice update we have there:

adamgadd99
Whippingdot

NOICE INDEED


@adamgadd99

AlphaComputer

@Whippingdot I was wondering about that! XD

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.

Whippingdot

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

Soulpanton

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

Coolgame4me

the code works in the post, but not in my own IDE.Is there a solution to this?

lperras

how do you do

KoolDagger

get_rect() loll get rekt

PattanAhmed

@eankeen Hi,
The screen fill is not working for me.

Would you mind if I invited you to my Repl.
Thanks!

RayhanADev

Oh wow @eankeen this is from so long ago xD. Do you have any og Repl stories? (°▽°)

TROYCOMEAUX

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.

AaronGreen5

run

beginner10coder

Lol I watched the DVD for just 15 and then it hit the corner :)

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

SeamusDonahue

im having the same problem! @jgunn

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

CreeperCraft1

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

509robotic

something keeps going wrong... it keeps giving me error messages... help pls

RahulChoubey1

I wrote something, but after running and then stopping for program fixes, the screen's cursor freezes permanently…

JUSTINCHEN22

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

Dominicl645

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

ninjutsu808

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

python88

amzing!

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

camgrover

@NidhiSinha I am getting the same error

DSALayan20

I don't get it