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
|
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <time.h>
#include <unistd.h>
//#define XCOLS 100
//#define YROWS 100
#define GRID_EMPTY 0
#define GRID_SNAKE 1
#define GRID_TRGET 2
#define MAX_GENS 100
char v = 0;
struct Snake {
/* position of head */
int head[2];
/* velocity of head */
int v[2];
/* body length */
size_t len;
};
void
print_grid(int x, int y, char grid[x][y]){
for (int j = 0; j < y; j++){
for (int i = 0; i < x; i++)
printf("%c", grid[i][j] == GRID_SNAKE ? '#' : grid[i][j] == GRID_TRGET ? '@' : ' ');
printf("\n");
}
}
void
new_target(int x, int y, char grid[x][y]){
int randx, randy;
freshvalues:
randx = rand() % x;
randy = rand() % y;
if (!grid[randx][randy])
grid[randx][randy] = GRID_TRGET;
else goto freshvalues;
}
void
plog(const char *msg, ...){
if (v){
va_list l;
va_start(l, msg);
vfprintf(stderr, msg, l);
va_end(l);
}
}
void
die(const int err, const char *msg){
fprintf(stderr, msg);
exit(err);
}
int
main(int argc, char **argv){
if (argc == 2 && !strcmp("-v", argv[1])) v = 1;
plog("Verbose logging enabled\n");
/* find terminal size */
struct winsize w;
if (ioctl(1, TIOCGWINSZ, &w) < 0){
perror("ioctl");
die(1, NULL);
}
int XCOLS = (int) w.ws_col;
int YROWS = (int) w.ws_row;
plog("found terminal size %dx%d\n", XCOLS, YROWS);
char grid[XCOLS][YROWS];
struct Snake snek;
snek.v[0] = 1;
snek.v[1] = 0;
/* initialise rand with a fresh seed */
srand((unsigned) time(NULL));
/* initialise grid to be all 0's to begin with. */
for (int i = 0; i < XCOLS; i++)
for (int j = 0; j < YROWS; j++)
grid[i][j] = GRID_EMPTY;
/* choose a random starting point */
snek.head[0] = rand() % XCOLS;
snek.head[1] = rand() % YROWS;
grid[snek.head[0]][snek.head[1]] = GRID_SNAKE;
/* and a random point for the target */
new_target(XCOLS, YROWS, grid);
int gen = MAX_GENS;
while (gen--){
print_grid(XCOLS, YROWS, grid);
plog("snek head is %d,%d\nmoving at [%d,%d]\n", snek.head[0], snek.head[1], snek.v[0], snek.v[1]);
grid[snek.head[0]][snek.head[1]] = GRID_EMPTY;
snek.head[0] += snek.v[0];
snek.head[1] += snek.v[1];
grid[snek.head[0]][snek.head[1]] = GRID_SNAKE;
printf("hi\r");
sleep(1);
}
}
|