Today's lecture covered how to make a code for 'Number Baseball Game' in C Programming.
Here's the rules of 'Number Baseball Game' as below.
1. Generate 3 digits randomly 2. Enter 3 digits to get the right answer. 3. If the digit position and value of the entered number are the same, it is considered a strike. 4. The digit position of the entered number is different, but if the value is the same, it is considered a ball. 5. Out if the number you enter does not have the same number as the number you created. 6. If you get the right answer before 3 outs, you win. If you get 3 outs, you lose. |
And I practice to write a code for implementing the 'Number Baseball Game' as below.
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
/* Initialize the variable for putting the values */
int Q_num1, Q_num2, Q_num3;
int A_num1, A_num2, A_num3;
int input;
int strike = 0, ball = 0, out = 0;
/* Initialize the randum seed function */
srand((unsigned)time(NULL));
/* Check the first number */
Q_num1 = rand() % 10;
/* Check the second number */
Q_num2 = rand() % 10;
while (Q_num2 == Q_num1) {
Q_num2 = rand() % 10;
}
/* Check the third number */
Q_num3 = rand() % 10;
while ((Q_num3 == Q_num1) || (Q_num3 == Q_num2)) {
Q_num3 = rand() % 10;
}
while(1) {
/* Input the number */
printf("Please input the number \n");
scanf("%d", &input);
A_num1 = input/100;
A_num2 = (input%100)/10;
A_num3 = input%10;
/* Checking the first number whether strike or ball */
if (A_num1 == Q_num1) strike++;
else if (A_num1 == Q_num2) ball++;
else if (A_num1 == Q_num3) ball++;
/* Checking the second number whether strike or ball */
if (A_num2 == Q_num1) ball++;
else if (A_num2 == Q_num2) strike++;
else if (A_num2 == Q_num3) ball++;
/* Checking the third number whether strike or ball */
if (A_num3 == Q_num1) strike++;
else if (A_num3 == Q_num2) ball++;
else if (A_num3 == Q_num3) strike++;
/* Counting when the strike and ball are zero */
if ((strike == 0) && (ball == 0)) out ++;
printf("%d strike, %d ball, %d out \n", strike, ball, out);
/* If input number make 3 strike, the player won the game */
if (strike == 3) {
printf("Player win \n");
printf("Anwer is %d%d%d, Q_num1, Q_num2, Q_num3);
break;
}
/* If input number make 3 out, the player fail the game */
if (out == 3) {
printf("Player fail \n");
printf("Answer is %d%d%d, Q_num1, Q_num2, Q_num3);
break;
}
/* Initialize the count */
strike = 0;
ball = 0;
}
return 0;
}
'Study Meeting > 빡공단 30기' 카테고리의 다른 글
[Day 15] How to use one-dimensional array (0) | 2023.01.17 |
---|---|
[Day 13] Repeated Statement: for and while (0) | 2023.01.13 |
[Day 12] Conditional Statement 2: switch - case (0) | 2023.01.12 |
[Day 11] Conditional Statement 1: if and else (0) | 2023.01.11 |
[Day 10] Operator 3: Bitwise Shift Operator (0) | 2023.01.11 |