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.
Related
I was trying to make a simple function to make a group of number that user enters them, using pointer of pointer but i keep getting this error and its hard to tell where the problem is, if there any other option to use something else that tells me where the problem is instead of this weird error.
#include <stdio.h>
void BuildGroub(int** group,int* count){
int i=0;
int j;
printf("Enter the size of the group \n");
scanf("%d", &*count);
while(*count != 0){
printf("Enter the %d number of the group:\n", i);
j=0;
scanf("%d", &**(group+i));
while(**(group+i)!=**(group+j)){
j++;
}
if(j==i){
i++;
count--;
} else{
printf("you have already entered this number please try again: \n");
}
}
}
int main(){
int count;
int group[100];
int *groupptr = &group;
BuildGroub(&groupptr,&count);
for(int i=0;i<count;i++){
printf("%d, ", group[i]);
}
return 0;
}
With this question, you do not need to use double pointer. If you want to learn how to use the double pointer, you can google then there are a ton of examples for you, for example, Double Pointer (Pointer to Pointer) in C.
In BuildGroub you decrease the count pointer
if(j==i){
i++;
count--;
}
, but in the condition of while loop, you compare the value that count pointer points to. it seems strange.
while(*count != 0)
Even if you change count-- to (*count)--, it will decrease the number of elements that you enter to 0 when you get out of the while loop, then in main function:
for(int i=0;i<count;i++){} // count is equal to 0 after calling BuildGroub function if you use (*count--) in while loop.
You should use a temp value for while loop function, for example:
int size = *count;
while(size != 0){
...
if (i == j) {
i++;
size--;
}
}
You should use, for example, group[i] instead of *(group+i). It will be easier to read your code.
The code complete:
#include <stdio.h>
void BuildGroub(int* group,int* count){
int i=0;
int j;
printf("Enter the size of the group \n");
scanf("%d", count);
int size = *count;
while(size != 0){
printf("Enter the %d_th number of the group:\n", i);
j=0;
scanf("%d", &group[i]);
while(group[i] != group[j]) {
j++;
}
if(j==i){
i++;
size--;
} else{
printf("you have already entered this number please try again: \n");
}
}
}
int main(){
int count;
int group[100];
int *groupptr = group;
BuildGroub(groupptr,&count);
for(int i=0;i<count;i++){
printf("%d, ", group[i]);
}
return 0;
}
The test:
./test
Enter the size of the group
5
Enter the 0_th number of the group:
1
Enter the 1_th number of the group:
2
Enter the 2_th number of the group:
2
you have already entered this number please try again:
Enter the 2_th number of the group:
3
Enter the 3_th number of the group:
3
you have already entered this number please try again:
Enter the 3_th number of the group:
4
Enter the 4_th number of the group:
5
1, 2, 3, 4, 5,
If you want to use a double pointer, you need to change your function like this:
void BuildGroub(int** group, int* count) {
int i = 0;
int j;
printf("Enter the size of the group \n");
scanf("%d", &*count); //I think this is redundant but works.
while (*count != 0) {
printf("Enter the %d number of the group:\n", i);
j = 0;
scanf("%d", (*group + i)); //The content of group + i
while ( *( *group + i) != *(*group + j)) { //the content of the content
j++;
}
if (j == i) {
i++;
(*count)--; //The content decrement
} else {
printf("you have already entered this number please try again: \n");
}
}
}
But you have a big problem in main and it is because you are using the parameter count to decrement until zero inside the function. So when the function finish, count value is zero and you don't print anything... You need to change this, using a internal variable to make the count, and finaly, setting the parameter to be using in main.
Is there any way to write this program by only using if-else, else if statements instead of using while.
And I also want all the inputs just in one line, instead of
enter the number1:
enter the number2:
enter the number3:
enter the number4:
enter the number5:
it should be like
Enter 5 numbers: _ _ _ _ _
And when I write the same largest number twice, I want this program to show me the largest number as the second-largest number, too.
For example:
Enter 5 integers: -88 53 41 53 -17
The largest one is: 53
The second largest one is: 53
53 is the multiple of 53
53 and 53 is equal to each other.
53 is an odd number.
This is my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int sayi = 0;
int sayac = 1;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
//ilk sayinin en buyuk oldugunu kabul ediyoruz.
int enbuyuk = sayi;
int ikinci_buyuk = sayi;
while (sayac != 5)
{
sayac++;
printf("Sayiyi Girin:");
scanf("%d", &sayi);
/*kitapligi ilk sayinin en buyuk oldugunu farz ediyor
* eger ikinci sayi daha buyukse buyuk olanın yerini alacak
* ayrica ikincisinide kontrol edecek
*/
if (sayi > enbuyuk)
{
ikinci_buyuk = enbuyuk;
enbuyuk = sayi;
}
else if (sayi < enbuyuk)
{
// This to avoid if numbers are arranges descending
if (sayac == 2)
{
ikinci_buyuk = sayi;
}
else if (sayi > ikinci_buyuk)
{
ikinci_buyuk = sayi;
}
//This to avoid if the user entered two equal numbers
else if (enbuyuk == ikinci_buyuk)
{
ikinci_buyuk = enbuyuk;
}
}
}
printf("sayac: %d\n", sayac);
printf("En buyuk sayi: %d\n", enbuyuk);
printf("İkinci en buyuk sayi: %d\n", ikinci_buyuk);
if (enbuyuk % ikinci_buyuk != 0)
{
printf("%d %d nin tam kati degildir. is not the multiple of", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d %d nin tam katidir. is the multiple of", enbuyuk, ikinci_buyuk);
}
if (enbuyuk != ikinci_buyuk)
{
printf(" %d ve %d birbirine esit degildir. not equal each other", enbuyuk, ikinci_buyuk);
}
else
{
printf(" %d ve %d birbirine esitir. equal each other", enbuyuk, ikinci_buyuk);
}
if (enbuyuk % 2 != 0)
{
printf("%d tek sayidir. odd number", enbuyuk);
}
else
{
printf("%d cift sayidir.even number", enbuyuk);
}
system("pause");
return 0;
}
From the title of your question:
if-else are a conditional code flow structure without any repetition. Without any other instruction (like goto for example) you can't make it a loop like while.
But I think this is not the core of your question. You seem to want to read 5 numbers and check them. For now you do this in a loop and you like to replace that loop with something else.
You can print the one and only prompt and then call a function for each of the 5 numbers to check them.
Since your variables are not translated and your intend is not clear, I'll leave the code inside the function as an exercise for you.
printf("Enter 5 integers: ");
for (int i = 1; i <= 5; ++i)
{
readnumber(/* you might need arguments */);
}
The function will read and check one number. scanf() will read just one number and leave the remainder of the input line for some next call.
void readnumber(/* see above */)
{
if (scanf("%d", &number) == 1)
{
/* handle the number */
}
else
{
/* handle the scan error */
}
}
You can read 5 numbers simply by prompting with a single printf() and reading into 5 variables, or 5 array elements with a single scanf():
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int a[5];
int first, second, i, j;
printf("Enter 5 numbers: ");
if (scanf("%d%d%d%d%d", &a[0], &a[1], &a[2], &a[3], &a[4]) != 5) {
printf("Invalid input\n");
return 1;
}
/* I cannot adapt the rest of the code because I cannot understand your language */
/* Here is my quick implementation from the desired output */
/* select the 2 largest numbers */
for (i = 0; i < 2; i++) {
for (j = i + 1; j < 5; j++) {
if (a[i] < a[j]) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
first = a[0];
second = a[1];
printf("The largest one is: %d\n", first);
printf("The second largest one is: %d\n", second);
if (second != 0 && first % second == 0)
printf("%d is a multiple of %d\n", first, second);
if (first == second)
printf("%d and %d are equal\n", first, second);
if (first % 2 != 0)
printf("%d is an odd number.\n", first);
return 0;
}
I need help with creating a Christmas tree in C which varies based on user input.
Firstly, the user is prompted for the number of levels they want on the tree. E.g. First level "*", second level "***". Two stars are added every level.
Valid levels run between 4 and 10 inclusive. Anything less than 4 or greater than 10 is invalid, an error message will be displayed in the program output and the minimum level of the tree will also be displayed (4 levels).
The final part of the tree is done by adding a trunk with a width of 3 stars and a height of 2 stars.
This is my c program. It is incomplete and I have no idea how to move on. I am totally confused.
#include <stdio.h>
void main()
{
char choice;
int level, levelcount, star, starcount;
printf("Do you want to print a Christmas Tree (Y/N)?");
scanf_s(" %c", &choice);
if (choice == 'Y')
{
printf("How tall is your Christmas Tree (Level 4 to 10)?");
scanf_s("%d", &levelcount);
starcount = 1;
for (level = 1; level <= levelcount; level++)
{
for (star = 1; star <= starcount; star++)
{
printf("*");
}
printf("\n");
}
starcount += 2;
}
else if (choice == 'N')
{
printf("Merry Christmas and Goodbye!\n");
}
}
Firstly, your code is in C and not C++. If you're using C++ you'd use functions such as cin or cout but here you're using printf and scanf.
To create this tree you're going to have two sections. One part that deals with the main tree, and the other that deals with the trunk. In the code below I used a variable offset to calculate a certain number to determine the midpoint of the tree. Basically, each level has an odd number of stars. If you subtract the offset from the number of stars, you'll find the number at the mid-point. Starting from 3 the offset is 1. 3 - 1 = 2 which is the mid-point. For every two stars added to the level, the offset must go up by one.
To print the tree:
#include <stdio.h>
void main()
{
char choice;
int level, levelcount, star, starcount, offset;
printf("Do you want to print a Christmas Tree (Y/N)?");
scanf_s(" %c", &choice);
if (choice == 'Y')
{
printf("How tall is your Christmas Tree (Level 4 to 10)?");
scanf_s("%d", &levelcount);
//Check if level is within valid range
starcount = 1;
offset = 0;
if (levelcount < 4 || levelCount > 10)
{
//Prints default tree (4 levels)
for (level = 1; level <= 4; level++)
{
for(star = 1; star <= starcount; star++)
{
printf("*");
}
printf("\n");
//Adds two stars each level
starcount += 2;
offset += 1;
}
}
else
{
//Prints tree with custom levels
for (level = 1; level <= levelCount; level++)
{
for(star = 1; star <= starcount; star++)
{
printf("*");
}
printf("\n");
//Adds two stars each level
starcount += 2;
offset += 1;
}
}
//Finds out the mid-point of the tree
int midpoint = starcount - offset;
//Prints the trunk
printf("%*s%s\n", offset - 1, "***");
printf("%*s%s\n", offset - 1, "***");
}
else if (choice == 'N')
{
printf("Merry Christmas and Goodbye!\n");
}
}
For the trunk section, since it was at a fixed width of 3 stars and had only two levels, a loop wasn't exactly necessary but it would be good to include it. The %*s was a specific modifier to print some extra spaces to the left so it would be at the mid-point of the tree.
For more on padding with spaces in C check this answer by Bill the Lizard. One of the comments below the answer will show how I managed to print a certain number of spaces determined by the variable offset - 1.
#include <stdio.h>
int main()
{
int a,b,c,d,e,f,g,h,i,j,k,row;
printf("enter rows :");
scanf("%d",&row);
printf ("* * * * * *merry christmas* * * * * *\n\n");
for (a=1;a<=row;a++)
{
for (b=row;b>=a;b--)
{
printf(" ");
}
for (c=1;c<=a;c++)
{
printf("* ");
}
printf("\n");
}
for (d=1;d<=row-2;d++)
{
for (g=row-1;g>=1;g--)
{
printf(" ");
}
printf("* *\n");
}
return 0;
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Develop a program that will play the Lotto game. The program should allow a user to
enter their 6 selected numbers and give them a set of options, each performing a
specific requirement. You must store the 6 numbers in a 1-Dimensional array.
There are a number of requirements that your program must meet. Your program
must be modularised (i.e. use functions) and each task should be dealt in a separate
function. The program should display a simple menu to the user and each option in
the menu will be implemented by calling a separate function. You must use pointer
notation to access array elements - NOT subscripts
The requirements are as follows (each implemented in a separate function):
Read the 6 selected numbers from the keyboard. Perform any necessary
validation (error-checking) required (e.g. all numbers must be different, range
1-42, etc.). THIS IS THE PART WHICH I CANNOT DO
Display the contents of the 1-D array containing your lotto numbers that you
entered.
Sort the contents of the array in increasing order (i.e. 1st element = smallest
number, 2nd element = 2nd smallest number, etc.). You may use any sorting
algorithm of your choice.
Compare your chosen lotto numbers in the 1-D array with the following
winning numbers:
1,3,5,7,9,11 - 42 (Bonus number)
5 Display the frequency of the numbers entered each time the user enters a new AND I HAVE NO CLUE HOW TO EVEN START THIS
set of numbers (without exiting the program) on the screen. For example, it
might display:
number 1 has been selected x times
number 7 has been selected x times
number 28 has been selected x times
etc.,
6 Exit program
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include <stdlib.h>
#define NUMBERS 6
// Declare Prototype
void getnumbers(int*);
void displaynumbers(int*);
void sortnumbers(int*);
void comparenumbers(int*,int*);
void frequencynumbers(int*);
void exit();
main()
{
int choice=0;
int lotto_no[NUMBERS];
int winning_no[NUMBERS]={1,3,5,7,9,11};
do
{
system("cls");
printf("\n======================MAGIC Lotto======================");
printf("\n\n\n--------------Use 1-6 to navigate the menu-------------");
printf("\n\n\n1.Pick your 6 lucky numbers");
printf("\n\n2.Disply your numbers");
printf("\n\n3.Display your lucky numbers in increasing order");
printf("\n\n4.Compare your numbers to see your prize!");
printf("\n\n5.Frequency of the numbers entered each time");
printf("\n\n6.Exit");
printf("\n\n\n========================================================");
printf("\n");
scanf("%d",&choice);
system("cls");//Clears the menu from the screen while we selesc an option from the Menu
if (choice == 1)
{
getnumbers(lotto_no);
}
if (choice == 2)
{
displaynumbers(lotto_no);
}
if(choice == 3)
{
sortnumbers(lotto_no);
}
if(choice == 4)
{
comparenumbers(lotto_no,winning_no);
}
if(choice == 5)
{
frequencynumbers(lotto_no);
}
if(choice == 6)
{
exit();
}
flushall();
getchar();
}
while(choice>1 || choice<7);
}
void getnumbers(int *lotto_no)
{
int i;
printf("Enter your numbers\n");
for(i=0;i<NUMBERS;i++)
{
scanf("%d", &*(lotto_no+i) );
if ( *(lotto_no+i) >0 || *(lotto_no + i ) <= 43 )
{
continue;
}
else
{
printf(" Please enter a value in between 1 and 42");
scanf("%d", &(*(lotto_no+i)));
}
}
}
void displaynumbers(int *lotto_num)
{
int i;
printf("Your lucky numbers are as follow:\n");
for(i=0;i<NUMBERS;i++)
{
printf("%d ",*(lotto_num+i));
}
}
void sortnumbers(int *lotto_num)
{
int i;
int j;
int temp;
for(i=0;i<NUMBERS;i++)
{
for(j=i;j<NUMBERS;j++)
{
if(*(lotto_num+i) > *(lotto_num+j))
{
temp=*(lotto_num+i);
*(lotto_num+i)=*(lotto_num+j);
*(lotto_num+j)=temp;
}
}
}
printf("Your lucky numbers are as follow:\n");
for(i=0;i<NUMBERS;i++)
{
printf("%d ",lotto_num[i]);
}
}
void comparenumbers(int *lotto_num,int *winning_num)
{
int i;
int j;
int c;
int b;
int g;
c=0;
b=42;
g=0;
for(i=0;i<NUMBERS;i++)
{
for(j=0;j<NUMBERS;j++)
{
if(*(lotto_num+i) == *(winning_num+j))
{
c++;
}
}
}
for(i=0;i<NUMBERS;i++)
{
if(*(lotto_num)==b)
{
g++;
}
}
if(c==6)
{
printf("JACKPOT!!!");
}
if(c==5)
{
printf("HOLIDAY!!!");
}
if(c==4)
{
printf("NIGHT OUT!!!");
}
if(c==3&&g==1)
{
printf("CINEMA TICKET!!!");
}
if(c==4&&g==1)
{
printf("WEEKEND AWAY!!!");
}
if(c==5&&g==1)
{
printf("NEW CAR!!!");
}
if(c<3)
{
printf("MAYBE NEXT TIME QQ :(");
}
}
void frequencynumbers(int *lotto_num)
{
}
void exit()
{
exit(0);
}
Your comparison is invalid:
if ( *(lotto_no+i) >0 || *(lotto_no + i ) <= 43 )
It means "if number is greater than 0 OR number is less or equal to 43.
Also you move on to the next number even if you enter incorrect number.
for(i=0;i<NUMBERS;)
{
int number = 0;
scanf("%d", &number);
// Replace OR with AND, and fix the upper comparison operator
if(number > 0 && number < 43 )
{
lotto_no[i] = number;
i++; // Only increase when number was correct
}
else
{
printf(" Please enter a value in between 1 and 42");
}
}
I'm trying task Number 1 & 5 here.
Lets see the first task
void getnumbers(int *lotto_no)
{
int i,j,temp;
printf("Enter 6 different numbers in the range 1-42\n");
for(i=0;i<6;i++)
{
printf("Enter number %d ",i+1);
scanf("%d",&temp);
for(j=0;j<i;j++)
{
while( (temp == *(lotto_no+j)) || (temp<1 || temp>42)) //Error checking
{
printf("Wrong input. Please enter a unique number in the range 1-42");
scanf("%d",&temp);
j=0;
}
}
*(lotto_no+i)=temp;
}
return
}
Now lets go for Task no 5. I'm taking another array int frequency[43]={0}. I'm creating another function void UpdateFrequency(int *, int *). In this frequnency will be updated and this will be called each time user enters a correct input combination i,e we should call this function in task 1.
void UpdateFrequency(int *lotto_no, int *frequency)
{
int i;
for(i=0;i<6;i++)
{
(*(frequency+(*(lotto_no+i))))+=1; //frequency[lotto_no[i]]+=1;
}
return;
}
void frequencynumbers(int *lotto_no, int *frequency)
{
int i;
for(i=0;i<6;i++)
{
printf("The frequency of number %d is %d\n",*(lotto_no+i),*(frequency+(*(lotto_no+i))));
}
return;
}
Here is one way you could go about answering your first question:
void getnumbers(int *lotto_no)
{
int i;
printf("Enter your numbers\n");
for(i=0;i<NUMBERS;i++)
{
do
{
printf("Please enter number %d, between 1 and 42\n", i+1);
scanf("%d", lotto_no+i); // or &lotto_no[i] if you prefer
}
while ( *(lotto_no + i) < 1 || *(lotto_no + i ) > 42 ); // or lotto_no[i]
printf("Number %d accepted\n", i+1);
}
}
I have removed the unnecessary & and * from your scanf as they are redundant. I reversed the inequalities so that the inner do while loop will continue for each number until a valid input is given.
An easy way to count the number of times a given number is entered would be to have an array of bins, one for each number. Then you could scanf into a temporary number and increment the corresponding element of bins:
void getnumbers(int *lotto_no)
{
int i, n, bins[42] = {}; // initialise zeroed array
printf("Enter your numbers\n");
for(i=0;i<NUMBERS;i++)
{
do {
printf("Please enter number %d, between 1 and 42\n", i+1);
scanf("%d", &n); // read into temporary variable
}
while ( n < 1 || n > 42 );
lotto_no[i] = n; // assign to lotto_no
++bins[n-1]; // increment corresponding counter
printf("Number %d accepted\n", i+1);
}
for(i=0; i<42; ++i)
{
if (bins[i] > 0) printf("number %d entered %d times\n", i+1, bins[i]);
}
}
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)