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
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
#include <signal.h> /* handling ctrl-c */
#include <sys/ioctl.h> /* terminal size */
#include <string.h> /* argument parsing */
#include "vector.h"
#include "snake.h"
#include "conio.h"
#include "colors.h"
#define UNUSED(x) (void)(x)
/*** GLOBAL VARIABLES ***/
volatile sig_atomic_t INT_CTRL_C = 0; /* flag for ctrl-c interrupt */
int SCORE = 0;
int boardSize = 15;
int updateInterval = 300000000L;
vectorp_t snakePositions;
vector_t foodPos;
vector_t lastMoveDir;
void interrupt_handler(int sig); /* passed into signal(3) to handle ctrl-c interrupts */
/* unsafe functions like printf cannot be called in async interrupt handler */
void interrupt_handler(int sig) {
UNUSED(sig);
INT_CTRL_C = 1;
}
int main(int argc, char **argv) {
int i;
struct winsize win;
int width;
int height;
int smallestAxis;
volatile int *lastInput;
int *cancellationToken;
threadArg_t threadArg;
pthread_t listenerID;
/* parsing arguments */
for (i = 1; i < argc; i ++) {
if (strcmp("--version", argv[i]) == 0) {
printf("snake3, version 1.0\n");
printf("Copyright 2023 Kai Stevenson\n");
printf("This software was licensed under the MIT license;\n");
printf("for more information, see the license file.\n");
return 0;
} else if (strcmp("--help", argv[i]) == 0) {
printf("usage: snake3 [--version] [--help]\n");
return 0;
} else {
printf("usage: snake3 [--version] [--help]\n");
return 1;
}
}
/* get terminal size */
ioctl(fileno(stdout), TIOCGWINSZ, &win);
width = (int)(win.ws_col);
height = (int)(win.ws_row);
/* multiplied by 2 to account for the fact that the board is twice as wide as high */
smallestAxis = width / 2 < height ? width / 2 : height;
boardSize = smallestAxis < boardSize ? smallestAxis : boardSize;
/* hide cursor */
printf("\033[?25l");
/* make a new thread handling interrupts */
signal(SIGINT, interrupt_handler);
/* init values */
snakePositions = init_vectorp(malloc(5 * sizeof(vector_t)), 5);
snakePositions.vectors[0] = init_vector(5, 5);
snakePositions.vectors[1] = init_vector(5, 4);
snakePositions.vectors[2] = init_vector(5, 3);
snakePositions.vectors[3] = init_vector(4, 3);
snakePositions.vectors[4] = init_vector(3, 3);
foodPos = init_vector(7, 9);
lastMoveDir = init_vector(0, 1);
srand(time(NULL));
/* clear the screen so as to prevent artifacting */
printf("\033[2J");
/* prepare the pointers which will be used to communicate with the input getting thread */
lastInput = calloc(1, sizeof(int));
cancellationToken = calloc(1, sizeof(int));
/* and the wrapper struct */
threadArg.returnV = (void*)lastInput;
threadArg.cancellationToken = cancellationToken;
/* create listener thread */
pthread_create(&listenerID, NULL, get_dir_loop, &threadArg);
/* main game logic loop */
while(1) {
struct timespec time;
int ateFood = 0;
int died = 0;
vector_t dir;
vectorp_t newSnakePositions;
/* handle ctrl-c interrupt */
if (INT_CTRL_C) {
/* unhide cursor */
printf("\033[?25h");
/* kill the listener thread */
*cancellationToken = 1;
printf("Your score was %d. Press any key to exit\n", SCORE);
pthread_join(listenerID, NULL);
free(cancellationToken);
free((int*)lastInput);
return 0;
}
/* first, draw the current state of the board */
draw_board();
/* handle player input;
* wait for the specified interval */
time.tv_sec = 0;
time.tv_nsec = updateInterval;
nanosleep(&time, NULL);
/* read the most recent value emitted by the listener */
dir = parse_dir(*(char*)lastInput);
/* if the player inputted a valid direction, use it. otherwise, use his last valid input */
if((dir.mx != 0 || dir.my != 0) && !(dir.mx == 1 && lastMoveDir.mx == -1) && !(dir.mx == -1 && lastMoveDir.mx == 1) && !(dir.my == 1 && lastMoveDir.my == -1) && !(dir.my == -1 && lastMoveDir.my == 1)) {
lastMoveDir = dir;
}
else {
}
/* check if snake landed on the food */
if((snakePositions.vectors[0].mx + lastMoveDir.mx == foodPos.mx) && (snakePositions.vectors[0].my + lastMoveDir.my == foodPos.my)) {
ateFood = 1;
SCORE = SCORE + 1;
if (updateInterval > 50000000) {
updateInterval -= 20000000;
}
/* move the food */
while(1) {
int overlap = 0;
foodPos = init_vector(1 + (rand() % (boardSize - 2)), 1 + (rand() % (boardSize - 2)));
/* if food overlaps snake, try again */
for(i = 0; i < snakePositions.length; i++) {
if((snakePositions.vectors[i].mx == foodPos.mx) && (snakePositions.vectors[i].my == foodPos.my)) {
overlap = 1;
}
}
if(!overlap) {
break;
}
}
}
/* move the snake */
newSnakePositions = move_snake(lastMoveDir, ateFood);
free(snakePositions.vectors);
snakePositions = newSnakePositions;
/* check if snake landed on self */
for(i = 1; i < snakePositions.length; i++) {
if(snakePositions.vectors[0].mx == snakePositions.vectors[i].mx && snakePositions.vectors[0].my == snakePositions.vectors[i].my) {
/* game over */
died = 1;
}
}
if(died) {
break;
}
}
/* clear the last getch call from the listener */
*cancellationToken = 1;
printf("\n%sYou died. Score: %d. Press any key to exit%s\n", RED, SCORE, COLOR_RESET);
printf("\033[?25h");
pthread_join(listenerID, NULL);
free(cancellationToken);
free((int*)lastInput);
return 0;
}
void* get_dir_loop(void* threadArg) {
while(!*(int*)((threadArg_t*)threadArg)->cancellationToken) {
*(char*)((threadArg_t*)threadArg)->returnV = getch();
}
return NULL;
}
/* parses WASD or HJKL, returns the necessary deltas to move within a 2d array */
vector_t parse_dir(char cDir) {
if(cDir == 'w' || cDir == 'k') {
return init_vector(0, -1);
}
else if(cDir == 'd' || cDir == 'l') {
return init_vector(1, 0);
}
else if(cDir == 's' || cDir == 'j') {
return init_vector(0, 1);
}
else if(cDir == 'a' || cDir == 'h') {
return init_vector(-1, 0);
}
else {
return init_vector(0, 0);
}
}
vectorp_t move_snake(vector_t dir, int lengthen) {
int i;
int newLength = snakePositions.length + (lengthen ? 1 : 0);
vector_t* newSnakePositions = malloc((newLength * sizeof(vector_t)));
/* wrap around edges */
int nhx = snakePositions.vectors[0].mx + dir.mx;
int nhy = snakePositions.vectors[0].my + dir.my;
nhx = nhx < 0 ? boardSize - 1 : nhx >= boardSize ? 0 : nhx;
nhy = nhy < 0 ? boardSize - 1 : nhy >= boardSize ? 0 : nhy;
newSnakePositions[0] = init_vector(nhx, nhy);
for(i = 1; i < newLength; i++) {
newSnakePositions[i] = snakePositions.vectors[i - 1];
}
return init_vectorp(newSnakePositions, newLength);
}
void draw_board() {
int r;
int c;
int i;
/* move the cursor to the top left corner of the screen */
printf("\033[0;0H");
/* iterate through and write the board */
for(r = 0; r < boardSize; r++) {
for(c = 0; c < boardSize; c++) {
/* determine the contents of the board position */
int type = 0;
for(i = 0; i < snakePositions.length; i++) {
if(snakePositions.vectors[i].mx == c && snakePositions.vectors[i].my == r) {
type = i ? 2 : 1;
break;
}
else {
type = 0;
}
}
if(foodPos.mx == c && foodPos.my == r) {
type = 3;
}
/* append the appropriate value */
if(type == 0) {
/* empty square */
printf("` ");
}
else if(type == 1) {
/* snake head */
printf("%s@ %s", GRN, COLOR_RESET);
}
else if(type == 2) {
/* snake body */
printf("%s* %s", GRN, COLOR_RESET);
}
else if(type == 3) {
/* food */
printf("%sF %s", MAG, COLOR_RESET);
}
}
printf("\n");
}
}
|