Exemple #1
0
def move():
    """
    Called when the Battlesnake Engine needs to know your next my_move.
    The data parameter will contain information about the board.
    Your response must include your my_move of up, down, left, or right.
    """
    start = timer()

    # my_moves
    delta = [
        [-1, 0],  # go up
        [0, -1],  # go left
        [1, 0],  # go down
        [0, 1]
    ]  # go right

    delta_name = ['up', 'left', 'down', 'right']

    # call for data
    data = bottle.request.json
    turn = data['turn']
    # pretty #print
    ##print(f"turn: {turn}\n{json.dumps(data, indent=2)}")
    # board size
    width = data['board']['width']
    height = data['board']['height']

    # my head and body locations
    snakes = data['board']['snakes']
    me = data['you']
    # my health
    my_health = me['health']
    ##print(f'me\n{me}')
    my_head_y = me['body'][0]['y']
    my_head_x = me['body'][0]['x']

    my_tail_y = me['body'][-1]['y']
    my_tail_x = me['body'][-1]['x']

    # find next tail
    my_next_tail_y = me['body'][-2]['y']
    my_next_tail_x = me['body'][-2]['x']

    next_tails = []
    for i in range(len(snakes)):
        next_tail_y = snakes[i]['body'][-2]['y']
        next_tail_x = snakes[i]['body'][-2]['x']

        next_tails.append([next_tail_y, next_tail_x])

    ##print(f'tail yx = {my_tail_y},{my_tail_x}\n'
    #     f'nexttail_yx: {next_tail_y},{next_tail_x}')
    my_id = me['id']

    # for comparison with opponent's snakes
    my_body_len = len(me['body'])

    # moves info
    which_move = ''
    my_move = ''
    move_num = 0

    # flags
    path_found = False
    ready = False
    risky = False
    riskier = False

    # make state info
    # make snakes_grid
    snakes_grid, solo_grid, snake_heads, snake_tails = \
        fill_snakes_grid(snakes, width, height, my_body_len, my_id)

    # check_grid
    check_grid = np.copy(snakes_grid)
    for i in range(len(next_tails)):
        next_tail_y = next_tails[i][0]
        next_tail_x = next_tails[i][1]
        check_grid[next_tail_y, next_tail_x] = 0
    # todo: use this? get distances to snake heads
    # dists, snaketype, y, x
    #snake_dists = check_dist_to_snakes(snake_heads, my_head_y, my_head_x)

    # find free spaces and dists
    # dist, freey, freex
    # check path to free only considers those beyond min_dist
    #free_spaces_arr = find_free_spaces(snakes_grid, my_head_y, my_head_x)

    if risky:
        snakes_grid[snakes_grid == next_samehead_val] = \
            next_smhead_val
        # todo  snakeheads (snaketype, y,x), take out the equal snakes
        # but it's only for food

    elif riskier:
        new_snake_heads = []
        snakes_grid[snakes_grid == next_bighead_val] = \
            next_smhead_val
        for f in range(len(snake_heads)):
            curr_head = snake_heads[f]
            curr_type = curr_head[0]
            if curr_type == big_head_val:
                new_snake_heads.append(curr_head)
        snake_heads = new_snake_heads[:]

    attack = False
    # todo: if longest, start moving towards next_smhead_val on snakes grid

    num_to_attack = 2
    if risky:
        num_to_attack = len(snakes) - 1
    # todo: on risky, could attack with more snakes left
    # attack when only one snake left
    if len(snakes) == num_to_attack:
        for i in range(len(snakes)):
            if len(snakes[i]['body']) < my_body_len:
                attack = True
            else:
                attack = False
                break

    max_dist_for_food = (width + height) * 2

    # leave walls asap
    leave_walls = False
    '''
    if ((my_head_x == 0 or my_head_x == (snakes_grid.shape[1] - 1)) or \
        (my_head_y == 0 or my_head_y == (snakes_grid.shape[0] - 1))) and \
            my_health > 10:
        # print('walls')
        my_move, path_found = get_away_walls(my_head_y, my_head_x,
                                             snakes_grid, check_grid, snake_tails)
        if path_found and my_move != 'snakeshit':
            found_free = check_path_to_tail(my_head_y, my_head_x,
                                            move_num, snakes_grid,
                                            check_grid,
                                            snake_tails)
            if found_free:
                which_move = 'get away walls'
                leave_walls = True
            else:
                path_found = False
    '''
    # if me_longest, chase 8s
    if attack and not leave_walls:
        # print('attack')
        target_arr = []
        # calculate distances and sort
        for j in range(len(snake_heads)):
            snake_type = snake_heads[j][0]
            target_y = snake_heads[j][1]
            target_x = snake_heads[j][2]
            dist = heuristic([target_y, target_x], [my_head_y, my_head_x])
            target_arr.append([dist, target_y, target_x])
        targets = sorted(target_arr, key=lambda x: x[0])
        for i in range(len(targets)):
            victim = targets[i]
            move_num, my_move, path_found = \
                search(victim[1], victim[2], my_head_y, my_head_x,
                       snakes_grid)
            if path_found and my_move != 'snakeshit':

                found_free = check_path_to_tail(my_head_y, my_head_x, move_num,
                                                snakes_grid, check_grid,
                                                snake_tails)
                if found_free:
                    break
                else:
                    path_found = False
            elif my_move == 'snakeshit':
                path_found = False

    # list of dicts of food locations
    food = data['board']['food']
    # list in order of nearest to furthest food tuples (dist, y,x)
    food_arr = []
    # if there is food
    if len(food) > 0:
        food_arr = fill_food_arr(food, my_head_y, my_head_x)
    # there is a food so A star for route to food using snake grid for g
    food_count = 0

    found_path = False
    # get food
    eating = False
    count = 0
    get_it = False
    if not path_found and not leave_walls and not attack:
        # print('food')
        while not eating and count < len(food_arr):
            curr_food = food_arr[count]
            food_dist = curr_food[0]
            food_y = curr_food[1]
            food_x = curr_food[2]
            food_count += 1
            if len(snakes) > 1:
                for i in range(len(snake_heads)):
                    curr_head = snake_heads[i]
                    head_type = curr_head[0]
                    snakehead_y = curr_head[1]
                    snakehead_x = curr_head[2]

                    opp_dist = heuristic([snakehead_y, snakehead_x],
                                         [food_y, food_x])
                    if food_dist < opp_dist:
                        get_it = True
                    elif head_type == small_head_val and \
                            food_dist <= opp_dist:
                        get_it = True
                    else:
                        get_it = False
                        break
            else:
                get_it = True

            if get_it:
                move_num, my_move, path_found = \
                    search(food_y, food_x, my_head_y, my_head_x,
                           snakes_grid, check_grid)
                if path_found:

                    found_free = check_path_to_tail(my_head_y, my_head_x,
                                                    move_num, snakes_grid,
                                                    check_grid, snake_tails)

                    if found_free:
                        which_move = 'get food'
                        eating = True
                    else:
                        path_found = False
                else:
                    path_found = False

            count += 1

    # shorten food_arr
    # food_arr = food_arr[food_count:]
    count = 0
    # chase my tail
    if not path_found and not leave_walls and not attack:
        # print('my tail')
        # chase tail if nothing in food_arr
        move_num, my_move, path_found = search(my_tail_y, my_tail_x, my_head_y,
                                               my_head_x, snakes_grid,
                                               check_grid)
        if path_found:
            '''
            found_free = check_path_to_free(my_head_y, my_head_x,
                                move_num, snakes_grid, free_spaces_arr)
            '''
            found_free = check_path_to_tail(my_head_y, my_head_x, move_num,
                                            snakes_grid, check_grid,
                                            snake_tails)
            if found_free:
                which_move = 'my tail'
            else:
                path_found = False
        else:
            path_found = False

    count = 0
    # chase other snakes' tails
    if not path_found and not leave_walls and not attack:
        # print('other tails')
        for q in range(len(snake_tails)):
            curr_tail = snake_tails[q]
            move_num, my_move, path_found = search(curr_tail[0], curr_tail[1],
                                                   my_head_y, my_head_x,
                                                   snakes_grid, check_grid)
            if path_found:
                '''
                found_free = check_path_to_free(my_head_y, my_head_x,
                                                move_num, snakes_grid, free_spaces_arr)
                '''
                found_free = check_path_to_tail(my_head_y, my_head_x, move_num,
                                                snakes_grid, check_grid,
                                                snake_tails)
                if found_free:
                    which_move = 'opponent tail'
                    break
                else:
                    path_found = False

            else:
                path_found = False

    # sorta random
    # todo: change 9s to 8s
    if not path_found and not leave_walls and not attack:
        # print('random')
        next_heads = [next_smhead_val, next_samehead_val, next_bighead_val]
        for t in range(len(delta)):
            next_y = my_head_y + delta[t][0]
            next_x = my_head_x + delta[t][1]
            if 0 <= next_y < snakes_grid.shape[0] and \
                    0 <= next_x < snakes_grid.shape[1]:
                if snakes_grid[next_y, next_x] == 0 or \
                        snakes_grid[next_y, next_x] in next_heads:
                    my_move = delta_name[t]
                    which_move = 'last resort'
                    # #print(f'my_move: {my_move}')
                    path_found = True
                    break

    shout = "get in my belly!"

    response = {"move": my_move, "shout": shout}
    end = timer()
    # print(f'\n\nturn: {turn}\ntime: {end-start}\nmy_move: {my_move}\n '
    # f'which_move: {which_move}\n\n')
    ##print(f'snakes_grid\n {snakes_grid}\nsolo_grid\n {solo_grid}\n')
    return HTTPResponse(
        status=200,
        headers={"Content-Type": "application/json"},
        body=json.dumps(response),
    )
Exemple #2
0
def search():
    return HTTPResponse(body=dumps(list(DATA.keys())),
                        headers={'Content-Type': 'application/json'})
Exemple #3
0
def index():
    if request.headers.get('X-Header'):
        return 'hello world'
    raise HTTPResponse('Internal server error', status=500, headers={})
Exemple #4
0
def echo_many_schema():
    arguments = parser.parse(hello_many_schema, request)
    return HTTPResponse(body=json.dumps(arguments),
                        content_type="application/json")
Exemple #5
0
    def static_file(filename,
                    root,
                    mimetype=True,
                    download=False,
                    charset='UTF-8',
                    etag=None):
        """ Open a file in a safe way and return an instance of :exc:`HTTPResponse`
            that can be sent back to the client.
            :param filename: Name or path of the file to send, relative to ``root``.
            :param root: Root path for file lookups. Should be an absolute directory
                path.
            :param mimetype: Provide the content-type header (default: guess from
                file extension)
            :param download: If True, ask the browser to open a `Save as...` dialog
                instead of opening the file with the associated program. You can
                specify a custom filename as a string. If not specified, the
                original filename is used (default: False).
            :param charset: The charset for files with a ``text/*`` mime-type.
                (default: UTF-8)
            :param etag: Provide a pre-computed ETag header. If set to ``False``,
                ETag handling is disabled. (default: auto-generate ETag header)
            While checking user input is always a good idea, this function provides
            additional protection against malicious ``filename`` parameters from
            breaking out of the ``root`` directory and leaking sensitive information
            to an attacker.
            Read-protected files or files outside of the ``root`` directory are
            answered with ``403 Access Denied``. Missing files result in a
            ``404 Not Found`` response. Conditional requests (``If-Modified-Since``,
            ``If-None-Match``) are answered with ``304 Not Modified`` whenever
            possible. ``HEAD`` and ``Range`` requests (used by download managers to
            check or continue partial downloads) are also handled automatically.
        """

        root = os.path.join(os.path.abspath(root), '')
        filename = os.path.abspath(os.path.join(root, filename.strip('/\\')))
        headers = dict()

        if not filename.startswith(root):
            return HTTPError(403, "Access denied.")
        if not os.path.exists(filename) or not os.path.isfile(filename):
            return HTTPError(404, "File does not exist.")
        if not os.access(filename, os.R_OK):
            return HTTPError(
                403, "You do not have permission to access this file.")

        if mimetype is True:
            if download and download is not True:
                mimetype, encoding = mimetypes.guess_type(download)
            else:
                mimetype, encoding = mimetypes.guess_type(filename)
            if encoding: headers['Content-Encoding'] = encoding

        if mimetype:
            if (mimetype[:5] == 'text/' or mimetype == 'application/javascript')\
            and charset and 'charset' not in mimetype:
                mimetype += '; charset=%s' % charset
            headers['Content-Type'] = mimetype

        if download:
            download = os.path.basename(
                filename if download is True else download)
            headers[
                'Content-Disposition'] = 'attachment; filename="%s"' % download

        stats = os.stat(filename)
        headers['Content-Length'] = clen = stats.st_size
        headers['Last-Modified'] = email.utils.formatdate(stats.st_mtime,
                                                          usegmt=True)
        headers['Date'] = email.utils.formatdate(time.time(), usegmt=True)

        getenv = request.environ.get

        if etag is None:
            etag = '%d:%d:%d:%d:%s' % (stats.st_dev, stats.st_ino,
                                       stats.st_mtime, clen, filename)
            etag = hashlib.sha1(tob(etag)).hexdigest()

        if etag:
            headers['ETag'] = etag
            check = getenv('HTTP_IF_NONE_MATCH')
            if check and check == etag:
                return HTTPResponse(status=304, **headers)

        if not (etag and check):
            ims = getenv('HTTP_IF_MODIFIED_SINCE')
            if ims:
                ims = parse_date(ims.split(";")[0].strip())
            if ims is not None and ims >= int(stats.st_mtime):
                return HTTPResponse(status=304, **headers)

        body = '' if request.method == 'HEAD' else open(filename, 'rb')

        headers["Accept-Ranges"] = "bytes"
        range_header = getenv('HTTP_RANGE')
        if range_header:
            ranges = list(parse_range_header(range_header, clen))
            if not ranges:
                return HTTPError(416, "Requested Range Not Satisfiable")
            offset, end = ranges[0]
            headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end - 1,
                                                           clen)
            headers["Content-Length"] = str(end - offset)
            if body: body = _file_iter_range(body, offset, end - offset)
            return HTTPResponse(body, status=206, **headers)
        return HTTPResponse(body, **headers)
Exemple #6
0
def ping_response():
    return HTTPResponse(status=200)
Exemple #7
0
def retrieve_videos(db):
    rows = video_repository.retrieve_videos(db)
    return HTTPResponse(status=200, body={'status': 'OK', 'data': rows})
Exemple #8
0
 def __handle_get_config(self):
     out_json = SerializeConfig.config(self.__config)
     return HTTPResponse(body=out_json)
Exemple #9
0
 def error_response(self, code, msg):
     resp = HTTPResponse(status=code, body=msg)
     logger.warn("{0}".format(resp))
     return resp
Exemple #10
0
def health():
    return HTTPResponse(status=200)
Exemple #11
0
def retornar(retorno,status):
    headers = {'Content-type': 'application/json'}
    theBody = {'retorno': retorno}
    return HTTPResponse(status=status, body=theBody,headers=headers)
def error_403():
    print("request was rejected.", request.environ.get('REMOTE_ADDR'))
    return HTTPResponse(status=403)
Exemple #13
0
def ping():
    """
    Used by the Battlesnake Engine to make sure your snake is still working.
    """
    return HTTPResponse(status=200)
Exemple #14
0
def error_404(error):
    r = HTTPResponse(status=302)
    r.set_header('Location', '/')
    return r
Exemple #15
0
def default_banned_http_response():
    '''Response for banned requests'''
    return HTTPResponse("'Banned'",
                        "401 Unauthorized",
                        {"WWW-Authenticate": 'Basic realm="Login Required"'})
Exemple #16
0
 def _authentication_error():
     return HTTPResponse(status=400, output="Invalid password")
Exemple #17
0
def end_response():
    return HTTPResponse(status=200)
Exemple #18
0
def clientHere(id):
    return HTTPResponse(status=200, body='')
Exemple #19
0
def retrieve_videos(playlist_id, db):
    rows = video_repository.retrieve_videos_from_playlist(playlist_id, db)
    return HTTPResponse(status=200, body={'status': 'OK', 'data': rows})
Exemple #20
0
def getPaymentMethod():
    body = json.dumps(["cash", "e_money"])
    return HTTPResponse(status=200, body=body)
Exemple #21
0
def search():
    return HTTPResponse(body=dumps(['users-vs-time', 'tracking-table']),
                        headers={'Content-Type': 'application/json'})
Exemple #22
0
def announced():
    result = bool(j.config.get("ANNOUNCED"))

    return HTTPResponse(j.data.serializers.json.dumps({"announced": result}),
                        status=200,
                        headers={"Content-Type": "application/json"})
Exemple #23
0
def handle_subarchive_path(archivefile,
                           subarchivepath,
                           mimetype,
                           encoding,
                           download=False,
                           charset='UTF-8',
                           etag=None,
                           format=None):
    """Show content of a path in a zip file.
    """
    from bottle import parse_range_header, parse_date, _file_iter_range, tob

    if not os.access(archivefile, os.R_OK):
        return http_error(403,
                          "You do not have permission to access this file.",
                          format=format)

    try:
        zip = zipfile.ZipFile(archivefile)
    except:
        return http_error(500, "Unable to open the ZIP file.", format=format)

    try:
        # KeyError is raised if subarchivepath does not exist
        info = zip.getinfo(subarchivepath)
    except KeyError:
        # subarchivepath does not exist
        # possibility a missing directory entry?
        return handle_zip_directory_listing(zip, archivefile, subarchivepath)

    fh = zip.open(subarchivepath, 'r')

    headers = dict()

    if encoding: headers['Content-Encoding'] = encoding

    if mimetype is True:
        if download and download is not True:
            mimetype, encoding = mimetypes.guess_type(download)
        else:
            mimetype, encoding = mimetypes.guess_type(subarchivepath)
        if encoding: headers['Content-Encoding'] = encoding

    if mimetype:
        if (mimetype[:5] == 'text/' or mimetype == 'application/javascript')\
        and charset and 'charset' not in mimetype:
            mimetype += '; charset=%s' % charset
        headers['Content-Type'] = mimetype

    if download:
        download = os.path.basename(
            subarchivepath if download is True else download)
        headers['Content-Disposition'] = 'attachment; filename="%s"' % download

    headers['Content-Length'] = clen = info.file_size

    lm = info.date_time
    epoch = int(
        time.mktime((lm[0], lm[1], lm[2], lm[3], lm[4], lm[5], 0, 0, -1)))
    headers['Last-Modified'] = email.utils.formatdate(epoch, usegmt=True)

    headers['Date'] = email.utils.formatdate(time.time(), usegmt=True)

    getenv = request.environ.get

    if etag is None:
        etag = '%d:%d:%s' % (epoch, clen, subarchivepath)
        etag = hashlib.sha1(tob(etag)).hexdigest()

    if etag:
        headers['ETag'] = etag
        check = getenv('HTTP_IF_NONE_MATCH')
        if check and check == etag:
            return HTTPResponse(status=304, **headers)

    if not (etag and check):
        ims = getenv('HTTP_IF_MODIFIED_SINCE')
        if ims:
            ims = parse_date(ims.split(";")[0].strip())
        if ims is not None and ims >= int(epoch):
            return HTTPResponse(status=304, **headers)

    body = '' if request.method == 'HEAD' else fh

    headers["Accept-Ranges"] = "bytes"
    range_header = getenv('HTTP_RANGE')
    if range_header:
        ranges = list(parse_range_header(range_header, clen))
        if not ranges:
            return http_error(416, "Requested Range Not Satisfiable")
        offset, end = ranges[0]
        headers["Content-Range"] = "bytes %d-%d/%d" % (offset, end - 1, clen)
        headers["Content-Length"] = str(end - offset)
        if body: body = _file_iter_range(body, offset, end - offset)
        return HTTPResponse(body, status=206, **headers)
    return HTTPResponse(body, **headers)
Exemple #24
0
def announce():
    j.config.set("ANNOUNCED", True)
    return HTTPResponse(j.data.serializers.json.dumps({"announced": True}),
                        status=200,
                        headers={"Content-Type": "application/json"})
Exemple #25
0
def doit(actionmode="NOSPOT"):
    #print("received headers:\n")

    # set up some useful stuff
    auth = False
    headers = {}
    headers_id = {}
    claims = {}
    claims_id = {}
    code = 0
    code_id = 0

    # find the keycloak headers in what we received
    for k, v in request.headers.items():
        #print("key k = ", k)
        #print("val v = ", v)

        if k == 'Authorization':
            # split out the 'Bearer ' from the header, we don't need it
            values = v.split(' ')
            # verify the access_token has wholesomeness
            code, headers, claims = verify_header(values[1], pub_key)

        # we don't use values in the id_token currently but
        # we can check it has wholesomeness anyeay
        if k == 'Id-Token':
            code_id, headersid, claims_id = verify_header(v, pub_key)

    # nothing found
    if code == 0:
        raise HTTPResponse(status=200, body="Quoi?")

    # the token is expired
    if code == 401:
        raise HTTPResponse(
            status=401,
            body=json.dumps({
                "error": "invalid_token",
                "error_description": "The access token expired"
            }),
            headers={
                'Content-type':
                'application/json',
                'WWW-Authenticate':
                'Bearer error="invalid_token"  error_description="The access token expired"'
            })

    # the token didn't veirfy, missing data or signing wrong
    if code == 400:
        raise HTTPResponse(
            status=400,
            body=json.dumps({
                "error":
                "invalid_token",
                "error_description":
                "The access token is malformed or data is wrong"
            }),
            headers={
                'Content-type':
                'application/json',
                'WWW-Authenticate':
                'Bearer error="invalid_token"  error_description="The access token is malformed or data is wrong"'
            })

    # the headers are wholesome
    if code == 200:
        # check the user has the right permissions for this access
        if not validate_user(Claims, claims):
            # user is not valid
            raise HTTPResponse(status=400, body="Bad user request")

        # here we have valid headers, a permitted user and good stuff
        # get the urlencode data into json
        d = request.query
        body = {}
        for k, v in d.items():
            #rint(k, v)
            body[k] = v

        # are we spotting or just checking
        body['callsign'] = claims['callsign']
        body['userID'] = claims['userID']
        jbody = json.dumps(body)

        print("request elements:")
        for k, v in body.items():
            print(k, v)

        print("request json:", jbody)

        if actionmode == 'SPOT':
            # call the spotter
            apiresp = req.get("http://127.0.0.1:8140/spotmessl", params=body)

            # did it work ok?
            if apiresp.status_code == 200:
                raise HTTPResponse(status=200, body="spot ok")
            else:
                raise HTTPResponse(status=400,
                                   body=json.dumps({
                                       "error":
                                       "spotting error",
                                       "error-description":
                                       "the spot was rejected"
                                   }))
        else:
            raise HTTPResponse(status=200,
                               headers={'Content-type': 'application/json'},
                               body=jbody)
Exemple #26
0
def heartbeat():
    return HTTPResponse(status=200)
 def test_valid_post_response_as_http_body(self):
     response = self._test_request(
         method='POST',
         extra_check=self.check_for_request_addons,
         response_json=HTTPResponse(body=self.VALID_JSON))
     self.assertEqual(response.status_int, 200)
Exemple #28
0
def health():
    status = subprocess.check_output(["sv", "status", "exporter"])
    if status.startswith("run: exporter:"):
        return "Exporter is running\n"
    else:
        return HTTPResponse(body='Exporter is not running\n', status=500)
Exemple #29
0
def response(file_name):
    body = open(file_name, 'rb') or gzip.open(file_name, 'rb')
    headers = {'Content-Encoding': 'gzip', 'Content-Type': 'application/zip'}
    return HTTPResponse(body=body, status=200, headers=headers)
Exemple #30
0
def r404(message):
	raise HTTPResponse(json.dumps({"success": False, "error": {"message": message}}), 404)