-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
184 lines (173 loc) · 4.27 KB
/
Copy pathmain.py
File metadata and controls
184 lines (173 loc) · 4.27 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
from http.server import BaseHTTPRequestHandler, HTTPServer
import typing
import os
import json
import sys
from game import Game, Player, MoveForwardsCard, TurnCard, ChangeLevelCard, ShootCard, RevengeCard
hostName = "0.0.0.0"
serverPort = 8080
class URLQuery:
def __init__(self, q):
self.orig = q
self.fields = {}
for f in q.split("&"):
s = f.split("=")
if len(s) >= 2:
self.fields[s[0]] = s[1]
def get(self, key):
if key in self.fields:
return self.fields[key]
else:
return ''
def read_file(filename: str) -> bytes:
"""Read a file and return the contents."""
f = open(filename, "rb")
t = f.read()
f.close()
return t
def write_file(filename: str, content: bytes):
"""Write data to a file."""
f = open(filename, "wb")
f.write(content)
f.close()
class HttpResponse(typing.TypedDict):
"""A dict containing an HTTP response."""
status: int
headers: dict[str, str]
content: str | bytes
game: Game = Game()
# game.addPlayer(Player("someone"))
# game.addPlayer(Player("someone else"))
# game.addPlayer(Player("a third person"))
def get(path: str, query: URLQuery) -> HttpResponse:
# playername = query.get("name")
if os.path.isfile("public_files" + path):
return {
"status": 200,
"headers": {
"Content-Type": {
"html": "text/html",
"js": "text/javascript",
"css": "text/css",
"svg": "image/svg+xml",
"ico": "image/x-icon"
}[path.split(".")[-1]]
},
"content": read_file("public_files" + path)
}
elif os.path.isdir("public_files" + path):
return {
"status": 200,
"headers": {
"Content-Type": "text/html"
},
"content": read_file("public_files" + path + "index.html")
}
elif path == "/status":
return {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"content": json.dumps(game.toDict(), indent='\t')
}
elif path.startswith("/card/"):
data = path.split("/")[2:]
card = {
"move_forwards": MoveForwardsCard,
"turn": TurnCard,
"change_level": ChangeLevelCard,
"shoot": ShootCard,
"revenge": RevengeCard
}[data[0]]
figure = game.players[int(data[1])].figure
card(figure, game).execute()
return {
"status": 200,
"headers": {
"Content-Type": "text/html"
},
"content": ""
}
else: # 404 page
print("404 GET " + path)
return {
"status": 404,
"headers": {
"Content-Type": "text/html"
},
"content": ""
}
def post(path: str, body: bytes) -> HttpResponse:
bodydata = body.decode("UTF-8").split("\n")
if path == "/join_game":
game.addPlayer(Player(bodydata[0]))
return {
"status": 200,
"headers": {},
"content": ""
}
elif path == "/ready":
game.readyPlayer(bodydata[0])
return {
"status": 200,
"headers": {},
"content": ""
}
elif path == "/submit_plan":
game.setPlan(bodydata)
return {
"status": 200,
"headers": {},
"content": ""
}
else:
print("404 POST " + path)
return {
"status": 404,
"headers": {
"Content-Type": "text/html"
},
"content": ""
}
class MyServer(BaseHTTPRequestHandler):
def do_GET(self):
splitpath = self.path.split("?")
res = get(splitpath[0], URLQuery(''.join(splitpath[1:])))
self.send_response(res["status"])
for h in res["headers"]:
self.send_header(h, res["headers"][h])
self.end_headers()
c = res["content"]
if isinstance(c, str): c = c.encode("utf-8")
self.wfile.write(c)
def do_POST(self):
res = post(self.path, self.rfile.read(int(self.headers["Content-Length"])))
self.send_response(res["status"])
for h in res["headers"]:
self.send_header(h, res["headers"][h])
self.end_headers()
c = res["content"]
if isinstance(c, str): c = c.encode("utf-8")
self.wfile.write(c)
def log_message(self, _format: str, *args) -> None:
return
# if 400 <= int(args[1]) < 500:
# # Errored request!
# print("\u001b[31m", end="")
# print(args[0].split(" ")[0], "request to", args[0].split(" ")[1], "(status code:", args[1] + ")")
# print("\u001b[0m", end="")
# # don't output requests
if __name__ == "__main__":
running = True
webServer = HTTPServer((hostName, serverPort), MyServer)
webServer.timeout = 1
print(f"Server started http://{hostName}:{serverPort}")
sys.stdout.flush()
while running:
try:
webServer.handle_request()
except KeyboardInterrupt:
running = False
webServer.server_close()
print("Server stopped")