Craps game in c - c

First of all, I'm really sorry for my bad English
I tried to explain the problem as much as I can
Craps game in c
The computer rolls two dice and if the result is 7 or 11 you directly win or the result is 2,3 and 12 you directly lose.
if the sum is 4,5,6,8,9 or 10 it wants you to roll the dice again. and this time you have to find the same sum 4,5,6,8,9 or 10
if you get 7 or 11 before finding the same number you lose. (This is where the problem is, even if the computer finds the same number twice. it doesn't print out as "you won."
https://imgur.com/KL358Fi
Examples:
dices are rolling... 11 You won.
do you want to play again (y/Y – n/N)? y
dices are rolling... 3 You Lose
do you want to play again (y/Y – n/N)? y
dices are rolling... 12 Kaybettiniz
Yeni oyun oynansin mi (y/Y – n/N)? y
dices are rolling... 7 You Won.
do you want to play again (y/Y – n/N)? y
dices are rolling... 7 you won
do you want to play again(y/Y – n/N)? y
dices are rolling... 9 result is unclear, dice will be rolled again. roll (r/R)?
dices are rolling... 8 result is unclear, dice will be rolled again. roll(r/R)?
Dices are rolling... 11 result is unclear, dice will be rolled again. roll (r/R)? R
dices are rolling... 9 You won.
Yeni oyun oynansın mı (y/Y –(n/N)? e
Zarlar atiliyor... 5 result is unclear, dice will be rolled again. roll (r/R) r
Zarlar atiliyor... 10 result is unclear, dice will be rolled again. roll (r/R) r
Zarlar atiliyor... 7 You lose.
do you want to play again (y/Y – n/N)? N
CRAPS has ended.
#include<stdio.h>
#include <time.h>
int main()
{
char ynd;
int kazan=0;
int sonuc=0;
char yoyun;
do{
printf("dice is rolling ");
srand(time(NULL));
kazan = rand()%11+1;
kazan++;
if( kazan==7 || kazan==11 )
{
printf(" %d you won.\n",kazan);
}
else if( kazan==2 || kazan==3 || kazan==12 )
{
printf(" %d you lose.\n",kazan);
}
sonuc=kazan;
if( kazan==4 || kazan==5 || kazan==6 || kazan==8 || kazan==9 || kazan==10 )
{
do{
printf("%d result is unclear, dice will be rolled again roll(r/R) ",kazan);
scanf(" %s",&ynd);
printf("dice is rolling ");
kazan = rand()%11+1;
kazan++;
if(kazan == sonuc)
{
printf("%d you won",kazan);
break;
}
else if(kazan==7){
printf("%d You lose",kazan);
break;
}
}
while(ynd=='r' || ynd=='R');
}
printf("want to play a new game ( y/Y-n/N )");
scanf(" %s",&yoyun);
} while(yoyun=='y' || yoyun=='Y');
printf("craps has ended");
return 0;
}

The code you posted does appear to print out "you won" if it finds the original number before finding 7. Perhaps you fixed your error in translation?
However, it does not result in a loss if it rolls 11 before finding the duplicate.
I also see some potential improvements:
You should #include <stdlib.h> to use srand and rand (gcc automatically fixes this for you). See here. In general try to resolve warnings produced by the compiler (search for them online if you don't understand).
I recommend only using srand(time(NULL)) at the beginning of the program because if the user plays the game rapidly they will end up with identical games until the second has elapsed.
You could use rand()%6+rand()%6+2 to simulate the distribution of dice rolls (for example, 7 is more likely than any other number). Simply using rand()%11+1 results in a uniform distribution.
You incremented the dice roll with ++ and 1 directly after you called rand. It would be more straightforward to just add 2 after you call rand.
No need to check if the dice roll is indeterminate. Simply use a final else and move sonuc=kazan into the block.
You may want to look into using a jump table rather than if statements because it could be more efficient in cases like this where the input (dice roll) is tightly packed integers.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main()
{
char ynd;
int kazan=0;
int sonuc=0;
char yoyun;
srand(time(NULL));
do {
printf("dice is rolling ");
kazan = rand()%6+rand()%6+2;
if( kazan==7 || kazan==11 )
{
printf(" %d you won.\n",kazan);
}
else if( kazan==2 || kazan==3 || kazan==12 )
{
printf(" %d you lose.\n",kazan);
}
else
{
sonuc=kazan;
do {
printf("%d result is unclear, dice will be rolled again roll(r/R) ",kazan);
scanf(" %s",&ynd);
printf("dice is rolling ");
kazan = rand()%6+rand()%6+2;
if(kazan == sonuc)
{
printf("%d you won.\n",kazan);
break;
}
else if(kazan==7 || kazan==11){
printf("%d You lose.\n",kazan);
break;
}
} while (ynd=='r' || ynd=='R');
}
printf("want to play a new game ( y/Y-n/N )");
scanf(" %s",&yoyun);
} while(yoyun=='y' || yoyun=='Y');
printf("craps has ended.\n");
return 0;
}

Related

Logical Operators in C causing issue with my loop?

I am making a game for an assignment where there are 2 players and each turn the player rolls 2 die. When I ask the player if they want to roll again everything goes south from there. I'm confused because even if I change my rollAgain character to 'n' it still plays my loop where I want it to run only if rollAgain is 'y' or 'Y'. This is my first program in C, I have only programmed in Java previously. I feel like I must be checking the logical operators incorrectly in my while loop but idk what I'm doing wrong, I've looked over all the code several times now.
Here is my code:
#include <stdio.h>
#include <stdlib.h> // NULL constant, srand() & rand() functions
#include <time.h> // access your computer’s clock time
// function prototype statements
int rollDice();
int calcPoints(int die1, int die2);
char checkOne(int die1, int die2);
int main()
{
int p1Score = 0;
int p2Score = 0;
int turnTotal = 0;
char rollAgain = 'Y';
char rolled1 = 'N';
int die1;
int die2;
printf("Welcome to the Pig Game. Each turn the player rolls two dice repeatedly until a single 1 is rolled or the player holds.\n\n");
printf("If a single 1 is rolled all points are lost. If the player holds, all earned points are kept.\n");
printf("If double 1's are rolled 25 points are earned, if any other doubles are rolled the value is doubled.\n");
printf("Player 1 has an advantage because they get to go first, the youngest player gets to be Player 1.\n\n");
printf("First player to 100 points wins, let the games begin!!!\n\n");
do
{
//----------------------P1's turn starts----------------------------------------
while ((rollAgain == 'Y' || rollAgain == 'y') && rolled1 == 'N')
{
die1 = rollDice(); //roll die 1
die2 = rollDice(); //roll die 2
printf("Player 1 rolls %d, and %d\n", die1, die2);
rolled1 = checkOne(die1, die2); //check if turn ending 1 is rolled if they did the below while loop will not run and the current while loop will end.
if(rolled1 == 'N') //if a single 1 wasn't rolled calculate total for the turn
{
turnTotal += calcPoints(die1, die2);
printf("Player 1 your turn total so far is %d. Would you like to roll again?\n", turnTotal);
fflush(stdin);
scanf_s("%c", &rollAgain);
}
}
//-------------------------P1's turn is now over---------------------------------
if (rolled1 == 'Y') //turnTotal isn't added to p1Score
{
printf("Sorry Player 1 your turn is over because you rolled a 1 on a single die :(\n");
printf("Your total score is now: %d.\n", p1Score);
}
else //player1 must have held
{
printf("Congratulations on scoring %d point this turn Player 1!\n", turnTotal);
p1Score += turnTotal;
printf("Your total score is now: %d.\n", p1Score);
}
//reset variables to start p2s turn
turnTotal = 0;
rolled1 = 'N';
rollAgain = 'Y';
//----------------------P2's turn starts----------------------------------------
while ((rollAgain == 'Y' || rollAgain == 'y') && rolled1 == 'N' && p1Score < 100) //player2's turn should not start if player 1 has already won the game so we must check p1's score as well
{
int die1 = rollDice(); //roll die 1
int die2 = rollDice(); //roll die 2
printf("Player 2 rolls %d, and %d\n", die1, die2);
rolled1 = checkOne(die1, die2); //check if turn ending 1 is rolled if it was the below while loop will not run and the current while loop will end.
if(rolled1 == 'N') //if a single 1 wasn't rolled calculate total for the turn
{
turnTotal += calcPoints(die1, die2);
printf("Player 2 your turn total so far is %d. Would you like to roll again?\n", turnTotal);
fflush(stdin);
scanf_s("%c", &rollAgain);
}
}
//-------------------------P2's turn is now over---------------------------------
if (rolled1 == 'Y' && p1Score < 100) //turnTotal isn't added to p1Score
{
printf("Sorry Player 2 your turn is over because you rolled a 1 on a single die :(\n");
printf("Your total score is now: %d.\n", p2Score);
}
if (rolled1 == 'N' && p1Score < 100) //player2 must have held, use an if statement rather than else because we don't want this code to play if p1 has already won
{
printf("Congratulations on scoring %d point this turn Player 2!\n", turnTotal);
p2Score += turnTotal;
printf("Your total score is now: %d.\n", p2Score);
}
//reset variables for p1's turn
turnTotal = 0;
rolled1 = 'N';
rollAgain = 'Y';
//if either player's score is > 100 the game is now over so the game ending code will now play
} while (p1Score < 100 && p2Score < 100);
if (p1Score >= 100) //player 1 has won, congratulate them
printf("Congratulations Player 1, you have won the game! Pat yourself on the back!\n");
else //player 1 didn't win so player 2 must have won since there are no draws
printf("Congratulations Player 2, you have won the game! You are awesome!\n");
return 0; //end main
}
//function rollDice rolles the dice for the player using a random number between 1-6.
int rollDice()
{
// seed the random number generator using the computers clock
srand(time(0));
//generate a random number between 1-6
int num = (rand() % 6) + 1;
return num;
}
//function calcPoints that calculates how many points the player earned.
int calcPoints(int die1, int die2)
{
int points;
if (die1 == die2) //check if doubles were rolled
{
//snake eyes = 25 points
if (die1 == 1)
points = 25;
//regular doubles = the value on the dice *2
else
points = (die1 + die2) * 2;
}
else //doubled weren't rolled
points = die1 + die2;
return points;
}
//function checkOne that checks if the player rolled a single 1 during their turn.
char checkOne(int die1, int die2)
{
if (die1 == 1 && die2 != 1)
return 'Y';
else if (die1 != 1 && die2 == 1)
return 'Y';
else
return 'N';
}
The players turn is supposed to end if a single 1 is rolled.
I would really appreciate any help I'm not sure where I am going wrong. The code just has a mind of its own after it asks if I want to roll again.
Player 1 rolls 2, and 2
Player 1 your turn total so far is 8. Would you like to roll again?
y
Player 1 rolls 3, and 3
Player 1 your turn total so far is 20. Would you like to roll again?
Congratulations on scoring 20 point this turn Player 1!
Your total score is now: 20.
Player 2 rolls 3, and 3
Player 2 your turn total so far is 12. Would you like to roll again?
this is the output I get if I say yes to rolling again. At the end of this output it allows me to input if I want to roll again.
Player 1 rolls 3, and 3
Player 1 your turn total so far is 12. Would you like to roll again?
n
Congratulations on scoring 12 point this turn Player 1!
Your total score is now: 12.
Player 2 rolls 1, and 1
Player 2 your turn total so far is 25. Would you like to roll again?
Congratulations on scoring 25 point this turn Player 2!
Your total score is now: 25.
Player 1 rolls 1, and 1
Player 1 your turn total so far is 25. Would you like to roll again?
this is the output I get if I say no to rolling again. At the end of this output it allows me to input if I want to roll again.
There are multiple classic issues in your code:
fflush(stdin); has undefined behavior. Just remove this statement, it does not consume the pending input in stdin.
scanf_s("%c", &rollAgain); will read the pending newline in the input stream. To skip it, you can just add a space in the format string and you must test if scanf_s succeeded to avoid undefined behavior at end of file:
if (scanf_s(" %c", &rollAgain) != 1) {
exit(1); // unexpected end of file or some other error
}
You should not reinitialize the random number generator every time you roll a die, just once at the beginning of the program (move the srand() function call to the beginning of the main function, and pass it clock() that varies much more rapidly than time(NULL)):
//function rollDice rolls the die for the player using a random number between 1-6.
int rollDice() {
//generate a random number between 1-6
return (rand() % 6) + 1;
}

Number guessing game in C

I had a problem at doing my number guessing game in C. While running the program it shows up return function when I put the char element in there. Can someone help me with this? Also how can I improve my code in order to make it workable? I'M really stuck with this issue.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int main()
{
char s, n, q;
int b;
bool (1=true), (0=false);
int secret;
secret = rand();
int guess;
int seed;
srand(seed);
printf("Welcome to the guessing game!\n");
do{
printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
if((s==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
}
else if((n ==1))
{
printf("Enter a new MAXIMUM\n");
scanf("%s", rand());
if(( s ==1))
{
printf("The secret number is Between 0 AND rand(). Guess\n");
scanf("%s", b);
printf("The secret number is between 0 and rand() Guess:");
scanf("%s", b);
if(guess = rand()){
printf("Congratulations you won, You took %d guesses!", b);
break;
}
else if(guess > rand())
{
printf("Too High, Guess again:");
}
else if(guess < rand()){
printf("Too Low, Guess Again:");
}
else{
printf("This number out of the number set!");
}
}
}
else{
printf("Unrecognized command");
}
}while(q == 1);
printf("You quited the game");
return 0;
}
This code has myriad issues to resolve. I'd suggest approaching your code writing process in small steps. It appears as though you wrote the entire program in one burst, ran it, and found it didn't work instead of incrementally adding small features and running each one to verify it works before moving on to the next step. Not doing this results in a difficult to debug program and a lack of understanding about how the program operates.
To be specific, try writing a three or four line program that collects and prints user input. Is the output working as you expect? Did you test its robustness on a variety of input? Can you write it to use a variety of data types? If something isn't working, did you research the problem and resolve it before steaming ahead?
Some areas of your program to investigate:
bool (1=true), (0=false); doesn't compile and isn't necessary for the program. If you #include <stdbool.h> you don't need to do this (you can simply write if (something == true)).
srand() is not properly called or seeded. Seed it once per program using the time() call from the header you included and call rand() once per game. Use the % operator to set the function output between 0 and max.
On each turn, compare guess against the value you previously stored rand() in rather than calling rand() during each comparison, which makes the game logic arbitrary.
%s input isn't appropriate; read chars %c and ints %d, passing appropriate variable references to scanf. scanf("%s, %s, %s", s, n, q); collects 3 whitespace separated strings for input instead of 1 char as the prompt suggests.
There is no game loop. Add an inner loop to run a game when the user chooses s and move your guess/response logic there.
Use more verbose variable names and correct brackets and indentation to improve readability.
Putting it all together, here's one possible working version. It could make better use of functions and implement secure user input (exercises for the reader):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char menu_choice;
int guess;
int guesses;
int secret;
int max = 100;
srand(time(NULL));
printf("Welcome to the guessing game!\n");
for (;;) {
printf("\nMenu: (s) to start a new game, (n) to set a new range, or (q) to quit: ");
scanf(" %c", &menu_choice);
if (menu_choice == 's') {
guesses = 0;
secret = rand() % max;
for (;;) {
printf("\nThe secret number is between 0 and %d. Enter a guess: ", max);
scanf("%d", &guess);
guesses++;
if (guess == secret) {
printf("\nCongratulations, you won! You guessed %d in %d guesses!\n", secret, guesses);
break;
}
else if (guess > secret) {
printf("Too high! Guess again.");
}
else if (guess < secret) {
printf("Too low! Guess again.");
}
else if (guess >= max) {
puts("Out of range");
}
}
}
else if (menu_choice == 'n') {
printf("\nEnter a new maximum: ");
scanf("%d", &max);
}
else if (menu_choice == 'q') {
puts("\nGoodbye!");
break;
}
else {
puts("\nUnrecognized command.");
}
}
return 0;
}
Sample run:
Welcome to the guessing game!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: n
Enter a new maximum: 50
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: s
The secret number is between 0 and 50. Enter a guess: 25
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 37
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 43
Too low! Guess again.
The secret number is between 0 and 50. Enter a guess: 47
Congratulations, you won! You guessed 47 in 4 guesses!
Menu: (s) to start a new game, (n) to set a new range, or (q) to quit: q
Goodbye!
printf("Menu: (s) to start a new game, (n) to set a new range, or (q) to quit:\n");
scanf("%s, %s, %s", s, n, q);
you dont need to use three variables s,n,q. you should ask the user to enter a single choice. either to start a new game or to quit or aything else.
secondly, rand() returns a random number every time. you are supposed to store random number somewhere. like this
rand_num=rand()
also
if(guess = rand())
is a wrong way of comparison. this should be
if(guess==rand_num)
finally binary search is the solution for your problem. please refer it on internet

How to store / re-roll dices in Dice Roll simulator in C

I have searched all around when trying to search for previous questions and answers, but I can't seem to find what I am looking for. At least not for plain C, so here I go.
As part of a University Task, I am writing a Roll Dice simulator in C. I have managed the initial task to make it possible to choose up to three players/users, and I have made it possible to roll the dices three times for each player/user.
Most probably it is possible to make it even easier (with less code), but so far it is working. The next part of the task is to make it possible to save dices, and only reroll some of them. I was thinking of making integers/variables like p1_keep1 (Player 1 Dice 1), p1_keep2 (Player 1 Dice 2), and so forth, but I am really stuck in how to implement it in the code to make it possible to save some dices and reroll the rest.
I thought about making a second loop under RollingDiceP1, RollingDiceP2 and RollingDiceP3 (see the code below for refference) where the dices are rolled, but I am unsure how to implement it, without making ittoo complicated. I tried with a while loop inside the do-while loop, but it became so complicated with ten of nested 'if else', so I deleted it, convinced there has to bea better way, though I have not manage to find/spot it yet.
In order to find a solution, is there something I can do to make my initial code "easier", or in other words, can I get the same result with less code?
If I could compress the code somehow, maybe it would be easier to spot/see the solution on how to save some of the dices, while re-rolling the rest.
As I said above, I did try a while loop inside the do-while loop, but it quickly became so vast and complicated that I could not manage to tag along, and I am convinced that there are better ways, though I have not managed to spot them yet. Any tip/help or push in the right direction would be appreciated. As you might spot in the code below, this is my third week with c, and as part-time student I have not been able to work that much with c yet. I am convinced there has to be a loop of some kind though, just not sure if while, do-while or for, is the most suitable one.
This is the challenge I am currently stuck in:
Challenge: Future implement your dice program so that the user can save some dice, and then only rolling the amount of dice that they haven't saved.Like you would normally do in Yahtzee.
My present code, looks like this, and help/tip or push in the right direction are highly appreciated:
/*
Author: Thorbjørn Elvestad
Student ID: XXXXX
E-mail: XXXXXXXXXXXXX#XXXXX.XXX
This is a Roll the Dice (for Yahtzee) simulation, where the computer rolls the dice,
and present the result to the users. Only the result is presented. The
user does not physically see the dice rolled. There can be a set number
of players, and each players got three rolls each before the next player
role.
This is Activity 1 of the Week 3 weekly activity.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Setting all functions to be used in the program */
void players (void);
void RollingDiceP1 (void);
void RollingDiceP2 (void);
void RollingDiceP3 (void);
/* Loading all global variables to be available for all functions in the program */
/* Setting variable for amount of players */
int numberPlayers = 0;
/* Setting variables for player 1-3 dices */
int p1_dice1 = 0, p1_dice2 = 0, p1_dice3 = 0, p1_dice4 = 0, p1_dice5 = 0;
int p2_dice1 = 0, p2_dice2 = 0, p2_dice3 = 0, p2_dice4 = 0, p2_dice5 = 0;
int p3_dice1 = 0, p3_dice2 = 0, p3_dice3 = 0, p3_dice4 = 0, p3_dice5 = 0;
/* Seting variable for allowed rounds of rolling the dice */
int rolldice_counter = 1;
char press_enter;
/*Initiating the main function */
int main(void)
{
/* Loading the Random Number generator */
srand(time(NULL));
printf("Howdy! \n");
printf("\n Welcome to the Roll a Dice Yahtzee Simulator, \n");
/* Loading functions for choosing amount of players */
players();
printf("Let us roll some dice! \n");
RollingDiceP1();
/* Checking if there are more players waiting for their turn */
while (1)
{
if (numberPlayers == 3)
{
printf("\n \n \n \n Player two, stay tuned... \n \n");
RollingDiceP2();
printf("\n \n \n \n Player three, stay tuned... \n \n");
RollingDiceP3();
break;
}
else if (numberPlayers == 2){
printf("\n \n \n \n Player 2, stay tuned... \n");
RollingDiceP2 ();}
else
printf("No more players waiting for rolling their dice, thanks for playing! \n");
break;
}
printf("No more players waiting for rolling their dices, thanks for playing! \n");
return 0;
}
/* Lets choose how many players to use the Yahtzee Roll Dice Simulator */
void players()
{
printf("Please type how many players (1-3):");
while (1)
{
scanf("%d", &numberPlayers);
if (numberPlayers == 1)
{
printf("You have selected %d players! ", numberPlayers);
break;
}
else if (numberPlayers == 2)
{
printf("You have selected %d players! ", numberPlayers);
break;
}
else if (numberPlayers == 3)
{
printf("You have selected %d players! ", numberPlayers);
break;
}
else printf("Invalid number of players, please choose 1-3 players:");
}
}
/* Rolling dices for player 1 */
void RollingDiceP1()
{
do
{
/* Rolling the dices, and fetching random numbers between 1-6 for Player 1 dices */
printf("\n Hold tight player 1, I am rolling your dices: \n");
p1_dice1 = rand() % 6 + 1;
p1_dice2 = rand() % 6 + 1;
p1_dice3 = rand() % 6 + 1;
p1_dice4 = rand() % 6 + 1;
p1_dice5 = rand() % 6 + 1;
/* Showing the result for player 1 */
printf("Your dices show:\n Dice 1: %d \n Dice 2: %d \n Dice 3: %d \n Dice 4: %d \n Dice 5: %d \n \n", p1_dice1, p1_dice2, p1_dice3, p1_dice4, p1_dice5);
printf("This is your roll number %d of 3 rolls, press any key and enter to continue \n", rolldice_counter);
scanf("%s", &press_enter);
} while (++rolldice_counter <= 3); /* Ending the do-while loop when rolldice_counter reach 0 */
rolldice_counter = 1;
}
/* Rolling dices for player 2 */
void RollingDiceP2()
{
do
{
/* Rolling the dices, and fetching random numbers between 1-6 for Player 2 dices */
printf("\n Hold tight player 2, I am rolling your dices: \n");
p2_dice1 = rand() % 6 + 1;
p2_dice2 = rand() % 6 + 1;
p2_dice3 = rand() % 6 + 1;
p2_dice4 = rand() % 6 + 1;
p2_dice5 = rand() % 6 + 1;
/* Showing the result for player 2 */
printf("Your dices show:\n Dice 1: %d \n Dice 2: %d \n Dice 3: %d \n Dice 4: %d \n Dice 5: %d \n \n", p2_dice1, p2_dice2, p2_dice3, p2_dice4, p2_dice5);
printf("This is your roll number %d of 3 rolls, press any key and enter to continue \n", rolldice_counter);
scanf("%s", &press_enter);
} while (++rolldice_counter <= 3); /* Ending the do-while loop when rolldice_counter reach 0 */
rolldice_counter = 1;
}
/* Rolling dices for player 3 */
void RollingDiceP3()
{
do
{
/* Rolling the dices, and fetching random numbers between 1-6 for Player 3 dices */
printf("\n Hold tight player 3, I am rolling your dices: \n");
p3_dice1 = rand() % 6 + 1;
p3_dice2 = rand() % 6 + 1;
p3_dice3 = rand() % 6 + 1;
p3_dice4 = rand() % 6 + 1;
p3_dice5 = rand() % 6 + 1;
/* Showing the result for player 3 */
printf("Your dices show:\n Dice 1: %d \n Dice 2: %d \n Dice 3: %d \n Dice 4: %d \n Dice 5: %d \n \n", p3_dice1, p3_dice2, p3_dice3, p3_dice4, p3_dice5);
printf("This is your roll number %d of 3 rolls, press any key and enter to continue \n", rolldice_counter);
scanf("%s", &press_enter);
} while (++rolldice_counter <= 3); /* Ending the do-while loop when rolldice_counter reach 0 */
rolldice_counter = 1;
}

C Code, Help Needed with Randomized dice game not giving correct answer

I am trying to make a game which randomizes 3 dice rolls, displays the first sum of the 3 dice and then asks the user if they think the sum of the next roll will be higher(h), lower(l) or the same(s). I feel I am close to having it working but when I run the game, I cant seem to get the user input to "line up" with what the answer should be (if that makes sense..).
Here is my code so far:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<math.h>
#include<time.h>
int main(){
srand(time(NULL));
char userInput;
int diceOne=(rand()%6)+1;
int diceTwo=(rand()%6)+1;
int diceThree=(rand()%6)+1;
int firstRoll = diceOne+diceTwo+diceThree;
int prevSum,newSum;
printf("***Welcome to the dice guessing game!***\n\n");
printf("Rules:\n type 'quit' to exit game\n'h' for higher\n'l' for lower\n's' for same.\n\n");
printf("dice one: %d\ndice two: %d\ndice three: %d\n",diceOne, diceTwo, diceThree);
printf("The starting total is: %d\n",firstRoll);
while(&userInput!="quit" ){
void randDice (void){
diceOne=(rand()%6)+1;
diceTwo=(rand()%6)+1;
diceThree=(rand()%6)+1;
}
printf("Guess:");
scanf("%c\n\n",&userInput);
prevSum = diceOne+diceTwo+diceThree;
randDice();
newSum = diceOne+diceTwo+diceThree;
if((userInput=='h') && (prevSum > newSum)){
printf("Correct!\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
} else if((userInput=='l') && (prevSum < newSum)){
printf("Correct!\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
} else if((userInput=='s') && (prevSum == newSum)){
printf("Correct!\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
} else {
printf("Incorrect\n");
printf("The sum of the three dice was: %d \n\n", prevSum);
}
}
return 0;
}
The output from running this code is as follows:
***Welcome to the dice guessing game!***
Rules:
type 'quit' to exit game
'h' for higher
'l' for lower
's' for same.
dice one: 3
dice two: 4
dice three: 1
The starting total is: 8
Guess:h
h
Incorrect
The sum of the three dice was: 8
Guess:h
Incorrect
The sum of the three dice was: 8
Guess:h
Correct!
The sum of the three dice was: 9
Guess:l
Incorrect
The sum of the three dice was: 4
As you can hopefully see, I have to enter two inputs the first time before the game will continue to run. In the example of the output I guessed h(higher) a few times and got it correct once when the sum of the dice changes form 8 to 9, but when I enter l(lower) and the dice change from 9 to 4, I get "incorrect".
while(&userInput!="quit" ){
You are reading single chars in your function, which means this will never equal true.
scanf("%c\n\n",&userInput);
Use fgets instead and then read that into a char with sscanf

Bug in a simplified (and incomplete) version of hangman game

I have written a first version of hangman. The game will be completed later, when this part of code will work.
The code:
#include <stdio.h>
#include <conio.h>
int main()
{
char word[]={"name"};
char word0[]={"----"};
char lett;
int i;
int c;
int e=0;
while(e<12)
{
gotoxy(2,2);
printf("\n%s\n",word0);
scanf("%c",&lett);
for(i=0,c=0;i<4;i++)
{
if(lett==word[i])
{
word0[i]=word[i];
c++;
}
}
printf("%d",c);
if(c==0)
{
e++;
printf("%d",e);
}
}
printf("You lose");
getchar();
}
The program ends before I make 12 errors and prints two values per cycle (not 1, which it should do) which don't coincide with the actual number of errors. Why?
The second 'cycle', as you call it, is reading the newline character. Try changing your scanf to this:
scanf("%c\n",&lett);
The second entry you get is the new line when you press, says, "a", then "Enter". The "Enter" is a new char which is then processed by your program.
Instead of using scanf("%c",&lett);, use scanf(" %c",&lett); (with a space before the '%' => this will ignore any spaces, new lines, etc.
Some minor changes make the code work.
Note that I had to change the I/O a bit (don't have gotoxy() function, and no interactive input since I was running this on codepad.org). See where the logic of your code is different and you should have your solution.
I added intermediate printf statements so you can follow the flow more clearly - usually a good idea when you are debugging.
Note - you might want to use case insensitive string comparison...
#include <stdio.h>
#include <string.h>
int main()
{
char word[]="name";
char word0[]="----";
char guess[]="bnexacdfm";
char lett;
int i;
int c;
int e=0;
int gi = 0;
while(e<12 && gi < strlen(guess))
{
// gotoxy(2,2);
printf("\n%s\n",word0);
lett = guess[gi++];
printf("you guessed: %c\n", lett);
// scanf("%c",&lett);
for(i=0,c=0;i<4;i++)
{
if(lett==word[i]) // really want case insensitive comparison here
{
word0[i]=word[i];
printf("found %c at position %d\n", lett, i);
c++;
}
}
printf("Number correct in this guess: %d\n",c);
if(c==0)
{
e++;
printf("Total number of incorrect guesses: %d\n",e);
}
}
if(strcmp(word, word0)==0) {
printf("well done! you win\n");
}
else {
printf("Sorry - you lose\n");
}
return 0;
// getchar();
}
Output:
----
you guessed: b
Number correct in this guess: 0
Total number of incorrect guesses: 1
----
you guessed: n
found n at position 0
Number correct in this guess: 1
n---
you guessed: e
found e at position 3
Number correct in this guess: 1
n--e
you guessed: x
Number correct in this guess: 0
Total number of incorrect guesses: 2
n--e
you guessed: a
found a at position 1
Number correct in this guess: 1
na-e
you guessed: c
Number correct in this guess: 0
Total number of incorrect guesses: 3
na-e
you guessed: d
Number correct in this guess: 0
Total number of incorrect guesses: 4
na-e
you guessed: f
Number correct in this guess: 0
Total number of incorrect guesses: 5
na-e
you guessed: m
found m at position 2
Number correct in this guess: 1
well done! you win
Link to code sample: http://codepad.org/56dC0stD

Resources