Class: Gambit::Tools::MoveHistory

Inherits:
Object
  • Object
show all
Includes:
Viewable
Defined in:
lib/gambit/tools/movehistory.rb

Overview

An objectified move history object.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Viewable

append_features, #view

Constructor Details

#initialize(*players) ⇒ MoveHistory

Creates a new MoveHistory object, optionally initialized with some players.



66
67
68
69
70
71
72
73
# File 'lib/gambit/tools/movehistory.rb', line 66

def initialize( *players )
	@players     = Array.new
	@turn        = 1
	@next_player = 0
	@moves       = Hash.new { |moves, turn| moves[turn] = Hash.new }

	add_players(*players)
end

Instance Attribute Details

#turnObject

The current turn number or name.



76
77
78
# File 'lib/gambit/tools/movehistory.rb', line 76

def turn
  @turn
end

Instance Method Details

#<<(move) ⇒ Object

Add move to the current player for the current turn.

Returns self for method chaining.



95
96
97
98
99
100
101
# File 'lib/gambit/tools/movehistory.rb', line 95

def <<( move )
	@moves[@turn][@players[@next_player]] = move
	
	find_next_player
	
	self
end

#[](turn, player = nil) ⇒ Object

Returns the moves for the provided turn (optionally for the given player.)



82
83
84
85
86
87
88
# File 'lib/gambit/tools/movehistory.rb', line 82

def []( turn, player = nil )
	if player.nil?
		@moves[turn]
	else
		@moves[turn][player]
	end
end

#add_player(player) ⇒ Object

Add a player to this MoveHistory.

Returns self for method chaining.



108
109
110
111
112
# File 'lib/gambit/tools/movehistory.rb', line 108

def add_player( player )
	@players << player

	self
end

#add_players(*players) ⇒ Object

Add a group of players to this MoveHistory.

Returns self for method chaining.



119
120
121
122
123
# File 'lib/gambit/tools/movehistory.rb', line 119

def add_players( *players )
	players.each { |player| add_player(player) }

	self
end

#eachObject

Iterate over each move, by turn and then by player.



126
127
128
129
130
# File 'lib/gambit/tools/movehistory.rb', line 126

def each(  )
	@moves.each do |(turn, moves)|
		@players.each { |player| yield moves[player] }
	end
end

#record(player, event) ⇒ Object

Add’s an event to the given player for the current turn. If the player already has and event for that turn, an Array is used to hold all added events in order.

Returns self for method chaining.



139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/gambit/tools/movehistory.rb', line 139

def record( player, event )
	if @moves[@turn][player].nil?
		@moves[@turn][player] = event
	elsif @moves[@turn][player].is_a? Array
		@moves[@turn][player] << event
	else
		@moves[@turn][player] = [@moves[@turn][player]]
		@moves[@turn][player] << event
	end
	
	self
end