def get_location(request): if LOCATION not in request.session: if "127.0.0.1" == request.META["REMOTE_ADDR"]: set_location(request, Coord(48, 11)) else: position = get_ip_location(request.META["REMOTE_ADDR"]) set_location(request, position) # return request.session[LOCATION] return Coord(request.session[LOCATION][0], request.session[LOCATION][1])
def walkingpath(request): """ Returns a List/Path of coordinates from origin to destination e.g. http://127.0.0.1:8000/api/walkingpath?originLatitude=48.1234&originLongitude=11.2034&destinationLatitude=48.4532&destinationLongitude=11.4563 :param request: :return: a json """ if request.method == 'GET': if "originLatitude" not in request.GET: return JSONResponse({'error': "origin latitude not found"}, status=400) if "originLongitude" not in request.GET: return JSONResponse({'error': "origin longitude not found"}, status=400) if "destinationLatitude" not in request.GET: return JSONResponse({'error': "destination latitude not found"}, status=400) if "destinationLongitude" not in request.GET: return JSONResponse({'error': "destination longitude not found"}, status=400) originlat = codecs.encode(request.GET["originLatitude"], 'utf-8') originlng = codecs.encode(request.GET["originLongitude"], 'utf-8') destlat = codecs.encode(request.GET["destinationLatitude"], 'utf-8') destlng = codecs.encode(request.GET["destinationLongitude"], 'utf-8') originlat = fix_wrong_coords(originlat) originlng = fix_wrong_coords(originlng) destlat = fix_wrong_coords(destlat) destlng = fix_wrong_coords(destlng) c = Controller(request.session) walking_route = get_walking_Route([originlng, originlat], [destlng, destlat]) start = Coord(originlat, originlng) dest = Coord(destlat, destlng) walking_route['walkingtime'] = c.get_walking_time(walking_route) path = walking_route["coords"] path.insert(0, start) path.append(dest) if (type(path) == int): return JSONResponse({'error': "There was an error on search: " + str(path)}, status=400) serializer = Walkingpath_serializer(path) json = { 'originLatitude': originlat, 'originLongitude': originlng, 'destinationLatitude': destlat, 'destinationLongitude': destlng, 'duration': walking_route['walkingtime'], 'path': serializer.data } return JSONResponse(json) elif request.method == 'POST': return JSONResponse({'error': "only get request supported"}, status=400)
def get_ip_location(ip): """ Looks up the location of the given IP-adress and returns the coords :param ip: as string :return: Coord-object """ if ip.count(".") != 3: print("Error: Not a valid IP-Adress (" + ip + ")") return Coord(0, 0) xml = get_xml("http://freegeoip.net/xml/" + ip) if len(xml) < 9: print("Error: IP-Location could not be found (" + ip + ")") return Coord(0, 0) return Coord(xml[8].text, xml[9].text)
def get_walking_coords(self, walking_route): """ Searches for a walking route and returns the coordinates on this route from start to destination :param walking_route: the XML returned by get_walking_Route :return: list of coords """ if walking_route == []: return [] coords = [] for waypoint in walking_route[1][0][1][0]: arr = waypoint.text.split(" ") coords.append(Coord(arr[1], arr[0])) shortcut = [] coords = replace_coordlist(coords, FH_LONGWAY1, []) return replace_coordlist(coords, FH_LONGWAY2, shortcut)
def stoplist(request): """ Returns a List of possible Stops which fit to the given name e.g. http://127.0.0.1:8000/api/stopList/?query=hauptbahnhof :param request: :return: a json """ initSession(request) if request.method == 'GET': if "query" not in request.GET: return JSONResponse({'error': "qurey not found"}, status=400) if "longitude" not in request.GET: return JSONResponse({'error': "longitude not found"}, status=400) if "latitude" not in request.GET: return JSONResponse({'error': "latitude not found"}, status=400) query = codecs.encode(request.GET["query"], 'utf-8') longitude = codecs.encode(request.GET["longitude"], 'utf-8') if float(longitude) < 0: longitude = str(360 + float(longitude)) latitude = codecs.encode(request.GET["latitude"], 'utf-8') if float(latitude) < 0: latitude = str(360 + float(latitude)) c = Controller(request.session) # Sets the location of the user for further requests loc.set_location(request, Coord(latitude, longitude)) stoplist = c.get_stoplist(query, [longitude, latitude]) if type(stoplist) == int: return JSONResponse({'error': "There was an error on search: " + str(stoplist)}, status=400) serializer = Efa_stop_list_serializer(stoplist) json = { 'query': query, 'suggestions': serializer.data } return JSONResponse(json) elif request.method == 'POST': return JSONResponse({'error': "only get request supported"}, status=400)
def route(request): """ Searches for the best Routes including walking and returns it as json Example: http://127.0.0.1:8000/api/route/?latitude=48.35882&longitude=10.90529&stopid=2000100 """ initSession(request) if request.method == 'GET': if "stopid" not in request.GET: return JSONResponse({'error': "stopid not found"}, status=400) if "longitude" not in request.GET: return JSONResponse({'error': "longitude not found"}, status=400) if "latitude" not in request.GET: return JSONResponse({'error': "latitude not found"}, status=400) stopid = codecs.encode(request.GET["stopid"], 'utf-8') longitude = codecs.encode(request.GET["longitude"], 'utf-8') latitude = codecs.encode(request.GET["latitude"], 'utf-8') if float(longitude) < 0: longitude = str(360 + float(longitude)) if float(latitude) < 0: latitude = str(360 + float(latitude)) loc.set_location(request, Coord(latitude, longitude)) c = Controller(request.session) # Here we do the search for the optimized Route routes = c.get_optimized_routes([longitude, latitude], stopid) if type(routes) == int: return JSONResponse({'error': "There was an error on search: " + str(routes)}, status=400) serializer = RouteListSerializer(RouteList(routes)) return JSONResponse({ 'stopid': stopid, 'longitude': longitude, 'latitude': latitude, 'data': serializer.data }) elif request.method == 'POST': return JSONResponse({'error': "only get request supported"}, status=400)
def get_coords(input_message): """ Запрос координат input_message - отображаемое сообщение """ while (True): user_input = Game.input_function(input_message) try: coords = user_input.split(",") if len(coords) != 2: raise Exception( "Некорректные данные. Слишко много, или мало координат." ) return Coord(int(coords[0]) - 1, int(coords[1]) - 1) except ValueError: print("Некорректные данные. Для ввода допустимы только цифры") except Exception as e: print(e) print()
def construct_player(cls, *args): """Создание игрока""" name = cls.get_name(args[0]) player = Player(name) print('Привет, {}, давай заполним твое поле'.format(name)) for s in cls.storage.ships: i = 0 while (i < s.quantity): try: #запрашиваем левую верхнюю координату корабля coord1 = cls.get_coords( 'Введите координаты для корабля {} № {} в формате "столбец,строка":' .format(s.name, i + 1)) coord2 = Coord(coord1.x, coord1.y) #запрашиваем способ расположения корабля только для многоклеточных if s.size > 1: direction = cls.get_direction( 'Укажите расположение корабля, вертикальное (В), или горизонтальное (Г): [В|Г]' ) if direction == 'В': coord2.y += s.size elif direction == 'Г': coord2.x += s.size #создаем корабль игрока ship = Ship(s.name, s.size, coord1, coord2) player.add_ship(ship) i += 1 clear_screen() Game.print_field(player.field.data, False) except Exception as e: print(e) player.field.clean_aura() return player