-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.c
1377 lines (1234 loc) · 31.3 KB
/
snake.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
#include <ncurses.h>
#include <stdbool.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
#include <time.h>
#include <pwd.h>
#define clean_exit(code) \
endwin(); \
exit(code);
#define in_range(x, min, max) (x >= min) && (x <= max)
// Constants important for gameplay
#define STARTING_SPEED 150
#define STARTING_LENGTH 5
#define POINTS_COUNTER_VALUE 1000
#define SUPERFOOD_COUNTER_VALUE 10
#define MIN_POINTS 100
#define STD_MAX_SPEED 50
#define GROW_FACTOR 10
#define SUPERFOOD_GROW_FACTOR 15
#define SPEED_FACTOR 2
#define GRACE_FRAMES 3
// Misc. constants
#define VERSION "0.58.0 (Beta)"
#define CC_END_YEAR "2024"
#define STD_FILE_NAME ".csnake"
#define FILE_LENGTH 20 // 19 characters are needed to display the max number for long long
typedef enum Direction
{
// No direction, standing still
HOLD,
// Negative y direction
UP,
// Positive y direction
DOWN,
// Positive x direction
RIGHT,
// Negative x direction
LEFT
} Direction;
typedef enum UserInteraction
{
// No interaction by the user
NONE,
// Request to pause the game
PAUSE,
// Request to restart the round
RESTART,
// Request to quit the program
QUIT,
// Direction button pressed
DIRECTION
} UserInteraction;
typedef enum UpdateResult
{
// Player was saved by a grace frame
GRACE,
// The round ends in a game over
GAME_OVER,
// The round may continue
CONTINUE
} UpdateResult;
typedef struct Coord
{
int x;
int y;
} Coord;
typedef struct LinkedCell
{
// Coordinate for the cell
Coord coord;
// The previous cell in the linked list
// `this->prev->next` should point to `this`
struct LinkedCell *prev;
// The next cell in the linked list
// `this->next->prev` should point to `this`
struct LinkedCell *next;
} LinkedCell;
typedef struct GameState
{
// Current score
long long points;
// Current direction
Direction direction;
// Previous direction from the last update
Direction old_direction;
// Current speed
int speed;
// Current position of the snake head
Coord pos;
// Position of the snake head from the last update
Coord old_pos;
// Current "bonus" points that would be added if food was hit
int points_counter;
// Current length of the snake
int length;
// Current amount of cells the snake still needs to grow
int growing;
// Amount of available update cycles that
int grace_frames;
// Amount of update cycles needed until the food becomes a super food
int superfood_counter;
// Current position of the food
Coord food_coord;
// Head of the snake
LinkedCell *head;
// Last cell of the snake
LinkedCell *last;
// Points to all walls as a single linked list
LinkedCell *wall;
} GameState;
typedef struct GameConfiguration
{
// Path to the savefile
char *save_file_path;
// Maximum possible speed
unsigned int max_speed;
// Highscore either read from savefile or updated from last game round
long long highscore;
// Specifies whether outer walls should be open
bool open_bounds_flag;
// Specifies whether menus should be skipped
bool skip_flag;
// Specifies whether a wall pattern (specified by `wall_pattern`) should be used
bool wall_flag;
// Specifies whether the savefile should be ignored
bool ignore_flag;
// Specifies whether the savefile should be removed
bool remove_flag;
// Selects a predefined pattern (if `wall_flag` is `true`)
short wall_pattern;
// Key-code used for direction control
int up_key, down_key, left_key, right_key;
// Colorpair index for the color to print the snake in
int snake_color;
} GameConfiguration;
// Global configuration (must be initialized with `init_configuration` before use)
static GameConfiguration *config;
// Logo generated on http://www.network-science.de/ascii/
// Used font: nancyj
static const char *LOGO[] = {
" a88888b. .d88888b dP ",
"d8' `88 88. '' 88 ",
"88 `Y88888b. 88d888b. .d8888b. 88 .dP .d8888b.",
"88 88888888 `8b 88' `88 88' `88 88888' 88ooood8",
"Y8. .88 d8' .8P 88 88 88. .88 88 `8b. 88. ...",
" Y88888P' Y88888P dP dP `88888P8 dP `YP `88888P'"};
char *init_file_path(void)
{
// Get "HOME" environment variable
char *home_dir = getenv("HOME");
if (home_dir == NULL)
{
return NULL;
}
// Allocate space for the home path, the filename, '/' and the zero byte
char *file_path = malloc(strlen(home_dir) + strlen(STD_FILE_NAME) + 2);
sprintf(file_path, "%s/%s", home_dir, STD_FILE_NAME);
return file_path;
}
void init_configuration(void)
{
config = malloc(sizeof(GameConfiguration));
config->save_file_path = init_file_path();
config->max_speed = STD_MAX_SPEED;
config->highscore = 0;
config->ignore_flag = false;
config->remove_flag = false;
config->open_bounds_flag = false;
config->skip_flag = false;
config->wall_flag = false;
config->wall_pattern = 1;
config->snake_color = 2;
config->up_key = KEY_UP;
config->down_key = KEY_DOWN;
config->left_key = KEY_LEFT;
config->right_key = KEY_RIGHT;
}
// Write a score to the score file, reading the file path from the global config
// Returns `false` on error, `true` otherwise
bool write_score_file(long long score)
{
// If we ignore the score file we return
// If the file path was not initialized we also return
if (config->ignore_flag || config->save_file_path == NULL)
{
return true;
}
// Memory for the string representation of the score
char score_str[FILE_LENGTH];
// Write highscore into memory
sprintf(score_str, "%.*lld", FILE_LENGTH - 1, score);
// Open file
FILE *file = fopen(config->save_file_path, "w");
if (file == NULL)
{
return false;
}
// Write score to file and close it
fputs(score_str, file);
fclose(file);
return true;
}
// Read the highscore from the score file, reading the file path from the global config
// Returns `false` on error, `true` otherwise
bool read_score_file(void)
{
// If we ignore the score file we return
if (config->ignore_flag)
return true;
// If the file path was not initialized we also return
if (config->save_file_path == NULL)
return true;
// File doesn't exist
if (access(config->save_file_path, F_OK) != 0)
{
config->highscore = 0;
return true;
}
// Memory for file contents
char content[FILE_LENGTH];
// Open file
FILE *file = fopen(config->save_file_path, "r");
if (file == NULL)
{
config->highscore = 0;
return false;
}
// Read file contents and interpret the score
if (fgets(content, FILE_LENGTH, file) == NULL)
config->highscore = 0;
else
config->highscore = atoll(content);
// Close the file
fclose(file);
return true;
}
inline Coord coord(int x, int y)
{
Coord coord;
coord.x = x;
coord.y = y;
return coord;
}
inline Coord get_max_coords(WINDOW *win)
{
return coord(getmaxx(win), getmaxy(win));
}
inline size_t half_len(const char string[])
{
return strlen(string) / 2;
}
void print_centered(WINDOW *window, int y, const char string[])
{
int max_x = getmaxx(window);
int x = (max_x / 2) - half_len(string);
mvwaddstr(window, y, x, string);
}
void print_offset(WINDOW *window, int x_offset, int y, const char string[])
{
int max_x = getmaxx(window);
int x = (max_x / 2) - half_len(string);
mvwaddstr(window, y, x + x_offset, string);
}
void print_status(WINDOW *status_win, GameState *state)
{
char txt_buf[50];
int max_x = getmaxx(status_win);
// Set normal
wattrset(status_win, A_BOLD);
// Deleting rows
wmove(status_win, 1, 0);
wclrtoeol(status_win);
wmove(status_win, 2, 0);
wclrtoeol(status_win);
// Redrawing the box
box(status_win, 0, 0);
// Set bold font
wattrset(status_win, A_BOLD);
if (max_x > 50)
{
// Print score
sprintf(txt_buf, "Score: %lld", state->points);
mvwaddstr(status_win, 1, (max_x / 3) - half_len(txt_buf), txt_buf);
// Print highscore
if (config->highscore != 0)
{
sprintf(txt_buf, "Highscore: %lld", config->highscore);
}
else
{
sprintf(txt_buf, "No highscore set");
}
mvwaddstr(status_win, 1, (2 * max_x / 3) - half_len(txt_buf), txt_buf);
// Print points counter
sprintf(txt_buf, "Bonus: %d", state->points_counter);
mvwaddstr(status_win, 2, (max_x / 3) - half_len(txt_buf), txt_buf);
// Print length
sprintf(txt_buf, "Length: %d", state->length);
mvwaddstr(status_win, 2, (2 * max_x / 3) - half_len(txt_buf), txt_buf);
}
else
{
// Print score
sprintf(txt_buf, "Score: %lld", state->points);
mvwaddstr(status_win, 1, (max_x / 2) - half_len(txt_buf), txt_buf);
// Print points counter
sprintf(txt_buf, "Bonus: %d", state->points_counter);
mvwaddstr(status_win, 2, (max_x / 2) - half_len(txt_buf), txt_buf);
}
// Refresh window
wrefresh(status_win);
}
void pause_game(WINDOW *status_win, const char string[], const int seconds)
{
// Clear status window
wclear(status_win);
// Redrawing the box
box(status_win, 0, 0);
// Print the message
print_centered(status_win, 1, string);
// Refresh the window
wrefresh(status_win);
// Pausing for 0 seconds means waiting for input
if (seconds == 0)
{
timeout(-1); // getch is in blocking mode
getch();
}
else
{
sleep(seconds);
flushinp(); // Flush typeahead during sleep
}
// Clear window
wclear(status_win);
// Redrawing the box
wattrset(status_win, A_BOLD);
box(status_win, 0, 0);
// Refreshing the window
wrefresh(status_win);
}
bool is_on_obstacle(LinkedCell *test_cell, const int x, const int y)
{
// Not a valid cell to test
if (test_cell == NULL)
return false;
do
{
// A cell has the same coordinates as the point to check
if ((test_cell->coord.x == x) && (test_cell->coord.y == y))
return true;
// Check next cell
test_cell = test_cell->prev;
} while (test_cell != NULL);
// No cell found
return false;
}
void new_random_coordinates(
LinkedCell *snake,
LinkedCell *wall,
Coord *coord,
Coord max_coords)
{
int x, y;
do
{
// Generate random coordinates
x = rand() % max_coords.x;
y = rand() % max_coords.y;
// Check if the coordinates are on the snake or wall
// If so, generate new values
} while (is_on_obstacle(snake, x, y) || is_on_obstacle(wall, x, y));
// Save coordinates
coord->x = x;
coord->y = y;
}
LinkedCell *create_wall(int start, int end, int constant, Direction dir, LinkedCell *last_cell)
{
int i;
LinkedCell *new_wall, *wall = malloc(sizeof(LinkedCell));
// Based on the direction set either x or y to a constant value
if ((dir == LEFT) || (dir == RIGHT))
{
wall->coord = coord(start, constant);
}
else
{
wall->coord = coord(constant, start);
}
// Connect the new wall to an old one
// If last_cell is NULL the list ends here
wall->prev = last_cell;
// Based on the direction build a wall from start to end
// and put it infrnt of the old list
switch (dir)
{
case UP:
for (i = start - 1; i > end; i--)
{
new_wall = malloc(sizeof(LinkedCell));
new_wall->coord = coord(constant, i);
new_wall->prev = wall;
wall = new_wall;
}
break;
case DOWN:
for (i = start + 1; i < end; i++)
{
new_wall = malloc(sizeof(LinkedCell));
new_wall->coord = coord(constant, i);
new_wall->prev = wall;
wall = new_wall;
}
break;
case LEFT:
for (i = start - 1; i > end; i--)
{
new_wall = malloc(sizeof(LinkedCell));
new_wall->coord = coord(i, constant);
new_wall->prev = wall;
wall = new_wall;
}
break;
case RIGHT:
for (i = start + 1; i < end; i++)
{
new_wall = malloc(sizeof(LinkedCell));
new_wall->coord = coord(i, constant);
new_wall->prev = wall;
wall = new_wall;
}
break;
case HOLD:
break;
}
return wall;
}
void free_linked_list(LinkedCell *cell)
{
// Nothing valid to free
if (cell == NULL)
return;
// Free list
LinkedCell *tmp_cell;
do
{
tmp_cell = cell->prev;
free(cell);
cell = tmp_cell;
} while (cell != NULL);
}
int snake_char_from_direction(Direction direction, Direction old_direction)
{
if (direction == UP)
{
if (old_direction == LEFT)
{
return ACS_LLCORNER;
}
else if (old_direction == RIGHT)
{
return ACS_LRCORNER;
}
else
{
return ACS_VLINE;
}
}
else if (direction == DOWN)
{
if (old_direction == LEFT)
{
return ACS_ULCORNER;
}
else if (old_direction == RIGHT)
{
return ACS_URCORNER;
}
else
{
return ACS_VLINE;
}
}
else if (direction == LEFT)
{
if (old_direction == UP)
{
return ACS_URCORNER;
}
else if (old_direction == DOWN)
{
return ACS_LRCORNER;
}
else
{
return ACS_HLINE;
}
}
else if (direction == RIGHT)
{
if (old_direction == UP)
{
return ACS_ULCORNER;
}
else if (old_direction == DOWN)
{
return ACS_LLCORNER;
}
else
{
return ACS_HLINE;
}
}
return 0;
}
bool update_position(GameState *state, Coord max_coord)
{
switch (state->direction)
{
case UP:
state->pos.y--;
break;
case DOWN:
state->pos.y++;
break;
case LEFT:
state->pos.x--;
break;
case RIGHT:
state->pos.x++;
break;
case HOLD:
return false;
default:
break;
}
if (config->open_bounds_flag)
{
// If you hit the outer bounds you'll end up on the other side
if (state->pos.y < 0)
{
state->pos.y = max_coord.y - 1;
}
else if (state->pos.y >= max_coord.y)
{
state->pos.y = 0;
}
else if (state->pos.x < 0)
{
state->pos.x = max_coord.x - 1;
}
else if (state->pos.x >= max_coord.x)
{
state->pos.x = 0;
}
return false;
}
else
{
return (state->pos.y < 0) || (state->pos.x < 0) || (state->pos.y >= max_coord.y) || (state->pos.x >= max_coord.x);
}
}
UserInteraction handle_input(GameState *state)
{
// Set timeout
timeout(state->speed);
// Getting input
int key = getch();
// Save old direction
state->old_direction = state->direction;
// Changing direction according to the input
if (key == config->left_key)
{
if (state->direction != RIGHT)
state->direction = LEFT;
return DIRECTION;
}
else if (key == config->right_key)
{
if (state->direction != LEFT)
state->direction = RIGHT;
return DIRECTION;
}
else if (key == config->up_key)
{
if (state->direction != DOWN)
state->direction = UP;
return DIRECTION;
}
else if (key == config->down_key)
{
if (state->direction != UP)
state->direction = DOWN;
return DIRECTION;
}
else if (key == '\n') // Enter-key
{
return PAUSE;
}
else if (key == 'R')
{
return RESTART;
}
else if (key == 'Q')
{
return QUIT;
}
return NONE;
}
void paint_objects(WINDOW *game_win, GameState *state)
{
// Paint food
wattrset(game_win, COLOR_PAIR((state->superfood_counter == 0) ? 4 : 3) | A_BOLD);
mvwaddch(game_win, state->food_coord.y, state->food_coord.x, '0');
// Paint the snake in the specified color
wattrset(game_win, COLOR_PAIR(config->snake_color) | A_BOLD);
int snake_char = snake_char_from_direction(state->direction, state->old_direction);
if (snake_char)
{
mvwaddch(game_win, state->old_pos.y, state->old_pos.x, snake_char);
}
// Draw head
mvwaddch(game_win, state->pos.y, state->pos.x, 'X');
}
UpdateResult update_state(WINDOW *game_win, WINDOW *status_win, GameState *state)
{
// Init max coordinates in relation to game window
Coord max_coord = get_max_coords(game_win);
// Save old coordinates
state->old_pos = state->pos;
// Update position and check if outer bounds were hit
bool wall_hit = update_position(state, max_coord);
// The snake hits something
if (wall_hit ||
is_on_obstacle(state->head, state->pos.x, state->pos.y) ||
is_on_obstacle(state->wall, state->pos.x, state->pos.y))
{
if (state->grace_frames == 0)
{
// No grace frames left, game over
return GAME_OVER;
}
else
{
// We still have grace frames so we reset the coordinate and
// let the player change the direction
state->grace_frames--;
state->pos = state->old_pos;
return GRACE;
}
}
// Reset grace frames
state->grace_frames = GRACE_FRAMES;
// Add new head to snake
LinkedCell *new_cell = malloc(sizeof(LinkedCell));
new_cell->coord = state->pos;
new_cell->prev = state->head;
state->head->next = new_cell;
state->head = new_cell;
// Head hits the food
if ((state->pos.x == state->food_coord.x) &&
(state->pos.y == state->food_coord.y))
{
// Let the snake grow and change the speed
state->growing +=
state->superfood_counter == 0 ? SUPERFOOD_GROW_FACTOR : GROW_FACTOR;
if (state->speed > config->max_speed)
{
state->speed -= SPEED_FACTOR;
}
state->points +=
(state->points_counter +
state->length + (STARTING_SPEED - state->speed) * 5) *
(state->superfood_counter == 0 ? 5 : 1);
state->points_counter = POINTS_COUNTER_VALUE;
state->superfood_counter =
(state->superfood_counter == 0) ? SUPERFOOD_COUNTER_VALUE : state->superfood_counter - 1;
new_random_coordinates(state->head, state->wall, &state->food_coord, max_coord);
}
// If the snake is not growing...
if (state->growing == 0)
{
// Clear last cell
wattrset(game_win, A_NORMAL);
mvwaddch(game_win, state->last->coord.y, state->last->coord.x, ' ');
// ...free the memory for this cell
LinkedCell *new_last;
state->last->next->prev = NULL;
new_last = state->last->next;
free(state->last);
state->last = new_last;
}
else
{
// If the snake is growing and moving, just decrement 'growing'...
state->growing--;
// ...and increment 'length'
state->length++;
}
// Decrement the points that will be added
if (state->points_counter > MIN_POINTS)
{
state->points_counter--;
}
return CONTINUE;
}
LinkedCell *init_wall(Coord max_coord)
{
int max_x = max_coord.x;
int max_y = max_coord.y;
// Creating walls (all walls are referenced by one pointer)
LinkedCell *wall = NULL;
if (config->wall_flag)
{
switch (config->wall_pattern)
{
case 1:
wall = create_wall(0, max_y / 4, max_x / 2, DOWN, NULL);
wall = create_wall(max_y, 3 * max_y / 4, max_x / 2, UP, wall);
wall = create_wall(0, max_x / 4, max_y / 2, RIGHT, wall);
wall = create_wall(max_x, 3 * max_x / 4, max_y / 2, LEFT, wall);
break;
case 2:
wall = create_wall(max_y / 4, 3 * max_y / 4, max_x / 4, DOWN, NULL);
wall = create_wall(max_y / 4, 3 * max_y / 4, 3 * max_x / 4, DOWN, wall);
break;
case 3:
wall = create_wall(max_x / 4, 3 * max_x / 4, max_y / 4, RIGHT, NULL);
wall = create_wall(max_x / 4, 3 * max_x / 4, 3 * max_y / 4, RIGHT, wall);
break;
case 4:
wall = create_wall(max_y / 2 + 2, 3 * max_y / 4, max_x / 4, DOWN, NULL);
wall = create_wall(max_y / 4, max_y / 2 - 1, max_x / 4, DOWN, wall);
wall = create_wall(max_y / 2 + 2, 3 * max_y / 4, 3 * max_x / 4, DOWN, wall);
wall = create_wall(max_y / 4, max_y / 2 - 1, 3 * max_x / 4, DOWN, wall);
wall = create_wall(max_x / 4, max_x / 2 - 1, max_y / 4, RIGHT, wall);
wall = create_wall(max_x / 4, max_x / 2 - 1, 3 * max_y / 4, RIGHT, wall);
wall = create_wall(max_x / 2 + 2, 3 * max_x / 4, max_y / 4, RIGHT, wall);
wall = create_wall(max_x / 2 + 2, 3 * max_x / 4 + 1, 3 * max_y / 4, RIGHT, wall);
break;
case 5:
wall = create_wall(0, max_y / 4, max_x / 4, DOWN, NULL);
wall = create_wall(0, max_y / 4, 3 * max_x / 4, DOWN, wall);
wall = create_wall(0, max_y / 4, max_x / 2, DOWN, wall);
wall = create_wall(max_y, 3 * max_y / 4, max_x / 4, UP, wall);
wall = create_wall(max_y, 3 * max_y / 4, 3 * max_x / 4, UP, wall);
wall = create_wall(max_y, 3 * max_y / 4, max_x / 2, UP, wall);
wall = create_wall(0, max_x / 4, max_y / 2, RIGHT, wall);
wall = create_wall(max_x, 3 * max_x / 4, max_y / 2, LEFT, wall);
break;
default:
fprintf(stderr, "Illegal wall pattern: %d\n", config->wall_pattern);
abort();
}
}
return wall;
}
GameState init_state(Coord max_coord)
{
// Init gamestate
GameState state;
state.points = 0;
state.speed = STARTING_SPEED;
state.pos.x = max_coord.x / 2;
state.pos.y = max_coord.y / 2;
state.old_pos = state.pos;
state.points_counter = POINTS_COUNTER_VALUE;
state.length = 1;
state.growing = STARTING_LENGTH - 1;
state.grace_frames = GRACE_FRAMES;
state.direction = HOLD;
state.old_direction = HOLD;
state.superfood_counter = SUPERFOOD_COUNTER_VALUE;
state.food_coord.x = 0;
state.food_coord.y = 0;
// Create first cell for the snake
LinkedCell *head = malloc(sizeof(LinkedCell));
head->coord = state.pos;
head->prev = NULL;
head->next = NULL;
state.head = head;
state.last = head;
// Init wall
state.wall = init_wall(max_coord);
return state;
}
// Plays one round of the game. Can be interrupted by the user.
// Returns `true` if a reset was requested, thus another round
// should start without showing the menu.
bool play_round(void)
{
// Init max coordinates
int global_max_x = getmaxx(stdscr);
int global_max_y = getmaxy(stdscr);
// Clear screen
clear();
refresh();
// Create subwindows
WINDOW *game_win = subwin(stdscr, global_max_y - 4, global_max_x, 0, 0);
WINDOW *status_win = subwin(stdscr, 4, global_max_x, global_max_y - 4, 0);
// Init max coordinates in relation to game window
Coord max_coord = get_max_coords(game_win);
// Init gamestate
GameState state = init_state(max_coord);
bool did_loose = false;
bool should_repeat = false;
// Set initial timeout
timeout(state.speed); // The timeout for getch() makes up the game speed
// Print status window since points have been set to 0
print_status(status_win, &state);
if (state.wall != NULL)
{
// Paint the wall
// It should never be overwritten, since it will not be redrawn
LinkedCell *tmp_cell1, *tmp_cell2;
tmp_cell2 = state.wall;
wattrset(game_win, COLOR_PAIR(5) | A_BOLD);
do
{
tmp_cell1 = tmp_cell2;
mvwaddch(game_win, tmp_cell1->coord.y, tmp_cell1->coord.x, ACS_CKBOARD);
tmp_cell2 = tmp_cell1->prev;
} while (tmp_cell2 != NULL);
}
// Init food coordinates
new_random_coordinates(state.head, state.wall, &state.food_coord, max_coord);
// Game-Loop
while (true)
{
// Paint snake head and food
paint_objects(game_win, &state);
// Update status window
print_status(status_win, &state);
// Refresh game window
wrefresh(game_win);
// Get input
UserInteraction interact = handle_input(&state);
if (interact == PAUSE)
{
wattrset(status_win, COLOR_PAIR(4) | A_BOLD);
pause_game(status_win, "--- PAUSED ---", 0);
}
else if (interact == RESTART)
{
should_repeat = true;
break;
}
else if (interact == QUIT)
{
clean_exit(0);
}
// No movement, so no update
if (state.direction == HOLD)
{
continue;
}
// Update game state
UpdateResult res = update_state(game_win, status_win, &state);
if (res == GAME_OVER)
{
did_loose = true;
break;
}
}
// Set a new highscore
if (state.points > config->highscore)
{
// Remember the highscore
config->highscore = state.points;
// Write highscore to local file
if (write_score_file(state.points))
{
wattrset(status_win, COLOR_PAIR(2) | A_BOLD);
pause_game(status_win, "--- NEW HIGHSCORE ---", 2);
}
else
{
endwin();
fprintf(stderr, "Unable to write savefile at %s\n", config->save_file_path);
fprintf(stderr, "Final highscore was: %lld\n", state.points);
exit(1);
}
}
if (did_loose)
{
wattrset(status_win, COLOR_PAIR(3) | A_BOLD);
pause_game(status_win, "--- GAME OVER ---", 2);
}
// Freeing memory used for the snake
free_linked_list(state.head);