【问题标题】:How do I make this maze? [closed]我如何制作这个迷宫? [关闭]
【发布时间】:2015-09-02 22:38:54
【问题描述】:

对于我的计算机课,我必须用我选择的语言制作迷宫,我选择了 python。我试过但我无法解决这里是我们得到的指示: 这个网格可以表示为一个二维整数数组:

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.

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

PROCEDURE 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

【问题讨论】:

  • 这是某种形式的 Pascal/PLSQL/whatnot,而不是 Python。问题出在哪里?
  • 我认为他们在示例中没有使用任何语言,据我所知,这是一种伪代码,无论如何他们说要在 python 中实现。
  • 在这里复制粘贴你的作业并加上“我试过了,但我做不出来”不是问题。做好自己的功课。

标签: python arrays


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2012-08-02
    相关资源
    最近更新 更多