-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgame.h
136 lines (110 loc) · 2.48 KB
/
game.h
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
#ifndef GAME_H
#define GAME_H
#include <stdint.h>
#include <stdlib.h>
#if defined(__EMSCRIPTEN__)
const int FIELD_WIDTH = 64;
const int FIELD_HEIGHT = 64;
#elif defined(__AVR__)
const int FIELD_WIDTH = 32;
const int FIELD_HEIGHT = 8;
#else
#error Unsupported platform.
#endif
/**
* Game field cell type.
*/
typedef enum {
CELL_TYPE_EMPTY,
CELL_TYPE_SNAKE,
CELL_TYPE_FOOD,
CELL_TYPE_BLOCK
} CELL_TYPE;
/**
* Direction to snake next cell.
*/
typedef enum {
DIRECTION_LEFT,
DIRECTION_RIGHT,
DIRECTION_UP,
DIRECTION_DOWN
} DIRECTION;
/**
* The result of game loop step.
*/
typedef enum {
STEP_RESULT_SUCCESS,
STEP_RESULT_FAIL
} STEP_RESULT;
/**
* Point coordinates.
*/
typedef struct Point {
/**
* X-coordinate: [0..FIELD_WIDTH].
*/
uint8_t x;
/**
* Y-coordinate: [0..FIELD_HEIGHT].
*/
uint8_t y;
} Point;
#define POINT(x, y) ((Point) {(uint8_t) x, (uint8_t) y})
#define POINT_IS_EQUAL(p1, p2) (p1.x == p2.x && p1.y == p2.y)
/**
* Snake data container.
*/
typedef struct Snake {
Point first_point;
Point last_point;;
} Snake;
/**
* Cell data will be encoded in one byte by the following bit schema:
* 2 bits - type of the cell, one of CELL_TYPE value.
* Next bits depends on type of the cell.
* - Snake cell:
* 2 bits - next cell direction, one of DIRECTION value.
* The first snake cell contains direction for future step.
*/
typedef uint8_t Cell;
#define GAME_CELL_MAKE_EMPTY ((Cell) CELL_TYPE_EMPTY)
#define GAME_CELL_MAKE_SNAKE(next_direction) ((Cell) (CELL_TYPE_SNAKE | ((next_direction) << 2)))
#define GAME_CELL_MAKE_FOOD ((Cell) CELL_TYPE_FOOD)
#define GAME_CELL_MAKE_BLOCK ((Cell) CELL_TYPE_BLOCK)
#define GAME_CELL_GET_TYPE(cell) ((CELL_TYPE) ((cell) & 0x03))
#define GAME_CELL_IS_TYPE(cell, type) (GAME_CELL_GET_TYPE(cell) == (type))
#define GAME_CELL_GET_SNAKE_NEXT(cell) ((DIRECTION) (((cell) >> 2) & 0x03))
/**
* Game field, contains only cells.
*/
typedef struct Field {
Cell cells[FIELD_WIDTH][FIELD_HEIGHT];
} Field;
/**
* Game root struct.
*/
typedef struct Game {
Field field;
Snake snake;
Point food_location;
short score;
} Game;
/**
* User input.
*/
typedef struct UserInput {
DIRECTION next_move;
} UserInput;
/**
* Initialize game struct.
*/
void game_init(Game *game);
/**
* Initialize game for next level.
*/
void game_prepare_level(Game *game);
/**
* Handle next game loop step.
*/
STEP_RESULT game_handle_next_step(Game *game, UserInput *input);
#endif