mp2i-info/tp3/rpg.c
2025-10-14 15:07:27 +02:00

90 lines
2.2 KiB
C

#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int max(int a, int b) { return a > b ? a : b; }
int min(int a, int b) { return a < b ? a : b; }
struct Personnage {
char nom[80];
int pv;
int atq;
int def;
};
typedef struct Personnage perso;
void print_p(perso *p) {
printf("%s : { PV:%d | ATQ:%d | DEF:%d }\n", p->nom, p->pv, p->atq, p->def);
}
void print_t(perso team[], int size) {
while (size) {
print_p(team);
team += 1;
size -= 1;
}
}
void atk(perso *attacker, perso *target, bool print) {
int dmg = min(max(attacker->atq - target->def, 1), target->pv) *
(attacker->pv != 0);
target->pv -= dmg;
if (print) {
printf("%s deals %d damages to %s\n", attacker->nom, dmg, target->nom);
}
}
void fight_p(perso *p1, perso *p2) {
bool turn = true;
while (p1->pv && p2->pv) {
atk(turn ? p1 : p2, turn ? p2 : p1, true);
turn = !turn;
}
}
void fight_t(perso t1[], int size1, perso t2[], int size2) {
int sizes[2] = {size1, size2};
perso *teams[2] = {t1, t2};
while (true) {
for (int t = 0; t < 2; t += 1) {
for (int i = 0; i < sizes[t]; i += 1) {
if (teams[t][i].pv) {
break;
} else if (i == sizes[t] - 1) {
return;
}
}
}
perso *target = &teams[0][rand() % sizes[0]];
for (int i = 0; i < sizes[1]; i += 1) {
atk(&teams[1][i], target, true);
}
perso *temp = teams[0];
teams[0] = teams[1];
teams[1] = temp;
sizes[0] = sizes[0] ^ sizes[1];
sizes[1] = sizes[0] ^ sizes[1];
sizes[0] = sizes[0] ^ sizes[1];
}
}
int main() {
srand(time(NULL));
// perso p1 = {"Kirito", 20, 3, 1};
// perso p2 = {"Asuna", 20, 2, 2};
// print_p(&p1);
// print_p(&p2);
// fight_p(&p1, &p2);
// print_p(&p1);
// print_p(&p2);
perso team1[] = {{"Kirito", 20, 3, 1}, {"Asuna", 20, 2, 2}};
perso team2[] = {{"Alice", 10, 5, 1}, {"Bob", 30, 1, 4}};
fight_t(team1, 2, team2, 2);
print_t(team1, 2);
print_t(team2, 2);
}