-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPS_2025.c
106 lines (98 loc) · 2.42 KB
/
RPS_2025.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
/**
_int8_t 1 byte (8 bits)
_int32_t 4 bytes (32bits)
_int64_t 8 bytes (64 bits)
__int128_t 16 bytes (128 bits)
*/
#define _GNU_SOURCE
#include "stdlib.h"
#include "stdint.h"
#include "stdbool.h" // True and False defines are the opposite way in this header for somereason?
#include "stdio.h"
#include "string.h"
#include "unistd.h"
#include "time.h"
// todo: avoid using system() in screenclearing
#ifdef _WIN32
#define clear() system("cls");
#else
#define clear() system("clear");
#endif
typedef struct{
short loses;
short wins;
short ties;
char input[10];
} player;
char *opt[] = {"rock","paper","scissors"};
char rnd[15];
void* p_alloc(player** pl,bool cond){
short a = 0;
if(cond == 1){
for(short a=0;a<2;a++) {
pl[a] = (player*)malloc(sizeof(player));
if(pl[a] == NULL){
perror("Memory allocation failed");
exit(EXIT_FAILURE);
}
memset(pl[a],0,sizeof(player));
}
}
else{
for(short i=0;i<2;i++){
free(pl[i]);
}
}
}
int cmp(char* a,char* b){
return strcmp(a,b) == 0;
}
char* logic(char* p,char* ai,player** pl){
if(cmp(p,ai)){
pl[0]->ties++;
return("Tie!");
}
else if((cmp(p,opt[0]) && cmp(ai,opt[1]))||
(cmp(p,opt[1]) && cmp(ai,opt[2]))||
(cmp(p,opt[2]) && cmp(ai,opt[0]))){
pl[0]->loses++;
pl[1]->wins++;
return("AI Win!");
}
else if((cmp(p,opt[1]) && cmp(ai,opt[0]))||
(cmp(p,opt[2]) && cmp(ai,opt[1]))||
(cmp(p,opt[0]) && cmp(ai,opt[2]))){
pl[0]->wins++;
pl[1]->loses++;
return("Player Win!");
}
return("Input Error");
}
void scores(player** pl){
clear();
printf("Returned [%s]\
\n\nScores(w/l):\nAi:[%d/%d]\
\nPlayer:[%d/%d]\nTies[%d]\n",rnd,pl[0]->wins,pl[0]->loses,pl[1]->wins,pl[1]->loses,pl[0]->ties);
}
short main(void){
player* pl[2];
srand(UINT32_MAX &~! time(NULL)); // Just some random values for seed
p_alloc(pl,true);
for(;;){
clear();
short abc = rand() % 3;
fprintf(stdout,"[RPS_2025]\nEnter\n\u279c ");
strcpy(pl[0]->input,opt[abc]);
scanf("%s",pl[1]->input);
if(cmp("exit",pl[1]->input)) break;
char* ret = logic(pl[0]->input,pl[1]->input,pl);
strcpy(rnd,ret);
scores(pl);
memset(&rnd,0,sizeof(rnd));
sleep(2);
}
scores(pl);
p_alloc(pl,false);
puts("\nExited...");
return(0);
}