// TticTacToe.cpp - Use: http://localhost/CGI/tictactoe.exe #include #include #include #include extern "C" int STRindex( char p[], char s[]) { int pl = strlen(p), sl = strlen(s); int pi = 0, si = 0; do { if(p[pi] == s[si]) { pi++; si++; } else { pi = 0; si++; } } while (pi < pl && si < sl); if (pi == pl) return si-pl; else return -1; } extern "C" void STRcpy(char s1[], char s2[]) { int i1=0, i2=0; while( s1[i1] != '\0') s2[i2++] = s1[i1++]; s2[i2] = '\0'; } extern "C" int endgame(char board[]) { for (int i=0; i<=8; i++) if (board[i]==(char)(i+'0')) return 0; return 1; } char * render(char message[], char board[]) { char *result=new char[128]; char move[]=" | | \n
"; char line[]="_|_|_\n
"; STRcpy(message, result); for (int i = 0; i<=5; i=i+3) { move[0]=board[i]; move[2]=board[i+1]; move[4]=board[i+2]; STRcpy(move,result+strlen(result)); STRcpy(line,result+strlen(result)); } move[0]=board[6]; move[2]=board[7]; move[4]=board[8]; STRcpy(move,result+strlen(result)); return result; } char * place(char symbol, char move, char board[]) { int i = (int)(move - '0'); if (i >= 0 && i <= 8) if (board[i] == move) { board[i] = symbol; return render("\n
", board); } return render("Bad move!\n
", board); } char * process(char clientinput[]) { char board[10]; char *result = new char[500]; char *game; char move; int index; if(clientinput == NULL) clientinput = ""; // Build browser controls STRcpy("TicTacToe\n
Enter Move X.
", result);
	STRcpy("
", result+strlen(result)); STRcpy("\n",result+strlen(result)); // If no board variable, new game if((index=STRindex("board=", clientinput)) == -1) { STRcpy("
\n", result+strlen(result)); STRcpy(render("", "012345678"), result+strlen(result)); } else { // Old game, get current board & move for(int i=0; i<=8; i++) board[i] = clientinput[index+6+i]; board[9]='\0'; index = STRindex("move=", clientinput); move = clientinput[index+5]; if(!endgame(board)) // Place x on game board game = place('x', move, board); // game contains HTML of board else { STRcpy("012345678", board); // Game over, initialize board empty game = "Game Over"; STRcpy("New Game. o moves.
\n", result+strlen(result)); } if (!endgame(board) && STRindex("Bad", game) == -1) // If X move OK make O move do { // Random move game = place('o', (char)(rand()%9)+'0', board); } while (STRindex("Bad", game) >= 0); STRcpy(game,result+strlen(result)); // Copy current game board STRcpy("
", result+strlen(result)); // Copy HTML for board variable STRcpy("\n",result+strlen(result)); } return result; } // // TicTacToe server on Port 80 void main(void) { char input[4096]; int length; cout << "Content-type: text/html\n\n"; sscanf( getenv("CONTENT_LENGTH"), "%d", &length); for (int i=0; i> input[i]; input[length]='\0'; cout << input << "
"; cout << process(input); }