Exemplo n.º 1
0
def start():

    token = request.json.get('token')
    if token is None:
        abort(401, 'Authentication token is absent! You should request token by POST {post_token_url}'.format(post_token_url=url_for('user.post_token')))
    requesting_user = User.verify_api_auth_token(token)

    hosted_room = Room.query.filter_by(host=requesting_user, closed=None).first()
    if not hosted_room:
        abort(403, 'User {username} does not have open rooms! Create room by POST {create_room_url} before managing games.'.format(
            username=requesting_user.username,
            create_room_url=url_for('room.create')
        ))
    if not app.config['MIN_PLAYER_TO_START'] <= hosted_room.connected_users.count() <= app.config['MAX_PLAYER_TO_START']:
        abort(403, 'Incorrect number of players to start ({players_count} connected to room {room_name}!'.format(
            players_count=hosted_room.connected_users.count(),
            room_name=hosted_room.room_name
        ))
    for room_game in hosted_room.games:
        if room_game.finished is None:
            abort(403, 'Game {game_id} is already started at {game_start} and is not finished yet! You cannot run more than one game in room at one moment!'.format(
                game_id=room_game.id,
                game_start=room_game.started
            ))

    g = Game(room=hosted_room)
    db.session.add(g)
    db.session.commit()

    players_list = []
    for player in hosted_room.connected_users.all():
        g.connect(player)
        p = Player(game_id=g.id, user_id=player.id)
        db.session.add(p)
        players_list.append(player.username)
    db.session.commit()

    return jsonify({
        'gameId': g.id,
        'room': g.room.room_name,
        'host': g.room.host.username,
        'status': 'active' if g.finished is None else 'finished',
        'started': g.started,
        'players': players_list
    }), 200