开发者

Maze Generation with Ruby

开发者 https://www.devze.com 2023-04-12 20:21 出处:网络
I have been working on polishing my Ruby skills lately and came across a nice snazzy presentation on maze generation.

I have been working on polishing my Ruby skills lately and came across a nice snazzy presentation on maze generation.

Presentation by Jamis Buck

I would want to implement a couple of algorithms and then generate image f开发者_运维百科iles for the mazes.

I am quite unsure on the second part of the job: "generating image of the maze". I want a simple gem that lets me map my mazes to image.

Maybe sometime soon I would also want the whole thing as a Ruby on Rails application for the web.

How can I put all of it together?


chunky_png gem is definitely a thing that worth trying out.


It's very easy using RMagick:

require 'rubygems'
require 'RMagick'

maze = <<-MAZE
##############
.............#
############.#
#............#
#.#.########.#
#.#..........#
#.############
MAZE

maze = maze.split("\n").map{|line| line.split('')}

square_size = 50

height = maze.size
width = maze.first.size

img_height = height * square_size
img_width = width * square_size

img = Magick::Image.new(img_width, img_height)

img_width.times do |col|
  img_height.times do |row|
    line_idx = (row/square_size).floor
    char_idx = (col/square_size).floor

    char = maze[line_idx][char_idx]

    color = (char == "#" ? "rgb(0, 0, 0)" : "rgb(255, 255, 255)")

    img.pixel_color(col, row, color)
  end
end

img.write('maze.png')


Time moves on. Jamis Buck has now completed a book called 'mazes for programmers' on the pragmatic bookshelf. I think this is your go to reference for Ruby and Mazes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号