Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to make a Python Maze Game in.. guess what? Python!
InvisibleOne (2678)

Fun little Maze Game

Step One - import some stuff

import os
import random
from colorama import Back, Style
from getch import getch

Step Two - Make a list of lists

map = [
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],
	['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'],

Step Three - Print it

for x in map:
	out = ''
	for i in x:
		if i == 'p': #p for path
			out += Back.BLACK + '   ' + Style.RESET_ALL
		elif i == 'x':
			out += Back.WHITE + '   ' + Style.RESET_ALL
		elif i == 'b':
			out += Back.GREEN + '   ' + Style.RESET_ALL
		elif i == 'w':
			out += Back.RED + '   ' + Style.RESET_ALL

Step Four - Make some variables

x = 1
y = 1

Step Five - A loop

while True:
	os.system('clear') #be prepared for cursor to go brrrr
	map[y][x] = 'b'
	print_map() #oops, did I forget to tell to make printing the map a function?

Step Six - Make it move

	i = getch()
	if i == 'w':
		y += 1
	elif i == 's':
		y -= 1
	elif i == 'd':
		x += 1
	elif i == 'a':
		x -= 1
	pass #cuase why do something when you can do nothing?

Step Seven - making sure you don’t collide with walls

#add this to each if statement respectively
and map[y+1][x] != 'x'
and map[y-1][x] != 'x'
and map[y][x+1] != 'x'
and map[y][x-1] != 'x'

Step Eight - Make the walls

for i in range(100): #lets make 100 walls
	map[random.randint(0,9)][random.randint(0,9)] = 'x'

Step Nine - How to win

map[random.randint(0,9)][random.randint(0,9)] = 'w' 
if map[y][x] = 'w':
	print("You Win!")

Step Ten - Play

Okay, so the fact that you guy leaves a tail is meant to be there since it lets us know where we’ve been.
But if you really do want to get rid of the tail, just put this right after our try

map[y][x] = 'p'

Yeah, we could remove it by setting that space back to ‘p’ before moving our player but remember my motto, why do something when you can do nothing?
Also, the fact that you might not win every single time and that you will probably lose every single time doesn’t mean it’s a bad game, it just means it a work in progress.

Note: If the repl does not work then blame the IDE

FloCal35 (483)

Wait, are you serious. A python maze in python


I would have never guessed

Cag82407 (0)

Bro if w is pressed you want y -=1 not +=1, same for s

Wumi4 (481)

Wait, how can I beat this, I'm stuck!

InvisibleOne (2678)

Must be a glitch... @Wumi4

jk, since it randomly places the walls it is very difficult to even have the ability to complete the maze