001    package ai;
002    
003    import java.util.ArrayList;
004    import java.util.List;
005    import java.util.Random;
006    
007    import rules.GameState;
008    
009    import core.Color;
010    import core.Game;
011    import core.Move;
012    import core.Player;
013    
014    
015    /**
016     * An ai player that makes random moves.
017     * 
018     * @specfield state : game state // the current state of the came according to
019     *            the ai
020     */
021    public class RandomPlayer extends Player
022    {
023            private GameState state;
024            private Random r;
025    
026            /**
027             * Creates a new random player of the given color
028             * 
029             * @param c
030             *            color of the player
031             * 
032             * @requires c not null
033             */
034            public RandomPlayer(Color c)
035            {
036                    super(c);
037                    state = new GameState();
038                    r = new Random();
039            }
040    
041            /**
042             * @see Player
043             */
044            public Move askForMove(Move opponentsMove)
045            {
046                    // If this is not the game's very first move
047                    if (state.getMoveNum() > 0 || this.getColor() == Color.BLACK)
048                    {
049                            // Update the board with the opponent's move
050                            state.makeMove(opponentsMove);
051                    }
052                    List<Move> l = new ArrayList<Move>(state.legalMoves());
053                    Move m = l.get(r.nextInt(l.size()));
054                    state.makeMove(m);
055                    return m;
056            }
057    
058            /**
059             * Has the player make a series of moves. Used to get the AI player up to
060             * speed on a newly loaded game
061             * 
062             * @param game
063             *            the new game
064             * 
065             * @modifies state
066             * 
067             * @requires game not null
068             */
069            public void update(Game game)
070            {
071                    state = new GameState();
072                    for (int i = 0; i < game.getMoveHistory().size() - 1; i++)
073                    {
074                            state.makeMove(game.getMoveHistory().get(i));
075                    }
076    
077                    if (this.getColor() != game.getCurrentPlayer().getColor())
078                    {
079                            state.makeMove(game.getMoveHistory().get(
080                                            game.getMoveHistory().size() - 1));
081                    }
082            }
083    }