示例#1
0
文件: AI.cpp 项目: Ubspy/Tic-Tac-Toe
aiMove AI::getBestMove(Board& board, int player) {

	int rv = board.checkVictory();

	if (rv == _aiPlayer) {
		return aiMove(10);
	} else if (rv == _humanPlayer) {
		return aiMove(-10);
	} else if(rv == TIE_VAL) {
		return aiMove(0);
	}

	std::vector<aiMove> moves;

	for (int y = 0; y < board.getSize(); y++) {
		for (int x = 0; x < board.getSize(); x++) {
			if (board.getVal(x, y) == NO_VAL) {
				aiMove move;
				move.x = x;
				move.y = y;
				board.setVal(x, y, player);
				if (player == _aiPlayer) {
					move.score = getBestMove(board, _humanPlayer).score;
				} else {
					move.score = getBestMove(board, _aiPlayer).score;
				}

				moves.push_back(move);
				board.setVal(x, y, NO_VAL);
			}
		}
	}

	int bestMove = 0;
	if (player == _aiPlayer) {
		int bestScore = -10000000;
		for (int i = 0; i < moves.size(); i++) {
			if (moves[i].score > bestScore) {
				bestMove = i;
				bestScore = moves[i].score;
			}
		}
	} else {
		int bestScore = -10000000;
		for (int i = 0; i < moves.size(); i++) {
			if (moves[i].score < bestScore) {
				bestMove = i;
				bestScore = moves[i].score;
			}
		}
	}
	return moves[bestMove];
}
示例#2
0
//Checks if game is over and handles the result
void Game::OnLoop() {
	bool emptyCells = haveEmptyCells();

	//If playing against computer and it is AI turn and there are still empty grid cells
	if (!roundOver && gameType == 1 && currentPlayer == 1 && emptyCells) {
		aiMove();
	}

	checkForWin();

	if (!roundOver && emptyCells) {
		return;
	}
	//No empty cells left, check for win or draw
	onGameOver();
};
示例#3
0
int main(int argc, char* argv[]) {

#if defined(WIN32)
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif
	chess::Engine* engine = new chess::Engine();
	int player = 1;
	engine->startup(player);
	unsigned char board[90];
	int state = engine->getState(board);
	while ((state & 0xf) < 3) {
		showBoard(board);
		if (engine->getPlayer() == player) {
			if (!youMove(engine))
				break;
		} else {
			if (!aiMove(engine))
				break;
		}
		state = engine->getState(board);
	}
	showBoard(board);
	if ((state & 0xF) == chess::Engine::BLACK_WIN) {
		if (player == 1)
			printf("You win!\n");
		else
			printf("You lost!\n");
	} else if ((state & 0xF) == chess::Engine::RED_WIN) {
		if (player == 0)
			printf("You win!\n");
		else
			printf("You lost!\n");
	} else if ((state & 0xF) == chess::Engine::DRAW) {
		printf("Draw with computer!\n");
	} else {
		printf("User cancel or error!\n");
	}
	
	delete engine;
#if defined(WIN32)
	_CrtDumpMemoryLeaks();
#endif
	return 0;
}
示例#4
0
文件: main.c 项目: Xenocidel/Chess
int main(){
	int in_game=0;
	int turnPre=0;
	int mode=-1;	 	/*range 1-3*/
	int diff=-1; 		/*range 0-3, 0 if pvp*/
	int timer=-1;		/*range 0, 5, 10, 20*/
	int side=-1;        /*range '0' for white, '1' for black*/
	int all41 = -1;		/* range 0-5 depending on piece */
	char confirm='n';	/*range 'n', 'y'*/
	char modeS[26];
	char diffS[26];
	char timerS[26];
	board *board = createNewGame();
	int timer1 = 0;
	int timer2 = 0;
	int timer3 = 0;
	int timer4 = 0;
	int timer5 = 0;
	int altcounter = 1;
	do{	/*game setup*/
		printf("\nChess v1.0 by nøl / C Gets Degrees\n\n");
		while (mode < 1){
			printf("Please select game mode:\n");
			printf("1. Player versus Player\n");
			printf("2. Player versus Computer\n");
			printf("3. Computer versus Computer\n\n");
			scanf("%d", &mode);
			switch(mode){
				case 1:
					printf("Player versus Player selected\n");
					break;
				case 2:
					printf("Player versus Computer selected\n\n");
					printf("Choose a side: White(0) or Black(1)?\n");
					scanf("%d", &side);
					switch(side){
						case 0:
							printf("White selected\n");
							break;
						case 1:
							printf("Black selected\n");
							break;
						default:
							printe(selection);
							side = -1;
							break;
					}
					break;
				case 3:
					printf("Computer versus Computer selected\n");
					break;
				default:
					printe(selection);
					mode = -1;
					break;
			}
		}
		while (all41 < 0){
			printf("\nPlease select game type. All-for-One mode creates all pieces of the same type!\n");
			printf("0. Standard Chess\n");
			printf("1. All-for-Pawn\n");
			printf("2. All-for-Knight\n");
			printf("3. All-for-Queen\n");
			printf("4. All-for-Rook\n");
			printf("5. All-for-Bishop\n");
			scanf("%d", &all41);
			switch(all41){
				case 0:
					printf("Standard chess selected\n");
					break;
				case 1:
					printf("All-for-Pawn selected\n");
					break;
				case 2:
					printf("All-for-Knight selected\n");
					break;
				case 3:
					printf("All-for-Queen selected\n");
					break;
				case 4:
					printf("All-for-Rook selected\n");
					break;
				case 5:
					printf("All-for-Bishop selected\n");
					break;
				default:
					printe(selection);
					all41 = -1;
					break;
			}
		}
		while (diff < 0){
			if (mode == 1){
				diff = 0;
				break;
			}
			printf("\nPlease select computer difficulty:\n");
			printf("1. Easy\n");
			printf("2. Medium\n");
			printf("3. Hard\n\n");
			scanf("%d", &diff);
			switch(diff){
				case 1:
					printf("Easy selected\n");
					break;
				case 2:
					printf("Medium selected\n");
					break;
				case 3:
					printf("Hard selected\n");
					break;
				default:
					printe(selection);
					diff = -1;
					break;
			}
		}
		while (timer < 0){
			printf("\nPlease select game timer length:\n");
			printf("0. No limit\n");
			printf("5. 5 minutes\n");
			printf("10. 10 minutes\n");
			printf("20. 20 minutes\n\n");
			scanf("%d", &timer);
			switch(timer){
				case 0:
					printf("No limit selected\n");
					timer = 0;
					break;
				case 5:
					printf("5 minutes selected\n");
					timer1 = timer*60;
					timer3 = timer*60;
					break;
				case 10:
					printf("10 minutes selected\n");
					timer1 = timer*60;
					timer3 = timer*60;
					break;
				case 20:
					printf("20 minutes selected\n");
					timer1 = timer*60;
					timer3 = timer*60;
					break;
				default:
					printe(selection);
					timer1 = 0;
					timer3 = 0;
					timer = -1;
					break;
			}
		}
		/*CREATE STRINGS FOR SELECTIONS*/
		switch(mode){
			case 1:
				strcpy(modeS, "Player versus Player");
				break;
			case 2:
				strcpy(modeS, "Player versus Computer");
				break;
			case 3:
				strcpy(modeS, "Computer versus Computer");
				break;
		}
		switch(diff){
			case 0:
				strcpy(diffS, "");
				break;
			case 1:
				strcpy(diffS, "\nDifficulty: Easy");
				break;
			case 2:
				strcpy(diffS, "\nDifficulty: Medium");
				break;
			case 3:
				strcpy(diffS, "\nDifficulty: Hard");
				break;
		}
		switch(timer){
			case 0:
				strcpy(timerS, "No time limit");
				break;
			case 5:
				strcpy(timerS, "5 minutes");
				break;
			case 10:
				strcpy(timerS, "10 minutes");
				break;
			case 20:
				strcpy(timerS, "20 minutes");
				break;
		}
		/*CONFIRM SELECTIONS*/
		printf("\n\nPlease confirm selections: [y/n]\n\n");
		printf("Mode: %s", modeS);
		printf("%s", diffS);
		printf("\nTimer: %s\n\n", timerS);
		scanf(" %c", &confirm);

		if (confirm == 'y' || confirm == 'Y'){
			in_game = 1;
			fgetc(stdin); /* absorb the /n produced by the last scanf */
			createMoveLog();
		}
		else if (confirm == 'n' || confirm == 'N'){
			mode = -1;
			side = -1;
			diff = -1;
			timer = -1;
			all41 = -1;
		}
		else{
			printe(selection);
		}
		
		int aiTeam1, aiTeam2;
		if(mode == 2){ /* Inverts input value 0 -> 1, 1 -> 0, other input will cause assertion failure */
			aiTeam1 = oppTeam(side); /* oppTeam function comes from ai.c. Reads an int, returns an int. */
		}
		if(mode == 3){ /* Default for CPU vs CPU */
			aiTeam1 = 0;
			aiTeam2 = 1;
		}
		
		while(in_game){ /* if side = 1, player is black */
			if (timer != 0){
				/* set up timer */
				if (altcounter % 2 != 0){
					timer5 = timer4 - timer2;
					timer1 = timer1 - timer5;
					altcounter = altcounter+1;
				}
				else{
					timer5 = timer4 - timer2;
					timer3 = timer3 - timer5;
					altcounter = altcounter+1;
				}
				if (timer1 <= 0){
				printf("\nWhite has run out of time!\n");
				exit(0);
				}
				if (timer3 <= 0){
					printf("\nBlack has run out of time!\n");
					exit(0);
				}
			}
			int alpha;
			cell *tmp1;
			switch(all41){
				case 0:
				break;
				case 1:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = pawn;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 2:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = knight;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 3:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = queen;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 4:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = rook;
							updatePrintPiece(tmp1);
						}
					}
					break;
				case 5:
					for(alpha = 0; alpha <64; alpha++){
						tmp1 = getCell(alpha, board);
						if (tmp1->piece != NULL && tmp1->piece->type != king){
							tmp1->piece->type = bishop;
							updatePrintPiece(tmp1);
						}
					}
					break;
			}
			
			turnPre = board->turn;
			timer2 = (int) time(NULL);
			updateGameDisplay(board); /* display the entire board only when its a new turn */
			while (turnPre == board->turn){
				cell *temp;
				switch(mode){
					case 1: /* PvP */ 
						updateMessage(board);
						/*board->turn++;*/
						break;
					case 2: /* P vs AI */
						if(board->turn%2 == aiTeam1){ /* AI's turn */
							printMessage(board->turn);
							if (board->turn == 0){
								temp = getCell(12, board);
								movePiece(temp->piece, getCell(20, board));
								temp = NULL;
							}
							else if (board->turn == 1){
								temp = getCell(52, board);
								movePiece(temp->piece, getCell(44, board));
							}
							else if (board->turn == 2){
								temp = getCell(3, board);
								movePiece(temp->piece, getCell(21, board));
							}
							else if (board->turn == 3){
								temp = getCell(59, board);
								movePiece(temp->piece, getCell(45, board));
							}
							else if (board->turn == 4){
								temp = getCell(5, board);
								movePiece(temp->piece, getCell(26, board));
							}
							else if (board->turn == 5){
								temp = getCell(61, board);
								movePiece(temp->piece, getCell(34, board));
							}
							else if (board->turn == 6){
								temp = getCell(21, board);
								movePiece(temp->piece, getCell(53, board));
							}
							else if (board->turn == 7){
								temp = getCell(45, board);
								movePiece(temp->piece, getCell(13, board));
							}
							else{
								aiMove(diff, aiTeam1, board);
							}
						}
						else{
							/* player's turn */
							updateMessage(board);
							/*board->turn++;*/
						}
						break;
					case 3: /* AI vs AI*/
						if(board->turn%2 == 0){ /* White's turn */
							/* aiTeam1 goes */
							printMessage(board->turn);
							aiMove(diff, aiTeam1, board);
							/*board->turn++;*/
						}
						else{ /* Black's turn */
							/* aiTeam2 goes */
							printMessage(board->turn);
							aiMove(diff, aiTeam2, board);
							/*board->turn++;*/
						}
						break;
				}
				/* Exits loop when turn is finished */
			}
			timer4 = (int) time(NULL);
			if (timer != 0 && board->turn > 1){
				printf("DEBUG: Current time: %d\n", timer4);
				printf("DEBUG: Current time: %d\n", timer2);
				printf("Time remaining for Player 1: %d seconds.\n", timer1);
				printf("Time remaining for Player 2: %d seconds.\n", timer3);
			}
		}
			
	}
	while(!in_game);
	
		
	return 0;
}
示例#5
0
/******************************************************
* PONG
* DESCRIPTION: JConsole2 Portable implementation of pong
* Created: 8/28/2013
******************************************************/
void Pong(char autoAi)
{
   char hit = 0;
   char pong_ball_start = 0;
   unsigned int userScore = 0;
   unsigned int compScore = 0;
   unsigned int highScore = EEProm_Read_16(pongHighScore);
   unsigned int ballSpeed = PONG_INITIALBALLSPEED;
   struct Paddle playerPaddle;
   struct Paddle aiPaddle;
   struct Solid ball;
   LcdClear();

   //Construct game objects
   constructPaddle2(&aiPaddle, 74, 1, 10);
   constructPaddle2(&playerPaddle, 7, 1, 10);
   displayPaddle(&playerPaddle, 0);
   displayPaddle(&aiPaddle, 0);
   displayPongScore(&userScore, &compScore);
   reset(&ball, 15, 1, 3, 3, 1);

   //Start timers
   StartTimer(0, PONG_PLAYERMOVETIME);  //Move player timer
   StartTimer(1, ballSpeed);  //Move player timer

   for (;;)
   {
	  if (CheckTimer(0))
	  {
		  if (GetDown())
		  {
		     paddle_moveDown(&playerPaddle);
		  }
		  else if (GetUp())
		  {
			  paddle_moveUp(&playerPaddle);
		  }
		  else if (GetEnterButton()) //Pause
		  {
			 if (Pause(showPongScore, userScore,  compScore, highScore) == 1)
			 {
			     return;
			 }
			 displayPaddle(&playerPaddle, 0);
			 displayPaddle(&aiPaddle, 0);
			 displaySolid(&ball, 0);
			 displayPongScore(&userScore, &compScore);
		  }
		  StartTimer(0, PONG_PLAYERMOVETIME);  //Move player timer
	  }
      if (CheckTimer(1))
      {
         //If ball moves and hits a wall, make a sound
         if (autoMoveSolid(&ball) > 1)
         {
        	 SendData(SOUND_BLOCK_DESTROYED);
         }
         aiMove(&aiPaddle, &ball); //Move computer players paddle
         if (autoAi == 1)
         {
            aiMove(&playerPaddle, &ball);
         }
         hit = checkForHit(&aiPaddle, &ball) + checkForHit(&playerPaddle, &ball);   //Check to see if ball hit either paddle
         if (hit != 0)
         {
        	 SendData(SOUND_BLOCK_DESTROYED);
        	displayPongScore(&userScore, &compScore);
        	if (ballSpeed > 10)
        	{
        	   ballSpeed = ballSpeed - 1;
        	}
         }
         //Ball hit on players side
         if (ball.xLocation == 1)
         {
            compScore++;
            displayPongScore(&userScore, &compScore);
            displayPaddle(&playerPaddle, 0);
            displayPaddle(&aiPaddle, 0);
            randomBallStart(&ball, &pong_ball_start);
         }
         //Ball hit on computers side
         else if (ball.xLocation == 76)
         {
            userScore++;
            displayPongScore(&userScore, &compScore);
            displayPaddle(&playerPaddle, 0);
            displayPaddle(&aiPaddle, 0);
            randomBallStart(&ball, &pong_ball_start);
            if (userScore > highScore)
            {
               highScore = userScore;
               EEProm_Write_16(highScore, pongHighScore);
            }
         }
         StartTimer(1, ballSpeed);  //Move player timer
      }
   }

}
示例#6
0
/**
* Hauptmethode
*/
int main(int argc, char *argv[]) {
	hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
	char o;
	char boardMode = 0; // 0/1
	char fullScreen = 1;
	char from[] = "??";
	char to[] = "??";
	char filename[255];
	char moves[28 * 16 * 2]; // keine Initialiserung!
	short movesCounter = 0;
	short board[120];
	int eval;
	int okay;
	int i;

	struct GameState gameState;
	struct GameState gameStateCopy;
	createStartBoard(board);
	setGameState(&gameState, board, 0, 3, 4);

	srand((unsigned int) time(NULL));  // Zufallsgenerator initialisieren

	if (fullScreen) system("cls");

	do {
		printf("\nSpieler: %i, Halbzug: %i\n", gameState.turnNumber % 2, gameState.turnNumber);
		printBoard(gameState.board, 0, boardMode);

		COLOR(128);
		printf("\n> Kommando:");
		COLOR(COLOR_DEFAULT);
		printf(" ");
        scanf("%c", &o); // Auf Char scannen
        fflush(stdin);

        if (fullScreen && o != 'm') system("cls");

        switch (o) {
        	case 'x':
        		// "magic" move - alles ist moeglich. Auch, Fehler zu produzieren.
        	case 'm':
        		printf("Zug von: ");
        		scanf("%s", from);
        		fflush(stdin);

        		printf("Zug nach: ");
        		scanf("%s", to);
        		fflush(stdin);

        		if (strlen(from) != 2 || strlen(to) != 2) {
        			printError("Ungueltige Koordinaten!\n");
        		} else {
        			autoSave(&gameState);
        			if (o == 'x') {
						doMovePartial(&gameState, convertCoordToIndex(from), convertCoordToIndex(to));
						doMoveFinal(&gameState, convertCoordToIndex(from), convertCoordToIndex(to));
        			} else {
        				if (doUserMove(&gameState, convertCoordToIndex(from), convertCoordToIndex(to))) system("cls");
        			}
        		}
        		break;
        	case 'n':
        		gameState.turnNumber--;
				printInfo("Zug zurueck.\n");
        		break;
        	case 'a':
        		do {
        			autoSave(&gameState);
        			okay = aiMove(&gameState, 0);
        		} while (autoMode && okay && ((gameState.turnNumber % 2 == 0 && gameState.ai0) || (gameState.turnNumber % 2 == 1 && gameState.ai1)));
        		break;
        	case 'c':
        		printInfo("Schach: %i\n", isCheck(&gameState));
        		break;
        	case 'h':
        		printHistory();
        		break;
        	case 'g':
        		generateMoves(&gameState, moves, &movesCounter);
        		printInfo("%i moegliche Zuege (ohne Beruecksichtigung von Schach).\n", movesCounter / 2);
				for (i = 0; i < movesCounter; i += 2) {
					printf("Zug mit %i von %i nach %i.\n", gameState.board[moves[i]], moves[i], moves[i + 1]);
				}
        		break;
        	case 'v':
        		eval = evaluateBoard(gameState.board);
        		printInfo("Evaluation (aus Sicht von weiss): %i\n", eval);
        		break;
        	case 't':
        		copyGameState(&gameState, &gameStateCopy);
    			okay = aiMove(&gameStateCopy, 3);
        		break;
        	case 'o':
        		okay = loadOpeningBookMove(&gameState, from, to);
        		if (okay) {
        			printInfo("Zugvorschlag aus dem Eroeffnungsbuch: mit %c von %s nach %s", getPieceSymbolAsChar(gameState.board[convertCoordToIndex(from)]), from, to);
        		} else {
        			printInfo("Das Eroeffnungsbuch enthaelt keinen passenden Zug!");
        		}
        		break;
        	case 's':
        		saveGame(&gameState, "quicksave", 1);
        		break;
        	case 'r':
				loadGame(&gameState, "quicksave");
        		break;
        	case 'l':
        		system("dir savegames\\*.sav /B");
				printf("\nLade Datei (Endung nicht angeben):\n");
				scanf("%s", filename);
				fflush(stdin);

				loadGame(&gameState, filename);
        		break;
        	case 'u':
        		loadAutoSave(&gameState);
        		break;
        	case 'b':
        		boardMode = (1 - boardMode);
        		printInfo("Brettdarstellung gewechselt auf: %i\n", boardMode);
        		break;
        	case 'd':
        		debugMode = (1 - debugMode);
        		printInfo("Debugmodus gewechselt auf: %i\n", debugMode);
        		break;
        	case '?':
        		printf("m (move)\tEinen Zug durchfuehren.\n");
        		printf("n (next)\tDen Spieler wechseln (ohne Zug, regelwidrig!)\n");
        		printf("a (ai)\t\tKI einen Zug durchfuehren lassen.\n");
        		printf("h (history)\tDen Spielverlauf anzeigen.\n");
        		printf("c (check)\tStellung auf Schach pruefen.\n");
        		printf("g (generate)\tMoegliche Zuege anzeigen lassen.\n");
        		printf("v (value)\tBewertung der Stellung anzeigen lassen.\n");
        		printf("t (tip)\t\tDie KI einen Zug-Tip anzeigen lassen.\n");
        		printf("s (save)\tQuicksave-Spielstand anlegen.\n");
        		printf("r (reload)\tQuicksave-Spielstand laden.\n");
        		printf("l (load)\tSpielstand laden (Dateiname angeben).\n");
        		printf("u (undo)\tLetzten Zug zuruecknehmen.\n");
        		printf("b (board)\tBrettdarstellung wechseln (fuer Debuggging).\n");
        		printf("d (open)\tDebugausgaben aktivieren/deaktivieren.\n");
        		printf("? (help)\tDiese Hilfe zu den Kommandos anzeigen lassen.\n");
        		printf("e (exit)\tDas Programm beenden.\n");
        		break;
        	case 'e':
        		// do nothing
        		break;
        	case '\n':
        		// do nothing
        		break;
        	default:
        		printError("Unbekannter Operator: %c\n", o);
        		break;
        }
        fflush(stdin);
	} while (o != 'e');

	return 0;
}