Exemplo n.º 1
0
int main(){
    struct player *players;
    struct card *deck;
    //struct player computer;
    int numPlayers;
    int i;


    deck = createDeck();
    shuffleDeck(deck);
    printf("__WELCOME_TO_HENRY'S_BLACK_JACK_GAME__\n");     
    printf("How many players? (MAX 5)\n");
    scanf("%d", &numPlayers);
     while(numPlayers < 1 || numPlayers > 5){
       printf("Minimum 1, Maximum 5\n");
       scanf("%d", &numPlayers);
     }
    players = makePlayers(numPlayers);
    printf("number of players %d\n", numPlayers);
    printf("_________LETS_PLAY_BLACK_JACK!________\n");
    for(i=0;i<numPlayers;i++){
      players[i].playersCards = NULL;
      players[i].amountCard = 2; //varför fungerar du inte?=
      printf("player: %s\n", players[i].name);
      dealCards(players[i].playersCards,deck,players[i].amountCard);
    }

    free(deck);
    free(players);
    return 0;
}
Exemplo n.º 2
0
Game::Game(float bet, float firstBet, int players, Player* player) : bet(bet), firstBet(firstBet), players(players), player(player)
{
	if (players != 0)
	{
		this->player = new Player[players];
		this->player = player;
		dealCards(); //time to deal cards to our players
	}
}
Exemplo n.º 3
0
int actDealer(struct player anyone, struct card *aDeck, int *counter, int pullLimit){ //
  char choice = 'h';
  int stay = 1;
  printf("%s TURN:\n", anyone.name);
  printCards(anyone.playerHand, anyone.startCards);
  checkHand(anyone.playerHand, anyone.startCards, &anyone.cardValue);
 /* Players  */
  if(pullLimit == 21){          
    if(anyone.cardValue == 21 && anyone.startCards == 2){   // check if Black Jack
      printf("BLACK JACK!\n");
      stay = 0;
    }
    while(choice == 'h' && stay == 1){           // gives,prints and updates card values while player types 'h'
      printf("Hit or stay? (h/s)\n");
      scanf("%c",&choice);
      getchar();
      if(choice == 'h' && anyone.cardValue <= 20){
        dealCards(&anyone, aDeck, counter);
        printCards(anyone.playerHand, anyone.startCards);
        checkHand(anyone.playerHand, anyone.startCards, &anyone.cardValue);
         
        if(anyone.cardValue > 20 || anyone.cardValue == -1)// if player is busted leave loop
            stay = 0;
          
      }
    }
  }

  /* Dealer */
  while(pullLimit < 18 && stay){
    while(anyone.cardValue < 16){                       // dealer has to pull until cardvalue > 16
        printf("Press enter to see next card\n");
        getchar();
        dealCards(&anyone, aDeck, counter);
        printCards(anyone.playerHand, anyone.startCards);
        checkHand(anyone.playerHand, anyone.startCards, &anyone.cardValue);
       }      
         stay = 0;
        
  }
  return anyone.cardValue;                // update cardvalue
}
Exemplo n.º 4
0
Arquivo: Deck.cpp Projeto: jbobrow/Set
void Deck::eventHandler(poEvent *event)
{
    switch (event->keyChar) {
    case ' ':
        removeAllCards();
        dealCards(12);
        updateNeededCards();
        printNeededRatios();
        break;

    case 'f':
        findSet();
        break;

    case 'u':
        updateNeededCards();
        printNeededRatios();
        break;

    case 'd':
        dealCards(12-cardsDealt.size());
        break;

    case 'a':
        dealCards(3);
        break;

    case 'p':
        Card *c1 = (Card *) cards[rand()%80];
        Card *c2 = (Card *) cards[rand()%80];
        Card *c3 = c1->findCardToCompleteSet(c2);
        if(c3 == NULL)	return;
        printf("--------------------------------------\n");
        printf("the card match for %i, %i, %i, %i\n", c1->_count, c1->_color, c1->_fill, c1->_shape);
        printf("               and %i, %i, %i, %i\n", c2->_count, c2->_color, c2->_fill, c2->_shape);
        printf("               is  %i, %i, %i, %i\n", c3->_count, c3->_color, c3->_fill, c3->_shape);
        printf("--------------------------------------\n");
        break;
    }
}
Exemplo n.º 5
0
void BlackJack::newRound()
{ 
    deck.shuffle();
    takeBet();
    dealCards();
    showCards();

    while(control) {
        menu();
    }

    checkWin();
    newDeal();
}
Exemplo n.º 6
0
Arquivo: Deck.cpp Projeto: jbobrow/Set
Deck::Deck()
{
    bWithReplacement = false;
    bDrawHeatmap = false;

    numProperties = 4;
    numOptions = 3;

    poRandSeed();

    createCards();
    //printDeck();

    dealCards(12);
    updateNeededCards();
    printNeededRatios();

    addEvent(PO_KEY_DOWN_EVENT, this);
}
Exemplo n.º 7
0
/* returns >= 0 if match should continue, -1 for failure */
static int setUpNewHand( const Game *game, const uint8_t fixedSeats,
			 uint32_t *handId, uint8_t *player0Seat,
			 rng_state_t *rng, ErrorInfo *errorInfo, State *state )
{
  ++( *handId );

  /* rotate the players around the table */
  if( !fixedSeats ) {

    *player0Seat = ( *player0Seat + 1 ) % game->numPlayers;
  }

  if( checkErrorNewHand( game, errorInfo ) < 0 ) {

    fprintf( stderr, "ERROR: unexpected game\n" );
    return -1;
  }
  initState( game, *handId, state );
  dealCards( game, rng, state );

  return 0;
}
Exemplo n.º 8
0
void BridgeGame::beginPlay() {
	display = PLAYING;
	dealCards();

	// decide roles based on bids
	for (int i = 0; bidHistory[i] != NULL; i++) {
		if (bidHistory[i]->suit == finalBid->suit &&
			// make sure bid is made by player or partner!
			 (bidHistory[i]->player == finalBid->player ||
			 	bidHistory[i]->player == getPlayer(finalBid->player)->partner->name)) {
			for (int j = 0; j < NUM_PLAYERS; j++) {
				if (bidHistory[i]->player + j < NUM_PLAYERS) {
					getPlayer(bidHistory[i]->player + j)->role = j;
				} else {
					getPlayer(bidHistory[i]->player + j - 4)->role = j;
				}
			}

			break;
		}
	}
}
Exemplo n.º 9
0
void Room::UpdateThree(uint32 diff)
{
	threePlayerList::iterator itr = _threePlayerList.begin();
	for (threePlayerList::iterator itr = _threePlayerList.begin(),next; itr != _threePlayerList.end(); itr = next)
	{
		next = itr;
		next++;
		if (LogoutThree(*itr))
		{
			_threePlayerList.erase(itr);
			continue;
		}
		if (allStart(*itr) && allAtThree(*itr) && allWaitDealCards(*itr))
		{
			dealCards(*itr);
		}
		if (roundOver(*itr))
		{
			_threePlayerList.erase(itr);
		}
	}
}
Exemplo n.º 10
0
/* run a match of numHands hands of the supplied game

   cards are dealt using rng, error conditions like timeouts
   are controlled and stored in errorInfo

   actions are read/sent to seat p on seatFD[ p ]

   if quiet is not zero, only print out errors, warnings, and final value

   if logFile is not NULL, print out a single line for each completed
   match with the final state and all player values.  The values are
   printed in player, not seat order.

   if transactionFile is not NULL, a transaction log of actions made
   is written to the file, and if there is any input left to read on
   the stream when gameLoop is called, it will be processed to
   initialise the state

   returns >=0 if the match finished correctly, -1 on error */
static int gameLoop( const Game *game, char *seatName[ MAX_PLAYERS ],
		     const uint32_t numHands, const int quiet,
		     const int fixedSeats, rng_state_t *rng,
		     ErrorInfo *errorInfo, const int seatFD[ MAX_PLAYERS ],
		     ReadBuf *readBuf[ MAX_PLAYERS ],
		     FILE *logFile, FILE *transactionFile )
{
  uint32_t handId;
  uint8_t seat, p, player0Seat, currentP, currentSeat;
  struct timeval t, sendTime, recvTime;
  Action action;
  MatchState state;
  double value[ MAX_PLAYERS ], totalValue[ MAX_PLAYERS ];

  /* check version string for each player */
  for( seat = 0; seat < game->numPlayers; ++seat ) {

    if( checkVersion( seat, readBuf[ seat ] ) < 0 ) {
      /* error messages already handled in function */

      return -1;
    }
  }

  gettimeofday( &sendTime, NULL );
  if( !quiet ) {
    fprintf( stderr, "STARTED at %zu.%06zu\n",
	     sendTime.tv_sec, sendTime.tv_usec );
  }

  /* start at the first hand */
  handId = 0;
  if( checkErrorNewHand( game, errorInfo ) < 0 ) {

    fprintf( stderr, "ERROR: unexpected game\n" );
    return -1;
  }
  initState( game, handId, &state.state );
  dealCards( game, rng, &state.state );
  for( seat = 0; seat < game->numPlayers; ++seat ) {
    totalValue[ seat ] = 0.0;
  }

  /* seat 0 is player 0 in first game */
  player0Seat = 0;

  /* process the transaction file */
  if( transactionFile != NULL ) {

    if( processTransactionFile( game, fixedSeats, &handId, &player0Seat,
				rng, errorInfo, totalValue,
				&state, transactionFile ) < 0 ) {
      /* error messages already handled in function */

      return -1;
    }
  }

  if( handId >= numHands ) {
    goto finishedGameLoop;
  }

  /* play all the (remaining) hands */
  while( 1 ) {

    /* play the hand */
    while( !stateFinished( &state.state ) ) {

      /* find the current player */
      currentP = currentPlayer( game, &state.state );

      /* send state to each player */
      for( seat = 0; seat < game->numPlayers; ++seat ) {

	state.viewingPlayer = seatToPlayer( game, player0Seat, seat );
	if( sendPlayerMessage( game, &state, quiet, seat,
			       seatFD[ seat ], &t ) < 0 ) {
	  /* error messages already handled in function */

	  return -1;
	}

	/* remember the seat and send time if player is acting */
	if( state.viewingPlayer == currentP ) {

	  sendTime = t;
	}
      }

      /* get action from current player */
      state.viewingPlayer = currentP;
      currentSeat = playerToSeat( game, player0Seat, currentP );
      if( readPlayerResponse( game, &state, quiet, currentSeat, &sendTime,
			      errorInfo, readBuf[ currentSeat ],
			      &action, &recvTime ) < 0 ) {
	/* error messages already handled in function */

	return -1;
      }

      /* log the transaction */
      if( transactionFile != NULL ) {

	if( logTransaction( game, &state.state, &action,
			    &sendTime, &recvTime, transactionFile ) < 0 ) {
	  /* error messages already handled in function */

	  return -1;
	}
      }

      /* do the action */
      doAction( game, &action, &state.state );
    }

    /* get values */
    for( p = 0; p < game->numPlayers; ++p ) {

      value[ p ] = valueOfState( game, &state.state, p );
      totalValue[ playerToSeat( game, player0Seat, p ) ] += value[ p ];
    }

    /* add the game to the log */
    if( logFile != NULL ) {

      if( addToLogFile( game, &state.state, value, player0Seat,
			seatName, logFile ) < 0 ) {
	/* error messages already handled in function */

	return -1;
      }
    }

    /* send final state to each player */
    for( seat = 0; seat < game->numPlayers; ++seat ) {

      state.viewingPlayer = seatToPlayer( game, player0Seat, seat );
      if( sendPlayerMessage( game, &state, quiet, seat,
			     seatFD[ seat ], &t ) < 0 ) {
	/* error messages already handled in function */

	return -1;
      }
    }

    if ( !quiet ) {
      if ( handId % 100 == 0) {
	for( seat = 0; seat < game->numPlayers; ++seat ) {
	  fprintf(stderr, "Seconds cumulatively spent in match for seat %i: "
		  "%i\n", seat,
		  (int)(errorInfo->usedMatchMicros[ seat ] / 1000000));
	}
      }
    }

    /* start a new hand */
    if( setUpNewHand( game, fixedSeats, &handId, &player0Seat,
		      rng, errorInfo, &state.state ) < 0 ) {
      /* error messages already handled in function */

      return -1;
    }
    if( handId >= numHands ) {
      break;
    }
  }

 finishedGameLoop:
  /* print out the final values */
  if( !quiet ) {
    gettimeofday( &t, NULL );
    fprintf( stderr, "FINISHED at %zu.%06zu\n",
	     sendTime.tv_sec, sendTime.tv_usec );
  }
  if( printFinalMessage( game, seatName, totalValue, logFile ) < 0 ) {
    /* error messages already handled in function */

    return -1;
  }

  return 0;
}
Exemplo n.º 11
0
bool Engine::playCurrentRound()
{
#define CHECK_QUIT \
if (mQuit.get()) { \
    return false; \
}

    lock();
    if (!mCurrentRoundIndex) {
        mCurrentRoundIndex = &mRoundIndex;
        // prepare round data
        // pick current player as first attacker
        mAttackers.push_back(mCurrentPlayer);
        // if there was no deal yet (very first round) - do not consider cards while picking next players
        std::map<const PlayerId*, CardSet>* cards = *mCurrentRoundIndex ? &mPlayersCards : NULL;
        // pick next player as defender
        mDefender = Rules::pickNext(mGeneratedIds, mCurrentPlayer, cards);
        // gather rest players as additional attackers
        const PlayerId* attacker = mDefender;
        while((attacker = Rules::pickNext(mGeneratedIds, attacker, cards)) != mCurrentPlayer) {
            if (attacker) {
                mAttackers.push_back(attacker);
            }
        }
        unlock();
        std::for_each(mGameObservers.begin(), mGameObservers.end(), RoundStartNotification(mAttackers, mDefender, mRoundIndex));
        // deal cards
        dealCards();
        lock();
        mMaxAttackCards = Rules::maxAttackCards(mPlayersCards[mDefender].size());
        assert(mMaxAttackCards);
    }

    CardSet& defenderCards = mPlayersCards[mDefender];

    if (!mCurrentRoundAttackerId) {
        mCurrentRoundAttackerId = mAttackers[0];
        mPassedCounter = 0;
    }

    Player& defender = *mPlayers[mDefender];

    unlock();

    for (;;) {

        if (mTableCards.attackCards().size() == mMaxAttackCards) {
            // defender has no more cards - defend succeeded
            break;
        }

        const Card* attackCardPtr;

        if (mPickAttackCardFromTable) {
            assert(!mTableCards.attackCards().empty());
            attackCardPtr = &*(mTableCards.attackCards().end() - 1);
        } else {
            CardSet attackCards = Rules::getAttackCards(mTableCards.all(), mPlayersCards[mCurrentRoundAttackerId]);

            Player& currentAttacker = *mPlayers[mCurrentRoundAttackerId];

            if (mTableCards.empty()) {
                attackCardPtr = attackCards.empty() ? NULL : &currentAttacker.attack(mDefender, attackCards);
            } else {
                // ask for pitch even with empty attackCards - expected NULL attack card pointer
                attackCardPtr = currentAttacker.pitch(mDefender, attackCards);
            }

            // check if quit requested and only after that transfer move to defender
            CHECK_QUIT;

            if (attackCards.empty() || !attackCardPtr) {
                lock();
                // player skipped the move - pick next attacker
                mCurrentRoundAttackerId = Rules::pickNext(mAttackers, mCurrentRoundAttackerId, &mPlayersCards);
                // if more than one attacker and we have first attacker again - reset pass counter
                if (mAttackers.size() > 1 && mCurrentRoundAttackerId == mAttackers[0]) {
                    mPassedCounter = 0;
                }
                mPassedCounter++;
                unlock();

                if (mPassedCounter == mAttackers.size()) {
                    // all attackers "passed" - round ended
                    break;
                }
                continue;
            }

            assert(attackCardPtr);

            if(!findByPtr(attackCards, attackCardPtr)) {
                // invalid card returned - the card is not from attackCards
                assert(!attackCards.empty());
                // take any card
                attackCardPtr = &*attackCards.begin();
            }

            Card attackCard = *attackCardPtr;

            lock();
            mTableCards.addAttackCard(attackCard);
            mPlayersCards[mCurrentRoundAttackerId].erase(attackCard);
            unlock();
            CHECK_QUIT;
            std::for_each(mGameObservers.begin(), mGameObservers.end(), CardsDroppedNotification(mCurrentRoundAttackerId, attackCard));
            // the card is removed from the `attackCards` and is added to `mTableCards`, so update its pointer
            attackCardPtr = &*std::find(mTableCards.attackCards().begin(), mTableCards.attackCards().end(), attackCard);
        }

        if (mDefendFailed) {
            continue;
        }

        CardSet defendCards = Rules::getDefendCards(*attackCardPtr, defenderCards, mDeck->trumpSuit());

        const Card* defendCardPtr = defender.defend(mCurrentRoundAttackerId, *attackCardPtr, defendCards);

        bool noCardsToDefend = defendCards.empty();
        bool userGrabbedCards = !defendCardPtr;
        bool invalidDefendCard = !findByPtr(defendCards, defendCardPtr);

        lock();
        mPickAttackCardFromTable = false;
        unlock();

        if(noCardsToDefend || userGrabbedCards || invalidDefendCard) {
            // defend failed
            lock();
            mDefendFailed = true;
            unlock();
        } else {
            lock();
            mTableCards.addDefendCard(*defendCardPtr);
            defenderCards.erase(*defendCardPtr);
            unlock();
            CHECK_QUIT;
            std::for_each(mGameObservers.begin(), mGameObservers.end(), CardsDroppedNotification(mDefender, *defendCardPtr));
        }
    }

    if (mDefendFailed) {
        lock();
        defenderCards.insert(mTableCards.all().begin(), mTableCards.all().end());
        defender.cardsUpdated(defenderCards);
        unlock();
        CHECK_QUIT;
        std::for_each(mGameObservers.begin(), mGameObservers.end(), CardsReceivedNotification(mDefender, mTableCards.all()));
    } else {
        std::for_each(mGameObservers.begin(), mGameObservers.end(), CardsGoneNotification(mTableCards.all()));
    }

    // cleanup
    lock();
    mCurrentRoundAttackerId = NULL;
    mMaxAttackCards = 0;
    mCurrentRoundIndex = NULL;
    unlock();
    CHECK_QUIT;

    std::for_each(mGameObservers.begin(), mGameObservers.end(), RoundEndNotification(mRoundIndex));

    return !mDefendFailed;
}
Exemplo n.º 12
0
int main(void){
  printf("WELCOME TO HENRYS BLACKJACK\n");
  //player1
  struct player player1;
  printf("Type name for player1: ");
  scanf("%s",player1.name);
  getchar();
  player1.playerHand = NULL;
  player1.cardValue = 0;
  player1.startCards = 2;
  printf("utan ptr: %d\n", player1.startCards);
  //player2
  struct player player2;
  printf("Type name for player2: ");
  scanf("%s",player2.name);
  getchar();
  player2.playerHand = NULL;
  player2.cardValue = 0;
  player2.startCards = 2;
  //computer
  struct player comp;
  strcpy(comp.name, "the dealer");
  comp.playerHand = NULL;
  comp.cardValue = 0;
  comp.startCards = 1;

  int cardCounter = 0;
  struct card *deck = NULL;
  deck = createDeck(deck);    // deck created
  int i;
  for(i=0; i<20; i++)
    shuffleDeck(deck);   // deck shuffled

  /* Name giving and first cards dealing  */
  printf("\n\nHand of %s:\n", player1.name);
  dealCards(&player1, deck, &cardCounter);
  printCards(player1.playerHand, player1.startCards);
  printf("\n\nHand of %s: \n", player2.name);
  dealCards(&player2, deck, &cardCounter);
  printCards(player2.playerHand, player2.startCards);

  printf("\n\nHand of %s: \n", comp.name);
  dealCards(&comp, deck, &cardCounter);
  printCards(comp.playerHand, comp.startCards);


  /* Hit or stay face  */
 printf("------------------------------------------------------\n");
 player1.cardValue = actDealer(player1,deck, &cardCounter,22);
 printf("------------------------------------------------------\n");
 player2.cardValue = actDealer(player2,deck, &cardCounter,22);
 printf("------------------------------------------------------\n");
    if(player1.cardValue  == -1 && player2.cardValue == -1){  // if both loses dealer does not have to continue
        printf("Both players lost!\n");
        printf("--------------------Game-finished---------------------\n");
        goto masteJagKompletteraNufragetecken;
    }
 comp.cardValue = actDealer(comp,deck,&cardCounter,17);
 printf("------------------------------------------------------\n");
 whoWon(player1, player2, comp);
 printf("--------------------Game-finished---------------------\n");

masteJagKompletteraNufragetecken:
/* Freeing memory */
free(deck);
free(player1.playerHand);
free(player2.playerHand);
free(comp.playerHand);
return 0;
}
Exemplo n.º 13
0
void Game::createGame() {
  setRules();
  createPlayers();
  shuffleDeck();
  dealCards();
}