在看到这篇用 PHP 制作完美迷宫生成(基于瓦片的版本)的旧文章后,我尝试将原始 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[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 输出确实不同:
###################
# # # #
### # # ##### ### #
# # # # # # # #
# # # ### # ### ###
# # # # # #
# # ### ##### ### #
# # # # #
# ### ########### #
# # # # #
# # ### ####### # #
# # # # # #
# ####### # # ### #
# # #
###################