-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
301 lines (259 loc) · 10 KB
/
main.py
File metadata and controls
301 lines (259 loc) · 10 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
from threading import Thread, RLock
from multiprocessing import Manager
from queue import Queue
from json import load, loads
import time
import os
#from uuid import uuid4
from shortuuid import uuid
from shortuuid import encode
from flask import Flask, Blueprint, send_from_directory, render_template, request
from flask_socketio import SocketIO, join_room, leave_room, emit, close_room
import base62
from game.board import Board
THREADS_LIMIT = 225 # Semi-arbitrary limit; Heroku allows 255 threads for free
INPUT_LIMIT = 8 # Maximum inputs to process per tick for a game
BLOCKS_PATH = "config/blocks.json"
FRAMES_PATH = "config/frames.json"
DEAD_TIME = 1 # Seconds to check for dead games
EXPIRE_TIME = 60 * 6 # Seconds until a game can be considered for death,
# a game is 'dead' when it has been alive for this amount
# of time, and 'running' is False.
NAMES = ["Left Board", "Right Board"]
new_q = Queue() # New host queue
inp_q = Queue() # Input queue
out_q = Queue() # Output queue
room_lock = RLock()
rooms = {} # Dictionary of 'rooms' aka GameThreads
app = Flask(__name__)
sockets = SocketIO(app, async_mode="threading") # SocketIO, started in page worker
html = Blueprint("html", __name__, "static", template_folder="static")
@html.route("/")
def index():
return send_from_directory("static", "controller.html")
@html.route("/css/<path:path>")
def css(path):
return send_from_directory("static/css", path)
@html.route("/js/<path:path>")
def js(path):
return send_from_directory("static/js", path)
@html.route("/host")
def host():
return send_from_directory("static", "host.html")
@html.route("/music/<path:path>")
def music(path):
return send_from_directory("static/music", path)
def pageWorker():
"""Static page serving and SocketIO."""
print("Starting page worker...")
global sockets
app.register_blueprint(html, url_prefix="/")
blocks = load(open(BLOCKS_PATH))
frames = load(open(FRAMES_PATH))
@sockets.on("host", namespace="/host")
def host():
hid = request.sid
with room_lock:
if len(rooms) < THREADS_LIMIT:
uid = uuid()[:10] # More chance of duplicate
# But 'rare enough'
join_room(uid)
new_q.put(uid)
else:
print("Warning: maximum capacity reached for game threads")
@sockets.on("ready", namespace="/host")
def ready(hid):
"""When the host is ready to begin the match.
Will only start the match if 2 players have joined.
Returns (boolean, message) to client, where boolean is True when
the game is starting.
"""
with room_lock:
if not hid in rooms:
return False, "Invalid room"
elif len(rooms[hid].boards) < 2:
return False, "Need 2 players to start"
else:
rooms[hid].state_q.put("start")
return True, "Starting game"
@sockets.on_error_default
def all_error_handler(e):
print(f"SocketIO Error: {e}")
@sockets.on("join")
def join(data):
"""
Handle player joining room. Data should be an object with:
room - Room ID to join.
Returns (boolean, message, [bid]) to client. Where the boolean is
True when the client has successfully joined the room. bid is only
returned when the client is in the room.
"""
try:
data = loads(data)
room_id = str(data["room"])
with room_lock:
if room_id not in rooms:
return False, "Invalid Room"
elif len(rooms[room_id].boards) >= 2:
return False, "Full Room"
join_room(room_id)
board_id = request.sid
room = rooms[room_id]
room.boards[board_id] = room.new_board()
return True, NAMES[len(room.boards) - 1], board_id
except Exception as e:
print(f"An error occurred on join: {e}")
return False, "Error"
@sockets.on("leave")
def leave(data):
"""
Handle player leaving room. Data should be an object with:
room - Room ID to leave.
bid - Board ID.
"""
try:
data = loads(data)
room_id = str(data["room"])
bid = str(data["bid"])
leave_room(room_id)
with room_lock:
del rooms[room_id].boards[bid]
except Exception as e:
print(f"Error occurred when leaving room: {e}")
@sockets.on("input")
def inp(msg):
try:
formatted = loads(msg)
print(formatted)
formatted["bid"] = request.sid
if not contains(formatted, ["room", "bid", "command"]):
return
with room_lock:
if formatted["room"] in rooms:
rooms[formatted["room"]].boards[formatted["bid"]].performInput(formatted["command"])
except Exception as err:
print(f"Input error: {err}")
sockets.run(app, port=os.environ.get("PORT", 33507), log_output=False,
host="0.0.0.0", debug=False)
class GameThread(Thread):
def __init__(self, state_q: Queue, input_q: Queue, blocks, frames):
"""
state_q - Game State Queue (start, stop, etc.).
input_q - Game Input Queue (from players).
blocks - Block data.
Frames - Frame data.
"""
super().__init__()
self.name = ""
self.polling = True # Polling for state_q event
self.expire_time = 0
self._blocks = blocks
self._frames = frames
self.boards = {} # Keys will be board ID (bid)
self.losses = 0 # When 2, end game
self.state_q = state_q if state_q else Queue()
self.input_q = input_q if input_q else Queue()
self.running = False # Game active?
def new_board(self) -> Board:
return Board(10, 20, self._blocks, self._frames)
def board_update(self):
"""Update all player boards.
Returns list of dictionary of board IDs and their raw grid data. Ready
to send to host client in following JSON format:
{
"bid": Str,
"grid": list
}
"""
result = []
for bid, b in self.boards.items():
b.update(1 / 60)
result.append({ "bid": bid, "grid": b.get_raw_grid() })
return result
def run(self):
while self.polling:
if self.state_q.get() == "start":
polling = False
self.start_game()
break
self.destroy()
def performInput(self, inp):
"""Add an input command to the input queue."""
input_q.put(inp)
def start_game(self):
sockets.emit("start game", room=self.name, namespace="/host")
self.running = True
current = None # Current frame's grid from update
last = None # Last frame's grid from update
while self.running and len(self.boards) >= 2:
try:
if self.state_q.get_nowait() == "stop": # Currently unused
print(f"({self.name}) Received stop in state queue")
self.running = False
for i in range(INPUT_LIMIT):
inp = self.input_q.get_nowait()
self.boards[inp[0]].performInput(inp[1])
except: # get_nowait
pass
for bid, b in self.boards.items():
self.running = not b.has_lost()
if not self.running:
print(f"({self.name}) Player {bid} has lost")
break
# Send new boards
# TODO: Optimize later
if current != None:
last = current[:]
current = self.board_update()
if current != last:
sockets.emit("update", current, room=self.name, namespace="/host")
time.sleep(.016)
def destroy(self):
print(f"({self.name}) Ending.")
def deadCheckWorker():
"""Checks if any game threads are dead and closes them."""
print("Starting killer worker...")
while True:
time.sleep(DEAD_TIME)
with room_lock:
current = time.perf_counter()
for key in list(rooms.keys()):
if current >= rooms[key].expire_time and not rooms[key].running:
print(f"{key} has been inactive, killing...")
rooms[key].polling = False # Possible data race?
del rooms[key]
print(f"Active rooms:\n{list(rooms.keys())}")
def restartingThread():
"""Handles creation of new game threads."""
print("Starting room worker...")
blocks = load(open("config/blocks.json"))["blocks"]
frames = load(open("config/frames.json"))
while True:
hid = new_q.get() # Unique room ID as string
with room_lock:
if len(rooms) < THREADS_LIMIT:
game_thread = GameThread(None, None, blocks, frames)
game_thread.name = hid
game_thread.expire_time = time.perf_counter() + EXPIRE_TIME
rooms[hid] = game_thread
game_thread.start()
#eventlet.spawn(game_thread.run)
sockets.emit("host greet",
{"room_id": hid},
room=hid,
namespace="/host")
#sockets.emit("start game", room=hid, namespace="/host")
else:
print("Warning: maximum capacity reached for game threads")
def contains(target: dict, keyList: list) -> bool:
"""Check if all the keys in keyList are in target."""
for key in keyList:
if key not in target:
return False
return True
page_thread = Thread(target=pageWorker, name="page")
handler_thread = Thread(target=restartingThread, name="handler")
kill_thread = Thread(target=deadCheckWorker, name="killer")
page_thread.start()
handler_thread.start()
kill_thread.start()