Class: PGN::Game
- Inherits:
-
Object
- Object
- PGN::Game
- Defined in:
- lib/pgn/game.rb
Overview
Constant Summary collapse
- LEFT =
/(a|\x1B\[D)\z/- RIGHT =
/(d|\x1B\[C)\z/- EXIT =
/(q|\x03)\z/
Instance Attribute Summary collapse
-
#comment ⇒ Object
Returns the value of attribute comment.
-
#moves ⇒ Array<String>
A list of the moves in standard algebraic notation.
-
#pgn ⇒ Object
Returns the value of attribute pgn.
-
#result ⇒ String
The outcome of the game.
-
#tags ⇒ Hash<String, String>
Metadata about the game.
Instance Method Summary collapse
-
#current_position ⇒ PGN::Position
The current Position (the last position after replaying all moves), or the starting position when there are no moves.
-
#each_position {|position| ... } ⇒ Enumerator, self
The replay loop is shared with #positions so eager and lazy paths produce identical position objects in identical order.
-
#fen_list ⇒ Array<String>
List of the fen representations of the positions.
- #initial_fen ⇒ Object
-
#initialize(moves, tags = nil, result = nil, pgn = nil, comment = nil) ⇒ Game
constructor
A new instance of Game.
-
#outcome ⇒ Symbol?
The terminal status of the game: :checkmate, :stalemate, or :draw (insufficient material, 50-move rule, or threefold repetition).
-
#play ⇒ Object
Interactively step through the game.
-
#pop ⇒ PGN::MoveText?
Remove and return the last move, or nil if there are none.
-
#positions ⇒ Array<PGN::Position>
List of the Positions in the game.
-
#push(san) ⇒ self
Append a move in SAN, validating legality when the native engine is available.
-
#root ⇒ Object
Build a fresh, navigable Node tree over the mainline.
- #starting_position ⇒ Object
-
#threefold? ⇒ Boolean
Whether any position has occurred three times in this game (the threefold-repetition draw).
-
#to_pgn ⇒ String
A canonical PGN string for this game, ending with a trailing newline.
Constructor Details
#initialize(moves, tags = nil, result = nil, pgn = nil, comment = nil) ⇒ Game
Returns a new instance of Game.
78 79 80 81 82 83 84 |
# File 'lib/pgn/game.rb', line 78 def initialize(moves, = nil, result = nil, pgn = nil, comment = nil) self.moves = moves self. = self.result = result self.pgn = pgn self.comment = comment end |
Instance Attribute Details
#comment ⇒ Object
Returns the value of attribute comment.
67 68 69 |
# File 'lib/pgn/game.rb', line 67 def comment @comment end |
#moves ⇒ Array<String>
Returns a list of the moves in standard algebraic notation.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/pgn/game.rb', line 66 class Game attr_accessor :tags, :result, :pgn, :comment attr_reader :moves LEFT = /(a|\x1B\[D)\z/ RIGHT = /(d|\x1B\[C)\z/ EXIT = /(q|\x03)\z/ # @param moves [Array<String>] a list of moves in SAN # @param tags [Hash<String, String>] metadata about the game # @param result [String] the outcome of the game # def initialize(moves, = nil, result = nil, pgn = nil, comment = nil) self.moves = moves self. = self.result = result self.pgn = pgn self.comment = comment end # @param moves [Array<String>] a list of moves in SAN # # Standardize castling moves to use O's instead of 0's # def moves=(moves) @moves = moves.map { |m| standardize_castling(m) } end # @return [String] a canonical PGN string for this game, ending with a # trailing newline. # def to_pgn PGN::Serializer.new(self).to_s end def initial_fen && ['FEN'] end def starting_position @starting_position ||= if initial_fen PGN::FEN.new(initial_fen).to_position else PGN::Position.start end end # @return [Array<PGN::Position>] list of the {PGN::Position}s in the game # def positions @positions ||= each_position.to_a end # @return [Enumerator, self] with a block: yields each {PGN::Position} # in order (starting position, then one per move) and returns self. # Without a block: returns an Enumerator that yields the same. # # The replay loop is shared with {#positions} so eager and lazy paths # produce identical position objects in identical order. def each_position return enum_for(:each_position) unless block_given? position = starting_position yield position moves.each do |move| position = position.move(move.notation) yield position end self end # @return [Array<String>] list of the fen representations of the positions # def fen_list positions.map { |p| p.to_fen.inspect } end # The current {PGN::Position} (the last position after replaying all # moves), or the starting position when there are no moves. # # @return [PGN::Position] def current_position positions.last end # Append a move in SAN, validating legality when the native engine is # available. Raises ArgumentError for an illegal move (when the engine is # loaded) and invalidates the memoized position list. # # @param san [String, PGN::MoveText] the move to append # @return [self] def push(san) move = standardize_castling(san) if PGN::Bitboard.const_defined?(:Engine, false) && !current_position.legal?(move.notation) raise ArgumentError, "illegal move: #{san}" end @moves << move @positions = nil self end # Remove and return the last move, or nil if there are none. Invalidates # the memoized position list. # # @return [PGN::MoveText, nil] def pop return nil if @moves.empty? move = @moves.pop @positions = nil move end # Whether any position has occurred three times in this game (the # threefold-repetition draw). Uses {PGN::Position#hash} (the Zobrist # hash of the FEN-relevant state), streaming {#each_position} so the # full position array need not be materialized for this check. # # @return [Boolean] def threefold? counts = Hash.new(0) each_position { |position| counts[position.hash] += 1 } counts.any? { |_, count| count >= 3 } end # The terminal status of the game: :checkmate, :stalemate, or :draw # (insufficient material, 50-move rule, or threefold repetition). nil # if the game is still in progress. Requires the native extension for # checkmate/stalemate detection. # # @return [Symbol, nil] def outcome final = positions.last result = final&.outcome return result if result return :draw if threefold? nil end # Interactively step through the game # # Use +d+ to move forward, +a+ to move backward, and +^C+ to exit. # def play index = 0 hist = Array.new(3, '') loop do puts "\e[H\e[2J" puts positions[index].inspect hist[0..2] = (hist[1..2] << $stdin.getch) case hist.join when LEFT index -= 1 if index.positive? when RIGHT index += 1 if index < moves.length when EXIT break end end end # Build a fresh, navigable {PGN::Node} tree over the mainline. The tree # is a live view of the underlying +MoveText+ structure; mutate it # through the node API, then call +#root+ again for a fresh tree. def root PGN::Node.new( move: nil, parent: nil, line: @moves, index: -1, starting_position: starting_position, game: self ) end private # A MoveText is reused as-is (no new object) when its notation needs no # '0'->'O' fix; otherwise a new MoveText is built. clean_text is idempotent # (it only strips a *single* outermost brace pair), so reusing or rebuilding # a MoveText never corrupts a comment that still contains inner braces. def standardize_castling(entry) return MoveText.new(entry.include?('0') ? entry.gsub('0', 'O') : entry) if entry.is_a?(String) notation = entry.notation.include?('0') ? entry.notation.gsub('0', 'O') : entry.notation return entry if notation.equal?(entry.notation) MoveText.new(notation, entry.annotation, entry.comment, entry.variations) end end |
#pgn ⇒ Object
Returns the value of attribute pgn.
67 68 69 |
# File 'lib/pgn/game.rb', line 67 def pgn @pgn end |
#result ⇒ String
Returns the outcome of the game.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/pgn/game.rb', line 66 class Game attr_accessor :tags, :result, :pgn, :comment attr_reader :moves LEFT = /(a|\x1B\[D)\z/ RIGHT = /(d|\x1B\[C)\z/ EXIT = /(q|\x03)\z/ # @param moves [Array<String>] a list of moves in SAN # @param tags [Hash<String, String>] metadata about the game # @param result [String] the outcome of the game # def initialize(moves, = nil, result = nil, pgn = nil, comment = nil) self.moves = moves self. = self.result = result self.pgn = pgn self.comment = comment end # @param moves [Array<String>] a list of moves in SAN # # Standardize castling moves to use O's instead of 0's # def moves=(moves) @moves = moves.map { |m| standardize_castling(m) } end # @return [String] a canonical PGN string for this game, ending with a # trailing newline. # def to_pgn PGN::Serializer.new(self).to_s end def initial_fen && ['FEN'] end def starting_position @starting_position ||= if initial_fen PGN::FEN.new(initial_fen).to_position else PGN::Position.start end end # @return [Array<PGN::Position>] list of the {PGN::Position}s in the game # def positions @positions ||= each_position.to_a end # @return [Enumerator, self] with a block: yields each {PGN::Position} # in order (starting position, then one per move) and returns self. # Without a block: returns an Enumerator that yields the same. # # The replay loop is shared with {#positions} so eager and lazy paths # produce identical position objects in identical order. def each_position return enum_for(:each_position) unless block_given? position = starting_position yield position moves.each do |move| position = position.move(move.notation) yield position end self end # @return [Array<String>] list of the fen representations of the positions # def fen_list positions.map { |p| p.to_fen.inspect } end # The current {PGN::Position} (the last position after replaying all # moves), or the starting position when there are no moves. # # @return [PGN::Position] def current_position positions.last end # Append a move in SAN, validating legality when the native engine is # available. Raises ArgumentError for an illegal move (when the engine is # loaded) and invalidates the memoized position list. # # @param san [String, PGN::MoveText] the move to append # @return [self] def push(san) move = standardize_castling(san) if PGN::Bitboard.const_defined?(:Engine, false) && !current_position.legal?(move.notation) raise ArgumentError, "illegal move: #{san}" end @moves << move @positions = nil self end # Remove and return the last move, or nil if there are none. Invalidates # the memoized position list. # # @return [PGN::MoveText, nil] def pop return nil if @moves.empty? move = @moves.pop @positions = nil move end # Whether any position has occurred three times in this game (the # threefold-repetition draw). Uses {PGN::Position#hash} (the Zobrist # hash of the FEN-relevant state), streaming {#each_position} so the # full position array need not be materialized for this check. # # @return [Boolean] def threefold? counts = Hash.new(0) each_position { |position| counts[position.hash] += 1 } counts.any? { |_, count| count >= 3 } end # The terminal status of the game: :checkmate, :stalemate, or :draw # (insufficient material, 50-move rule, or threefold repetition). nil # if the game is still in progress. Requires the native extension for # checkmate/stalemate detection. # # @return [Symbol, nil] def outcome final = positions.last result = final&.outcome return result if result return :draw if threefold? nil end # Interactively step through the game # # Use +d+ to move forward, +a+ to move backward, and +^C+ to exit. # def play index = 0 hist = Array.new(3, '') loop do puts "\e[H\e[2J" puts positions[index].inspect hist[0..2] = (hist[1..2] << $stdin.getch) case hist.join when LEFT index -= 1 if index.positive? when RIGHT index += 1 if index < moves.length when EXIT break end end end # Build a fresh, navigable {PGN::Node} tree over the mainline. The tree # is a live view of the underlying +MoveText+ structure; mutate it # through the node API, then call +#root+ again for a fresh tree. def root PGN::Node.new( move: nil, parent: nil, line: @moves, index: -1, starting_position: starting_position, game: self ) end private # A MoveText is reused as-is (no new object) when its notation needs no # '0'->'O' fix; otherwise a new MoveText is built. clean_text is idempotent # (it only strips a *single* outermost brace pair), so reusing or rebuilding # a MoveText never corrupts a comment that still contains inner braces. def standardize_castling(entry) return MoveText.new(entry.include?('0') ? entry.gsub('0', 'O') : entry) if entry.is_a?(String) notation = entry.notation.include?('0') ? entry.notation.gsub('0', 'O') : entry.notation return entry if notation.equal?(entry.notation) MoveText.new(notation, entry.annotation, entry.comment, entry.variations) end end |
#tags ⇒ Hash<String, String>
Returns metadata about the game.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/pgn/game.rb', line 66 class Game attr_accessor :tags, :result, :pgn, :comment attr_reader :moves LEFT = /(a|\x1B\[D)\z/ RIGHT = /(d|\x1B\[C)\z/ EXIT = /(q|\x03)\z/ # @param moves [Array<String>] a list of moves in SAN # @param tags [Hash<String, String>] metadata about the game # @param result [String] the outcome of the game # def initialize(moves, = nil, result = nil, pgn = nil, comment = nil) self.moves = moves self. = self.result = result self.pgn = pgn self.comment = comment end # @param moves [Array<String>] a list of moves in SAN # # Standardize castling moves to use O's instead of 0's # def moves=(moves) @moves = moves.map { |m| standardize_castling(m) } end # @return [String] a canonical PGN string for this game, ending with a # trailing newline. # def to_pgn PGN::Serializer.new(self).to_s end def initial_fen && ['FEN'] end def starting_position @starting_position ||= if initial_fen PGN::FEN.new(initial_fen).to_position else PGN::Position.start end end # @return [Array<PGN::Position>] list of the {PGN::Position}s in the game # def positions @positions ||= each_position.to_a end # @return [Enumerator, self] with a block: yields each {PGN::Position} # in order (starting position, then one per move) and returns self. # Without a block: returns an Enumerator that yields the same. # # The replay loop is shared with {#positions} so eager and lazy paths # produce identical position objects in identical order. def each_position return enum_for(:each_position) unless block_given? position = starting_position yield position moves.each do |move| position = position.move(move.notation) yield position end self end # @return [Array<String>] list of the fen representations of the positions # def fen_list positions.map { |p| p.to_fen.inspect } end # The current {PGN::Position} (the last position after replaying all # moves), or the starting position when there are no moves. # # @return [PGN::Position] def current_position positions.last end # Append a move in SAN, validating legality when the native engine is # available. Raises ArgumentError for an illegal move (when the engine is # loaded) and invalidates the memoized position list. # # @param san [String, PGN::MoveText] the move to append # @return [self] def push(san) move = standardize_castling(san) if PGN::Bitboard.const_defined?(:Engine, false) && !current_position.legal?(move.notation) raise ArgumentError, "illegal move: #{san}" end @moves << move @positions = nil self end # Remove and return the last move, or nil if there are none. Invalidates # the memoized position list. # # @return [PGN::MoveText, nil] def pop return nil if @moves.empty? move = @moves.pop @positions = nil move end # Whether any position has occurred three times in this game (the # threefold-repetition draw). Uses {PGN::Position#hash} (the Zobrist # hash of the FEN-relevant state), streaming {#each_position} so the # full position array need not be materialized for this check. # # @return [Boolean] def threefold? counts = Hash.new(0) each_position { |position| counts[position.hash] += 1 } counts.any? { |_, count| count >= 3 } end # The terminal status of the game: :checkmate, :stalemate, or :draw # (insufficient material, 50-move rule, or threefold repetition). nil # if the game is still in progress. Requires the native extension for # checkmate/stalemate detection. # # @return [Symbol, nil] def outcome final = positions.last result = final&.outcome return result if result return :draw if threefold? nil end # Interactively step through the game # # Use +d+ to move forward, +a+ to move backward, and +^C+ to exit. # def play index = 0 hist = Array.new(3, '') loop do puts "\e[H\e[2J" puts positions[index].inspect hist[0..2] = (hist[1..2] << $stdin.getch) case hist.join when LEFT index -= 1 if index.positive? when RIGHT index += 1 if index < moves.length when EXIT break end end end # Build a fresh, navigable {PGN::Node} tree over the mainline. The tree # is a live view of the underlying +MoveText+ structure; mutate it # through the node API, then call +#root+ again for a fresh tree. def root PGN::Node.new( move: nil, parent: nil, line: @moves, index: -1, starting_position: starting_position, game: self ) end private # A MoveText is reused as-is (no new object) when its notation needs no # '0'->'O' fix; otherwise a new MoveText is built. clean_text is idempotent # (it only strips a *single* outermost brace pair), so reusing or rebuilding # a MoveText never corrupts a comment that still contains inner braces. def standardize_castling(entry) return MoveText.new(entry.include?('0') ? entry.gsub('0', 'O') : entry) if entry.is_a?(String) notation = entry.notation.include?('0') ? entry.notation.gsub('0', 'O') : entry.notation return entry if notation.equal?(entry.notation) MoveText.new(notation, entry.annotation, entry.comment, entry.variations) end end |
Instance Method Details
#current_position ⇒ PGN::Position
The current Position (the last position after replaying all moves), or the starting position when there are no moves.
147 148 149 |
# File 'lib/pgn/game.rb', line 147 def current_position positions.last end |
#each_position {|position| ... } ⇒ Enumerator, self
The replay loop is shared with #positions so eager and lazy paths produce identical position objects in identical order.
125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/pgn/game.rb', line 125 def each_position return enum_for(:each_position) unless block_given? position = starting_position yield position moves.each do |move| position = position.move(move.notation) yield position end self end |
#fen_list ⇒ Array<String>
Returns list of the fen representations of the positions.
139 140 141 |
# File 'lib/pgn/game.rb', line 139 def fen_list positions.map { |p| p.to_fen.inspect } end |
#initial_fen ⇒ Object
101 102 103 |
# File 'lib/pgn/game.rb', line 101 def initial_fen && ['FEN'] end |
#outcome ⇒ Symbol?
The terminal status of the game: :checkmate, :stalemate, or :draw (insufficient material, 50-move rule, or threefold repetition). nil if the game is still in progress. Requires the native extension for checkmate/stalemate detection.
198 199 200 201 202 203 204 205 |
# File 'lib/pgn/game.rb', line 198 def outcome final = positions.last result = final&.outcome return result if result return :draw if threefold? nil end |
#play ⇒ Object
Interactively step through the game
Use d to move forward, a to move backward, and ^C to exit.
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
# File 'lib/pgn/game.rb', line 211 def play index = 0 hist = Array.new(3, '') loop do puts "\e[H\e[2J" puts positions[index].inspect hist[0..2] = (hist[1..2] << $stdin.getch) case hist.join when LEFT index -= 1 if index.positive? when RIGHT index += 1 if index < moves.length when EXIT break end end end |
#pop ⇒ PGN::MoveText?
Remove and return the last move, or nil if there are none. Invalidates the memoized position list.
172 173 174 175 176 177 178 |
# File 'lib/pgn/game.rb', line 172 def pop return nil if @moves.empty? move = @moves.pop @positions = nil move end |
#positions ⇒ Array<PGN::Position>
Returns list of the Positions in the game.
115 116 117 |
# File 'lib/pgn/game.rb', line 115 def positions @positions ||= each_position.to_a end |
#push(san) ⇒ self
Append a move in SAN, validating legality when the native engine is available. Raises ArgumentError for an illegal move (when the engine is loaded) and invalidates the memoized position list.
157 158 159 160 161 162 163 164 165 166 |
# File 'lib/pgn/game.rb', line 157 def push(san) move = standardize_castling(san) if PGN::Bitboard.const_defined?(:Engine, false) && !current_position.legal?(move.notation) raise ArgumentError, "illegal move: #{san}" end @moves << move @positions = nil self end |
#root ⇒ Object
Build a fresh, navigable Node tree over the mainline. The tree
is a live view of the underlying MoveText structure; mutate it
through the node API, then call #root again for a fresh tree.
234 235 236 237 238 239 |
# File 'lib/pgn/game.rb', line 234 def root PGN::Node.new( move: nil, parent: nil, line: @moves, index: -1, starting_position: starting_position, game: self ) end |
#starting_position ⇒ Object
105 106 107 108 109 110 111 |
# File 'lib/pgn/game.rb', line 105 def starting_position @starting_position ||= if initial_fen PGN::FEN.new(initial_fen).to_position else PGN::Position.start end end |
#threefold? ⇒ Boolean
Whether any position has occurred three times in this game (the threefold-repetition draw). Uses Position#hash (the Zobrist hash of the FEN-relevant state), streaming #each_position so the full position array need not be materialized for this check.
186 187 188 189 190 |
# File 'lib/pgn/game.rb', line 186 def threefold? counts = Hash.new(0) each_position { |position| counts[position.hash] += 1 } counts.any? { |_, count| count >= 3 } end |
#to_pgn ⇒ String
Returns a canonical PGN string for this game, ending with a trailing newline.
97 98 99 |
# File 'lib/pgn/game.rb', line 97 def to_pgn PGN::Serializer.new(self).to_s end |