forked from arwn/snek
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.cpp
117 lines (104 loc) · 2.03 KB
/
snake.cpp
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
#include <cstdio>
#include <iostream>
#include <tuple>
#include <list>
#include <unistd.h>
#include <vector>
#include <memory>
#include <iterator>
#include "curses_view/curses_view.hpp"
#include "snake.hpp"
static GameBoard board ={
{Empty, Empty, Empty, Empty, Empty},
{Empty, Empty, Empty, Empty, Empty},
{Empty, Head, Empty, Empty, Empty},
{Empty, Empty, Empty, Empty, Empty},
{Fruit, Empty, Empty, Empty, Empty},
};
void
get_direction(int key, Direction *d)
{
switch (key) {
case 'w':
*d = North; break;
case 'a':
*d = West; break;
case 's':
*d = South; break;
case 'd':
*d = East; break;
}
}
// TODO: this function doesn't work, make it linked list.
int
move_snake(Direction d, std::list<std::tuple<int, int>> snek)
{
auto head = snek.front();
int x = std::get<0>(head);
int y = std::get<1>(head);
switch (d) {
case North:
--y;
// board[y - 1][x] = Head;
break;
case South:
++y;
// board[y + 1][x] = Head;
break;
case East:
++x;
// board[y][x + 1] = Head;
break;
case West:
--x;
// board[y][x - 1] = Head;
break;
}
if (x < 0 || y < 0)
return 1;
board[std::get<1>(head)][std::get<0>(head)] = Tail;
auto back = snek.back();
board[std::get<1>(back)][std::get<0>(back)] = Empty;
snek.pop_back();
snek.push_front(std::tuple<int, int>(x, y));
board[y][x] = Head;
// for (auto y = 0; y < board.size(); y++) {
// for (auto x = 0; x < board.size(); x++) {
// if (board[y][x] == Head) {
// }
// }
// }
return 0;
}
void
draw_board(std::shared_ptr<iview> view)
{
int dy = 0;
int dx = 0;
for (auto &row : board) {
dy++;
dx = 0;
for (auto &col : row) {
dx++;
view->draw_tile(col, dy, dx);
}
}
}
int
main(void)
{
std::shared_ptr<iview> view = std::make_shared<curses_view>();
view->init();
Direction d = East;
std::list<std::tuple<int, int>> snek;
snek.push_front(std::tuple(3,3));
while (view->running == true) {
get_direction(view->get_key(), &d);
int crash = move_snake(d, snek);
draw_board(view);
view->flush_display();
sleep(1);
}
view->destroy();
return 0;
}