-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevel.py
More file actions
308 lines (279 loc) · 9.72 KB
/
Level.py
File metadata and controls
308 lines (279 loc) · 9.72 KB
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
import random
import Tile
import string
import math
import RobotAI
import socket
import threading
class Level():
def __init__(self,w,h):
self.width = w
self.height = h
self.loadLevelFromFile("levels/Arena.txt")
#self.generateLevel()
self.ticks=0
self.player = None
self.entities = []
self.hasAStarWorker = False
## self.workers = 1 #number of worker
## self.addr_list = [] #list of client addresses and connections
## self.HOST = ''
## self.PORT = 1337
## self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
## self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
## self.s.bind((self.HOST, self.PORT))
## self.sendTilesToAStarWorker()
## t = threading.Thread(target=self.listenForResult)
## t.start()
"""Populates the tiles list to hold the level data.
@Params:
path(string): path to level file
@Return:
None
"""
def loadLevelFromFile(self,path):
levelF = open(path,'r')
data = levelF.read()
x=-1
y=0
data = string.split(data,"@")
header = string.split(data[0],",")
self.width = int(header[0])
self.height = int(header[1])
self.tiles = [0]*(self.width*self.height)
for i in data[1]:
if i ==';':
x=-1
y+=1
continue
try:
self.setTile(x,y,Tile.tiles[Tile.getID(i)])
except:
pass
x+=1
"""Generates a random level
@Params:
None
@Return:
None
"""
def generateLevel(self):
for x in range(self.width):
for y in range(self.height):
self.tiles[x+(y*self.width)] = random.randint(1,4)
"""Updates the tiles and entities
@Params:
None
@Return:
None
"""
def tick(self):
self.ticks+=1
for e in self.entities:
e.tick()
for tile in Tile.tiles:
tile.tick()
for x in range(self.width):
for y in range(self.height):
if self.getTile(x,y).id== 5 and self.ticks%random.randint(1,10000)==0:
self.setTile(x,y,Tile.amberlight)
self.souroundingTiles(x,y,Tile.redlight,Tile.amberlight)
#self.sendChangeToWorker(x,y,Tile.greenlight)
if self.getTile(x,y).id== 9 and self.ticks%random.randint(1,10000)==0:
self.setTile(x,y,Tile.greenlight)
self.souroundingTiles(x,y,Tile.amberlight,Tile.greenlight)
if self.getTile(x,y).id== 6 and self.ticks%random.randint(1,10000)==0:
self.setTile(x,y,Tile.redlight)
self.souroundingTiles(x,y,Tile.greenlight,Tile.redlight)
#self.sendChangeToWorker(x,y,Tile.redlight)
"""recursively sets all identical surrounding tiles
to a new tile
@Params:
x(int): x co-ordinate of starting tile
y(int): y co-ordinate of starting tile
get(tile): tile to be changed
set(tile): tile to set
"""
def souroundingTiles(self,x,y, get,set):
for i in range(9):
dx = (i % 3) -1
dy = (i / 3) -1
if self.getTile(x+dx,y+dy).id== get.id:
self.setTile(x, y, set)
self.souroundingTiles(x+dx,y+dy,get,set)
"""Renders tiles and entities
@Params:
screen(pygame.surface): pygame surface to draw on to
xoff(int): x offset of the objects to render
yoff(int): y offset of the objects to render
@Return:
None
"""
def render(self,screen,xoff,yoff):
for x in range(self.width):
for y in range(self.height):
self.getTile(x,y).render(self,screen,(x<<5)-xoff,(y<<5)-yoff,x,y)
for e in self.entities:
e.render(screen,xoff,yoff)
"""changes to tile in level.tiles at index x+(y*level.width) to
tile.id
@Params:
x(int): x position of tile
y(int): y position of tile
tile(Tile): tile to set
@Return:
None
"""
def setTile(self,x, y, tile):
if x < 0 or y < 0 or x >= self.width or y >= self.height:
return
self.tiles[x+(y*self.width)] = tile.id
"""gets the tile form level.tiles
@Params:
x(int): x position of tile
y(int): y position of tile
@Return:
tile(Tile)
"""
def getTile(self,x,y):
if 0 > x or x >= self.width or 0 > y or y >= self.height:
return Tile.void
return Tile.tiles[self.tiles[x + y * self.width]]
"""gets distance between two points
@Params:
a(vec2): first point
b(vec2): second point
@Return:
distance(double): distance between a and b
"""
def getDistance(self,a,b):
dx = a[0] - b[0]
dy = a[1] - b[1]
return math.sqrt(dx*dx+dy*dy)
"""returns true if i is in list l
@Params:
l(list): list to check
i(object): object to look for
@Return:
inList(boolean): true if i is in l
"""
def inList(self,l,i):
for node in l:
if node.pos == i:
return True
return False
"""gets the best option from list l
@Params:
l(list): list of nodes
@Return:
bestNode(Node): node with lowest cost fo far
"""
def lookForFastest(self,l):
currentSmallest =0
bestNode = None
if len(l)==1:
return l[0]
for i in l:
if i.costSoFar<currentSmallest or currentSmallest==0:
currentSmallest =i.costSoFar
bestNode = i
return bestNode
"""finds the fastest path between two points
@Params:
start(vec2): starting point
goal(vec2): end point
@Return:
path(Node): next node to move to
"""
def findPath(self,start,goal):
distance_from_start = {}
path_from_start[start] = 0
open_list = [start]
distance_from_start[start] = 0
path_from_start[start] = [start]
while len(open_list) > 0:
current = open_list[0]
open_list.remove(open_list[0])
for neighbour in self[current].keys():
if neighbour not in distance_from_start:
distance_from_start[neighbour] = distance_from_start[current] + 1
if neighbour == goal:
return distance_from_start[goal]
open_list.append(neighbour)
return False
#print "No path :("
#return None
"""sends tiles to A* worker
@Params:
None
@Params:
None
"""
def sendTilesToAStarWorker(self):
self.s.listen(self.workers) #Listens for (n) number of client connections
print 'Waiting for client...'
for i in range(self.workers): #Connects to all clients
conn, addr = self.s.accept() #Accepts connection from client
print 'Connected by', addr
self.addr_list.append((conn,addr)) #Adds address to address list
print "connected!",conn,addr
for i in range(self.workers): #Converts array section into string to be sent
data = self.tiles
data.append(self.width)
data.append(self.height)
arraystring = repr(data)
conn.sendto(arraystring , self.addr_list[i][1]) #Sends array string
print 'Tiles sent to worker'
self.hasAStarWorker = True
"""sends updates to A* workers
@Params:
x(int): x pos of tile
y(int): y pos of tile
tile(Tile): tile that has changed
@Return:
None
"""
def sendChangeToWorker(self,x,y,tile):
for i in range(self.workers): #Converts array section into string to be sent
data = ["c"]
data.append(x)
data.append(y)
data.append(tile.id)
arraystring = repr(data)
self.addr_list[i][0].sendto(arraystring , self.addr_list[i][1])
"""requests an update from the A* worker
@Params:
workerID(int): id of the worker
start(vec2): start of path
goal(vec2): end of path
@Return:
None
"""
def requestAStar(self,workerID,start,goal):
arraystring = repr([start,goal])
worker_add = self.addr_list[workerID][0]
worker_add .sendto( arraystring , self.addr_list[workerID][1] ) #Sends array string
print 'requesting A*!'
"""Listens to result from A* worker
@Params:
None
@Return:
None
"""
def listenForResult(self):
while True:
for i in range(self.workers): #Receives sorted sections from each client
arraystring = ''
print 'Receiving data from clients...'
while 1:
data = self.addr_list[i][0].recv(4096) #Receives data in chunks
print "Recieved:",data
data = eval(data)
self.entities[i].path = [Node((int(data[0]),int(data[1])),None,0,0)]
class Node(object):
def __init__(self,pos,parent,costSoFar,distanceToEnd):
self.pos = pos
self.parent = parent
self.costSoFar = costSoFar
self.distanceToEnd = distanceToEnd
self.totalCost = distanceToEnd +costSoFar