-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
228 lines (212 loc) · 7.02 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
import sys
import time
import json
from hashlib import sha256
from contextlib import contextmanager
import random
import asyncio
import aiohttp
import aiohttp.web
connections = {}
games = {}
parties = {}
#fil = open('log.log', 'w')
BLOCW, BLOCH = 20, 20
WIDTH, HEIGHT = 60 * BLOCW, 35 * BLOCH
BIGAPPLE_TIME = 8
def rx():
return random.randint(0, WIDTH // BLOCW - 1) * BLOCW
def ry():
return random.randint(0, HEIGHT // BLOCH - 1) * BLOCH
def m(*a):
return json.dumps(a)
def n(s):
return json.loads(s)
def newpid(gam):
gam['nextpid'] = gam.setdefault('nextpid', 0) + 1
return gam['nextpid']
@contextmanager
def newsock(s, path, d=connections):
if path not in d:
d[path] = set()
d[path].add(s)
try:
yield s
finally:
if path in d:
d[path].remove(s)
if not d[path]:
del d[path]
async def echo(request):
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
path = request.match_info['path']
with newsock(ws, path):
async for msg in ws:
if msg.type != aiohttp.WSMsgType.TEXT:
continue
for s in connections[path]:
await s.send_str(msg.data)
return ws
async def bigapple(gam):
while 1:
gam['bigapple?'] = not gam['bigapple?']
if gam['bigapple?']:
gam['bigapple'] = (rx() // 2 * 2, ry() // 2 * 2)
await asyncio.gather(*(
s.send_str(m('B', 0, *gam['bigapple']))
for s in gam['socks'].values()
))
else:
await asyncio.gather(*(
s.send_str(m('b', 0, 0))
for s in gam['socks'].values()
))
await asyncio.sleep(BIGAPPLE_TIME)
@contextmanager
def newgame(s, pid, path):
if path not in games:
raise aiohttp.web.HTTPNotFound
if not games[path]['socks']:
games[path]['task'] = asyncio.create_task(bigapple(games[path]))
games[path]['socks'][pid] = s
games[path]['lens'][pid] = 1
try:
yield s
finally:
if path in games:
del games[path]['socks'][pid]
if not games[path]['socks']:
games[path]['task'].cancel()
del games[path]
async def game(request):
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
print(request.match_info)
path = request.match_info['path']
game = games[path]
PID = newpid(game)
with newgame(ws, PID, path):
await ws.send_str(m('+', PID))
await asyncio.gather(*(
ws.send_str(m('+', pid))
for pid in game['socks']
if pid != PID
), *(
s.send_str(m('+', PID))
for s in game['socks'].values()
if s != ws
),
ws.send_str(m('a', 0, 0, *game['apple']))
)
async for msg in ws:
if msg.type != aiohttp.WSMsgType.TEXT:
continue
print('>{}'.format(msg.data))#, file=fil)
try:
deeta = n(msg.data)
except json.JSONDecodeError:
await ws.close(code=4000, message=b'Invalid message')
break
if deeta[0] == 'a':
game['apple'] = (rx(), ry())
game['lens'][PID] += 1
await asyncio.gather(*(
s.send_str(m('a', PID, game['lens'][PID], *game['apple']))
for s in game['socks'].values()
))
if deeta[0] == 'b':
if not game['bigapple?']:
await ws.close(code=4000, message=b'Big apple not availabe')
break
game['bigapple'] = (rx() // 2 * 2, ry() // 2 * 2)
game['bigapple?'] = False
game['lens'][PID] += 4
await asyncio.gather(*(
s.send_str(m('b', PID, game['lens'][PID]))
for s in game['socks'].values()
))
if deeta[0] == 'd':
await asyncio.gather(*(
s.send_str(m('d', PID, *deeta[1:]))
for s in game['socks'].values()
))
if deeta[0] not in {'a', 'b', 'd'}:
await ws.close(code=4000, message=b'Invalid oplet')
break
await asyncio.gather(*(
s.send_str(m('-', PID))
for s in game['socks'].values()
))
return ws
@contextmanager
def partysock(s, path):
if path not in parties:
parties[path] = {'owner': s, 'socks': set(), 'ready': 0}
parties[path]['socks'].add(s)
try:
yield s
finally:
if path in parties:
parties[path]['socks'].remove(s)
if not parties[path]['socks']:
del parties[path]
async def party(request):
#server: member joined
ws = aiohttp.web.WebSocketResponse()
await ws.prepare(request)
path = request.match_info['path']
#PID = (await ws.receive_str())[5:]
startable = False
with partysock(ws, path):
for s in parties[path]['socks']:
#tell clients
if s != ws:
await s.send_str(str(len(parties[path]['socks'])))
async for msg in ws:
if msg.type != aiohttp.WSMsgType.TEXT:
continue
#server: member ready
if msg.data == 'ready':
parties[path]['ready'] += 1
elif msg.data == 'unready':
parties[path]['ready'] -= 1
startable = False
await parties[path]['owner'].send_str('unstartable')
for s in parties[path]['socks']:
await s.send_str('ready: {}'.format(parties[path]['ready']))
if msg.data == 'start' and ws == parties[path]['owner'] and startable:
gameroom = sha256((str(time.time()) + path).encode('ascii')).hexdigest()
games[gameroom] = {
'socks': {},
'apple': (rx(), ry()),
'bigapple': (rx() // 2 * 2, ry () // 2 * 2),
'bigapple?': True,
'lens': {},
}
for s in parties[path]['socks']:
await s.send_str('start: ' + gameroom)
#all ready?
if parties[path]['ready'] == len(parties[path]['socks']):
await parties[path]['owner'].send_str('startable')
startable = True
elif startable:
await parties[path]['owner'].send_str('unstartable')
startable = False
return ws
async def party_size(request):
return aiohttp.web.Response(text=str(
len(parties[request.match_info['path']]['socks'])
))
async def wakeup():
while 1:
await asyncio.sleep(1)
asyncio.get_event_loop().create_task(wakeup())
app = aiohttp.web.Application()
app.add_routes([
aiohttp.web.get('/echo/{path}', echo),
aiohttp.web.get('/game/{path}', game),
aiohttp.web.get('/party/{path}', party),
aiohttp.web.get('/party_size/{path}', party_size)
])
aiohttp.web.run_app(app)