Exemple #1
0
bool Game::startGame(int size){
	this->length= size;
	newBoard(this->length);
	bool gameEnd = false;
	bool victory = false;
	do
	{
		insertNewNumber();
		if (checkIfGameOver() == true){
			break;
		}
		string oldNumber = uniqNumber();

		string message = "Press up, down, left, right or q for quit";
		while (1){
			PrintBoard();
			string d = input(message);
			if (d == "quit"){
				gameEnd=true;
				break;
			}
			moveDirection(d);	//left worked
			if (oldNumber != uniqNumber()){
				break;
			}
			message = "You can't go there, try another button or q for quit";
		}
		if (victory==false){
			victory = checkIfVictorius();
		}
	}
	while(gameEnd==false);
	PrintBoard();
	return victory; 
}
Exemple #2
0
int main()
{
    char GameBoard[GameHeigth][GameWidth] = {" "};  //Skapar plan-arrayen
    int NumberOfTurns = 0,Starter;  //Antal rundor, vem som startar
    int MaxRounds = GameHeigth*GameWidth;   //Antal maxrundor=bredd*höjd

    unsigned seed;
    seed = (unsigned)time(NULL); //Seed för random
    srand(seed);
    Starter = 1+(rand()%2);



    if(Starter==1) //Om spelaren ska börja
	{
        printf("You start!\n");
        for(; ; ) //Manuellt exitad loop
        {
        PrintBoard(GameBoard); //Skriv ut planen
        PlayerMove(GameBoard); //Be spelaren lägga ut en markör
        CheckWin(GameBoard); //Kolla om någon vunnit
        NumberOfTurns++;

			 if(NumberOfTurns == MaxRounds) //Om antalet rundor = maxrundor avsluta spelet
			 {
				   printf("Draw!");
				  break;
			 }

        ComputerMove(GameBoard); //Slumpa en position åt datorn
        CheckWin(GameBoard); //Kolla om någon vunnit
        NumberOfTurns++;

        }
    }
    else if(Starter==2)	//Om datorn ska börja
    {
        printf("Ai starts!\n");
        for(; ; )
        {
        ComputerMove(GameBoard);
        CheckWin(GameBoard);
        NumberOfTurns++;
			 if(NumberOfTurns == MaxRounds)
			 {
				  printf("Draw");
				  break;
			 }
        PrintBoard(GameBoard);
        PlayerMove(GameBoard);
        CheckWin(GameBoard);
        NumberOfTurns++;


        }

    }

    return 0;
}
int main()
{
	struct board_t board;
	int winner = 0;
	int pTurn = 0;
	int pCard = 0;
	int mLane = 0;
	struct card_t generatedCard;
	struct deck_t generatedDeck = GenerateMultipleCards(30);
	WriteGeneratedDeckToFile(&generatedDeck,"idiocracy.csv");
	generatedCard = GenerateCard();
	print_card(generatedCard,1);
	// INIT STUFF HERE !
	if (!init_board(&board)) {
		printf("Error.File Not Found! WTF, DO NOT TOUCH THE DATA !\n");
		return -1;
	}
	// =================
	winner = 0;
	while(winner == 0) {
		pCard = 0;
		turn_begin(&board.Player[pTurn]);
		//Print Board Here !
		PrintBoard(board);
		//==================
		if (pTurn == 0) 
		while (pCard != 6) {
			printf("Choose card:");
			scanf("%d",&pCard);
			if (pCard !=6 && board.Player[pTurn].Open_Spots_Hand[pCard-1] != 1) {
				printf("\nChoose lane:");
				scanf("%d",&mLane);
				int result = play_card(&board,pTurn,pCard-1,mLane-1);
						PrintBoard(board);
			}		
			
		}
		else RunSimpleAI(&board,pTurn);
		turn_end(&board,pTurn);
		if (board.Player[pTurn].health <= 0) {				
			winner = 1-pTurn;		
			break;	
		}		
		pTurn = 1-pTurn;				
	}
	printf("\n\nWinner is Player: %d\n\n",winner+1);
	
	return 0;
}
void SelfPlay()
{
	printf("\n\n--------------The Bot Will Now Play itself to Some Randomized Depth-------------\n\n");
	printf("Press Any Key To See The Next Move\n");
	BOARD *board=new BOARD;
	SetStart(board);
	getchar();
	while(1)
	{
		MOVE *list=new MOVE;
		GenMoves(board,list);
		if(list->Count==0)
		{
			printf("%c LOST THE GAME\n\n",PceSideChar[board->Side]);
			break;
		}
		int Depth=5+rand()%4;
		vector<int>BestMove=SearchPos(board,Depth);
		PrintBoard(board);
		MakeMove(board,BestMove);
		getchar();
		getchar();
	}
	StartGame();
}
Exemple #5
0
int PlayGame(int *Parameter){

    Board gameBoard,nextBoard;
    int i;
    int maxLevel;

    InitGame(gameBoard);
    PrintBoard(gameBoard);

    while (1){
        NextStep(nextBoard,gameBoard, Parameter, COUNT_STEP, MoveLeft, MoveRight, MoveUp, MoveDown);
        UpdateBoard(gameBoard,nextBoard);
        maxLevel = FinishGame(gameBoard);
        if ( maxLevel != 0){
            break;
        }
        if (PLAY_MODE == 1)
            if ( TotalScore > 1000)
                Sleep(1000);
            else
                Sleep(100);
    }

    return maxLevel;
}
Exemple #6
0
void FindSudoku(int board[V][V]){


int buffer[V][V];

int i;
int j;

for(i=0;i<V;i++){
for(j=0;j<V;j++){

buffer[i][j]=board[i][j];

}
}

if(FindSudoku_Util(buffer)){
PrintBoard(buffer);
}else{
printf("\nThis sudoku cant be solved");
}





}
Exemple #7
0
int main(){
	
	int board[25];
	InitialiseBoard(&board[0]); //reference address for pointers as first element of array
	PrintBoard(&board[0]);
	return 0;
}
Exemple #8
0
/**
 * @brief  main 
 *
 * @param  argc
 * @param  argv[]
 *
 * @return  
 */
int main ( int argc, char *argv[] ) { 
	char board[N][N] = { {0,0} };
//	int *player = &Player;
	int x = 0, y =0;
	int flag = 2;
	status s = -1;
	CreateBoard(board);
	while ( true ) {
		PrintBoard(board, x, y);
		PrintInfo(flag, Player);
		if ( s == WIN ) {
			printf ( "\033[33mSome one win!\n\033[0m" );
			break;
		}
		s = PlayChess(board, Player, &x, &y);
		if ( s == -1 ) continue;
		if ( s == RES ) {
			printf ( "Someone rescinded!\n" );
		}
		if ( s == QUIT ) {
			printf ( "Gave Over\n" );
			break;
		}
		s =  CheckBoard(board, Player, &x,&y);
		Player = ( Player + 1 ) % 2;

	}
	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */
Exemple #9
0
void PrintAll(tGame * game, tCommand * command)
{
	DELSHELL();

	PrintBoard(&game->visualboard);
	
	printf("%s", KMSG);
	if (game->gametype)
		printf("Movimientos restantes: %d\n", game->moves);
	
	printf("Undos restantes: %d\n", game->undos);
	printf("Flags restantes: %d\n", game->flags_left);
	
	if (command->command_ref == COMMAND_QUERY)
	{
		PrintQuery(&command->query);
		free(command->query.results.array);
	}
	else if (command->command_ref == COMMAND_UNDO && \
			(command->undo.undo_error == TRUE))
	{
		printf("%s%s\n", KERR, UNDO_ERR);
		command->undo.undo_error = FALSE;
	}
	printf("%s", KDEF);
	return;
}
Exemple #10
0
void PerftTest(int depth, S_BOARD *pos) {
	S_MOVELIST list[1];
	int move;
	int MoveNum = 0;
	int start = GetTimeMs();
	long cumnodes, oldnodes;

	ASSERT(CheckBoard(pos));

	PrintBoard(pos);
	printf("\nStarting Test To Depth:%d\n", depth);
	leafNodes = 0;
	
	GenerateAllMoves(pos, list);

	for(MoveNum = 0; MoveNum < list->count; ++MoveNum) {
		move = list->moves[MoveNum].move;
		if(!MakeMove(pos, move))
			continue;

		cumnodes = leafNodes;
		Perft(depth - 1, pos);
		TakeMove(pos);
		oldnodes = leafNodes - cumnodes;
		printf("move %d : %s : %ld\n", MoveNum + 1, PrMove(move), oldnodes);
	}

	printf("\nTest Complete : %ld nodes visited in %dms\n", leafNodes, GetTimeMs() - start);
}
Exemple #11
0
void main(){
	char nice='y';
	while(nice == 'y'){
		char winner = 'N';
		bool turn=true, validty;
		int move, counter=1, i, m=49;
		char board[9];
		for (i=0; i<9; i++){
			board[i] = m;
			m++;
		}
		PrintBoard(board);
		while (winner == 'N'){
			printf("Where do you want to go? Pick an available number: ");
			scanf("%d", &move);
			validty = IsValidMove(board, move-1);
			while (validty==false || board[move-1]=='X' || board[move-1]=='O'){
				printf("INVALID MOVE. PICK AGAIN.\n");
				printf("Where do you want to go? Pick an available number: ");
				scanf("%d", &move);
				validty = IsValidMove(board, move-1);
			}
			if (turn)
				board[move-1] = 'X';
			else
				board[move-1] = 'O';
			PrintBoard(board);
			winner = WinnerIfAny(board);
			if (counter==9 && winner=='N')
				winner = 'S';
			turn = !turn;
			counter++;
		}
		if(winner != 'S')
			printf("CONGRATULATIONS PLAYER %c!!! YOU WON!!!\n", winner);
		else
			printf("STAKENATE!!!\n");
		printf("Would you like to play another game?(y/n):");
		flushall();
		scanf("%c", &nice);
	}
}
Exemple #12
0
int main()
{
	struct card_t card[2];
	struct deck_t deck1;
	struct player_t Player1;
	struct board_t board;
	int winner = 0;
	int pTurn = 0;
	int pCard = 0;
	int mLane = 0;
	// INIT STUFF HERE !
	if (!init_board(&board)) {
		printf("Error.File Not Found! WTF, DO NOT TOUCH THE DATA !\n");
		return -1;
	}
	// =================
	winner = 0;
	while(winner == 0) {
		pCard = 0;
		turn_begin(&board.Player[pTurn]);
		//Print Board Here !
		PrintBoard(board);
		//==================
		while (pCard != 6) {
			printf("Choose card:");
			scanf("%d",&pCard);
			if (pCard !=6 && board.Player[pTurn].Open_Spots_Hand[pCard-1] != 1) {
				printf("\nChoose lane:");
				scanf("%d",&mLane);
				int result = play_card(&board,pTurn,pCard-1,mLane-1);
						PrintBoard(board);
			}		
			
		}
		turn_end(&board,pTurn);
		pTurn = 1-pTurn;	
		if (board.Player[pTurn].health <= 0) winner = pTurn+1;	
	}
	if("\n\nWinner is Player: %d\n\n",winner);
	
	return 0;
}
Exemple #13
0
int main( int , char * [] ) {
    double runTime = PerfTime();

    LoadGrid();
    LoadDic();
    PrintBoard();
    BoardValid();
    LoadBoardState();
    StashBoardState();
    PrintBoard();
    BoardValid();

    double setupEnd = PerfTime();

    // find all the seed points
    Coords seedPoints = GetSeedPoints();
    logf( 1, CLEAR "Seed\n" );
    for( auto i : seedPoints ) {
        logf( 1, CLEAR "%i,%i\n", i.x, i.y );
    }

    // for each seed point:

    // find all words for that point, score them, from highest score down, validate them

    // return the highest seed point highest scoring word

    double checking = PerfTime();
    int scoreBefore = BoardScore();
    AddAndCheck( "voi", 3, 4, HORIZONTAL );
    int scoreAfter = BoardScore();
    logf( 1, CLEAR "Score diff = %i (%i -> %i)\n", scoreAfter - scoreBefore, scoreBefore, scoreAfter );
    //PrintBoard();
    BoardValid();

    double done = PerfTime();
    logf( 1, CLEAR "Timing (%f s) Loading\n", setupEnd - runTime );
    //logf( 1, CLEAR "Timing (%f s) Preparing\n", prepared-prepping);
    logf( 1, CLEAR "Timing (%f s) running\n", done-checking );

    return 0;
}
Exemple #14
0
void PrintResult(tGame * game)
{
	switch (game->gamestate)
	{
		case GAMESTATE_WIN:
			PrintBoard(&game->visualboard);
			printf ("%sGanaste!%s\n", KEXC, KDEF);
			if (game->gametype == GAMETYPE_CAMPAIGN)
				game->campaign_level++;
			break;

		case GAMESTATE_CANTWIN:
			printf("%s%s%s\n", KEXC, NOMOVES_ERR, KDEF);
			game->gamestate = GAMESTATE_LOSE;
		case GAMESTATE_LOSE:
			PrintBoard(&game->hiddenboard);
			printf("%sPerdiste!%s\n", KEXC, KDEF);
			break;	
	}
}
Exemple #15
0
void MirrorEvalTest(S_BOARD *pos) {
	FILE *file;
	char lineIn [1024];
	int ev1 = 0; int ev2 = 0;
	int positions = 0;

	file = fopen("mirror.epd","r");

	if(file == NULL) {
		printf("File Not Found\n");
		return;
	} else {
		while(fgets (lineIn, 1024, file) != NULL) {
			ParseFen(lineIn, pos);
			positions++;
			ev1 = EvalPosition(pos);
			MirrorBoard(pos);
			ev2 = EvalPosition(pos);

			if(ev1 != ev2) {
				printf("\n\n\n");
				ParseFen(lineIn, pos);
				PrintBoard(pos);
				MirrorBoard(pos);
				PrintBoard(pos);
				printf("\n\nMirror Fail:\n%s\n", lineIn);
				getchar();
				return;
			}

			if((positions % 1000) == 0) {
				printf("position %d\n", positions);
			}

			memset(&lineIn[0], 0, sizeof(lineIn));
		}
	}
}
Exemple #16
0
void DoGame(game_state_t * game)
{

	//white always start
	color_t current_player = COLOR_WHITE;

	//print board first time
	PrintBoard(game);

	//play until somebody won
	while (!GameWinning(game,COLOR_BLACK) && !GameWinning(game,COLOR_WHITE))
	{
		if (Settings_UserColor_Get()==current_player)
		{
			UserTurn (game);
		}
		else
		{
			CPUTurn(game);
		}

		//print board after turn
		PrintBoard(game);

		//switch player
		current_player = (current_player==COLOR_WHITE) ? COLOR_BLACK : COLOR_WHITE;
	}

	//print winning side
	if (GameWinning(game,COLOR_BLACK))
	{
		printf("black player wins!\n");
	}
	else
	{
		printf("white player wins!\n");
	}
}
Exemple #17
0
void Trial(int i) {
    // 进入本函数时,在SCALE×SCALE棋盘前的i-1行已放置了互不攻击的i-1个棋子
    // 现从第i行起继续为后续棋子选择合适的位置
    // 当i>n时,秋的一个合法布局,输出之
    int j;
    if(i>=SCALE) {
        printf("No. %d\n",count);
        PrintBoard();
        count++;
    }
    else for(j=0; j<SCALE; j++) {
            PlaceChess(i,j);
            if(TRUE==IsValidLayout())
                Trial(i+1);
            RemoveChess(i,j);
        }
}
Exemple #18
0
/* Runs a breadth-first, queue-based algorithim to find minimum number of moves until the entire board has been 'covered'. 
*/
void RunTour(){
	Path path; 
	Queue<Path >queue;
	Grid<int> board= InitBoard();
	int iterations=NOT_VISITED;
	path.numMoves=NOT_VISITED;
	path.currX=STARTX;
	path.currY=STARTY;
	queue.enqueue(path);
	while (!queue.isEmpty()) {  
		path = queue.dequeue(); 
		if (path.numMoves>iterations){
			iterations=path.numMoves;
			PrintBoard (board, path);
		}
		EnqueueMoves(path, queue, board);
	}
}
void HandleDisconnect(int reason, ENetPeer* source)
{	
	Player* p = board->getPlayerByAddress((int)source);
	ostringstream output;
	if (p != NULL) {
		if (board->isStarted()) {
			// mark player as lost
			p->isDefeated(true);
			output << "SD" << p->getId() << "\0";
			Broadcast(output.str().c_str(),true);
			printf("Player %d disconnected. Signalled as lost.\n",p->getId());
		} else {
			// remove player from play list
			board->removePlayer(p->getId());
			printf("Player %d disconnected. Removed from player list.\n",p->getId());
		}
		PrintBoard();
	}
	// Aw, someone left the game.
}
Exemple #20
0
int AskUndo(tGame * game, tUndo * undo)
{
	char input[MAX_COMMAND_LEN];
	char * pinput;

	int wasundo = FALSE;
	int wasquit = FALSE;

	PrintBoard(&game->visualboard);

	printf("%sPerdiste! ¿Hacer Undo? (Ingresar undo o quit)%s\n", KASK, KDEF);

	do{
		pinput = fgets(input, MAX_COMMAND_LEN, stdin);
		if (pinput != NULL)
		{
			wasundo = (strcmp(input,"undo\n") == 0);
			wasquit = (strcmp(input,"quit\n") == 0);
		}

		if (!wasundo && !wasquit)
			printf("%s%s%s\n", KERR, ASKUNDO_ERR, KDEF);
	}
	while ( (!wasundo && !wasquit) || (pinput == NULL));


	if (wasundo)
	{
		Undo(game, undo);
		game->undos--;
		if (game->gametype != GAMETYPE_INDIVIDUAL_NOLIMIT)
			game->moves--;
		return TRUE;
	}
	else
	{
		game->gamestate = GAMESTATE_LOSE;
		return FALSE;
	}

}
Exemple #21
0
void AddAndCheck( const char *letters, int arow, int acol, bool vert ) {
    int row = arow;
    int col = acol;

    while( *letters ) {
        int cell = row * 15 + col;
        board_state[ cell ] = *letters;

        // advance
        if( !vert ) {
            col += 1;
        } else {
            row += 1;
        }
        ++letters;
    }
    if( !BoardValid() ) {
        PrintBoard();
        RecoverBoardState();
    }
}
Exemple #22
0
int MoveListOk(const S_MOVELIST *list,  const S_BOARD *pos) {
	if(list->count < 0 || list->count >= MAXPOSITIONMOVES) {
		return FALSE;
	}

	int MoveNum;
	int from = 0;
	int to = 0;
	for(MoveNum = 0; MoveNum < list->count; ++MoveNum) {
		to = TOSQ(list->moves[MoveNum].move);
		from = FROMSQ(list->moves[MoveNum].move);
		if(!SqOnBoard(to) || !SqOnBoard(from)) {
			return FALSE;
		}
		if(!PieceValid(pos->pieces[from])) {
			PrintBoard(pos);
			return FALSE;
		}
	}

	return TRUE;
}
void Test_CPUTurn (game_state_t * game)
{

	//put a piece in position
	position_t pos;
	char identity;

	pos = Position ('d', 4);
	identity = WHITE_M;
	SetPiece(pos, identity, game);
	piece_t piece1 ;
	piece1.identity = identity;
	piece1.position = pos;

	pos = Position ('c', 5);
	identity = BLACK_M;
	SetPiece(pos, identity, game);
	piece_t piece2 ;
	piece2.identity = identity;
	piece2.position = pos;

	pos = Position ('d', 2);
	identity = WHITE_K;
	SetPiece(pos, identity, game);
	piece_t piece3 ;
	piece3.identity = identity;
	piece3.position = pos;

	//b,2
	pos = Position ('b', 2);
	identity = WHITE_K;
	SetPiece(pos, identity, game);

	PrintBoard(game);


	CPUTurn(game);
}
int main()
{
    struct board_t boardd;
    int player = 0;

    init_board(&boardd);



    init_deck(&boardd.Player[player].deck);
    card_generator( &boardd, player);
    //deck_from_file(&boardd, "ggop.txt", player);
    init_player(&boardd.Player[player]);
    init_manapool(&boardd.Player[player].manapool);


    init_deck(&boardd.Player[player + 1].deck);
    //card_generator( *boardd, player + 1);
    deck_from_file(&boardd, "ggopme.txt", player + 1);
    init_player(&boardd.Player[player +1]);
    init_manapool(&boardd.Player[player + 1].manapool);

    int i;
    for(i = 0; i < 5; i++){
        turn_begin( &boardd.Player[player]);
        turn_begin( &boardd.Player[player + 1]);
    }

    int card;
    int board_num = 0;
    int board_num2 = 0;
    int choice;
    player++;

    do{
  

    if ( bot(&boardd,&board_num2) == 1 ) board_num2++; 

    PrintBoard(boardd);

   


    scanf("%d",&choice);
    if (choice > 0 && choice <= 5 ){
        card = choice - 1;
        if (play_card(&boardd, player, card, board_num) == 1 ) {
                boardd.Card_Positions[board_num][player] = 0;
                board_num++;
		boardd.Player[player].manapool.left -= boardd.Player[player].cards_in_hand[card].magic_cost;
		
		/*struct card_t card_to_use;
		draw_card(&boardd.Player[player].deck, &card_to_use);
		boardd.Player[player].cards_in_hand[card] = card_to_use;*/
		
        }
    }
	
    PrintBoard(boardd);

    turn_end(&boardd, player, &board_num, &board_num2);

    PrintBoard(boardd);
	
    char a; scanf("%s",&a);

    //system("cls");
    printf("\033[2J\033[1;1H");

	if(board_num >= 5) board_num = 0;
	if(board_num2 >= 5) board_num2 = 0;

    }while(boardd.Player[player].health > 0 && boardd.Player[1 - player].health > 0);

    if(boardd.Player[player].health > 0) printf("Ti pechelish ;) \n");
        else printf("Ti gubish\n");

    return 0;
}
Exemple #25
0
void ProcessIncoming(void)
{
	Message message;
	unsigned long int numBytesRead, numBytesWritten;
	int status;
	int numErrors;
	char c;
	int i;

	numErrors = 0;

	while(true) {
		// Get message header
		if(read(hOutputPipe, &message, sizeof(message)) <= 0) {
			if(simptris) EndSimptris();
			return;
		}

		// Get message body
		if(message.length > 0) {
			if(message.length >= CRT_OUT_BUFFER_SIZE) message.length = CRT_OUT_BUFFER_SIZE - 1;
			read(hOutputPipe, buffer, message.length);
		}

		switch(message.action) {
		case EXIT:
			if(simptris) EndSimptris();
			return;
		case CLEAR_SCREEN:
			if(simptris) {
				clear();
				DrawBoardFrame();
				refresh();
			}
			else {
				int i, numRows, numCols;
				GetTermSize(&numRows, &numCols);
				numCols--;
				printf("<END OF OUTPUT>");
				for(i = 0; i < 24; i++) putchar('\n');	// Add blank lines
				while(numCols-- > 0) putchar('_');			// Make separator
				while(numRows-- > 0) putchar('\n');			// Scroll screen
	
				printf("\033[2J");	// Wipe screen
				printf("\033[H");	// Return cursor to home position (or "\033[0;0f" would work)
				fflush(stdout);		// Ensure redraw of screen
			}
			break;
		case PRINT_STRING:
			printString(buffer, message.length);
			fflush(stdout);
			break;
		case PRINT_CHAR:
			putchar(buffer[0]);
			fflush(stdout);
			break;
		case INIT_BOARD:
			if(!InitSimptris()) {
				printf("Simptris couldn't be initialized.\nPress Enter to terminate...");
				getchar();
				return;
			}
			else simptris = true;
			break;
		case PRINT_BOARD:
			PrintBoard(buffer);
			refresh();
			break;
		case PRINT_SCORE:
			PrintScore(*((int *)buffer));
			refresh();
			break;
		default:
			numErrors++;
			if(!simptris) printf("<COMMUNICATION ERROR>\n");
			else printw("<COMMUNICATION ERROR>\n");

			if(numErrors >= MAX_COM_ERRORS) {
				if(simptris) EndSimptris();
				printf("Too many communication errors!\nPress any key to terminate...");
				return;
			}
		}
	}
}
Exemple #26
0
void InteractivePrompt(int halfsteps)
{
	FILE* f;
	char buffer[256];
	int num;
	int done = 0;

	if(interactiveHalfstepCounter > 0)
	{
		interactiveHalfstepCounter--;
		if(interactiveHalfstepCounter != 0)
		{
			return;
		}
	}

	PrintBoard(halfsteps);

	while(!done)
	{
		fputs(">> ", stdout);
        fgets(buffer, 256, stdin);

		// A numeric value.
		if(sscanf(buffer, "%d", &num) > 0)
		{
			if(num <= 0)
			{
				fputs("\r\n\r\nError (full step count must be positive)\r\n\r\n", stdout);
			}
			else
			{
				interactiveHalfstepCounter = 2 * num - halfsteps % 2;
				done = 1;
			}
		}
		else
		{
			if(strlen(buffer) > 2)
			{
				buffer[0] = '~';
			}
			switch(buffer[0])
			{
				case '\r':
				case '\n':
					interactiveHalfstepCounter = 2 - halfsteps % 2;
					done = 1;
					break;
				case 'h':
					interactiveHalfstepCounter = 1;
					done = 1;
					break;
				case 'c':
					INTERACTIVE = 0;
					done = 1;
					break;
				case 'x':
					f = fopen("redblue.txt", "w");
					PrintBoardToFile(halfsteps, f);
					fclose(f);

					interactiveExit = 1;
					done = 1;
					break;
				default:
					fputs("\r\n\r\nError\r\n\r\n", stdout);
					break;
			}
		}
	}
}
Exemple #27
0
int main(int argc, char** argv)
{
	FILE* f;
	int i, j;
    size_t size;
	int seedNumber;
	int REPORT = 0;
	int bytesToAllocateForArgsText = 0;

	puts("\r\n");
	puts(argv[0]);
	puts("\r\n");
	if(argc == 1)
	{
		PrintUsage(0);
	}

	// gather N, T, W, maxFullsteps, winPercent, seedNumber, INTERACTIVE from commandline args; 
	N = T = W = winPercent = INTERACTIVE = 0;
	maxFullsteps = -1;
	seedNumber = time(NULL);
	for(i = 1; i < argc; i++)
	{
		bytesToAllocateForArgsText += strlen(argv[i]) + 1;
		switch(argv[i][0])
		{
			case 'p':
				if(strlen(argv[i]) >= 2)
				{
					W = atoi(&(argv[i][1]));
				}
				else
				{
					printf("Invalid process count.\r\n");
					PrintUsage(1);
				}
				break;
			case 'b':
				if(strlen(argv[i]) >= 2)
				{
					N = atoi(&(argv[i][1]));
				}
				else
				{
					printf("Invalid size parameter for board.\r\n");
					PrintUsage(1);
				}
				break;
			case 't':
				if(strlen(argv[i]) >= 2)
				{
					T = atoi(&(argv[i][1]));
				}
				else
				{
					printf("Invalid size parameter for overlay.\r\n");
					PrintUsage(1);
				}
				break;
			case 'c':
				if(strlen(argv[i]) >= 2)
				{
					winPercent = atoi(&(argv[i][1]));
				}
				else
				{
					printf("Invalid win percentage.\r\n");
					PrintUsage(1);
				}
				break;
			case 'm':
				if(strlen(argv[i]) >= 2)
				{
					j = sscanf(&(argv[i][1]), "%d", &maxFullsteps);
					if(!j)
					{
						printf("Invalid max steps.\r\n");
						PrintUsage(1);
					}
				}
				else
				{
					printf("Invalid max steps.\r\n");
					PrintUsage(1);
				}
				break;
			case 's':
				if(strlen(argv[i]) >= 2)
				{
					j = sscanf(&(argv[i][1]), "%d", &seedNumber);
					if(!j)
					{
						printf("Invalid seed.\r\n");
						PrintUsage(1);
					}
				}
				else
				{
					PrintUsage(1);
				}
				break;
#ifndef DISABLE_INTERACTIVE
			case 'i':
				if(strlen(argv[i]) != 1)
				{
					printf("Invalid parameter %s.\r\n", argv[i]);
					PrintUsage(1);
				}
				INTERACTIVE = 1;
				break;
#endif
			case 'R':
				REPORT = 1;
				break;
			default:
				printf("Invalid parameter %s.\r\n", argv[i]);
				PrintUsage(1);
				break;
		}
	}

	argsText = malloc(bytesToAllocateForArgsText + 1);
	argsText[0] = 0;
	for(i = 1; i < argc; i++)
	{
		strcat(argsText, argv[i]);
		strcat(argsText, " ");
	}
	printf("Argument text: '%s' \r\n", argsText);

	srand(seedNumber);

	if(W <= 0)
	{
		printf("Invalid or nonexistant process count, must be greater than zero.\r\n");
		PrintUsage(1);
	}
	if(N < 2)
	{
		printf("Invalid or nonexistant size parameter for board, must be greater than or equal or 2.\r\n");
		PrintUsage(1);
	}
	if(T <= 0 || N % T != 0)
	{
		printf("Invalid or nonexistant size parameter for overlay.\r\n");
		PrintUsage(1);
	}
	if(winPercent <= 0)
	{
		printf("Invalid or nonexistant termination condition percent, must be (1-100).\r\n");
		PrintUsage(1);
	}
	if(maxFullsteps < 0)
	{
		printf("Invalid or nonexistant number of max full steps, must be greater than or equal to zero.\r\n");
		PrintUsage(1);
	}

	board = malloc(N * N);
	if(!board)
	{
		perror("Not enough memory.\r\n");
		SHUTDOWN(-1);
	}
	for(i = 0; i < N * N; i++)
	{
		board[i] = rand() % 3;
	}

	// Set up the miscellaneous. 
	maxHalfsteps = maxFullsteps * 2;
	percentHalfsteps = -1; 
	maxBluePercent = maxRedPercent = 0;

	omp_set_num_threads(W);

	StartTime();
	#pragma omp parallel
	{ 
		if(omp_get_thread_num() == 0)
		{
			W  = omp_get_num_threads();
			printf("W = %d\r\n", W);
			// If N is greater than or equal to the number of workers, there is work for every thread. 
			if(N >= W) 
			{ 
				// If workers divide N, then every worker does the same amount of work. 
				if(N % W == 0) 
				{ 
					rcLeftOver = rcSplit = N / W; 
				} 
				// If workers do not divide N, 
				// Then the truncation of N / W is handed to W - 1 of W workers, 
				// And the final worker will take all the remaining work. 
				else 
				{ 
					rcSplit = N / W; 
					rcLeftOver = N - (rcSplit * (W - 1)); 
				} 
			} 
			else 
			{ 
				// Each worker up to N takes 1 row. 
				// Leftover is set here, but won't actually used. 
				rcSplit = 1; 
				rcLeftOver = 1; 
			 
				// Set the number of workers equal to the size of the board, 
				// so that we don't spawn threads that will always be doing nothing. 
				W = N; 
			}
			// Calculate how many times T divides N in advance. 
			// This will be used a lot in the board evaluation phase. 
			subregionCount = N / T; 
			// Size of each subregion in cells. 
			subregionCells = T * T;
		}
		
		#pragma omp barrier
		printf("%d got here\r\n", omp_get_thread_num());
		
		ThreadExecute(omp_get_thread_num());
	}

	if(INTERACTIVE)
	{
		if(!interactiveExit)
		{
			PrintBoard(percentHalfsteps);
		}
	}
	else
	{
		f = fopen("redblue.txt", "w");
		PrintBoardToFile(percentHalfsteps, f);
		fclose(f);
	}

	free(argsText);
	free(board);

	SHUTDOWN(0);
	return 0;
}
Exemple #28
0
void CheckWin(char GameBoard[GameHeigth][GameWidth])    //Funktion för att kolla om någon vunnit
{
    int i = 0,j = 0;
    for(i = 0;i<GameHeigth;i++) //Upprepa för höjden
    {
        for(j = 0;j<GameWidth;j++) //Upprepa för bredden
        {
            if(GameBoard[i][j]==GameBoard[i+1][j]&&GameBoard[i+1][j]==GameBoard[i+2][j])    //Om någon får 3 i rad vertikalt
            {
                if(GameBoard[i][j]=='X')    //Om användaren vinner
                {
                    PrintBoard(GameBoard);  //Skriv ut planen
                    printf("\nYou beat the computer, congratulations!\n");
                    system("PAUSE");
                    exit(0);
                }
                else if(GameBoard[i][j]=='O')   //Om datorn vinner
                {
                    PrintBoard(GameBoard);
                    printf("\nThe computer beat you.");
                    system("PAUSE");
                    exit(0);

                }
            }
            else if(GameBoard[i][j]==GameBoard[i][j+1]&&GameBoard[i][j+1]==GameBoard[i][j+2])   //Om någon får 3 i rad horisontellt
            {
                if(GameBoard[i][j]=='X')
                {
                    PrintBoard(GameBoard);
                    printf("\nYou beat the computer, congratulations!\n");
                    system("PAUSE");
                    exit(0);
                }
                else if(GameBoard[i][j]=='O')
                {
                    PrintBoard(GameBoard);
                    printf("\nThe computer beat you.");
                    system("PAUSE");
                    exit(0);

                }
            }
            else if(GameBoard[i][j]==GameBoard[i+1][j+1]&&GameBoard[i+1][j+1]==GameBoard[i+2][j+2])    //Om någon får 3 i rad diagonellt neråt
            {

                if(GameBoard[i][j]=='X')
                {
                    PrintBoard(GameBoard);
                    printf("\nYou beat the computer, congratulations!\n");
                    system("PAUSE");
                    exit(0);
                }
                else if(GameBoard[i][j]=='O')
                {
                    PrintBoard(GameBoard);
                    printf("\nThe computer beat you.");
                    system("PAUSE");
                    exit(0);

                }
            }
            else if(j>1&&GameBoard[i][j]==GameBoard[i+1][j-1]&&GameBoard[i+1][j-1]==GameBoard[i+2][j-2])    //Om någon får 3 i rad diagonellt uppåt, kan ge felaktigt utslag om i är mindre än 1
            {
                if(GameBoard[i][j]=='X')
                {
                    PrintBoard(GameBoard);
                    printf("\nYou beat the computer, congratulations!\n");
                    system("PAUSE");
                    exit(0);
                }
                else if(GameBoard[i][j]=='O')
                {
                    PrintBoard(GameBoard);
                    printf("\nThe computer beat you.\n");
                    system("PAUSE");
                    exit(0);
                }
            }
        }
    }
    return;
}
void PlayBot()
{
	printf("\n\nAt Any Time In The Game If You Want To See The Grid Indexing In Which You Have To Make A Move\n\n");
	printf("During Enter A Move Command...Just Press 0 And Press Enter \n\n");
	BOARD *board=new BOARD;
	SetStart(board);
	printf("The Starting Board\n\n");
	PrintBoard(board);
	char Inp[200];
	int Side;
	printf("\nChoose Your Side...\n\n0. For Black\n1. For White\n");
	scanf("%d",&Side);
	if(Side==0)
	{
		MOVE *list1=new MOVE;
		GenMoves(board,list1);
		vector<int>BestMove1=SearchPos(board,8);
		MakeMove(board,BestMove1);
		PrintBoard(board);
	}
	while(1)
	{
		printf("\n\nEnter Your Move\n");
		getchar();
		scanf("%[^\n]",&Inp);
		if(Inp[0]=='0')
		{
			PrintIndex();
			continue;
		}
		else if(Inp[0]=='1')
		{
			printf("\nYour Possible MoveList is\n");
			MOVE *YourMoveList=new MOVE;
			GenMoves(board,YourMoveList);
			PrintMoveList(YourMoveList);
		}
		vector<int>Move=ParseMove(Inp);
		if(MoveExists(board,Move))
			MakeMove(board,Move);
		else
		{
			MOVE *User=new MOVE;
			GenMoves(board,User);
			if(User->Count==0)
			{
				printf("Sorry You Lost\n\n");
				break;
			}
			else
				printf("Invalid Move...Enter Again\n\n");
			continue;
		}
		PrintBoard(board);
		printf("-----------------------------------Bot's Turn----------------------------------\n");
		MOVE *Bot=new MOVE;
		GenMoves(board,Bot);
		if(Bot->Count==0)
		{
			printf("--------------------------Congratulations You Win--------------------------\n");
			break;
		}
		vector<int>BestMove=SearchPos(board,8);
		MakeMove(board,BestMove);
		PrintBoard(board);
	}
	StartGame();	
}
Exemple #30
0
int main(void)
{
    int     input             = -1;
    int     smileyTypeInput   = -1;
    int     smileyHealthInput = -1;
    int     xCoordinateInput  = -1;
    int     yCoordinateInput  = -1;
    int     turns             = 0;
    Smiley* board[BOARD_SIZE][BOARD_SIZE];
    
    // Set up board
    InitializeSmileyBoard(board);
    
    srand(time(0));
    
    PrintSmileyDemo();
    
    // Main loop; continues until user exits program
    while (input != 0)
    {
        PrintBoard(board);
        
        // Prompt for initial user input
        printf("Please choose from the following:\n");
        printf("1: Add a smiley to the board\n");
        printf("2: Do nothing this turn\n");
        printf("0: Exit\n");
        
        input = GetIntegerInput();
        
        switch (input)
        {
                // Add smiley to the board
            case 1:
                // Smiley type
                smileyTypeInput = GetSmileyType();
                
                // If type is -1, then cancel operation
                if (smileyTypeInput == -1)
                {
                    break;
                }
                
                // Smiley health
                smileyHealthInput = GetSmileyHealth();
                
                // If health is -1, then cancel operation
                if (smileyHealthInput == -1)
                {
                    break;
                }
                
                // Coordinates
                GetCoordinate(&xCoordinateInput, 'x');
                GetCoordinate(&yCoordinateInput, 'y');
                
                // If the given coordinates are empty and valid, then place the Smiley there
                if ((IsValidCoordinatePair(xCoordinateInput, yCoordinateInput)) &&
                    (board[yCoordinateInput][xCoordinateInput] == NULL))
                {
                    board[yCoordinateInput][xCoordinateInput] = CreateSmiley((SmileyType) smileyTypeInput, 
                                                                             (SmileyHealth) smileyHealthInput);
                }
                
                // Else display error message and cancel operation
                else
                {
                    printf("There is already a Smiley at (%d, %d).\n", xCoordinateInput, yCoordinateInput);
                }
                
                break;
            case 2:
                printf("You wait.\n");
                break;
            case 0:
                continue;
            default:
                break;
        }
        
        IterateBoard(board);
        turns++;
    }
    
    FreeSmileysOnBoard(board);
    printf("Press ENTER to continue");
    getchar();
    exit(0);
}