コード例 #1
0
    def __makeChange(self, value):
        excess = self.getTotal() - value
        for aCoin in self.inserted:
            if aCoin.getValue() == Coins.QUARTER_VALUE:
                self.quarters += 1
            elif aCoin.getValue() == Coins.DIME_VALUE:
                self.dimes += 1
            elif aCoin.getValue() == Coins.NICKEL_VALUE:
                self.nickels += 1
        self.inserted = []

        quarters = int(excess / Coins.QUARTER_VALUE)
        if quarters > 0:
            excess = round(excess - (Coins.QUARTER_VALUE * quarters), 2)
            for i in range(quarters):
                self.coinReturn.append(Coin(Coins.QUARTER_WEIGHT, Coins.QUARTER_DIAMETER))
                self.quarters -= 1

        dimes = int(round(excess / Coins.DIME_VALUE))
        if dimes > 0:
            excess = round(excess - (Coins.DIME_VALUE * dimes), 2)
            for i in range(dimes):
                self.coinReturn.append(Coin(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER))
                self.dimes -= 1

        nickels = int(excess / Coins.NICKEL_VALUE)
        if nickels > 0:
            excess = round(excess - (Coins.NICKEL_VALUE * nickels), 2)
            for i in range(nickels):
                self.coinReturn.append(Coin(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER))
                self.nickels -= 1
コード例 #2
0
 def __init__(self, _MIN_VALUE=_MIN, _MAX_VALUE=_MAX):
     #valeurs pour les sentinelles, -infini à +infini
     self._MIN_VALUE = _MIN_VALUE
     self._MAX_VALUE = _MAX_VALUE
     #une instance de Coin pour les tours de hauteurs variables
     self._coin = Coin()
     #hauteur de départ
     self._height = 1
     #taille initiale de 0
     self._size = 0
     #les 4 sentinelles et leurs interrelations
     #lr = low-right; ll = low-left; ul = upper-left; ur = upper-right
     sentinel_lr = SkipListNode(self._MAX_VALUE)
     sentinel_ll = SkipListNode(self._MIN_VALUE, None, sentinel_lr, None,
                                None)
     sentinel_lr._prev = sentinel_ll
     sentinel_ul = SkipListNode(self._MIN_VALUE, None, None, sentinel_ll,
                                None)
     sentinel_ur = SkipListNode(self._MAX_VALUE, sentinel_ul, None,
                                sentinel_lr, None)
     sentinel_ul._next = sentinel_ur
     sentinel_ll._abov = sentinel_ul
     sentinel_lr._abov = sentinel_ur
     #par convention, le début de la skiplist est la sentinelle _ul
     self._start = sentinel_ul
コード例 #3
0
    def testWhenCoinIsPassedInvalidWeightAndDiameterTheCoinIsInvalidAndHasProvidedWeightAndDiameter(
            self):
        aCoin = Coin(2.5, 0.75)  # A penny

        self.assertEqual(aCoin.isValid(), False)
        self.assertEqual(aCoin.getWeight(), 2.5)
        self.assertEqual(aCoin.getDiameter(), 0.75)
コード例 #4
0
    def insert(self, weight, diameter):
        aCoin = Coin(weight, diameter)
        if aCoin.isValid():
            self.inserted.append(aCoin)
        else:
            self.coinReturn.append(aCoin)

        return aCoin.isValid()
コード例 #5
0
 def create_coin(self):
     # Generate unique coin id
     c = Coin(self._current_id)
     # Sign by scrooge
     c.sign(self._sk.sign(str(c).encode('utf-8')))
     self._current_id += 1
     self._coins.append(c)
     # Add coin to block chain, as owned by Scrooge user
     self._ledger._users_coins[self.vk].append(c)
コード例 #6
0
def get_answer(request_type):
    if '코인' in request_type:
        obj_coin = Coin()
        return obj_coin.getCoinInfo()
    elif '원티드' in request_type:
        obj_wanted = Wanted()
        return obj_wanted.getWantedInfo()
    elif '프로그래머스' in request_type:
        obj_prgrammers = Programmers()
        return obj_prgrammers.getProgrammersInfo()
    return default_answer
コード例 #7
0
 def Destroy(self):
     self.dead = True
     self.game.needs_sorting = True
     self.game.game_objects.remove(self)
     self.game.enemy_generator.spawned_bear = False
     self.game.enemy_generator.bear_timer = 20
     # self.game.enemy_generator.rebear += 1
     if not self.game.player.dead:
         self.game.NextLevel()
         for i in range(DROPS_COINS):
             coin = Coin(self.game)
             x, y = RandomPointInCircle(self.radius)
             coin.x = self.x + x
             coin.y = self.y + y
             self.game.AddObject(coin)
コード例 #8
0
    def createCoins(self,values,issuerurl):
        """requests a coin of a value from the specified issuer
        """
        issuer = self.issuers[issuerurl]    
         
        if type(values) != type([]):
            values, rest = partition(issuer.getPubKeys().keys(),int(values))

        for v in values:
            #create blanks
            coin = Coin(issuer.getUrl(),decodeKey(issuer.getPubKeys_encoded()[str(v)]),v)
            blind = coin.getBlind()
            hash = coin.getHash()
            self.coins[hash] = coin
            self.pending[hash] = coin
コード例 #9
0
 def __init__( self, _MIN_VALUE = -999999999, _MAX_VALUE = 999999999 ):
     self._MIN_VALUE = _MIN_VALUE
     self._MAX_VALUE = _MAX_VALUE
     self._coin = Coin()
     self._height = 1
     self._count = 0
     sentinel_lr = SkipListNode( self._MAX_VALUE )
     sentinel_ll = SkipListNode( self._MIN_VALUE, None, sentinel_lr, None, None )
     sentinel_lr._prev = sentinel_ll
     sentinel_ul = SkipListNode( self._MIN_VALUE, None, None, sentinel_ll, None )
     sentinel_ur = SkipListNode( self._MAX_VALUE, sentinel_ul, None, sentinel_lr, None )
     sentinel_ul._next = sentinel_ur
     sentinel_ll._abov = sentinel_ul
     sentinel_lr._abov = sentinel_ur
     self._start = sentinel_ul
コード例 #10
0
    def createCoins(self, values, issuerurl):
        """requests a coin of a value from the specified issuer
        """
        issuer = self.issuers[issuerurl]

        if type(values) != type([]):
            values, rest = partition(issuer.getPubKeys().keys(), int(values))

        for v in values:
            #create blanks
            coin = Coin(issuer.getUrl(),
                        decodeKey(issuer.getPubKeys_encoded()[str(v)]), v)
            blind = coin.getBlind()
            hash = coin.getHash()
            self.coins[hash] = coin
            self.pending[hash] = coin
コード例 #11
0
ファイル: coins.py プロジェクト: iccowan/CSC_117
def createCoins(win):
    # Create 100 points and add them to a list
    # Init list
    coins = list()

    # Each row
    for i in range(5, 100, 10):
        # Each column
        for j in range(5, 100, 10):
            pt = Point(i, j)
            if i == 95 and j == 95:
                c = Coin(win, pt, True)
            else:
                c = Coin(win, pt, False)
            coins.append(c)

    return coins
コード例 #12
0
ファイル: Main.py プロジェクト: ParshJP/aMAZEing-Game
def setCoins():
    global listCoins, level

    # hashtag  Set list of coins depending on the current level
    listCoins = [0] * len(CoinDimensions[level])

    # hashtag  Iterate through the parameters of each coin for the current level and initialize Coin class object
    for index in range(len(listCoins)):
        dimensions = CoinDimensions[level][index]
        listCoins[index] = Coin(canvas, dimensions[0], dimensions[1])
コード例 #13
0
class TestCoin(unittest.TestCase):
    def setUp(self):
        self.values = ['heads', 'tails']
        self.test_coin = Coin()

    def test_instance_creation(self):
        """
        Test that the the test_coin object created is indeed an instance of a Coin
        :return:
        """
        self.assertIsInstance(self.test_coin, Coin)

    def test_face_value_init(self):
        self.assertIn(self.test_coin.face, self.values)

    def test_get_face(self):
        self.assertIn(self.test_coin.get_face(), self.values)

    def test_flip(self):
        self.test_coin.flip()
        self.assertIn(self.test_coin.get_face(), self.values)
コード例 #14
0
ファイル: EATrainer.py プロジェクト: thaleaschlender/GAME_AI
    def init_gamestates(self):
        self.gamestates = list()

        all_sprites = pygame.sprite.Group()
        P1 = Player(self.DISPLAYSURF)
        E1 = Obstacle(self.DISPLAYSURF, self.speed, 40, 70, 0)
        E2 = Obstacle(self.DISPLAYSURF, self.speed, 405, 50, -350)
        C1 = Coin(self.DISPLAYSURF, self.speed, 20, 20, 700)
        all_sprites.add(P1, E1, E2, C1)
        state = Gamestate(self.DISPLAYSURF, self.speed, 0, 0, all_sprites)

        for i in range(self.pop_size):
            self.gamestates.append(state.copy())
コード例 #15
0
 def __makeChangeFromPennies(self, input):
     coins = [
         Coin("£2", 200),
         Coin("£1", 100),
         Coin("50p", 50),
         Coin("20p", 20),
         Coin("10p", 10),
         Coin("5p", 5),
         Coin("2p", 2),
         Coin("1p", 1)
     ]
     statements = []
     statements = self.__findCoinCountForEachCoin(input, coins, statements)
     # statements = self.__createCoinStatements(coins)
     return self.__buildOutputString(statements)
コード例 #16
0
def make_coin_obj(row):
    '''
    INPUT: row (row) - the row from a pandas dataframe
    OUTPUT: a Coin object that keeps track of all information
    '''
    name = row['COIN_NAME']
    quantity = float(row['BUY_QUANTITY'])
    buy_currency = row['BUY_CURRENCY']
    buy_price = float(row['BUY_PRICE'])
    coin = Coin(name=name,
                buy_price=buy_price,
                quantity=quantity,
                buy_currency=buy_currency)
    return coin
コード例 #17
0
    def Update(self):
        # get the distance the players moved since we last spawned something
        d = Distance(self.last_spawn_position_x, self.last_spawn_position_y,
                     self.game.player.x, self.game.player.y)

        self.warm_up_time += self.game.delta_time

        if d > self.spawn_rate and self.warm_up_time > WARM_UP:
            # then we'll spawn something
            # create a random point in front of the player, outside of the screen
            vx = self.game.player.x - self.last_spawn_position_x
            vy = self.game.player.y - self.last_spawn_position_y
            rx, ry = RandomVector(vx, vy, self.scatter_angle_variance,
                                  self.scatter_spawning_distance,
                                  self.distance_variance)
            newx = self.game.player.x + rx
            newy = self.game.player.y + ry

            coin = Coin(self.game)
            coin.x = newx
            coin.y = newy
            self.game.AddObject(coin)

            # finalize
            self.last_spawn_position_x = self.game.player.x
            self.last_spawn_position_y = self.game.player.y

            if not self.first_time_pop_up:
                floating_text = FloatingText.New(self.game, (255, 255, 255),
                                                 "Collect $ to",
                                                 self.game.width * 0.6,
                                                 self.game.height * 0.2,
                                                 line2="upgrade weapon",
                                                 target_object=coin)
                self.game.AddObject(floating_text)
                self.first_time_pop_up = True
コード例 #18
0
ファイル: Board.py プロジェクト: W3SS/AI_Donkey_Kong
 def GenerateCoins(self):
     for i in range(6, len(self.map)):
         for j in range(len(self.map[i])):
             if self.map[i][j] == 0 and ((i + 1 < len(self.map) and self.map[i + 1][j] == 1) or (
                         i + 2 < len(self.map) and self.map[i + 2][j] == 1)):
                 randNumber = math.floor(random.random() * 1000)
                 if randNumber % 35 == 0 and len(self.Coins) <= 25:  # At max there will be 26 coins in the map
                     self.map[i][j] = 3
                     if j - 1 >= 0 and self.map[i][j - 1] == 3:
                         self.map[i][j] = 0
                     if self.map[i][j] == 3:
                         # Add the coin to our coin list
                         self.Coins.append(Coin(pygame.image.load('Assets/coin1.png'), (j * 15 + 15 / 2, i * 15 + 15 / 2)))
     if len(self.Coins) <= 20:  # If there are less than 21 coins, we call the function again
         self.GenerateCoins()
コード例 #19
0
 def GenerateCoins(self):
     for i in range(6, len(self.map)):
         for j in range(len(self.map[i])):
             if self.map[i][j] == 0 and ((i + 1 < len(self.map) and self.map[i + 1][j] == 1) or (
                         i + 2 < len(self.map) and self.map[i + 2][j] == 1)):
                 randNumber = math.floor(random.random() * 1000)
                 if randNumber % 35 == 0 and len(self.Coins) <= 25:  # Se va a crear un maximo de 26 monedas
                     self.map[i][j] = 3
                     if j - 1 >= 0 and self.map[i][j - 1] == 3:
                         self.map[i][j] = 0
                     if self.map[i][j] == 3:
                         # agregar un coin a nuestro grupo
                         self.Coins.append(Coin(pygame.image.load('Assets/Apple.png'), (j * 15 + 15 / 2, i * 15 + 15 / 2)))
     if len(self.Coins) <= 20:  # si estan menos de 21 coins el programa se vuelva a generar
         self.GenerateCoins()
コード例 #20
0
ファイル: Turel.py プロジェクト: Naruto-sys/Welcome-to-hell
    def update(self, *args):
        if self.hp <= 0:
            self.all_sprites.add(
                Coin(self.rect.x / 50, self.rect.y / 50, self.hero))

            self.kill()
            self.hero.kills += 1
            return

        self.shooting(self.hero, self.rect.x, self.rect.y)

        x = self.hero.rect.x + self.hero.rect.w // 2
        y = self.hero.rect.y + self.hero.rect.h // 2
        rel_x, rel_y = x - self.rect.x, y - self.rect.y
        angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
        self.image, self.rect = rotate(self.frame, self.rect, int(angle))
コード例 #21
0
    def __init__(self):
        """Generate the level"""
        self.sprite_list = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()
        self.width = 0

        # Open the level
        f = open('Levels/1-1.lvl', 'r')

        # Create all blocs
        for y, line in enumerate(self.reverse_lines(f)):
            line = self.split(line.rstrip('\n'))
            for x, value in enumerate(line):
                self.width += 16 * SPRITE_SCALE
                if value != '0':
                    bloc = None
                    if value == '1':
                        bloc = arcade.Sprite('Sprites/bloc.png', SPRITE_SCALE)
                    elif value == '2':
                        bloc = arcade.Sprite('Sprites/Box.png', SPRITE_SCALE)
                    elif value == '3':
                        bloc = arcade.Sprite('Sprites/mysterybox.png',
                                             SPRITE_SCALE)
                    elif value == '4':
                        bloc = arcade.Sprite('Sprites/pipe_tl.png',
                                             SPRITE_SCALE)
                    elif value == '5':
                        bloc = arcade.Sprite('Sprites/pipe_tr.png',
                                             SPRITE_SCALE)
                    elif value == '6':
                        bloc = arcade.Sprite('Sprites/pipe_dl.png',
                                             SPRITE_SCALE)
                    elif value == '7':
                        bloc = arcade.Sprite('Sprites/pipe_dr.png',
                                             SPRITE_SCALE)
                    elif value == '8':
                        # Creae a new coin
                        self.coin_list.append(Coin(x, y))
                        continue
                    # Set bloc base data
                    bloc.center_x = x * bloc.width
                    bloc.center_y = y * bloc.height
                    self.sprite_list.append(bloc)
コード例 #22
0
 def deposit(self, currency, user_addr, deposit_token, val=0):
     if currency == "BTC":
         if isinstance(deposit_token, BTCToken):
             if user_addr in self.btc_valid_tokens:
                 self.btc_valid_tokens[user_addr].append(deposit_token)
             else:
                 self.btc_valid_tokens[user_addr] = [deposit_token]
             self.send_deposit_token(user_addr, deposit_token)
         else:
             raise ValueError("Provided deposit token is not a BTCToken")
     elif currency == "ETH":
         if isinstance(deposit_token, ETHToken):
             for i in range(self.N):
                 self.global_coin_id += 1
                 new_coin = Coin(self.global_coin_id, 0, (val / self.N))
                 deposit_token.coins.append(new_coin)
             if user_addr in self.eth_valid_tokens:
                 self.eth_valid_tokens[user_addr].append(deposit_token)
             else:
                 self.eth_valid_tokens[user_addr] = [deposit_token]
             self.send_deposit_token(user_addr, deposit_token)
         else:
             ValueError("Provided deposit token is not a ETHToken")
コード例 #23
0
ファイル: main.py プロジェクト: felipe-carvalho12/Flappy-Bird
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and game_active:
                bird_yvelocity = -3
                flap_sound.play()
            elif event.key == pygame.K_SPACE and not game_active:
                game_active = True
                bird_rect.center = (50, int(screen_h/2))
                bird_yvelocity = 0
                coins.clear()
                pipes.clear()
                score = 0

        if event.type == SPAWNCOIN and game_active:
            rdm_coin_pos = random.choice(coin_pos)
            new_coin = Coin(top_pipe_surface, (400, rdm_coin_pos))
            coins.append(new_coin)

        if event.type == COINFLIP and game_active:
            coin_index += 1
            if coin_index >= len(coin_frames):
                coin_index = 1
            for coin in coins:
                coin.surface = coin_frames[coin_index]
                coin.rect = coin.surface.get_rect(center=(int(coin.rect.centerx), int(coin.rect.centery)))

        if event.type == BIRDFLAP and game_active:
            bird_index += 1
            if bird_index >= len(bird_frames):
                bird_index = 0
            bird_surface = bird_frames[bird_index]
コード例 #24
0
    def testWhenCoinIsPassValidWeightAndDiameterTheCoinIsValidAndHasProvidedWeightAndDiameter(
            self):
        nickel = Coin(Coins.NICKEL_WEIGHT, Coins.NICKEL_DIAMETER)  # A nickel

        self.assertEqual(nickel.isValid(), True)
        self.assertEqual(nickel.getWeight(), Coins.NICKEL_WEIGHT)
        self.assertEqual(nickel.getDiameter(), Coins.NICKEL_DIAMETER)
        self.assertEqual(nickel.getValue(), Coins.NICKEL_VALUE)

        dime = Coin(Coins.DIME_WEIGHT, Coins.DIME_DIAMETER)  # A dime
        self.assertEqual(dime.isValid(), True)
        self.assertEqual(dime.getWeight(), Coins.DIME_WEIGHT)
        self.assertEqual(dime.getDiameter(), Coins.DIME_DIAMETER)
        self.assertEqual(dime.getValue(), 0.1)

        quarter = Coin(Coins.QUARTER_WEIGHT,
                       Coins.QUARTER_DIAMETER)  # A quarter
        self.assertEqual(quarter.isValid(), True)
        self.assertEqual(quarter.getWeight(), Coins.QUARTER_WEIGHT)
        self.assertEqual(quarter.getDiameter(), Coins.QUARTER_DIAMETER)
        self.assertEqual(quarter.getValue(), Coins.QUARTER_VALUE)
コード例 #25
0
             print(die1.list_of_rolls)
             for i, freq in zip(range(len(die1.freq_list)), die1.freq_list):
                 print(f'{i+1}:{freq}', end='\t')
         else:
             print('Sorry, you have to roll the die at least once!')
     else:
         print('Sorry, the die must have at least 3 sides!')
 elif choice == str(2):
     num_flips = input('How many times do you want to flip the coin? ')
     try:
         num_flips = int(num_flips)
     except ValueError:
         print('Sorry, that wasn\'t a number!')
         continue
     if num_flips >= 1:
         coin1 = Coin(num_flips)
         coin1.flip()
         coin1.flip_stats()
         print(coin1.list_of_flips)
         print(f'Heads: {coin1.freq_list[0]}\tTails: {coin1.freq_list[1]}')
     else:
         print('Sorry, you have to flip the coin at least once!')
 elif choice == str(3):
     num_draws = input('How many cards do you want to draw? ')
     try:
         num_draws = int(num_draws)
     except ValueError:
         print('Sorry, that wasn\'t a number!')
         continue
     if 1 <= num_draws <= 52:
         card1 = Card(num_draws)
コード例 #26
0
def volatility_strategy(coins_name: list):
    os.makedirs('logs', exist_ok=True)
    print(f'{get_now_time()} 시작가: {get_krw():.2f}')

    print_order_config(config.items(section="VB_ORDER"))
    coin_dict = dict()
    for coin_name in coins_name:
        coin_dict[coin_name] = Coin(coin_name)
    while True:
        for i, coin in enumerate(coin_dict.values()):
            candles = get_candles('KRW-' + coin.coin_name,
                                  count=2,
                                  minute=UNIT,
                                  candle_type=CANDLE_TYPE)
            coin.high_price = max(candles[0]["trade_price"], coin.high_price)
            now = candles[0]['candle_date_time_kst']

            if coin.state == State.BOUGHT:
                coin.earnings_ratio = (
                    candles[0]["trade_price"] -
                    coin.avg_buy_price) / candles[0]["trade_price"] * 100
                coin.max_earnings_ratio = max(coin.earnings_ratio,
                                              coin.max_earnings_ratio)
            if coin.state == State.WAIT:
                print(
                    f'{get_now_time()} {coin.coin_name:>6}({set_state_color(coin.state)})| '
                    f'목표 가: {coin.buy_price:>11.2f}, 현재 가: {candles[0]["trade_price"]:>10}'
                    f' ({set_dif_color(candles[0]["trade_price"], coin.buy_price)}) '
                    f'최대 {coin.max_earnings_ratio:>6.2f} %')
            elif coin.state == State.BOUGHT:
                print(
                    f'{get_now_time()} {coin.coin_name:>6}({set_state_color(coin.state)})| '
                    f'구매 가: {coin.avg_buy_price:>11.2f}, 현재 가: {candles[0]["trade_price"]:>10}'
                    f' ({set_dif_color(candles[0]["trade_price"], coin.avg_buy_price)}) '
                    f'최대 {coin.max_earnings_ratio:6.2f} %')

            # 매도 조건
            # 1. 시간 캔들이 바뀐 경우
            # 2. 수익률이 5 % 이상인 경우
            if coin.check_time != now or (coin.state == State.BOUGHT and coin.earnings_ratio >= 5)\
                    or (coin.state == State.BOUGHT and coin.earnings_ratio <= -5):
                print(f'1. time_change: {coin.check_time != now} '
                      f'2. ratio: {coin.earnings_ratio}')
                if coin.check_time != now and i == 0:
                    print(
                        f'----------------------------------- UPDATE ---------------------------------------'
                    )
                if coin.state == State.BOUGHT:
                    sell_result = coin.sell_coin()
                    print(
                        f'\033[104m{get_now_time()} {coin.coin_name:>6}(  SELL)| {int(round(get_sell_price(sell_result)))}원\033[0m'
                    )
                if coin.check_time != now:
                    coin.state = State.WAIT
                    coin.max_earnings_ratio = 0
                    coin.earnings_ratio = 0
                if coin.check_time != now and i == len(coin_dict) - 1:
                    print(
                        f'---------------------------------------------------------------------------------'
                    )
                coin.check_time = now
                coin.variability = candles[1]['high_price'] - candles[1][
                    'low_price']
                coin.buy_price = candles[0][
                    "opening_price"] + coin.variability * (PERCENT_BUY_RANGE /
                                                           100)
                coin.high_price = candles[0]["opening_price"]
                coin.buy_balance = cal_buy_balance(coin.variability,
                                                   coin.high_price)
                if coin.buy_balance == 0:
                    coin.state = State.PASS
                print(
                    f'{coin.coin_name}| variability:{coin.variability}, buy_price:{coin.buy_price}, buy_balance:{coin.buy_balance}'
                )
            else:  # 시간이 동일하다면
                if coin.state != State.WAIT:
                    continue
                if coin.variability == 0 or candles[0][
                        'trade_price'] <= coin.buy_price:
                    continue

                # 매수
                buy_result = coin.buy_coin(price=coin.buy_balance)
                if not buy_result:
                    continue
                print(
                    f'\033[101m{get_now_time()} {coin.coin_name:>6}(   BUY)| {coin.bought_amount}원\033[0m'
                )
コード例 #27
0
    def build_level(self, Level):
        # build the level
        self.player_list.empty()
        self.player = Level().player
        self.player_list.add(self.player)
        self.player.ball_list = pygame.sprite.Group()
        self.invincible_enemy_list.empty()
        self.jump_blocks_list.empty()
        self.exit_blocks_list.empty()
        self.kill_blocks_list.empty()
        self.fake_blocks_list.empty()
        self.coin_list.empty()
        self.enemy_list.empty()
        self.platform_list.empty()
        self.enemy_platform_list.empty()
        self.enemy_list.add(Level().enemies)
        self.invincible_enemy_list.add(Level().invincible_enemies)
        x = y = 0
        for row in Level().level:
            for col in row:
                if col == "P":
                    p = Platform(x, y)
                    self.platform_list.add(p)
                    #self.enemy_platform_list.add(p)
                if col == "R":
                    r = EnemyPlatform(x, y)
                    self.platform_list.add(r)
                    self.enemy_platform_list.add(r)
                if col == "X":
                    e = ExitBlock(x, y)
                    self.exit_blocks_list.add(e)
                if col == "J":
                    j = JumpBlock(x, y)
                    self.jump_blocks_list.add(j)
                if col == "S":
                    s = Structure(x, y)
                    self.platform_list.add(s)
                if col == "Q":
                    q = EnemyStructure(x, y)
                    self.platform_list.add(q)
                    self.enemy_platform_list.add(q)
                if col == "K":
                    k = KillBlock(x, y)
                    self.kill_blocks_list.add(k)
                    #self.enemy_platform_list.add(k)
                if col == "I":
                    i = InvisibleBlock(x, y)
                    self.enemy_platform_list.add(i)
                if col == "B":
                    b = Brick(x, y)
                    self.platform_list.add(b)
                    #self.enemy_platform_list.add(b)
                if col == "U":
                    u = KillBlock2(x, y)
                    self.kill_blocks_list.add(u)
                    self.enemy_platform_list.add(u)
                if col == "E":
                    e = Enemy(x, y, 'normal')
                    self.enemy_list.add(e)
                if col == "Z":
                    z = Enemy(x, y, 'invincible')
                    self.invincible_enemy_list.add(z)
                if col == "C":
                    c = Coin(x, y)
                    self.coin_list.add(c)
                if col == "F":
                    f = FakePlatform(x, y)
                    self.fake_blocks_list.add(f)
                x += PLATFORM_WIDTH
            y += PLATFORM_HEIGHT
            x = 0

        self.total_level_width = len(Level().level[0]) * PLATFORM_WIDTH
        self.total_level_height = len(Level().level) * PLATFORM_HEIGHT
コード例 #28
0
def short_volatility_strategy(coins_name: list):
    print_order_config(config.items(section="VB_ORDER"))
    coin_dict = dict()
    for coin_name in coins_name:
        coin_dict[coin_name] = Coin(coin_name)
    while True:
        for coin in coin_dict.values():
            candles = get_candles('KRW-' + coin.coin_name,
                                  count=2,
                                  minute=unit)
            now = candles[0]['candle_date_time_kst']
            print(
                f'{get_now_time()} {coin.coin_name}({set_state_color(coin.state)})| '
                f'목표 가: {coin.buy_price:>11.2f}, 현재 가: {candles[0]["trade_price"]:>10}'
                f' ({set_dif_color(candles[0]["trade_price"], coin.buy_price)})'
            )

            if coin.check_time != now:
                print(f'{coin.check_time} -> \033[36m{now}\033[0m')
                if coin.state == State.BOUGHT or coin.state == State.TRYBUY:
                    sell_result = coin.sell_coin()
                    if sell_result == "Not bought":
                        print(
                            f'\033[100m{get_now_time()} {coin.coin_name}( ERROR)|\033[0m'
                        )
                    else:
                        print(
                            f'\033[104m{get_now_time()} {coin.coin_name}(  SELL)| '
                            f'{int(get_sell_price(access_key))}\033[0m')
                        with open("../logs/VB_order.log", "a") as f:
                            f.write(
                                f'{get_now_time()} {coin.coin_name}(  SELL)| '
                                f'{int(get_sell_price(access_key))}원\n')
                    if coin.state == State.TRYBUY:
                        coin.cansel_buy()
                        print(
                            f'\033[104m{get_now_time()} {coin.coin_name}( CANCEL)|\033[0m'
                        )
                coin.check_time = now
                coin.variability = candles[1]['high_price'] - candles[1][
                    'low_price']
                coin.buy_price = candles[0][
                    "opening_price"] + coin.variability * (percent_buy_range /
                                                           100)
            else:  # 시간이 동일하다면
                if coin.state == State.BOUGHT or coin.variability == 0:
                    continue
                if candles[0]['trade_price'] <= coin.buy_price:
                    continue

                # 매수
                limit = True
                buy_result = coin.buy_coin(price=10000, limit=limit)
                os.makedirs('../logs', exist_ok=True)
                if limit:
                    print(
                        f'\033[95m{get_now_time()} {coin.coin_name}(TRYBUY)| '
                        f'{buy_result.get("locked"):>6}원\033[0m')
                    with open("../logs/VB_order.log", "a") as f:
                        f.write(f'{get_now_time()} {coin.coin_name}(TRYBUY)| '
                                f'{buy_result.get("locked"):>6}원\033[0m')
                else:
                    print(
                        f'\033[101m{get_now_time()} {coin.coin_name}(   BUY)| '
                        f'{int(get_buy_price(coin.coin_name))}원\033[0m')
                    with open("../logs/VB_order.log", "a") as f:
                        f.write(f'{get_now_time()} {coin.coin_name}(   BUY)| '
                                f'{int(get_buy_price(coin.coin_name))}원\n')
コード例 #29
0
class SkipList():
    def __init__(self, _MIN_VALUE=_MIN, _MAX_VALUE=_MAX):
        #valeurs pour les sentinelles, -infini à +infini
        self._MIN_VALUE = _MIN_VALUE
        self._MAX_VALUE = _MAX_VALUE
        #une instance de Coin pour les tours de hauteurs variables
        self._coin = Coin()
        #hauteur de départ
        self._height = 1
        #taille initiale de 0
        self._size = 0
        #les 4 sentinelles et leurs interrelations
        #lr = low-right; ll = low-left; ul = upper-left; ur = upper-right
        sentinel_lr = SkipListNode(self._MAX_VALUE)
        sentinel_ll = SkipListNode(self._MIN_VALUE, None, sentinel_lr, None,
                                   None)
        sentinel_lr._prev = sentinel_ll
        sentinel_ul = SkipListNode(self._MIN_VALUE, None, None, sentinel_ll,
                                   None)
        sentinel_ur = SkipListNode(self._MAX_VALUE, sentinel_ul, None,
                                   sentinel_lr, None)
        sentinel_ul._next = sentinel_ur
        sentinel_ll._abov = sentinel_ul
        sentinel_lr._abov = sentinel_ur
        #par convention, le début de la skiplist est la sentinelle _ul
        self._start = sentinel_ul

    #taille de la skiplist
    def __len__(self):
        return self._size

    # prettyprint
    def __str__(self):
        #on prend le début de la skiplist
        current = self._start
        pp = "SkipList of height " + str(self._height) + ":\n"
        #pour chaque niveau
        for level in range(self._height, -1, -1):
            p = current
            pp += "level " + str(level) + " ["
            #le premier élément du niveau est le suivant de la sentinelle
            p = p._next
            while not (p is None):
                if (not p._next is None):
                    pp += str(p._elem)
                    if (not p._next._next is None):
                        pp += ","
                p = p._next
            #on descend par la sentinelle
            current = current._belo
            pp += "]\n"
        return pp

    #iterateur : parcours les éléments du niveau 0
    def __iter__(self):
        #on prend le niveau du début de la skiplist (plus haut)
        level = self._start
        #on descend jusqu'au niveau 0 par les sentinelles
        while not (level._belo is None):
            level = level._belo
        #on parcourt les éléments du niveau 0,
        #le premier étant le suivant de la sentinelle
        current = level._next
        while not (current._next is None):
            yield current._elem
            current = current._next

    #retourne l'élément le plus petit de la skiplist
    def Min(self):
        #si la skiplist est vide, il n'existe pas
        if self._size == 0:
            return None
        #on prend le début de la skiplist
        tower = self._start
        #on descend jusqu'au niveau 0 par les sentinelles
        while not (tower._belo is None):
            tower = tower._belo
        #l'élément le plus petit est le suivant de la sentinelle
        return tower._next._elem

    #retourne l'élément le plus grand de la skiplist
    def Max(self):
        #si la skiplist est vide, il n'existe pas
        if self._size == 0:
            return None
        #on prend la sentinelle à droite du début de la skiplist
        tower = self._start._next
        #on descend jusqu'au niveau 0 par les sentinelles de droite
        while not (tower._belo is None):
            tower = tower._belo
        #l'élément le plus grand est le précédent de la sentinelle
        return tower._prev._elem

    #recherche et retourne un élément, ou son précédent s'il n'existe pas
    def SkipSearch(self, element):
        #on prend le début de la skiplist
        p = self._start
        #tant que sur un niveau supérieur à 0
        while not (p._belo is None):
            #on descend de niveau
            p = p._belo
            #tant que l'élément suivant est < que l'élément recherché
            while element >= p._next._elem:
                #on prend l'élément suivant
                p = p._next
        #s'arrête et retourne l'élément recherché ou son précédent
        return p

    #augmente la hauteur de la skiplist
    def increaseHeight(self):
        #on retient les anciennes sentinelles du plus haut niveau
        old_sentinel_l = self._start
        old_sentinel_r = self._start._next
        #on crée deux nouvelles sentinelles pour la nouveau niveau
        new_sentinel_l = SkipListNode(self._MIN_VALUE, None, None,
                                      old_sentinel_l, None)
        new_sentinel_r = SkipListNode(self._MAX_VALUE, new_sentinel_l, None,
                                      old_sentinel_r, None)
        new_sentinel_l._next = new_sentinel_r
        #on relie les pointeurs du dessus des vielles sentinelles aux nouvelles
        old_sentinel_l._abov = new_sentinel_l
        old_sentinel_r._abov = new_sentinel_r
        #on augmente la variable qui indique la hauteur de la skiplist
        self._height += 1
        #on ajuste le début de la skiplist
        self._start = new_sentinel_l

    #insère un noeud après le noeud p et au-dessus du noeud q
    def insertAfterAbove(self, p, q, element):
        #p est pour le précédent
        #q est pour celui au-dessous
        #arguments de SkipListNode : element, prev, next, belo, abov
        #abov toujours None car on insère toujours au niveau le plus haut
        #le nouveau noeud a p comme précédent, p._next comme suivant,
        #     q au-dessous et rien au-dessus
        newnode = SkipListNode(element, p, p._next, q, None)
        #on relie le précédent de l'ancien suivant, next._prev, au nouveau noeud
        p._next._prev = newnode
        #on relie le suivant du précédent, p._next, au nouveau noeud
        p._next = newnode
        #s'il y a un noeud en-dessous, q n'est pas à None, on le relie au nouveau noeud
        #which is abov it
        if not (q is None):
            q._abov = newnode
        #on retourne le nouveau noeud
        return newnode

    #insertion d'un nouvel élément
    #retourne le noeud du plus haut niveau du nouvel élément s'il n'existait pas
    #sinon, le noeud du niveau 0 de celui qui existait
    def SkipInsert(self, element):
        #on commence par le chercher
        p = self.SkipSearch(element)
        #on sauve le résultat de la recherche
        q = p
        #si l'élément existait
        if p._elem == element:
            #on doit modifier sa valeur à chaque niveau
            #imaginez des éléments du type ( clé, valeur )
            #on doit ajuster la valeur de tous les éléments de sa tour
            while (not p is None):
                p._elem = element
                p = p._abov
            #dans ce cas, on a terminé, on retourne
            return q

        #comme l'élément n'existe pas, p pointe sur le noeud précédent
        #nous sommes au niveau 0, donc belo est None
        q = self.insertAfterAbove(p, None, element)

        #on a inséré un noeud au niveau 0 pour le nouvel élément
        #on doit maintenant monter sa tour en fonction de pile ou face
        i = 0
        coin_flip = self._coin.flip()
        while coin_flip == _FACE:
            i += 1  #i indique le niveau courant d'insertion
            #si on a atteint le niveau du haut
            #on doit ajouter un nouveau niveau, on appelle increaseHeight()
            if i >= self._height:
                self.increaseHeight()
            #on doit ajouter un noeud sur le niveau au-dessus
            #on cherche un noeud dans les précédents, débutant à p, qui permet de monter de niveau
            while p._abov is None:
                #on va voir le précédent
                p = p._prev
            #p pointe vers un noeud qui en possède un au-dessus, on le suit pour monter
            p = p._abov
            #q pointe vers le noeud inséré précédemment,
            #il correspond au noeud en dessous du noeud à insérer
            q = self.insertAfterAbove(p, q, element)
            #on relance le jeton
            coin_flip = self._coin.flip()

        #ici on a terminé la tour de l'élément à insérer
        #avant de sortir, on incrémente de 1 la taille de la skiplist
        self._size += 1
        #on retourne le dernier noeud inséré, celui du plus haut niveau ajouté
        return q

    #_SkipHeadCut
    def decreaseHeight(self):
        p = self._start._belo
        while (not p._belo is None and p._next._elem == self._MAX_VALUE):
            self._start = p
            self._height -= 1
            p = p._belo
        return p

    #supprime et retourne un élément, s'il existe
    #sinon, retourne None
    def SkipRemove(self, element):
        #on commence par le chercher
        p = self.SkipSearch(element)
        #s'il existe
        if p._elem == element:
            #on retire le noeud de cet élément à chaque niveau
            tower = p
            while not (tower is None):
                #comme la suppression dans une liste chaînée
                tower._prev._next = tower._next
                tower._next._prev = tower._prev
                #on monte de niveau
                tower = tower._abov
            #on retourne
            return p
        return None
コード例 #30
0
    def run(self):
        #modified Framework from PyKinectBodyGame demo (Microsoft)
        # -------- Main Program Loop -----------

        pygame.mixer.music.load('sounds/Shelter.ogg')
        #music from Porter Robinson Soundcloud
        pygame.mixer.music.play(-1)

        while not self._done:
            # --- Main event loop

            for event in pygame.event.get():  # User did something
                if event.type == pygame.QUIT:  # If user clicked close
                    self._done = True  # Flag that we are done so we exit this loop

                elif event.type == pygame.VIDEORESIZE:  # window resized
                    self._screen = pygame.display.set_mode(
                        event.dict['size'],
                        pygame.HWSURFACE | pygame.DOUBLEBUF | pygame.RESIZABLE,
                        32)

            if self._kinect.has_new_color_frame():
                frame = self._kinect.get_last_color_frame()
                self.draw_color_frame(frame, self._frame_surface)
                frame = None

            if self.splashScreen == True:
                #frame = self._kinect.get_last_color_frame()
                #self.draw_color_frame(frame, self._frame_surface)
                background = pygame.image.load("images/CreditsToVickyYe.png")
                #image editing credit to vicky ye
                #original image from upscaletravel.com

                self._frame_surface.blit(background, [0, 0])
                self._frame_surface.blit(
                    self.gameoverfont.render("LETS PLAY", True,
                                             (255, 255, 255)),
                    (self.screen_width // 2 - 800, 50))
                self._frame_surface.blit(
                    self.scorefont.render(
                        "STEP IN FRONT AND CLAP TO START GAME", True,
                        (255, 255, 255)), (self.screen_width // 2 - 800, 150))

                self.snow.add(Snow())
                self.snow.update(self.screen_width, self.screen_height)
                self.snow.draw(self._frame_surface)

            if self.splashScreen == False:
                #Draw Graphics

                if float(self.time) == 0:
                    self.originaltime = time.time()

                self.draw_background()
                self.getHighScore()
                self.draw_path()

                #updates path coordinates after drawing it
                self.up_path_left = 800 + 4 * self.curve4 + self.ofset + self.curveoffset
                self.up_path_right = 1120 + 4 * self.curve4 + self.ofset + self.curveoffset
                self.bot_path_left = 200 + self.curve1 + self.ofset + self.curveoffset
                self.bot_path_right = 1720 + self.curve1 + self.ofset + self.curveoffset

                self.draw_sky()
                self.draw_mountains()
                self.draw_score()
                self.draw_lives()
                self.draw_time()

                #displays in
                if float(self.time) < 5:
                    self._frame_surface.blit(
                        self.scorefont.render(
                            "SQUAT AND COLLECT COINS, STAND TO JUMP OVER OBSTACLES",
                            True, (0, 0, 0)),
                        (self.screen_width // 2 - 500, 50))
                    self._frame_surface.blit(
                        self.scorefont.render("PUT HANDS ON HEAD TO PAUSE",
                                              True, (0, 0, 0)),
                        (self.screen_width // 2 - 300, 150))
                    self._frame_surface.blit(
                        self.scorefont.render(
                            "YOU HAVE 3 LIVES BUT IF YOU GO OFF THE PATH YOU LOSE THEM ALL",
                            True, (0, 0, 0)),
                        (self.screen_width // 2 - 550, 250))

                if 6 > float(self.time) > 5:

                    self._frame_surface.blit(
                        self.gameoverfont.render("GOOD LUCK!", True,
                                                 (0, 0, 0)),
                        (self.screen_width // 2 - 250, 300))

                self.time = "{0:.2f}".format(time.time() - self.originaltime)

                #increase speed as game progresses
                for coin in self.coins:
                    coin.updateVelocity(0, .01)

                for rock in self.rocks:
                    rock.updateVelocity(0, .01)

                #changs color of the sky
                if self.skyb == 255:
                    self.colorIncreasing = False
                if self.skyb == 220:
                    self.colorIncreasing = True

                if self.colorIncreasing == False:
                    self.skyb -= .25
                    self.skyr -= .25
                if self.colorIncreasing == True:
                    self.skyb += .25
                    self.skyr += .25

                    #sprites are generated by producing a random number
                #if 0 produce sprite
                #range of random number indicates frequency

                x = random.randint(0, 40)
                if x == 0 and len(self.rocks) < 1:
                    r = Rock(self.up_path_left + 250, self.up_path_right + 50)
                    self.rocks.add(r)
                self.rocks.update(self.screen_width, self.screen_height)
                self.rocks.draw(self._frame_surface)

                n = random.randint(0, 20)
                if n == 0:
                    c = Coin(self.up_path_left + 150, self.up_path_right)
                    self.coins.add(c)
                    #print(self.coins)
                    #print(n)
                self.coins.update(self.screen_width, self.screen_height)
                self.coins.draw(self._frame_surface)

                self.snow.add(Snow())
                self.snow.update(self.screen_width, self.screen_height)
                self.snow.draw(self._frame_surface)

                z = random.randint(0, 500)
                if z == 0:
                    k = Kosbie(self.up_path_left + 150, self.up_path_right)
                    self.kosbie.add(k)

                self.kosbie.update(self.screen_width, self.screen_height)
                self.kosbie.draw(self._frame_surface)

                if float(self.time) > 9 and float(
                        self.time) % 5 < 0.075 and self.isPaused == False:
                    i = random.randint(0, 4)
                    self.previouscurve = self.curve
                    self.curve = self.curvevalues[i]

                    #print(self.curve)
                if abs(self.curve1 - self.curve) > 4 and abs(self.curve4 -
                                                             self.curve) > 4:
                    if self.curve > self.curve1:
                        if self.curve1 != self.curve:
                            self.curveIn()

                    if self.curve < self.curve1:
                        if self.curve1 != self.curve:
                            self.curveOut()

                #curve offset is the offset from curving
                if self.curve == 120:
                    self.curveoffset += 10
                if self.curve == 60:
                    self.curveoffset += 5
                if self.curve == -60:
                    self.curveoffset -= 5
                if self.curve == -120:
                    self.curveoffset -= 10

            #adjust sprite location based on curve
                if self.curve == 60 and self.curveoffset != 0:
                    for coin in self.coins:
                        coin.updatePosition(4, 0)
                    for rock in self.rocks:
                        rock.updatePosition(4, 0)

                if self.curve == -60 and self.curveoffset != 0:
                    for coin in self.coins:
                        coin.updatePosition(-4, 0)
                    for rock in self.rocks:
                        rock.updatePosition(-4, 0)

                if self.curve == 120 and self.curveoffset != 0:
                    for coin in self.coins:
                        coin.updatePosition(8, 0)
                    for rock in self.rocks:
                        rock.updatePosition(8, 0)

                if self.curve == -120 and self.curveoffset != 0:
                    for coin in self.coins:
                        coin.updatePosition(-8, 0)
                    for rock in self.rocks:
                        rock.updatePosition(-8, 0)

                self.draw_person()

            # Get skeletons
            if self._kinect.has_new_body_frame():
                self._bodies = self._kinect.get_last_body_frame()

            #print(self._bodies)
            #print(self._kinect.max_body_count)
            # --- draw skeletons to _frame_surface
            if self._bodies is not None:

                for i in range(0, self._kinect.max_body_count):
                    #TEST LATER

                    body = self._bodies.bodies[i]

                    if (body.is_tracked and isInCircle(
                            self.left_hand[0], self.left_hand[1], 100,
                            self.right_hand[0], self.right_hand[1])):
                        self.splashScreen = False

                    if not body.is_tracked:
                        continue

                    joints = body.joints
                    # ---convert joint coordinates to color space
                    joint_points = self._kinect.body_joints_to_color_space(
                        joints)
                    if self.splashScreen == True:
                        self.draw_body(joints, joint_points,
                                       SKELETON_COLORS[i])
                        #temp for testing purpose

                    #moving hand logic
                    #finds colorspace point of each hand
                    if (joints[PyKinectV2.JointType_HandLeft].TrackingState !=
                            PyKinectV2.TrackingState_NotTracked):
                        self.left_hand = (
                            joint_points[PyKinectV2.JointType_HandLeft].x,
                            joint_points[PyKinectV2.JointType_HandLeft].y)
                        # print(self.left_hand)
                        pass
                    if (joints[PyKinectV2.JointType_HandRight].TrackingState !=
                            PyKinectV2.TrackingState_NotTracked):
                        self.right_hand = (
                            joint_points[PyKinectV2.JointType_HandRight].x,
                            joint_points[PyKinectV2.JointType_HandRight].y)
                    # print("righthand:" + str(self.right_hand))

                    self.draw_hands(self.left_hand[0], self.left_hand[1],
                                    self.right_hand[0], self.right_hand[1])

                    for kosbie in self.kosbie:
                        try:

                            if (kosbie.rect.collidepoint(self.left_hand)
                                    and self.isJumping == False
                                    and coin.rect.y > 500):
                                kosbie.kill()
                                self.score += 10
                                if self.lives < 3:
                                    self.lives += 1
                                #self.coinsound.play()
                            elif (kosbie.rect.collidepoint(self.right_hand)
                                  and self.isJumping == False
                                  and coin.rect.y > 500):
                                kosbie.kill()
                                self.score += 10
                                if self.lives < 3:
                                    self.lives += 1
                                self.coinsound.play()

                        except:
                            pass

                    for coin in self.coins:
                        try:
                            #print(coin.rect)
                            if (coin.rect.collidepoint(self.left_hand)
                                    and self.isJumping == False
                                    and coin.rect.y > 500):
                                coin.kill()
                                self.score += 1
                                self.coinsound.play()

                            elif (coin.rect.collidepoint(self.right_hand)
                                  and self.isJumping == False
                                  and coin.rect.y > 500):
                                coin.kill()
                                self.score += 1
                                self.coinsound.play()

                        except:
                            pass

                    if self.score > self.highscore:
                        self.highscore = self.score
                        self.saveHighScore(self.highscore)

                    #jumping logic
                    #tests if is jumping
                    if (joints[PyKinectV2.JointType_HipLeft].TrackingState !=
                            PyKinectV2.TrackingState_NotTracked):
                        self.prevleftleg = self.left_leg
                        self.left_leg = joints[
                            PyKinectV2.JointType_HipLeft].Position.y
                        #print("leftleg:"+ str(self.left_leg))
                    if (joints[PyKinectV2.JointType_HipRight].TrackingState !=
                            PyKinectV2.TrackingState_NotTracked):
                        self.prevrightleg = self.right_leg
                        self.right_leg = joints[
                            PyKinectV2.JointType_HipRight].Position.y
                        #print("BLAH",self.right_leg)

                    self.jump -= 10
                    if self.jump < 0:
                        self.jump = 0

                    if self.left_leg > -.5 and self.right_leg > -.5:
                        #y coordinate of the each hip
                        #checks to make sure you are not standing up
                        #print("JUMP MAN")
                        self.isJumping = True

                    #else:
                    #   self.isJumping=False
                    #print(self.isJumping)

                    if self.isJumping == True and self.isFalling == False:
                        self.jump += 100
                        if self.jump > 200:
                            self.isFalling = True
                            self.jump = 200

                    if self.jump == 0:
                        self.isJumping = False
                        self.isFalling = False

                    #tilting logic
                    if (joints[
                            PyKinectV2.JointType_SpineShoulder].TrackingState
                            != PyKinectV2.TrackingState_NotTracked and
                            joints[PyKinectV2.JointType_SpineMid].TrackingState
                            != PyKinectV2.TrackingState_NotTracked):
                        self.lowerbody = joints[
                            PyKinectV2.JointType_SpineMid].Position.x
                        self.previousbody = self.bodylocation
                        self.bodylocation = joints[
                            PyKinectV2.JointType_SpineShoulder].Position.x

                    if (self.bodylocation -
                            self.lowerbody) > .025 and self.previousbody > 0:

                        self.ofset -= 15
                        if self.tilting < 50:
                            self.tilting += 10

                        for coin in self.coins:
                            coin.updatePosition(-5, 0)

                        for rock in self.rocks:
                            rock.updatePosition(-5, 0)

                    elif (self.bodylocation -
                          self.lowerbody) < -.025 and self.previousbody < 0:

                        self.ofset += 15
                        if self.tilting > -50:
                            self.tilting -= 10
                        for coin in self.coins:
                            coin.updatePosition(5, 0)

                        for rock in self.rocks:
                            rock.updatePosition(5, 0)

                    else:
                        if self.tilting < 0 and self.tilting != 0:
                            self.tilting += 10
                        if self.tilting > 0 and self.tilting != 0:
                            self.tilting -= 10

                    for rock in self.rocks:
                        #print(rock.rect.centery)
                        #print(abs(rock.rect.centerx-self.skier_x))
                        try:
                            #checks if rock is at bottom and if colliding when not jumping
                            if (rock.rect.centery > 1050
                                    and rock.rect.collidepoint(
                                        self.skier_x, self.skier_y + 100)
                                    and self.isJumping == False):
                                #self.isGameOver=True
                                self.loselife = True
                                rock.kill()

                        except:
                            pass

                    #checks to make sure player is still in path'
                    #print(200+self.ofset)
                    #print(self.bot_path_left,self.bot_path_right)
                    if not self.bot_path_left < self.skier_x < self.bot_path_right:
                        #self.isGameOver=True
                        self.loselife = True

                    if self.loselife == True:
                        self.lives -= 1
                        self.loselife = False
                    if self.lives == 0:
                        self.isGameOver = True

                    #tracks
                    if (joints[PyKinectV2.JointType_Head].TrackingState !=
                            PyKinectV2.TrackingState_NotTracked):
                        self.head = (joint_points[PyKinectV2.JointType_Head].x,
                                     joint_points[PyKinectV2.JointType_Head].y)

                    if (joints[PyKinectV2.JointType_ElbowRight].TrackingState
                            != PyKinectV2.TrackingState_NotTracked):
                        self.elbow = (
                            joint_points[PyKinectV2.JointType_ElbowRight].x,
                            joint_points[PyKinectV2.JointType_ElbowRight].y)

                    #checks if dabbing
                    #if dabbing switch face of skier

                    if (isInCircle(self.head[0], self.head[1], 150,
                                   self.elbow[0], self.elbow[1])):
                        self.isYoungchk *= -1

                    if (isInCircle(self.head[0], self.head[1], 100,
                                   self.left_hand[0], self.left_hand[1])
                            and isInCircle(self.head[0], self.head[1], 100,
                                           self.right_hand[0],
                                           self.right_hand[1])):
                        self.isPaused = True
                    else:
                        self.isPaused = False

                    if self.isPaused == True:
                        self._frame_surface.fill([255, 255, 255])
                        background = pygame.image.load("images/doggo.jpg")
                        #image fromhttp://drivethrutv.com/project/subaru-dogs-skiing/
                        #background =  pygame.transform.scale(background
                        # , (self.screen_width,self.screen_height));
                        self._frame_surface.blit(background, [0, 0])
                        self._frame_surface.blit(
                            self.otherfont.render("PAUSED", True,
                                                  (112, 112, 112)),
                            (self.screen_width // 2 - 800,
                             self.screen_height // 2))
                        self._frame_surface.blit(
                            self.otherfont.render(
                                "USE YOUR HANDS TO COLLECT COINS", True,
                                (112, 112, 112)),
                            (self.screen_width // 2 - 800,
                             self.screen_height // 2 + 200))
                        self._frame_surface.blit(
                            self.otherfont.render("TILT AND JUMP", True,
                                                  (112, 112, 112)),
                            (self.screen_width // 2 - 800,
                             self.screen_height // 2 + 300))
                        self._frame_surface.blit(
                            self.otherfont.render(
                                "TO STAY ON PATH AND AVOID OBSTACLES", True,
                                (112, 112, 112)),
                            (self.screen_width // 2 - 800,
                             self.screen_height // 2 + 400))
                        self.isJumping = True

            if self._bodies == None:
                self.isPaused = True

                #game over conditions
            if self.isGameOver == True:
                self.applause.play()
                self._frame_surface.fill([255, 255, 255])
                background = pygame.image.load("images/lmao.jpg")
                background = pygame.transform.scale(
                    background, (self.screen_width, self.screen_height))
                self._frame_surface.blit(background, [0, 0])

                self._frame_surface.blit(
                    self.otherfont.render("GAME OVER :(", True, (0, 0, 0)),
                    (self.screen_width // 2 - 850,
                     self.screen_height // 2 - 100))
                self._frame_surface.blit(
                    self.otherfont.render("CLAP TO RESTART", True, (0, 0, 0)),
                    (self.screen_width // 2 - 850,
                     self.screen_height // 2 + 300))
                if self.highscore == self.score:
                    self._frame_surface.blit(
                        self.otherfont.render(
                            "NEW HIGH SCORE: %s" % self.highscore, True,
                            (0, 0, 0)), (self.screen_width // 2 - 850,
                                         self.screen_height // 2 + 100))
                else:
                    self._frame_surface.blit(
                        self.otherfont.render(
                            "HIGH SCORE: %s" % self.highscore, True,
                            (0, 0, 0)), (self.screen_width // 2 - 850,
                                         self.screen_height // 2 + 100))

            for event in pygame.event.get():
                #if event.type == pygame.MOUSEBUTTONDOWN:
                #   self.isJumping=True
                #  print('JUMPING BOI')
                #else:
                #   self.isJumping=False
                if event.type == pygame.KEYUP:
                    self.__init__()
                    self.time = 0
            if self.isGameOver == True and isInCircle(
                    self.left_hand[0], self.left_hand[1], 100,
                    self.right_hand[0], self.right_hand[1]):
                self.__init__()
                self.time = 0

            #copy back buffer surface pixels to the screen, resize it if
            #needed and keep aspect ratio

    #(screen size may be different from Kinect's color frame size)
            h_to_w = (float(self._frame_surface.get_height()) /
                      self._frame_surface.get_width())
            target_height = int(h_to_w * self._screen.get_width())
            surface_to_draw = pygame.transform.scale(
                self._frame_surface, (self._screen.get_width(), target_height))
            self._screen.blit(surface_to_draw, (0, 0))
            surface_to_draw = None
            pygame.display.update()

            # --- Go ahead and update the screen with what we've drawn.
            pygame.display.flip()

            # --- Limit to 60 frames per second
            self._clock.tick(60)

        # Close our Kinect sensor, close the window and quit.
        self._kinect.close()
        pygame.quit()
コード例 #31
0
def min_catch_strategy(coins_name: list):
    os.makedirs('logs', exist_ok=True)
    log_file = open("logs/MCS_order.log", "a")
    print(f'{get_now_time()} 시작가: {get_krw():.2f}')
    log_file.write(f'{get_now_time()} 시작가: {get_krw():.2f}\n')

    print_order_config(config.items(section="VB_ORDER"))
    coin_dict = dict()
    for coin_name in coins_name:
        coin_dict[coin_name] = Coin(coin_name)
    while True:
        for i, coin in enumerate(coin_dict.values()):
            try:
                candles = get_candles('KRW-' + coin.coin_name,
                                      count=2,
                                      minute=UNIT,
                                      candle_type=CANDLE_TYPE)
                coin.high_price = max(candles[0]["trade_price"],
                                      coin.high_price)
                now = candles[0]['candle_date_time_kst']

                if coin.state != State.PASS:
                    print(
                        f'{get_now_time()} {coin.coin_name:>6}({set_state_color(coin.state)}{coin.MCS_bought_cnt})| '
                        f'목표 가: {coin.MCS_buy_price[coin.MCS_bought_cnt] if coin.MCS_bought_cnt < MAX_BOUGHT_CNT else 0:>11.2f}, '
                        f'현재 가: {candles[0]["trade_price"]:>10},'
                        f'구매 가: {coin.avg_buy_price:>11.2f}'
                        f' ({set_dif_color(candles[0]["trade_price"], coin.MCS_buy_price[coin.MCS_bought_cnt] if coin.MCS_bought_cnt < MAX_BOUGHT_CNT else 0)}) '
                        f' ({set_dif_color(candles[0]["trade_price"], coin.avg_buy_price)}) '
                    )

                # 매도 조건
                # 시간 캔들이 바뀐 경우
                if coin.check_time != now:
                    if i == 0:
                        print(
                            f'----------------------------------- UPDATE ---------------------------------------'
                            f'\n{coin.check_time} -> \033[36m{now}\033[0m')

                    if coin.state in [State.BOUGHT, State.ADDBUY
                                      ] or coin.MCS_bought_cnt != 0:
                        sell_result = coin.sell_coin()
                        print(
                            f'\033[104m{get_now_time()} {coin.coin_name:>6}(  SELL)| {int(round(get_sell_price(sell_result)))}원\033[0m'
                        )
                        log_file.write(
                            f'{get_now_time()}, {coin.coin_name}, SELL, {int(round(get_sell_price(sell_result)))}\n'
                        )

                    coin.state = State.WAIT
                    coin.max_earnings_ratio = 0
                    coin.earnings_ratio = 0
                    coin.check_time = now
                    coin.variability = candles[1]['high_price'] - candles[1][
                        'low_price']
                    coin.high_price = candles[0]["opening_price"]

                    print(coin.variability, coin.high_price * 0.015)
                    if coin.variability < coin.high_price * 0.015:
                        coin.state = State.PASS
                    coin.avg_buy_price = 0

                    coin.MCS_bought_cnt = 0
                    coin.MCS_buy_price = [
                        candles[0]["opening_price"] -
                        coin.variability * var * BUY_DIF_RANGE
                        for var in range(1, MAX_BOUGHT_CNT + 1)
                    ]
                    print(coin.MCS_buy_price)

                    if i == len(coin_dict) - 1:
                        print(
                            f'---------------------------------------------------------------------------------'
                        )
                else:  # 시간이 동일하다면
                    if coin.MCS_bought_cnt >= MAX_BOUGHT_CNT\
                            or candles[0]['trade_price'] > coin.MCS_buy_price[coin.MCS_bought_cnt]\
                            or coin.state == State.PASS:
                        continue

                    # 매수
                    buy_result = coin.buy_coin(price=BUY_AMOUNT)
                    coin.MCS_bought_cnt += 1
                    if not buy_result:
                        continue
                    print(
                        f'\033[101m{get_now_time()} {coin.coin_name:>6}(  BUY{coin.MCS_bought_cnt})| {coin.bought_amount}원\033[0m'
                    )
                    log_file.write(
                        f'{get_now_time()}, {coin.coin_name}, BUY{coin.MCS_bought_cnt}, {coin.bought_amount}\n'
                    )
            except IndexError as e:
                continue