What is Pygame?
Pygame is a library, that is used to create graphics, graphs, and video games. It is used to create more "simple" games, to create a game with advanced graphics you would want to use an actual game engine. If you wanted to create games similar to Skyrim, Witcher, Assassin's Creed, or League of Legends you would want to use a game engine like UnReal or Unity.
Where to begin
To start pygame, you have to install it first, it is not automatically installed when you download Python. In your computers terminal type $ pip3 install pygame
. Now that pygame is installed, import it into your favorite code editor; before anymore code is written you have to initialize it. To do this type pygame.init()
under where you imported pygame.
Now to create the window that the player views, set the screen with height and width as arguments- screen = pygame.display.set_mode((width, height))
. When this code runs, a window will pop for a split second and then disappear, at this point that is what your code is supposed to do, so don't panic. To get the game window to stay, all you have to do is create a while true loop and within this loop is where you will write all of the elements of your game and update any code. Don't forget to create a way to update the screen by adding pygame.display.update()
within that while true loop.
At this point do not run your code. Your game will be stuck because you don't have a way to exit out of the game window. To be able close the game window create a for loop-
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
Now you will be able to exit the game window, but it's now throwing an error because it is the first part of the solution. The second part is to get exit() by importing it from sys import exit
and underneath pygame.quit()
add exit()
.
Something to consider when you are setting up your game, is to set the frame rate, this will help the game stay consistent between different computers. Create a clock clock = pygame.time.Clock()
, and in the for loop set it to 60 frames per second (fps), clock.tick(60)
.
Basic Code
Here is an example of how basic starter code in pygame would look like.
import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800, 400))
#set game name here
pygame.display.set_caption(“Name”)
# the c in time.Clock has to capitalized
clock = pygame.time.Clock()
while True:
# write all elements
# update everything
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.update()
# this is the maximum frame rate
clock.tick(60)
References-
Clear Code- “The Ultimate Introduction to Pygame”
https://www.youtube.com/watch?v=AY9MnQ4x3zk
*note- This post is basically my notes from the above video.
Pygame Documentation
https://pythonprogramming.net/pygame-python-3-part-1-intro/
Pygame Events-
https://www.pygame.org/docs/ref/event.html
Top comments (0)