Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
91 lines (74 loc) · 1.61 KB
/
Copy pathmain.cpp
File metadata and controls
91 lines (74 loc) · 1.61 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
// main.cpp
#include <SFML/Graphics.hpp>
#include "Game_of_Life.h"
#include <thread>
constexpr unsigned D_SIZE = 100;
constexpr unsigned CELL = 10;
constexpr float TICK = 0.1f;
int main()
{
sf::RenderWindow app(sf::VideoMode({ D_SIZE * CELL, D_SIZE * CELL }),
"Life Game!", sf::Style::Default);
// app.setFramerateLimit(60);
// 初始化Life
GameOfLife gol(D_SIZE, CELL);
sf::Clock Game_clock;
float acc = 0.0f;
bool paused = true;
while (app.isOpen())
{
while (std::optional<sf::Event> e = app.pollEvent())
{
if (e->is<sf::Event::Closed>())
{
app.close();
}
if (auto* mousePressed = e->getIf<sf::Event::MouseButtonPressed>())
{
if (mousePressed->button == sf::Mouse::Button::Left)
{
gol.toggleCell(mousePressed->position);
}
}
if (auto* keyPressed = e->getIf<sf::Event::KeyPressed>())
{
if (keyPressed->code == sf::Keyboard::Key::Space)
{
paused = !paused;
}
}
if (auto* keyPressed = e->getIf<sf::Event::KeyPressed>())
{
if (keyPressed->code == sf::Keyboard::Key::Escape)
{
gol.resetCell();
}
}
}
if (!paused)
{
float dt = Game_clock.restart().asSeconds();
// printf("%f\n", dt);
// 最多只允许追赶 5 个逻辑帧
constexpr float MAX_DT = TICK * 5.0f;
if (dt > MAX_DT) dt = MAX_DT;
acc += dt;
// printf("acc:%f, TICK:%f\n", acc, TICK);
while (acc >= TICK)
{
gol.step();
acc -= TICK;
}
}
else
{
Game_clock.restart();
}
app.clear();
// draw...
app.draw(gol);
app.display();
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return 0;
}