Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'enumerator'
- class Area
- attr_reader :width, :height
- def initialize(width, height)
- @width = width
- @height = height
- @slots = "0"*(@width*@height)
- end
- def slot(x,y)
- (x-1)+(y-1)*@width # x+y*@width if you want 0,0 to be topleft instead of 1,1
- end
- def coordinates(slot)
- y,x = *slot.divmod(@width)
- return x+1, y+1
- end
- def occupy(x,y)
- @slots[slot(x,y)] = ?X
- end
- def unoccupy(x,y)
- @slots[slot(x,y)] = ?0
- end
- def occupied?(x,y) # prefixes like 'is_' suck ;-)
- @slots[slot(x,y)] == ?0
- end
- def to_s
- #(0...@height).map { |i| @slots[i*@width, @width] }.join("\n")
- @slots.gsub(/.{#{@width}}/, "\\\&\n")
- end
- end
- a = Area.new(10,10)
- a.occupy(9,2)
- puts a
Add Comment
Please, Sign In to add comment