From: zharkovstas Date: Sat, 18 May 2019 14:09:33 +0000 (+0500) Subject: Add backend X-Git-Url: https://git.xn--bdkaa.com/?a=commitdiff_plain;h=27ad31ac1a7cf81d5f190ef38d1ecfce2a0d7a55;p=where-are-you.py.git Add backend --- diff --git a/.gitignore b/.gitignore index 894a44c..4ad6467 100644 --- a/.gitignore +++ b/.gitignore @@ -102,3 +102,5 @@ venv.bak/ # mypy .mypy_cache/ + +.idea/ \ No newline at end of file diff --git a/app.py b/app.py new file mode 100644 index 0000000..733e0e1 --- /dev/null +++ b/app.py @@ -0,0 +1,73 @@ +from bottle import get, post, run, request +import uuid +from geo import distance + + +class Game: + def __init__(self, game_id, current_coordinates): + self.id = game_id + self.current_coordinates = current_coordinates + self.is_finished = False + self.answer_coordinates = None + self.distance = None + + +games = {} + + +@get('/api/games') +def get_games(): + return { + "games": [{"game_id": g.id, "coordinates": g.current_coordinates if g.is_finished else None} for g in + games.values()] + } + + +@post('/api/games') +def post_game(): + game_id = str(uuid.uuid4()) + + game = Game(game_id, (56.832469, 60.605989)) + games[game_id] = game + + return { + "game_id": game_id + } + + +@get('/api/games/') +def get_game(game_id): + game = games[game_id] + + return { + "id": game_id + } + + +@post('/api/games//finish') +def finish_game(game_id): + game = games[game_id] + + if game.is_finished: + return { + "right_coordinates": game.current_coordinates, + "distance": game.distance + } + + answer = request.json + + answer_coordinates = (answer["latitude"], answer["longitude"]) + + d = distance(game.current_coordinates, answer_coordinates) + + game.is_finished = True + game.answer_coordinates = answer_coordinates + game.distance = d + + return { + "right_coordinates": game.current_coordinates, + "distance": d + } + + +run(host='localhost', port=8080, debug=True, server='paste') diff --git a/geo.py b/geo.py new file mode 100644 index 0000000..2e13c6b --- /dev/null +++ b/geo.py @@ -0,0 +1,18 @@ +from math import sin, cos, sqrt, atan2, radians + +R = 6373000.0 + + +def distance(point1, point2): + lat1 = radians(point1[0]) + lon1 = radians(point1[1]) + lat2 = radians(point2[0]) + lon2 = radians(point2[1]) + + dlon = lon2 - lon1 + dlat = lat2 - lat1 + + a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 + c = 2 * atan2(sqrt(a), sqrt(1 - a)) + + return R * c diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..791f9dc Binary files /dev/null and b/requirements.txt differ