Ruby中的迷宫生成
在看了这篇关于making的老文章之后,我尝试将原始PHP代码翻译成Ruby。几次尝试之后,我看不出我在哪里犯了错误 以下是我的Ruby代码:Ruby中的迷宫生成,ruby,algorithm,maze,Ruby,Algorithm,Maze,在看了这篇关于making的老文章之后,我尝试将原始PHP代码翻译成Ruby。几次尝试之后,我看不出我在哪里犯了错误 以下是我的Ruby代码: maze_width = 9 maze_height = 7 moves = [] width = 2*maze_width +1 height = 2*maze_height +1 maze = Hash.new{|h, k| h[k] = []} for x in 0..height-1 for y in 0..width-1
maze_width = 9
maze_height = 7
moves = []
width = 2*maze_width +1
height = 2*maze_height +1
maze = Hash.new{|h, k| h[k] = []}
for x in 0..height-1
for y in 0..width-1
maze[x][y] = 1
end
end
x_pos = 1
y_pos = 1
maze[x_pos][y_pos] = 0
moves.push(y_pos + (x_pos * width))
while(!moves.empty?)
possible_directions = ""
# puts "x_pos: #{x_pos} y_pos: #{y_pos}"
if(maze[x_pos+2][y_pos]== 1 and x_pos+2!=0 and x_pos+2!=height-1)
possible_directions += "S"
end
if(maze[x_pos-2][y_pos]== 1 and x_pos-2!=0 and x_pos-2!=height-1)
possible_directions += "N"
end
if(maze[x_pos][y_pos-2]== 1 and y_pos-2!=0 and y_pos-2!=width-1)
possible_directions += "W"
end
if(maze[x_pos][y_pos+2]== 1 and y_pos+2!=0 and y_pos+2!=width-1)
possible_directions += "E"
end
if(!possible_directions.empty?)
move = rand(possible_directions.length)
case(possible_directions[move].chr)
when "N":
maze[x_pos-2][y_pos] = 0;
maze[x_pos-1][y_pos] = 0;
x_pos -= 2;
when "S":
maze[x_pos+2][y_pos] = 0;
maze[x_pos+1][y_pos] = 0;
x_pos += 2;
when "W":
maze[x_pos][y_pos-2] = 0;
maze[x_pos][y_pos-1] = 0;
y_pos -= 2;
when "E":
maze[x_pos][y_pos+2] = 0;
maze[x_pos][y_pos+1] = 0;
y_pos += 2;
end
moves.push(y_pos+(x_pos*width))
else
back = moves.pop
x_pos = (back/width).floor
y_pos = back%width
end
end
# draw the maze
for x in 0..height-1
for y in 0..width-1
print((maze[x][y] == 1) ? "#" : " ")
end
puts
end
如果我这样做,它会显示一个丑陋且不完美的迷宫:
###################
# # #
# # #
#
## # #
# # #
# # #
#
# #
# #
## # #
# # #
# #
#
###################
这与PHP输出完全不同:
###################
# # # #
### # # ##### ### #
# # # # # # # #
# # # ### # ### ###
# # # # # #
# # ### ##### ### #
# # # # #
# ### ########### #
# # # # #
# # ### ####### # #
# # # # # #
# ####### # # ### #
# # #
###################
在不同语言之间翻译代码时,要注意挑剔的语义差异。在这里,最让人头疼的是Ruby中的负索引从数组末尾开始倒数,而不是返回null。迷宫代码没有任何范围检查,以查看
x_pos
或y_pos
是否正在从阵列末端移动;如果请求不存在的元素,它只依赖于返回null的数组。最终的结果是,你允许从左边和上面移动,并得到荒谬的结果。
如果随机化器打对了,你也会在右边和底部出现零异常,所以你也需要检查这些异常
因此,在四个方向检查中,添加一些范围代码。e、 g,转动这个:
if(maze[x_pos+2][y_pos]== 1 and x_pos+2!=0 and x_pos+2!=height-1)
possible_directions += "S"
end
if(maze[x_pos-2][y_pos]== 1 and x_pos-2!=0 and x_pos-2!=height-1)
possible_directions += "N"
end
为此:
if(x_pos+2 < height and maze[x_pos+2][y_pos]== 1 and x_pos+2!=0 and x_pos+2!=height-1)
possible_directions += "S"
end
if(x_pos-2 > 0 and maze[x_pos-2][y_pos]== 1 and x_pos-2!=0 and x_pos-2!=height-1)
possible_directions += "N"
end
if(x_pos+20,迷宫[x_pos-2][y_pos]==1,x_pos-2!=0,x_pos-2!=高度-1)
可能的方向+=“N”
结束
同样地,对于
y_pos
和width
程序,您可以在每个程序中输出中间值,以查看Ruby程序出错的地方?谢谢!这正是你对你的答案的评论。现在它工作正常了!