jag

snake_c

public

Small snake game in C

Star0
Watch0
c59c050ea12411934c5fbe11f67979c7a65dc9cf
2
ssh://git@git.jaglekon.de:30/jag/snake_c.git
snake.cC557 lines13.0 KB
1
#include "snake.h"
2
3
4
int main(int argc, char *args[]) {
5
6
  /* command argument handling */
7
8
  if (argc > 1) {
9
    if (argc > 2) {
10
      printf("Too many parameters\n");
11
      goto help_info;
12
    }
13
14
    if (!strcmp(args[1], "-h") || !strcmp(args[1], "--help")) {
15
16
      printf("This is a small TUI snake game.\n\n");
17
      printf("Controls: Arrow keys/WASD to control the snake.\n");
18
      printf("          P/Enter to pause.\n");
19
      printf("          Q to quit.\n");
20
21
      return 0;
22
    }
23
24
    printf("Argument \"%s\" not recognized\n", args[1]);
25
26
  help_info:
27
    printf("Try \"-h\" or \"--help\" for more information\n");
28
    return 1;
29
  }
30
31
  
32
  /* game settings */
33
34
  speed game_speed = AVERAGE;
35
  selected game_size = {WIDTH, HEIGHT};
36
37
  score leader_board[SCORE_NUMBER] = {};
38
  uint16_t score = 0;
39
40
  /* Handling Files to store settings & highscores */
41
42
  char *env;
43
  char *folder_path;
44
45
  if ((env = getenv("XDG_DATA_HOME")) == NULL) {
46
    if ((env = getenv("HOME")) == NULL) {
47
      printf("are you ok?\n");
48
      return 1;
49
    }
50
    
51
    uint8_t error = 0;
52
53
    char local[] = "/.local";
54
    char share[] = "/share";
55
56
    folder_path = malloc(strlen(env) + strlen(local) + 
57
      strlen(share) + strlen(SETTINGS_FOLDER) + 2);
58
59
    sprintf(folder_path, "%s%s", env, local);
60
    error += make_folder(folder_path);
61
62
    strcat(folder_path, share);
63
    error += make_folder(folder_path);
64
65
    if (error <= 1) {
66
      printf("Failed to create Folder");
67
      return 1;
68
    } 
69
  } else {
70
    folder_path = malloc(strlen(env) + strlen(SETTINGS_FOLDER) + 2);
71
    sprintf(folder_path, "%s", env);
72
  }
73
74
  sprintf(folder_path + strlen(folder_path), "/%s", SETTINGS_FOLDER);
75
  if (!make_folder(folder_path)) {
76
    printf("Failed to create Folder");
77
    return 1;
78
  }
79
80
  char *settings_path = malloc(strlen(folder_path) + strlen(SETTINGS_FILE) + 2); 
81
  sprintf(settings_path, "%s/%s", folder_path, SETTINGS_FILE);
82
83
84
  {
85
    FILE* setting_file = fopen(settings_path, "r");
86
87
    if (setting_file != NULL) {
88
      
89
      char setting_input[STRING_LEN]; 
90
91
      fgets(setting_input, sizeof(setting_input), setting_file);
92
      game_speed = string_to_num(setting_input, 0, SPEED_L - 1, game_speed);
93
94
      fgets(setting_input, sizeof(setting_input), setting_file);
95
      game_size.x = string_to_num(setting_input, MIN_SIZE, MAX_SIZE, game_size.x);
96
97
      fgets(setting_input, sizeof(setting_input), setting_file);
98
      game_size.y = string_to_num(setting_input, MIN_SIZE, MAX_SIZE, game_size.y);
99
100
      fclose(setting_file);
101
    }
102
  }
103
104
  char *score_path = malloc(strlen(folder_path) + strlen(SCORE_FILE) + 2);
105
  sprintf(score_path, "%s/%s", folder_path, SCORE_FILE);
106
107
  free(folder_path);
108
109
  {
110
    FILE* score_file = fopen(score_path, "r");
111
112
    if (score_file != NULL) {
113
114
      char score_input[STRING_LEN];
115
116
      uint8_t i;
117
      for (i = 0; i < SCORE_NUMBER; i++) {
118
        fgets(score_input, sizeof(score_input), score_file);
119
        if (score_input[0] != '\0') {
120
          uint8_t j;
121
          for(j = 0; score_input[j] != '\0'; j++) {
122
            if (score_input[j] == '\n' || score_input[j] == ' ' || score_input[j] == '\t') {
123
              score_input[j] = '\0';
124
              break;
125
            }
126
          }
127
          score_input[SCORE_LEN - 1] = '\0';
128
          strncpy(leader_board[i].name, score_input, SCORE_LEN);
129
        }
130
131
        fgets(score_input, sizeof(score_input), score_file);
132
        leader_board[i].points = string_to_num(score_input, 0, UINT16_MAX, leader_board[i].points);
133
      }
134
      fclose(score_file);
135
    }
136
  }
137
138
  /* Setting up terminal with termios */
139
140
  struct termios old, new;
141
142
  tcgetattr(STDIN_FILENO, &old);
143
144
  new = old;
145
146
  new.c_lflag &= ~(ECHO | ICANON);
147
  new.c_cc[VMIN] = 0;
148
  new.c_cc[VTIME] = 0;
149
150
  tcsetattr(STDIN_FILENO, TCSANOW, &new);
151
152
  srand(time(NULL));
153
154
  printf("\033[?25l");
155
156
  struct winsize init_size, current_size;
157
  ioctl(STDOUT_FILENO, TIOCGWINSZ, &init_size);
158
  current_size = init_size;
159
  bool too_small = false;
160
161
162
  /* Animation at the start */
163
  if (!start_animation())
164
    goto end_of_program;
165
166
167
  /* Menu */
168
169
  bool menu = true;
170
  main_menu setting = MAIN_MENU;
171
  bool change_menu = true;
172
173
  main_menu selected_menu = NEW_GAME;
174
  settings selected_setting = HEIGHT_S;
175
176
  struct timespec mili100 = {0, 1000000 * 100};
177
178
menu_start:
179
180
  while (menu) {
181
182
    direction pressed_key = DIRECTIONS;
183
184
    char string[STRING_LEN] = {};
185
    ssize_t length_string = read(STDIN_FILENO, string, sizeof(string) - 1);
186
187
188
    ioctl(STDOUT_FILENO, TIOCGWINSZ, &current_size);
189
190
    if (current_size.ws_col != init_size.ws_col ||
191
        current_size.ws_row != init_size.ws_row) {
192
      init_size = current_size;
193
      change_menu = true;
194
    }
195
196
197
    if (length_string > 0) {
198
      string[length_string] = '\0';
199
200
      pressed_key = read_direction(string, false);
201
    }
202
203
    if (pressed_key == Q_KEY || pressed_key == ESCAPE)
204
      goto end_of_program;
205
206
207
    if (setting == MAIN_MENU) {
208
      
209
      if (!too_small) {
210
        switch (pressed_key) {
211
          case UP:
212
            selected_menu = (selected_menu + (MAIN_MENU - 1)) % MAIN_MENU;
213
            change_menu = true;
214
            break;
215
          case DOWN:
216
            selected_menu = (selected_menu + 1) % MAIN_MENU;
217
            change_menu = true;
218
            break;
219
          default:
220
            break;
221
        }
222
      }
223
224
      if (change_menu) {
225
        too_small = draw_menu(selected_menu, init_size);
226
        change_menu = false;
227
      }
228
229
      if (pressed_key == ENTER && !too_small) {
230
        switch (selected_menu) {
231
        case NEW_GAME:
232
          menu = false;
233
          break;
234
        case SETTINGS:
235
          setting = SETTINGS;
236
          break;
237
        case HIGHSCORE:
238
          setting = HIGHSCORE;
239
          break;
240
        default:
241
          goto end_of_program; 
242
          break;
243
        }
244
        change_menu = true;
245
      }
246
247
    } else if (setting == SETTINGS) {
248
249
      /* Settings Menu */
250
251
      if (change_menu) {
252
        
253
        draw_settings(selected_setting, game_speed, game_size, init_size);
254
255
        change_menu = false;
256
      }
257
258
259
      if (pressed_key < DIRECTIONS) {
260
261
        int8_t setting_change = 0;
262
263
        switch (pressed_key) {
264
          case UP:
265
            selected_setting = (selected_setting + (SETTINGS_MENU - 1)) % SETTINGS_MENU;
266
            break;
267
          case DOWN:
268
            selected_setting = (selected_setting + 1) % SETTINGS_MENU;
269
            break;
270
          case LEFT:
271
            setting_change = 1;
272
            break;
273
          case RIGHT:
274
            setting_change = -1;
275
            break;
276
          default:
277
            break;
278
        }
279
        
280
        if (setting_change) {
281
          switch (selected_setting) {
282
            case SPEED_S:
283
              if (
284
                game_speed + setting_change <= SPEED_L - 1 &&
285
                ((int8_t) game_speed) + setting_change >= 0 
286
              ) {
287
                game_speed += setting_change;
288
              }
289
              break;
290
            case WIDTH_S:
291
              if (
292
                game_size.x - setting_change >= MIN_SIZE &&
293
                game_size.x - setting_change <= MAX_SIZE
294
              ) {
295
                game_size.x -= setting_change;
296
              }
297
              break;
298
            case HEIGHT_S:
299
              if (
300
                game_size.y - setting_change >= MIN_SIZE &&
301
                game_size.y - setting_change <= MAX_SIZE
302
              ) {
303
                game_size.y -= setting_change;
304
              }
305
              break;
306
            default:
307
              break;
308
          }
309
        }
310
311
        change_menu = true;
312
313
      }
314
315
      if (pressed_key == ENTER) {
316
        switch (selected_setting) {
317
          case BACK_S:
318
            setting = MAIN_MENU;
319
            break;
320
          default:
321
            break;
322
        }
323
        change_menu = true;
324
      }
325
    } else if (setting == HIGHSCORE) {
326
      
327
      if(change_menu) {
328
        uint8_t i;
329
330
        for (i = 0; i < SCORE_NUMBER; i++) {
331
          if (score > leader_board[i].points)
332
            break;
333
        }
334
335
        if (i < SCORE_NUMBER) {
336
337
          uint8_t new_score = i;
338
339
          for (i = SCORE_NUMBER - 1; i > new_score; i--) {
340
            leader_board[i] = leader_board[i -1]; 
341
          }
342
343
          leader_board[new_score].points = score;
344
          leader_board[new_score].name[0] = '\0';
345
346
          draw_highscore (new_score, leader_board);
347
     
348
        } else {
349
          draw_highscore (-1, leader_board);    
350
        }
351
      }
352
353
      if(pressed_key == ENTER) {
354
        setting = MAIN_MENU;
355
        change_menu = true;
356
      }
357
    } else if(setting == NEW_GAME) {
358
359
      if(pressed_key == ENTER) {
360
        setting = HIGHSCORE;
361
        change_menu = true;
362
      }
363
    }
364
365
  nanosleep(&mili100, NULL);
366
  }
367
368
  menu = true;
369
370
  /* initialisation of the game */
371
372
  snake my_snake;
373
  my_snake.length = STARTING_LENGTH;
374
375
  my_snake.position = malloc((my_snake.length + 1) * sizeof(snake_part));
376
377
  direction shift = RIGHT;
378
  direction tmp_direction = shift;
379
380
  {
381
    uint16_t i;
382
383
    my_snake.position[0].coords.y = game_size.y >> 1;
384
    my_snake.position[0].coords.x = game_size.x >> 1;
385
    my_snake.position[0].directions[0] = shift;
386
    my_snake.position[0].directions[1] = shift;
387
    for (i = 1; i <= my_snake.length; i++) {
388
      my_snake.position[i].coords.y = -1;
389
      my_snake.position[i].coords.x = -1;
390
    }
391
  }
392
393
  board_state **board = malloc(game_size.y * sizeof(board_state*));
394
  board_state *values = calloc(game_size.y * game_size.x, sizeof(board_state));
395
396
  if(board == NULL || values == NULL)
397
    goto end_of_program;
398
399
  {
400
    uint8_t i;
401
402
    for (i = 0; i < game_size.y; i++)
403
      board[i] = values + i * game_size.x;
404
  }
405
406
  update_field(my_snake, game_size, board, true);
407
408
  uint8_t paused = 0;
409
410
411
  if ((too_small = draw_board(game_size, board, current_size, true, 0, score)))
412
    paused = 1;
413
414
  bool run = true;
415
416
  struct timespec milispeed = {0, 1000000 * (SPEED + game_speed * 25)};
417
418
  /* start of the actual game loop */
419
420
  while (run) {
421
422
    /* input handling  */
423
424
425
    direction pressed_key;
426
427
    char string[STRING_LEN] = {};
428
    ssize_t length_string = read(STDIN_FILENO, string, sizeof(string) - 1);
429
430
    if (length_string > 0) {
431
      string[length_string] = '\0';
432
433
      pressed_key = read_direction(string, true);
434
435
      if (!too_small) {
436
        if (pressed_key == P_KEY || pressed_key == ENTER) {
437
          paused = (paused == 1) ? 0 : 1;
438
          if (paused)
439
            draw_board(game_size, board, current_size, true, paused, score);
440
        } 
441
442
        if (!paused && pressed_key < DIRECTIONS)
443
          tmp_direction = pressed_key;
444
      }
445
446
      if (pressed_key == Q_KEY || pressed_key == ESCAPE)
447
        run = false;
448
    }
449
  
450
451
    /* game logic */
452
453
    /*
454
    struct timeval current;
455
    gettimeofday(&current, NULL);*/
456
457
    if (/*time_diff >= SPEED * 1000*/ true) {
458
459
      ioctl(STDOUT_FILENO, TIOCGWINSZ, &current_size);
460
461
      if (current_size.ws_col != init_size.ws_col ||
462
          current_size.ws_row != init_size.ws_row) {
463
        init_size = current_size;
464
465
        paused = 1;
466
        too_small = draw_board(game_size, board, current_size, true, paused, score);
467
      }
468
469
      if (!paused) {
470
471
        if (tmp_direction < DIRECTIONS &&
472
            ((shift + (DIRECTIONS >> 1)) % DIRECTIONS) != tmp_direction) {
473
          shift = tmp_direction;
474
        }
475
476
        uint8_t update = update_snake(game_size ,&my_snake, shift);
477
478
        uint8_t head_y = my_snake.position[0].coords.y;
479
        uint8_t head_x = my_snake.position[0].coords.x;
480
481
        if (board[head_y][head_x] == FRUIT) {
482
          my_snake.length++;
483
          score += 1 + 
484
            (((MAX_SIZE >> 1) / (game_size.y) + 
485
            (MAX_SIZE >> 1) / (game_size.x) + 
486
            (my_snake.length - STARTING_LENGTH)) / (game_speed + 1));
487
          snake_part *tmp = realloc(my_snake.position, (my_snake.length + 1) * sizeof(snake_part));
488
          if (tmp == NULL)
489
            goto end_free;
490
          my_snake.position = tmp;
491
492
          my_snake.position[my_snake.length].coords.y = -1;
493
          my_snake.position[my_snake.length].coords.x = -1;
494
        }
495
496
        update_field(my_snake, game_size, board, false);
497
498
        draw_board(game_size, board, current_size, false, 0, score);
499
500
        switch (update) {
501
          case 0: 
502
            goto end_free;
503
            break;
504
          case 2:
505
            setting = NEW_GAME;
506
            draw_board(game_size, board, current_size, false, 2, score);
507
            goto end_free;
508
            break;
509
          default:
510
            break;
511
        }
512
513
      }
514
    }
515
    nanosleep(&milispeed, NULL);
516
  }
517
518
end_free:
519
520
  free(my_snake.position);
521
  free(board);
522
  free(values);
523
524
  if (setting == NEW_GAME)
525
    goto menu_start;
526
527
end_of_program:
528
529
  tcsetattr(STDIN_FILENO, TCSANOW, &old);
530
  printf("\033[?25h\n\n");
531
532
  printf("\033[32m");
533
  printf("\033[2J\033[H");
534
535
536
  {
537
    FILE* setting_file = fopen(settings_path, "w");
538
539
    fprintf(setting_file, "%d\n%d\n%d", game_speed, game_size.x, game_size.y);
540
    
541
    fclose(setting_file);
542
543
    FILE* score_file = fopen(score_path, "w");
544
    uint8_t i;
545
546
    for (i = 0; i < SCORE_NUMBER; i++) {
547
      fprintf(score_file, "%s\n%i\n", leader_board[i].name, leader_board[i].points);
548
    }
549
550
    fclose(score_file);
551
  }
552
553
  free(settings_path);
554
  free(score_path);
555
  
556
  return 0;
557
}