Welcome to the second part of pygame_book, the first book to make videogames with pygame that is completely open and built into a python script that makes you navigate throught the different chapters being costantly updated and full of examples understandable by humans.
Ok, let’s display something on the screen surface
We saw, the first part, something like this (let’s call this game.py). If you want to go the repository for these files, go to https://github.com/formazione/pygame_book
In this repository you will also find a script called pygame_book that lets you navigate through the files and that will become a manual to create a 2d platformer.
# Thi is imported by game.py import pygame as pg class Game: def __init__(self, w, h): "Initialize main surface (screen) and starting the loop" self.w = w self.h = h self.size = w, h self.screen = pg.display.set_mode(self.size) self.loop() def close_window(self, event, game): "Close the window with the x button or Esc" quit = event.type == pg.QUIT escape = event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE if quit or escape: game = 0 return game def loop(self): "The loop that make the game go on" game = 1 while game: for event in pg.event.get(): game = self.close_window(event, game) pg.quit() if __name__ == "__main__": game = Game(16*50, 16*50)
The result was this
Let’s use this from another module
Now we want to load this script from another one, so that we do not have too many lines of code in the main one. Let’s call this main.py with this code.
''' needs the main.py (aka window.py) in the scripts folder ''' from game import Game game = Game(400, 400)
So, now we have the main.py module that imports the class Game from game.py.
This video will make everything clear
Ok, a video is better than a thousand words, so let’s see what I want to do in this project.
So I am using the code from this other project: https://github.com/formazione/pysnippets that let’s you create a browser for your files to take memo of what you are doing. This project is also a work in progress, so expect various bugs. It is a GUI made with tkinter (post about it).
See ya in the next videos about pygame, tkinter and kivy.
Subscribe to the newsletter for updates
Tkinter templates
My youtube channel
Twitter: @pythonprogrammi - python_pygame