Mercurial > maze-src
comparison cell.rb @ 0:1eef88068f9f tip
initial commit of maze game source
| author | ferencd |
|---|---|
| date | Sun, 15 Sep 2019 11:46:47 +0200 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| -1:000000000000 | 0:1eef88068f9f |
|---|---|
| 1 #--- | |
| 2 # Excerpted from "Mazes for Programmers", | |
| 3 # published by The Pragmatic Bookshelf. | |
| 4 # Copyrights apply to this code. It may not be used to create training material, | |
| 5 # courses, books, articles, and the like. Contact us if you are in doubt. | |
| 6 # We make no guarantees that this code is fit for any purpose. | |
| 7 # Visit http://www.pragmaticprogrammer.com/titles/jbmaze for more book information. | |
| 8 #--- | |
| 9 | |
| 10 # Direction constants | |
| 11 NORTH, SOUTH, EAST, WEST, NOWHERE = 1, 2, 4, 8, 0 | |
| 12 | |
| 13 DIRECTIONS = { :EAST => 'E', :WEST => 'W', :NORTH => 'N', :SOUTH => 'S', :NOWHERE => '?'} | |
| 14 | |
| 15 require 'distances' | |
| 16 | |
| 17 class Cell | |
| 18 attr_reader :row, :column | |
| 19 attr_accessor :north, :south, :east, :west | |
| 20 | |
| 21 def initialize(row, column) | |
| 22 @row, @column = row, column | |
| 23 @links = {} | |
| 24 end | |
| 25 | |
| 26 def link(cell, bidi=true) | |
| 27 @links[cell] = true | |
| 28 cell.link(self, false) if bidi | |
| 29 self | |
| 30 end | |
| 31 | |
| 32 def unlink(cell, bidi=true) | |
| 33 @links.delete(cell) | |
| 34 cell.unlink(self, false) if bidi | |
| 35 self | |
| 36 end | |
| 37 | |
| 38 def links | |
| 39 @links.keys | |
| 40 end | |
| 41 | |
| 42 def linked?(cell) | |
| 43 @links.key?(cell) | |
| 44 end | |
| 45 | |
| 46 def neighbors | |
| 47 list = [] | |
| 48 list << north if north | |
| 49 list << south if south | |
| 50 list << east if east | |
| 51 list << west if west | |
| 52 list | |
| 53 end | |
| 54 | |
| 55 def distances | |
| 56 distances = Distances.new(self) | |
| 57 frontier = [ self ] | |
| 58 | |
| 59 while frontier.any? | |
| 60 new_frontier = [] | |
| 61 | |
| 62 frontier.each do |cell| | |
| 63 cell.links.each do |linked| | |
| 64 next if distances[linked] | |
| 65 distances[linked] = distances[cell] + 1 | |
| 66 new_frontier << linked | |
| 67 end | |
| 68 end | |
| 69 | |
| 70 frontier = new_frontier | |
| 71 end | |
| 72 | |
| 73 distances | |
| 74 end | |
| 75 | |
| 76 | |
| 77 def direction(cell) | |
| 78 return NORTH if cell == north | |
| 79 return SOUTH if cell == south | |
| 80 return EAST if cell == east | |
| 81 return WEST if cell == west | |
| 82 0 | |
| 83 end | |
| 84 | |
| 85 end |
