Use integer coordinates everywhere.
[kaya.git] / lib / board / pool.rb
blob41f8de4c0c97ac8f9945a0888653b36bafbc7176
1 require 'item'
3 class Pool < Qt::GraphicsItemGroup
4   BACKGROUND_ZVALUE = -10
5   
6   include Observable
7   include ItemUtils
8   
9   attr_reader :rect
10   attr_reader :scene
11   
12   def initialize(scene, theme, game, field)
13     super(nil, scene)
14     @scene = scene
15     @scene.add_element(self)
16     
17     @theme = theme
18     @game = game
19     @field = field
20     
21     @items = []
22     @size = Point.new(3, 5)
23   end
24   
25   def redraw
26     pieces = @items.map do |item|
27       destroy_item(item)
28       item.name
29     end
30     
31     pieces.each_with_index do |piece, index|
32       add_piece(index, piece)
33     end
34   end
35   
36   def set_geometry(rect)
37     @rect = rect
38     
39     self.pos = @rect.top_left.to_f
40     
41     @unit = (@rect.width / @size.x).floor
42     redraw
43   end
44   
45   def add_piece(index, piece)
46     item = create_piece piece, 
47       @theme.pieces.pixmap(piece, Qt::Point.new(@unit, @unit)),
48       :pos => to_real(index)
49     @items.insert(index, item)
50     
51     # TODO shift the other items
52     
53     item
54   end
55   
56   def on_click(pos)
57     index = to_logical(pos)
58     puts "index = #{index}"
59   end
60   
61   def to_logical(p)
62     result = Point.new((p.x.to_f / @unit).floor,
63                        (p.y.to_f / @unit).floor)
64     y = result.y
65     x = y % 2 == 0 ? result.x : @size.x - result.x - 1
66     x + y * @size.x
67   end
68   
69   def to_real(index)
70     x = index % @size.x
71     y = index / @size.x
72     x = @size.x - x - 1 if y % 2 == 1
73     
74     Qt::PointF.new(x * @unit, y * @unit)
75   end
76 end