-
Notifications
You must be signed in to change notification settings - Fork 0
/
ant.py
executable file
·93 lines (66 loc) · 2.75 KB
/
ant.py
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
import pyglet as _pyglet
from vector import Vector as _Vector
from ffnn.neuralnet import NeuralNet as _NeuralNet
ANT_IMAGE = "resources/images/ant.png"
PRO_ANT_IMAGE = "resources/images/ant-good.png"
def load_centered_image(image_path):
image = _pyglet.image.load(image_path)
image.anchor_x = image.width // 2
image.anchor_y = image.height // 2
return image
class Ant(_pyglet.sprite.Sprite):
image = load_centered_image(ANT_IMAGE)
pro_image = load_centered_image(PRO_ANT_IMAGE)
def __init__(self, parent_window, pos, move_vec, batch=None):
super(Ant, self).__init__(Ant.image, pos[0], pos[1], batch=batch)
self.parent_window = parent_window
self.scale = 0.4
self.radius = Ant.image.width/2 * self.scale
self.look_vector = move_vec
self.pos = _Vector(pos[0], pos[1], True)
self.speed = 5
self.rrate = 40
self.neural_net = _NeuralNet(4, 2, [6])
self.score = 0
def updateImage(self, is_pro):
if is_pro:
self.image = Ant.pro_image
else:
self.image = Ant.image
def update(self, dt, food):
closest_food = self.getClosestFoodVec(food);
ltrack, rtrack = self.neural_net.GetOutput((self.look_vector.x,
self.look_vector.y,
closest_food.x,
closest_food.y))
r_rate = (rtrack - ltrack ) * self.rrate
self.look_vector.magnitude = (rtrack + ltrack) / 2 * self.speed
self.look_vector.angle += r_rate
self.rotation = 90 - self.look_vector.angle
self.pos[0] += self.look_vector[0] * dt
self.pos[1] += self.look_vector[1] * dt
self.x = self.pos.x
self.y = self.pos.y
# Clamping/wrapping
if self.pos.x > self.parent_window.width: self.pos.x = 0
if self.pos.x < 0: self.pos.x = self.parent_window.width
if self.pos.y > self.parent_window.height: self.pos.y = 0
if self.pos.y < 0: self.pos.y = self.parent_window.height
def collidesWith(self, other_ant):
if (other_ant.pos-self.pos).magnitude < (other_ant.radius+self.radius):
return True
else:
return False
def getClosestFood(self, food):
closest = None
for f in food:
if closest == None or \
(self.pos - f.pos).magnitude < (self.pos-closest).magnitude:
closest = f.pos
return closest
def getClosestFoodVec(self, food):
closest = None
for f in food:
if closest == None or (self.pos-f.pos).magnitude < closest.magnitude:
closest = self.pos-f.pos
return closest