7 Game* Game::theGame = NULL;
8 bool Game::gameCreated = false;
10 Game::Game(const char * redPath, const char * bluePath, const bool enableGraphics, double newStallTime, const bool allowIllegal, FILE * newLog, const Piece::Colour & newReveal, int newMaxTurns, bool newPrintBoard, double newTimeoutTime) : red(NULL), blue(NULL), turn(Piece::RED), theBoard(10,10), graphicsEnabled(enableGraphics), stallTime(newStallTime), allowIllegalMoves(allowIllegal), log(newLog), reveal(newReveal), turnCount(0), input(NULL), maxTurns(newMaxTurns), printBoard(newPrintBoard), timeoutTime(newTimeoutTime)
15 fprintf(stderr, "Game::Game - Error - Tried to create more than one Game!\n");
20 signal(SIGPIPE, Game::HandleBrokenPipe);
24 if (graphicsEnabled && (!Graphics::Initialised()))
25 Graphics::Initialise("Stratego", theBoard.Width()*32, theBoard.Height()*32);
26 #endif //BUILD_GRAPHICS
30 MakeControllers(redPath, bluePath);
32 if (red == NULL || blue == NULL)
34 fprintf(stderr, "Game::Game - Error creating controller: ");
38 fprintf(stderr, " BOTH! (red: \"%s\", blue: \"%s\"\n", redPath, bluePath);
40 fprintf(stderr, " RED! (red: \"%s\")\n", redPath);
43 fprintf(stderr, "BLUE! (blue: \"%s\")\n", bluePath);
46 logMessage("Game initialised.\n");
49 Game::Game(const char * fromFile, const bool enableGraphics, double newStallTime, const bool allowIllegal, FILE * newLog, const Piece::Colour & newReveal, int newMaxTurns, bool newPrintBoard, double newTimeoutTime) : red(NULL), blue(NULL), turn(Piece::RED), theBoard(10,10), graphicsEnabled(enableGraphics), stallTime(newStallTime), allowIllegalMoves(allowIllegal), log(newLog), reveal(newReveal), turnCount(0), input(NULL), maxTurns(newMaxTurns), printBoard(newPrintBoard), timeoutTime(newTimeoutTime)
54 fprintf(stderr, "Game::Game - Error - Tried to create more than one Game!\n");
59 signal(SIGPIPE, Game::HandleBrokenPipe);
62 if (graphicsEnabled && (!Graphics::Initialised()))
63 Graphics::Initialise("Stratego", theBoard.Width()*32, theBoard.Height()*32);
64 #endif //BUILD_GRAPHICS
66 input = fopen(fromFile, "r");
68 red = new FileController(Piece::RED, input);
69 blue = new FileController(Piece::BLUE, input);
80 if (log != NULL && log != stdout && log != stderr)
83 if (input != NULL && input != stdin)
88 * Attempts to setup the board and controllers
89 * @param redName the name of the red AI
90 * @param blueName the name of the blue AI
91 * @returns A colour, indicating if there were any errors
92 Piece::NONE indicates no errors
93 Piece::BOTH indicates errors with both AI
94 Piece::RED / Piece::BLUE indicates an error with only one of the two AI
96 Piece::Colour Game::Setup(const char * redName, const char * blueName)
101 logMessage("Controller for Player RED is invalid!\n");
102 if (!red->HumanController())
103 logMessage("Check that executable \"%s\" exists and has executable permissions set.\n", redName);
107 logMessage("Controller for Player BLUE is invalid!\n");
108 if (!blue->HumanController())
109 logMessage("Check that executable \"%s\" exists and has executable permissions set.\n", blueName);
117 else if (!blue->Valid())
122 for (int y = 4; y < 6; ++y)
124 for (int x = 2; x < 4; ++x)
126 theBoard.AddPiece(x,y,Piece::BOULDER, Piece::NONE);
128 for (int x = 6; x < 8; ++x)
130 theBoard.AddPiece(x,y,Piece::BOULDER, Piece::NONE);
135 MovementResult redSetup = red->Setup(blueName);
136 MovementResult blueSetup = blue->Setup(redName);
139 Piece::Colour result = Piece::NONE;
140 if (redSetup != MovementResult::OK)
142 if (blueSetup != MovementResult::OK)
144 logMessage("BOTH players give invalid setup!\n");
145 result = Piece::BOTH;
149 //logMessage("Player RED gave an invalid setup!\n");
154 else if (blueSetup != MovementResult::OK)
156 //logMessage("Player BLUE gave an invalid setup!\n");
157 result = Piece::BLUE;
161 logMessage("%s RED SETUP\n", red->name.c_str());
162 if (redSetup == MovementResult::OK)
164 for (int y=0; y < 4; ++y)
166 for (int x=0; x < theBoard.Width(); ++x)
168 if (theBoard.GetPiece(x, y) != NULL)
169 logMessage("%c", Piece::tokens[(int)(theBoard.GetPiece(x, y)->type)]);
178 logMessage("INVALID!\n");
181 logMessage("%s BLUE SETUP\n", blue->name.c_str());
182 if (blueSetup == MovementResult::OK)
184 for (int y=0; y < 4; ++y)
186 for (int x=0; x < theBoard.Width(); ++x)
188 if (theBoard.GetPiece(x, theBoard.Height()-4+y) != NULL)
189 logMessage("%c", Piece::tokens[(int)(theBoard.GetPiece(x, theBoard.Height()-4+y)->type)]);
198 logMessage("INVALID!\n");
206 void Game::Wait(double wait)
211 TimerThread timer(wait*1000000); //Wait in seconds
214 #ifdef BUILD_GRAPHICS
215 if (!graphicsEnabled)
217 while (!timer.Finished());
221 #endif //BUILD_GRAPHICS
223 while (!timer.Finished())
225 #ifdef BUILD_GRAPHICS
227 while (SDL_PollEvent(&event))
237 #endif //BUILD_GRAPHICS
243 void Game::HandleBrokenPipe(int sig)
247 fprintf(stderr, "ERROR - Recieved SIGPIPE during game exit!\n");
250 if (theGame->turn == Piece::RED)
252 theGame->logMessage("Game ends on RED's turn - REASON: ");
253 if (theGame->blue->Valid()) //Should probably check this
254 theGame->blue->Message("DEFAULT");
256 else if (theGame->turn == Piece::BLUE)
259 theGame->logMessage("Game ends on BLUE's turn - REASON: ");
260 if (theGame->red->Valid()) //Should probably check this
261 theGame->red->Message("DEFAULT");
265 theGame->logMessage("Game ends on ERROR's turn - REASON: ");
269 theGame->logMessage("SIGPIPE - Broken pipe (AI program no longer running)\n");
271 if (Game::theGame->printBoard)
272 Game::theGame->theBoard.PrintPretty(stdout, Piece::BOTH);
275 #ifdef BUILD_GRAPHICS
276 if (Game::theGame->graphicsEnabled && theGame->log == stdout)
278 theGame->logMessage("CLOSE WINDOW TO EXIT\n");
279 Game::theGame->theBoard.Draw(Piece::BOTH);
283 while (SDL_PollEvent(&event))
295 #endif //BUILD_GRAPHICS
297 if (theGame->log == stdout || theGame->log == stderr)
299 theGame->logMessage( "PRESS ENTER TO EXIT\n");
300 theGame->theBoard.Print(theGame->log);
301 while (fgetc(stdin) != '\n');
309 void Game::PrintEndMessage(const MovementResult & result)
313 logMessage("Game ends in the SETUP phase - REASON: ");
317 if (turn == Piece::RED)
319 logMessage("Game ends on RED's turn - REASON: ");
321 else if (turn == Piece::BLUE)
323 logMessage("Game ends on BLUE's turn - REASON: ");
327 logMessage("Game ends on ERROR's turn - REASON: ");
333 case MovementResult::OK:
334 logMessage("Status returned OK, unsure why game halted...\n");
336 case MovementResult::DIES:
337 logMessage("Status returned DIES, unsure why game halted...\n");
339 case MovementResult::KILLS:
340 logMessage("Status returned KILLS, unsure why game halted...\n");
342 case MovementResult::BOTH_DIE:
343 logMessage("Status returned BOTH_DIE, unsure why game halted...\n");
345 case MovementResult::NO_BOARD:
346 logMessage("Board does not exit?!\n");
348 case MovementResult::INVALID_POSITION:
349 logMessage("Coords outside board\n");
351 case MovementResult::NO_SELECTION:
352 logMessage("Move does not select a piece\n");
354 case MovementResult::NOT_YOUR_UNIT:
355 logMessage("Selected piece belongs to other player\n");
357 case MovementResult::IMMOBILE_UNIT:
358 logMessage("Selected piece is not mobile (FLAG or BOMB)\n");
360 case MovementResult::INVALID_DIRECTION:
361 logMessage("Selected unit cannot move that way\n");
363 case MovementResult::POSITION_FULL:
364 logMessage("Attempted move into square occupied by neutral or allied piece\n");
366 case MovementResult::VICTORY_FLAG:
367 logMessage("Captured the flag\n");
369 case MovementResult::VICTORY_ATTRITION:
370 logMessage("Destroyed all mobile enemy pieces\n");
372 case MovementResult::BAD_RESPONSE:
373 logMessage("Unintelligable response\n");
375 case MovementResult::NO_MOVE:
376 logMessage("Response timeout after %2f seconds.\n", timeoutTime);
378 case MovementResult::COLOUR_ERROR:
379 logMessage("Internal controller error - COLOUR_ERROR\n");
381 case MovementResult::ERROR:
382 logMessage("Internal controller error - Unspecified ERROR\n");
384 case MovementResult::DRAW_DEFAULT:
385 logMessage("Game declared a draw after %d turns\n", turnCount);
387 case MovementResult::DRAW:
388 logMessage("Game declared a draw because neither player has mobile pieces\n");
390 case MovementResult::SURRENDER:
391 logMessage("This player has surrendered!\n");
393 case MovementResult::BAD_SETUP:
397 logMessage("An illegal setup was made by RED\n");
400 logMessage("An illegal setup was made by BLUE\n");
403 logMessage("An illegal setup was made by BOTH players\n");
406 logMessage("Unknown internal error.\n");
416 fprintf(stdout, "%d Final State\n", turnCount);
417 theBoard.PrintPretty(stdout, Piece::BOTH);
418 fprintf(stdout, "\n");
421 #ifdef BUILD_GRAPHICS
422 if (graphicsEnabled && log == stdout)
424 logMessage("CLOSE WINDOW TO EXIT\n");
425 theBoard.Draw(Piece::BOTH);
429 while (SDL_PollEvent(&event))
441 #endif //BUILD_GRAPHICS
445 logMessage("PRESS ENTER TO EXIT\n");
446 while (fgetc(stdin) != '\n');
447 exit(EXIT_SUCCESS); //Might want to actually exit, you foolish fool
452 /** Checks for victory by attrition (destroying all mobile pieces)
454 * @returns OK for no victory,
455 * DRAW if both players have no pieces, or
456 * VICTORY_ATTRITION if the current player has won by attrition
458 MovementResult Game::CheckVictoryAttrition()
460 if (theBoard.MobilePieces(Piece::OppositeColour(turn)) == 0)
462 if (theBoard.MobilePieces(turn) == 0)
463 return MovementResult::DRAW;
465 return MovementResult::VICTORY_ATTRITION;
467 return MovementResult::OK;
470 MovementResult Game::Play()
473 MovementResult result = MovementResult::OK;
477 Piece::Colour toReveal = reveal;
482 logMessage("Messaging red with \"START\"\n");
483 red->Message("START");
487 while (!Board::HaltResult(result) && (turnCount < maxTurns || maxTurns < 0))
489 if (red->HumanController() && blue->HumanController())
490 toReveal = Piece::RED;
495 fprintf(stdout, "START:\n");
497 fprintf(stdout, "%d BLUE:\n", turnCount);
498 theBoard.PrintPretty(stdout, toReveal);
499 fprintf(stdout, "\n\n");
502 #ifdef BUILD_GRAPHICS
504 theBoard.Draw(toReveal);
505 #endif //BUILD_GRAPHICS
510 if (!Board::HaltResult(result))
512 result = CheckVictoryAttrition();
514 if (Board::HaltResult(result))
517 logMessage( "%d RED: ", turnCount);
518 result = red->MakeMove(buffer);
519 red->Message(buffer);
520 blue->Message(buffer);
521 logMessage( "%s\n", buffer.c_str());
523 if (!Board::HaltResult(result))
525 result = CheckVictoryAttrition();
527 if (Board::HaltResult(result))
535 if (blue->HumanController() && red->HumanController())
536 toReveal = Piece::BLUE;
540 fprintf(stdout, "%d RED:\n", turnCount);
541 theBoard.PrintPretty(stdout, toReveal);
542 fprintf(stdout, "\n\n");
545 #ifdef BUILD_GRAPHICS
547 theBoard.Draw(toReveal);
548 #endif //BUILD_GRAPHICS
555 if (!Board::HaltResult(result))
557 result = CheckVictoryAttrition();
559 if (Board::HaltResult(result))
562 logMessage( "%d BLU: ", turnCount);
563 result = blue->MakeMove(buffer);
564 blue->Message(buffer);
565 red->Message(buffer);
566 logMessage( "%s\n", buffer.c_str());
568 if (!Board::HaltResult(result))
570 result = CheckVictoryAttrition();
572 if (Board::HaltResult(result))
575 if (theBoard.MobilePieces(Piece::RED) == 0)
576 result = MovementResult::DRAW;
578 if (theBoard.MobilePieces(Piece::RED) == 0)
580 if (theBoard.MobilePieces(Piece::BLUE) == 0)
581 result = MovementResult::DRAW;
583 result = MovementResult::VICTORY_ATTRITION;
597 if ((maxTurns >= 0 && turnCount >= maxTurns) && result == MovementResult::OK)
599 result = MovementResult::DRAW_DEFAULT;
610 * Logs a message to the game's log file if it exists
611 * @param format the format string
612 * @param additional parameters - printed using va_args
613 * @returns the result of vfprintf or a negative number if the log file does not exist
615 int Game::logMessage(const char * format, ...)
620 va_start(ap, format);
622 int result = vfprintf(log, format, ap);
629 * Waits for a user command
630 * Currently ignores the command.
632 void Game::ReadUserCommand()
634 fprintf(stdout, "Waiting for user to press enter... (type QUIT to exit)\n");
636 for (char c = fgetc(stdin); c != '\n' && (int)(c) != EOF; c = fgetc(stdin))
641 if (command == "QUIT")
643 fprintf(stdout, "Ordered to quit... exiting...\n");
648 MovementResult FileController::QuerySetup(const char * opponentName, std::string setup[])
651 char c = fgetc(file);
659 while (fgetc(file) != '\n');
661 for (int y = 0; y < 4; ++y)
664 for (int x = 0; x < Game::theGame->theBoard.Width(); ++x)
666 setup[y] += fgetc(file);
669 if (fgetc(file) != '\n')
671 return MovementResult::BAD_RESPONSE;
674 return MovementResult::OK;
679 MovementResult FileController::QueryMove(std::string & buffer)
681 //This bit is kind of hacky and terrible, and yes I am mixing C with C++
682 //Yes I should have used fstream for the whole thing and it would be much easier.
687 fgets(buf, sizeof(buf), file);
688 char * s = (char*)(buf);
689 while (*s != ':' && *s != '\0')
692 //Move forward to the start of the move information
693 for (int i=0; i < 2; ++i)
695 if (*s != '\0' && *s != '\n')
699 //Unfortunately we can't just copy the whole line
701 //We have to remove the movement result tokens
704 vector<string> tokens;
705 Game::Tokenise(tokens, buffer, ' ');
708 if (tokens.size() < 1)
709 return MovementResult::BAD_RESPONSE;
713 if (tokens[0] == "NO_MOVE") //tokens[0] is either the x coordinate, or "NO_MOVE"
714 return MovementResult::OK;
715 if (tokens.size() < 2)
716 return MovementResult::BAD_RESPONSE;
718 buffer += tokens[1]; //The y coordinate
720 buffer += tokens[2]; //The direction
722 //Check for a possible multiplier. If tokens[3] is an integer it will be the multiplier, otherwise it won't be.
723 if (tokens.size() > 3 && atoi(tokens[3].c_str()) != 0)
730 //(tokens[3] should include a new line)
739 return MovementResult::OK;
745 int Game::Tokenise(std::vector<string> & buffer, std::string & str, char split)
748 for (unsigned int x = 0; x < str.size(); ++x)
750 if (str[x] == split && token.size() > 0)
752 buffer.push_back(token);
758 if (token.size() > 0)
759 buffer.push_back(token);
760 return buffer.size();
764 * Creates Controller baseds off strings. Takes into account controllers other than AI_Controller.
765 * @param redPath - Either the path to an AI_Controller compatable executable, or one of %human or %network or %network:[IP_ADDRESS]
766 * @param bluePath - Ditto
767 * Sets this->red to a controller using redPath, and this->blue to a controller using bluePath
768 * TODO: Make nicer (this function should be ~half the length)
770 void Game::MakeControllers(const char * redPath, const char * bluePath)
772 Network * redNetwork = NULL;
773 Network * blueNetwork = NULL;
774 //To allow for running two network controllers (I don't know why you would, but beside the point...) use two ports
775 static const int port1 = 4560;
776 static const int port2 = 4561;
778 if (redPath[0] == '@')
780 if (strcmp(redPath, "@human") == 0)
781 red = new Human_Controller(Piece::RED, graphicsEnabled);
784 const char * network = strstr(redPath, "@network");
790 network = strstr(network, ":");
794 logMessage("Creating server for red AI... ");
795 redNetwork = new Server(port1);
796 logMessage("Successful!\n");
801 network = (const char*)(network+1);
802 logMessage("Creating client for red AI... ");
803 redNetwork = new Client(network, port2);
804 logMessage("Connected to address %s\n", network);
807 logMessage(" (Red's responses will be received over the connection)\n");
808 red = new NetworkReceiver(Piece::RED, redNetwork);
812 red = new AI_Controller(Piece::RED, redPath, timeoutTime);
814 if (bluePath[0] == '@')
816 if (strcmp(bluePath, "@human") == 0)
817 blue = new Human_Controller(Piece::BLUE, graphicsEnabled);
820 const char * network = strstr(bluePath, "@network");
826 network = strstr(network, ":");
830 logMessage("Creating server for blue AI... ");
831 blueNetwork = new Server(port2);
832 logMessage("Successful!\n");
837 network = (const char*)(network+1);
838 logMessage("Creating client for blue AI... ");
839 blueNetwork = new Client(network, port1);
840 logMessage("Connected to address %s\n", network);
842 logMessage(" (Blue's responses will be received over the connection)\n");
843 blue = new NetworkReceiver(Piece::BLUE, blueNetwork);
847 blue = new AI_Controller(Piece::BLUE, bluePath, timeoutTime);
849 if (redNetwork != NULL)
852 blue = new NetworkSender(Piece::BLUE,blue, redNetwork);
853 logMessage(" (Blue's responses will be copied over the connection)\n");
855 if (blueNetwork != NULL)
858 red = new NetworkSender(Piece::RED, red, blueNetwork);
859 logMessage(" (Red's responses will be copied over the connection)\n");