# == Synopsis # # Play a game of Trap the Cap. # # == Author # Neil Smith # # == Change history # Version 1.1:: 23 April 2008 require 'lib/libttc' require 'lib/libpplayer' # Play a game to completion, given a set of player agents. class GameHandler attr_reader :game # Create a game handler that uses a set of players def initialize(players, limit = 5000, verbose = false, very_verbose = false) @game = Game.new(players.length) @verbose = verbose @very_verbose = very_verbose @limit = limit # Give each player a name @named_players = Hash.new (@game.players.zip players).each do |kv| @named_players[kv[0]] = kv[1] end end # Play a game of Trap the Cap. If players make illegal moves, disqualify them and restart the game. # Terminate the game if there's a winner, there's only one player left, # or the game has gone on too long. def play while @game.history.length < @limit roll = rand(6) + 1 move_to_apply = @named_players[@game.current_player].best_move(@game, roll) puts "Move #{@game.history.length + 1}: Player #{@game.current_player} rolled #{roll}: making move #{move_to_apply}" if @verbose @game.apply_moves! [move_to_apply] puts @game if @very_verbose end puts "Game terminated after #{@game.history.length} moves" if @verbose [:draw, @limit] rescue GameWonNotice => win_notification winner = win_notification.message[-1,1] puts "Game won by #{winner} in #{@game.history.length} moves" if @verbose [@named_players[winner], @game.history.length] rescue InvalidCaptureError, InvalidMoveError puts "Disqualifying player #{@game.current_player}" if @verbose @named_players.delete @game.current_player if @named_players.length > 1 retry else puts "Game won by #{@named_players.keys[0]} by default" if @verbose [@named_players[@named_players.keys[0]], 0] end end end