I have fixed my code style and have updated what it looks like, but it's skipping all the rounds and inputs I want to make
If I formatted the returns wrong(Which is what I'm thinking), or I didn't nest my functions properly, those are the only issues I can imagine would be wrong
#define ROUNDS 3
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main()
{
//Greets the user at the start of the round
void greeting();{
printf("Welcome to the Toothpick Game!\n");
printf("Here are the rules.\n");
printf("There are currently 31 toothpicks on the table.\n");
printf("You and I will each get a turn to pick either 1, 2, or 3 toothpick off the table.\n");
printf("The player that gets to puck the last toothpicks looses the game!\n");
printf("Sounds easy right? Well lets see if you can beat me!\n");
printf("Ready to play?... Here we go!\n");
} //display welcome message to user
for(int x = 0; x < ROUNDS; ++x)
{
int result = playRound(x + 1); //call playRound and assign result the value function returns
void winnerAnnouncment(int user);{//overall winner of round announcement
}
}
printf("********************************************************\n");
printf("Thank you for playing!\n");
return 0;
}
int playRound(int round)
{
int toothpicks = 31; //number of toothpicks to start with
int winner, taken, choice, leftover;
printf("Welcome to a new round %d!\n", round);
printf("You may go first!\n");
int leftOnTable(int toothpicks, int taken);{ //calculate number of toothpicks left
toothpicks = toothpicks - taken;
while(toothpicks != 0)//loop to control playing of the game
{
int humanPick();{ //retrieve the user's guess
int userchoice;
printf("How many toothpicks do you want to take? ");
scanf("%d", &taken);
printf("Okay... You took %d off the table", taken);
if (toothpicks = 1)
winner = 0;
int computerPick(int choice, int leftover);{ //computer makes its pick
if (toothpicks > 4){//Caculates what the computer will take based off of the users choice
choice = 4 - userchoice;
toothpicks = toothpicks - choice;
leftover = choice;
printf("I am taking %d toothpicks off the table.", choice);
}
if(toothpicks = 2 || 3 || 4)//calculates how many toothpicks the computer will take to leave one left on the table
if (toothpicks == 2){
choice = toothpicks - 1;
leftover = 1;
printf("I am taking %d toothpicks off the table.", choice);
}
if (toothpicks == 3){
choice = toothpicks - 1;
printf("I am taking %d toothpicks off the table.", choice);
}
if (toothpicks == 4){
choice = toothpicks - 1;
leftover = 1;
printf("I am taking %d toothpicks off the table.", choice);
}
if (toothpicks = 1){
choice = 1;
leftover = 0;
toothpicks = leftover;
winner = 1;
printf("I will take the last toothpick.");
}
}
}
return toothpicks;
}
}
return round;
}
Multiple times throughout the code used is an assignment operator = instead of the == likely intended.
In addition, the following:
userchoice is never initialized to a value.
Nested functions aren't supported by the C standard.
Numerous semicolons are found before the function definitions (e.g. void greeting();{...}).
This declares, but doesn't define the function. The following is code that executes in a new code block (new scope).
Incorrect || operator usage in conditionals (Broken:toothpicks == 2 || 3 || 4 Fixed: toothpicks == 2 || toothpicks == 3 || toothpicks == 4).
This condition would always be true. The conditional toothpicks == 2 is tested, if this proves untrue the conditional 3 is tested. 3 is true, and so this condition is always true.
The functions leftOnTable and greeting are never called.
Additional unused variables include: result and winner
Other logical errors may exist.
This should answer, if only partially, why the program isn't working as expected. Perhaps with more information about why nested functions are being used and the intended functionality of the program, I could provide a working code fix to every present issue.
Related
I have the following code:
do{
int health = 3;
int xVal;
int yVal;
printf("Enter an x value from 0 to 9\n");
scanf("%d", &xVal);
printf("You entered '%d'\n",xVal);
printf("Enter a y value from 0 to 9\n");
scanf("%d", &yVal );
printf("You entered '%d'\n",yVal);
printf("Value at '%d', '%d' is '%d'\n", yVal , xVal, matrix[yVal][xVal]);
if ( matrix[yVal][xVal] == 5 )
{
health = health - 1;
printf("Ouch... You have found a 5 and lost a point\n If you lose %d more, you will lose.\n", health);
}
if (health == 0)
{
isGameOver = true;
printf("You have lost.\n");
}
if ( matrix[yVal][xVal] == 9 )
{
isGameOver = true;
printf("You have won.\n");
}
} while(isGameOver != true);
The problem comes each time I find a five in the array, it only subtracts from the health counter once.
If I find 2 fives, it will stay as a 2 rather than counting down to one, the whole point of my game is that if you find 3 "5"s, you lose.
The problem is you are declaring health = 3 inside the loop, so each time it loops it resets it to 3. Move it to before the loop (ie before the "do" statement)
First, here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define NUM_SUITS 4
#define NUM_RANKS 13
bool in_hand[NUM_SUITS][NUM_RANKS] = {false};
bool newcard = {false};
int num_cards, rank, suit, totrank;
const char rank_code[] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K',};
const char suit_code[] = {'C','D','H','S'};
int main_hand ()
{
suit = rand() % NUM_SUITS;
rank = rand() % NUM_RANKS;
if (!in_hand[suit][rank]) {
in_hand[suit][rank] = true;
num_cards--;
if (suit == 0){
printf("%c of Clubs \n", rank_code[rank]);
}
else if (suit == 1){
printf("%c of Diamonds \n", rank_code[rank]);
}
else if (suit == 2){
printf("%c of Hearts \n", rank_code[rank]);
}
else if (suit == 3){
printf("%c of Spades \n", rank_code[rank]);
}
}
}
int print_hand (suit)
{
}
int totrank_check (totrank)
{
if (totrank > 21) {
printf ("You lose!");
}
else if (totrank == 21) {
printf ("You win!");
}
}
int main()
{
bool stay = {false};
srand((unsigned) time(NULL));
totrank = 0;
num_cards = 2;
printf("Your hand: ");
while (num_cards > 0) {
main_hand();
totrank = totrank + (rank + 1);
}
printf("Total rank: %d\n", totrank);
totrank_check(totrank);
printf("\n");
while (totrank < 24 && stay == false) {
printf("Another card? 1. Yes 0. No\n");
scanf("%d", &newcard);
if(!newcard) {
main_hand();
}
totrank = totrank + (rank + 1);
totrank_check(totrank);
printf("Total rank: %d\n", totrank);
printf("Stay? 1. Yes 0. No\n");
scanf("%d", &stay);
}
return 0;
}
Basically it's a code that "simulates" and hand of blackjack.
It starts, rand() chooses two numbers, the rank and the suit of the cards, that are set as true in a matrix so that they can't be chosen again in the same combination and then printed.
There's a check for the total rank of the cards (so that if it exceeds 21 you automatically lose) and then you are asked if you want another card or you want to stay.
Here's the error: if you choose that you want another cards, this new card will be the same as the last one.
Basically, you get a Ace of Spades, the and Two of Diamonds, then you want another card and you get another Two of Diamonds. And the another, and another. If you remove the rank check in the second while you can see that the rank grows based on the rank of the last card.
Before, the printfs were in that print_hand() function, and you could see that you always got the same card, now I moved them in the main_hand() function because I thought that it might be the problem (it wasn't) and because having a separate function for the print was redundant. But you can see that technically, the if(!in_hand[suit][rank]) works, because, since the card is the same, it doesn't enter the if and it doesn't get printed.
I don't know what's causing this problem. Any idea?
Please note I'm already using srand((unsigned) time(NULL)); to seed rand().
scanf("%d", &newcard); and scanf("%d", &stay); are a problem as the variables are bool, but the format specifier is for int. In 2 places, change like:
// scanf("%d", &newcard);
int t;
scanf("%d", &t);
newcard = !!t;
3 functions return int but do not return anything. Change to void functions.
// int main_hand() {
void main_hand() {
There appears to be other logic issues too.
1) Code sometimes exists without knowing if won/loss
2) #Jongware comment above correct:
Lastly: If the same random sequence is still coming up, strip code to a bare main srand time printf rand and see if that works. time(), if not working always returns -1.
Or simple add the following and verify srand() called with different values.
int main(void) {
unsigned now = (unsigned) time(NULL);
printf("now = %u\n", now);
srand(now);
First, here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define NUM_SUITS 4
#define NUM_RANKS 13
bool in_hand[NUM_SUITS][NUM_RANKS] = {false};
bool newcard = {false};
int num_cards, rank, suit, totrank;
const char rank_code[] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K',};
const char suit_code[] = {'C','D','H','S'};
int main_hand ()
{
suit = rand() % NUM_SUITS;
rank = rand() % NUM_RANKS;
if (!in_hand[suit][rank]) {
in_hand[suit][rank] = true;
num_cards--;
if (suit == 0){
printf("%c of Clubs \n", rank_code[rank]);
}
else if (suit == 1){
printf("%c of Diamonds \n", rank_code[rank]);
}
else if (suit == 2){
printf("%c of Hearts \n", rank_code[rank]);
}
else if (suit == 3){
printf("%c of Spades \n", rank_code[rank]);
}
}
}
int print_hand (suit)
{
}
int totrank_check (totrank)
{
if (totrank > 21) {
printf ("You lose!");
}
else if (totrank == 21) {
printf ("You win!");
}
}
int main()
{
bool stay = {false};
srand((unsigned) time(NULL));
totrank = 0;
num_cards = 2;
printf("Your hand: ");
while (num_cards > 0) {
main_hand();
totrank = totrank + (rank + 1);
}
printf("Total rank: %d\n", totrank);
totrank_check(totrank);
printf("\n");
while (totrank < 24 && stay == false) {
printf("Another card? 1. Yes 0. No\n");
scanf("%d", &newcard);
if(!newcard) {
main_hand();
}
totrank = totrank + (rank + 1);
totrank_check(totrank);
printf("Total rank: %d\n", totrank);
printf("Stay? 1. Yes 0. No\n");
scanf("%d", &stay);
}
return 0;
}
Basically it's a code that "simulates" and hand of blackjack.
It starts, rand() chooses two numbers, the rank and the suit of the cards, that are set as true in a matrix so that they can't be chosen again in the same combination and then printed.
There's a check for the total rank of the cards (so that if it exceeds 21 you automatically lose) and then you are asked if you want another card or you want to stay.
Here's the error: if you choose that you want another cards, this new card will be the same as the last one.
Basically, you get a Ace of Spades, the and Two of Diamonds, then you want another card and you get another Two of Diamonds. And the another, and another. If you remove the rank check in the second while you can see that the rank grows based on the rank of the last card.
Before, the printfs were in that print_hand() function, and you could see that you always got the same card, now I moved them in the main_hand() function because I thought that it might be the problem (it wasn't) and because having a separate function for the print was redundant. But you can see that technically, the if(!in_hand[suit][rank]) works, because, since the card is the same, it doesn't enter the if and it doesn't get printed.
I don't know what's causing this problem. Any idea?
Please note I'm already using srand((unsigned) time(NULL)); to seed rand().
scanf("%d", &newcard); and scanf("%d", &stay); are a problem as the variables are bool, but the format specifier is for int. In 2 places, change like:
// scanf("%d", &newcard);
int t;
scanf("%d", &t);
newcard = !!t;
3 functions return int but do not return anything. Change to void functions.
// int main_hand() {
void main_hand() {
There appears to be other logic issues too.
1) Code sometimes exists without knowing if won/loss
2) #Jongware comment above correct:
Lastly: If the same random sequence is still coming up, strip code to a bare main srand time printf rand and see if that works. time(), if not working always returns -1.
Or simple add the following and verify srand() called with different values.
int main(void) {
unsigned now = (unsigned) time(NULL);
printf("now = %u\n", now);
srand(now);
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");
}
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)