int randBuy(struct gameState *game){
  int card;
  if (game->coins >= getCost(province))
    card = province;
  else
    card = floor(Random()*(treasure_map+1));

  if (game->coins == 0){
    game->numBuys = 0;
    return 0;
  }


  if (getCost(card) > game->coins || game->supplyCount[card] <= 0) {
    if (buyCard(card,game) == 0) {
      printf("Bad attempt to buy card was successfull: ");
      printCard(card);
      printf("\n\r");
      return -1;
    }
    else
      return 0;
  }


  printf("Card to buy: ");
  printCard(card);
  printf("\n\r");
  return buyCard(card,game);
}
Exemple #2
0
void buyCost5(struct gameState *p, int * k){
	int i = 0;
	int counter = 0;
	int j = 0;
	for(;i<10;i++){
		if (k[i] == outpost || k[i] == minion || k[i] == duchy)
			counter++;
		else if(k[i] == council_room || k[i] == mine || k[i] == tribute)
			counter++;
	}
	int * costFive = malloc(sizeof(int)*counter);
	for(i =0; i<10;i++){
		if (k[i] == outpost || k[i] == minion || k[i] == duchy)
			costFive[j] = k[i];
		else if(k[i] == council_room || k[i] == mine || k[i] == tribute)
			costFive[j] = k[i];
	}
	if(counter != 0){
		int num = rand() % counter;
		buyCard(costFive[num],p);
		printf("%s bought\n",printCard(costFive[num]));
		}
	else{
		buyCard(silver,p);
		printf("%s bought\n",printCard(silver));
		}
}
}

int main(int argc, char** argv){
   struct gameState *G;
      int numplayers, money, handpos, rseed, rcard, choice1, choice2, choice3, coinflip, i, numtests,r;
      int *k;
      int players[4];
      numtests=1;
      for(i=0; i<numtests; i++){
	 G=newGame();
	    rseed=atoi(argv[1]);
	    k = malloc(sizeof(int)*10);
	    numplayers=rand()%3+2;
	    chooseKingdomCards(k);
	    initializeGame(numplayers, k, rseed, G);

	    printf("FOR SEED %d\n", rseed);
	    if(isGameOver(G)){
	       printf("game creation error\n");
	       printf("test %d failed\n",i);
	    }
	    else{
	       while(!isGameOver(G)){
                printf("player %d turn start\n", whoseTurn(G));
		  handpos=-1;
		     coinflip=rand()%10;
		  rcard=chooseHandCard(G, k, &handpos);
		     choice1=rand()%2;
		     choice2=0;
		     if(choice1==0){
			choice2=1;
		     }
		  choice3=rand()%2;
		     if(rcard!=-1 || rcard==curse){
			r=playCard(handpos, choice1,choice2,choice3,G);
			printf("player %d played ", whoseTurn(G));
			printCard(rcard, r);
		     }
		  money=countMoney(G);
		     printf("money: %d\n", money);
		     rcard=randomBuyCard(G, money, k);
		     if(coinflip!=9){			//small chance to not buy anything
			r=buyCard(rcard, G);
			printf("player %d bought ", whoseTurn(G));
			printCard(rcard, r);
		     }
		     printf("player %d hand\n", whoseTurn(G));
		     printhand(G);
		     printf("player %d score: %d\n", whoseTurn(G), scoreFor(whoseTurn(G),G));
		     printf("player %d turn ending\n", whoseTurn(G));
		     endTurn(G);
		     if(isGameOver(G)){
			printf("game over player %d won\n", getWinners(players, G));
		     }
	       }
	       free(k);
	       free(G);
	       printf("test %d passed\n", i);
	    }
      }
Exemple #4
0
void buyCost4(struct gameState *p, int * k){
	int i = 0;
	int counter = 0;
	int j = 0;
	for(;i<10;i++){
		if (k[i] == cutpurse || k[i] == baron || k[i] == feast)
			counter++;
		else if(k[i] == gardens || k[i] == remodel || k[i] == smithy)
			counter++;
		else if(k[i] == salvager || k[i] == sea_hag || k[i] == treasure_map)
			counter++;
	}
	int * costFour = malloc(sizeof(int)*counter);
	for(i =0; i<10;i++){
		if (k[i] == cutpurse || k[i] == baron || k[i] == feast){
			costFour[j] = k[i];
			j++;}
		else if(k[i] == gardens || k[i] == remodel || k[i] == smithy){
			costFour[j] = k[i];
			j++;}
		else if(k[i] == salvager || k[i] == sea_hag || k[i] == treasure_map){
			costFour[j] = k[i];
			j++;}
	}
	if(counter != 0){
		int num = rand() % counter;
		buyCard(costFour[num],p);
		printf("%s bought\n",printCard(costFour[num]));
		}
	else{
		buyCard(silver,p);
		printf("%s bought\n",printCard(silver));
		}
}
/*
	handle info
*/
void handleInfo(int type){
	// clock_t start, finish;
	// double duration;
	// fprintf(file, "handle info type: %d\n", type);
	switch(type){
		case 0: // seat info
			initEveryHandParams();
			splitSeatInfo(tmpInfo);
			fprintf(file, "-----------------hand %d------------------\n\n", pubInfo.handNum);
			fprintf(file, "my seat: %d \n", myInfo.mySeat);
			break;
		case 1: // blind info
			splitBlindInfo(tmpInfo, &(pubInfo.smallBlind), &(pubInfo.bigBlind));
			break;
		case 2: // hand card
			splitHandCardInfo(tmpInfo, myInfo.handCard);
			printCard("handcard");
			pubInfo.progress = PRGS_PREFLOP; //pre flop
			break;
		case 3: // inqure and take action !!!!
			// start = clock();
			splitInquireInfo(tmpInfo, pubInfo.inquire);
			takeAction();
			// finish = clock();
			// duration = (double)(finish - start) / CLOCKS_PER_SEC;
			// fprintf(file, "take action use %f ms\n", duration*1000);
			break;
		case 4: // flop
			splitPublicCardInfo(tmpInfo, pubInfo.publicCard, "flop");
			printCard("flop");
			pubInfo.progress = PRGS_FLOP; // flop
			break;
		case 5: // turn
			splitPublicCardInfo(tmpInfo, pubInfo.publicCard, "turn");
			printCard("turn");
			pubInfo.progress = PRGS_TURN; //turn
			break;
		case 6: // river
			splitPublicCardInfo(tmpInfo, pubInfo.publicCard, "river");
			printCard("river");
			pubInfo.progress = PRGS_RIVER; //river
			break;
		case 7: //show down info
			splitShowDownInfo(tmpInfo);
			break;
		case 8: // pot win
			splitPotWinInfo(tmpInfo);
			break;
		case 9: // notify
			//splitInquireInfo(tmpInfo, pubInfo.notify);
			break;
		default:
			break;
	}
	return ;
}
Exemple #6
0
/*
 Loops the printCard function for every struct card in the struct deck.
 -----------------------------------------------------------------------------------------
 Parameters: deck *d
 Preconditions: d is not null
 Postconditions: the printCard function is called on every struct card in the struct deck.
 */
void printDeck(deck *d) {
    
    int i;
    assert(d);
    
    for (i = 0; i < NO_OF_CARDS; i++){
        printCard(d->cards[i]);
    }
}
Exemple #7
0
int main() {
    Card * deck = createDeck();
    //    printCard(deck[0]);
    //    printCard(deck[1]);
    for(int c=0;c<NUM_CARDS;c++) {
        printCard(deck[c]);
    }
    free(deck);
    return 0;
}
void printDeck(const std::array<Card, 52> &deck)
{
	for (const auto &card : deck)
	{
		printCard(card);
		std::cout << ' ';
	}

	std::cout << '\n';
}
Exemple #9
0
/**
 * Prints the deck that the argument points to. Doesn't use columns.
 * @param deck pointer to first card in the array.
 */
void printDeck(struct card * deck) {

    int i;

    for (i = 0; i < NUMCARDS; i++) {

        printCard(*(deck + i));
        printf("\n");

    }

}
Exemple #10
0
void printFounds(int founds[4][13])
{
	int i,j;
	for(j=12;j>=0;j--)
	{
		for(i=0;i<4;i++)
		{
			printCard(founds[i][j]);
		}
		printf("\n");
	}
}
Exemple #11
0
void buyCost2(struct gameState *p, int * k){
	int i = 0;
	int counter = 0;
	int j = 0;
	for(;i<10;i++){
		if (k[i] == embargo)
			counter++;
	}
	int * costTwo = malloc(sizeof(int)*counter);
	for(i =0; i<10;i++){
		if (k[i] == embargo)
			costTwo[j] = k[i];
	}
	if(counter != 0){
		int num = rand() % counter;
		buyCard(costTwo[num],p);
		printf("%s bought\n",printCard(costTwo[num]));
		}
	else{
		buyCard(estate,p);
		printf("%s bought\n",printCard(estate));
		}
}
Exemple #12
0
void print_hand( std::vector<Card> &hand )
{

  std::string types[]{"two","three","four","five","six","seven","eight","nine","ten","jack","queen","king","ace"};
  std::string suits[]{"heart","club","spade","diamond"};
  for( Card &c : hand ) {
    std::cout << types[c.type] << " of " << suits[c.suit] << " ";
  }

  std::cout << "\n";
  for_each( begin(hand), end(hand), 
	    [](const Card &c) { printCard(c); std::cout << " "; } );
  std::cout << "\n";
}
Exemple #13
0
void buyCost3(struct gameState *p, int * k){
	int i = 0;
	int counter = 0;
	int j = 0;
	for(;i<10;i++){
		if (k[i] == village || k[i] == great_hall || k[i] == steward || k[i] == ambassador)
			counter++;
	}
	int * costThree = malloc(sizeof(int)*counter);
	for(i =0; i<10;i++){
		if (k[i] == village || k[i] == great_hall || k[i] == steward || k[i] == ambassador)
			costThree[j] = k[i];
	}
	if(counter != 0){
		int num = rand() % counter;
		buyCard(costThree[num],p);
		printf("%s bought\n",printCard(costThree[num]));
		}
	else{
		buyCard(silver,p);
		printf("%s bought\n",printCard(silver));
		}
}
Exemple #14
0
int main() {

	runTests();

	for (int i = 0; i < 52; i++) {
		deck[i].suit = i/13;
		deck[i].value = (i%13)+1;
	}

	shuffle();


	for (int i = 0; i < 52; i++) {
		printCard(deck[i]);
		printf("\n");
	}
}
Exemple #15
0
void storePlayable(struct gameState *p, int * pc){
	int i = 0;
	int j = 0;
	while(i<numHandCards(p)){
		if(handCard(i, p) != copper && (handCard(i, p) != silver) && (handCard(i, p) != gold)){
			if((handCard(i, p) != estate) && (handCard(i, p) != province) && (handCard(i, p) != curse)){
				if(printCard(handCard(i,p)) != ""){
					pc[j] = handCard(i,p);
					i++;
					j++;}
			}
			else 
				i++;
		}
		else
			i++;
	}
}
Exemple #16
0
void printTable(int table[7][20]){
	int i,j;
	int empty;
	char card;
	for(i=19;i>=0;i--){
		//don't print when whole row is empty
		empty=1;
		for(j=0;j<7;j++){
			if(table[j][i]!=0) empty = 0;
		}
		if(empty) continue;
		
		for(j=0;j<7;j++){
			printCard(table[j][i]);
		}
		printf("\n");
	}
}
int main ()
{
	int** newCard; 
	int index;
	Player Harry; //This is how you make a player. 
	Player Bob
	for(index=0; index<10; index++)//generate bingoCards for every player connected
	{
		newCard = createCard();
		initCard(newCard);
	}
	
	/*Heres a little demo on how you would access elements inside the struct*/
	strncpy(Harry.playerName,"Harrison",20); //copy Name into the structs playerName field.
	Harry.playerBingoCard = newCard; //give Harry his bingo card so he can beat old women at bingo 
	printf("Player Name: %s\n", Harry.playerName); //access Player's name
	printCard(Harry.playerBingoCard); //access Player's bingo card	
	return 0; 	
}
Exemple #18
0
void runTests() {

	Deck testDeck;
	testDeck.length = 0;

	if(!isEmpty(testDeck)) {
		printf("isEmpty test 1 failed!\n");
	}

	testDeck.length = 1;

	if(isEmpty(testDeck)) {
		printf("isEmpty test 2 failed!\n");
	}

    testDeck.length = 0;

    Card testCard;
    testCard.suit = Hearts;
    testCard.value = 13;

    addCard(&testDeck, testCard);

    printCard(testDeck.cards[0]);
    printf("\n======\n");

	if(isEmpty(testDeck)) {
		printf("addCard test 1 failed!\n");
	}

	//Card yourmom = 
	removeCard(&testDeck);
	//printCard(yourmom);




}
Exemple #19
0
/**
 * Prints players' hands using players' hands' cards' formal names.
 * @param players number of hands to print
 * @param cardsPerHand number of cards per hand
 * @param hands pointer to first hand in the array of hands
 */
void printHandsNamed(int players, int cards, struct hand * hands) {

    int player;
    int card;

    for (player = 0; player < players; player++) { //For each player

        printf("Player %i: \n", player + 1);

        for (card = 0; card < cards; card++) { //For each card in hand

            //Print
            printf("\t");
            printCard(hands[player].cards[card]);
            printf("\n");

        }

        printf("\n");

    }

}
Exemple #20
0
void Pantalla::printGame(std::vector<Carta*> m, int pot_m){
	int x, y, size_pot;
	size_pot = 0;
	int temp = pot_m;
	while(temp > 1){
		size_pot++;
		temp /= 10;
	}
	size_pot += 6;
	getmaxyx(mesa,y,x);
	wmove(mesa, 1,(x/2)-(size_pot/2));
	wprintw(mesa, "pot = %d", pot_m);

	int x_cont = 3;
	for(auto item:m){
		//mvwprintw(mesa, 2, x_cont, item->getRepre());
		printCard(item, mesa, x_cont, 2);
		x_cont += 6;
	}

	refresh();
	wrefresh(mesa);
}
Exemple #21
0
/** \brief Imprime um estado de jogo

    Esta função imprime o estado atual do jogo no browser

    @param gameState    estado atual do jogo
*/
void render (state gameState) {

    char *path = DECK;

    printf("<svg width = \"1200\" height = \"800\">\n");

    printf("<rect x = \"0\" y = \"0\" height = \"800\" width = \"1200\" style = \"fill:#007700\"/>\n");

    printf("</svg>\n");

    /* Anotar quem já jogou para não haver confusão ao imprimir as cartas */
    /* (porque se ainda não houveram jogadas, o valor de lastplay será ~((long long int) 0))) */

    bool hasPlayed[4] = {true, true, true, true};     /* Quais jogadores já jogaram */
    bool hasPassed[4] = {false, false, false, false}; /* Quais jogadores passaram */

    int m;
    for (m = 0; m < 4; m++) {

        if (gameState.lastPlays[m] == 0) { /* Se este jogador passou */

            hasPassed[m] = true;

        } else if (~(gameState.lastPlays[m]) == 0) { /* Se este jogador ainda não fez nada neste jogo */

            hasPlayed[m] = false;
        }
    }

    /* Largura das cartas (não pode ser modificado aqui, read only) */
    int cardWidth = 80;

    /* Espaço entre cartas */
    int spaceBetweenCards = 30;

    /* Posições iniciais para cada mão */
    /*              mão 3              */
    /*       mão 4        mão 2        */
    /*              mão 1              */
    int hand1x = 400, hand1y = 650;
    int hand2x = 1065, hand2y = 520;
    int hand3x = (hand1x + (spaceBetweenCards * 12)), hand3y = 50;
    int hand4x = 85, hand4y = (hand2y - (spaceBetweenCards * 12)); /* As duas mãos laterais são imprimidas na vertical uma ao contrário da outra */

    int play1x = hand1x + 170, play1y = hand1y - 150;
    int play2x = hand2x - 250, play2y = hand2y - 190;
    int play3x = play1x, play3y = hand3y + 130;
    int play4x = play2x - 490, play4y = play2y;

    int handx[4] = {hand1x, hand2x, hand3x, hand4x};
    int handy[4] = {hand1y, hand2y, hand3y, hand4y};

    int playx[4] = {play1x, play2x, play3x, play4x};
    int playy[4] = {play1y, play2y, play3y, play4y};

    /* Calcular o distanciamento das mãos em pixeis em relação à sua posição original com base no seu tamanho */

    int handDeltas[4], playDeltas[4];

    int l;
    for (l = 0; l < 4; l++) {

        int handLength = getHandLength(gameState.hands[l]);
        int lastPlayLength = getHandLength(gameState.lastPlays[l]);

        int handLengthPx = cardWidth + ( spaceBetweenCards * ( handLength - 1 ) );
        /* int lastPlayLengthPx = cardWidth + ( spaceBetweenCards * ( lastPlayLength - 1 ) ); */

        /* A deslocação é de 1/(13 * 2) da largura da mão por cada carta removida (por cada carta a menos de 13) */
        int deltaHand = (13 - handLength) * ( ( 1 / (26) ) * handLengthPx );

        /* A deslocação é de 1/2 * spaceBetweenCards por cada carta acima de 1 */

        int deltaLastPlay;

        if (lastPlayLength > 0) {

           deltaLastPlay = (lastPlayLength - 1) * ( (1/2) * spaceBetweenCards);

        } else {

            deltaLastPlay = 0;
        }

        handDeltas[l] = deltaHand;
        playDeltas[l] = deltaLastPlay;
    }

    /* Aplicar deltas às posições originais */

    handx[0] += handDeltas[0];
    handy[1] -= handDeltas[1];
    handx[2] -= handDeltas[2];
    handy[3] += handDeltas[3];

    playx[0] -= playDeltas[0];
    playx[1] -= playDeltas[1];
    playx[2] -= playDeltas[2];
    playx[3] -= playDeltas[3];

    if (gameState.sort == 0) { /* para o default do sort=0, que vai meter ordem por valores @@@@@@@@@@@ VITOR */

        int i, j, k;

        for (j = 0; j < 13; j++) { /* Percorrer valores */

            for (i = 0; i < 4; i++) { /* Percorrer naipes */

                for (k = 0; k < 4; k++) { /* Percorrer todas as mãos / últimas jogadas e descobrir se a carta pertence a uma delas */

                    if (cardExists(gameState.hands[k], i, j)) {

                        if (k == 0) {

                            /* Se a carta for do utilizador e estiver selecionada, imprime-se mais acima */
                            if (cardExists(gameState.selection, i, j)) {

                                printCard(path, handx[k], (handy[k] - 20), i, j, gameState, 2);

                            } else {

                                printCard(path, handx[k], handy[k], i, j, gameState, 2);
                            }

                            handx[k] += spaceBetweenCards; /* Incrementar o x para a próxima carta na mão de baixo */

                        } else if (k == 1) {

                            printCard(path, handx[k], handy[k], i, j, gameState, 1);

                            handy[k] -= spaceBetweenCards;

                        } else if (k == 2) {

                            printCard(path, handx[k], handy[k], i, j, gameState, 0);

                            handx[k] -= spaceBetweenCards; /* Decrementar o x para a próxima carta na mão de cima */

                        } else if (k == 3) {

                            printCard(path, handx[k], handy[k], i, j, gameState, 3);

                            handy[k] += spaceBetweenCards;
                        }

                    } else if (hasPlayed[k] && !hasPassed[k] && cardExists(gameState.lastPlays[k], i, j)) {

                        printCard(path, playx[k], playy[k], i, j, gameState, 2);

                        if (k == 0) {

                            playx[k] += spaceBetweenCards;

                        } else if (k == 1) {

                            playx[k] += spaceBetweenCards;

                        } else if (k == 2) {

                            playx[k] += spaceBetweenCards;

                        } else if (k == 3) {

                            playx[k] += spaceBetweenCards;
                        }
                    }
                }
            }
        }
    }

    else { /* para o caso de o jogador ter mudado a ordenação, tornando o valor do sort=1, que vai meter ordem por naipes @@@@@@@@@@@ VITOR */

        int i, j, k;

        for (i = 0; i < 4; i++) { /* Percorrer naipes- FOI TROCADA A ORDEM - VITOR */

            for (j = 0; j < 13; j++) { /* Percorrer valores - FOI TROCADA A ORDEM - VITOR */

                for (k = 0; k < 4; k++) { /* Percorrer todas as mãos / últimas jogadas e descobrir se a carta pertence a uma delas */

                    if (cardExists(gameState.hands[k], i, j)) {

                        if (k == 0) {

                            /* Se a carta for do utilizador e estiver selecionada, imprime-se mais acima */
                            if (cardExists(gameState.selection, i, j)) {

                                printCard(path, handx[k], (handy[k] - 20), i, j, gameState, 2);

                            } else {

                                printCard(path, handx[k], handy[k], i, j, gameState, 2);
                            }

                            handx[k] += spaceBetweenCards; /* Incrementar o x para a próxima carta na mão de baixo */

                        } else if (k == 1) {

                            printCard(path, handx[k], handy[k], i, j, gameState, 1);

                            handy[k] -= spaceBetweenCards;

                        } else if (k == 2) {

                            printCard(path, handx[k], handy[k], i, j, gameState, 0);

                            handx[k] -= spaceBetweenCards; /* Decrementar o x para a próxima carta na mão de cima */

                        } else if (k == 3) {

                            printCard(path, handx[k], handy[k], i, j, gameState, 3);

                            handy[k] += spaceBetweenCards;
                        }

                    } else if (hasPlayed[k] && !hasPassed[k] && cardExists(gameState.lastPlays[k], i, j)) {

                        printCard(path, playx[k], playy[k], i, j, gameState, 2);

                        if (k == 0) {

                            playx[k] += spaceBetweenCards;

                        } else if (k == 1) {

                            playx[k] += spaceBetweenCards;

                        } else if (k == 2) {

                            playx[k] += spaceBetweenCards;

                        } else if (k == 3) {

                            playx[k] += spaceBetweenCards;
                        }
                    }
                }
            }
        }
    }

    /* Imprimir os textos "Passou" nos jogadores que passaram nesta jogada */
    int p;
    for (p = 0; p < 4; p++) {

        if (hasPassed[p] == true) {
            printPass(playx[p], playy[p] - 20);
        }
    }

    /* Imprimir botões */

    printf("<div id=\"button-container\">");

    /* Botão de jogar */

    char playStateString[10240];

    /* Se a seleção atual for jogável */
    if (isSelectionPlayable(gameState)) {

        state stateAfterPlay = gameState;

        stateAfterPlay.play = true;

        sprintf(playStateString, "%s?q=%s", SCRIPT, stateToString(stateAfterPlay));

        printf("<a href=\"%s\" class=\"btn green\">Jogar</a>", playStateString);

    } else {

        printf("<a href=\"#\" class=\"btn green disabled\">Jogar</a>");
    }

    /* Botão de passar */

    state stateAfterPass = gameState;

    stateAfterPass.pass = true;

    char passStateString[10240];

    sprintf(passStateString, "%s?q=%s", SCRIPT, stateToString(stateAfterPass));

    printf("<a href=\"%s\" class=\"btn orange\">Passar</a>", passStateString);

    /* Botão de limpar */

    state stateAfterClear = gameState;

    stateAfterClear.selection = 0;

    char clearStateString[10240];

    sprintf(clearStateString, "%s?q=%s", SCRIPT, stateToString(stateAfterClear));

    printf("<a href=\"%s\" class=\"btn purple\">Limpar</a>", clearStateString);

    /* Botão de recomeçar */

    printf("<a href=\"%s\" class=\"btn red\">Recomeçar</a>", SCRIPT);

    /* Botão de ordenar */

    char sortStateString[10240];

    state stateAfterSort = gameState;

    stateAfterSort.sort = !(stateAfterSort.sort);

    sprintf(sortStateString, "%s?q=%s", SCRIPT, stateToString(stateAfterSort));

    printf("<a href=\"%s\" class=\"btn blue\">Ordem</a>", sortStateString);

    /* Botão de dica */

    state stateAfterTip = gameState;

    stateAfterTip.selection = chooseAIPlay(stateAfterTip, 0); /* Cria uma possível jogada, usando a função dos bots */

    char tipStateString[10240];

    sprintf(tipStateString, "%s?q=%s", SCRIPT, stateToString(stateAfterTip));

    printf("<a href=\"%s\" class=\"btn yellow\">Dica</a>", tipStateString);

    printf("</div>");

    /*
    int scorePlayer0 = (getHandLenght(gameState.hands[0] * (-1));
    int scorePlayer1 = (getHandLenght(gameState.hands[1] * (-1));
    int scorePlayer2 = (getHandLenght(gameState.hands[2] * (-1));
    int scorePlayer3 = (getHandLenght(gameState.hands[3] * (-1));

    printf("<a href=\"%d\" class=\"btn yellow\">%s - %d, %s - %d, %s - %d, %s - %d</a>", Score, "Player 0", scorePlayer0, "Player 1", scorePlayer1, "Player 2", scorePlayer2, "Player 3", scorePlayer3);

    printf para dar score.
    */

}
Exemple #22
0
void doMassPoint(float analysis, Option option, RunEra runEra)
{

    bool blind = false;

    //
    // set up the looper
    //

    SmurfLooper *looper = new SmurfLooper(analysis, option, runEra);
    //looper->setGoodRunList("../runlists/runlist_1092.txt");
    const float lumi = 19467;
    looper->setLumiScale(lumi, lumi); 


    //
    // set up samples
    //
    int ana = (int)analysis;

    SmurfSample *sample_data = new SmurfSample(option, DATA, kBlack, "Data", analysis);

    // higgs samples
    SmurfSample *sample_gghww = new SmurfSample(option, GGHWW, kCyan, "ggH", analysis);
    SmurfSample *sample_qqhww = new SmurfSample(option, QQHWW, kCyan, "qqH", analysis);
    SmurfSample *sample_zhww = new SmurfSample(option, ZHWW, kCyan, "ZH", analysis);
    SmurfSample *sample_whww = new SmurfSample(option, WHWW, kCyan, "WH", analysis);

    // backgrounds
    SmurfSample *sample_qqww = new SmurfSample(option, QQWW, kYellow+2, "qqWW", analysis);
    SmurfSample *sample_ggww = new SmurfSample(option, GGWW, kYellow+2, "ggWW", analysis);

    SmurfSample *sample_vv = new SmurfSample(option, VV, kGreen, "VV", analysis);
    SmurfSample *sample_top = new SmurfSample(option, TOP, kMagenta, "Top", analysis);
    // note this considers only the Drell Yan part
    SmurfSample *sample_dyll = new SmurfSample(option, ZLL, kBlue, "DYLL", analysis);
    // NOTE. this zjets is a historial nameing..
    // this corresponds to the WZ/ZZ where both leptons are from the same Z
    //SmurfSample *sample_zjets       = new SmurfSample(option, ZJETS, kBlue, "Zjets", analysis);
    SmurfSample *sample_wjets       = new SmurfSample(option, WJETSDATA,    kCyan, "Wjets",     analysis);
    SmurfSample *sample_wjetsEle    = new SmurfSample(option, WJETSELEDATA, kCyan, "WjetsE",    analysis);
    SmurfSample *sample_wjetsMu     = new SmurfSample(option, WJETSMUDATA,  kCyan, "WjetsM",    analysis);
    SmurfSample *sample_wgamma      = new SmurfSample(option, WGAMMA,       kCyan, "Wgamma",        analysis);
    SmurfSample *sample_wgammanorm  = new SmurfSample(option, WGAMMANORM,   kCyan, "Wgammanorm",    analysis);
    SmurfSample *sample_wg3l        = new SmurfSample(option, WG3L,         kCyan, "Wg3l",          analysis);
    SmurfSample *sample_ztt         = new SmurfSample(option, ZTT,          kBlue+2, "Ztt",         analysis);

    // Below are needed for the central shape
    //SmurfSample *sample_dyll_loosemet = new SmurfSample(option, ZLLLOOSEMET, kBlue, "DYLLLooseMET", analysis);

    // Below are needed for the shape variation studies
    SmurfSample *sample_top_var         = new SmurfSample(option, TOPALTER,     kMagenta,   "TopVar", analysis);
    SmurfSample *sample_wwmcnlo         = new SmurfSample(option, WWMCNLO,      kBlue+2,    "WWMCNLO", analysis);
    SmurfSample *sample_wwmcnlo_up      = new SmurfSample(option, WWMCNLOUP,    kBlue+2,    "WWMCNLOUp", analysis);
    SmurfSample *sample_wwmcnlo_down    = new SmurfSample(option, WWMCNLODOWN,  kBlue+2,    "WWMCNLODown", analysis);
    //SmurfSample *sample_wjets_mc        = new SmurfSample(option, WJETS,        kCyan,      "WjetsMC", analysis);
    //SmurfSample *sample_wjets_mc_loose  = new SmurfSample(option, WJETSMCLOOSE, kCyan,      "WjetsMCLoose", analysis);    
    //SmurfSample *sample_dyll_data       = new SmurfSample(option, ZLLDATA,      kBlue,      "DYLLDATA", analysis);
    SmurfSample *sample_gghww_ref       = new SmurfSample(option, GGHWWREF,     kCyan,      "ggHRef", analysis);
    SmurfSample *sample_gghww_jhu       = new SmurfSample(option, GGHWWJHU,     kCyan,      "ggHJHU", analysis);


    bool skimwithmva = true;

    // Below is the setup for running the smurf ntuples at the ww-preselection skim
    if ( skimwithmva) {
        char *dataDir = "/smurf/jaehyeok/data/Run2012_Summer12_SmurfV9_53X/mitf-alljets_19p5ifb_new/WW/"; // TAS
        //char *dataDir  = "/nfs-7/userdata/jaehyeok/smurfntuples/mitf-alljets/WW/"; // UAF

        // set up the mva histogram ranges
        unsigned int n = 20;
        float min = -1.0;
        float max = 1.0;
        if ( option == HWW_OPT_SMURFMESEL) min = 0.0;

        if ( analysis > 0. ) {
            // higgs
            for (int njet=0; njet < 2; njet++) {
                if ( option == XWW_OPT_MT2DMLL_JCP )  
                    sample_gghww->add(Form("%s/mva/%i/xww2p%i_%ij.root", dataDir, int(analysis), int(analysis), njet));
                else
                    sample_gghww->add(Form("%s/mva/%i/hww%i_%ij.root", dataDir, int(analysis), int(analysis), njet));
            }
            sample_gghww->addShapeVariation2D(LEPEFFVAR,    "histo_ggH_CMS_hww_MVALepEffBounding", false);
            sample_gghww->addShapeVariation2D(LEPRESVAR,    "histo_ggH_CMS_hww_MVALepResBounding", true);
            sample_gghww->addShapeVariation2D(METVAR,       "histo_ggH_CMS_hww_MVAMETResBounding", true);
            sample_gghww->addShapeVariation2D(JETRESVAR,    "histo_ggH_CMS_hww_MVAJESBounding", false);

            for (int njet=0; njet < 2; njet++) 
                sample_qqhww->add(Form("%s/mva/%i/hww%i_%ij.root", dataDir, int(analysis), int(analysis), njet));
            sample_qqhww->addShapeVariation2D(LEPEFFVAR, "histo_qqH_CMS_hww_MVALepEffBounding", false);
            sample_qqhww->addShapeVariation2D(LEPRESVAR, "histo_qqH_CMS_hww_MVALepResBounding", true);
            sample_qqhww->addShapeVariation2D(METVAR, "histo_qqH_CMS_hww_MVAMETResBounding", true);
            sample_qqhww->addShapeVariation2D(JETRESVAR, "histo_qqH_CMS_hww_MVAJESBounding", false);

            for (int njet=0; njet < 2; njet++) 
                sample_zhww->add(Form("%s/mva/%i/hww%i_%ij.root", dataDir, int(analysis), int(analysis), njet));
            sample_zhww->addShapeVariation2D(LEPEFFVAR, "histo_ZH_CMS_hww_MVALepEffBounding", false);
            sample_zhww->addShapeVariation2D(LEPRESVAR, "histo_ZH_CMS_hww_MVALepResBounding", true);
            sample_zhww->addShapeVariation2D(METVAR, "histo_ZH_CMS_hww_MVAMETResBounding", true);
            sample_zhww->addShapeVariation2D(JETRESVAR, "histo_ZH_CMS_hww_MVAJESBounding", false);

            for (int njet=0; njet < 2; njet++) 
                sample_whww->add(Form("%s/mva/%i/hww%i_%ij.root", dataDir, int(analysis), int(analysis), njet));
            sample_whww->addShapeVariation2D(LEPEFFVAR, "histo_WH_CMS_hww_MVALepEffBounding", false);
            sample_whww->addShapeVariation2D(LEPRESVAR, "histo_WH_CMS_hww_MVALepResBounding", true);
            sample_whww->addShapeVariation2D(METVAR, "histo_WH_CMS_hww_MVAMETResBounding", true);
            sample_whww->addShapeVariation2D(JETRESVAR, "histo_WH_CMS_hww_MVAJESBounding", false);
        }

        // bkgs
        // qqWW
        for (int njet=0; njet < 2; njet++) 
            sample_qqww->add(Form("%s/mva/%i/qqww_%ij.root", dataDir, int(analysis), njet));

        if ( analysis < 200) 
            sample_qqww->addShapeVariation2D(LEPEFFVAR, "histo_qqWW_CMS_hww_MVALepEffBounding", true);
        else 
            sample_qqww->addShapeVariation2D(LEPEFFVAR, "histo_qqWW_CMS_hww_MVALepEffBounding", false);
        sample_qqww->addShapeVariation2D(LEPRESVAR, "histo_qqWW_CMS_hww_MVALepResBounding", true);
        sample_qqww->addShapeVariation2D(METVAR, "histo_qqWW_CMS_hww_MVAMETResBounding", true);
        sample_qqww->addShapeVariation2D(JETRESVAR, "histo_qqWW_CMS_hww_MVAJESBounding", false);

        // ggWW
        for (int njet=0; njet < 2; njet++) 
            sample_ggww->add(Form("%s/mva/%i/ggww_%ij.root", dataDir, int(analysis), njet));

        if ( analysis < 200) 
            sample_ggww->addShapeVariation2D(LEPEFFVAR, "histo_ggWW_CMS_hww_MVALepEffBounding", true);
        else 
            sample_ggww->addShapeVariation2D(LEPEFFVAR, "histo_ggWW_CMS_hww_MVALepEffBounding", false);
        sample_ggww->addShapeVariation2D(LEPRESVAR, "histo_ggWW_CMS_hww_MVALepResBounding", true);
        sample_ggww->addShapeVariation2D(METVAR, "histo_ggWW_CMS_hww_MVAMETResBounding", true);
        sample_ggww->addShapeVariation2D(JETRESVAR, "histo_ggWW_CMS_hww_MVAJESBounding", false);

        // Drell-Yan
        for (int njet=0; njet < 2; njet++) {
            sample_dyll->add(Form("%s/mva/%i/dyll_%ij.root", dataDir, int(analysis), njet));
            //sample_dyll_loosemet->add(Form("%s/mva/%i/dyll_%ij.root", dataDir, int(analysis), njet));
            //ample_zjets->add(Form("%s/mva/%i/dyll_%ij.root", dataDir, int(analysis), njet));
        }

        // Top 
        for (int njet=0; njet < 2; njet++) {
            sample_top->add(Form("%s/mva/%i/ttbar_powheg_%ij.root", dataDir, int(analysis), njet));
            sample_top->add(Form("%s/mva/%i/tw_%ij.root", dataDir, int(analysis), njet));
        }

        sample_top->addShapeVariation2D(LEPRESVAR, "histo_Top_CMS_hww_MVALepResBounding", true);
        sample_top->addShapeVariation2D(METVAR, "histo_Top_CMS_hww_MVAMETResBounding", true);
        sample_top->addShapeVariation2D(JETRESVAR, "histo_Top_CMS_hww_MVAJESBounding", false);

        // VV 
        for (int njet=0; njet < 2; njet++) {
            sample_vv->add(Form("%s/mva/%i/wz_%ij.root", dataDir, int(analysis), njet));
            sample_vv->add(Form("%s/mva/%i/zz_%ij.root", dataDir, int(analysis), njet)); 
            sample_vv->add(Form("%s/mva/%i/www_%ij.root", dataDir, int(analysis), njet)); 
        }

        sample_vv->addShapeVariation2D(LEPEFFVAR, "histo_VV_CMS_hww_MVALepEffBounding", false);
        sample_vv->addShapeVariation2D(LEPRESVAR, "histo_VV_CMS_hww_MVALepResBounding", true);
        sample_vv->addShapeVariation2D(METVAR, "histo_VV_CMS_hww_MVAMETResBounding", true);
        sample_vv->addShapeVariation2D(JETRESVAR, "histo_VV_CMS_hww_MVAJESBounding", false);


        // Wgamma : l + gamma sample 
        for (int njet=0; njet < 2; njet++) {
            sample_wgamma->add(Form("%s/mva/%i/wgammafo_%ij.root", dataDir, int(analysis), njet));
            sample_wgamma->add(Form("%s/mva/%i/zgammafo_%ij.root", dataDir, int(analysis), njet));
        }

        // Wgamma Normalization
        for (int njet=0; njet < 2; njet++) {
            sample_wgammanorm->add(Form("%s/mva/%i/wgamma_%ij.root", dataDir, int(analysis), njet));
            sample_wgammanorm->add(Form("%s/mva/%i/zgamma_%ij.root", dataDir, int(analysis), njet));
        }

        // Wg3l ( Wgamma* )
        for (int njet=0; njet < 2; njet++) {
            sample_wg3l->add(Form("%s/mva/%i/wglll_%ij.root", dataDir, int(analysis), njet));
        } 

        // Ztt
        for (int njet=0; njet < 2; njet++) {
            sample_ztt->add(Form("%s/mva/%i/data_ztt_%ij.root", dataDir, int(analysis), njet));
        }

        // Wjets 
        for (int njet=0; njet < 2; njet++) {
            sample_wjetsEle->add(Form("%s/mva/%i/data_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/qqww_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/ggww_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/ttbar_powheg_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/tw_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/wz_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/zz_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/wgamma_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/zgamma_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/wglll_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsEle->add(Form("%s/mva/%i/dyll_PassFail_%ij.root", dataDir, int(analysis), njet));

            sample_wjetsMu->add(Form("%s/mva/%i/data_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/qqww_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/ggww_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/ttbar_powheg_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/tw_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/wz_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/zz_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/wgamma_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/zgamma_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/wglll_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_wjetsMu->add(Form("%s/mva/%i/dyll_PassFail_%ij.root", dataDir, int(analysis), njet));
        }
        sample_wjetsEle->addShapeVariation2D(WJETSELESHAPEVAR, "histo_WjetsE_CMS_hww_MVAWEBounding", true);
        sample_wjetsMu->addShapeVariation2D(WJETSMUSHAPEVAR, "histo_WjetsM_CMS_hww_MVAWMBounding", true);


        // data
        if ( !blind) {
            for (int njet=0; njet < 2; njet++) 
                sample_data->add(Form("%s/mva/%i/data_%ij.root", dataDir, int(analysis), njet));
        }

        // for Shape variations
        // wjets
        for (int njet=0; njet < 2; njet++) {
            //sample_wjets_mc->add(Form("%s/mva/%i/wjets_%ij.root", dataDir, int(analysis), njet));
            //sample_wjets_mc_loose->add(Form("%s/mva/%i/wjets_PassFail_%ij.root", dataDir, int(analysis), njet));
            sample_top_var->add(Form("%s/mva/%i/ttbar_%ij.root", dataDir, int(analysis), njet));
            sample_top_var->add(Form("%s/mva/%i/tw_%ij.root", dataDir, int(analysis), njet));
            sample_wwmcnlo->add(Form("%s/mva/%i/wwmcnlo_%ij.root", dataDir, int(analysis), njet));
            sample_wwmcnlo_up->add(Form("%s/mva/%i/wwmcnloup_%ij.root", dataDir, int(analysis), njet));
            sample_wwmcnlo_down->add(Form("%s/mva/%i/wwmcnlodown_%ij.root", dataDir, int(analysis), njet));
            //sample_dyll_data->add(Form("%s/mva/%i/data_%ij.root", dataDir, int(analysis), njet));
            //sample_dyll_data->add(Form("%s/mva/%i/wz_%ij.root", dataDir, int(analysis), njet));
            //sample_dyll_data->add(Form("%s/mva/%i/zz_%ij.root", dataDir, int(analysis), njet));

            sample_gghww_ref->add(Form("%s/mva/%i/hww%i_%ij.root", dataDir, int(analysis), int(analysis), njet));
            sample_gghww_jhu->add(Form("%s/mva/%i/xww2p%i_%ij.root", dataDir, int(analysis), int(analysis), njet));
        }
    } 

    //
    // do the looping
    //

    looper->loop(sample_data);
    looper->loop(sample_gghww);
    looper->loop(sample_qqhww);
    looper->loop(sample_whww);
    looper->loop(sample_zhww);
    looper->loop(sample_qqww);
    looper->loop(sample_ggww);
    looper->loop(sample_vv);
    looper->loop(sample_top);
    looper->loop(sample_dyll);
    //looper->loop(sample_dyll_loosemet);
    //looper->loop(sample_zjets);
    looper->loop(sample_wjetsEle);
    looper->loop(sample_wjetsMu);
    looper->loop(sample_wgammanorm);
    looper->loop(sample_wgamma);
    looper->loop(sample_wg3l);
    looper->loop(sample_ztt);

    // for shape syst.
    //looper->loop(sample_wjets_mc_loose);
    //looper->loop(sample_wjets_mc);
    looper->loop(sample_top_var);
    looper->loop(sample_wwmcnlo);
    looper->loop(sample_wwmcnlo_up);
    looper->loop(sample_wwmcnlo_down);
    looper->loop(sample_dyll_data);
    looper->loop(sample_gghww_ref);
    looper->loop(sample_gghww_jhu);


    //
    // make tables
    //

    std::vector<SmurfSample*> samplesToTabulate;

    samplesToTabulate.push_back(sample_data);
    samplesToTabulate.push_back(sample_gghww);
    samplesToTabulate.push_back(sample_qqhww);
    samplesToTabulate.push_back(sample_whww);
    samplesToTabulate.push_back(sample_zhww);
    samplesToTabulate.push_back(sample_qqww);
    samplesToTabulate.push_back(sample_ggww);
    samplesToTabulate.push_back(sample_vv);
    samplesToTabulate.push_back(sample_top);
    samplesToTabulate.push_back(sample_dyll);
    samplesToTabulate.push_back(sample_zjets);
    samplesToTabulate.push_back(sample_wjetsEle);
    samplesToTabulate.push_back(sample_wjetsMu);
    samplesToTabulate.push_back(sample_wgammanorm);
    samplesToTabulate.push_back(sample_wgamma);
    samplesToTabulate.push_back(sample_wg3l);
    samplesToTabulate.push_back(sample_ztt);
    printResultsTable(samplesToTabulate, option, true);

    //
    // for shape variations
    // 
    //samplesToTabulate.push_back(sample_dyll_loosemet);
    //samplesToTabulate.push_back(sample_wjets_mc); 
    //samplesToTabulate.push_back(sample_wjets_mc_loose);
    samplesToTabulate.push_back(sample_top_var);
    samplesToTabulate.push_back(sample_wwmcnlo);
    samplesToTabulate.push_back(sample_wwmcnlo_up);
    samplesToTabulate.push_back(sample_wwmcnlo_down);
    samplesToTabulate.push_back(sample_dyll_data);
    samplesToTabulate.push_back(sample_gghww_ref); 
    samplesToTabulate.push_back(sample_gghww_jhu); 

    //  
    // make cards
    //
    printf("\n\n[doAllHWW::doMassPoint] Writing cards\n");

    const std::string cardDir = "../cards/hwwjcp_19p5fb/";

    ShapeVar_t mva_option = (1ll<<STATVAR) | (1ll<<TOPSHAPEVAR) | (1ll<<WWSHAPEVAR) | (1ll<<DYSHAPEVAR)
        | (1ll<<LEPEFFVAR) | (1ll<<METVAR) | (1ll<<LEPRESVAR) | (1ll<<JETRESVAR) | (1ll<<WJETSELESHAPEVAR) | (1ll<<WJETSMUSHAPEVAR);

    for (int jetbin = 0; jetbin < 2; ++jetbin) { 
        printCard(samplesToTabulate, option, jetbin, analysis, cardDir, ((1<<1)|(1<<2)), mva_option, runEra);
        print2DShapeHistograms(samplesToTabulate, option, jetbin, analysis, cardDir, ((1<<1)|(1<<2)), runEra);
    }


    //
    // save histograms  
    //

    const std::string outFile = Form("histos_hww_analysis%i_%i.root", option, int(analysis));
    saveHist(outFile.c_str());  
    deleteHistos();


    //
    // clean up
    //

    delete looper;
    delete sample_data;
    delete sample_gghww;
    delete sample_qqhww;
    delete sample_zhww;
    delete sample_whww;
    delete sample_qqww;
    delete sample_ggww;
    delete sample_vv;
    delete sample_top;
    delete sample_dyll;
    delete sample_ztt;
    //delete sample_zjets;
    delete sample_wjets;
    delete sample_wjetsEle;
    delete sample_wjetsMu;
    delete sample_wgamma;
    delete sample_wgammanorm;
    delete sample_wg3l;

    //delete sample_dyll_loosemet;
    delete sample_top_var;
    delete sample_wwmcnlo;
    delete sample_wwmcnlo_up;
    delete sample_wwmcnlo_down;
    //delete sample_wjets_mc;
    //delete sample_wjets_mc_loose;
    //delete sample_dyll_data;
    delete sample_gghww_ref;
    delete sample_gghww_jhu;


}
Exemple #23
0
int playGame() //simulates 1 game
{
	int table[7][20];
	int deck[52];
	int founds[4][13];
	int i,j,h;
	int wastePos;
	int win;
	
	//clear table
	for(i=0;i<7;i++){ 
		for(j=0;j<20;j++){
			table[i][j]=0;
		}
	}
	//clear foundations
	for(i=0;i<4;i++){ 
		for(j=0;j<13;j++){
			founds[i][j]=0;
		}
	}
	shuffleDeck(deck);
	layTable(table,deck);
	if(DEBUG >= 10) 
	{
		printf("Table at start of game:\n");
		printTable(table);
	}

	//solve
	for(i=0;i<20;i++){
		checkTable(table,founds);
		checkTable(table,founds);
		for(wastePos=0; wastePos<52; wastePos++) //check waste cards
		{
			if(deck[wastePos]!=99) checkWaste(table,deck, wastePos, founds);
		}
		
		//check for win
		win=1;
		for(j=0;j<4;j++){
			if(founds[j][12] == 0) win = 0;
		}
		if(win)
		{
			if(DEBUG >= 10) printf("Win after %d cycles", i);
			return 1;
		}
	}
	
	//print results
	if(DEBUG >= 10)
	{
		printf("\nFoundations at finish:\n");
		printFounds(founds);
		printf("\nTable at finish:\n");
		printTable(table);
	}

	if(DEBUG >= 10)
	{
		printf("\nRemaining cards in waste:\n");
		for(i=0;i<52;i++)
		{
			if(deck[i]!=99)
			{
				printCard(deck[i]);
				printf("\n");
			}
			//printf("%d\n",deck[i]%13);
		}
	}
	return 0;
}
Exemple #24
0
int main(int argc, char** argv)
{
  int testcounter = 0;
  int numTests = 20;
  //The random card values are between 0 and 26, so mod by 27, you should be
  //pretty jevo about it. As for initiating games, super easy to randomize
  //number of players playing, however, playing games is still intersting,
  //ask about in class on Tuesday (May 19th, 2015)
  struct gameState G;
  struct gameState *p = &G;
  while(testcounter != numTests){

    srand(time(NULL));
  
  int k[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  int r; //Store our random card values;
  int i, j;
  int numPlayers = rand() % 5; 
  int money = 0;

  //Make sure I have more than 2 players
  if (numPlayers < 2){
    while(1){
      numPlayers = rand() % 5;
      if (numPlayers < 2)
	continue;
      else
	break;
    }
  }
  int players[numPlayers];
  //intialize deck with cards ( have to be greater than or equal to 7)
  for (i = 0; i < 10; i++){
    r = rand() % 27;
    while (r < 7){
      r = rand() % 27;
    }
    k[i] = r;
  }
  
  //Make sure kingdom cards are random
  for (i = 0; i < 10; i++){
    r = rand() % 27;
    while (r < 7){
      r = rand() % 27;
    }
    if (k[i] == 0)
      k[i] = r;
    for (j = i+1; j < 10; j++){
      if (k[i] == k[j]){
	k[i] = r;
	i = -1;
	break;
      }     
    }
  }
  

 
  printf("***STARTING GAME***\n");
  initializeGame(numPlayers, k, atoi(argv[1])+ rand(), p);
  
  while (!isGameOver(p)){
    
    printf("\nCards in player %d's hand:  ", whoseTurn(p));
    for (i = 0; i < numHandCards(p); i++){
      if (i < 4){
	printCard(handCard(i, p));
	printf(", ");
      }
      else{
	printCard(handCard(i, p));
      }
    }
    printf("\n");

    //Not entirely sure what this phase does, 
    for (i = 0; i < numHandCards(p); i++){
      if (handCard(i, p) == copper)
	money++;
      else if (handCard(i, p) == silver)
	money += 2;
      else if (handCard(i, p) == gold)
	money += 3;
    }
    
    //How much money does the player have
    for (i = 0; i < numPlayers; i++){
      money = 0;
      j = 0;     
      while (j < numHandCards(p)){
        r = rand() % 2;

	if (handCard(j, p) == copper){
	  playCard(j, -1, -1, -1, p);
	  money++;
	}
	else if (handCard(j, p) == silver){
	  playCard(j, -1, -1, -1, p);
	  money += 2;
	}
	else if (handCard(j, p) == gold){
	  playCard(j, -1, -1, -1, p);
	  money += 3;
	}
	
	// 1/3 chance of being able to play another card besides money:

	if (r == 0){
	  if (handCard(j,p) == adventurer){
	    playCard(j, -1, -1, -1, p);
	    printf("Player %d: ***Played Adventurer***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == feast){
	    playCard(j, copper, -1, -1, p);
	    printf("Player %d: ***Played Feast***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == council_room){
	    playCard(j, -1, -1, -1, p);
	    printf("Player %d: ***Played Council Room***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == mine){
	    playCard(j, copper, gardens, -1, p);	    
	    printf("Player %d: ***Played Mine***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == smithy){
	    playCard(j, -1, -1, -1, p);
	    printf("Player %d: ***Played Smithy***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == remodel){
	    playCard(j, embargo, duchy, -1, p);	    
	    printf("Player %d: ***Played Remodel***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == village){
	    playCard(j, -1, -1, -1, p);
	    printf("Player %d: ***Played Village***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == baron){
	    playCard(j, -1, -1, -1, p);
	    printf("Player %d: ***Played Baron***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == great_hall){
	    playCard(j, -1, -1, -1, p);	    
	    printf("Player %d: ***Played Great Hall***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == minion){
	    playCard(j, adventurer, copper, -1, p);
	    printf("Player %d: ***Played Minion***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == steward){
	    playCard(j, 1, -1, -1, p);	    
	    printf("Player %d: ***Played Steward***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == tribute){
	    playCard(j, -1, -1, -1, p);
	    printf("Player %d: ***Played Tribute***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == ambassador){
	    playCard(j, 1, 1, -1, p);
	    printf("Player %d: ***Played Ambassador***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == cutpurse){
	    playCard(j, -1, -1, -1, p);
	    printf("Player %d: ***Played Cutpurse***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == embargo){
	    playCard(j, copper, -1, -1, p);
	    printf("Player %d: ***Played Embargo***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == outpost){
	    playCard(j, -1, -1, -1, p);	    
	    printf("Player %d: ***Played Outpost***\n", whoseTurn(p));
	  }	  
	  else if (handCard(j,p) == salvager){
	    playCard(j, copper, -1, -1, p);
	    printf("Player %d: ***Played Salvager***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == sea_hag){
	    playCard(j, -1, -1, -1, p);	    
	    printf("Player %d: ***Played Sea Hag***\n", whoseTurn(p));
	  }
	  else if (handCard(j,p) == treasure_map){
	    playCard(j, -1, -1, -1, p);	    
	    printf("Player %d: ***Played Treasure Map***\n", whoseTurn(p));
	  }
	}
	j++;
      }
      
      int check = 0, count = 0;
      //***Buying Phase***
      if (money >= 8){
	printf("Player %d: Bought Province\n\n", whoseTurn(p));
	buyCard(province, p);
	}
      else if (money >= 6){
	// adventurer
	for (count = 0; count < 10; count++){
	  if (k[count] == adventurer){
	    check = 1;
	  }
	}
	if (check == 1 && (rand() % 3 == 0)){ // 1/3 to buy adventurer
	  printf("Player %d: Bought Adventurer\n\n", whoseTurn(p));
	  buyCard(adventurer, p);
	}
	else {
	  printf("Player %d: Bought Gold\n\n", whoseTurn(p));
	  buyCard(gold, p);
	}
      }
      else if (money >= 5){
	//council_room, mine, minion, tribute, outpost
	for (count = 0; count < 10; count++){
	  if (k[count] == council_room || k[count] == mine ||
	      k[count] == minion || k[count] == tribute ||
	      k[count] == outpost){
	    
	    check += 1;
	  }
	}
	if (rand() % 5 == 0){
	  for (count = 0; count < 10; count++){
	    if(check > 0 && k[count] == council_room && rand()% 5 == 0){
	      printf("Player %d: Bought Council Room\n\n", whoseTurn(p));
	      buyCard(council_room, p);
	      break;
	    }
	    else if(check > 0 && k[count] == mine && rand()% 5 == 0){
	      printf("Player %d: Bought Mine\n\n", whoseTurn(p));
	      buyCard(mine, p);
	      break;
	    }
	    else if(check > 0 && k[count] == minion && rand()% 5 == 0){
	      printf("Player %d: Bought Minion\n\n", whoseTurn(p));
	      buyCard(minion, p);
	      break;
	    }
	    else if(check > 0 && k[count] == tribute && rand()% 5 == 0){
	      printf("Player %d: Bought Tribute\n\n", whoseTurn(p));
	      buyCard(tribute, p);
	      break;
	    }
	    else if(check > 0 && k[count] == outpost && rand()% 5 == 0){
	      printf("Player %d: Bought Outpost\n\n", whoseTurn(p));
	      buyCard(outpost, p);
	      break;
	    }
	  }
	}
	else {		      
	  printf("Player %d: Bought Duchy\n\n", whoseTurn(p));
	  buyCard(duchy, p);
	}
      }
      else if (money >= 4){
	//feast, gardens, remodel, smithy, baron, cutpurse, salvager, sea_hag
	// treasure_map
	for (count = 0; count < 10; count++){
	  if (k[count] == feast || k[count] == gardens || k[count] == remodel
	      || k[count] == smithy || k[count] == baron || 
	      k[count] == cutpurse || k[count] == salvager ||
	      k[count] == sea_hag || k[count] == treasure_map) {	   
	    
	      check += 1;
	  }
	}
	// 1/5 chance of buying a card in deck
	if (rand() % 5 == 0){
	  for (count = 0; count < 10; count++){
	    if(check > 0 && k[count] == feast && rand()% 5 == 0){
	      printf("Player %d: Bought Feast\n\n", whoseTurn(p));
	      buyCard(feast, p);
	      break;
	    }
	    else if(check > 0 && k[count] == gardens && rand()% 5 == 0){
	      printf("Player %d: Bought Gardens\n\n", whoseTurn(p));
	      buyCard(gardens, p);
	      break;
	    }
	    else if(check > 0 && k[count] == smithy && rand()% 5 == 0){
	      printf("Player %d: Bought Smithy\n\n", whoseTurn(p));
	      buyCard(smithy, p);
	      break;
	    }
	    else if(check > 0 && k[count] == baron && rand()% 5 == 0){
	      printf("Player %d: Bought Baron\n\n", whoseTurn(p));
	      buyCard(baron, p);
	      break;
	    }
	    else if(check > 0 && k[count] == cutpurse && rand()% 5 == 0){
	      printf("Player %d: Bought Cutpurse\n\n", whoseTurn(p));
	      buyCard(cutpurse, p);
	      break;
	    }
	    else if(check > 0 && k[count] == salvager && rand()% 5 == 0){
	      printf("Player %d: Bought Salvager\n\n", whoseTurn(p));
	      buyCard(salvager, p);
	      break;
	    }
	    else if(check > 0 && k[count] == sea_hag && rand()% 5 == 0){
	      printf("Player %d: Bought Sea Hag\n\n", whoseTurn(p));
	      buyCard(sea_hag, p);
	      break;
	    }
	    else if(check > 0 && k[count] == treasure_map && rand()% 5 == 0){
	      printf("Player %d: Bought Treasure Map\n\n", whoseTurn(p));
	      buyCard(treasure_map, p);
	      break;
	    }
	  }
	}
      }
      else if (money >= 3){
	//embargo, ambassador, steward, great_hall,village
	for (count = 0; count < 10; count++){
	  if (k[count] == embargo || k[count] == ambassador || 
	      k[count] == steward || k[count] == great_hall || 
	      k[count] == village){
	    
	    check += 1;
	  }	  
	}
	if (rand() % 5 == 0) {
	  for (count = 0; count < 10; count++){
	    if(check > 0 && k[count] == embargo && rand()% 5 == 0){
	      printf("Player %d: Bought Embargo\n\n", whoseTurn(p));
	      buyCard(embargo, p);
	      break;
	    }
	    else if(check > 0 && k[count] == ambassador && rand()% 5 == 0){
	      printf("Player %d: Bought Ambassador\n\n", whoseTurn(p));
	      buyCard(ambassador, p);
	      break;
	    }
	    else if(check > 0 && k[count] == steward && rand()% 5 == 0){
	      printf("Player %d: Bought Steward\n\n", whoseTurn(p));
	      buyCard(steward, p);
	      break;
	    }
	    else if(check > 0 && k[count] == great_hall && rand()% 5 == 0){
	      printf("Player %d: Bought Great Hall\n\n", whoseTurn(p));
	      buyCard(great_hall, p);
	      break;
	    }
	    else if(check > 0 && k[count] == village && rand()% 5 == 0){
	      printf("Player %d: Bought Village\n\n", whoseTurn(p));
	      buyCard(village, p);
	      break;
	    }
	  }
	}
	else {
	  printf("Player %d: Bought Silver\n\n", whoseTurn(p));
	  buyCard(silver, p);
	}
      }
      endTurn(p);
      
      for (i = 0; i < numPlayers; i++){
	printf("Player %d: %d\n", i, scoreFor(i, p));  
      }
    }
  }
    //***End of Game***
    printf("***GAME FINISHED***\n");
    
    for (i = 0; i < numPlayers; i++){
      printf("Player %d: %d\n", i, scoreFor(i, p));
    }
    getWinners(players, p);
    testcounter++;
  }    
    return 0;
}
Exemple #25
0
/* Decodes PER and BER encoded cards */
int main2()
{
    int code = 0;		/* return code */
    BBCard *cardPtr = NULL;	/* pointer to decoded data */

    /*
     * Handle ASN.1/C++ runtime errors with C++ exceptions.
     */
    asn1_set_error_handling(throw_error, TRUE);

    try {
	bcas_Control ctl;	/* ASN.1/C++ control object */

	try {
	    EncodedBuffer encodedData;	/* encoded data */
	    BBCard_PDU pdu;	/* coding container for a BBCard value */
	    int encRule;	/* default encoding rules */

#ifdef RELAXED_MODE
	    /*
	     * Set relaxed mode.
	     */
	    ctl.setEncodingFlags(NOCONSTRAIN | RELAXBER | RELAXPER);
	    ctl.setDecodingFlags(NOCONSTRAIN | RELAXBER | RELAXPER);
#endif

	    ctl.setEncodingFlags(ctl.getEncodingFlags() | DEBUGPDU);
	    ctl.setDecodingFlags(ctl.getDecodingFlags() | DEBUGPDU);

	    /*
	     * Do decoding. Note that API is the same for any encoding method.
	     * Get encoding rules which were specified on the ASN.1 compiler
	     * command line.
	     */
	    encRule = ctl.getEncodingRules();

	    /*
	     * Set the decoder's input.
	     */
	    if (encRule == OSS_BER) {
		encodedData.set_buffer(berDataLen, (char *)berEncodedData);
	    } else if (encRule == OSS_PER_ALIGNED) {
		encodedData.set_buffer(perDataLen, (char *)perEncodedData);
	    }

	    /*
	     * Print the encoded message.
	     */
	    printf("Printing the %s-encoded PDU...\n\n",
			encRule == OSS_BER ? "BER": "PER");
	    encodedData.print_hex(ctl);

	    /*
	     * Decode the encoded PDU whose encoding is in "encodedData".
	     * An exception will be thrown on any error.
	     */
	    printf("\nThe decoder's trace messages (only for SOED)...\n\n");
	    pdu.decode(ctl, encodedData);

	    /*
	     * Read and print the decoded data.
	     */
	    cardPtr = pdu.get_data();
	    printCard(cardPtr);
	} catch (ASN1DecodeException &exc) {
	    /*
	     * An error occurred during decoding.
	     */
	    code = report_error(&ctl, "decode", exc);
	}
    } catch (ASN1DecodeException &exc) {
	/*
	 * An error occurred during control object initialization.
	 */
	code = report_error(NULL, "initialization", exc);
    } catch (...) {
	/*
	 * An unexpected exception is caught.
	 */
	printf("Unexpected exception caught.\n");
	code = -1;
    }
    /*
     * Delete the decoded data (if there are any).
     */
    delete cardPtr;
    return code;
}
Exemple #26
0
void Game::printBoard()
{
	// Printing score first
	printRoundScore();
	
	// First line
	std::cout << "  ";
	int i = 0;
	int start = (NB_TURNS - hands[2].size()) / 2;
	for (auto b = hands[2].begin(); b != hands[2].end(); i++)
	{
		if (start - i < 1)
		{
			printCard(std::cout, *b);
			b++;
		}
		else
			std::cout << "  ";
	}
	std::cout << std::endl;
	
	// second to seventh lines
	auto b = hands[1].begin();
	auto c = hands[3].begin();
	int b_start = (NB_TURNS - hands[1].size() + 1) / 2;
	int c_start = (NB_TURNS - hands[3].size()) / 2;
	for (int i = 0; i < NB_TURNS; i++)
	{
		if (b_start < 1 && b != hands[1].end())
		{
			printCard(std::cout, *b);
			b++;
		}
		else
			std::cout << "  ";
		b_start--;
		
		if (i == 1 && state.turn[2].suit != INVALID_SUIT && state.first_to_play == 2) { // player 2 first to play
			std::cout << "|     "; printCard(std::cout, state.turn[2]); std::cout << "       |";
		}
		else if (i == 2 && state.turn[2].suit != INVALID_SUIT && state.first_to_play != 2) { // player 2 not first to play
			std::cout << "|     "; printCard(std::cout, state.turn[2]); std::cout << "       |";
		}
		else if (i == 3 && state.turn[3].suit != INVALID_SUIT) { // player 3 first/not first to play card
			std::cout << "|         " << (state.first_to_play == 3?"  ":""); printCard(std::cout, state.turn[3]); std::cout << (state.first_to_play != 3?"  ":"") << " |";
		}
		else if (i == 4 && state.turn[1].suit != INVALID_SUIT) { // player 1 first/not first to play card
			std::cout << "| " << (state.first_to_play != 1?"  ":""); printCard(std::cout, state.turn[1]); std::cout << (state.first_to_play == 1?"  ":"") << "         |";
		}
		else if (i == 5 && state.turn[0].suit != INVALID_SUIT && state.first_to_play != 0) { // player 0 not first to play
			std::cout << "|       "; printCard(std::cout, state.turn[0]); std::cout << "     |";
		}
		else if (i == 6 && state.turn[0].suit != INVALID_SUIT && state.first_to_play == 0) { // player 0 first to play
			std::cout << "|       "; printCard(std::cout, state.turn[0]); std::cout << "     |";
		}
		else if (i == 0 || i == 7) // first and end line
			std::cout << "----------------";
		else // blank lines
			std::cout << "|              |";
		
		if (c_start < 1 && c != hands[3].end())
		{
			printCard(std::cout, *c);
			c++;
		}
		c_start--;
		
		std::cout << std::endl;
	}
	
	// eighth line
	std::cout << "  ";
	i = 0;
	start = (NB_TURNS - hands[0].size() + 1) / 2;
	for (auto b = hands[0].begin(); b != hands[0].end(); i++)
	{
		if (start - i < 1)
		{
			printCard(std::cout, *b);
			b++;
		}
		else
			std::cout << "  ";
	}
	std::cout << std::endl << std::endl;
}
Exemple #27
0
bool Game::deal()
{
	int deck_top = NB_CARDS-1;
	std::cout << "New deal." << std::endl;
	
	// First 3 cards
	for (int i = 0; i < NB_PLAYERS; i++) {
		for (int j = 0; j < DEAL_FIRST_TURN; j++) {
			hands[(dealer+i)%NB_PLAYERS].push_back(deck[deck_top--]);
		}
	}
	
	// Next 2 cards
	for (int i = 0; i < NB_PLAYERS; i++) {
		for (int j = 0; j < DEAL_SECOND_TURN; j++)
			hands[(dealer+i)%NB_PLAYERS].push_back(deck[deck_top--]);
	}
	
	// Bids
	Card extra = deck[deck_top--];
	state.leader = NOBODY;
	createNewRoundStates();
	for (int i = 0; i < NB_PLAYERS; i++)
	{
		if (players[i]->firstBid(extra)) {
			state.trump_suit = extra.suit;
			state.leader = i;
			break;
		}
	}
	
	if (state.leader == NOBODY)
		std::cout << "Nobody took the card during the first round." << std::endl;
	for (int i = 0; i < NB_PLAYERS && state.leader == NOBODY; i++)
	{
		if ((state.trump_suit = players[i]->secondBid(extra)) != INVALID_SUIT) {
			state.leader = i;
			break;
		}
	}
	
	if (state.leader == NOBODY)
	{
		std::cout << "Nobody took the card during the second round." << std::endl;
		return false;
	}
	std::cout << "Player " << state.leader << " takes the card: ";
	printCard(std::cout, extra);
	std::cout << " with " << suitToString(state.trump_suit) << "." << std::endl;
	
	hands[state.leader].push_back(extra);
	
	// Deals the remaining cards
	for (int i = 0; i < NB_PLAYERS; i++) {
		int player = (dealer+i)%NB_PLAYERS;
		for (int j = (player==state.leader?1:0); j < DEAL_THIRD_TURN; j++)
			hands[player].push_back(deck[deck_top--]);
	}
	
	return true;
}
Exemple #28
0
void *connection_handler(void *socket_desc)
{
	//Get the socket descriptor
	int sock = *(int*)socket_desc;
	int read_size;
	char *message , client_message[2000];

	/*close(0); 
	close(1); 
	close(2); */
	dup2( sock, STDOUT_FILENO );  /* duplicate socket on stdout */
	dup2( sock, STDERR_FILENO );  /* duplicate socket on stderr too */
	dup2( sock, STDIN_FILENO );

	int** newCard;
	int index;
	int numbCalledArray[1000] = {0};
	int *ptrCalledArrayTail;
	ptrCalledArrayTail = numbCalledArray;

	Player Harry; //This is how you make a player.

	newCard = createCard();
	initCard(newCard);
 

	/*Heres a little demo on how you would access elements inside the struct*/
	strncpy(Harry.playerName,"Harrison",20); //copy Name into the structs playerName field.
	Harry.playerBingoCard = newCard; //give Harry his bingo card so he can beat old women at bingo
	printf("Player Name: %s\n", Harry.playerName); //access Player's name
	printCard(Harry.playerBingoCard); //access Player's bingo card


	/*Heres a demo on how you would draw a number
	ptrCalledArrayTail = drawNumber(ptrCalledArrayTail, numCalledArray);
	printf("The final number drawn is %d", *ptrCalledArrayTail--);
	*/
     
    //Send some messages to the client
    //message = "Greetings! I am your connection handler\n";
    //write(sock , message , strlen(message));

    

    drawStuff(Harry.playerBingoCard);  
    //write(sock , drawStuff(Harry.playerBingoCard) , strlen(message));
     
    //Receive a message from client
    /*while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //Send the message back to client
        write(sock , client_message , strlen(client_message));
    
	bzero(client_message, 2000);
    }
     
    if(read_size == 0)
    {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }
     */
         
    //Free the socket pointer
    free(socket_desc);
     
    return 0;
}

void printhand(struct gameState *G){
      int i;
      for(i=0; i<numHandCards(G); i++){
        printCard(handCard(i,G),0);
int main (int argc, char** argv) {
	int finalKingdomCards[10][2];
	int kingdomCards[10][2];
  struct gameState G;
  struct gameState *p = &G;
  int money;
  int i, j, h, randomIndex, randomCategory, randomNumberSeed, curCard;
  int player;
  int numPlayers;
  int k[10];
  int kingdomCard;
  int cardFound;
	
	FILE *fp;
	fp = fopen("testCase.c", "w");
	randomNumberSeed = 16;
	
fprintf(fp, 	"#include \"testFunctions.h\" \n\
int main (int argc, char** argv) { \n\
	struct gameState G; \n\
	struct gameState *p = &G; \n\
	int money; \n\
	int player; \n\
	int numPlayers;\n" );

  srand(randomNumberSeed);
  
  
  /* Play NUM_GAMES games of dominion. */
  for (h = 0; h < NUM_GAMES; h++) {
	  
	  

  
	  /* Make an array of the 10 kingdom cards (#7-26) that will be used in this game */
	  printf("Kingdom Cards:\n");
	  i = 0;
	  while (i < 10) {
			kingdomCard = (rand() % 20) + 7;
			cardFound = 0;
			
			for (j = 0; j < i; j++) {
				if (kingdomCard == k[j]) {
					cardFound = 1;
					break;
				}
			}
				
			if (!cardFound && (kingdomCard != salvager) && (kingdomCard != tribute)) {
				finalKingdomCards[i][0] = kingdomCard;
				finalKingdomCards[i][1] = 0;
				kingdomCards[i][0] = kingdomCard;
				kingdomCards[i][1] = 0;
				k[i] = kingdomCard;
				printCard(k[i]);
				i++;
			}
	  }
	
	 fprintf(fp, "\n\tint k[10] = {");
	 for (i = 0; i < 9; i++)
		 fprintf(fp, "%d, ", k[i]);
	 fprintf(fp, "%d};", k[9]);
	 
	 /* random number of players (from 2-4) */
		numPlayers = (rand() % 3) + 2;
		fprintf(fp, "\n\tnumPlayers = %d;",numPlayers);
	  
	  
	  /* Allocate memory for game. */   
		initializeGame(numPlayers, k, randomNumberSeed, p);
		
		fprintf(fp, "\n\tinitializeGame(numPlayers, k, 16, p);");
	 
	  while (!isGameOver(p)) {
			money = countMoney(p);
			player = whoseTurn(p);
			
			fprintf(fp, "\n\tmoney = countMoney(p);");
			fprintf(fp, "\n\tplayer = whoseTurn(p);");
			
			
			
			/* Loop through current player's hand and play the first kingdom card
			encountered. */
			for (i = 0; i < numHandCards(p); i++) {
				
				curCard = handCard(i, p);
				
				if (!p->numActions)
					break;
			
				if ((curCard <= 26) && (curCard >= 7) && (curCard != gardens)) {
					
					
					/* This part pushes something onto the stack which corrupts some
						data and causes invalid cards to enter the game */
					// printf("%d: About to play ", player);
					// printCard(curCard);
					// printf("...\n");
					
					switch(curCard) {
						case ambassador:
							for (j = 0; j < numHandCards(p); j++) {
								if (handCard(j, p) == curse) {
									if (playCard(i, j, -1, -1, p) != -1) {
										fprintf(fp, "\n\tplayCard(%d, %d, -1, -1, p);", i, j);
									}
									else
										printf("%d: There was a problem with playing ambassador\n\n\n", player);
									money = countMoney(p);
									break;
								}
							}	
							break;
					
						case baron:
							if (playCard(i, 0, 1, 1, p) != -1) {
								fprintf(fp, "\n\tplayCard(%d, 0, 1, 1, p);", i);
							}
							else {
								printf("%d: ", player);
								printf("There was a problem with playing ");
								printCard(curCard);
								printf("\n\n\n");
							}			
							money = countMoney(p);
							break;
							
						case feast:
							for (j = 0; j < numHandCards(p); j++) {
								if (supplyCount(handCard(j, p), p) > 1
								&& getCardCost(handCard(j, p)) <= 5) {
									if (playCard(i, handCard(j, p), 1, 1, p) == 0) {
										fprintf(fp, "\n\tplayCard(%d, %d, 1, 1, p);", i, handCard(j, p));
									}
									else
										printf("%d: There was a problem with playing feast\n\n\n", player);
									money = countMoney(p);
									break;
								}
							}
							break;
						
						/* Find treasure card to trash (pass as choice1 as position)
						treasure card to gain: pass as choice2 by name. */
						case mine:
							for (j = 0; j < numHandCards(p); j++) {
								if (handCard(j, p) == copper) {
									if (playCard(i, j, silver, -1, p) == 0) {
										fprintf(fp, "\n\tplayCard(%d, %d, silver, -1, p);", i, j);
									}
									else
										printf("%d: There was a problem with playing mine\n\n\n", player);
									money = countMoney(p);
									break;
								}
								
								else if (handCard(j, p) == silver) {
									if (playCard(i, j, gold, -1, p) == 0) {
										fprintf(fp, "\n\tplayCard(%d, %d, gold, -1, p);", i, j);
									}
									else
										printf("%d: There was a problem with playing mine\n\n\n", player);
									money = countMoney(p);
									break;
								}
							}					
							break;
						
						case remodel:
							for (j = 0; j < numHandCards(p); j++) {
								if (getCardCost(handCard(j, p)) >= 3) {
									if (playCard(i, j, duchy, -1, p) == 0) {
										fprintf(fp, "\n\tplayCard(%d, %d, duchy, -1, p);", i, j);
									}
									else 
										printf("%d: There was a problem with playing remodel!\n\n\n", player);
									money = countMoney(p);
									break;
								}
							}					
							break;
						
						
						default:
							if (playCard(i, 1, 1, 1, p) != -1) {
								fprintf(fp, "\n\tplayCard(%d, 1, 1, 1, p);", i);
							}
							else {
								printf("%d: ", player);
								printf("Failed to play ");
								printCard(curCard);
								printf("\n\n");
							}			
							money = countMoney(p);
							break;
					}
				}
			}
			
			
			randomCategory = (rand() % 100) + 1;	
			
			/* Always buy a province if you can afford it */
			if (money >= 8) {
				if (buyCard(province, p) == 0) {
					fprintf(fp, "\n\tbuyCard(province, p);");
				}
				else
					printf("%d: failed to buy province\n", player);
			}
			
			
			/* Buy money 55% of the time */
			else if (randomCategory > 45) {
				if (money >= 6) {
					if (buyCard(gold, p) == 0)
						fprintf(fp, "\n\tbuyCard(gold, p);");
					else
						printf("%d: failed to buy gold\n", player); 
				}
				
				else if (money >= 3) {
					if (buyCard(silver, p) == 0)
						fprintf(fp, "\n\tbuyCard(silver, p);");
					else
						printf("%d: failed to buy silver\n", player); 
				}
			}
			
			/* Buy a Kingdom card 40% of the time */
			else if (randomCategory > 5) {
				for (i = 0; i < 20; i++) {
					randomIndex = rand() % 10;
					
					if (getCardCost(k[randomIndex]) <= money) {
						if (buyCard(k[randomIndex], p) == 0) {
							fprintf(fp, "\n\tbuyCard(%d, p);", k[randomIndex]);
							incrementCard(k[randomIndex], finalKingdomCards);
							break;
						}
						
						else {
							printf("%d: failed to buy ", player);
							printCard(k[randomIndex]);
							printf("\n");
							break;
						}
					}		
				}
			}
			
			/* Buy a duchy 5% of the time */
			else {
				if (money >= 5) {
					if (buyCard(duchy, p) == 0)
						fprintf(fp, "\n\tbuyCard(duchy, p);");
					else
						printf("%d: failed to buy duchy\n", player);
				}
			}
				
			endTurn(p);
			fprintf(fp, "\n\tendTurn(p);\n");
			
			for (i = 0; i < numPlayers; i++) {
				printf ("Player %d Score: %d\n", i, scoreFor(i, p));
			}
			printf("\n");


			




			
			/* Look through every card in play */
			for (j = 0; j < numPlayers; j++) {
				
				/* Check hand */
				for (i = 0; i < p->handCount[j]; i++) {
					
					curCard = p->hand[j][i];
					
					if (contains(k, curCard))
						incrementCard(curCard, kingdomCards);
					
					if (!(curCard <= treasure_map && curCard >= curse)) {
						printf("\n\n");
						printCard(curCard);
						printf("\n\n");
					}
					assert(curCard <= treasure_map && curCard >= curse);
				}
				
				/* Check discard pile */
				for (i = 0; i < p->discardCount[j]; i++) {
					
					curCard = p->discard[j][i];
					
					if (contains(k, curCard))
						incrementCard(curCard, kingdomCards);
					
					if (!(curCard <= treasure_map && curCard >= curse)) {
						printf("\n\n");
						printCard(curCard);
						printf("\n\n");
					}
					assert(curCard <= treasure_map && curCard >= curse);
				}

				/* Check deck */
				for (i = 0; i < p->deckCount[j]; i++) {
					
					curCard = p->deck[j][i];
					
					if (contains(k, curCard))
						incrementCard(curCard, kingdomCards);
					
					if (!(curCard <= treasure_map && curCard >= curse)) {
						printf("\n\n");
						printCard(curCard);
						printf("\n\n");
					}
					assert(curCard <= treasure_map && curCard >= curse);
				}
			}








		
			/* Now it's the other player's turn */
	  }

		

		printf("All tests passed!\n\n\n\n");
  }
	
	
	fprintf(fp, "\n\treturn 0;\n}");
	fclose(fp);
		
  return 0;
}