Making Mazes
Back to index
This sample program produces a very simple "maze" using a 5x5 grid. Get this
program up and running and study it carefully so that you understand how it
works.
#!/usr/bin/python
# simple maze using 5x5 grid
from Tkinter import *
master = Tk()
w = Canvas(master, width=200, height=200)
w.pack()
c=0
i=0
m= [0,0,0,0,0,
0,1,1,1,0,
0,1,0,1,0,
0,1,1,1,0,
0,0,0,0,0,]
for x in m:
if x == 1:
c='blue'
else:
c='black'
w.create_rectangle(40*(i%5),40*(i/5),40*(i%5)+40,40*(i/5)+40,fill=c)
i += 1
mainloop()
There are a couple key parts of this demo program. First of all, there's the
array called m. It could have been written as one long line, but instead it
was broken up into five lines so that its purpose is more comprehensible.
You should have realized that the ones in the array correspond to blue
squares in the output graphic and that the zeroes in the array correspond to
black squares. The key line which produces the output is this line:
w.create_rectangle(40*(i%5),40*(i/5),40*(i%5)+40,40*(i/5)+40,fill=c)
As long as you understand how the modulus operator works, this line should
be fairly easy to interpret. If not, then you need to spend some time
experimenting with the modulus operator until you understand how it works.
ASSIGNMENT:
Make the following changes to the sample program:
- Create a maze based on a 10x10 grid
- You may increase the size of the canvas area to accomodate 20x20 squares
or you can leave the canvas size the same and work with smaller squares
- Make your maze much more interesting than the one produced by the sample
program
|