我如何制作这个迷宫?

时间:2015-06-17 15:26:00

标签: python arrays

对于我的计算课,我必须用我选择的语言制作迷宫,我选择了python。我尝试了但是我无法解决这里是我们给出的指示: 此网格可以表示为2-D整数数组:

DECLARE maze AS ARRAY OF ARRAY OF INTEGER INITIALLY []

SET maze TO [ [] ] * 9  # array with 9 elements, each an empty array
DECLARE maze AS ARRAY OF ARRAY OF INTEGER INITIALLY []

#This loop fills the 2-D array with the value -1.

SET maze TO [ [] ] * 9  # array with 9 elements, each an empty array
FOR counter FROM 0 TO 8 DO
    maze[ counter ] = [0] * -1

    # Update each element to be a 4-element array of -1s

END FOR

一旦初始化了2D数组或数组数组,如果您想将其内容打印为表格,可以使用以下代码完成:

FOR column FROM 0 TO 8 DO
    FOR row FROM 0 TO 3 DO
       SEND maze[column] [row] TO DISPLAY
    END FOR
    <print new line>
END FOR

这种计算结构通常被称为嵌套循环。

我们现在可以设置需要包含带有一组语句的房间号的单元格。

SET maze[0][1] TO 1 
SET maze[1][1] TO 2
SET maze[1][2] TO 4
SET maze[2][2] TO 5
SET maze[2][3] TO 1  .... etc.

完成这组命令后,可以使用程序对从一个房间移动到另一个房间的结果进行编码。

程序ChangeRoom(INTEGER room,INTEGER direction)

DECLARE newRoom INITIALLY 0  
IF maze[room][direction] = -1  THEN
     SEND "you have hit a wall" TO DISPLAY
   ELSE
     SET newRoom TO maze[room][direction]
     SEND "You are now in room "& newRoom TO DISPLAY
 END IF
   SET room TO newRoom

END PROCEDURE

1 个答案:

答案 0 :(得分:1)

这应该让你开始:

import random
def init_maze():
    maze = [[]] * 9
    for counter in range(0, 9):
        maze[counter] = [-1] * 4
    return maze

def print_maze(maze):

    for column in range(0, 9):
        for row in range(0, 4):
            print maze[column][row],
        print ''

def set_cells(maze):
    for column in range(0, 9):
        for row in range(0, 4):
            maze[column][row] = random.randint(1,5)
    return maze

def change_room(room, direction):
    newRoom = 0
    if maze[room][direction] == -1:
        print "you have hit a wall"
    else:
        newRoom = maze[room][direction]
        print "You are now in room {0}".format(newRoom)
    room = newRoom

maze = init_maze()
print_maze(maze)
print 'Randomizing...'
maze = set_cells(maze)
print 'Done'
print_maze(maze)