Initial commit
[trapthecap.git] / src / .svn / text-base / play.rb.svn-base
1 # == Synopsis
2 #
3 # Play a game of Trap the Cap.
4 #
5 # == Author
6 # Neil Smith
7 #
8 # == Change history
9 # Version 1.1:: 23 April 2008
10
11 require 'lib/libttc'
12 require 'lib/libpplayer'
13
14 # Play a game to completion, given a set of player agents.
15 class GameHandler
16
17 attr_reader :game
18
19 # Create a game handler that uses a set of players
20 def initialize(players, limit = 5000, verbose = false, very_verbose = false)
21 @game = Game.new(players.length)
22 @verbose = verbose
23 @very_verbose = very_verbose
24 @limit = limit
25
26 # Give each player a name
27 @named_players = Hash.new
28 (@game.players.zip players).each do |kv|
29 @named_players[kv[0]] = kv[1]
30 end
31 end
32
33 # Play a game of Trap the Cap. If players make illegal moves, disqualify them and restart the game.
34 # Terminate the game if there's a winner, there's only one player left,
35 # or the game has gone on too long.
36 def play
37 while @game.history.length < @limit
38 roll = rand(6) + 1
39 move_to_apply = @named_players[@game.current_player].best_move(@game, roll)
40 puts "Move #{@game.history.length + 1}: Player #{@game.current_player} rolled #{roll}: making move #{move_to_apply}" if @verbose
41 @game.apply_moves! [move_to_apply]
42 puts @game if @very_verbose
43 end
44 puts "Game terminated after #{@game.history.length} moves" if @verbose
45 [:draw, @limit]
46 rescue GameWonNotice => win_notification
47 winner = win_notification.message[-1,1]
48 puts "Game won by #{winner} in #{@game.history.length} moves" if @verbose
49 [@named_players[winner], @game.history.length]
50 rescue InvalidCaptureError, InvalidMoveError
51 puts "Disqualifying player #{@game.current_player}" if @verbose
52 @named_players.delete @game.current_player
53 if @named_players.length > 1
54 retry
55 else
56 puts "Game won by #{@named_players.keys[0]} by default" if @verbose
57 [@named_players[@named_players.keys[0]], 0]
58 end
59 end
60 end
61