迷路作ってみた
アルゴリズムは自動生成迷路にのってる棒倒し法。
ソースはあんまりキレイじゃないかも。。
ネストが多いと見づらいね( ´・ω・`) リファクタすべき?
明日ちょっとやってみようかな。
CGIバージョンはここ。
#!/usr/local/bin/ruby #print "Content-Type: text/html\n\n" # 棒倒し法によって迷路を作成する # 迷路は英語で Maze class Maze def initialize(height = 21, width = 21) @height = height @width = width @wall = '■' @enp = '□' # 0..n は n を含む # 0...n は n を含まない @map = (0...@height).map{ Array.new(@width, @enp) } @direction = %w(up down right left) make_outside make_inside make_rand end def make_outside @height.times do |h| @width.times do |w| if h == 0 or h == @height-1 or w == 0 or w == @width-1 @map[h][w] = @wall end end end end def make_inside @height.times do |h| next if h % 2 == 1 or h == 0 or h == @height -1 @width.times do |w| next if w == 0 or w == @width - 1 @map[h][w] = @wall if w % 2 == 0 end end end def make_rand @height.times do |h| next if h % 2 == 1 or h == 0 or h == @height -1 @width.times do |w| next if w == 0 or w == @width - 1 # 1行目かどうかの判定 if w % 2 == 0 d = @direction[rand(4)] case d when 'up' # 上方向へ棒をつくれるのは1行目のときだけ if @map[h-1][w] == @enp and h == 2 @map[h-1][w] = @wall else redo end when 'down' if @map[h+1][w] == @enp @map[h+1][w] = @wall else redo end when 'right' if @map[h][w-1] == @enp @map[h][w-1] = @wall else redo end when 'left' if @map[h][w+1] == @enp @map[h][w+1] = @wall else redo end end end end end end def disp @map.each do |m| m.each do |n| print n end puts end end end height = ARGV[0] || 21 # ARGV[0].to_i だとダメ width = ARGV[1] || 21 height = heigth.to_i width = width.to_i maze = Maze.new(height, width) maze.disp
□(しかく)と口(くち)だと、くちの方が大きい?