Number Guessing Game with two players - c

Can someone please help me figure out what is wrong with my program it is prety complex for me. It is a number guessing game where two player can play. It starts by saying which player goes first and the player then has to input his number either 1 or 2 and then enter a guess or either pass (players can't pass more than 3 times or twice in a row). It is working very good except that everytime player 1 starts it asks him for a guess twice in a row bu then works fine, and when player 2 starts it alternates like it should like this:
And this is my code It quite a lot of code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int playerNumber = 0;
int number = 0;
int playerInput = 0;
int guess = 0;
char input;
char str[6] = {0};
int playerA = 1;
int playerB = 2;
int passA = 3;
int passB = 3;
int i = 1;
int playerTurn = 0;
int turn = 0;
srand(time(NULL));
playerNumber = 1 + rand() % 2; /* Random number is generated */
srand(time(NULL));
number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
printf("\nIt's player's %d turn\n", playerNumber);
printf("Player Number?\n");
scanf("%d", &playerInput);
while (playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
if (playerA != playerNumber)
playerB = playerNumber;
if (i%2 == 1) {
playerNumber = playerA;
}
else {
playerNumber = playerB;
}
i = i+1;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s", str);
if (strcmp(str, "pass") == 0){
if (playerNumber == playerA){
passB = passB -1;
printf("Player 2 has %d more 'Pass' left!\n", passB);
}
else{
passA = passA -1;
printf("Player 1 has %d more 'Pass' left!\n", passA);
}
}
else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is to low */
printf("Your guess was to low.\n ");
else if(guess > number) /* if the guess is higher, output: the guess is to high */
printf("Your guess was to high.\n ");
else /* is the guess is equial to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
return 0;
}

First of all, you should use consistent indentation. That will make it easier to read your code.
Second, you should use newlines and whitespace to group like-lines together. Think of writing code like writing prose, and newlines as ways to separate paragraphs. You don't double-space almost anything, because it wastes space and is harder to read (people aren't used to it) so don't double-space your code.
Third, your use of the playerA and playerB variables is an OK concept, but there are better ways to do it. The typical convention in C/C++ is to use a #define for magic numbers, with all caps - #define PLAYER_A 1. Following this convention will make your code more readable. Also, since your players are "1" and "2" it is more readable to use #define PLAYER1 1 or PLAYER_1.
You use the variable "i" but the convention for using variables named i, j, k, m, or n is as loop counters that are incremented either at the top of the loop or at the bottom of the loop. Incrementing the loop counter in the middle of the loop makes it much easier for the counter to get lost. Move the increment to the top or the bottom.
Do the work by hand to see what your variables are as the program executes. Your teacher has done this in class. Just write down each variable and write its value next to it, then change the variables as they will change while the program executes. This technique will help you fix other difficult bugs in the future, rather than me giving you the answer.

You have an infinite loop in your code,
your code given below is wrong,
while(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}
It should be,
if(playerNumber != playerInput)
{
printf("You Have to wait your turn.\nPlayer number?\n");
}

Related

My for loop sequence is not ending with the perimeters are met to end

For the below code I created a RNG and ask the user to input a number from one to 20 until they guess the correct number. When they guess the correct number the printf prints the correct text so I know guesses[i] == randomNumber
I would think that the for loop would terminate since now guesses[i] != randomNumber no longer holds a true value. The loop is not terminating and continues to ask the user to guess.
Am I missing something here?
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <stdlib.h>
int main(void) {
time_t t;
srand(time(&t));
int randomNumber = (rand() % 19) + 1;
int guesses[30] = {0};
int i;
for (i = 0; guesses[i] != randomNumber; i++)
{
printf("Hello master, I will grant you 3 wishes if you can guess what number I have selected between 1 and 20: ");
scanf("%d", &guesses[i]);
if (guesses[i] == randomNumber) {
printf("It took you %d guesses to guess correct but I lied I cannot grant you any wishes, have a nice day. \n\n", i + 1);
}
else if(guesses[i] < randomNumber) {
printf("You guessed too low, try a higher number. \n\n");
}
else if(guesses[i] > randomNumber) {
printf("You guessed too high, try a lower number. \n\n");
}
}
return 0;
}
When the user inputs its guess, i increases by the loop increment instruction, and now your condition is applied to guess[i] which is actually the next i not the input user.
Welcome to SO..
I believe that testing the condition (guesses[i] != randomNumber) happens before advancing i (i++), so you are actually testing against i that was already advanced by 1
You can either try to use ++i instead of i++
OR
You can use a while loop instead of a for loop:
i = 0;
while (guesses[i] != randomNumber && i < 30) {
i++;
printf("Hello master, I will grant you 3 wishes if you can guess what number I have selected between 1 and 20: ");
scanf("%d", &guesses[i]);
if (guesses[i] == randomNumber) {
printf("It took you %d guesses to guess correct but I lied I cannot grant you any wishes, have a nice day. \n\n", i + 1);
}
else if(guesses[i] < randomNumber) {
printf("You guessed too low, try a higher number. \n\n");
}
else if(guesses[i] > randomNumber) {
printf("You guessed too high, try a lower number. \n\n");
}
}
Note how I also added a test for i < 30 to not get out of the array index bounds

adding an outer while loop to my c program - beginner 1 to continue 0 to stop

This is my first post on stack overflow, so this is my code so far, i'm just starting computer engineering and am having some trouble.
#include <stdio.h>
int main ( void ) {
int num, sum = 0, i, ssq = 0, isq, n;
printf("Enter an integer: ");
scanf("%d", &num);
for (i = 1; i <= num; i++) {
sum = sum + (i * i);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
while (i >= 0) {
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
printf("Enter an integer: ");
scanf("%d", &num);
for (isq = 1; isq <= n; isq++);
ssq = ssq + (isq * isq);
printf("The sum of the squares of integers from 0 to %d is %d\n", num, sum);
if (i == 0) break;
}
return 0;
}
This is what I have so far believe it or not it took me 12 hours to do the first part, I've literally been up all night working on this, before the while loop and now I'm completely lost. I added the ssq=0, isq, and n ints in to try to help with no avail. At this point I'm just rearranging stuff for hours on end, this is my first post so please don't be too hard on me!
This contains a whole host of errors, from typos to code duplication, as #HappyCoder has noted above.
First of all, the outer part and the loop part do exactly the same. Think about it for a moment. You first do some task, unconditionally, then ask the user if they want to start over. The task itself doesn't change! Hence, what we can do is this:
do the task;
ask the user if they want to quit or go on;
if yes, return to the start.
In code, this can be done with an endless loop that you break out of if the user wants to stop:
while(1) {
// do user input and calculations here;
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &i);
if (i == 0)
break;
}
See, now we only have one instance of the calculation code! Now, you can throw away half the variables declared in the beginning, since they are duplicate.
Now on to the calculations. You have an uninitialized variable, ssq, in the loop. See where code duplication can get you. In the outer part, it is initialized properly. Inside the loop, however, it is not guaranteed to hold any concrete value, most likely it contains garbage.
Also, as noted by #JohnHascall, this subtle error introduced most likely by a typo:
for (isq = 1; isq <= n; isq++); // <---- the evil semicolon
ssq = ssq + (isq * isq);
The semicolon after the for loop makes the loop empty, and the summation only happens once, but not in the loop, as you want it to be.
Then, you output (print) sum not ssq inside the loop, which is obviously not what you want to print. And, you use the uninitialized n variable from outside the loop as the boundary, instead of the user inputted num.
I want to add yet one more. Sanely naming the variables is a big deal as it helps you to catch potential errors and keep track of how variables are being used throughout the code, not to mention easier understanding of the code by others. Look: int i -> int choice better isn't it?
So we can rewrite the code like this:
#include <stdio.h>
int main ( void )
{
int boundary, choice, isq, ssq;
while (1) {
printf("Enter an integer: ");
scanf("%d", &boundary);
ssq = 0;
for (isq = 1; isq <= boundary; isq++) {
ssq = ssq + (isq * isq);
}
printf("The sum of the squares of integers from 0 to %d is %d\n", boundary, ssq);
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &choice);
if (choice == 0)
break;
}
return 0;
}
for (isq=1; isq<=n; isq++);
ssq = ssq + (isq*isq);
The problem here is that 'n' is not initialized and not used in above scanf statement, you need to use 'num' instead of 'n'
for (isq=1; isq<=num; isq++)
ssq = ssq + (isq*isq);
One likely problem is here:
for (isq = 1; isq <= n; isq++);
ssq = ssq + (isq * isq);
You probably want:
for (isq = 1; isq <= n; isq++) {
ssq = ssq + (isq * isq);
}
Also, you should add:
ssq = 0;
above that loop (think about your 2nd trip through the loop).
Here is #iksemyonov 's answer refactored to honor the "no more than 7 lines in a method" rule (using a hard and fast arbitrary number like 7 is absurd, but the principle of making function do a specific understandable task is reasonable).
#include <stdio.h>
static int getBoundary ( void ) {
int boundary;
printf("Enter an integer: ");
scanf("%d", &boundary);
return boundary;
}
static int computeSSQ ( int limit ) {
int ssq = 0;
for (; limit > 0; --limit) ssq += (limit*limit);
return ssq;
}
static int again ( void ) {
int choice;
printf("Would you like to go again? (1 for yes, 0 for no): ");
scanf("%d", &choice);
return choice;
}
int main ( void ) {
do {
int boundary = getBoundary();
int ssq = computeSSQ(boundary);
printf("The sum of the squares of integers from 0 to %d is %d\n",
boundary, ssq);
} while (again());
return 0;
}
You have made a few mistakes here:
You have put a semicolon after the for loop inside the while block which should be removed.
Inside the while block you have accepted value for 'num' while you have used 'n' in the for loop (for which value is uninitialized). So you should accept the value of 'n' instead of 'num' or else replace 'n' in the for loop with 'num'.
If you want to exit the while loop immediately after user inputs 0 then move the if (i == 0) break; statement to below the scanf ("%d", &i) statement.
In the printf() statement next to the for loop, you have used value of 'sum' while you have calculated value for ssq.
Also you should write ssq = 0 after the printf() statement to reset its value to 0.
Correct all these and the program will work.
what you want to do was basically a menu driven program... i would suggest , like the above one's are right too... but another way you can do is using do{
//the task , i.e. the sum
} while(i!=0);
doing this since do while is an exit controlled loop as you might be knowing... so as in earlier stages u can be free from using break; keyword...
also as you are starting an early bird tip i would like to give is that the suggestion of using functions by #John above ....is good but not if you are doing mistakes in a normal int main() 15 lines code... since if you go in user defined functions like stated above you might go wrong in passing the arguments or basics of function passing... so go for a normal int main code for now...
Note i didnt meant that what # John said was wrong or something...just gave my view/advice

Write a program that multiplies user entered number till product of these numbers reach 1000

I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}

For loop guessing game in C

a program to get the user to guess the number that the program has picked as the lucky number. It uses one for loop and plenty of if statements. The problem is that my code stops after 2 tries, but suppose to give user 3 tries. Here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int iSecret, iGuess;
srand(time(NULL));
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3 || iSecret == iGuess; tries++)
{
printf("Please, enter a number between 1 and 20! ");
scanf("%d", &iGuess);
if (iGuess == iSecret)
{
printf("\nCongratulations! You won!");
return 0;
}
else if (iGuess > iSecret)
{
tries++;
printf("\nYour guess was too high.\n");
}
else if (iGuess < iSecret)
{
tries++;
printf("\nYour guess was too low.\n");
}
if (tries == 3)
break;
}
printf("\nYou have reached your third trials. The correct number is %d.\n",
iSecret);
return 0;
}
You are incrementing tries twice: once in the for definition, and also later in the body of the loop.
Remove the extra tries++ statements.
You increment tries inside the code, as well as in the for statement. Strip out the tries++ statements in the if-blocks.
You're incrementing the variable tries multiple times during loop execution,
once every turn and everytime you didn't guess your secret right
for loop already increments tries .. you don't need to do tries++ inside if statements
you don't need the || condition in for loop as you are already doing the check in if statements
here is the fixed code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int iSecret, iGuess;
srand ( time(NULL) );
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3 ; tries++) {
printf ("Please, enter a number between 1 and 20! ");
scanf ("%d", &iGuess);
if(iGuess == iSecret){
printf ("\nCongratulations! You won!");
return 0;
}
else if (iGuess > iSecret){
printf ("\nYour guess was too high.\n");
}
else if (iGuess < iSecret){
printf ("\nYour guess was too low.\n");
}
}
printf ("\nYou have reached your third trials. The correct number is %d.\n", iSecret);
return 0;
}
Output:
$ ./test
Welcome to the number guessing game!
For each game, you have at most 3 chances to guess a secret number from 1 to 20.
Please, enter a number between 1 and 20! 2
Your guess was too low.
Please, enter a number between 1 and 20! 3
Your guess was too low.
Please, enter a number between 1 and 20! 4
Your guess was too low.
You have reached your third trials. The correct number is 10.
in addition to incrementing tries too many times, the code is overly complicated, you can simplify the logic like
int main ()
{
int iSecret, iGuess;
srand ( time(NULL) );
iSecret = rand() % 20 + 1;
int tries = 0;
printf("\nWelcome to the number guessing game!\nFor each game, you have at most 3 chances to guess a secret number from 1 to 20.\n");
for (tries = 0; tries < 3; tries++) {
printf ("Please, enter a number between 1 and 20! ");
scanf ("%d", &iGuess);
if(iGuess == iSecret) {
printf ("\nCongratulations! You won!");
return 0;
}
printf ( "\nYour guess was too %s.\n", iGuess>iSecret?"high":"low");
}
printf ("\nYou have reached your third trials. The correct number is %d.\n", iSecret);
return 0;
}

C: Creating a game, but I'm getting an off by one error and an infinite loop error in certain cases

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)

Resources