-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame1.cpp
More file actions
813 lines (695 loc) · 28.2 KB
/
Copy pathgame1.cpp
File metadata and controls
813 lines (695 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <math.h>
#include <stdarg.h>
#define MOVING 0
#define FIGHTING 1
#define DEAD 2
#define PASIVO 0
#define ALERTA 1
#define MUERTO 2
#define MOVEMENT_DELAY 500000 // 0.5 segundos
#define ATTACK_DELAY 500000 // 0.5 segundos
#define LOCK_RETRY_DELAY 50000 // 0.05 segundos para reintentar lock
typedef struct {
int x;
int y;
} Coordenada;
typedef struct {
int id;
int hp;
int max_hp;
int attack_damage;
int attack_range;
int current_x, current_y;
Coordenada start_coords;
Coordenada *path;
int path_length;
int path_capacity;
int current_path_index;
int estado;
pthread_t thread;
pthread_mutex_t mutex;
} Heroe;
typedef struct {
int id;
int hp;
int max_hp;
int attack_damage;
int vision_range;
int attack_range;
int current_x, current_y;
Coordenada start_coords;
int estado;
int is_alive;
pthread_t thread;
pthread_mutex_t mutex;
} Monstruo;
typedef struct {
int grid_width;
int grid_height;
int hero_count;
int monster_count;
Heroe *heroes;
Monstruo *monstruos;
pthread_mutex_t print_mutex;
pthread_mutex_t *grid_mutexes;
} DatosJuego;
typedef struct {
DatosJuego *juego;
int entity_id;
} ThreadData;
int calcular_distancia_manhattan(int x1, int y1, int x2, int y2) {
return abs(x1 - x2) + abs(y1 - y2);
}
int get_grid_index(int x, int y, int width) {
return y * width + x;
}
int coords_validas(int x, int y, int width, int height) {
return x >= 0 && x < width && y >= 0 && y < height;
}
void print_safe(pthread_mutex_t *mutex, const char *format, ...) {
va_list args;
va_start(args, format);
pthread_mutex_lock(mutex);
vprintf(format, args);
fflush(stdout);
pthread_mutex_unlock(mutex);
va_end(args);
}
void inicializar_heroe(Heroe *h, int id) {
h->id = id;
h->hp = 0;
h->max_hp = 0;
h->attack_damage = 0;
h->attack_range = 0;
h->current_x = 0;
h->current_y = 0;
h->start_coords.x = 0;
h->start_coords.y = 0;
h->path = NULL;
h->path_length = 0;
h->path_capacity = 0;
h->current_path_index = 0;
h->estado = MOVING;
pthread_mutex_init(&h->mutex, NULL);
}
void inicializar_monstruo(Monstruo *m, int id) {
m->id = id;
m->hp = 0;
m->max_hp = 0;
m->attack_damage = 0;
m->vision_range = 0;
m->attack_range = 0;
m->current_x = 0;
m->current_y = 0;
m->start_coords.x = 0;
m->start_coords.y = 0;
m->estado = PASIVO;
m->is_alive = 1;
pthread_mutex_init(&m->mutex, NULL);
}
void agregar_coordenada_path(Heroe *h, int x, int y) {
if (h->path_length >= h->path_capacity) {
h->path_capacity = (h->path_capacity == 0) ? 10 : h->path_capacity * 2;
Coordenada *temp = (Coordenada*)realloc(h->path, h->path_capacity * sizeof(Coordenada));
if (temp == NULL) {
fprintf(stderr, "Error al asignar memoria para path\n");
exit(EXIT_FAILURE);
}
h->path = temp;
}
h->path[h->path_length].x = x;
h->path[h->path_length].y = y;
h->path_length++;
}
void leer_configuracion(const char *nombre_archivo, DatosJuego *juego) {
FILE *archivo = fopen(nombre_archivo, "r");
char linea[512];
if (archivo == NULL) {
perror("Error al abrir el archivo de configuración");
exit(EXIT_FAILURE);
}
printf("=== Leyendo configuración ===\n");
juego->hero_count = 0;
juego->monster_count = 0;
juego->heroes = NULL;
juego->monstruos = NULL;
juego->grid_mutexes = NULL;
int heroes_capacity = 0;
int monsters_capacity = 0;
while (fgets(linea, sizeof(linea), archivo)) {
if (strstr(linea, "_HP") && strstr(linea, "HERO_")) {
int hero_num;
sscanf(linea, "HERO_%d_HP", &hero_num);
if (hero_num > juego->hero_count) {
juego->hero_count = hero_num;
}
}
else if (strncmp(linea, "MONSTER_COUNT", 13) == 0) {
sscanf(linea, "MONSTER_COUNT %d", &juego->monster_count);
}
}
heroes_capacity = juego->hero_count;
monsters_capacity = juego->monster_count;
if (heroes_capacity > 0) {
juego->heroes = (Heroe*)malloc(heroes_capacity * sizeof(Heroe));
if (juego->heroes == NULL) {
fprintf(stderr, "Error al asignar memoria para héroes\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < heroes_capacity; i++) {
inicializar_heroe(&juego->heroes[i], i + 1);
}
}
if (monsters_capacity > 0) {
juego->monstruos = (Monstruo*)malloc(monsters_capacity * sizeof(Monstruo));
if (juego->monstruos == NULL) {
fprintf(stderr, "Error al asignar memoria para monstruos\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < monsters_capacity; i++) {
inicializar_monstruo(&juego->monstruos[i], i + 1);
}
}
rewind(archivo);
while (fgets(linea, sizeof(linea), archivo)) {
if (linea[0] == '\n' || linea[0] == '#') continue;
if (strncmp(linea, "GRID_SIZE", 9) == 0) {
sscanf(linea, "GRID_SIZE %d %d", &juego->grid_width, &juego->grid_height);
}
else if (strstr(linea, "_HP") && strstr(linea, "HERO_")) {
int hero_num, hp;
sscanf(linea, "HERO_%d_HP %d", &hero_num, &hp);
int idx = hero_num - 1;
if (idx >= 0 && idx < heroes_capacity) {
juego->heroes[idx].hp = hp;
juego->heroes[idx].max_hp = hp;
}
}
else if (strstr(linea, "_ATTACK_DAMAGE") && strstr(linea, "HERO_")) {
int hero_num, damage;
sscanf(linea, "HERO_%d_ATTACK_DAMAGE %d", &hero_num, &damage);
int idx = hero_num - 1;
if (idx >= 0 && idx < heroes_capacity) {
juego->heroes[idx].attack_damage = damage;
}
}
else if (strstr(linea, "_ATTACK_RANGE") && strstr(linea, "HERO_")) {
int hero_num, range;
sscanf(linea, "HERO_%d_ATTACK_RANGE %d", &hero_num, &range);
int idx = hero_num - 1;
if (idx >= 0 && idx < heroes_capacity) {
juego->heroes[idx].attack_range = range;
}
}
else if (strstr(linea, "_START") && strstr(linea, "HERO_")) {
int hero_num, x, y;
sscanf(linea, "HERO_%d_START %d %d", &hero_num, &x, &y);
int idx = hero_num - 1;
if (idx >= 0 && idx < heroes_capacity) {
juego->heroes[idx].start_coords.x = x;
juego->heroes[idx].start_coords.y = y;
juego->heroes[idx].current_x = x;
juego->heroes[idx].current_y = y;
}
}
else if (strstr(linea, "_PATH") && strstr(linea, "HERO_")) {
int hero_num;
sscanf(linea, "HERO_%d_PATH", &hero_num);
int idx = hero_num - 1;
if (idx >= 0 && idx < heroes_capacity) {
char *p = strchr(linea, '(');
while (p != NULL) {
int x, y;
if (sscanf(p, "(%d,%d)", &x, &y) == 2) {
agregar_coordenada_path(&juego->heroes[idx], x, y);
}
p = strchr(p + 1, '(');
}
while (fgets(linea, sizeof(linea), archivo)) {
if (linea[0] != '(') {
fseek(archivo, -(long)strlen(linea), SEEK_CUR);
break;
}
p = linea;
while (*p) {
if (*p == '(') {
int x, y;
if (sscanf(p, "(%d,%d)", &x, &y) == 2) {
agregar_coordenada_path(&juego->heroes[idx], x, y);
}
}
p++;
}
}
}
}
else if (strstr(linea, "_HP") && strstr(linea, "MONSTER_")) {
int monster_num, hp;
sscanf(linea, "MONSTER_%d_HP %d", &monster_num, &hp);
int idx = monster_num - 1;
if (idx >= 0 && idx < monsters_capacity) {
juego->monstruos[idx].hp = hp;
juego->monstruos[idx].max_hp = hp;
}
}
else if (strstr(linea, "_ATTACK_DAMAGE") && strstr(linea, "MONSTER_")) {
int monster_num, damage;
sscanf(linea, "MONSTER_%d_ATTACK_DAMAGE %d", &monster_num, &damage);
int idx = monster_num - 1;
if (idx >= 0 && idx < monsters_capacity) {
juego->monstruos[idx].attack_damage = damage;
}
}
else if (strstr(linea, "_VISION_RANGE") && strstr(linea, "MONSTER_")) {
int monster_num, vision;
sscanf(linea, "MONSTER_%d_VISION_RANGE %d", &monster_num, &vision);
int idx = monster_num - 1;
if (idx >= 0 && idx < monsters_capacity) {
juego->monstruos[idx].vision_range = vision;
}
}
else if (strstr(linea, "_ATTACK_RANGE") && strstr(linea, "MONSTER_")) {
int monster_num, range;
sscanf(linea, "MONSTER_%d_ATTACK_RANGE %d", &monster_num, &range);
int idx = monster_num - 1;
if (idx >= 0 && idx < monsters_capacity) {
juego->monstruos[idx].attack_range = range;
}
}
else if (strstr(linea, "_COORDS") && strstr(linea, "MONSTER_")) {
int monster_num, x, y;
sscanf(linea, "MONSTER_%d_COORDS %d %d", &monster_num, &x, &y);
int idx = monster_num - 1;
if (idx >= 0 && idx < monsters_capacity) {
juego->monstruos[idx].start_coords.x = x;
juego->monstruos[idx].start_coords.y = y;
juego->monstruos[idx].current_x = x;
juego->monstruos[idx].current_y = y;
}
}
}
fclose(archivo);
int grid_size = juego->grid_width * juego->grid_height;
juego->grid_mutexes = (pthread_mutex_t*)malloc(grid_size * sizeof(pthread_mutex_t));
if (juego->grid_mutexes == NULL) {
fprintf(stderr, "Error al asignar memoria para grid_mutexes\n");
exit(EXIT_FAILURE);
}
for (int i = 0; i < grid_size; i++) {
pthread_mutex_init(&juego->grid_mutexes[i], NULL);
}
printf("=== Configuración cargada ===\n");
printf("=== Grid mutexes inicializados: %d casillas ===\n\n", grid_size);
}
Heroe* encontrar_heroe_mas_cercano(Monstruo *m, DatosJuego *juego) {
Heroe *mas_cercano = NULL;
int distancia_minima = 999999;
for (int i = 0; i < juego->hero_count; i++) {
Heroe *h = &juego->heroes[i];
pthread_mutex_lock(&h->mutex);
int h_estado = h->estado;
int h_x = h->current_x;
int h_y = h->current_y;
pthread_mutex_unlock(&h->mutex);
if (h_estado != DEAD) {
int dist = calcular_distancia_manhattan(m->current_x, m->current_y, h_x, h_y);
if (dist < distancia_minima) {
distancia_minima = dist;
mas_cercano = h;
}
}
}
return mas_cercano;
}
void alertar_monstruos(Monstruo *alertador, DatosJuego *juego) {
for (int i = 0; i < juego->monster_count; i++) {
Monstruo *m = &juego->monstruos[i];
if (m->id == alertador->id) continue;
pthread_mutex_lock(&m->mutex);
if (m->estado == PASIVO) {
int dist = calcular_distancia_manhattan(
alertador->current_x, alertador->current_y,
m->current_x, m->current_y
);
if (dist <= alertador->vision_range) {
m->estado = ALERTA;
pthread_mutex_unlock(&m->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[MONSTRUO %d] Alertado por MONSTRUO %d\n", m->id, alertador->id);
pthread_mutex_unlock(&juego->print_mutex);
} else {
pthread_mutex_unlock(&m->mutex);
}
} else {
pthread_mutex_unlock(&m->mutex);
}
}
}
void* thread_heroe(void *arg) {
ThreadData *data = (ThreadData*)arg;
DatosJuego *juego = data->juego;
int hero_id = data->entity_id;
Heroe *heroe = &juego->heroes[hero_id];
int inicial_idx = get_grid_index(heroe->current_x, heroe->current_y, juego->grid_width);
// Intentar obtener lock de casilla inicial con reintentos
while (pthread_mutex_trylock(&juego->grid_mutexes[inicial_idx]) != 0) {
usleep(LOCK_RETRY_DELAY);
}
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] Comienza en (%d, %d) - Casilla bloqueada\n",
heroe->id, heroe->current_x, heroe->current_y);
pthread_mutex_unlock(&juego->print_mutex);
for (int i = 0; i < heroe->path_length; i++) {
pthread_mutex_lock(&heroe->mutex);
if (heroe->estado == DEAD) {
pthread_mutex_unlock(&heroe->mutex);
break;
}
pthread_mutex_unlock(&heroe->mutex);
int nueva_x = heroe->path[i].x;
int nueva_y = heroe->path[i].y;
if (!coords_validas(nueva_x, nueva_y, juego->grid_width, juego->grid_height)) {
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] ADVERTENCIA: Coordenada (%d, %d) fuera del grid\n",
heroe->id, nueva_x, nueva_y);
pthread_mutex_unlock(&juego->print_mutex);
continue;
}
int vieja_x = heroe->current_x;
int vieja_y = heroe->current_y;
int viejo_idx = get_grid_index(vieja_x, vieja_y, juego->grid_width);
int nuevo_idx = get_grid_index(nueva_x, nueva_y, juego->grid_width);
if (viejo_idx != nuevo_idx) {
// Intentar obtener lock con reintentos
int intentos = 0;
while (pthread_mutex_trylock(&juego->grid_mutexes[nuevo_idx]) != 0) {
usleep(LOCK_RETRY_DELAY);
intentos++;
if (intentos > 20) { // Después de 20 intentos, esperar en la casilla actual
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] Casilla (%d, %d) ocupada, esperando...\n",
heroe->id, nueva_x, nueva_y);
pthread_mutex_unlock(&juego->print_mutex);
intentos = 0;
usleep(MOVEMENT_DELAY);
}
}
heroe->current_x = nueva_x;
heroe->current_y = nueva_y;
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] Se mueve de (%d, %d) a (%d, %d)\n",
heroe->id, vieja_x, vieja_y, nueva_x, nueva_y);
pthread_mutex_unlock(&juego->print_mutex);
pthread_mutex_unlock(&juego->grid_mutexes[viejo_idx]);
} else {
heroe->current_x = nueva_x;
heroe->current_y = nueva_y;
}
usleep(MOVEMENT_DELAY);
int hay_monstruos_en_rango = 0;
do {
hay_monstruos_en_rango = 0;
for (int j = 0; j < juego->monster_count; j++) {
Monstruo *m = &juego->monstruos[j];
pthread_mutex_lock(&m->mutex);
if (m->is_alive) {
int dist = calcular_distancia_manhattan(
heroe->current_x, heroe->current_y,
m->current_x, m->current_y
);
if (dist <= heroe->attack_range) {
hay_monstruos_en_rango = 1;
int hp_antes = m->hp;
m->hp -= heroe->attack_damage;
int hp_despues = m->hp;
if (m->hp <= 0) {
m->hp = 0;
m->is_alive = 0;
m->estado = MUERTO;
pthread_mutex_unlock(&m->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] Ataca a MONSTRUO %d (HP: %d -> %d)\n",
heroe->id, m->id, hp_antes, hp_despues);
printf("[MONSTRUO %d] Ha muerto\n", m->id);
pthread_mutex_unlock(&juego->print_mutex);
} else {
pthread_mutex_unlock(&m->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] Ataca a MONSTRUO %d (HP: %d -> %d)\n",
heroe->id, m->id, hp_antes, hp_despues);
pthread_mutex_unlock(&juego->print_mutex);
}
usleep(ATTACK_DELAY);
break;
} else {
pthread_mutex_unlock(&m->mutex);
}
} else {
pthread_mutex_unlock(&m->mutex);
}
}
pthread_mutex_lock(&heroe->mutex);
if (heroe->hp <= 0) {
heroe->estado = DEAD;
pthread_mutex_unlock(&heroe->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] Ha muerto\n", heroe->id);
pthread_mutex_unlock(&juego->print_mutex);
int current_idx = get_grid_index(heroe->current_x, heroe->current_y, juego->grid_width);
pthread_mutex_unlock(&juego->grid_mutexes[current_idx]);
free(data);
return NULL;
}
pthread_mutex_unlock(&heroe->mutex);
} while (hay_monstruos_en_rango);
}
pthread_mutex_lock(&heroe->mutex);
if (heroe->estado != DEAD) {
pthread_mutex_unlock(&heroe->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[HEROE %d] Ha llegado a su destino\n", heroe->id);
pthread_mutex_unlock(&juego->print_mutex);
} else {
pthread_mutex_unlock(&heroe->mutex);
}
int final_idx = get_grid_index(heroe->current_x, heroe->current_y, juego->grid_width);
pthread_mutex_unlock(&juego->grid_mutexes[final_idx]);
free(data);
return NULL;
}
void* thread_monstruo(void *arg) {
ThreadData *data = (ThreadData*)arg;
DatosJuego *juego = data->juego;
int monster_id = data->entity_id;
Monstruo *monstruo = &juego->monstruos[monster_id];
int inicial_idx = get_grid_index(monstruo->current_x, monstruo->current_y, juego->grid_width);
// Intentar obtener lock con reintentos
while (pthread_mutex_trylock(&juego->grid_mutexes[inicial_idx]) != 0) {
usleep(LOCK_RETRY_DELAY);
}
pthread_mutex_lock(&juego->print_mutex);
printf("[MONSTRUO %d] Comienza en (%d, %d) - Casilla bloqueada\n",
monstruo->id, monstruo->current_x, monstruo->current_y);
pthread_mutex_unlock(&juego->print_mutex);
while (1) {
pthread_mutex_lock(&monstruo->mutex);
if (!monstruo->is_alive) {
pthread_mutex_unlock(&monstruo->mutex);
int current_idx = get_grid_index(monstruo->current_x, monstruo->current_y, juego->grid_width);
pthread_mutex_unlock(&juego->grid_mutexes[current_idx]);
break;
}
if (monstruo->estado == PASIVO) {
pthread_mutex_unlock(&monstruo->mutex);
int heroe_detectado = 0;
for (int i = 0; i < juego->hero_count; i++) {
Heroe *h = &juego->heroes[i];
pthread_mutex_lock(&h->mutex);
int h_estado = h->estado;
int h_x = h->current_x;
int h_y = h->current_y;
pthread_mutex_unlock(&h->mutex);
if (h_estado != DEAD) {
int dist = calcular_distancia_manhattan(
monstruo->current_x, monstruo->current_y, h_x, h_y
);
if (dist <= monstruo->vision_range) {
pthread_mutex_lock(&monstruo->mutex);
monstruo->estado = ALERTA;
pthread_mutex_unlock(&monstruo->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[MONSTRUO %d] Detecta a HEROE %d en su rango de visión\n",
monstruo->id, h->id);
pthread_mutex_unlock(&juego->print_mutex);
alertar_monstruos(monstruo, juego);
heroe_detectado = 1;
break;
}
}
}
if (!heroe_detectado) {
usleep(MOVEMENT_DELAY);
}
}
else if (monstruo->estado == ALERTA) {
pthread_mutex_unlock(&monstruo->mutex);
Heroe *objetivo = encontrar_heroe_mas_cercano(monstruo, juego);
if (objetivo == NULL) {
int current_idx = get_grid_index(monstruo->current_x, monstruo->current_y, juego->grid_width);
pthread_mutex_unlock(&juego->grid_mutexes[current_idx]);
break;
}
pthread_mutex_lock(&objetivo->mutex);
int obj_x = objetivo->current_x;
int obj_y = objetivo->current_y;
pthread_mutex_unlock(&objetivo->mutex);
int dist = calcular_distancia_manhattan(
monstruo->current_x, monstruo->current_y, obj_x, obj_y
);
if (dist <= monstruo->attack_range) {
pthread_mutex_lock(&objetivo->mutex);
int hp_antes = objetivo->hp;
objetivo->hp -= monstruo->attack_damage;
int hp_despues = objetivo->hp;
if (objetivo->hp <= 0) {
objetivo->hp = 0;
objetivo->estado = DEAD;
pthread_mutex_unlock(&objetivo->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[MONSTRUO %d] Ataca a HEROE %d (HP: %d -> %d)\n",
monstruo->id, objetivo->id, hp_antes, hp_despues);
printf("[HEROE %d] Ha sido derrotado\n", objetivo->id);
pthread_mutex_unlock(&juego->print_mutex);
} else {
pthread_mutex_unlock(&objetivo->mutex);
pthread_mutex_lock(&juego->print_mutex);
printf("[MONSTRUO %d] Ataca a HEROE %d (HP: %d -> %d)\n",
monstruo->id, objetivo->id, hp_antes, hp_despues);
pthread_mutex_unlock(&juego->print_mutex);
}
usleep(ATTACK_DELAY);
}
else {
int old_x = monstruo->current_x;
int old_y = monstruo->current_y;
int new_x = old_x;
int new_y = old_y;
if (old_x < obj_x) {
new_x++;
} else if (old_x > obj_x) {
new_x--;
} else if (old_y < obj_y) {
new_y++;
} else if (old_y > obj_y) {
new_y--;
}
if (coords_validas(new_x, new_y, juego->grid_width, juego->grid_height)) {
int viejo_idx = get_grid_index(old_x, old_y, juego->grid_width);
int nuevo_idx = get_grid_index(new_x, new_y, juego->grid_width);
if (viejo_idx != nuevo_idx) {
// Intentar obtener lock con reintentos
int intentos = 0;
while (pthread_mutex_trylock(&juego->grid_mutexes[nuevo_idx]) != 0) {
usleep(LOCK_RETRY_DELAY);
intentos++;
if (intentos > 20) {
pthread_mutex_lock(&juego->print_mutex);
printf("[MONSTRUO %d] Casilla (%d, %d) ocupada, esperando...\n",
monstruo->id, new_x, new_y);
pthread_mutex_unlock(&juego->print_mutex);
intentos = 0;
usleep(MOVEMENT_DELAY);
}
}
monstruo->current_x = new_x;
monstruo->current_y = new_y;
pthread_mutex_lock(&juego->print_mutex);
printf("[MONSTRUO %d] Se mueve hacia HEROE %d: (%d,%d) -> (%d,%d)\n",
monstruo->id, objetivo->id, old_x, old_y, new_x, new_y);
pthread_mutex_unlock(&juego->print_mutex);
pthread_mutex_unlock(&juego->grid_mutexes[viejo_idx]);
}
}
usleep(MOVEMENT_DELAY);
}
} else {
pthread_mutex_unlock(&monstruo->mutex);
}
}
free(data);
return NULL;
}
void liberar_heroe(Heroe *h) {
if (h->path != NULL) {
free(h->path);
h->path = NULL;
}
pthread_mutex_destroy(&h->mutex);
}
void liberar_monstruo(Monstruo *m) {
pthread_mutex_destroy(&m->mutex);
}
void liberar_juego(DatosJuego *juego) {
if (juego->heroes != NULL) {
for (int i = 0; i < juego->hero_count; i++) {
liberar_heroe(&juego->heroes[i]);
}
free(juego->heroes);
juego->heroes = NULL;
}
if (juego->monstruos != NULL) {
for (int i = 0; i < juego->monster_count; i++) {
liberar_monstruo(&juego->monstruos[i]);
}
free(juego->monstruos);
juego->monstruos = NULL;
}
if (juego->grid_mutexes != NULL) {
int grid_size = juego->grid_width * juego->grid_height;
for (int i = 0; i < grid_size; i++) {
pthread_mutex_destroy(&juego->grid_mutexes[i]);
}
free(juego->grid_mutexes);
juego->grid_mutexes = NULL;
}
pthread_mutex_destroy(&juego->print_mutex);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Uso: %s <archivo_configuracion>\n", argv[0]);
return EXIT_FAILURE;
}
DatosJuego juego;
pthread_mutex_init(&juego.print_mutex, NULL);
leer_configuracion(argv[1], &juego);
printf("=== INICIANDO SIMULACIÓN ===\n");
printf("Grid: %dx%d\n", juego.grid_width, juego.grid_height);
printf("Héroes: %d\n", juego.hero_count);
printf("Monstruos: %d\n\n", juego.monster_count);
for (int i = 0; i < juego.hero_count; i++) {
ThreadData *data = (ThreadData*)malloc(sizeof(ThreadData));
data->juego = &juego;
data->entity_id = i;
pthread_create(&juego.heroes[i].thread, NULL, thread_heroe, data);
}
for (int i = 0; i < juego.monster_count; i++) {
ThreadData *data = (ThreadData*)malloc(sizeof(ThreadData));
data->juego = &juego;
data->entity_id = i;
pthread_create(&juego.monstruos[i].thread, NULL, thread_monstruo, data);
}
for (int i = 0; i < juego.hero_count; i++) {
pthread_join(juego.heroes[i].thread, NULL);
}
for (int i = 0; i < juego.monster_count; i++) {
pthread_join(juego.monstruos[i].thread, NULL);
}
printf("\n=== SIMULACIÓN TERMINADA ===\n");
liberar_juego(&juego);
return EXIT_SUCCESS;
}