Exemplo n.º 1
0
def game_information(data):
    game_id = data['game_id']

    # Read game
    file_name = "gameId_{}.json".format(game_id)
    game = read4json('games/' + file_name)

    # General info to return
    general_info = {
        'players number':
        game['players number'],
        'players ready':
        game['players ready'],
        'rounds number':
        game['rounds number'],
        'round actual':
        game['round actual'],
        'game id':
        game['game id'],
        'date':
        game['date'],
        'state':
        game['state'],
        'players info': [{
            'id': player['id'],
            'asigned': player['asigned'],
            'can play': player['can play']
        } for player in game['players']]
    }
    emit('game_general_information', general_info)
Exemplo n.º 2
0
def game_info(message):
    """
    All the information about the game.

    Parameters
    ----------
    game_id: int
      Unique game id.
    admin_key : str
      Unique admin key.

    Request body
    ------------
    game: JSON
      JSON with all the informaton about the game.

    Errors
    ------
    400: Game id not exist.
    401: Admin key invalid.
    """
    check_game_id(message['game_id'])
    check_admin_key(message['game_id'], message['admin_key'])

    # Read game file
    file_name = "gameId_{}.json".format(message['game_id'])
    game = read4json('games/' + file_name)

    return jsonify(game)
Exemplo n.º 3
0
def delet_player(game_id, admin_key, player_id):
    """
    Delet an existent players.

    Parameters
    ----------
    game_id: int
      Unique game id.
    admin_key : str
      Unique admin key.
    player_id: int
      Unique player id.

    Request body
    ------------
    message: str
      Ok

    Errors
    ------
    400: Game id not exist.
    400: Player id not exist.
    401: Admin key invalid.
    """
    check_game_id(game_id)
    check_admin_key(game_id, admin_key)

    # Read game file
    file_name = "gameId_{}.json".format(game_id)
    game = read4json('games/' + file_name)

    # Check if the player id exist
    if len(game['players']) < player_id:
        abort(400, 'Player id not exist')

    # Delet player and generate a new key for this payer
    game['players'][player_id]['asigned'] = False
    game['players'][player_id]['key'] = key_generator()

    # Save the game file
    file_name = "{}gameId_{}.json".format(games_path, game_id)
    save2json(file_name, game)

    # Read all unasigned players numbers
    asigned = [x['asigned'] for x in game['players']]
    numbers = [num for num, val in enumerate(asigned) if not val]

    out = {
        'messag': 'player deleted',
        'player ready': game['players num'] - len(numbers),
        'missing players': len(numbers)
    }
    return jsonify(out)
Exemplo n.º 4
0
def player_information(data):
    """
    Send player information
    """
    game_id = data['game_id']
    player_id = data['player_id']

    # Read game
    file_name = "gameId_{}.json".format(game_id)
    game = read4json('games/' + file_name)

    info = game['players'][player_id]
    emit('player_information', info)
Exemplo n.º 5
0
def player_connection():
    """
    Connect the player to the server via webSocket.
    Join the player in a room[game_id].

    Query Parameters
    ----------------
    game_id: int
      Unique game id.
    player_id: int
      Unique player id.

    Event return name
    -----------------
    connecting_players

    Return
    ------
    players_ready: list
      List with True or False of all players if the player is ready.
    start_game: bool
      If all players are ready, is True. Else, False.

    TODO
    ----
    * No estoy controlando el player_id ni el game_id
    """
    player_id = int(request.args.get('player_id'))
    game_id = int(request.args.get('game_id'))
    # The room name is the unique game id
    join_room(game_id)
    join_room(str(game_id) + '-' + str(player_id))

    # Read game file
    file_name = "gameId_{}.json".format(game_id)
    game = read4json('games/' + file_name)

    ready = [player['asigned'] for player in game['players']]
    can_start = all([player['asigned'] for player in game['players']])
    out = {'players_ready': ready, 'start_game': can_start}

    emit('connecting_players', out, room=game_id)
Exemplo n.º 6
0
def check_admin_key(game_id, key):
    """
    Check if the admin key is correct.

    Parameters
    ----------
    key: str
      Unique key use to authenticating.
    game_id: int
      Unique game id.

    Error
    -----
    401: Invalid key.
    """
    file_name = "gameId_{}.json".format(game_id)
    game_file = read4json('games/' + file_name)

    if key != game_file["admin key"]:
        abort(401, 'Invalid admin key')
Exemplo n.º 7
0
def check_player_key(game_id, player_id, key):
    """
    Check if the player key is correct.

    Parameters
    ----------
    pleyer_id: int
      Unique player id
    key: str
      Unique key use to authenticating.
    game_id: int
      Unique game id.

    Error
    -----
    401: Invalid key.
    """
    file_name = "gameId_{}.json".format(game_id)
    game_file = read4json('games/' + file_name)

    if key != game_file["players"][player_id]['key']:
        abort(401, 'Invalid player key')
Exemplo n.º 8
0
def extract_resources(data):
    """
    Make a resource extraction.

    Parameter
    ---------
    game_id: int
      Unique game id.
    player_id: int
      Unique player id.
    extraction: int
      Number of extracted resources.

    Event return name
    -----------------
    game_general_infomation

    Return
    ------


    TODO
    ------
    Error: Is not your turn to play.
    Error: Is not all player ready to play.
    """
    """
    # Check if all players are ready to play
    ready = all([player['asigned'] for player in game['players']])
    if not ready:
        return jsonify({'error': "Missing players to start the game."})

    # Check if is the player turn to play
    if not game['players'][player_id]['can play']:
        return jsonify({'error': 'Is not your turn to play'})
    """
    game_id = data['game_id']
    player_id = data['player_id']

    # Read game
    file_name = "gameId_{}.json".format(game_id)
    game = read4json('games/' + file_name)

    # Save player extraction
    extraction = {
        'extraction': data['extraction'],
        'total extraction': -1,
        'other extraction': -1,
        'penalty': 0,
        'gain': -1,
        'gain_penalty': -1
    }
    game['players'][player_id]['rounds'].append(extraction)
    game['players'][player_id]['can play'] = False

    # Check if round finished
    can_play = [player['can play'] for player in game['players']]
    round_end = True not in can_play
    if round_end:
        calculate_gain(game)
        send_rules_message(game)

    # Save the game file
    file_name = "{}gameId_{}.json".format(games_path, game_id)
    save2json(file_name, game)

    # General info to return
    general_info = {
        'players number':
        game['players number'],
        'players ready':
        game['players ready'],
        'rounds number':
        game['rounds number'],
        'round actual':
        game['round actual'],
        'game id':
        game['game id'],
        'date':
        game['date'],
        'state':
        game['state'],
        'players info': [{
            'id': player['id'],
            'asigned': player['asigned'],
            'can play': player['can play']
        } for player in game['players']]
    }

    emit('game_general_information', general_info, room=game_id)
Exemplo n.º 9
0
def new_player(game_id):
    """
    Create new player in a existen game. Generate the player credential.

    Parameter
    ---------
    game_id: int
      Unique game id.

    Request body
    ------------
    player id: int
      Unique player id randomly assigned.
    player key: str
      Unique player key used for authenticating.

    Error
    -----
    400: Game id not exist.
    400: All players was assigned.
    """
    check_game_id(game_id)

    # Read game
    file_name = "gameId_{}.json".format(game_id)
    game = read4json('games/' + file_name)

    # Read all unasigned players numbers
    asigned = [x['asigned'] for x in game['players']]
    numbers = [num for num, val in enumerate(asigned) if not val]

    # All players were assigned
    if not numbers:
        abort(400, 'All players was assigned.')

    # Choice a random number of player
    player_id = int(random.choice(numbers))
    game['players'][player_id]['asigned'] = True

    # Update the game state
    ready_players = game["players number"] - (len(numbers) - 1)
    if ready_players > 0:
        text = "waiting players ({0}/{1})".format(ready_players,
                                                  game["players number"])
        game['state'] = text
    else:
        game['state'] = "play"

    game['players ready'] = ready_players

    # Check if all players are asigned.
    # If true, 'can play' of each play is put true
    ready = all([player['asigned'] for player in game['players']])
    if ready:
        for player in game['players']:
            player['can play'] = True

    # Save the game file
    file_name = "{}gameId_{}.json".format(games_path, game_id)
    save2json(file_name, game)

    out = {
        'player id': player_id,
        'player key': game['players'][player_id]['key']
    }
    return jsonify(out)