evo / server / server.py

The default branch has multiple heads

  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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from collections import deque
from random import random, randint

# Tornado server for drumcircle xml

from tornado.options import define, options

define("port", default=8888, help="run on the given port", type=int)
define("history", default='history.log', help="history log filename", type=str)
define("database", default='database.db', help="database filename", type=str)
define("tanks", default=5, help="number of tanks", type=int)
define("specs", default=10, help="species per tank", type=int)
define("giants", default=0, help="how many giants?", type=int)
define("debug", default=0, help="debug runlevel", type=int)
define("debug_delay", default=0, help="debug: fake response delay", type=float)
define("debug_failure", default=0, help="debug: fake request failure", type=int)

history_file = None
history_dom = None

class MainHandler(tornado.web.RequestHandler):
	def get(self):
		self.write("Nothing is here.")

# levelution 

import traceback
import xml.dom.minidom
import time

AIR="a"
WALL="b"
LAVA="c"

PLAYER=1
EXIT=2

def randomfrom(s):
	return s[randint(0,len(s)-1)]

def randomfromdict(s):
	return s[randomfrom(s.keys())]

class Board:
	def __init__(self, xdim = 24, ydim = 24, suppress = False):
		self.xdim = xdim
		self.ydim = ydim
		if not suppress:
			self.basic()
			self.noise(10, WALL)
			self.noise(3, LAVA)
			self.px = randint(1,self.xdim-2)
			self.py = self.ydim-2
			self.ex = randint(1,self.xdim-2)
			self.ey = randint(2,4)
		
	def clone(self):
		c = Board(self.xdim,self.ydim, True)
		c.str = list(self.str)
		c.px = self.px
		c.py = self.py
		c.ex = self.ex
		c.ey = self.ey
		return c
	
	def basic(self):
		cap = [WALL] * self.xdim
		mid = [WALL] + [AIR]*(self.xdim-2) + [WALL]
		self.str = cap + mid*(self.ydim-2) + cap
	
	def recombine(self, fwb):
		i = 0
		strmax = len(fwb.str)
		while i < strmax:
			if self.str[i] != AIR or fwb.str[i] != AIR:
				prefer_fwb = random() < 0.5
				if prefer_fwb:
					prefer = fwb.str
				else:
					prefer = self.str
				i2 = 1
				while not (i+i2 >= strmax or (i+i2)%self.xdim == 0 or prefer[i+i2] == AIR):
					i2 += 1
				if prefer_fwb:
					self.str[i:i+i2] = prefer[i:i+i2]
				i += i2
			else:
				i += 1
		return self
	
	def mutate(self):
		self.noise(1, WALL)
		self.noise(1, AIR)
		if random()<0.3:
			self.noise(1,LAVA)
			self.noise(1,AIR)
		return self
	
	# Dust, don't flip
	def noise(self, c, what):
		for i in range(c):
			x = randint(1,self.xdim-2)
			y = randint(1,self.ydim-2)
			e = randint(1,self.xdim/4)
			x -= e/2
			for i2 in range(e):
				x2 = x+i2
				if x2 >= 1 and x2 < self.xdim-1:
					self.set(y,x2,what)
	
	def clear(self):
		self.str = AIR * (self.xdim*self.ydim)
	
	def i(self, x,y):
		return x*self.xdim+y
	
	def get(self, x,y):
		return self.str[self.i(x,y)]
	
	def set(self, x,y,v):
		self.str[self.i(x,y)] = v
		
	def xml(self, doc, r):
		r.setAttribute("map",''.join(self.str))
		r.setAttribute("mapx",str(self.xdim))
		r.setAttribute("mapy",str(self.ydim))
		e = doc.createElement("e")
		def add(doc, e, x, y, c):
			n = doc.createElement("nil")
			n.setAttribute("x", str(x))
			n.setAttribute("y", str(y))
			n.setAttribute("c", str(c))
			e.appendChild(n)
		add(doc,e,self.px,self.py,"1")
		add(doc,e,self.ex,self.ey,"2")
		r.appendChild(e)
		return r
	
class Spec:
	def __init__(self, gid, suppress = False):
		self.gid = gid
		self.sid = -1
		self.checked = False
		self.won = False
		if not suppress:
			self.board = Board()
		
	def clone(self):
		c = Spec(self.gid, True)
		c.board = self.board.clone()
		return c
		
	def mutate(self):
		self.board.mutate()
		return self
		
	def recombine(self, fwb):
		self.board.recombine(fwb.board)
		return self
		
	def xml(self, doc, r):
		r.setAttribute("gid", str(self.gid))
		r.setAttribute("sid", str(self.sid))
		self.board.xml(doc,r)
		
	def archive_xml(self, doc, r):
		slo = history_dom.createElement("spawn")
		slo.setAttribute("sid",str(self.sid))
		self.board.xml(doc,slo)
		r.appendChild(slo)
		
	def report(self, post_obj):
		self.checked = True
		if post_obj.hasAttribute("won") and int(post_obj.getAttribute("won")):
			self.won = True
			self.deaths = int(post_obj.getAttribute("deaths"))
			self.lastf = int(post_obj.getAttribute("lastf"))
		if history_file:
			history_file.write(post_obj.toxml())
			history_file.write("\n")
	
class Genome:
	def __init__(self, _id):
		self.id = _id
		self.specs = {} # Unordered
		self.specs_stack = [] # Ordered
		basic = Spec(self.id)
		self.issue_next = 0
		self.generation_count = 1
		self.id_generator = 0
		for i in range(options.specs):
			nid = self.nextid()
			s = basic.clone().mutate()
			s.sid = nid
			self.specs[nid] = s
			self.specs_stack.append(s)
		self.last_valid = self.specs_stack[0]
		self.specs_stack.reverse()

	def nextid(self):
		self.id_generator += 1
		return self.id_generator

	def any(self):
		if len(self.specs_stack) == 0:
			old_specs_list = self.specs.values()
			new_specs_list = old_specs_list # Do a funny dance so we can recover if there's an exception.
			new_specs = self.specs
			try:
				def fitness(x,y): # resort by these criteria
					if not (x.checked or y.checked):
						return 0
					if not (x.won or y.won):
						return 0
					if not x.checked or not x.won:
						return 1
					if not y.checked or not y.won:
						return -1
					if x.deaths != y.deaths:
						return cmp(x.deaths, y.deaths)
					return cmp(x.lastf, y.lastf) # Last ditch
				sorted_old_specs_list = sorted(old_specs_list, cmp=fitness)
				if sorted_old_specs_list[0].checked and sorted_old_specs_list[0].won:
					winner1 = sorted_old_specs_list[0]
					winner2 = sorted_old_specs_list[1]
				else:
					winner1 = self.last_valid
					winner2 = randomfrom(sorted_old_specs_list)
				candidate_specs_list = []
				candidate_specs = {}
				if options.debug > 1:
					print("Recombining genome %d. Winning specs: %d, %d" % (self.id, winner1.sid, winner2.sid))
				for old_spec in old_specs_list:
					if old_spec.checked:
						s = winner1.clone().recombine(winner2).mutate()
						s.sid = self.nextid()
					else:
						s = old_spec
						if options.debug > 2:
							print("Preserving spec %d" % (s.sid))
					candidate_specs_list.append(s)
					candidate_specs[s.sid] = s
				new_specs_list = candidate_specs_list
				self.generation_count = self.generation_count + 1
				
				if history_file:
					lo = history_dom.createElement("breed")
					lo.setAttribute("gid", str(self.id))
					lo.setAttribute("gc", str(self.generation_count))
					lo.setAttribute("winner1", str(winner1.sid))
					lo.setAttribute("winner2", str(winner2.sid))
					for sid,s in self.specs.iteritems():
						s.archive_xml(history_dom, lo)
					history_file.write(lo.toxml())
					history_file.write("\n")
					history_file.flush()
					
				candidate_specs_list.reverse()
				new_specs_list = candidate_specs_list
				new_specs = candidate_specs
				self.last_valid = winner1
			finally:
				self.specs_stack = new_specs_list
				self.specs = new_specs
		
		return self.specs_stack.pop()
	
	def report(self, post_obj):
		sid = int(post_obj.getAttribute("sid"))
		self.specs[sid].report(post_obj)

class Manager:
	def __init__(self):
		self.tanks = {}
		for _i in range(options.tanks):
			i = _i + 1
			if options.debug > 0:
				print("Generating tank %d" % i)
			self.tanks[i] = Genome(i)
	
	def any(self):
		return randomfromdict(self.tanks)
		
	def report(self, post_obj):
		for a in ["gid","sid","deaths","lastf"]:
			if not post_obj.hasAttribute(a):
				return
		try:
			gid = int(post_obj.getAttribute("gid"))
			self.tanks[gid].report(post_obj)
		except (ValueError, IndexError, KeyError):
			pass

class LuaHandler(tornado.web.RequestHandler):
	def result(self, doc, post_obj):
		return doc.createElement("nil")

	def updateFor(self,post):
#		t = time.time()
		if options.debug_failure:
			if random()<1.0/options.debug_failure:
				return ""
		try:
			post_obj = None
			if (post):
				if options.debug > 0:
					print("POST: %s" % post)
				dom = xml.dom.minidom.parseString(post)
				document = dom.documentElement
				post_obj = document
				
			output = xml.dom.minidom.Document()
			dc = self.result(output, post_obj)
			output.appendChild(dc)
			returnstring = output.toxml()

			response = returnstring
			
			if options.debug > 0:
				print(response)

			if options.debug_delay > 0: # Fake delay to test stuff 
				from time import sleep
				time.sleep(options.debug_delay)

			return response
		except:
			traceback.print_exc()
			return ""

	def put(self):
		self.write( self.updateFor( self.request.body ) )
		
	def get(self):
		self.write( self.updateFor( None ) )

class WelcomeHandler(LuaHandler):
	def result(self, doc, post_obj):
		r = doc.createElement("welcome")
		r.setAttribute("message","This game is an internetwide distributedevolutionary algorithm created with the goal of making the hardest platformer\nlevels possible. You will play a series of levels; in each, you must reach the\nblue dot. Those levels which prove most difficult will be allowed to breed and\ncreate new levels for future players.\n\nThere is no win condition. The purpose\nof this game is not to be won. The\npurpose of this game is to get\nprogressively better at killing you.\n\nControls: arrow keys, s to suicide")
		host = self.request.headers['Host']
		um = doc.createElement("um")
		um.setAttribute("level", "http://%s/level" % host)
		r.appendChild(um)
		return r
		
class LevelHandler(LuaHandler):
	def result(self, doc, post_obj):
		if post_obj:
			m.report(post_obj)
		r = doc.createElement("level")
		s = m.any()
		s.any().xml(doc, r)
		return r

class UnUpdateHandler(tornado.web.RequestHandler):
	def get(self):
		self.write("""<dc>
	<board>
		<set>
			<c p="201" x="-0.240000" y="0.000000" i="1056209845" />
		</set>
	</board>
</dc>
""")

# After the fact

def main():
	tornado.options.parse_command_line()
	if options.debug > 0:
		print("Debug level %s" % (options.debug))
	if options.history:
		global history_file
		global history_dom
		print("Logging to %s" % (options.history))
		history_file = open(options.history, AIR)
		history_dom = xml.dom.minidom.Document()
	if options.database:
		global database
		print("Will save to %s" % (options.database))
		
	global m
	m = Manager()
	
	if history_file: # initial logging
		lo = history_dom.createElement("init")
		for gid, g in m.tanks.iteritems():
			lot = history_dom.createElement("tank")
			lot.setAttribute("gid", str(gid))
			lot.setAttribute("gc", str(g.generation_count))
			for sid,s in g.specs.iteritems():
				s.archive_xml(history_dom, lot)
			lo.appendChild(lot)
			lot = None # How aggressive is Python's gc...?
		history_file.write(lo.toxml())
		history_file.write("\n")
		history_file.flush()
		lo = None
	
	application = tornado.web.Application([
		(r"/", MainHandler),
		(r"/welcome", WelcomeHandler),
		(r"/level", LevelHandler),
	])
	http_server = tornado.httpserver.HTTPServer(application)
	http_server.listen(options.port)
	tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
	main()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.