3 # Library to support Cartagena play
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 # Version 1.0:: 11 Jun 2008
26 $SYMBOLS = [:bottle, :dagger, :gun, :hat, :keys, :skull]
28 # The number of cards of each symbol in the deck
29 $CARDS_PER_SYMBOL = 17
31 # The number of cards initiall dealt to each player
32 $INITIAL_CARDS_PER_PLAYER = 3
34 # Maximum number of pieces on a position
35 $MAX_PIECES_PER_POSITION = 3
37 # Number of actions that can be taken by each player in sequence
38 $MAX_MOVES_PER_TURN = 3
42 # Moves can only be [1..6] spaces
43 class InvalidMoveError < StandardError
46 # Game is won when only one player has uncaptured pieces
47 class GameWonNotice < StandardError
50 # A position on the board.
53 attr_accessor :contains
55 def initialize(symbol)
61 # A tile that makes up the board. Each tile has two sides, each with six
62 # positions. Tiles can be either way up, and either way round.
64 attr_reader :exposed, :front, :back
66 def initialize(front, back)
67 @front = front.collect {|s| Position.new(s)}
68 @back = back.collect {|s| Position.new(s)}
70 @exposed_side = :front
74 if @exposed_side == :front
79 @exposed_side = :front
84 @exposed = @exposed.reverse
92 attr_accessor :positions
95 # A laborious procedure to create all the positions and tie them all together
96 def initialize(tiles_used)
97 # A hash of all positions, indexed by position names
98 @tiles = [Tile.new([:hat, :keys, :gun, :bottle, :skull, :dagger],
99 [:hat, :keys, :gun, :bottle, :skull, :dagger]),
100 Tile.new([:gun, :hat, :dagger, :skull, :bottle, :keys],
101 [:gun, :hat, :dagger, :skull, :bottle, :keys]),
102 Tile.new([:skull, :gun, :bottle, :keys, :dagger, :hat],
103 [:skull, :gun, :bottle, :keys, :dagger, :hat]),
104 Tile.new([:dagger, :bottle, :keys, :gun, :hat, :skull],
105 [:dagger, :bottle, :keys, :gun, :hat, :skull]),
106 Tile.new([:keys, :dagger, :skull, :hat, :gun, :bottle],
107 [:keys, :dagger, :skull, :hat, :gun, :bottle]),
108 Tile.new([:bottle, :skull, :hat, :dagger, :keys, :gun],
109 [:bottle, :skull, :hat, :dagger, :keys, :gun])
110 ].shuffle[0...tiles_used]
111 @tiles = @tiles.each do |t|
119 @positions = [Position.new(:cell)]
120 @tiles.each {|t| t.exposed.each {|p| @positions << p}}
121 @positions << Position.new(:boat)
133 # For each position, show its name and what it touches
136 @positions.each {|position| out_string << "#{position.symbol}\n"}
143 # Each piece on the board is an object
145 attr_reader :player, :number
146 attr_accessor :position
148 def initialize(position, player, number)
155 "#{@player}:#{@number}"
162 def show(convert_to_zero_based_player_number = false)
163 if convert_to_zero_based_player_number
164 "#{@player + 1}:#{@number}"
166 "#{@player}:#{@number}"
170 def move_to(new_position)
171 @position = new_position
179 attr_reader :piece, :origin, :destination, :card_played
181 def initialize(piece, origin, destination, card_played = :unspecified)
184 @destination = destination
185 @card_played = card_played
188 def show(board, convert_to_zero_based_player_number = false)
189 if @card_played == :unspecified
190 "#{@piece.show(convert_to_zero_based_player_number)}: #{board.positions.index(@origin)} -> #{board.positions.index(@destination)}"
192 "#{@piece.show(convert_to_zero_based_player_number)}: #{board.positions.index(@origin)} -> #{board.positions.index(@destination)} (#{@card_played})"
196 def format(board, convert_to_zero_based_player_number = false)
197 display_player_number = if convert_to_zero_based_player_number then
202 if @card_played ==:unspecified
203 "#{display_player_number} #{board.positions.index(@origin)} #{board.positions.index(@destination)}"
205 "#{display_player_number} #{board.positions.index(@origin)} #{board.positions.index(@destination)} #{@card_played}"
209 # Write a move to a string
210 # Note the inverse, String#to_move, is defined below
212 "#{@piece.player} #{@origin.to_s} #{@destination.to_s} #{@card_played}"
223 # A class to record each of the states previously found in a game.
224 # Note that this is a deep copy of the pieces and what they've captured, so
225 # you'll need to convert back
227 attr_accessor :move, :player, :board, :pieces_before_move, :deck_before_move,
228 :players_cards_before_move, :moves_by_current_player
229 # this_game_state = GameState.new(move, player, @board, @pieces, @deck, @players_cards)
232 def initialize(move, player, board, pieces, deck, players_cards, moves_by_current_player)
233 @move, @player, @board, @pieces_before_move, @deck_before_move,
234 @players_cards_before_move, @moves_by_current_player =
235 copy_game_state(move, player, board, pieces, deck, players_cards,
236 moves_by_current_player)
240 # @move.to_s == other.move.to_s and
241 # @player == other.player and
242 # @piece_after_move == other.pieces_after_move
245 def copy_game_state(move, player, board, pieces, deck, players_cards, moves_by_current_player)
247 moving_player = move.piece.player
249 copy_board = board.dup
250 copy_board.positions = board.positions.collect {|pos| pos.dup}
251 copy_board.positions.each {|pos| pos.contains = []}
253 copy_pieces = pieces.collect do |players_pieces|
254 players_pieces.collect do |piece|
255 new_piece_position = copy_board.positions[board.positions.index(piece.position)]
256 new_piece = Piece.new(new_piece_position, piece.player, piece.number)
257 new_piece_position.contains << new_piece
262 piece_index = pieces[moving_player].index(move.piece)
263 origin_index = board.positions.index(move.origin)
264 destination_index = board.positions.index(move.destination)
265 copy_move = Move.new(copy_pieces[moving_player][piece_index],
266 copy_board.positions[origin_index],
267 copy_board.positions[destination_index])
270 copy_players_cards = players_cards.collect {|p| p.dup}
271 copy_moves_by_current_player = moves_by_current_player
273 return copy_move, copy_player, copy_board, copy_pieces, copy_deck, copy_players_cards, copy_moves_by_current_player
279 # A game of Cartagena. It keeps a history of all previous states.
283 attr_accessor :current_player
285 attr_accessor :players_cards
286 attr_accessor :moves_by_current_player
293 def initialize(players = 5, number_of_tiles = 6, pieces_each = 6)
294 @board = Board.new(number_of_tiles)
297 @players = [].fill(0, players) {|i| i}
300 @moves_by_current_player = 0
302 1.upto($CARDS_PER_SYMBOL) {|x| @cards.concat($SYMBOLS)}
303 @deck = @cards.shuffle
306 0.upto(pieces_each - 1) do |count|
307 piece = Piece.new(@board.positions[0], p, count)
308 @pieces[p][count] = piece
309 @board.positions[0].contains << piece
311 @players_cards[p] = []
312 deal_cards!($INITIAL_CARDS_PER_PLAYER, p)
316 def deal_cards!(number_of_cards, player = @current_player)
317 1.upto(number_of_cards) do
320 @players_cards.each do |p|
322 @deck.delete_at(@deck.index(c))
325 @deck = @deck.shuffle
327 # @deck = @cards.shuffle if @deck.empty?
328 @players_cards[player] << @deck.pop
332 # Check that a move is valid. Throw an exception if it's invalid
333 def validate_move(move, player = @current_player)
334 # Check the move is a valid one
335 raise(InvalidMoveError, "Move #{move}: Player #{player} does not exist") unless @players.include?(player)
336 raise(InvalidMoveError, "Move #{move}: None of player #{player}'s pieces on position #{move.origin}") unless move.origin.contains.find {|pc| pc.player == player}
337 raise(InvalidMoveError, "Move #{move}: Origin and destination are the same") if move.origin == move.destination
339 origin_position = @board.positions.index(move.origin)
340 destination_position = @board.positions.index(move.destination)
341 # Is this move an advance or a retreat?
342 if destination_position > origin_position
344 if move.destination == @board.positions[-1] # A move into the boat
345 raise(InvalidMoveError, "Move #{move}: Move into boat and card unspecified") if move.destination == @board.positions[-1] and move.card_played == :unspecified
346 unless @players_cards[player].find {|c| c == move.card_played}
347 raise(InvalidMoveError, "Player #{player} does not have a card to move a piece into the boat")
350 if move.card_played != :unspecified and move.destination.symbol != move.card_played
351 raise(InvalidMoveError, "Player #{player} trying to move to #{move.destination}, a #{move.destination.symbol} square with a a #{move.card_played} card")
353 unless @players_cards[player].find {|c| c == move.destination.symbol}
354 raise(InvalidMoveError, "Player #{player} does not have a card to move a piece to a #{move.destination.symbol} square")
356 # Check target square is vacant
357 raise(InvalidMoveError, "Advance move #{move}: destination occupied") unless move.destination.contains.empty?
359 # Check all the intervening squares with this symbol are occupied
360 intervening_empty_position = @board.positions[origin_position...destination_position].index_find do |p|
361 p.symbol == move.destination.symbol and
364 raise(InvalidMoveError, "Advance move #{move}: location #{intervening_empty_position} is empty") if intervening_empty_position
367 # Check target position has one or two pieces already on it
368 destination_count = move.destination.contains.length
369 raise(InvalidMoveError, "Retreat move #{move}: destination has no pieces already on it") if destination_count == 0
370 raise(InvalidMoveError, "Retreat move #{move}: destination has too many (#{destination_count}) pieces already on it") if destination_count >= $MAX_PIECES_PER_POSITION
371 # Check none of the intervening squares have any pieces on them
372 # puts "Checking positions #{destination_position} to #{origin_position}"
373 intervening_target_position = @board.positions[(destination_position + 1)...origin_position].index_find do |p|
374 # puts "Examining postition #{p} at location #{@board.positions.index(p)} which contains #{p.contains.length} pieces"
375 p.contains.length > 0 and
376 p.contains.length < $MAX_PIECES_PER_POSITION
378 raise(InvalidMoveError, "Retreat move #{move.show(@board)}: location #{intervening_target_position} is a viable target") if intervening_target_position
382 # Apply a single move to a game.
383 def apply_move!(move, player = @current_player, validate = true)
385 validate_move(move, player) if validate
387 raise(InvalidMoveError, "Too many consecutive moves by #{@current_player}: has taken #{@moves_by_current_player} and validate is #{validate}") if validate and player == @current_player and @moves_by_current_player >= $MAX_MOVES_PER_TURN
389 # Record the old state
390 this_game_state = GameState.new(move, @current_player, @board, @pieces, @deck, @players_cards, @moves_by_current_player)
391 @history << this_game_state
394 move.origin.contains.delete move.piece
395 move.destination.contains << move.piece
396 move.piece.position = move.destination
398 if player == @current_player
399 @moves_by_current_player += 1
401 @current_player = player
402 @moves_by_current_player = 1
406 if @board.positions.index(move.destination) > @board.positions.index(move.origin)
409 card_to_remove = if move.card_played != :unspecified
412 move.destination.symbol
414 if @players_cards[player].include?(card_to_remove)
415 @players_cards[player].delete_at(@players_cards[player].index(card_to_remove))
420 deal_cards!(move.destination.contains.length - 1, player)
423 # If this player has all their pieces in the boat, declare a win.
424 if @pieces[player].all? {|pc| pc.position == @board.positions[-1]}
425 raise(GameWonNotice, "Game won by #{player}")
431 state_to_restore = @history[-1]
432 move, @current_player, @board, @pieces, @deck, @players_cards,
433 @moves_by_current_player =
434 state_to_restore.copy_game_state(state_to_restore.move,
435 state_to_restore.player,
436 state_to_restore.board,
437 state_to_restore.pieces_before_move,
438 state_to_restore.deck_before_move,
439 state_to_restore.players_cards_before_move,
440 state_to_restore.moves_by_current_player)
444 # Apply a list of moves in order
445 def apply_moves!(moves)
447 @current_player = move.piece.player
448 apply_move!(move, @current_player)
449 next_player! if @moves_by_current_player >= $MOVES_PER_TURN
454 # Set the current player to be the next player
456 if @current_player == @players[-1]
457 @current_player = @players[0]
459 @current_player = @players[@players.index(@current_player) + 1]
461 @moves_by_current_player = 0
466 def reset_current_player(new_current_player)
467 @current_player = new_current_player
468 @moves_by_current_player = 0
472 # Return an array of all possible moves from this state, given the active player
473 def possible_moves(player = @current_player)
475 @pieces[player].each do |piece|
476 # Do a forward move for each card held
477 unless piece.position == @board.positions[-1]
478 @players_cards[player].each do |card|
479 destination = @board.positions[@board.positions.index(piece.position)..-1].find do |pos|
480 (pos.symbol == card and pos.contains == []) or
483 # puts "Player #{player}, card #{card}, piece #{piece.number} at position #{@board.positions.index(piece.position)} to #{@board.positions.index(destination)}, a #{destination.symbol}"
484 moves << Move.new(piece, piece.position, destination, card)
487 # Do a reverse move for the piece
488 unless piece.position == board.positions[0]
489 destination = @board.positions[1...@board.positions.index(piece.position)].reverse.find do |pos|
490 pos.contains.length == 1 or pos.contains.length == 2
493 # puts "Player #{player}, piece #{piece.number} at position #{@board.positions.index(piece.position)} retreats to #{@board.positions.index(destination)}, a #{destination.symbol} containing #{destination.contains.length} pieces"
494 moves << Move.new(piece, piece.position, destination)
498 # moves.each {|m| puts m.show(@board)}
502 def build_state_string
503 outstr = "Current player = #{@current_player}\n"
504 0.upto((@board.positions.length)-1) do |i|
505 outstr << "#{i}: #{@board.positions[i].symbol}: "
506 @board.positions[i].contains.each do |piece|
507 outstr << "P#{piece.player}:#{piece.number} "
511 0.upto((@players.length)-1) do |i|
512 outstr << "Player #{i} holds " << (@players_cards[i].sort_by {|c| c.to_s}).join(', ') << "\n"
514 outstr << "Deck holds " << @deck.join(', ') << "\n"
518 # Show the state of the board
520 puts build_state_string
521 # @pieces.keys.sort.each do |piece_name|
522 # if @pieces[piece_name].captured
523 # puts "Piece #{piece_name} captured, at #{@pieces[piece_name].position}"
525 # puts "Piece #{piece_name} is at #{@pieces[piece_name].position}, holds #{(@pieces[piece_name].contains.collect{|c| c.name}).join(' ')}"
539 def set_testing_game!
545 # Given a set of lines from an input file, turn them into a Game object and
546 # a set of Move objects.
547 # Note the multiple return values.
549 def Game.read_game(gamelines)
550 gamelines.each {|l| l.chomp!}
551 # puts "Creating game with #{gamelines[0].to_i} players"
552 game = Game.new(gamelines[0].to_i, 6, 6)
556 game.board.positions[i-1] = Position.new(gamelines[i].to_sym)
557 # puts "Making board position #{i-1} a #{gamelines[i].to_sym}"
560 # read all the moves so far
563 current_player_moves = 0
566 player_card_counts = game.players_cards.map{|p| 3}
567 # player_card_counts.each {|i| i = 3}
568 # unused_cards = game.cards.map{|c| c}
570 player_card_counts = game.players_cards.map {|p| $INITIAL_CARDS_PER_PLAYER}
571 unused_cards = game.cards.map {|c| c}
573 while gamelines[i].in_move_format?
574 move = gamelines[i].to_move(game, true)
575 # puts "Applying move #{move.show(game.board)} from line #{i} of the file. Current player before move application is #{game.current_player}"
576 if move.piece.player == current_player
577 current_player_moves += 1
579 current_player = move.piece.player
580 current_player_moves = 1
582 # if move is an advance move, decrement the cards held by the player and remove the card from unused cards
583 # throw an error if an advance move is made when all the cards of that type have been used
584 # if unused_cards becomes empty, restock it.
585 if game.board.positions.index(move.destination) > game.board.positions.index(move.origin)
586 raise(InvalidMoveError, "Game reading: Player #{move.piece.player} attempting an advance move with no cards in hand. Move is #{gamelines[i]} on line #{i}") if player_card_counts[move.piece.player] == 0
587 raise(InvalidMoveError, "Game reading: Player #{move.piece.player} attempting an advance move to a #{move.destination.symbol} place when all those cards have been used. Move is #{gamelines[i]} on line #{i}") unless unused_cards.include? move.destination.symbol
588 player_card_counts[current_player] -= 1
589 unused_cards.delete_at(unused_cards.index(move.destination.symbol))
590 # if move is a retreat move, increment the cards held by the player
592 player_card_counts[current_player] += move.destination.contains.length
593 if unused_cards.length == player_card_counts.inject {|sum, n| sum + n }
594 unused_cards = game.cards.map {|c| c}
597 game.apply_move!(move, move.piece.player, false)
599 # puts "Applied move #{move.show(game.board)} from line #{i} of the file"
603 # note the current player
604 game.current_player = gamelines[i].to_i - 1
605 if game.current_player == current_player
606 game.moves_by_current_player = current_player_moves
608 game.moves_by_current_player = 0
610 puts "Setting current player to #{game.current_player} on line #{i}"
611 current_player = game.current_player
614 game.players_cards = game.players_cards.map {|c| []}
615 player_card_counts.each_index {|index| puts "#{index} should have #{player_card_counts[index]} cards"}
616 game.players_cards.each_index {|index| puts "#{index} has #{game.players_cards[index]} cards"}
617 puts "Current player is #{game.current_player} whose cards are #{game.players_cards[game.current_player]}"
618 # game.players_cards[game.current_player] = []
619 (i+1).upto(gamelines.length - 1) do |j|
620 game.players_cards[game.current_player] << gamelines[j].to_sym
621 unused_cards.delete_at(unused_cards.index(move.destination.symbol))
622 puts "Reading line #{j} to give player #{game.current_player} a #{gamelines[j].to_sym} card"
624 raise(InvalidMoveError, "Player #{game.current_player} given #{game.players_cards[game.current_player].length} cards, but should have #{player_card_counts[game.current_player]} cards from play") if game.players_cards[game.current_player].length != player_card_counts[game.current_player]
626 # Update the game deck
628 puts "#{unused_cards.length} unused cards"
629 player_card_counts.each {|c| puts "has #{c} cards"}
630 unused_cards = unused_cards.shuffle
631 player_card_counts[game.current_player] = 0
632 player_card_counts.each_index do |player|
633 if player_card_counts[player] > 0
634 game.deal_cards!(player_card_counts[player], player)
635 # 1.upto(count) {unused_cards.pop}
638 game.deck = unused_cards
639 puts "#{game.deck.length} cards remaining in deck"
640 game.players_cards.each {|cards| puts "holds #{cards}"}
647 # Extension to String class to convert a move-description string into a Move object.
648 # This is the inverse of the Move#to_s method
652 return ((elements.length == 3 or elements.length == 4) and
653 elements[0].to_i > 0 and elements[0].to_i < 6 and
654 elements[1].to_i >= 0 and elements[1].to_i <= 37 and
655 elements[2].to_i >= 0 and elements[2].to_i <= 37)
658 def to_move(game, convert_to_zero_based_player_number = false)
659 move_elements = self.downcase.split
660 player = move_elements[0].to_i
661 player = player - 1 if convert_to_zero_based_player_number
662 origin_index = move_elements[1].to_i
663 destination_index = move_elements[2].to_i
664 raise(InvalidMoveError, "Invalid origin #{origin_index} in move read") unless origin_index >= 0 and origin_index < game.board.positions.length
665 raise(InvalidMoveError, "Invalid destination #{destination_index} in move read") unless destination_index > 0 and destination_index <= game.board.positions.length
666 raise(InvalidMoveError, "Player #{player} does not have a piece on position #{origin_index} in move read") unless game.board.positions[origin_index].contains.any? {|p| p.player == player}
667 piece = game.board.positions[origin_index].contains.find {|p| p.player == player}
668 piece_name = piece.number
669 if move_elements.length == 4
670 raise(InvalidMoveError, "Invalid card played: #{move_elements[3]}") unless $SYMBOLS.include?(move_elements[3].chomp.to_sym)
671 Move.new(game.pieces[player][piece_name],
672 game.board.positions[origin_index],
673 game.board.positions[destination_index],
674 move_elements[3].chomp.to_sym)
676 Move.new(game.pieces[player][piece_name],
677 game.board.positions[origin_index],
678 game.board.positions[destination_index])
684 # Read a game description file and convert it into a Game object and set of Move objects.
685 # Note that Game.read_game method returns multiple values, so this one does too.
687 def IO.read_game(filename)
688 gamelines = IO.readlines(filename)
689 return Game.read_game(gamelines)
693 # Extension to the Array class to include the Array#shuffle function
699 def index_find(&block)