-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
1101 lines (938 loc) · 40 KB
/
main.c
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* main.c
* Created on Mai, 21th 2024
* Author: Lisa Matubara, Luziane Santos e Thaís Aguiar, com base no trabalho de Tiago Barros
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include "screen.h"
#include "keyboard.h"
#include "timer.h"
// REQUISITO 1 - STRUCT
// Define a struct Raquete com seus elementos (typedef cria um alias (raquete))
typedef struct Raquete {
int x, y; // posição (x, y) da raquete
int largura; // largura da raquete
int altura; // altura da raquete
char simbolo; // símbolo que forma a raquete
} raquete;
// REQUISITO 1 - STRUCT
// Define a struct Obstaculo com seus elementos (typedef cria um alias (obstaculo))
typedef struct Obstaculo {
int x, y; // posição (x, y) do obstáculo
int altura; // altura do obstáculo
int direcao; // direção de movimento (1 para baixo, -1 para cima)
char simbolo; // símbolo que forma o obstáculo
} obstaculo;
// REQUISITO 1 - STRUCT
typedef struct Tempo {
int minutos;
int segundos;
struct Tempo *proximo;
} Tempo;
// REQUISITO 2 - PONTEIROS
Tempo *melhoresTempos = NULL;
// Define a posição inicial (x,y) da bola e seus incrementos (+1)
int x = 34, y = 12;
int incX = 1, incY = 1;
// Cria variável com o número de raquetes
int qtde_raquete = 2;
// Cria variáveis para acumular pontuação
int jogador1 = 0;
int jogador2 = 0;
// Define o tempo máximo em segundos (2 minutos)
#define TEMPO_MAXIMO 150
// Estrutura para armazenar o tempo de início
struct timeval tempoInicio;
// Função para exibir a tela inicial - nome Pong
void exibirTelaInicial() {
screenClear();
screenDrawBorders();
screenSetColor(WHITE, DARKGRAY);
screenGotoxy((MAXX / 2) - 15, MAXY / 2 - 4);
printf(" ____ ____ _ _ ____ ");
screenGotoxy((MAXX / 2) - 15, MAXY / 2 - 3);
printf("| __ \\ / __ \\| \\ | |/ __ \\");
screenGotoxy((MAXX / 2) - 15, MAXY / 2 - 2);
printf("| |__) | | | | \\| | | ___");
screenGotoxy((MAXX / 2) - 15, MAXY / 2 - 1);
printf("| ___/| | | | . ` | ||__ |");
screenGotoxy((MAXX / 2) - 15, MAXY / 2);
printf("| | | |__| | |\\ | |__| |");
screenGotoxy((MAXX / 2) - 15, MAXY / 2 + 1);
printf("|_| \\____/|_| \\_|\\____/");
screenGotoxy((MAXX / 2) - 5, MAXY / 2 + 3);
screenSetColor(YELLOW, DARKGRAY);
printf("▶ Começar");
screenUpdate();
while (1) {
int ch = readch();
if (ch == 10) { // Enter
break;
}
}
}
// REQUISITO 2 - PONTEIROS
int exibirMenuJogadores() {
const char *opcoes[] = {"Apenas um jogador (1)", "Dois Jogadores (2)"};
int opcao = 0;
while (1) {
screenClear();
screenDrawBorders();
screenGotoxy((MAXX / 2) - 12, (MAXY / 2) - 2);
screenSetColor(WHITE, DARKGRAY);
printf("Quantos jogadores?");
for (int i = 0; i < 2; i++) {
screenGotoxy((MAXX / 2) - 12, (MAXY / 2) + i);
if (i == opcao) {
screenSetColor(YELLOW, DARKGRAY);
printf("▶ %s", opcoes[i]);
screenSetColor(WHITE, DARKGRAY); // Reseta a cor após imprimir a linha selecionada
} else {
screenSetColor(WHITE, DARKGRAY);
printf(" %s", opcoes[i]);
}
}
screenUpdate();
int ch = readch();
if (ch == 10) { // Enter
break;
} if (ch == 'A') {
opcao = (opcao > 0) ? opcao - 1 : 2; // Move para cima
} else if (ch == 'B') {
opcao = (opcao < 2) ? opcao + 1 : 0; // Move para baixo
}
}
return opcao;
}
// REQUISITO 2 - PONTEIROS
// Menu para 1 jogador (Jogar ou Ranking)
int exibirMenu1Jogador() {
const char *opcoes[] = {"Jogar", "Ranking"};
int opcao = 0;
while (1) {
screenClear();
screenDrawBorders();
screenGotoxy((MAXX / 2) - 12, (MAXY / 2) - 4);
screenSetColor(WHITE, DARKGRAY);
printf("O que você deseja fazer?");
for (int i = 0; i < 2; i++) {
screenGotoxy((MAXX / 2) - 12, (MAXY / 2) - 2 + i);
if (i == opcao) {
screenSetColor(YELLOW, DARKGRAY);
printf("▶ %s", opcoes[i]);
screenSetColor(WHITE, DARKGRAY); // Reseta a cor após imprimir a linha selecionada
} else {
screenSetColor(WHITE, DARKGRAY);
printf(" %s", opcoes[i]);
}
}
screenUpdate();
int ch = readch();
if (ch == 10) { // Enter
break;
} if (ch == 'A') {
opcao = (opcao > 0) ? opcao - 1 : 2; // Move para cima
} else if (ch == 'B') {
opcao = (opcao < 3) ? opcao + 1 : 0; // Move para baixo
}
}
return opcao;
}
// REQUISITO 2 - PONTEIROS
// Menu para selecionar o nível de 1 jogador
int exibirMenuNiveis1() {
const char *niveis[] = {"Iniciante", "Intermediário", "Avançado", "Expert"};
int opcao = 0;
while (1) {
screenClear();
screenDrawBorders();
for (int i = 0; i < 4; i++) {
screenGotoxy((MAXX / 2) - 12, (MAXY / 2) - 2 + i);
if (i == opcao) {
screenSetColor(YELLOW, DARKGRAY);
printf("▶ %s", niveis[i]);
screenSetColor(WHITE, DARKGRAY); // Reseta a cor após imprimir a linha selecionada
} else {
screenSetColor(WHITE, DARKGRAY);
printf(" %s", niveis[i]);
}
}
screenUpdate();
int ch = readch();
if (ch == 10) { // Enter
break;
} if (ch == 'A') {
opcao = (opcao > 0) ? opcao - 1 : 4; // Move para cima
} else if (ch == 'B') {
opcao = (opcao < 4) ? opcao + 1 : 0; // Move para baixo
}
}
return opcao;
}
// REQUISITO 2 - PONTEIROS
// Menu para selecionar o nível de 2 jogadores
int exibirMenuNiveis2() {
const char *niveis[] = {"Iniciante", "Intermediário", "Avançado", "Expert"};
int opcao = 0;
while (1) {
screenClear();
screenDrawBorders();
for (int i = 0; i < 4; i++) {
screenGotoxy((MAXX / 2) - 12, (MAXY / 2) - 2 + i);
if (i == opcao) {
screenSetColor(YELLOW, DARKGRAY);
printf("▶ %s", niveis[i]);
screenSetColor(WHITE, DARKGRAY); // Reseta a cor após imprimir a linha selecionada
} else {
screenSetColor(WHITE, DARKGRAY);
printf(" %s", niveis[i]);
}
}
screenUpdate();
int ch = readch();
if (ch == 10) { // Enter
break;
} if (ch == 'A') {
opcao = (opcao > 0) ? opcao - 1 : 4; // Move para cima
} else if (ch == 'B') {
opcao = (opcao < 3) ? opcao + 1 : 0; // Move para baixo
}
}
return opcao;
}
// Função para exibir as instruções
void exibirInstrucoes(int nivel) {
screenClear();
screenDrawBorders();
screenSetColor(WHITE, DARKGRAY);
switch(nivel) {
case 0:
screenGotoxy(3, 2);
printf("Instruções - Nível Iniciante");
screenGotoxy(3, 4);
printf("Player 1 (Esquerda) ou Single Player:");
screenGotoxy(3, 5);
printf("- Digite 'W' ou 'w' para movimentar a raquete para cima");
screenGotoxy(3, 6);
printf("- Digite 'S' ou 's' para movimentar a raquete para baixo");
screenGotoxy(3, 8);
printf("Player 2 (Direita) ou bot:");
screenGotoxy(3, 9);
printf("- Digite 'O' ou 'o' para movimentar a raquete para cima");
screenGotoxy(3, 10);
printf("- Digite 'L' ou 'l' para movimentar a raquete para baixo");
screenGotoxy(3, 12);
printf("Especificações:");
screenGotoxy(3, 13);
printf("- Raquete altura: modo fácil");
screenGotoxy(3, 14);
printf("- Velocidade da bola: modo fácil");
screenGotoxy(3, 15);
printf("- Obstáculo: Não");
screenGotoxy(3, 17);
printf("Ganha quem fizer 5 pontos primeiro ou");
screenGotoxy(3, 18);
printf("tiver mais pontos quando acabar os 90 segundos de cronômetro.");
screenGotoxy(3, 20);
printf("Pressione \"Enter\" para continuar.");
screenGotoxy(3, 22);
printf("Boa sorte!");
break;
case 1:
screenGotoxy(3, 2);
printf("Instruções - Nível Intermediário");
screenGotoxy(3, 4);
printf("Player 1 (Esquerda) ou Single Player:");
screenGotoxy(3, 5);
printf("- Digite 'W' ou 'w' para movimentar a raquete para cima");
screenGotoxy(3, 6);
printf("- Digite 'S' ou 's' para movimentar a raquete para baixo");
screenGotoxy(3, 8);
printf("Player 2 (Direita) ou bot:");
screenGotoxy(3, 9);
printf("- Digite 'O' ou 'o' para movimentar a raquete para cima");
screenGotoxy(3, 10);
printf("- Digite 'L' ou 'l' para movimentar a raquete para baixo");
screenGotoxy(3, 12);
printf("Especificações:");
screenGotoxy(3, 13);
printf("- Raquete altura: modo difícil");
screenGotoxy(3, 14);
printf("- Velocidade da bola: modo fácil");
screenGotoxy(3, 15);
printf("- Obstáculo: Não");
screenGotoxy(3, 17);
printf("Ganha quem fizer 5 pontos primeiro ou");
screenGotoxy(3, 18);
printf("tiver mais pontos quando acabar os 90 segundos de cronômetro.");
screenGotoxy(3, 20);
printf("Pressione \"Enter\" para continuar.");
screenGotoxy(3, 22);
printf("Boa sorte!");
break;
case 2:
screenGotoxy(3, 2);
printf("Instruções - Nível Avançado");
screenGotoxy(3, 4);
printf("Player 1 (Esquerda) ou Single Player:");
screenGotoxy(3, 5);
printf("- Digite 'W' ou 'w' para movimentar a raquete para cima");
screenGotoxy(3, 6);
printf("- Digite 'S' ou 's' para movimentar a raquete para baixo");
screenGotoxy(3, 8);
printf("Player 2 (Direita) ou bot:");
screenGotoxy(3, 9);
printf("- Digite 'O' ou 'o' para movimentar a raquete para cima");
screenGotoxy(3, 10);
printf("- Digite 'L' ou 'l' para movimentar a raquete para baixo");
screenGotoxy(3, 12);
printf("Especificações:");
screenGotoxy(3, 13);
printf("- Raquete altura: modo difícil");
screenGotoxy(3, 14);
printf("- Velocidade da bola: modo difícil");
screenGotoxy(3, 15);
printf("- Obstáculo: Não");
screenGotoxy(3, 17);
printf("Ganha quem fizer 5 pontos primeiro ou");
screenGotoxy(3, 18);
printf("tiver mais pontos quando acabar os 90 segundos de cronômetro.");
screenGotoxy(3, 20);
printf("Pressione \"Enter\" para continuar.");
screenGotoxy(3, 22);
printf("Boa sorte!");
break;
case 3:
screenGotoxy(3, 2);
printf("Instruções - Nível Expert");
screenGotoxy(3, 4);
printf("Player 1 (Esquerda) ou Single Player:");
screenGotoxy(3, 5);
printf("- Digite 'W' ou 'w' para movimentar a raquete para cima");
screenGotoxy(3, 6);
printf("- Digite 'S' ou 's' para movimentar a raquete para baixo");
screenGotoxy(3, 8);
printf("Player 2 (Direita) ou bot:");
screenGotoxy(3, 9);
printf("- Digite 'O' ou 'o' para movimentar a raquete para cima");
screenGotoxy(3, 10);
printf("- Digite 'L' ou 'l' para movimentar a raquete para baixo");
screenGotoxy(3, 12);
printf("Especificações:");
screenGotoxy(3, 13);
printf("- Raquete altura: modo difícil");
screenGotoxy(3, 14);
printf("- Velocidade da bola: modo difícil");
screenGotoxy(3, 15);
printf("- Obstáculo: Sim");
screenGotoxy(3, 17);
printf("Ganha quem fizer 10 pontos primeiro ou");
screenGotoxy(3, 18);
printf("tiver mais pontos quando acabar os 90 segundos de cronômetro.");
screenGotoxy(3, 20);
printf("Pressione \"Enter\" para continuar.");
screenGotoxy(3, 22);
printf("Boa sorte!");
break;
}
screenUpdate();
while (1) {
int ch = readch();
if (ch == 10) { // Enter
break;
}
}
}
// Função para exibir as instruções do modo single player
void exibirInstrucoesSinglePlayer() {
screenClear();
screenDrawBorders();
screenSetColor(WHITE, DARKGRAY);
screenGotoxy(3, 2);
printf("Instruções - Modo Single Player");
screenGotoxy(3, 4);
printf("Você (Player) controla a raquete da esquerda:");
screenGotoxy(3, 5);
printf("- Digite 'W' ou 'w' para movimentar a raquete para cima");
screenGotoxy(3, 6);
printf("- Digite 'S' ou 's' para movimentar a raquete para baixo");
screenGotoxy(3, 8);
printf("O Bot (Adversário) controla a raquete da direita:");
screenGotoxy(3, 9);
printf("- O Bot se moverá automaticamente para rebater a bola.");
screenGotoxy(3, 11);
printf("O tamanho da raquete, velocidade da bola e obstáculos");
screenGotoxy(3, 12);
printf("estão conforme o nível de dificuldade selecionado.");
screenGotoxy(3, 15);
printf("Ganha quem fizer 5 pontos primeiro");
screenGotoxy(3, 19);
printf("Pressione \"Enter\" para continuar.");
screenGotoxy(3, 21);
printf("Boa sorte!");
screenUpdate();
while (1) {
int ch = readch();
if (ch == 10) { // Enter
break;
}
}
}
// Função que movimenta a bola no terminal
void printBola(int nextX, int nextY) {
screenSetColor(CYAN, DARKGRAY);
screenGotoxy(x, y);
printf(" ");
x = nextX;
y = nextY;
screenGotoxy(x, y);
printf("●"); // Usando a bolinha Unicode
}
// REQUISITO 2 - PONTEIROS
// Inicializa a raquete com seus parâmetros
void iniciar_raquete(raquete *rptr, int x, int y, int largura, int altura, char simbolo) {
rptr->x = x;
rptr->y = y;
rptr->largura = largura;
rptr->altura = altura;
rptr->simbolo = simbolo;
}
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
// Função para imprimir a raquete na tela
void imprimir_raquete(raquete *rptr) {
screenSetColor(MAGENTA, DARKGRAY);
for (int i = 0; i < rptr->altura; i++) {
screenGotoxy(rptr->x, rptr->y + i);
printf("%c", rptr->simbolo);
}
}
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
// Função para apagar a raquete da tela
void apagar_raquete(raquete *rptr) {
for (int i = 0; i < rptr->altura; i++) {
screenGotoxy(rptr->x, rptr->y + i);
printf(" ");
}
}
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
// Função para imprimir o obstáculo na tela
void imprimir_obstaculo(obstaculo *optr) {
screenSetColor(RED, DARKGRAY);
for (int i = 0; i < optr->altura; i++) {
screenGotoxy(optr->x, optr->y + i);
printf("%c", optr->simbolo);
}
}
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
// Função para apagar o obstáculo da tela
void apagar_obstaculo(obstaculo *optr) {
for (int i = 0; i < optr->altura; i++) {
screenGotoxy(optr->x, optr->y + i);
printf(" ");
}
}
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
// Função para verificar se houve colisão com a raquete
int verificar_colisao(raquete *rptr, int Ox, int Oy) {
for (int i = 0; i < rptr->altura; i++) {
for (int j = 0; j < rptr->largura; j++) {
if (Ox == rptr->x + j && Oy == rptr->y + i) {
return 1; // Houve colisão com a raquete
}
}
}
return 0; // Não houve colisão com a raquete
}
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
// Função para verificar se houve colisão com o obstáculo
int verificar_colisao_obstaculo(obstaculo *optr, int Ox, int Oy) {
for (int i = 0; i < optr->altura; i++) {
if (Ox == optr->x && Oy == optr->y + i) {
return 1; // Houve colisão com o obstáculo
}
}
return 0; // Não houve colisão com o obstáculo
}
// Função para desenhar a linha pontilhada no meio da tela
void desenharLinhaPontilhada() {
screenSetColor(WHITE, DARKGRAY);
for (int i = MINY + 1; i < MAXY; i++) {
if (i % 2 == 0) {
screenGotoxy((MAXX - MINX) / 2, i);
printf("|");
}
}
}
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
// Função para inserir um novo tempo na lista
void inserirTempo(int minutos, int segundos) {
// Verifica se o tempo já existe na lista
Tempo *atual = melhoresTempos;
while (atual != NULL) {
if (atual->minutos == minutos && atual->segundos == segundos) {
return; // O tempo já existe, não insere duplicado
}
atual = atual->proximo;
}
Tempo *novo = (Tempo *)malloc(sizeof(Tempo));
novo->minutos = minutos;
novo->segundos = segundos;
novo->proximo = NULL;
if (melhoresTempos == NULL || (melhoresTempos->minutos > minutos || (melhoresTempos->minutos == minutos && melhoresTempos->segundos > segundos))) {
novo->proximo = melhoresTempos;
melhoresTempos = novo;
} else {
Tempo *atual = melhoresTempos;
while (atual->proximo != NULL && (atual->proximo->minutos < minutos || (atual->proximo->minutos == minutos && atual->proximo->segundos < segundos))) {
atual = atual->proximo;
}
novo->proximo = atual->proximo;
atual->proximo = novo;
}
}
// REQUISITOS 5 - ESCREVER ARQUIVO
void salvarTempos() {
FILE *file = fopen("melhores_tempos.txt", "w");
if (file != NULL) {
Tempo *atual = melhoresTempos;
while (atual != NULL) {
fprintf(file, "%02d:%02d\n", atual->minutos, atual->segundos);
atual = atual->proximo;
}
fclose(file);
} else {
printf("Erro ao abrir o arquivo de melhores tempos para escrita!\n");
}
}
// REQUISITOS 5 - LER ARQUIVO
void carregarPontuacoes() {
FILE *file = fopen("melhores_tempos.txt", "r");
if (file != NULL) {
int minutos, segundos;
while (fscanf(file, "%d:%d", &minutos, &segundos) == 2) {
inserirTempo(minutos, segundos); // Insere o tempo na lista
}
fclose(file);
} else {
screenGotoxy((MAXX / 2) - (strlen("Ainda não há recordes!") / 2), MAXY / 2);
printf("Ainda não há recordes!\n");
screenUpdate();
}
}
void mover_bot(raquete *rptr, int bolaY, int chanceErro) {
int erro = rand() % 100; // Gera um número entre 0 e 99
// REQUISITOS 1 e 2 - STRUCTS E PONTEIROS
if (erro >= chanceErro) { // chanceErro% de chance de cometer um erro
if (bolaY < rptr->y && rptr->y > MINY + 1) {
rptr->y--;
} else if (bolaY > rptr->y + rptr->altura - 1 && rptr->y < MAXY - rptr->altura) {
rptr->y++;
}
} else {
// Movimenta aleatoriamente para cima ou para baixo
if (rand() % 2 == 0 && rptr->y > MINY + 1) {
rptr->y--;
} else if (rptr->y < MAXY - rptr->altura) {
rptr->y++;
}
}
}
// REQUISITOS 2 e 5 - PONTEIROS E ESCRITA ARQUIVOS
// Função para salvar a pontuação dos jogadores em um arquivo
void salvar_pontuacao(int jogador1, int jogador2) {
FILE *file = fopen("pontuacao.txt", "w");
if (file != NULL) {
fprintf(file, "Jogador 1: %d\n", jogador1);
fprintf(file, "Jogador 2: %d\n", jogador2);
fclose(file);
} else {
printf("Erro ao abrir o arquivo de pontuação!\n");
}
}
// Função para exibir a pontuação dos jogadores
void exibirPontuacao() {
screenSetColor(YELLOW, DARKGRAY);
screenGotoxy((MAXX / 4) - 1, MAXY - 1);
printf("%d", jogador1);
screenGotoxy((3 * MAXX / 4) - 1, MAXY - 1);
printf("%d", jogador2);
}
// Função para calcular o tempo restante e exibir no canto superior central
// REQUISITO 1 - STRUCTS
void exibirTimer() {
struct timeval tempoAtual;
gettimeofday(&tempoAtual, NULL);
long tempoPassado = (tempoAtual.tv_sec - tempoInicio.tv_sec);
long tempoRestante = TEMPO_MAXIMO - tempoPassado;
if (tempoRestante < 0) {
tempoRestante = 0;
}
screenSetColor(GREEN, DARKGRAY);
screenGotoxy((MAXX / 2) - 3, MINY);
printf("%02ld:%02ld", tempoRestante / 60, tempoRestante % 60);
}
void limparEstadoDoJogo() {
jogador1 = 0;
jogador2 = 0;
x = 34;
y = 12;
incX = 1;
incY = 1;
}
// REQUISITO 2 - PONTEIROS
void exibirResultado(const char *mensagem) {
screenClear();
screenSetColor(RED, DARKGRAY);
screenGotoxy((MAXX / 2) - (strlen(mensagem) / 2), MAXY / 2);
printf("%s", mensagem);
screenGotoxy((MAXX / 2) - (strlen("Pressione \"Enter\" para voltar à tela inicial") / 2), MAXY / 2 + 2);
screenSetColor(WHITE, DARKGRAY);
printf("Pressione \"Enter\" para voltar à tela inicial");
screenUpdate();
while (1) {
int ch = readch();
if (ch == 10) { // Enter
limparEstadoDoJogo(); // Reseta o estado do jogo
break; // Sai do loop de exibição de resultado
}
}
}
// REQUISITO 4 - LISTA ENCADEADA
void exibirRanking() {
screenClear();
screenDrawBorders();
screenSetColor(WHITE, DARKGRAY);
screenGotoxy((MAXX / 2) - 20, 5);
printf("Melhores Tempos no Expert\n");
carregarPontuacoes(); // Carrega os tempos do arquivo
Tempo *atual = melhoresTempos;
int pos = 1;
int yPos = 7;
while (atual != NULL && pos <= 10) {
screenGotoxy((MAXX / 2) - 20, yPos++);
printf("%d. %02d:%02d", pos++, atual->minutos, atual->segundos);
atual = atual->proximo;
}
screenGotoxy((MAXX / 2) - (strlen("Pressione 'Enter' para voltar.") / 2), MAXY / 2 + 6);
printf("Pressione \"Enter\" para voltar.\n");
screenUpdate();
while (1) {
int ch = readch();
if (ch == 10) { // Enter
break;
}
}
}
int main() {
static int ch = 0;
obstaculo obst; // Declaração do obstáculo para o modo Expert
int chanceErro; // Declaração da variável chanceErro
keyboardInit();
while (1) {
// Exibe a tela inicial
exibirTelaInicial();
// Exibe o menu de número de jogadores
int jogadores = exibirMenuJogadores();
int opcao1Jogador;
if (jogadores == 0) { // Se for 1 jogador
while (1) {
opcao1Jogador = exibirMenu1Jogador();
if (opcao1Jogador == 0) { // Jogar
int nivel = exibirMenuNiveis1();
if (nivel == 4) {
continue; // Voltar para Menu de 1 Jogador
} else {
exibirInstrucoesSinglePlayer();
// Implementação do jogo para um jogador com bot
int alturaRaquete;
int velocidadeBola;
int obstaculoAtivo = 0;
int pontuacaoMaxima = 5; // Padrão
if (nivel == 0) { // Iniciante
chanceErro = 40;
velocidadeBola = 70;
alturaRaquete = 6;
} else if (nivel == 1) { // Intermediário
chanceErro = 30;
velocidadeBola = 70;
alturaRaquete = 4;
} else if (nivel == 2) { // Avançado
chanceErro = 20;
velocidadeBola = 60;
alturaRaquete = 4;
} else if (nivel == 3) { // Expert
chanceErro = 10;
velocidadeBola = 60;
alturaRaquete = 3;
obstaculoAtivo = 1;
obst.x = (MAXX - MINX) / 2; // Posição inicial no meio da tela
obst.y = 10; // Posição inicial y
obst.altura = 5; // Altura do obstáculo para nível Expert
obst.direcao = 1; // Começa se movendo para baixo
obst.simbolo = '#'; // Símbolo do obstáculo
}
// REQUISITO 3 - ALOCAÇÃO DINÂMICA DE MEMÓRIA
// Aloca memória para as raquetes
raquete *rptr = (raquete *) malloc(qtde_raquete * sizeof(raquete));
screenInit(1);
desenharLinhaPontilhada();
timerInit(velocidadeBola);
gettimeofday(&tempoInicio, NULL); // Obtém o tempo de início
printBola(x, y);
// Inicia as raquetes com a posição (x,y), largura, altura e símbolo
// REQUISITO 2 - PONTEIROS
iniciar_raquete(&rptr[0], 4, 10, 1, alturaRaquete, '|'); // Raquete esquerda
iniciar_raquete(&rptr[1], 76, 10, 1, alturaRaquete, '|'); // Raquete direita
// REQUISITOS 1 E 2 - STRUCTS E PONTEIROS
while (ch != 27) // Jogo ativo enquanto não teclar ESC
{
// Verifica a entrada do usuário (tecla clicada)
if (keyhit()) {
ch = readch();
// Apaga a raquete atual
apagar_raquete(&rptr[0]);
apagar_raquete(&rptr[1]);
// Movimenta a raquete esquerda com 'w' ou 'W' e 's' ou 'S'
if ((ch == 'w' || ch == 'W') && rptr[0].y > MINY + 1) {
rptr[0].y--;
}
if ((ch == 's' || ch == 'S') && rptr[0].y < MAXY - rptr[0].altura) {
rptr[0].y++;
}
// Imprime a nova posição da raquete do jogador
imprimir_raquete(&rptr[0]);
}
// Apaga a raquete do bot
apagar_raquete(&rptr[1]);
// Movimenta o bot
mover_bot(&rptr[1], y, chanceErro);
// Imprime a nova posição da raquete do bot
imprimir_raquete(&rptr[1]);
if (timerTimeOver() == 1) {
// Verifica se houve colisão com a moldura
int newX = x + incX;
int newY = y + incY;
// Verifica se a bola atingiu as paredes laterais (pontuação do adversário)
if (newX >= (MAXX - strlen("O") - 1)) {
jogador1++; // Jogador 1 pontua
newX = (MAXX - MINX) / 2; // Reinicializa a posição da bola
newY = (MAXY - MINY) / 2;
incX = -incX; // Inverte a direção da bola
} else if (newX <= MINX + 1) {
jogador2++; // Bot pontua
newX = (MAXX - MINX) / 2; // Reinicializa a posição da bola
newY = (MAXY - MINY) / 2;
incX = -incX; // Inverte a direção da bola
}
if (newY >= MAXY - 1 || newY <= MINY + 1) {
incY = -incY;
}
// Verifica se houve colisão com as raquetes
for (int i = 0; i < qtde_raquete; i++) {
if (verificar_colisao(&rptr[i], newX, newY)) {
incX = -incX;
break;
}
}
// Verifica se houve colisão com o obstáculo
if (obstaculoAtivo && verificar_colisao_obstaculo(&obst, newX, newY)) {
incX = -incX;
}
// Atualiza a posição do obstáculo se ativo
if (obstaculoAtivo) {
apagar_obstaculo(&obst);
obst.y += obst.direcao;
if (obst.y <= MINY + 1 || obst.y + obst.altura >= MAXY) {
obst.direcao = -obst.direcao;
}
imprimir_obstaculo(&obst);
}
printBola(newX, newY);
for (int i = 0; i < qtde_raquete; i++) {
imprimir_raquete(&rptr[i]);
}
exibirPontuacao();
screenUpdate();
// Verifica condições de vitória
// REQUISITOS 1 E 2 - STRUCTS E PONTEIROS
struct timeval tempoAtual;
gettimeofday(&tempoAtual, NULL);
long tempoPassado = (tempoAtual.tv_sec - tempoInicio.tv_sec);
// Um buffer chamado mensagem é declarado com um tamanho de 50 caracteres
// Dependendo da pontuação dos jogadores, a mensagem correta é formatada e armazenada em mensagem usando snprintf
if (jogador1 >= pontuacaoMaxima || jogador2 >= pontuacaoMaxima) {
char mensagem[50];
if (jogador1 > jogador2) {
snprintf(mensagem, sizeof(mensagem), "Jogador 1 ganhou!");
if (nivel == 3) { // Se for nível Expert
inserirTempo(tempoPassado / 60,
tempoPassado % 60); // Insere o tempo na lista
salvarTempos(); // Salva os tempos no arquivo
}
} else if (jogador2 > jogador1) {
snprintf(mensagem, sizeof(mensagem), "Bot ganhou!");
} else {
snprintf(mensagem, sizeof(mensagem), "Empate!");
}
exibirResultado(mensagem);
break;
}
}
}
salvar_pontuacao(jogador1,
jogador2); // Salva a pontuação ao final do jogo no arquivo pontuacao.txt (\build)
// REQUISITO 3 - ALOCAÇÃO DINÂMICA DE MEMÓRIA (liberando)
free(rptr);
}
} else if (opcao1Jogador == 1) { // Ranking
exibirRanking();
}
}
}
if (jogadores == 1) { // Se for 2 jogadores
int nivel = exibirMenuNiveis2();
exibirInstrucoes(nivel);
// Ajusta configurações baseadas no nível
int alturaRaquete = 6;
int velocidadeBola = 70;
int obstaculoAtivo = 0;
int pontuacaoMaxima = 5; // Padrão
if (nivel == 1) { // Intermediário
alturaRaquete = 4;
} else if (nivel == 2) { // Avançado
alturaRaquete = 4;
velocidadeBola = 60;
} else if (nivel == 3) { // Expert
alturaRaquete = 3;
velocidadeBola = 60;
pontuacaoMaxima = 10; // Pontuação máxima para nível Expert
obstaculoAtivo = 1;
obst.x = (MAXX - MINX) / 2; // Posição inicial no meio da tela
obst.y = 10; // Posição inicial y
obst.altura = 5;
obst.direcao = 1; // Começa se movendo para baixo
obst.simbolo = '#';
}
// REQUISITO 3 - ALOCAÇÃO DINÂMICA DE MEMÓRIA
// Aloca memória para as raquetes
raquete *rptr = (raquete *) malloc(qtde_raquete * sizeof(raquete));
screenInit(1);
desenharLinhaPontilhada();
timerInit(velocidadeBola);
gettimeofday(&tempoInicio, NULL); // Obtém o tempo de início
printBola(x, y);
// Inicia as raquetes com a posição (x,y), largura, altura e símbolo
// REQUISITO 2 - PONTEIROS
iniciar_raquete(&rptr[0], 4, 10, 1, alturaRaquete, '|'); // Raquete esquerda
iniciar_raquete(&rptr[1], 76, 10, 1, alturaRaquete, '|'); // Raquete direita
// REQUISITOS 1 E 2 - STRUCTS E PONTEIROS
while (ch != 27) // Jogo ativo enquanto não teclar ESC
{
// Verifica a entrada do usuário (tecla clicada)
if (keyhit()) {
ch = readch();
// Apaga a raquete atual
apagar_raquete(&rptr[0]);
apagar_raquete(&rptr[1]);
// Movimenta a raquete esquerda com 'w' ou 'W' e 's' ou 'S'
if ((ch == 'w' || ch == 'W') && rptr[0].y > MINY + 1) {
rptr[0].y--;
}
if ((ch == 's' || ch == 'S') && rptr[0].y < MAXY - rptr[0].altura) {
rptr[0].y++;
}
// Movimenta a raquete direita com 'o' ou 'O' e 'l' ou 'L'
if ((ch == 'o' || ch == 'O') && rptr[1].y > MINY + 1) {
rptr[1].y--;
}
if ((ch == 'l' || ch == 'L') && rptr[1].y < MAXY - rptr[1].altura) {
rptr[1].y++;
}
// Imprime a nova posição da raquete