赞 | 68 |
VIP | 397 |
好人卡 | 580 |
积分 | 22 |
经验 | 311270 |
最后登录 | 2022-3-9 |
在线时间 | 4033 小时 |
Lv3.寻梦者 (版主) …あたしは天使なんかじゃないわ
- 梦石
- 0
- 星屑
- 2208
- 在线时间
- 4033 小时
- 注册时间
- 2010-10-4
- 帖子
- 10779
|
本帖最后由 taroxd 于 2015-1-3 16:44 编辑
不过由于鄙人阅读脚本的能力甚是太好,别人写的基本都看不懂OTZ Umm..所以还是自己写好了
十分赞同楼主这一观点,于是我也写了一个玩了玩
果然 Ruby 写类似伪代码的东西就是舒爽
(暂时还没有定义访问方法和 each 系列的迭代方法,不过有了转成字符串的 to_s ,能输出就能凑合着玩了)
class Maze def initialize(xsize, ysize, ox = rand(xsize), oy = rand(ysize)) @xsize = xsize @ysize = ysize prim(ox, oy) end # 生成迷宫 def prim(ox, oy) init_maze init_list remove_wall(ox, oy) add_adjacent_wall_to_list(ox, oy) while (pos_data = list_sample) (x, y), (new_x, new_y) = pos_data if wall?(new_x, new_y) remove_wall(x, y) remove_wall(new_x, new_y) add_adjacent_wall_to_list(new_x, new_y) end remove_from_list(x, y) end end def wall?(x, y) exist?(x, y) && !@maze[x][y] end def to_s @xsize.times.map { |x| @ysize.times.map { |y| wall?(x, y) ? '●' : '○' }.join }.join("\n") end private def init_maze @maze = Array.new(@xsize) { Array.new(@ysize) } end def init_list @list = {} end def remove_wall(x, y) @maze[x][y] = true if exist?(x, y) end # 返回 [[墙X,墙Y], [前方X, 前方Y]] def list_sample @list.to_a.sample end def add_adjacent_wall_to_list(x, y) each_dx_dy do |dx, dy| new_x = x + dx new_y = y + dy add_to_list(new_x, new_y, new_x + dx, new_y + dy) if wall?(new_x, new_y) end end def each_dx_dy yield -1, 0 yield 1, 0 yield 0, -1 yield 0, 1 end def add_to_list(x, y, new_x, new_y) @list[[x, y]] = [new_x, new_y] if exist?(x, y) end def remove_from_list(x, y) @list.delete [x, y] end def exist?(x, y) x.between?(0, @xsize - 1) && y.between?(0, @ysize - 1) end end # puts Maze.new(15, 15)
class Maze
def initialize(xsize, ysize, ox = rand(xsize), oy = rand(ysize))
@xsize = xsize
@ysize = ysize
prim(ox, oy)
end
# 生成迷宫
def prim(ox, oy)
init_maze
init_list
remove_wall(ox, oy)
add_adjacent_wall_to_list(ox, oy)
while (pos_data = list_sample)
(x, y), (new_x, new_y) = pos_data
if wall?(new_x, new_y)
remove_wall(x, y)
remove_wall(new_x, new_y)
add_adjacent_wall_to_list(new_x, new_y)
end
remove_from_list(x, y)
end
end
def wall?(x, y)
exist?(x, y) && !@maze[x][y]
end
def to_s
@xsize.times.map { |x|
@ysize.times.map { |y| wall?(x, y) ? '●' : '○' }.join
}.join("\n")
end
private
def init_maze
@maze = Array.new(@xsize) { Array.new(@ysize) }
end
def init_list
@list = {}
end
def remove_wall(x, y)
@maze[x][y] = true if exist?(x, y)
end
# 返回 [[墙X,墙Y], [前方X, 前方Y]]
def list_sample
@list.to_a.sample
end
def add_adjacent_wall_to_list(x, y)
each_dx_dy do |dx, dy|
new_x = x + dx
new_y = y + dy
add_to_list(new_x, new_y, new_x + dx, new_y + dy) if wall?(new_x, new_y)
end
end
def each_dx_dy
yield -1, 0
yield 1, 0
yield 0, -1
yield 0, 1
end
def add_to_list(x, y, new_x, new_y)
@list[[x, y]] = [new_x, new_y] if exist?(x, y)
end
def remove_from_list(x, y)
@list.delete [x, y]
end
def exist?(x, y)
x.between?(0, @xsize - 1) && y.between?(0, @ysize - 1)
end
end
# puts Maze.new(15, 15)
|
|