Write a code for a game called double dices.
Each player takes their turn to roll two dices. (So, player one rolls 2 dices then player 2 rolls two dices). To roll a dice player 1 presses the number 1 and player 2 presses the number 2. The dice numbers are from 1 to 6. If the sum of the two dices = 12 then that player is the winner
If the sum of the two dices = 10 the player gets a golden token 2 golden tokens without the any player reaching sum 12 will automatically make the player the winner. Create a module that checks for the winner and output who the winner is.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define Roll 2
// Function Declarition
void winner(int [], int []);
int main()
{
int player1[Roll], player2[Roll], p1sum=0, p2sum=0;
int i, j, dice, p1[0], p2[0];
srand(time(0));
// Prompts Player 1 to press enter.
printf("\n Player 1: Press Enter to roll your dice!!!\n");
getc(stdin);// collects the propmt.
//
for(i = 0; i < Roll; i++)
{
player1[i] = (rand() % 6) + 1;
p1sum += player1[i];
}
printf("\t Player 1 rolled %d dice\n\t The Sum of the two rolls are: %d\n", i + 0, p1sum);
printf("\n Player 2: Press Enter to roll your dice!!!\n");
getc(stdin);
for(j = 0; j < Roll; j++)
{
player2[j] = (rand() % 6) + 1;
p2sum += player2[j];
}
printf("\t Player 2 rolled %d dice\n\t The Sum of the two rolls are: %d\n", j + 0, p2sum);
// initializing an array to variable p1sum.
// Function Call.
winner(p1sum, p2sum);
return 0;
}
void winner(int p1sum [], int p2sum [])
{
int x, w;
//int p1sum = p1[0];
//int p2sum = p2[0];
p1sum[0];
p2sum[0];
for (w=0; w < Roll; w++)
{
if (p1sum == 12)
{
printf("\nPlayer 1, You've Won the prize");
}
else if (p2sum == 12)
{
printf("\nPlayer 2, You've Won the prize");
}
else if (p1sum == 10)
{
printf("\nPlayer 1 gets a golden token");
}
else if (p2sum == 10)
{
printf("\nPlayer 2 gets a golden token");
}
}
}
make methods like:
int rollDice(int rollCount);
boolean findWinner(int score1, int score2);
Then code something like this:
int sum1,sum2;
do {
sum1 = rollDice(2);
sum2 = rollDice(2);
}while(!findWinner(sum1, sum2))
Related
I try to code a little dice game in C. I am a beginner in C and still have to learn a lot. The user inserts the numbers of 5 dices. The program puts every number into an array and then prints out one of 4 cases:
Grand = same number on all 5 dices
Poker = same number on 4 dices
Full House = 3 equal and 2 equal numbers
Lose = No Grand, Poker or Full House
I just could write an if-statement-block that checks every possible combination and then prints the right case into the console. But that would take me quite a while. So I wanted to ask if there is an easier way to achieve that.
I coded the Grand and Lose so far:
#include <stdio.h>
int main() {
int dices[5];
printf("Program Dice game \n\n");
for(int i=0; i < 5; i++) {
printf("dice %i: ", i+1);
scanf("%i", &dices[i]);
}
printf("dice \t");
printf("1 \t");
printf("2 \t");
printf("3 \t");
printf("4 \t");
printf("5 \n");
printf("number \t");
for(int i=0; i < 5; i++) {
printf("%i \t", dices[i]);
}
printf("\n\n");
if(dices[0] == dices[1] && dices[0] == dices[2]
&& dices[0] == dices[3] && dices[0] == dices[4]) {
printf("Win! Grand!");
} else {
printf("Lose!");
}
return 0;
}
One solution could be to sort your dice array. This way, you'll have a lot fewer comparaisons to do. here's an exemple:
int cmp_func (const void *a, const void *b)
{
return (*(int*)a - *(int*)b);
}
int main() {
int dice[5] = {2, 3, 2, 3, 3}; //arbitrary dice combination
qsort(dice, 5, sizeof(int), cmp_func);
if (dice[0] == dice[4])
{
printf("Grand\n");
}
else if (dice[1] == dice[4] || dice[0] == dice[3])
{
printf("Poker\n");
}
else if ((dice[0] == dice[2] && dice[3] == dice[4]) || (dice[0] == dice[1] && dice[2] == dice[4]))
{
printf("Full House\n");
}
else
{
printf("Lose\n");
}
return (0);
}
Once your dice are sorted, if the first one is equal to the last one, you can assume they're all equals. If the first one is equal to the fouth one OR the second one is equal to the last one, you can assume you have 4 same dice, etc...
Note that if the initial order of your dice array matters, you'll have to duplicate it and use the other array to sort / test.
I'm having some trouble with my homework and I hope someone can help me with it.
They want me to create a dice game with the following requests:
5 dice are rolled.
Grand is what you get by rolling 5x the same number
Poker for 4x the same number
Full House for getting 3x the same number and another 2 with the same number aswell. example:(5,5,5,2,2)
I have written a code in which i can get some of the requests done. But I also have to save the values as an array which causes me alot of trouble. Can someone please show me how it is done? and explain it aswell? This is my code so far:
#include <stdio.h>
#include <stdlib.h>
int main () {
srand (time(0));
int dice[5];
int i;
printf ("Program dice\n");
for (i=0; i<5; i++)
dice [1] = (rand ()%6 )+ 1;
printf ("Würfel 1: %d \n", dice [1]);
dice [2] = (rand ()%6 )+ 1;
printf ("Würfel 2: %d \n", dice [2]);
dice [3] = (rand ()%6 )+ 1;
printf ("Würfel 3: %d \n", dice [3]);
dice [4] = (rand ()%6 )+ 1;
printf ("Würfel 4: %d \n", dice [4]);
dice [5] = (rand ()%6 )+ 1;
printf ("Würfel 5: %d \n", dice [5]);
for(i = 0; i < 6; i++)
if (dice [i] == 5)
{
printf ("You've won! Grand!");
return (0);
}
else
{
printf ("You lost.");
return (0);
}
return 0;
}
First, let's take a look on how you generate the numbers... consider you are using an array, you can access it using the [] operator, it means that if you have an array, and you want to access the first element, considering that array index start from 0, you can do it by doing array[0] and since we are inside a for loop with a i that get values from 0 to 5, you can generate your dice roll with this
int dice[5];
for (int i=0; i<5; i++){
dice [i] = (rand ()%6 )+ 1;
printf ("Würfel %d: %d \n", i, dice [i]);
}
than, you have to create the logic behind each possible game win
I think it is better to restructure the code.
You should store the count for each dice roll. For example, (5,5,5,3,3) should generate (0,0,2,0,3,0).
Now just use these instead.
Try this:
#include <stdio.h>
#include <stdlib.h>
const int DICE_ROLLS = 5;
int main()
{
srand(time(0));
int number_of_rolls[6] = {0};
// Simulate the random rolls
for(int i = 0; i < DICE_ROLLS; ++i)
{
// Get a new roll ( from 1 to 6)
int dice_value = rand() % 6 + 1;
// If it is 1, increment rolls for number_of_rolls[0]
++number_of_rolls[ dice_value - 1 ];
}
// Now it is simple. To check for all five, do
for(int i = 0; i < DICE_ROLLS; ++i)
{
if(number_of_rolls[i] == 5)
{
printf("You've won! Grand!");
}
}
return 0;
}
Hopefully you get the gist now. :-)
I gave my students a similar question a while back. My solution can be found here, although I only implemented checking for the same values (yahtzee/kniffel).
The code is written to be pseudo object orientated in that you have a struct cup that is initialized to store an array of pointers to dice object. The cup is then filled with a specified number of struct dict, found here. Following that you can roll the cup which uses the rand() function to randomize values for each die in your cup.
int max_value = 0, dice_count = 0, ret;
struct cup *my_cup = NULL;
prompt_int("Please enter the max value of each die", &max_value);
prompt_int("Please enter the number of die in the cup", &dice_count);
my_cup = create_cup(dice_count);
fill_cup(my_cup, max_value);
roll_cup(my_cup);
ret = check_cup(my_cup)
switch(ret){
//Respond[ to combinations
}
In the main.c you will find a function called check_cup in which you can put checking logic to check for certain combinations of dice, at the moment it just checks if all the dice are the same and returns 0, this could be modified to return certain values for certain.
I am writing a program in C that plays the game Craps. After my first roll, when I either land the point (win) or lose, the program just ends instead of calling is_win or is_loss.
But if it calls is_win or is_loss on my first roll, everything works fine.
I'm fairly certain this has something to do with the pointer pbal. I've been getting errors in the debugger saying unable to read memory, also Exception Thrown: Read access violation. I am still fairly new to pointers so I'm assuming this is the root cause of the problem.
# include "header.h"
int print_menu(void) {
int choice = 0;
printf("\n1. Enter balance\n2. Play game\n3. Get rules\n4. End game");
printf("\nEnter which you would like to do: ");
scanf("%d", &choice);
return choice;
}
void print_rules(void) {
printf("\nFirst Roll: If your die roll adds to 7 or 11, you win.\nIf it adds to 2, 3, or 12, you immediately lose.\nIf it adds to another number, that number becomes your 'point'");
printf("\nSecond Roll: If your die roll adds to your point, you win. If it adds to 7, you lose.\nKeep rolling until you get one of these.\n\n");
}
int get_balance(balance) {
printf("\nEnter how much money you would like to add (whole dollars): ");
scanf("%d", &balance);
return balance;
}
int prompt_bet(balance) {
int bet = 0;
do {
printf("\nEnter how much you would like to bet for this game: ");
scanf("%d", &bet);
} while (bet > balance); //repeats until its false that bet>bal
return bet;
}
int roll_dice(void) {
srand((unsigned int)time(NULL));
int enter = 1;
printf("\nEnter a 0 to roll your dice: ");
scanf("%d", &enter);
int die1 = rand() % 6 + 1;
int die2 = rand() % 6 + 1;
int dice = die1 + die2;
printf("You rolled a %d and a %d, with a total of %d.\n", die1, die2, dice);
return dice;
}
int calc_first_roll(int dice, int bet, int balance, int * pbal) {
int result0 = 0;
if (dice == 7 || dice == 11) {
is_win(bet, balance, pbal);
}
else if (dice == 2 || dice == 3 || dice == 12) {
is_loss(bet, balance, pbal);
}
else {
printf("Your point is %d", dice);
int point = dice;
int done = 1;
do {
dice = roll_dice();
done = calc_other_rolls(point, dice, balance, bet, *pbal);
} while (!done);
}
return result0;
}
void is_win(int bet, int balance, int *pbal) {
/* the pointer *pbal is pointing to mainbalance. I had to pass it
through everything to get it to affect mainbal the way I wanted it to.
Think of mainbalance as the permanent memory for keeping their bets & money right,
and int balance is just a messenger that doesn't get in the way of me trying
to use a pointer on mainbalance. */
*pbal = balance + bet;
printf("You win! Your new balance is %u\n", *pbal);
}
void is_loss(int bet, int balance, int *pbal) {
*pbal = balance - bet;
printf("You lost. Your new balance is %u\n", *pbal);
}
int calc_other_rolls(int point, int dice, int balance, int bet, int *pbal) {
int done = 0;
if (dice == 7) { //Goes straight to is_l / is_w instead of looping back to calc_first
is_loss(bet, balance, *pbal);
done = 0;
}
else if (dice == point) {
is_win(bet, balance, *pbal);
done = 0;
}
else {
done = 0;
}
return done;
}
# include "header.h"
int main(void) {
int mainbalance = 0;
int choice = 0;
int *pbal = &mainbalance;
do {
choice = print_menu();
if (choice == 1) {
mainbalance = get_balance();
printf("Your balance is: %d\n", mainbalance);
choice = 8; //reprints menu
}
if (choice == 3) {
print_rules();
choice = 8;
}
if (choice == 4)
exit(1);
if (choice == 2) {
int bet = prompt_bet(mainbalance);
int dice = roll_dice();
int x = calc_first_roll(dice, bet, mainbalance, pbal);
choice = 8;
}
} while (choice > 4 || choice < 1); //keeps running code until test becomes false.
return 0;
}
In this section:
if (dice == 7) { //Goes straight to is_l / is_w instead of looping back to calc_first
is_loss(bet, balance, *pbal);
done = 0;
}
else if (dice == point) {
is_win(bet, balance, *pbal);
done = 0;
}
You're not passing is_loss and is_win the pointer, you're passing the integer value, that pbal points to. * outside of a declaration is always dereferencing.
So if calc_other_rolls gets int *pbal as an argument and you wanna pass it to another function that takes int * then you should do func(pbal) and not func(*pbal), since the second one passes the value not the pointer.
Edit: As #hollow pointed out, this gets flagged by the compiler if you enable warnings, so use them.
I have a new problem. I got most of the things fixed. I need my (turnAgain) function fixed. I specifically need to fix my if else statement. I need it to let the player continue rolling if they type in 'r'. else if they type 'h' the other player gets to roll. And I need it to say try again type 'r' or 'h' if they type in something that is is not 'r' or 'h'. I just dont know how to do that. New to coding thanks!! I REALLY NEEEEEEEEEEEEEEEEEEEEEEED HELP.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#define SIDES 6
typedef enum {doublesPoints, onesPoints, noPoints, singlesPoints} status;
void prnRules(void)
// function: prnRules
// pre: none
// post: prints the rules
{
printf("%s\n",
"The goal is to be the first player to reach 50 points.\n\n"
"On a turn, a player rolls the two dice repeatedly until either a 1 is rolled \n"
"or the player chooses to hold and stop rolling.\n\n"
"If a 1 is rolled, that player's turn ends and no points are earned for the round.\n"
"If the player chooses to hold, all of the points rolled during that round are added to their score.\n\n"
"If a player rolls double 1s, that counts as 25 points.\n"
"Other doubles are worth 2x double points, so that a 2-2 is worth 8 points; 3-3 is worth 12; \n"
"4-4 is worth 16; 5-5 is worth 20; and 6-6 is worth 24.\n\n"
"When a player reaches a total of 50 or more points, the game ends and that player is the winner.\n");
}
int rollDie ()
// function: rollDie
// pre: none
// post: generates a random number for the die
{
int d;
d = rand() % SIDES + 1;
return d;
}
status turnPoints(int die1, int die2)
// function: turnStatus
// pre: dice have been rolled
// post: returns the status of the roll (doublesPoints, onesPoints, no Points, singlesPoints)
{
if (die1 == die2 && !(die1 == 1 && die2 == 1))
return doublesPoints;
else if (die1 == 1 && die2 == 1)
return onesPoints;
else if ((die1 == 1 || die2 == 1) && !(die1 == 1 && die2 == 1))
return noPoints;
else
return singlesPoints;
}
void turnAgain(int status)
{
char rollDie;
do
{
printf("Would you like to roll again or hold(r/h)?");
scanf("%c",&rollDie);
} while(rollDie!='r'&&rollDie!='h');
if(rollDie=='r')
{
}
else
{
}
//to switch the current player when the turn is over
int switchPlayer(int currentPlayer)
{
if (currentPlayer == 1)
return 2;
else
return 1;
}
char gameAgain()
// function: gameAgain
// pre: none
// post: returns a valid (y or n) answer
{
char ans;
do
{
printf("Play another game (y or n)? ");
ans = getchar();
getchar();
}while (ans != 'y' && ans != 'n');
return ans;
}
int gameOver (int p1Total, int p2Total)
// function: gameOver
// pre: none
// post: returns a '1' if either total exceeds 50
{
if (p1Total || p2Total >= 50)
{
return 1;
}
else
{
return 0;
}
}
//The final print statement with all the totals
void finalOutput(int p1Total, int p2Total)
// function: finalOutput
// pre: gameOver returns a '1'
// post: returns the final scores of the game
{
printf("\n");
printf("WE HAVE A WINNER!!!\n");
printf("Player 1 your final score was %d\n", p1Total);
printf("Player 2 your final score was %d\n", p2Total);
}
int updatePlayerTotal(int currentPlayer, int turnTotal, int playerTotal)
// function: pudatePlayerTotal
// pre: none
// post: returns the player total
{
printf("Player %d, your total at the start of this turn was %d .\n",
currentPlayer, playerTotal);
playerTotal = playerTotal + turnTotal;
printf("Your total at the end of this turn is %d.\n\n", playerTotal);
return playerTotal;
}
int main (void)
{//begin main
// variable declarations
int sum; // for sum of two dice
char answer; // for yes/no questions
int tempTotal = 0; // temporary player total for the round
int p1Total = 0; // running total for player 1
int p2Total = 0; // running total for player 2
int total = 0; // player total after each round
int die1 = 0; // the roll value of die1
int die2 = 0; // the roll value of die2
int currentPlayer = 1; // start with Player 1
int status = 0; // status for choice to continue
srand(time(NULL)); // seed random # generator
do // play at least one game
{//Begin game loop
//give option to view the rules
printf("Welcome to the game of Fifty. Would you like to view the rules? (y or n)?\n");
answer = getchar();
getchar();
if (answer == 'y')
prnRules();
do // until game is won
{//Begin roll loop1
{ //Begin roll loop2
die1 = rollDie();
die2 = rollDie();
sum = (die1 + die2);
printf("Player %d:\n", currentPlayer);
printf("Die 1 is a %d.\n", die1);
printf("Die 2 is a %d.\n", die2);
//award points (rolled a double but not double 1's)
if (turnPoints(die1, die2) == doublesPoints)
{
printf(" Player %d, you rolled a double %d!\n ", currentPlayer, die1);
printf(" That's worth %d points.\n", (sum * 2));
tempTotal = (tempTotal + total + (sum * 2));
status = 1;
}
//award points (rolled double 1's)
else if (turnPoints(die1, die2) == onesPoints)
{
printf(" Player %d, You rolled a double 1!\n ", currentPlayer);
printf(" That's worth 25 points.\n");
tempTotal = (tempTotal + total + 25);
status = 1;
}
//award no points (one of the two dice = 1)
else if (turnPoints(die1, die2) == noPoints)
{
printf("Sorry Player %d, you rolled a single 1. You do not earn any points this round\n", currentPlayer);
printf("Your current total is %d\n", total);
tempTotal = 0;
total = total + tempTotal;
status = 0;
}
//award points (rolled singles)
else if (turnPoints(die1, die2) == singlesPoints)
{
printf("Player %d, your roll totals %d points.\n", currentPlayer, sum);
tempTotal = tempTotal + (total + sum);
status = 1;
}
}while (status == 1 && (turnAgain(status) == 'y'));//end roll loop2 - while player continues roll
if (turnAgain(status) == 'n')//(answer == 'n')
{
total = (tempTotal + total);
if (currentPlayer == 1)
{
p1Total = updatePlayerTotal(currentPlayer, tempTotal, p1Total);
}
else
{
p2Total = updatePlayerTotal(currentPlayer, tempTotal, p2Total);
}
//switch players
currentPlayer = switchPlayer(currentPlayer);
}
}while (gameOver(p1Total, p2Total) != 1); //end loop1 - continue while game is not over
answer = gameAgain();
}while (answer != 'n'); //end game loop - loop while wanting to play again
return 0;
}//end main
int rollDie ()
// function: rollDie
// pre: none
// post: generates a random number for the die
{
int d;
d = rand() % SIDES + 1;
return d;
}
...
int turnAgain(int status)
---> you forget the left brace {
char rollDie; // Conflict, rollDie redeclared
Compile with warnings:
die1 = rollDie();
^
demo.c:60:10: note: declared here
char rollDie;
I'm in an intro to C class, and my professor has assigned us to code a game called "tea party" for our current assignment. I've finished coding the game, and it works for the most part, but there are some certain kinks that I can't seem to work out.
The rules of the game are simple: two players take turns spinning the spinner (emulated by entering "0" and pressing enter), and collecting all 7 items for the tea party. The first player to get all 7 items wins. The only catch is that you cannot collect a sandwich, fruit, or dessert unless you have a plate first. If you land on the LOSE A PIECE square, you must give up one of your pieces. Both of the errors come from the lose a piece instance in the game, so I'm thinking the error must originate from the "get_lost_piece" function.
One of them is that the pieces from the "player" array are numbered oddly in that they are 1 value higher than they should be. The other error is that when a player tries to remove their plate while they have an item that requires the plate, it should print out "Sorry, it is bad manners to eat without a plate. Enter another choice:", but instead, I get an infinite loop that reads "You lost item 1."
Here is the code I have:
#include <stdio.h>
#include <time.h>
#define SLOW_MODE 1
#define NUMPLAYERS 2
#define NUMPIECES 7
#define MAXLEN 20
#define NO_WINNER -1
const char CHOICES[NUMPIECES+1][MAXLEN] = {"PLATE", "NAPKIN", "TEA CUP", "CREAM AND SUGAR", "SANDWICH", "FRUIT", "DESSERT", "LOSE A PIECE"};
void update_player(int player[], int square);
int get_lost_piece(int player[]);
int search(int piece_list[], int choice);
int get_spin();
void init_player(int player[]);
int get_winner(int players[][NUMPIECES]);
int get_next_player(int player_num);
int count_pieces(int player[]);
void print_player(int player[], int player_num);
int main() {
srand(time(0));
int players[NUMPLAYERS][NUMPIECES];
// Initialize each player in the game.
int i;
for (i=0; i<NUMPLAYERS; i++)
init_player(players[i]);
int player_number = 0;
// Play until we get a winner.
int status = get_winner(players);
while (status == NO_WINNER) {
int dummy;
// In slow mode, we stop before every spin.
if (SLOW_MODE) {
printf("Player %d, it is your turn. Type 0 and enter to spin.\n", player_number+1);
scanf("%d", &dummy);
}
// Get the current player's spin and print out her pieces.
int square = get_spin();
printf("Player %d, have landed on the square %s.\n", player_number+1, CHOICES[square]);
update_player(players[player_number], square);
print_player(players[player_number], player_number+1);
// Update the game status.
player_number = get_next_player(player_number);
status = get_winner(players);
printf("\n\n");
}
printf("Congrats player %d, you win!\n", status+1);
return 0;
}
// Pre-conditions: player stores the contents of one player and square is in between 0 and 7, inclusive.
// Post-conditions: The turn for player will be executed with the given square selected.
void update_player(int player[], int square) {
if (square == 7) {
if (count_pieces(player) == 0)
{
printf("There is no piece for you to lose. Lucky you, sort of.\n");
return;
}
else{
int q;
q = get_lost_piece(player);
player[q]= 0;
}
return;
}
player[square]=search(player, square);
// Restricted by having no plate!
if (player[0] == 0) {
if(square == 4 || square == 5 ||square == 6){
printf("Sorry, you can't obtain that item because you don't have a plate yet.\n");}
else{
if (player[square] == 0){
player[square]++;
}
}
}
// Process a regular case, where the player already has a plate.
else {
if (player[square] == 0){
player[square]++;
}
}
}
// Pre-conditions: player stores the contents of one player that has at least one piece.
// Post-conditions: Executes asking a player which item they want to lose, and reprompts them
// until they give a valid answer.
int get_lost_piece(int player[]) {
int choice = -1;
// Loop until a valid piece choice is made.
while (1) {
if (choice == -1){
printf("Which piece would you like to lose?\n");
print_player(player,choice);
scanf("%d", &choice);}
if (player[choice] == 0 && choice < 7 && choice >= 0){
printf("Sorry, that was not one of the choices");
scanf("%d", &choice);
}
if (player[0] == 1 && choice == 4 || choice == 5 ||choice == 6){
printf("Sorry, it is bad manners to eat without a plate. Enter another choice:\n");
scanf("%d", &choice);
}
else{
printf("You lost piece %d\n", choice);
}
}
return choice;
}
// Pre-conditions: piece_list stores the contents of one player
// Post-conditions: Returns 1 if choice is in between 0 and 6, inclusive and corresponds to
// an item in the piece_list. Returns 0 if choice is not valid or if the
// piece_list doesn't contain it.
int search(int piece_list[], int choice) {
int i;
for (i=0; i<NUMPIECES; i++){
if(piece_list[i]==choice){
return 1;}
else {return 0;}
}
}
// Pre-condition: None
// Post-condition: Returns a random value in between 0 and 7, inclusive.
int get_spin() {
return rand() % 8;
}
// Pre-condition: None
// Post-condition: Initializes a player to have no pieces.
void init_player(int player[]) {
int j;
for (j=0; j< NUMPIECES; j++)
player[j]=0;
}
// Pre-condition: players stores the current states of each player in the tea party game.
// Post-condition: If a player has won the game, their 0-based player number is returned.
// In the case of no winners, -1 is returned.
int get_winner(int players[][NUMPIECES]) {
int i =0;
for (i=0; i<NUMPLAYERS; i++){
if(count_pieces(players[i]) == NUMPIECES) {
return i;}
}
return -1;
}
// Pre-condition: 0 <= player_num < NUMPLAYERS
// Post-condition: Returns the number of the next player, in numerical order, with
// a wrap-around to the beginning after the last player's turn.
int get_next_player(int player_num) {
player_num++;
if (player_num == NUMPLAYERS){
player_num = 0;
}
return player_num;
}
// Pre-conditions: player stores the contents of one player
// Post-conditions: Returns the number of pieces that player has.
int count_pieces(int player[]) {
int y, counter;
counter = 0;
for ( y = 0; y < 7; y++){
if(player[y] == 1){
counter++;
}
}
return counter;
}
// Pre-conditions: player stores the contents of one player and player_num is that
// player's 1-based player number.
// Post-conditions: Prints out each item the player has, numbered with the numerical
// "codes" for each item.
void print_player(int player[], int player_num) {
int i;
printf("\n");
printf("Player %d\n", player_num);
for (i=0; i < 7; i++){
if (player[i] == 1){
printf("%d. %s\n", i + 1, CHOICES[i]);
}
}
}
Thanks for the help in advance. I get the feeling that the solution is staring me right in the face, but after spending a couple of days on this, I'm having difficulty spotting the problem.
need #include <stdlib.h> for rand(), srand()
add player_number parameter to get_lost_piece() and pass it to print_player.
The following is just one idea for refactoring. It could be done many different ways.
Get input once at the start of the loop.
Use continue keyword in each if statement to redo the loop.
It works fine when I change the logic of get_lost_piece() to:
while...
get choice
if choice < 1 || choice > 7 "1-7 please..." continue
if player[choice - 1] == 0 "sorry..." continue
if choice == 1 (and player[] contains foods) "bad manners..." continue
return choice - 1;
Helpful hints
Loop should be limited and needs to give player a quit option.
Check out FAQ entry: scanf() returns errors, leaves stuff on input stream.
Test early, test often.
Turn up compiler warnings (as suggested by catcall)