コード例 #1
0
 def __init__(self, bot):
     self.bot = bot  # The bot object.
     self.database = database.Database(self.bot)  # database object -> used to update and get coin amount
     self.blackjack_players = []
     self.blackjack_game_status = 0
     self.deck = []
     self.coins = Coin(bot)
     self.dealerCards = []
コード例 #2
0
 def fill_register(self):
     """Method will fill SodaMachine's register with certain amounts of each coin when called."""
     for index in range(8):
         self.register.append(coins.Quarter())
     for index in range(10):
         self.register.append(Coin.Dime())
     for index in range(20):
         self.register.append(Coin.Nickel())
     for index in range(50):
         self.register.append(Coin.Penny())
コード例 #3
0
 def fill_wallet(self):
     """Method will fill wallet's money list with certain amount of each type of coin when called."""
     for index in range(8):
         self.money.append(Coin.Quarter())
     for index in range(10):
         self.money.append(Coin.Dime())
     for index in range(20):
         self.money.append(Coin.Nickel())
     for index in range(50):
         self.money.append(Coin.Penny())
コード例 #4
0
ファイル: lottery.py プロジェクト: Rettend/BuffBot
 def __init__(self, bot):
     self.bot = bot
     self.database = database.Database(self.bot)
     self.coins = Coin(bot)
     # self.lotteryTickets = {} // Different implementation
     self.ticketCost = 100
     self.winningTicket = 0
     self.ticketCounter = 0
     self.prizePool = 0
     self.generate_tickets(100)
コード例 #5
0
 def post(self):
     coin_name = self.request.get('name')
     coin_buy = self.request.get('buy')
     coin_noise = self.request.get('noise')
     coin_volatility = self.request.get('volatility')
     coin = Coin(name=coin_name,
                 buy=int(coin_buy),
                 noise=float(coin_noise),
                 volatility=float(coin_volatility),
                 units=0.01)
     coin.put()
     self.redirect('/')
コード例 #6
0
 def get(self):
     coins = Coin.query().order(-Coin.date).fetch(len(coinKeys))
     template_values = {
         'coins': coins,
     }
     template = JINJA_ENVIRONMENT.get_template('index.html')
     self.response.write(template.render(template_values))
コード例 #7
0
 def getEnableCoins(self):
     coins = Coin.query().order(-Coin.date).fetch(len(coinKeys))
     enableCoins = 0
     for coin in coins:
         if coin.notice == True:
             enableCoins = enableCoins + 1
     enableCoins = len(coins) - enableCoins
     logging.info(enableCoins)
     return enableCoins
コード例 #8
0
ファイル: coingroup.py プロジェクト: dev271/pacman
 def createCoinList(self, filename):
     layout = numpy.loadtxt(filename, dtype=str)
     col, row = layout.shape
     for i in range(row):
         for j in range(col):
             value = layout[j][i]
             if (value == 'X'):
                 pos = (i * self.radius, j * self.radius)
                 self.coinlist.append(Coin(self.radius, pos))
     return self.coinlist
コード例 #9
0
ファイル: game.py プロジェクト: Jai2500/The_Mandalorian
def spawn_coins(y):
    size = np.random.randint(4, 9, 2)
    size[0] = min(size[0], GROUND_SIZE[0] - y)
    coin_list = []
    global ObjNumber
    for i in range(size[0]):
        for j in range(size[1]):
            coin_list.append(
                GAMERULE.set_spawn_velo(
                    Coin([y + i, SCREEN_DIM[1] + j], ObjNumber)))
            ObjNumber += 1
    pawns[1] += coin_list
コード例 #10
0
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        coins = Coin.query().order(-Coin.date).fetch(len(coinKeys))

        for coin in coins:
            if coin.notice:
                site = noti_site + coin.name
                req = urllib2.Request(site, headers=hdr)
                body = json.load(urllib2.urlopen(req))
                obj = body
                msg = coin.name + " -> return:" + str(
                    (float(obj[dataKey][lastKey]) / float(coin.buy) - 1) *
                    100) + "%"
                #broadcase(msg)
                result = api.marketSell(coin.name, coin.units)
                logging.info(msg)
                sleep(15)

        for key in coinKeys:
            site = cal_site + key
            req = urllib2.Request(site, headers=hdr)
            obj = json.load(urllib2.urlopen(req))
            openValue = float(obj[dataKey][openKey])
            lastValue = float(obj[dataKey][lastKey])
            highValue = float(obj[dataKey][highKey])
            lowValue = float(obj[dataKey][lowKey])

            logging.info("key:" + key + ",last:" + str(lastValue))
            buy = lastValue + 0.5 * (highValue - lowValue)
            noise = 1 - math.fabs(openValue - lastValue) / (highValue -
                                                            lowValue)
            volatility = (highValue - lowValue) / lastValue * 100
            coin = Coin(name=key,
                        buy=int(buy),
                        noise=float(noise),
                        volatility=float(volatility),
                        units=0.01)
            coin.put()
コード例 #11
0
ファイル: receipts.py プロジェクト: antiface/CreditCoin
  def deserialize(self, l):
    self.sig=decode(l[0])
    self.pub=l[1]
    self.pub=loadPublic(self.pub)
    self.time=l[2]
    self.cmd=l[3]
    self.coin=Coin()
    self.coin.deserialize(l[4])

    if len(l)==6:
      if self.cmd=='create':
        self.args=l[5]
      else:
        self.args=loadPublic(l[5])
コード例 #12
0
    def get(self):
        urlfetch.set_default_fetch_deadline(60)
        coins = Coin.query().order(-Coin.date).fetch(len(coinKeys))
        for coin in coins:
            site = noti_site + coin.name
            req = urllib2.Request(site, headers=hdr)
            obj = json.load(urllib2.urlopen(req))

            if int(obj[dataKey][lastKey]) > coin.buy and coin.notice == False:
                noise_coins = Coin.query(
                    Coin.name == str(coin.name)).order(-Coin.date).fetch(30)
                noise = 0.0
                for noise_coin in noise_coins:
                    noise = noise + noise_coin.noise
                msg = "Buy:" + coin.name + ", Price:" + str(
                    coin.buy) + ", Noise:" + str(noise / len(noise_coins))
                enableCoins = self.getEnableCoins()
                units = api.selectUnits(coin.name, coin.volatility,
                                        enableCoins)
                coin.units = api.marketBuy(coin.name, units)
                coin.notice = True
                coin.put()
                logging.info(msg)
コード例 #13
0
async def on_ready():
    print('Logged in as')
    print('------')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

    tax = Tax(bot)
    tax_task = asyncio.ensure_future(tax.wealth_tax())

    coins = Coin(bot)
    await coins.give_coin()

    await tax_task
コード例 #14
0
ファイル: lottery.py プロジェクト: Rettend/BuffBot
class Lottery:
    def __init__(self, bot):
        self.bot = bot
        self.database = database.Database(self.bot)
        self.coins = Coin(bot)
        # self.lotteryTickets = {} // Different implementation
        self.ticketCost = 100
        self.winningTicket = 0
        self.ticketCounter = 0
        self.prizePool = 0
        self.generate_tickets(100)

    @commands.command(
        name="buyticket",
        pass_context=True,
        help="Buy tickets for 100 coins for a chance to win loyal guns")
    async def buy_ticket(self, ctx):
        user = ctx.message.author
        if not self.coins.check_balance(user, self.ticketCost):
            await self.bot.say((
                "{}, You don't have enough coins to buy a ticket \n - Current balance: "
                + str(self.database.get_coins(user.id))).format(user.mention))
        else:
            self.database.remove_coins(user.id, self.ticketCost, user.mention)
            if self.ticketCounter == self.winningTicket:
                self.generate_tickets(100)
                self.database.insert_coins(user.id, self.prizePool,
                                           user.mention)
                await self.bot.say((
                    "{}, Congratulations, you won the lottery with a prizepool of "
                    + str(self.prizePool) + "\n- Current balance: " +
                    str(self.database.get_coins(user.id))).format(user.mention)
                                   )
            else:
                self.ticketCounter += 1
                await self.bot.say(
                    ("{}, You lost, better luck next time!" +
                     "\n - Current balance: " +
                     str(self.database.get_coins(user.id))).format(
                         user.mention))

    # Creates a new winning number, while resetting the counter, were the nr_of_tickets represents the odds of winning
    def generate_tickets(self, nr_of_tickets):
        self.ticketCounter = 1
        self.prizePool = nr_of_tickets * int(self.ticketCost * 0.9) / 2
        self.winningTicket = random.randint(1, nr_of_tickets)
コード例 #15
0
 def check_hit(self, other):
     # checks if the block has been hit
     if not self.state['blank'] or self.allow_hits:
         hit = False
         if self.rect.collidepoint(other.rect.midtop):
             hit = True
         if hit:  # leave other parameter as None to force hit state (for testing)
             other.rect.y = self.rect.bottom
             other.y_vel = 7
             if not self.state['meta'] == CoinBlock.HIT_STATE:
                 self.state['meta'] = CoinBlock.HIT_STATE
                 self.state['move-state'] = CoinBlock.MOVE_UP_STATE
             if self.coin_counter > 0:
                 self.coin_counter -= 1  # deduct coin counter
                 x_pos = self.rect.left + int(self.rect.width * 0.25)
                 n_coin = Coin(
                     x_pos, 0, self.screen
                 )  # create new coin and move it to above the block
                 n_coin.rect.bottom = self.item_location
                 self.coins.append([n_coin, self.speed * 2
                                    ])  # coin object, and speed
                 self.map_group.add(n_coin)
                 if not self.coin_counter > 0:
                     self.set_blank()
                 self.sound.play()
                 return n_coin.points
             elif self.rubble_group is not None and other.state_info['big']:
                 rubble_img = image.load(
                     'images/super-mario-bricks-rubble.png')
                 speeds = [(-15, 5), (-10, 5), (10, 5), (15, 5)]
                 for speed in speeds:
                     rubble = BlockRubble(self.rect.x, self.rect.y,
                                          rubble_img, speed[0], speed[1],
                                          self.screen)
                     self.rubble_group.add(rubble)
                     self.map_group.add(rubble)
                 self.break_sound.play()
                 self.kill()
コード例 #16
0
 def init_game_objects(self):
     # creates the game objects
     self.game_objects = {
         'floors': [],
         'blocks': pygame.sprite.Group(),
         'q_blocks': pygame.sprite.Group(),
         'rubble': pygame.sprite.Group(),
         'coins': pygame.sprite.Group(),
         'pipes': pygame.sprite.Group(),
         'collide_objs': pygame.sprite.Group(
         ),  # for checking collisions with all collide-able objects
         'flag': pygame.sprite.Group(),
         'items': pygame.sprite.Group(),
         'koopa': pygame.sprite.Group(),
         'goomba': pygame.sprite.Group(),
         'win-zone': []
     }
     floor_data = self.retrieve_map_data('walls')
     block_data = self.retrieve_map_data('blocks')
     q_block_data = self.retrieve_map_data('q-blocks')
     pipe_data = self.retrieve_map_data('pipes')
     coin_data = self.retrieve_map_data('coins')
     flag_data = self.retrieve_map_data('flag')
     background = self.retrieve_map_data('decorations')
     for obj in floor_data:  # walls represented as pygame Rects
         self.game_objects['floors'].append(
             pygame.Rect(obj.x, obj.y, obj.width, obj.height))
     for block in block_data:
         if not block.properties.get('pipe', False):
             b_sprite = CoinBlock.coin_block_from_tmx_obj(
                 block, self.screen, self.map_group, self.game_objects)
         else:
             b_sprite = Block(block.x, block.y, block.image, self.screen)
         self.map_group.add(b_sprite)  # draw using this group
         self.game_objects['blocks'].add(
             b_sprite)  # check collisions using this group
         self.game_objects['collide_objs'].add(b_sprite)
     for q_block in q_block_data:
         q_sprite = QuestionBlock.q_block_from_tmx_obj(
             q_block, self.screen, self.map_group, self.game_objects)
         self.map_group.add(q_sprite)  # draw using this group
         self.game_objects['q_blocks'].add(
             q_sprite)  # check collisions using this group
         self.game_objects['collide_objs'].add(q_sprite)
     for coin in coin_data:
         c_sprite = Coin(coin.x, coin.y, self.screen)
         self.map_group.add(c_sprite)
         self.game_objects['coins'].add(c_sprite)
     for pipe in pipe_data:
         p_sprite = Pipe.pipe_from_tmx_obj(pipe, self.screen)
         self.map_group.add(p_sprite)  # draw using this group
         self.game_objects['pipes'].add(
             p_sprite)  # check collisions using this group
         self.game_objects['collide_objs'].add(p_sprite)
     for flag_part in flag_data:
         if flag_part.image:
             f_sprite = Block(flag_part.x, flag_part.y, flag_part.image,
                              self.screen)
             self.map_group.add(f_sprite)  # draw using this group
             self.game_objects['flag'].add(
                 f_sprite)  # check collisions using this group
         else:
             self.game_objects['win-zone'].append(
                 pygame.Rect(flag_part.x, flag_part.y, flag_part.width,
                             flag_part.height))
     for bg in background:
         self.map_group.add(Decoration(bg.x, bg.y, bg.image))
コード例 #17
0
                beam.place(board.matrix, m1, m2, i, 0, l, 2)
        elif f == 3:
            if i == 0 or i == l - 1:
                beamhead.place(board.matrix, m1, m2, i, -i, l, l + 1)
            else:
                beam.place(board.matrix, m1, m2, i, -i, l, l + 1)
    l1 = l + l1 + 20
speed = Speed()
speed.loadObstacle('speed_up')
l1 = 0
for i in range(5):
    m1 = random.randint(1, 33)
    m2 = random.randint(20 + l1, 80 + l1 + 10)
    speed.place(board.matrix, m1, m2)
    l1 = 5 + l1 + 50
coin = Coin()
coin.loadObstacle('coin')
for i in range(7):
    c1 = random.randint(2, 5)
    c2 = random.randint(3, 8)
    x = random.randint(1, 33)
    y = random.randint(30 + i * 20, 240 + i * 20)
    for j in range(c1):
        for k in range(c2):
            coin.place(board.matrix, x + j, y + k)
magnet = Magnet()
magnet.loadObstacle('magnet')
x1 = 20
x2 = 200
magnet.place(board.matrix, x1, x2)
mando = Mando()
コード例 #18
0
ファイル: main.py プロジェクト: SartakPeriwal/Jetpack-Joyride
from firebeam import Firebeam
from magnet import Magnet
from dragon import Dragon
from time import time
from bullet import Bullet
from random import randint
screen = Board(40, 10000)
man = Mando(35, 3)
man.place(screen)

drag = Dragon(30, 500)
drag.place(screen)
for i in range(40):
    x = randint(5, 30)
    y = randint(25, 450)
    coin_p = Coin(x, y)
    coin_p.place(screen)

for j in range(10, 30):
    x = randint(5, 30)
    y = randint(50, 350)
    beam = Firebeam(x, y)
    beam.place(screen)

mag = Magnet(2, 80)
mag.place(screen)

counter3 = time()
screen.print_board(0, man, drag)
#print("time left==")
#print(100-counter3)
コード例 #19
0
def main():

    # start pygame
    pygame.init()

    # pygame font
    pygame.font.init()
    font = pygame.font.Font(None, constants.SCORE_FONT_SIZE)

    # screen size
    screen = pygame.display.set_mode(constants.size)

    # background setup
    background_image = pygame.image.load(constants.WORLD).convert()
    bg_image_rect = background_image.get_rect()
    background_image = pygame.transform.scale(
        background_image,
        (int(bg_image_rect.width * constants.WORLD_MULTIPLIER),
         int(bg_image_rect.height * constants.WORLD_MULTIPLIER)))
    bg_image_rect = background_image.get_rect()  # after expanding

    # water splash
    WaterSplash = pygame.image.load(constants.WATER_SPLASH).convert()
    ws_image_rect = WaterSplash.get_rect()

    # game name
    pygame.display.set_caption(constants.GAME_NAME)

    # player
    player = Player()

    # enemy
    enemy_sprite_list = pygame.sprite.Group()
    enemy = Enemy(int(random.randint(400, 800)), 50)

    # coins
    coin_sprite_list = pygame.sprite.Group()
    coin = Coin(int(random.randint(400, 800)), 50)
    coin_score = 0

    # wave
    wave_sprite_list = pygame.sprite.Group()
    wave = Wave(constants.GROUND_HEIGHT, constants.SCREEN_WIDTH)

    # complete sprite list group
    all_sprite_list = pygame.sprite.Group()
    all_sprite_list.add(player)  # add player
    #all_sprite_list.add(enemy)			# add enemy

    # is done constant
    done = False

    # clock
    clock = pygame.time.Clock()

    # camera
    camera_x = 0
    camera_y = 0
    """
	move_x = -1 * constants.PLAYER_START_POS
	temp_x = 0
	L = constants.SCREEN_WIDTH / 2
	R = bg_image_rect.right - L
	"""
    # other constants
    prev_camera_x = camera_x

    # start times
    start_time_bomb = time.time()
    start_time_coin = time.time()
    start_time_wave = time.time()

    # -- Main Program Loop --
    while not done:

        # events
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if done:
                break

            # till key is pressed
            if event.type == pygame.KEYDOWN:
                #if event.key == pygame.K_LEFT:
                #	player.MoveLeft()
                if event.key == pygame.K_RIGHT:
                    player.MoveRight()
                if event.key == pygame.K_UP:
                    player.jump()

            # if key is taken
            if event.type == pygame.KEYUP:
                #if event.key == pygame.K_LEFT and player.change_x < 0:
                #	player.stop()
                if event.key == pygame.K_RIGHT and player.change_x > 0:
                    player.stop()

        # calculating player state
        if player.change_x > 0:
            player.state = 'r'
        elif player.change_x < 0:
            player.state = 'l'
        else:
            player.state = 's'

        # infinite scrolling window created
        if abs(camera_x) > constants.SCREEN_WIDTH / 2:  # end of viewport
            player.end_of_viewport = 0
            rel_x = (camera_x +
                     (constants.SCREEN_WIDTH / 2)) % bg_image_rect.width
            screen.blit(background_image,
                        [rel_x - bg_image_rect.width, camera_y])
            if rel_x < constants.SCREEN_WIDTH:
                screen.blit(background_image, [rel_x, camera_y])
            if player.sstop == 0:  # if screen moves
                camera_x += -1 * player.change_x
        else:
            player.end_of_viewport = 1
            screen.blit(background_image, [0, camera_y])
            if player.sstop == 0:  # if screen moves
                camera_x += -1 * player.change_x

        if abs(camera_x) > 0:  # game starts
            # for bombs
            if time.time() - start_time_bomb >= 6.5:
                start_time_bomb = time.time()
                rn = int(random.randint(300, 800))
                enemy = Enemy(rn, 50)
                enemy_sprite_list.add(enemy)

            # for coins
            if time.time() - start_time_coin >= 2.0:
                start_time_coin = time.time()
                rn = int(random.randint(400, 800))
                coin = Coin(rn, 350)
                coin_sprite_list.add(coin)

            # for waves
            if time.time() - start_time_wave >= 5.0:
                start_time_wave = time.time()
                wave = Wave(constants.SCREEN_WIDTH,
                            constants.GROUND_HEIGHT - 65)
                wave_sprite_list.add(wave)

        # update every sprite list
        all_sprite_list.update()
        enemy_sprite_list.update(player.state, player.end_of_viewport,
                                 player.sstop)
        coin_sprite_list.update(player.state, player.end_of_viewport,
                                player.sstop)
        wave_sprite_list.update(player.state, player.end_of_viewport,
                                player.sstop)

        # if bombs off screen - remove
        for enemies in enemy_sprite_list:
            if enemies.rect.y > constants.SCREEN_HEIGHT:
                enemy_sprite_list.remove(enemies)

        # if coins off screen - remove
        for coins in coin_sprite_list:
            if coins.rect.x < 0:
                coin_sprite_list.remove(coins)

        # if waves of screen remove
        for waves in wave_sprite_list:
            if waves.rect.x < 0:
                wave_sprite_list.remove(waves)

        # bombs and player collision detection
        if len(enemy_sprite_list) > 0:
            bullet_hit_list = pygame.sprite.spritecollide(
                player, enemy_sprite_list, True)
            if len(bullet_hit_list) > 0:
                break

        # coins and player collision
        if len(coin_sprite_list) > 0:
            coin_hit_list = pygame.sprite.spritecollide(
                player, coin_sprite_list, True)
            coin_score += len(coin_hit_list)

        # waves and player collsion
        if len(wave_sprite_list) > 0:
            wave_hit_list = pygame.sprite.spritecollide(
                player, wave_sprite_list, False)
            if len(wave_hit_list) > 0:
                break

        # FILL SCREEN
        # blit score
        distance = font.render("Distance = " + str(abs(camera_x) / 10), True,
                               constants.RED, None)
        stars = font.render("Stars = " + str(coin_score), True, constants.RED,
                            None)
        screen.blit(distance, [0, 0])
        screen.blit(stars, [0, 20])

        # blit water splash if and only if he is steady and moving
        if player.pos_state == 's' and player.change_x > 0:
            ws_image_rect.right = player.rect.left - (player.rect.width / 2)
            ws_image_rect.bottom = player.rect.bottom - (player.rect.height /
                                                         2)
            screen.blit(WaterSplash,
                        [ws_image_rect.right, ws_image_rect.bottom])

        # draw everthing
        all_sprite_list.draw(screen)
        player.block_sprite_list.draw(screen)
        enemy_sprite_list.draw(screen)
        coin_sprite_list.draw(screen)
        wave_sprite_list.draw(screen)

        # fps
        clock.tick(60)

        # update screen
        pygame.display.flip()

    # exit pygame
    pygame.quit()
コード例 #20
0
ファイル: game.py プロジェクト: vasu0403/Jetpack-Joyride
        fire_beams.append(
            Beam(start_pos_i2, start_pos_j2, length2, orientation2,
                 game_board.grid, beam_num))
        beam_num = beam_num + 1
for i in range(65, columns - 181, 70):  # adding coins, speed boost and magnets
    random.shuffle(Random_object)
    random.shuffle(Random_object_row)
    object_type = Random_object[0]
    object_middle_row = Random_object_row[
        0]  # containes the middle row of object to placed on board

    if object_type == 1:  # object_type 1 is for coins
        for j in range(-2, 3):
            for k in range(5):
                if is_coin[j + 2][k] == 1:
                    game_board.grid[object_middle_row + j][i + k] = Coin()

    elif object_type == 2:  # object_type 2 is for spped boost
        speedBoosts.append(
            SpeedBoost(object_middle_row, i, game_board.grid, speedBoost_num))
        speedBoost_num += 1

    elif object_type == 3:
        Magnet(object_middle_row, i, game_board.grid)
prev_ice_ball_shoot = time.time()
while True:
    char = user_input()
    cur_time = time.time()
    if cur_time - prev_time_left >= 1:
        time_left -= 1
        prev_time_left = cur_time
コード例 #21
0
ファイル: receipts.py プロジェクト: antiface/CreditCoin
class Receipt:
  def __init__(self, sig=None, pub=None, time=None, cmd=None, coin=None, args=None):
    print('Receipt: '+str(pub))
    self.sig=sig
    self.pub=pub
    self.time=time
    self.cmd=cmd
    self.coin=coin
    self.args=args

    if self.sig:
      h=hashlib.sha1()
      h.update(self.serialize(saveSig=True, jsonify=True))
      self.id=base64.b32encode(h.digest())

    self.priv=None

  def load(self, filename):
    f=open(filename, 'rb')
    l=json.loads(f.read())
    f.close()
    self.deserialize(l)

    h=hashlib.sha1()
    h.update(self.serialize(saveSig=True, jsonify=True))
    self.id=base64.b32encode(h.digest())

  def deserialize(self, l):
    self.sig=decode(l[0])
    self.pub=l[1]
    self.pub=loadPublic(self.pub)
    self.time=l[2]
    self.cmd=l[3]
    self.coin=Coin()
    self.coin.deserialize(l[4])

    if len(l)==6:
      if self.cmd=='create':
        self.args=l[5]
      else:
        self.args=loadPublic(l[5])

  def save(self, filename, saveSig):
    f=open(filename, 'wb')
    f.write(self.serialize(saveSig=saveSig, jsonify=True))

  def serialize(self, saveSig=False, jsonify=False):
    if self.args:
      if type(self.args)==unicode:
        msg=[encode(self.pub.save_pkcs1('DER')), self.time, self.cmd, self.coin.serialize(jsonify=False), self.args]
      else:
        msg=[encode(self.pub.save_pkcs1('DER')), self.time, self.cmd, self.coin.serialize(jsonify=False), encode(self.args.save_pkcs1('DER'))]
    else:
      msg=[encode(self.pub.save_pkcs1('DER')), self.time, self.cmd, self.coin.serialize(jsonify=False)]

    if saveSig:
      msg=[encode(self.sig)]+msg

    if jsonify:
      return json.dumps(msg)
    else:
      return msg

  def setPrivate(self, priv):
    self.priv=priv

  def sign(self):
    if self.priv:
      print('Signing')
      self.sig=rsa.sign(self.serialize(saveSig=False, jsonify=True), self.priv, 'SHA-1')

      h=hashlib.sha1()
      h.update(self.serialize(saveSig=True, jsonify=True))
      self.id=base64.b32encode(h.digest())
    else:
      print('No private key')

  def verify(self):
#    if rsa.verify(self.serialize(saveSig=False, jsonify=True), str(self.sig), self.pub):
#      return True
#    else:
#      return False
    return True
コード例 #22
0
ファイル: poll_coins.py プロジェクト: skwongg/coins
from cassandra.cluster import Cluster
from cassandra.cqlengine import connection
from cassandra.cqlengine.management import sync_table
from coins import Coin
CQLENG_ALLOW_SCHEMA_MANAGEMENT='CQLENG_ALLOW_SCHEMA_MANAGEMENT'

cluster=Cluster()
connection.setup(['127.0.0.1'], "cassy", protocol_version=3)

class CoinPrice
a = Coin()




##Cassandra coin model syncs to default cassandra connection under cassy keyspace.
##row key for time series data  https://academy.datastax.com/resources/getting-started-time-series-data-modeling

#row partitioning:
# In some cases, the amount of data gathered for a single device isn’t practical to fit onto a single row. Cassandra can store up to 2 billion columns per row, but if we’re storing data every millisecond you wouldn’t even get a month’s worth of data. The solution is to use a pattern called row partitioning by adding data to the row key to limit the amount of columns you get per device. Using data already available in the event, we can use the date portion of the timestamp and add that to the weather station id. This will give us a row per day, per weather station, and an easy way to find the data. (figure 2)


# day = datetime.date.today().strftime('%m-%d-%Y')
# name = "XRP"
# ticker="XRPUSD"
# pair="XRPUSD"
# icon_url="https://www.google.com"
# price="0.8934"
# price=0.8934
# btc_price=0.00001
# created_at=datetime.datetime.now()
コード例 #23
0
ファイル: holdem.py プロジェクト: Rettend/BuffBot
    def __init__(self, bot):
        self.bot = bot
        self.database = database.Database(self.bot)
        self.holdem_players = []
        self.game_status = 0
        self.deck = []
        self.dealersHand = []
        self.coins = Coin(bot)

        # TODO: Command: holdem new, join, start, Call, raise, fold
        # TODO: Gather players

        @commands.group(name="holdem", pass_context=True)
        async def holdem(self, ctx):
            if ctx.invoked_subcommand is None:
                await self.bot.say(
                    "This is not a valid command, please add a subcommand")

        @holdem.command(name="new", pass_context=True)
        async def new_game(self, ctx):
            if self.game_status != 0:
                self.bot.say("A game is already running, please wait to join")
                return None,
            self.deck = self.generateDeck()
            self.game_status = 1
            welcome_msg =   "_______                   _    _       _     _\n" \
                          " |__   __|                 | |  | |     | |   | |               \n" \
                          "    | | _____  ____ _ ___  | |__| | ___ | | __| | ___ _ __ ___  \n" \
                          "    | |/ _ \ \/ / _` / __| |  __  |/ _ \| |/ _` |/ _ | '_ ` _ \ \n" \
                          "    | |  __/>  | (_| \__ \ | |  | | (_) | | (_| |  __| | | | | |\n" \
                          "    |_|\___/_/\_\__,_|___/ |_|  |_|\___/|_|\__,_|\___|_| |_| |_|\n"
            await self.bot.say(
                welcome_msg, "A Texas Hold'em table has opened"
                "Please use !holdem join <Blind> to join the table")

        @holdem.command(name="join", pass_context=True)
        async def join_game(self, ctx, bet):
            user = ctx.message.author
            if self.game_status != 1:
                await self.bot.say(
                    "No tables are open, please open one to play")
                return None

            if self.players_at_table(ctx.message.author):
                await self.bot.say(user.mention +
                                   "You're seated and ready to play")
                return None

            if float(bet) <= 0 and not self.coins.check_balance(bet):
                await self.bot.say(user.mention +
                                   " please make sure your bet is higher"
                                   "than 0 and that you've got enough coins")
                return None

            self.database.remove_coins(userid=user.id,
                                       coins=float(bet),
                                       mention=user.mention)

            # TODO : Make drawcard Dynamic
            self.holdem_players.append({
                "user":
                user,
                "cards": [self.drawCard(), self.drawCard()],
                "bet":
                float(bet),
                "Status":
                0
            })

            await self.bot.say(
                user.mention +
                " You've joined the table, please wait for the game to start,")

        @holdem.command(name="start", pass_context=True)
        async def start_game(self, ctx):

            if len(self.holdem_players) < 2:
                await self.bot.say(
                    "There needs to be at least 2 players at the table")
                return None
            # TODO: Solve this when you use the join command
            elif len(self.holdem_players) > 9:
                await self.bot.say("There are too many people at the table")
                return None

            self.game_status = 3
            self.dealersHand = [self.drawCard(), self.drawCard()]

            start_msg = "Let's play Texas Hold'em!"
            await self.bot.say(start_msg)

            for player in self.holdem_players:
                self.bot.send_message(
                    player["user"], "This is your hand: " +
                    player['cards'][0].getStringSymbol() +
                    player['cards'][0].getStringValue())
                pass

            community_cards_msg = "Here are the community cards: " + \
                         self.dealerCards[0].getStringSymbol() + self.dealerCards[0].getStringValue()
            await self.bot.say(community_cards_msg)

        @holdem.command(name="Call", pass_context=True)
        async def holdem_call(self, ctx):
            player = self.players_at_table(ctx.message.author)
            if player is None:
                await self.bot.say("You're not at this table, " +
                                   ctx.message.author.mention)
                return None

            if player["status"] != 0:
                await self.bot.say(ctx.message.author.mention +
                                   " is calling the bet")
                return None
            pass

        @holdem.command(name="raise", pass_context=True)
        async def holdem_stand(self, ctx, bet_raise):
            player = self.players_at_table(ctx.message.author)
            if player is None:
                await self.bot.say("You're not at this table, " +
                                   ctx.message.author.mention)
                return None

            if bet_raise <= 0 or None:
                await self.bot.say(ctx.message.author.mention +
                                   "You need to specify a bet")
                return None

            for player in self.players_at_table:
                if player["name"] == player:
                    player["bet"] += bet_raise

            await self.bot.say(ctx.message.author.mention + " Raised the bet")
コード例 #24
0
 if container.TIME_REMAINING <= 0:
     container.exit_sequence(False)
 # Update and Render
 TIMESTEP += 1
 FRAME.broadcast_timestep(OBJECTS)
 FRAME.broadcast_timestep([SPEEDUP, SHIELD])
 FRAME.broadcast_render(OBJECTS)
 osmanager.clrscr()
 # Spawn and Process coins
 FRAME.broadcast_timestep(COINS)
 FRAME.broadcast_render(COINS)
 for coin in COINS:
     if not coin.delete_me and coin.detect_collision(PLAYER):
         coin.delete_me = True
         container.SCORE += 1
 COINS = COINS + Coin.spawn(0.05)
 # Render the Frame
 FRAME.render()
 # Initialize the new FireBeams and Collision Detect
 if TIMESTEP < container.ENDGAME_TIME:
     NEW_FIREBEAM = FireBeam.spawn()
     if NEW_FIREBEAM is not False:
         OBJECTS.append(NEW_FIREBEAM)
 if TIMESTEP > PLAYER.last_died + 4 and not container.SHEILD_UP:
     for obj in OBJECTS:
         if isinstance(obj, FireBeam) and obj.detect_collision(PLAYER):
             FRAME.player_die()
             PLAYER.last_died = TIMESTEP
 # Initialize the Boss Enemy and Our Dragon
 if TIMESTEP == container.ENDGAME_TIME + container.DROGON_DELAY:
     DROGON = Drogon()
コード例 #25
0
class Gamble:
    def __init__(self, bot):
        self.bot = bot  # The bot object.
        self.database = database.Database(self.bot)  # database object -> used to update and get coin amount
        self.blackjack_players = []
        self.blackjack_game_status = 0
        self.deck = []
        self.coins = Coin(bot)
        self.dealerCards = []


    @commands.group(name="bj", pass_context=True)
    async def bj (self, ctx) :
        if ctx.invoked_subcommand is None:
            await self.bot.say('Invalid rungame command passed...')

    @bj.command(name="new", pass_context=True)
    async def new_blackjack_game(self, ctx):
        if not global_methods.is_admin(ctx.message.author):
            await self.bot.say("You're not a big boy")
            return None
        if self.blackjack_game_status != 0:
            self.bot.say("A game is already in place.. wait until it is finished.")
            return None,

        self.deck = self.generateCards()
        self.blackjack_game_status = 1
        await self.bot.say("A blackjack table have now opened.. "
                           "please do ``` !bj join <bet> ``` to join the table.")

    @bj.command(name="join", pass_context=True)
    async def join_blackjack_game(self, ctx, bet):
        user = ctx.message.author
        if self.blackjack_game_status != 1:
            await self.bot.say("No table is open for the moment..")
            return None

        if self.player_in_blackjack_table(ctx.message.author) :
            await self.bot.say(
                "{}, You're in here, buddy!.".format(user.mention))
            return None

        if float(bet) <= 0 and not self.coins.check_balance(bet):
            await self.bot.say(
                "{}, please make sure your bet is higher than 0 and you've enough coins.".format(user.mention))
            return None

        self.database.remove_coins(userid=user.id, coins=float(bet), mention=user.mention)

        self.blackjack_players.append({
            "user": user, "cards": [self.drawCard(), self.drawCard()], "bet": float(bet), "status": 0
        })

        await self.bot.say(
            "{}, you've joined the table.. please wait for a host to start the round".format(user.mention))

    @bj.command(name="start", pass_context=True)
    async def start_blackjack_table(self, ctx):
        if not global_methods.is_admin(ctx.message.author):
            await self.bot.say("You're not a big boy")
            return None
        self.blackjack_game_status = 3;
        self.dealerCards = [self.drawCard(), self.drawCard()]
        output = "Welcome to the blackjack room!!! \n"
        output += "Dealers card shown to you fellows is {}\n".format(
            self.dealerCards[0].getStringSymbol() + self.dealerCards[0].getStringValue())
        output += "====================================================\n"
        for player in self.blackjack_players:
            output += "{} has these cards: {}. That's a total score of {}\n" \
                .format(player['user'].mention,
                        player['cards'][0].getStringSymbol() + player['cards'][0].getStringValue()
                        + " " + player['cards'][1].getStringSymbol() + player['cards'][1].getStringValue(),
                        self.blackjack_calculate_card_values(player['cards']))
            pass

        await self.bot.say(output)
        pass

    @bj.command(name = "hit", pass_context=True)
    async def blackjack_hit(self, ctx):
        player = self.player_in_blackjack_table(ctx.message.author)
        if player == None:
            await self.bot.say("{}, you're currently not in a game..".format(ctx.message.author.mention))
            return None

        if player['status'] != 0 :
            await self.bot.say("{}, you're standing..".format(ctx.message.author.mention))
            return None

        player['cards'].append(self.drawCard())
        output = "{}, you're selected hit.. \n".format(ctx.message.author.mention)

        cards = ""
        for card in player['cards'] : cards += card.getStringSymbol() + card.getStringValue()
        output += "{}, you've these cards: {}. That's a total score of {}\n" \
            .format(player['user'].mention, cards,
                    self.blackjack_calculate_card_values(player['cards']))

        if self.blackjack_calculate_card_values(player['cards']) >= 21:
            player['status'] = 1
            if self.blackjack_is_every_one_standing():
                await self.blackjack_calculate_winner()

        await self.bot.say(output)

    @bj.command(name="stand", pass_context=True)
    async def blackjack_stand(self, ctx):
        player = self.player_in_blackjack_table(ctx.message.author)
        if player == None:
            await self.bot.say("{}, you're currently not in a game..".format(ctx.message.author.mention))
            return None

        if player['status'] != 0:
            await self.bot.say("{}, you're standing..".format(ctx.message.author.mention))
            return None
        pass

        player['status'] = 1
        await self.bot.say("{}, you're standing..".format(ctx.message.author.mention))

        if self.blackjack_is_every_one_standing():
            await self.blackjack_calculate_winner()

    @bj.command(name="forceStand", pass_context=True)
    async def blackjack_force_stand(self, ctx) :
        if not global_methods.is_admin(ctx.message.author):
            await self.bot.say("You're not a big boy")
            return None
        for player in self.blackjack_players :
            player['status'] = 1

        await self.blackjack_calculate_winner()

    async def blackjack_calculate_winner(self):

        while self.blackjack_calculate_card_values(self.dealerCards) <= 17:
            self.dealerCards.append(self.drawCard())

        dealer_score = self.blackjack_calculate_card_values(self.dealerCards)
        dealer_cards = ""
        for card in self.dealerCards: dealer_cards += card.getStringSymbol() + card.getStringValue()
        output = "====================================================\n"
        output += "                                        ~WINNERS AND LOSERS~ \n"
        output += "Dealer got these cards: {}, that's a total score of {}\n".format(dealer_cards, dealer_score)

        for player in self.blackjack_players :
            player_score = self.blackjack_calculate_card_values(player['cards'])
            player_cards = ""
            for card in player['cards']: player_cards += card.getStringSymbol() + card.getStringValue()

            if dealer_score > 21 and player_score <= 21 or \
                dealer_score < 21 and player_score > dealer_score and player_score <= 21:
                output += "{} won over dealer with a score of {} with cards {} \n".format(
                    player['user'].mention, player_score, player_cards)
                if len(player['cards']) == 2 and player_score == 21 :
                    self.database.insert_coins(player['user'].id, player['bet'] * 3, player['user'].mention)
                else :
                    self.database.insert_coins(player['user'].id, player['bet'] * 2, player['user'].mention)

            elif dealer_score == player_score and dealer_score <= 21 :
                output += "{} draw with dealer with a score of {} with cards {} \n".format(
                    player['user'].mention, player_score, player_cards)

                self.database.insert_coins(player['user'].id, player['bet'], player['user'].mention)

            else :
                output += "{} lost against dealer with a score of {} with cards {} \n".format(
                    player['user'].mention, player_score, player_cards)

        self.blackjack_players = []
        self.dealerCards = []
        self.blackjack_game_status = 0
        output += "====================================================\n"
        await self.bot.say(output)



    def blackjack_is_every_one_standing(self):
        for player in self.blackjack_players :
            if player['status'] == 0: return False
        return True

    def player_in_blackjack_table(self, user):
        for player in self.blackjack_players :
            if player['user'] == user: return player
        return None

    def blackjack_calculate_card_values(self, cards:list):
        score = 0
        for card in cards :
            temp_score = score + card.getCardValue()
            if temp_score > 21 :
                if card.getCardValue() == 11 :
                    temp_score -= 10;
                else :
                    for c_temp in cards :
                        if c_temp.getCardValue() == 21 :
                            temp_score -= 10
                            if temp_score <= 21 : break

            score = temp_score

        return score

    def drawCard (self) :
        if not len(self.deck) > 0 :
            self.deck = self.generateCards()
        return self.deck.pop()


    def generateCards(self):
        '''
        Generate cards and then shuffle them
        @return shuffled deck
        '''
        cards = []  # The veriable that holds all the cards
        deck = 5  # How many deck that is created

        # create deck(s)
        for y in range(0, deck):
            symbol = 0  # deligere symbol
            value = 0  # Deligere value

            # Generate a deck of cards
            for x in range(0, 4):
                for i in range(0, 13):
                    obj = Card(symbol, value)
                    cards.append(obj)
                    value += 1
                symbol += 1
                value = 0

        # Shuffle the decks and return it
        return random.sample(cards, len(cards))