示例#1
0
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)
示例#2
0
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
示例#3
0
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)
示例#4
0
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)
示例#5
0
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
示例#6
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")
示例#7
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()
示例#8
0
    def __init__(self):
        self.creatures = [
            Creature("Toad", 1),
            Creature("Frog", 3),
            Dragon("Dragon", 50),
            Creature("Lion", 10)
        ]

        self.wizard = Wizard('Gandolf', 30)
示例#9
0
    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()
示例#10
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
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)
示例#12
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)
示例#13
0
    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)
示例#14
0
def test_set_wrong_value_type():
    wizard_dict = WizardDictionary()
    merlin = Wizard("Merlin",
                    {Magic.illusionism, Magic.mentalism, Magic.gomancery})
    with pytest.raises(TypeError):
        wizard_dict[merlin] = "Artur"
示例#15
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()
示例#16
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.'
        })
示例#17
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)

 
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()
示例#19
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")
示例#20
0
def test_contains():
    merlin = Wizard("Merlin")
    arthur = Apprentice("Arthur")
    wizards = WizardDictionary({merlin: arthur})
    assert merlin in wizards
示例#21
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.")
示例#22
0
def test_non_existing_wizard():
    wizard = Wizard("Magicni")
    wizdict = WizardDictionary()
    with pytest.raises(KeyError):
        wizdict[wizard]
示例#23
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()
示例#24
0
def test_get_value():
    merlin = Wizard("Merlin")
    arthur = Apprentice("Arthur")
    wizards = WizardDictionary({merlin: arthur})
    assert wizards.get_value(merlin) == arthur
示例#25
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!")
示例#26
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))
示例#27
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))
示例#28
0
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
示例#29
0
def test_one():
    merlin = Wizard("Merlin")
    arthur = Apprentice("Arthur")
    wizard_dict = WizardDictionary()
    wizard_dict._wizdic = {merlin: arthur}
    assert len(wizard_dict) == 1
示例#30
0
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!")