-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulation.py
117 lines (90 loc) · 3.44 KB
/
simulation.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import pygame
import pymunk
import pymunk.pygame_util
import math
from organism import Organsim
import neat
def run(sim_instance):
running = True
sim_instance.createBoundaries()
new_org = Organsim(sim.space, sim.width, sim.height)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
break
new_org.moveHuman(event)
print(new_org.getState())
sim.fpsCheck()
sim_instance.draw()
sim.step()
pygame.quit()
class Simulation:
def __init__(self, width, height, fps, dt=None):
pygame.init()
self.width = width
self.height = height
self.window = pygame.display.set_mode((width, height))
self.fps = fps
self.run = True
self.dt = 1/fps
if dt:
self.dt = dt
self.clock = pygame.time.Clock()
self.space = pymunk.Space()
self.space.gravity = (0, 981)
self.draw_options = pymunk.pygame_util.DrawOptions(self.window)
def draw(self):
self.window.fill("white")
self.space.debug_draw(self.draw_options)
pygame.display.update()
def step(self):
self.space.step(self.dt)
def pauseDraw(self):
self.window.fill("black")
pygame.display.update()
def createBoundaries(self):
rects = [
[( self.width/2, self.height-(self.width/100)), (self.width, (self.width/100) * 2)],
[( self.width/2, (self.width/100)), (self.width, (self.width/100)*2)],
[((self.width/100), self.height/2), ((self.width/100)*2, self.height)],
[( self.width - (self.width/100), self.height/2), ((self.width/100)*2, self.height)]
]
for pos, size in rects:
body = pymunk.Body(body_type=pymunk.Body.STATIC)
body.position = pos
shape = pymunk.Poly.create_box(body, size)
shape.elasticity = 0.4
shape.friction = 0.5
self.space.add(body, shape)
def fpsCheck(self):
self.clock.tick(self.fps)
def getFps(self):
return self.clock.get_fps()
def trainAIBootleg(self, networks):
frame_count = 0
run = True
self.createBoundaries()
organisms = [Organsim(self.space, self.width, self.height) for network in networks]
while run:
if frame_count > 300:
fitness = []
for organism in organisms:
fitness.append(organism.getFitness())
return fitness
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
for i, organism in enumerate(organisms):
inputs = organism.getState()
output = networks[i].activate(inputs)
organism.moveAI(output, force_multiplier=0.1)
self.step()
self.fpsCheck()
#print(self.getFps())
self.draw()
frame_count += 1
if __name__ == "__main__":
sim = Simulation(1000, 800, 60)
sim.trainAIBootleg([1,2])
#run(sim)