-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
609 lines (478 loc) · 14.8 KB
/
server.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
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
#
# Valley Of Trolls - v20141207 2359
#
# For Ludum Dare 31 compo (solo).
# Made by Johannes Lundberg a happy weeked in Uppsala, Sweden.
#
# Source code is public domain.
# All rights reserved on graphics and sound.
#
# Contact: @johannesl or [email protected]
#
from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
import gevent
from random import randint
from datetime import datetime
import json
import math
import sys
games = []
waiting = []
MOUNTAIN = 0
TROLL = 1
VILLAGE = 2
SOLDIER = 3
EMPTY = 4
NORTH = 0
NORTHEAST = 1
SOUTHEAST = 2
SOUTH = 3
SOUTHWEST = 4
NORTHWEST = 5
#
# GAME LOGIC
#
gamelog = open("../log.txt","a")
def dir2txy (direction, tx, ty):
if direction == NORTH:
return tx,ty-1
if direction == NORTHEAST and tx%2 == 0:
return tx+1,ty
elif direction == NORTHEAST:
return tx+1,ty-1
if direction == SOUTHEAST and tx%2 == 0:
return tx+1,ty+1
elif direction == SOUTHEAST:
return tx+1,ty
if direction == SOUTH:
return tx,ty+1
if direction == SOUTHWEST and tx%2 == 0:
return tx-1,ty+1
elif direction == SOUTHWEST:
return tx-1,ty
if direction == NORTHWEST and tx%2 == 0:
return tx-1,ty
elif direction == NORTHWEST:
return tx-1,ty-1
print dir2txy(SOUTH, 0, 0) # 0,1
print dir2txy(NORTHEAST, 0, 0) # 1,0
print dir2txy(SOUTHEAST, 0, 0) # 1,1
#sys.exit(0)
class Game:
def __init__(self):
self.gamestate = []
self.clients = []
self.paused = 0
self.playersReported = 0
self.winner = -1
# FIXME
self.minplayers = 4
self.playercount = 0
self.playersOnline = 0
self.turn = -1
def generatemap(self):
# Generate a new map
# Empty map
for y in range(0,5):
for x in range(0,7):
#if x % 2 == 0:
# if y >= 4: continue
# Empty tile for now
self.gamestate.append( {} )
# Four starting positions
starts = [
[(0,0), (1,0), (1,1)],
[(5,0), (6,0), (5,1)],
[(0,3), (1,3), (1,4)],
[(5,3), (6,3), (5,4)]
]
for i in range(0,self.minplayers):
randint(0,3)
x,y = starts[i][randint(0,2)]
self.hometile( self.gamestate[y*7+x], i )
# The rest of the map
for y in range(0,5):
for x in range(0,7):
if x % 2 == 0:
if y >= 4: continue
# Random tile contents
tile = self.gamestate[y*7+x]
if tile == {}:
self.randomizetile(tile, x, y)
def randomizetile (self, tile, x, y):
# Randomize new tile
i = randint(0,9)
if i < 5:
tile['type'] = VILLAGE # Village
elif i == 6:
tile['type'] = MOUNTAIN # Mountain
elif i == 7:
if randint(0,1) == 0:
tile['type'] = EMPTY # Empty
else:
tile['type'] = MOUNTAIN
else:
tile['type'] = TROLL # Troll
if i == 9:
if randint(0,1) == 0:
tile['type'] = EMPTY # Empty
else:
tile['type'] = MOUNTAIN
elif i == 8 or i == 7 or i == 5:
tile['type'] = VILLAGE # Village
elif i == 6:
tile['type'] = TROLL # Mountain
elif i == 4:
tile['type'] = VILLAGE # Super Village
else:
tile['type'] = EMPTY # Troll
tile['owner'] = 4
if tile['type'] == 2:
tile['owner'] = 4
if i == 4:
tile['size'] = randint(70,130)
tile['economy'] = randint(0,5)
tile['defense'] = randint(0,4)
else:
tile['size'] = randint(20,40)
tile['economy'] = 0
tile['defense'] = 0
#tile['type'] = 4
tile['orders'] = [0,0,0,0,0,0]
tile['mode'] = 0
tile['burning'] = 0
def hometile (self, tile, player):
tile['type'] = 2
tile['owner'] = player
tile['economy'] = 1
tile['defense'] = 0
tile['orders'] = [0,0,0,0,0,0]
tile['size'] = 80
tile['burning'] = 0
def startgame (self):
self.gameid = datetime.utcnow().isoformat()
self.generatemap()
s = '%s,gamestarted,%s' % (self.gameid,self.playercount)
print s
gamelog.write( s + '\n' )
gamelog.flush()
self.sendstate()
# New turn data from client received
def addorders (self, player, data):
self.playersReported += 1
for key in data:
# skip for now
if key == 'turn': continue
x,y = key.split(',')
tx = int(x)
ty = int(y)
# safety
if tx < 0 or tx >= 7:
continue
if ty < 0 or ty >= 5:
continue
if tx % 2 == 0 and ty >= 4:
continue
mode, orders = data[key]
print mode,orders
# Split armies out
totalweight = 0
for direction in range(0,len(orders)):
if orders[direction] > 0:
# Valid direction? FIXME
dx,dy = dir2txy( direction, tx, ty )
if orders[direction] == 1:
weight = 1
else:
weight = 3
totalweight += weight
print totalweight
tile = self.gamestate[ty*7+tx]
startsize = tile['size']
for direction in range(0,len(orders)):
if orders[direction] == 0 or tile['size'] <= 0: continue
dx,dy = dir2txy( direction, tx, ty )
dtile = self.gamestate[dy*7+dx]
print direction,dx,dy,dtile
if orders[direction] == 1:
weight = 1
else:
weight = 3
size = math.ceil( startsize*weight / float(totalweight) )
if weight == 1 and size > math.ceil(startsize/3):
size = math.ceil(startsize/3)
if size > tile['size']:
size = tile['size']
print direction, weight, size
#dtile['type'] = MOUNTAIN
# Is this soldier leaving?
tile['size'] -= size
if tile['type'] == SOLDIER and tile['size'] == 0:
tile['owner'] = 4
tile['type'] = EMPTY
if dtile['owner'] == player:
if dtile.has_key('supporters'):
dtile['supporters'] += size
else:
dtile['supporters'] = size
else:
if not dtile.has_key('attackers'):
dtile['attackers'] = {}
# Group attackers of the same tribe
if not dtile['attackers'].has_key(player):
dtile['attackers'][player] = 0
dtile['attackers'][player] += size
print dtile['attackers']
if not self.paused and self.playersReported == self.playersOnline:
self.newturn()
def newturn (self):
self.turn += 1
self.playersReported = 0
# Resource boost
for ty in range(0,5):
for tx in range(0,7):
if tx % 2 == 0:
if ty >= 4: continue
tile = self.gamestate[ty*7+tx]
if tile['type'] == VILLAGE and tile['owner'] < 4:
tile['size'] += 4 + tile['economy']
# Supporters
for ty in range(0,5):
for tx in range(0,7):
if tx % 2 == 0:
if ty >= 4: continue
tile = self.gamestate[ty*7+tx]
if tile.has_key('supporters'):
tile['size'] += tile['supporters']
del tile['supporters']
# Attacks?
newtrolls = 0
for ty in range(0,5):
for tx in range(0,7):
if tx % 2 == 0:
if ty >= 4: continue
tile = self.gamestate[ty*7+tx]
if tile.has_key('attackers'):
# Internal fight between attackers first (lucky defender)
if len(tile['attackers']) > 1:
l = tile['attackers'].values()
l.sort()
biggestlooser = l[-2]
for key in tile['attackers']:
if tile['attackers'][key] == l[-1]:
player = key
size = tile['attackers'][key] - biggestlooser
tile['burning'] = 1
else:
player = tile['attackers'].keys()[0]
size = tile['attackers'][player]
# Unoccupied?
if tile['type'] == EMPTY:
tile['owner'] = player
tile['size'] = size
tile['type'] = SOLDIER
else:
tile['burning'] = 1 # FIXME
# Troll
if tile['type'] == TROLL:
if size >= 40:
tile['type'] = SOLDIER
tile['owner'] = player
tile['size'] = size - 20
tile['burning'] = 2
# Spawn up to 2 new trolls
newtrolls += randint(1,2)
elif tile['type'] == SOLDIER:
defensebonus = 0.8
if size > math.floor(tile['size']*defensebonus): # Negative defense bonus
tile['owner'] = player
tile['size'] = size - math.floor(tile['size']*defensebonus)
tile['burning'] = 2
else:
tile['size'] -= math.ceil( size/defensebonus )
elif tile['type'] == VILLAGE:
# 10% default defense bonus
defensebonus = 1.1
if tile['defense'] > 0:
defensebonus += 0.1*tile['defense']
if size > math.floor(tile['size']*defensebonus):
tile['owner'] = player
tile['size'] = size - math.floor(tile['size']*defensebonus)
tile['burning'] = 2
else:
tile['size'] -= math.ceil( size/defensebonus )
# Enemy village
del tile['attackers']
#self.paused = 1
# New trolls
empty = []
for ty in range(0,5):
for tx in range(0,7):
if tx % 2 == 0:
if ty >= 4: continue
tile = self.gamestate[ty*7+tx]
if tile['burning'] == 0:
if tile['type'] == EMPTY:
empty.append( (tx,ty,0) )
if tile['type'] == SOLDIER and tile['size'] < 20:
empty.append( (tx,ty,2) )
while newtrolls > 0:
if len(empty) > 0:
i = randint(0,len(empty)-1)
tile = self.gamestate[empty[i][1]*7+empty[i][0]]
tile['type'] = TROLL
tile['owner'] = 4
tile['size'] = 0
tile['burning'] = empty[i][2]
del empty[i]
newtrolls -= 1
self.sendstate()
# Clear away burning
for ty in range(0,5):
for tx in range(0,7):
if tx % 2 == 0:
if ty >= 4: continue
tile = self.gamestate[ty*7+tx]
tile['burning'] = 0
if tile['type'] != VILLAGE and tile['type'] != SOLDIER:
tile['owner'] = 4
# Any winner?
living = {}
for ty in range(0,5):
for tx in range(0,7):
if tx % 2 == 0:
if ty >= 4: continue
tile = self.gamestate[ty*7+tx]
if tile['type'] == VILLAGE or tile['type'] == SOLDIER:
if tile['owner'] < 4:
living[tile['owner']] = 1
if self.winner == -1 and len(living) == 1:
self.winner = living.keys()[0]
self.sendstate()
# Grow surviving villages
pass
def sendstate (self):
if self.turn < 500:
s = '%s,gamestate,%s,%s' % (datetime.utcnow().isoformat(),self.gameid,json.dumps(self.gamestate).replace(' ',''))
gamelog.write( s + '\n' )
gamelog.flush()
if self.winner > -1:
print 'WE HAVE A WINNER', self.winner
for client in self.clients:
if client.player == self.winner:
client.ws.send( '{"win":"youwin"}' )
else:
client.ws.send( '{"win":"youloose"}' )
self.paused = 1
else:
# Send out intial gamestate to all players
drop = []
for client in self.clients:
s = json.dumps(self.gamestate)
try:
client.ws.send( s )
except:
drop.append( client)
for client in drop:
self.disconnectplayer( client )
def sendplayercount(self):
self.playercount = len(self.clients)
if self.playercount == self.minplayers:
playercount = 4
self.turn = 0
self.playersOnline = self.playercount
self.playersReported = 0
else:
playercount = self.playercount
drop = []
for client in self.clients:
try:
client.ws.send( json.dumps({'team':client.player,'playercount':playercount}))
except:
drop.append( client)
for client in drop:
self.disconnectplayer( client )
def disconnectplayer(self,client):
if not client in self.clients: return
del self.clients[self.clients.index(client)]
try:
s = '%s,connectiondropped,%s' % (datetime.utcnow().isoformat(), self.gameid)
except:
s = '%s,connectiondropped' % (datetime.utcnow().isoformat())
print s
gamelog.write( s + '\n' )
gamelog.flush()
self.playersOnline -= 1
if self.turn == -1:
# Renumber players
for i in range(0,len(self.clients)):
self.clients[i].player = i
self.sendplayercount()
def addplayer(self,client):
client.player = len(self.clients)
client.game = self
self.clients.append( client )
# Update all clients with new player count (and their teams)
self.sendplayercount()
if self.playercount == 2:
gevent.spawn( self.forcestart )
if self.turn == 0:
self.startgame()
def forcestart(self):
print 'forcestart?'
gevent.sleep(30)
if self.turn != -1: return
playercount = len(self.clients)
if playercount >= 2:
self.minplayers = self.playercount
self.sendplayercount()
print 'minplayers', self.minplayers, self.turn
if self.turn == 0:
self.startgame()
def joinNextGame(client):
if len(games) == 0:
games.append( Game() )
print '1games',len(games),'turn',games[-1].turn
if games[-1].turn != -1:
games.append( Game() )
print '2games',len(games),'turn',games[-1].turn
games[-1].addplayer( client )
#return games[0],player # Set these on the player object
#game = Game()
#print game.gamestate
class ServerApplication(WebSocketApplication):
def on_open(self):
s = '%s,newconnection' % (datetime.utcnow().isoformat())
print s
gamelog.write( s + '\n' )
gamelog.flush()
self.status = 0
def on_message(self, message):
# join request
if self.status == 0:
# Find game to join
self.status = 1
joinNextGame(self)
# GAME NOW STARTS, SEND gamestate TO ALL PLAYERS (TODO)
#games[0].startgame()
#self.ws.send( json.dumps(self.game.gamestate) )
elif self.game.turn >= 0:
#print 'got',message
try:
msg = json.loads(message)
except:
self.game.disconnectplayer(self)
return
self.game.addorders( self.player, msg )
#self.ws.send( json.dumps(self.game.gamestate) )
else:
# drop player here
self.game.disconnectplayer(self)
def on_close(self, reason):
# FIXME: Ensure graceful disconnect of players
self.game.disconnectplayer(self)
#print reason
WebSocketServer(
('', 29349),
Resource({'/': ServerApplication})
).serve_forever()