You are on page 1of 14

Learning to use pygame

Sunday, November 19, 2023

First I install the pygame package and import it in my script. Then


the next thing to do is initialize pygame. This command is used to help
the programmer be able to properly utilize the pygame package. Think
of it as starting a car thereby getting ready to drive it.
Code
import pygame

pygame.init()

then I will set the window of the program and I will do this by setting up
the width and length of the window. It is stored in a variable usually
called screen
screen = pygame.display.set_mode((width,length))
u replace the width with the number you want to set the width to(unit is
pixels though u don’t need to add it) then u set the length’s number.
screen = pygame.display.set_mode((800,400))

When we run what we initially wrote. A pygame will open for a while
and close. Well the window does not open for a long time because
python will terminate the code after executing the last line. To prevent
this we must use a while True loop to allow it to run continuously
Code
while True:
#draw all our elements and update everything
for event in pygame.event.get():

when u run this code now the window runs continuously but there is a
problem. We can’t close the window so now we must write code to
implement the close button in the window control box
if event.type == pygame.QUIT:
pygame.quit()
this will implement a functioning close button. Now we encounter
another problem. When we close the window, we get an error. This is
because the pygame.quit() is ending the program which is the opposite
of pygame.init() which is initializing the program. To solve this problem
we must import a function from the system library which is exit
import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))
while True:
#draw all our elements and update everything
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
finally at the end of the while loop always ensure it ends with
pygame.display.update()

this ensures that the window can accept user input which will update in
the program. To prevent yourself from forgetting to write this important
code write it first after typing while True: and write the rest of the code
in between.

This is how the code finally looks like


import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))
while True:
#draw all our elements and update everything
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
pygame.display.update()

Wednesday, November 22, 2023


Now the window’s name is pygame there is a way to change this
pygame.display.set_caption('adventure run')
type the new name in the parenthesis

now our window is blank(black). There is a way to change the colour of


the display surface, the size and position.
test_surface = pygame.Surface((100,200))

test_surface.fill('Red')

the numbers determine the width and length of the display surface. You
enter the colour in the parenthesis of fill.If you want the colour to fill the
screen then make the numbers the same as the screen variable.
NB: the Surface after the pygame. Should always start with a capital ‘S’
and start the colour you enter with a capital letter

Now to determine the positioning of the display surface just in case the
surface is not the same size as the screen. You type this
screen.blit(test_surface,(0,0))
the numbers in the parenthesis act like x and y on the Cartesian plane.
But here the plane acts a little different. So on the original Cartesian
plane the point 0,0 starts at the bottom left corner while in python this
point is at the top left corner.
Now we are coming to set the pace of the game.
clock = pygame.time.Clock()
clock.tick(60)

we are going to set the pace to 60 pixels per second

Below I will show how the code is supposed to look and the positioning
of the various commands

import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption('adventure run')
clock = pygame.time.Clock()

test_surface = pygame.Surface((100,200))
test_surface.fill('Red')
while True:
#draw all our elements and update everything
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(test_surface,(0,0))
pygame.display.update()
clock.tick(60)

Thursday, November 23, 2023


Using colour to fill the background was just a test run. We can replace
the display surface with images. Here we are going to import the image
sky and ground
Importing the images
sky_surface=pygame.image.load(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\Sky.png')
ground_surface=pygame.image.load(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\ground.png')

Setting their position on the screen


screen.blit(sky_surface,(0,0))
screen.blit(ground_surface,(0,300))

We can display text on the display surface. But before we can do that we
have to determine what type of font style we want to use and import that
file
test_font=pygame.font.Font(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\pixletype.ttf',50)

the number is indicating the font size


Now we are going to determine the words we will display, the colour
and the antialias
text_surface = test_font.render("my game",False,'Pink')
the first word in the parenthesis is the words u want to display, the
second one which is the Boolean is determining whether we want the
activate antialias or not. This is used to make the edges of our text
round. If we want to activate it we type ‘True’ instead. The third word is
the colour of the text

Next we are determine the positioning of the text on the display surface
screen.blit(text_surface,(300,50))

Now we are going to implement one of the enemies in the game which is
the snail.
snail_surface=pygame.image.load(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\snail1 (3).png')
now we just use the screen.blit command and enter the coordinates the
snail will just be static on the screen. But we want it to move. The code
we use is this
snail_x_pos = 600

under the while True loop


snail_x_pos -= 3
screen.blit(snail_surface,(snail_x_pos,250))
this will cause the snail to move to the left(-=) to move it to the right
type plus. Three was used so it will not move too slowly. One will cause
it to move too slowly.
Now we want the snail to come back when it reaches the end. We will
use an ‘if’ statement to make it come back to the starting position.
snail_x_pos -= 3
if snail_x_pos < -100: snail_x_pos = 800
screen.blit(snail_surface,(snail_x_pos,250))

Below is how the code is supposed to look and the positioning of the
various commands

import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption('adventure run')
clock = pygame.time.Clock()
test_font = pygame.font.Font(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\pixletype.ttf',50)
sky_surface = pygame.image.load(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\Sky.png')
ground_surface = pygame.image.load(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\ground.png')
text_surface = test_font.render("my game",False,'Pink')

snail_surface = pygame.image.load(r'C:\Users\ALEXANDRA\OneDrive\Desktop\
pythonProject\mygame\snail1 (3).png')
snail_x_pos = 600
while True:
#draw all our elements and update everything
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(sky_surface,(0,0))
screen.blit(ground_surface,(0,300))
screen.blit(text_surface,(300,50))
snail_x_pos -= 3
if snail_x_pos < -100: snail_x_pos = 800
screen.blit(snail_surface,(snail_x_pos,250))

pygame.display.update()
clock.tick(60)

Sunday, November 26, 2023


Rectangles
Rectangles are used in pygame to better position images and detect
collisions. Currently our snail is not touching the floor and we are going
to use rectangles to help us with that. Below I will show the various
positions in a rectangle
We will create a variable called snail_rectangle and import the rectangle
command and set our coordinates
snail_surface = pygame.image.load('snail1 (3).png')
snail_rectangle = snail_surface.get_rect(midbottom = (600,300))

it uses the same principle with the first number being the x coordinate
and the second being the y coordinate. It is important to use 300 as the y
coordinate because it is at this point that the floor picture is
now that we are using rectangles for the snail picture we have to change
the code so that the snail can move and reappear at the other side when it
leaves the screen
snail_rectangle.right -= 3
if snail_rectangle.left < -100: snail_rectangle.left = 800
screen.blit(snail_surface,snail_rectangle)

we are going to import the player image and use a rectangle to determine
its positioning
pygame.image.load('player_walk_1.png')
player_rectangle = player_surface.get_rect(midbottom = (80,300))
screen.blit(player_surface,player_rectangle)

now, originally, rectangles are set by inputting numbers for the


left,top,width and height. But we didn’t use that method because we
were importing images
#player_rectangle = pygame.Rect(left,top,width,height)

.convert() or .convert_alpha()
This method converts imported images to a suitable format for pygame.
Use .convert() on the first image used as the display surface and
use .convert_alpha() when another image will be placed on top of
another image
sky_surface = pygame.image.load('Sky.png').convert()
ground_surface = pygame.image.load('ground.png').convert()
snail_surface =
pygame.image.load('snail1(3).png').convert_alpha()
player_surface=pygame.image.load('player_walk_1.png').convert_alp
ha()

Below is how the code is supposed to look and the positioning of the
various commands

import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800,400))
pygame.display.set_caption('adventure run')
clock = pygame.time.Clock()
test_font = pygame.font.Font('pixletype.ttf',50)

sky_surface = pygame.image.load('Sky.png').convert()
ground_surface = pygame.image.load('ground.png').convert()
text_surface = test_font.render("my game",False,'Pink')

snail_surface = pygame.image.load('snail1
(3).png').convert_alpha()
snail_rectangle = snail_surface.get_rect(midbottom = (600,300))

player_surface =
pygame.image.load('player_walk_1.png').convert_alpha()

player_rectangle = player_surface.get_rect(midbottom = (80,300))


while True:
#draw all our elements and update everything
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(sky_surface,(0,0))
screen.blit(ground_surface,(0,300))
screen.blit(text_surface,(300,50))

snail_rectangle.right -= 3
if snail_rectangle.left < -100: snail_rectangle.left = 800
screen.blit(snail_surface,snail_rectangle)
#player_rectangle.left += 1
screen.blit(player_surface,player_rectangle)

pygame.display.update()
clock.tick(60)

Sunday, December 24, 2023


Detecting collisions with rectangles
We used rectangles for the images so we can detect collisions.
The format for the code is first_rectangle.colliderect(other_rectangle)
They can be used with if statement like the one I’m about to show where
when the snail rectangle collides with the player rectangle the word
collision is outputted
if player_rectangle.colliderect(snail_rectangle):
#print('collision')
we can also detect if the mouse pointer collides with another rectangle
image with that we do not use colliderect but collidepoint
mouse_position = pygame.mouse.get_pos()
if player_rectangle.collidepoint(mouse_position):
print('collision')

we used the variable mouse_position and stored the mouse pointer’s


position in it to use it because we cannot know the exact position of the
mouse pointer so we can use code to get the position
we can also use this to determine if certain buttons are pressed on the
mouse
mouse_position = pygame.mouse.get_pos()
if player_rectangle.collidepoint(mouse_position):
print(pygame.mouse.get_pressed())

it outputs three Booleans stored in a tuple. If no button is pressed, it


output a tuple containing three False values. If the left mouse button is
pressed the first false value changes to True. If the right mouse button is
pressed the last false value changes to True
we can also determine if a mouse button is pressed or not using an event
if event.type == pygame.MOUSEBUTTONDOWN:
print(‘button down’)

so if you press any mouse button the phrase button down is outputted.
You can also determine if the mouse button is released after being
pressed
if event.type == pygame.MOUSEBUTTONUP:
print(‘button up’)
if you do not press the mouse button at all. Nothing is outputted but if
you press and release it,the moment you release it ‘button up’ is
outputted
we learnt earlier how to detect if the mouse pointer collides with the
player. Here is another method using the event type
if event.type == pygame.MOUSEMOTION:
if player_rectangle.collidepoint(event.pos):
print('collision')

import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((800, 400))
pygame.display.set_caption('adventure run')
clock = pygame.time.Clock()
test_font = pygame.font.Font('pixletype.ttf', 50)

sky_surface = pygame.image.load('Sky.png').convert()
ground_surface = pygame.image.load('ground.png').convert()
text_surface = test_font.render("my game", False, 'Pink')

snail_surface = pygame.image.load('snail1
(3).png').convert_alpha()
snail_rectangle = snail_surface.get_rect(midbottom=(600, 300))

player_surface =
pygame.image.load('player_walk_1.png').convert_alpha()
# player_rectangle = pygame.Rect(left,top,width,height)
player_rectangle = player_surface.get_rect(midbottom=(80, 300))
while True:
# draw all our elements and update everything
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()

if event.type == pygame.MOUSEMOTION:
if player_rectangle.collidepoint(event.pos):
print('collision')

screen.blit(sky_surface, (0, 0))


screen.blit(ground_surface, (0, 300))
screen.blit(text_surface, (300, 50))

snail_rectangle.right -= 3
if snail_rectangle.left < -100:
snail_rectangle.left = 800
screen.blit(snail_surface, snail_rectangle)

# player_rectangle.left += 1
screen.blit(player_surface, player_rectangle)

# if player_rectangle.colliderect(snail_rectangle):
#print('collision')
#mouse_position = pygame.mouse.get_pos()
#if player_rectangle.collidepoint(mouse_position):
# print('collision')
# print(pygame.mouse.get_pressed())

pygame.display.update()
clock.tick(60)

Wednesday, December 27, 2023


Using rectangles to draw shapes and lines
For this you use a special command called pygame.draw.the preferred
shape. You can use this command to draw rectangles,circles,ovals,lines
etc.
Drawing rectangles
We are going to use the rectangle and display the score text in it
pygame.draw.rect(screen, 'red', score_rectangle, 6,20)
the 6 is the width and the 20 the border radius
Drawing a line
this draws a line from the left top of the window to the right
bottom of the window
pygame.draw.line(screen,'pink',(0,0), (800,400), 20)
starting end point line thickness
point

this draws a line that follows the mouse pointer

#pygame.draw.line(screen,'pink',(0,0),pygame.mouse.get_pos(),20)

You might also like