Pygame Master 1

I think that the most hard stuff to start with Pygame is to… start, if you forgive the words game. In fact there are a lot non intuitive stuff to learn just to make a simple window without making it to crash, to load a sound in the right way, and image, not to talk about other stuff. Once you learned this, you can make very nice thing with pygame, so it’s a shame that you can be stopped by these silly stuff. For this reason, I am making this post where you can take care of all these basic stuffs at easy to have everything under control and without having to rewrite them everytime. So, here I will show you some stuff I learned and that I wished someone could have told me before.

It’s just a window with everything ready to go

The first thing we are going to do is to fix the window with the way to close it (with the x button and the escape key) and to initialize the code for the audio to be the best. I added also a class for the colors, it is not necessary, but I like to have everything organized in the right place with the right name, to get the full controll of all the code process. It is a personal choice, I know, you do not have to do it.

import pygame
import sys
from glob import glob
import os


class Colors:
    BLACK = (0, 0, 0)
    RED = (255, 0, 0)
    GREEN = (0, 255, 0)
    YELLOW = (255, 255, 0)
    ORANGE = (128, 255, 0)
    BLUE = (0, 0, 255)
    GRAY = (255, 255, 255)


def mixer():
    "Initializing pygame and mixer"
    pygame.mixer.pre_init(44100, -16, 1, 512)
    pygame.init()
    pygame.mixer.quit()
    pygame.mixer.init(22050, -16, 2, 512)
    pygame.mixer.set_num_channels(32)


def load_sounds(directory="sounds"):
    "store in sounds dic all the sound in the directory by their name"
    global sounds
    if "sounds" not in os.listdir():
        os.mkdir("sounds")

    lsounds = glob(f"{directory}\\*.wav")
    # Dictionary with all sounds, keys are the name of wav
    sounds = {}
    for sound in lsounds:
        sounds[sound.split("\\")[1][:-4]] = pygame.mixer.Sound(f"{sound}")

def play(sound):
    "It plays the sounds by the name of the file without .wav"
    global sounds
    try:
        pygame.mixer.Sound.play(sounds[sound])
    except KeyError:
        print(f"------\nAlert!\nfile '{sound}.wav' not found in 'sounds'\n------")
        print("Check the name of the file in the sounds folder")


def create_fonts(family="Arial", size=24):
    return pygame.font.SysFont(family, size)


def init(size=(400, 400), name="Game"):
    "The screen and the clock"
    global screen, clock
    screen = pygame.display.set_mode((400, 400))
    pygame.display.set_caption("Game")
    clock = pygame.time.Clock()
    mixer()
    load_sounds()


def event_listener():
    "Intercept the user inputs"
    for event in pygame.event.get():
        k = pygame.KEYDOWN
        e = pygame.K_ESCAPE
        escape = event.type == k and event.key == e
        if event.type == pygame.QUIT or escape:
            pygame.quit()
            sys.exit()


def main():
    "Takes care of the process inside the main window"
    while 1:
        # Intercept user inputs
        event_listener()
        pygame.display.update()
        clock.tick(360)


# ====================== Start ======
''' This initialize pygame, the mixer, load the sounds
'''
init(size=(400, 400), name="Game")
play("over2")
# this opens the window
main()

So the while loop takes care of what is goin’ on on the window. I’ve put outside the input control (event_listener()) to mantain the while loop clean and easy to manage, because it’s there that all the things starts to happen.

What now?

In the next post we will see how to take care of the graphic part and the fonts.

1.1 – Pong the father of Arkanoid

Pong v. 1.0 – Pygame example

1.2 – Starting arkanoid… from pong

Arkanoid… let’s make it better…

1.3 – Adding background

ArkaPyGame 1.3 – Adding a background

1.4 – Collision detection

ArkaPygame 1.4 – Collision detected

1.5 – Bricks collisions

Arkanoid in pygame part 5

1.6 – Still on Collisions

Arkanoid part 6 – Still on bricks collision

1.7 – Fixed strange bouncing

Arkanoid 1.7 – Fixed strange bouncing

1.8 – How to destroy the bricks

Arkanoid 1.8 – First stage almost complete: destroy bricks

1.9 – More levels

Arkanoid 1.9 – more stages

2.1 – Infinite level generator

Arkanoid 2.0 – infinite levels

2.3 – Sounds and faster frame rate tecnique

ArkaPyGame 2.1 – Arkanoid like game made with Pygame

2.5 – New nicer levels simmetric and in color and menus

Arkanoid-Pygame 2.5 – New levels and menu

2.6 – Keyboard control

ArkaGame 2.6 – Adding keyboard commands

2.7 – Mouse exclusive control

Arkanoid 2.7 with Pygame – Mouse control

2.xxx – Tiny version

TinyArka – “Mini” version of Arkanoid with pygame

5.0 – Arkagame: 5 different versions

Breakout / Arkanoid – 5 versions in one (pygame)

Github repository
https://github.com/formazione/arkapygame


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.