-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDroneSimulator.py
325 lines (275 loc) · 10.5 KB
/
DroneSimulator.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# coding=utf-8
"""
Structura:
Rows, Cols: dimensiunile hărții, nu se schimbă
X, Y: coordonatele curente ale dronei
Tx, Ty: coordonatele target-ului (nu se schimbă de-a lungul simulării)
NR_OBSTACOLE, urmează 2 x NR_OBSTACOLE cu coordonatele lor (nu se schimbă de-a lungul simulării)
NR_CETATENI, urmează 2 x NR_CETATENI cu coordonatele lor
NR_DRONE, urmează 2 x NR_DRONE celule cu coordonatele lor
[1] ROWS
[2] COLS
[3] x
[4] y
[5] Tx
[6] Ty
[7] No
[8] - [&Nc] 2xNo of < x,y> obstacole (&Nc = 8 + No + No)
[&Nc] Nc
[&Nc+1] - [&Nd] 2xNc of < x,y> cetateni (&Nd = &Nc + 1 + Nc + Nc
[&Nd] Nd
[&Nd+1] - [END] 2xNd of < x,y> drone
MAP EXAMPLE:
{
"simulatedDrone": {"type": "Drone", "identifier": "@", "position": {"x": 0, "y": 0}},
"map": {
"rows": 10,
"cols": 10,
"target": {"x": 5, "y": 7},
"objects": [
{"type": "Obstacle", "position": {"x": 2, "y": 0}},
{"type": "Obstacle", "position": {"x": 2, "y": 1}},
{"type": "Obstacle", "position": {"x": 2, "y": 2}}
]
}
}
"""
import json
import math
class DroneMemory:
ROWS = 1
COLS = 2
DX = 3
DY = 4
TX = 5
TY = 6
NOBS = 7
def __init__(self, mapfile):
self.memory = [0] * 1000000
self.mapfile = mapfile
self.cetateni = []
self.drone = []
self.cetidx = 0
self.map = []
self.loadmap(mapfile)
self.step = 0
def loadmap(self, mapfile):
self.map = json.load(open(mapfile, "r"))
self.memory[self.ROWS] = int(self.map['map']['rows'])
self.memory[self.COLS] = int(self.map['map']['rows'])
self.memory[self.DX] = int(self.map['simulatedDrone']['position']['x'])
self.memory[self.DY] = int(self.map['simulatedDrone']['position']['y'])
self.memory[self.TX] = int(self.map['map']['target']['x'])
self.memory[self.TY] = int(self.map['map']['target']['y'])
self.memory[self.NOBS] = len([item for item in self.map['map']['objects'] if item['type'] == 'Obstacle'])
# load the obstacles
idx = self.NOBS + 1
for object in self.map['map']['objects']:
if object['type'] == 'Obstacle':
self.memory[idx] = int(object['position']['x'])
self.memory[idx + 1] = int(object['position']['y'])
idx += 2
self.cetidx = idx
self.cetateni = [item for item in self.map['map']['objects'] if item['type'] == 'Cetatean']
self.drone = [item for item in self.map['map']['objects'] if item['type'] == 'Drone'] + [self.map['simulatedDrone']]
self.update_toti_dusmanii()
def update_toti_dusmanii(self):
idx = self.update_inamici(self.cetidx, self.cetateni)
idx = self.update_inamici(idx, self.drone)
def refresh(self):
self.step += 1
if 'steps' in self.map and \
self.step in [item['stepNumber'] for item in self.map['steps']]:
crtstep = next(item for item in self.map['steps'] if item['stepNumber'] == self.step)
self.cetateni = self.cetateni + [item for item in crtstep['objects'] if item['type'] == 'Cetatean']
toremove = []
for cetatean in self.cetateni:
x = cetatean['position']['x']
y = cetatean['position']['y']
moves = {
'RIGHT': {'x': 1, 'y': 0},
'DOWN': {'x': 0, 'y': 1},
'LEFT': {'x': -1, 'y': 0},
'UP': {'x': 0, 'y': -1}
}
cetatean['position']['x'] += moves[cetatean['direction']]['x']
cetatean['position']['y'] += moves[cetatean['direction']]['y']
if cetatean['position']['x'] < 0 or \
cetatean['position']['y'] < 0 or \
cetatean['position']['x'] >= self.memory[self.COLS] or \
cetatean['position']['y'] >= self.memory[self.ROWS]:
toremove.append(cetatean)
self.cetateni = [item for item in self.cetateni if item not in toremove]
self.update_toti_dusmanii()
def update_inamici(self, idx, inamici):
self.memory[idx] = len(inamici)
idx += 1
for object in inamici:
if object['identifier'] == '@':
self.memory[idx] = self.memory[DroneMemory.DX]
self.memory[idx + 1] = self.memory[DroneMemory.DY]
else:
self.memory[idx] = int(object['position']['x'])
self.memory[idx + 1] = int(object['position']['y'])
idx += 2
return idx
@property
def memory(self):
return self.memory
def dumpMemoryMatrix(self, start, rows, cols):
for y in range(0, rows):
line = ''
for x in range(0, cols):
if (x - 1) == self.memory[DroneMemory.DX] and \
(y - 1) == self.memory[DroneMemory.DY]:
chdisp = '@@'
else:
chdisp = str(self.memory[start + y * cols + x])
line += '{0:>3}'.format(chdisp)
print line
class DroneSimulator:
def __init__(self, asm):
self.asm = asm
self.done = False
self.memory = None
self.regA = 0
self.regN = 0
self.__status = ''
self.moves = 0
self.CPU = 0
def getscore(self, probnum):
if probnum > 6:
probnum *= 2
return probnum * 10000 / math.log((self.moves**2)*self.CPU)
@property
def status(self):
return self.__status
@property
def drone_x(self):
return self.memory[DroneMemory.DX]
@property
def drone_y(self):
return self.memory[DroneMemory.DY]
def memupdate(self, mem):
self.memory = mem
def updatePosition(self):
moves = {
0 : {'x' : 0, 'y' : 0},
1 : {'x' : 0, 'y' : -1},
2 : {'x' : 1, 'y' : 0},
3 : {'x' : 0, 'y' : 1},
4 : {'x' : -1, 'y' : 0}
}
self.memory[DroneMemory.DX] += moves[self.memory[0]]['x']
self.memory[DroneMemory.DY] += moves[self.memory[0]]['y']
def checkTarget(self):
return self.memory[DroneMemory.DX] == self.memory[DroneMemory.TX] and \
self.memory[DroneMemory.DY] == self.memory[DroneMemory.TY]
def checkBounds(self):
return self.memory[DroneMemory.DX] < 0 or \
self.memory[DroneMemory.DY] < 0 or \
self.memory[DroneMemory.DX] >= self.memory[DroneMemory.COLS] or \
self.memory[DroneMemory.DY] >= self.memory[DroneMemory.ROWS]
def checkObstacles(self):
obsaddress = DroneMemory.NOBS + 1
for i in range(0, self.memory[DroneMemory.NOBS]):
if self.memory[DroneMemory.DX] == self.memory[obsaddress + 2 * i] and \
self.memory[DroneMemory.DY] == self.memory[obsaddress + 2 * i + 1]:
return True
return False
def checkCetateni(self):
cetaddress = DroneMemory.NOBS + self.memory[DroneMemory.NOBS] * 2 + 1
for i in range(0, self.memory[cetaddress]):
cetx = self.memory[cetaddress + 1 + 2 * i]
cety = self.memory[cetaddress + 1 + 2 * i + 1]
if abs(self.memory[DroneMemory.DX] - cetx) <= 3 and \
abs(self.memory[DroneMemory.DY] - cety) <= 3:
return True
return False
def step(self):
self.moves += 1
next = self.sim(self.asm[0])
while next > -1:
if next == 380: # crude breakpoint method: change the number and ste a breakpoint to 'pass'
pass
next = self.sim(self.asm[next])
self.updatePosition()
self.done = True
if self.checkTarget():
self.__status = 'Success!'
elif self.checkBounds():
self.__status = 'Out of map bounds!'
elif self.checkObstacles():
self.__status = 'Destroyed by collision with obstacle!'
elif self.checkCetateni():
self.__status = 'A cetatean has slingshot your ass!'
else:
self.done = False
def sim(self, instr):
self.CPU += 1
#self.tracepresim(instr)
retval = getattr(self, "sim" + instr.name)(instr)
#self.tracepresim(instr)
return retval
def tracepresim(self, instr):
around = 0
first = max(0, instr.lineno - around)
last = min(len(self.asm) - 1, instr.lineno + around)
#print '\n'
for i in range(first, last + 1):
pointer = ' '
dbgins = self.asm[i]
if instr.lineno == i:
pointer = '>'
instrtext = pointer + str(dbgins.lineno) + ": " + \
dbgins.name + ' ' + str(dbgins.humanparam) + ':' + \
str(self.value(dbgins.param))
print '{0:40} {1}'.format(instrtext, str(dbgins.macro))
pass
def address(self, param):
return int(param[1:-1])
def setmemval(self, addr, val):
if addr < 0:
raise ValueError("Invalid set from addr + [" + str(addr) + "]")
else:
self.memory[addr] = val
def getmemval(self, addr):
if addr < 0:
raise ValueError("Invalid get from addr + [" + str(addr) + "]")
else:
return self.memory[addr]
def value(self, param):
if param == '[N]':
return self.getmemval(self.regN)
elif isinstance(param, str) and len(param) > 0 and param[0] == '[':
return self.getmemval(self.address(param))
else:
try:
return int(param)
except ValueError:
return -999999
def simLDA(self, instr):
self.regA = self.value(instr.param)
return instr.lineno + 1
def simSTA(self, instr):
if instr.param == '[N]':
self.setmemval(self.regN, self.regA)
else:
self.setmemval(self.address(instr.param), self.regA)
return instr.lineno + 1
def simLDN(self, instr):
self.regN = self.value(instr.param)
return instr.lineno + 1
def simSUBA(self, instr):
self.regA -= self.value(instr.param)
return instr.lineno + 1
def simADDA(self, instr):
self.regA += self.value(instr.param)
return instr.lineno + 1
def simJGE(self, instr):
if self.regA < 0:
return instr.lineno + 1
else:
return self.value(instr.param)
def simHLT(self, instr):
return -1