3 # Play a game of Cartagena.
9 # Version 1.1:: 23 April 2008
11 require 'lib/libcartagena'
13 # Play a game to completion, given a set of player agents.
18 # Create a game handler that uses a set of players
19 def initialize(players
, game_length_limit
= 5000, verbose
= false, very_verbose
= false)
20 @game = Game
.new(players
.length
)
22 @very_verbose = very_verbose
23 @game_length_limit = game_length_limit
25 # Give each player a name
26 @named_players = Hash
.new
27 (@game.players
.zip players
).each
do |kv
|
28 @named_players[kv
[0]] = kv
[1]
32 # Play a game of Cartagena. If players make illegal moves, disqualify them and restart the game.
33 # Terminate the game if there's a winner, there's only one player left,
34 # or the game has gone on too long.
36 while @game.history
.length
< @game_length_limit
37 move_to_apply
= @named_players[@game.current_player
].best_move(@game, roll
)
38 puts
"Move #{@game.history.length + 1}: Player #{@game.current_player} rolled #{roll}: making move #{move_to_apply}" if @verbose
39 @game.apply_moves
! [move_to_apply
]
40 puts
@game if @very_verbose
42 puts
"Game terminated after #{@game.history.length} moves" if @verbose
44 rescue GameWonNotice
=> win_notification
45 winner
= win_notification
.message
[-1,1]
46 puts
"Game won by #{winner} in #{@game.history.length} moves" if @verbose
47 [@named_players[winner
], @game.history
.length
]
48 rescue InvalidMoveError
49 puts
"Disqualifying player #{@game.current_player}" if @verbose
50 @named_players.delete
@game.current_player
51 if @named_players.length
> 1
54 puts
"Game won by #{@named_players.keys[0]} by default" if @verbose
55 [@named_players[@named_players.keys
[0]], 0]