-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplication.cpp
More file actions
112 lines (93 loc) · 1.97 KB
/
application.cpp
File metadata and controls
112 lines (93 loc) · 1.97 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
/**
rocket.cpp
Purpose: Core of the program.
@author Joshua Varga
@version 1.0
*/
#include "application.h"
Application::Application(int w, int h, int s, int p, float m)
{
width = w;
height = h;
stepLimit = s;
populationSize = p;
mutationRate = m;
window.create(sf::VideoMode(width, height), "Smart Rockets",
sf::Style::Titlebar | sf::Style::Close);
window.setFramerateLimit(60);
// Random seed.
srand((unsigned int)time(NULL));
// Rocket
rocketTexture.loadFromFile("assets/rocket.png");
// Asteroid.
asteroidTexture.loadFromFile("assets/asteroid.png");
asteroid.setTexture(asteroidTexture);
asteroid.setPosition(224, 64);
// Earth.
earthTexture.loadFromFile("assets/earth.png");
earth.setTexture(earthTexture);
earth.setPosition(176, 128);
earth.setScale(8, 8);
rockets.resize(populationSize);
for (int i = 0; i < populationSize; i++)
{
Rocket rocket(stepLimit, rocketTexture);
rockets[i] = rocket;
}
}
void Application::pollEvents()
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case (sf::Event::Closed):
{
window.close();
}
}
}
}
void Application::run()
{
while (window.isOpen())
{
if (step < stepLimit)
{
step++;
}
else
{
step = 0;
geneticAlgorithm.createGenePool(rockets);
double avg = 0;
for (int i = 0; i < (int)rockets.size(); i++)
{
avg += rockets[i].getFitness();
}
std::cout << "avg: " << avg / rockets.size() << std::endl;
for (int i = 0; i < (int)rockets.size(); i++)
{
Rocket rocket(geneticAlgorithm.evolve(mutationRate), rocketTexture);
// Rocket rocket(stepLimit, rocketTexture);
rockets[i] = rocket;
}
}
pollEvents();
window.clear();
for (int i = 0; i < populationSize; i++)
{
rockets[i].calculateFitness(asteroid);
if (step < stepLimit)
{
rockets[i].update(step);
}
rockets[i].collision(earth, asteroid);
window.draw(rockets[i]);
}
window.draw(earth);
window.draw(asteroid);
window.display();
}
}