Install pygame
pip install pygame
Full tutorial page
This page will get you through a nice example to make a full game, with a flappy bird example. Go here.
Make a window with pygame
Youtube video to start with pygame
import pygame pygame.init() screen = pygame.display.set_mode((400, 600)) square = pygame.Surface((20, 20)) square.fill((255, 0, 0)) while True: screen.blit(square, (100, 100)) if pygame.event.get(pygame.QUIT): break pygame.display.update() pygame.quit()
Or, maybe, with some different code… if you like it.
import pygame import sys pygame.init() screen = pygame.display.set_mode((600, 400)) def quit(): if event.type == pygame.QUIT: pygame.quit() print("\nExit from pygame\n\n") sys.exit() while True: for event in pygame.event.get(): quit()
Make a window with pygame zero
Draw circles and rectangles
import pygame as pg
with open("draw.py") as file:
code = file.read()
code = code.splitlines()
pg.init()
screen = pg.display.set_mode((600, 500))
# screen.fill((128, 255, 255))
# circle args: surface, color, posxy, radius
font = pg.font.SysFont("Arial", 12)
def text(x, y, sentence):
sentence = font.render(sentence, 1, pg.Color("WHITE"))
screen.blit(sentence, (x, y))
pg.draw.circle(screen, (255, 0, 0), (400, 300), 130)
pg.draw.rect(screen, (100, 200, 0), pg.Rect(300, 30, 100, 50))
lnum = 0
for line in code:
text(0, 0 + lnum, line)
lnum += 15
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
pg.display.update()
A window with fonts and a splash page example
import pygame def render_multiline(data): "Shows a multiline string with text, y pos and color for each line separated by comma" tc = [] for line in data.split("\n"): if line != "": text, size, color = line.split(",") size = int(size) tc.append([text, size, color]) # 2. Each list of the list above is send to write to render text for t, s, c in tc: for i in t.split("\n"): write(i, 200, s, color=c) s += 30 TEXT1 = """*** ARKAGAME ***, 30, gold A Game by Giovanni Gatto, 80, red pythonprogramming.altevista.org, 120, coral Game vaguely inspired by classic games, 180, cyan like breakout or Arkanoid, 200, cyan CHOOSE YOUR GAME, 260, green 1 - Monochromatic, 290, coral 2 - Full color, 310, cyan 3 - Tiny breaks, 330, cyan 4 - Tiny version 2, 350, cyan 5 - Randomized Versions, 370, cyan Use the mouse to move the bar, 450, cyan ************ August 2020 - Genuary 2021 *************, 480, gray""" pygame.init() def write(text, x, y, color="Coral",): "Returns a surface with a text in the center of the screen, at y coord." surface_text = font.render(text, 1, pygame.Color(color)) text_rect = surface_text.get_rect(center=(500 // 2, y)) screen.blit(surface_text, text_rect) return surface_text font = pygame.font.SysFont("Arial", 24) font2 = pygame.font.SysFont("Arial", 20) screen = pygame.display.set_mode((500, 600)) clock = pygame.time.Clock() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() clock.tick(30) render_multiline(TEXT1) pygame.display.update()
Load images into surfaces and flipping them too
This function will return a surface with an image whose name is passed as an argument, without the png at the end, just the name. If you have those images in a folder you will have to pass the argument as “folder/filename”.
Same thing for the flipped image.
So if you do player = load(“hero”) you will load the hero.png that is in the root folder and have a surface with the image called player. If you want to blit it on the screen you do screen.blit(player, (100, 100)).
If you have the image in a folder you do player = load(“imgs/hero”).
If you want the flipped image:
player_flip = flip(“imgs/hero”)
This will make the code easier to read.
def load(file): return pygame.image.load(file + ".png") def flip(file): return pygame.transform.flip(load(file), 0, 1)
Rotate an image
This will use the above load function to rotate di image, you just have to pass the name of the image without the .png and the angle. This way you will always call the original image each time you rotate it, so the image does not lose quality, but rember that starting from the original image, you will have to rotate it relatively to the original image, not to the last rotated image. So, if you want to go fro 90 to 91, you cannot to a +1 thing, but you must pass 91 as angle. You could use a counter to do that and then pass the counter as the angle.
def rotate(file, angle): return pygame.transform.rotate(load(file), angle)
Preparing for sounds
I think this is not necessary anymore with pygame 2.0, now that is official.
pygame.mixer.init(44100, -16, 2, 512) jump = pygame.mixer.Sound("sounds/jump.wav") jump.set_volume(0.5) hit = pygame.mixer.Sound("sounds/hit.wav") hit.set_volume(0.3) # To play a sound use: play(jump) def play(snd): "Plays one of the sounds in the sounds folder using play('name')" pygame.mixer.Sound.play(snd)
Adding a soundtrack
Load music indefinitively
pygame.mixer.init() pygame.mixer.music.load("music.mpe") pygame.mixer.music.play(-1)
[wip]
Add gravity to a sprite
def gravity(sprite): sprite.rect.top += 1
A scrolling basement class
class Base(pygame.sprite.Sprite): def __init__(self, file, x, y): global g super(Base, self).__init__() self.x = x self.y = y self.image = load(file) self.rect = pygame.Rect(self.x, self.y, 32, 32) g.add(self) def update(self): self.rect.left -= 1 # 400 is the width of the screen if self.rect.left < -400: self.rect.left = 399
A class for the background
class Bg(pygame.sprite.Sprite): def __init__(self, file, x, y): global g super(Bg, self).__init__() self.x = x self.y = y self.image = load(file) self.rect = pygame.Rect(self.x, self.y, w, h) g.add(self)
Making mask syntax memorable
Make this a method of the sprite class you of which you want to detect collision.
def make_mask(self): return pygame.mask.from_surface(self.image)
If you want to detect collisions with more enemies or object create and call this method in the Sprite class
def check_collision(self): global gameover for pipe in pipes: if pygame.sprite.collide_mask(pipe, self): print("touched") gameover = 1
A class to save maxscore
Create a file called score.py in a folder called functions and in the main file import it like this:
from functions.score import *
then create an istance of the class Score like this
score = Score("myscore.txt")
when you need to save the score (at the game over moment for example), write this:
game.save_score(score)
the score.py file to put into the folder functions is this:
import os class Score: def __init__(self, file) -> None: "Goes to load_maxscore() to see the last maxscore" self.file = file self.maxscore = self.load_maxscore() def file_is_empty(self) -> bool: "Returns True if there is nothing in the file -> writes 10" with open(self.file, "r") as file_check: f = file_check.read() if f == "": return True else: return False def save_score(self, score): "Saves the score if it's greater than the previous maxscore" print(score, self.maxscore) if int(score) >= int(self.maxscore): self.write_maxscore(str(score)) def write_maxscore(self, score: int): "Write in the score.txt file if it does not exists" with open(self.file, "w") as file: file.write(str(score)) self.maxscore = score def read_maxscore(self): "if the file exists and is not empty reads it and returns the score" with open(self.file, "r") as file_saved: last_maxscore = int(file_saved.read()) print("Maxscore = " + str(last_maxscore)) return last_maxscore def file_exists(self) -> True: "Check if file exists in the folder" if self.file in os.listdir(): return True else: return False def load_maxscore(self) -> int: "If there is a file with a maxscore it returns it\ so that it will be in self.maxscore,\ otherwise it will create a new file with a maxscore of 10\ and will return this 10" if self.file_exists(): if not self.file_is_empty(): # This reads the score and put in Puuzzle.maxscore maxscore = int(self.read_maxscore()) return maxscore else: self.write_maxscore("1") return 3 else: self.write_maxscore("1") return 3
Make a button
Full screen
Particles in pygame
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame