def main(): armor_effect = [ArmorEffect('frost'), ArmorEffect('fire')] weapon_effect = [WeaponEffect('frost', 20, 2), WeaponEffect('fire', 1, 2)] temp = [ Warrior('Abe', health=300, weapons=[ Sword(name='Frost Sword', effects=weapon_effect[0]), Sword() ]), Warrior('Bjorn', health=300, weapons=[Sword()], armor=Armor(effects=armor_effect)), Warrior('Sigmair', health=300, weapons=[Sword(), Bow(effects=weapon_effect[1])]) ] while True: if len(temp) > 1: duel = random.sample(temp, 2) if duel[1].health > 0 and duel[0].health > 0: duel[0].attack(duel[1]) print() if duel[1].health == 0: temp.remove(duel[1]) elif len(temp) == 1: break else: print("Недостаточно участников.") break
def console(self): # commands & functions self.switcher = { "load": self.load, "set": self.set, "unset": self.unset, "global": self.setglobal, "show": self.show, "run": self.run, "back": self.back, "warrior": self.warrior, "quit": self.quit, "help": self.help, } # Configuring the commpleter self.comp = Completer([ 'load', 'set', 'unset', 'global', 'show', 'run', 'back', 'warrior', 'quit', 'help' ]) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(self.comp.complete) print(banners.get_banner()) cprint(' [+]', 'yellow', end='') print(' Starting the console...') cprint(' [*]', 'green', end='') print(' Console ready!\n') self.session = None while True: try: if self.session is None: # /* Definitions available for use by readline clients. */ # define RL_PROMPT_START_IGNORE '\001' # define RL_PROMPT_END_IGNORE '\002' user_input = input( '\001\033[1;32m\002iBombShell> \001\033[0m\002').strip( ) else: user_input = input('iBombShell[' + '\001\033[1;32m\002' + self.session.header() + '\001\033[0m\002' + ']> ').strip() if user_input == "": continue else: self.switch(user_input) except KeyboardInterrupt: signal.signal(signal.SIGINT, self.keyboard_interrupt_handler) print("") Warrior.get_instance().kill_warriors() except Exception as e: print_error(e)
def do_GET(self): warrior_path = Config.get_instance().get_warrior_path() + "ibs-" regex = re.findall(r'^(.+)/([^/]+)$', self.path) route = '' try: route = regex[0][0].strip('/') route_id = regex[0][1] except Exception: print_error('Error creating warrior...') a = '' if route == "ibombshell": try: with open('{}{}'.format(warrior_path, route_id), 'r') as f: a = f.read() if a is not '': print("") print_ok('Warrior {} get iBombShell commands...'.format( route_id)) with open('{}{}'.format(warrior_path, route_id), 'w') as f: f.write('') else: Warrior.get_instance().review_status(route_id) except Exception: print_error('Warrior {} don\'t found'.format(route_id), start="\n") self._set_response() #self.wfile.write("GET request for {}".format(self.path).encode('utf-8')) self.wfile.write(a.encode('utf-8'))
def do_GET(self): warrior_path = Config.get_instance().get_warrior_path() + "ibs-" ipSrc = self.client_address[0] #regex = re.findall(r'^(.+)/([^/]+)$', self.path) admin = None os_version = None os_arch = None try: regex = re.findall(r'^(.+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)$', self.path) admin = regex[0][2] os_version = unquote(regex[0][3]).strip("\r\n") os_arch = unquote(regex[0][4]).strip("\r\n") except: regex = re.findall(r'^(.+)/([^/]+)$', self.path) route = '' try: route = regex[0][0] routeId = regex[0][1] except Exception: cprint('\n[!] Error creating warrior...', 'red') a = '' if route == "/ibombshell": try: with open('{}{}'.format(warrior_path, routeId), 'r') as f: a = f.read() if a is not '': cprint( '\n[+] Warrior {} get iBombShell commands...'.format( routeId), 'green') with open('{}{}'.format(warrior_path, routeId), 'w') as f: f.write('') else: Warrior.get_instance().review_status(routeId) except Exception: cprint('\n[!] Warrior {} don\'t found'.format(routeId), 'red') elif route == "/newibombshell": if not Warrior.get_instance().exist_warrior(routeId): with open('{}{}'.format(warrior_path, routeId), 'w') as f: f.write('') is_admin = False if admin and admin == "admin": is_admin = True cprint("\n[+] New warrior {} from {}".format(routeId, ipSrc), 'green') Warrior.get_instance().add_warrior(routeId, ipSrc, is_admin, os_version, os_arch) else: cprint('\n[!] Warrior already exists!', 'red') self._set_response() #self.wfile.write("GET request for {}".format(self.path).encode('utf-8')) self.wfile.write(a.encode('utf-8'))
def __init__(self, charT): if charT == 'H': self.h = Hacker() self.charType = "Hacker" elif charT == 'W': self.h = Warrior() self.charType = "Warrior" self.maxHP = self.h.getHP() self.strength = self.h.getStr() self.defense = self.h.getDef()
def main(): # Create 2 Warriors paul = Warrior("Paul", 50, 30, 10) sam = Warrior("Sam", 50, 30, 10) print(paul) print(sam) # Create Battle object battle1 = battle.Battle() print(battle1) # Initiate Battle battle1.startFight(paul, sam)
def __init__(self, name, img, containers, realSize=cblocals.TILE_IMAGE_SIZE, speed=150., attackTime=0.5, afterAttackRestTime=0.2, weaponInAndOut=False, sightRange=200,): GameSprite.__init__(self, *containers) Stealth.__init__(self) Warrior.__init__(self, attackTime, afterAttackRestTime) self._x = self._y = 0 self.rect = pygame.Rect( (self.x, self.y), (cblocals.TILE_IMAGE_SIZE) ) self.name = name self.characterType = "Guy" self.experienceLevel = 1 self._brain = None self._presentationBrain = PresentationStateMachine(self) self._load_images(img, weaponInAndOut) self.lastUsedImage = 'head_south_1' self._stepTime = 0 self._mustChangeImage = False self.direction = self._lastUsedDirection = cblocals.DIRECTION_S self._isMoving = False self.maxSpeed = self._speed = speed self.sightRange = sightRange self.rest_time_needed = .3 self.side = 'Cheese Boys' self._enemyTarget = None self.navPoint = NavPoint(self) self.heading = None # From where a succesfull attack is coming self.damageHeading = None self.size = realSize self._heatRectData = (5, 5, 10, 15) self.hitPoints = self.hitPointsLeft = 20 self._baseAC = 1 self._th0 = None self._speech = SpeechCloud(self) # *** Pathfinding *** self.pathfinder = None # This is inited only after the call onto addToGameLevel self.afterInit()
def run_module(self): warrior = self.args["warrior"] if(Warrior.get_instance().get_status(warrior) != "Dead"): print("Killing warrior {}".format(warrior)) function = """function quit{ $global:condition = $false } """ function += 'quit' super(CustomModule, self).run(function) else: cprint ('[+] Warrior is dead', 'yellow') Warrior.get_instance().remove_warrior(warrior)
def play(self): """ execute de game :return: """ #generate warrior warrior = Warrior(100, 20, 0) #play till warrior dies while warrior.life_points > 0: #print intro print "\nYou're getting really deep into the cave..." #generate enemy enemy = self.generate_enemy() print "\nA " + enemy.character_type + " appeared!" while True: #select action print "You can:" print " ATTACK " print " RUN " option = raw_input('What do you want to do? ') option = option.upper() if option == "ATTACK": #play till warrior or enemy dies #should add a random system of turns while enemy.life_points > 0 and warrior.life_points > 0: warrior.attack(enemy) if enemy.life_points > 0: enemy.attack(warrior) else: print "You killed a " + enemy.character_type warrior.enemy_counter += 1 break elif option == "RUN": #should add a random system of fails print "You run as fast as you can!" break else: print "Please select a correct option" return warrior.enemy_counter
def __init__(self, level): self.__warrior = Warrior() if level < 10: self.__warrior.set_speed(10) self.__warrior.set_attack(10) self.__warrior.set_defense(10) elif level >= 10 and level < 20: self.__warrior.add_sword() elif level >= 20 and level < 30: self.__warrior.add_sword() self.__warrior.add_armor() elif level >= 30 and level <= 50: self.__warrior.add_sword() self.__warrior.add_armor() self.__warrior.add_boots()
def run(self, function): if Warrior.get_instance().exist_warrior(self.args["warrior"]): with open('{}ibs-{}'.format(self.warrior_path, self.args["warrior"]), 'a') as f: # TODO: Reemplazar la escritura por añadido (append) f.write(function) cprint ('[+] Done!', 'green') else: cprint ('[!] Failed... Warrior don´t found', 'red')
def run(self, function): if not Warrior.get_instance().exist_warrior(self.args["warrior"]): raise Exception('Failed... Warrior don´t found') with open('{}ibs-{}'.format(self.warrior_path, self.args["warrior"]), 'a') as f: # TODO: Reemplazar la escritura por añadido (append) f.write(function) print_ok('Done!')
def check_encounter(self, hero): #randomized value to determine if a user meets a enemy if (randint(0, 100) <= (self.encounter_rate * 100)): #create new enemy and pop a name from the list #if the list is empty then enter the final boss if (len(self.enemy_names) > 0): enemy_temp = self.enemy_names.pop() enemy = None _type = enemy_temp["type"] _name = enemy_temp["name"] if (_type == "warrior"): print("You have encountered {} the warrior".format(_name)) enemy = Warrior(_name, False) elif (_type == "knight"): print("You have encountered {} the knight".format(_name)) enemy = Knight(_name, "", False) elif (_type == "sorceress"): print( "You have encountered {} the sorceress".format(_name)) enemy = Sorceress(_name, False) elif (_type == "theif"): print("You have encountered {} the theif".format(_name)) enemy = Theif(_name, False) for i in range(hero.level + self.level_inc): enemy.level_up() return hero.enter_battle(enemy) else: return self.summon_boss(hero) print("Nothing around here...") return True
class WarriorTest(unittest.TestCase): def setUp(self) -> None: self.warrior = Warrior("male", "elf", "Mae", "ciupaga") def testGenerateCharacter(self): self.assertEqual(self.warrior.equipment, "ciupaga") def testGenerateName(self): self.warrior2 = Warrior(sex="male") name = self.warrior2.generate_name() self.warrior2.name = name self.assertEqual(self.warrior2.name, name) def testTypeName(self): self.warrior3 = Warrior() typing_name = self.warrior3.type_name() self.warrior3.name = typing_name self.assertEqual(self.warrior3.name, typing_name)
def __init__(self): #read name file to load all the names and their types enemies = [] self._file = os.getcwd() + "\\frozen_enemy.txt" enemies = self.read_enemy_file(self._file) Environment.__init__(self, "Frozen Mountains of Absolute Doom", enemies, 0.75, randint(1, 2)) self.boss = Warrior("The Great Ice Giant, Halafor", False) self.boss.hero_stats.hit_points += 250 self.boss.hero_stats.mana_points += 150 self.boss.hero_stats.attack_power += 70 self.boss.hero_stats.defense += 70
def choose_hero(): #Choose your hero print(""" 1. Warrior A hero with great strength and the ability to enhance that strength through anger 2. Knight The noblest of heroes, a true defensive powerhouse, armed with a sheild and healing magic, this hero shines in defense 3. Theif Not the typical hero candidate, but a powerful one nonetheless, with the ability to sneak and deal heavy damage on an opponent of much greater and lesser strength 4. Sorceress A powerful mage hero who's abilities are not limited to their skillset of multiple magic types but the ability to create their own spell with the possibility of dealing huge damage """) choice = 0 while(1): try: choice = int(input("Choose what kind of hero you want to be: ")) if(choice > 0 and choice < 5): name = input("Please enter your name: ") if(choice == 1): #warrior return Warrior(name) break elif(choice == 2): #knight familia = input("As a knight you must have a family name: ") return Knight(name, familia) break elif(choice == 3): #theif return Theif(name) break elif(choice == 4): #sorceress return Sorceress(name) break else: print("Please enter a number between 1 and 4") except ValueError: print("Please enter a whole number")
def getCharacter(): print("Warrior Mage Ranger") character = None answer = raw_input("Answer:") if answer.lower() in ['w','warrior']: character = Warrior() if answer.lower() in ['m','mage']: character = Mage() #Character("mage") if answer.lower() in ['r','ranger']: character = Ranger() #Character("ranger") if answer.lower() in ['quit','q']: sys.exit() return character
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()
def initialize_all(self): print("Welcome to Kafustrok. Light blesses you. ") for i in range(self._DIMENSION): for j in range(self._DIMENSION): self._lands[i][j] = Land() for i in range(self._total_num): pos = self.get_un_occupied_position() if i < self._m: self.lands[pos.x][pos.y].occupied_obj = Monster(pos.x, pos.y, i, self) elif i < self._m + self._e: self.lands[pos.x][pos.y].occupied_obj = Elf(pos.x,pos.y, i - self._m, self) elif i < self._m + self._e + self._w: self.lands[pos.x][pos.y].occupied_obj = Warrior(pos.x, pos.y, i - self._m - self._e, self) self._teleportable_obj.append(self.lands[pos.x][pos.y].occupied_obj) else: self.lands[pos.x][pos.y].occupied_obj = Potion(pos.x, pos.y, i - self._m - self._e - self._w, self) self._teleportable_obj.append(self.lands[pos.x][pos.y].occupied_obj)
def warrior(self, user_input=[]): check_len_2 = (len(user_input) >= 2) if user_input[0] == 'list': Warrior.get_instance().print_warriors() elif user_input[0] == "rename": if not check_len_2: self._raise_exception_specify("warrior") Warrior.get_instance().rename_warrior(user_input[1]) elif user_input[0] == "kill": if not check_len_2: self._raise_exception_specify("warrior") Warrior.get_instance().kill_warrior(user_input[1])
class Game: def __init__(self, player_warrior_name, enemy_warrior_name, health): self.player_warrior = Warrior(player_warrior_name, health) self.enemy_warrior = Warrior(enemy_warrior_name, health) self.max_health = health def start(self): """Game loop. Breaks if player or enemy turn ends in victory""" while True: turn = randint(1, 2) # turn 1 is a player, turn 2 is a enemy if turn == 1: if self.player_turn() == "Win": break elif turn == 2: if self.enemy_turn() == "Win": break def player_turn(self): sleep(2) self.player_warrior.do_random_action(self.enemy_warrior) self.display_fight_status() if self.is_enemy_dead(): print(f"{self.player_warrior.name} победил!") return "Win" elif self.is_enemy_health_low(): self.enemy_warrior.increase_heal_chance() def enemy_turn(self): sleep(2) self.enemy_warrior.do_random_action(self.player_warrior) self.display_fight_status() if self.is_player_dead(): print(f"{self.enemy_warrior.name} победил!") return "Win" def is_player_dead(self): return self.player_warrior.health <= 0 def is_enemy_dead(self): return self.enemy_warrior.health <= 0 def is_enemy_health_low(self): """Checks if health is below 35%""" return self.enemy_warrior.health <= self.max_health * 0.35 def display_fight_status(self): print( f"----- {self.player_warrior.name}: {self.player_warrior.health}, " f"{self.enemy_warrior.name}: {self.enemy_warrior.health} -----", "\n")
def main(): art = Noble("King Arthur") lance = Noble("Lancelot du Lac") jim = Noble("Jim") linus = Noble("Linus Torvalds") billie = Noble("Bill Gates") cheetah = Warrior("Tarzan", 10) wizard = Warrior("Merlin", 15) theGovernator = Warrior("Conan", 12) nimoy = Warrior("Spock", 15) lawless = Warrior("Xena", 20) mrGreen = Warrior("Hulk", 8) dylan = Warrior("Hercules", 3) jim.hire(nimoy) lance.hire(theGovernator) art.hire(wizard) lance.hire(dylan) linus.hire(lawless) billie.hire(mrGreen) art.hire(cheetah) jim.display() lance.display() art.display() linus.display() billie.display() art.fire(cheetah) art.display() art.battle(lance) jim.battle(lance) linus.battle(billie) billie.battle(lance)
from warrior import Warrior class Fight: @staticmethod def start_fight(warrior_1, warrior_2): while warrior_1.hp > 0 and warrior_2.hp > 0: warrior_1.hp = warrior_1.hp - warrior_2.attack() + warrior_1.block() print(f"{warrior_1.name}: {warrior_1.hp}") warrior_2.hp = warrior_2.hp - warrior_1.attack() + warrior_2.block() print(f"{warrior_2.name}: {warrior_2.hp}") if warrior_1.hp <= 0: return warrior_2.name elif warrior_2.hp <= 0: return warrior_1.name warrior_kratos = Warrior("Kratos",100, 10) warrior_subzero = Warrior("Subzero",100, 10) winner = Fight.start_fight(warrior_kratos,warrior_subzero) print(f"{winner} has won!")
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()
def create_ogre(): # strong but clumsy ogre = Warrior('Ogre', 150, 80, 20, 40) return ogre
def create_goblin(): # agile but weak goblin = Warrior('Goblin', 70, 30, 90, 60) return goblin
def complete_set_warrior(self, args): warriors = list(Warrior.get_instance().get_warriors().keys()) return [ warrior + ' ' for warrior in warriors if (warrior.startswith(args[1].strip(" ")) and warrior != args[1]) ]
def create_dragon(): # the killer dragon = Warrior('Dragon', 300, 150, 10, 10) return dragon
def create_knight(): # the basic class knight = Warrior('Knight', 100, 40, 70, 50) return knight
Classes and Inheritance in python Created on Tue Apr 2 14:53:55 2019 2 @author: Tyler Steele """ from warrior import Warrior from knight import Knight from sorceress import Sorceress """ Example Scenario """ # Create 3 characters player = Warrior('Tyler') ally = Knight('Lancelot') enemy = Sorceress('Witch') # Display beginning stats player.display_stats() enemy.display_stats() ally.display_stats() player.reckless_strike(enemy) ally.critical_strike(enemy) # Display stats after physical attacks player.display_stats() enemy.display_stats() ally.display_stats()
def __init__(self): self.warrior1 = Warrior() self.warrior2 = Warrior() self.odds1, self.odds2 = self._genOdds(self.warrior1,self.warrior2) self.announcer = Announcer()
class Battle: def __init__(self): self.warrior1 = Warrior() self.warrior2 = Warrior() self.odds1, self.odds2 = self._genOdds(self.warrior1,self.warrior2) self.announcer = Announcer() def _genOdds(self,warrior1,warrior2): """This helper function will determine the odds of each warrior winning based on the stats and equipment value of each warrior.""" war1val = warrior1.getStats() + warrior1.getDamStat() + warrior1.getDefValue() war2val = warrior2.getStats() + warrior2.getDamStat() + warrior2.getDefValue() totodds = war1val + war2val return int((float(war1val)/totodds)*10), 10 - int((float(war2val)/totodds)*10) def getOdds(self, warrior): if warrior == self.warrior1: return self.odds1 else: return self.odds2 def battle(self): """This method sets up the battle then calls the turn method to determine the outcome of each round and then update the warriors.""" while self.warrior1.getHP() > 0 and self.warrior2.getHP() > 0: self.fightRound(self.warrior1,self.warrior2) if self.warrior1.getHP() <= 0: return self.warrior2.getName(), self.odds2 elif self.warrior2.getHP() <= 0: return self.warrior2.getName(), self.odds1 def fightRound(self,warrior1,warrior2): """This method will simulate one round of combat by checking which warrior has higher dexterity, then seeing who got damaged how much.""" if warrior1.getDex() > warrior2.getDex(): self._simHit(warrior1,warrior2) if warrior2.getHP() <= 0: print print self.announcer.getDead(warrior2) return warrior1.getName(),self.odds1 raw_input("\nPush <Enter> to continue.") else: self._simHit(warrior2,warrior1) if warrior1.getHP() <= 0: print print self.announcer.getDead(warrior1) return warrior2.getName(),self.odds2 raw_input("\nPush <Enter> to continue.") else: self._simHit(warrior2,warrior1) if warrior1.getHP() <= 0: print print self.announcer.getDead(warrior1) return warrior2.getName(),self.odds2 raw_input("\nPush <Enter> to continue.") else: self._simHit(warrior1,warrior2) if warrior2.getHP() <= 0: print print self.announcer.getDead(warrior2) return warrior1.getName(), self.odds1 raw_input("\nPush <Enter> to continue.") def _simHit(self,warrior1,warrior2): """Helper function to determine who hits first and how much damage they do. Critical hits and dodges occur when a 20 is rolled.""" aroll, droll = randrange(1,21) + (warrior1.getDex() * .5), randrange(1,21) + (warrior2.getDex() * .5) if aroll >= 20 or droll >= 20: if aroll >= 20 and droll != 20: if warrior1.getDex() > warrior1.getStr(): try: warrior2.updateHP(warrior1.getDamStat() * randrange(2,(int(warrior1.getDex()*.4)))) except ValueError: warrior2.updateHP(warrior1.getDamStat()*2) print print self.announcer.getCriticalHit(warrior1,warrior2) raw_input("\nPush <Enter> to continue.") else: try: warrior2.updateHP(warrior1.getDamStat() * randrange(2,(int(warrior1.getDex()*.4)))) except ValueError: warrior2.updateHP(warrior1.getDamStat()*2) print print self.announcer.getCriticalHit(warrior1,warrior2) raw_input("\nPush <Enter> to continue.") elif droll >= 20 and aroll != 20: warrior2.updateHP(0) print print self.announcer.getCriticalDodge(warrior1,warrior2) raw_input("\nPush <Enter> to continue.") else: warrior1.updateHP(int(warrior2.getDamStat()*.2)) warrior2.updateHP(int(warrior1.getDamStat()*.2)) print print self.announcer.getCriticalBoth() raw_input("\nPush <Enter> to continue.") elif aroll > droll: if warrior1.getDex() > warrior1.getStr(): try: warrior2.updateHP(warrior1.getDamStat() * randrange(0,int(warrior1.getDex()*.2)) - randrange(0,int(warrior2.getDefValue()))) except ValueError: warrior2.updateHP(warrior1.getDamStat() - randrange(0,1 + int(warrior2.getDefValue()))) print print self.announcer.getHit(warrior1,warrior2) raw_input("\nPush <Enter> to continue.") else: try: warrior2.updateHP(warrior1.getDamStat() * randrange(0,int(warrior1.getStr()*.2 - randrange(0,int(warrior2.getDefValue()))))) except ValueError: warrior2.updateHP(warrior1.getDamStat() - randrange(0,1 + int(warrior2.getDefValue()))) print print self.announcer.getHit(warrior1,warrior2) raw_input("\nPush <Enter> to continue.") else: print print self.announcer.getDodge(warrior1,warrior2) raw_input("\nPush <Enter> to continue.")
def console(): # Configuring the commpleter comp = Completer([ 'load', 'set', 'unset', 'show', 'run', 'back', 'warrior', 'quit', 'help' ]) readline.set_completer_delims(' \t\n;') readline.parse_and_bind("tab: complete") readline.set_completer(comp.complete) print(banners.get_banner()) cprint(' [+]', 'yellow', end='') print(' Starting the console...') cprint(' [*]', 'green', end='') print(' Console ready!\n') session = None while True: try: if session is None: # With termcolor not work colors # user_input = input( # colored('iBombShell> ', 'green', attrs=['bold'])).split() # /* Definitions available for use by readline clients. */ # define RL_PROMPT_START_IGNORE '\001' # define RL_PROMPT_END_IGNORE '\002' user_input = input( '\001\033[1;32m\002iBombShell> \001\033[0m\002').split() else: # user_input = input( # "iBombShell[" # + colored(session.header(), 'green', attrs=['bold']) # + "]> ").split() user_input = input('iBombShell[' + '\001\033[1;32m\002' + session.header() + '\001\033[0m\002' + ']> ').split() if user_input == []: continue elif user_input[0] in CLEAR_COMMANDS: os.system('cls' if os.name == 'nt' else 'clear') elif user_input[0] == 'help': print_help() elif user_input[0] == 'back': session = None elif user_input[0] == 'warrior' and len(user_input) >= 2: if user_input[1] == 'list': Warrior.get_instance().print_warriors() elif user_input[1] == "rename": if len(user_input) > 2: Warrior.get_instance().rename_warrior(user_input[2]) else: raise Exception("Specify the warrior") elif user_input[1] == "kill": if len(user_input) > 2: Warrior.get_instance().kill_warrior(user_input[2]) else: raise Exception("Specify the warrior") elif user_input[0] in END_COMMANDS: Warrior.get_instance().kill_warriors() elif user_input[0] == 'load': if (len(user_input) == 1): print_load_module() continue session = Session(user_input[1]) # The module is incorrect if not (session.correct_module()): cprint('[!] Invalid module', 'red') session = None else: comp.set_commands_to_set(session.get_options_name()) elif user_input[0] == 'show': if session is None: print_load_module() continue session.show() elif user_input[0] == 'set': if session is None: print_load_module() continue else: value = ' '.join([str(x) for x in user_input[2:]]) session.set(user_input[1], value) elif user_input[0] == 'unset': if session is None: print_load_module() continue else: session.unset(user_input[1]) elif user_input[0] == 'run': if session is None: print_load_module() continue session.run() else: cprint('[!] Command not found', 'red') except KeyboardInterrupt: print("") Warrior.get_instance().kill_warriors() except Exception as e: cprint(e, "red")
def enter(): game_world.clear() global UI global HP_BAR UI = load_image('Images//status_pane.png') HP_BAR = load_image('Images//hp_bar.png') global charImage charImage = load_image('Images//warriorLR.png') global font font = load_image('Images//font2x.png') global eatSound eatSound = load_wav('Sounds//snd_item.wav') global lvlUpSound lvlUpSound = load_wav('Sounds//snd_levelup.wav') lvlUpSound.set_volume(64) global bgm bgm = load_music('Sounds//game.mp3') bgm.set_volume(128) bgm.repeat_play() global maps maps = map.Map(1) game_world.add_object(maps, 0) global floorTriggers floorTriggers = floorTrigger.FloorTrigger(18 * 32, 6 * 32) floorTriggers.set_background(maps) game_world.add_object(floorTriggers, 1) global monsters monsters = [] # monster = Monster(176, 240) # monster2 = Monster(240, 240) # spawn in 240, 240 n = 0 while n < 12: t = random.randint(0, 1) mx = random.randint(0, map.tileX - 1) my = random.randint(0, map.tileY - 1) if map.map1[my][mx] == 2: n += 1 if t == 0: monsters.append(Monster(mx * 32 + 16, my * 32 + 16)) else: monsters.append(Scorpio(mx * 32 + 16, my * 32 + 16)) game_world.add_objects(monsters, 1) global items items = [] game_world.add_objects(items, 1) # game_world.add_object(monster, 1) # game_world.add_object(monster2, 1) global warrior warrior = Warrior() game_world.add_object(warrior, 1) global once once = Once() maps.set_center_object(warrior) warrior.set_background(maps) for monster in monsters: monster.set_background(maps)
class LeveledWarrior(object): def __init__(self, level): self.__warrior = Warrior() if level < 10: self.__warrior.set_speed(10) self.__warrior.set_attack(10) self.__warrior.set_defense(10) elif level >= 10 and level < 20: self.__warrior.add_sword() elif level >= 20 and level < 30: self.__warrior.add_sword() self.__warrior.add_armor() elif level >= 30 and level <= 50: self.__warrior.add_sword() self.__warrior.add_armor() self.__warrior.add_boots() def fight(self): self.__warrior.fight() def defense(self): self.__warrior.defense() def move(self): self.__warrior.move()
from warrior import Warrior from Weapon import Weapon from Shield import Shield import random name1 = "The best of the best" name2 = "Superhero" warrior1 = Warrior(name1, 100, Weapon("hero's weapon", 50, 50), Shield("hero's shield", 70, (10, 20))) warrior2 = Warrior(name2, 100, Weapon("superhero's weapon", 50, 50), Shield("superhero's shield", 70, (10, 20))) anyoneAlive = True while anyoneAlive: prHp = warrior2.GetHp() anyoneAlive = not warrior1.Attack(warrior2) nowHp = warrior2.GetHp() print(name1 + " нанес удар в размере " + str(prHp - nowHp)) if (not anyoneAlive): break prHp = warrior1.GetHp() anyoneAlive = not warrior2.Attack(warrior1) nowHp = warrior1.GetHp() print(name2 + " нанес удар в размере " + str(prHp - nowHp)) if (warrior1.GetHp() <= 0): print(name2 + " победил!") else: print(name1 + " победил!")