/
viz.py
269 lines (217 loc) · 10.4 KB
/
viz.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
import Tkinter as tk
import numpy as n
import Desert as des
from DesertAgent import State as state
import random as r
import Ant as a
import HiveClass as hive
#==========User Adjusatable===================
SIM_LENGTH = 364 #How many ticks in a simulation
DESERT_SIZE = 50 #Size of desert
NUM_HIVES = 4 #How many hives
AMT_ANTS_PER_HIVE = 20 #How many ants start in each hive
#============================================
DESSICATION_LEVEL = 1 #Level an ant dies of thirst
STARVATION_LEVEL = 1 #Level an ant dies of starvation
MAX_FOOD_WHATER = 1 #Maximum level of food and water an ant can carry
MOISTURE_FROM_FOOD = 1 #Moisture gained from eating
# Controls the simulation. Allows you to run sims and change various variables.
class viz:
def __init__(self, dim, window_width, window_height, delay):
self.wWidth = window_width
self.dim = dim
self.root=tk.Tk()
c = tk.Canvas(self.root,width=window_width * 1.2,height=window_height * 1.2)
c.pack()
canvas = c
self.canvas = c
self.size_ratio = (self.wWidth / self.dim) * .8
self.text_width = window_width * 1.2
self.text_height = window_height * 1.2
self.wHeight = window_height
self.cell = n.empty((self.dim, self.dim), dtype=object)
self.text_cells = n.empty((self.dim + 10, self.dim + 10), dtype=object)
self.__setup_grid__()
self.delay = delay
self.running = True
self.labels = None
self.number_labels = 3
self.tick = 0
# the enviorment is a grid of DesertAgent
# 0: desert
# 1: food
# 2: water
# 3: hive
# function that is called by the tkinter canvas that updates ojects in sim every frame
def update_frame(self,enviornment):
#print enviornment.get_season()
for i in range(self.dim):
for j in range(self.dim):
curr_agent = enviornment.getItem(j,i)
enviornment_type = curr_agent.getState()
#print enviornment_type
if (curr_agent.battle):
self.canvas.itemconfig(self.cell[i,j], fill="black")
elif enviornment_type is state.DESERT:
self.canvas.itemconfig(self.cell[i,j], fill="yellow")
elif enviornment_type is state.FOOD:
color = self.get_food_color_intensity(curr_agent.getFood())
self.canvas.itemconfig(self.cell[i,j], fill= color)
elif enviornment_type is state.WATER:
self.canvas.itemconfig(self.cell[i,j], fill="blue")
elif enviornment_type is state.HIVE:
self.canvas.itemconfig(self.cell[i,j], fill="brown")
else:
self.canvas.itemconfig(self.cell[i,j], fill="green")
for i in range(len(enviornment.getHives())):
hives = enviornment.getHives()
label_string_desert = "Number of ants in Desert " + str(enviornment.get_number_ants_in_desert())
label_string = "Number of ants in Hive " + str(i + 1) + " " + str(len(hives[i].list_ants))
food_label_string = "Food Level of Hive " + str(i + 1) + " " + str(round(hives[i].getFoodLevel(),3))
self.canvas.itemconfig(self.labels[2 * i], text=label_string)
self.canvas.itemconfig(self.labels[2*i+1], text=food_label_string)
self.canvas.itemconfig(self.labels[2*i+2], text=label_string_desert)
def create_labels(self,env):
labels = []
hives = env.getHives()
for i in range(self.number_labels):
labels.append( self.canvas.create_text(1000, 800 + 15 *3* i, anchor="s"))
labels.append( self.canvas.create_text(1000, 815 +15*3* i, anchor="s"))
labels.append( self.canvas.create_text(1000, 830 +15* 3* i, anchor="s"))
#print labels
self.labels =labels
def create_stat_labels(self,env):
self.create_labels(env)
def get_food_color_intensity(self, greenVal):
rgb = (0,255-greenVal*100,0)
return '#%02x%02x%02x' % rgb
def __setup_grid__(self):
for i in range(self.dim):
for j in range(self.dim):
self.cell[i, j] = self.canvas.create_rectangle(self.size_ratio * j, self.size_ratio * i,
self.size_ratio * j+ self.size_ratio, self.size_ratio * i + self.size_ratio, outline="")
for i in range(self.dim + 10):
for j in range(self.dim + 10):
self.text_cells[i,j] = self.canvas.create_rectangle(0, self.text_width, 0, self.text_height, outline="")
def dispViz(self):
self.root.mainloop()
def draw_frame(self,enviorment):
self.update_frame(enviorment)
if self.running and self.tick <= SIM_LENGTH:
self.canvas.after(self.delay,self.Run_Sim, enviorment)
#stats_text = """
#-------------------
#| ------ line1 |
#| ------ line2 |
#| ------ line3 |
#-------------------"""
#legend_frame = tk.LabelFrame(self.canvas,text=stats_text,padx=5, pady=5)
#legend_label = tk.Label(legend_frame,text=stats_text)
#legend_label.pack()
#self.canvas.create_window(500,500,window=legend_frame,anchor="se")
#for i in enviorment.getHives():
# location = i.getLocation()
# ants = i.getAnts()
# canvas_id = self.canvas.create_text(location[0] * 10, location[1] * 10)
# self.canvas.itemconfig(canvas_id, text="Number of in this Hive" + str(len(ants)))
# self.canvas.insert(canvas_id, 6, "new ")
else :
self.dispViz()
# Runs a simulation. Initialize all values based on keywords if passed in.
# For each time tick, run phase 1-3. When the simulation runs to the
# variable sim_length, end it.
def Run_Sim(self, enviornment):
#print("Tick " + str(self.tick))
self.tick += 1
self.Phase_One(enviornment)
#print enviornment.getHives()
for i in enviornment.getHives():
#print i.getFoodLevel()
ants = i.getAnts()
i.update_nest()
number_of_gathers_to_create = i.dispatch_number_gathers()
if number_of_gathers_to_create is not None:
if(len(number_of_gathers_to_create) > 0):
self.create_ants(number_of_gathers_to_create, i.getLocation(), i, testEnviorment, a.JOB.GATHERER)
self.append_to_hive(number_of_gathers_to_create, i.getLocation(), i, testEnviorment, a.JOB.GATHERER)
number_of_soliders_to_create = i.dispatch_number_of_soliders()
if number_of_soliders_to_create is not None:
if(len(number_of_soliders_to_create) > 0):
self.create_ants(number_of_soliders_to_create, i.getLocation(), i, testEnviorment, a.JOB.WARRIOR)
# print ants
self.Phase_Two(ants,enviornment)
self.draw_frame(enviornment)
self.Phase_Three(enviornment)
# TODO
return
def ant_movement(self, ants,env):
#print ants[1]
for i in range(len(ants)):
[x,y] = ants[i].move( self.dim, env)
#print str(x) + " " + str(y)
self.canvas.move(ants[i].getShape(), self.size_ratio* x, self.size_ratio* y)
# Ants eat and drink. Eggs turn into pupae. Pupae grow up.
# The queen lays eggs based on amount of food in nest.
def Phase_One(self, enviornment):
enviornment.combat()
# TODO
return
# First - execute combat for the entire desert. Remove all ants destroyed.
# Second - move all ants based on caste, current job,
# and pheromones of neighbor cells.
def Phase_Two(self,ants,enviornment):
self.ant_movement(ants,enviornment)
# TODO
return
# Kill all dessicated and starving ants. Update desert (add/remove food
# and moisture based on season, remove hives with no ants, and update season)
def Phase_Three(self,enviornment):
enviornment.update_seasons()
rand = r.random()
enviornment.update_ants(self.canvas)
#if rand < .01:
# self.running = False
# TODO
return
def get_random_color(self):
# color changing from
# http://stackoverflow.com/questions/11340765/default-window-colour-tkinter-and-hex-colour-codes
rgb = tuple(n.random.randint(0,255, (3)))
return '#%02x%02x%02x' % rgb
def create_ants(self, testAnts, loc,myHive, myEnv, job):
color = myHive.get_color()
#print color
for i in n.arange(n.alen(testAnts)):
#print loc
testAnts[i] = a.ANT(loc[0],loc[1],0,0, self.canvas.create_rectangle(loc[0]*self.size_ratio ,loc[1] *self.size_ratio + self.size_ratio,(loc[0]*self.size_ratio),loc[1]*self.size_ratio,
outline = color), myHive, myEnv, job)
myEnv.set_number_ants_in_desert(1);
def append_to_hive(self, testAnts, loc,myHive, myEnv, job):
color = myHive.get_color()
for i in n.arange(n.alen(testAnts)):
myHive.setAnts(a.ANT(loc[0],loc[1],0,0, self.canvas.create_rectangle(loc[0]*self.size_ratio ,loc[1] *self.size_ratio + self.size_ratio,(loc[0]*self.size_ratio),loc[1]*self.size_ratio,
outline = color), myHive, myEnv, job))
def create_hive(self, myHive, location):
myHive = hive.Hive((location[0], location[1]))
return myHive
#def add_ant_from_hive(self, ANT_agent, Hive):
def getCanvas():
print viz.canvas
return viz.canvas
if __name__ == '__main__':
dim = DESERT_SIZE
num_ants_per_hive = AMT_ANTS_PER_HIVE
vizTest = viz(dim,1000,1000, 100)
amt_hives = NUM_HIVES
testEnviorment = des.Desert(dim,amt_hives)
#print testEnviorment.__str__()
hives = testEnviorment.getHives()
vizTest.create_stat_labels(testEnviorment)
print vizTest.canvas
for i in hives:
myAnts = n.empty(num_ants_per_hive, dtype=object)
i.set_color(vizTest.get_random_color())
vizTest.create_ants(myAnts, i.getLocation(), i, testEnviorment, a.JOB.GENERICINITIAL)
i.setAnts(myAnts)
vizTest.Run_Sim(testEnviorment)
vizTest.dispViz()