Reputation: 11
I am trying to make an upgrade system within my game. I am using 3 bool variables (for 3 different weapons). I am having trouble making an if else comparator that will look at which bool variables are true/false (which weapons you have and don't have), and take you to an appropriate combat scenario. The if else comparator does not work, regardless of what weapon you have. It automatically goes to the "else" part of the statement (where you go if you do not have a weapon). I have included a simplified version, with only 1 bool variable. Please help.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int choice;
int choice2;
bool weapon1 = false;
start:
printf("Where would you like to go? 1. Store 2. Arena: ");
scanf("%d", &choice);
if (choice == 1) {
printf("You got weapon1 from the store \n");
bool weapon1 = true;
goto start;
}
else if (choice == 2) {
printf("You went to the arena\n");
if (weapon1) {
printf("You won the battle because you had a weapon\n");
exit(0);
}
else {
printf("You lost the battle because you did not have a weapon\n");
exit(0);
}
}
return 0;
}
Upvotes: 0
Views: 74
Reputation: 68089
Use of goto
in C (with some exceptions ligoing to the end of the function) is considers a horrible practice
When you have defined the variable you shall not use its type at the beginning of the assignment as it new definition. Instead bool weapon1 = true;
do weapon1 = true;
#include <stdbool.h>
#include <stdio.h>
int main()
{
int choice;
int choice2;
bool weapon1 = false;
bool endgame = false;
do
{
printf("Where would you like to go? 1. Store 2. Arena: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("You got weapon1 from the store \n");
weapon1 = true;
break;
case 2:
if (weapon1) printf("You won the battle because you had a weapon\n");
else printf("You lost the battle because you did not have a weapon\n");
endgame = true;
break;
default:
break;
}
}while(!endgame);
}
Upvotes: 0
Reputation: 79
The problem is that you reinitialize the weapon boolean variable. Correct code is this:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
int choice;
int choice2;
bool weapon1 = false;
start:
printf("Where would you like to go? 1. Store 2. Arena: ");
scanf("%d", & choice);
if (choice == 1) {
printf("You got weapon1 from the store \n");
weapon1 = true;
goto start;
} else if (choice == 2) {
printf("You went to the arena\n");
if (weapon1) {
printf("You won the battle because you had a weapon\n");
exit(0);
} else {
printf("You lost the battle because you did not have a weapon\n");
exit(0);
}
}
return 0;
}
Upvotes: 0
Reputation: 224576
Writing bool weapon1 = true;
inside the braces associated with if (choice == 1)
defines a new weapon1
that is unrelated to the earlier weapon1
.
Change it to weapon1 = true;
, which assigns to the earlier weapon1
without defining a new weapon1
.
Turn on all or most warning messages in your compiler and pay attention to them.
Upvotes: 3