-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathstep18.cpp
117 lines (107 loc) · 2.57 KB
/
step18.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 "co_async/debug.hpp"
#include "co_async/task.hpp"
#include "co_async/timer_loop.hpp"
#include "co_async/epoll_loop.hpp"
#include "co_async/async_loop.hpp"
#include "co_async/when_any.hpp"
#include "co_async/when_all.hpp"
#include "co_async/limit_timeout.hpp"
#include "co_async/and_then.hpp"
#include <cstring>
#include <termios.h>
[[gnu::constructor]] static void disable_canon() {
struct termios tc;
tcgetattr(STDIN_FILENO, &tc);
tc.c_lflag &= ~ICANON;
tc.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tc);
}
using namespace std::chrono_literals;
co_async::EpollLoop epollLoop;
co_async::TimerLoop timerLoop;
char map[20][20];
int x = 10;
int y = 10;
int dx = 0;
int dy = 0;
bool running;
void on_key(char c) {
if (c == 'q') {
running = false;
} else if (c == 'a') {
dx = -1;
dy = 0;
} else if (c == 'd') {
dx = 1;
dy = 0;
} else if (c == 'w') {
dx = 0;
dy = -1;
} else if (c == 's') {
dx = 0;
dy = 1;
}
}
void on_time() {
if (x + dx >= 20 || x + dx < 0 ||
y + dy >= 20 || y + dy < 0) {
running = false;
return;
}
x += dx;
y += dy;
}
void on_draw() {
std::memset(map, ' ', sizeof(map));
map[y][x] = '@';
std::string s = "\x1b[H\x1b[2J\x1b[3J";
for (int i = 0; i < 20; ++i) {
s += '#';
}
s += '\n';
for (int i = 0; i < 20; ++i) {
s += '#';
for (int j = 0; j < 20; ++j) {
s += map[i][j];
}
s += "#\n";
}
for (int i = 0; i < 20; ++i) {
s += '#';
}
s += '\n';
write(STDOUT_FILENO, s.data(), s.size());
}
inline co_async::Task<std::string> read_string(co_async::EpollLoop &loop, co_async::AsyncFile &file) {
co_await wait_file_event(loop, file, EPOLLIN | EPOLLRDHUP);
std::string s;
s.resize(64);
auto len = readFileSync(file, s);
s.resize(len);
co_return s;
}
co_async::Task<> async_main() {
co_async::AsyncFile file(STDIN_FILENO);
auto nextTp = std::chrono::system_clock::now();
running = true;
while (true) {
auto res = co_await limit_timeout(timerLoop, read_string(epollLoop, file), nextTp);
if (res) {
for (char c: *res) {
on_key(c);
}
on_draw();
} else {
on_time();
if (!running) break;
on_draw();
nextTp = std::chrono::system_clock::now() + 500ms;
}
}
}
int main() {
co_async::AsyncLoop loop;
auto t = async_main();
run_task(loop, t);
return 0;
}