Exemple #1
0
def up(db):
    with db.atomic():
        migrator = PostgresqlMigrator(db)
        db.bind(MODELS, bind_refs=False, bind_backrefs=False)
        db.create_tables(MODELS)
        if Coin.get_or_none(Coin.id == 1) is None:
            Coin.create(name='Bitcoin', symbol='BTC')
            Coin.create(name='Ethereum', symbol='ETH')
            Coin.create(name='Litecoin', symbol='LTC')
            Coin.create(name='Coin 3', symbol='CO3')
            Coin.create(name='Coin 4', symbol='CO4')
            Coin.create(name='Coin 5', symbol='CO5')

        global_indef = Game.create(name='Global Indefinite',
                                   starting_cash=10000.00,
                                   shareable_link='INDEF',
                                   shareable_code='INDEF',
                                   ends_at=None)

        # insert achievements into database
        Achievement.create(
            name="Win", description="Finish in first place in a private game")
        Achievement.create(
            name="Double net worth",
            description="Achieved by doubling your net worth in a game")
        Achievement.create(name="Identity Crisis",
                           description="Change your username")

        # insert goals into database
        Goal.create(name="Entrepreneur", description="Create a private game")

        all_coins = Coin.select()
        for coin in all_coins:
            GameCoin.create(game=global_indef, coin=coin)

        global_timed = Game.create(name='Global Timed',
                                   starting_cash=10000.00,
                                   shareable_link='TIMED',
                                   shareable_code='TIMED',
                                   ends_at=datetime.utcnow() +
                                   timedelta(minutes=1))
        # CHANGEME for devel purposes, making it 1 min for now
        GameCoin.create(game=global_timed, coin=Coin.get())

        # from auth.services import register
        hashed = bcrypt.hashpw("admin".encode(), bcrypt.gensalt()).decode()
        admin = Profile.create(username="******",
                               hashed_password=hashed,
                               is_admin=True)
        # Required so that admin can still view graphs in the landing page
        GameProfile.create(profile=admin, game=global_indef, cash=0.0)
Exemple #2
0
 def test_buy_coin_without_cash(self):
     profile = Profile.get_or_none(Profile.username == 'theusername')
     GameProfile.create(game=1, profile=profile, cash=0)
     GameCoin.create(game=1, coin=1)
     Ticker.create(coin=1, price=10, price_change_day_pct=1.1)
     res = self.client.post(
         '/game/1/coin',
         data=json.dumps({
             'coinId': '1',
             'coinAmount': '1',
         }),
         content_type='application/json',
         headers={'Authorization': 'Bearer ' + self.token})
     self.assertEqual(int(HTTPStatus.BAD_REQUEST), res._status_code)
Exemple #3
0
 def test_liquefy_success(self):
     profile = Profile.get_or_none(Profile.username == 'theusername')
     game_profile = GameProfile.create(game=1, profile=profile, cash=0)
     GameCoin.create(game=1, coin=1)
     GameProfileCoin.create(game_profile=game_profile,
                            coin=1,
                            coin_amount=2)
     Ticker.create(
         coin=1,
         price=10,
         captured_at=(datetime.utcnow()).isoformat(),
         price_change_day_pct=1.1,
     )
     res = self.client.delete(
         '/game/1/coins', headers={'Authorization': 'Bearer ' + self.token})
     self.assertEqual(int(HTTPStatus.OK), res._status_code)
Exemple #4
0
def update_game(
    game_id,
    name,
    starting_cash,
    ends_at,
    active_coins,
):
    game = Game.get_or_none(Game.id == game_id)
    if not game:
        raise BadRequest(f'A game with id {game_id} does not exist')
    game.name = name
    game.starting_cash = starting_cash
    game.ends_at = ends_at
    # delete all GameCoins for this game and just re-create
    GameCoin.delete().where(Game.id == game_id)
    create_gamecoins_for_game(game, active_coins)
    return game
Exemple #5
0
 def test_get_coins_success(self):
     profile = Profile.get_or_none(Profile.username == 'theusername')
     GameProfile.create(game=1, profile=profile, cash=10000)
     GameCoin.create(
         game=1,
         coin=1,
     )
     for coin in Coin.select():
         Ticker.create(
             coin=coin,
             price=30.0,
             captured_at=(datetime.utcnow()).isoformat(),
             price_change_day_pct=1.1,
         )
     res = self.client.get(
         '/game/1/coins?timeSpan=1&sortBy=0&numPerPage=10&pageNum=1',
         headers={'Authorization': 'Bearer ' + self.token})
     self.assertEqual(int(HTTPStatus.OK), res._status_code)
Exemple #6
0
def create_gamecoins_for_game(game, active_coins):
    if len(active_coins) == 0:
        raise BadRequest('At least one coin must be allowed in a game')
    res = []
    for coin in active_coins:
        coin = Coin.get_or_none(Coin.id == coin['id'])
        if coin is None:
            raise BadRequest('Invalid coin')
        res.append(GameCoin.create(
            game=game,
            coin=coin,
        ))
    return res
Exemple #7
0
 def test_sell_coin_success(self):
     profile = Profile.get_or_none(Profile.username == 'theusername')
     game_profile = GameProfile.create(game=1, profile=profile, cash=0)
     GameCoin.create(game=1, coin=1)
     GameProfileCoin.create(game_profile=game_profile,
                            coin=1,
                            coin_amount=2)
     Ticker.create(
         coin=1,
         price=10,
         captured_at=(datetime.utcnow()).isoformat(),
         price_change_day_pct=1.1,
     )
     res = self.client.post(
         '/game/1/coin',
         data=json.dumps({
             'coinId': '1',
             'coinAmount': '-1',
         }),
         content_type='application/json',
         headers={'Authorization': 'Bearer ' + self.token})
     self.assertEqual(int(HTTPStatus.OK), res._status_code)
Exemple #8
0
def check_global_timed_game():
    game = Game.get(Game.shareable_link == 'TIMED')
    if game.ends_at < datetime.utcnow():
        # end global timed game, and start another
        profiles = []
        for game_profile in GameProfile.select().where(GameProfile.game == game):
            profiles.append(game_profile.profile)
            send_notification(game_profile.profile, 'The global timed game has expired')
            game_profile.delete_instance(recursive=True)
        game.delete_instance(recursive=True)
        global_timed = Game.create(name='Global Timed',
                        starting_cash=10000.00,
                        shareable_link='TIMED',
                        shareable_code='TIMED',
                        ends_at=datetime.utcnow() + timedelta(minutes=1))
        # CHANGEME for devel purposes, making it 1 min for now
        GameCoin.create(game=global_timed, coin=Coin.get())
        for profile in profiles:
            GameProfile.create(
                game=global_timed,
                profile=profile,
                cash=global_timed.starting_cash
            )
Exemple #9
0
def buy_coin(coin_id, coin_amount, game_profile):
    ticker = Ticker.select().where(Ticker.coin == coin_id).order_by(
        Ticker.captured_at.desc())
    if ticker.count() == 0:
        raise BadRequest('Coin has no prices')
    ticker = ticker.get()
    new_cash = game_profile.cash - (ticker.price * coin_amount)
    if new_cash < 0:
        raise BadRequest('Not enough cash to buy this coin amount')
    game_coin = GameCoin.get_or_none(GameCoin.game == game_profile.game,
                                     GameCoin.coin == coin_id)
    if game_coin is None:
        raise BadRequest('Coin does not exist in this game')
    gameProfileCoin = GameProfileCoin.get_or_none(
        GameProfileCoin.game_profile == game_profile.id,
        GameProfileCoin.coin == coin_id)

    if gameProfileCoin is None:
        GameProfileCoin.create(game_profile=game_profile.id,
                               coin=coin_id,
                               coin_amount=coin_amount)

        rows = GameProfile.update(cash=new_cash).where(
            GameProfile == game_profile).execute()

        if rows == 0:
            raise BadRequest('Money could not be removed from your account')
        return coin_amount
    else:
        new_coin_amount = gameProfileCoin.coin_amount + coin_amount
        rows = GameProfile.update(cash=new_cash).where(
            GameProfile == game_profile).execute()
        if rows == 0:
            raise BadRequest('Money could not be removed from your account')
        GameProfileCoin.update(coin_amount=new_coin_amount).where(
            GameProfileCoin.id == gameProfileCoin.id).execute()
        return new_coin_amount