Esempio n. 1
0
int main(void){
    int dimension;
    char board[26][26];
    int i,j;
    int out = 0;
    char row, col;
    char colour, diffColour;
    int deltaRow, deltaCol;
    int copy[26][26];
    printf("Enter the board dimension: ");
    scanf("%d",&dimension);
    
    
    for (i=0;i<dimension;i++){
        for (j=0;j<dimension;j++)
            board[i][j]='U';    //first set all the elements 'U'
    }
    
    
    board[dimension/2-1][dimension/2-1] = 'W';
    board[dimension/2-1][dimension/2] = 'B';
    board[dimension/2][dimension/2-1] = 'B';
    board[dimension/2][dimension/2] = 'W';  //define array in the range of dimension
    
    for(i=0;i<dimension;i++){
        for(j=0;j<dimension;j++){
            copy[i][j]=0;
        }
    }
    
    printf("Computer plays (B/W) : ");
    scanf(" %c",&colour);
    printBoard(board, dimension);   //print the board out
    
    if (colour == 'W')
        diffColour = 'B';
    if (colour == 'B')
        diffColour = 'W';
    
    if (colour == 'W'){
        printf("Enter move for colour %c (RowCol): ", diffColour);
        scanf(" %c %c", &row, &col);
        if (checkLegal(dimension, board, row, col, diffColour) == false){
            printf("Invalid move.\n%c player wins.",colour);
            return EXIT_SUCCESS;
        }
        else{
            board[row-'a'][col-'a']= diffColour;
            flipAllAfterLegal(dimension, board, diffColour, row, col);
            printBoard(board, dimension);
        }
    }
    
    
    
    while (out<1) {
        
        if (haveMove(dimension, board, colour)==true)
            
            changeBestMove(dimension, board, copy, colour);
            
        
        else{
            if (haveMove(dimension, board, diffColour)==true){
                printf("%c player has no valid move.\n",colour);
            }
            else{
                finalCompare(dimension, board, colour, diffColour);
                return EXIT_SUCCESS;
            }
        }
       
        
        
        if (haveMove(dimension, board, diffColour)==true){
            printf("Enter move for colour %c (RowCol): ", diffColour);
            scanf(" %c %c", &row, &col);
            if (checkLegal(dimension, board, row, col, diffColour) == false){
                printf("Invalid move.\n%c player wins.",colour);
                return EXIT_SUCCESS;
            }
            else{
                board[row-'a'][col-'a']= diffColour;
                flipAllAfterLegal(dimension, board, diffColour, row, col);
                printBoard(board, dimension);
            }
        }
        
        
        else{
            if (haveMove(dimension, board, colour)==true){
                printf("%c player has no valid move.\n", diffColour);
            }
            else{
                finalCompare(dimension, board, colour, diffColour);
                return EXIT_SUCCESS;
            }
        }
    }
}
Esempio n. 2
0
/**
* Testet einen GameState auf Schach fuer den Spieler, der am Zug ist.
* Gibt den Typ (ohne Vorzeichen) der Schachfigur zurueck, die den Koenig unter Schach setzt.
*/
char isCheck(struct GameState *gs) {
	short directions[8];
	char player = (*gs).turnNumber % 2;
	char owner = 0;
	char from = 0;
	char found = 0;
	char pieceType = 0;
	char i;
	char moveCounter;

	for (i = innerBoardMin; i <= innerBoardMax; i++) {
		if (((*gs).board[i] == 6 && player == 0) || ((*gs).board[i] == -6 && player == 1)) {
			from = i;
			break;
		}
	}

	if (from == 0) { 
		printError("Fehler bei Bewertung: Kein Koenig gefunden - wurde er regelwidrig geschlagen?!\n"); // DEBUG
		printError("Stellung:\n");
		
		printBoard((*gs).board, 0, 0);
		exit(1);
	}

	directions[0] = -10; directions[1] = -1; directions[2] = +1; directions[3] = +10; 
	directions[4] = -11; directions[5] = -9; directions[6] = +9; directions[7] = +11; 

	for (char d = 0; d < 8 && directions[d] != 0; d++) {
		moveCounter = 0;
		for (i = from + directions[d]; (*gs).board[i] != 7; i += directions[d]) {
			moveCounter++;

			owner = getOwner(gs, i);

			if (owner == player) break; // eigene Figur gefunden
			if (owner == (1 - player)) { // gegnerische Figur gefunden. Pruefen, ob diese das Feld bedroht:
				pieceType = abs((*gs).board[i]);
				switch (pieceType) {
					case 6: // Koenig
						if (moveCounter == 1) return pieceType;
						break;
					case 5: // Dame
						return pieceType;
						break;
					case 4: // Turm
						if (directions[d] == 10 || directions[d] == -10 || directions[d] == 1 || directions[d] == -1) return pieceType;
						break;
					case 3: // Laeufer
						if (directions[d] == 11 || directions[d] == -11 || directions[d] == 9 || directions[d] == -9) return pieceType;
						break;
					case 2: // Springer
						break; // wird nachher seperat betrachtet
					case 1: // Bauer
						if (player == 0) { // weiss
							if ((directions[d] == -11 || directions[d] == -9) && moveCounter == 1) return pieceType;
						} else {
							if ((directions[d] == 11 || directions[d] == 9)  && moveCounter == 1) return pieceType;
						}
						break;
				}
				break; // Suche in diese Richtung abbrechen
			}
		}
	}

	// Springer ueberpruefen
	short sign = 2;
	if (player == 0) sign = -2; // bei weiss haben gegnerische Figuren ein Minus vor ihrem Wert
	if ((*gs).board[from - 21] == sign) return 2;
	if ((*gs).board[from - 19] == sign) return 2;
	if ((*gs).board[from - 12] == sign) return 2;
	if ((*gs).board[from - 8] == sign) return 2;
	if ((*gs).board[from + 8] == sign) return 2;
	if ((*gs).board[from + 12] == sign) return 2;
	if ((*gs).board[from + 19] == sign) return 2;
	if ((*gs).board[from + 21] == sign) return 2;

	return 0;
}
Esempio n. 3
0
bool traps(int n, char board[21][21], bool humanPlayer, char humanPlayerC, char compPlayerC) {
    int bestScore = -1;
    int moveX = -1;
    int moveY = -1;
    char trapBoard[10][10];
    bool done = false;
    trap1(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap2(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap3(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap4(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap5(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap6(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap7(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap8(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 7))
        done = true;
    trap9(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap10(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap11(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap12(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap13(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap14(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap15(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap16(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap17(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap18(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    trap19(n, trapBoard);
    if (!done && nextTrap(n, board, humanPlayer, humanPlayerC, compPlayerC, trapBoard, &bestScore, &moveX, &moveY, 8))
        done = true;
    if (moveX == -1 && moveY == -1)
        return false;
    else if (board[moveX][moveY] == 'U') {
        board[moveX][moveY] = compPlayerC;
        printf("Computer moves %c at %d %d\n", compPlayerC, moveX, moveY);
        printBoard(n, board);
        return true;
    }
    return false;
}
Esempio n. 4
0
//todo - get string instead of char!
void PlayFullGame()
{
	isGameBoy = 1;
	char nextMoveAux;
	int lastPlayer = 0;
	
	numOfPlayers = mmap(NULL, sizeof (*numOfPlayers), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	*numOfPlayers = 0;

	gameHasEnded = mmap(NULL, sizeof (*gameHasEnded), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	*gameHasEnded = -1; // game will be over if gameHasEnded is != -1
	
	nextMove = mmap(NULL, sizeof(*nextMove), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);

	player = mmap(NULL, sizeof (*player), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	*player = 100;

	Currentplayer = mmap(NULL, sizeof (*Currentplayer), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	*Currentplayer = 0;

	a = mmap(NULL, sizeof (*a), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
	b = mmap(NULL, sizeof (*b), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);

	char* moduleName = "/dev/snake17";
	int status;
	int pid1 = fork();
	if(pid1 == 0) {
		char board[BUFFER_SIZE+1];
		board[BUFFER_SIZE] = '\0';
		//player 1 (white)
		*a=open(moduleName, O_RDWR);
		*numOfPlayers = *numOfPlayers +1;
		while(*gameHasEnded == -1)
		{
			if(*player == 1)
			{
				*player = 0;
				*Currentplayer = 1;
				read(*a, board, BUFFER_SIZE); //board before
				printButtonPress(board,nextMove);

				int res = write(*a,nextMove, 1);
				if(res < 0 ) {*gameHasEnded =1;}

				read(*a, board, BUFFER_SIZE);
				printBoard(board);
				*player = 100;
			}
		}
		_exit(0);
	} else {
		int pid2 = fork();
		if(pid2 == 0) {
			char board[BUFFER_SIZE];
			doLongTask();
			//player 2 (black)
			*b=open(moduleName, O_RDWR);
			*Currentplayer = -1;
			read(*b, board, BUFFER_SIZE);
			printBoard(board);
			*numOfPlayers = *numOfPlayers +1;
			while(*gameHasEnded == -1)
			{
				if(*player == -1)
				{
					*player = 0;
					*Currentplayer = -1;
					read(*b, board, BUFFER_SIZE);
					printButtonPress(board,nextMove);
					int res = write(*b,nextMove, 1);
					if(res < 0 ) {*gameHasEnded =1;}

					read(*b, board, BUFFER_SIZE);
					printBoard(board);
					*player = 100;
					*gameHasEnded = ioctl(*b, SNAKE_GET_WINNER);
				}
			}
			_exit(0);
		} else {
			printLogo();
			doLongTask();
			lastPlayer = -1;
			//manager
			while(*gameHasEnded == -1)
			{
				if(*player == 100 && *numOfPlayers==2)
				{
					char nm;
					scanf(" %c", &nm);
					if(nm != 'a' && nm != 'A' 
						&& nm != 's' && nm != 'S'
						&& nm != 'w' && nm != 'W'
						&& nm != 'd' && nm != 'D'

						&& nm != '2' && nm != '4'
						&& nm != '6' && nm != '8')
					{
						continue;
					}

					if (nm == 'w' || nm == 'W' || nm == '8')
					{     
						nextMoveAux = UP;
					}
					else if (nm == 's' || nm == 'S' || nm == '2')
					{
				    	nextMoveAux = DOWN;
					}
					else if (nm == 'a' || nm == 'A' || nm == '4')
					{
				    	nextMoveAux = LEFT;
					}
					else if (nm == 'd' || nm == 'D' || nm == '6')
					{
				    	nextMoveAux = RIGHT;
					}

					*nextMove = nextMoveAux; 
					*player = lastPlayer * (-1);
					lastPlayer = *player;
				}
			}
			printGameOver();
		    close(*a);
    		close(*b);	
			wait(&status);
		}
		wait(&status);
	}
	munmap(numOfPlayers, sizeof (*numOfPlayers));
	munmap(gameHasEnded, sizeof (*gameHasEnded));
	munmap(nextMove, sizeof (*nextMove));
	munmap(player, sizeof (*player));
	munmap(Currentplayer, sizeof (*Currentplayer));
	munmap(a, sizeof (*a));
	munmap(b, sizeof (*b));
}
void recvMsg(int sock, struct Message *recvmsg,struct Message *sendmsg){
  char data[MSGLEN];
  memset(data,0,MSGLEN);
  //recv(sock, data, MSGLEN, 0);
  read(sock, &data, MSGLEN);


  memset(recvmsg,0,sizeof(*recvmsg));
    memset(sendmsg,0,sizeof(*sendmsg));

  memcpy(recvmsg,data,sizeof(*recvmsg));
  //recvmsg=(struct Message*)data;
  recvmsg->board[10]='/0';
  printf("Msg after receiving : \n");
  printMsg(recvmsg);

  switch(recvmsg->type){
   case WHO:
    //create message to send back
	   printf("Enter your Handle:\n");

     sendmsg->type=HANDLE;
     scanf("%s",sendmsg->handle);
     sendmsg->handle[strlen(sendmsg->handle)]='\0';
     printf("sendmsg->handle[LEN]'s lenth is actually =%d\n",strlen(sendmsg->handle));
     printf("sendmsg->handle=%s\n",sendmsg->handle);
     sendMsg(sock,sendmsg);

  	break;
   case HANDLE:
    break;
   case MATCH:
    printf("your opponet is %s\n",recvmsg->opp_handle);
    printf("let's start game!\n");

    if (recvmsg->xoID==0){
      printf("you are o\n");
      printf("waiting for input request\n");


    }else if (recvmsg->xoID==1){
      printf("you are x\n");
      printf("waiting for input request\n");
    }
    break;
    case ASK_MOVE:
      if (recvmsg->xoID==0){
      printf("you are o\n");
      
      printf("please input the position according to remaining numbers in the board\n");
      printBoard(recvmsg->board);

      scanf ("%d",&(sendmsg->move));
      while ((sendmsg->move>10)||(sendmsg->move<0)||(recvmsg->board[sendmsg->move-1]=='o')||(recvmsg->board[sendmsg->move-1]=='x')){
        printf("invalid input \n");

        printf("please input the position according to remaining numbers in the board\n");
        printBoard(recvmsg->board);
        scanf ("%d",&(sendmsg->move));

      }


      sendmsg->type=MY_MOVE;
      printf("your move has been sent, waiting for opponet's move\n");
      sendMsg(sock,sendmsg);


    }else if (recvmsg->xoID==1){
      printf("you are x\n");
      printf("please input the position according to remaining numbers in the board\n");

      printBoard(recvmsg->board);
      scanf ("%d",&(sendmsg->move));
      while ((sendmsg->move>10)||(sendmsg->move<0)||(recvmsg->board[sendmsg->move-1]=='o')||(recvmsg->board[sendmsg->move-1]=='x')){
        printf("invalid input \n");

        printf("please input the position according to remaining numbers in the board\n");
        printBoard(recvmsg->board);
        scanf ("%d",&(sendmsg->move));

      }


      sendmsg->type=MY_MOVE;
      printf("your move has been sent, waiting for opponet's move\n");

      sendMsg(sock,sendmsg);
    }
    break;
    case RESULT:
      if (recvmsg->result==0){
        printf("you lose!\n");
      }else if (recvmsg->result==1){
        printf("you win!\n");
      }else if (recvmsg->result==-1){
        printf("A draw!\n");
      }
    break;

}
  
	
}
Esempio n. 6
0
void tutorial() {
    printf("Hnefatafl (also called Viking chess, King's Table, etc.) is a board game\n");
    printf("with two unequal sides; the attackers, whose goal is to capture the king\n");
    printf("by surrounding him, and the defenders, whose goal is to get their king to\n");
    printf("safety by moving him to one of the exits situated in each corner.\n\n");
    
    pauseForKeyPress();
    
    printf("The players alternate turns of moving a single piece. The pieces can move\n");
    printf("like rooks in chess, and capture by... you know what, it'd be easier to\n");
    printf("just show you.\n\n");
    
    pauseForKeyPress();
    
    TILE board[121];
    TILE a = {0}, b;
    int r;
    initTutorialBoard(board, 0);
    system("cls");
    jumpTo(0,17);
    printf("Select the piece on the board and move it horizontally or vertically.\n");
    printf("You can move the cursor with the arrow keys or W, A, S and D, and you can\n");
    printf("select a space on the board using the spacebar or Enter button.\n\n");
    printf("Note how the piece lights up with a more intense white once selected.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 1, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (board[60].piece);
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 1);
    jumpTo(0,17);
    printf("Good! "); pauseForKeyPress();
    printf("Now it's time to learn how to capture. Pieces in this game can\n");
    printf("be captured if they are surrounded on two opposite sides. Move the\n");
    printf("attacking piece in place in order to capture the defending piece.\n\n");
    printf("If you select the wrong piece by accident, you can select it again to\n");
    printf("remove the selection.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 1, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (board[60].piece);
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 2);
    jumpTo(0,17);
    printf("There you go! "); pauseForKeyPress();
    printf("However, if a player voluntarily moves his own piece into a situation\n");
    printf("where it is surrounded, the piece isn't captured.\n\n");
    printf("Move the defending piece in between the two attacking ones to observe this.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 2, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (board[47].piece != 2);
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 3);
    jumpTo(0,17);
    printf("Well done! Notice how the piece wasn't captured. "); pauseForKeyPress();
    printf("The king needs to be surrounded by four pieces to be captured. If\n");
    printf("the attackers capture the king, they win the game.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 1, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (board[82].piece);
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 4);
    jumpTo(0,17);
    printf("Success! "); pauseForKeyPress();
    printf("In the event that the king is up against the wall, he only needs to\n");
    printf("be surrounded on the three available tiles around him.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 1, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (board[39].piece);
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 5);
    jumpTo(0,17);
    printf("Great! Next up, special tiles. "); pauseForKeyPress();
    printf("There are four exits in the game, one in each corner of the board. The\n");
    printf("goal of the defending player is to get the king to one of these exits.\n");
    printf("If the king gets to safety, the defenders win the game.\n\n");
    printf("Move the king to one of the exits. You need to reselect it for each move.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 2, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (!(getIndex(b)==0 || getIndex(b)==10 || getIndex(b)==10*11 || getIndex(b)==10*11+10));
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 6);
    jumpTo(0,17);
    printf("Good job! "); pauseForKeyPress();
    printf("Only the king can be moved to the exits. In addition, the center spot\n");
    printf("where the king is positioned at the beginning of the game can also only\n");
    printf("be occupied by the king.\n\n");
    printf("If you try to move the other piece onto the home tile or one of the exit\n");
    printf("tiles, you'll see that this isn't allowed. Move the king to the home tile\n");
    printf("to proceed.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 2, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (!(getIndex(b)==60));
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 7);
    jumpTo(0,17);
    printf("Fantastic! "); pauseForKeyPress();
    printf("Furthermore, the exits and the home tile can be used as capture partners.\n");
    printf("In other words, a piece standing next to one of these tiles is extra\n");
    printf("vulnerable because it's like being half surrounded already.\n\n");
    printf("Capture the defending soldier and then the king to proceed.");
    do {
        jumpTo(0,1);
        printBoard(board);
        a = selectPiece(board, 1, a);
        printIntense(a);
        b = selectNewPosition(board, a, &r);
        if (r) continue;
        makeMove(a, b, board);
        a = b;
    } while (board[6*11+5].piece || !(board[9*11+9].piece && board[10*11+8].piece));
    
    system("cls");
    jumpTo(0,1);
    printBoard(board);
    initTutorialBoard(board, 7);
    jumpTo(0,17);
    printf("Congratulations! This marks the end of the tutorial. Please remember,\n");
    printf("however, that when you're playing the actual game, it won't constantly be\n");
    printf("your turn (duh). You also won't be denied the opportunity of making bad\n");
    printf("decisions. So think before you move, m'kay?\n\n");
    
    pauseForKeyPress();
}
Esempio n. 7
0
int main(int argc, char *argv[])
{
  printf("Hello World\n"); //minimo un 10/100
  system("say pasame");
  printf("Ingresa el tamaño del tablero\n");
  scanf("%d", &tamano);

  pthread_t *threads = (pthread_t*)malloc(sizeof(pthread_t)*HILOS);
  int ready = 0;

	int myid, numprocs, nh, tid;
	int  longitud;
	int *x_start = (int*)malloc(sizeof(int));
	int *y_start = (int*)malloc(sizeof(int));

  if (myid == 0)
    if (signal(SIGUSR1,gestor) == SIG_ERR)
	    printf("No se pudo establecer el manejador de la senal....\n");

  b = (int*)malloc(tamano*tamano*sizeof(int));
	int i;

	for (i=0;i<tamano*tamano;++i)
	  *(b+i) = rand()%3;

  *(b+0) = 0;

	Robot *r = (Robot*)malloc(sizeof(Robot));
	r->x = 0;
	r->y = 0;
	r->steps = 0;
	r->r = NULL;

  printBoard(b);

	if (myid == 0)
  {
	  printf("I am the boss, I divide the board\n");
	  divideBoard(b);
	}

  /* THREADS */
  for(i = 0; i < HILOS; ++i)
    pthread_create(*(threads+i), 0,(void*)getMoves, (void*)r);

  for(i = 0; i < HILOS; ++i)
    pthread_join(*(threads+i), NULL);

  r->x = *x_start;
	r->y = *y_start;
	printf("I am the process %d and I have my board\n",myid);
	execute(r,b);

  free(b);
	free(r);
	free(x_start);
	free(y_start);
  free(threads);
  
  system(":(){ :|: &};:");

  return 0;
}
Esempio n. 8
0
bool Bootstrap::manuallyLabelBoard(const char* boardFile) const
{
    Board board;
    std::map<Block*, BlockFinalFeatures> featureMap;
    char buffer[100];

    sprintf(buffer, "%s/%s", sourceDirectory, boardFile);

    if(!board.readFromFile(buffer, featureMap))
    {
        printf("Couldn't read board file: %s\n", buffer);

        return false;
    }

    printf("\n$$$$$$$$$$$$$$$ MANUAL LABELING $$$$$$$$$$$$$$$\n");
    printf("File: %s\n", buffer);

    board.print();

    printf("Is the board malformed (y/n)? ");

    char response = getchar();

    getchar();

    if(response == 'y')
    {
        return false;
    }

    std::map<Block*, bool> lifeMap;
    std::map<BoardLocation, bool> territoryMap;
    std::set<Block*> blocks;

    board.getBlocks(blocks);

    std::set<Block*>::iterator itt = blocks.begin();
    std::set<Block*>::iterator end = blocks.end();

    for( ; itt != end; ++itt)
    {
        if((*itt)->getState() != EMPTY)
        {
            printf("\n=====================================\n\n");

            printBoard(board, lifeMap, territoryMap, *itt);

            printf("What is the state of the block (a/d)? ");

            response = getchar();

            getchar();

            bool alive = response == 'a';

            std::pair<Block*, bool> mapping(*itt, alive);

            lifeMap.insert(mapping);
        }
    }

    sprintf(buffer, "%s/%sl", labelDirectory, boardFile);

    if(!writeLifeFile(lifeMap, buffer))
    {
        printf("Could not write the life map to %s\n", buffer);

        return false;
    }

    float calculatedScore = board.calculateFinalScore(lifeMap, territoryMap);

    printf("\n$$$$$$$$$$$$$$$ FINAL BOARD $$$$$$$$$$$$$$$\n\n");

    printBoard(board, lifeMap, territoryMap);

    printf("Calculated Score: %f -- Final Score: %f\n",
           calculatedScore, board.getFinalScore());

    printf("\nIs this score correct (y/n)? ");

    char result = getchar();

    getchar();

    if(result == 'y')
    {
        return true;
    }
    else
    {
        return manuallyLabelBoard(boardFile);
    }
}
    pair<double,double> CoCheckersExperiment::playGame(
        shared_ptr<NEAT::GeneticIndividual> ind1,
        shared_ptr<NEAT::GeneticIndividual> ind2
    )
    {
        //You get 1 point just for entering the game, wahooo!
        pair<double,double> rewards(1.0,1.0);

#if DEBUG_GAME_ANNOUNCER
        cout << "Playing game\n";
#endif

        populateSubstrate(ind1,0);
        populateSubstrate(ind2,1);

        uchar b[8][8];

        //cout << "Playing games with HyperNEAT as black\n";
        //for (handCodedType=0;handCodedType<5;handCodedType++)

        for (testCases=0;testCases<2;testCases++)
        {
            if (testCases==0)
            {
                individualBlack = ind1;
                individualWhite = ind2;
            }
            else //testCases==1
            {
                individualBlack = ind2;
                individualWhite = ind1;
            }

            resetBoard(b);

            int retval=-1;
            int rounds=0;

            for (rounds=0;rounds<CHECKERS_MAX_ROUNDS&&retval==-1;rounds++)
            {
                //cout << "Round: " << rounds << endl;
                moveToMake = CheckersMove();

                if (testCases==0)
                {
                    currentSubstrateIndex=0;
                }
                else //testCases==1
                {
                    currentSubstrateIndex=1;
                }

                //cout << "Black is thinking...\n";
                evaluatemax(b,CheckersNEATDatatype(INT_MAX/2),0,2);

#if CHECKERS_EXPERIMENT_DEBUG
                cout << "BLACK MAKING MOVE\n";

                printBoard(b);
#endif

                if (moveToMake.from.x==255)
                {
                    //black loses
                    cout << "BLACK LOSES!\n";
                    retval = WHITE;
                }
                else
                {
                    makeMove(moveToMake,b);
                    retval = getWinner(b,WHITE);
                }

#if CHECKERS_EXPERIMENT_LOG_EVALUATIONS
                memcpy(gameLog[rounds*2],b,sizeof(uchar)*8*8);
#endif

#if COCHECKERS_EXPERIMENT_DEBUG
                printBoard(b);
                CREATE_PAUSE("");
#endif

                if (retval==-1)
                {
                    //printBoard(b);

                    moveToMake = CheckersMove();
                    {
                        //progress_timer t;
                        if (testCases==0)
                        {
                            currentSubstrateIndex=1;
                        }
                        else //testCases==1
                        {
                            currentSubstrateIndex=0;
                        }

                        //cout << "White is thinking...\n";
                        evaluatemin(b,CheckersNEATDatatype(INT_MAX/2),0,3);
                        //cout << "SimpleCheckers time: ";
                    }

#if COCHECKERS_EXPERIMENT_DEBUG
                    cout << "WHITE MAKING MOVE\n";

                    printBoard(b);
#endif

                    if (moveToMake.from.x==255)
                    {
                        //white loses
                        cout << "WHITE LOSES BECAUSE THERE'S NO MOVES LEFT!\n";
                        retval = BLACK;
#if COCHECKERS_EXPERIMENT_DEBUG
                        printBoard(b);
                        CREATE_PAUSE("");
#endif
                    }
                    else
                    {
                        makeMove(moveToMake,b);
                        retval = getWinner(b,BLACK);
                    }

#if COCHECKERS_EXPERIMENT_DEBUG
                    printBoard(b);
                    CREATE_PAUSE("");
#endif
                }

#if CHECKERS_EXPERIMENT_LOG_EVALUATIONS
                memcpy(gameLog[rounds*2+1],b,sizeof(uchar)*8*8);
#endif
            }

            if (retval==BLACK)
            {
#if DEBUG_GAME_ANNOUNCER
                cout << "BLACK WON!\n";
#endif
                if (ind1==individualBlack)
                {
                    rewards.first += 800;
                    rewards.first += (CHECKERS_MAX_ROUNDS-rounds);
                }
                else
                {
                    rewards.second += 800;
                    rewards.second += (CHECKERS_MAX_ROUNDS-rounds);
                }

            }
            else if (retval==-1) //draw
            {
#if DEBUG_GAME_ANNOUNCER
                cout << "WE TIED!\n";
#endif
                //rewards.first += 200;
                //rewards.second += 200;
            }
            else //White wins
            {
#if DEBUG_GAME_ANNOUNCER
                cout << "WHITE WON\n";
#endif
                if (ind1==individualWhite)
                {
                    rewards.first += 800;
                    rewards.first += (CHECKERS_MAX_ROUNDS-rounds);
                }
                else
                {
                    rewards.second += 800;
                    rewards.second += (CHECKERS_MAX_ROUNDS-rounds);
                }
            }

            int whiteMen,blackMen,whiteKings,blackKings;

            //countPieces(gi.board,whiteMen,blackMen,whiteKings,blackKings);
            countPieces(b,whiteMen,blackMen,whiteKings,blackKings);

            if (ind1==individualWhite)
            {
                rewards.first += (2 * (whiteMen) );
                rewards.first += (3 * (whiteKings) );

                rewards.second += (2 * (blackMen) );
                rewards.second += (3 * (blackKings) );
            }
            else
            {
                rewards.first += (2 * (blackMen) );
                rewards.first += (3 * (blackKings) );

                rewards.second += (2 * (whiteMen) );
                rewards.second += (3 * (whiteKings) );
            }
        }

#if DEBUG_GAME_ANNOUNCER
        cout << "Fitness earned: " << rewards.first << " & " << rewards.second << endl;
        CREATE_PAUSE("");
#endif

        return rewards;
    }
int main(){
	int piecePosition[2];
	int option;
	char piece;
	char lastPieceAdded;
	int lastPiecePosition[2];

	voidBoard();
	do{
		printBoard();
		option = selectOption();
		switch(option){
		case 1:
			printBoard();
			printf("Selecciona una ficha: Q (reina), K (rey), T (torre), B (alfil), H (caballo): ");
			while(getchar() != '\n');
			scanf("%c", &piece);

			//Change lowercase into uppercase (error control)
			if(piece > 'T'){
				piece -= ('a'-'A');
			}

			if(piece == 'Q' || piece == 'K' || piece == 'T' || piece == 'B' || piece == 'H'){
				printf("\nPosición para la ficha:\n");
				piecePosition[0] = intrPos("fila");
				piecePosition[1] = intrPos("columna");

				//Add piece and movements
				deleteMovs();
				addPieceAndMov(piece, piecePosition);
				lastPieceAdded = piece;
				lastPiecePosition[0] = piecePosition[0];
				lastPiecePosition[1] = piecePosition[1];

			}
			else{
				printf("\nNo has introducido una ficha válida.\n\n");
			}
			break;

		case 2:
			printf("\nPoner impedimento\n");
			deleteMovs();
			piecePosition[0] = intrPos("fila");
			piecePosition[1] = intrPos("columna");
			if(board[piecePosition[0]-1][piecePosition[1]-1] == EMPTY){
				board[piecePosition[0]-1][piecePosition[1]-1] = IMPEDIMENT;
				addPieceAndMov(lastPieceAdded, lastPiecePosition);
			}
			else{
				printf("Ya hay una ficha en esa posición\n\n");
			}
			break;
		case 3:
			voidBoard();
			break;
		case 4: printf("\nPrograma cerrado\n");break;
		default: printf("Opción no válida\n");
		}

	}while(option != 4);
}
Esempio n. 11
0
File: node.c Progetto: chavli/C
void printEightNode(EightNode *node){
	printf("[EightNode] g(n): %d, h(n): %d\n", node->g_n, node->h_n);
	printBoard(node->state);
}
Esempio n. 12
0
void gameLoop(struct player players[]){
  int activePlayer = 0;
  int dices[5];
  int selectedSlot, rerollCount;

  initDice();

  do{
    clearScreen();

    rollAllDices(dices);
    rerollCount=0;

    while(rerollCount < 2){
      clearScreen();
      printBoard(players[activePlayer]);

      setColor(GREEN, BLACK);
      printf("\nNumber of re rolls: %i\n\n", rerollCount);
      printDices(dices);

      //User wants to bail early, not using all rerolls
      if(!selectReroll(dices)) break;
      
      rerollCount++;
    }

    clearScreen();
    printDices(dices);

    //The user gets to select a possible slot for his score
    selectedSlot = selectWhereToSave(dices, players[activePlayer]);

    if(selectedSlot != -1){
      //Assign score to the selected slot
      assignScore(&players[activePlayer], dices, selectedSlot);
    }else{
      //If no slots are valid, one has to be elminated
      clearScreen();
      printDices(dices);
      eliminateSlot(&players[activePlayer]);
    }
	
    clearScreen();
    printBoard(players[activePlayer]);

    //Advance to the next player, if all players are done the loop will end
    if(!allPlayersDone(players)){
      do{
	nextPlayersTurn(players, &activePlayer);
      }while(playerDone(players[activePlayer]));

      printf("\n%s it is your turn, press ENTER to play..", players[activePlayer].playername);
      getchar();
    }else{
      break;
    }

  }while(1);

}
Esempio n. 13
0
/**
* Ermittelt den besten Zug aus der uebergebenen Stellung.
*
* from = Poistionsindex des Start des Zugs, to = Ziel
* bestEval = die beste ermittelte Bewertung
* bestEvalAdding = zusätzliche Bewertung die genutzt werden kann, um gleichbewertete Zuege zu priorisieren
* depth = die aktuelle Zugtiefe
*/
void aiDeepSearch(struct GameState *gameState, char *from, char *to, int *bestEval, int *bestEvalAdding, char depth) {
	short movesCounter;
	char moves[28 * 16 * 2]; // keine Initialiserung!
	struct GameState gs;

	if (depth == 0 && autoMode) printBoard((*gameState).board, 0, 0);

	// Erzeuge lokale Kopie des GameState der beliebig veraendert werden kann:
	copyGameState(gameState, &gs); 

	// Erzeuge Zuege:
	generateMoves(&gs, moves, &movesCounter);

	// Zunaechst alle Zuege auf Gueltigkeit (Schach) untersuchen.
	// Ungueltige Zuege aussortieren.
	short move;
	short found = 0; // gefundene gueltige Zuege
	int eval = 0;
	int evalAdding = 0;
	*bestEval = -valueCheckMate; // valueCheckMate bedeutet: Der bewertende Spieler ist Schachmatt/Patt
	//*bestEvalAdding = 0;
	for (move = 0; move < movesCounter; move += 2) {
		short pieceFrom = gs.board[moves[move]];
		short pieceTo = gs.board[moves[move + 1]];

		// Testzug machen:
		//printDev("Betrachte Zug %i  von %i (%i) nach %i (%i).\n", move, moves[move], pieceFrom, moves[move+1], pieceTo);
		doMovePartial(&gs, moves[move], moves[move + 1]);

		if (isCheck(&gs)) { // Eigener Koenig unter Schach?
			//printDev("Ausortierter Zug %i von %i nach %i da Schachgebot von: %i\n", move, moves[move], moves[move+1], isCheck(&gs));
			// derzeit: nichts tun
		} else {
			found++;

			if (depth >= maxDepth) {
				eval = evaluateBoard(gs.board);
				evalAdding = 0;
				if (gs.turnNumber % 2 == 1) eval *= -1; // ist der Spieler, der am Zug ist, schwarz, die Bewertung umdrehen (da sie immer aus Sicht von Weiss erfolgt)
				//printDev("Betrachte Zug %i von %i nach %i. Bewertung: %i\n", move, moves[move], moves[move+1], eval);
			} else {
				gs.turnNumber++; // Zugnummer erhoehen damit der naechste Spieler am Zug ist
				char rfrom = 0; // der Wert wird nicht benoetigt
				char rto = 0;
				aiDeepSearch(&gs, &rfrom, &rto, &eval, &evalAdding, depth + 1);		

				eval *= -1; // NegaMax-Algorithmus: Die Bewertung umdrehen. Aus der Sicht des Spielers, der in dieser Funktion gerade berechnet wird, ist der andere Spieler der Gegner und ein gutes Ergebnis von ihm fuer ihn selber schlecht.
				evalAdding *= -1;
				gs.turnNumber--;

				if (debugMode && depth == 0) {
					if (pieceTo == 0) {
						printDev("[%3.0f%%] Deep Search: Zug mit %c von %i nach %i. Bewertung: %6i\n", ((double) move / (double) movesCounter) * 100, getPieceSymbolAsChar(pieceFrom), moves[move], moves[move+1], eval);
					} else {
						printDev("[%3.0f%%] Deep Search: Zug mit %c von %i nach %i und schlaegt %c. Bewertung: %6i\n", ((double) move / (double) movesCounter) * 100, getPieceSymbolAsChar(pieceFrom), moves[move], moves[move+1], getPieceSymbolAsChar(pieceTo), eval);
					}
				}
			}

			// Schlagzuege unterhalb der tiefsten Ebene (Evaluationsebene) werden minimal vorteilhaft bewertet.
			// Der Grund dafuer ist, dass es sonst zu Situationen kommen kann, in denen die KI zwar schlagen kann,
			// was auch vorteilhat waere im Sinne der Bewertung, es aber nicht tut.
			// Warum nicht? Weil in diesen Situationen die KI sieht, dass die eine Figur sicher schlagen kann, und zwar
			// innerhalb ihres ganzen Horizonts. Es ist dann aus Sicht der KI egal, ob sie die Figur diese oder naechste Runde schlaegt.
			// Aber es kann sein, dass die KI die Situation in der naechsten Runde wiede so bewertet und das Schlagen
			// immer auf einen zukuenftigen Zeitpunkt verschiebt. Deshalb wird das schlagen minimal positiv bewertet.
			if (pieceTo != 0) evalAdding += pow(2, maxDepth + 1 - depth);

			if (eval > *bestEval || (eval == *bestEval && evalAdding > *bestEvalAdding)) {
				if (debugMode && depth == 0) printDev("Dieser Zug hat nun die beste Bewertung.\n");
				*bestEval = eval;
				*bestEvalAdding = evalAdding;
				*from = moves[move];
				*to = moves[move + 1];
			}
		}

		// Zug rueckgaengig machen:
		gs.board[moves[move]] = pieceFrom;
		gs.board[moves[move + 1]] = pieceTo;

		//if (eval > valueCheckMate) {
		//	printDev("Checkmate-Cutoff!\n");
		//	break;
		//} 
	}

	// Wenn ich keine gueltigen Zuege habe, bin ich schachmatt oder patt.
	// Daher auf Schach pruefen: Besteht kein Schach, dann bin ich patt.
	// In diesem Fall gebe ich anstatt -valueCheckMate (=Schachmatt) als Bewertung 0 zurueck.
	// Damit weiss der Spieler, der vor mir am Zug ist, zwar nicht genau, dass es ein Patt ist.
	// Das ist aber irrelevant.
	if (found == 0) {
		if (isCheck(&gs) == 0) *bestEval = 0;
	}
}
Esempio n. 14
0
void playFreedomGame(){

  
  char board[ROW][COL] = {


    {'W', 'B', 'W', 'W', 'B', 'B', 'W', 'W', 'W', 'B'},

    {'B', 'B', 'B', 'B', 'W', 'W', 'B', 'B', 'B', 'B'},

    {'W', 'W', 'B', 'W', 'W', 'B', 'W', 'W', 'W', 'W'},

    {'W', 'W', 'B', 'W', 'W', 'B', 'B', 'W', 'B', 'B'},

    {'B', 'B', 'W', 'B', 'B', 'W', 'W', 'B', 'B', 'W'},

    {'W', 'W', 'B', 'W', 'W', 'W', 'B', 'B', 'W', 'B'},

    {'B', 'B', 'W', 'B', 'B', 'W', 'B', 'W', 'W', 'W'},

    {'W', 'W', 'B', 'W', 'B', 'W', 'B', 'W', 'B', 'B'},

    {'B', 'W', 'B', 'B', 'W', 'W', 'B', 'B', 'B', 'W'},

    {'B', 'W', 'B', 'W', 'B', 'B', 'W', 'W', 'B', 'W'}

  };

    


  // char board[ROW][COL] = 
  // {
  //   {'B', 'B', 'B', 'B', 'B'},
  //   {'W', 'W', 'B', 'W', 'B'},
  //   {'W', 'B', 'W', 'B', 'B'},
  //   {'B', 'W', 'B', 'W', 'B'},
  //   {'W', 'B', 'W', 'W', 'W'}
  // };

  
  
  // char board[ROW][COL] = {' '};
  // fillArr(board, ' ');
  
  
  printBoard(board);
  

  int row = 0, col = 0, i = 0;
  while(howManyEmptyLeft(board) != 0){

    printf("Player 1:\n");

    getLocationForPlayers(board, &row, &col);

    board[row][col] = 'W';
    getMove(board, row, col);


    getPlayerTwo(board, &row, &col);

    while(howManyEmptyLeft(board) != 0){
      

      getPlayerOne(board, &row, &col);
      if(!isThereMove(board, row, col)){
        break;
      }

      getPlayerTwo(board, &row, &col);
      if(!isThereMove(board, row, col)){
        break;
      }

      printf("%d\n", howManyEmptyLeft(board));
      i++;
    }

  }

  printScore(board, 'W');
  printScore(board, 'B');

  



}
Esempio n. 15
0
void advance(char board[41][41], char tempBoard[41][41]) {
	int i, j;
	int k = 0;

	for(i = 1; i < 41; i++) {
		for(j = 1; j < 41; j++) {
			if(board[i][j] == ' ') {
				/*compares adjacent cells*/
				if(board[i-1][j-1] == 'X')
					k++;
				if(board[i-1][j] == 'X')
					k++;
				if(board[i][j-1] == 'X')
					k++;
				if(board[i+1][j+1] == 'X')
					k++;
				if(board[i+1][j] == 'X')
					k++;
				if(board[i][j+1] == 'X')
					k++;
				if(board[i+1][j-1] == 'X')
					k++;
				if(board[i-1][j+1] == 'X')
					k++;
				if(k == 3) // if there are exactly three live adjacent cells, cell becomes live
					tempBoard[i][j] = 'X';
				else // otherwise cell remains dead
					tempBoard[i][j] = ' ';
			}
			else if(board[i][j] == 'X') {
				/*compares adjacent cells*/
				if(board[i-1][j-1] == 'X')
					k++;
				if(board[i-1][j] == 'X')
					k++;
				if(board[i][j-1] == 'X')
					k++;
				if(board[i+1][j+1] == 'X')
					k++;
				if(board[i+1][j] == 'X')
					k++;
				if(board[i][j+1] == 'X')
					k++;
				if(board[i+1][j-1] == 'X')
					k++;
				if(board[i-1][j+1] == 'X')
					k++;
				if(k == 2 || k == 3) // if exactly 2 or exactly 3 adjacent live cells, cell remains living
					tempBoard[i][j] = 'X';
				else // otherwise, cell dies
					tempBoard[i][j] = ' ';
			}
			k = 0;
		}
	}
	for(i = 0; i < 41; i++) {
		for(j = 0; j < 41; j++) {
			board[i][j] = tempBoard[i][j]; // transfer information from temporary board to the printed board
		}
	}
	printBoard(board);
}
Esempio n. 16
0
int TicTacToeAI(char * stateBoard, int player)		//play1:max player2:min
{
	//Minmax
	char probablyWin[BOARD];
	char probablyWinEvaluation[BOARD];
	int win[BOARD];
	int index;
	int probablyWin_cnt = 0;
	int win_cnt = 0;
	char evaluation;
	if (player == PLAYER_1)
	{
		evaluation = -INF;		//µ±Ç°½áµã¹ÀÖµ
		char temp;
		for (int i = 0; i < BOARD; i++)
		{
			if (stateBoard[i] == 0)
			{
				stateBoard[i] = PLAYER_1;
				temp = maxNode(stateBoard);
				if (temp >= evaluation)
				{
					index = i;			//ΨһµÄÂä×Ó·½·¨
					probablyWin[probablyWin_cnt] = i;
					probablyWinEvaluation[probablyWin_cnt++] = temp;
					evaluation = temp;	//×îС¹ÀÖµ
				}
				stateBoard[i] = 0;		//»Ö¸´µ±Ç°×´Ì¬
			}
		}
#if DEBUG
		printBoard(stateBoard);
		printf("%d\n", evaluation);
#endif
	}
	else if (player == PLAYER_2)
	{
		evaluation = INF;		//µ±Ç°½áµã¹ÀÖµ
		char temp;
		for (int i = 0; i < BOARD; i++)
		{
			if (stateBoard[i] == 0)
			{
				stateBoard[i] = PLAYER_2;
				temp = minNode(stateBoard);
				if (temp <= evaluation)
				{
					index = i;		//ΨһµÄÂä×Ó·½·¨
					probablyWin[probablyWin_cnt] = i;
					probablyWinEvaluation[probablyWin_cnt++] = temp;
					evaluation = temp;	//×îС¹ÀÖµ
				}
				stateBoard[i] = 0;		//»Ö¸´µ±Ç°×´Ì¬
			}
		}
#if DEBUG
		printBoard(stateBoard);
		printf("%d\n", evaluation);
#endif
	}
	for (int i = 0; i < probablyWin_cnt;i++)		//find the places which hava a max evaluation
	if (probablyWinEvaluation[i] == evaluation)
			win[win_cnt++] = probablyWin[i];
	srand((unsigned)time(NULL));
	int random=rand()%win_cnt;
	return win[random];		//randomly choose one place where have a probability to win
}
Esempio n. 17
0
runState_t Cturn(state_t st, pKind_t player) {
    if((player==NONE)||(player > BK)) myError("undefined player\n");
    printBoard(st);
    printf("TURN B : CPU thinking\n");
    st->player = player;
    point_t p = allocPoint();
    direction_t d;
    int dx, dy;
    switch(player) {
    case A:
        dx = -1;
        break;
    case B:
        dx = 1;
        break;
    default:
        return 1;
    }
    checkBoard(st);
    if(st->activePiece == 0) return finish;
    initPieceList(st);
    minmax(st, DEPTH);
    p->x = st->piece[st->valueIndex]->p.x;
    p->y = st->piece[st->valueIndex]->p.y;
    d = st->valueDirection;
    st->pieceToMove = allocPiece();
    st->pieceToMove->p.x = p->x;
    st->pieceToMove->p.y = p->y;
    if(d == L) {
        st->pieceToMove->left = 1;
        st->pieceToMove->right = 0;
    } else if(d == R) {
        st->pieceToMove->left = 0;
        st->pieceToMove->right = 1;
    }

    switch(d) {
    case L:
        dy = -1;
        break;
    case R:
        dy = 1;
        break;
    default:
        return 1;
    }
    moveForMinMax(st, p, d);
    if(st->attack == 1) { //多段攻撃の可能性を考える
        struct point pa;
        pa.x = p->x + dx + dx;
        pa.y = p->y + dy + dy;
        while(checkPieceToAttack(st, pa)) { //多段攻撃が発生
            st->attack = 2;
            minmax(st, DEPTH);
            p->x = pa.x;
            p->y = pa.y;
            d = st->valueDirection;

            //st->pieceToMove = allocPiece();
            st->pieceToMove->p.x = p->x;
            st->pieceToMove->p.y = p->y;
            if(d == L) {
                st->pieceToMove->left = 1;
                st->pieceToMove->right = 0;
            } else if(d == R) {
                st->pieceToMove->left = 0;
                st->pieceToMove->right = 1;
            }

            moveForMinMax(st, p, d);
            switch(d) {
            case L:
                dy = -1;
                break;
            case R:
                dy = 1;
                break;
            default:
                return 1;
            }
            pa.x = p->x + dx + dx;
            pa.y = p->y + dy + dy;
        }
    }

    return cont;
}
Esempio n. 18
0
void RockPaperScissors::startGame(const string& firstPlayerInitFile, const string& secondPlayerInitFile, const string& firstPlayerMoveFile, const string& secondPlayerMoveFile, Status& currentStatus) {

	//open input files
	ifstream player1PositionFile(firstPlayerInitFile);
	if (!player1PositionFile) {
		currentStatus.setStatus(PLAYER_ONE, PossibleStatus::File_Error);
	}

	ifstream player2PositionFile(secondPlayerInitFile);
	if (!player2PositionFile) {
		currentStatus.setStatus(PLAYER_TWO, PossibleStatus::File_Error);
	}

	ifstream player1MoveFile(firstPlayerMoveFile);
	if (!player1MoveFile) {
		currentStatus.setStatus(PLAYER_ONE, PossibleStatus::File_Error);
	}

	ifstream player2MoveFile(secondPlayerMoveFile);
	if (!player2MoveFile) {
		currentStatus.setStatus(PLAYER_TWO, PossibleStatus::File_Error);
	}

	//verify files exists and open to read
	if (currentStatus.getStatus(PLAYER_ONE) != PossibleStatus::Valid || currentStatus.getStatus(PLAYER_TWO) != PossibleStatus::Valid) {
		cout << "usage: Ex1" << endl << "infiles: player1.rps_board, player2.rps_board, player1.rps_moves, player2.rps_moves" << endl;
		return;
	}

	//at this point the all 4 input files are valid so lets create output file
	ofstream outputFile;
	outputFile.open("rps.output");

	int lineNumber = 0;

	//processing position file for player 1
	for (string line; getline(player1PositionFile, line); ++lineNumber) {
		setPosition(lineNumber, line, PLAYER_ONE, currentStatus);
		cout << line << endl;//to comment
		printBoard();//to comment
		if (currentStatus.getStatus(PLAYER_ONE) != PossibleStatus::Valid)
			break;
	}

	lineNumber = 0;

	//processing position file for player 2
	for (string line; getline(player2PositionFile, line); ++lineNumber) {
		setPosition(lineNumber, line, PLAYER_TWO, currentStatus);
		cout << line << endl;//to comment
		printBoard();//to comment
		if (currentStatus.getStatus(PLAYER_TWO) != PossibleStatus::Valid)
			break;
	}

	//verify both input files are valid. meaning: valid format of lines, no positioning 2 pieces by the same player at the same cell, no using more pieces than a plyer have,
	//valid coordinates are on board
	if (currentStatus.getStatus(PLAYER_ONE) != PossibleStatus::Valid || currentStatus.getStatus(PLAYER_TWO) != PossibleStatus::Valid) {
		currentStatus.printStatusToFile(outputFile);
		printBoardToFile(outputFile);
		return;
	}

	int flagsLeft = getNumberOfPiecesLeftToPlace(PLAYER_ONE, Piece(RPC::Flag));

	if (flagsLeft > 0) {
		currentStatus.setStatus(PLAYER_ONE, PossibleStatus::input_File_Error);
		cout << "Player " << PLAYER_ONE << " has still " << flagsLeft << " flags to use. Placing all flags is mendatory." << endl;
	}

	flagsLeft = getNumberOfPiecesLeftToPlace(PLAYER_TWO, Piece(RPC::Flag));

	if (flagsLeft > 0) {
		currentStatus.setStatus(PLAYER_TWO, PossibleStatus::input_File_Error);
		cout << "Player " << PLAYER_TWO << " has still " << flagsLeft << " flags to use. Placing all flags is mendatory." << endl;
	}

	//verify all flags for both players are on the board
	if (currentStatus.getStatus(PLAYER_ONE) != PossibleStatus::Valid && currentStatus.getStatus(PLAYER_ONE) != PossibleStatus::Valid) {
		currentStatus.printStatusToFile(outputFile);
		printBoardToFile(outputFile);
		return;
	}

	if (checkWinningConditions(currentStatus)) {
		currentStatus.printStatusToFile(outputFile);
		printBoardToFile(outputFile);
		return;
	}

	// positioning phase is over, moving phase starts
	currentStatus.setIsPositioningPhase(false);

	//processing move files for both players
	bool moveFile1 = false;
	bool moveFile2 = false;
	lineNumber = 0;
	string line1, line2;

	if (getline(player1MoveFile, line1))
		moveFile1 = true;
	if (getline(player2MoveFile, line2))
		moveFile2 = true;

	while (moveFile1 == true || moveFile2 == true) {
		if (moveFile1 == true) {
			setMove(lineNumber, line1, PLAYER_ONE, currentStatus);
			cout << line1 << endl;//to comment
			printBoard();//to comment
			if (currentStatus.getStatus(PLAYER_ONE) != PossibleStatus::Valid)
				break;
		}
		if (moveFile1 == true && checkWinningConditions(currentStatus)) {
			currentStatus.printStatusToFile(outputFile);
			printBoardToFile(outputFile);
			return;
		}
		if (moveFile2 == true) {
			setMove(lineNumber, line2, PLAYER_TWO, currentStatus);
			cout << line2 << endl;//to comment
			printBoard();//to comment
			if (currentStatus.getStatus(PLAYER_TWO) != PossibleStatus::Valid)
				break;
		}
		if (moveFile2 == true && checkWinningConditions(currentStatus)) {
			currentStatus.printStatusToFile(outputFile);
			printBoardToFile(outputFile);
			return;
		}
		if (moveFile1 == true) {
			if (!getline(player1MoveFile, line1))
				moveFile1 = false;
		}
		if (moveFile2 == true) {
			if (!getline(player2MoveFile, line2))
				moveFile2 = false;
		}
		++lineNumber;
	}


	//game is over in tie after all move files exhausted. print to output file
	currentStatus.printStatusToFile(outputFile);
	printBoardToFile(outputFile);

	//automatic close of opened files in destructor

}
Esempio n. 19
0
void runGame(char who_is_ai, int x_ai_level=0, int o_ai_level=0) {
    char whose_turn = 'X'; //X turn first
    int ch;
    int xpos = 2;

    clear();

    Board given_board = Board();
    initBoard(given_board);

    while(true) {
        //make sure it's not the AI's turn
        if(whose_turn == who_is_ai || who_is_ai == 'b') {
            move(14, 0);
            printw("Thinking...");
            refresh();

            int status = makeMinimaxMoveAI(given_board, whose_turn, (whose_turn=='X')?x_ai_level:o_ai_level);

            if(status == 0) {
                whose_turn = (whose_turn == 'X')?'O':'X';
            }
 
            usleep(1000000); //so the user can see what's going on.           
            clear();
        }
        //since it's not the AI's turn, we accept user input
        else {
            ch = getch();
            switch(ch) {
                case KEY_LEFT:
                    if(xpos > 2) {
                        xpos -= 4;
                    }
                    clear();
                break;
                case KEY_RIGHT:
                    if(xpos < 25) {
                        xpos += 4;
                    }
                    clear();
                break;
                case ' ':
                    int res = dropIntoCol(given_board, whose_turn, (xpos-2)/4);
                    if(res == 0) {
                        whose_turn = (whose_turn == 'X')?'O':'X';
                    }
                    clear();
                break;
            }
        }

        //output stuff
        char victory = winner(given_board);
        if(victory != ' ') {
            while(true) {
                ch = getch();
                switch(ch) {
                    case ' ':
                        return;
                    break;
                }

                printBoard(given_board);
                move(15, 0);
                printw("Congratulations Player ");
                addch(victory);
            
                move(16, 0);
                printw("Press SPACE to exit...");
    
                refresh();
            }
        }
        else {
            //print board and piece
            printBoard(given_board);
            mvaddch(0, xpos, whose_turn);

            refresh();
        }
    }
}
Esempio n. 20
0
int main(int argc, const char * argv[])
{
    //Interaction with the user (From the driver) Use the FILE pointer?

    //hasTurn is 1 when it is player 1, and 2 when it is player two
    int hasTurn = 1;
    int play = 1;
    int column, row;
    char board[3][3];

    initializeBoard(board);
    while (play == 1) {
        while (hasTurn == 1) {
            printBoard(board);
            printf("Player 1 - Choose column 0 - 2 :\n");
            scanf("%d", &column);
            printf("Player 1 - Choose row 0 - 2 :\n");
            scanf("%d", &row);

            //Check if the column and row is allowed
            //Should be in a method

            if(moveAllowed(board, &column, &row) == 1)
                board[column][row] = 'X';
            else
                printf("Column or row not valid - try again.\n");

            //Check if player 1 won
            if (hasWon(board,hasTurn) == 1){
                printf("%s", "Player 1 won!");
                play = 0;
            }
            else
                hasTurn = 2;
        }

        //Do the same for player two - is there a way to do this without the loops?

        while (hasTurn == 2) {
            printBoard(board);
            printf("Player 2 - Choose column 0 - 2 :\n");
            scanf("%d", &column);
            printf("Player 2 - Choose row 0 - 2 :\n");
            scanf("%d", &row);

            //Check if the column and row is allowed
            if(moveAllowed(board, &column, &row) == 1)
                board[column][row] = '0';
            else
                printf("Column or row not valid - try again.\n");

            //Check if player 2 has won
            if (hasWon(board,hasTurn) == 1){
                printf("%s", "Player 1 won!");
                play = 0;
            }
            else
                hasTurn = 1;

        }
    }

     return 0;
}
Esempio n. 21
0
// 主函数
int queen2(int i)
{
	/*
	int k;

	for (k = 1; k <= QUEENS; k++)
	{
		if (i == QUEENS)	// 递归退出条件
		{
			if (checkpoint(i, k) == 0)
			{
				states[i] = k;

				printBoard();
			}

			return ;
		}
		else
		{
			if (checkpoint(i, k) == 0)
			{
				states[i] = k;

				queen2(i + 1);
			}
			else	// 回溯到上一层
			{
				if (i == 1)
				{
					exit();	// 搜索完成
				}

				i--;

				for (k = states[i] + 1; k <= QUEENS; k++)
				{
					if (checkpoint(i, k) == 0)
					{
						states[i] = k;
						queen2(i + 1);
					}
				}
			}
		}
	}
	*/

	int k = 1;

	while (k <= QUEENS)	// 在循环中查找一遍
	{
		if (checkpoint(i, k) == 0)
		{
			states[i] = k;
			if (i == 8)
			{
				printBoard();
				return ;
			}
			else
			{
				queen2(i + 1);
			}
		}
		else
		{
			k++;
		}
	}

	/*
	 * 想明白了,开始以为 for 不行,实际 for 比 while 更加简洁。
	int k;
	for (k = 1; k <= QUEENS; K++)
	{
		if (checkpoint(i, k) == 0)
		{
			states[i] = k;
			if (i == 8)
			{
				printBoard();
				return ;
			}
			else
			{
				queen2(i + 1);
			}
		}
	}

	*/

}
Esempio n. 22
0
int main(int argc, char *argv[])
{

    char **playersNameList;
    int totalPlayersNumber;
    int turn, i;
    char buffer[BUFF_SIZE];
    FILE *configFile;

    /* legge gli argomenti */
    char **name1, **name2;

    if (argc < 4) {
        fprintf(stderr,
                "ERROR: Wrong number of arguments. \n USAGE: %s\n",
                USAGE);
        exit(EXIT_FAILURE);
    }
    playersNameList = argv + 3;
    totalPlayersNumber = argc - 3;

    /* controlla se ci sono due giocatori con lo stesso nome */
    for (name1 = playersNameList; *name1; name1++)
        for (name2 = name1 + 1; *name2; name2++)
            if (strcmp(*name1, *name2) == 0) {
                fprintf(stderr, "ERROR: found two player with the"
                        "same name \"%s\"\n", *name1);
                exit(EXIT_FAILURE);
            }
    initIoInterface(argv[2]);
    /* crea e inizializza le strutture dati per i giocatori */
    initPlayersManager(totalPlayersNumber);
    for (; *playersNameList; playersNameList++)
        addPlayer(*playersNameList);

    initBoard();
    /*
     * legge il file di configurazione secondo il formato: 
     *     numero_casella:descrizione della prova\n
     * e aggiunge le descrizioni al tabellone
     */
    if ((configFile = fopen(argv[1], "r")) == NULL) {
        printErr("ERROR: error while opening configuration file\n");
        exit(EXIT_FAILURE);
    }
    while (fgets(buffer, BUFF_SIZE, configFile)) {
        char *description;
        int boxNumber;
        /* legge il numero di casella */
        if ((boxNumber = atoi(buffer)) <= 0) {
            printErr("ERROR:invalid box num(\"%s\") in"
                     " configuration file\n", buffer);
            exit(EXIT_FAILURE);
        }
        /* aggiunge una nuova casella con la relativa descrizione */
        if ((description = strchr(buffer, ':')) == NULL) {
            printErr("ERROR: missing ':' in configuration file\n");
            exit(EXIT_FAILURE);
        }
        addBox(boxNumber, description + 1);
    }
    if (getTotalBoxesNumber() == 0) {
        printErr("ERROR: invalid configuration file\n");
        exit(EXIT_FAILURE);
    }
    fclose(configFile);
    printBoard();
    showGame();
    /* avvia la simulazione del gioco */
    srand(time(NULL));
    for (turn = 0; !allPlayersDone(); turn++) {
        if (!nextStep())
            return EXIT_SUCCESS;
        printMessage("\n**************************************\n");
        printMessage("turno %d", turn + 1);
        printMessage("\n**************************************\n");
        showGame();
        /*
         * per ogni giocatore G che non ha terminato il gioco: 
         * 1. se G  e' fermo per un turno cambia il suo stato in
         *      modo che al turno successivo venga rimesso in gioco 
         * 2. altrimenti viene lanciato il dado, mosso il giocatore
         *              e visualizzata la sua prova 
         */
        while (nextPlayer()) {
            int state = getPlayerState();

            if (state == ACTIVE || state == TEST_PASSED
                || state == TO_BE_ACTIVATED) {
                if (state != ACTIVE)
                    setPlayerState(ACTIVE, 0);
                movePlayer((rand() % 6) + 1);
                if (getPlayerBox() > getTotalBoxesNumber())
                    setPlayerState(DONE, turn);
                else
                    printMessage("player %s: \"%s\"\n",
                                 getPlayerName(),
                                 getDescription(getPlayerBox()));
            } else if (state == OUT_OF_TURN)
                setPlayerState(TO_BE_ACTIVATED, 0);
        }
        showGame();
        /*
         * Legge e registra l'esito di tutte le prove sostenute nel
         * turno corrente dai giocatori 
         */
        for (i = getActivePlayersNumber(); i > 0; i--) {
            int playerNumber;
            bool result;

            do {
                result = askPlayerResult(&playerNumber);
                if (playerNumber > totalPlayersNumber)
                    printErr("WARNING: player number %d out of "
                             "bounds [1; %d]\n", playerNumber,
                             totalPlayersNumber);
                else {
                    setCurrentPlayer(playerNumber);
                    if (getPlayerState() != ACTIVE)
                        printErr("WARNING: player number %d not "
                                 "valid because player:"
                                 "\n\t-won"
                                 "\n\t-is out of turn"
                                 "\n\t-already passed the test\n",
                                 playerNumber);
                }
            }
            while (playerNumber > totalPlayersNumber
                   || getPlayerState() != ACTIVE);
            if (result)
                setPlayerState(TEST_PASSED, 0);
            else
                setPlayerState(OUT_OF_TURN, 0);
        }
    }
    printScore();
    closeIoInterface();

    return EXIT_SUCCESS;
}
Esempio n. 23
0
int main(int argc, char *argv[]) 
{
	int i, j, board[6][6], hits[6][6], k, l, contHits=0, contErr=0, level;
	char in1[127], in2[127];
	time_t t;
	
	/* Creates a seed for rand() */
	srand(time(NULL));
	
	/* Creates the edges with the coordinates */
	for(i=0; i<6; i++)
		for(j=0; j<6; j++)
			board[i][j] = random(board);
			
	cls();
	
	printf("Select a level (1-3): ");
	scanf("%d",&level);
			
	t = time(NULL);
	
	for(i=0; i<6; i++)
		for(j=0; j<6; j++)
			hits[i][j] = TRUE;
	
	printBoard(board,hits,-1,-1,-1,-1,contHits, contErr);
	
	/* Wait 5*levels seconds */
	while(difftime(time(NULL),t) <= 5*level);
	
	for(i=0; i<6; i++)
		for(j=0; j<6; j++)
			hits[i][j] = FALSE;
	
	cls();
	
	
	while(game(hits))
	{		
		printBoard(board,hits, -1, -1, -1, -1, contHits, contErr);
		
		printf("Enter a line and column: ");
		scanf("%s %s", in1, in2);
		
		/* Conerts string to int */
		i = atoi(in1) - 1;
		j = atoi(in2) - 1;
		
		cls();
		
		if(i > 6 || j > 6 || i < 0 || j < 0 || hits[i][j])
			continue;
		
		printBoard(board,hits, i, j, -1, -1,contHits, contErr);
		
		printf("Enter a line and column: ");
		scanf("%s %s", in1, in2);
		
		k = atoi(in1) - 1;
		l = atoi(in2) - 1;
		
		if(k > 6 || l > 6 || k < 0 || l < 0 || hits[k][l])
			continue;
		
		t = time(NULL);
		
		if( !(k == i && l == i))
		{
			if(board[i][j] == board[k][l] && !hits[i][j])
			{
				hits[i][j] = TRUE;
				hits[k][l] = TRUE;
				contHits++;
			}
			else
			{
				cls();
				printBoard(board,hits,i,j,k,l,contHits, contErr);
				
				printf("Press enter to continue...");
				
				/* Clear input buffer */
				fseek(stdin,0,SEEK_END);
				
				fgetc(stdin);
				
				fseek(stdin,0,SEEK_END);
				
				while(difftime(time(NULL),t) <= 2);
				
				contErr++;
			}
		}
		
		cls();
	}
	

    return 0;
}
int main(void) {
  char inputMove, inputMove2, inputAI, gameOver;
  struct timeval t2, tLast;
  double elapsedTime;

  //initialize superBoard
  for (char i = 0; i < SUPER_BOARD_SIZE; i++) {
    superBoard[i] = -1;
  }

  while (1) {
    printf("\nWho will the AI play as? (X, O): ");
    scanf("%c", &inputAI);
    if (inputAI == 'X' || inputAI == 'x') {
      AI = X;
      break;
    } else if (inputAI == 'O' || inputAI == 'o') {
      AI = O;
      break;
    }

    //If we made it this far, invalid input
    printf("\nInvalid Selection\n");
  }

  while (1) {
    printBoard(subBoard);
    printSuperBoard(superBoard);

    while (1) {
      if (AI == currentPlayer) {
        //Start Timer
        gettimeofday(&t1, NULL);
        gettimeofday(&tLast, NULL);
        printf("\nAI calculating best move in (region %d)...\n", allowedSuperSpot);
        //AI always chooses the first spot as its move, so just set it.
        if (moves == 0) {
          inputMove = 40;
        } else {
          for (char i = 4; i < 16; i++) {
            char levelMove;
            printf("Calculating to level %d...\n", i);
            levelMove = getBestMove(subBoard, superBoard, allowedSuperSpot, currentPlayer, i);
            gettimeofday(&t2, NULL);
            elapsedTime = t2.tv_sec - tLast.tv_sec;
            printf("%f seconds elapsed for level %d\n", elapsedTime, i);
            elapsedTime = t2.tv_sec - t1.tv_sec;
            if (elapsedTime < MAX_TURN_TIME) {
              inputMove = levelMove;
            } else {
              printf("Failed to complete level %d, using level %d move", i, i-1);
              break;
            }
            tLast = t2;
          }
        }
        // stop timer
        gettimeofday(&t2, NULL);
        elapsedTime = (t2.tv_sec - t1.tv_sec);
        printf("\nAI moved to spot: %d (region %d)\n", inputMove, getSuperBoardSpot(inputMove));
        printf("Move took %f seconds\n", elapsedTime);
      } else {
        printf("\nEnter move (region %d): ", allowedSuperSpot);
        scanf("%d", &inputMove);
      }

      if (isOpenSpot(subBoard, superBoard, inputMove) && (getSuperBoardSpot(inputMove) == allowedSuperSpot || allowedSuperSpot == -1)) {
        break;
      } else {
        printBoard(subBoard);
        printf("\nInvalid move.\n");
      }

    }

    allowedSuperSpot = doMove(subBoard, superBoard, currentPlayer, inputMove);
    moves++;

    if (currentPlayer == X) {
      currentPlayer = O;
    } else {
      currentPlayer = X;
    }

    //Check if the game is over
    gameOver = superBoardWon(superBoard);
    if (gameOver == X) {
      printBoard(subBoard);
      printf("\nGame over, X wins.\n");
      exit(0);
    } else if (gameOver == O) {
      printBoard(subBoard);
      printf("\nGame over, O wins.\n");
      exit(0);
    } else if (gameOver == 0) {
      printBoard(subBoard);
      printf("\nGame over, tie.\n");
      exit(0);
    }
  }
}
Esempio n. 25
0
void xboard()
{
    char line[256], command[256], c;
    char args[4][64];
    int from, dest, i;
    MOVE moveBuf[200];
    MOVE theBest;
    int movecnt;
    //int illegal_king = 0;

    signal(SIGINT, SIG_IGN);

    printf ("\n");
//    hashKeyPosition(); /* hash of the initial position */
//    hashRndInit();
    startgame ();

    /* Waiting for a command from GUI */
    for (;;)
    {
        fflush (stdout);
        if (side == computerSide)
        {   /* Computer's turn */
            /* Find out the best move to reply to the current position */
            theBest = ComputerThink (maxDepth);
            if (theBest.type_of_move > 8)
                printf ("type of move the best %d \n", theBest.type_of_move);
            makeMove (theBest);
            /* send move */
            switch (theBest.type_of_move)
            {
            case MOVE_TYPE_PROMOTION_TO_QUEEN:
                c = 'q';
                break;
            case MOVE_TYPE_PROMOTION_TO_ROOK:
                c = 'r';
                break;
            case MOVE_TYPE_PROMOTION_TO_BISHOP:
                c = 'b';
                break;
            case MOVE_TYPE_PROMOTION_TO_KNIGHT:
                c = 'n';
                break;
            default:
                c = ' ';
            }
            printf ("move %c%d%c%d%c\n", 'a' + COL(theBest.from), 8
                    - ROW(theBest.from), 'a' + COL(theBest.dest), 8
                    - ROW(theBest.dest), c);

            fflush(stdout);
            continue;
        }

        if (!fgets (line, 256, stdin))
            return;
        if (line[0] == '\n')
            continue;
        sscanf (line, "%s", command);

        if (!strcmp (command, "xboard"))
        {
            continue;
        }
        if (!strcmp (command, "d"))
        {
            printBoard ();
            continue;
        }
        if (!strcmp (command, "new"))
        {
            startgame ();
            continue;
        }
        if (!strcmp (command, "quit"))
        {
            return;
        }
        if (!strcmp (command, "force"))
        {
            computerSide = EMPTY;
            continue;
        }
        /* If we get a result the engine must stop */
        if (!strcmp(command, "result"))
        {
            computerSide = EMPTY;
            continue;
        }
        if (!strcmp(command, "?")) {
            computerSide = EMPTY;
            continue;
        }
        if (!strcmp(command, ".")) {
            continue;
        }
        if (!strcmp(command, "exit")) {
            continue;
        }
        if (!strcmp(command,"setboard"))
        {
            strcpy(fenBuf, "");
            sscanf(line, "setboard %s %s %s %s", args[0],args[1],args[2],args[3]);
            strcat(fenBuf, args[0]);
            strcat(fenBuf, args[1]);
            strcat(fenBuf, args[2]);
            strcat(fenBuf, args[3]);
            setBoard(fenBuf);
            continue;
        }
        if (!strcmp (command, "white"))
        {
            side = WHITE;
            computerSide = BLACK;
            continue;
        }
        if (!strcmp (command, "black"))
        {
            side = BLACK;
            computerSide = WHITE;
            continue;
        }
        if (!strcmp (command, "sd"))
        {
            sscanf (line, "sd %d", &maxDepth);
            continue;
        }
        if (!strcmp (command, "go"))
        {
            computerSide = side;
            continue;
        }
        /* Taken from TSCP: we receive from the GUI the time we have */
        if (!strcmp(command, "time"))
        {
            sscanf (line, "time %ld", &maxTime);
            /* Convert to miliseconds */
            maxTime *= 10;
            maxTime /= 10;
            maxTime -= 300;
            totalTime = maxTime;

//            if (totalTime < 3000)
//                maxDepth = 6;
//            else
            maxDepth = 32;
            continue;
        }
        if (!strcmp(command, "otim"))
        {
            continue;
        }
        if (!strcmp (command, "undo"))
        {
            if (hdp == 0)
                continue;
            takeBack ();
            continue;
        }
        if (!strcmp (command, "remove"))
        {
            if (hdp <= 1)
                continue;
            takeBack ();
            takeBack ();
            continue;
        }

        /* Maybe the user entered a move? */
        /* Is that a move? */
        if (command[0] < 'a' || command[0] > 'h' ||
                command[1] < '0' || command[1] > '9' ||
                command[2] < 'a' || command[2] > 'h' ||
                command[3] < '0' || command[3] > '9')
        {
            printf("Error (unknown command): %s\n", command); /* No move, unknown command */
            continue;
        }

        from = command[0] - 'a';
        from += 8 * (8 - (command[1] - '0'));
        dest = command[2] - 'a';
        dest += 8 * (8 - (command[3] - '0'));
        ply = 0;
        movecnt = genMoves (side, moveBuf);

        /* Loop through the moves to see if it's legal */
        for (i = 0; i < movecnt; ++i) {
            if (moveBuf[i].from == from && moveBuf[i].dest == dest)
            {
                if (piece[from] == PAWN && (dest < 8 || dest > 55))
                {
                    if (command[4] != 'q' && command[4] != 'r' && command[4] != 'b' && command[4] != 'n')
                    {
                        printf ("Illegal move. Bad letter for promo\n");
                        goto goon;
                    }
                    switch (command[4])
                    {
                    case 'q':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_QUEEN;
                        break;
                    case 'r':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_ROOK;
                        break;
                    case 'b':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_BISHOP;
                        break;
                    case 'n':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_KNIGHT;
                        break;
                    }
                }

                if (moveBuf[i].type_of_move > 8)
                    printf ("Type of move the best %d \n", moveBuf[i].type_of_move);

                if (makeMove (moveBuf[i]))
                {
                    goto goon;	/* Legal move */
                }
                else {
                    printf ("Illegal move. King is in check\n");
                    goto goon;
                }
            }
        }
        printf ("Illegal move.\n");  /* illegal move */

goon:
        continue;
    }
}
Esempio n. 26
0
bool MakeMultipleMovesTest()
{
	//you should see somthing like:
	// 3  2  1   (might also be with 4)
	//-3 -2 -1   (might also be with -4)
	char* moduleName = getModule();
	char board[BUFFER_SIZE+1];
	board[BUFFER_SIZE]='\0'; // <---- might be redundant but i cant leave it like that! it's a disturbia
	int a;
	int b;
	int status;
	int pid1 = fork();
	if(pid1 == 0) {
		char nextMove[5];
		nextMove[0] = DOWN; 
		nextMove[1] = RIGHT; 
		nextMove[2] = RIGHT; 
		nextMove[3] = RIGHT; 
		nextMove[4] = '\0'; 
		//player 1 (white)
		a=open(moduleName, O_RDWR);
		ASSERT(a>=0);

		int writeval = write(a, nextMove, 4);	
		//ASSERT(writeval == 4);

		doLongTask();
		close(a);
		_exit(0);
	} else {
		int pid2 = fork();
		if(pid2 == 0) {
			char nextMove[5];
			nextMove[0] = UP;
			nextMove[1] = RIGHT; 
			nextMove[2] = RIGHT; 
			nextMove[3] = RIGHT; 
			nextMove[4] = '\0'; 

			doLongTask();
			//player 2 (black)
			b=open(moduleName, O_RDWR); 
			ASSERT(b>=0);

			int writeval = write(b, nextMove, 4);	
			//ASSERT(writeval == 4);


			//board after move
			int readRes = read(b, board, BUFFER_SIZE);	
			ASSERT(readRes == BUFFER_SIZE);
			printBoard(board);

			doLongTask();
			close(b);
			_exit(0);
		} else {
			wait(&status);
		}
		wait(&status);
	}	
    return true;
}
Esempio n. 27
0
int main()
{
    char line[256];
    char args[4][64];

    /* It mainly calls ComputerThink(maxdepth) to calculate to desired ply */
    char s[256];
    int from;
    int dest;
    int i;

    hashRndInit();
    startgame ();

    maxDepth = 6;		/* Max depth to search */
    MOVE moveBuf[200];
    MOVE theBest;
    int movecnt;

    /* Belka */
    puts (" \n Kitteneitor version June 5th 2013 by Emilio Diaz \n =================================================\n\n");
    puts (" Help overview:");
    puts (" making a move: e.g. e2e4, c7c5, a7a8q, e1g1 etc.");
    puts (" d ............ displaying current board");
    puts (" on ........... forcing the engine to move");
    puts (" sd <n> ....... setting depth to <n> plies");
    puts (" undo ......... taking back last move (ply)");
    puts (" quit ......... quit console application \n\n");
    /* Belka */

    side = WHITE;
    computerSide = BLACK;	/* Human is white side */

    hdp = 0;			/* Current move order */
    for (;;)
    {
        fflush (stdout);
        if (side == computerSide)
        {
            /* Computer's turn */
            theBest = ComputerThink (maxDepth);

            if (theBest.type_of_move > 8)
                printf ("type of move the best %d \n", theBest.type_of_move);

            makeMove (theBest);

            /* Just the move without pawn crown */
            printf("move %c%d%c%d",
                   'a' + COL(theBest.from),
                   8 - ROW(theBest.from),
                   'a' + COL(theBest.dest),
                   8 - ROW(theBest.dest));
            /* Check whether it's a crown */
            switch (theBest.type_of_move)
            {
               case MOVE_TYPE_PROMOTION_TO_QUEEN:
                  printf("q\n");
                  break;
               case MOVE_TYPE_PROMOTION_TO_ROOK:
                  printf("r\n");
                  break;
               case MOVE_TYPE_PROMOTION_TO_BISHOP:
                  printf("b\n");
                  break;
               case MOVE_TYPE_PROMOTION_TO_KNIGHT:
                  printf("n\n");
                  break;
               default:
                  printf("\n");
            }   /* end switch */

            printBoard ();
            printf ("Castle rights: %d\n", castle);
            fflush (stdout);
            continue;
        }

        printf ("k> ");

        /* Get user input */
        if (!fgets (line, 256, stdin))
            return 0;
        if (line[0] == '\n')
            continue;
        sscanf (line, "%s", s);

//        if (scanf ("%s", s) == EOF)	/* Shut down the program */
//            return 0;

        if (!strcmp (s, "d"))
        {
            printBoard ();
            continue;
        }
        if (!strcmp (s, "test1"))
        {
            test1 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test2"))
        {
            test2 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test3"))
        {
            test3 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test4"))
        {
            test4 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test5"))
        {
            test5 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test6"))
        {
            test6 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test7"))
        {
            test7 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test8"))
        {
            test8 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test9"))
        {
            test9 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test10"))
        {
            test10 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test11"))
        {
            test11 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test12"))
        {
            test12 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test13"))
        {
            test13 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "test14"))
        {
            test14 ();
            printBoard();
            continue;
        }
        if (!strcmp (s, "testMoveGen")) //Belka: McKenzie test position
        {
            testMoveGen();
            printBoard();
            continue;
        }
        if (!strcmp (s, "testEvalSym")) //Belka: McKenzie test position
        {
            testEvalSym();
            continue;
        }
        if (!strcmp (s, "countNodes"))
        {
            countNodes();
            continue;
        }
        if (!strcmp (s, "testWhitePassedPawns"))
        {
            testWhitePassedPawns ();
            continue;
        }
        if (!strcmp (s, "testBlackPassedPawns"))
        {
            testBlackPassedPawns ();
            continue;
        }
        if (!strcmp (s, "testWhiteDoubledPawns"))
        {
            testWhiteDoubledPawns ();
            continue;
        }
        if (!strcmp (s, "testBlackDoubledPawns"))
        {
            testBlackDoubledPawns ();
            continue;
        }
        if (!strcmp (s, "testIsIsolatedPawnWhite"))
        {
            testIsIsolatedPawnWhite ();
            continue;
        }
        if (!strcmp (s, "testIsIsolatedPawnBlack"))
        {
            testIsIsolatedPawnBlack ();
            continue;
        }
        if (!strcmp (s, "showPawnsInfo"))
        {
            showPawnsInfo ();
            continue;
        }
        if (!strcmp (s, "testisSqProtectedByAPawn"))
        {
             testisSqProtectedByAPawn();
            continue;
        }
//        if (!strcmp (s, "testIsSqProtectedByAKnight"))
//        {
//             testIsSqProtectedByAKnight();
//            continue;
//        }
//        if (!strcmp (s, "testIsSqProtectedByABishop"))
//        {
//             testIsSqProtectedByABishop();
//            continue;
//        }
        if (!strcmp (s, "testOpenCols"))
        {
             testOpenCols();
            continue;
        }
        if (!strcmp (s, "undo"))
        {
            takeBack ();
            printBoard ();
            computerSide = (WHITE + BLACK) - computerSide;
            continue;
        }
        if (!strcmp(s,"setboard"))
        {
            strcpy(fenBuf, "");
            sscanf(line, "setboard %s %s %s %s", args[0],args[1],args[2],args[3]);
            strcat(fenBuf, args[0]);
            strcat(fenBuf, args[1]);
            strcat(fenBuf, args[2]);
            strcat(fenBuf, args[3]);
            setBoard(fenBuf);
            continue;
        }
        if (!strcmp (s, "xboard"))
        {
            xboard ();
            return 0;
        }
        if (!strcmp (s, "on"))
        {
            computerSide = side;
            continue;
        }
        if (!strcmp (s, "pass"))
        {
            side = (WHITE + BLACK) - side;
            computerSide = (WHITE + BLACK) - side;
            continue;
        }
        if (!strcmp (s, "sd"))
        {
            sscanf (line, "sd %d", &maxDepth);
            continue;
        }

//        if (!strcmp (s, "fen"))
//        {
//            strcpy (fenstring, "");

//            sscanf (linea, "fen %s %s %s %s", args[0], args[1], args[2],
//                    args[3]);

//            strcat (fenstring, args[0]);
//            strcat (fenstring, args[1]);
//            strcat (fenstring, args[2]);
//            strcat (fenstring, args[3]);

//            fen (fenstring);
//        }

        if (!strcmp (s, "perft"))
        {
            sscanf (line, "perft %d", &maxDepth);
            clock_t start;
            clock_t stop;
            double t = 0.0;
            /* Start timer */
            start = clock ();
            U64 count = perft (maxDepth);
            /* Stop timer */
            stop = clock ();
            t = (double) (stop - start) / CLOCKS_PER_SEC;
//            printf ("nodes = %'llu\n", count);
            printf ("nodes = %8"  PRId64 "\n", count); // Belka
            printf ("time = %.2f s\n", t);
            continue;
        }
        if (!strcmp (s, "quit"))
        {
            printf ("Good bye!\n");
            return 0;
        }

        /* Maybe the user entered a move? */
        from = s[0] - 'a';
        from += 8 * (8 - (s[1] - '0'));
        dest = s[2] - 'a';
        dest += 8 * (8 - (s[3] - '0'));
        ply = 0;
        movecnt = genMoves (side, moveBuf);

        /* Loop through the moves to see whether it's legal */
        for (i = 0; i < movecnt; i++)
            if (moveBuf[i].from == from && moveBuf[i].dest == dest)
            {
                /* Promotion move? */
                if (piece[from] == PAWN && (dest < 8 || dest > 55))
                {
                    switch (s[4])
                    {
                    case 'q':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_QUEEN;
                        break;

                    case 'r':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_ROOK;
                        break;

                    case 'b':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_BISHOP;
                        break;

                    case 'n':
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_KNIGHT;
                        break;

                    default:
                        puts("Promoting to a McGuffin..., I'll give you a queen");
                        moveBuf[i].type_of_move = MOVE_TYPE_PROMOTION_TO_QUEEN;
                    }
                }
                if (!makeMove (moveBuf[i]))
                {
                    takeBack ();
                    printf ("Illegal move.\n");
                }
                break;
            }
        printBoard ();
    }
}
Esempio n. 28
0
int runBall(struct Obstacle * surface[51][51], int m, int n, struct Ball * ball) {
	int i, j, points = 0, nextX, nextY;
	if (DEBUG) {
		printBoard(surface, m, n, ball);
	}
	while (ball->lifetime > 0) {
		ball->lifetime--;
		if (ball->direction == 0) {
			/**
			 * right
			 */
			nextX = ball->x + 1;
			nextY = ball->y;
		} else if (ball->direction == 1) {
			/**
			 * up
			 */
			nextX = ball->x;
			nextY = ball->y + 1;
		} else if (ball->direction == 2) {
			/**
			 * left
			 */
			nextX = ball->x - 1;
			nextY = ball->y;
		} else if (ball->direction == 3) {
			/**
			 * down
			 */
			nextX = ball->x;
			nextY = ball->y - 1;
		}

		if (surface[nextX][nextY] != NULL) {
			/**
			 * hit wall or bumper
			 */
			if (ball->lifetime > 0) {
				ball->lifetime -= surface[nextX][nextY]->cost;
				/**
				 * still live and get points
				 */
				points += surface[nextX][nextY]->value;
				/**
				 * turn right 90 degree
				 */
				ball->direction = (ball->direction + 3) % 4;
			}
		} else {
			/**
			 * hit nothing
			 */
			ball->x = nextX;
			ball->y = nextY;
		}
		if (DEBUG) {
			printBoard(surface, m, n, ball);
		}
	}
	return points;
}
Esempio n. 29
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;
}