C | Comparison between two groups of arrays - c

I'm pretty fresh in the computers world and started to work on c.
now i'm building a little project about generating code (shown below):
My main:
#include <stdio.h>
#include "connect.h"
#define EASY 20
#define NORMAL 15
#define HARD 10
#define CRAZY 30
int main ()
{
int choice = 1;
char enter, returnV;
system("cls");
printf("Welcome to ""THE MAGSHIMIM CODE BREAKER""!!!\n");
printf("\n");
printf("A secret password was chosen to protect the credit card of Pancratius,\nthe descendant of Antiochus\n");
printf("Your mission is to stop Pancratius by revealing his secret password.\n");
printf("the rules are the follows:\n");
printf("\n");
printf("1. In each round you try to guess the secret password (4 distinct digits)\n");
printf("2. After every guess you'll receive two hints about the password");
printf("\nHITS the number of digits in your guess witch were exactly right.\n");
printf("MISSES the number of digits in your guess witch belong to the password but weremiss-placed\n");
printf("3 - if you'll fail to guess the password after a certain number of rounds \tPancratius will buy all the gift to Hanukkah!!!\n");
printf("\n");
printf("Press Enter to continue...\n");
enter = getch();
if (enter = '\n'){
do{
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
if (choice == 1 || choice == 2 || choice == 3 || choice == 4 ){
switch(choice){
case (1):
system("cls");
returnV = levels(EASY);
break;
case (2):
system("cls");
returnV = levels(NORMAL);
break;
case (3):
system("cls");
returnV = levels(HARD);
break;
case (4):
system("cls");
returnV = levels(CRAZY);
break;
switch(returnV){
case('y'):
break;
case('n'):
return 0;
break;
}
}
}
else if (choice != 1 || choice != 2 || choice != 3 || choice != 4 ){
system("cls");
printf("please choose level:\n");
printf("1 - easy (20 rounds)\n");
printf("2 - normal (15 rounds)\n");
printf("3 - hard (10 rounds)\n");
printf("4 - crazy (random number of rounds 5-25)\n");
printf("Make a choice:");
_flushall();
scanf("%1d",&choice);
}
} while (returnV != 'n');
}
system("PAUSE");
}
header file to connect:
char levels (int level);
"levels" function:
#include <stdio.h>
#include "connect.h"
#include <time.h>
#include <stdlib.h>
char cases (int myCase, char crazyl);
char levels (int level) {
char crazyl = 'n',playerChoice;
switch (level){
case (20):
playerChoice = cases (level,crazyl);
printf ("\n%c\n",playerChoice);
return playerChoice;
break;
case (15):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (10):
playerChoice = cases (level,crazyl);
return playerChoice;
break;
case (30):
crazyl = 'x';
level = rand() % (25 - 5 + 1);
playerChoice = cases (level,crazyl);
return playerChoice;
}
}
int ranGen (int code1,int code2, int code3, int code4);
char cases (int level,char crazyl)
{
unsigned int check;
char choise = 't',code1,code2,code3,code4;
if(level > 0){
while (level > 0){
if(crazyl == 'n'){
printf("Write your guess (only 1-6, no ENTER is needed) [%d guess left]\n",level);
}
else if (crazyl == 'x'){
printf("Write your guess (only 1-6, no ENTER is needed) [xxx guess left]\n");
}
code1 = getch();
printf("%c",code1);
code2 = getch();
printf("\t%c",code2);
code3 = getch();
printf("\t%c\t",code3);
code4 = getch();
printf("%c\n",code4);
if(code1 > '0' && code1 < '7' && code2 > '0' && code2 < '7' && code3 > '0' && code3 < '7' && code4 > '0' && code4 < '7'){
check = ranGen(code1,code2,code3,code4);
level--;
} else {
printf("\nnot a good number only numbers between 1-6\n");
level--;
}
if (level == 0) {
printf("FOR GOD SAKE WE LOST!!!\n");
printf("The secret password was:\n");
while (choise != 'y' || choise != 'n') {
if (choise != 'y' || choise != 'n') {
printf("keep playing? (y/n):");
_flushall();
scanf("%1c",&choise);
if (choise == 'y' || choise == 'n' ) {
return choise;
} else {
continue;
}
}
}
}
}
}
}
int ranGen(int code1,int code2, int code3, int code4) {
unsigned int ranCode[3],check,code[3];
code[0] = (int) code1 - 48;
code[1] = (int) code2 - 48;
code[2] = (int) code3 - 48;
code[3] = (int) code4 - 48;
do {
ranCode[0] = rand() % (6 - 1 + 1);
ranCode[1] = rand() % (6 - 1 + 1);
ranCode[2] = rand() % (6 - 1 + 1);
ranCode[3] = rand() % (6 - 1 + 1);
} while (code[0] != ranCode[0] || code[1] != ranCode[1] || code[2] != ranCode[2] || code[3] != ranCode[3]);
}
Now my problem is in ranGen function at "levels" paste.
I need to Generate 4 random numbers between 1-6 that different from each other
(1234 is ok, 1878 not ok, 2234 not ok either) and that the user will guess the digits while if he made a correct digits lets say:
generated code = 2345
guess = 1364
The user will get: 1 HIT and 1 MISS while if user will input 2222 he will get 1 HIT and 3 MISSES.
Now im pretty lost here and any help will be great.

I see the problems in your ranGen() function...
you have...
unsigned int ranCode[3],check,code[3];
ranCode[3] gives you 3 elements in that array. Array elements start counting at zero, so that would give you ranCode[0], ranCode[1] and ranCode[2]. If you want ranCode[3] and code[3], than you need to change the above line to...
unsigned int ranCode[4],check,code[4];
That gives you 4 elements, numbered from 0 to 3 (0, 1, 2 & 3 equals 4 numbers).
I'm also not certain what you are trying to do with...
ranCode[0] = rand() % (6 - 1 + 1);
...in your program, it will evaluate what is inside the brackets first, so 6 - 1 = 5, + 1 = 6. So in essence, that line will also look like ranCode[0] = rand() % 6; to the compiler and will give a number from 0 to 5. If you wish to add one to the result, you can use: ranCode[0] = (rand() % 6) + 1;, that would do the random number first, then add one to it for 1 to 6 (which is what I assume you wanted for a dice roll?).
Anyhow, you're passing code4 to a nonexistent element, out of range and probably corrupting memory somewhere, which would have undefined behaviour, possibly crash the system, or effect another variable's memory etc.

Related

My program immediately exits after it asks for a character [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 1 year ago.
I hope you are doing well everyone. I was given this homework by my teacher.
Which is the problem below:
Write a program that will ask for n positive whole numbers. Your program will only stop asking for a number if the input number is 0 or < 0. From these inputs, determine all the prime numbers. After determining the prime numbers, write a menu option shown below:
[A] Display One’s
[B] Display Ten’s
[C] Display Hundred’s
[D] Display Thousand’s
If the user presses on of these options, then it will display what is being asked. To further understand and shorten the instructions, an illustration is provided below.
Input numbers: 123, 112, 1377, 2, 13, 0
Prime numbers: 123 1377 2 13
If the user presses ‘A’, then the output is
123 = 3
1377 = 7
2 = 2
13 = 3
If the user presses ‘B’, then the output is
123 = 23
1377 = 77
2 = 0
13 = 13
If the user presses ‘C’, then the output is
123 = 123
1377 = 377
2 = 0
13 = 0
If the user presses ‘D’, then the output is
123 = 0
1377 = 1377
2 = 0
13 = 0
I've written a program that I thought would solve the problem, but somehow after I input a character (A,B,C,D) the program immediately terminates?
If someone could point any other mistakes or have any suggestions in mind. I'll be open to them and I'll be grateful. Thanks so much in advance. :))
#include<stdio.h>
int isPrime(int num);
void Sort(char sort, int psize, int* prime);
int main ()
{
int psize=0;
int i, num=1;
int arr[1000], prime[1000];
char sort;
do
{
printf("Enter array element:");
scanf("%d", &num);
if(num<=0) break;
if(isPrime(num))
{
prime[psize]= num; //assign to prime array if it is a prime
psize++;
}
} while(num>0);
printf("\nEnter [A] to Display One's\nEnter[B] Display Ten's\nEnter[C]Display Hundred's\nEnter[D]Display Thousand's");
scanf("%c", &sort);
Sort(sort, psize, prime);
}
int isPrime (int num)
{
int i, flag=1;
for(i=2;i<num;i++)
{
if(num%i==0)
{
flag=0;
break;
}
}
return flag;
}
void Sort(char sort, int psize, int* prime)
{
int i, ans;
if(sort == 'A'){
printf("Ones\n");
for(i=0;i<psize;i++)
{
ans = prime[i] % 10;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'B'){
printf("Tens\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 10)
ans = prime[i] % 100;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'C'){
printf("Hundreds\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 100)
ans = prime[i] % 1000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
else if(sort == 'D'){
printf("Thousands\n");
for(i=0;i<psize;i++)
{
if(prime[i] >= 1000)
ans = prime[i] % 10000;
else
ans = 0;
printf("%d = %d\n", prime[i], ans);
}
}
}
I think that will help you out.
put a fflush() after your scanf function like:
scanf("%d", &num);
fflush(stdin);
Or you use a easier way
int getNumber()
{
char userinput = '1';
int number = 0;
/*
Ascii-table
0 = 48
1 = 49
...
9 = 57
*/
while(1)
{
userinput = getchar();
if (userinput == '\n') break;
if (userinput >= 48 && userinput <= 57)
number = (number * 10) + (userinput - 48);
}
return number;
}
Replace your scanf("%d", &num); with num = getNumber(); - that works!
So, here another code with A-D letters
I hope this will be enough now - And all useres forgive me for my uncomplete code review ^^" :
int getNumber( int opt )
{
char userinput = '1';
int number = 0;
/*
Ascii-table
0 = 48
1 = 49
...
9 = 57
*/
while(1)
{
userinput = getchar();
if (userinput == '\n') break;
/*
opt (Options)
1: Numbers
2: Letters A-D
Other numbers undefined!
*/
switch(opt)
{
case 1:
/* Only 0-9 allowed */
if (userinput >= 48 && userinput <= 57)
number = (number * 10) + (userinput - 48);
break;
case 2:
/* Only A-D allowed */
if (userinput >= 'A' && userinput <= 'D')
number = userinput;
break;
default:
/* Nothing to do - wrong input */
number = 0;
break;
}
}
return number;
}
Replace your scanf("%d", &num); with num = getNumber(1);
Replace your scanf("%d", &sort); with sort = getNumber(2);

Re-assign value to variable if rand() repeats a number

I am making a tic tac toe game in which the user competes against the computer. Whenever the person chooses a spot between 1 and 9, the computer needs to choose one too. For this, I am using rand(). However, if the spot is already taken, I need the computer to calculate a new one. I've tried using while and do-while loops but when I apply them, cmd stops working and doesn't let me continue the game.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct symbol{
int marcado;
char simbolo;
} SPOT;
SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};
void table();
void User();
void AI();
int main(){
system("cls");
User();
AI();
Check();
return 0;
}
void table(){
printf("\n %c | %c | %c ",spot1.symbol,spot2.symbol,spot3.symbol);
}
this is the function in which the user chooses a spot:
void User(){
char choice;
do{
do{
board();
printf("\n\nChoose a spot: ");
fflush(stdin);
scanf("%c",&choice);
}while(choice < '1' || choice > '3');
switch(choice){
case '1': if(choice == '1'){
system("cls");
if(casilla1.marcado == 1){
printf("\noccupied\n");
}
else if(casilla1.marcado == 0){
casilla1.marcado = 1;
casilla1.simbolo = 'X';
AI();
}
}
break;
case '2': if(choice == '2'){
system("cls");
if(casilla2.marcado == 1){
printf("\noccupied\n");
}
else if(casilla2.marcado == 0){
casilla2.marcado = 1;
casilla2.simbolo = 'X';
AI();
}
}
break;
case '3': if(choice == '3'){
system("cls");
if(casilla3.marcado == 1){
printf("\noccupied");
}
else if(casilla3.marcado == 0){
casilla3.marcado = 1;
casilla3.simbolo = 'X';
AI();
}
}
break;
}while(Check() != 0 && Check() != 1);
}
and this is the function for the computer. In which I am having trouble in the 'else if' statements since I don't know what to put in them.
void AI(){
int random;
srand(time(NULL));
random = rand() % 3 + 1;
if (random == 1){
if(casilla1.marcado == 0){
casilla1.simbolo = 'O';
casilla1.marcado = 1;
}
else if(casilla1.marcado == 1){
random = rand() % 3 + 1
}
}
if (random == 2){
if(casilla2.marcado == 0){
casilla2.simbolo = 'O';
casilla2.marcado = 1;
}
else if(casilla2.marcado == 1){
random = rand() % 3 + 1;
}
}
if (random == 3){
if(casilla3.marcado == 0){
casilla3.simbolo = 'O';
casilla3.marcado = 1;
}
else if(casilla3.marcado == 1){
random = rand() % 3 + 1;
}
}
}
As I said before, I've tried putting the whole AI() inside the different types of loops, putting only rand() inside them, and so on, and still can't get it to work.
First, choose your data structures better. Instead of:
SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};
use
SPOT casilla[3] = { {0,'1'}, {0,'2'}, {0,'3'} };
As a consequence, the switch constructs are not needed any longer. Instead of:
if(casilla1.marcado == 0){
if(casilla2.marcado == 0){
if(casilla3.marcado == 0){
use:
if(casilla[random-1].marcado == 0){
the person chooses a spot between 1 and 9
and
random = rand() % 9 + 1;
You only have 3 casilla. Where are the other 6?
I've tried using while and do-while loops
In AI() there are no loops. Maybe you can show us a code with loops?
printf("\n\nChoose a spot: ");
fflush(stdin);
You probably wanted to fflush() stdout?

comparing an inputted string to a printed function

Below is a code I wrote for a dice game called cho han. To input your guess I've used number to represent the words 'odd' and 'even'. Since then I have tried to write it again, but to actually write odd or even in the scanf section, but can't get it to work. Any help would be appreciated :)
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter '1'. To guess even, enter '2'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
scanf_s("%d", &guess);
if (guess == 2)
{
printf("\nyour guess is even.\n");
}
if (guess == 1)
{
printf("\nyour guess is odd.\n");
}
if (guess > 2 || guess < 1)
{
printf("\nInvalid guess.\nYou lose!\n");
return (1);
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
result = x + y;
printf("\ncombined total of both rolls is %d", result);
if (result == 1 || result == 3 || result == 5 || result == 7 || result == 9 || result == 11)
{
printf("\ncombined total of both rolls is odd.\n");
}
else
{
printf("\ncombined total of both rolls is even.\n");
}
if (guess == 1 && result == 1 || guess == 1 && result == 3 || guess == 1 && result == 5 || guess == 1 && result == 7 || guess == 1 && result == 9 || guess == 1 && result == 11)
{
printf("\nYou win!\n");
}
else if (guess == 2 && result == 2 || guess == 2 && result == 4 || guess == 2 && result == 6 || guess == 2 && result == 8 || guess == 2 && result == 10 || guess == 2 && result == 12)
{
printf("\nYou win!\n");
}
else
{
printf("\nYou lose!\n");
}
return 0;
}
You should change scanf_s to scanf
The line if (result == 1 || result == 3 ... could be if (result % 2 == 1) {
You could use strcmp to solve your question
The following code could work:
//cho-han
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void)
{
srand(time(NULL));
int x = (rand() % 6) + 1;
int y = (rand() % 6) + 1;
int result = 0;
int guess = 0;
char buf[10];
printf("The values of two dice rolls will be added up. The aim is to guess whether that total number will be odd or even.\n");
printf("To guess odd, enter 'odd'. To guess even, enter 'even'.\n\n");
printf("Please enter your guess for the combined total of the two dice rolls: ");
fgets(buf, sizeof buf, stdin);
if (strcmp(buf, "even\n") == 0) {
guess = 2;
printf("\nyour guess is even.\n");
} else if (strcmp(buf, "odd\n") == 0) {
guess = 1;
printf("\nyour guess is odd.\n");
} else {
printf("\nInvalid guess.\nYou lose!\n");
return 1;
}
printf("\ndice roll 1 = %d\n", x);
printf("dice roll 2 = %d\n", y);
printf("\ncombined total of both rolls is %d", x + y);
result = (x + y) % 2;
if (result == 1)
printf("\ncombined total of both rolls is odd.\n");
else
printf("\ncombined total of both rolls is even.\n");
if (guess == result)
printf("\nYou win!\n");
else
printf("\nYou lose!\n");
return 0;
}
You need to change your guess to char type and scanf to capture string.
char guess[256];
scanf("%s", guess);
And then the best way would be to call toupper() and compare with your text using strcmp().

Coding Tic Tac Toe in C with only If statements

So the past week I've been attempting to learn some C, I was giving an exercise to code a really simplistic version of tic tac toe.
I have been asked:
Prompt two users to enter a ‘naught’ or a ‘cross’ respectively into one of the nine positions on the tic, tac, toe grid
After all 9 inputs have been made display the grid
To make it simpler: only when all 9 grid positions have been entered figure out if there is a winner (you can do this with a few ‘if’ statements)
.
I'm told this can be done with a few if statements, so far I have only learnt up to if's, including the basic int, char, float, double, ect.
So, what I'm not truly grasping in how to only use if statements to check if:
the position is already taken, if it has prompt the user to try again or place the current persons naught or cross in that position.
keep track of the positions the two users enter, so I know which position each of the two users they have entered to check those positions if its empty or not.
I feel like I am somewhat over thinking this but I am unsure, if anyone has got any help that'd be great.
This is what I've written so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char board[9];
int num;
printf("Today we are playing a game of Tic Tac Toe\n");
printf("To play the game you need to line up 3 of the same type 'x's or o's' in a line to win\n");
printf("Before we start, whoever wants to be 'X' starts first, and whoever wants to be 'O' starts second\n");
printf("The board looks like this\n");
printf("%d%c%d%c%d\n", 1, 124, 2, 124, 3);
printf("%d%c%d%c%d\n", 4, 124, 5, 124, 6);
printf("%d%c%d%c%d\n", 7, 124, 8, 124, 9);
printf("Lets begin");
printf("\n");
printf("\n");
printf("\n");
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'O';
printf("Please enter a number between 1 - 9 ");
scanf("%d", &num);
board[num] = 'X';
return 0;
}
Note: Could I also ask that all answers be kept to only using if statements as that is as far as I am up too, and it is how the exercise is meant to be completed, although probably this is ten times easier with for/while and arrays.
Thank you!
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define ROWS 3
#define COLUMNS 3
#define PLAYER_ONE 'X'
#define PLAYER_TWO 'O'
void board();//calling class required by C
int checkForWinner();//calling class required by C
char tic_tac_toe[ROWS][COLUMNS] =
{
{ '1', '2', '3'},
{ '4', '5', '6'},
{ '7', '8', '9'}
};
int main()
{
int isGameOn=1, currentPlayer=1, pick;
char checked;
do
{
board();
currentPlayer = (currentPlayer % 2) ? 1 : 2;
printf("Player %d, pick a number: ", currentPlayer);
scanf("%d", &pick);
checked = (currentPlayer == 1) ? 'X' : 'O';
isGameOn = checkForWinner();
if(pick == 1 && tic_tac_toe[0][0] == '1'){
tic_tac_toe[0][0] = checked;
if(isGameOn == 1)break;
}else if(pick == 2 && tic_tac_toe[0][1] == '2'){
tic_tac_toe[0][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 3 && tic_tac_toe[0][2] == '3'){
tic_tac_toe[0][2] = checked;
if(isGameOn == 1){break;}
}else if(pick == 4 && tic_tac_toe[1][0] == '4'){
tic_tac_toe[1][0] = checked;
if(isGameOn == 1){break;}
}else if(pick == 5 && tic_tac_toe[1][1] == '5'){
tic_tac_toe[1][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 6 && tic_tac_toe[1][2] == '6'){
tic_tac_toe[1][2] = checked;
if(isGameOn == 1){break;}
}else if(pick == 7 && tic_tac_toe[2][0] == '7'){
tic_tac_toe[2][0] = checked;
if(isGameOn == 1){break;}
}else if(pick == 8 && tic_tac_toe[2][1] == '8'){
tic_tac_toe[2][1] = checked;
if(isGameOn == 1){break;}
}else if(pick == 9 && tic_tac_toe[2][2] == '9'){
tic_tac_toe[2][2] = checked;
if(isGameOn == 1){break;}
}
else{
printf("Invalid moved");
}
isGameOn = checkForWinner();
if(isGameOn == 1){
printf("***************************************\n");
printf("The winner is player %d\n", currentPlayer);
printf("***************************************");
break;
}
currentPlayer++;
}while(isGameOn == -1);
board();
return(0);
}
/*Functions*/
/*Board display*/
void board()
{
printf("\n");
printf("%c\t %c\t %c\n", tic_tac_toe[0][0], tic_tac_toe[0][1], tic_tac_toe[0][2]);
printf("%c\t %c\t %c\n", tic_tac_toe[1][0], tic_tac_toe[1][1], tic_tac_toe[1][2]);
printf("%c\t %c\t %c\n", tic_tac_toe[2][0], tic_tac_toe[2][1], tic_tac_toe[2][2]);
}
/*Checking for winner*/
int checkForWinner()
{
/*checkign vertical line*/
for(int col=0; col<COLUMNS; col++){
int row=0;
if(tic_tac_toe[row][col] == tic_tac_toe[row+1][col] && tic_tac_toe[row+1][col] == tic_tac_toe[row+2][col]){
return 1;
}
}
/*checking horizontal line*/
if(tic_tac_toe[0][0] == tic_tac_toe[0][1] && tic_tac_toe[0][1] == tic_tac_toe[0][2]){
return 1;
}
else if(tic_tac_toe[1][0] == tic_tac_toe [1][1] && tic_tac_toe[1][1] == tic_tac_toe[1][2])
{
return 1;
}
else if(tic_tac_toe[2][0] == tic_tac_toe [2][1] && tic_tac_toe[2][1] == tic_tac_toe[2][2])
{
return 1;
}
else if(tic_tac_toe[0][0] == tic_tac_toe[1][1] && tic_tac_toe[1][1] == tic_tac_toe[2][2])/*diagonal*/
{
return 1;
}
else {
return -1;
}
}

If, else & while bug (not activating / activating twice)

I'm having this problem in where when the player choose to attack. It won't print anything at first but will only print when the player hits the knight. Something else is also if the player chooses an invalid choice in gender, the first mistake will print once but if the mistake happen again it will print twice. I would appreciate any help, just doing my lil' project.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
int main()
{
char enter = 0;
char pNAME[30];
char pGENDER;
char pWEAPON[20];
char pARMOR [10];
int pWEAPONID;
int choice1,choice2 = 0,choice3;
int pAGE;
int pATK = 0;
int pHP = 30;
int pATKS = 10;
int pATKC = 0;
int knightHP = 25;
int knightATKS = 20;
int knightATKC;
int kingHP = 30;
int kingATKC;
srand((unsigned)time(NULL));
printf("While you are enjoying your breakfast at your house, suddenly you get teleported to a different dimension and no one to be seen except an old man.\n");
printf("\nOld Man: What is your name warrior?\n");
printf("\nInsert name:");
scanf("%s",pNAME);
fpurge( stdin );
printf("\nInsert gender (m/f):");
scanf("%c",&pGENDER);
fpurge( stdin );
while ( pGENDER != 'f' &&pGENDER != 'm' )
{
printf("\nInvalid entry, please try again.\n");
printf("\nInsert gender (m/f):");
scanf("%c",&pGENDER);
}
printf("\nOld Man: Now how old are you warrior?\n");
printf("\nInsert Age:");
scanf("%d",&pAGE);
fpurge( stdin );
if ( pAGE < 18)
{
printf("\nOy mate! No stalker!\n");
printf("\nTeleporting back to reality...\n");
return 0;
}
if ( pAGE > 80)
{
printf("\nNo oldies allowed!\n");
printf("\nTeleporting back to reality...\n");
return 0;
}
printf("\nOld Man: Welcome warrior I fear the knights has taken over our kingdom, and you, %s, are the only one who can save us.\n",pNAME);
printf("\n%s: How am I suppose to do that?[Enter]\n",pNAME);
while (enter != '\r' && enter != '\n') { enter = getchar(); }
printf("Old Man: Pick one of these three items\n");
printf("\n[1] Axe : Damage = 7\t Accuracy = 70%% Critical = 7%%\n"); //
printf("\n[2] Sword : Damage = 5\t Accuracy = 77%% Critical = 8%%\n");
printf("\n[3] Knife : Damage = 3\t Accuracy = 83%% Critical = 9%%\n");
printf("\nYou choose: ");
scanf("%d",&pWEAPONID);
if (pWEAPONID == 1)
{
pATK = 8;
pATKS = 14; // 10/14 chance
strcpy(pWEAPON, "Axe");
}
if (pWEAPONID == 2)
{
pATK = 6;
pATKS = 14; // 10/13 chance
strcpy(pWEAPON, "Sword");
}
if (pWEAPONID == 3)
{
pATK = 4;
pATKS = 12; // 10/12 chance
strcpy(pWEAPON, "Knife");
}
if (pWEAPONID > 3)
{
printf("\nYou are gonna be fighting with your bare fist");
pATK = 2;
pATKS = 11; // 10/11 chance
strcpy(pWEAPON, "Fist");
}
printf("\nOld Man: Good choice, you chose the %s, now continue foward to destroy The Evil King\n",pWEAPON);
printf("\nWhile you are continuing your journey to destroy The Evil King, you come face to face with a knight\n");
printf("\nWhat do you want to do?\n");
printf("\n[1] Run [2] Battle:");
scanf("%d",&choice1);
if (choice1 == 1) //Dead
{
printf("\nYou attempted to run, but the knight chases you with his horse and a spear.\n");
printf("\nThe knight stabs you right through your body.\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
while (pHP != 0 && knightHP != 0) // Combat starts
{
knightATKC = rand()%knightATKS; // 15/20 chance
sleep(1);
// Knight's turn
if ( knightATKC == 1 || knightATKC == 2 || knightATKC == 3 || knightATKC == 4 || knightATKC == 5 || knightATKC == 6 || knightATKC == 7 || knightATKC == 8 || knightATKC == 9 || knightATKC == 10 || knightATKC == 11 || knightATKC == 0 )
{
printf("\nThe knight swings his spear at %s\n",pNAME);
printf("The knight hits %s for 4 HP\n",pNAME);
pHP = pHP - 4;
printf("%s has %d/30 HP\n",pNAME,pHP);
if (pHP == 0 || pHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:"); // Charge and Heal not activated yet
scanf("%d",&choice1);
}
else if (knightATKC == 12 || knightATKC == 13 )
{
printf("\nThe knight slashes his spear at %s\n",pNAME);
printf("The knight critically hit %s for 6 HP\n",pNAME);
pHP = pHP - 6;
printf("%s has %d/30 HP\n",pNAME,pHP);
if (pHP == 0 || pHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:"); // Charge and Heal not activated yet
scanf("%d",&choice2);
}
else if (knightATKC == 14)
{
printf("\nThe knight's horse kicks %s\n",pNAME);
printf("The knight's horse hit %s for 8 HP\n",pNAME);
pHP = pHP - 8;
printf("%s has %d/30 HP\n",pNAME,pHP);
if (pHP == 0 || pHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
return 0;
}
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:");
scanf("%d",&choice2);
}
else
{
printf("\nThe knight swings his spear at %s\n",pNAME);
printf("You blocked his spear with your %s\n",pWEAPON);
printf("%s has %d/30 HP\n",pNAME,pHP);
printf("\nWhat do you want to do?\n");
printf("[1] Attack [2] Charge your attack [3] Heal:"); // Charge and Heal not activated yet
scanf("%d",&choice2);
}
// Player's turns
if (choice2 == 1)
{
pATKC = rand()%pATKS;
if (pATKC == 0 || pATKC == 1 || pATKC == 2 || pATKC == 3 || pATKC == 4 || pATKC == 5 || pATKC == 6 || pATKC == 7 || pATKC == 8 || pATKC == 9)
{
printf("\nYou swing your %s at the knight\n",pWEAPON);
printf("You hit the knight with your %d\n",pATK);
knightHP = knightHP - pATK;
printf("The knight has %d/25\n",knightHP);
if (knightHP == 0 || knightHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
}
printf("\nWhat do you want to do?\n");
printf("[1] Run [2] Attempt to block\n");
scanf("%d",&choice3);
}
else if (pATKC == 10)
{
printf("\nYou swing your %s at the knight\n",pWEAPON);
printf("You critically hit the knight for %f\n",pATK * 1.5);
knightHP = knightHP - (pATK * 1.5);
printf("The knight has %d/25\n",knightHP);
printf("\nWhat do you want to do?\n");
printf("[1] Run [2] Attempt to block\n");
scanf("%d",&choice3);
}
else
{
printf("\nYou swing your %s at the knight\n",pWEAPON);
printf("The knight intercept your %s with his spear\n",pWEAPON);
printf("The knight has %d/25\n",knightHP);
printf("\nWhat do you want to do?\n");
printf("[1] Run [2] Attempt to block\n"); // Not activated yet
scanf("%d",&choice3);
}
}
}
the posted code does not compile, so it certainly does not run.
here are a few of the many listed problems with the code
Always enable all warnings when compiling.
For gcc, at a minimum use: -Wall -Wextra -pedantic
line:column: message
35:5: warning implicit declaration of function `fpurge`
224:5: error: expected declaration or statement at end of input
27:9: warning: unused variable `kingATKC`
26:9: warning: unused variable `kingHP`
15:10: warning: unused variable `pARMOR`
BTW: fpurge is not a supported function in the stdio.h header file
Suggest, rather than calling fpurge(), use:
while( '\n' != getchar() );
when calling scanf(), always check the returned value, not the parameter value, to assure the operation was successful
when inputting the 'gender', apply tolower to the value so user could enter either upper or lower case
this code: around line 232 is killing the hero when it should be killing the knight
if (knightHP == 0 || knightHP <0)
{
printf("\nYou fell to the ground heavily damages, while the knight lungs at your for the final hit\n");
printf("\nYou are dead, thanks for playing.\n");
}
upon any death, the resulting HP can be less than 0 however this line:
while (pHP != 0 && knightHP != 0) // Combat starts
only terminates the loop if HP == 0 it should be:
while (pHP > 0 && knightHP > 0) // Combat starts
Suggest, for a combat sequence, that there is only one place where the hero can input a decision about what they want to do next.
Suggest, make each combat activity a separate sub function.
The above two suggestions will greatly increase the simplicity of each function and make the code much easier to debug.

Resources