-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
106 lines (78 loc) · 1.89 KB
/
main.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
#include <string>
#include <iostream>
#include "Grid.h"
int main(int argc, char *argv[])
{
// x-dimension to be multiples of 16 for performance
const int W=16*6;
// can be anything
const int H=32;
int ch;
resizeterm(W+2,H+2);
initscr();
clear();
cbreak();
keypad(stdscr, TRUE);
// ncurses console screen
Screen<W,H> screen;
// snake game grid [ compute method calculates the main game-logic ]
Grid<W,H> grid;
// star snake facing upwards
char dir=grid.UP;
// game exits when snake head collides with a snake
bool exit = false;
// no delay for keyboard input
nodelay(stdscr, TRUE);
// eating latch (game gives apple automatically in every second frame)
bool eat = false;
// benchmark variables
size_t avgTime = 0;
int ctFrame = 0;
// game loop
while(true)
{
ctFrame++;
std::this_thread::sleep_for(std::chrono::nanoseconds(100000000));
switch(ch=getch())
{ case KEY_LEFT:
dir=grid.LEFT;
break;
case KEY_RIGHT:
dir=grid.RIGHT;
break;
case KEY_UP:
dir=grid.UP;
break;
case KEY_DOWN:
dir=grid.DOWN;
break;
case 27:
exit = true;
break;
}
if(exit)
break;
size_t nanoseconds;
// if head collides tail, then exit game
if(grid.compute( eat=!eat,dir,nanoseconds))
{
avgTime+=nanoseconds;
// ncurses finish
endwin();
// output performance of player and computer
std::cout<<"score="<<grid.len<<std::endl;
std::cout<<"average compute time = "<<avgTime/ctFrame<<" nanoseconds"<<std::endl;
return 0;
}
// update screen and accumulate average frame time
avgTime+=nanoseconds;
grid.updateScreen(screen);
screen.render(nanoseconds);
}
// ncurses finish
endwin();
// output performance of player and computer
std::cout<<"score="<<grid.len<<std::endl;
std::cout<<"average compute time = "<<avgTime/ctFrame<<" nanoseconds"<<std::endl;
return 0;
}