Anonymous user
Langton's ant: Difference between revisions
→{{header|Ruby}}
Line 3,252:
=={{header|Ruby}}==
<lang ruby>class Ant
class OutOfBoundsException < StandardError; end
class Plane
def initialize(x, y)
@size_x, @size_y = x, y
@cells = Array.new(y) {Array.new(x, :white)}
end
def white?(px, py)
@cells[py][px] == :white
end
def toggle_colour(px, py)
@cells[py][px] = (white?(px, py) ? :black : :white)
end
def check_bounds(px, py)
unless (0 <= px and px < @size_x) and (0 <= py and py < @size_y)
raise OutOfBoundsException, "(#@size_x, #@size_y)"
end
end
def to_s
@cells.collect {|row|
row.collect {|cell| cell == :white ? "." : "#"}.join + "\n"
}.join
end
end
dir_move = [[:north, [0,-1]], [:east, [1,0]], [:south, [0,1]], [:west, [-1,0]]]
Move = Hash[dir_move]
directions = dir_move.map{|dir, move| dir} # [:north, :east, :south, :west]
Right = Hash[ directions.zip(directions.rotate).to_a ]
Left = Right.invert
def initialize(size_x, size_y, pos_x=size_x/2, pos_y=size_y/2)
@plane = Plane.new(size_x, size_y)
@pos_x, @pos_y = pos_x, pos_y
@direction = :south
@plane.check_bounds(@pos_x, @pos_y)
end
def run
moves = 0
loop do
begin
moves += 1
move
Line 3,278 ⟶ 3,307:
moves
end
def move
@plane.
if @plane.
@direction = Right[@direction]
else
@direction = Left[@direction]
end
end
def
@pos_y += dy
@plane.check_bounds(@pos_x, @pos_y)
end
def position
"(#@pos_x, #@pos_y)"
end
def to_s
@
end
end
#
# the simulation
#
ant = Ant
moves = ant.run
puts "out of bounds after #{moves} moves: #{ant.position}"
puts ant
{{out}}
<pre style="height: 40ex; overflow: scroll">out of bounds after 11669 moves: (26, -1)
..........................#.#.......................................................................
|