Exemple #1
0
    def create_history(self) -> bool:
        """Creates a instance of bet in bet_history in database

        """
        logger.debug(f'bet.create_history: {self}')

        # Check if needed fields are not None
        if self._winner is None or self._bet_time is None or self._is_history is None:
            logger.error('missing needed field')
            raise exception.UnableToWrite(
                message='Unable to write missing needed fields',
                class_='Bet',
                attribute='winner, bet_time, is_history')

        # Check if create_bet_history was successful, return true if it was
        if database_operation.create_bet_history(DbHandler.db_cnc, self.id,
                                                 self._amount, self.match.id,
                                                 self.bettor.id,
                                                 self._bet_target.id,
                                                 self._winner.id,
                                                 self._bet_time):
            logger.debug('Wrote bet to bet_history')
            # Delete bet from table, raise exception if unable to write
            if not database_operation.delete_bet(DbHandler.db_cnc, self.id):
                logger.error(f'Unable to delete bet({self.id}) from bets')
                raise exception.UnableToDelete(attribute='bets')
            return True
        else:
            logger.error(f'Unable to write bet({self.id}) to bet_history')
            raise exception.UnableToWrite(attribute='bet_history')
Exemple #2
0
def create_bet(ctx: commands.Context, bet_id: int, amount: int,
               match: matches.Match, bettor: account.Account,
               bet_target: account.Account) -> Union[Bet, int]:
    """Creates a bet in database and returns the bet from database as a Bet

    """
    logger.debug(
        f'bet.create_bet: {bet_id}, {amount}, {match}, {bettor}, {bet_target}')

    # Assuming bet_id is None, refill bet_id with results of bet_create, if zero write was unsuccessful
    bet_id = database_operation.create_bet(DbHandler.db_cnc, bet_id, amount,
                                           match.id, bettor.id, bet_target.id)
    logger.debug(f'bet_id: {bet_id}')

    # Check if bet_id is valid (Non zero)
    if not bet_id:
        logger.error('Unable to create bet')
        raise exception.UnableToWrite(class_='Bet', attribute='bet')

    # Create bet from bet_id if bet_id is valid
    bet = get_bet(ctx, bet_id)
    logger.debug(f'bet: {bet}')
    if not bet:
        logger.error('Unable to create bet')
        raise exception.UnableToRead(class_='Bet', attribute='bet')

    return bet
Exemple #3
0
def create_match(ctx,
                 match_id: int,
                 amount: int,
                 challenger: acc.Account,
                 recipient: acc.Account,
                 active: bool = False,
                 accepted: bool = False,
                 game: str = 'melee',
                 format: str = 'Bo3') -> Union[Match, int]:
    logger.debug(
        f'match.create_match: {match_id}, {amount}, {challenger}, {recipient}, {active}, {accepted}'
    )

    # Assuming match_id is None, refill match_id with results of create_match, if zero write was unsuccessful
    match_id = database_operation.create_match(DbHandler.db_cnc, match_id,
                                               amount, challenger.id,
                                               recipient.id, active, accepted,
                                               game, format)
    logger.debug(f'match_id: {match_id}')

    # Check if match_id is valid (Non zero)
    if not match_id:
        logger.error('Unable to create match')
        raise exception.UnableToWrite(attribute='matches')

    # Create Match from match_id, check if match is valid
    match = get_match(ctx, match_id)
    logger.debug(f'match: {match}')
    if not match:
        logger.error('Unable to create match')
        raise exception.UnableToRead(class_='Match', attribute='match')

    return match
Exemple #4
0
    def bet_target(self, bet_target: account.Account):
        logger.debug(f'bet_target: {bet_target}')

        if database_operation.update_bet(DbHandler.db_cnc, self._amount,
                                         bet_target.id, self._amount):
            logger.debug(f'Updated bet_target')
            self._bet_target = bet_target
        else:
            logger.error('Unable to write bet_target')
            raise exception.UnableToWrite(class_='Bet', attribute='bet_target')
Exemple #5
0
 def friendly_last_used(self, time: datetime):
     logger.debug(f'friendly_last_used_setter: {time}')
     # Try and write to database
     try:
         database_operation.update_friendly(database_setup.DbHandler.db_cnc,
                                            self.id, time)
         logger.debug(f'Wrote friendly_last_used: {time}')
     except Exception as e:
         logger.error(f'Unable to write friendly_last_used: {e}')
         raise exception.UnableToWrite(class_='Account',
                                       attribute='friendly_last_used')
Exemple #6
0
    def amount(self, amount):
        logger.debug(f'amount_setter" {amount}')

        # Update amount in database, check if write was successful then update Bet info
        if database_operation.update_bet(DbHandler.db_cnc, self.id,
                                         self._bet_target.id, amount):
            logger.debug(f'amount updated')
            self._amount = amount
        else:
            logger.error('Unable to update amount')
            raise exception.UnableToWrite(class_='Bet',
                                          attribute='amount',
                                          value=amount)
Exemple #7
0
    def accepted(self, accepted: bool):
        logger.debug(f'accepted_setter: {accepted}')

        # Update accepted in database, check if write was successful then update Match info
        if database_operation.update_match_accepted(DbHandler.db_cnc, self.id,
                                                    int(accepted)):
            self._accepted = accepted
            logger.debug('Updated accepted')
        else:
            logger.error('Unable to update accepted')
            raise exception.UnableToWrite(class_='Match',
                                          attribute='accepted',
                                          value=accepted)
Exemple #8
0
    def nickname(self, nickname: str):
        logger.debug(f'nickname_setter: {nickname}')

        # Update nickname in database, check if write was successful then update Account info
        if database_operation.update_player_nickname(
                database_setup.DbHandler.db_cnc, self.id, nickname):
            self._nickname = nickname
            logger.debug('Updated nickname')
        else:
            logger.error('Unable to update nickname')
            raise exception.UnableToWrite(class_='Account',
                                          attribute='nickname',
                                          value=nickname)
Exemple #9
0
    def create_history(self) -> bool:
        logger.debug(f'match.create_History: {self}')
        # Check if create_match_history was successful, return True if it was
        if database_operation.create_match_history(
                DbHandler.db_cnc, self.id, self.amount, self.challenger.id,
                self.recipient.id, self._winner.id, self._match_time,
                self._game, self._format):
            logger.debug('Wrote match to match_history')
            # Delete match from table, raise exception if unable to write
            if not database_operation.delete_match(DbHandler.db_cnc, self.id):
                logger.error('Unable to delete match from matches')
                raise exception.UnableToDelete(attribute='matches')

            return True
        else:
            logger.error('Unable to write to match_history')
            raise exception.UnableToWrite(attribute='match_history')
Exemple #10
0
    def marbles(self, amount: int):
        logger.debug(f'marbles_setter: {amount}')
        # Check if amount is negative, set to zero if it's negative
        if amount < 0:
            logger.debug('amount was less than zero')
            amount = 0

        # Update marble count in database, check if write was successful then update Account info
        if database_operation.update_marble_count(
                database_setup.DbHandler.db_cnc, self.id, amount):
            self._marbles = amount
            logger.debug('Updated marbles')
        else:
            logger.error('Unable to update marbles')
            raise exception.UnableToWrite(class_='Account',
                                          attribute='marbles',
                                          value=amount)
Exemple #11
0
def process_bets(ctx, match: matches.Match) -> bool:
    """Processes all the bets for a given match
    """
    logger.debug(f'process_bets: {match}')

    # Check if match is a history match
    if not match.is_history:
        logger.error(f"Passed a match that isn't history to process_bets")
        return False

    # Get all bets for match, validate that it's not empty
    bet_data = database_operation.get_bet_info_match_all(
        DbHandler.db_cnc, match.id)
    if not len(bet_data):
        logger.debug(f"No bets placed on this match")
        return False

    # Create list of bets to be filled and processed
    bets = []
    for bet in bet_data:
        # Check if bet and match.id are equal
        if bet[2] == match.id:
            logger.debug(f'Valid bet({bet[0]})')

        # Get bettor account and bet target account, validate
        bettor = account.get_account_from_db(ctx, DbHandler.db_cnc, bet[3])
        bet_target = account.get_account_from_db(ctx, DbHandler.db_cnc, bet[4])
        if not bettor or not bet_target:
            logger.error(f'Unable to get accounts from bet')
            raise exception.UnableToRead(class_='Account', attribute='account')

        # Create bet to append onto bets
        bet_temp = Bet(bet[0], bet[1], match, bettor, bet_target, match.winner)
        logger.debug(f'bet_temp: {bet_temp}')
        if not bet_temp:
            logger.error(f'Unable to create bet')
            raise exception.UnableToWrite(class_='Bet', attribute='bet')
        bets.append(bet_temp)

    # Check if bets has been propagated
    if not len(bets):
        logger.error(f'bets was not propagated')
        return False

    # Total marble count
    marble_pot = 0

    # Total of loser marbles and losers
    loser_count = 0
    loser_pot = 0

    # Total of winner marbles and winners
    winner_count = 0
    winner_pot = 0

    # Calculations that need all bets
    for process_bet in bets:
        # Check if bet is winner
        if process_bet.is_winner():
            # Increment winner count and add bet amount to winner pool
            winner_count += 1
            winner_pot += process_bet.amount
        else:
            # Increment loser count and add bet amount to loser pool
            loser_count += 1
            loser_pot += process_bet.amount
        # Increment total marbles
        marble_pot += process_bet.amount

    logger.debug(f'marble_pot: {marble_pot}, '
                 f'loser: sum({loser_pot}),count({loser_count}), '
                 f'winner: sum({winner_pot}),count({winner_count})')

    # Calculate winner_pot_ratio and winnings per bet
    for calculate_bets in bets:
        if calculate_bets.is_winner():
            # Ratio of your bet in winner_pot
            winner_pot_ratio = calculate_bets.amount / winner_pot
            logger.debug(f'pot_ratio: {winner_pot_ratio}')

            # If loser pot* winner_pot_ratio < 1: return bet amount + one marble
            if (loser_pot * winner_pot_ratio) < 1:
                bet_returns = calculate_bets.amount + 1
            else:
                bet_returns = calculate_bets.amount + (loser_pot *
                                                       winner_pot_ratio)

            # If no losers, house matches bet and returns double amount
            if loser_count == 0:
                bet_returns = calculate_bets.amount * 2

            logger.debug(f'user: {calculate_bets.bettor.nickname}'
                         f'winner_pot_ratio: {winner_pot_ratio}'
                         f'bet_returns: {bet_returns}')

            # Add bet_returns to bettors marbles
            calculate_bets.bettor.marbles += bet_returns

        # Update calculate_bet to prep for making into history
        calculate_bets.bet_time = datetime.datetime.utcnow()
        calculate_bets.is_history = True
        # Delete bet
        calculate_bets.delete_bet()
        # Make bet history
        calculate_bets.create_history()

    return True
Exemple #12
0
def get_match(ctx: commands.Context,
              match_id: int,
              history: bool = False) -> Union[Match, int]:
    """Returns Match for Match with match_id

    **Arguments**

    - `<ctx>` Context used to get members and other information
    - `<match_id>` Id of the match to get
    - `<history>` Used to specify if you'd like to get a match from match_history or matches

    """
    logger.debug(f'get_match: {match_id}, {history}')

    # Check if ctx.channel is dm, return zero if true
    if isinstance(ctx.channel, discord.DMChannel):
        logger.error('ctx channel is dm, get_match not allowed in dms')
        raise exception.DiscordDM

    # Declare match_info to be filled later with tuple of match data from database
    match_info = 0

    # Checks history to decide which table to get match_info from
    if history:
        match_info = database_operation.get_match_history_info(
            DbHandler.db_cnc, match_id)
    else:
        match_info = database_operation.get_match_info_by_id(
            DbHandler.db_cnc, match_id)
    logger.debug(f'match_info: {match_info}')

    # Checks if match_info is int, if true return. Is tuple when filled with data
    if isinstance(match_info, int):
        logger.error(f'match_info was type int')
        return 0

    # Check history to get data specific to history matches
    if history:
        # Get Account of challenger
        challenger = acc.get_account_from_db(ctx, DbHandler.db_cnc,
                                             match_info[2])
        logger.debug(f'challenger: {challenger}')
        # Checks if challenger is int, if true return 0
        if isinstance(challenger, int):
            logger.error('challenger is type int')
            raise exception.UnableToRead(class_='Account', attribute='account')

        # Get Account of recipient
        recipient = acc.get_account_from_db(ctx, DbHandler.db_cnc,
                                            match_info[3])
        logger.debug(f'recipient: {recipient}')
        # Check if recipient is int, if true return 0
        if isinstance(recipient, int):
            logger.error('recipient is type int')
            raise exception.UnableToRead(class_='Account', attribute='account')

        # Get Account for winner
        winner = acc.get_account_from_db(ctx, DbHandler.db_cnc, match_info[4])
        logger.debug(f'winner: {winner}')
        # Checks if winner is int, if true return 0
        if isinstance(winner, int):
            logger.error('winner is type int')
            raise exception.UnableToRead(class_='Account', attribute='account')

        # Create Match with match_info data
        match = Match(match_info[0], match_info[1], True, challenger,
                      recipient, True, winner, match_info[5], match_info[6],
                      match_info[7], True)
        logger.debug(f'match: {match}')
        # Checks if match is type int, if true return 0
        if isinstance(match, int):
            logger.error('match is type int')
            raise exception.UnableToWrite(class_='Match', attribute='match')

        # Return match
        return match
    else:
        # Get Account of challenger
        challenger = acc.get_account_from_db(ctx, DbHandler.db_cnc,
                                             match_info[3])
        logger.debug(f'challenger: {challenger}')
        # Checks if challenger is int, if true return 0
        if isinstance(challenger, int):
            logger.error('challenger is type int')
            raise exception.UnableToRead(class_='Account', attribute='account')

        # Get Account of recipient
        recipient = acc.get_account_from_db(ctx, DbHandler.db_cnc,
                                            match_info[4])
        logger.debug(f'recipient: {recipient}')
        # Check if recipient is int, if true return 0
        if isinstance(recipient, int):
            logger.error('recipient is type int')
            raise exception.UnableToRead(class_='Account', attribute='account')
        # Create match with match_info data
        match = Match(match_info[0],
                      match_info[1],
                      match_info[2],
                      challenger,
                      recipient,
                      match_info[5],
                      _game=match_info[6],
                      _format=match_info[7])

        # Checks if match is type int, if true return 0
        if isinstance(match, int):
            logger.error('match is type int')
            raise exception.UnableToWrite(class_='Match', attribute='match')

        # Return match
        return match