我怎么做这个迷宫?

布鲁斯·W

对于我的计算机课程,我必须使用我选择的python语言来做一个迷宫。我尝试过,但无法解决,这是我们得到的指示:此网格可以表示为2D整数数组:

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

初始化二维数组或数组数组后,如果您想将其内容打印为表格,可以使用以下代码完成:

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房间,INTEGER方向)

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
亨斯特

这应该使您开始:

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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章