/* Performs an enemy attack on a player */ void enemyAttack(ENEMY the_enemy, int round) { int inRoll = 0; int attack_result = 0; int damage = 0; battleStats(the_enemy,round); mvwprintw(win,10,3,"The %s attacks %s with a %s...",the_enemy.enemy_name,player.player_name,weapons[the_enemy.e_weapon].weapon_name); napms(500); inRoll = rollDie(1,20); if (inRoll == 1) mvwprintw(win,11,5,"...the %s misses!",the_enemy.enemy_name); attack_result = inRoll + the_enemy.str; if (inRoll == 20 || attack_result > (player.def + player.armor)) { damage = (the_enemy.str + weapons[the_enemy.e_weapon].basehit + rollDie(1,weapons[the_enemy.e_weapon].base_str)) - (player.def + player.armor); if (damage <= 0) { mvwprintw(win,11,5,"...the strike glances off %s's armor",player.player_name); } else { mvwprintw(win,11,5,"...the %s deals %i damage to %s!",the_enemy.enemy_name,damage,player.player_name); player.hp -= damage; } } else { mvwprintw(win,11,5,"...the %s misses!",the_enemy.enemy_name); } wrefresh(win); napms(500); }
int Die::Roll() { m_nLastDieRollValue = rollDie(); m_pnDieRollValues[m_nLastDieRollValue - 1]++; ++m_nTotalDieRolls; return(m_nLastDieRollValue); }
/* Stat rolls should be greater than 5 for all stats according to D&D rules */ int statRoll(int max) { int val = 0; while (val <= 5) { val = rollDie(1,max); } return val; }
/* Checks to see if the player hit something Simulates a 1d20 roll with some modifiers If the player rolls a 20, they automatically hit If the player rolls 1, the automatically miss */ bool playerDidHit(ENEMY nme) { int attack_result = 0; int baseRoll = rollDie(1,20); player.critical_hit = FALSE; if (baseRoll == 1) return FALSE; if (baseRoll == 20) { player.critical_hit = TRUE; return TRUE;} attack_result = baseRoll + player.attack_bonus + player.str; if (attack_result > (nme.ac + nme.def)) return TRUE; else return FALSE; }
int checkPRNG(){ for (int i = 0; i < 1000000; i++){ arrayPRNG[rollDie()]++; } int i = 0; while (i < 1000){ arrayPRNG2[i]++; if (rollDie() == rollDie() && rollDie() == rollDie() && rollDie() == rollDie()){ i++; } } }
int main(void){ srand(time(NULL)); int numOfDies,numOfSides,i; while(1){ printf("How many dice?\nDice:"); scanf("%d",&numOfDies); printf("How many sides on the die/dice?\nSides:"); scanf("%d",&numOfSides); for(i=0;i<numOfDies;i++){ printf("%d ",rollDie(numOfSides)); } printf("\n"); } return 0; }
int rollDice(int numDice, int diceSize, int modifier, int verbose) { // Initialize the final value int finalValue = 0; // Initialize the individual rolls int rollValue = 0; if (verbose) { printf(KRED "\nRolling %dd%d+%d...\n", numDice, diceSize, modifier); printf(KBLU "====================\n"); } int i; for (i = 0; i < numDice; i++) { // Roll a singular die rollValue = rollDie(diceSize); if (verbose) { // Print individual roll values if verbose printf(KCYN "d%d Roll %d: \t%d\n", diceSize, i + 1, rollValue); } // Add each roll value to the final value finalValue += rollValue; } // Add the die additive parameter to the vinal value if (verbose && modifier != 0) { // Print individual roll values if verbose printf(KGRN "Modifier: \t%d\n", modifier); } finalValue += modifier; // Print the total roll value if (verbose) { printf(KBLU "====================\n"); } printf(KRED "%dd%d+%d Result:" KYEL "\t%d" KNRM "\n\n", numDice, diceSize, modifier, finalValue); // Return the final value of the roll return finalValue; }
void doBattle() { int round = 1; int nme_idx; int gold_amt = 0; int expGiven = 0; int key; int damage = 0; int canFlee = 0; bool didFlee = FALSE; ENEMY the_enemy; /* Pick an enemy randomly from the list */ nme_idx = rollDie(0,MAX_ENEMIES); if (nme_idx == MAX_ENEMIES) nme_idx = MAX_ENEMIES - 1; /* Keep a temporary copy so we can kill it without hurting the prototypes */ the_enemy = enemies[nme_idx]; /* If the enemy has an e_weapon of -1 we give them one randomly */ if (the_enemy.e_weapon == -1) { nme_idx = rollDie(0,MAX_WEAPONS); if (nme_idx == MAX_WEAPONS) nme_idx = MAX_WEAPONS - 1; the_enemy.e_weapon = nme_idx; } /* Calculate victory condition values */ expGiven = rollDie(1,the_enemy.exp); if (the_enemy.max_gold != 0) gold_amt = rollDie(1,the_enemy.max_gold); while (the_enemy.hp > 0 && player.is_dead == FALSE && player.hp > 0 && didFlee == FALSE) { flushinp(); battleStats(the_enemy,round); wattrset(win,A_BOLD); mvwprintw(win,7,12,"[A]ttack"); mvwprintw(win,8,12,"[F]lee"); wattrset(win,A_NORMAL); noecho(); keypad(win, TRUE); raw(); key = wgetch(win); flushinp(); switch(key) { case 'F': case 'f': canFlee = rollDie(1,6) + rollDie(1,6) + rollDie(1,6); if (player.agi > canFlee) { battleStats(the_enemy,round); mvwprintw(win,10,3,"%s flees from the battle!",player.player_name); wrefresh(win); napms(500); didFlee = TRUE; walk_counter = 0; } else { battleStats(the_enemy,round); mvwprintw(win,10,3,"%s attempts to flee but fails!",player.player_name); wrefresh(win); napms(1000); enemyAttack(the_enemy,round); round++; } break; case 'A': case 'a': //keypad(win,FALSE); battleStats(the_enemy,round); mvwprintw(win,10,3,"%s attacks the %s...",player.player_name,the_enemy.enemy_name,weapons[player.weapon].weapon_name); //napms(750); if (playerDidHit(the_enemy) == TRUE) { damage = (player.str + weapons[player.weapon].basehit + player.attack_bonus + rollDie(1,weapons[player.weapon].base_str)) - (the_enemy.def + the_enemy.armor); if (damage <= 0) { mvwprintw(win,11,5,"...%s's strike glances off the %s!",player.player_name,the_enemy.enemy_name); } else { mvwprintw(win,11,5,"...%s hits the %s for %i damage!",player.player_name,the_enemy.enemy_name,damage); the_enemy.hp -= damage; } } else { mvwprintw(win,11,5,"...%s misses!",player.player_name); } wrefresh(win); napms(750); if (the_enemy.hp > 0) { enemyAttack(the_enemy,round); round++; } break; default: wattrset(win,A_REVERSE); mvwprintw(win,10,10,"Invalid Option. Try again."); wattrset(win,A_NORMAL); wrefresh(win); napms(500); break; } if (player.hp < 0) player.hp = 0; if (player.hp == 0) player.is_dead = TRUE; drawStatsArea(); } flushinp(); if (player.is_dead == TRUE) { wbkgd(win,COLOR_PAIR(4) | A_DIM); wclear(win); box(win,ACS_VLINE,ACS_HLINE); mvwprintw(win,10,20,"Thou art dead!"); mvwprintw(win,12,20,"Press any key..."); wrefresh(win); wgetch(win); game_state = GAME_DONE; } else if (didFlee == FALSE) { //wclear(encounterwin); if (player.gold + gold_amt >= INT_MAX) player.gold = INT_MAX; else player.gold += gold_amt; player.slain++; walk_counter = 0; wbkgd(win,COLOR_PAIR(1) | A_DIM); wclear(win); box(win,ACS_VLINE,ACS_HLINE); mvwprintw(win,3,10,"Victory!"); mvwprintw(win,5,5,"%s hast slain the %s!",player.player_name,the_enemy.enemy_name); mvwprintw(win,6,5,"%s found %i gold on the %s",player.player_name,gold_amt,the_enemy.enemy_name); if (expGiven > 0) mvwprintw(win,7,5,"%s gained %i XP from the battle",player.player_name,expGiven); if (levelUp(expGiven) == 1) { wattrset(win,A_BOLD); mvwprintw(win, 9, 5,"%s has gained a level!",player.player_name); wattrset(win,A_NORMAL); } wattrset(win,A_REVERSE); mvwprintw(win,13,10,"Press any key to continue thine journey..."); wattrset(win,A_NORMAL); wrefresh(win); drawStatsArea(); wgetch(win); } }
/** * Initiates the die */ void Die::initialize() { srand(mInitiator++); rollDie(); };
/* rolls a pair of dice Return: Sum of each die */ int rollDice(void) { return rollDie() + rollDie(); }
//Determines the result of an attack between countries based on the forces used bool Game::attack(Territory* sourceAttacking, int armiesAttacking, Territory* target, int defendingArmies, bool alreadyWonOneBattleThisTurn){ int attacking = armiesAttacking; int defending = defendingArmies; attackLogString += "Attack: Player " + std::to_string(sourceAttacking->getIndexOfControllingPlayer()+1) + " attacked "; attackLogString += "Player " + std::to_string(target->getIndexOfControllingPlayer()+1) + " from " + sourceAttacking->getName(); attackLogString += " with " + std::to_string(armiesAttacking) + " armies to " + target->getName() + " with " + std::to_string(defendingArmies) + ".\n"; std::vector<int> attRolls; std::vector<int> defRolls; srand(time(NULL)); while (attacking != 0 && defending != 0){//while there are attacking or defending armies remaining for (int i = 0; i < attacking; i++){ if (i < 3){ attRolls.push_back(rollDie()); } } for (int i = 0; i < defending; i++){ if (i < 2){ defRolls.push_back(rollDie()); } } if (defRolls.size() > 1 && attRolls.size() > 1){//for atleast 2 dice in attacker and defender if (getGreatest(defRolls) >= getGreatest(attRolls)){//if def is greater or equal to attacking attacking = attacking-1; } else{//if attacking is greater defending = defending - 1; } if (getSecondGreatest(defRolls) >= getSecondGreatest(attRolls)){//if def is greater or equal to attacking attacking = attacking - 1; } else{//if attacking is greater defending = defending-1; } } else{//for less than 2 dices in either attacking or defending if (getGreatest(defRolls) >= getGreatest(attRolls)){//if def is greater or equal to attacking attacking = attacking - 1; } else{//if attacking is greater defending = defending-1; } } attRolls.clear(); defRolls.clear(); } if (attacking == 0){ attackLogString += "The defending army was victorious!\n"; target->setArmiesInTerritory(defending); return false; } else if (defending == 0){ attackLogString += "The attacking army was victorious!\n"; int tempIndexOfDef = target->getIndexOfControllingPlayer(); target->setArmiesInTerritory(attacking); players->at(target->getIndexOfControllingPlayer())->removeTerritoryOwned(target);//removing from defender the territory target->setIndexOfControllingPlayer(sourceAttacking->getIndexOfControllingPlayer()); players->at(sourceAttacking->getIndexOfControllingPlayer())->addTerritoryOwned(target);//adding to attacker the territory if (alreadyWonOneBattleThisTurn == false){//wont allow to win more than 1 cards per turn int card = rand() % 3 + 1; if (card == 1){ players->at(sourceAttacking->getIndexOfControllingPlayer())->setArtilleryCards(players->at(sourceAttacking->getIndexOfControllingPlayer())->getArtilleryCards() + 1); } else if (card == 2){ players->at(sourceAttacking->getIndexOfControllingPlayer())->setCavalryCards(players->at(sourceAttacking->getIndexOfControllingPlayer())->getCavalryCards() + 1); } else if (card == 3){ players->at(sourceAttacking->getIndexOfControllingPlayer())->setInfantryCards(players->at(sourceAttacking->getIndexOfControllingPlayer())->getInfantryCards() + 1); } } if (players->at(tempIndexOfDef)->getNumberOfTerritories() == 0){//if player lost, transfers cards players->at(sourceAttacking->getIndexOfControllingPlayer())->setArtilleryCards(players->at(sourceAttacking->getIndexOfControllingPlayer())->getArtilleryCards() + players->at(tempIndexOfDef)->getArtilleryCards()); players->at(sourceAttacking->getIndexOfControllingPlayer())->setCavalryCards(players->at(sourceAttacking->getIndexOfControllingPlayer())->getCavalryCards() + players->at(tempIndexOfDef)->getCavalryCards()); players->at(sourceAttacking->getIndexOfControllingPlayer())->setInfantryCards(players->at(sourceAttacking->getIndexOfControllingPlayer())->getInfantryCards() + players->at(tempIndexOfDef)->getInfantryCards()); players->at(tempIndexOfDef)->setArtilleryCards(0); players->at(tempIndexOfDef)->setCavalryCards(0); players->at(tempIndexOfDef)->setInfantryCards(0); } return true; } }
int playGame() { //Variables for the game int position = 0, i = 0, newPosition = 0, dieRolls = 0, tempRollPath[100]; //Game loop for squares 1 - 100 while (position < 100){ newPosition = position + rollDie(); //Extra if statement to ensure //the user never goes over 100 if (newPosition <= 100){ position = newPosition + gameBoard[newPosition]; gameSquareCounter[position]++; if (dieRolls <= minRolls){ tempRollPath[dieRolls] = position; }; }; dieRolls++; //Game loop for squares 1 - 94 while (position <= 94){ //Add a die rolls to the current position position = position + rollDie(); //Add the value of any snake / ladder on the new square position = position + gameBoard[position]; //Increment the number of times the user has landed on their square gameSquareCounter[position]++; //If this is a possible path for Nmin add the position to the temp array if (dieRolls <= minRolls){ tempRollPath[dieRolls] = position; }; //Increment the number of dice rolls for this game dieRolls++; }; }; //Keep a count of the total number of dice rolls for all games completeDieRolls = completeDieRolls + dieRolls; //Remember how many dice rolls this game took rollHistory[dieRolls]++; //Check if this is a new min path, or a new path for Nmin exists if (dieRolls < minRolls){ //Reset the counter for min paths minRoutes = 0; //Set the new minRolls minRolls = dieRolls; //Clear the path array and make every element 0 for (i = 0; i < 1000; i++){ if (rollPath[i] == 0){ //If the slot is zero then this is the end of the recorded paths and //the rest of the array will also be zero, so you can exit the loop i = 1000; } else { rollPath[i] = 0; }; }; } else if (dieRolls == minRolls){ int diff = 0, j = 0, uniqueRoute = 1; //Check the current path history to see if this path is already counted for //Incrememnt by i + minRolls every time as the array is in blocks which are minRolls in length for (i = 0; i <= (minRoutes * minRolls); i = i + minRolls){ j = 0; //Exit the loop if the slot in the rollPath array is zero as this is the end of recorded paths //Exit the loop if uniqueRoute == 0 as the path has been found to not be unique if (rollPath[i] == 0 || uniqueRoute == 0){ diff = i; i = (minRoutes * minRolls) + 1; } else { //Compare the temp array against a path in the rollPath Array while (j < minRolls && uniqueRoute == 1){ if (rollPath[i + j] == tempRollPath[j]){ j++; if (j == minRolls){ uniqueRoute = 0; }; } else { j = minRolls; }; }; }; }; //If a unique route exists add it to the rollPath array if (uniqueRoute == 1){ minRoutes++; for (i = 0; i < minRolls; i++){ rollPath[i + diff] = tempRollPath[i]; }; }; }; }
/************************************************************* * Function: play () * * Date Created: September 29, 2012 * * Date Last Modified: September 30, 2012 * * Description: This function is the main function called to * * start a game of craps. * * Input parameters: void * * Returns: void * * Preconditions: User knows the rules of the game of craps * * Postconditions: User has doesn't want to continue playing * * or player is bankrupt. * *************************************************************/ void play (void) { int dieOne = 0, dieTwo = 0, /* values for two dice */ sumDice = 0, /* sum of two dice */ playerPoint = 0, /* player's point */ gameStatus = 0, /* status of game */ numberOfRolls = 0, /* tracks number of rolls */ playMore = 0; /* status indicator for more game */ double initialBankBalance = 0.0, /* value for initial bank balance */ balance = 0.0, /* value for current bank balance */ wager = 0.0; /* value for wager or bet */ /* Prompts user for inital bank balance */ initialBankBalance = getBankBalance (); balance = initialBankBalance; do { do { /* Before each rool, prompt user for a wager */ wager = getWagerAmount (); } while (!(checkWagerAmount (wager, balance))); /* A player rolls two dice. */ printf ("<Press ENTER to roll the dice>"); pressEnter (); /* Gets two random values from 1-6, and are saved on the variables dieOne and dieTwo */ dieOne = rollDie (); dieTwo = rollDie (); /* Shows in the screen two animated die and then the the actual values of the dice */ animateDices (dieOne, dieTwo); /* After the dice have come to rest, the sum of the spots on the two upward faces is calculated. */ sumDice = calculateSumDice (dieOne, dieTwo); switch (isWinLossOrPoint (sumDice)) { case WINS: /* If the sum is 7 or 11 on the first throw, the player wins. */ gameStatus = WINS; break; case POINT: /* If the sum is 4, 5, 6, 8, 9, or 10 on the first throw, then the sum becomes the player's "point." */ gameStatus = POINT; playerPoint = sumDice; do { /* Prompts player to roll die until player gets the point or craps */ printf ("Continue rolling the dice until you get a sum of %d\n", playerPoint); printf ("<Press ENTER to roll the dice>"); pressEnter (); /* gets two random values for dieOne and dieTwo */ dieOne = rollDie (); dieTwo = rollDie (); /* animates two dice on the screen */ animateDices (dieOne, dieTwo); /* gets the sum of the two dice */ sumDice = calculateSumDice (dieOne, dieTwo); /* checks if user wins, craps or neither */ gameStatus = isPointLossOrNeither (sumDice, playerPoint); } while (gameStatus == POINT); break; case CRAPS: /* If the sum is 2, 3, or 12 on the first throw (called "craps"), the player loses (i.e. the "house" wins). */ gameStatus = CRAPS; break; } /* Once a game is loss or won, the bank balance should be adjusted. */ balance = adjustBankBalance (balance, wager, gameStatus); /* Keeps track of the number of plays */ numberOfRolls++; /* Prints out messages on screen */ chatterMessages (numberOfRolls, gameStatus, initialBankBalance, balance); printf ("<Press ENTER to continue>"); pressEnter (); if (balance > 0) { /* If balance is greater than 0, Prompts player to play more or not */ playMore = playAgain (balance); } else { playMore = 0; } } while (playMore); }