I have been working on this simple program for about an hour and I really don't understand where my logic went wrong. The 'game' is suppose to end when either player 1 or player 2 takes the last marble in the bag. I added comments to my code explaining what I am trying to do. Can someone please help?
Instructions:
Write a program to play a game of marbles. The game starts with 32 marbles and two players. Each player must take 1, 2 or 3 marbles on their turn. Turns go back and forth between the two players. The winner is the person who takes the last marble. Your program should prompt each player with a message that states the current number of marbles and asks them how many they'd like to take. Continue until there is a winner. Then your program should print out the winner (either player #1 or player #2.)
My Code:
Code:
#include <stdio.h>
int main() {
int num_marbles1, num_marbles2, all_marbles=32;
printf("There are 32 marbles remaining.\n\n");
while(all_marbles!=0 && all_marbles>0){ //while loop that runs as long as the number of marbles is NOT equal to 0
printf("How many marbles would you like to take? ...Player 1\n");
scanf("%d", &num_marbles1);
printf("There are %d marbles remaining\n\n", all_marbles=all_marbles-num_marbles1); //resets 'all_marbles' value after player 1 takes
out selected number of marbles
printf("How many marbles would you like to take? ...Player 2\n");
scanf("%d", &num_marbles2);
printf("There are %d marbles remaining.\n", all_marbles=all_marbles-num_marbles2);//resets 'all_marbles' value after player 2 takes out
selected number of marbles
if (all_marbles-num_marbles1<0 || all_marbles-num_marbles2<0) //in the case that the user tries to take out more marbles then what is in the bag
printf("\n Sorry, you both lose.\n");
else if (all_marbles-num_marbles1==0) //in the case that player one takes the last marble in the bag
printf("\nPlayer 1 Wins.\n");
else if (all_marbles-num_marbles2==0) //in the case that player two takes the last marble in the bag
printf("\nPlayer 2 Wins.\n");
}
system ("PAUSE");
return 0;
}