예제 #1
0
int cardEffect(int card, int choice1, int choice2, int choice3, struct gameState *state, int handPos, int *bonus)
{
  int i;
  int j;
  int k;
  int x;
  int index;
  int currentPlayer = whoseTurn(state);
  int nextPlayer = currentPlayer + 1;

  int tributeRevealedCards[2] = {-1, -1};
  int temphand[MAX_HAND];// moved above the if statement
  int drawntreasure=0;
  int cardDrawn;
  int z = 0;// this is the counter for the temp hand
  if (nextPlayer > (state->numPlayers - 1)){
    nextPlayer = 0;
  }
  
	
  //uses switch to select card and perform actions
  switch( card ) 
    {
            
    case adventurer:
        playAdventurer(drawntreasure,currentPlayer, state, handPos, cardDrawn, temphand, z);
            return 0;
			
    case council_room:
        playCouncilRoom(currentPlayer, i, state, handPos);
            return 0;
            
    case feast:
      //gain card with cost up to 5
      //Backup hand
      for (i = 0; i <= state->handCount[currentPlayer]; i++){
	temphand[i] = state->hand[currentPlayer][i];//Backup card
	state->hand[currentPlayer][i] = -1;//Set to nothing
      }
      //Backup hand

      //Update Coins for Buy
      updateCoins(currentPlayer, state, 5);
      x = 1;//Condition to loop on
      while( x == 1) {//Buy one card
	if (supplyCount(choice1, state) <= 0){
	  if (DEBUG)
	    printf("None of that card left, sorry!\n");

	  if (DEBUG){
	    printf("Cards Left: %d\n", supplyCount(choice1, state));
	  }
	}
	else if (state->coins < getCost(choice1)){
	  printf("That card is too expensive!\n");

	  if (DEBUG){
	    printf("Coins: %d < %d\n", state->coins, getCost(choice1));
	  }
	}
	else{

	  if (DEBUG){
	    printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]);
	  }

	  gainCard(choice1, state, 0, currentPlayer);//Gain the card
	  x = 0;//No more buying cards

	  if (DEBUG){
	    printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]);
	  }

	}
      }     

      //Reset Hand
      for (i = 0; i <= state->handCount[currentPlayer]; i++){
	state->hand[currentPlayer][i] = temphand[i];
	temphand[i] = -1;
      }
      //Reset Hand
      			
      return 0;
			
    case gardens:
      return -1;
			
    case mine:
      j = state->hand[currentPlayer][choice1];  //store card we will trash

      if (state->hand[currentPlayer][choice1] < copper || state->hand[currentPlayer][choice1] > gold)
	{
	  return -1;
	}
		
      if (choice2 > treasure_map || choice2 < curse)
	{
	  return -1;
	}

      if ( (getCost(state->hand[currentPlayer][choice1]) + 3) > getCost(choice2) )
	{
	  return -1;
	}

      gainCard(choice2, state, 2, currentPlayer);

      //discard card from hand
      discardCard(handPos, currentPlayer, state, 0);

      //discard trashed card
      for (i = 0; i < state->handCount[currentPlayer]; i++)
	{
	  if (state->hand[currentPlayer][i] == j)
	    {
	      discardCard(i, currentPlayer, state, 0);			
	      break;
	    }
	}
			
      return 0;
			
    case remodel:
      j = state->hand[currentPlayer][choice1];  //store card we will trash

      if ( (getCost(state->hand[currentPlayer][choice1]) + 2) > getCost(choice2) )
	{
	  return -1;
	}

      gainCard(choice2, state, 0, currentPlayer);

      //discard card from hand
      discardCard(handPos, currentPlayer, state, 0);

      //discard trashed card
      for (i = 0; i < state->handCount[currentPlayer]; i++)
	{
	  if (state->hand[currentPlayer][i] == j)
	    {
	      discardCard(i, currentPlayer, state, 0);			
	      break;
	    }
	}


      return 0;
		
    case smithy:
        playSmithy(handPos, currentPlayer, state);
            return 0;
		
    case village:
        playVillage(currentPlayer, state, handPos);
            return 0;
		
    case baron:
      state->numBuys++;//Increase buys by 1!
      if (choice1 > 0){//Boolean true or going to discard an estate
	int p = 0;//Iterator for hand!
	int card_not_discarded = 1;//Flag for discard set!
	while(card_not_discarded){
	  if (state->hand[currentPlayer][p] == estate){//Found an estate card!
	    state->coins += 4;//Add 4 coins to the amount of coins
	    state->discard[currentPlayer][state->discardCount[currentPlayer]] = state->hand[currentPlayer][p];
	    state->discardCount[currentPlayer]++;
	    for (;p < state->handCount[currentPlayer]; p++){
	      state->hand[currentPlayer][p] = state->hand[currentPlayer][p+1];
	    }
	    state->hand[currentPlayer][state->handCount[currentPlayer]] = -1;
	    state->handCount[currentPlayer]--;
	    card_not_discarded = 0;//Exit the loop
	  }
	  else if (p > state->handCount[currentPlayer]){
	    if(DEBUG) {
	      printf("No estate cards in your hand, invalid choice\n");
	      printf("Must gain an estate if there are any\n");
	    }
	    if (supplyCount(estate, state) > 0){
	      gainCard(estate, state, 0, currentPlayer);
	      state->supplyCount[estate]--;//Decrement estates
	      if (supplyCount(estate, state) == 0){
		isGameOver(state);
	      }
	    }
	    card_not_discarded = 0;//Exit the loop
	  }
			    
	  else{
	    p++;//Next card
	  }
	}
      }
			    
      else{
	if (supplyCount(estate, state) > 0){
	  gainCard(estate, state, 0, currentPlayer);//Gain an estate
	  state->supplyCount[estate]--;//Decrement Estates
	  if (supplyCount(estate, state) == 0){
	    isGameOver(state);
	  }
	}
      }
	    
      
      return 0;
		
    case great_hall:
      //+1 Card
      drawCard(currentPlayer, state);
			
      //+1 Actions
      state->numActions++;
			
      //discard card from hand
      discardCard(handPos, currentPlayer, state, 0);
      return 0;
		
    case minion:
      //+1 action
      state->numActions++;
			
      //discard card from hand
      discardCard(handPos, currentPlayer, state, 0);
			
      if (choice1)		//+2 coins
	{
	  state->coins = state->coins + 2;
	}
			
      else if (choice2)		//discard hand, redraw 4, other players with 5+ cards discard hand and draw 4
	{
	  //discard hand
	  while(numHandCards(state) > 0)
	    {
	      discardCard(handPos, currentPlayer, state, 0);
	    }
				
	  //draw 4
	  for (i = 0; i < 4; i++)
	    {
	      drawCard(currentPlayer, state);
	    }
				
	  //other players discard hand and redraw if hand size > 4
	  for (i = 0; i < state->numPlayers; i++)
	    {
	      if (i != currentPlayer)
		{
		  if ( state->handCount[i] > 4 )
		    {
		      //discard hand
		      while( state->handCount[i] > 0 )
			{
			  discardCard(handPos, i, state, 0);
			}
							
		      //draw 4
		      for (j = 0; j < 4; j++)
			{
			  drawCard(i, state);
			}
		    }
		}
	    }
				
	}
      return 0;
		
    case steward:
      if (choice1 == 1)
	{
	  //+2 cards
	  drawCard(currentPlayer, state);
	  drawCard(currentPlayer, state);
	}
      else if (choice1 == 2)
	{
	  //+2 coins
	  state->coins = state->coins + 2;
	}
      else
	{
	  //trash 2 cards in hand
	  discardCard(choice2, currentPlayer, state, 1);
	  discardCard(choice3, currentPlayer, state, 1);
	}
			
      //discard card from hand
      discardCard(handPos, currentPlayer, state, 0);
      return 0;
		
    case tribute:
      if ((state->discardCount[nextPlayer] + state->deckCount[nextPlayer]) <= 1){
	if (state->deckCount[nextPlayer] > 0){
	  tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
	  state->deckCount[nextPlayer]--;
	}
	else if (state->discardCount[nextPlayer] > 0){
	  tributeRevealedCards[0] = state->discard[nextPlayer][state->discardCount[nextPlayer]-1];
	  state->discardCount[nextPlayer]--;
	}
	else{
	  //No Card to Reveal
	  if (DEBUG){
	    printf("No cards to reveal\n");
	  }
	}
      }
	    
      else{
	if (state->deckCount[nextPlayer] == 0){
	  for (i = 0; i < state->discardCount[nextPlayer]; i++){
	    state->deck[nextPlayer][i] = state->discard[nextPlayer][i];//Move to deck
	    state->deckCount[nextPlayer]++;
	    state->discard[nextPlayer][i] = -1;
	    state->discardCount[nextPlayer]--;
	  }
			    
	  shuffle(nextPlayer,state);//Shuffle the deck
	} 
	tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
	state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1;
	state->deckCount[nextPlayer]--;
	tributeRevealedCards[1] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
	state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1;
	state->deckCount[nextPlayer]--;
      }    
		       
      if (tributeRevealedCards[0] == tributeRevealedCards[1]){//If we have a duplicate card, just drop one 
	state->playedCards[state->playedCardCount] = tributeRevealedCards[1];
	state->playedCardCount++;
	tributeRevealedCards[1] = -1;
      }

      for (i = 0; i <= 2; i ++){
	if (tributeRevealedCards[i] == copper || tributeRevealedCards[i] == silver || tributeRevealedCards[i] == gold){//Treasure cards
	  state->coins += 2;
	}
		    
	else if (tributeRevealedCards[i] == estate || tributeRevealedCards[i] == duchy || tributeRevealedCards[i] == province || tributeRevealedCards[i] == gardens || tributeRevealedCards[i] == great_hall){//Victory Card Found
	  drawCard(currentPlayer, state);
	  drawCard(currentPlayer, state);
	}
	else{//Action Card
	  state->numActions = state->numActions + 2;
	}
      }
	    
      return 0;
		
    case ambassador:
      j = 0;		//used to check if player has enough cards to discard

      if (choice2 > 2 || choice2 < 0)
	{
	  return -1;				
	}

      if (choice1 == handPos)
	{
	  return -1;
	}

      for (i = 0; i < state->handCount[currentPlayer]; i++)
	{
	  if (i != handPos && i == state->hand[currentPlayer][choice1] && i != choice1)
	    {
	      j++;
	    }
	}
      if (j < choice2)
	{
	  return -1;				
	}

      if (DEBUG) 
	printf("Player %d reveals card number: %d\n", currentPlayer, state->hand[currentPlayer][choice1]);

      //increase supply count for choosen card by amount being discarded
      state->supplyCount[state->hand[currentPlayer][choice1]] += choice2;
			
      //each other player gains a copy of revealed card
      for (i = 0; i < state->numPlayers; i++)
	{
	  if (i != currentPlayer)
	    {
	      gainCard(state->hand[currentPlayer][choice1], state, 0, i);
	    }
	}

      //discard played card from hand
      discardCard(handPos, currentPlayer, state, 0);			

      //trash copies of cards returned to supply
      for (j = 0; j < choice2; j++)
	{
	  for (i = 0; i < state->handCount[currentPlayer]; i++)
	    {
	      if (state->hand[currentPlayer][i] == state->hand[currentPlayer][choice1])
		{
		  discardCard(i, currentPlayer, state, 1);
		  break;
		}
	    }
	}			

      return 0;
		
    case cutpurse:

      updateCoins(currentPlayer, state, 2);
      for (i = 0; i < state->numPlayers; i++)
	{
	  if (i != currentPlayer)
	    {
	      for (j = 0; j < state->handCount[i]; j++)
		{
		  if (state->hand[i][j] == copper)
		    {
		      discardCard(j, i, state, 0);
		      break;
		    }
		  if (j == state->handCount[i])
		    {
		      for (k = 0; k < state->handCount[i]; k++)
			{
			  if (DEBUG)
			    printf("Player %d reveals card number %d\n", i, state->hand[i][k]);
			}	
		      break;
		    }		
		}
					
	    }
				
	}				

      //discard played card from hand
      discardCard(handPos, currentPlayer, state, 0);			

      return 0;

		
    case embargo:
            
            if (playEmbargo(state, choice1, handPos, currentPlayer) == -1){
                return -1;
            }
            else{
                return 0;
            }
      
    case outpost:
      //set outpost flag
      state->outpostPlayed++;
			
      //discard card
      discardCard(handPos, currentPlayer, state, 0);
      return 0;
		
    case salvager:
      //+1 buy
      state->numBuys++;
			
      if (choice1)
	{
	  //gain coins equal to trashed card
	  state->coins = state->coins + getCost( handCard(choice1, state) );
	  //trash card
	  discardCard(choice1, currentPlayer, state, 1);	
	}
			
      //discard card
      discardCard(handPos, currentPlayer, state, 0);
      return 0;
		
    case sea_hag:
        playSeaHag(state, i, currentPlayer);
		
    case treasure_map:
      //search hand for another treasure_map
      index = -1;
      for (i = 0; i < state->handCount[currentPlayer]; i++)
	{
	  if (state->hand[currentPlayer][i] == treasure_map && i != handPos)
	    {
	      index = i;
	      break;
	    }
	}
      if (index > -1)
	{
	  //trash both treasure cards
	  discardCard(handPos, currentPlayer, state, 1);
	  discardCard(index, currentPlayer, state, 1);

	  //gain 4 Gold cards
	  for (i = 0; i < 4; i++)
	    {
	      gainCard(gold, state, 1, currentPlayer);
	    }
				
	  //return success
	  return 1;
	}
			
      //no second treasure_map found in hand
      return -1;
    }
	
  return -1;
}
void CvMapGenerator::addUniqueBonusType(BonusTypes eBonusType)
{
	int* piAreaTried = new int[GC.getMapINLINE().getNumAreas()];

	for (int iI = 0; iI < GC.getMapINLINE().getNumAreas(); iI++)
	{
		piAreaTried[iI] = FFreeList::INVALID_INDEX;
	}

	CvBonusInfo& pBonusInfo = GC.getBonusInfo(eBonusType);

	int iBonusCount = calculateNumBonusesToAdd(eBonusType);

	bool bIgnoreLatitude = GC.getGameINLINE().pythonIsBonusIgnoreLatitudes();

	FAssertMsg(pBonusInfo.isOneArea(), "addUniqueBonusType called with non-unique bonus type");

	while (true)
	{
		int iBestValue = 0;
		int iLoop = 0;
		CvArea *pBestArea = NULL;
		CvArea *pLoopArea = NULL;

		for(pLoopArea = GC.getMapINLINE().firstArea(&iLoop); pLoopArea != NULL; pLoopArea = GC.getMapINLINE().nextArea(&iLoop))
		{
			bool bTried = false;

			for (int iI = 0; iI < GC.getMapINLINE().getNumAreas(); iI++)
			{
				if (pLoopArea->getID() == piAreaTried[iI])
				{
					bTried = true;
					break;
				}
			}

			if (!bTried)
			{
				int iNumUniqueBonusesOnArea = pLoopArea->countNumUniqueBonusTypes() + 1; // number of unique bonuses starting on the area, plus this one
				int iNumTiles = pLoopArea->getNumTiles();
				int iValue = iNumTiles / iNumUniqueBonusesOnArea;

				if (iValue > iBestValue)
				{
					iBestValue = iValue;
					pBestArea = pLoopArea;
				}
			}
		}

		if (pBestArea == NULL)
		{
			break; // can't place bonus on any area
		}

		for (int iI = 0; iI < GC.getMapINLINE().getNumAreas(); iI++)
		{
			if (piAreaTried[iI] == FFreeList::INVALID_INDEX)
			{
				piAreaTried[iI] = pBestArea->getID();
				break;
			}
		}

		// Place the bonuses:

		int* piShuffle = shuffle(GC.getMapINLINE().numPlotsINLINE(), GC.getGameINLINE().getMapRand());

		for (int iI = 0; iI < GC.getMapINLINE().numPlotsINLINE(); iI++)
		{
			CvPlot* pPlot = GC.getMapINLINE().plotByIndexINLINE(piShuffle[iI]);
			FAssertMsg(pPlot != NULL, "addUniqueBonusType(): pPlot is null");

			if (GC.getMapINLINE().getNumBonuses(eBonusType) >= iBonusCount)
			{
				break; // We already have enough
			}

			if (pBestArea == pPlot->area())
			{
				if (canPlaceBonusAt(eBonusType, pPlot->getX_INLINE(), pPlot->getY_INLINE(), bIgnoreLatitude))
				{
					pPlot->setBonusType(eBonusType);

					for (int iDX = -(pBonusInfo.getGroupRange()); iDX <= pBonusInfo.getGroupRange(); iDX++)
					{
						for (int iDY = -(pBonusInfo.getGroupRange()); iDY <= pBonusInfo.getGroupRange(); iDY++)
						{
							if (GC.getMapINLINE().getNumBonuses(eBonusType) < iBonusCount)
							{
								CvPlot* pLoopPlot	= plotXY(pPlot->getX_INLINE(), pPlot->getY_INLINE(), iDX, iDY);

								if (pLoopPlot != NULL && (pLoopPlot->area() == pBestArea))
								{
									if (canPlaceBonusAt(eBonusType, pLoopPlot->getX_INLINE(), pLoopPlot->getY_INLINE(), bIgnoreLatitude))
									{
										if (GC.getGameINLINE().getMapRandNum(100, "addUniqueBonusType") < pBonusInfo.getGroupRand())
										{
											pLoopPlot->setBonusType(eBonusType);
										}
									}
								}
							}
						}
					}
				}
			}
		}

		SAFE_DELETE_ARRAY(piShuffle);
	}

	SAFE_DELETE_ARRAY(piAreaTried);
}
예제 #3
0
int initializeGame(int numPlayers, int kingdomCards[10], int randomSeed,
		   struct gameState *state) {

  int i;
  int j;
  int it;			
  //set up random number generator
  SelectStream(1);
  PutSeed((long)randomSeed);
  
  //check number of players
  if (numPlayers > MAX_PLAYERS || numPlayers < 2)
    {
      return -1;
    }

  //set number of players
  state->numPlayers = numPlayers;

  //check selected kingdom cards are different
  for (i = 0; i < 10; i++)
    {
      for (j = 0; j < 10; j++)
        {
	  if (j != i && kingdomCards[j] == kingdomCards[i])
	    {
	      return -1;
	    }
        }
    }


  //initialize supply
  ///////////////////////////////

  //set number of Curse cards
  if (numPlayers == 2)
    {
      state->supplyCount[curse] = 10;
    }
  else if (numPlayers == 3)
    {
      state->supplyCount[curse] = 20;
    }
  else
    {
      state->supplyCount[curse] = 30;
    }

  //set number of Victory cards
  if (numPlayers == 2)
    {
      state->supplyCount[estate] = 8;
      state->supplyCount[duchy] = 8;
      state->supplyCount[province] = 8;
    }
  else
    {
      state->supplyCount[estate] = 12;
      state->supplyCount[duchy] = 12;
      state->supplyCount[province] = 12;
    }

  //set number of Treasure cards
  state->supplyCount[copper] = 60 - (7 * numPlayers);
  state->supplyCount[silver] = 40;
  state->supplyCount[gold] = 30;

  //set number of Kingdom cards
  for (i = adventurer; i <= treasure_map; i++)       	//loop all cards
    {
      for (j = 0; j < 10; j++)           		//loop chosen cards
	{
	  if (kingdomCards[j] == i)
	    {
	      //check if card is a 'Victory' Kingdom card
	      if (kingdomCards[j] == great_hall || kingdomCards[j] == gardens)
		{
		  if (numPlayers == 2){ 
		    state->supplyCount[i] = 8; 
		  }
		  else{ state->supplyCount[i] = 12; }
		}
	      else
		{
		  state->supplyCount[i] = 10;
		}
	      break;
	    }
	  else    //card is not in the set choosen for the game
	    {
	      state->supplyCount[i] = -1;
	    }
	}

    }

  ////////////////////////
  //supply intilization complete

  //set player decks
  for (i = 0; i < numPlayers; i++)
    {
      state->deckCount[i] = 0;
      for (j = 0; j < 3; j++)
	{
	  state->deck[i][j] = estate;
	  state->deckCount[i]++;
	}
      for (j = 3; j < 10; j++)
	{
	  state->deck[i][j] = copper;
	  state->deckCount[i]++;		
	}
    }

  //shuffle player decks
  for (i = 0; i < numPlayers; i++)
    {
      if ( shuffle(i, state) < 0 )
	{
	  return -1;
	}
    }

  //draw player hands
  for (i = 0; i < numPlayers; i++)
    {  
      //initialize hand size to zero
      state->handCount[i] = 0;
      state->discardCount[i] = 0;
      //draw 5 cards
      // for (j = 0; j < 5; j++)
      //	{
      //	  drawCard(i, state);
      //	}
    }
  
  //set embargo tokens to 0 for all supply piles
  for (i = 0; i <= treasure_map; i++)
    {
      state->embargoTokens[i] = 0;
    }

  //initialize first player's turn
  state->outpostPlayed = 0;
  state->phase = 0;
  state->numActions = 1;
  state->numBuys = 1;
  state->playedCardCount = 0;
  state->whoseTurn = 0;
  state->handCount[state->whoseTurn] = 0;
  //int it; move to top

  //Moved draw cards to here, only drawing at the start of a turn
  for (it = 0; it < 5; it++){
    drawCard(state->whoseTurn, state);
  }

  updateCoins(state->whoseTurn, state, 0);

  return 0;
}
int cardEffect(int card, int choice1, int choice2, int choice3, struct gameState *state, int handPos, int *bonus)
{
        int i;
        int j;
        int k;
        int x;
        int index;
        int currentPlayer = whoseTurn(state);
        int nextPlayer = currentPlayer + 1;

        int tributeRevealedCards[2] = {-1, -1};
        int temphand[MAX_HAND];// moved above the if statement
        int drawntreasure=0;
        // int cardDrawn;
        int z = 0;// this is the counter for the temp hand
        if (nextPlayer > (state->numPlayers - 1)) {
                nextPlayer = 0;
        }


        //uses switch to select card and perform actions
        switch( card )
        {
        case adventurer:
                return adventurerEffect(state, drawntreasure, z, temphand);

        case council_room:
                //+4 Cards
                for (i = 0; i < 4; i++)
                {
                        drawCard(currentPlayer, state);
                }

                //+1 Buy
                state->numBuys++;

                //Each other player draws a card
                for (i = 0; i < state->numPlayers; i++)
                {
                        if ( i != currentPlayer )
                        {
                                drawCard(i, state);
                        }
                }

                //put played card in played card pile
                discardCard(handPos, currentPlayer, state, 0);

                return 0;

        case feast:
                //gain card with cost up to 5
                //Backup hand
                for (i = 0; i <= state->handCount[currentPlayer]; i++) {
                        temphand[i] = state->hand[currentPlayer][i];//Backup card
                        state->hand[currentPlayer][i] = -1;//Set to nothing
                }
                //Backup hand

                //Update Coins for Buy
                updateCoins(currentPlayer, state, 5);
                x = 1;//Condition to loop on
                while( x == 1) {//Buy one card
                        if (supplyCount(choice1, state) <= 0) {
                                if (DEBUG)
                                        printf("None of that card left, sorry!\n");

                                if (DEBUG) {
                                        printf("Cards Left: %d\n", supplyCount(choice1, state));
                                }
                        }
 /* MUTANT (negate) */                        else if(! (state->coins < getCost(choice1))) {
                                printf("That card is too expensive!\n");

                                if (DEBUG) {
                                        printf("Coins: %d < %d\n", state->coins, getCost(choice1));
                                }
                        }
                        else{

                                if (DEBUG) {
                                        printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]);
                                }

                                gainCard(choice1, state, 0, currentPlayer);//Gain the card
                                x = 0;//No more buying cards

                                if (DEBUG) {
                                        printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]);
                                }

                        }
                }

                //Reset Hand
                for (i = 0; i <= state->handCount[currentPlayer]; i++) {
                        state->hand[currentPlayer][i] = temphand[i];
                        temphand[i] = -1;
                }
                //Reset Hand

                return 0;

        case gardens:
                return -1;

        case mine:
                j = state->hand[currentPlayer][choice1]; //store card we will trash

                if (state->hand[currentPlayer][choice1] < copper || state->hand[currentPlayer][choice1] > gold)
                {
                        return -1;
                }

                if (choice2 > treasure_map || choice2 < curse)
                {
                        return -1;
                }

                if ( (getCost(state->hand[currentPlayer][choice1]) + 3) > getCost(choice2) )
                {
                        return -1;
                }

                gainCard(choice2, state, 2, currentPlayer);

                //discard card from hand
                discardCard(handPos, currentPlayer, state, 0);

                //discard trashed card
                for (i = 0; i < state->handCount[currentPlayer]; i++)
                {
                        if (state->hand[currentPlayer][i] == j)
                        {
                                discardCard(i, currentPlayer, state, 0);
                                break;
                        }
                }

                return 0;

        case remodel:
                j = state->hand[currentPlayer][choice1]; //store card we will trash

                if ( (getCost(state->hand[currentPlayer][choice1]) + 2) > getCost(choice2) )
                {
                        return -1;
                }

                gainCard(choice2, state, 0, currentPlayer);

                //discard card from hand
                discardCard(handPos, currentPlayer, state, 0);

                //discard trashed card
                for (i = 0; i < state->handCount[currentPlayer]; i++)
                {
                        if (state->hand[currentPlayer][i] == j)
                        {
                                discardCard(i, currentPlayer, state, 0);
                                break;
                        }
                }


                return 0;

        case smithy:
                return smithyEffect(state, handPos);

        case village:
                //+1 Card
                drawCard(currentPlayer, state);

                //+2 Actions
                state->numActions = state->numActions + 2;

                //discard played card from hand
                discardCard(handPos, currentPlayer, state, 0);
                return 0;

        case baron:
                return baronEffect(state, choice1);

        case great_hall:
                //+1 Card
                drawCard(currentPlayer, state);

                //+1 Actions
                state->numActions++;

                //discard card from hand
                discardCard(handPos, currentPlayer, state, 0);
                return 0;

        case minion:
                return minionEffect(state, handPos, choice1, choice2);

        case steward:
                return stewardEffect(state, handPos, choice1, choice2, choice3);

        case tribute:
                if ((state->discardCount[nextPlayer] + state->deckCount[nextPlayer]) <= 1) {
                        if (state->deckCount[nextPlayer] > 0) {
                                tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
                                state->deckCount[nextPlayer]--;
                        }
                        else if (state->discardCount[nextPlayer] > 0) {
                                tributeRevealedCards[0] = state->discard[nextPlayer][state->discardCount[nextPlayer]-1];
                                state->discardCount[nextPlayer]--;
                        }
                        else{
                                //No Card to Reveal
                                if (DEBUG) {
                                        printf("No cards to reveal\n");
                                }
                        }
                }

                else{
                        if (state->deckCount[nextPlayer] == 0) {
                                for (i = 0; i < state->discardCount[nextPlayer]; i++) {
                                        state->deck[nextPlayer][i] = state->discard[nextPlayer][i];//Move to deck
                                        state->deckCount[nextPlayer]++;
                                        state->discard[nextPlayer][i] = -1;
                                        state->discardCount[nextPlayer]--;
                                }

                                shuffle(nextPlayer,state);//Shuffle the deck
                        }
                        tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
                        state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1;
                        state->deckCount[nextPlayer]--;
                        tributeRevealedCards[1] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
                        state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1;
                        state->deckCount[nextPlayer]--;
                }

                if (tributeRevealedCards[0] == tributeRevealedCards[1]) {//If we have a duplicate card, just drop one
                        state->playedCards[state->playedCardCount] = tributeRevealedCards[1];
                        state->playedCardCount++;
                        tributeRevealedCards[1] = -1;
                }

                for (i = 0; i <= 2; i++) {
                        if (tributeRevealedCards[i] == copper || tributeRevealedCards[i] == silver || tributeRevealedCards[i] == gold) {//Treasure cards
                                state->coins += 2;
                        }

                        else if (tributeRevealedCards[i] == estate || tributeRevealedCards[i] == duchy || tributeRevealedCards[i] == province || tributeRevealedCards[i] == gardens || tributeRevealedCards[i] == great_hall) {//Victory Card Found
                                drawCard(currentPlayer, state);
                                drawCard(currentPlayer, state);
                        }
                        else{//Action Card
                                state->numActions = state->numActions + 2;
                        }
                }

                return 0;

        case ambassador:
                return ambassadorEffect(state, handPos, choice1, choice2);

        case cutpurse:

                updateCoins(currentPlayer, state, 2);
                for (i = 0; i < state->numPlayers; i++)
                {
                        if (i != currentPlayer)
                        {
                                for (j = 0; j < state->handCount[i]; j++)
                                {
                                        if (state->hand[i][j] == copper)
                                        {
                                                discardCard(j, i, state, 0);
                                                break;
                                        }
                                        if (j == state->handCount[i])
                                        {
                                                for (k = 0; k < state->handCount[i]; k++)
                                                {
                                                        if (DEBUG)
                                                                printf("Player %d reveals card number %d\n", i, state->hand[i][k]);
                                                }
                                                break;
                                        }
                                }

                        }

                }

                //discard played card from hand
                discardCard(handPos, currentPlayer, state, 0);

                return 0;


        case embargo:
                return embargoEffect(state, handPos, choice1);

        case outpost:
                //set outpost flag
                state->outpostPlayed++;

                //discard card
                discardCard(handPos, state->whoseTurn, state, 0);
                return 0;

        case salvager:
                //+1 buy
                state->numBuys++;

                if (choice1)
                {
                        //gain coins equal to trashed card
                        state->coins = state->coins + getCost( handCard(choice1, state) );
                        //trash card
                        discardCard(choice1, currentPlayer, state, 1);
                }

                //discard card
                discardCard(handPos, currentPlayer, state, 0);
                return 0;

        case sea_hag:
                for (i = 0; i < state->numPlayers; i++) {
                        if (i != currentPlayer) {
                                state->discard[i][state->discardCount[i]] = state->deck[i][state->deckCount[i]--];          state->deckCount[i]--;
                                state->discardCount[i]++;
                                state->deck[i][state->deckCount[i]--] = curse;//Top card now a curse
                        }
                }
                return 0;

        case treasure_map:
                //search hand for another treasure_map
                index = -1;
                for (i = 0; i < state->handCount[currentPlayer]; i++)
                {
                        if (state->hand[currentPlayer][i] == treasure_map && i != handPos)
                        {
                                index = i;
                                break;
                        }
                }
                if (index > -1)
                {
                        //trash both treasure cards
                        discardCard(handPos, currentPlayer, state, 1);
                        discardCard(index, currentPlayer, state, 1);

                        //gain 4 Gold cards
                        for (i = 0; i < 4; i++)
                        {
                                gainCard(gold, state, 1, currentPlayer);
                        }

                        //return success
                        return 1;
                }

                //no second treasure_map found in hand
                return -1;
        }

        return -1;
}
int cardEffect(int card, int choice1, int choice2, int choice3, struct gameState *state, int handPos, int *bonus)
{
	int i;
	int j;
	int index;
	int currentPlayer = whoseTurn(state);
	int nextPlayer = currentPlayer + 1;

	int tributeRevealedCards[2] = { -1, -1 };
	int temphand[MAX_HAND];// moved above the if statement
	int drawntreasure = 0;
	int cardDrawn;
	int z = 0;// this is the counter for the temp hand
	if (nextPlayer > (state->numPlayers - 1)) {
		nextPlayer = 0;
	}


	//uses switch to select card and perform actions
	switch (card)
	{
	case adventurer:
		playedCard(handPos, NULL, NULL, state);
		while (drawntreasure < 2) {
			if (drawCard(currentPlayer, state) == -1)
				break;
			cardDrawn = state->hand[currentPlayer][state->handCount[currentPlayer] - 1];//top card of hand is most recently drawn card.
			if (cardDrawn == copper || cardDrawn == silver || cardDrawn == gold)
				drawntreasure++;
			else {
				temphand[z] = cardDrawn;
				state->hand[currentPlayer][state->handCount[currentPlayer] - 1] = -1;
				state->handCount[currentPlayer]--; //this should just remove the top card (the most recently drawn one).
				z++;
			}
		}
		while (z > 0) {
			state->discard[currentPlayer][state->discardCount[currentPlayer]++] = temphand[z - 1]; // discard all cards in play that have been drawn
			z--;
		}
		endPlayed(state, 0);
		return 0;

	case council_room:
		return councilRoomEffect(currentPlayer, handPos, state);

	case feast:
		if (choice1 < curse || choice1 > treasure_map)
			return -1;

		if (supplyCount(choice1, state) <= 0) {
			if (DEBUG)
				printf("None of that card left, sorry!\n");

			if (DEBUG) {
				printf("Cards Left: %d\n", supplyCount(choice1, state));
			}
			return -1;
		}
		else if (5 < getCost(choice1)) {
			if (DEBUG) {
				printf("That card is too expensive!\n");
				printf("Coins: %d < %d\n", state->coins, getCost(choice1));
			}
			return -1;
		}	

		playedCard(handPos, NULL, NULL, state);

		if (DEBUG) {
			printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]);
		}

		gainCard(choice1, state, 0, currentPlayer);//Gain the card

		if (DEBUG) {
			printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + state->discardCount[currentPlayer]);
		}

		//trash feast
		endPlayed(state, 1);

		return 0;

	case gardens:
		return -1;

	case mine:
		if (choice1 >= state->handCount[currentPlayer] || choice1 < 0 || choice1 == handPos)
			return -1;

		j = state->hand[currentPlayer][choice1];  //store card we will trash

		if (state->hand[currentPlayer][choice1] < copper || state->hand[currentPlayer][choice1] > gold)
		{
			return -1;
		}

		if (choice2 > gold || choice2 < copper)
		{
			return -1;
		}

		if ((getCost(state->hand[currentPlayer][choice1]) + 3) > getCost(choice2))
		{
			return -1;
		}

		playedCard(handPos, &choice1, NULL, state);

		//trash old treasure
		discardCard(choice1, currentPlayer, state, 1);

		//gain new treasure
		gainCard(choice2, state, 2, currentPlayer);

		endPlayed(state, 0);

		return 0;

	case remodel:
		if (choice1 >= state->handCount[currentPlayer] || choice1 < 0 || choice1 == handPos)
			return -1;

		if (choice2 < curse || choice2 > treasure_map)
			return -1;

		if ((getCost(state->hand[currentPlayer][choice1]) + 2) > getCost(choice2))
		{
			return -1;
		}

		playedCard(handPos, &choice1, NULL, state);

		//trash choice
		discardCard(choice1, currentPlayer, state, 1);

		//gain new card
		gainCard(choice2, state, 0, currentPlayer);

		endPlayed(state, 0);
		return 0;

	case smithy:
		return smithyEffect(currentPlayer, handPos, state);

	case village:
		return villageEffect(currentPlayer, handPos, state);

	case baron:
		if (!(choice1 == 1 || choice1 == 2))
			return -1;

		if (choice1 == 1) {//Boolean true or going to discard an estate
			int p = 0;//Iterator for hand!
			int card_not_discarded = 1;//Flag for discard set!
			while (card_not_discarded) {
				if (p >= state->handCount[currentPlayer]) {
					if (DEBUG) {
						printf("No estate cards in your hand, invalid choice\n");						
					}
					return -1;
				}
				else if (state->hand[currentPlayer][p] == estate) {//Found an estate card!
					playedCard(handPos, &p, NULL, state);
					*bonus += 4;//Add 4 coins to the amount of coins
					discardCard(p, currentPlayer, state, 0);
					card_not_discarded = 0;//Exit the loop
				}
				else {
					p++;//Next card
				}
			}
		}

		else {
			playedCard(handPos, NULL, NULL, state);
			gainCard(estate, state, 0, currentPlayer);//Gain an estate	
		}
		state->numBuys++;//Increase buys by 1!
		endPlayed(state, 0);
		return 0;

	case great_hall:
		return greatHallEffect(currentPlayer, handPos, state);

	case minion:
		if (!(choice1 == 1 || choice1 == 2))
			return -1;

		playedCard(handPos, NULL, NULL, state);

		//+1 action
		state->numActions++;

		if (choice1 == 1)      //+2 coins
		{
			*bonus += 2;
		}

		else if (choice1 == 2)     //discard hand, redraw 4, other players with 5+ cards discard hand and draw 4
		{
			//discard hand
			while (numHandCards(state) > 0)
			{
				discardCard(0, currentPlayer, state, 0);
			}

			//draw 4
			for (i = 0; i < 4; i++)
			{
				drawCard(currentPlayer, state);
			}

			//other players discard hand and redraw if hand size > 4
			for (i = 0; i < state->numPlayers; i++)
			{
				if (i != currentPlayer)
				{
					if (state->handCount[i] > 4)
					{
						//discard hand
						while (state->handCount[i] > 0)
						{
							discardCard(0, i, state, 0);
						}

						//draw 4
						for (j = 0; j < 4; j++)
						{
							drawCard(i, state);
						}
					}
				}
			}

		}
		endPlayed(state, 0);
		return 0;

	case steward:
		if (!(choice1 == 1 || choice1 == 2 || choice1 == 3))
			return -1;
		if (choice1 == 3 && ((choice2 >= state->handCount[currentPlayer] || choice2 < 0) || (choice3 >= state->handCount[currentPlayer] || choice3 < 0) || choice2 == choice3 || (choice2 == handPos || choice3 == handPos)))
			return -1;

		if (choice1 == 1)
		{
			playedCard(handPos, NULL, NULL, state);
			//+2 cards
			drawCard(currentPlayer, state);
			drawCard(currentPlayer, state);
		}
		else if (choice1 == 2)
		{
			//+2 coins
			playedCard(handPos, NULL, NULL, state);
			*bonus += 2;
		}
		else
		{
			playedCard(handPos, &choice2, &choice3, state);
			//trash 2 cards in hand
			if (choice2 < choice3) {
				int tmp = choice2;
				choice2 = choice3;
				choice3 = tmp;
			}

			//discard order matters, must discard max to min for correct effect
			discardCard(choice2, currentPlayer, state, 1);
			discardCard(choice3, currentPlayer, state, 1);			
		}
		endPlayed(state, 0);
		return 0;

	case tribute:
		playedCard(handPos, NULL, NULL, state);
		if ((state->discardCount[nextPlayer] + state->deckCount[nextPlayer]) <= 1) {
			if (state->deckCount[nextPlayer] > 0) {
				tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer] - 1];
				state->deckCount[nextPlayer]--;
				state->discard[nextPlayer][state->discardCount[nextPlayer]] = tributeRevealedCards[0];
				state->discardCount[nextPlayer]++;
			}
			else if (state->discardCount[nextPlayer] > 0) {
				tributeRevealedCards[0] = state->discard[nextPlayer][state->discardCount[nextPlayer] - 1];
			}
			else {
				//No Card to Reveal
				if (DEBUG) {
					printf("No cards to reveal\n");
				}
				endPlayed(state, 0);
				return 0;
			}
		}

		else {
			if (state->deckCount[nextPlayer] == 0) {
				j = state->discardCount[nextPlayer];
				for (i = 0; i < j; i++) {
					state->deck[nextPlayer][i] = state->discard[nextPlayer][i];//Move to deck
					state->deckCount[nextPlayer]++;
					state->discard[nextPlayer][i] = -1;
					state->discardCount[nextPlayer]--;
				}

				shuffle(nextPlayer, state);//Shuffle the deck
			}
			tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer] - 1];
			state->deck[nextPlayer][state->deckCount[nextPlayer] - 1] = -1;
			state->deckCount[nextPlayer]--;

			if (state->deckCount[nextPlayer] == 0) {
				j = state->discardCount[nextPlayer];
				for (i = 0; i < j; i++) {
					state->deck[nextPlayer][i] = state->discard[nextPlayer][i];//Move to deck
					state->deckCount[nextPlayer]++;
					state->discard[nextPlayer][i] = -1;
					state->discardCount[nextPlayer]--;
				}

				shuffle(nextPlayer, state);//Shuffle the deck
			}

			state->discard[nextPlayer][state->discardCount[nextPlayer]] = tributeRevealedCards[0];
			state->discardCount[nextPlayer]++;

			tributeRevealedCards[1] = state->deck[nextPlayer][state->deckCount[nextPlayer] - 1];
			state->deck[nextPlayer][state->deckCount[nextPlayer] - 1] = -1;
			state->deckCount[nextPlayer]--;
			state->discard[nextPlayer][state->discardCount[nextPlayer]] = tributeRevealedCards[1];
			state->discardCount[nextPlayer]++;
		}

		if (tributeRevealedCards[0] == tributeRevealedCards[1]) {//If we have a duplicate card, just drop one 
			tributeRevealedCards[1] = -1;
		}

		for (i = 0; i < 2; i++) {
			if (tributeRevealedCards[i] == copper || tributeRevealedCards[i] == silver || tributeRevealedCards[i] == gold) {//Treasure cards
				*bonus += 2;
			}

			if (tributeRevealedCards[i] == estate || tributeRevealedCards[i] == duchy || tributeRevealedCards[i] == province || tributeRevealedCards[i] == gardens || tributeRevealedCards[i] == great_hall) {//Victory Card Found
				drawCard(currentPlayer, state);
				drawCard(currentPlayer, state);
			}
			if (tributeRevealedCards[i] >= adventurer && tributeRevealedCards[i] <= treasure_map){//Action Card
				state->numActions = state->numActions + 2;
			}
		}

		endPlayed(state, 0);

		return 0;

	case ambassador:
		j = 0;        //used to check if player has enough cards to discard

		if (choice2 > 2 || choice2 < 0)
		{
			return -1;
		}

		if (choice1 == handPos || choice1 >= numHandCards(state) || choice1 < 0)
		{
			return -1;
		}

		for (i = 0; i < state->handCount[currentPlayer]; i++)
		{
			if (i != handPos && i == state->hand[currentPlayer][choice1])
			{
				j++;
			}
		}
		if (j < choice2)
		{
			return -1;
		}

		playedCard(handPos, &choice1, NULL, state);

		if (DEBUG)
			printf("Player %d reveals card number: %d\n", currentPlayer, state->hand[currentPlayer][choice1]);

		//increase supply count for choosen card by amount being discarded
		state->supplyCount[state->hand[currentPlayer][choice1]] += choice2;

		//each other player gains a copy of revealed card
		for (i = 0; i < state->numPlayers; i++)
		{
			if (i != currentPlayer)
			{
				gainCard(state->hand[currentPlayer][choice1], state, 0, i);
			}
		}

		//trash copies of cards returned to supply
		for (j = 0; j < choice2; j++)
		{
			for (i = state->handCount[currentPlayer] - 1; i >= 0; i--)
			{
				if (state->hand[currentPlayer][i] == state->hand[currentPlayer][choice1])
				{
					discardCard(i, currentPlayer, state, 1);
					break;
				}
			}
		}

		endPlayed(state, 0);

		return 0;

	case cutpurse:
		return cutpurseEffect(currentPlayer, handPos, state, bonus);

	case embargo:
		if (choice1 < curse || choice1 > treasure_map)
			return -1;
		//see if selected pile is in play
		if (state->supplyCount[choice1] == -1)
		{
			return -1;
		}

		playedCard(handPos, NULL, NULL, state);

		//+2 Coins
		*bonus += 2;

		//add embargo token to selected supply pile
		state->embargoTokens[choice1]++;

		//trash card
		endPlayed(state, 1);
		return 0;

	case outpost:
		if (state->outpostTurn == 1)
			return -1;
		
		playedCard(handPos, NULL, NULL, state);
		//set outpost flag
		state->outpostPlayed = 1;

		//we actually don't call endPlayed() here on purpose
		return 0;

	case salvager:
		if (choice1 >= state->handCount[currentPlayer] || choice1 < 0 || choice1 == handPos)
			return -1;

		playedCard(handPos, &choice1, NULL, state);

		//+1 buy
		state->numBuys++;
		
		//gain coins equal to trashed card
		*bonus += getCost(handCard(choice1, state));
		
		//trash card
		discardCard(choice1, currentPlayer, state, 1);
		
		endPlayed(state, 0);
		return 0;

	case sea_hag:
		playedCard(handPos, NULL, NULL, state);
		for (i = 0; i < state->numPlayers; i++) {
			if (i != currentPlayer) {
				if (state->deckCount[i] + state->discardCount[i] > 0) {
					if (state->deckCount[i] == 0) {
						j = state->discardCount[i];
						for (index = 0; index < j; index++) {
							state->deck[i][index] = state->discard[i][index];//Move to deck
							state->deckCount[i]++;
							state->discard[i][index] = -1;
							state->discardCount[i]--;
						}

						shuffle(i, state);//Shuffle the deck
					}
					state->discard[i][state->discardCount[i]] = state->deck[i][state->deckCount[i] - 1];
					state->discardCount[i]++;
					//conveniently, this happens to add it to the top of the deck
					gainCard(curse, state, 1, i);
				}
				else { //literally no cards in their deck or discard, so they just get a curse in their deck
					gainCard(curse, state, 1, i);
				}				
			}
		}
		endPlayed(state, 0);
		return 0;

	case treasure_map:
		//search hand for another treasure_map
		index = -1;
		for (i = 0; i < state->handCount[currentPlayer]; i++)
		{
			if (state->hand[currentPlayer][i] == treasure_map && i != handPos)
			{
				index = i;
				break;
			}
		}
		if (index > -1){
			playedCard(handPos, &index, NULL, state);
			//trash other treasure_map
			discardCard(index, currentPlayer, state, 1);

			//gain 4 Gold cards
			for (i = 0; i < 4; i++)
			{
				gainCard(gold, state, 1, currentPlayer);
			}
		}
		else {
			return -1;
		}
		endPlayed(state, 1);
		return 0;
		
	}

	return -1;
}
예제 #6
0
static NWDSCCODE __NWDSChangeObjectPasswordStep2(
		NWCONN_HANDLE conn,
		NWObjectID objectID,
		NWObjectID pseudoID,
		nuint8 rndseed[4],
		nuint8 *connPublicKey,
		const char* oldPassword,
		const char* newPassword
) {
	nuint8* privateKey;
	size_t privateKeyLen;
	nuint8 ec_newpwd[4096];
	size_t ec_newpwd_len;
	nuint8 oldPwdHash[16];
	nuint8 newPwdHash[16];
	NWDSCCODE err;
	NWDSCCODE gpk_err;
	size_t di;
	Buf_T *ib;
	Buf_T *ob;
	nuint8 tmpID[4];
	
	DSET_HL(tmpID, 0, pseudoID);
	shuffle(tmpID, oldPassword, strlen(oldPassword), oldPwdHash);
	shuffle(tmpID, newPassword, strlen(newPassword), newPwdHash);
	
	err = __NWDSGetPrivateKey(conn, connPublicKey, rndseed, objectID, oldPwdHash, NULL, &privateKey, &privateKeyLen);
	if (err != 0 && err != NWE_PASSWORD_EXPIRED)
		goto quit;
	if (privateKeyLen < 10) {
		err = ERR_INVALID_SERVER_RESPONSE;
		goto free_privkey;
	}
	DSET_LH(privateKey, 2, 1);
	WSET_LH(privateKey, 6, 2);

	gpk_err = err;
	ec_newpwd_len = sizeof(ec_newpwd);
	err = __NWEncryptWithSK(newPwdHash, 16, privateKey + 2, privateKeyLen - 2, ec_newpwd, &ec_newpwd_len);
	if (err)
		goto free_privkey;
	di = ec_newpwd_len + 0x34;
	
	err = NWDSAllocBuf(di + 8, &ib);
	if (err)
		goto free_privkey_ecnewpwd;
	NWDSBufPut(ib, rndseed, 4);
	NWDSBufPutBuffer(ib, oldPwdHash, 16);
	NWDSBufPutLE32(ib, strlen(newPassword));
	NWDSBufPutBuffer(ib, newPwdHash, 16);
	NWDSBufPutBuffer(ib, ec_newpwd, ec_newpwd_len);
	
	err = NWDSAllocBuf(di + 256, &ob);
	if (err)
		goto free_privkey_ecnewpwd_ib;
	err = rsa_crypt2(connPublicKey, ib, ob);
	if (err)
		goto free_privkey_ecnewpwd_ib_ob;
	err = __NWDSChangePasswordV0(conn, objectID, ob);
	if (!err)
		err = gpk_err;
free_privkey_ecnewpwd_ib_ob:;
	NWDSClearFreeBuf(ob);
free_privkey_ecnewpwd_ib:;
	NWDSClearFreeBuf(ib);
free_privkey_ecnewpwd:;
	memset(ec_newpwd, 0, sizeof(ec_newpwd));
free_privkey:;
	memset(privateKey, 0, privateKeyLen);
	free(privateKey);
quit:;
	memset(oldPwdHash, 0, sizeof(oldPwdHash));
	memset(newPwdHash, 0, sizeof(newPwdHash));
	return err;
}
int cardEffect(int card, int choice1, int choice2, int choice3, struct gameState *state, int handPos, int *bonus)
{
	int i;
	int j;
	int k;
	int index;
	int currentPlayer = whoseTurn(state);
	int nextPlayer = currentPlayer + 1;

	int tributeRevealedCards[2] = {-1, -1};
	int drawntreasure=0;
	if (nextPlayer > (state->numPlayers - 1)){
		nextPlayer = 0;
	}
  
	
	//uses switch to select card and perform actions
	switch( card ) 
		{
		case adventurer:
			return adventurerCard (drawntreasure, state, currentPlayer);
		case council_room:
			return councilRoomCard (currentPlayer, state, handPos);
		case feast:
			return feastCard (currentPlayer, state, choice1);			
		case gardens:
			return -1;			
		case mine:
			return mineCard (currentPlayer, state, choice1, choice2, handPos);
		case remodel:
			return remodelCard (currentPlayer, state, choice1, choice2, handPos);
		case smithy:
			//+3 Cards
			for (i = 0; i < 3; i++)
				{
					drawCard(currentPlayer, state);
				}
			
			//discard card from hand
			discardCard(handPos, currentPlayer, state, 0);
			return 0;
		
		case village:
			//+1 Card
			drawCard(currentPlayer, state);
			
			//+2 Actions
			state->numActions = state->numActions + 2;
			
			//discard played card from hand
			discardCard(handPos, currentPlayer, state, 0);
			return 0;
		
		case baron:
			state->numBuys++;//Increase buys by 1!
			if (choice1 > 0){//Boolean true or going to discard an estate
				int p = 0;//Iterator for hand!
				int card_not_discarded = 1;//Flag for discard set!
				while(card_not_discarded){
					if (state->hand[currentPlayer][p] == estate){//Found an estate card!
						state->coins += 4;//Add 4 coins to the amount of coins
						state->discard[currentPlayer][state->discardCount[currentPlayer]] = state->hand[currentPlayer][p];
						state->discardCount[currentPlayer]++;
						for (;p < state->handCount[currentPlayer]; p++){
							state->hand[currentPlayer][p] = state->hand[currentPlayer][p+1];
						}
						state->hand[currentPlayer][state->handCount[currentPlayer]] = -1;
						state->handCount[currentPlayer]--;
						card_not_discarded = 0;//Exit the loop
					}
					else if (p > state->handCount[currentPlayer]){
						if(DEBUG) {
							printf("No estate cards in your hand, invalid choice\n");
							printf("Must gain an estate if there are any\n");
						}
						if (supplyCount(estate, state) > 0){
							gainCard(estate, state, 0, currentPlayer);
							state->supplyCount[estate]--;//Decrement estates
							if (supplyCount(estate, state) == 0){
								isGameOver(state);
							}
						}
						card_not_discarded = 0;//Exit the loop
					}
			    
					else{
						p++;//Next card
					}
				}
			}
			    
			else{
				if (supplyCount(estate, state) > 0){
					gainCard(estate, state, 0, currentPlayer);//Gain an estate
					state->supplyCount[estate]--;//Decrement Estates
					if (supplyCount(estate, state) == 0){
						isGameOver(state);
					}
				}
			}
	    
      
			return 0;
		
		case great_hall:
			//+1 Card
			drawCard(currentPlayer, state);
			
			//+1 Actions
			state->numActions++;
			
			//discard card from hand
			discardCard(handPos, currentPlayer, state, 0);
			return 0;
		
		case minion:
			//+1 action
			state->numActions++;
			
			//discard card from hand
			discardCard(handPos, currentPlayer, state, 0);
			
			if (choice1)		//+2 coins
				{
					state->coins = state->coins + 2;
				}
			
			else if (choice2)		//discard hand, redraw 4, other players with 5+ cards discard hand and draw 4
				{
					//discard hand
					while(numHandCards(state) > 0)
						{
							discardCard(handPos, currentPlayer, state, 0);
						}
				
					//draw 4
					for (i = 0; i < 4; i++)
						{
							drawCard(currentPlayer, state);
						}
				
					//other players discard hand and redraw if hand size > 4
					for (i = 0; i < state->numPlayers; i++)
						{
							if (i != currentPlayer)
								{
									if ( state->handCount[i] > 4 )
										{
											//discard hand
											while( state->handCount[i] > 0 )
												{
													discardCard(handPos, i, state, 0);
												}
							
											//draw 4
											for (j = 0; j < 4; j++)
												{
													drawCard(i, state);
												}
										}
								}
						}
				
				}
			return 0;
		
		case steward:
			if (choice1 == 1)
				{
					//+2 cards
					drawCard(currentPlayer, state);
					drawCard(currentPlayer, state);
				}
			else if (choice1 == 2)
				{
					//+2 coins
					state->coins = state->coins + 2;
				}
			else
				{
					//trash 2 cards in hand
					discardCard(choice2, currentPlayer, state, 1);
					discardCard(choice3, currentPlayer, state, 1);
				}
			
			//discard card from hand
			discardCard(handPos, currentPlayer, state, 0);
			return 0;
		
		case tribute:
			if ((state->discardCount[nextPlayer] + state->deckCount[nextPlayer]) <= 1){
				if (state->deckCount[nextPlayer] > 0){
					tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
					state->deckCount[nextPlayer]--;
				}
				else if (state->discardCount[nextPlayer] > 0){
					tributeRevealedCards[0] = state->discard[nextPlayer][state->discardCount[nextPlayer]-1];
					state->discardCount[nextPlayer]--;
				}
				else{
					//No Card to Reveal
					if (DEBUG){
						printf("No cards to reveal\n");
					}
				}
			}
	    
			else{
				if (state->deckCount[nextPlayer] == 0){
					for (i = 0; i < state->discardCount[nextPlayer]; i++){
						state->deck[nextPlayer][i] = state->discard[nextPlayer][i];//Move to deck
						state->deckCount[nextPlayer]++;
						state->discard[nextPlayer][i] = -1;
						state->discardCount[nextPlayer]--;
					}
			    
					shuffle(nextPlayer,state);//Shuffle the deck
				} 
				tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
				state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1;
				state->deckCount[nextPlayer]--;
				tributeRevealedCards[1] = state->deck[nextPlayer][state->deckCount[nextPlayer]-1];
				state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1;
				state->deckCount[nextPlayer]--;
			}    
		       
			if (tributeRevealedCards[0] == tributeRevealedCards[1]){//If we have a duplicate card, just drop one 
				state->playedCards[state->playedCardCount] = tributeRevealedCards[1];
				state->playedCardCount++;
				tributeRevealedCards[1] = -1;
			}

			for (i = 0; i <= 2; i ++){
				if (tributeRevealedCards[i] == copper || tributeRevealedCards[i] == silver || tributeRevealedCards[i] == gold){//Treasure cards
					state->coins += 2;
				}
		    
				else if (tributeRevealedCards[i] == estate || tributeRevealedCards[i] == duchy || tributeRevealedCards[i] == province || tributeRevealedCards[i] == gardens || tributeRevealedCards[i] == great_hall){//Victory Card Found
					drawCard(currentPlayer, state);
					drawCard(currentPlayer, state);
				}
				else{//Action Card
					state->numActions = state->numActions + 2;
				}
			}
	    
			return 0;
		
		case ambassador:
			j = 0;		//used to check if player has enough cards to discard

			if (choice2 > 2 || choice2 < 0)
				{
					return -1;				
				}

			if (choice1 == handPos)
				{
					return -1;
				}

			for (i = 0; i < state->handCount[currentPlayer]; i++)
				{
					if (i != handPos && i == state->hand[currentPlayer][choice1] && i != choice1)
						{
							j++;
						}
				}
			if (j < choice2)
				{
					return -1;				
				}

			if (DEBUG) 
				printf("Player %d reveals card number: %d\n", currentPlayer, state->hand[currentPlayer][choice1]);

			//increase supply count for choosen card by amount being discarded
			state->supplyCount[state->hand[currentPlayer][choice1]] += choice2;
			
			//each other player gains a copy of revealed card
			for (i = 0; i < state->numPlayers; i++)
				{
					if (i != currentPlayer)
						{
							gainCard(state->hand[currentPlayer][choice1], state, 0, i);
						}
				}

			//discard played card from hand
			discardCard(handPos, currentPlayer, state, 0);			

			//trash copies of cards returned to supply
			for (j = 0; j < choice2; j++)
				{
					for (i = 0; i < state->handCount[currentPlayer]; i++)
						{
							if (state->hand[currentPlayer][i] == state->hand[currentPlayer][choice1])
								{
									discardCard(i, currentPlayer, state, 1);
									break;
								}
						}
				}			

			return 0;
		
		case cutpurse:

			updateCoins(currentPlayer, state, 2);
			for (i = 0; i < state->numPlayers; i++)
				{
					if (i != currentPlayer)
						{
							for (j = 0; j < state->handCount[i]; j++)
								{
									if (state->hand[i][j] == copper)
										{
											discardCard(j, i, state, 0);
											break;
										}
									if (j == state->handCount[i])
										{
											for (k = 0; k < state->handCount[i]; k++)
												{
													if (DEBUG)
														printf("Player %d reveals card number %d\n", i, state->hand[i][k]);
												}	
											break;
										}		
								}
					
						}
				
				}				

			//discard played card from hand
			discardCard(handPos, currentPlayer, state, 0);			

			return 0;

		
		case embargo: 
			//+2 Coins
			state->coins = state->coins + 2;
			
			//see if selected pile is in play
			if ( state->supplyCount[choice1] == -1 )
				{
					return -1;
				}
			
			//add embargo token to selected supply pile
			state->embargoTokens[choice1]++;
			
			//trash card
			discardCard(handPos, currentPlayer, state, 1);		
			return 0;
		
		case outpost:
			//set outpost flag
			state->outpostPlayed++;
			
			//discard card
			discardCard(handPos, currentPlayer, state, 0);
			return 0;
		
		case salvager:
			//+1 buy
			state->numBuys++;
			
			if (choice1)
				{
					//gain coins equal to trashed card
					state->coins = state->coins + getCost( handCard(choice1, state) );
					//trash card
					discardCard(choice1, currentPlayer, state, 1);	
				}
			
			//discard card
			discardCard(handPos, currentPlayer, state, 0);
			return 0;
		
		case sea_hag:
			for (i = 0; i < state->numPlayers; i++){
				if (i != currentPlayer){
					state->discard[i][state->discardCount[i]] = state->deck[i][state->deckCount[i]-1];
					state->discardCount[i]++;
					state->deck[i][state->deckCount[i]-1] = curse;//Top card now a curse
				}
			}
			return 0;
		
		case treasure_map:
			//search hand for another treasure_map
			index = -1;
			for (i = 0; i < state->handCount[currentPlayer]; i++)
				{
					if (state->hand[currentPlayer][i] == treasure_map && i != handPos)
						{
							index = i;
							break;
						}
				}
			if (index > -1)
				{
					//trash both treasure cards
					discardCard(handPos, currentPlayer, state, 1);
					discardCard(index, currentPlayer, state, 1);

					//gain 4 Gold cards
					for (i = 0; i < 4; i++)
						{
							gainCard(gold, state, 1, currentPlayer);
						}
				
					//return success
					return 1;
				}
			
			//no second treasure_map found in hand
			return -1;
		}
	
	return -1;
}
예제 #8
0
void ImageDataLayer<Dtype>::ShuffleImages() {
  caffe::rng_t* prefetch_rng =
      static_cast<caffe::rng_t*>(prefetch_rng_->generator());
  shuffle(lines_.begin(), lines_.end(), prefetch_rng);
}
예제 #9
0
int main(void) {
    clock_t start, end;
    start = clock();
    
    int i, j, k,x;
    int current_count = 0;
    int setosa_count;
    int versicolor_count;
    int virginica_count;
    char answer_flower[20];
    
    Neuron *current_root, *answer;
    Neuron *root[TRIAL_NUM][10];
    
    // データの読み込み
    read_datums(data, flower_type);
    shuffle(150, data, flower_type);
    
    //rootの初期化
    for (i = 0; i<TRIAL_NUM; i++) {
        for (j = 0; j<10; j++) {
            root[i][j] = NULL;
        }
    }
    
    for (i = 0; i<TRIAL_NUM; i++) {
        for (j = 0; j<10; j++) {
            split_datums(
                         data,
                         flower_type,
                         traning_data,
                         traning_result,
                         testing_data,
                         testing_result,
                         j
                         );
            
            shuffle(135, traning_data, traning_result);
            
            current_root = create_tree(traning_data, traning_result);
            //	    show(current_root);
            
            root[i][j] = current_root;
            current_root = NULL;
            
            if (i % 5 == 0) {
                for (x = 0; x < 15; x++) {
                    setosa_count = virginica_count = versicolor_count = 0;
                    for (k = 0; k <= i; k++) {
                        answer = get_perhaps_nearest(root[k][j], testing_data[x]);
                        if (strcmp(answer->result, "setosa\n") == 0) {
                            setosa_count++;
                        }
                        else if (strcmp(answer->result, "virginica\n") == 0) {
                            virginica_count++;
                        }
                        else {
                            versicolor_count++;
                        }
                    }
                    //				printf("%d,%d,%d\n", setosa_count, virginica_count, versicolor_count);
                    
                    if (setosa_count > virginica_count) {                //a>b
                        if (setosa_count > versicolor_count) {		//a>b && a>c
                            //setosaが一番多いとき
                            strcpy(answer_flower, "setosa\n");
                        }
                        else {									//a>b && a<=c
                            //virginicaが一番少なく、setosaとversicolorが同数またはversicolorが一番多いとき
                            strcpy(answer_flower, "versicolor\n");
                        }
                    }
                    else if(setosa_count==virginica_count==versicolor_count){
                        //3つが同数のとき、一番最後に作ったツリーの答えを使う。
                        strcpy(answer_flower, answer->result);
                    }
                    else {										//b>=a
                        if (virginica_count < versicolor_count) { // b>=a && b<c
                            // versicolorが一番多いとき
                            strcpy(answer_flower, "versicolor\n");
                        }
                        else{	 //b>a && b>=c
                            // versicolorとvirginicaが同数か一番多いとき
                            strcpy(answer_flower, "virginica\n");
                        }
                    }
                    //					printf("%s%s", answer_flower, testing_result[x]);
                    if (strcmp(answer_flower, testing_result[x]) == 0) {
                        current_count++;
                    }
                }
            }
            for (x = 0; x < 135; x++) {
                for (k = 0; k < 4; k++) {
                    traning_data[x][k] = 0;
                }
                strcpy(traning_result[x],"0");
            }
        }
        if (i % 5 == 0) {
            printf("シャッフル回数%d回,確率%.4f\n", i + 1, 100 * (float)current_count / 150);
            current_count = 0;
        }
    }
    
    
    //rootを全て開放する
    for (i = 0; i<TRIAL_NUM; i++) {
        if (root[i][0] == NULL) {
            break;
        }
        for (j = 0; j<10; j++) {
            free_tree(root[i][j]);
        }
    }
    
    end = clock();
    printf("実行時間:%f[ms]\n", ((float)(end - start) / CLOCKS_PER_SEC) * 1000);
    
    while (1);
    
    return 0;
}
예제 #10
0
int play_poker(card deck[52]) {
	int	flush_cnt = 0, hand_cnt = 0;
	int	i, j, x, y, done = FALSE, fold = FALSE, menu = TRUE;
	long	bet=0, pot=0;
	char    ch, buf[128];
	card	hand[NPLAYERS][5];	/* each player is dealt 5 cards */
	
	srand(time(NULL));	/* seed the random number generator */
	shuffle(deck);
	deal_the_cards(deck, hand);
	bet = 10;
	printf("Antie is $%ld\n\n", bet);
	if(character.trading_credits < 10) {
		printf("You don't even have enough to Antie.\n");
		printf("The dealer kicks you out of the game,\n");
		printf("And says \"Go Wumpus Hunting!\"\n\n");
		return 0;
	} else {
		printf("Welcome to poker.\n");
		printf("Game is five card, no draw.\n");
		printf("\nYou against the dealer.\n");
		printf("The dealer Anties 10 dollars.\n\n");
		character.trading_credits -= 10;
		pot += 20;
		Pause2();
	}
	
	while(!done) {
		if(menu) {
			printf("\nDealer's Hand\n");
			prn_facedown_hand();
			printf("\nYour Hand\n");			
			prn_faceup_hand(hand[1]);
   			printf("\x1b[0;35m    1        2        3        4        5\x1b[0m\n");

			printf("\n(r)=raise, (c)=call, (f)=fold\n");
        	}
        	printf("\nPot is %ld gold\n",pot);
        	printf("[(?)=help] -> ");
        	for(;;) {
        		/*****************/
        		/* get keys here */
        		/*****************/
			ch = GetKey(0);
			if(ch == '1' ||
			ch == '2' ||
			ch == '3' ||
			ch == '4' ||
			ch == '5' ||
			ch == 'f' ||
			ch == 'q' ||
			ch == 'r' ||
			ch == 'c' ||
			ch == '?') break;
        	}
        	switch(tolower(ch)) {
		case 'r':
			printf("raise..\n\n");
			
			printf("You have $%d in pocket\n\n", character.trading_credits);
			printf("Raise how much? ");
			GetStr(buf, 10, 0);
			bet = atol(buf);
			if(bet == 0) {
				printf("\nYou can't raise by zero trading_credits, try calling.\n\n");
				done = TRUE;
				break;
			} else if(character.trading_credits >= bet) {
				printf("\nBet Amount is now $%d\n", bet);
				character.trading_credits -= bet;
				pot += (bet * 2);
				printf("Dealer see's you and calls!\n");
				/***********************************/
				/* here the dealer has to decide   */
				/* if he is going to raise or call */
				/* the bet.                        */
				/***********************************/
			} else {
				printf("\nYou don't have enough trading_credits!\n");
			}
			menu = FALSE;
			done = FALSE;
			fold = FALSE;
			break;
		case 'c':
			printf("call..\n");
			
			printf("\nDealer calls as well.\n");
			/****************************/
			/* what does the dealer do? */
			/****************************/
			menu = FALSE;
			done = TRUE;
			fold = FALSE;
			break;
        	case 'q':
        	case 'f':
        		printf("fold..\n\n");
        		printf("\x1b[0mDealer's Hand\n");
        		prn_facedown_hand();
        		printf("\x1b[0mYour Hand\n");
        		prn_facedown_hand();
        		printf("\nYou lost a pot of %ld gold to the dealer.\n", pot);
        		
        		fold = TRUE;
        		menu = FALSE;
        		done = TRUE;
        		break;
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
			y = atoi(&ch);
			printf("\x1b[1;32mremove card #%d\n\n", y);
			/********************************************/
			/* questions:                               */
			/* how to change a character to an integer? */
			/* how to take one card from the hand, then */
			/* add another card from deck, to the hand? */
			/********************************************/
			printf("\x1b[0mYou can't do that in this game.\n");
			done = FALSE;
			menu = FALSE;
			fold = FALSE;
			break;
		case '?':
			printf("\x1b[0mhelp..\n\n");
			menu = TRUE;
			done = FALSE;
			fold = FALSE;
			break;
		default:
			break;
		}
	}
	
	if(!fold) {
		int dc, yc;
		printf("Dealer: ");
		dc = TopCard(hand[0]);
		printf("   YOU: ");
		yc = TopCard(hand[1]);
		
		printf("\n\x1b[0mDealer's Hand\n");
		prn_faceup_hand(hand[0]);
         	printf("\n\x1b[0mYour Hand\n");
 		prn_faceup_hand(hand[1]);        	
		printf("\x1b[0m\n");
		
		if(dc == yc) {
			printf("A draw. (pot is split)\n");
			character.trading_credits += (pot/2);
		} else if(dc > yc) {
			printf("Dealer wins!\n");
		} else if(dc < yc) {			
			printf("You win!\n");
			printf("Awarding %d gold and %d exp point.\n",pot,pot/2);
			character.trading_credits += pot;
			character.exp += pot / 2;
		}
	}
	update_empire();				
	return 0;
}
예제 #11
0
double  monte_Analysis(Deck *deck, Player *person){
	 int i, j, k, z, bestType = 0;
	 double avebucket = 0.0, maxave = 0.0, bestprob = 0.0, ave = 0.0, rank = 0.0, sum = 0.0;
	 double maxscale = 0;
	 int scalenum = 0;
	 int scale[10];
	 Player dummy = player_init("Dummy", 255);
	 int choices[][5] = {
		  {0,0,0,0,1},
		  {0,0,0,1,0},
		  {0,0,0,1,1},
		  {0,0,1,0,0},
		  {0,0,1,0,1},
		  {0,0,1,1,0},
		  {0,0,1,1,1},
		  {0,1,0,0,0},
		  {0,1,0,0,1},
		  {0,1,0,1,0},
		  {0,1,0,1,1},
		  {0,1,1,0,0},
		  {0,1,1,0,1},
		  {0,1,1,1,0},
		  {0,1,1,1,1},
		  {1,0,0,0,0},
		  {1,0,0,0,1},
		  {1,0,0,1,0},
		  {1,0,0,1,1},
		  {1,0,1,0,0},
		  {1,0,1,0,1},
		  {1,0,1,1,0},
		  {1,0,1,1,1},
		  {1,1,0,0,0},
		  {1,1,0,0,1},
		  {1,1,0,1,0},
		  {1,1,0,1,1},
		  {1,1,1,0,0},
		  {1,1,1,0,1},
		  {1,1,1,1,0},
		  {1,1,1,1,1},
		  {0,0,0,0,0},
	 };

	 dummy.hand[0] = person->hand[0];
	 dummy.hand[1] = person->hand[1];
	 dummy.hand[2] = person->hand[2];
	 dummy.hand[3] = person->hand[3];
	 dummy.hand[4] = person->hand[4];

	 for(i = 0;i<32;i++){
		  maxscale = 0;
		  scalenum = 0;
		  sum = 0;
		  for(z=0;z<10;z++){
				scale[z] = 0;
		  }
		  for(j = 0; j < MCTRIALS; j++){
				dummy.hand[0] = person->hand[0];
				dummy.hand[1] = person->hand[1];
				dummy.hand[2] = person->hand[2];
				dummy.hand[3] = person->hand[3];
				dummy.hand[4] = person->hand[4];
				shuffle(deck, 47);
				for(k = 0; k < HAND_SIZE; k++){
					 if(choices[i][k] == 1){
						  exchangeMC(deck, &dummy, k);
					 }
				}
				rank = handRank(&dummy);
				sum += (double)rank;
				if(rank <= 12){
					 scale[0]++;
				}
				else if(rank > 12 && rank <=25){
					 scale[1]++;
				}
				else if(rank > 25 && rank <=54){
					 scale[2]++;
				}
				else if(rank >54 && rank <=67){
					 scale[3]++;
				}
				else if(rank >67 && rank <=81){
					 scale[4]++;
				}
				else if(rank >81 && rank <=97){
					 scale[5]++;
				}
				else if(rank >97 && rank <=113){
					 scale[6]++;
				}
				else if(rank > 113 && rank <=127){
					 scale[7]++;
				}
				else if(rank > 127 && rank <= 139){
					 scale[8]++;
				}
				else if(rank == 140){
					 scale[9]++;

				}
		  }
		  ave = (double)sum/(double)MCTRIALS;
		  if(ave > maxave){
				maxave = ave;
				bestType = i;
				for(z = 0;z<10;z++){
					 if (scale[z] > maxscale){
						  maxscale = scale[z];
						  scalenum = z;
					 }
				}
				avebucket = (double) maxscale / (double)MCTRIALS;
				if (avebucket > bestprob){
					 bestprob = avebucket;
					 person->probnum = scale[scalenum];
				}
		  }
	 }
	 person->mc_reco[0] = choices[bestType][0];
	 person->mc_reco[1] = choices[bestType][1];
	 person->mc_reco[2] = choices[bestType][2];
	 person->mc_reco[3] = choices[bestType][3];
	 person->mc_reco[4] = choices[bestType][4];
	 person->bestprob = bestprob;
	 return maxave;
}
예제 #12
0
파일: cards.c 프로젝트: sway4ka/card-desk
int main(int argc, char *argv[]) {

	int argv2;
	sscanf(argv[2], "%d", &argv2);


	// //variant 1 - peremewat' karti
	if (argv2 == 1) {

		// zapominaem file s kartami v strokovii massiv cards[][]
		char cards[NUM_CARDS][LEN_STRING];
		read_main_file(cards);

		//perezapisivaem massiv obratno v fail v sly4ainom poryadke
		shuffle(cards);
	}


	// razda4a kart igrokam
	if (argv2 == 2) {

		// zapominaem file s kartami v strokovii massiv cards[][]
		char cards[NUM_CARDS][LEN_STRING];
		read_main_file(cards);

		//izvlekaem koli4estvo igrokov i koli4estvo razdavaemih kart
		int argv3, argv4;
		sscanf(argv[3], "%d", &argv3);
		sscanf(argv[4], "%d", &argv4);

		int num_gamers = argv3;
		int num_cards_for_gamer = argv4;

		// generiruem imena failov igrokov 
		char file_list[num_gamers][LEN_STRING];
		generation_file_names(file_list, num_gamers);

		// zapisivaem karti v faili igrokov
		card_to_gamers(cards, file_list, num_gamers, num_cards_for_gamer);

		// perezapisivaem v fail nerozdannie karti 
		rest_cards(cards, num_gamers, num_cards_for_gamer);
	}


 	//zabiraem karti y igrokov
	if (argv2 == 3) {

		int argv3;
		sscanf(argv[3], "%d",&argv3);
		int num_gamers = argv3;

	//sozdaem massiv nazvanii failov igrokov
		char file_list[num_gamers][LEN_STRING];
		get_file_list(argv, file_list, num_gamers);

	//dopisivaem karti igrokov v fail s kolodoi kart
		return_cards(file_list, num_gamers);
	}

	return EXIT_SUCCESS;
}
예제 #13
0
/* ######################################################################### */
static int htrans(int a[],int nx,int ny)
{
int nmax, log2n, h0, hx, hy, hc, nxtop, nytop, i, j, k;
int oddx, oddy;
int shift, mask, mask2, prnd, prnd2, nrnd2;
int s10, s00;
int *tmp;

	/*
	 * log2n is log2 of max(nx,ny) rounded up to next power of 2
	 */
	nmax = (nx>ny) ? nx : ny;
	log2n = (int) (log((float) nmax)/log(2.0)+0.5);
	if ( nmax > (1<<log2n) ) {
		log2n += 1;
	}
	/*
	 * get temporary storage for shuffling elements
	 */
	tmp = (int *) malloc(((nmax+1)/2)*sizeof(int));
	if(tmp == (int *) NULL) {
	        ffpmsg("htrans: insufficient memory");
		return(DATA_COMPRESSION_ERR);
	}
	/*
	 * set up rounding and shifting masks
	 */
	shift = 0;
	mask  = -2;
	mask2 = mask << 1;
	prnd  = 1;
	prnd2 = prnd << 1;
	nrnd2 = prnd2 - 1;
	/*
	 * do log2n reductions
	 *
	 * We're indexing a as a 2-D array with dimensions (nx,ny).
	 */
	nxtop = nx;
	nytop = ny;

	for (k = 0; k<log2n; k++) {
		oddx = nxtop % 2;
		oddy = nytop % 2;
		for (i = 0; i<nxtop-oddx; i += 2) {
			s00 = i*ny;				/* s00 is index of a[i,j]	*/
			s10 = s00+ny;			/* s10 is index of a[i+1,j]	*/
			for (j = 0; j<nytop-oddy; j += 2) {
				/*
				 * Divide h0,hx,hy,hc by 2 (1 the first time through).
				 */
				h0 = (a[s10+1] + a[s10] + a[s00+1] + a[s00]) >> shift;
				hx = (a[s10+1] + a[s10] - a[s00+1] - a[s00]) >> shift;
				hy = (a[s10+1] - a[s10] + a[s00+1] - a[s00]) >> shift;
				hc = (a[s10+1] - a[s10] - a[s00+1] + a[s00]) >> shift;

				/*
				 * Throw away the 2 bottom bits of h0, bottom bit of hx,hy.
				 * To get rounding to be same for positive and negative
				 * numbers, nrnd2 = prnd2 - 1.
				 */
				a[s10+1] = hc;
				a[s10  ] = ( (hx>=0) ? (hx+prnd)  :  hx        ) & mask ;
				a[s00+1] = ( (hy>=0) ? (hy+prnd)  :  hy        ) & mask ;
				a[s00  ] = ( (h0>=0) ? (h0+prnd2) : (h0+nrnd2) ) & mask2;
				s00 += 2;
				s10 += 2;
			}
			if (oddy) {
				/*
				 * do last element in row if row length is odd
				 * s00+1, s10+1 are off edge
				 */
				h0 = (a[s10] + a[s00]) << (1-shift);
				hx = (a[s10] - a[s00]) << (1-shift);
				a[s10  ] = ( (hx>=0) ? (hx+prnd)  :  hx        ) & mask ;
				a[s00  ] = ( (h0>=0) ? (h0+prnd2) : (h0+nrnd2) ) & mask2;
				s00 += 1;
				s10 += 1;
			}
		}
		if (oddx) {
			/*
			 * do last row if column length is odd
			 * s10, s10+1 are off edge
			 */
			s00 = i*ny;
			for (j = 0; j<nytop-oddy; j += 2) {
				h0 = (a[s00+1] + a[s00]) << (1-shift);
				hy = (a[s00+1] - a[s00]) << (1-shift);
				a[s00+1] = ( (hy>=0) ? (hy+prnd)  :  hy        ) & mask ;
				a[s00  ] = ( (h0>=0) ? (h0+prnd2) : (h0+nrnd2) ) & mask2;
				s00 += 2;
			}
			if (oddy) {
				/*
				 * do corner element if both row and column lengths are odd
				 * s00+1, s10, s10+1 are off edge
				 */
				h0 = a[s00] << (2-shift);
				a[s00  ] = ( (h0>=0) ? (h0+prnd2) : (h0+nrnd2) ) & mask2;
			}
		}
		/*
		 * now shuffle in each dimension to group coefficients by order
		 */
		for (i = 0; i<nxtop; i++) {
			shuffle(&a[ny*i],nytop,1,tmp);
		}
		for (j = 0; j<nytop; j++) {
			shuffle(&a[j],nxtop,ny,tmp);
		}
		/*
		 * image size reduced by 2 (round up if odd)
		 */
		nxtop = (nxtop+1)>>1;
		nytop = (nytop+1)>>1;
		/*
		 * divisor doubles after first reduction
		 */
		shift = 1;
		/*
		 * masks, rounding values double after each iteration
		 */
		mask  = mask2;
		prnd  = prnd2;
		mask2 = mask2 << 1;
		prnd2 = prnd2 << 1;
		nrnd2 = prnd2 - 1;
	}
	free(tmp);
	return(0);
}
예제 #14
0
static int docset_check(Db *db, DocInfo *info, void *ctx)
{
    int errcode = 0;
    docset *ds = ctx;
    counterset *ctr = &ds->counters;
    ctr->totaldocs++;
    if (info->deleted) {
        ctr->deleted++;
    }
    EQUAL_INFO_BUF(id);
    EQUAL_INFO_BUF(rev_meta);
    Doc *doc;
    try(couchstore_open_doc_with_docinfo(db, info, &doc, DECOMPRESS_DOC_BODIES));
    if (testdocset.docs[testdocset.pos].data.size > 0) {
        assert(doc);
        EQUAL_DOC_BUF(data);
        EQUAL_DOC_BUF(id);
    }
    testdocset.pos++;
    couchstore_free_document(doc);
cleanup:
    assert(errcode == 0);
    return 0;
}

static int dociter_check(Db *db, DocInfo *info, void *ctx)
{
    int errcode = 0;
    docset *ds = ctx;
    counterset *ctr = &ds->counters;
    ctr->totaldocs++;
    if (info->deleted) {
        ctr->deleted++;
    }
    Doc *doc;
    try(couchstore_open_doc_with_docinfo(db, info, &doc, DECOMPRESS_DOC_BODIES));
    assert(doc);
    couchstore_free_document(doc);
cleanup:
    assert(errcode == 0);
    return 0;
}

static int dump_count(Db *db)
{
    int errcode = 0;
    ZERO(counters);
    try(couchstore_changes_since(db, 0, 0, counter_inc, &counters));
cleanup:
    assert(errcode == 0);
    return errcode;
}

static char zerometa[] = {0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3};

static void test_save_docs(int count, const char *doc_tpl)
{
    int errcode = 0;
    int i;
    char *idBuf, *valueBuf;
    Doc **docptrs;
    DocInfo **nfoptrs;
    sized_buf *ids;
    uint64_t idtreesize = 0;
    uint64_t seqtreesize = 0;
    uint64_t docssize = 0;
    uint64_t dbfilesize = 0;
    uint64_t *sequences = NULL;

    fprintf(stderr, "save_docs (doc count %d)... ", count);
    fflush(stderr);

    docset_init(count);
    srandom(0xdeadbeef);  // doc IDs should be consistent across runs
    for (i = 0; i < count; ++i) {
        idBuf = (char *) malloc(sizeof(char) * 32);
        assert(idBuf != NULL);
        int idsize = sprintf(idBuf, "doc%d-%lu", i, (unsigned long)random());
        valueBuf = (char *) malloc(sizeof(char) * (strlen(doc_tpl) + 20));
        assert(valueBuf != NULL);
        int valsize = sprintf(valueBuf, doc_tpl, i + 1);
        setdoc(&testdocset.docs[i], &testdocset.infos[i],
                idBuf, idsize, valueBuf, valsize, zerometa, sizeof(zerometa));
        testdocset.datasize += valsize;
    }

    docptrs = (Doc **) malloc(sizeof(Doc*) * count);
    assert(docptrs != NULL);
    for (i = 0; i < count; ++i) {
        docptrs[i] = &testdocset.docs[i];
    }

    nfoptrs = (DocInfo **) malloc(sizeof(DocInfo*) * count);
    assert(nfoptrs != NULL);
    for (i = 0; i < count; ++i) {
        nfoptrs[i] = &testdocset.infos[i];
    }

    unlink(testfilepath);
    Db *db;
    try(couchstore_open_db(testfilepath, COUCHSTORE_OPEN_FLAG_CREATE, &db));
    assert(strcmp(couchstore_get_db_filename(db), testfilepath) == 0);
    try(couchstore_save_documents(db, docptrs, nfoptrs, count, 0));
    try(couchstore_commit(db));
    couchstore_close_db(db);

    try(couchstore_open_db(testfilepath, 0, &db));

    // Read back by doc ID:
    fprintf(stderr, "get by ID... ");
    testdocset.pos = 0;
    for (i = 0; i < count; ++i) {
        DocInfo* out_info;
        try(couchstore_docinfo_by_id(db, testdocset.docs[i].id.buf, testdocset.docs[i].id.size,
                                     &out_info));
        docset_check(db, out_info, &testdocset);
        couchstore_free_docinfo(out_info);
    }

    // Read back in bulk by doc ID:
    fprintf(stderr, "bulk IDs... ");
    ids = malloc(count * sizeof(sized_buf));
    for (i = 0; i < count; ++i) {
        ids[i] = docptrs[i]->id;
    }
    ZERO(testdocset.counters);
    try(couchstore_docinfos_by_id(db, ids, count, 0, dociter_check, &testdocset));
    assert(testdocset.counters.totaldocs == count);
    assert(testdocset.counters.deleted == 0);

    // Read back by sequence:
    fprintf(stderr, "get by sequence... ");
    sequences = malloc(count * sizeof(*sequences));
    testdocset.pos = 0;
    for (i = 0; i < count; ++i) {
        DocInfo* out_info;
        sequences[i] = testdocset.infos[i].db_seq;
        assert(sequences[i] == (uint64_t)i + 1);
        try(couchstore_docinfo_by_sequence(db, testdocset.infos[i].db_seq, &out_info));
        docset_check(db, out_info, &testdocset);
        couchstore_free_docinfo(out_info);
    }

    // Read back in bulk by sequence:
    fprintf(stderr, "bulk sequences... ");
    testdocset.pos = 0;
    ZERO(testdocset.counters);
    try(couchstore_docinfos_by_sequence(db, sequences, count, 0, docset_check, &testdocset));
    assert(testdocset.counters.totaldocs == count);
    assert(testdocset.counters.deleted == 0);

    // Read back using changes_since:
    fprintf(stderr, "changes_since... ");
    testdocset.pos = 0;
    ZERO(testdocset.counters);
    try(couchstore_changes_since(db, 0, 0, docset_check, &testdocset));
    assert(testdocset.counters.totaldocs == count);
    assert(testdocset.counters.deleted == 0);

    idtreesize = db->header.by_id_root->subtreesize;
    seqtreesize = db->header.by_seq_root->subtreesize;
    const raw_by_id_reduce *reduce = (const raw_by_id_reduce*)db->header.by_id_root->reduce_value.buf;
    docssize = decode_raw48(reduce->size);
    dbfilesize = db->file_pos;

    assert(dbfilesize > 0);
    assert(idtreesize > 0);
    assert(seqtreesize > 0);
    assert(docssize > 0);
    assert(idtreesize < dbfilesize);
    assert(seqtreesize < dbfilesize);
    assert(docssize < dbfilesize);
    assert(db->header.local_docs_root == NULL);
    assert((idtreesize + seqtreesize + docssize) < dbfilesize);

    couchstore_close_db(db);
cleanup:
    free(ids);
    free(sequences);
    for (i = 0; i < count; ++i) {
        free(docptrs[i]->id.buf);
        free(docptrs[i]->data.buf);
    }
    free(docptrs);
    free(nfoptrs);
    assert(errcode == 0);
}

static void test_save_doc(void)
{
    fprintf(stderr, "save_doc... ");
    fflush(stderr);
    int errcode = 0;
    docset_init(4);
    SETDOC(0, "doc1", "{\"test_doc_index\":1}", zerometa);
    SETDOC(1, "doc2", "{\"test_doc_index\":2}", zerometa);
    SETDOC(2, "doc3", "{\"test_doc_index\":3}", zerometa);
    SETDOC(3, "doc4", "{\"test_doc_index\":4}", zerometa);
    unlink(testfilepath);
    Db *db;
    try(couchstore_open_db(testfilepath, COUCHSTORE_OPEN_FLAG_CREATE, &db));
    try(couchstore_save_document(db, &testdocset.docs[0],
                                     &testdocset.infos[0], 0));
    try(couchstore_save_document(db, &testdocset.docs[1],
                                     &testdocset.infos[1], 0));
    try(couchstore_save_document(db, &testdocset.docs[2],
                                     &testdocset.infos[2], 0));
    try(couchstore_save_document(db, &testdocset.docs[3],
                                     &testdocset.infos[3], 0));
    try(couchstore_commit(db));
    couchstore_close_db(db);

    // Check that sequence numbers got filled in
    unsigned i;
    for (i = 0; i < 4; ++i) {
        assert(testdocset.infos[i].db_seq == i + 1);
    }

    //Read back
    try(couchstore_open_db(testfilepath, 0, &db));
    try(couchstore_changes_since(db, 0, 0, docset_check, &testdocset));
    assert(testdocset.counters.totaldocs == 4);
    assert(testdocset.counters.deleted == 0);

    DbInfo info;
    assert(couchstore_db_info(db, &info) == COUCHSTORE_SUCCESS);
    assert(info.last_sequence == 4);
    assert(info.doc_count == 4);
    assert(info.deleted_count == 0);
    assert(info.header_position == 4096);

    couchstore_close_db(db);
cleanup:
    assert(errcode == 0);
}

static void test_compressed_doc_body(void)
{
    fprintf(stderr, "compressed bodies... ");
    fflush(stderr);
    int errcode = 0;
    docset_init(2);
    SETDOC(0, "doc1", "{\"test_doc_index\":1, \"val\":\"blah blah blah blah blah blah\"}", zerometa);
    SETDOC(1, "doc2", "{\"test_doc_index\":2, \"val\":\"blah blah blah blah blah blah\"}", zerometa);
    Doc *docptrs [2] =  { &testdocset.docs[0],
                          &testdocset.docs[1]
                        };
    DocInfo *nfoptrs [2] =  { &testdocset.infos[0],
                              &testdocset.infos[1]
                            };
    testdocset.infos[1].content_meta = COUCH_DOC_IS_COMPRESSED; //Mark doc2 as to be snappied.
    unlink(testfilepath);
    Db *db;
    try(couchstore_open_db(testfilepath, COUCHSTORE_OPEN_FLAG_CREATE, &db));
    try(couchstore_save_documents(db, docptrs, nfoptrs, 2,
                                      COMPRESS_DOC_BODIES));
    try(couchstore_commit(db));
    couchstore_close_db(db);
    //Read back
    try(couchstore_open_db(testfilepath, 0, &db));
    try(couchstore_changes_since(db, 0, 0, docset_check, &testdocset));
    assert(testdocset.counters.totaldocs == 2);
    assert(testdocset.counters.deleted == 0);
    couchstore_close_db(db);
cleanup:
    assert(errcode == 0);
}

static void test_dump_empty_db(void)
{
    fprintf(stderr, "dump empty db... ");
    fflush(stderr);
    unlink(testfilepath);
    Db *db;
    couchstore_error_t errcode;
    
    try(couchstore_open_db(testfilepath, COUCHSTORE_OPEN_FLAG_CREATE, &db));
    try(couchstore_close_db(db));
    try(couchstore_open_db(testfilepath, 0, &db));
    dump_count(db);
    assert(counters.totaldocs == 0);
    assert(counters.deleted == 0);

    DbInfo info;
    assert(couchstore_db_info(db, &info) == COUCHSTORE_SUCCESS);
    assert(strcmp(info.filename, testfilepath) == 0);
    assert(info.last_sequence == 0);
    assert(info.doc_count == 0);
    assert(info.deleted_count == 0);
    assert(info.space_used == 0);
    assert(info.header_position == 0);

    couchstore_close_db(db);
cleanup:
    assert(errcode == 0);
}

static void test_local_docs(void)
{
    fprintf(stderr, "local docs... ");
    fflush(stderr);
    int errcode = 0;
    Db *db;
    LocalDoc lDocWrite;
    LocalDoc *lDocRead = NULL;
    unlink(testfilepath);
    try(couchstore_open_db(testfilepath, COUCHSTORE_OPEN_FLAG_CREATE, &db));
    lDocWrite.id.buf = "_local/testlocal";
    lDocWrite.id.size = 16;
    lDocWrite.json.buf = "{\"test\":true}";
    lDocWrite.json.size = 13;
    lDocWrite.deleted = 0;
    couchstore_save_local_document(db, &lDocWrite);
    couchstore_commit(db);
    couchstore_close_db(db);
    couchstore_open_db(testfilepath, 0, &db);
    couchstore_open_local_document(db, "_local/testlocal", 16, &lDocRead);
    assert(lDocRead);
    assert(lDocRead->json.size == 13);
    assert(memcmp(lDocRead->json.buf, "{\"test\":true}", 13) == 0);
    couchstore_free_local_document(lDocRead);
    couchstore_close_db(db);
cleanup:
    assert(errcode == 0);
}

static void test_open_file_error(void)
{
    fprintf(stderr, "opening nonexistent file errors... ");
    fflush(stderr);
    unlink(testfilepath);
    Db *db;
    int errcode = couchstore_open_db(testfilepath, 0, &db);

    if(errcode != 0) {
        print_os_err();
    }

    assert(errcode == COUCHSTORE_ERROR_NO_SUCH_FILE);

    // make sure os.c didn't accidentally call close(0):
    assert(lseek(0, 0, SEEK_CUR) >= 0 || errno != EBADF);
}

static void shuffle(Doc **docs, DocInfo **docinfos, size_t n)
{
    if (n > 1) {
        size_t i;
        for (i = 0; i < n - 1; i++) {
          size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
          DocInfo *docinfo;
          Doc *doc = docs[j];
          docs[j] = docs[i];
          docs[i] = doc;

          docinfo = docinfos[j];
          docinfos[j] = docinfos[i];
          docinfos[i] = docinfo;
        }
    }
}

static int docmap_check(Db *db, DocInfo *info, void *ctx)
{
    (void)db;
    char* docmap = (char*)ctx;
    int i;
    char buffer[100];
    memcpy(buffer, info->id.buf, info->id.size);
    buffer[info->id.size] = 0; // null terminate
    sscanf(buffer, "doc%d", &i);
    assert(docmap[i] == 0);
    docmap[i] = 1;
    return 0;
}

static void test_changes_no_dups(void)
{
    fprintf(stderr, "changes no dupes... ");
    fflush(stderr);
    int errcode = 0;
    int i;
    const int numdocs = 10000;
    int updatebatch = 1000;
    Doc **docptrs;
    DocInfo **nfoptrs;
    char *docmap;
    Db *db;
    docset_init(numdocs);
    for (i=0; i < numdocs; i++) {
        char* id = malloc(100);
        char* body = malloc(100);
        sprintf(id, "doc%d", i);
        sprintf(body, "{\"test_doc_index\":%d}", i);
        setdoc(&testdocset.docs[i], &testdocset.infos[i],
                id, strlen(id),
                body, strlen(body),
                zerometa, sizeof(zerometa));
    }
    docptrs = malloc(numdocs * sizeof(Doc*));
    nfoptrs = malloc(numdocs * sizeof(DocInfo*));
    docmap = malloc(numdocs);
    for (i=0; i < numdocs; i++) {
        docptrs[i] = &testdocset.docs[i];
        nfoptrs[i] = &testdocset.infos[i];
    }
    unlink(testfilepath);
    try(couchstore_open_db(testfilepath, COUCHSTORE_OPEN_FLAG_CREATE, &db));
    // only save half the docs at first.
    try(couchstore_save_documents(db, docptrs, nfoptrs, numdocs/2, 0));
    try(couchstore_commit(db));
    couchstore_close_db(db);

    for (i=0; i < numdocs/2; i++) {
        // increment the rev for already added docs
        nfoptrs[i]->rev_seq++;
    }
    srand(10); // make deterministic
    // now shuffle so some bulk updates contain previous docs and new docs
    shuffle(docptrs, nfoptrs, numdocs);
    try(couchstore_open_db(testfilepath, 0, &db));
    for (i=0; i < numdocs; i += updatebatch) {
        // now do bulk updates and check the changes for dups
        try(couchstore_save_documents(db, docptrs + i, nfoptrs + i, updatebatch, 0));
        try(couchstore_commit(db));
        memset(docmap, 0, numdocs);
        try(couchstore_changes_since(db, 0, 0, docmap_check, docmap));
    }

    DbInfo info;
    assert(couchstore_db_info(db, &info) == COUCHSTORE_SUCCESS);
    assert(info.last_sequence == (uint64_t)(numdocs + numdocs/2));
    assert(info.doc_count == (uint64_t)numdocs);
    assert(info.deleted_count == 0);

    couchstore_close_db(db);
cleanup:
    for (i=0; i < numdocs; i++) {
        free(docptrs[i]->id.buf);
        free(docptrs[i]->data.buf);
    }
    free(docptrs);
    free(nfoptrs);
    free(docmap);
    assert(errcode == 0);
}


static void mb5086(void)
{
    Db *db;
    Doc d;
    DocInfo i;
    couchstore_error_t err;

    fprintf(stderr, "regression mb-5086.... ");
    fflush(stderr);

    setdoc(&d, &i, "hi", 2, "foo", 3, NULL, 0);
    err = couchstore_open_db("mb5085.couch", COUCHSTORE_OPEN_FLAG_CREATE, &db);
    assert(err == COUCHSTORE_SUCCESS);
    assert(couchstore_save_document(db, &d, &i, 0) == COUCHSTORE_SUCCESS);
    assert(couchstore_commit(db) == COUCHSTORE_SUCCESS);
    assert(couchstore_close_db(db) == COUCHSTORE_SUCCESS);
    assert(remove("mb5085.couch") == 0);
}

static void test_huge_revseq(void)
{
    Db *db;
    Doc d;
    DocInfo i;
    DocInfo *i2;
    couchstore_error_t err;

    fprintf(stderr, "huge rev_seq.... ");
    fflush(stderr);

    setdoc(&d, &i, "hi", 2, "foo", 3, NULL, 0);
    i.rev_seq = 5294967296;

    err = couchstore_open_db("bigrevseq.couch", COUCHSTORE_OPEN_FLAG_CREATE, &db);
    assert(err == COUCHSTORE_SUCCESS);
    assert(couchstore_save_document(db, &d, &i, 0) == COUCHSTORE_SUCCESS);
    assert(couchstore_commit(db) == COUCHSTORE_SUCCESS);
    assert(couchstore_docinfo_by_id(db, "hi", 2, &i2) == COUCHSTORE_SUCCESS);
    assert(i2->rev_seq == 5294967296);
    couchstore_free_docinfo(i2);
    assert(couchstore_close_db(db) == COUCHSTORE_SUCCESS);
    assert(remove("bigrevseq.couch") == 0);
}


int main(int argc, const char *argv[])
{
    int doc_counts[] = { 4, 69, 666, 9090 };
    unsigned i;
    const char *small_doc_tpl = "{\"test_doc_index\":%d}";
    const char *large_doc_tpl =
        "{"
        "\"test_doc_index\":%d,"
        "\"field1\": \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\","
        "\"field2\": \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\","
        "\"field3\": \"cccccccccccccccccccccccccccccccccccccccccccccccccc"
        "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
        "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
        "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
        "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
        "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
        "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\""
        "}";

    if (argc > 1)
        strcpy(testfilepath, argv[1]);
    printf("Using test database at %s\n", testfilepath);

    test_bitfield_fns();

    test_open_file_error();
    fprintf(stderr, "OK \n");
    test_dump_empty_db();
    fprintf(stderr, " OK\n");
    test_save_doc();
    fprintf(stderr, " OK\n");
    for (i = 0; i < (sizeof(doc_counts) / sizeof(int)); ++i) {
        test_save_docs(doc_counts[i], small_doc_tpl);
        fprintf(stderr, " OK\n");
        test_save_docs(doc_counts[i], large_doc_tpl);
        fprintf(stderr, " OK\n");
    }
    test_local_docs();
    fprintf(stderr, " OK\n");
    test_compressed_doc_body();
    fprintf(stderr, " OK\n");
    test_changes_no_dups();
    fprintf(stderr, " OK\n");
    mb5086();
    fprintf(stderr, " OK\n");
    unlink(testfilepath);
    test_huge_revseq();
    fprintf(stderr, " OK\n");
    unlink(testfilepath);

    // make sure os.c didn't accidentally call close(0):
    assert(lseek(0, 0, SEEK_CUR) >= 0 || errno != EBADF);

    return 0;
}
int initializeGame(int numPlayers, int kingdomCards[10], int randomSeed,
		   struct gameState *state) {

  int i;
  int j;
  int it;			
  //set up random number generator
  SelectStream(1);
  PutSeed((long)randomSeed);
  
  //check number of players
  if (numPlayers > MAX_PLAYERS || numPlayers < 2)
    {
      return -1;
    }

  //set number of players
  state->numPlayers = numPlayers;

  //check selected kingdom cards are different
  for (i = 0; i < 10; i++)
    {
      for (j = 0; j < 10; j++)
        {
	  if (j != i && kingdomCards[j] == kingdomCards[i])
	    {
	      return -1;
	    }
        }
    }


  //initialize supply
  ///////////////////////////////

  //set number of Curse cards
  if (numPlayers == 2)
    {
      state->supplyCount[curse] = 10;
    }
  else if (numPlayers == 3)
    {
      state->supplyCount[curse] = 20;
    }
  else
    {
      state->supplyCount[curse] = 30;
    }

  //set number of Victory cards
  if (numPlayers == 2)
    {
      state->supplyCount[estate] = 8;
      state->supplyCount[duchy] = 8;
      state->supplyCount[province] = 8;
    }
  else
    {
      state->supplyCount[estate] = 12;
      state->supplyCount[duchy] = 12;
      state->supplyCount[province] = 12;
    }

  //set number of Treasure cards
  state->supplyCount[copper] = 60 - (7 * numPlayers);
  state->supplyCount[silver] = 40;
  state->supplyCount[gold] = 30;

  //set number of Kingdom cards
  for (i = adventurer; i <= treasure_map; i++)       	//loop all cards
    {
      for (j = 0; j < 10; j++)           		//loop chosen cards
	{
	  if (kingdomCards[j] == i)
	    {
	      //check if card is a 'Victory' Kingdom card
	      if (kingdomCards[j] == great_hall || kingdomCards[j] == gardens)
		{
		  if (numPlayers == 2){ 
		    state->supplyCount[i] = 8; 
		  }
		  else{ state->supplyCount[i] = 12; }
		}
	      else
		{
		  state->supplyCount[i] = 10;
		}
	      break;
	    }
	  else    //card is not in the set choosen for the game
	    {
	      state->supplyCount[i] = -1;
	    }
	}

    }

  ////////////////////////
  //supply intilization complete

  //set player decks
  for (i = 0; i < numPlayers; i++)
    {
      state->deckCount[i] = 0;
      for (j = 0; j < 3; j++)
	{
	  state->deck[i][j] = estate;
	  state->deckCount[i]++;
	}
      for (j = 3; j < 10; j++)
	{
	  state->deck[i][j] = copper;
	  state->deckCount[i]++;		
	}
    }

  //shuffle player decks
  for (i = 0; i < numPlayers; i++)
 /* MUTANT (rep_op) */        for (i = 0; i != numPlayers; i++)
      if ( shuffle(i, state) < 0 )
	{
	  return -1;
	}
    }
예제 #16
0
/////////////////////////////////////////////////////////
// processImage
//
/////////////////////////////////////////////////////////
void pix_puzzle :: processYUVImage(imageStruct &image)
{
  unsigned char *src = image.data;
  unsigned char *dest;

  int x, y, xx, yy, i;
  unsigned char *p, *q;

  if (m_force || (myImage.xsize*myImage.ysize*myImage.csize != image.xsize*image.ysize*image.csize)){
    myImage.clear();
    m_force = false;

    myImage.xsize = image.xsize;
    myImage.ysize = image.ysize;
    myImage.setCsizeByFormat(image.format);
    myImage.reallocate();

    makePuzzleBlocks(image.xsize, image.ysize, image.csize);
    shuffle();
  }

  myImage.xsize = image.xsize;
  myImage.ysize = image.ysize;
  myImage.setCsizeByFormat(image.format);

  dest = myImage.data;

  i=0;
  for (y=0; y<blockh; y++){
    for(x=0; x<blockw; x++) {
      p = &src[blockoffset[blockpos[i]]];
      q = &dest[blockoffset[i]];
      if(m_game && spacepos == i) { // leave one rectangle blank (for the puzzle game)
	for(yy=0; yy<blockysize; yy++) {
	  for(xx=0; xx<blockxsize*image.csize; xx++) {
	    q[xx] = 0;
	  }
	  q += image.xsize*image.csize;
	}
      } else {
	for(yy=0; yy<blockysize; yy++) {
	  for(xx=0; xx<blockxsize*image.csize; xx++) {
	    q[xx] = p[xx];
	  }
	  q += image.xsize*image.csize;
	  p += image.xsize*image.csize;
	}
      }
      i++;
    }
  }

  p = src +  blockw * blockxsize;
  q = dest + blockw * blockxsize;

  if(marginw) {
    for(y=0; y<blockh*blockysize; y++) {
      for(x=0; x<marginw; x++) {
	*q++ = *p++;
      }
      p += image.xsize - marginw;
      q += image.xsize - marginw;
    }
  }

  if(marginh) {
    p = src + (blockh * blockysize) * image.xsize;
    q = dest + (blockh * blockysize) * image.xsize;
    memcpy(p, q, marginh*image.xsize*image.csize);
  }

  image.data=myImage.data;
}