Implement ActionList::Entry#clear.
[kaya.git] / lib / point.rb
blobeb97f54d43078a909f751eb6f7ccf59511ea7110
1 # Copyright (c) 2009 Paolo Capriotti <p.capriotti@gmail.com>
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
8 require 'toolkit'
10 class Point
11   include PrintablePoint
12   attr_reader :x, :y
13   
14   def initialize(x, y)
15     @x = x
16     @y = y
17   end
18   
19   def == other
20     other and @x == other.x and @y == other.y
21   end
22   
23   def + other
24     self.class.new(@x + other.x, @y + other.y)
25   end
26   
27   def - other
28     self.class.new(@x - other.x, @y - other.y)
29   end
30   
31   def * factor
32     self.class.new(@x * factor, @y * factor)
33   end
34   
35   def / factor
36     self.class.new(@x / factor, @y / factor)
37   end
38   
39   def eql?(other)
40     other.instance_of?(Point) and self == other
41   end
42   
43   def hash
44     [@x, @y].hash
45   end
46   
47   def unit
48     Point.new(@x.unit, @y.unit)
49   end
50   
51   def =~(other)
52     other.nil? or
53     (((not other.x) or other.x == x) and
54       ((not other.y) or other.y == y))
55   end
56   
57   def to_coord(ysize)
58     "#{(self.x + ?a).chr if x}#{(ysize - self.y) if self.y}"
59   end
60   
61   def self.from_coord(s, ysize, opts = { })
62     if s =~ /^([a-zA-Z]?)(\d*)/
63       letter = $1
64       number = $2
65       x = unless letter.empty? 
66         if letter =~ /[a-z]/
67           letter[0] - ?a
68         else 
69           letter[0] - ?A
70         end
71       end
72       y = ysize - number.to_i unless number.empty?
73       if (x and y) or (not opts[:strict])
74         new x, y
75       end
76     end
77   end
78 end
80 class PointRange
81   include Enumerable
82   
83   attr_reader :src, :dst, :delta
84   
85   def initialize(src, dst)
86     @src = src
87     @dst = dst
88     @delta = @dst - @src
89     @increment = @delta.unit
90   end
91   
92   def each
93     current = @src
94     while current != @dst
95       yield current
96       current += @increment
97     end
98   end
99   
100   def parallel?
101     @delta.x == 0 or @delta.y == 0
102   end
103   
104   def diagonal?
105     @delta.x.abs == @delta.y.abs
106   end
107   
108   def valid?
109     parallel? or diagonal?
110   end
113 class Numeric
114   def unit
115     self <=> 0
116   end