-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
202 lines (189 loc) · 8.07 KB
/
main.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""
Bot Evolution v1.1
"""
import os
import sys
import pickle
import pygame as pg
from pygame.locals import *
import numpy as np
import datetime
import settings
import populationk
import random
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=gpu,floatX=float32"
import theano
def main():
np.random.seed()
pg.init()
# Initialize runtime variables.
periodically_save = raw_input("Use saved data?")
if periodically_save.lower() in ("y", "yes"):
periodically_save = True
else:
periodically_save = False
# print periodically_save
pop = None
if periodically_save and os.path.isfile("save.txt"):# and input("Save file detected! Use it? (y/n): ").lower() == 'y':
settings.FPS, settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT, settings.TIME_MULTIPLIER, pop = pickle.load(open("save.txt", "rb"))
# print "Using saved data!"
else:
pop_size = 10
mutation_rate = 0.5
no_food = pop_size/2
# while True:
# pop_size = int(input("Population size: "))
# if pop_size < 5:
# # print("Population size must be at least 5!")
# else:
# break
# while True:
# mutation_rate = float(input("Mutation rate: "))
# if mutation_rate <= 0 or mutation_rate >= 1:
# # print("Mutation rate must be in the range (0, 1)!")
# else:
# break
# while True:
# settings.TIME_MULTIPLIER = float(input("Time multiplier: "))
# if settings.TIME_MULTIPLIER < 1:
# # print("Time multiplier must be at least 1!")
# else:
# break
# adv = input("Advance options? (y/n): ")
# if adv == "y":
# while True:
# settings.FPS = int(input("Frames per second: "))
# if settings.FPS < 1:
# # print("FPS must be at least 1!")
# else:
# break
# while True:
# settings.WINDOW_WIDTH = int(input("Window width: "))
# if settings.WINDOW_WIDTH < 50:
# # print("Window width must be at least 50!")
# else:
# break
# while True:
# settings.WINDOW_HEIGHT = int(input("Window height: "))
# if settings.WINDOW_HEIGHT < 50:
# # print("Window height must be at least 50!")
# else:
# break
pop = populationk.Population(pop_size, mutation_rate, no_food)
# if input("Periodically save every half hour? (y/n): ").lower() == 'y':
# periodically_save = True
print("\nNote: ")
print("\tPress 'r' to reset the populationk.")
print("\tPress 'p' to pause / unpause.")
print("\tPress 's' to save populationk's data (for use next time).")
print("\tPress 'q' to quit.")
print("\tPress 'up' / 'down' to change the populationks mutation rate.")
print("\tPress 'left' / 'right' to change the time multiplier.")
print("\tClick on the screen to lay down food.")
# Core variables.
FONT_SIZE = 30
FONT = pg.font.SysFont("Arial", FONT_SIZE)
fps_clock = pg.time.Clock()
window = pg.display.set_mode((settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT))
pg.display.set_caption("Bot Evolution")
# Main loop.
dt = 0.0
fps_clock.tick(int(settings.FPS / (settings.TIME_MULTIPLIER / 5.0 + 1)))
paused = False
while True:
key_pressed = {"up": False, "down": False, "left": False, "right": False}
for event in pg.event.get():
if event.type == QUIT:
pop.save_strongest_bots()
pg.quit()
sys.exit()
elif event.type == pg.KEYDOWN:
if event.key == pg.K_r:
pop = populationk.Population(pop.SIZE, pop.mutation_rate)
if event.key == pg.K_s:
pickle.dump([settings.FPS, settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT, settings.TIME_MULTIPLIER, pop], open("save.txt", "wb"))
if event.key == pg.K_p:
paused = not paused
if event.key == pg.K_q:
pop.save_strongest_bots()
pg.quit()
sys.exit()
elif event.type == pg.MOUSEBUTTONUP:
pos = pg.mouse.get_pos()
pop.food.pop(random.randint(0, len(pop.food)-1))
food = populationk.Food(pop)
food.x = pos[0]
food.y = pos[1]
pop.food.append(food)
if paused:
dt = fps_clock.tick(int(settings.FPS / (settings.TIME_MULTIPLIER / 5.0 + 1))) / 1000.0 * int(settings.FPS / (settings.TIME_MULTIPLIER / 5.0 + 1))
continue
if periodically_save and datetime.datetime.now().minute % 30 == 0:
pickle.dump([settings.FPS, settings.WINDOW_WIDTH, settings.WINDOW_HEIGHT, settings.TIME_MULTIPLIER, pop], open("save.txt", "wb"))
keys = pg.key.get_pressed()
if keys[pg.K_UP]:
key_pressed["up"] = True
if keys[pg.K_DOWN]:
key_pressed["down"] = True
if key_pressed["up"] and key_pressed["down"]:
key_pressed["up"] = False
key_pressed["down"] = False
if keys[pg.K_LEFT]:
key_pressed["left"] = True
if keys[pg.K_RIGHT]:
key_pressed["right"] = True
if key_pressed["left"] and key_pressed["right"]:
key_pressed["left"] = False
key_pressed["right"] = False
update(dt, pop, key_pressed)
window.fill((0, 0, 0))
render(window, FONT, pop)
pg.display.update()
dt = fps_clock.tick(int(settings.FPS / (settings.TIME_MULTIPLIER / 5.0 + 1))) / 1000.0 * int(settings.FPS / (settings.TIME_MULTIPLIER / 5.0 + 1))
display_time_remaining = 0.0
def update(dt, pop, key_pressed):
global display_time_remaining
if key_pressed["up"] or key_pressed["down"] or key_pressed["left"] or key_pressed["right"]:
display_time_remaining = 3.0
if key_pressed["up"]:
pop.mutation_rate += 0.001
elif key_pressed["down"]:
pop.mutation_rate -= 0.001
if pop.mutation_rate <= 0:
pop.mutation_rate = 0.001
elif pop.mutation_rate >= 1:
pop.mutation_rate = 0.999
if key_pressed["left"]:
settings.TIME_MULTIPLIER -= 0.1
elif key_pressed["right"]:
settings.TIME_MULTIPLIER += 0.1
if settings.TIME_MULTIPLIER < 1:
settings.TIME_MULTIPLIER = 1.0
else:
display_time_remaining -= 1.0 / settings.FPS * dt
if display_time_remaining < 0:
display_time_remaining = 0.0
pop.update(dt)
def render(window, FONT, pop):
for food in pop.food:
pg.draw.circle(window, food.RGB, (int(food.x), int(food.y)), food.HITBOX_RADIUS)
for bot in pop.bots:
# Draw body.
# print bot.RGB
pg.draw.circle(window, bot.RGB, (int(bot.x), int(bot.y)), bot.HITBOX_RADIUS)
# Draw field-of-vision lines.
LINE_THICKNESS = 1
PROTRUSION = int(bot.HITBOX_RADIUS * 1.5)
to_x = int(bot.x + (bot.HITBOX_RADIUS + PROTRUSION) * np.cos(bot.theta - bot.FIELD_OF_VISION_THETA / 2))
to_y = int(bot.y - (bot.HITBOX_RADIUS + PROTRUSION) * np.sin(bot.theta - bot.FIELD_OF_VISION_THETA / 2))
pg.draw.line(window, bot.RGB, (bot.x, bot.y), (to_x, to_y), LINE_THICKNESS)
to_x = int(bot.x + (bot.HITBOX_RADIUS + PROTRUSION) * np.cos(bot.theta + bot.FIELD_OF_VISION_THETA / 2))
to_y = int(bot.y - (bot.HITBOX_RADIUS + PROTRUSION) * np.sin(bot.theta + bot.FIELD_OF_VISION_THETA / 2))
pg.draw.line(window, bot.RGB, (bot.x, bot.y), (to_x, to_y), LINE_THICKNESS)
if display_time_remaining > 0:
resultSurf = FONT.render("Mutation Rate: %.3f Speed: %.1fx" % (pop.mutation_rate, settings.TIME_MULTIPLIER), True, (255, 255, 255))
resultRect = resultSurf.get_rect()
resultRect.topleft = (25, 25)
window.blit(resultSurf, resultRect)
if __name__ == "__main__":
main()