# A program that draws a maze for the user to solve with the turtle # Author: Nicholas Coleman # # The maze map is set up as a list of lists of one-digit hexadecimals. # Each hexadecimal digit corresponds to a 4-bit encoding of a particular # cell configuration: # * 1-bit: east wall # * 2-bit: north wall # * 4-bit: west wall # * 8-bit: south wall # For example, 0xB = 11 = 8 + 2 + 1 = south, north, and east walls # # The program is currently set up to draw a hard-coded maze, move the # turtle to the entrance, then allow the user to use the arrow keys to # move the turtle through the maze. # If the user clicks the window it will exit. # It does not currently prevent the user from moving through walls, and # it does not tell the user if they have successfully completed the maze. from turtle import * def main(): cellWidth = 50 startPos = 1 mazeMap = [[0xE, 0xD, 0x6, 0xC, 0x6], [0x2, 0xC, 0x3, 0xB, 0xA], [0x8, 0x1, 0x6, 0xE, 0xA], [0xB, 0xE, 0x9, 0x1, 0x2], [0xC, 0x1, 0x5, 0x6, 0x9], [0xB, 0xD, 0x5, 0x1, 0x7]] drawMaze(mazeMap, cellWidth, startPos) shape("turtle") listen() onkey(moveUp, "Up") onkey(moveDown, "Down") onkey(moveLeft, "Left") onkey(moveRight, "Right") exitonclick() def drawCell(cellNum, cellWidth): for side in [0x1, 0x2, 0x4, 0x8]: if cellNum & side: pendown() else: penup() forward(cellWidth) left(90) def drawMaze(mazeMap, cellWidth, startPos): # number of rows and columns numRows = len(mazeMap) numCols = len(mazeMap[0]) # where start drawing the upper-left cell xPosUL = -(numCols / 2 * cellWidth) yPosUL = (numRows / 2 - 1) * cellWidth # where to put the turtle after drawing the maze. xPosStart = xPosUL - cellWidth / 2 yPosStart = yPosUL - startPos * cellWidth + cellWidth / 2 # go to the lower-left corner of the upper-left cell penup() goto(xPosUL, yPosUL) # draw each cell in the maze using the map given for row in range(numRows): for col in range(numCols): drawCell(mazeMap[row][col], cellWidth) penup() forward(cellWidth) if numRows - row > 1: goto(xcor() - cellWidth * numCols, ycor() - cellWidth) else: goto(xPosStart, yPosStart) def moveUp(): goto(xcor(), ycor() + 50) def moveDown(): goto(xcor(), ycor() - 50) def moveLeft(): goto(xcor() - 50, ycor()) def moveRight(): goto(xcor() + 50, ycor()) main()