-
Notifications
You must be signed in to change notification settings - Fork 0
/
SnakeIA.cpp
129 lines (110 loc) · 2.25 KB
/
SnakeIA.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
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
//
// SnakeIA.cpp for Snake in /home/wilmot_p/PROJETS/Snake
//
// Made by WILMOT Pierre
// Login <[email protected]>
//
// Started on Fri Apr 27 13:17:08 2012 WILMOT Pierre
// Last update Mon May 7 10:00:09 2012 WILMOT Pierre
//
#include <iostream>
#include "SnakeIA.hpp"
#include "Map.hpp"
#define GENE_SIZE (256)
SnakeIA::SnakeIA()
{
char d[] = "UDRL";
for (int i(0); i < 5 ; ++i)
{
while (m_gene[i].size() != GENE_SIZE)
{
m_gene[i].push_back(d[rand() % 4]);
}
}
}
SnakeIA::SnakeIA(Snake const &a, Snake const &b)
{
std::string c;
std::string d;
for (int i(0); i < 5 ; ++i)
{
c = a.getGene(i);
d = b.getGene(i);
while (m_gene[i].size() != 256)
{
if (rand() % 2)
{
if ((m_gene[i].size()) % 2)
m_gene[i].push_back(c[m_gene[i].size()]);
else
m_gene[i].push_back(d[m_gene[i].size()]);
}
}
}
}
SnakeIA::SnakeIA(
std::string const &G1,
std::string const &G2,
std::string const &G3,
std::string const &G4,
std::string const &G5
)
{
std::cout << "Creating Snake from Database" << std::endl;
m_gene[0] = G1;
m_gene[1] = G2;
m_gene[2] = G3;
m_gene[3] = G4;
m_gene[4] = G5;
}
SnakeIA::~SnakeIA()
{
}
std::string SnakeIA::getGene(int i) const
{
return (m_gene[i]);
}
SnakeIA::e_Direction SnakeIA::getMove(Map const &m, Cdn<int> &head) const
{
unsigned int result(0);
unsigned int env[4];
env[0] = (m.return_env1(head));
env[1] = (m.return_env2(head));
env[2] = (m.return_env3(head));
env[3] = (m.return_env4(head));
int b(1);
for (int i(0) ; i < 4 ; ++i)
{
if (m_gene[i][env[i]] == 'U')
result += 0 * b;
if (m_gene[i][env[i]] == 'D')
result += 1 * b;
if (m_gene[i][env[i]] == 'R')
result += 2 * b;
if (m_gene[i][env[i]] == 'L')
result += 3 * b;
b *= 4;
}
if (m_gene[4][result] == 'U')
return (UP);
if (m_gene[4][result] == 'D')
return (DOWN);
if (m_gene[4][result] == 'R')
return (RIGHT);
if (m_gene[4][result] == 'L')
return (LEFT);
return (UP);
}
SnakeIA::e_Direction SnakeIA::getRandomMove() const
{
int i(rand() % 4);
if (i == 0)
return (UP);
if (i == 1)
return (DOWN);
if (i == 2)
return (LEFT);
if (i == 3)
return (RIGHT);
return (UP);
}