Ejemplo n.º 1
0
def main():

    for i in range(99):
        coin = Coin()
        print(coin, end=", ")
    coin = Coin()
    print(coin, end=".")

    print("\n\nHeads so far: ", Coin.get_heads_so_far())
    print("Tails so far: ", Coin.get_tails_so_far())

    print("\nBye, Bye!\n")
Ejemplo n.º 2
0
class Game(object):
    def __init__(self, hacker, zardus, id):
        self.player1 = hacker
        self.player2 = zardus
        self.competitor_bet1 = random.randint(0, 1)
        self.competitor_bet2 = random.randint(0, 1)
        self.player2_bet = self.player2.bet(id, self.competitor_bet2)
        self.coin = Coin(id)
        self.id = id

    def error(self):
        print(f"Selection does not exist. {LOSE_MSG}")
        return LOSE

    def run(self):
        print(
            f"[Round {self.id}]: Your competitor bets on {self.competitor_bet1}"
        )
        print(OPTIONS)
        selection = input().strip()
        if selection == COIN:
            print(COIN_ROTATE)
            selection = input().strip()
            if selection == LEFT:
                self.coin.rotate_left()
            elif selection == RIGHT:
                self.coin.rotate_right()
            elif selection != NOT_CHANGE:
                return self.error()
            player1_bet = self.coin.flip(self.competitor_bet1)
        elif selection == ZERO:
            player1_bet = 0
        elif selection == ONE:
            player1_bet = 1
        elif selection == "q":
            print("Magic quit option")
            sys.exit(0)
        else:
            return self.error()

        print(
            f"[Round {self.id}]: zardus's competitor bets on {self.competitor_bet2}, "
            + f"you bet on {player1_bet}")
        return self.play(player1_bet, self.player2_bet)

    def play(self, p1_bet, p2_bet):
        if p1_bet ^ p2_bet == self.competitor_bet1 * self.competitor_bet2:
            print(WIN_MSG)
            return WIN
        else:
            print(LOSE_MSG)
            return LOSE
Ejemplo n.º 3
0
def enter():
    game_framework.reset_time()
    global map, player, house, background, avalanche, coin, snows, map_on_coins, game_over, santa, game_clear, distance, stones
    map = Map()
    player = Player()
    house = House()
    background = Background()
    avalanche = Avalanche()
    coin = Coin()
    game_over = Game_over()
    santa = Santa()
    game_clear = Game_clear()
    distance = Distance()
    map_on_coins = [Map_on_Coin() for i in range(200)]
    snows = [Snow() for i in range(20)]
    stones = [Stone() for i in range(10)]

    Player.x = 300.0
    Player.y = 300.0
    Player.unreal_x = 300.0
    Player.unreal_y = 0
    Player.jump_before_y = 0
    Map.map_move_y_minor = 0
    Avalanche.game_over = 0
    Game_clear.game_clear = 0
    Santa.game_clear = 0
Ejemplo n.º 4
0
    def get_coins_by_owner(self, *, owner, name=None):
        query = "OwnerID=:owner"
        query_vals = {":owner": owner}
        table = self.get_table("Coin")
        if name:
            filters = "contains (lowername,:Coinname)"
            query_vals[":Coinname"] = name.lower()
        else:
            filters = None

        proj = "HashKey, #CoinName, T, MaxDate, MinDate, Frequency, StrategyCode"
        if filters:
            res = table.query(IndexName="OwnerID-index",
                              FilterExpression=filters,
                              KeyConditionExpression=query,
                              ExpressionAttributeValues=query_vals,
                              ExpressionAttributeNames={"#CoinName": "Name"},
                              ProjectionExpression=proj)
        else:
            res = table.query(IndexName="OwnerID-index",
                              KeyConditionExpression=query,
                              ExpressionAttributeValues=query_vals,
                              ExpressionAttributeNames={"#CoinName": "Name"},
                              ProjectionExpression=proj)

        if res['Count'] > 0:
            return sorted([Coin(OwnerId=owner, Data=f) for f in res['Items']],
                          key=sort_by_name)
        return []
Ejemplo n.º 5
0
    def setup_coins(self, values, weights):
        """Turn the input of values and weight into coins

        set values for the min and max range for values

        Args:
            values: the input values
            weights: the weight of each value
        """

        if len(values) != len(weights):
            raise ValueError(
                'Values and weight must have same number of inputs')

        for i in range(0, len(values)):  # Making Coins
            value = values[i]
            coin = Coin(value, weights[i])
            self.coin_list.append(coin)

            if isinstance(value, (int, float)) and not math.isnan(value):
                self.total_weight += weights[i]  # Sum total weight of coins
                if self.min_value is None or self.min_value > value:
                    self._min_value = value
                if self.max_value is None or self.max_value < value:
                    self.max_value = value
Ejemplo n.º 6
0
    def get_coins(self, *, owner, coinids, get_ts=False):

        query = "OwnerID=:owner"
        table = self.get_table("Coin")

        N = len(coinids)
        vallist = [':hashkey_%s' % i for i in range(N)]
        filterexp = 'HashKey in (' + ','.join(vallist) + ')'

        qvals = dict([(':hashkey_%s' % i, coinids[i]) for i in range(N)])
        qvals[':owner'] = owner

        proj = "HashKey, #CoinName, T, MaxDate, MinDate, Frequency, StrategyCode"
        if get_ts:
            proj = proj + ',Performance'
        res = table.query(IndexName="OwnerID-index",
                          FilterExpression=filterexp,
                          KeyConditionExpression=query,
                          ExpressionAttributeValues=qvals,
                          ExpressionAttributeNames={"#CoinName": "Name"},
                          ProjectionExpression=proj)
        if res['Count'] > 0:
            if get_ts:
                for item in res['Items']:
                    self.update_perf_item(item)
            return [Coin(OwnerId=owner, Data=f) for f in res['Items']]
        return []
Ejemplo n.º 7
0
def enter():
    global mario, map, enemy, object, fire_ball, chimney, mario_life
    global mario_life2, mario_life3, mario_life4
    global item_box, brick, item, coin_box, turtle, coin, balls
    mario = Mario()
    map = Map()
    enemy = Enemy()
    object = Object()
    fire_ball = Ball()
    chimney = Chimney()
    mario_life = Mario_Life()
    mario_life2 = Mario_Life2()
    mario_life3 = Mario_Life3()
    mario_life4 = Mario_Life4()
    item_box = Object_Item()
    brick = Brick()
    item = Item()
    coin_box = Coin_Box()
    turtle = Turtle()
    coin = Coin()

    game_world.add_object(map, 0)
    game_world.add_object(object, 1)
    game_world.add_object(mario, 0)
    game_world.add_object(enemy, 1)
    #game_world.add_object(chimney, 0)
    game_world.add_object(mario_life, 1)
    game_world.add_object(mario_life2, 0)
    game_world.add_object(mario_life3, 1)
    game_world.add_object(mario_life4, 0)
    game_world.add_object(item_box, 1)
    game_world.add_object(brick, 0)
    game_world.add_object(coin_box, 1)
    #game_world.add_object(turtle, 0)
    pass
Ejemplo n.º 8
0
def enter():
    global game_map
    game_map = Game_map()
    game_world.add_object(game_map, 0)

    global score
    score = Score()
    game_world.add_object(score, 1)

    global player
    player = Player()
    game_world.add_object(player, 1)

    global coins, big_coins
    coins = [Coin() for i in range(10)]
    big_coins = [BigCoin() for i in range(10)]

    game_world.add_objects(coins, 1)
    game_world.add_objects(big_coins, 1)

    global emy_Red, emy_Blue, emy_Pink, emy_Orange

    emy_Red = Emy_Red()
    emy_Blue = Emy_Blue()
    emy_Pink = Emy_Pink()
    emy_Orange = Emy_Orange()

    game_world.add_object(emy_Red, 1)
    game_world.add_object(emy_Blue, 1)
    game_world.add_object(emy_Pink, 1)
    game_world.add_object(emy_Orange, 1)
Ejemplo n.º 9
0
    def deadProcess(self):
        self.coinTime += mainframe.frame_time

        if self.BossHandLeft != None:
            self.BossHandLeft.hp = 0
        if self.BossHandRight != None:
            self.BossHandRight.hp = 0

        self.almost_die(3)

        if self.coinTime > self.coinDelay:
            game_world.add_object(
                Coin(
                    random.randint(int(self.posX - self.sizeX // 2),
                                   int(self.posX + self.sizeX // 2)),
                    random.randint(int(self.posY - self.sizeY // 3),
                                   int(self.posY + self.sizeY // 3)), 1.5, 1.5,
                    random.randint(5, 10) * (self.difficulty) * 100), COIN)
            self.coinTime = 0
            self.coinCount += 1

        if self.coinCount > 50:
            return True
        else:
            return False
Ejemplo n.º 10
0
def run_game():
    #Initialize game and create screen object
    pygame.init()
    pygame.mixer.music.load('sounds/background.wav')
    pygame.mixer.music.play(-1)
    coin_sound = pygame.mixer.Sound("sounds/coin_collect.wav")
    create_sound = pygame.mixer.Sound("sounds/create.wav")
    delete_sound = pygame.mixer.Sound("sounds/delete.wav")
    # gameover_sound = pygame.mixer.Sound("sounds/gameover.wav")

    lin_settings = Settings()
    stats = GameStats(lin_settings)
    stats.initialize_high_score()
    screen = pygame.display.set_mode(
        (lin_settings.screen_width,lin_settings.screen_height), pygame.FULLSCREEN)
    pygame.display.set_caption("Lines")
    print(lin_settings.screen_width, lin_settings.screen_height)

    sb = Scoreboard(lin_settings, screen, stats)

    dot = Dot(screen)
    coin = Coin(screen, lin_settings)
    play_button = Button(lin_settings, screen, "Play", (screen.get_rect().centerx + 250, 40), (0, 255, 0))
    # undo_button = Button(lin_settings, screen, "Undo", (screen.get_rect().centerx - 250, 40), (255, 255, 0))

    #main loop of the game
    while True:
        gf.check_events(screen, dot, stats, coin, lin_settings, sb, play_button, 
            create_sound, coin_sound, delete_sound)
        gf.update_screen(lin_settings, screen, dot, coin, sb, stats, play_button)
Ejemplo n.º 11
0
def main():
    coinmarketcap = Market()
    markets_coin = coinmarketcap.ticker(limit=20)

    coins = []
    for i in range(0, 20):
        coins.append(
            Coin(name=markets_coin[i]['name'],
                 accronym=markets_coin[i]['symbol'],
                 in_usd=markets_coin[i]['price_usd'],
                 available_supply=markets_coin[i]['available_supply'],
                 total_supply=markets_coin[i]['total_supply']))

    print("\033c")
    for i in coins:
        sys.stdout.write(str(i))
    time.sleep(20)

    while (True):

        count_coin = 0
        markets_coin = coinmarketcap.ticker(limit=20)
        for i in coins:
            i.update(markets_coin[count_coin]['price_usd'])
            count_coin += 1

        print("\033c")
        for i in coins:
            sys.stdout.write(str(i))

        time.sleep(20)
Ejemplo n.º 12
0
    def addCoin(self, coin):

        try:
            # API url with the typed coin connected
            url = 'https://api.coingecko.com/api/v3/coins/' + coin

            response = (requests.get(url)).json()
            MyCoins.myListOfCoins.append(
                Coin(coin, response["market_data"]['current_price']['usd'],
                     response["market_data"]['price_change_percentage_24h']))
            print('\nAdded coin: {}'.format(coin))

        except (requests.exceptions.RequestException,
                ConnectionResetError) as error:
            print(
                '\nCould not find coin. Unexpected response after typed coin: ',
                error)

        except IndexError as indexError:
            print('IndexError: ', indexError)

        except KeyError as keyError:
            print('KeyError. Could not find', keyError)

        except ValueError as valueError:
            print('ValueError: :', valueError)

        except TypeError as typeError:
            print('TypeError: ', typeError)
Ejemplo n.º 13
0
    def update(self):
        self.time += mainframe.frame_time

        if self.shootCheck == True:
            self.shootTime += mainframe.frame_time

        # update
        self.update_AI()
        self.update_anim()

        # 맵 밖을 나가면 몬스터를 없앤다.
        if (self.posX < 0 - self.sizeX) or (self.posX >
                                            static.canvas_width + self.sizeX):
            return True
        elif (self.posY < 0 - self.sizeY):
            return True
        # 체력이 다되면 몬스터를 없앤다.
        elif (self.hp <= 0):
            game_world.add_object(
                Effect(self.posX, self.posY, 'random_effect', '',
                       self.originSizeX, self.originSizeY), EFFECT)
            game_world.curtain_object(PLAYER, 0).parsingScoreBar(
                random.randint(100, 500) * self.difficulty)
            game_world.add_object(
                Coin(self.posX, self.posY, 1.5, 1.5,
                     random.randint(1, 5) * (self.difficulty) * 100), COIN)
            Monster.sound.get(str(random.randint(1, 2))).play()
            return True
        else:
            return False
Ejemplo n.º 14
0
def get_coin_info(symbol, json_data):
    ath = 0.
    last_ath = ''
    found = False

    if (symbol == 'IOTA'):
        symbol = 'M' + symbol  # dirty IOTA fix ( ticker is MIOTA :( )

    changed = False
    for data in json_data:
        for key, val in data.items():
            if (key == 'name'):
                name = str(val)
            elif (key == 'symbol'):
                coin_symbol = str(val)
            elif (key == 'price_usd'):
                price = val
            elif (key == 'available_supply'):
                supply_now = val
        if (coin_symbol.lower() == symbol.lower()):
            found = True
            break

    if not found:
        print(symbol + ' not found!')
        return None

    return Coin(name, symbol, price, supply_now, ath, last_ath)
Ejemplo n.º 15
0
    def get_coin_by_name(self, *, owner, name, get_ts=False):

        table = self.get_table("Coin")
        qvals = {"#Coinname": name}
        qvals[':owner'] = owner

        proj = "HashKey, #CoinName, T, MaxDate, MinDate, Frequency, StrategyCode"
        # since Coin data is stored with Coin table the projection is used to
        # determine if the performance data need to be retrieved
        if get_ts:
            proj = proj + ',Performance'

        res = table.query(IndexName="OwnerID-Name-index",
                          KeyConditionExpression=Key('OwnerID').eq(owner)
                          & Key("Name").eq(name),
                          ExpressionAttributeNames={"#CoinName": "Name"},
                          ProjectionExpression=proj)

        if res['Count'] > 0:
            if get_ts:
                for item in res['Items']:
                    self.update_perf_item(item)

            return [Coin(OwnerId=owner, Data=f) for f in res['Items']]
        return []
Ejemplo n.º 16
0
 def spawn(self):
     if self.do_spawn:
         preliminarily_group_coins = pygame.sprite.Group()
         preliminarily_group_nitro = pygame.sprite.Group()
         preliminarily_group_npc = pygame.sprite.Group()
         if self.chance(15):
             coin = Coin(preliminarily_group_coins, random.choice(
                 self.x_places), random.randrange(50, 350), self.road)
             if self.check(coin):
                 self.coin_group.add(coin)
         if self.chance(3):
             nitro = Nitro(preliminarily_group_nitro, self.road, random.choice(
                 self.x_places), random.randrange(50, 350))
             if self.check(nitro):
                 self.nitro_group.add(nitro)
         if self.chance(30):
             x = random.choice(self.x_places)
             if self.x_places[0] <= x <= self.x_places[1]:
                 x -= random.randrange(60, 90)
                 y = random.randrange(-150, -110)
                 npc = Npc(preliminarily_group_npc, x, y, True)
             else:
                 x -= random.randrange(60, 90)
                 y = random.randrange(890, 990)
                 npc = Npc(preliminarily_group_npc, x, y, False)
             if self.check(npc):
                 self.enemy_group.add(npc)
         if self.player.bg_time == 0:
             self.bg_time = time.time()
             self.player.bg_time = 1
Ejemplo n.º 17
0
    def drop_coin(self, mouse_pos):
        """Drop one coin from the top of the column closest to `mouse_pos`"""
        board = self.board
        board_xy = (self.settings.padding_left, self.settings.padding_top)

        # coin is spawned at the top of the column closest to the mouse
        col = closest_column(board, mouse_pos, self.settings)
        try:
            start_pos = board.rects[0][col].center
        except TypeError:
            return

        start_pos = (start_pos[0] + board_xy[1], start_pos[1] + board_xy[0])

        # coin will fall to the next open row
        row = get_next_open_row(board, col)
        try:
            end_pos = board.rects[row][col].center
        except TypeError:
            # if row is full: do nothing
            return

        end_pos = (end_pos[0] + board_xy[1], end_pos[1] + board_xy[0])

        # add it to the group of coin sprites
        self.coins.add(
            Coin(self.settings, self.screen, self.state, start_pos, end_pos,
                 self.music))

        print(f"dropped at col {col}.")

        # place the current player's number at (row, col)
        board.grid[row][col] = self.state

        print(board.grid)
Ejemplo n.º 18
0
 def _provide_flight_object(self):
     seed = ["alien", "coin"]
     selected_type = random.choice(seed)
     if selected_type == "alien":
         flight_object = Alien(self)
     if selected_type == "coin":
         flight_object = Coin(self)
     return flight_object
Ejemplo n.º 19
0
def genCoins(num):
    coinGroup = pygame.sprite.OrderedUpdates()
    for coin in range(num):
        myCoin = Coin().makeCoin()
        myCoin.rect.left = random.randint(1, 20) * TILE_SIZE
        myCoin.rect.top = random.randint(1, 10) * 80
        coinGroup.add(myCoin)
    return coinGroup
Ejemplo n.º 20
0
    def __init__(self):
        self.coin = Coin(0.4)
        self.goal = 100
        self.discount_rate = 1
        self.epsilon = 0.000001

        self.value_archive = []
        self.action_archive = []
    def test_retrieve_symbol(self):
        coin_info = backend.get_coins_list(coingecko)

        coin = Coin("bitcoin")
        coin.retrieve_symbol(coin_info)
        self.assertEqual(coin._symbol, "btc")

        coin = Coin("testing123")
        coin.retrieve_symbol(coin_info)
        self.assertEqual(coin._symbol, None)
Ejemplo n.º 22
0
 def generate_coins(self):
     n_coin = 200
     for _ in range(n_coin):
         while True:
             r = randint(4, self.__row - 6)
             c = randint(0, self.__col - 1)
             if not self._backing[(r, c)]:
                 break
         self.add_entity(Coin(r, c, self))
Ejemplo n.º 23
0
def make_coin_from_scratch(ID):
    try:
        f = '/data/whole/' + str(ID) + '.jpg'
        c = Coin().make_from_image(f)
        binarize_coin(c.img, ID).tofile('/data2/images/img/' + str(ID))
        binarize_coin(c.cr, ID).tofile('/data2/images/cr/' + str(ID))
        binarize_coin(c.rad, ID).tofile('/data2/images/rad/' + str(ID))
    except:
        bad_coins.append(ID)
Ejemplo n.º 24
0
    def get_coin(self, hashkey, get_ts=True):
        table = self.get_table("Coin")
        res = table.get_item(Key={'HashKey': hashkey})

        if 'Item' in res:
            if get_ts:
                self.update_perf_item(res['Item'])
            return Coin(Data=res['Item'])
        return None
Ejemplo n.º 25
0
    def analyse_txn(self, row: Dict[str, str]) -> None:
        date = self.dateparser.parse(row['Date'])

        # Preserve file ordering even when timestamps are identical
        if date == self.last_date:
            date += datetime.timedelta(milliseconds=1)
            # self.write("   >> shifted to " +
            #       date.isoformat(timespec='milliseconds'))
        self.last_date = date

        def safefloat(s: str) -> Optional[float]:
            return float(s) if s else None

        def safewallet(s: str) -> Wallet:
            return Wallet.named(s) if s else EXTERNAL

        recipient_name = row['Receiving Wallet']
        if row['Type'] == 'transfer' and row['Label'] == 'to_pool':
            recipient_name = recipient_name + ' pool'

        txn = Transaction(
            date=date,
            tx_type=row['Type'],
            label=row['Label'],
            sender=safewallet(row['Sending Wallet']),
            sent_amount=safefloat(row['Sent Amount']),
            sent_currency=Coin(row['Sent Currency']),
            sent_cost_basis=safefloat(row['Sent Cost Basis']),
            recipient=safewallet(recipient_name),
            received_amount=safefloat(row['Received Amount']),
            received_currency=Coin(row['Received Currency']),
            received_cost_basis=safefloat(row['Received Cost Basis']),
            fee_amount=safefloat(row['Fee Amount']),
            fee_currency=Coin(row['Fee Currency']),
            tx_src=row['TxSrc'],
            tx_dest=row['TxDest'],
            tx_id=row['TxHash'],
            desc=row['Description'],
        )

        # if txn.sender == txn.recipient:
        #     pprint(row)

        self.analyser.add_txn(txn)
    def test_init(self):
        coin = Coin("bitcoin",
                    symbol="btc",
                    price=None,
                    price_previous=None,
                    in_message=True,
                    last_updated=None)

        self.assertEqual(coin.get_id(), "bitcoin")
        self.assertEqual(coin.get_symbol(), "btc")
        self.assertEqual(coin.get_price(), None)
        self.assertEqual(coin.get_price_previous(), None)
        self.assertEqual(coin.get_price_change(), None)
        self.assertEqual(coin.get_in_message(), True)
        self.assertEqual(coin.get_last_updated(), None)
Ejemplo n.º 27
0
    def test_get_next_update_string(self):
        update_interval = 60

        # Normal
        coins = [None, None]
        coins[0] = Coin("bitcoin",
                        last_updated=datetime(2020, 5, 26, 13, 0, 0))

        coins[1] = Coin("tron", last_updated=datetime(2020, 5, 26, 13, 0, 0))

        next_update_string = backend.get_next_update_string(
            coins, update_interval)
        self.assertEqual(next_update_string, "13:01:00")

        # No coins
        coins = []
        next_update_string = backend.get_next_update_string(
            coins, update_interval)
        self.assertEqual(next_update_string, "N/A")
Ejemplo n.º 28
0
 def __init__(self, i, bg):
     self.bg = bg
     self.x, self.y = self.chestList[i]  # 32 = chest의 높이 // 2
     if Chest.image == None:
         Chest.image = load_image('image\Golden_Chest.png')
     self.frame = 0
     self.openning = False
     self.openCount = 1
     #self.itemList = [Potion(self.x, self.y), Potion(self.x, self.y+320), Fire_Book(self.x, self.y),
     #                Coin(self.x+30, self.y+30), Lightning_Book(self.x, self.y)]
     self.itemList = [
         Potion(self.x, self.y, self.bg),
         Fire_Book(self.x, self.y, self.bg),
         Lightning_Book(self.x, self.y, self.bg),
         Coin(self.x, self.y, self.bg),
         Coin(self.x, self.y, self.bg),
         Coin(self.x, self.y, self.bg),
         Coin(self.x, self.y, self.bg)
     ]
Ejemplo n.º 29
0
 def list_risk_factors(self):
     table = self.get_table("RiskFactor")
     proj = "Ticker,#FactorName,T,FactorType,MaxDate"
     res = table.scan(ProjectionExpression=proj,
                      ExpressionAttributeNames={"#FactorName": "Name"})
     if 'Items' in res:
         return [
             Coin(OwnerId='Coin-AI', Data=item) for item in res['Items']
         ]
     return []
Ejemplo n.º 30
0
    def __init__(self):

        self.player = Player()  # игрок
        self.coin = Coin()  # монетка
        self.aim = Aim()  # прицел
        self.generator_obstacles = None  # генератор смертельных ячеек
        self.level_editor = None  # редактор уровня
        self.enemy = Enemy()  # враг

        self.win = None  # окно
        self._image_surf = None
        self.screen_size = 500  # размер экрана (квадратный)
        self.obst_size = None  # размер смертельной ячейки
        self.obst_list = []  # список координат смертельных ячеек
        self.free_rects = []  # координаты свободных клеток
        self.shuffle = None  # отступ по краям карты
        self.dot = None  # координаты точки прицела
        self.clock = pygame.time.Clock()
        self.time_counter = 0  # секундомер для смены смертельных ячеек
        self.myfont = None  # шрифт
        self.textsurface = None
        self.seconds_count = None  # секундомер для сбора очков
        self.weapon = 1  # начальное оружие 1 - для сбора очков, -1 для стрельбы
        self.bullet_list = []  # списко пуль
        self.heart_image = None
        self.gameover_image = None
        self.congratulations_image = None
        self.win_image = None
        self.volume_images = None
        self.tips = ()  # список картинок подсказок
        self.tip_index = 0  # индекс текущей подсказки

        self._running = True   # флаг заппуска приложения
        self.intro = True  # сцена меню
        self.gameover = False  # сцена "конец игры"
        self.editor = False  # сцена редактора
        self.timer_On = False  # флаг для начала отсчета времени сбора
        self.random_generate = False  # рандомная генерация смертельных ячеек
        self.is_up_pressed = False  # флаг для плавной смены оружия
        self.stop_click = False  # запрет клика в меню
        self.islevel_complete = False
        self.iswin = False
        self.istips = False
Ejemplo n.º 31
0
    if not enemy_exists:
        enemy_x = random.randint(0, width)
        enemy_y = random.randint(0, height)
        enemy = Enemy(os.path.join('assets', 'bear.png'), enemy_x, enemy_y, 150, 150, width, height)
        enemy_group.add(enemy)
        enemy_exists = True

    #if no coin exists, create one with random x and y position
    if not coin_exists:
        random.seed()
        coin_x = random.randint(0, width)
        coin_y = random.randint(0, height)
        coin_num = random.randint(1, 10)
        coin_exists = True
        if coin_num == 10:
            phil = Coin(os.path.join('assets', 'phil.png'), coin_x, coin_y)
            coin_group.add(phil)
            phil.tsang = True
        elif coin_num == 9:
            regi = Enemy(os.path.join('assets', 'regi.png'), coin_x, coin_y, 200, 200, width, height)
            bonus_group.add(regi)
        else:
            coin = Coin(os.path.join('assets', 'coin{}.png'.format(str(coin_num))), coin_x, coin_y)
            coin_group.add(coin)
            coin.tsang = False


    #check for coin hits
    coin_hits = pygame.sprite.spritecollide(sam, coin_group, True)
    for coin in coin_hits:
        #play sound and add 10 to score for every hit, change boolean to tell game to create new coin