-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
217 lines (184 loc) · 7.42 KB
/
main.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
from fastapi import FastAPI
from fastapi.responses import JSONResponse, HTMLResponse, RedirectResponse
import logging
from services.utils import COMMANDS, create_html
from models.items import GamePayload, RobotPayload, StartResponse, ErrorMessage, PlayResponse, DeletionMessage
from models.setting import get_app_settings
from services.play import create_random_game, create_game, move_robot
from models.game import Game
# Setting logging
logging.basicConfig(filename='record.log',
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
# Caching the games by id
GAMES = {}
app_settings = get_app_settings()
app = FastAPI(
title=app_settings.title,
description=app_settings.description,
version=app_settings.version,
debug=app_settings.debug,
)
@app.get("/")
def read_root() -> RedirectResponse:
""" The root route, redirect to API document """
return RedirectResponse("/docs")
@app.post("/games/start", responses={200: {"model": StartResponse}, 400: {"model": ErrorMessage}})
def start_game(item: GamePayload) -> JSONResponse:
"""
Start a game
:param item: parameters to initialize a game instance
:return: the game information
"""
try:
dim, robots, robots_count, dinosaurs, dinosaurs_count = \
item.grid_dim, item.robots, item.robots_count, item.dinosaurs, item.dinosaurs_count
if dim <= 2:
logger.debug(f"The dimension is not big enough: {dim}")
return JSONResponse(
status_code=400,
content={"status": False, "detail": "You must create a bigger grid"}
)
if robots and dinosaurs:
match: Game = create_game(dim, robots=robots, dinosaurs=dinosaurs)
else:
match: Game = create_random_game(dim, robots_count=robots_count, dinosaurs_count=dinosaurs_count)
GAMES[str(match.game_id)] = match
logger.info(f">>>>> Game {match.game_id} started <<<<<<")
res = {
"game_id": str(match.game_id),
"grid": f"{match.dim}*{match.dim}",
"dinosaurs": len(match.dinosaurs_position),
"dinosaurs_position": match.dinosaurs_position,
"robots": len(match.robots_position),
"robots_position": list(match.robots.values()),
}
logger.info(f"{res}")
return JSONResponse(status_code=200, content=res)
except Exception as e:
logger.error(f"Exception: {e}")
return JSONResponse(
status_code=400,
content={"status": False, "detail": str(e)}
)
@app.get("/games/{game_id}", responses={400: {"model": ErrorMessage}, 404: {"model": ErrorMessage}})
def display_game(game_id: str) -> HTMLResponse:
"""
Display the game board in html
:param game_id: a specified game id
:return: html page
"""
try:
if game_id not in GAMES:
logger.error(f"Game ID '{game_id}' does not exist")
return JSONResponse(
status_code=404,
content={"status": False, "detail": f"Game ID '{game_id}' does not exist"}
)
game = GAMES[game_id]
html = create_html(game_id, game.get_board(), game.dim)
return HTMLResponse(content=html, status_code=200)
except Exception as e:
logger.error(f"Exception: {e}")
return JSONResponse(
status_code=400,
content={"status": False, "detail": str(e)}
)
@app.put("/games/{game_id}",
responses={200: {"model": PlayResponse}, 400: {"model": ErrorMessage}, 404: {"model": ErrorMessage}})
async def play_robots(game_id: str, item: RobotPayload) -> JSONResponse:
"""
Operate specified robot to move forward and backward, turn right and left, and attack
:param game_id: a specified game id
:param item: parameters to operate the robot
:return: the state of current game
"""
try:
if game_id not in GAMES:
logger.error(f"Game ID '{game_id}' does not exist")
return JSONResponse(
status_code=404,
content={"status": False, "detail": f"Game ID '{game_id}' does not exist"}
)
game: Game = GAMES[game_id]
robots_list = list(game.robots.keys())
chose_robot = str(item.robot_id)
if chose_robot not in robots_list:
chose_robot = list(game.robots.keys())[0]
logger.info(f"Moved robot id: {chose_robot}")
if item.command not in range(5):
logger.error(f"Invalid command: {item.command}")
return JSONResponse(
status_code=400,
content={
"status": False,
"detail": "You must insert the correct instructions as following \
0 -> forward, 1 -> backward, 2 -> right, 3 -> left, 4 -> attack"
}
)
command = COMMANDS[item.command]
game = await move_robot(game, chose_robot, command)
res = {
"game_id": game_id,
"robot_id": chose_robot,
"command": command,
"new_position": game.robots[chose_robot],
"dinosaurs": len(game.dinosaurs_position),
"dinosaurs_position": game.dinosaurs_position,
"number_of_moves": game.get_number_of_moves(),
"all_dinosaurs_has_been_terminated": not bool(game.dinosaurs_position),
}
logger.info(f"{res}")
if res["all_dinosaurs_has_been_terminated"]:
logger.info(f">>>>> Game {game_id} completed <<<<<<")
return JSONResponse(status_code=200, content=res)
except Exception as e:
logger.error(f"Exception: {e}")
return JSONResponse(
status_code=400,
content={"status": False, "detail": str(e)}
)
@app.delete("/games/{game_id}",
responses={200: {"model": DeletionMessage}, 400: {"model": ErrorMessage}, 404: {"model": ErrorMessage}})
def remove_game(game_id: str) -> JSONResponse:
"""
Remove a specified game instance in the cache
:param game_id: a specified game id
:return: the state of remove
"""
try:
if game_id not in GAMES:
logger.error(f"Game ID '{game_id}' does not exist")
return JSONResponse(
status_code=404,
content={"status": False, "detail": f"Game ID '{game_id}' does not exist"}
)
GAMES.pop(game_id)
res = {
"game_id": game_id,
"is_deleted": game_id not in GAMES,
}
logger.info(f"{res}")
return JSONResponse(status_code=200, content=res)
except Exception as e:
logger.error(f"Exception: {e}")
return JSONResponse(
status_code=400,
content={"status": False, "detail": str(e)}
)
@app.delete("/games", responses={400: {"model": ErrorMessage}})
def remove_games() -> JSONResponse:
""" Remove all games instances in the cache """
logger.info("Delete all games")
try:
[GAMES.pop(game) for game in GAMES.copy()]
logger.info("all games deleted")
return JSONResponse(status_code=204, content={})
except Exception as e:
logger.error(f"Exception: {e}")
return JSONResponse(
status_code=400,
content={"status": False, "detail": str(e)}
)