Movelist is now reenabled and working.
[kaya.git] / lib / history.rb
blobb33e6f6711346366bbb409d98eedcd2f0a3c8cbf
1 require 'observer_utils.rb'
3 class History
4   include Enumerable
5   include Observable
6   
7   attr_reader :current
8   
9   Item = Struct.new(:state, :move, :text)
10   OutOfBound = Class.new(Exception)
12   def initialize(state)
13     @history = [Item.new(state.dup, nil, "Mainline")]
14     @current = 0
15   end
16   
17   def each
18     @history.each {|item| yield item.state, item.move }
19   end
20   
21   def add_move(state, move)
22     item = Item.new(state.dup, move, nil)
23     old_size = @history.size
24     
25     @history = @history[0..@current]
27     @history << item
28     @current = @history.size - 1
29     
30     fire :new_move
31   end
32   
33   def forward
34     raise OutOfBound if @current >= @history.size - 1
35     @current += 1
36     item = @history[@current]
37     
38     fire :current_changed
39     [item.state, item.move]
40   end
41   
42   def back
43     raise OutOfBound if @current <= 0
44     move = @history[@current].move
45     @current -= 1
46     
47     fire :current_changed
48     [@history[@current].state, move]
49   end
50   
51   def go_to(index)
52     item = self[index]
53     @current = index
54     fire :current_changed
55     [item.state, item.move]
56   end
57   
58   def state
59     @history[current].state
60   end
61   
62   def move
63     @history[current].move
64   end
65   
66   def size
67     @history.size
68   end
69   
70   def [](index)
71     if index >= @history.size || index < 0
72       raise OutOfBound 
73     end
74     @history[index]
75   end
76 end