2 * agent++ : A Sample agent for UCC::Progcomp2013
4 * @purpose Definition of Agent class
8 #include <cassert> // for sanity checks
14 * @param new_colour - colour of the Agent
16 Agent::Agent(const string & new_colour) : colour(Piece::str2colour(new_colour)), board(), selected(NULL)
31 * @purpose Selects a piece at random
32 * @returns Square containing the selected piece
34 Square & Agent::Select()
36 vector<Piece*> & v = board.pieces(colour); // get pieces
37 int choice = rand() % v.size(); // pick random index
38 Piece * p = v[choice]; // get piece at the index
39 assert(p->colour == colour);
40 selected = p; // update selected
41 //cerr << "Selected " << p->x << "," << p->y << " [" << p->types[0] << "," << p->types[1] << "]\n";
42 return board.square(p->x, p->y); // get Square from board
47 * @purpose Pick a square to move a selected piece into
48 * @returns Square to move last selected piece into
50 Square & Agent::Move()
52 assert(selected != NULL);
53 vector<Square*> moves; // all possible moves for selected piece
54 board.Get_moves(selected, moves); // populate possible moves
55 assert(moves.size() > 0);
56 int choice = rand() % moves.size(); // pick random index
57 return *(moves[choice]); // return that move
62 * @purpose The "Game Loop" for the agent; read commands and call appropriate function to make responses
63 * @param in - Stream to read input from (use std::cin)
64 * @param out - Stream to write output to (use std::cout)
66 void Agent::Run(istream & in, ostream & out)
68 string cmd; // buffer for tokens
71 in >> cmd; // read first token only
76 else if (cmd == "SELECTION?")
78 Square & s = Select(); // get selection
79 out << s.x << " " << s.y << "\n"; // return response through output
81 else if (cmd == "MOVE?")
83 Square & s = Move(); // get move
84 out << s.x << " " << s.y << "\n"; // return response through output
88 // There were multiple tokens...
91 s >> x; // Convert first token (in cmd) to an int
92 in >> y; // Read second token from in
94 in >> cmd; // Read third token
96 if (cmd == "->") // Token indicates a move was made
98 int x2; int y2; // remaining two tokens indicate destination
100 board.Update_move(x, y, x2, y2); // update the board
104 // Tokens are for a selection
105 int index; stringstream s2(cmd);
106 s2 >> index; // convert third token to an index
107 in >> cmd; // Read fourth token - the new type of the piece
108 board.Update_select(x, y, index, cmd); // update the board