Implemented layouting.
[kaya.git] / lib / point.rb
blobc83a8b310956d6098d03cc3317e92387c466ca18
1 require 'qtutils'
3 class Point
4   include PrintablePoint
5   attr_reader :x, :y
6   
7   def initialize(x, y)
8     @x = x
9     @y = y
10   end
11   
12   def == other
13     other and @x == other.x and @y == other.y
14   end
15   
16   def + other
17     self.class.new(@x + other.x, @y + other.y)
18   end
19   
20   def - other
21     self.class.new(@x - other.x, @y - other.y)
22   end
23   
24   def * factor
25     self.class.new(@x * factor, @y * factor)
26   end
27   
28   def / factor
29     self.class.new(@x / factor, @y / factor)
30   end
31   
32   def eql?(other)
33     other.instance_of?(Point) and self == other
34   end
35   
36   def hash
37     [@x, @y].hash
38   end
39   
40   def unit
41     Point.new(@x.unit, @y.unit)
42   end
43   
44   def =~(other)
45     other.nil? or
46     (((not other.x) or other.x == x) and
47       ((not other.y) or other.y == y))
48   end
49   
50   def to_coord(ysize)
51     "#{(x + ?a).chr if x}#{(ysize - y) if y}"
52   end
53   
54   def self.from_coord(s, ysize)
55     if s =~ /^([a-zA-Z]?)(\d*)/
56       letter = $1
57       number = $2
58       x = unless letter.empty? 
59         if letter =~ /[a-z]/
60           letter[0] - ?a
61         else 
62           letter[0] - ?A
63         end
64       end
65       y = ysize - number.to_i unless number.empty?
66       new x, y
67     end
68   end
69 end
71 class PointRange
72   include Enumerable
73   
74   attr_reader :src, :dst, :delta
75   
76   def initialize(src, dst)
77     @src = src
78     @dst = dst
79     @delta = @dst - @src
80     @increment = @delta.unit
81   end
82   
83   def each
84     current = @src
85     while current != @dst
86       yield current
87       current += @increment
88     end
89   end
90   
91   def parallel?
92     @delta.x == 0 or @delta.y == 0
93   end
94   
95   def diagonal?
96     @delta.x.abs == @delta.y.abs
97   end
98   
99   def valid?
100     parallel? or diagonal?
101   end
104 class Numeric
105   def unit
106     self <=> 0
107   end