Пример #1
0
def api_game_score(game_token):
    """Post a score from the game once the game is over to this endpoint to save it"""
    def check_score(score, game_start_timestamp):
        """
        Checks to see if a given score is even feasible.
        Given it takes 5 seconds to go across the stage left-to-right and
        there are 120 points available per stage crossing attempt. We know
        when you started playing as well as what time it is now so we can
        calculate if your score is even feasible.
        """
        seconds_to_cross_stage = 5
        points_per_coin = 10
        points_per_stage_cross = 12 * points_per_coin
        seconds_elapsed = time() - float(game_start_timestamp)
        practical_maximum = (seconds_elapsed /
                             seconds_to_cross_stage) * points_per_stage_cross
        if score > practical_maximum or score % points_per_coin != 0:
            return False
        else:
            return True

    try:
        token, score_str = base64.standard_b64decode(game_token).decode(
            'utf-8').split(',')
        score = int(score_str)
    except ValueError:
        abort(400)

    game_instance = Score.verify_web_token(token)

    if not game_instance:
        abort(400)

    valid_score = check_score(score, game_instance.created_at)

    if game_instance.token_used or not valid_score:
        return Response(json.dumps({
            'text': 'Permission Denied, score not updated.',
            'score': score
        }),
                        status=403,
                        mimetype='application/json')
    else:
        game_score = int(score)
        game_instance.update(score=game_score,
                             token_used=True,
                             last_modified_at=time())
        return Response(json.dumps({
            'text': 'Score updated',
            'score': game_score
        }),
                        status=200,
                        mimetype="application/json")