RockPaperScissor game not getting expected result - C programming - c

I was writing c program on rock paper and scissor game but could not get the expected result.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
char player[50], choice[10];
puts("Enter your name: ");
gets(player);
int player1 = 0, comp = 0;
for (int i = 0; i < 3; i++)
{
srand(time(NULL));
printf("%s: ", player);
scanf("%s", choice);
int computer = rand()%3;
if (computer == 0){
printf("computer: rock\n");
} else if(computer == 1){
printf("computer: paper\n");
}else{
printf("computer: scissor\n");
}
if (computer == 0 && choice == "paper"){
player1++;
}else if (computer == 0 && choice == "rock"){
continue;
}else if (computer == 0 && choice == "scissor"){
comp++;
}else if (computer == 1 && choice == "paper"){
continue;
}else if (computer == 1 && choice == "rock"){
comp++;
}else if (computer == 1 && choice == "scissor"){
player1++;
}else if (computer == 2 && choice == "paper"){
player1++;
}else if (computer == 2 && choice == "rock"){
comp++;
}else if (computer == 2 && choice == "scissor"){
continue;
}else {
printf("Invalid Entry.");
}
printf("\n");
}
if (player1 > comp){
printf("%s wins.", player);
}else if (player1 == comp) {
printf("%s and computer draws.", player);
}else{
printf("%s loses.", player);
}
return 0;
}
The program works but I am not getting the expecteed result in all 3 runs of the for loop I get only invalid entry as output due to which I can't count the score and the result as both player and comp variable are idle due to this.
output:
Enter your name:
Sam
Sam: rock
computer: scissor
Invalid Entry.
Sam: scissor
computer: scissor
Invalid Entry.
Sam: paper
computer: paper
Invalid Entry.
Sam and computer draws.
I have checked to best my skill and could not find any mistake I don't know why if else-if is acting weirdly, Help me to get correct output and explain me what the problem and where the mistake is.

You need to comare strings using strcmp from <string.h>. Note that strcmp returns 0 if the strings match.
#include <string.h>
int strcmp(const char *str1, const char *str2);
For example you would have to replace choice == "paper" with !strcmp(choise, "paper").
And you should also use fgets instead of gets.
char player[50];
fgets(str, 50, stdin);
Alternatively you could use and scanf (inferior in many cases).
char player[50];
scanf("%49[^\n]", player); /* take \0 into account */

Related

How to let player chose to be X or O as well as an option to play the game again?

So I need some help in this Tic-Tac-Toe game. I have almost everything working correctly I just need to add on some features. Those features include: 1.) allowing the player to choose whether they want to play as X or O in the game, and 2.) giving the option for the players to replay the game if they wish. I've gotten the base mechanics of the game to work out nicely, I just can't figure out how to add these features into the code. I've started to "lay the foundation" for the first feature (giving the player the option to choose their mark). (Honestly, I'm just really tired from studying for the past 48hrs for finals and I could really use a helping hand here). Here is my full code:
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable : 4996)
#include <stdio.h>
#include <conio.h>
int checkwin(char gridspace[]);
void gameboard(char gridspace[]);
int gameLoop(int choice, int player, char gridspace[], char mark);
void main(void)
{
char grid[10] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int player = 1, victory, choice;
char mark, player1, player2;
int markchoice;
do // game loop start
{
gameboard(grid); // draws the game board
if (player % 2) // player turn conditional
{
player = 1;
}
else
{
player = 2;
}
printf("Player 1, choose which mark you would like to play as (1=X or 2=O)\n"); // asks the player to choose a mark
scanf("%c", &markchoice);
if (markchoice == 1) // mark choice conditional
{
mark = 'X';
}
else
{
mark = 'O';
}
printf("Player %d, enter the number of the place you wish to place your mark: ", player); // asks the player to place their mark on a space
scanf("%d", &choice);
if (player == 1) // mark type (X or O) placement conditional
{
mark;
}
else
{
mark;
}
gameLoop(choice, player, grid, mark); // calls the main game function that houses the conditionals
victory = checkwin(grid); // checks the state of the game (if its in progress, a draw, or a player has achieved victory.
player++;
} while (victory == -1); //end of game loop
gameboard(grid); // redraws the game board
if (victory == 1) // conditional that breaks the game loop and gives a result (victory or draw)
{
printf("==>\aPlayer %d win ", --player);
}
else
{
printf("==>\aGame draw");
getch();
}
return 0;
} // end of main
int gameLoop(int choice,int player, char gridspace[], char mark) // function for game loop
decisionals
{
if (choice == 1 && gridspace[1] == '1')
gridspace[1] = mark;
else if (choice == 2 && gridspace[2] == '2')
gridspace[2] = mark;
else if (choice == 3 && gridspace[3] == '3')
gridspace[3] = mark;
else if (choice == 4 && gridspace[4] == '4')
gridspace[4] = mark;
else if (choice == 5 && gridspace[5] == '5')
gridspace[5] = mark;
else if (choice == 6 && gridspace[6] == '6')
gridspace[6] = mark;
else if (choice == 7 && gridspace[7] == '7')
gridspace[7] = mark;
else if (choice == 8 && gridspace[8] == '8')
gridspace[8] = mark;
else if (choice == 9 && gridspace[9] == '9')
gridspace[9] = mark;
else
{
printf("Invalid move, input a different number.");
player--;
getch();
}
return 1;
}// end of game loop function
int checkwin(char gridspace[]) // check win function
{
if (gridspace[1] == gridspace[2] && gridspace[2] == gridspace[3])
return 1;
else if (gridspace[4] == gridspace[5] && gridspace[5] == gridspace[6])
return 1;
else if (gridspace[7] == gridspace[8] && gridspace[8] == gridspace[9])
return 1;
else if (gridspace[1] == gridspace[4] && gridspace[4] == gridspace[7])
return 1;
else if (gridspace[2] == gridspace[5] && gridspace[5] == gridspace[8])
return 1;
else if (gridspace[3] == gridspace[6] && gridspace[6] == gridspace[9])
return 1;
else if (gridspace[1] == gridspace[5] && gridspace[5] == gridspace[9])
return 1;
else if (gridspace[3] == gridspace[5] && gridspace[5] == gridspace[7])
return 1;
else if (gridspace[1] != '1' && gridspace[2] != '2' && gridspace[3] != '3' &&
gridspace[4] != '4' && gridspace[5] != '5' && gridspace[6] != '6' && gridspace[7]
!= '7' && gridspace[8] != '8' && gridspace[9] != '9') // if all spaces are filled but no
three match then the game is a draw
return 0;
else // if no three spaces match and empty spaces still exist then the game is still in
progress.
return -1;
} // end of check win function
void gameboard(char gridspace[]) // game board function.
{
system("cls");
printf("\n\n\tTic Tac Toe\n\n");
printf("Enter a number for where you wish to place your mark");
printf("Player 1 (X) - Player 2 (O)\n\n\n");
printf(" | | \n");
printf(" %c | %c | %c \n", gridspace[1], gridspace[2], gridspace[3]);
printf("_____|_____|_____\n");
printf(" | | \n");
printf(" %c | %c | %c \n", gridspace[4], gridspace[5], gridspace[6]);
printf("_____|_____|_____\n");
printf(" | | \n");
printf(" %c | %c | %c \n", gridspace[7], gridspace[8], gridspace[9]);
printf(" | | \n\n");
} // end of board drawing funciton.
Any and all help would be greatly appreciated. So thank you in advance!
to allow multiple rounds you can add another while loop outside the game one in order to reset all the stats and restart the game until player decides to stop(you can use a scanf to check for y/n).

Yes & No answer in C

I am trying to make a C program where I can ask the following user yes or no questions:
Do you like beer? Y or N
Are you old enough? Y or N
How old are you?
if the user said over 18 print the message: let's go for some beers
but if one of the 2 first questions or the age is N, print: sorry maybe next time
I think the issue is with the If statement , perhaps I am not encapsulating the conditions.
#include <stdio.h>
int main(){
char answer;
int age = 0 ;
printf("Do you like beers Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n so your answer is %c\n", answer);
printf("Are you old enough to have a beer?\n");
scanf(" %c", &answer);
printf("\n so your answer is %c\n", answer);
if (answer == 'Y') {
printf("how old are you?\n");
scanf(" %d", &age);
if (age >= 18)
printf("\n Let's go for some beers , I will pay the first round \n");
}if else (age < 18 && answer == 'N')
printf("\n sorry my friend , maybe next time \n");
// printf("You may NOT ");
return 0;
}
From your code snippet above, it looks like your else statement is formatted incorrectly (if else instead of else if). Also, since you are testing whether or not either question was false, you should use the || operand. So you would want to do something like:
else if (age < 18 || answer == 'N')
The issue is your last if statement is only true if the user is under 18 AND said No. you want it to be either or.
Change the last if statement from
if else (age < 18 && answer == 'N')
To:
if else (age < 18 || answer == 'N')
You are using the same variable "answer". So, when you enter the answer to the second question it replace the first answer.
int main(){
char answer;
char answer2;
int age = 0 ;
printf("Do you like beers Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n so you answer is %c\n", answer);
printf("Are you older enough to have a beer?\n");
scanf(" %c", &answer2);
printf("\n so you answer is also %c\n", answer2);
if (answer == 'Y' && answer2 == 'Y') {
printf("how old are yo.\n");
scanf(" %d", &age);
if (age >= 18)
printf("\n lets go for some beers , I will paid the first round \n");
}
else if (answer == 'N' || answer2 == 'N')
printf("\n sorry my friend , maybe next time \n");
// printf("You may NOT ");
return 0;
}
Hope this is what you needed. Cheers.
I think that you can think that the structure of your program is roughly as follows.
REPLY = PROMPT(Q1_MESSAGE)
IF(REPLY == YES){
//Narrow down the conditions
REPLY = PROMPT(Q2_MESSAGE)
IF(REPLY == YES){
//Narrow down the conditions
REPLY = PROMPT(Q3_MESSAGE)
IF(REPLY >= 18){
DISPLAY(GOOD_MESSAGE)
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
A nested IF can be considered as AND condition as a condition.
So by summarizing the question message and its response part into a function, it is possible to write as follows.
IF(FUNC1() == TRUE AND FUNC2() == TRUE AND FUNC3() == TRUE){//Function call proceeds from left to right (Shortcut evaluated)
DISPLAY(GOOD_MESSAGE)
} ELSE {
DISPLAY(NO_GOOD_MESSAGE)
}
As an example, you can write concretely as follows.
#include <stdio.h>
int main(void){
char YN(const char *prompt);
int enter_age(const char *prompt);
if(YN("Do you like beers Enter Y or N: \n") == 'Y' &&
YN("Are you old enough to have a beer?\n") == 'Y' &&
enter_age("How old are you?\n") >= 20){
printf("\nLet's go for some beers, I will take the first round.\n");
} else {
printf("\nSorry my friend, maybe next time.\n");
}
return 0;
}
char YN(const char *prompt){
char ans[2], ret, ch;
int ret_scnf;
while(1){
fputs(prompt, stdout);
if((ret_scnf = scanf(" %1[YNyn]%c", ans, &ch)) == 2 && ch == '\n'){
if(*ans == 'Y' || *ans == 'y'){
ret = 'Y';
break;
} else if(*ans == 'N' || *ans == 'n'){
ret = 'N';
break;
}
} else if(ret_scnf == EOF){
ret = 'N';
break;
}
scanf("%*[^\n]");scanf("%*c");//clear input
}
return ret;
}
int enter_age(const char *prompt){
int ret_scnf, age;
char ch;
while(1){
fputs(prompt, stdout);
if((ret_scnf = scanf("%d%c", &age, &ch)) == 2 && ch == '\n'){
if(age < 0)//Can I enter years old at the age of 0?
continue;
return age;
} else if(ret_scnf == EOF){
age = -1;
break;
}
scanf("%*[^\n]");scanf("%*c");
}
return age;
}

C: How do I break this loop in my code?

I've looked at questions asked on stackoverflow before, but this is my first time asking, so I apologize in advance for any format mistakes. I've been taking a class on C programming for about a month, and I've been given an assignment to use a do/while loop in my main function to loop a displayMenu(), which allows the user to input either 1, 2, or 3 to display a certain block of information.
int main(void)
{
int option = 0;
do
{
option = displayMenu();
}
while (option == displayName() || displayColor() || displayFood());
}
//Display the menu for choosing an option or exiting the program
int displayMenu()
{
int choice = 1;
while (choice == 1 || 2 || 3)
{
puts("Choose which piece of information you would like to know:");
printf("%s", "1 - My name, 2 - My favorite color, 3 - My favorite food\n");
printf("%s", "Or type in any other number to exit the program: ");
scanf("%d", &choice);
puts("");
if (choice == 1)
displayName();
if (choice == 2)
displayColor();
if (choice == 3)
displayFood();
}
return choice;
}
Now, I'm sure the error is somewhere within these two methods, but just in case, I'm posting the display methods.
//Function to display my name
int displayName()
{
int value = 1;
puts("My name is x.\n");
return value;
}
//Function to display my favorite color
int displayColor()
{
int value = 2;
puts("My favorite color is y.\n");
return value;
}
//Function to display my favorite food
int displayFood()
{
int value = 3;
puts("My favorite food is z.\n");
return value;
}
If the user inputs 1, 2, or 3, the program correctly displays the information and loops to prompt the user again about inputting another value. However, if any other number is input, the program prompts the user again to input a value, when instead it should be closing the program.
What am I doing wrong? I tried inserting a
else return choice;
after the first three if statements, because i thought that would be needed to break the loop, but it didn't work. Does it have something to do with my while conditions? I'm unsure if my conditions are right, (about == and || precedence and whatnot), so if someone could clarify that too it'd be nice.
I know there are probably more efficient methods to executing this program, but I'm limited to what I've been taught in the class, which really isn't anything more than what I've coded.
while (choice == 1 || 2 || 3)
is equivalent to
while ((choice == 1) || 2 || 3)
which is equivalent to
while (1)
What you want is:
while (choice == 1 || choice == 2 || choice == 3)
This line is an infite loop:
while (choice == 1 || 2 || 3)
I guess what you want is:
while (choice == 1 || choice == 2 || choice == 3)
Ignoring the many errors in the original code, what you can do to refactor the loop logic is to use an array of function pointers:
int (*functions[])(void) = { displayName, displayColor, displayFood };
int choice = -1;
do {
choice = get_choice(); // assuming get_choice returns an integer between 0 and 2, or -1 on error/eof.
if (choice != -1)
functions[choice]();
} while (choice != -1)
this will make your code more concise, provided all of your functions have the same prototype.
Well because you got your answer I will not try to give you another Answer which will probably be the same.
One thing you should know, what happens if the user type a letter or a number + a letter (1j) ?
You should have control of your programs when you are dealing with text menus.
Here is a better approach of your program:
#include <stdio.h>
#include <string.h>
int checkInput(int min, int max){
int option,check;
char c;
do{
printf("Choose an Option:\t");
if(scanf("%d%c",&option,&c) == 0 || c != '\n'){
while((check = getchar()) != 0 && check != '\n');
printf("\tThe option has to be between %d and %d\n\n",min,max);
}else if(option < min || option > max){
printf("\tThe option has to be between %d and %d\n\n",min,max);
}else{
break;
}
}while(1);
return option;
}
void quit(void){
printf("Goodbye...\n");
}
//Function to display my name
int displayName(void){
int value = 1;
puts("My name is x.\n");
return value;
}
//Function to display my favorite color
int displayColor(void){
int value = 2;
puts("My favorite color is y.\n");
return value;
}
//Function to display my favorite food
int displayFood(void){
int value = 3;
puts("My favorite food is z.\n");
return value;
}
int displayMenu(void);
int main(void){
int option = 0;
do{
option = displayMenu();
}
while (option != 0);
}
//Display the menu for choosing an option or exiting the program
int displayMenu(void){
int choice;
do{
puts("Choose which piece of information you would like to know:");
printf("%s", "1 - My name\n2 - My favorite color\n3 - My favorite food\n\n");
printf("%s", "Or type in any other number to exit the program: ");
choice = checkInput(0,3);
puts("");
if (choice == 1){
displayName();
}else if (choice == 2){
displayColor();
}else if (choice == 3){
displayFood();
}else if( choice == 0){
quit();
}
}while (choice != 0);
return choice;
}
probably a do{}while(); is better then while{}.

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