Beispiel #1
0
int main()
{
    char board[3][3];
    int move;
    for (int i = 0; i < 3; ++i)
		for (int j = 0; j < 3; ++j)
	    	board[i][j] = ' ';
    draw_board(board);
    do {
		printf("Your Move : ");
		scanf("%d", &move);
		if (move >= 0 && move <= 8 && board[move / 3][move % 3] == ' ') {
			board[move / 3][move % 3] = 'X';
			draw_board(board);
		} else {
			printf("Invalid Move!!!\n");
			continue;
		}
		if (check_winner(board) != INCOM)
			break;
		comp_move(board);
		draw_board(board);
		if (check_winner(board) != INCOM)
			break;
    }
    while (1);

    if (check_winner(board) == COMPW)
		printf("Computer wins the Game. Better luck next time\n\n");
    else if (check_winner(board) == USERW)
		printf("You have won the game! \n\n");
    else
		printf("Damn! It's a draw.\n\n");
    return 0;
}
Beispiel #2
0
void			start_game(t_grid *grid)
{
	int			random;
	int			i;
	int			winner;

	ft_putendl("starting the game");
	srand(time(NULL));
	random = rand() % 2;
	i = 0;
	while ((!(winner = check_winner(grid, 'X')))
			&& (!(winner = check_winner(grid, 'O'))) && (!(winner = tie(grid))))
	{
		random ^= 1;
		if (random)
		{
			while (player_turn(grid) == 0)
				i++;
		}
		else
			ai_turn(grid);
	}
	display_grid(grid);
	call_winner(winner);
}
Beispiel #3
0
static int		eval(t_grid *grid)
{
    if (check_winner(grid, 'X'))
        return (3000);
    else if (check_winner(grid, '0'))
        return (-3000);
    return (0);
}
char check_win_main(char main_matrix[][3])
{
        char copy_main[3][3];

        int x,y;
        for(x=0;x<3;x++)
        {
                for(y=0;y<3;y++)
                {
                        if(main_matrix[x][y]=='t')
                        {
                                copy_main[x][y]='s';
                        }

                        else
                        {
                                copy_main[x][y]=main_matrix[x][y];
                        }
                }
        }

        if(check_winner(copy_main)=='o')
        {
                return 'o';
        }
        if(check_winner(copy_main)=='x')
        {
                return 'x';
        }

        int flag=0;

        for(x=0;x<3;x++)
        {
                for(y=0;y<3;y++)
                {
                        if(main_matrix[x][y]=='s')
                        {
                                flag=1;
                                break;
                        }
                }
        }

        if(flag==0)
        {
                return 't';
        }

        return 's';
}
Beispiel #5
0
int				min(t_grid *grid, int depth, int i)
{
    int			min;
    int			tmp;

    min = 3000;
    if (depth <= 0)
        return (eval(grid));
    while (i < grid->columns)
    {
        if (grid->map[0][i] == '.')
        {
            put_piece(grid, i + 1, 'O');
            if (check_winner(grid, 'O') != 0)
            {
                remove_piece(grid, i + 1);
                return (-3000);
            }
            tmp = max(grid, depth - 1, 0);
            if (tmp < min)
                min = tmp;
            remove_piece(grid, i + 1);
        }
        i++;
    }
    return (min);
}
Beispiel #6
0
int				max(t_grid *grid, int depth, int i)
{
    int			max;
    int			tmp;

    max = -3000;
    if (depth <= 0)
        return (eval(grid));
    while (i < grid->columns)
    {
        if (grid->map[0][i] == '.')
        {
            put_piece(grid, i + 1, 'X');
            if (check_winner(grid, 'X') != 0)
            {
                remove_piece(grid, i + 1);
                return (3000);
            }
            tmp = min(grid, depth - 1, 0);
            if (tmp > max)
                max = tmp;
            remove_piece(grid, i + 1);
        }
        i++;
    }
    return (max);
}
Beispiel #7
0
int				minimax(t_grid *grid, int max, int i)
{
    int			ret;
    int			tmp;

    ret = 0;
    while (i < grid->columns)
    {
        if (grid->map[0][i] == '.')
        {
            put_piece(grid, i + 1, 'X');
            if (check_winner(grid, 'X') != 0)
            {
                remove_piece(grid, i + 1);
                return (i);
            }
            tmp = min(grid, 3, 0);
            if (tmp > max)
            {
                tmp = max;
                ret = i;
            }
            remove_piece(grid, i + 1);
        }
        i++;
    }
    return (ret);
}
Beispiel #8
0
void do_done(CHAR_DATA * ch, char * thedir)
{
CHAR_DATA *rch;
if(!ch->infight)
{
printf_to_char(ch,"You're not in a fight.");
return;
}

if(!TURN(ch))
{
printf_to_char(ch,"It's not your turn.");
return;
}
   
    check_winner(ch->in_room);
    
    for (rch = ch->in_room->people; rch != NULL; rch = rch->next_in_room)
    {  
         printf_to_char(rch,"%s ends %s turn.\n",fcn(ch), ch->sex ? "his" : "her");
         do_map(rch,"forced");
         rch->AT++;
    }
       ch->AT = 0;

advance_turn(ch); 
}
Beispiel #9
0
int main() {
  int *board = create_board();

  check_winner(board);

  return 0;
}
Beispiel #10
0
/* Boucle principale du jeu */
int	game_loop(char board[3][3])
{
  int	win;
  int	turn;
  int	error;
  int	player;
  char	input[64];
  int	insert_nb;

  win = -1;
  turn = 0;
  error = -42;
  while (win == -1)
    {
      player = turn % 2;
      system("clear");
      display_board(board);
      display_error(error);
      printf("Player %d enter the case number where to put an %c : ", player + 1, player == 0 ? 'X' : 'O');
      scanf("%s", input);
      error = check_input(board, input);
      if (error == -42)
	{
	  insert_nb = input[0] - '1';
	  board[insert_nb / 3][insert_nb % 3] = player;
	  win = check_winner(board, player);
	  if (win >= 0)
	    return (player);
	  else if (turn >= 8)
	    return (2);
	  turn++;
	}
    }
  return (0);
}
Beispiel #11
0
void advance_turn(CHAR_DATA * ch)
{
CHAR_DATA *rch;
int q=0;

for (rch = ch->in_room->people; rch != NULL; rch = rch->next_in_room)
    {
if(rch->infight)
q++;    
}
if(q<1);
return;

    check_winner(ch->in_room);

q = 0;
    for (rch = ch->in_room->people; rch != NULL; rch = rch->next_in_room)
    {  
    if(rch == NULL || !rch->infight)
    continue;
    do_map(rch,"forced");
    }

ch->in_room->next = NULL;
while(ch->in_room->next == NULL)
{
    for (rch = ch->in_room->people; rch != NULL; rch = rch->next_in_room)
    {
    if(rch == NULL || !rch->infight)
    continue;
    
    if(rch->ATToCast < rch->AT)
    {
    say_spell (rch, rch->SnToCast);
    tile_spell(rch, rch->SnToCast);
    rch->ATToCast = 0;
    rch->SnToCast = 0;
    rch->casting = FALSE;
    rch->CastTargY = 0;
    rch->CastTargX = 0;   
    }

    rch->AT += rch->speed;
    if(rch->AT >= 100)
    {
    rch->AT = 100;
    ch->in_room->turn = rch;
    break;
    }
    }
}

    ch->in_room->turn->MoveLeft = ch->in_room->turn->base_move;
    ch->in_room->turn->AttackLeft = 1;

    printf_to_char(rch,"%s's turn.\n",fcn(ch->in_room->turn));

}
Beispiel #12
0
int get_score(char board[3][3], enum player p)
{
    if (check_winner(board) != INCOM)
		return check_winner(board);
    int score = -1;
    for (int i = 0; i < 9; ++i) {
		if (board[i / 3][i % 3] == ' ') {
	    	if (p == USR) {
				board[i / 3][i % 3] = 'X';
				if (score == -1)
		    		score = get_score(board, COMP);
				else
		    		score = min(score, get_score(board, COMP));
	    	} else if (p == COMP) {
				board[i / 3][i % 3] = 'o';
				score = max(score, get_score(board, USR));
	    }
	    board[i / 3][i % 3] = ' ';
	}
    }
    return score;
}
int main()
	{
	char matrix[3][3][3][3];
	char main_matrix[3][3];
	int iplay,jplay,turn,move;
	char temp;
	scanf("%c",&turn);
	scanf("%c",&temp);
	scanf("%d %d",&iplay,&jplay);
	scanf("%c",&temp);
        int i,j,k,l,a,b,c,d;

        for(i=0;i<3;i++)
        {
                for(j=0;j<3;j++)
                {
                        for(k=0;k<3;k++)
                        {
                                for(l=0;l<3;l++)
                                {
                                        scanf("%c",&matrix[i][k][j][l]);
                                        if(matrix[i][k][j][l]=='X')matrix[i][k][j][l]='x';
                                        else if(matrix[i][k][j][l]=='O')matrix[i][k][j][l]='o';
                                        else if(matrix[i][k][j][l]=='-')matrix[i][k][j][l]='s';
                                }
                        }
                        scanf("%c",&temp);
                }
        }
        for (i=0;i<3;i++)
        {
                for(j=0;j<3;j++)
                {
                        main_matrix[i][j]=check_winner(matrix[i][j]);
                }
        }
	struct Node *root= (struct Node *) malloc(sizeof(struct Node));
	move=minimax(root,turn,matrix,main_matrix,iplay,jplay,1,1,82);
	a=move/1000;
	b=move/100 - a*10;
	c=move/10 - a*100 - b*10;
	d=move-a*1000 - b*100 - c*10;
	printf("%d %d %d %d",a,b,c,d);
        return 0;

	}
Beispiel #14
0
const char* game(int user)
{
	int i, j, k, move, win = 0;
	for_ij b[i][j] = 0;
 
	printf("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9\n");
	printf("You have O, I have X.\n\n");
	for (k = 0; k < 9; k++, user = !user) {
		while(user) {
			printf("your move: ");
			if (!scanf("%d", &move)) {
				scanf("%*s");
				continue;
			}
			if (--move < 0 || move >= 9) continue;
			if (b[i = move / 3][j = move % 3]) continue;
 
			b[i][j] = 1;
			break;
		}
		if (!user) {
			if (!k) { /* randomize if computer opens, less boring */
				best_i = rand() % 3;
				best_j = rand() % 3;
			} else
				test_move(-1, 0);
 
			b[best_i][best_j] = -1;
			printf("My move: %d\n", best_i * 3 + best_j + 1);
		}
 
		showboard();
		if ((win = check_winner())) 
			return win == 1 ? "You win.\n\n": "I win.\n\n";
	}
	return "A draw.\n\n";
}
Beispiel #15
0
int test_move(int val, int depth)
{
	int i, j, score;
	int best = -1, changed = 0;
 
	if ((score = check_winner())) return (score == val) ? 1 : -1;
 
	for_ij {
		if (b[i][j]) continue;
 
		changed = b[i][j] = val;
		score = -test_move(-val, depth + 1);
		b[i][j] = 0;
 
		if (score <= best) continue;
		if (!depth) {
			best_i = i;
			best_j = j;
		}
		best = score;
	}
 
	return changed ? best : 0;
}
Beispiel #16
0
// from UDP made simple at https://www.abc.se/~m6695/udp.html
int main(int argc, char *argv[]) {
	

	struct sockaddr_in si_me, si_oth,si_other[4];
	int s, sockFd[4];
	socklen_t slen=sizeof(struct sockaddr_in);
	ssize_t len;
	FILE *fd;

	fd = fopen("/var/tmp/serve_client","w");
	char buf[BUFLEN]={"start"};
	char *trick[4];
	FF_trick(trick);

	//Game initiation, shuffling and dealing.
	Card sorted_deck[52];
	Card shuffled_deck[52];
	char *deck[52];
	new_deck(sorted_deck);
	shuffle_deck(sorted_deck,shuffled_deck);
	convert_card_struct(shuffled_deck,deck,buf);
	Game *game = malloc(sizeof(Game));
	memcpy(game->deck,deck,sizeof(deck));
	for (int k = 0; k < 4; k++) memcpy(game->buffer[k],buf, sizeof(buf));
	for (int k = 0; k < 4; k++) printf("Shuffled deck: \n%s\n\n",game->buffer[k]);

	//get communication going
	if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
		diep("socket");
	printf("socket open\n");
	memset((char *) &si_me, 0, sizeof(si_me));
	si_me.sin_family = AF_INET;
	si_me.sin_port = htons(GAMEPORT);
	si_me.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(s, (struct sockaddr *) &si_me, sizeof(si_me))==-1)
		diep("bind");
	printf("bound\n");

	//Player initiation
	int counter[4];
	for(int i=0;i<4;i++){
		counter[i] = i;
	}

	pthread_t players[4];
	for(int i=0;i<4;i++){
		pthread_t tmp=0;
		players[i] = tmp;
	}
	//Player thread arguments are initiated
	Player player[4];
	for(int i=0;i<4;i++){
		memset((char *) &si_other[i], 0, sizeof(si_other[i]));
		Player tmp={i,&s,game,&si_me,&si_other[i]};
		memcpy(&player[i], (void *) &tmp, sizeof(tmp));
	}
	//deal cards into each player's game buffer
	for (int k = 0; k < 4; k++) {
		sprintf(player[k].game->buffer[k],"%s;",game->deck[k]);
		for(int j=4;j<52;j+=4) {
			strcat(player[k].game->buffer[k], game->deck[(j+k)]);
			strcat(player[k].game->buffer[k],";");
		}
		printf("Player %d game buffer: %s\n",k,player[k].game->buffer[k]);
	}
	for (int k = 0; k < 4; k++)printf("Player %d game buffer: %s\n",k,player[k].game->buffer[k]);

	//deal cards into player hands
	for (int k = 0; k < 4; k++) {
		for(int j=0;j<52;j+=4) {
			player[k].game->hands[k][j/4] = malloc(3);
			strcpy(player[k].game->hands[k][j/4], game->deck[(j+k)]);
		}
	}
	/* print hands
	for (int k = 0; k < 4; k++) {
		printf("Player %d game hand: ", k);
		for (int l = 0; l < 13; l++) {
			printf("%s ", player[k].game->hands[k][l]);
		}
		printf("\n");
	}*/


	int j=0,connected=0;
	void *buffer = (void *) strdup(buf);
	bool connections[]={false,false,false,false};
	char *this_is_my_pos[4];

	do{
		printf("inet: %s\tsocket descriptor: %d\n\n",
		       inet_ntoa(player[j].si_other->sin_addr),
				 player[j].sockfd);
		if((len = recvfrom(s, buffer, BUFLEN, 0, &si_oth, &slen)) == -1) diep("recvfrom()");

		//check given position
		separate_strings(buffer,";",this_is_my_pos,4);
		if((j=find_DD(this_is_my_pos,4))== -1) printf("not a new connection\n");
		if(j < 4 && j >= 0 && !connections[j]){
			//In preparation for threads
			sockFd[j]= s;
			player[j].sockfd = &sockFd[j];
			strcpy(si_other[j].sin_zero,si_oth.sin_zero);
			si_other[j].sin_addr.s_addr=si_oth.sin_addr.s_addr;
			si_other[j].sin_port=si_oth.sin_port;
			si_other[j].sin_family=si_oth.sin_family;
			player[j].si_other = &si_other[j];

			printf("pthread to addr: %d\n",si_oth.sin_addr.s_addr);
			//pthread_create(&players[j],NULL,&player_waits_or_plays,(void *) &player[j]);

			//Signal that four clients are connected
			connections[j]=true;
			connected += 1;
		} else perror("not a new connection\n");


		printf("Received packet from IP-address: %s: Port: %d\nPosition: %d\nData: %s\nLength: %d\n",
		       inet_ntoa(si_oth.sin_addr), ntohs(si_oth.sin_port),
		       j,
		       (char *) buffer,(int) len);
		//strängen delas upp i fyra
		separate_strings(buffer,";",trick,4);
		printf("received split into: %s",trick[0]);
		for(int i=1;i<4;i++) printf(" %s",trick[i]);

		//skicka första handen
		printf("\nSending packet: \n%s\nto player %d\n", game->buffer[j],j);
		if (sendto(s, game->buffer[j], 200, 0, (struct sockaddr *) &si_oth,  slen)==-1)
			diep("sendto()");

	} while (connected<4);

	int starter=0;
	// Här börjar spelet, första handen har skickats till klienterna. Vem börjar?
	starter=who_starts(game->hands);
	int winner=-1;

	printf("player %d starts\n", starter);
	EE_trick(trick,starter);
	printf("Winner: %d\n", winner=check_winner(trick,starter));
	EE_trick(trick,starter);
	EE_trick(game->trick,starter);

	// Lägg nu sticket i fyra buffertar, en till varje spelare (overkill!)
	for (int m = 0; m < 4; m++) {
		for (int k = 0; k < 4; k++) {
			if (!k) sprintf(player[m].game->buffer[m], "%s;", trick[0]);
			else {
				strcat(game->buffer[m], trick[k]);
				strcat(game->buffer[m], ";");
			}
			printf("Game buffer: %s\n", game->buffer[m]);
		}
	}
	for (int k = 0; k < 4; k++)printf("Player %d game buffer: %s\n",k,player[k].game->buffer[k]);

	for (int l = 0; l < 4; l++) {
		if ((len = recvfrom(s, buffer, BUFLEN, 0, (struct sockaddr *) &si_oth, &slen)) == -1)
			diep("recvfrom()");
		if (si_other[l].sin_addr.s_addr == si_oth.sin_addr.s_addr) {
			if (sendto(s, game->buffer[l], sizeof(game->buffer[l]), 0, (struct sockaddr *) &si_other[l],
				   slen) == -1)
				diep("sendto()");
			printf("Skickar %s till spelare %d\n",game->buffer[l], player[l].pos);
		}
	}

	/*for (int l = 0; l < 4; l) {
		if((len = recvfrom(s, buffer, BUFLEN, 0, (struct sockaddr *) &si_oth, &slen)) == -1) diep("recvfrom()");
	}*/
	int o=0;
	do{
		if((len = recvfrom(s, buffer, BUFLEN, 0, (struct sockaddr *) &si_oth, &slen)) == -1) diep("recvfrom()");
		printf("from addr: %d\n",si_oth.sin_addr.s_addr);
		if ((strstr(buffer,"00"))) {
			for (int m = 0; m < 4; m++) {
				sprintf(player[m].game->buffer[m], "%s;", buffer);
				printf("Buffer written: %s\n", buffer);
			}
			for (int l = 0; l < 4; l++) {
				if (si_other[l].sin_addr.s_addr == si_oth.sin_addr.s_addr) {
					if (sendto(s, game->buffer[l], sizeof(game->buffer[l]), 0,
						   (struct sockaddr *) &si_other[l],
						   slen) == -1)
						diep("sendto()");
					printf("Skickar %s till spelare %d\n", buffer, player[l].pos);
					//pthread_create(&players[l], NULL, &player_waits_or_plays, (void *) &player[l]);
				}

			}
		}
	} while (!(strstr(buffer,"00")));
	void *new_buffer;
	void *best_buffer;
	new_buffer = malloc(40);
	best_buffer = malloc(40);
	int FFs=0, best_count=4;
	// så länge första handen spelas vill vi jämföra skickade händer med mottagna händer
	while(strstr(buffer, "00") && strstr(buffer,"FF")){
		if((len = recvfrom(s, new_buffer, BUFLEN, 0, (struct sockaddr *) &si_oth, &slen)) == -1) diep("recvfrom()");
		//Vill du ha hela din hand igen?
		if(strstr((char*) new_buffer, "DD")){
			for (int i = 0; i < 4; i++) {
				if(si_oth.sin_addr.s_addr==player[i].si_other->sin_addr.s_addr){
					if (sendto(s, game->hands[i],
						   sizeof(game->hands[i]), 0,
						   (struct sockaddr *) &si_other[i],
						   slen) == -1) diep("sendto()");
					// inga onödiga loopar!
					break;
				}
			}
			//tillbaka till att ta emot igen!
			continue;
		}
		else if((strcmp((char *) buffer, (char *) new_buffer)) && !(strstr(new_buffer, "EE"))) {
			printf("Gammalt stick: %s\nUppdaterat stick: %s",(char*) buffer, (char*) new_buffer);
			char *tmp = strdup(new_buffer);
			if((FFs= count_FF(tmp)) < best_count) best_count = FFs;
			else continue;		// skriv inte över sticket om det inte nästa kort spelats
			strcpy((char*)buffer, new_buffer);
			split((char*) buffer,';',game->trick);


			//bufferten måste återställas efter split()
			strcpy((char*)buffer, new_buffer);
			printf("\nkontroll av pekare: : \n");
			for (int i = 0; i < 4; i++) printf("trick %d: %s\n",i,game->trick[i]);
			for (int i = 0; i < 4; i++) printf("trick %d: %s\n",i,game->trick[i]);

			for (int l = 0; l < 4; l++){
				strcpy(game->buffer[l],new_buffer);
				if (sendto(s, game->buffer[l], sizeof(game->buffer[l]), 0,
					   (struct sockaddr *) &si_other[l], slen) == -1)
					diep("sendto()");
				else printf("Precis skickat %s till spelare %d\n",game->buffer[l], player[l].pos);
			}
		}
	}
	assert(!strstr(game->buffer[0],"FF"));
	split(game->buffer[0],';',trick);
	//Ta reda på vem som vann sticket
	//int winner=-1;
	printf("Winner: %d\n", winner=check_winner(trick,starter));
	// Jag räknar med att klienten ställer frågor om sticket
	EE_trick(trick,winner);
	EE_trick(game->trick,winner);

	// Förmodligen börjar en do-while-loop här som kör så länge


	// Switch-sats beroende på



	/*while(strcmp(buffer,"quit")){
		printf("buffer: %s \n",player[j].game->buffer);
		if ((len = recvfrom(s, buffer, BUFLEN, 0, &si_oth, &slen)) == -1) diep("recvfrom()");
		printf("Received packet from %s:%d\nData: %s\nLength: %d\n",
		       inet_ntoa(si_oth.sin_addr), ntohs(si_oth.sin_port), (char *) buffer,len);
	*/	//counter[j] = pthread_create(&players[j], NULL, &player_waits_or_plays, (void *) &player[j]);
		//pthread_join((players[j]),NULL);

	printf("\nclient data: %s \n",buffer);
	separate_strings(buffer,";",trick,4);
	printf("received split into: %s",trick[0]);
	for(int i=1;i<4;i++) printf(" %s",trick[i]);
	printf("\n");
	/*	//Receive data and start game threads for each client
		for(int j=0;j<4;j++) {
			if ((len = recvfrom(player[j].sockfd, player[j].game->buffer, BUFLEN, 0, &si_other[i], &slen)) == -1) diep("recvfrom()");
			counter[j++] = pthread_create(&players[j], NULL, &player_waits_or_plays, (void *) &player[j]);
			printf("Received packet from %s:%d\nData: %s\nLength: %d\n",
			       inet_ntoa(si_other[i].sin_addr), ntohs(si_other[i].sin_port), (char *) buffer,len);
		}

 // Jag försöker föra över detta till trådarna--------------------//
		char cards_to_send[40];
		i=0;
		sprintf(cards_to_send,"%s;",player[i].game->deck[player[i].pos]);
		for(int j=4;j<52;j+=4) {
			strcat(cards_to_send, player[i].game->deck[player[i].pos+j]);
			strcat(cards_to_send,";");
		}
		printf("Sending packet2: \n%s\n", cards_to_send);
		if (sendto(s, cards_to_send, 40, 0, (struct sockaddr *) &si_other[i],  slen)==-1)
			diep("sendto()");
	int k=0;
*/
    	close(s);
    	return 0;
}
int minimax(struct Node *current,char turn,char matrix[3][3][3][3],char main_matrix[3][3],char x,char y,char w, char z,char maxd)
	{
		count ++;
		printf("%d\n",count);
		char mind,maxi,maxival;
		if(maxd>=0)
			{
			mind=maxd;
	
		int p,i,j,f,l,*empty,k,move;
		char a,b,c,d;
		empty = NULL;
		char copy[3][3][3][3];
		for(i=0;i<81;i++)
			current->child[i]=NULL;
		if (check_winner(matrix[w][z])=='x')
			{
				main_matrix[w][z]='x';
				printf("one");
				if(check_win_main(main_matrix)=='x')
					{
						printf("two");
						current->val=1;
						current->depth=0;
						return 1;
					}
				else
					if(check_win_main(main_matrix)=='t')
					{
						current->val=0;
						current->depth=0;
						return 0;
					}

			}
		else
			if (check_winner(matrix[w][z])=='o')
				{
					
					main_matrix[w][z]='o';
		//			printmatrix2d(main_matrix);
					if(check_win_main(main_matrix)=='o')
						{
							current->val=-1;
							current->depth=0;
							return -1;
						}
					else
						if(check_win_main(main_matrix)=='t')
						{
							current->val=0;
							current->depth=0;
							return 0;
						}
				}
	
		empty=check_empty(matrix,main_matrix,x,y);
	//	printf("empty 0 = %d\n",empty[0]);
		for(i=0;empty[i]!=-1&&i<81;i++)
			{
		//		printf("Inside Loop---%d\n",i);
				a=empty[i]/1000;
				b=empty[i]/100 - a*10;
				c=empty[i]/10 - a*100 - b*10;
				d=empty[i]-a*1000 - b*100 - c*10;
				for(p=0;p<3;p++)
                        	{
                        	for(j=0;j<3;j++)
                                {
                                        for(f=0;f<3;f++)
                                                {
                                                        for(l=0;l<3;l++)
                                                                {
                                                                	copy[p][j][f][l]=matrix[p][j][f][l]; 
                                                                }
                                                }
                                }
                       		}
                

				current->child[i]=(struct Node *) malloc(sizeof(struct Node));
//				if(turn == 'x')
//					{
//					copy[a][b][c][d]='x';
//					minimax(current->child[i],'o',copy,main_matrix,c,d,a,b);
//					}
//				else
//					{
//					copy[a][b][c][d]='o';
//					minimax(current->child[i],'x',copy,main_matrix,c,d,a,b);
//					}
//
			if(i!=0)
				{
					if(turn=='x')
					{
						copy[a][b][c][d]=='x';
						if(maxival==1)
						{
							k=minimax(current->child[i],'o',copy,main_matrix,c,d,a,b,mind-1);
							if(k==1)
							{
								current->depth=(current->child[i])->depth+1;
								mind=current->depth;
								maxi=i;
							}
						}
						else
						{
							k=minimax(current->child[i],'o',copy,main_matrix,c,d,a,b,82);
							if(k==maxival)
							{
								if (((current->child[i])->depth + 1)>maxd)
								{
									current->depth=((current->child[i])->depth + 1);
									maxi=i;
									maxd=current->depth;
								}
							}
							else
							{
								if(k>maxival)
								{
									current->depth=((current->child[i])->depth + 1);
									maxd=current->depth;
									maxi=i;
									maxival=k;
								}
							}
								
						}	
					}
					else
						{
						 copy[a][b][c][d]=='o';
                                                if(maxival==-1)
                                                {
                                                        k=minimax(current->child[i],'x',copy,main_matrix,c,d,a,b,mind-1);
                                                        if(k==1)
                                                        {
                                                                current->depth=(current->child[i])->depth+1;
                                                                mind=current->depth;
                                                                maxi=i;
                                                        }
                                                }
                                                else
                                                {
                                                        k=minimax(current->child[i],'x',copy,main_matrix,c,d,a,b,82);
                                                        if(k==maxival)
                                                        {
                                                                if (((current->child[i])->depth + 1)>maxd)
                                                                {
                                                                        current->depth=((current->child[i])->depth + 1);
                                                                        maxi=i;
                                                                        maxd=current->depth;
                                                                }
                                                        }
                                                        else
                                                        {
                                                                if(k<maxival&&k!=-2)
                                                                {
                                                                        current->depth=((current->child[i])->depth + 1);
                                                                        maxd=current->depth;
                                                                        maxi=i;
                                                                        maxival=k;
                                                                }
                                                        }
                                                                
                                                }
						}
						} 
						                                                
				else
				{
					if(turn=='x')
					{
						copy[a][b][c][d]='x';
						maxival=minimax(current->child[i],'x',copy,main_matrix,c,d,a,b,82);
						maxi=i;
						current->depth=((current->child[i])->depth + 1);
						if(maxival=1)
							mind=current->depth;
					}
					else
					{
						copy[a][b][c][d]='o';
                                                maxival=minimax(current->child[i],'o',copy,main_matrix,c,d,a,b,82);
                                                maxi=i;
                                                current->depth=((current->child[i])->depth + 1);
						if(maxival==-1)
							mind=current->depth;
					}
				}
			
					
					
			}
//		if(turn=='x')
//			k=maxmove(current);
//		else
//			k=minmove(current);
//		current->depth=(current->child[k])->depth + 1;
		move=empty[maxi];
		free(empty);
		empty=NULL;
		return maxival;
		 }
		 else
		 return -2;
			
	}
Beispiel #18
0
int main(int argc, char **argv) {
  cl_int err;

  int generations = 0;

  if (argc < 3) {
    fprintf(stderr, "Usage: %s <bbbattle_file> <bbbout_file>\n", argv[0]);
    exit(1);
  }

  /* create buffers and load bbbattle file */

  int width  = 0;
  int height = 0;
  int teams  = 0;
  char *alive_h;
  char *dying_h;
  struct rgb24 team_colors[256];
  int team_counts[256];

  FILE *bbbf = fopen(argv[1], "r");

  if (bbbf == NULL) {
    perror(argv[1]);
    return 1;
  }

  int bbberr = read_bbbattle(&width, &height, &teams, &alive_h, &dying_h, team_colors, bbbf);
  fclose(bbbf);
  assert(bbberr == READ_BBBATTLE_SUCCESS);

  /* open bbbout stream */

  bbbout_stream *bbbo = bbbout_open_write(argv[2], width, height, teams, team_colors);
  
  if (bbbo == NULL) {
    perror(argv[2]);
    return 1;
  }

  bbbout_write_generation(bbbo, 0, alive_h, dying_h, team_counts);

  if (check_winner(teams, team_counts, team_colors) != 0) {
    fputs("Error: the initial generation was already won, i.e., only one team had alive cells. Check the input file.\n", stderr);
    return 1;
  }

  /* create platform */

  cl_uint n_platforms = 0;

  err = clGetPlatformIDs(1, &platform, &n_platforms);

  if (n_platforms == 0) return 1;

  char platform_name[256];
  size_t platform_name_size;

  char platform_vendor[256];
  size_t platform_vendor_size;

  err = clGetPlatformInfo(platform, CL_PLATFORM_NAME, 256, platform_name, &platform_name_size);
  err = clGetPlatformInfo(platform, CL_PLATFORM_VENDOR, 256, platform_vendor, &platform_vendor_size);

  platform_name[platform_name_size] = '\0';
  platform_vendor[platform_vendor_size] = '\0';

  printf("Platform Name: %s, Vendor: %s\n", platform_name, platform_vendor);
  
  /* create device */

  cl_uint n_devices = 0;

#ifdef OPENCL_CPU
  err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 1, &device, &n_devices);
#else
  err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &n_devices);
#endif

  if (n_devices == 0) return 1;

  char device_name[256];
  size_t device_name_size;

  char device_vendor[256];
  size_t device_vendor_size;

  err = clGetDeviceInfo(device, CL_DEVICE_NAME, 256, device_name, &device_name_size);
  err = clGetDeviceInfo(device, CL_DEVICE_VENDOR, 256, device_vendor, &device_vendor_size);

  device_name[device_name_size] = '\0';
  device_vendor[device_vendor_size] = '\0';

#ifdef OPENCL_CPU
  printf("CPU Name: %s, Vendor: %s\n\n", device_name, device_vendor);
#else
  printf("GPU Name: %s, Vendor: %s\n\n", device_name, device_vendor);
#endif

  /* create context */

  cl_context_properties cprops[3];

  cprops[0] = CL_CONTEXT_PLATFORM;
  cprops[1] = (cl_context_properties) platform;
  cprops[2] = 0;

  context = clCreateContext(cprops, 1, &device, NULL, NULL, &err);
  assert(err == CL_SUCCESS);

  const size_t program_source_len = strlen(program_source);

  cl_program program = clCreateProgramWithSource(context, 1, (const char **) &program_source, &program_source_len, &err);
  assert(err == CL_SUCCESS);

  char options[64];

#ifdef OPENCL_CPU
  sprintf(options, "-DWIDTH=%i -DHEIGHT=%i -DOPENCL_CPU", width, height);
#else
  sprintf(options, "-DWIDTH=%i -DHEIGHT=%i", width, height);
#endif

  err = clBuildProgram(program, 1, &device, options, NULL, NULL);
  if (err != CL_SUCCESS) {
    char log[65536];
    size_t log_size;

    clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG, 65536, log, &log_size);

    fwrite(log, 1, log_size, stderr);

    assert(err == CL_SUCCESS);
  }

  /* create command queue */

  queue = clCreateCommandQueue(context, device, 0, &err);

  /* create device buffers */

  const size_t mem_size = width * height * sizeof(char);

  dimensions[0] = width;
  dimensions[1] = height;

  alive_d = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, mem_size, alive_h, &err);
  assert(err == CL_SUCCESS);

  dying_d = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR | CL_MEM_ALLOC_HOST_PTR, mem_size, dying_h, &err);
  assert(err == CL_SUCCESS);

  new_alive_d = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, mem_size, NULL, &err);
  assert(err == CL_SUCCESS);

  /* get the kernel */

  step_bbbattle = clCreateKernel(program, "step_bbbattle", &err);
  assert(err == CL_SUCCESS);

  err = clSetKernelArg(step_bbbattle, 0, sizeof(cl_mem),  &alive_d);     assert(err == CL_SUCCESS);
  err = clSetKernelArg(step_bbbattle, 1, sizeof(cl_mem),  &dying_d);     assert(err == CL_SUCCESS);
  err = clSetKernelArg(step_bbbattle, 2, sizeof(cl_mem),  &new_alive_d); assert(err == CL_SUCCESS);

  /* run kernel and stream to bbbout */

  char *alive_target;

  int gen = 1;
  while (1) {
    step();
    alive_target = clEnqueueMapBuffer(queue, alive_d, CL_TRUE, CL_MAP_READ, 0, mem_size, 0, NULL, NULL, &err);
    assert(err == CL_SUCCESS);

    memcpy(alive_h, alive_target, mem_size);
    clEnqueueUnmapMemObject(queue, alive_d, alive_target, 0, NULL, NULL);

    bbbout_write_generation(bbbo, gen, alive_h, NULL, team_counts);

    print_status(gen, teams, team_counts, team_colors);

    if (check_winner(teams, team_counts, team_colors) != 0) {
      break;
    }

    gen++;
  }

  bbbout_close(bbbo);

  free(alive_h);
  free(dying_h);

  clReleaseCommandQueue(queue);
  clReleaseKernel(step_bbbattle);
  clReleaseProgram(program);
  clReleaseMemObject(alive_d);
  clReleaseMemObject(dying_d);
  clReleaseMemObject(new_alive_d);
  clReleaseContext(context);

#ifdef CL_VERSION_1_2
  clReleaseDevice(device);
#endif

  return 0;
}
Beispiel #19
0
void game_starts(void)
{ 
  int step;
  for (step = 1; step <= 9; step++)
  {
    if(step % 2 == 1)
    {
      if (com == 'O')
        {
          switch(difficulty)
          {
          case 1:
          computerstep();
          break;
          case 2:
          midcomputerstep();
          break;
          case 3:
          hardcomputerstep();
          break;
          default:
          break; 
          }
        }

      else
        playerstep();
    }
    else if (step % 2 == 0)
    {
      if (com == 'X')
        {
          switch(difficulty)
          {
          case 1:
          computerstep();
          break;
          case 2:
          midcomputerstep();
          break;
          case 3:
          hardcomputerstep();
          break;
          default:
          break; 
          }
        }
      else
        playerstep();
    }

    print_board();

    if(check_winner() == com) 
    {
      printf ("You lose! You need more practice. Haha\n");
      return;
    }
  
    else if(check_winner() == user)
    {
      printf("Congrats, you win! I cannot stop you...\n");
      return;
    }
   
  }
    {
      printf("This game is draw. Nice game!\n");
      return;
    }
}
Beispiel #20
0
void fmap (CHAR_DATA * ch, bool forced, bool range, char *argument)
{
char buf1[70];
char buf2[70];
char buf3[70];
int i,j;
int total = 0;
CHAR_DATA * fighters[16];
int fightcount = 0;
CHAR_DATA *rch;
int theturn = 0;

if(!ch->in_room->map.init)
{
ch->in_room->map.init = TRUE;
generate_random_terrain(ch->in_room);
}   

if (IS_SET (ch->comm, COMM_NOMAP) && forced == TRUE)
return;

    for (rch = ch->in_room->people; rch != NULL; rch = rch->next_in_room)
    {
    if(rch->infight)
        {
        if(TURN(rch))
        theturn = 1;
        fighters[fightcount] = rch;
        fightcount++;
        }
     }

printf_to_char(ch,"\n\r%s",echo_off_str);

printf_to_char(ch," {y 0123456789abcdefghijklmnop{x\n\r");
printf_to_char(ch," ----------------------------  |-----------------------------------------------|\n\r");
for(i=0;i<16;i++)
{
char buf2[MSL];
printf_to_char(ch,"{W%c|{x",gridname[i]);
for(j=0;j<26;j++)
{
total += parse_room(ch,i,j,range);
}
if(i < fightcount)
{

sprintf(buf2," %s{x{w{W - %s%-19s {C %3dAT %5dHP %5dMP{W",fighters[i]->fdisp,get_t_color(fighters[i]),fcn(fighters[i]),fighters[i]->AT,fighters[i]->hit,fighters[i]->mana);
}
else
sprintf(buf2,"{x%47s{x"," ");
printf_to_char(ch,"{W|%c |%s|\n\r",gridname[i],buf2);
}

if(ch->in_room->turn != NULL)
{
char buf7[40];
CHAR_DATA *rch = ch->in_room->turn;

if(rch->level > 99)
sprintf(buf7,"{gL{W**{c ---{bexp{W             | PA MA BR FA MV JM SP |");
else
sprintf(buf7,"{gL{R%2d{c %3d{bexp{W             | PA MA BR FA MV JM SP |",rch->level,((rch->level + 1) * 100) - rch->exp);
 
sprintf(buf1," %s%-23s{W|{r%4d{c/{r%4d{RHP {g%3d{c/{g%3d{GMP{W |",get_t_color(rch),fcn(rch),rch->hit,rch->max_hit,rch->mana,rch->max_mana);
sprintf(buf2," %s",buf7);
sprintf(buf3,"                        | %2d %2d %2d %2d %2d %2d %2d {W|",rch->PhysAttack,rch->MagAttack,
rch->Brave,rch->Faith,rch->MoveLeft,rch->jump,rch->speed);
printf_to_char(ch," {W----------------------------  |-----------------------------------------------|\n\r");
printf_to_char(ch," |{y0123456789abcdefghijklmnop{W|  |%-44s",buf1);
//parse_room(ch,(rch->mposy - 1),(rch->mposx - 1),FALSE);
//parse_room(ch,(rch->mposy - 1),rch->mposx,FALSE);
//parse_room(ch,(rch->mposy - 1),(rch->mposx + 1),FALSE);
printf_to_char(ch,"{W\n\r");
printf_to_char(ch," {W----------------------------  |%-44s",buf2);
//parse_room(ch,rch->mposy,(rch->mposx - 1),FALSE);
//parse_room(ch,rch->mposy,rch->mposx,FALSE);
//parse_room(ch,rch->mposy,(rch->mposx + 1),FALSE);
printf_to_char(ch,"{W\n\r");
printf_to_char(ch," {W|%-26s|  |%-44s",ch->in_room->name,buf3);
//parse_room(ch,(rch->mposy + 1),(rch->mposx - 1),FALSE);
//parse_room(ch,(rch->mposy + 1),rch->mposx,FALSE);
//parse_room(ch,(rch->mposy + 1),(rch->mposx + 1),FALSE);
printf_to_char(ch,"{W\n\r");
}


printf_to_char(ch," ----------------------------  |-----------------------------------------------|\n\r");



check_winner(ch->in_room);
printf_to_char(ch,"%s", echo_on_str);

}
Beispiel #21
0
int main(int argc, char *argv[]) {
  

	int sockfd, newsockfd, portno, clilen, game, bytes_recv,bytes_sent,line,col,count, flag,aux,aux2;
	struct sockaddr_in serv_addr, cli_addr;
	char *client_name;
	char buffer[SIZE_BUFFER];
	char choice,symbol,client_symbol;
	
	
	symbol='X';
	client_symbol='O';
	
	game=0;

	client_name=(char*)malloc(NAME_SIZE*sizeof(char));

	
	if (argc < 2) {
        	printf("ERROR : INVALID USAGE\n");
		printf("(%s port \n",argv[0]);
        	return -1;
        }

	sockfd = socket(AF_INET,SOCK_STREAM,0);
	
	if (sockfd < 0){
		perror("ERROR opening socket");
		return -1;
	}


	bzero((char *) &serv_addr, sizeof(serv_addr));
	portno = atoi(argv[1]);
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons(portno);

	if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){
		perror("ERROR on binding\n");
		return -1;
	}

	
	if(listen(sockfd,5)<0) {
		perror("ERROR : FAILED TO LISTEN\n");
		return -1;
	}

	clilen = sizeof(cli_addr);

	system("clear");
	server_header();
	do {
 		bzero(client_name,NAME_SIZE);
		printf("Waiting for a chalenger...\n");
		
		newsockfd=accept(sockfd,(struct sockaddr *)&cli_addr,&clilen);
		
		if (newsockfd < 0){
     			perror("ERROR on accept");
			return -1;
		}
		
		
		bytes_recv=read(newsockfd,client_name,NAME_SIZE);
		
		if(bytes_recv<0) {
			perror("ERROR : FAILED TO ACQUIRE DATA INFORMATION");
			return -1;
		}
	
		printf("New chalenger found : %s\n",client_name);
		printf("Do you want to play with this challenger (Y/N)? : ");
		scanf(" %c",&choice);
		
		bzero(buffer,SIZE_BUFFER);

		if(choice=='Y' || choice=='y') {
			strcpy(buffer,"01");
			bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);
    			
                        if(bytes_sent<0) {
                        perror("ERROR : FAILED TO SEND DATA INFORMATION");
                        return -1; 
                        }
			bzero(buffer,SIZE_BUFFER);
			game=1;
			system("clear");
		}
		else if(choice=='N' || choice=='n') {
			strcpy(buffer,"00");

			bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);
			
			if(bytes_sent<0) {
                        perror("ERROR : FAILED TO SEND DATA INFORMATION");
                        return -1;
              	 	}

			close(newsockfd);
			continue;
			}
	
		else {
			printf("Option not available\n");
			return -1;
			}
		
	} while(game==0);

	init();
	server_header();
	display_board();
	
	count=0;
	flag=0;
	aux=0;
	aux2=0;

	while (count<9) { 

		if(flag==0) {
	
			do{
			printf("Your move...\n");
			printf("Line (1 to 3) : ");
			scanf("%d",&line);
			printf("Column (1 to 3) : ");
			scanf("%d",&col);
			}while(check_move(line,col)==0);
			
			move(line,col,symbol);
			system("clear");
			server_header();
			display_board();

			buffer[0]=line+'0';
			buffer[1]=col+'0';
		
			bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);

			if(bytes_sent<0) {
				perror("ERROR : FAILED TO SEND DATA INFORMATION");
				return -1;
			}

			bzero(buffer,SIZE_BUFFER);
			count++;
		} 
		else {
		
			printf("\nThe challenger’s move...\n");
			
			bytes_recv=read(newsockfd,buffer,SIZE_BUFFER);

			if(bytes_recv<0) {
				perror("ERROR : FAILED TO ACQUIRE DATA INFORMATION");
				return -1;
			}
			
			line=buffer[0]-'0';
			col=buffer[1]-'0';
			move(line,col,client_symbol);
			system("clear");
			server_header();
			display_board();
			count++;
		}

		
		
		if(count>4) { // min 5 moves to found a winner

			aux=check_winner(symbol);
			aux2=check_winner(client_symbol);
			
			if(aux==1) {
			
				printf("You won the game\n");

				strcpy(buffer,"00");
				bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);
				
				if(bytes_sent<0) {
					perror("ERROR : FAILED TO SEND DATA INFORMATION");
					return -1; 
				}
				break;
			}
		
			else if(aux2==1) {
                 
                                printf("You lost the game\n");

                                strcpy(buffer,"01");
                                bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);
                         
                                if(bytes_sent<0) {
                                        perror("ERROR : FAILED TO SEND DATA INFORMATION");
                                        return -1;
                                }
                                break;
                        }
			else {
				strcpy(buffer,"22");
                                bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);

                                if(bytes_sent<0) {
                                        perror("ERROR : FAILED TO SEND DATA INFORMATION");
                                        return -1;
                                }
			}

				
		}
		
		if(flag==1)
			flag=0;
		else
			flag=1;
		
	}
	
	if(aux==0 && aux2==0) {
		
		printf("The game ended with a draw\n");
		
		strcpy(buffer,"11");
                
		bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);
                
		if(bytes_sent<0) {
                	perror("ERROR : FAILED TO SEND DATA INFORMATION");
                        return -1;
               	}
	}
	
	
	strcpy(buffer,"22");
	bytes_sent=write(newsockfd,buffer,SIZE_BUFFER);
	if(bytes_sent<0) {
		perror("ERROR : FAILED TO SEND DATA INFORMATION");
		return -1;
	}

	close(sockfd);
	close(newsockfd);
	free(client_name);

	return 0;
}