Build Simple Python Games

Python developers never never get tired

Ali Aref
8 min readAug 16, 2021

Have you ever wondered how video games are createdšŸ¤”? Itā€™s not as complicated as you might thinkšŸ„“!
In this tutorial, youā€™ll create a simple game called PackmanšŸ‘£šŸ‘¾, Connect šŸ”“šŸŸ”, SnakešŸ and Tic Tak Toe ā­•ļøāŒ.
To write this game, youā€™ll use Python. No, Iā€™m not talking about a big snake! šŸ˜…, Python is a computer programming languagešŸ’». We chose Python for this tutorial because itā€™s a simple language to start out with, and is fun and easy to learn.

If you are new to Python, before you begin check out this book: Think Python: How to Think Like a Computer Scientist. That should get you up to speed.

Then dive back here and get ready ā€” thereā€™s a war coming on between the bunnies and the badgers. Keep reading to jump into the fray!

Pacman

Pacman ā€” classic arcade game. Use the arrow keys to navigate and eat all the white food. Watch out for red ghosts that roam the maze.
First install freegames and turtle as

pip install turtle
pip install freegames

then write the pacman code itā€™s simple and easy as

""" Simple Python GUI Games, ~ AliAref """""" PACMAN """
from random import choice
import turtle
from turtle import *
from freegames import floor, vectorstate = {"score": 0}
path = Turtle(visible=False)
writer = Turtle(visible=False)
turtle.title("Pacman ~ AliAref")
aim = vector(5, 0)
pacman = vector(-40, -80)
ghosts = [
[vector(-180, 160), vector(5, 0)],
[vector(-180, -160), vector(0, 5)],
[vector(100, 160), vector(0, -5)],
[vector(100, -160), vector(-5, 0)],
]
# fmt: off
tiles = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0,
0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
]
# fmt: on
def square(x, y):
"Draw square using path at (x, y)."
path.up()
path.goto(x, y)
path.down()
path.begin_fill()
for count in range(4):
path.forward(20)
path.left(90)
path.end_fill()def offset(point):
"Return offset of point in tiles."
x = (floor(point.x, 20) + 200) / 20
y = (180 - floor(point.y, 20)) / 20
index = int(x + y * 20)
return index
def valid(point):
"Return True if point is valid in tiles."
index = offset(point)
if tiles[index] == 0:
return False
index = offset(point + 19)if tiles[index] == 0:
return False
return point.x % 20 == 0 or point.y % 20 == 0def world():
"Draw world using path."
bgcolor("black")
path.color("blue")
for index in range(len(tiles)):
tile = tiles[index]
if tile > 0:
x = (index % 20) * 20 - 200
y = 180 - (index // 20) * 20
square(x, y)
if tile == 1:
path.up()
path.goto(x + 10, y + 10)
path.dot(2, "white")
def move():
"Move pacman and all ghosts."
writer.undo()
writer.write(state["score"])
clear()if valid(pacman + aim):
pacman.move(aim)
index = offset(pacman)if tiles[index] == 1:
tiles[index] = 2
state["score"] += 1
x = (index % 20) * 20 - 200
y = 180 - (index // 20) * 20
square(x, y)
up()
goto(pacman.x + 10, pacman.y + 10)
dot(20, "yellow")
for point, course in ghosts:
if valid(point + course):
point.move(course)
else:
options = [
vector(5, 0),
vector(-5, 0),
vector(0, 5),
vector(0, -5),
]
plan = choice(options)
course.x = plan.x
course.y = plan.y
up()
goto(point.x + 10, point.y + 10)
dot(20, "red")
update()for point, course in ghosts:
if abs(pacman - point) < 20:
return
ontimer(move, 100)def change(x, y):
"Change pacman aim if valid."
if valid(pacman + vector(x, y)):
aim.x = x
aim.y = y
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
writer.goto(160, 160)
writer.color("white")
writer.write(state["score"])
listen()
onkey(lambda: change(5, 0), "Right")
onkey(lambda: change(-5, 0), "Left")
onkey(lambda: change(0, 5), "Up")
onkey(lambda: change(0, -5), "Down")
world()
move()
done()

And thatā€™s it!

Connect

Connect 4 game. Click a row to drop a disc. The first player to connect four discs vertically, horizontally, or diagonally wins!
Install prerequisites as

pip install turtle
pip install freegames

then code the connect game

""" Simple Python GUI Games, ~ AliAref """""" Connect """
import turtle
from turtle import *
from freegames import lineturns = {'red': 'yellow', 'yellow': 'red'}
state = {'player': 'yellow', 'rows': [0] * 8}
def grid():
"Draw Connect Four grid."
bgcolor('light blue')
for x in range(-150, 200, 50):
line(x, -200, x, 200)
for x in range(-175, 200, 50):
for y in range(-175, 200, 50):
up()
goto(x, y)
dot(40, 'white')
update()def tap(x, y):
"Draw red or yellow circle in tapped row."
player = state['player']
rows = state['rows']
row = int((x + 200) // 50)
count = rows[row]
x = ((x + 200) // 50) * 50 - 200 + 25
y = count * 50 - 200 + 25
up()
goto(x, y)
dot(40, player)
update()
rows[row] = count + 1
state['player'] = turns[player]
turtle.title("Connect Game ~ AliAref")
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
onscreenclick(tap)
done()

As easy as that!

TicTacToe

A classic game. Click the screen to place an X or O. Connect three in a row and you win!
Install Prerequisites

pip install turtle
pip install freegames

and finally your tic tac toe game, code will be as

""" Simple Python GUI Games, ~ AliAref """""" Tic Tac Toe """
import turtle
from turtle import *
from freegames import line
def grid():
"Draw tic-tac-toe grid."
line(-67, 200, -67, -200)
line(67, 200, 67, -200)
line(-200, -67, 200, -67)
line(-200, 67, 200, 67)
def drawx(x, y):
"Draw X player."
line(x, y, x + 133, y + 133)
line(x, y + 133, x + 133, y)
def drawo(x, y):
"Draw O player."
up()
goto(x + 67, y + 5)
down()
circle(62)
def floor(value):
"Round value down to grid with square size 133."
return ((value + 200) // 133) * 133 - 200
state = {'player': 0}
players = [drawx, drawo]
def tap(x, y):
"Draw X or O in tapped square."
x = floor(x)
y = floor(y)
player = state['player']
draw = players[player]
draw(x, y)
update()
state['player'] = not player
turtle.title("Tic Tak Teo ~ AliAref")
setup(420, 420, 370, 0)
hideturtle()
tracer(False)
grid()
update()
onscreenclick(tap)
done()

And your done!

Snake

This was most of us favorite game when we were kids. We can actually code this game in python by importing just two modules! How cool is that!

Firstly, we need to install turtle. If you donā€™t have it already installed, open your terminal or cmd and type in the following command.

pip install turtle

Here is the simplest python snake game!

""" Simple Python GUI Games, ~ AliAref """""" Snake """
import turtle
import random
w, h = 500, 500
food_size = 10
delay = 100
offsets = {"up": (0, 20), "down": (0, -20), "left": (-20, 0), "right": (20, 0)}def reset():
global snake, snake_dir, food_position, pen
snake = [[0, 0], [0, 20], [0, 40], [0, 60], [0, 80]]
snake_dir = "up"
food_position = get_random_food_position()
food.goto(food_position)
move_snake()
def move_snake():
global snake_dir
new_head = snake[-1].copy()
new_head[0] = snake[-1][0] + offsets[snake_dir][0]
new_head[1] = snake[-1][1] + offsets[snake_dir][1]
if new_head in snake[:-1]:
reset()
else:
snake.append(new_head)
if not food_collision():
snake.pop(0)
if snake[-1][0] > w / 2:
snake[-1][0] -= w
elif snake[-1][0] < -w / 2:
snake[-1][0] += w
elif snake[-1][1] > h / 2:
snake[-1][1] -= h
elif snake[-1][1] < -h / 2:
snake[-1][1] += h
pen.clearstamps()for segment in snake:
pen.goto(segment[0], segment[1])
pen.stamp()
screen.update()turtle.ontimer(move_snake, delay)def food_collision():
global food_position
if get_distance(snake[-1], food_position) < 20:
food_position = get_random_food_position()
food.goto(food_position)
return True
return False
def get_random_food_position():
x = random.randint(-w / 2 + food_size, w / 2 - food_size)
y = random.randint(-h / 2 + food_size, h / 2 - food_size)
return (x, y)
def get_distance(pos1, pos2):
x1, y1 = pos1
x2, y2 = pos2
distance = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
return distance
def go_up():
global snake_dir
if snake_dir != "down":
snake_dir = "up"
def go_right():
global snake_dir
if snake_dir != "left":
snake_dir = "right"
def go_down():
global snake_dir
if snake_dir != "up":
snake_dir = "down"
def go_left():
global snake_dir
if snake_dir != "right":
snake_dir = "left"
screen = turtle.Screen()
screen.setup(w, h)
screen.title("Snake ~ AliAref")
screen.bgcolor("lightblue")
screen.setup(500, 500)
screen.tracer(0)
pen = turtle.Turtle("square")
pen.penup()
food = turtle.Turtle()
food.shape("circle")
food.color("red")
food.shapesize(food_size / 10)
food.penup()
screen.listen()
screen.onkey(go_up, "Up")
screen.onkey(go_right, "Right")
screen.onkey(go_down, "Down")
screen.onkey(go_left, "Left")
reset()
turtle.done()

Conclusion

And thatā€™s it! These are some of the easy games in Python that you can create as a beginner and have some fun! We loved building these projects and we hope you do too!

--

--

No responses yet