Add licence and installation instructions.
[kaya.git] / lib / games / shogi / notation.rb
blobcfbaf9f4aba170ce2b127dcc26d40a6dd33125b7
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 'strscan'
10 module Shogi
12 class Notation
13   def initialize(piece_factory, size)
14     @piece_factory = piece_factory
15     @size = size
16   end
18   def from_scanner(scanner)
19     if scanner.scan(/(\+?[A-Z])?(\d[a-z])?([-*x])?(\d[a-z])([+=])?/)
20       { :type => (@piece_factory.type_from_symbol(scanner[1]) if scanner[1]),
21         :src => point_from_coord(scanner[2]),
22         :drop => scanner[3] == '*',
23         :dst => point_from_coord(scanner[4]),
24         :promote => scanner[5] == '+' }
25     end
26   end
27   
28   def from_s(str)
29     from_scanner(StringScanner.new(str))
30   end
31   
32   def read(input)
33     result = case input
34     when String
35       from_s(input)
36     else
37       from_scanner(input)
38     end
39     result
40   end
41   
42   def each_alternative(notation)
43     yield notation.dup.tap{|n| n[:src] = nil }
44   end
45   
46   def point_from_coord(coord)
47     if coord =~ /^(\d)([a-z])$/
48       Point.new(@size.x - $1.to_i, $2[0] - ?a)
49     end
50   end
51   
52   def point_to_coord(p)
53     "#{@size.x - p.x}#{(p.y + ?a).chr}"
54   end
55 end
57 end