Exemplo n.º 1
0
def delete(update, context):
    """
    Delete the 'Confirmed' match from 'predictions' table.
    """

    chat_id = update.message.chat_id
    user = utl.get_nickname(update)

    if utl.wrong_chat(chat_id=chat_id):
        message_id = update.message.message_id
        context.bot.deleteMessage(chat_id=chat_id, message_id=message_id)
        return context.bot.send_message(
            chat_id=utl.get_user_chat_id(update),
            text='Usa questo gruppo per i comandi.')

    pred_to_delete = utl.prediction_to_delete(nickname=user)
    if not pred_to_delete:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Nessun pronostico da eliminare')

    dbf.db_delete(table='predictions', where=f'id = {pred_to_delete}')

    dbf.db_delete(table='to_play', where=f'pred_id = {pred_to_delete}')

    utl.remove_bet_without_preds()

    context.bot.send_message(chat_id=chat_id, text='Pronostico eliminato')

    # Send summary in group chat
    summary_updated = utl.create_summary_pending_bet()
    return context.bot.send_message(
        parse_mode='HTML',
        chat_id=cfg.GROUP_ID,
        text=f'Pronostico eliminato.\n\n{summary_updated}')
Exemplo n.º 2
0
def cancel(update, context, text: str = ''):
    """
    Delete the 'Not Confirmed' match from 'predictions' table.
    """

    chat_id = update.message.chat_id
    user = utl.get_nickname(update)

    if utl.wrong_chat(chat_id=chat_id):
        message_id = update.message.message_id
        context.bot.deleteMessage(chat_id=chat_id, message_id=message_id)
        return context.bot.send_message(
            chat_id=utl.get_user_chat_id(update),
            text='Usa questo gruppo per i comandi.')

    if utl.nothing_pending(nickname=user):
        return context.bot.send_message(chat_id=chat_id,
                                        text='Nessun pronostico da eliminare')

    dbf.db_delete(table='predictions',
                  where=f'user = "******" AND status = "Not Confirmed"')
    utl.remove_bet_without_preds()

    if not text:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Pronostico eliminato')
    else:
        return context.bot.send_message(chat_id=chat_id, text=text)
Exemplo n.º 3
0
def confirm(update, context):
    """
    Confirm the match and update the database.
    """

    chat_id = update.message.chat_id
    user = utl.get_nickname(update)

    if utl.wrong_chat(chat_id=chat_id):
        message_id = update.message.message_id
        context.bot.deleteMessage(chat_id=chat_id, message_id=message_id)
        return context.bot.send_message(
            chat_id=utl.get_user_chat_id(update),
            text='Usa questo gruppo per i comandi.')

    if utl.nothing_pending(nickname=user):
        return context.bot.send_message(chat_id=chat_id,
                                        text='Nessun pronostico da confermare')

    if utl.match_already_chosen(nickname=user):
        return cancel(update,
                      context,
                      text='Pronostico non valido perché già presente')

    if utl.match_already_started(table='predictions', nickname=user):
        return cancel(update, context, text='Match già iniziato')

    if utl.quote_outside_limits(nickname=user):
        return cancel(update, context, text='Quota fuori limiti')

    # Remove other "Not Confirmed" preds of the same match, if any
    utl.remove_pending_same_match(nickname=user)

    # Update prediction status
    dbf.db_update(table='predictions',
                  columns=['status'],
                  values=['Confirmed'],
                  where=f'user = "******" AND status = "Not Confirmed"')

    # Insert bet in the table "to_play"
    bet_id = utl.get_pending_bet_id()
    utl.update_to_play_table(nickname=user, bet_id=bet_id)

    # Notify user in private chat
    context.bot.send_message(chat_id=chat_id,
                             text='Pronostico aggiunto correttamente')

    # Send summary in group chat
    summary = utl.create_summary_pending_bet()
    context.bot.send_message(parse_mode='HTML',
                             chat_id=cfg.GROUP_ID,
                             text=summary)

    # Play the bet automatically
    if utl.autoplay():
        return play(update, context)
Exemplo n.º 4
0
def main():
    """Client side of Dice Wars
    """
    parser = ArgumentParser(prog='Dice_Wars-client')
    parser.add_argument('-p',
                        '--port',
                        help="Server port",
                        type=int,
                        default=5005)
    parser.add_argument('-a',
                        '--address',
                        help="Server address",
                        default='127.0.0.1')
    parser.add_argument('-d',
                        '--debug',
                        help="Enable debug output",
                        default='WARN')
    parser.add_argument('-s',
                        '--seed',
                        help="Random seed for a client",
                        type=int)
    parser.add_argument('--ai', help="Ai version")
    args = parser.parse_args()

    random.seed(args.seed)

    config = configparser.ConfigParser()
    config.read('dicewars.config')
    ai_driver_config = config['AI_DRIVER']

    ui.MAX_TRANSFERS_PER_TURN = ai_driver_config.getint('MaxTransfersPerTurn')

    log_level = get_logging_level(args)

    logging.basicConfig(level=log_level)

    hello_msg = {
        'type': 'client_desc',
        'nickname': get_nickname(args.ai),
    }
    game = Game(args.address, args.port, hello_msg)

    if args.ai:
        ai = AIDriver(game, get_ai_constructor(args.ai), ai_driver_config)
        ai.run()
    else:
        app = QApplication(sys.argv)
        human_ui = ui.ClientUI(game)
        sys.exit(app.exec_())
Exemplo n.º 5
0
def join_meeting(meeting_uuid: str, user_uuid: str):
    validate_meeting_uuid(meeting_uuid)
    validate_user_uuid(user_uuid)

    check_json_data()
    nickname = get_nickname()

    meeting = find_meeting(meeting_uuid)
    user = find_user(user_uuid)

    membership = Membership(user=user, meeting=meeting, nickname=nickname)
    db.session.add(membership)
    try:
        db.session.commit()
    except (IntegrityError, FlushError):
        raise ApiException('Already a member', 400)

    return '', 204
Exemplo n.º 6
0
def main():
    """Client side of Dice Wars
    """
    parser = ArgumentParser(prog='Dice_Wars-client')
    parser.add_argument('-p',
                        '--port',
                        help="Server port",
                        type=int,
                        default=5005)
    parser.add_argument('-a',
                        '--address',
                        help="Server address",
                        default='127.0.0.1')
    parser.add_argument('-d',
                        '--debug',
                        help="Enable debug output",
                        default='WARN')
    parser.add_argument('-s',
                        '--seed',
                        help="Random seed for a client",
                        type=int)
    parser.add_argument('--ai', help="Ai version")
    args = parser.parse_args()

    random.seed(args.seed)

    log_level = get_logging_level(args)

    logging.basicConfig(level=log_level)
    logger = logging.getLogger('CLIENT')

    hello_msg = {
        'type': 'client_desc',
        'nickname': get_nickname(args.ai),
    }
    game = Game(args.address, args.port, hello_msg)

    if args.ai:
        ai = AIDriver(game, get_ai_constructor(args.ai))
        ai.run()
    else:
        app = QApplication(sys.argv)
        ui = ClientUI(game)
        sys.exit(app.exec_())
Exemplo n.º 7
0
def create_meeting():
    check_json_data()
    owner_uuid = get_owner_uuid()
    name = get_meeting_name()
    description = get_meeting_description()
    dt = get_datetime()
    nickname = get_nickname()

    owner = find_user(owner_uuid)

    meeting = Meeting(name=name,
                      description=description,
                      datetime=dt,
                      owner=owner)
    membership = Membership(meeting=meeting, user=owner, nickname=nickname)
    db.session.add(membership)
    db.session.commit()

    return make_response({
        'uuid': meeting.uuid,
    }, 201, {'Location': f'/api/v1/meetings/{meeting.uuid}'})
Exemplo n.º 8
0
def main():
    args = parser.parse_args()
    if args.ai_under_test is not None:
        combatants_provider = EvaluationCombatantsProvider(
            PLAYING_AIs, args.ai_under_test)
    else:
        combatants_provider = TournamentCombatantsProvider(PLAYING_AIs)
    random.seed(args.seed)

    signal(SIGCHLD, signal_handler)

    if args.load:
        with open(args.load, 'rb') as f:
            all_games = pickle.load(f)
    else:
        all_games = []

    boards_played = 0
    reporter = SingleLineReporter(not args.report)
    try:
        for board_definition in board_definitions(args.board):
            if boards_played == args.nb_boards:
                break
            boards_played += 1

            combatants = combatants_provider.get_combatants(args.game_size)
            nb_permutations, permutations_generator = rotational_permunations_generator(
                combatants)
            for i, permuted_combatants in enumerate(permutations_generator):
                reporter.report('\r{} {}/{} {}'.format(
                    boards_played, i + 1, nb_permutations,
                    ' vs. '.join(permuted_combatants)))
                game_summary = run_ai_only_game(
                    args.port,
                    args.address,
                    procs,
                    permuted_combatants,
                    board_definition,
                    fixed=UNIVERSAL_SEED,
                    client_seed=UNIVERSAL_SEED,
                    logdir=args.logdir,
                    debug=args.debug,
                )
                all_games.append(game_summary)
    except (Exception, KeyboardInterrupt) as e:
        sys.stderr.write("Breaking the tournament because of {}\n".format(
            repr(e)))
        lockfile = open('/mnt/w/lock', 'w')
        fcntl.flock(lockfile, fcntl.LOCK_EX)
        for p in procs:
            p.kill()
        fcntl.flock(lockfile, fcntl.LOCK_UN)

    reporter.clean()

    if args.save:
        with open(args.save, 'wb') as f:
            pickle.dump(all_games, f)

    for game in all_games:
        participants = game.participants()
        for player in players_info:
            if get_nickname(player) in participants:
                players_info[player]['games'].append(game)

    performances = [
        PlayerPerformance(player, info['games'], PLAYING_AIs)
        for player, info in players_info.items()
    ]
    performances.sort(key=lambda perf: perf.winrate, reverse=True)

    perf_strings = [performances[0].competitors_header()
                    ] + [str(perf) for perf in performances]
    fields = [perf.split() for perf in perf_strings]

    print(column_t(fields))
Exemplo n.º 9
0
def get(update, context):
    """
    /get team       -> Return all quotes of the match, if found
    /get team_bet   -> Return the requested quote, if found
    /get team_quote -> Return all the bets with the specified quote, if found
    """

    args = context.args
    chat_id = update.message.chat_id
    text = ' '.join(args).upper()

    if utl.wrong_chat(chat_id=chat_id):
        message_id = update.message.message_id
        context.bot.deleteMessage(chat_id=chat_id, message_id=message_id)
        return context.bot.send_message(
            chat_id=utl.get_user_chat_id(update),
            text='Usa questo gruppo per i comandi.')

    if utl.wrong_format(input_text=text):
        message = ('Formato non corretto. ' +
                   'Ex:\n\t- /get squadra_pronostico\n\t- /get squadra')
        return context.bot.send_message(chat_id=chat_id, text=message)

    team = utl.fix_team_name(text.split('_')[0])
    if not team:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Squadra non riconosciuta')

    match_details = utl.get_match_details(team_name=team)
    if not match_details:
        return context.bot.send_message(
            chat_id=chat_id, text=f'Nessun match trovato per {team}')

    # If only team is sent, send all quotes of that match
    if '_' not in text:
        standard, combo = utl.all_bets_per_team(team_name=team)

        if not combo:
            return context.bot.send_message(chat_id=chat_id, text=standard)

        context.bot.send_message(parse_mode='MarkdownV2',
                                 chat_id=chat_id,
                                 text=f'`{standard}`')
        return context.bot.send_message(parse_mode='MarkdownV2',
                                        chat_id=chat_id,
                                        text=f'`{combo}`')

    # Try to recognize the bet sent by user
    bet = text.split('_')[1]
    bet = utl.fix_bet_name(bet)
    if not bet:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Pronostico non riconosciuto')

    # Extract match details
    match_id, league, team1, team2, dt, _ = match_details[0]
    team1 = team1.replace('*', '')
    team2 = team2.replace('*', '')

    quote = utl.get_bet_quote(match_id=match_id, bet_name=bet)
    if not quote:
        return context.bot.send_message(chat_id=chat_id,
                                        text='Pronostico non quotato')

    bet_id = utl.get_pending_bet_id()
    if not bet_id:
        bet_id = utl.insert_new_bet_entry()

    # Insert prediction as "Not Confirmed"
    user = utl.get_nickname(update)
    pred_id = dbf.db_insert(table='predictions',
                            columns=[
                                'bet_id', 'user', 'date', 'team1', 'team2',
                                'league', 'bet_alias', 'quote', 'status'
                            ],
                            values=[
                                bet_id, user, dt, team1, team2, league, bet,
                                quote, 'Not Confirmed'
                            ],
                            last_index=True)

    # Remove other pending predictions the user might have
    dbf.db_delete(table='predictions',
                  where=(f'id != {pred_id} AND user = "******" AND ' +
                         'status = "Not Confirmed"'))

    # Ask user for confirmation
    bet_details = '{} - {} {} @{}'.format(team1, team2, bet, quote)
    message = f'{bet_details}\n\n/confirm                /cancel'
    return context.bot.send_message(chat_id=chat_id, text=message)
Exemplo n.º 10
0
def main():

    args = parser.parse_args()

    PLAYING_AIs.append(args.user_ai_name)
    players_info = {ai: {'games': []} for ai in PLAYING_AIs}

    if args.ai_under_test is not None:
        combatants_provider = EvaluationCombatantsProvider(
            PLAYING_AIs, args.ai_under_test)
    else:
        combatants_provider = TournamentCombatantsProvider(PLAYING_AIs)
    random.seed(args.seed)

    signal(SIGCHLD, signal_handler)

    all_games = []

    boards_played = 0
    try:
        for board_definition in board_definitions(args.board):
            if boards_played == args.nb_boards:
                break
            boards_played += 1

            combatants = combatants_provider.get_combatants(args.game_size)
            nb_permutations, permutations_generator = rotational_permunations_generator(
                combatants)
            for i, permuted_combatants in enumerate(permutations_generator):
                game_summary = run_ai_only_game(
                    args.port,
                    args.address,
                    procs,
                    permuted_combatants,
                    board_definition,
                    fixed=UNIVERSAL_SEED,
                    client_seed=UNIVERSAL_SEED,
                )
                all_games.append(game_summary)
    except (Exception, KeyboardInterrupt) as e:
        sys.stderr.write("Breaking the tournament because of {}\n".format(
            repr(e)))
        for p in procs:
            p.kill()
        raise

    for game in all_games:
        participants = game.participants()
        for player in players_info:
            if get_nickname(player) in participants:
                players_info[player]['games'].append(game)

    performances = [
        PlayerPerformance(player, info['games'], PLAYING_AIs)
        for player, info in players_info.items()
    ]
    performances.sort(key=lambda perf: perf.winrate, reverse=True)

    perf_strings = [performances[0].competitors_header()
                    ] + [str(perf) for perf in performances]
    fields = [perf.split() for perf in perf_strings]

    print(column_t(fields))