Changed colour of blue pieces
[progcomp2012.git] / judge / manager / game.cpp
1 #include "game.h"
2 #include <stdarg.h>
3 #include <string>
4
5 using namespace std;
6
7
8
9 Game* Game::theGame = NULL;
10 bool Game::gameCreated = false;
11
12 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, const char * newImageOutput) : 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), imageOutput(newImageOutput)
13 {
14         gameCreated = false;
15         if (gameCreated)
16         {
17                 fprintf(stderr, "Game::Game - Error - Tried to create more than one Game!\n");
18                 exit(EXIT_FAILURE);
19         }
20         gameCreated = true;
21         Game::theGame = this;
22         signal(SIGPIPE, Game::HandleBrokenPipe);
23
24
25         #ifdef BUILD_GRAPHICS
26         if (graphicsEnabled && (!Graphics::Initialised()))
27         {
28                         string s = "Stratego: ";
29                         s += string(redPath);
30                         s += " ";
31                         s += string(bluePath);
32                         Graphics::Initialise(s.c_str(), theBoard.Width()*GRID_SIZE, theBoard.Height()*GRID_SIZE);
33         }
34         #endif //BUILD_GRAPHICS
35
36
37
38         MakeControllers(redPath, bluePath);
39
40         if (red == NULL || blue == NULL)
41         {
42                 fprintf(stderr, "Game::Game - Error creating controller: ");
43                 if (red == NULL)
44                 {
45                         if (blue == NULL)
46                                 fprintf(stderr, " BOTH! (red: \"%s\", blue: \"%s\"\n", redPath, bluePath);
47                         else
48                                 fprintf(stderr, " RED! (red: \"%s\")\n", redPath);
49                 }
50                 else
51                         fprintf(stderr, "BLUE! (blue: \"%s\")\n", bluePath);
52                 exit(EXIT_FAILURE);
53         }
54 //      logMessage("Game initialised.\n");
55 }
56
57 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,const char * newImageOutput) : 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), imageOutput(newImageOutput)
58 {
59         gameCreated = false;
60         if (gameCreated)
61         {
62                 fprintf(stderr, "Game::Game - Error - Tried to create more than one Game!\n");
63                 exit(EXIT_FAILURE);
64         }
65         gameCreated = true;
66         Game::theGame = this;
67         signal(SIGPIPE, Game::HandleBrokenPipe);
68
69         #ifdef BUILD_GRAPHICS
70         if (graphicsEnabled && (!Graphics::Initialised()))
71         {
72                         string s = "Stratego: (file) ";
73                         s += string(fromFile);
74                         Graphics::Initialise(s.c_str(), theBoard.Width()*GRID_SIZE, theBoard.Height()*GRID_SIZE);
75         }
76         #endif //BUILD_GRAPHICS
77
78         input = fopen(fromFile, "r");
79
80         red = new FileController(Piece::RED, input);
81         blue = new FileController(Piece::BLUE, input);
82
83
84 }
85
86 Game::~Game()
87 {
88         
89         delete red;
90         delete blue;
91
92         if (log != NULL && log != stdout && log != stderr)
93                 fclose(log);
94
95         if (input != NULL && input != stdin)
96                 fclose(input);
97 }
98
99 /**
100  * Attempts to setup the board and controllers
101  * @param redName the name of the red AI
102  * @param blueName the name of the blue AI
103  * @returns A colour, indicating if there were any errors
104         Piece::NONE indicates no errors
105         Piece::BOTH indicates errors with both AI
106         Piece::RED / Piece::BLUE indicates an error with only one of the two AI
107  */
108 Piece::Colour Game::Setup(const char * redName, const char * blueName)
109 {
110
111         if (!red->Valid())
112         {
113                 logMessage("Controller for Player RED is invalid!\n");
114                 if (!red->HumanController())
115                         logMessage("Check that executable \"%s\" exists and has executable permissions set.\n", redName);
116         }
117         if (!blue->Valid())
118         {
119                 logMessage("Controller for Player BLUE is invalid!\n");
120                 if (!blue->HumanController())
121                         logMessage("Check that executable \"%s\" exists and has executable permissions set.\n", blueName);
122         }
123         if (!red->Valid())
124         {
125                 if (!blue->Valid())
126                         return Piece::BOTH;
127                 return Piece::RED;
128         }
129         else if (!blue->Valid())
130         {
131                 return Piece::BLUE;
132         }
133
134         for (int y = 4; y < 6; ++y)
135         {
136                 for (int x = 2; x < 4; ++x)
137                 {
138                         theBoard.AddPiece(x,y,Piece::BOULDER, Piece::NONE);
139                 }
140                 for (int x = 6; x < 8; ++x)
141                 {
142                         theBoard.AddPiece(x,y,Piece::BOULDER, Piece::NONE);
143                 }
144         }
145
146
147         MovementResult redSetup = red->Setup(blueName);
148         MovementResult blueSetup = blue->Setup(redName);
149
150
151         Piece::Colour result = Piece::NONE;
152         if (redSetup != MovementResult::OK)
153         {       
154                 if (blueSetup != MovementResult::OK)
155                 {
156                         logMessage("BOTH players give invalid setup!\n");
157                         result = Piece::BOTH;
158                 }
159                 else
160                 {
161                         //logMessage("Player RED gave an invalid setup!\n");
162                         result = Piece::RED;
163                 }
164                 
165         }
166         else if (blueSetup != MovementResult::OK)
167         {
168                 //logMessage("Player BLUE gave an invalid setup!\n");
169                 result = Piece::BLUE;
170         }
171
172
173         logMessage("%s RED SETUP\n", red->name.c_str());
174         if (redSetup == MovementResult::OK)
175         {
176                 for (int y=0; y < 4; ++y)
177                 {
178                         for (int x=0; x < theBoard.Width(); ++x)
179                         {
180                                 if (theBoard.GetPiece(x, y) != NULL)
181                                         logMessage("%c", Piece::tokens[(int)(theBoard.GetPiece(x, y)->type)]);
182                                 else
183                                         logMessage(".");
184                         }
185                         logMessage("\n");
186                 }       
187         }
188         else
189         {
190                 logMessage("INVALID!\n");
191         }
192
193         logMessage("%s BLUE SETUP\n", blue->name.c_str());
194         if (blueSetup == MovementResult::OK)
195         {
196                 for (int y=0; y < 4; ++y)
197                 {
198                         for (int x=0; x < theBoard.Width(); ++x)
199                         {
200                                 if (theBoard.GetPiece(x, theBoard.Height()-4+y) != NULL)
201                                         logMessage("%c", Piece::tokens[(int)(theBoard.GetPiece(x, theBoard.Height()-4+y)->type)]);
202                                 else
203                                         logMessage(".");
204                         }
205                         logMessage("\n");
206                 }       
207         }
208         else
209         {
210                 logMessage("INVALID!\n");
211         }
212
213         
214         return result;
215
216 }
217
218 void Game::Wait(double wait)
219 {
220         if (wait <= 0)
221                 return;
222
223
224
225
226         #ifdef BUILD_GRAPHICS
227
228
229         if (!graphicsEnabled)
230         {
231                 usleep(1000000*wait); //Wait in seconds
232                 return;
233         }
234
235         TimerThread timer(wait*1000000); //Wait in seconds
236         timer.Start();
237         while (!timer.Finished())
238         {
239         
240                 SDL_Event  event;
241                 while (SDL_PollEvent(&event))
242                 {
243                         switch (event.type)
244                         {
245                                 case SDL_QUIT:
246                                         timer.Stop();
247                                         exit(EXIT_SUCCESS);
248                                         break;
249                         }
250                 }
251         }
252         timer.Stop();
253
254         #else
255         usleep(wait*1000000); //Wait in seconds
256         #endif //BUILD_GRAPHICS
257         
258 }
259
260 void Game::HandleBrokenPipe(int sig)
261 {
262         if (theGame == NULL)
263         {
264                 fprintf(stderr, "ERROR - Recieved SIGPIPE during game exit!\n");
265                 exit(EXIT_FAILURE);
266         }
267         if (theGame->turn == Piece::RED)
268         {
269                 theGame->logMessage("Game ends on RED's turn - REASON: ");
270                 if (theGame->blue->Valid()) //Should probably check this
271                         theGame->blue->Message("DEFAULT");      
272         }
273         else if (theGame->turn == Piece::BLUE)
274         {
275         
276                 theGame->logMessage("Game ends on BLUE's turn - REASON: ");
277                 if (theGame->red->Valid()) //Should probably check this
278                         theGame->red->Message("DEFAULT");
279         }
280         else
281         {
282                 theGame->logMessage("Game ends on ERROR's turn - REASON: ");
283                         
284         }
285         
286         theGame->logMessage("SIGPIPE - Broken pipe (AI program no longer running)\n");
287
288         if (Game::theGame->printBoard)
289                 Game::theGame->theBoard.PrintPretty(stdout, Piece::BOTH);
290
291         
292         #ifdef BUILD_GRAPHICS
293         if (Game::theGame->graphicsEnabled && theGame->log == stdout)
294         {
295                 theGame->logMessage("CLOSE WINDOW TO EXIT\n");
296                 Game::theGame->theBoard.Draw(Piece::BOTH);
297                 while (true)
298                 {
299                         SDL_Event  event;
300                         while (SDL_PollEvent(&event))
301                         {
302                                 switch (event.type)
303                                 {
304                                         case SDL_QUIT:
305                                                 exit(EXIT_SUCCESS);
306                                                 break;
307                                 }
308                         }                       
309                 }
310         }
311         else
312         #endif //BUILD_GRAPHICS
313         {
314                 if (theGame->log == stdout || theGame->log == stderr)
315                 {
316                         theGame->logMessage( "PRESS ENTER TO EXIT\n");
317                         theGame->theBoard.Print(theGame->log);
318                         while (fgetc(stdin) != '\n');
319                 }
320         }
321         
322
323         exit(EXIT_SUCCESS);
324 }
325
326 void Game::PrintEndMessage(const MovementResult & result)
327 {
328         if (turnCount == 0)
329         {
330                 logMessage("Game ends in the SETUP phase - REASON: ");
331         }
332         else
333         {
334                 if (turn == Piece::RED)
335                 {
336                         logMessage("Game ends on RED's turn - REASON: ");       
337                 }
338                 else if (turn == Piece::BLUE)
339                 {
340                         logMessage("Game ends on BLUE's turn - REASON: ");
341                 }
342                 else
343                 {
344                         logMessage("Game ends on ERROR's turn - REASON: ");
345                         
346                 }
347         }
348         switch (result.type)
349         {
350                 case MovementResult::OK:
351                         logMessage("Status returned OK, unsure why game halted...\n");
352                         break;
353                 case MovementResult::DIES:
354                         logMessage("Status returned DIES, unsure why game halted...\n");
355                         break;
356                 case MovementResult::KILLS:
357                         logMessage("Status returned KILLS, unsure why game halted...\n");
358                         break;
359                 case MovementResult::BOTH_DIE:
360                         logMessage("Status returned BOTH_DIE, unsure why game halted...\n");
361                         break;
362                 case MovementResult::NO_BOARD:
363                         logMessage("Board does not exit?!\n");
364                         break;
365                 case MovementResult::INVALID_POSITION:
366                         logMessage("Coords outside board\n");
367                         break;
368                 case MovementResult::NO_SELECTION:
369                         logMessage("Move does not select a piece\n");
370                         break;
371                 case MovementResult::NOT_YOUR_UNIT:
372                         logMessage("Selected piece belongs to other player\n");
373                         break;
374                 case MovementResult::IMMOBILE_UNIT:
375                         logMessage("Selected piece is not mobile (FLAG or BOMB)\n");
376                         break;
377                 case MovementResult::INVALID_DIRECTION:
378                         logMessage("Selected unit cannot move that way\n");
379                         break;
380                 case MovementResult::POSITION_FULL:
381                         logMessage("Attempted move into square occupied by neutral or allied piece\n");
382                         break;
383                 case MovementResult::VICTORY_FLAG:
384                         logMessage("Captured the flag\n");
385                         break;
386                 case MovementResult::VICTORY_ATTRITION:
387                         logMessage("Destroyed all mobile enemy pieces\n");
388                         break;
389                 case MovementResult::BAD_RESPONSE:
390                         logMessage("Unintelligable response\n");
391                         break;
392                 case MovementResult::NO_MOVE:
393                         logMessage("Response timeout after %2f seconds.\n", timeoutTime);
394                         break;
395                 case MovementResult::COLOUR_ERROR:
396                         logMessage("Internal controller error - COLOUR_ERROR\n");
397                         break;
398                 case MovementResult::ERROR:
399                         logMessage("Internal controller error - Unspecified ERROR\n");
400                         break;
401                 case MovementResult::DRAW_DEFAULT:
402                         logMessage("Game declared a draw after %d turns\n", turnCount);
403                         break;
404                 case MovementResult::DRAW:
405                         logMessage("Game declared a draw because neither player has mobile pieces\n");
406                         break;
407                 case MovementResult::SURRENDER:
408                         logMessage("This player has surrendered!\n");
409                         break;
410                 case MovementResult::BAD_SETUP:
411                         switch (turn)
412                         {
413                                 case Piece::RED:
414                                         logMessage("An illegal setup was made by RED\n");
415                                         break;
416                                 case Piece::BLUE:
417                                         logMessage("An illegal setup was made by BLUE\n");
418                                         break;
419                                 case Piece::BOTH:
420                                         logMessage("An illegal setup was made by BOTH players\n");
421                                         break;
422                                 case Piece::NONE:
423                                         logMessage("Unknown internal error.\n");
424                                         break;
425                         }
426                         break;
427
428         }
429
430         if (printBoard)
431         {
432                 system("clear");
433                 fprintf(stdout, "%d Final State\n", turnCount);
434                 theBoard.PrintPretty(stdout, Piece::BOTH);
435                 fprintf(stdout, "\n");
436         }
437
438         #ifdef BUILD_GRAPHICS
439         if (graphicsEnabled && log == stdout)
440         {
441                 logMessage("CLOSE WINDOW TO EXIT\n");
442                 theBoard.Draw(Piece::BOTH);
443                 while (true)
444                 {
445                         SDL_Event  event;
446                         while (SDL_PollEvent(&event))
447                         {
448                                 switch (event.type)
449                                 {
450                                         case SDL_QUIT:
451                                                 exit(EXIT_SUCCESS);
452                                                 break;
453                                 }
454                         }                       
455                 }
456         }
457         else
458         #endif //BUILD_GRAPHICS
459         {
460                 if (log == stdout)
461                 {
462                         logMessage("PRESS ENTER TO EXIT\n");
463                         while (fgetc(stdin) != '\n');
464                         exit(EXIT_SUCCESS); //Might want to actually exit, you foolish fool
465                 }
466         }
467
468 }
469 /** Checks for victory by attrition (destroying all mobile pieces)
470  *
471  *  @returns OK for no victory, 
472  *      DRAW if both players have no pieces, or 
473  *      VICTORY_ATTRITION  if the current player has won by attrition
474  */
475 MovementResult Game::CheckVictoryAttrition()
476 {
477         if (theBoard.MobilePieces(Piece::OppositeColour(turn)) == 0)
478         {
479                 if (theBoard.MobilePieces(turn) == 0)
480                         return MovementResult::DRAW;
481                 else
482                         return MovementResult::VICTORY_ATTRITION;
483         }
484         return MovementResult::OK;
485
486 }
487 MovementResult Game::Play()
488 {
489
490         MovementResult result = MovementResult::OK;
491         turnCount = 1;
492         string buffer;
493
494         Piece::Colour toReveal = reveal;
495         
496         
497         
498
499 //      logMessage("Messaging red with \"START\"\n");
500         red->Message("START");
501         
502         int moveCount = 0;
503
504         while (!Board::HaltResult(result) && (turnCount < maxTurns || maxTurns < 0))
505         {
506                 if (red->HumanController() && blue->HumanController())
507                         toReveal = Piece::RED;
508                 if (printBoard)
509                 {
510                         system("clear");
511                         if (turnCount == 0)
512                                 fprintf(stdout, "START:\n");
513                         else
514                                 fprintf(stdout, "%d BLUE:\n", turnCount);
515                         theBoard.PrintPretty(stdout, toReveal);
516                         fprintf(stdout, "\n\n");
517                 }
518
519                 #ifdef BUILD_GRAPHICS
520                 if (graphicsEnabled)
521                 {
522                         theBoard.Draw(toReveal);
523                         if (imageOutput != "")
524                         {
525                                 string imageFile = "" + imageOutput + "/"+ itostr(moveCount) + ".bmp";
526                                 Graphics::ScreenShot(imageFile.c_str());
527                         }
528
529                 }
530                 #endif //BUILD_GRAPHICS
531                 
532                 turn = Piece::RED;
533                 blue->Pause();
534                 red->Continue();
535                 if (!Board::HaltResult(result))
536                 {
537                         result = CheckVictoryAttrition();
538                 }
539                 if (Board::HaltResult(result))
540                         break;
541
542                 logMessage( "%d RED: ", turnCount);
543                 result = red->MakeMove(buffer);
544                 red->Message(buffer);
545                 blue->Message(buffer);
546                 logMessage( "%s\n", buffer.c_str());
547
548                 if (!Board::HaltResult(result))
549                 {
550                         result = CheckVictoryAttrition();
551                 }
552                 if (Board::HaltResult(result))
553                         break;
554
555                 if (stallTime >= 0)
556                         Wait(stallTime);
557                 else
558                         ReadUserCommand();
559
560                 if (blue->HumanController() && red->HumanController())
561                         toReveal = Piece::BLUE;
562                 if (printBoard)
563                 {
564                         system("clear");
565                         fprintf(stdout, "%d RED:\n", turnCount);
566                         theBoard.PrintPretty(stdout, toReveal);
567                         fprintf(stdout, "\n\n");
568                 }
569
570                 ++moveCount;
571                 
572                 #ifdef BUILD_GRAPHICS
573                 if (graphicsEnabled)
574                 {
575                         theBoard.Draw(toReveal);
576                         if (imageOutput != "")
577                         {
578                                 string imageFile = "" + imageOutput + "/" + itostr(moveCount) + ".bmp";
579                                 Graphics::ScreenShot(imageFile.c_str());
580                         }
581                 }
582                 #endif //BUILD_GRAPHICS
583
584                 
585                 
586                 turn = Piece::BLUE;
587                 red->Pause();
588                 blue->Continue();
589                 if (!Board::HaltResult(result))
590                 {
591                         result = CheckVictoryAttrition();
592                 }
593                 if (Board::HaltResult(result))
594                         break;
595
596                 logMessage( "%d BLU: ", turnCount);
597                 result = blue->MakeMove(buffer);
598                 blue->Message(buffer);
599                 red->Message(buffer);
600                 logMessage( "%s\n", buffer.c_str());
601
602                 if (!Board::HaltResult(result))
603                 {
604                         result = CheckVictoryAttrition();
605                 }
606                 if (Board::HaltResult(result))
607                         break;
608
609                 if (theBoard.MobilePieces(Piece::RED) == 0)
610                         result = MovementResult::DRAW;
611
612                 if (theBoard.MobilePieces(Piece::RED) == 0)
613                 {
614                         if (theBoard.MobilePieces(Piece::BLUE) == 0)
615                                 result = MovementResult::DRAW;
616                         else
617                                 result = MovementResult::VICTORY_ATTRITION;
618                         break;                  
619                 }
620
621                 if (stallTime >= 0)
622                         Wait(stallTime);
623                 else
624                         ReadUserCommand();
625         
626                 ++moveCount;
627
628                 ++turnCount;
629         }
630
631         if ((maxTurns >= 0 && turnCount >= maxTurns) && result == MovementResult::OK)
632         {
633                 result = MovementResult::DRAW_DEFAULT;
634         }
635
636         
637         return result;
638
639                 
640
641 }
642
643 /**
644  * Logs a message to the game's log file if it exists
645  * @param format the format string
646  * @param additional parameters - printed using va_args
647  * @returns the result of vfprintf or a negative number if the log file does not exist
648  */
649 int Game::logMessage(const char * format, ...)
650 {
651         if (log == NULL)
652                 return -666;
653                 va_list ap;
654         va_start(ap, format);
655
656         int result = vfprintf(log, format, ap);
657         va_end(ap);
658
659         return result;
660 }
661
662 /**
663  * Waits for a user command
664  * Currently ignores the command.
665  */
666 void Game::ReadUserCommand()
667 {
668         fprintf(stdout, "Waiting for user to press enter... (type QUIT to exit)\n");
669         string command("");
670         for (char c = fgetc(stdin); c != '\n' && (int)(c) != EOF; c = fgetc(stdin))
671         {
672                 command += c;
673         }
674
675         if (command == "QUIT")
676         {
677                 fprintf(stdout, "Ordered to quit... exiting...\n");
678                 exit(EXIT_SUCCESS);
679         }
680 }
681
682 MovementResult FileController::QuerySetup(const char * opponentName, std::string setup[])
683 {
684
685         char c = fgetc(file);
686         name = "";
687         while (c != ' ')
688         {
689                 name += c;
690                 c = fgetc(file);
691         }
692
693         while (fgetc(file) != '\n');
694
695         for (int y = 0; y < 4; ++y)
696         {
697                 setup[y] = "";
698                 for (int x = 0; x < Game::theGame->theBoard.Width(); ++x)
699                 {
700                         setup[y] += fgetc(file);
701                 }
702
703                 if (fgetc(file) != '\n')
704                 {
705                         return MovementResult::BAD_RESPONSE;
706                 }
707         }
708         return MovementResult::OK;
709
710         
711 }
712
713 MovementResult FileController::QueryMove(std::string & buffer)
714 {
715         //This bit is kind of hacky and terrible, and yes I am mixing C with C++
716         //Yes I should have used fstream for the whole thing and it would be much easier.
717         //Oh well.
718
719         char buf[BUFSIZ];
720
721         fgets(buf, sizeof(buf), file);
722         char * s = (char*)(buf);
723         while (*s != ':' && *s != '\0')
724                 ++s;
725         
726         //Move forward to the start of the move information
727         for (int i=0; i < 2; ++i)
728         {
729                 if (*s != '\0' && *s != '\n')
730                         ++s;
731         }
732         
733         //Unfortunately we can't just copy the whole line
734         buffer = string(s);
735         //We have to remove the movement result tokens
736         
737
738         vector<string> tokens;
739         Game::Tokenise(tokens, buffer, ' ');
740         buffer.clear();
741
742         if (tokens.size() < 1)
743                 return MovementResult::BAD_RESPONSE;
744         buffer += tokens[0];
745
746         
747         if (tokens[0] == "NO_MOVE") //tokens[0] is either the x coordinate, or "NO_MOVE"
748                 return MovementResult::OK;
749         if (tokens.size() < 2)
750                 return MovementResult::BAD_RESPONSE;
751         buffer += " ";
752         buffer += tokens[1]; //The y coordinate
753         buffer += " ";
754         buffer += tokens[2]; //The direction
755         
756         //Check for a possible multiplier. If tokens[3] is an integer it will be the multiplier, otherwise it won't be.
757         if (tokens.size() > 3 && atoi(tokens[3].c_str()) != 0)
758         {
759                 buffer += " ";
760                 buffer += tokens[3];
761         }
762         else
763         {
764                 //(tokens[3] should include a new line)
765                 //buffer += "\n";
766         }
767
768         
769
770         
771         
772         
773         return MovementResult::OK;
774 }
775
776 /**
777  * Tokenise a string
778  */
779 int Game::Tokenise(std::vector<string> & buffer, std::string & str, char split)
780 {
781         string token = "";
782         for (unsigned int x = 0; x < str.size(); ++x)
783         {
784                 if (str[x] == split && token.size() > 0)
785                 {
786                         buffer.push_back(token);
787                         token = "";
788                 }
789                 if (str[x] != split)
790                         token += str[x];
791         }
792         if (token.size() > 0)
793                 buffer.push_back(token);
794         return buffer.size();
795 }
796
797 /**
798  * Creates Controller baseds off strings. Takes into account controllers other than AI_Controller.
799  * @param redPath - Either the path to an AI_Controller compatable executable, or one of %human or %network or %network:[IP_ADDRESS]
800  * @param bluePath - Ditto
801  * Sets this->red to a controller using redPath, and this->blue to a controller using bluePath
802  * TODO: Make nicer (this function should be ~half the length)
803  */
804 void Game::MakeControllers(const char * redPath, const char * bluePath)
805 {
806         Network * redNetwork = NULL;
807         Network * blueNetwork = NULL;
808         //To allow for running two network controllers (I don't know why you would, but beside the point...) use two ports
809         static const int port1 = 4560;
810         static const int port2 = 4561;
811
812         if (redPath[0] == '@')
813         {
814                 if (strcmp(redPath, "@human") == 0)
815                         red = new Human_Controller(Piece::RED, graphicsEnabled);
816                 else
817                 {
818                         const char * network = strstr(redPath, "@network");
819                         if (network == NULL)
820                         {
821                                 red = NULL;
822                                 return;
823                         }
824                         network = strstr(network, ":");
825                 
826                         if (network == NULL)
827                         {
828                                 logMessage("Creating server for red AI... ");
829                                 redNetwork = new Server(port1);
830                                 logMessage("Successful!\n");
831
832                         }
833                         else
834                         {
835                                 network = (const char*)(network+1);
836                                 logMessage("Creating client for red AI... ");
837                                 redNetwork = new Client(network, port2);
838                                 logMessage("Connected to address %s\n", network);
839                         }
840
841                         logMessage("    (Red's responses will be received over the connection)\n");
842                         red = new NetworkReceiver(Piece::RED, redNetwork);
843                 }               
844         }
845         else
846                 red = new AI_Controller(Piece::RED, redPath, timeoutTime);
847
848         if (bluePath[0] == '@')
849         {
850                 if (strcmp(bluePath, "@human") == 0)
851                         blue = new Human_Controller(Piece::BLUE, graphicsEnabled);
852                 else
853                 {
854                         const char * network = strstr(bluePath, "@network");
855                         if (network == NULL)
856                         {
857                                 blue = NULL;
858                                 return;
859                         }
860                         network = strstr(network, ":");
861                 
862                         if (network == NULL)
863                         {
864                                 logMessage("Creating server for blue AI... ");
865                                 blueNetwork = new Server(port2);
866                                 logMessage("Successful!\n");
867
868                         }
869                         else
870                         {
871                                 network = (const char*)(network+1);
872                                 logMessage("Creating client for blue AI... ");
873                                 blueNetwork = new Client(network, port1);
874                                 logMessage("Connected to address %s\n", network);
875                         }
876                         logMessage("    (Blue's responses will be received over the connection)\n");
877                         blue = new NetworkReceiver(Piece::BLUE, blueNetwork);
878                 }               
879         }
880         else
881                 blue = new AI_Controller(Piece::BLUE, bluePath, timeoutTime);
882
883         if (redNetwork != NULL)
884         {
885                 
886                 blue = new NetworkSender(Piece::BLUE,blue, redNetwork);
887                 logMessage("    (Blue's responses will be copied over the connection)\n");
888         }
889         if (blueNetwork != NULL)
890         {
891                 
892                 red = new NetworkSender(Piece::RED, red, blueNetwork);
893                 logMessage("    (Red's responses will be copied over the connection)\n");
894         }
895
896         red->FixName(); blue->FixName();
897         
898 }
899
900 string itostr(int i)
901 {
902         stringstream s;
903         s << i;
904         return s.str();
905 }
906

UCC git Repository :: git.ucc.asn.au