-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
126 lines (109 loc) · 2.85 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
/**
* @file main.cpp
* @author combofish ([email protected])
* @brief 主要逻辑实现。
* @version 0.6
* @date 2021-10-16
*
* @copyright Copyright (c) 2021
*
*/
#include "main.h"
#include "GUI_Interface/GUI.h"
#include "dot.h"
#include "snake.h"
#include "snake_window.h"
using namespace snake_game;
/**
* @brief
*
* @param d
*/
void event_loop(Address d);
/**
* @brief
*
* @param d
*/
void snake_game_run(Address d);
int main() {
Graph_lib::Point p1(100, 100);
try {
Snake_window win(p1, 600, 400, "Snake");
win.set_label("Snake Game");
Fl::add_timeout(GAME_SPEED, event_loop, &win);
return Graph_lib::gui_main();
} catch (exception &e) {
std::cerr << "exception: " << e.what() << std::endl;
return 1;
} catch (...) {
std::cerr << "Some ecception" << std::endl;
return 2;
}
}
/**
* @brief
*
* @param d
*/
void event_loop(Address d) {
// Snake_window *instance = static_cast<Snake_window *>(d);
Snake_window &snake_win = reference_to<Snake_window>(d);
// cout << "Delay 1s" << endl;
// cout << "Is Ready: " << instance->is_ready << endl;
// cout << "Game Status: " << (int)instance->game_status << endl;
// cout << "Current Direction: " << (int)instance->current_direction() <<
// endl;
switch (snake_win.game_status) {
case GameStatus::PAUSE: {
// cout << "Game Pause" << endl;
break;
};
case GameStatus::RUN: {
snake_game_run(d);
break;
}
case GameStatus::COLLISION: {
// std::cout << "Collision" << endl;
// std::cout << "Game Over!" << std::endl;
snake_win.game_over();
break;
}
}
Fl::redraw();
Fl::repeat_timeout(GAME_SPEED, event_loop, d);
}
/**
* @brief
*
* @param d
*/
void snake_game_run(Address d) {
Snake_window &snake_win = reference_to<Snake_window>(d);
/* Judge Eat. */
bool is_eat =
snake_win.snake.judge_eat(snake_win.game_direction, snake_win.food_dot);
if (is_eat) {
// cout << "Eat" << endl;
/* Update Food Dot. */
snake_win.food_dot =
Dot::get_random_dot_exclude(snake_win.snake.locations());
snake_win.paint_dot(snake_win.food_dot);
} else {
/* */
bool is_collision =
snake_win.snake.judge_collision(snake_win.game_direction);
if (is_collision) {
snake_win.game_status = snake_game::GameStatus::COLLISION;
} else {
/* Snake length don't increase. */
Dot p = snake_win.snake.move(snake_win.game_direction);
snake_win.clean_dot(p);
}
}
/* Redraw Snake Locations. */
snake_win.paint_dots(snake_win.snake.locations());
/* Update Score. */
snake_win.update_score();
/**/
}