-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.cpp
54 lines (48 loc) · 1.84 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
#include <SFML/Graphics.hpp>
#include "config.hpp"
#include "food.hpp"
#include "snake.hpp"
int main() {
sf::RenderWindow window(sf::VideoMode(screenWidth * tileSize, screenHeight * tileSize), "Snake");
Snake snake(window.getSize().x / 2.0f, window.getSize().y / 2.0f);
Food food(window.getSize().x / 2.0f + 60, window.getSize().y / 2.0f + 60);
sf::Clock clock;
float deltaTime{};
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
} else if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Up) {
snake.updateDirection(Direction::UP);
} else if (event.key.code == sf::Keyboard::Down) {
snake.updateDirection(Direction::DOWN);
} else if (event.key.code == sf::Keyboard::Left) {
snake.updateDirection(Direction::LEFT);
} else if (event.key.code == sf::Keyboard::Right) {
snake.updateDirection(Direction::RIGHT);
}
}
}
if (deltaTime > 0.2) {
deltaTime = 0.0f;
snake.move();
if (snake.checkBorderCollision(window) || snake.checkSuicide()) {
window.close();
} else if (snake.getBody().front().getGlobalBounds().intersects(food.getBody().getGlobalBounds())) {
food.generateNewPos();
snake.addNewSegment();
}
} else {
deltaTime += clock.restart().asSeconds();
}
window.clear();
for (const auto& segment : snake.getBody()) {
window.draw(segment);
}
window.draw(food.getBody());
window.display();
}
return 0;
}