5 #include "controller.h"
10 * Queries the AI program to setup its pieces
11 * @returns the result of the response
13 Board::MovementResult Controller::Setup(const char * opponentName)
19 assert(SendMessage("RED %s %d %d", opponentName, Board::theBoard.Width(), Board::theBoard.Height()));
24 assert(SendMessage("BLUE %s %d %d", opponentName, Board::theBoard.Width(), Board::theBoard.Height()));
25 y = Board::theBoard.Height()-4;
30 //Should never see this;
36 int usedUnits[(int)(Piece::BOMB)];
37 for (int ii = 0; ii <= (int)(Piece::BOMB); ++ii)
40 //The setup is spread across 4 lines of the board - blue at the top, red at the bottom. AI has 2.5s for each line.
45 for (int ii=0; ii < 4; ++ii)
48 if (!GetMessage(line, 2.5))
50 fprintf(stderr, "Timeout on setup\n");
51 return Board::BAD_RESPONSE;
53 if ((int)(line.size()) != Board::theBoard.Width())
55 fprintf(stderr, "Bad length of \"%s\" on setup\n", line.c_str());
56 return Board::BAD_RESPONSE;
59 for (int x = 0; x < (int)(line.size()); ++x)
61 Piece::Type type = Piece::GetType(line[x]);
62 if (type != Piece::NOTHING)
64 //fprintf(stderr, "x y %d %d\n", x, y+ii);
65 // fprintf(stderr, "Found unit of type '%c' (%d '%c') %d vs %d\n", line[x], (int)(type), Piece::tokens[(int)(type)], usedUnits[(int)(type)], Piece::maxUnits[(int)type]);
66 /// fprintf(stderr, "Marshal is %d '%c', flag is %d '%c'\n", (int)Piece::MARSHAL, Piece::tokens[(int)(Piece::MARSHAL)], (int)Piece::FLAG, Piece::tokens[(int)(Piece::FLAG)]);
68 usedUnits[(int)(type)] += 1;
69 if (usedUnits[type] > Piece::maxUnits[(int)type])
71 fprintf(stderr, "Too many units of type %c\n", Piece::tokens[(int)(type)]);
72 return Board::BAD_RESPONSE;
75 Board::theBoard.AddPiece(x, y+ii, type, colour);
80 if (usedUnits[(int)Piece::FLAG] <= 0)
82 return Board::BAD_RESPONSE; //You need to include a flag!
90 * Queries the AI program to respond to a state of Board::theBoard
91 * @returns The result of the response and/or move if made
93 Board::MovementResult Controller::MakeMove(string & buffer)
97 return Board::NO_MOVE; //AI has quit
98 Board::theBoard.Print(output, colour);
104 if (!GetMessage(buffer,2))
106 return Board::NO_MOVE; //AI did not respond. It will lose by default.
109 int x; int y; string direction="";
110 stringstream s(buffer);
116 Board::Direction dir;
117 if (direction == "UP")
121 else if (direction == "DOWN")
125 else if (direction == "LEFT")
129 else if (direction == "RIGHT")
135 fprintf(stderr, "BAD_RESPONSE \"%s\"\n", buffer.c_str());
136 return Board::BAD_RESPONSE; //AI gave bogus direction - it will lose by default.
142 Board::MovementResult moveResult = Board::theBoard.MovePiece(x, y, dir, multiplier, colour);
157 case Board::BOTH_DIE:
158 buffer += " BOTHDIE";
161 buffer += " ILLEGAL";
166 if (!Board::LegalResult(moveResult))
167 return Board::OK; //HACK - Legal results returned!