I'm very new at C programming, and whenever I take up a language, I always write a very simple fighting game. I think I completed the game for now, and was just curious on what you all thought of the code, what I've done wrong, what I could do to improve it, and any other tips you could give me. Right off the bat, I used 4 globals, which I know is a no-no, but I can't think of another way to do it without adding more variables. Yes, this is pretty long for what it is, and I would very much appreciate any feedback thanks
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int hislife = 20; // Enemy's life
int yourlife = 20; // Your life
int rand_damage; // Random damage dealt.
int damage_self; // Damage dealt to self if superhit
int chance() {
int to_hit = rand() % 10 + 1;
if (to_hit >= 6) {
return(2);
} else {
return(1);
}
}
int damage() {
int damg = rand() % 4 + 1;
return(damg);
}
void youswing() {
if (chance() == 2) {
rand_damage = damage();
hislife -= rand_damage;
printf("Hit enemy for %d damage!\n", rand_damage);
} else {
printf("Missed!\n");
}
}
void heswing() {
if (chance() == 1) {
rand_damage = damage();
yourlife -= rand_damage;
printf("Enemy hit you for %d damage!\n", rand_damage);
} else {
printf("Enemy missed you!\n");
}
}
int main() {
char input[100]; // Data inputted
char choice; // Input Assignment
srand((unsigned int)time(NULL));
while ((choice != 'Q') && (choice != 'q')) {
if (hislife <= 0) {
printf("Good job. He's dead. Hope you're proud.\n");
break;
} else if (yourlife <= 0) {
printf("You're dead, and you suck.\n");
break;
} else if ((yourlife <= 0) && (hislife <= 0)) {
printf("You killed him, but you're dead too. Such is life..\n");
break;
}
printf("His life: %d - Your life: %d\n", hislife, yourlife);
printf("(A)ttack, (S)uperhit, (Q)uit: ");
fgets(input, sizeof(input), stdin);
sscanf(input, "%c", &choice);
if ((choice == 'A') || (choice == 'a')) {
printf("\n");
if (chance() == 1) {
youswing();
heswing();
} else {
heswing();
youswing();
}
printf("\n");
} else if ((choice == 'S') || (choice == 's')) {
if (chance() == 2) {
rand_damage = damage() + 3;
hislife -= rand_damage;
damage_self = damage() - 2;
if (damage_self <= 0) {
damage_self = 1;
}
yourlife -= damage_self;
printf("\nYou swung a wreckless blow for %d damage, taking %d damage to yourself\n", rand_damage, damage_self);
} else {
damage_self = damage() - 2;
if (damage_self <= 0) {
damage_self = 1;
}
yourlife -= damage_self;
printf("\nYou threw a completely wreckless blow, hurting yourself for %d damage!\n", damage_self);
}
if (chance() == 1) {
rand_damage = damage();
yourlife -= rand_damage;
printf("Enemy hit you for %d damage!\n", rand_damage);
} else {
printf("Enemy missed you!\n");
}
} else if ((choice == 'Q') || (choice == 'q')) {
printf("Goodbye\n");
} else {
printf("Unknown: %c\n", choice);
}
}
return(0);
}