-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrocket.cpp
More file actions
120 lines (97 loc) · 2.29 KB
/
rocket.cpp
File metadata and controls
120 lines (97 loc) · 2.29 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
/**
rocket.cpp
Purpose: Rocket capable of learning through genetic algorithms.
@author Joshua Varga
@version 1.0
*/
#include "rocket.h"
double Rocket::heading(sf::Vector2f vector)
{
return (180 / M_PI) * atan2(vector.y, vector.x);
}
double Rocket::map(double x, double in_min, double in_max, double out_min, double out_max)
{
double slope = 1.0 * (out_max - out_min) / (in_max - in_min);
return out_min + slope * (x - in_min);
}
void Rocket::draw(sf::RenderTarget &target, sf::RenderStates states) const
{
target.draw(sprite, states);
}
Rocket::Rocket(int stepLimit, sf::Texture &texture)
{
position = sf::Vector2f(240, 624);
velocity = sf::Vector2f(0, 0);
sprite.setTexture(texture);
sprite.setPosition(position);
for (int i = 0; i < stepLimit; i++)
{
dna.push_back(sf::Vector2f((float)(rand() % 3 - 1), (float)(rand() % 3 - 1)));
}
}
Rocket::Rocket(std::vector<sf::Vector2f> newDna, sf::Texture &texture)
{
position = sf::Vector2f(240, 624);
velocity = sf::Vector2f(0, 0);
sprite.setTexture(texture);
sprite.setPosition(position);
dna = newDna;
}
void Rocket::applyForce(sf::Vector2f force)
{
acceleration += force;
}
void Rocket::collision(sf::Sprite earth, sf::Sprite asteroid)
{
if (position.x < 0 || position.x > 480 || position.y < 0 || position.y > 640)
{
fitness -= 200;
crashed = true;
}
if (earth.getGlobalBounds().intersects(sprite.getGlobalBounds()))
{
fitness -= 200;
crashed = true;
}
if (asteroid.getGlobalBounds().intersects(sprite.getGlobalBounds()))
{
position = asteroid.getPosition();
sprite.setPosition(position);
fitness += 200;
crashed = true;
}
if (fitness < 0)
{
fitness = 0;
}
}
void Rocket::calculateFitness(sf::Sprite asteroid)
{
float distance = sqrt(pow((asteroid.getPosition().x - position.x), 2) +
pow((asteroid.getPosition().y - position.y), 2));
fitness = map(distance, 0, 640, 640, 0);
}
double Rocket::getFitness()
{
return fitness;
}
void Rocket::setFitness(double newFitness)
{
fitness = newFitness;
}
std::vector<sf::Vector2f> Rocket::getDna()
{
return dna;
}
void Rocket::update(int step)
{
if (!crashed)
{
applyForce(dna[step]);
velocity += acceleration;
position += velocity;
acceleration = sf::Vector2f(0, 0);
sprite.setPosition(position);
sprite.setRotation((float)(heading(velocity) + 90));
}
}