コード例 #1
0
ファイル: views.py プロジェクト: 42cc/django-wizard
def wizard_view(request, step):
    wizard = Wizard(
        'wizard',
        wizard_steps
    )
    wizard.set_step_init_args(request)
    return wizard.handle_request(request, step)
コード例 #2
0
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()

        self.settings = Settings()
        # Takes full screen or not
        if self.settings.full_screen:
            self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
            self.settings.screen_width = self.screen.get_rect().width
            self.settings.screen_height = self.screen.get_rect().height
        else:
            self.screen = pygame.display.set_mode(
                (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Ghosts Attack")

        # Variable for control time.
        self.clock = pygame.time.Clock()

        # Create an instance to store game statistics,
        # and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.wizard = Wizard(self)
        self.balls = pygame.sprite.Group()
        self.ghosts = pygame.sprite.Group()
        self._create_crowd()

        # Make the Play button.
        self.play_button = Button(self, "Play")
コード例 #3
0
ファイル: main.py プロジェクト: breakfastset/wizarding_world
def main():
    wizard1 = Wizard("Harry Potter", 12, 20, 1000)
    wizard2 = Wizard("Dumbledore", 75, 98, 200000)
    wizard3 = Wizard("Voldermort", 50, 99, 250000)

    print(wizard1)
    print(wizard2)
    print(wizard3)
コード例 #4
0
    def __init__(self):
        self.creatures = [
            Creature("Toad", 1),
            Creature("Frog", 3),
            Dragon("Dragon", 50),
            Creature("Lion", 10)
        ]

        self.wizard = Wizard('Gandolf', 30)
コード例 #5
0
    def __init__(self, config, screen):
        """Initialize the sprite list."""
        self.config = config
        self.screen = screen

        #initialize the sprites
        self.wiz = Wizard(config, self)
        self.monsters = Group()
        self.missiles = Group()
コード例 #6
0
ファイル: downloader.py プロジェクト: wardrich/ss-plex.bundle
    def __init__(self, endpoint, destination = None, limit = 0, strategy = 'curl', avoid_small_files = False):
        self.endpoint    = endpoint
        self.destination = destination
        self.success     = False
        self.limit       = limit
        self.wizard      = Wizard(self.endpoint)
        self.strategy    = strategy
        self.avoid_small = avoid_small_files

        self.init_callbacks()
コード例 #7
0
ファイル: test_wizard.py プロジェクト: dankoni88/Python
def test_apprentice_has_mentor():
    wizard_dict = WizardDictionary()
    arthur = Apprentice("Arthur", {Magic.gomancery, Magic.pyromancery})
    merlin = Wizard("Merlin",
                    {Magic.illusionism, Magic.mentalism, Magic.gomancery})
    gandalph = Wizard(
        "Gandalph", {Magic.illusionism, Magic.mentalism, Magic.psychomentrism})
    wizard_dict[merlin] = arthur
    with pytest.raises(ValueError):
        wizard_dict[gandalph] = arthur
コード例 #8
0
ファイル: test_wizard.py プロジェクト: dankoni88/Python
def test_iter():
    merlin = Wizard("Merlin")
    arthur = Apprentice("Arthur")
    sherlock = Wizard("Sherlock")
    watson = Apprentice("Vatson")
    wizard_dict = WizardDictionary({merlin: arthur, sherlock: watson})
    i = iter(wizard_dict)
    assert next(i) == merlin
    assert next(i) == sherlock
    with pytest.raises(StopIteration):
        next(i)
コード例 #9
0
ファイル: main.py プロジェクト: Aagatekk/ChallengePy
class Main:

    harry = Wizard('Harry', 13)
    harrys_wallet = Wallet("Harry")
    harrys_wallet.read_wallet_file()
    harrys_wallet.display_balances()
    harrys_wallet.deposit_money('USD', 100000)
    harrys_wallet.display_balances()
    harrys_wallet.save_balances()
    harrys_wallet.display_balances()

    hermione = Wizard('Hermione', 13)
コード例 #10
0
ファイル: test_wizard.py プロジェクト: dankoni88/Python
def test_set_item():
    wizard_dict = WizardDictionary()
    artur = Apprentice("Arthur", {Magic.gomancery, Magic.pyromancery})
    merlin = Wizard("Merlin",
                    {Magic.illusionism, Magic.mentalism, Magic.gomancery})
    wizard_dict[merlin] = artur
    assert wizard_dict[merlin] == artur
コード例 #11
0
class WvmSpritesList():
    """A class listing all the Sprites of the game."""

    def __init__(self, config, screen):
        """Initialize the sprite list."""
        self.config = config
        self.screen = screen

        #initialize the sprites
        self.wiz = Wizard(config, self)
        self.monsters = Group()
        self.missiles = Group()

    def update_all(self):
        """Update the positions of all sprites."""
        self.update_missiles()
        self.wiz.update()
        self.monsters.update()

    def update_missiles(self):
        """update magic missiles positions"""
        self.missiles.update()
        # remove the missiles that have left the screen
        for mi in self.missiles.copy():
            if mi.rect.left >= self.screen.get_rect().right:
                self.missiles.remove(mi)

    def draw(self):
        self.screen.fill(self.config.bg_color)
        for mi in self.missiles:
            mi.draw_missile()
        self.wiz.blitme()
        for mo in self.monsters:
            mo.blitme()

    def fire_missile(self):
        """Fire a missile if limit not reached yet."""
        if len(self.missiles) < self.wiz.magic_missile_allowed:
            self.missiles.add(MagicMissile(self.config, self))

    def create_monster(self):
        """Create a new monster and place it randomly at the right."""
        monster=Monster(self.config, self)
        #TODO move the monster
        self.monsters.add(monster)
コード例 #12
0
    def __init__(self, config, screen):
        """Initialize the sprite list."""
        self.config = config
        self.screen = screen

        #initialize the sprites
        self.wiz = Wizard(config, self)
        self.monsters = Group()
        self.missiles = Group()
コード例 #13
0
class WvmSpritesList():
    """A class listing all the Sprites of the game."""
    def __init__(self, config, screen):
        """Initialize the sprite list."""
        self.config = config
        self.screen = screen

        #initialize the sprites
        self.wiz = Wizard(config, self)
        self.monsters = Group()
        self.missiles = Group()

    def update_all(self):
        """Update the positions of all sprites."""
        self.update_missiles()
        self.wiz.update()
        self.monsters.update()

    def update_missiles(self):
        """update magic missiles positions"""
        self.missiles.update()
        # remove the missiles that have left the screen
        for mi in self.missiles.copy():
            if mi.rect.left >= self.screen.get_rect().right:
                self.missiles.remove(mi)

    def draw(self):
        self.screen.fill(self.config.bg_color)
        for mi in self.missiles:
            mi.draw_missile()
        self.wiz.blitme()
        for mo in self.monsters:
            mo.blitme()

    def fire_missile(self):
        """Fire a missile if limit not reached yet."""
        if len(self.missiles) < self.wiz.magic_missile_allowed:
            self.missiles.add(MagicMissile(self.config, self))

    def create_monster(self):
        """Create a new monster and place it randomly at the right."""
        monster = Monster(self.config, self)
        #TODO move the monster
        self.monsters.add(monster)
コード例 #14
0
    def __init__(self, endpoint, environment = environment.default, destination = None, limit = 0):
        super(Downloader, self).__init__()
        self.endpoint    = endpoint
        self.destination = destination
        self.success     = False
        self.limit       = limit
        self.environment = environment
        self.wizard      = Wizard(self.endpoint, environment = self.environment)

        self.init_callbacks()
コード例 #15
0
 def gen_enemies(self):
     if sum(self.current_wave) <= 0 and len(self.enemies) == 0:
         self.wave += 1
         self.current_wave = waves[self.wave]
         self.pause = True
         self.playPauseButton.change_img()
     else:
         wave_enemies = [Scorpion(), Wizard(), Invader(), Sword()]
         for x in range(len(self.current_wave)):
             if self.current_wave[x] != 0:
                 self.enemies.append(wave_enemies[x])
                 self.current_wave[x] -= 1
                 break
コード例 #16
0
    def __init__(self):
        pygame.init()

        self.settings = Settings(self)

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption(self.settings.game_name)
        self.wizard = Wizard(self)
        self.inventory = Inventory(self)
        self.inventory_window = InventoryWindow(self)

        # Create an instance to game statistics
        self.stats = GameStats(self)
        self.info = Info(self)
        self.items = pygame.sprite.Group()
        self._create_items()

        # Set the background color.
        self.bg_color = (150, 230, 150)
コード例 #17
0
def execute_wizard(name, **datas):
    """Executes given wizard with the given data

    @param name: name of the wizard
    @param datas: datas

    @return: wizard view (mostly XHTML code)
    """
    params = TinyDict()
    params.name = name
    params.datas = datas
    params.state = 'init'

    return Wizard().create(params)
コード例 #18
0
ファイル: agent_manager.py プロジェクト: drolando/SoftDev
    def initAgents(self, world):
        self.agentlayer = world.map.getLayer('TechdemoMapGroundObjectLayer')
        world.agentlayer = self.agentlayer
        self.boy = Boy(TDS, world, 'PC:boy', self.agentlayer)
        self.game.instance_to_agent[self.boy.agent.getFifeId()] = self.boy
        self.boy.start()
        self.agent_list.append(self.boy)

        self.girl = Girl(TDS, world, 'PC:girl', self.agentlayer, self)
        self.game.instance_to_agent[self.girl.agent.getFifeId()] = self.girl
        self.girl.start()
        self.agent_list.append(self.girl)

        self.wizard = Wizard(TDS, world, 'PC:wizard', self.agentlayer, self)
        self.game.instance_to_agent[self.wizard.agent.getFifeId()] = self.wizard
        self.wizard.start()
        self.agent_list.append(self.wizard)

        self.beekeepers = create_anonymous_agents(TDS, world, 'beekeeper', self.agentlayer, Beekeeper)
        for beekeeper in self.beekeepers:
            self.game.instance_to_agent[beekeeper.agent.getFifeId()] = beekeeper
            beekeeper.start()
            self.agent_list.append(beekeeper)

        self.cage = Cage(TDS, world, 'sword_crate', self.agentlayer)
        self.game.instance_to_agent[self.cage.agent.getFifeId()] = self.cage
        self.cage.start()
        self.agent_list.append(self.cage)

        self.bees = []
        for i in range(1, 8):
            bee = code.agents.bee.Bee(TDS, world, 'NPC:bee:0{}'.format(i), self.agentlayer, self)
            self.bees.append(bee)
            self.game.instance_to_agent[bee.agent.getFifeId()] = bee
            bee.start()
            self.agent_list.append(bee)

        self.warrior = Warrior(TDS, world, 'PC:warrior', self.agentlayer)
        self.game.instance_to_agent[self.warrior.agent.getFifeId()] = self.warrior
        self.warrior.start()
        self.agent_list.append(self.warrior)

        self.chemist = Chemist(TDS, world, 'NPC:chemist', self.agentlayer)
        self.game.instance_to_agent[self.chemist.agent.getFifeId()] = self.chemist
        self.chemist.start()
        self.agent_list.append(self.chemist)

        self.playableAgent = []
        self.reset()
コード例 #19
0
class Game:
    def __init__(self):
        self.creatures = [
            Creature("Toad", 1),
            Creature("Frog", 3),
            Dragon("Dragon", 50),
            Creature("Lion", 10)
        ]

        self.wizard = Wizard('Gandolf', 30)

    def play_round(self):
        opponent = random.choice(self.creatures)
        print("Opponent type: {}".format(type(opponent)))
        if self.wizard.battle(opponent):
            self.creatures.remove(opponent)
        else:
            print("Oh no, the wizard is defeated!")
コード例 #20
0
ファイル: level.py プロジェクト: emilkivela/ot-harjoitustyo
    def _initialize_sprites(self, level_room):

        for y in range(15):
            for x in range(20):
                cell = level_room[y][x]
                normalized_x = x * self.cell_size
                normalized_y = y * self.cell_size

                if cell == 0:
                    self.floors.add(Cobble(normalized_x, normalized_y))
                elif cell == 1:
                    self.walls.add(Brick(normalized_x, normalized_y))
                elif cell == 2:
                    self.wizard = Wizard(normalized_x, normalized_y)
                    self.floors.add(Cobble(normalized_x, normalized_y))
                elif cell == 3:
                    self.door.add(Door(normalized_x, normalized_y))
                elif cell == 4:
                    self.floors.add(Cobble(normalized_x, normalized_y))
                    self.skeletons.add(Skeleton(normalized_x, normalized_y))

        self.all_sprites.add(self.floors, self.walls, self.wizard, self.door, self.skeletons)
コード例 #21
0
def run_game():
    background = pygame.image.load('sprites/bkg.png')
    background_red = pygame.image.load('sprites/bkgred.png')
    background_dark_red = pygame.image.load('sprites/bkgdarkred.png')
    background_light = pygame.image.load('sprites/bkglight.png')
    pygame.init()
    GL = Game_Logic()
    screen = pygame.display.set_mode((510, 500))
    screen.fill((125, 125, 125))
    spellbook = Spellbook(screen)
    pygame.display.flip()
    pygame.display.set_caption('Wizards')
    icon = pygame.image.load('sprites/logo.png')
    pygame.display.set_icon(icon)

    prev_time = pygame.time.get_ticks(
    )  #Used for getting time between minion attacks
    text_box = TextBox(screen)

    round = 1

    character_party = [Wizard(
        'dark', 5, text_box, 140,
        True)]  #player's party (index always 0 unless we extend on game)
    enemy_party = [
        Wizard('earth', 1, text_box),
        Wizard('water', 1, text_box),
        Wizard('fire', 1, text_box),
        Wizard('dark', 1, text_box),
        Wizard('light', 1, text_box)
    ]  #Max size for party is 5

    current_pics = [0, 24, 12, 16, 8]  #for animation purposes
    wizard_element_pic = 0
    target_num = 2  #index of what enemy to target

    shifting = False  #is the shift key being held

    play_intro(screen)

    while True:
        #print(pygame.time.get_ticks()) -> use if statements to do constant attacking

        screen.fill((0, 0, 0))
        if character_party[0].hp > character_party[0].max_hp * 0.4:
            screen.blit(background, (0, 0))
        elif character_party[0].hp > character_party[0].max_hp * 0.2:
            screen.blit(background_red, (0, 0))
        else:
            screen.blit(background_dark_red, (0, 0))
        GL.update_HP_bar(screen, character_party[0])
        GL.update_enemy_HP_bar(screen, enemy_party)
        GL.update_screen(screen, character_party, enemy_party, current_pics,
                         target_num,
                         wizard_element_pic)  #animates all characters

        screen.blit(icon, (150, 250))  #player character

        for i in range(len(current_pics)):
            current_pics[i] = current_pics[i] + 2 if current_pics[
                i] <= 27 else 0  # for animation

        wizard_element_pic = wizard_element_pic + 2 if wizard_element_pic <= 27 else 0

        text_box.update(screen)

        if shifting:
            spellbook.open(screen)

        #pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN and event.key != pygame.K_LSHIFT:  #checks to see if target needs to be changed or if user is typing
                spell = text_box.input(event)
                new_index = GL.key_LR(event, target_num, enemy_party)
                if new_index != None:
                    target_num = new_index
                    print('new target num', target_num)
                if spell != None:
                    if spell.count(' ') >= 1:
                        GL.check_valid_prefix_spell(character_party[0],
                                                    spell.rpartition(' ')[0],
                                                    spell.rpartition(' ')[2],
                                                    enemy_party, target_num)
                    else:
                        GL.check_valid_spell(character_party[0], spell,
                                             enemy_party[target_num])
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_LSHIFT:
                shifting = True
            elif event.type == pygame.KEYUP and event.key == pygame.K_LSHIFT:
                shifting = False

        #game attempt
        if pygame.time.get_ticks(
        ) - prev_time > 5000:  #checks if 5 seconds have passed (for first level) then all units attack, attacking animation NOT IMPLEMENTED YET
            prev_time = pygame.time.get_ticks()
            GL.ai_constant_attack(screen, enemy_party, character_party[0])
            screen.fill((0, 0, 0))
            screen.blit(background_red, (0, 0))
            GL.update_HP_bar(screen, character_party[0])
            GL.update_enemy_HP_bar(screen, enemy_party)
            GL.update_screen_attacking(screen, character_party, enemy_party,
                                       current_pics, target_num,
                                       wizard_element_pic)
            text_box.update(screen)
            screen.blit(icon, (150, 250))
            if shifting:
                spellbook.open(screen)
            print(character_party[0].hp)
        pygame.display.flip()
        pygame.time.wait(40)

        #if not GL.health_is_gt_0(character_party[0]):   #checks if the main character has health greater than 0, breaks loop if less than 0
        #   break

        if GL.all_enemies_dead(enemy_party):
            round += 1
            enemy_party = GL.new_enemies(round, text_box)

        print(character_party[0].hp)
        print(target_num)

        print('len', len(enemy_party))
コード例 #22
0
ファイル: agent_manager.py プロジェクト: drolando/SoftDev
class AgentManager():

    def __init__(self, world):
        self.player = 0
        self.player_faces = ['gui/images/hud_boy.png', 'gui/images/hud_girl.png', 'gui/images/hud_warrior.png', 'gui/images/hud_wizard.png']
        self.agent_list = []
        self.game = code.game.Game.getGame()

    """
        Intializes all the agents. All these instances are also added to the self.agent_list list
        to simplify the searches by name or id.
    """
    def initAgents(self, world):
        self.agentlayer = world.map.getLayer('TechdemoMapGroundObjectLayer')
        world.agentlayer = self.agentlayer
        self.boy = Boy(TDS, world, 'PC:boy', self.agentlayer)
        self.game.instance_to_agent[self.boy.agent.getFifeId()] = self.boy
        self.boy.start()
        self.agent_list.append(self.boy)

        self.girl = Girl(TDS, world, 'PC:girl', self.agentlayer, self)
        self.game.instance_to_agent[self.girl.agent.getFifeId()] = self.girl
        self.girl.start()
        self.agent_list.append(self.girl)

        self.wizard = Wizard(TDS, world, 'PC:wizard', self.agentlayer, self)
        self.game.instance_to_agent[self.wizard.agent.getFifeId()] = self.wizard
        self.wizard.start()
        self.agent_list.append(self.wizard)

        self.beekeepers = create_anonymous_agents(TDS, world, 'beekeeper', self.agentlayer, Beekeeper)
        for beekeeper in self.beekeepers:
            self.game.instance_to_agent[beekeeper.agent.getFifeId()] = beekeeper
            beekeeper.start()
            self.agent_list.append(beekeeper)

        self.cage = Cage(TDS, world, 'sword_crate', self.agentlayer)
        self.game.instance_to_agent[self.cage.agent.getFifeId()] = self.cage
        self.cage.start()
        self.agent_list.append(self.cage)

        self.bees = []
        for i in range(1, 8):
            bee = code.agents.bee.Bee(TDS, world, 'NPC:bee:0{}'.format(i), self.agentlayer, self)
            self.bees.append(bee)
            self.game.instance_to_agent[bee.agent.getFifeId()] = bee
            bee.start()
            self.agent_list.append(bee)

        self.warrior = Warrior(TDS, world, 'PC:warrior', self.agentlayer)
        self.game.instance_to_agent[self.warrior.agent.getFifeId()] = self.warrior
        self.warrior.start()
        self.agent_list.append(self.warrior)

        self.chemist = Chemist(TDS, world, 'NPC:chemist', self.agentlayer)
        self.game.instance_to_agent[self.chemist.agent.getFifeId()] = self.chemist
        self.chemist.start()
        self.agent_list.append(self.chemist)

        self.playableAgent = []
        self.reset()

    """
        This method checks if the first 3 bees are near the beeboxes.
    """
    def beesAtHome(self):
        for bee in self.bees:
            if int(bee.agentName[-2:]) <= 3 and bee.mode == code.agents.bee._MODE_WILD:
                return False
        return True

    """
        This method checks if the bees whith id >= 4 are all dead.
    """
    def beesDead(self):
        for bee in self.bees:
            if int(bee.agentName[-2:]) >= 4 and bee.mode != code.agents.bee._MODE_DEAD:
                return False
        return True

    def reset(self):
        for p in self.playableAgent:
            p.reset()
        self.playableAgent = [self.boy, self.girl]
        self.active_agent = self.boy


    """
        Returns the current active agent.
    """
    def getActiveAgent(self):
        return self.active_agent

    """
        Returns the FIFE instance of the current active agent.
    """
    def getActiveInstance(self):
        return self.active_agent.agent

    """
        Returns the current active agent's location.
    """
    def getActiveAgentLocation(self):
        return self.active_agent.agent.getLocation()

    def getHero(self):
        return self.active_agent

    def getGirl(self):
        return self.girl

    """
        Changes the current active agent. The list self.playableAgent contains all the
        currently playable characters.
    """
    def toggleAgent(self, world, face_button):
        self.player = (self.player + 1) % len(self.playableAgent)

        face_button.up_image = self.player_faces[self.player]
        face_button.down_image = self.player_faces[self.player]
        face_button.hover_image = self.player_faces[self.player]

        for i in range(len(self.playableAgent)):
            self.playableAgent[i].idle()
            if i == self.player:
                self.playableAgent[i].isActive = True
                world.cameras['main'].attach(self.playableAgent[i].agent)
                world.cameras['small'].attach(self.girl.agent)
                self.active_agent = self.playableAgent[i]
            else:
                self.playableAgent[i].isActive = False
                self.playableAgent[i].follow_hero()

    """
        Returns the Agent to the agent with a specific fifeId.
    """
    def getAgentFromId(self, fifeId):
        for ag in self.agent_list:
            if ag.agent.getFifeId() == fifeId:
                return ag
        return None

    """
        Returns the Agent to the agent with a specific name.
    """
    def getAgentByName(self, name):
        for ag in self.agent_list:
            if ag.agentName == name:
                return ag
        return None

    """
        Adds a new playable agent if it's not yet present inside the playableAgent list.
    """
    def addNewPlayableAgent(self, name):
        for a in self.playableAgent:
            if a.agentName == name:
                return
        for a in self.agent_list:
            if a.agentName == name:
                self.playableAgent.append(a)
                if a.agentName != self.active_agent.agentName:
                    a.follow_hero()

    def destroy(self):
        for a in self.agent_list:
            a.destroy()
コード例 #23
0
 def test_strike_no_manna(self):
     wizard = Wizard('Merlin',100,10,0)
     opponent = Wizard('Gandalf',100,10,20)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna,0)
     self.assertEqual(opponent.hp,97)
コード例 #24
0
ファイル: wizard_test.py プロジェクト: Wushaowei001/frankedus
 def test_strike_without_manna(self):
     wizard = Wizard('Merlin', 40, 9, 0)
     opponent = Wizard('Other', 30, 5, 10)
     wizard.strike(opponent)
     self.assertEqual(opponent.hp, 27)
コード例 #25
0
 def test_strike_too_less_manna(self):
     wizard = Wizard('Merlin', 40, 12, 4)
     opponent = Wizard('Oz', 40, 10, 30)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 4)
     self.assertEqual(opponent.hp, 36)
コード例 #26
0
 def test_strike_without_manna(self):
     wizard = Wizard('Merlin', 40, 9, 0)
     enemy = Wizard('Oz', 50, 8, 5)
     wizard.strike(enemy)
     self.assertEqual(wizard.manna, 0-0)
     self.assertEqual(enemy.hp, 50-9/3)
コード例 #27
0
 def test_strike_with_manna(self):
     wizard = Wizard("Merlin", 40, 9, 0)
     opponent = Wizard("Other", 30, 5, 20)
     wizard.strike(opponent)
     self.assertEqual(opponent.hp, 27)
コード例 #28
0
 def test_strike_3(self):
     wizard = Wizard("Voldemort", 40, 10, 3)
     opponent = Wizard("Hermioner", 9, 2, 10)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 3)
コード例 #29
0
 def test_strike_4(self):
     wizard = Wizard("Harry", 40, 10, 25)
     opponent = Wizard("Hermioner", 9, 2, 10)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 20)
コード例 #30
0
 def test_strike(self):
     wizard = Wizard("Merlin", 40, 2, 20)
     opponent = Wizard("Dumbledor", 10, 2, 10)
     wizard.strike(opponent)
     self.assertEqual(opponent.hp, 4)
コード例 #31
0
            answer = input("What Sub Class (Assasin or Thief): ").lower()
            if (answer == "assasin"):
                player = Assasin(player.strength, player.constitution,
                                 player.dexterity, player.intelligence,
                                 player.wisdom, player.charisma)
            elif (answer == "thief"):
                player = Thief(player.strength, player.constitution,
                               player.dexterity, player.intelligence,
                               player.wisdom, player.charisma)
            else:
                print("Please enter Assasin or Thief.")
###############################################################################

# Wizard Class Branch##########################################################
    if (characterClass.lower() == 'wizard'):
        player = Wizard(player.strength, player.constitution, player.dexterity,
                        player.intelligence, player.wisdom, player.charisma)
        print(player.getStats())
        answer = None
        while answer not in ("arcane", "storm"):
            answer = input("What Speciality (Arcane or Storm): ").lower()
            if (answer == "arcane"):
                player = Arcanum(player.strength, player.constitution,
                                 player.dexterity, player.intelligence,
                                 player.wisdom, player.charisma)
            elif (answer == "storm"):
                player = Storms(player.strength, player.constitution,
                                player.dexterity, player.intelligence,
                                player.wisdom, player.charisma)
            else:
                print("Please enter Arcane or Storm.")
コード例 #32
0
ファイル: wizard_test.py プロジェクト: Wushaowei001/frankedus
 def test_strike_with_manna(self):
     wizard = Wizard('Merlin', 40, 10, 20)
     opponent = Wizard('Other', 30, 5, 10)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 15)
コード例 #33
0
	def test_strike_wo_mana(self):
		wizard = Wizard('GHAARRiYYY', 50, 30, 0)
		opponent = Wizard('VOLDERMORT', 100, 70, 20)
		wizard.strike(opponent)
		self.assertEqual(opponent.hp, 90)
コード例 #34
0
ファイル: hero_game.py プロジェクト: JMcWhorter150/hero_game
import math
from hero import Hero
from battle import Battle
from goblin import Goblin
from medic import Medic
from sayan import Sayan
from shadow import Shadow
from store import Store
from thief import Thief
from wizard import Wizard
from zombie import Zombie
from mimic import Mimic
hero = Hero('Oakley')
enemies = [
    Goblin('Bob'),
    Wizard('Jethro'),
    Medic('Mercy'),
    Thief('Barry'),
    Mimic('Harry'),
    Zombie('Rick'),
    Shadow('Matt'),
    Sayan('Goku')
]
# enemies = [Thief('Barry')] Goblin('Bob'), Wizard('Jethro'), Medic('Mercy'), Thief('Barry'), Zombie('Rick'), Shadow('Matt'), Sayan('Goku'),
battle_engine = Battle()
shopping_engine = Store()

for enemy in enemies:
    hero_won = battle_engine.do_battle(hero, enemy)
    if not hero_won:
        print("YOU LOSE!")
コード例 #35
0
def init_new_player(conn):
    new_wiz = Wizard(RemotePlayer(conn))
    game_state.wizards.append(new_wiz)
    game_state.entities.append(new_wiz)
    print("{} has joined the game!".format(new_wiz.name))
コード例 #36
0
 def test_strike_five_manna(self):
     wizard = Wizard("Merlin", 40, 10, 20)
     opponent = Wizard("opi", 40, 10, 20)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 15)
     self.assertEqual(opponent.hp, 10)
コード例 #37
0
ファイル: test_wizard.py プロジェクト: dankoni88/Python
def test_wizard_unsuitable(wizard_skills, apprentice_skills):
    wizard_dict = WizardDictionary()
    arthur = Apprentice("Arthur", apprentice_skills)
    merlin = Wizard("Merlin", wizard_skills)
    with pytest.raises(ValueError):
        wizard_dict[merlin] = arthur
コード例 #38
0
from wizard import Wizard
from random import randint
from game_logic import Game_Logic

GL = Game_Logic()
enemies = [Wizard('earth', 1)]  #, Wizard('water', 1), Wizard('earth', 1)]

you = Wizard('fire', 1)
you.hp = 25
while you.hp > 0:
    print('your hp', you.hp)
    for enemy in enemies:
        print('enemy hps', enemy.hp)

    spell_num = (input('input a spell '))
    GL.check_valid_spell(you, spell_num, enemies[0])

    #you.exec_turn(enemies[0], you.spells[spell_num])

    #you.exec_turn(enemies[randint(0, len(enemies)) - 1], you.spells[randint(0,len(you.spells)) - 1])

    enemy.exec_turn(you, 'burn')

    print()
コード例 #39
0
 def test_strike_triple_damage(self):
     wizard = Wizard('Merlin', 40, 10, 20)
     opponent = Wizard('Oz', 40, 10, 30)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 15)
     self.assertEqual(opponent.hp, 10)
コード例 #40
0
class WizardsBroth:
    """Overal class to manage game assist and behavior"""
    def __init__(self):
        pygame.init()

        self.settings = Settings(self)

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption(self.settings.game_name)
        self.wizard = Wizard(self)
        self.inventory = Inventory(self)
        self.inventory_window = InventoryWindow(self)

        # Create an instance to game statistics
        self.stats = GameStats(self)
        self.info = Info(self)
        self.items = pygame.sprite.Group()
        self._create_items()

        # Set the background color.
        self.bg_color = (150, 230, 150)

    def _create_items(self):
        count = 3  #random.randint(1,3)
        print(f"count {count}")
        for i in range(count):
            item = Item(self, random.randint(0, 2))
            item_width, item_height = item.rect.size
            item.x = random.randint(0, self.settings.screen_width - 20)
            item.y = random.randint(0, self.settings.screen_height - 20)
            self.items.add(item)

    def _reset_and_start_game(self):
        self.stats.game_active = True
        self.inventory.items = []
        self.inventory_window.prep_inventory()

    def _pick_up_item(self):
        if self.stats.can_pick_up:
            print("voidaan nostaa")
        else:
            print("Täällä ei ole mitään kerättävää")

    def _check_events(self):
        # Watch for keyboard and mouse events.

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.wizard.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.wizard.moving_left = False
        elif event.key == pygame.K_UP:
            self.wizard.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.wizard.moving_down = False

    def _check_keydown_events(self, event):
        """Respond to keypresses."""
        if event.key == pygame.K_RIGHT:
            self.wizard.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.wizard.moving_left = True
        elif event.key == pygame.K_q:
            sys.exit()
        elif event.key == pygame.K_UP:
            self.wizard.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.wizard.moving_down = True
        elif event.key == pygame.K_SPACE:
            self._pick_up_item()
        elif event.key == pygame.K_o:
            self.stats.more_info = True
        elif event.key == pygame.K_ESCAPE:
            self.stats.more_info = False
            self.stats.show_inventory = False
        elif event.key == pygame.K_p:
            if not self.stats.game_active:
                self._reset_and_start_game()
        elif event.key == pygame.K_t:
            self.stats.show_inventory = True

    def __update_screen(self):
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.bg_color)
        self.wizard.blitme()
        self.items.draw(self.screen)

        if self.stats.show_inventory:
            self.inventory_window.show_inventory()

        if not self.stats.game_active and not self.stats.more_info:
            self.info.show_message(self.settings.start_message)

        if self.stats.more_info:
            self.info.show_message(self.settings.instructions)

        # Make the most recently drawn screen visible.
        pygame.display.flip()

    def _check_can_pick(self):
        if pygame.sprite.spritecollideany(self.wizard, self.items):
            self.stats.can_pick_up = True
        else:
            self.stats.can_pick_up = False

    def run_game(self):
        """Start the main loop for game."""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.wizard.update()
                self._check_can_pick()

            self.__update_screen()
コード例 #41
0
def main(argv):

    path = None
    first_arg = None
    second_arg = None
    config = None
    apath = None
    print("QT VERSION %s" % QT_VERSION_STR)

    try:
        first_arg = argv[1]
        second_arg = argv[2]
    except IndexError:
        pass

    if first_arg is not None:
        if first_arg == "-c":
            config = True
            if second_arg is not None:
                path = second_arg
        else:
            path = first_arg

    try:
        #app = QApplication(argv)
        app = MyApp(argv)

        QCoreApplication.setOrganizationDomain('www.trickplay.com')
        QCoreApplication.setOrganizationName('Trickplay')
        QCoreApplication.setApplicationName('Trickplay Debugger')
        QCoreApplication.setApplicationVersion('0.0.1')

        s = QProcessEnvironment.systemEnvironment().toStringList()
        for item in s:
            k, v = str(item).split("=", 1)
            if k == 'PWD':
                apath = v

        apath = os.path.join(apath, os.path.dirname(str(argv[0])))
        main = MainWindow(app, apath)
        main.config = config

        main.show()
        main.raise_()
        wizard = Wizard()
        app.main = main

        path = wizard.start(path)
        if path:
            settings = QSettings()
            settings.setValue('path', path)

            app.setActiveWindow(main)
            main.start(path, wizard.filesToOpen())
            main.show()

        sys.exit(app.exec_())

    # TODO, better way of doing this for 'clean' exit...
    except KeyboardInterrupt:
        exit("Exited")
def main():
    staff1 = Staff(50)
    staff2 = Staff(75)
    staff3 = Staff(50)
    staff4 = Staff(-10)

    #Testing Staff.getPower()
    print()
    print("Testing Staff.getPower().")
    print("Test Staff.getPower(), expected 50 was", staff1.getPower())
    print("Test Staff.getPower(), expected 75 was", staff2.getPower())
    print("Test Staff.getPower(), expected 50 was", staff3.getPower())
    print("Test Staff.getPower(), expected 25 was", staff4.getPower())
    print()

    #Testing Staff == and !=
    print("Testing Staff == and !=.")
    print("Test Staff ==, expected True  was", staff1 == staff3)
    print("Test Staff ==, expected False was", staff2 == staff3)
    print("Test Staff !=, expected True  was", staff1 != staff4)
    print("Test Staff !=, expected False was", staff1 != staff3)
    print()

    #Testing Staff string representation
    print("Testing Staff string representation.")
    print('Expected "Staff of power 50." was "%s"' % str(staff1))
    print('Expected "Staff of power 75." was "%s"' % str(staff2))
    print()

    wizard1 = Wizard("Hermione", staff1)
    wizard2 = Wizard("Ron", staff2)

    #Testing Wizard.getName()
    print("Testing Wizard.getName()")
    print("Expected Hermione  was", wizard1.getName())
    print("Expected Ron was", wizard2.getName())
    print()

    #Testing Wizard.getStaff()
    print("Testing Wizard.getStaff()")
    print('Expected "Staff of power 50." was "%s"' % str(wizard1.getStaff()))
    print('Expected "Staff of power 75." was "%s"' % str(wizard2.getStaff()))
    print()

    #Testing Wizard.getPower()
    print("Testing Wizard.getPower().")
    print("Test Wizard.getPower(), expected 50 was", wizard1.getPower())
    print("Test Wizard.getPower(), expected 75 was", wizard2.getPower())
    print()

    #Testing Wizard string representation.
    print("Testing Wizard string representation.")
    print('Expected "Wizard Hermione with staff of power 50."\n     was "%s"' %
          str(wizard1))
    print('Expected "Wizard Ron with staff of power 75."\n     was "%s"' %
          str(wizard2))
    print()

    #some battles
    #Expected: Hermione defeats Draco
    battle(Wizard("Hermione", Staff(1000)), Wizard("Draco", Staff(250)))
    print()

    #Expected: Ron defeats Draco
    battle(Wizard("Draco", Staff(500)), Wizard("Ron", Staff(1500)))
    print()

    #Expected: It's a draw
    battle(Wizard("Hermione", Staff(1)), Wizard("Harry", Staff(1)))
    print()

    #Expected: Unknown!
    battle(Wizard("Harry", Staff(100)), Wizard("Hermione", Staff(100)))
    print()
コード例 #43
0
def main(argv):

    path = None
    first_arg = None
    second_arg = None
    config = None
    apath = None
    print("QT VERSION %s" % QT_VERSION_STR )

    try:
        first_arg = argv[1]
        second_arg = argv[2]
    except IndexError:
        pass

    if first_arg is not None:
        if first_arg == "-c":
            config = True 
            if second_arg is not None:
                path = second_arg
        else:
            path = first_arg
        
    try:
        #app = QApplication(argv)
        app = MyApp(argv)

        QCoreApplication.setOrganizationDomain('www.trickplay.com');
        QCoreApplication.setOrganizationName('Trickplay');
        QCoreApplication.setApplicationName('Trickplay Debugger');
        QCoreApplication.setApplicationVersion('0.0.1');
            
        s = QProcessEnvironment.systemEnvironment().toStringList()
        for item in s:
            k , v = str( item ).split( "=" , 1 )
            if k == 'PWD':
                apath = v

        apath = os.path.join(apath, os.path.dirname(str(argv[0])))
        main = MainWindow(app, apath)
        main.config = config

        main.show()
        main.raise_()
        wizard = Wizard()
        app.main = main

        path = wizard.start(path)
        if path:
            settings = QSettings()
            settings.setValue('path', path)

            app.setActiveWindow(main)
            main.start(path, wizard.filesToOpen())
            main.show()

        sys.exit(app.exec_())

    # TODO, better way of doing this for 'clean' exit...
    except KeyboardInterrupt:
		exit("Exited")
コード例 #44
0
class GhostsAttack:
    """Overall class to manage game assets and behavior."""
    def __init__(self):
        """Initialize the game, and create game resources."""
        pygame.init()

        self.settings = Settings()
        # Takes full screen or not
        if self.settings.full_screen:
            self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
            self.settings.screen_width = self.screen.get_rect().width
            self.settings.screen_height = self.screen.get_rect().height
        else:
            self.screen = pygame.display.set_mode(
                (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Ghosts Attack")

        # Variable for control time.
        self.clock = pygame.time.Clock()

        # Create an instance to store game statistics,
        # and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.wizard = Wizard(self)
        self.balls = pygame.sprite.Group()
        self.ghosts = pygame.sprite.Group()
        self._create_crowd()

        # Make the Play button.
        self.play_button = Button(self, "Play")

    def run_game(self):
        """Start the main loop for the game."""
        while True:
            # Reduce redraw the screen to FPS. Save PC resource
            self.clock.tick(self.settings.FPS)

            self._check_events()
            if self.stats.game_active:
                self.wizard.update()
                self._update_balls()
                self._update_ghosts()

            self._update_screen()

    def _check_events(self):
        """Respond to key presses and mouse events."""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.stats.write_high_score()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_play_button(mouse_pos)

    def _check_keydown_events(self, event):
        """Respond to key presses."""
        if event.key == pygame.K_RIGHT:
            self.wizard.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.wizard.moving_left = True
        elif event.key == pygame.K_q:
            self.stats.write_high_score()
            sys.exit()
        elif event.key == pygame.K_SPACE:
            self._fire_ball()

    def _check_keyup_events(self, event):
        """Respond to key releases."""
        if event.key == pygame.K_RIGHT:
            self.wizard.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.wizard.moving_left = False

    def _fire_ball(self):
        """Create a new ball and add it to the balls group."""
        if len(self.balls) < self.settings.balls_allowed:
            new_ball = Ball(self)
            self.balls.add(new_ball)

    def _check_play_button(self, mouse_pos):
        """Start a new game when the player clicks Play."""
        button_clicked = self.play_button.rect.collidepoint(mouse_pos)
        if button_clicked and not self.stats.game_active:
            # Reset the game settings.
            self.settings.initialize_dynamic_settings()
            # Reset the game statistics.
            self.stats.reset_stats()
            self.stats.game_active = True
            self.sb.prep_score()
            self.sb.prep_hearts()
            # Get rid of any remaining ghosts and balls.
            self.ghosts.empty()
            self.balls.empty()
            # Create a new crowd and center the wizard.
            self._create_crowd()
            self.wizard.center_wizard()
            # Hide the mouse cursor.
            pygame.mouse.set_visible(False)

    def _update_balls(self):
        """Update position of balls and get rid of old balls."""
        # Update balls positions
        self.balls.update()

        # Get rid of balls that have disappeared.
        for ball in self.balls.copy():
            if ball.rect.bottom <= 0:
                self.balls.remove(ball)

        self._check_ball_ghost_collisions()

    def _check_ball_ghost_collisions(self):
        """Respond to ball-ghost collisions."""
        # Remove any ballets and ghosts that have collided.
        collisions = pygame.sprite.groupcollide(self.balls, self.ghosts, True,
                                                True)
        if collisions:
            for ghosts in collisions.values():
                self.stats.score += self.settings.ghost_points * len(ghosts)
            self.sb.prep_score()
            self.sb.check_high_score()

        if not self.ghosts:
            # Destroy existing balls and create new crowd.
            self.balls.empty()
            self._create_crowd()
            self.settings.increase_speed()

    def _update_screen(self):
        """Update images on the screen, and flip to the new screen."""
        # Redraw the screen during each pass through the loop.
        self.screen.fill(self.settings.bg_color)
        # Add the wizard to the game
        self.wizard.blitme()
        # Add balls to the game
        for ball in self.balls.sprites():
            ball.draw_ball()
        # Add ghosts to the game
        self.ghosts.draw(self.screen)
        # Draw the score information.
        self.sb.show_score()
        # Draw the play button if the game is inactive.
        if not self.stats.game_active:
            self.play_button.draw_button()
        # Make the most recently drawn screen visible.
        pygame.display.flip()

    def _create_crowd(self):
        """Create the crowd of ghosts."""
        # Create a ghost and find the number of ghosts in a row.
        # Spacing between each ghost is equal to one ghost width.
        ghost = Ghost(self)
        ghost_width, ghost_height = ghost.rect.size
        available_space_x = self.settings.screen_width - (2 * ghost_width)
        number_ghosts_x = available_space_x // (2 * ghost_width)
        # Determine the number of rows of ghosts that fit on the screen.
        wizard_height = self.wizard.rect.height
        available_space_y = (self.settings.screen_height - (3 * ghost_height) -
                             wizard_height)
        number_rows = available_space_y // (2 * ghost_height)

        # Create the full crowd of ghosts
        for row_number in range(number_rows):
            for ghost_number in range(number_ghosts_x):
                self._create_ghost(ghost_number, row_number)

    def _create_ghost(self, ghost_number, row_number):
        # Create a ghost and place it in the row.
        ghost = Ghost(self)
        ghost_width, ghost_height = ghost.rect.size
        ghost.x = ghost_width + 2 * ghost_width * ghost_number
        ghost.rect.x = ghost.x
        ghost.rect.y = ghost.rect.height + 2 * ghost.rect.height * row_number
        self.ghosts.add(ghost)

    def _update_ghosts(self):
        """Update the positions of all ghosts in the crowd."""
        self._check_fleet_edges()
        self.ghosts.update()

        # Look for ghost-wizard collisions.
        if pygame.sprite.spritecollideany(self.wizard, self.ghosts):
            self._wizard_hit()
        # Look for ghosts hitting the bottom of the screen.
        self._check_ghosts_bottom()

    def _check_fleet_edges(self):
        """Respond appropriately if any ghosts have reached an edge."""
        for ghost in self.ghosts.sprites():
            if ghost.check_edges():
                self._change_crowd_direction()
                break

    def _change_crowd_direction(self):
        """Drop the entire crowd and change the crowd's direction."""
        for ghost in self.ghosts.sprites():
            ghost.rect.y += self.settings.crowd_drop_speed
        self.settings.crowd_direction *= -1

    def _wizard_hit(self):
        """Respond to the wizard being hit by an ghost."""
        if self.stats.wizards_left > 0:
            # Decrement wizards_left, and update scoreboard.
            self.stats.wizards_left -= 1
            self.sb.prep_hearts()
            # Get rid of any remaining ghosts and balls.
            self.ghosts.empty()
            self.balls.empty()
            # Create a new crowd and center the wizard.
            self._create_crowd()
            self.wizard.center_wizard()
            # Pause
            sleep(0.5)
        else:
            self.stats.game_active = False
            pygame.mouse.set_visible(True)

    def _check_ghosts_bottom(self):
        """Check if any ghosts have reached the bottom of the screen."""
        screen_rect = self.screen.get_rect()
        for ghost in self.ghosts.sprites():
            if ghost.rect.bottom >= screen_rect.bottom:
                # Treat this the same as if the wizard got hit.
                self._wizard_hit()
                break
コード例 #45
0
ファイル: test_wizard.py プロジェクト: florimaros/florimaros
 def test_strike_with_manna(self):
     wizard = Wizard("Merlin", 40, 10, 20)
     opponent = Wizard("Malfoy", 30, 5, 10)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 15)
コード例 #46
0
class Downloader(object):
    def __init__(self, endpoint, environment = environment.default, destination = None, limit = 0):
        super(Downloader, self).__init__()
        self.endpoint    = endpoint
        self.destination = destination
        self.success     = False
        self.limit       = limit
        self.environment = environment
        self.wizard      = Wizard(self.endpoint, environment = self.environment)

        self.init_callbacks()

    @classmethod
    def status_file_for(cls, endpoint):
        import os.path, tempfile
        tmpdir = tempfile.gettempdir()
        status = util.normalize_url(endpoint)
        return os.path.join(tmpdir, status)

    def file_name(self):
        original = self.consumer.file_name().encode()
        ext      = original.split('.')[-1]
        with_ext = '%s.%s' % (self.file_hint(), ext)

        return self.sanitize_file(with_ext)

    def sanitize_file(self, file_name):
        import re
        encoded  = file_name.encode()
        replaced = re.sub(r'[^a-zA-Z0-9. ]', '', encoded)

        return replaced

    def file_hint(self):
        return self.wizard.file_hint

    def status_file(self):    return Downloader.status_file_for(self.endpoint)
    def asset_url(self):      return self.consumer.asset_url().encode()
    def local_partfile(self): return self.local_file() + '.part'
    def local_file(self):
        import os.path
        return os.path.join(self.destination, self.file_name())

    def add_callback(self, group, cb): self.callbacks[group].append(cb)
    def on_start(self, cb):    self.add_callback('start',    cb)
    def on_success(self,  cb): self.add_callback('success',  cb)
    def on_error(self, cb):    self.add_callback('error',    cb)

    def run_start_callbacks(self):
        self.run_callbacks('_start')
        self.run_callbacks('start')

    def run_success_callbacks(self):
        self.run_callbacks('_success')
        self.run_callbacks('success')

    def run_error_callbacks(self):
        self.run_callbacks('_error')
        self.run_callbacks('error')

    def run_callbacks(self, group):
        for cb in self.callbacks[group]:
            cb(self)

    def init_callbacks(self):
        groups = ( 'start', 'success', 'error' )
        self.callbacks = {}

        for g in groups:
            self.callbacks[g]       = []
            self.callbacks['_' + g] = []

        def debug_dl(dl):
            lines = [ dl.pid, dl.consumer.url, dl.asset_url(), dl.local_file() ]

            for line in lines:
                self.environment.log(line)

        def rename_partfile(dl):
            import os
            os.rename( dl.local_partfile(), dl.local_file() )

        def cleanup_status_file(dl):
            dl.cleanup_status_file()

        #self.add_callback('_start',   debug_dl)
        self.add_callback('_success', rename_partfile)
        self.add_callback('_success', cleanup_status_file)

    def download(self):
        def perform_download(consumer):
            self.consumer = consumer
            self.success  = self.really_download()

        self.wizard.sources(perform_download)

        if self.success:
            self.run_success_callbacks()
        else:
            self.run_error_callbacks()

    def curl_options(self):
        options = [
            'curl',
            '--location',
            '--referer',    self.consumer.url,
            '--cookie',     self.consumer.agent_cookie_string(),
            '--user-agent', self.consumer.ua,
            '--stderr',     self.status_file(),
            '--output',     self.local_partfile()
        ]

        if int(self.limit) > 0:
            options.append('--limit-rate')
            options.append('%sK' % self.limit)

        options.append(self.asset_url())

        return options

    def really_download(self):
        from signal import SIGTERM
        import subprocess
        import re

        piped    = subprocess.Popen(self.curl_options())
        self.pid = piped.pid

        self.run_start_callbacks()
        piped.wait()

        returned = abs(piped.returncode)
        status   = DownloadStatus(self.status_file())
        status.parse_status_file()

        if re.search(r'(k|K|\d)$', status.total_size):
            returned = 99

        if 0 == returned:
            return True
        elif SIGTERM == returned:
            self.cleanup()
            return False
        else:
            self.cleanup()
            raise Exception('cURL returned %s, trying next source.' % returned)

    def cleanup_status_file(self):
        self.attempt_remove(self.status_file())

    def cleanup(self):
        self.cleanup_status_file()
        self.attempt_remove(self.local_file())
        self.attempt_remove(self.local_partfile())

    def attempt_remove(self, f):
        import os
        try:    os.remove(f)
        except: pass
コード例 #47
0
from hero import Hero
from zombie import Zombie
from goblin import Goblin
from wizard import Wizard
from battle import Battle
from store import Store

hero = Hero('Oakley')
zombie = Zombie()
enemies = [Goblin('Bob'), Wizard('Jethro')]
battle_engine = Battle()
shopping_engine = Store()

for enemy in enemies:
    hero_won = battle_engine.do_battle(hero, enemy)
    if not hero_won:
        print("YOU LOSE!")
        exit(0)
    shopping_engine.do_shopping(hero)

print("But not you Chris Aquino")
print("YOU WIN!")
コード例 #48
0
 def test_strike_no_manna(self):
     wizard = Wizard('Merlin', 40, 10, 4)
     other = Wizard('Ursula', 40, 10, 20)
     wizard.strike(other)
     self.assertEqual(wizard.manna, 4)
     self.assertEqual(other.hp, 37)
コード例 #49
0
	def test_strike(self):
		wizard = Wizard('HARYYRYR', 50, 50, 20)
		opponent = Wizard('Tom Denem', 100, 70, 20)
		wizard.strike(opponent)
		self.assertEqual(opponent.hp, -50)
コード例 #50
0
from wizard import Wizard

btc_wizard = Wizard('BTC_ETH', 10)
btc_etc = Wizard('BTC_ETC', 10)
eth_etc = Wizard('ETH_ETC', 10)

btc_wizard.start_book('BTC_ETH', 10)

 
コード例 #51
0
	def test_manna(self):
		wizard = Wizard('hafaprotter', 50, 50, 20)
		opponent = Wizard('VODLMER', 100, 70, 20)
		wizard.strike(opponent)
		self.assertEqual(wizard.manna, 15)
コード例 #52
0
class WebRoot:
    _cp_config = {'tools.stateBlock.on': True}
    appPath = ''

    def __init__(self, app_path):
        WebRoot.appPath = app_path

    _globals = helper.guiGlobals
    browser = WebFileBrowser()
    ajax = AjaxCalls(env)
    wizard = Wizard(env)
    api = WebApi()

    def redirect(self, abspath, *args, **KWs):
        assert abspath[0] == '/'
        raise cherrypy.HTTPRedirect(
            '%s%s' % (common.SYSTEM.c.webRoot, abspath), *args, **KWs)

    @cherrypy.expose
    def index(self, status_message='', version=''):
        template = env.get_template('index.html')
        return template.render(**self._globals())

    @cherrypy.expose
    def status(self, runTask=None):
        if runTask is None:
            tasks.coreUpdateCheck()
        else:
            common.SCHEDULER.runTaskNow(runTask)
        template = env.get_template('about.html')
        return template.render(platform=platform,
                               originalArgs=sys.argv,
                               xdm=xdm,
                               **self._globals())

    @cherrypy.expose
    def plugins(self, recache=''):
        now = datetime.datetime.now()
        if common.REPOMANAGER.last_cache is not None:
            last_cache = common.REPOMANAGER.last_cache
        else:
            last_cache = now - datetime.timedelta(hours=25)
        delta = datetime.timedelta(hours=24)
        if not common.REPOMANAGER.cached or recache or (now - last_cache >
                                                        delta):
            t = tasks.TaskThread(tasks.cacheRepos)
            t.start()
        if recache:
            return ''

        template = env.get_template('plugins.html')
        return template.render(**self._globals())

    @cherrypy.expose
    def completed(self):
        template = env.get_template('completed.html')
        return template.render(**self._globals())

    @cherrypy.expose
    def settings(self, **kwargs):
        plugins = []
        if kwargs:
            indexes = sorted(kwargs.keys())
            for index in indexes:
                pluginClassGetter = kwargs[index]
                plugins.extend(
                    getattr(common.PM, pluginClassGetter)(returnAll=True))
        else:
            plugins = common.PM.getAll(True)
        template = env.get_template('settings.html')
        return template.render(plugins=plugins, **self._globals())

    @cherrypy.expose
    def settingsPluginHtml(self, **kwargs):
        plugins = []
        if kwargs:
            indexes = sorted(kwargs.keys())
            for index in indexes:
                pluginClassGetter = kwargs[index]
                try:
                    plugins.extend(
                        getattr(common.PM, pluginClassGetter)(returnAll=True))
                except AttributeError:
                    pass
        else:
            return ""
        template = env.get_template('settingsPlugin.html')
        return template.render(plugins=plugins, **self._globals())

    @cherrypy.expose
    def forcesearch(self, id):
        element = Element.get(Element.id == id)
        newStatus = tasks.searchElement(element)
        element.save()
        self.redirect('/')

    @cherrypy.expose
    def results(self, search_query=''):
        template = env.get_template('results.html')
        templateGlobals = self._globals()
        searchers = templateGlobals['mtms']

        if search_query.startswith('All: '):
            search_query = search_query.replace('All: ', '')
        else:
            for mtm in templateGlobals['mtms']:
                if search_query.startswith('%s: ' % mtm.type):
                    search_query = search_query.replace('%s: ' % mtm.type, '')
                    searchers = [mtm]
                    break
        return template.render(searchers=searchers,
                               search_query=search_query,
                               **templateGlobals)

    @cherrypy.expose
    def getMediaTypePaint(self, identifier, status=''):

        mt = common.PM.getMediaTypeManager(identifier)[0]
        if status == 'home':
            status = mt.homeStatuses()
        elif status == 'completed':
            status = mt.completedStatues()
        return mt.paint(status=status)

    @cherrypy.expose
    def getPaint(self, id):
        e = Element.get(Element.id == id)
        return e.manager.paint(e)

    @cherrypy.expose
    def getChildrensPaint(self, id):
        e = Element.get(Element.id == id)
        return e.manager.paintChildrenOf(e)

    @cherrypy.expose
    def createInstance(self, plugin, instance):
        c = None
        for cur_plugin in common.PM.getAll(True):
            if cur_plugin.type == plugin and not cur_plugin.single:
                cleanInstance = re.sub(ur'[\W]+',
                                       u'_',
                                       instance,
                                       flags=re.UNICODE)
                c = cur_plugin.__class__(instance=cleanInstance)
                break
        common.PM.cache()
        url = '%s/settings/' % common.SYSTEM.c.webRoot
        if c:
            url = '%s/settings/#%s' % (common.SYSTEM.c.webRoot,
                                       c.name.replace(' ', '_').replace(
                                           '(', '').replace(')', ''))
        raise cherrypy.HTTPRedirect(url)

    @cherrypy.expose
    def removeInstance(self, plugin, instance):
        for cur_plugin in common.PM.getAll(True):
            if cur_plugin.type == plugin and cur_plugin.instance == instance:
                c = cur_plugin.deleteInstance()
                break
        common.PM.cache()
        self.redirect('/settings/')

    @cherrypy.expose
    def refreshinfo(self, id):
        log("init update")
        tasks.updateElement(Element.get(Element.id == id))
        raise cherrypy.HTTPRedirect('%s/' % common.SYSTEM.c.webRoot)

    @cherrypy.expose
    def delete(self, id):
        e = Element.get(Element.id == id)
        manager = e.manager
        manager.deleteElement(e)
        self.redirect('/')

    @cherrypy.expose
    def setStatus(self, id, s):
        ele = Element.get(Element.id == id)
        ele.status = common.getStatusByID(int(s))
        ele.save()
        if ele.status == common.WANTED:
            tasks.searchElement(ele)
        self.redirect('/')

    @cherrypy.expose
    def getDownload(self, id):
        download = Download.get(Download.id == id)
        tasks.snatchOne(download.element, [download])
        self.redirect('/')

    @cherrypy.expose
    def makePermanent(self, id):
        element = Element.get(Element.id == id)
        status = common.getStatusByID(
            element.manager.c.default_new_status_select)
        element.manager.makeReal(element, status)
        if status == common.WANTED:
            t = tasks.TaskThread(tasks.searchElement, element)
            t.start()
        self.redirect('/')

    # TODO: what in the world is this !?
    @cherrypy.expose
    def addElement(self, mt, providerTag, pID):
        mtm = common.PM.getMediaTypeManager(mt)[0]
        log("adding %s %s %s" % (mt, providerTag, pID))
        for p in common.PM.P:
            if not (p.runFor(mtm) and p.tag == providerTag):
                continue
            new_e = p.getElement(pID)
            if new_e:
                new_e.save()
                new_e.downloadImages()
        self.redirect('/')

    @cherrypy.expose
    def clearSearches(self):
        tasks.removeTempElements()
        self.redirect('/')

    @cherrypy.expose
    def startDownloadChecker(self):
        tasks.runChecker()
        self.redirect("/")

    @cherrypy.expose
    def log(self, entries=30):
        logEntries = ''
        entryTemplate = env.get_template('log_entry.html')
        for _log in log.getEntries(entries):
            logEntries += entryTemplate.render(log=_log)

        template = env.get_template('log.html')
        return template.render(platform=platform,
                               logEntries=logEntries,
                               logPath=xdm.LOGPATH,
                               **self._globals())

    @cherrypy.expose
    def saveSettings(self, **kwargs):
        redirect_to = '/settings/'
        if 'saveOn' in kwargs:
            redirect_to += "#%s" % kwargs['saveOn']
            del kwargs['saveOn']
        self.ajax.save(**kwargs)
        self.redirect(redirect_to)

        # actions = list(set(actions))
        common.PM.cache()
        final_actions = {}
        for cur_class_name, cur_actions in actions.items():
            for cur_action in cur_actions:
                if not cur_action in final_actions:
                    final_actions[cur_action] = []
                final_actions[cur_action].append(cur_class_name)
        for action, plugins_that_called_it in final_actions.items():
            actionManager.executeAction(action, plugins_that_called_it)
        common.SYSTEM = common.PM.getSystem('Default')[
            0]  # yeah SYSTEM is a plugin
        return json.dumps({
            'result': True,
            'data': {},
            'msg': 'Configuration saved.'
        })
コード例 #53
0
 def test_without_manna(self):
     wizard = Wizard("Merlin", 40, 10, 20)
     opponent = Wizard("Other",30, 5, 20)
     wizard.strike(opponent)
     self.assertEqual(opponent.manna, 15)
コード例 #54
0
ファイル: game.py プロジェクト: huttonb/BBB
 def __init__(self):
     self.wizard_one = Wizard()
     self.wizard_two = Wizard()
     self.game_field = None #TODO: Create Game Field
     self.turn = 0
     self.start_game()
コード例 #55
0
ファイル: downloader.py プロジェクト: wardrich/ss-plex.bundle
class Downloader(object):
    def __init__(self, endpoint, destination = None, limit = 0, strategy = 'curl', avoid_small_files = False):
        self.endpoint    = endpoint
        self.destination = destination
        self.success     = False
        self.limit       = limit
        self.wizard      = Wizard(self.endpoint)
        self.strategy    = strategy
        self.avoid_small = avoid_small_files

        self.init_callbacks()

    @property
    def file_name(self):
        hinted = self.wizard.file_hint.encode()
        consumed = self.consumer.file_name.encode()
        ext = consumed.split('.')[-1]
        merged = '%s.%s' % (hinted, ext)

        return sanitize_file(merged)

    @property
    def status_file(self):
        return status_file_for(self.endpoint)

    @property
    def local_partfile(self):
        return self.local_file + '.part'

    @property
    def local_file(self):
        import os.path
        return os.path.join(self.destination, self.file_name)

    def add_callback(self, group, cb): self.callbacks[group].append(cb)
    def on_start(self, cb):    self.add_callback('start',    cb)
    def on_success(self,  cb): self.add_callback('success',  cb)
    def on_error(self, cb):    self.add_callback('error',    cb)

    def run_start_callbacks(self):
        log.debug('Running start callbacks')
        self.run_callbacks('_start')
        self.run_callbacks('start')

    def run_success_callbacks(self):
        log.debug('Running success callbacks')
        self.run_callbacks('_success')
        self.run_callbacks('success')

    def run_error_callbacks(self):
        log.debug('Running error callbacks')
        self.run_callbacks('_error')
        self.run_callbacks('error')

    def run_callbacks(self, group):
        for cb in self.callbacks[group]:
            cb(self)

    def init_callbacks(self):
        groups = ( 'start', 'success', 'error' )
        self.callbacks = {}

        for g in groups:
            self.callbacks[g]       = []
            self.callbacks['_' + g] = []

        def rename_partfile(dl):
            try:
                import os
                os.rename( dl.local_partfile, dl.local_file )
            except: pass

        def cleanup_status_file(dl):
            dl.cleanup_status_file()

        self.add_callback('_success', rename_partfile)
        self.add_callback('_success', cleanup_status_file)

    def download(self):
        def perform_download(consumer):
            self.consumer = consumer
            self.success  = self.really_download()

        self.wizard.sources(perform_download)

        if self.success:
            self.run_success_callbacks()
            log.info('Finished downloading %s' % self.wizard.file_hint)
        else:
            self.run_error_callbacks()

    def download_command(self):
        return globals()[self.strategy + '_strategy_command'](self)

    def really_download(self):
        from signal import SIGTERM
        import subprocess

        command  = self.download_command()
        piped    = subprocess.Popen(command)
        self.pid = piped.pid

        log.info(command)
        self.run_start_callbacks()
        piped.wait()

        returned = abs(piped.returncode)

        if self.avoid_small:
            status = status_for(self.endpoint, strategy = self.strategy)

            if status.file_too_small():
                returned = 99

        if 0 == returned:
            return True
        elif SIGTERM == returned:
            log.info('SIGTERM received, download will abort')
            self.cleanup()
            return False
        else:
            log.info('%s received, trying next source' % returned)
            self.cleanup()
            raise Exception('cURL returned %s, trying next source.' % returned)

    def cleanup_status_file(self):
        self.attempt_remove(self.status_file)

    def cleanup(self):
        self.cleanup_status_file()
        self.attempt_remove(self.local_file)
        self.attempt_remove(self.local_partfile)

    def attempt_remove(self, f):
        import os
        try:    os.remove(f)
        except: pass
コード例 #56
0
 def test_strike_manna_decrease(self):
     wizard = Wizard('Merlin', 40, 10, 20)
     opponent = Wizard('Oz', 40, 10, 30)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 15)
コード例 #57
0
 def test_strike_less_than_five_manna(self):
     wizard = Wizard("Merlin", 40, 9, 4)
     opponent = Wizard("opi", 40, 10, 20)
     wizard.strike(opponent)
     self.assertEqual(wizard.manna, 4)
     self.assertEqual(opponent.hp, 37)
コード例 #58
0
ファイル: wizard_test.py プロジェクト: Wushaowei001/frankedus
 def test_reduce_manna(self):
     wizard = Wizard('Merlin', 40, 10, 20)
     opponent = Wizard('Other', 30, 5, 10)
     wizard.strike(opponent)
     self.assertEqual(opponent.hp, 0)