Guest User

Untitled

a guest
Apr 21st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.72 KB | None | 0 0
  1. require 'enumerator'
  2.  
  3. class Area
  4. attr_reader :width, :height
  5.  
  6. def initialize(width, height)
  7. @width = width
  8. @height = height
  9. @slots = "0"*(@width*@height)
  10. end
  11.  
  12. def slot(x,y)
  13. (x-1)+(y-1)*@width # x+y*@width if you want 0,0 to be topleft instead of 1,1
  14. end
  15.  
  16. def coordinates(slot)
  17. y,x = *slot.divmod(@width)
  18. return x+1, y+1
  19. end
  20.  
  21. def occupy(x,y)
  22. @slots[slot(x,y)] = ?X
  23. end
  24.  
  25. def unoccupy(x,y)
  26. @slots[slot(x,y)] = ?0
  27. end
  28.  
  29. def occupied?(x,y) # prefixes like 'is_' suck ;-)
  30. @slots[slot(x,y)] == ?0
  31. end
  32.  
  33. def to_s
  34. #(0...@height).map { |i| @slots[i*@width, @width] }.join("\n")
  35. @slots.gsub(/.{#{@width}}/, "\\\&\n")
  36. end
  37. end
  38.  
  39. a = Area.new(10,10)
  40. a.occupy(9,2)
  41. puts a
Add Comment
Please, Sign In to add comment