-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
347 lines (283 loc) · 6.59 KB
/
main.cpp
File metadata and controls
347 lines (283 loc) · 6.59 KB
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include <random>
using namespace sf;
static const int M = 10, N = 20;
static const int STEP = 18;
enum class Direction
{
NONE, UP, LEFT, DOWN, RIGHT
};
class GameObject
{
protected:
Sprite tile_;
Vector2i pos_;
public:
explicit GameObject(const Texture & texture)
{
tile_.setTexture(texture);
}
const Sprite & GetTile() const
{
return tile_;
}
const Vector2i & GetPosition() const
{
return pos_;
}
};
class Body: public GameObject
{
private:
Direction direction_ = Direction::NONE;
public:
explicit Body(const Texture & texture, const Vector2i & pos) : GameObject(texture)
{
pos_ = pos;
tile_.setTextureRect(IntRect(0, 0, STEP, STEP));
}
Direction GetDirection() const
{
return direction_;
}
// возвращаем предыдущее направление
Direction Move(Direction dir)
{
auto prev_dir = direction_;
if (dir != Direction::NONE)
direction_ = dir;
switch (direction_)
{
case Direction::UP:
pos_.y -= 1;
break;
case Direction::DOWN:
pos_.y += 1;
break;
case Direction::LEFT:
pos_.x -= 1;
break;
case Direction::RIGHT:
pos_.x += 1;
break;
default: ;
}
tile_.setPosition(static_cast<Vector2f>(pos_ * STEP));
return prev_dir;
}
};
class Snake : private std::vector<Body>
{
private:
Body tail_;
int score_ = 0;
private:
void CheckDirection(Direction & dir) const
{
if (dir == Head().GetDirection() ||
(dir == Direction::UP && Head().GetDirection() == Direction::DOWN) ||
(dir == Direction::DOWN && Head().GetDirection() == Direction::UP) ||
(dir == Direction::RIGHT && Head().GetDirection() == Direction::LEFT) ||
(dir == Direction::LEFT && Head().GetDirection() == Direction::RIGHT) )
{
dir = Direction::NONE;
}
}
const Body & Head() const
{
return *begin();
}
public:
Snake(std::initializer_list<Body> bodies) : std::vector<Body>(bodies), tail_(back()) {}
bool CheckIntersects() const
{
if (Head().GetPosition().y < 0 ||
Head().GetPosition().y >= N ||
Head().GetPosition().x < 0 ||
Head().GetPosition().x >= M )
{
return true;
}
for (int i = 0; i < size(); i++)
for (int j = 0; j < size(); j++)
{
if (i == j) continue;
if (at(i).GetPosition() == at(j).GetPosition())
return true;
}
return false;
}
bool HasPosition(const Vector2i & pos) const
{
for (const auto & body : *this)
if (body.GetPosition() == pos)
return true;
return false;
}
const Vector2i & GetPosition() const
{
return Head().GetPosition();
}
std::vector<Sprite> GetTiles() const
{
std::vector<Sprite> tiles;
tiles.reserve(size());
for (const auto & body : *this)
tiles.push_back(body.GetTile());
return tiles;
}
void Move(Direction dir)
{
// не даем ползти в текущую или противоположную сторону
CheckDirection(dir);
if (dir == Direction::NONE)
dir = Head().GetDirection();
// сохраняем хвост на случай, если его нужно будет отрастить
tail_ = back();
for (auto & body : *this)
{
dir = body.Move(dir);
if (dir == Direction::NONE)
dir = Head().GetDirection();
}
}
void Eat()
{
push_back(tail_);
++score_;
}
int GetScore() const
{
return score_;
}
};
class Food : public GameObject
{
private:
std::random_device rd_;
public:
explicit Food(const Texture & texture): GameObject(texture)
{
tile_.setTextureRect(IntRect(STEP, 0, STEP, STEP));
}
void Reset()
{
std::mt19937 gen_ (rd_());
std::uniform_int_distribution<> disX(0, M-1), disY(0, N-1);
pos_.x = disX(gen_);
pos_.y = disY(gen_);
tile_.setPosition(static_cast<Vector2f>(pos_ * STEP));
}
};
int main()
{
RenderWindow window(sf::VideoMode(M*STEP, N*STEP), "Snake");
enum SoundName
{
SN_MOVE, SN_EAT, SN_GAMEOVER, SN_TOTAL
};
SoundBuffer s_buffs[SN_TOTAL];
s_buffs[SN_MOVE].loadFromFile("../data/move.ogg");
s_buffs[SN_EAT].loadFromFile("../data/eat.ogg");
s_buffs[SN_GAMEOVER].loadFromFile("../data/gameover.ogg");
Sound sounds[SN_TOTAL];
for (int i = SN_MOVE; i < SN_TOTAL; i++)
sounds[i].setBuffer(s_buffs[i]);
Texture texture;
texture.loadFromFile("../data/tiles.png");
Food food(texture);
Snake snake = {
Body(texture, Vector2i{2,0}),
Body(texture, Vector2i{1,0}),
Body(texture, Vector2i{0,0})
};
Clock clock;
float timer = 0, delay = 0.5;
bool GameOver = false, GameBegin = true;
auto direction = Direction::NONE;
auto reset_food = [&]()
{
do //сбрасываем так, чтобы небыло пересечений со змеей
{
food.Reset();
}
while (snake.HasPosition(food.GetPosition()));
};
while (window.isOpen())
{
timer += clock.getElapsedTime().asSeconds();
clock.restart();
Event event{};
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
window.close();
if (event.type == Event::KeyPressed && direction == Direction::NONE)
{
switch (event.key.code)
{
case Keyboard::Left:
direction = Direction::LEFT; break;
case Keyboard::Right:
direction = Direction::RIGHT; break;
case Keyboard::Up:
direction = Direction::UP; break;
case Keyboard::Down:
direction = Direction::DOWN; break;
default: ;
}
}
}
if (timer >= delay && !GameOver)
{
// проверяем пересечение со стенами и с собой
GameOver = snake.CheckIntersects();
if (GameOver)
{
sounds[SN_GAMEOVER].play();
continue;
}
// двигаем всю змею согласно направлению на поле
snake.Move(direction);
// съедаем еду
if (snake.GetPosition() == food.GetPosition())
{
snake.Eat();
delay -= 0.01; // усложняем задачу
reset_food();
sounds[SN_EAT].play();
}
else sounds[SN_MOVE].play();
timer = 0;
direction = Direction::NONE;
}
if (GameBegin)
{
GameBegin = false;
snake.Move(Direction::RIGHT);
reset_food();
}
window.clear();
if (GameOver)
{
Font font;
font.loadFromFile("../data/kenney_blocks.ttf");
Text text("Game Over\nScore: "+std::to_string(snake.GetScore()), font, 25);
auto textRect = text.getLocalBounds();
text.setOrigin(textRect.left + textRect.width/2.0f, textRect.top + textRect.height/2.0f);
text.setPosition(window.getSize().x/2.0f,window.getSize().y/2.0f);
text.setFillColor(Color::Red);
window.draw(text);
}
else
{
window.draw(food.GetTile());
for (auto & tile : snake.GetTiles())
window.draw(tile);
}
window.display();
}
return 0;
}