Class: MagicCloud::Layouter::Place

Inherits:
Object
  • Object
show all
Defined in:
lib/magic_cloud/layouter/place.rb

Overview

Incapsulating place lookup process

  1. find initial random place

  2. at each step, shift in spiral from the previous place

  3. always knows, if the place “ready” for shape (empty and inside board)

Instance Method Summary collapse

Constructor Details

#initialize(layouter, shape) ⇒ Place

Returns a new instance of Place.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/magic_cloud/layouter/place.rb', line 12

def initialize(layouter, shape)
  @layouter, @shape = layouter, shape

  # initial position
  @start_x = (@layouter.width/2-@shape.width/2).to_i
  @start_y = (@layouter.height/2-@shape.height/2).to_i

  # when shift of position is more than max delta (diagonal of cloud)
  # there is no hope it will eventually found its place
  @max_delta = Math.sqrt(@layouter.width**2 + @layouter.height**2)

  # algo of next position calc
  @spiral = make_spiral(@shape.size)

  # direction of spiral
  @dt = rand < 0.5 ? 1 : -1 

  # initial point of time before we start to look for place
  @t = -@dt
end

Instance Method Details

#next!Object



33
34
35
36
37
38
39
40
41
# File 'lib/magic_cloud/layouter/place.rb', line 33

def next!
  @t += @dt
  dx, dy = @spiral.call(@t)

  fail PlaceNotFound if [dx, dy].map(&:abs).min > @max_delta

  @shape.x = @start_x + dx
  @shape.y = @start_y + dy
end

#ready?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/magic_cloud/layouter/place.rb', line 43

def ready?
  !out_of_board? && !@layouter.board.collides?(@shape)
end