-
Notifications
You must be signed in to change notification settings - Fork 3
/
map.c
71 lines (62 loc) · 1.92 KB
/
map.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
// SPDX-License-Identifier: GPL-3.0-only
// Copyright © 2024 Mario D'Andrea https://ormai.dev
#include <stdlib.h>
#include <sys/ioctl.h>
#include "map.h"
#include "snake.h"
#include "term.h"
#include "window.h"
struct map *map_create(void) {
struct map *map = malloc(sizeof(struct map));
const struct winsize ws = get_term_size();
map->width = ws.ws_col / 3; // see translate()
map->height = ws.ws_row * 2 / 3;
map->area = map->width * map->height;
map->offset = (struct point){(ws.ws_col - map->width * 2) / 2,
(ws.ws_row - map->height) / 2};
map->grid = malloc(sizeof(int * [map->height + 1]));
for (int i = 0; i <= map->height; ++i) {
map->grid[i] = calloc(map->width + 1, sizeof(int));
}
return map;
}
void map_destroy(struct map *map) {
if (map != NULL) {
if (map->grid != NULL) {
for (int i = 0; i <= map->height; ++i) {
free(map->grid[i]);
}
free(map->grid);
}
free(map);
map = NULL;
}
}
bool is_inside(const struct map *map, const struct snake *snake) {
const struct point head = snake->body[snake->length - 1];
return head.x <= map->width && head.x >= 0 && head.y <= map->height &&
head.y >= 0;
}
void spawn_apple(struct map *map) {
static const unsigned max_tries = 5;
unsigned tries = 0;
do {
if (tries++ > max_tries) {
// After max_tries use the first available point
bool found_it = false;
for (int i = 0; i < map->height && !found_it; ++i) {
for (int j = 0; j < map->width && !found_it; ++j) {
if (map->grid[i][j] == false) {
found_it = true;
map->grid[i][j] = true;
map->apple = (struct point){i, j};
}
}
}
}
map->apple.x = rand() % (map->width + 1);
map->apple.y = rand() % (map->height + 1);
} while (map->grid[map->apple.y][map->apple.x] == true);
set_color(MAGENTA);
draw_point(map, map->apple);
}