I am in trouble with my dice game. I have a task:
The rules of the game are the following:
1. The player rolls the dice and adds up the face values.
2. If the first roll is a 7 or 11, the player wins.
3. If the first roll is a 2, 3 or 12, the player looses.
4. If the first roll is any other number, that sum becomes the player's point.
5. To win, the player must continue rolling the dice until he/she “makes point.”
6. The player loses by rolling a 7 before the point.
1) Define WON and LOST as macros in your program. Use the values of 0 for WON and 1 for LOSE
2) Implement a function, with function prototype int rollDice( void );
rollDice( ) should use rand( ) to randomly generate a number between 1 - 6
return the number generated by rand( )
3) Implement a function, with function prototype int playGame( void );
When the player is ready to play, (s)he would use the key ENTER to roll the dice
If the user wins in his/her first roll, congratulate the player and return with WON
If the user looses in his/her first roll, congratulate the player and return with LOSE
Let the user keep playing until (s)he wins / loses, give an appropriate massage and finish the game with the last roll value.
4) Your main( ) should
Call your function playGame( )
Ask the user if (s)he wants to continue playing another game, keeping track of the numbers of losses and wins
When the user decides to finish playing, display the number of wins and losses (s)he had.
Give the user an appropriate message depending on the number of wins or losses (s)he had
Return with a value of EXIT_SUCCESS
Here is what I have now, but it tells me that there are mistakes. Can anyone please help me with this task?
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#define WON 0
#define LOSE 1
int rollDice(void);
int playGame(void);
int rollDice(void) {
return ((rand() % 6) + 1);
}
int playGame(void){
int dice_1 = 0;
int dice_2 = 0;
int sum = 0;
time_t t;
srand(time(&t));
printf("ROLL THE DICE WITH [ENTER]\n");
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
if (sum == 7 || sum == 11){
printf("Congratulations you roll %d and WON at your first try!", sum);
}
else {
printf("Your roll was %d ,you lose try agian.\n", sum);
}
return 0;
}
int main (void){
playGame();
}
The Error is (in gcc linux):
x.c:9:1: error: stray ‘\302’ in program
int rollDice(void);
^
x.c:9:1: error: stray ‘\240’ in program
x.c:10:1: error: stray ‘\302’ in program
int playGame(void);
^
x.c:10:1: error: stray ‘\240’ in program
x.c:12:1: error: stray ‘\302’ in program
int rollDice(void) {
^
x.c:12:1: error: stray ‘\240’ in program
x.c:16:1: error: stray ‘\302’ in program
int playGame(void){
^
x.c:16:1: error: stray ‘\240’ in program
There are a few things wrong here.
You're not reading/using the return value from playGame(). You should be storing the result and acting on it.
Your logic isn't complete, as the criteria for "playing for point" and a loss both are the same.
You don't have anything in place that forces the program to wait for the user to press ENTER.
I have included a completed code listing for you below.
Code Listing
/*******************************************************************************
* Preprocessor directives
******************************************************************************/
#include <stdio.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include <stdbool.h>
#define WON 0
#define LOSE 1
/*******************************************************************************
* Function prototypes
******************************************************************************/
int rollDice(void);
int playGame(void);
/*******************************************************************************
* Function definitions
******************************************************************************/
/*----------------------------------------------------------------------------*/
int rollDice(void) {
return ((rand() % 6) + 1);
}
/*----------------------------------------------------------------------------*/
int playGame(void){
int dice_1 = 0;
int dice_2 = 0;
int sum = 0;
int result;
int point = 0;
time_t t;
bool playForPoint = false;
srand(time(&t)); // Initialize random seed
printf("ROLL THE DICE WITH [ENTER]\n");
fgetc(stdin);
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
printf("D1:%2d - D2:%2d - Sum:%2d\n", dice_1, dice_2, sum);
switch ( sum )
{
case 7:
case 11:
result = WON;
break;
case 2:
case 3:
case 12:
result = LOSE;
break;
default:
playForPoint = true;
point = sum;
printf("Playing for point:%d. Please hit enter.\n", point);
fgetc(stdin);
break;
}
while ( playForPoint )
{
dice_1 = rollDice();
dice_2 = rollDice();
sum = dice_1 + dice_2;
printf("D1:%2d - D2:%2d - Sum:%2d\n", dice_1, dice_2, sum);
if ( sum == 7 ) {
playForPoint = false;
result = LOSE;
} else if ( sum == point ) {
playForPoint = false;
result = WON;
} else {
printf("Please roll the dice again with [ENTER].\n");
fgetc(stdin);
}
}
return result;
}
/*----------------------------------------------------------------------------*/
int main (void){
int result = playGame();
switch ( result )
{
case WON:
printf("You won the game.\n");
break;
case LOSE:
printf("You lost the game.\n");
break;
default:
printf("Something went wrong in the program.\n");
break;
}
return 0;
}
Sample Output
ROLL THE DICE WITH [ENTER]
D1: 3 - D2: 5 - Sum: 8
Playing for point:8. Please hit enter.
D1: 3 - D2: 1 - Sum: 4
Please roll the dice again with [ENTER].
D1: 3 - D2: 2 - Sum: 5
Please roll the dice again with [ENTER].
D1: 1 - D2: 5 - Sum: 6
Please roll the dice again with [ENTER].
D1: 3 - D2: 2 - Sum: 5
Please roll the dice again with [ENTER].
D1: 2 - D2: 6 - Sum: 8
You won the game.
You haven't yet satisfied the rules of the game. Your code takes 7 and 11 as winners and any other number as a loser.
After the 7/11 check, you need to check for 2, 3, or 12 and print a "lose" message if true. If not, you have the point number, and you need to prompt the user to keep rolling until he either gets the point number (win) or a 7 (lose).
You also need to keep track of wins/losses in main. You'll need to call playGame in a loop, prompting the user to continue on each iteration.
Related
Write a code for a game called double dices.
Each player takes their turn to roll two dices. (So, player one rolls 2 dices then player 2 rolls two dices). To roll a dice player 1 presses the number 1 and player 2 presses the number 2. The dice numbers are from 1 to 6. If the sum of the two dices = 12 then that player is the winner
If the sum of the two dices = 10 the player gets a golden token 2 golden tokens without the any player reaching sum 12 will automatically make the player the winner. Create a module that checks for the winner and output who the winner is.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define Roll 2
// Function Declarition
void winner(int [], int []);
int main()
{
int player1[Roll], player2[Roll], p1sum=0, p2sum=0;
int i, j, dice, p1[0], p2[0];
srand(time(0));
// Prompts Player 1 to press enter.
printf("\n Player 1: Press Enter to roll your dice!!!\n");
getc(stdin);// collects the propmt.
//
for(i = 0; i < Roll; i++)
{
player1[i] = (rand() % 6) + 1;
p1sum += player1[i];
}
printf("\t Player 1 rolled %d dice\n\t The Sum of the two rolls are: %d\n", i + 0, p1sum);
printf("\n Player 2: Press Enter to roll your dice!!!\n");
getc(stdin);
for(j = 0; j < Roll; j++)
{
player2[j] = (rand() % 6) + 1;
p2sum += player2[j];
}
printf("\t Player 2 rolled %d dice\n\t The Sum of the two rolls are: %d\n", j + 0, p2sum);
// initializing an array to variable p1sum.
// Function Call.
winner(p1sum, p2sum);
return 0;
}
void winner(int p1sum [], int p2sum [])
{
int x, w;
//int p1sum = p1[0];
//int p2sum = p2[0];
p1sum[0];
p2sum[0];
for (w=0; w < Roll; w++)
{
if (p1sum == 12)
{
printf("\nPlayer 1, You've Won the prize");
}
else if (p2sum == 12)
{
printf("\nPlayer 2, You've Won the prize");
}
else if (p1sum == 10)
{
printf("\nPlayer 1 gets a golden token");
}
else if (p2sum == 10)
{
printf("\nPlayer 2 gets a golden token");
}
}
}
make methods like:
int rollDice(int rollCount);
boolean findWinner(int score1, int score2);
Then code something like this:
int sum1,sum2;
do {
sum1 = rollDice(2);
sum2 = rollDice(2);
}while(!findWinner(sum1, sum2))
I am new to programming C and I don't know why my program is not printing the desired output.
#include <stdio.h>
void main(void)
{
char res,res1;
float money=10;
printf("***Wealcome to Peace of Mind***");
printf("\nHello we have the menu please check::");
printf("\n***Menú***");
printf("\n");
printf("\n<<<Bebidas>>>");
printf("\n 1 - Coca-Cola = 1,5 2 - IceTea = 1,4");
printf("\n 3 - Super Bock = 1,70 4 - Sumol = 1,6");
printf("\n");
scanf("%d",&res);
switch(res)
{
case 1 || 'Coca-Cola':money - CocaCola;break;
}
printf("%.1f",money);
//Is that result i want:
printf("\n%.1f",10-1.5);
}
Output of my program:
The syntax of your case statement is not correct. Also the code is using scanf() to read an integer, but storing the integer-sized value in a char.
I tidied up the code:
#include <stdio.h>
int main(void)
{
int res;
float cost = 0;
float money = 10;
printf("***Wealcome to Peace of Mind***\n");
printf("Hello we have the menu please check::\n");
printf("***Menú***\n");
printf("\n");
printf("<<<Bebidas>>>\n");
printf(" 1 - Coca-Cola = 1,5 2 - IceTea = 1,4\n");
printf(" 3 - Super Bock = 1,70 4 - Sumol = 1,6\n");
printf("\n");
scanf("%d", &res);
switch(res)
{
case 1:
cost = 1.5;
break;
case 2:
cost = 1.4;
break;
// TODO: case 3 & 4
default:
printf("Invalid Entry\n");
cost = 0;
}
printf("money = %.1f\n", money - cost);
return 0;
}
Some further notes:
As commentators pointed out, put \n at the end of the string
When you compile, turn on warnings, and try to fix all of them.
In case blocks, it's good practice to have a default to catch errors
It would be worthwhile to store the drink prices as #define constants (or as an array of values, or some common area so the value is only set once in the program, and everything else just references that.)
#define COLA_COST 1.5
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;
}
I am trying to ask for 20 integers and count when then number 2 and 5 are selected with a static variable. This is what I can up with using code blocks. it is not asking for 20 number only 1.
#include <stdio.h>
#include <stdlib.h>
int totalCount2(int ); \*this is where i added the function call*\
int totalCount5(int );
void output( int, int);
int main()
{
int count2;
int count5;
int yourNumber;
int yourNumberCounter;
yourNumberCounter = 1;
count2 =0;
count5 =0;
printf("Please enter a number between 1 and 6.\n");
scanf("%d", &yourNumber);
while(yourNumberCounter<= 20)
{
if(yourNumber ==2){
totalCount2(count2);
break;
}
else if(yourNumber ==5){
totalCount5(count5);
break;
}
else if(yourNumber <= 6 || yourNumber >=1){
yourNumberCounter = yourNumberCounter +1;
}
else if(yourNumber >6 || yourNumber <6){
printf("You have to choose a number between 1 and 6. try again");
}
}
return 0;
}
int totalCount2(int count2){
static int count2only;
count2only = count2++;
return count2only;
}
int totalCount5(int count5){
static int count5only;
count5only += count5;
return count5only;
}
void output(count2, count5){
printf("Out of the 20 numbers you input. You entered the number two %d times\n You entered the number five %d times\n", count2, count5);
return;
}
I am not sure if I am using static variables count2 and count5 correctly. I am studying from a book and think maybe someone sees something I am doing wrong.
printf("Please enter a number between 1 and 6.\n");
scanf("%d", &yourNumber);
while(yourNumberCounter<= 20)
is outside of the loop
should be
while(yourNumberCounter<= 20){
printf("Please enter a number between 1 and 6.\n");
scanf("%d", &yourNumber);
The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.
delete all the breaks.
also learn to use the debugger.
google: "how to debug c code" and the name of your IDE - the program you write code with.
I'm learning C and find rand() very strange:
I've the following game:
I have played the game several times and the correct answer was something near 47.
For example:
between 1 and 100 it would be 47
between 1 and 500 it would be 247 or 347.
between 1 and 1000 it would be 347.
I don't want the number to be easily guessed after the third time.
Is there any problem? how can I modify this code to do the job?
#include<stdio.h>
#include<stdlib.h>
void main()
{int n,l,c,tries;
char yn;
first:
n=0,c=0,l=0,tries=0;
do{
printf(" 1: Easy\n 2:Medium\n 3:hard\n");
scanf("%d",&l);
}while(l<1 || l>3);
switch(l)
{
case 1:
n = rand % 100 +1;
printf("I picked a number between 1 and 100\n");
break;
case 2:
n = rand()%500 + 1;
printf("I picked a number between 1 and 500\n");
break;
case 3:
n = rand()%1000 + 1;
printf("I picked a number between 1 and 1000\n");
break;
}
do
{
tries++;
printf("Enter your guess: \t");
scanf("%d",&c);
if(c == n)
printf("You Won\n number of gusses= %d\n", tries);
else
{
if(c > n)
printf("High\n");
else
printf("Low\n");
}
}while(c !=n);
printf("Try Again \?(Y/N)\n");
scanf(" %c",&yn);
if(yn == 'Y' || yn == 'y')
goto first;
}
If you reboot your pc you'll see that the results will be different.
Random is not clever as you expect, and, to tell you the truth, is not properly random! (:
By the way, to provide a different seed to the random alghoritm, you have to call, only one time:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
srand(time(0));
Take a look to the documentation!
edit
To improve your code:
int randN = 100;
switch (l) {
case 1:
break;
case 2:
randN = 500;
break;
case 3:
randN= 1000;
break;
default:
randN = rand() % 1000 + 1;
break;
}
n = rand() % randN + 1;
printf("I picked a number between 1 and %i.\n", randN);
use srand and then use rand i.e
int main()
{
srand(time(0)); // use current time as seed for random generator
int random_variable = rand();
printf("Random Value= %d",random_variable);
return 0;
}