def setup(self): self.dungeon = Dungeon("map.txt") self.hero = Hero("Geralt", "white wolf", 150, 150, 5) self.hero.equip(Weapon("Sword", 30)) self.hero.learn(Spell("wolf's attack", 20, 20, 2)) self.dungeon.spawn(self.hero) self.command = None
def test_hero_ability_attack_mean_value(): athena = Hero("Athena") strength = random.randint(10, 30000) big_strength = Ability("Overwhelming Strength", strength) athena.add_ability(big_strength) calculated_mean = strength // 2 iterations = 6000 accepted_window = 400 total_attack = 0 for _ in range(iterations): attack_value = athena.attack() assert attack_value >= 0 and attack_value <= strength total_attack += attack_value actual_mean = total_attack / iterations print("Max Allowed Damage: {}".format(strength)) print("Attacks Tested: {}".format(iterations)) print("Mean -- calculated: {} | actual: {}".format(calculated_mean, actual_mean)) print("Acceptable Distance from Mean: {} | Average distance from mean: {}". format(accepted_window, abs(calculated_mean - actual_mean))) print("Acceptable min attack: {} | Acceptable max attack: {}".format( actual_mean - accepted_window, actual_mean + accepted_window)) assert actual_mean <= calculated_mean + accepted_window and actual_mean >= calculated_mean - accepted_window
def test_hero_weapon_attack_mean_value(): kkrunch = Hero("Kaptain Krunch") strength = random.randint(10, 30000) min_attack = strength // 2 big_strength = Weapon("Sword of Whimsy", strength) kkrunch.add_ability(big_strength) calculated_mean = (strength - min_attack) // 2 + min_attack accepted_window = 400 iterations = 6000 sum_of_sqr = 0 total_attack = 0 for _ in range(iterations): attack_value = kkrunch.attack() assert attack_value >= min_attack and attack_value <= strength total_attack += attack_value deviation = attack_value - calculated_mean sum_of_sqr += deviation * deviation actual_mean = total_attack / iterations print("Max Allowed Damage: {}".format(strength)) print("Attacks Tested: {}".format(iterations)) print("Mean -- calculated: {} | actual: {}".format(calculated_mean, actual_mean)) print("Acceptable Min: {} | Acceptable Max: {}".format( actual_mean - accepted_window, actual_mean + accepted_window)) print("Tested Result: {}".format(actual_mean)) assert actual_mean <= calculated_mean + accepted_window assert actual_mean >= calculated_mean - accepted_window
def setUp(self): self.hero = Hero("Gosho", 30, "Goshko") self.orc = Orc("Pesho", 100, 1.3) self.fight = Fight(self.hero, self.orc) self.weapon = Weapon("qax", 40, 0.3) self.hero.weapon = self.weapon self.orc.weapon = self.weapon
def mainPane(self): locations = ["Tavern", "Shop", "Forest", "Inn", "Castle"] character_approval = False while character_approval != True: hero = Hero(Weapon().generate_weapon()) print("Your character is " + hero.char.name + "\nEquipped with a " + hero.get_weapon().name + " that does " + str(hero.get_weapon().low_damage) + "-" + str(hero.get_weapon().high_damage) + " damage.") char_generation = input("Do you approve of this character: ") if "Y" in char_generation.upper(): character_approval = True while True: print("\nLocations: ") counter = 1 for i in locations: print(str(counter) + ". " + i) counter += 1 location_choice = input("Where would you like to go: ") if int(location_choice) is 1: Tavern(hero) if int(location_choice) is 2: Shop(hero) if int(location_choice) is 3: forest = Forest() forest.entry(hero) if int(location_choice) is 4: hotel = Inn(hero) if int(location_choice) is 5: Castle(hero) input()
def Parser(self, text): Text = text # Within 120 seconds on the game if self.hero1 == None: self.BTNnode.detachNode() if Text == "-random": self.hero1 = Hero(random.randint(0, 96)) elif Text == "-random int": self.hero1 = Hero(random.randint(66, 96)) elif Text == "-random str": self.hero1 = Hero(random.randint(0, 36)) elif Text == "-random agi": self.hero1 == Hero(random.randint(36, 66)) if Text == "-repick": if self.rindex == False: if self.hero1 != None: self.hero1.destroy() self.hero1 = None self.index = -1 self.chooseHero() self.rindex = True else: Error("Cannot Repick") elif Text == "-": pass else: pass
def lets_play(): command_list = [{ 'w': 'up', 's': 'down', 'a': 'left', 'd': 'right' }, 'f', 'spawn', 'status', 'u', 'p'] print('\nLets play a game!\n ') name = input('Write a name for your hero: ') title = input('How is your hero known as: ') h = Hero(name=name, title=title, health=100, mana=100, mana_regeneration_rate=2) name = input('Give a name to your weapon: ') w = Weapon(name=name, damage=20) h.equip(w) print('\n{} will fight with {} to save The Princess!\n'.format( h.known_as(), w.name)) input('Press enter to start the game!') map = Dungeon("level1.txt") map.spawn(h) map.print_map() input_data = input( "\nType w/s/a/d to move your hero up/down/left/right\ , f for fight, spawn for spawn, status to show hero's status, u for update spell/weapon or e for exitd: " ) while (input_data != 'e'): if input_data in command_list[0].keys(): map.move_hero(command_list[0][input_data]) map.print_map() elif input_data == command_list[1]: map.hero_attack() map.print_map() elif input_data == command_list[2]: map.spawn(h) map.print_map() elif input_data == command_list[3]: print('\n', h, h.weapon, h.spell) elif input_data == command_list[4]: which = input('Type spell/weapon: ') print( 'Are you sure. You have {} and the update is 20. Type y or n:' .format(map.hero.money)) result = input() if result == 'y': map.hero.update(which) else: print('Update not successful') elif input_data == 'm': print("\nType w/s/a/d to move your hero up/down/left/right\ , f for fight, spawn for spawn, status to show hero's status, u for update spell/weapon or e for exit" ) else: print('Comming soon!') print('Type m to see the curret command menu.') print('\n') input_data = input('Command: ')
def treat_click(self): #funcao que trata o evento de quando o rato e clicado pos = pygame.mouse.get_pos() #verifica se novo jogo e caregado if self.mouse_click(pos, self.menu_list[0][3][0], self.menu_list[0][3][1], self.menu_list[0][2][0], self.menu_list[0][2][1]): self.click_sound() Hero_ship = Hero(30, self.Hero_speed, self.HeroX_Initial, self.HeroY_Initial, "art/HeroShips/heroship_level1.png") level = NewLevels(Hero_ship, self.screen , self.CUSTOMEVENT, self.SPANEVENT, self.ScoreBoard) level.run_game() #verifica se Gode Mode e carregado elif self.mouse_click(pos, self.menu_list[1][3][0], self.menu_list[1][3][1], self.menu_list[1][2][0], self.menu_list[1][2][1]): self.click_sound() Hero_ship = Hero(25, self.Hero_speed, self.HeroX_Initial, self.HeroY_Initial, "art/HeroShips/heroship_level1.png") level = NewLevels(Hero_ship, self.screen , self.CUSTOMEVENT, self.SPANEVENT, self.ScoreBoard) Hero_ship.god_mode = True level.run_game() #verifica se Exit e carregado elif self.mouse_click(pos, self.menu_list[2][3][0], self.menu_list[2][3][1], self.menu_list[2][2][0], self.menu_list[2][2][1]): self.click_sound() pygame.quit() sys.exit()
def __init__(self): # 初始化pygame pygame.init() self.setting = Setting() self.offset = {pygame.K_LEFT: 0, pygame.K_RIGHT: 0, pygame.K_UP: 0, pygame.K_DOWN: 0} # 初始化游戏 self.screen = pygame.display.set_mode(self.setting.windows) # 初始化一个用于显示的窗口 pygame.display.set_caption('This is my first pygame-program') # 设置窗口标题 self.background = pygame.image.load('image/background.jpg') self.feiji = pygame.image.load('image/fj.png') self.bullet = pygame.image.load('image/bullet.png') self.enemy_img = pygame.image.load('image/enemy.png') self.gameover_img = pygame.image.load('image/gameover.jpg') self.pass_img = pygame.image.load('image/pass.jpg') # 创建敌人组 self.enemy_group = pygame.sprite.Group() # 创建击毁敌人组 self.enemy_down_group = pygame.sprite.Group() # 飞机出事位置 feiji_pos = [(self.setting.windows[0] - self.feiji.get_rect().width) / 2, self.setting.windows[1] - 100] # 飞机对象 self.heros = Hero(self.feiji, feiji_pos) # 限制游戏帧数 self.clock = pygame.time.Clock() # 重绘次数 self.ticks = 0 # 分数 self.makes = 0 # 最高分数 self.makesMax = 99999
def test_attack_with_spell_if_hero__doesnt_know_spell(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) self.assertEqual(h.attack(by='magic'), 0)
def test_get_mana(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) self.assertEqual(h.get_mana(), 100)
def test_is_alive_if_not_alive(self): h = Hero(name="Bron", title="Dragonslayer", health=0, mana=100, mana_regeneration_rate=2) self.assertFalse(h.is_alive())
class TestHero(unittest.TestCase): '''Class level Docstring: Ensures reliability of Hero class.''' def setUp(self): self.m = Hero("SkonadloneS") self.n = Bokoblin("Gary") def tearDown(self): del self.m, self.n #Hero Attack testing- basic, defense, special def test_basic_attack(self): m.basic_attack(n) self.assertEqual() def test_defense_attack(self): m.defense_attack(n) self.assertEqual() def test_special_attack(self): m.special_attack(n) self.assertEqual() #attack name tests def test_basic_name(self): self.assertEqual(self.m.basic_name(), "Used the Master Sword") def test_defense_name(self): self.assertEqual(self.m.defense_name(), "Shield strike") def test_special_name(self): self.assertEqual(self.m.special_name(), "Used a bomb")
def test_can_cast_if_no_enough_mana(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=0, mana_regeneration_rate=2) self.assertFalse(h.can_cast())
def test_hero_attack_weapon(): big_strength = Ability("Overwhelming Strength", 200) Athena = Hero("Athena") Athena.add_ability(big_strength) test_runs = 100 for _ in range(0, test_runs): attack = big_strength.attack() assert attack <= 200 and attack >= 0
def create_player(): ''' returns default player named link if the user didnt enter anything in prompt. ''' player_name = input("Enter your name(default = Link): ") return Hero("link") if player_name in ("", " ", "\n", " \n") else Hero(player_name)
def test_attack_with_weapon_if_hero_doesnt_have_weapon(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) damage = h.attack(by='weapon') self.assertEqual(damage, 0)
def test_take_healing_and_overflow_max(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) h.take_healing(50) self.assertEqual(h.health, 100)
def test_attack_without_weapon_or_spell(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) damage = h.attack() self.assertEqual(damage, 0)
def test_take_damage_and_die(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) h.take_damage(120) self.assertEqual(h.health, 0)
def test_equip_weapon(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) wpn = Weapon('sword', 20) h.equip(wpn) self.assertEqual(h.equiped, wpn)
def test_known_as(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) expected = 'Bron the Dragonslayer' returned = h.known_as() self.assertEqual(returned, expected)
def test_hero_add_ability(): big_strength = Ability("Overwhelming Strength", 300) Athena = Hero("Athena") assert len(Athena.abilities) == 0 Athena.add_ability(big_strength) assert len(Athena.abilities) == 1 # Check for correct type assert "Ability" in str(Athena.abilities[0]) assert Athena.abilities[0].name == "Overwhelming Strength"
def test_can_cast_if_possible(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) spell = Spell('abra kadabra', 30, 20, 2) h.learn(spell) self.assertTrue(h.can_cast())
def test_take_healing_but_not_reach_max(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) h.health = 10 h.take_healing(70) self.assertEqual(h.health, 80)
def test_learn_spell(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) spell = Spell('abra kadabra', 30, 20, 2) h.learn(spell) self.assertEqual(h.spell, spell)
def setUp(self): self.hero1 = Hero() self.weapon1 = Weapon() self.spell1 = Spell() self.dead_hero = Hero() self.dead_hero.current_health = 0 self.dead_hero.current_mana = 0 self.injured_hero = Hero() self.injured_hero.current_health = 10 self.injured_hero.current_mana = 10
def test_that_zone_save_changes_does_not_overwrite_hero(self): from Hero import Hero id = dbHelp.create_test_hero_using_test_values() h = Hero.construct_model_from_pk(id) h.zone.maxMonsters = 1000 h.zone.save_changes(id) self.assertNotIn(ZoneDBFields.MAX_MONSTERS,h.dict) h2 = Hero.construct_model_from_pk(id) self.assertNotIn(ZoneDBFields.MAX_MONSTERS,h2.dict)
def test_that_zone_save_changes_does_not_overwrite_hero(self): from Hero import Hero id = dbHelp.create_test_hero_using_test_values() h = Hero.construct_model_from_pk(id) h.zone.maxMonsters = 1000 h.zone.save_changes(id) self.assertNotIn(ZoneDBFields.MAX_MONSTERS, h.dict) h2 = Hero.construct_model_from_pk(id) self.assertNotIn(ZoneDBFields.MAX_MONSTERS, h2.dict)
def test_if_hero_save_saves_zone(self): tmpSave = Zone.save_changes Zone.save_changes = lambda s,h: 0 id = dbHelp.create_test_hero_using_test_values() h = Hero.construct_model_from_pk(id) h.zone.maxMonsters = 100 h.save_changes() h2 = Hero.construct_model_from_pk(id) self.assertNotEqual(h2.zone.maxMonsters,100) Zone.save_changes = tmpSave
def test_print_heroes(): team = Team("One") jodie = Hero("Jodie Foster") team.add_hero(jodie) athena = Hero("Athena") team.add_hero(athena) output_string = capture_console_output(team.view_all_heroes) assert "Jodie Foster" in output_string assert "Athena" in output_string
def test_attack_with_spell_if_hero_knows_spell_and_has_enough_mana(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) spell = Spell('abra kadabra', 30, 20, 2) h.learn(spell) damage = h.attack(by='magic') self.assertEqual(damage, 30)
def test_attack_with_weapon_if_hero_has_weapon(self): h = Hero(name="Bron", title="Dragonslayer", health=100, mana=100, mana_regeneration_rate=2) wpn = Weapon('sword', 20) h.equip(wpn) damage = h.attack(by='weapon') self.assertEqual(damage, 20)
def test_zone_on_hero_from_db(self): from AllDBFields import ZoneDefinitionFields pk = dbtestHelp.create_test_hero_using_test_values() hero = Hero.construct_model_from_pk(pk) hero.zone = dbtestHelp.create_test_zone_obj() self.assertEqual(hero.zone.definitionKey, ZoneDefinitionFields.EMPTY_SPACE) hero.save_changes() hero2 = Hero.construct_model_from_pk(pk) self.assertEqual(hero2.zone.definitionKey, ZoneDefinitionFields.EMPTY_SPACE)
def action_reroll(self): if self.hero and self.hero.alive: response = { 'message': self.get_text('noreroll') % self.hero.get_attributes(), 'success': 0, } return response else: # Clear all old level data. self._dh.clear_levels() # Reroll new hero. #logging.info('Rerolling hero.') #logging.info(self._gamedata['hero']) self.hero = Hero(self._gamedata['hero']) self.hero.reroll() self.level = self.get_level(self.hero.level) attribs = self.hero.get_attributes() self.save_data() msg = self.get_text('newhero') try: msg = msg % attribs except KeyError, e: #print "Key not found in hero attribs:", e, attribs logging.error("Couldn't find a given text replacement: %s" % str(e)) if self.level._text: msg = "%s %s" % (msg, self.level._text) response = { 'message': msg, 'data': { 'hero': attribs, } } return response
def setUp(self): self.pudge = Hero() self.magic = Spell(mana_cost=5, damage=33) self.sword = Weapon(damage=30) self.pudge.learn(self.magic) self.pudge.equip(self.sword) self.battle = Fight(self.pudge, (4, 6), (4, 5), 'walk')
def insert_new_user(login,pw,shipName=""): """ This used during the create new user process saves a new user to the database args: login: unique email address supplied by the user pw: password supplied by the user. shipName: The space ship name is supplied by the user. Not required but lame if not there. returns: a tuple containing the primary key of the newly inserted user from the User table, the primary key of the account created for the new user, and the primary key of the hero created for the new user. """ from Account import Account from Hero import Hero if is_login_taken(login): raise FileExistsError("That email is already taken") loginPk = safe_insert_new_user(login,pw) accountId = Account.create_new_account_in_db(loginPk) heroId = Hero.construct_new_hero_in_db(accountId,shipName) return (loginPk,accountId,heroId)
def test_get_heroPk_by_accountPk(self): from Account import Account from Hero import Hero pk = dbHelp.create_login_using_test_values() accntPk = Account.create_new_account_in_db(pk) hPk = Hero.construct_new_hero_in_db(accntPk) rPk = auth.get_heroPk_by_accountPk(accntPk) self.assertEqual(hPk,rPk)
class TestFight(unittest.TestCase): def setUp(self): self.hero = Hero("Gosho", 30, "Goshko") self.orc = Orc("Pesho", 100, 1.3) self.fight = Fight(self.hero, self.orc) self.weapon = Weapon("qax", 40, 0.3) self.hero.weapon = self.weapon self.orc.weapon = self.weapon def test_simulate_fight(self): self.fight.simulate_fight() self.assertFalse(self.orc.is_alive() and self.hero.is_alive()) def test_simulate_fight_orc_no_weapon(self): self.fight.simulate_fight() self.orc.weapon = None self.assertFalse(self.orc.is_alive() and self.hero.is_alive())
class HeroTest(unittest.TestCase): def setUp(self): self.hero = Hero(10, 0) def test_hero_default(self): self.assertEqual( (self.hero.health, self.hero.magic, self.hero.x, self.hero.y), (10, 0, None, None)) def test_setHealth(self): self.hero.setHealth(-1) self.assertEqual(self.hero.health, 0) self.hero.setHealth(5) self.assertEqual(self.hero.health, 5)
def setUp(self): self.name = 'Rado' self.title = 'RadoRado' self.health = 70 self.mana = 80 self.mana_regen_rate = 15 self.hero = Hero( self.name, self.title, self.health, self.mana, self.mana_regen_rate ) self.spell = Spell('Kodene', 23, 30, 2) self.weapon = Weapon('AXE', 23)
def __init__(self, recall_string=None, name_entry_cb=None): GameEngineElement.__init__(self) self.name = "" self.dungeon_id = "al1.txt" self.position = (-1, -1) self.playerFacing = NORTH self.hero = Hero() # 4 types of stats and difficulties self.problem_stats = {} self.difficulty = {} for stat in ["mult", "div", "geo", "shop"]: # Each type of stat has 3 "levels" easy, medium, hard # Shop uses level for too much, too little, exact self.problem_stats[stat] = [(0, 0), (0, 0), (0, 0)] # Difficulty: 1=Easy 2=Meduim(default) 3=Hard self.difficulty[stat] = 2 self.puzzlesSolved = 0 self.inventory = [] bg = pygame.image.load(MENU_PATH + "mafh_splash.gif").convert() self.background = DrawableObject([bg], "") self.background.scale(self.game_engine.width, self.game_engine.height) self.add_to_scene([self.background]) # create background rect draw_width = self.game_engine.width / 4 draw_height = self.game_engine.height / 4 surf = pygame.Surface((draw_width + 60, draw_height + 60)) surf.fill((150, 150, 255)) self.blueRect = DrawableObject([surf], "") self.add_to_scene([self.blueRect]) font = pygame.font.Font(None, 16) self.text_list = [] self.text_list.append(DrawableFontObject("1", font)) self.text_list.append(DrawableFontObject("2", font)) self.text_list.append(DrawableFontObject("name", font)) self.add_to_scene(self.text_list) if recall_string: self.load_from_json_string(recall_string) if self.name == "": self.name_cb = name_entry_cb self.add_to_engine()
class TestFight(unittest.TestCase): def setUp(self): self.pudge = Hero() self.magic = Spell(mana_cost=5, damage=33) self.sword = Weapon(damage=30) self.pudge.learn(self.magic) self.pudge.equip(self.sword) self.battle = Fight(self.pudge, (4, 6), (4, 5), 'walk') def test_direct_and_dist(self): direct_and_dist = self.battle.find_direct_and_dist() self.assertEqual(direct_and_dist[0], 'right') self.assertEqual(direct_and_dist[1], 1) def test_is_spell_more_eq_dmg(self): self.assertTrue(self.battle.is_spell_more_eq_dmg()) def test_fight_scenario(self): self.assertTrue(self.battle.fight_scenario()) print (self.battle) def test_combat_logg(self): pass
def check_in_and_get_notices(heroPk,accountPk,checkinTimeUtc,utcOffset): """ this should be called on page load and should be used to get any notices for the use args: heroPk: we want a pymongo objectId for the hero table accountPk: we want a pymongo objectId for the hero table checkinTimeUtc: this needs to be that the user check in and it needs to be utc utcOffset: the time-zone offset from UTC, in minutes, for the current locale. returns: we return a dict with two elements: 'story' which will be a list of huge things of text and 'zoneChoice' which is a list of dicts each of which contain 'zonePk','description' but zoneChoice may be none. """ from Hero import Hero from Account import Account hero = Hero.construct_model_from_pk(heroPk) account = Account.construct_model_from_pk(accountPk) lastCheckinTime = account.lastCheckInTime account.lastCheckInTime = checkinTimeUtc account.save_changes() if not lastCheckinTime: messages = build_first_time_checkin_messages(hero) hero.save_changes() return messages if hero.isInZoneLimbo: autoPickedZoneDict = random.choice(hero.zone.nextZoneReferenceList) hero.zone = Zone.construct_model_from_dict(autoPickedZoneDict) hero.monster = Monster.construct_new_monster(hero.zone.definitionKey,hero.zone.lvl) timeDiffInDays = (checkinTimeUtc - lastCheckinTime)/(60*60*24) if timeDiffInDays >= 1: pass
def test_save_counts(self): hDict = dbHelp.create_test_hero_dict() h = Hero.construct_model_from_dict(hDict) oldHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME) oldZoneCOunt = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME) h.save_changes() newHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME) newZoneCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME) self.assertEqual(oldHeroCount+1,newHeroCount) self.assertEqual(oldZoneCOunt+1,newZoneCount) oldHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME) oldZoneCOunt = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME) h.save_changes() newHeroCount = tu.get_record_count_from_table(HeroDbFields.COLLECTION_NAME) newZoneCount = tu.get_record_count_from_table(ZoneDBFields.COLLECTION_NAME) self.assertEqual(oldHeroCount,newHeroCount) self.assertEqual(oldZoneCOunt,newZoneCount)
def main(): d = Dungeon("level1.txt") hero = Hero("batman", "the dark knight", 100, 100, 3) wep = Weapon("Axe", 10) hero.equip(wep) print(d.spawn(hero)) d.move_hero("right") d.print_map() print(hero.get_health()) spell = Spell("cherna maiq", 10, 20, 3) hero.learn(spell) print(d.hero_atack(by="spell")) d.print_map()
def test_hero_properties_from_id(self): hPk = dbHelp.create_test_hero_using_test_values() h = Hero.construct_model_from_pk(hPk) self.assertIsNotNone(h.get_pk()) self.assertEqual(h.lvl,7) self.assertEqual(h.maxHp,40) self.assertEqual(h.nowHp,20) self.assertEqual(h.maxXp,50) self.assertEqual(h.nowXp,0) self.assertEqual(h.gold,100) self.assertEqual(h.attackLvl,5) self.assertEqual(h.defenseLvl,6) self.assertDictEqual(h.zoneVisitCounts,{ZoneDefinitionFields.ASTEROID_FIELD:5,ZoneDefinitionFields.EMPTY_SPACE:11}) self.assertEqual(h.zone.definitionKey,ZoneDefinitionFields.EMPTY_SPACE) self.assertIsNotNone(h.zone.get_pk()) self.assertEqual(h.monster.definitionKey,MonsterDefinitionFields.AMBUSH_PIRATES) self.assertEqual(h.shipName,"USS testship")
def tournament(self): # clear anything in the terminal. clear() # instantiate monsters and put them in legion lists print textwrap.dedent(self.description) # first fight myMonster = Goblin() myHero = Hero() myHero.introduction() myHero.add_weapon(Items.weapon["Test Sword"]) myHero.add_armor(Items.armor["Cloth Armor"]) self.fight(myHero, myMonster) # second fight self.next_round(myHero) myMonster = Warrior() myMonster.add_weapon(Items.weapon["Battle Axe"]) myMonster.add_armor(Items.armor["Chain Armor"]) self.fight(myHero, myMonster)
def setUp(self): self.outcast_land = Dungeon.load_level() self.fighter = Hero(mana=62, name='Centaur', title='Warrunner') self.fighter_spell = Spell(mana_cost=1) self.fighter.learn(self.fighter_spell) self.outcast_land.spawn(self.fighter)
def test_get_health(self): self.assertEqual(Hero.get_health(self.hero), self.hero.health)
class TestDungeons(unittest.TestCase): def setUp(self): self.outcast_land = Dungeon.load_level() self.fighter = Hero(mana=62, name='Centaur', title='Warrunner') self.fighter_spell = Spell(mana_cost=1) self.fighter.learn(self.fighter_spell) self.outcast_land.spawn(self.fighter) def test_loading_map(self): self.assertEqual(type(self.outcast_land.dungeon_map), list) self.assertEqual(len(self.outcast_land.dungeon_map[0]), 10) def test_show_map(self): # print("===== BEFORE RESP======") self.test_land = Dungeon.load_level() # print(self.test_land) def test_spawn(self): alabala = "WTF" with self.assertRaises(ThisIsNotAHero): self.outcast_land.spawn(alabala) # print("==== AFTER RESP =====") # print(self.outcast_land.show_map()) with self.assertRaises(NoMoreSpawnPoints): self.outcast_land.spawn(self.fighter) def test_move_hero_right_once(self): with self.assertRaises(WrongDirection): self.outcast_land.move_hero("asdad") self.assertTrue(self.outcast_land.move_hero("right")) self.assertFalse(self.outcast_land.move_hero("up")) def test_move_hero_right_twice_hit_wall(self): self.assertTrue(self.outcast_land.move_hero("right")) self.assertFalse(self.outcast_land.move_hero("right")) def test_move_hero_right_once_down_once(self): self.assertTrue(self.outcast_land.move_hero("right")) self.assertTrue(self.outcast_land.move_hero("down")) def test_hero_start_fight_no_enemy_in_line(self): self.assertTrue(self.outcast_land.move_hero("right")) self.assertTrue(self.outcast_land.move_hero("down")) # print(self.outcast_land.show_map()) self.assertFalse(self.outcast_land.hero_attack(by='spell')) def test_move_hero_right_and_find_enemy(self): self.assertTrue(self.outcast_land.move_hero("right")) self.assertTrue(self.outcast_land.move_hero("down")) self.assertTrue(self.outcast_land.move_hero("down")) self.assertTrue(self.outcast_land.move_hero("down")) print(self.outcast_land.show_map()) self.fighter.learn(Spell(mana_cost=30)) # print(self.outcast_land.show_map()) self.assertTrue(self.outcast_land.hero_attack(by='spell')) def test_move_hero_right_once_hit_bottom_wall(self): self.assertTrue(self.outcast_land.move_hero("right")) self.assertTrue(self.outcast_land.move_hero("down")) self.assertTrue(self.outcast_land.move_hero("down")) self.assertTrue(self.outcast_land.move_hero("down")) self.assertFalse(self.outcast_land.move_hero("down")) def test_first_right_turn(self): self.assertTrue(self.outcast_land.move_hero("right")) self.assertTrue(self.outcast_land.move_hero("down")) self.assertTrue(self.outcast_land.move_hero("down")) self.assertTrue(self.outcast_land.move_hero("down")) self.fighter.learn(Spell(mana_cost=30)) self.fighter.equip(Weapon(damage=3, name='Blazing Blade')) self.assertTrue(self.outcast_land.move_hero("right")) # self.outcast_land.show_map() def test_update_map(self): self.assertTrue(self.outcast_land.move_hero("right"), True)
def StageTwo(hero, winstyle = 0): # Initialize screen pygame.init() bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32) screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth) pygame.display.set_caption('Cyborg-Fu!') # Creating Background bgdtile = load_image('graytile.png') background = pygame.Surface(SCREENRECT.size) for x in range(0, SCREENRECT.width, bgdtile.get_width()): for y in range(0, SCREENRECT.height, bgdtile.get_width()): background.blit(bgdtile, (x, y)) #Missle & Attack object groups must be determined before characters. shots = pygame.sprite.Group() pshots = pygame.sprite.Group() clubs = pygame.sprite.Group() blade = pygame.sprite.Group() blood = pygame.sprite.Group() ogres = pygame.sprite.Group() #scoreboard score = Score() scoresprite = pygame.sprite.RenderPlain(score) prof = Creature("prof", [740, 30], [1, 1], [10], "still", "prof.png", "nil") Ogre([100, 100], clubs) #Text TEXT = "Ogres may seem stupid, but they're a lot smarter than runts! Be careful!" text = Text(TEXT) textgroup = pygame.sprite.Group() #Create Characters global tesi global gunner if hero == "tesi": tesi = Tesi(blade) life = Life(tesi) Mana(tesi) lifesprite = pygame.sprite.RenderPlain(life) heroes = pygame.sprite.Group(tesi) sprites = pygame.sprite.Group(tesi, prof, score, life, text) if hero == "gunner": gunner = Hero(shots) life = Life(gunner) Mana(gunner) lifesprite = pygame.sprite.RenderPlain(life) heroes = pygame.sprite.Group(gunner) sprites = pygame.sprite.Group(gunner, prof, score, life, text) #Assign life values Alives = 0 Blives = 0 #Checkmarks to avoid repeating text CHECKMARK1 = 0 CHECKMARK2 = 0 CHECKMARK3 = 0 #Default groups for each sprite class Creature.containers = sprites Shot.containers = shots PowerShot.containers = pshots Ogre.containers = ogres Text.containers = sprites # Blit everything to the screen screen.blit(background, (0, 0)) pygame.display.flip() # Initialise clock clock = pygame.time.Clock() #Tesi's blade BLADE = 1 COLLIDELATENCY = 0 ogrereload = OGRE_RELOAD # Event loop while 1: clock.tick(60) COLLIDELATENCY = COLLIDELATENCY - 1 """Creating actions that cause a change in dialogue""" if score.score == 4: if CHECKMARK1 == 0: msg = "These Ogres cost a lot, I hope you can handle more than two!" newText = Text(msg) sprites.add(newText) CHECKMARK1 = 1 if ogrereload: ogrereload = ogrereload - 1 elif not int(random.random() * OGRE_ODDS): choice = random.choice((1,2,3,4,5)) if choice == 1: if Alives <= 0: loc = [100, 50] ogreA = Ogre(loc, clubs) ogres.add(ogreA) Alives = 1 if choice == 2: if Blives <= 0: loc = [200, 50] ogreB = Ogre(loc, clubs) ogres.add(ogreB) Blives = 1 ogrereload = OGRE_RELOAD if hero == "tesi": for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return if event.type == KEYDOWN: if event.key == K_e: tesi.healing = 1 if event.key == K_SPACE: if BLADE == 1: tesi.throw(blade) BLADE = BLADE - 1 COLLIDELATENCY = 60 if Alives == 1: ogreA.dodge() if Blives == 1: ogreB.dodge() if event.key == K_w: tesi.moveup() if event.key == K_s: tesi.movedown() if event.key == K_a: tesi.moveleft() if event.key == K_d: tesi.moveright() if event.key == K_l: if BLADE == 1: tesi.swing(blade) COLLIDELATENCY = 150 elif event.type == KEYUP: if event.key == K_e: tesi.healing = 0 if event.key == K_a or event.key == K_d or event.key == K_w or event.key == K_s: tesi.state = "still" # Tesi gets his blade back if COLLIDELATENCY <= 0: if pygame.sprite.spritecollide(tesi, blade, dokill): BLADE = BLADE + 1 if pygame.sprite.spritecollide(tesi, clubs, dontkill): tesi.bleed(blood) tesi.life = tesi.life - 6 if hero == "gunner": for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return if event.type == KEYDOWN: if event.key == K_e: gunner.powershot(pshots) if event.key == K_SPACE: gunner.doublefire(shots) if Alives == 1: ogreA.dodge() if Blives == 1: ogreB.dodge() if event.key == K_w: gunner.moveup() if event.key == K_s: gunner.movedown() if event.key == K_a: gunner.moveleft() if event.key == K_d: gunner.moveright() elif event.type == KEYUP: if event.key == K_a or event.key == K_d or event.key == K_w or event.key == K_s: gunner.state = "still" if pygame.sprite.spritecollide(gunner, clubs, dontkill): gunner.bleed(blood) gunner.life = gunner.life - 10 gunner.knockback() if hero == "tesi": loc = tesi.rect if hero == "gunner": loc = gunner.rect if Alives == 1: ogreA.chase(loc) ogreA.tryclub(loc) if pygame.sprite.spritecollide(ogreA, shots, dokill): ogreA.bleed(blood) ogreA.life = ogreA.life - 10 if ogreA.life <= 0: Alives = 0 score.plus(2) if pygame.sprite.spritecollide(ogreA, pshots, dontkill): ogreA.bleed(blood) ogreA.life = ogreA.life - 15 if ogreA.life <= 0: Alives = 0 score.plus(2) if pygame.sprite.spritecollide(ogreA, blade, dontkill): ogreA.bleed(blood) ogreA.life = ogreA.life - 4 if ogreA.life <= 0: Alives = 0 score.plus(2) if Blives == 1: ogreB.chase(loc) ogreB.tryclub(loc) if pygame.sprite.spritecollide(ogreB, shots, dokill): ogreB.bleed(blood) ogreB.life = ogreB.life - 10 if ogreB.life <= 0: Blives = 0 score.plus(2) if pygame.sprite.spritecollide(ogreB, pshots, dontkill): ogreB.bleed(blood) ogreB.life = ogreB.life - 15 if ogreB.life <= 0: Blives = 0 score.plus(2) if pygame.sprite.spritecollide(ogreB, blade, dontkill): ogreB.bleed(blood) ogreB.life = ogreB.life - 4 if ogreB.life <= 0: Blives = 0 score.plus(2) if pygame.sprite.spritecollide(prof, ogres, dontkill): msg = "Professor: (Sigh) Attack the subject, stupid ogres!" newText = Text(msg) sprites.add(newText) ogres.empty() Alives = 0 Blives = 0 if pygame.sprite.spritecollide(prof, heroes, dontkill): if score.score <= 9: if CHECKMARK2 == 0: msg = "Professor: Attack the ogres, let me see what you can do!" newText = Text(msg) sprites.add(newText) CHECKMARK2 = 1 if score.score >= 10: if CHECKMARK3 == 0: msg = "Excellent work. What shall be your next challenge.. hm?" newText = Text(msg) sprites.add(newText) CHECKMARK3 = 1 ogres.empty() Alives = 2 Blives = 2 StageThree(hero) ogres.clear(screen, background) ogres.update() ogres.draw(screen) blood.clear(screen, background) blood.update() blood.draw(screen) shots.clear(screen, background) shots.update() shots.draw(screen) pshots.clear(screen, background) pshots.update() pshots.draw(screen) blade.clear(screen, background) blade.update() blade.draw(screen) clubs.clear(screen, background) clubs.update() clubs.draw(screen) textgroup.clear(screen, background) textgroup.update() textgroup.draw(screen) sprites.clear(screen, background) sprites.update() sprites.draw(screen) pygame.display.flip()
def game_play(): ''' After selecting "Play", this new game loop runs ''' # Make the hero unit & grid of sectors hero = Hero(screen) # Create ALL sectors in the game sect0 = makeSector0(hero, screen) sect1 = makeSector1(hero, screen) sect2 = makeSector2(hero, screen) sect3 = makeSector3(hero, screen) sect4 = makeSector4(hero, screen) sect5 = makeSector5(hero, screen) sect6 = makeSector6(hero, screen) sect7 = makeSector7(hero, screen) sect8 = makeSector8(hero, screen) sect9 = makeSectorBound(hero, screen) sect10 = makeSectorBound(hero, screen) sect11 = makeSectorBound(hero, screen) sect12 = makeSectorBound(hero, screen) sect13 = makeSectorBound(hero, screen) sect14 = makeSectorBound(hero, screen) sect15 = makeSectorBound(hero, screen) sect16 = makeSectorBound(hero, screen) sect17 = makeSectorBound(hero, screen) sect18 = makeSectorBound(hero, screen) sect19 = makeSectorBound(hero, screen) sect20 = makeSectorBound(hero, screen) sect21 = makeSectorBound(hero, screen) sect22 = makeSectorBound(hero, screen) sect23 = makeSectorBound(hero, screen) sect24 = makeSectorBound(hero, screen) # Establish the positional relationships between sectors makeNeighbors([sect0, sect1, sect2, sect3, sect4, sect5, sect6, sect7, sect8, sect9, sect10, sect11, sect12, sect13, sect14, sect15, sect16, sect17, sect18, sect19, sect20, sect21, sect22, sect23, sect24]) background = sect1.background background_rect = background.get_rect() curSect = sect0 curSect.loadTheme() pygame.mixer.music.play(-1) game_done = False ticks_elapsed = 0 font = pygame.font.Font(None, 90) font.set_bold(True) pauseText = font.render("GAME PAUSED", 1, (51, 217, 34)) heroGroup = pygame.sprite.Group() heroGroup.add(hero) # Game loop while (not game_done): time_elapsed = clock.tick(FPS) # TODO: Implement joystick controls for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: if event.key == K_ESCAPE: game_done = True elif event.key == K_DOWN: hero.setDY(hero.speedSetting) elif event.key == K_LEFT: hero.setDX(-1 * hero.speedSetting) elif event.key == K_RIGHT: hero.setDX(hero.speedSetting) elif event.key == K_UP: hero.setDY(-1 * hero.speedSetting) elif event.key == K_c: hero.cycleWeapons() elif event.key == K_p: screen.blit (pauseText, ((SCREEN_WIDTH / 2) - 200, (SCREEN_HEIGHT / 2) - 20)) pygame.display.update() pause_game(-1) elif event.key == K_SPACE: #TODO: Change these velocities according to rotation newLaser = hero.fireWeapon(hero.x, hero.y, 14) if (newLaser != None): curSect.tempProjGroup.add(newLaser) if ((joystick != None) and (joystick.get_init)): if(joystick.get_button(6)): newLaser = hero.fireWeapon(hero.x, hero.y, 14) if (newLaser != None): curSect.tempProjGroup.add(newLaser) if(joystick.get_button(8)): hero.cycleWeapons() if(joystick.get_button(9)): screen.blit (pauseText, ((SCREEN_WIDTH / 2) - 200, (SCREEN_HEIGHT / 2) - 20)) pygame.display.update() pause_game(-1) # New event handling for mouse control # Start by getting the relative screen corner position: relScreenX = hero.x - (0.5 * SCREEN_WIDTH) relScreenY = hero.y - (0.5 * SCREEN_HEIGHT) (x_relative, y_relative) = pygame.mouse.get_pos() x_relative = x_relative - hero.x + relScreenX y_relative = y_relative - hero.y + relScreenY #js controls if ((joystick != None) and (joystick.get_init)): x_relative = get_js_pos( joystick.get_axis(0)) y_relative = get_js_pos( joystick.get_axis(1)) hero.vector_path(x_relative, y_relative, 1) #print("x_rel: {} y_rel: {}".format(x_relative, y_relative)) if (pygame.mouse.get_pressed()[0]): (x_relative, y_relative) = pygame.mouse.get_pos() x_relative = x_relative - hero.x + relScreenX y_relative = y_relative - hero.y + relScreenY hero.vector_path(x_relative, y_relative, 1) #print("x_rel: {} y_rel: {}".format(x_relative, y_relative)) else: hero.vector_path(x_relative, y_relative, 0) if (pygame.mouse.get_pressed()[2]): newLaser = hero.fireWeapon(hero.x, hero.y, 14) if (newLaser != None): curSect.tempProjGroup.add(newLaser) curSect = curSect.checkTransition() background = curSect.background background_rect = background.get_rect() # Draw background, update sprites, redraw sprites #Then do the rest screen.fill(BACKGROUND_COLOR) screen.blit(background, background_rect.move(-relScreenX, -relScreenY)) hero.update(hero) hero.draw(relScreenX, relScreenY, hero) # Check if hero is OOB: if (hero.x <= 10 and curSect.neighbors[WEST] == 0): hero.dx = hero.dx * -1.65 if (hero.x >= curSect. width - 10 and curSect.neighbors[EAST] == 0): hero.dx = hero.dx * -1.65 if (hero.y <= 10 and curSect.neighbors[NORTH] == 0): hero.dy = hero.dy * -1.65 if (hero.y >= curSect.height - 10 and curSect.neighbors[SOUTH] == 0): hero.dy = hero.dy * -1.65 if hero.level >= 5: victoryText = font.render("Earth is freed! Feel free to explore!", 1, (100, 200, 100)) screen.blit (victoryText, (425, 40 + (7 * SCREEN_HEIGHT / 8))) # Update and draw everything in the sector.... curSect.tempUnitGroup.update(hero) curSect.tempProjGroup.update(None, hero.x + (0.5 * SCREEN_WIDTH), hero.y + (0.5 * SCREEN_HEIGHT), hero, curSect.tempUnitGroup) #curSect.tempObstGroup.update() if((curSect.storm_side != 0) and (len(curSect.tempObstGroup) <= 25)): curSect.asteroid_storm(relScreenX, relScreenY, screen) #update for objects made this way for asteroid storm for obs in curSect.tempObstGroup: hit_flag = 0 if(isinstance(obs, Asteroid)): for target in curSect.tempObstGroup: obs.check_coll(target) if(obs.hit_something == True): obs.update(target, curSect.tempObstGroup) hit_flag = 1 break if(hit_flag != 1): obs.update(None, curSect.tempObstGroup) else: obs.update() # Manage the enemy projectiles: for unit in curSect.tempUnitGroup: # Moves the projectile unit.curWeap.firedList.update(hero,hero.x + (0.5 * SCREEN_WIDTH), hero.y + (0.5 * SCREEN_HEIGHT), hero, heroGroup) if not isinstance(unit, Hero): if unit.x <= WESTERN_BOUNDARY: unit.x = random.randint (0, curSect.width) unit.dx = unit.dx * -1 if unit.x >= curSect.width - EASTERN_BOUNDARY: unit.x = random.randint (0, curSect.width) unit.dx = unit.dx * -1 if unit.y <= 0: unit.y = random.randint (0, curSect.width) unit.dy = unit.dy * -1 if unit.y >= curSect.height - SOUTHERN_BOUNDARY: unit.y = random.randint (0, curSect.width) unit.dy = unit.dy * -5 # Hero's projectile hit this unit for laser in curSect.tempProjGroup: if(laser.hit_something == False): if (laser.check_collide(unit) == True): if (unit.active == False): hero.hpCur = hero.hpCur + 5 # Killing enemies restores health for laser in unit.curWeap.firedList: laser.draw(relScreenX, relScreenY, hero) unit.draw(relScreenX, relScreenY, hero) # Draw the hero's projectile for proj in curSect.tempProjGroup: proj.draw(relScreenX, relScreenY, hero) for obst in curSect.tempObstGroup: if (proj.check_collide(obst) == True): pass #TODO: Projectile repeatedly hits obst. Fix this for unit in curSect.tempObstGroup: unit.draw(relScreenX, relScreenY, hero) if (unit.check_collide(hero) == True): pass # Update health and stamina display font = pygame.font.Font(None, 30) hpText = font.render("Health: " + str(hero.getHpCur()), 1, (150, 200, 150)) stamText = font.render("Stamina: " + str(hero.getStaminaCur()), 1, (100, 200, 100)) screen.blit (hpText, (SCREEN_WIDTH / 50, 7 * SCREEN_HEIGHT / 8)) screen.blit (stamText, (SCREEN_WIDTH / 50, 40 + (7 * SCREEN_HEIGHT / 8))) pygame.display.update() # Hero death --> Respawns at the coordinates stored in the sector if(hero.hpCur <= 0): # TODO: Death sound needs to be more pronounced hero.Death.play() font = pygame.font.Font(None, 90) font.set_bold(True) deathText = font.render("YOU DIED", 1, (51, 34, 217)) screen.blit (deathText, ((SCREEN_WIDTH / 2) - 200, (SCREEN_HEIGHT / 2) - 20)) pygame.display.update() pause_game(HERO_DEATH_WAIT) # Respawn in the first sector hero.hpCur = hero.hpMax curSect = sect0 hero.x = curSect.respawnX hero.y = curSect.respawnY # Reset the hitbox hero.rect.x = curSect.respawnX hero.rect.y = curSect.respawnY hero.rect.x = hero.rect.x - hero.image_w / 2 hero.rect.y = hero.rect.y - hero.image_h / 2 hero.active = True # Regenerate hero's stamina if ((ticks_elapsed % HERO_STAMINA_RECOVERY_RATE == 0) and (hero.staminaMax > hero.staminaCur)): hero.staminaCur += 1 # Loop the music if not pygame.mixer.music.get_busy(): pygame.mixer.music.load(curSect.music) pygame.mixer.music.play() ticks_elapsed += 1 pygame.mixer.music.stop()
class Profile(GameEngineElement): def __init__(self, recall_string=None, name_entry_cb=None): GameEngineElement.__init__(self) self.name = "" self.dungeon_id = "al1.txt" self.position = (-1, -1) self.playerFacing = NORTH self.hero = Hero() # 4 types of stats and difficulties self.problem_stats = {} self.difficulty = {} for stat in ["mult", "div", "geo", "shop"]: # Each type of stat has 3 "levels" easy, medium, hard # Shop uses level for too much, too little, exact self.problem_stats[stat] = [(0, 0), (0, 0), (0, 0)] # Difficulty: 1=Easy 2=Meduim(default) 3=Hard self.difficulty[stat] = 2 self.puzzlesSolved = 0 self.inventory = [] bg = pygame.image.load(MENU_PATH + "mafh_splash.gif").convert() self.background = DrawableObject([bg], "") self.background.scale(self.game_engine.width, self.game_engine.height) self.add_to_scene([self.background]) # create background rect draw_width = self.game_engine.width / 4 draw_height = self.game_engine.height / 4 surf = pygame.Surface((draw_width + 60, draw_height + 60)) surf.fill((150, 150, 255)) self.blueRect = DrawableObject([surf], "") self.add_to_scene([self.blueRect]) font = pygame.font.Font(None, 16) self.text_list = [] self.text_list.append(DrawableFontObject("1", font)) self.text_list.append(DrawableFontObject("2", font)) self.text_list.append(DrawableFontObject("name", font)) self.add_to_scene(self.text_list) if recall_string: self.load_from_json_string(recall_string) if self.name == "": self.name_cb = name_entry_cb self.add_to_engine() def reload_dungeon(self): self.__load_dungeon(self.game_engine.get_object("dungeon").id) # restore HP self.hero.setHealth(self.hero.maxHealthPoints()) def next_dungeon(self): self.__load_dungeon(self.game_engine.get_object("dungeon").next) def __load_dungeon(self, id): self.position = (-1, -1) self.playerFacing = NORTH d = self.game_engine.get_object("dungeon") self.dungeon_id = id d.remove_from_engine() self.game_engine.remove_object("dungeon") self.game_engine.add_object("dungeon", Dungeon(self.dungeon_id)) self.remove_keys() def load_from_json_string(self, recall_string): print "TO BE IMPLEMENTED" def dump_to_json_string(self): print "TO BE IMPLEMENTED" def update_problem_stat(self, p_type, level, correct): assert p_type in self.problem_stats assert level >= 0 and level < len(self.problem_stats) - 1 correct, wrong = self.problem_stats[p_type][level] if correct: self.problem_stats[p_type][level] = (correct + 1, wrong) else: self.problem_stats[p_type][level] = (correct, wrong + 1) def move_to(self, x, y): self.position = (x, y) def turn(self, dir): if dir == RIGHT: self.playerFacing = (self.playerFacing - 1) % 4 elif dir == LEFT: self.playerFacing = (self.playerFacing + 1) % 4 def give_item(self, item): self.inventory.append(item) def remove_keys(self): i = 0 new_inv = [] for item in self.inventory: if not isinstance(item, Key): new_inv.append(item) self.inventory = new_inv def add_to_engine(self): super(Profile, self).add_to_engine() def remove_from_engine(self): super(Profile, self).remove_from_engine() def event_handler(self, event): """ Handles user input (used only for name entry) """ if event.type == pygame.KEYDOWN: if pygame.key.name(event.key) == "backspace": self.name = self.name[0:-1] return True elif pygame.key.name(event.key) == "return": self.remove_from_engine() self.name_cb() return True else: self.name += event.unicode return True def draw(self): """ Draws user input for name to the screen """ width = self.game_engine.width height = self.game_engine.height draw_width = width / 4 draw_height = height / 4 self.background.setPosition(0, 0) self.blueRect.setPosition(draw_width, draw_height) # name self.text_list[0].changeText(self.name, (0, 0, 0)) self.text_list[0].setPosition(draw_width + 60, draw_height + 60) # text1 self.text_list[1].changeText(_("Enter Name:"), (0, 0, 0)) self.text_list[1].setPosition(draw_width, draw_height) # text2 self.text_list[2].changeText(_("Return to continue"), (0, 0, 0)) self.text_list[2].setPosition(draw_width + 20, draw_height + 20)
def SetupHero(self, no): self.hpicked.insert(self.hindex, no) self.hindex += 1 self.BTNnode.detachNode() self.hero1 = Hero(no) self.hero1.getModel().setTag("Hero1", "1")
class World(DirectObject.DirectObject): def __init__(self): self.creeps = None self.open = False self.sec = 0 self.min = 0 self.pindex = 1 # This is the Pause Index self.index = -1 # This is the hero Index self.rindex = False # This is the Repick Index self.hpicked = [] # This List Stores All The Heroes Picked and Removes Them for i in range(0, 110): self.hpicked.append(-1) # Gotta change and check this self.hindex = 0 # When a hero is picked this index saves it and stores it in the list self.RND = render.attachNewNode("rend") self.LightHandler = None self.Players() self.LoadTerrain() # Load the Map self.SetupCamera() self.SetupLight() self.SetupEvents() self.SetupTimer() self.chooseHero() self.SetupMap() self.SetupCreeps() self.SetupCollision() self.displayed = False self.keyMap = {"cam-left": 0, "cam-right": 0, "cam-up": 0, "cam-down": 0, "zoom-in": 0, "zoom-out": 0} self.chatindex = 0 self.chat = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.text = ["text1", "text2", "text3", "text4", "text5" "text6" "text7" "text8" "text9", "text10", "text11"] self.task = None def Players(self): self.hero1 = None self.hero2 = None self.hero3 = None self.hero4 = None self.hero5 = None self.hero6 = None self.hero7 = None self.hero8 = None self.hero9 = None self.hero10 = None self.player1 = None self.player2 = None self.player3 = None self.player4 = None self.player5 = None self.player6 = None self.player7 = None self.player8 = None self.player9 = None self.player10 = None def LoadTerrain(self): self.terrain = loader.loadModel("models/environment") self.terrain.setTag("Map", "1") self.terrain.reparentTo(self.RND) self.itmpan1 = OnscreenImage(image=MYDIRIMG + "/3.png", scale=(0.3, 0, 0.09), pos=(0.61, 0, -0.915)) self.itmpan2 = OnscreenImage(image=MYDIRIMG + "/3.png", scale=(0.3, 0, 0.09), pos=(0.61, 0, -0.740)) self.t2 = OnscreenImage(image=MYDIRIMG + "/t2.png", scale=(0.25, 0, 0.06), pos=(1.160, 0, -0.71)) self.t1 = OnscreenImage(image=MYDIRIMG + "/t1.png", scale=(0.25, 0, 0.06), pos=(1.160, 0, -0.83)) self.end = OnscreenImage(image=MYDIRIMG + "/end.png", scale=(0.1, 0, 0.2), pos=(1.510, 0, -0.80)) self.back = OnscreenImage(image=MYDIRIMG + "/back.png", scale=(0.57, 0, 0.2), pos=(-0.26, 0, -0.80)) def SetupCollision(self): base.cTrav = CollisionTraverser() self.collHandler = CollisionHandlerQueue() self.pickerNode = CollisionNode("mouseRay") self.pickerNP = camera.attachNewNode(self.pickerNode) self.pickerNode.setFromCollideMask(GeomNode.getDefaultCollideMask()) self.pickerRay = CollisionRay() self.pickerNode.addSolid(self.pickerRay) base.cTrav.addCollider(self.pickerNP, self.collHandler) def ObjectClick(self): if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() self.pickerRay.setFromLens(base.camNode, mpos.getX(), mpos.getY()) base.cTrav.traverse(render) # Assume for simplicity's sake that myHandler is a CollisionHandlerQueue. if self.collHandler.getNumEntries() > 0: # This is so we get the closest object. self.collHandler.sortEntries() self.pickedObj = self.collHandler.getEntry(0).getIntoNodePath() self.pickedObj1 = self.pickedObj.findNetTag("Unit") self.pickedObj2 = self.pickedObj.findNetTag("MyHero") self.pickedObj3 = self.pickedObj.findNetTag("Map") self.pickedObj4 = self.pickedObj.findNetTag("MyHero") if self.pickedObj1 == self.creeps.getModel(): if self.displayed is False: self.displayed = True self.creeps.display() else: if self.displayed is True: self.displayed = False self.creeps.displaynot() if self.hero != None: if self.pickedObj2 == self.hero1.getModel(): if self.displayed is False: self.displayed = True self.hero1.display() else: if self.displayed is True: self.displayed = False self.hero1.displaynot() def SetupCamera(self): base.camera.setPos(0, 0, 180) base.camera.setP(-30) base.camera.lookAt(0, 0, 0) def SetupTimer(self): self.btn = aspect2d.attachNewNode("btn") self.btn.setTransparency(1) self.timesec = OnscreenText(text="", pos=(1.3, -0.71), fg=(1, 1, 1, 1), mayChange=1, scale=0.05) self.timemin = OnscreenText(text="", pos=(1.1, -0.71), fg=(1, 1, 1, 1), mayChange=1, scale=0.05) self.pausebtn = DirectButton( text="Pause (%d)" % (self.pindex), parent=self.btn, text_fg=(0, 0.2, 0, 1), text_pos=(0.05, -0.15), text_scale=(0.48, 0.53), image=(MYDIRIMG + "btnof.png", MYDIRIMG + "btnon.png", MYDIRIMG + "btnon.png", None), frameColor=(0, 0, 0, 0), pos=(-1.0, 0, -0.81), image_scale=(1.0, 0, 0.7), scale=(0.15, 0, 0.10), command=self.Pause, ) self.infobtn = DirectButton( text="Info", parent=self.btn, text_fg=(0, 0.2, 0, 1), text_pos=(0.05, -0.15), text_scale=0.6, image=(MYDIRIMG + "btnof.png", MYDIRIMG + "btnon.png", MYDIRIMG + "btnon.png", None), frameColor=(0, 0, 0, 0), pos=(-1.0, 0, -0.68), image_scale=(1.0, 0, 0.7), scale=(0.15, 0, 0.10), command=self.Pause, ) taskMgr.doMethodLater(1, self.Timer, "tickTask") def SetupMap(self): self.minimap = minimap(None) def SetupLight(self): self.LightHandler = Lights(None) def SetupEvents(self): self.DEntry = DirectEntry( text="", pos=(-0.6, 0.0, -0.7), image=MYDIRIMG + "/tooltips9.png", frameColor=(0, 0, 0, 1), width=27, image_pos=(13.5, 0, 0.2), image_scale=(15, 0, 0.6), scale=0.05, initialText="", numLines=1, focus=1, command=self.Parser, ) self.DEntry.setTransparency(1) self.DEntry.detachNode() taskMgr.add(self.MoveCamera, "CameraControl") self.accept("enter", self.MsgBox) self.accept("wheel_up", self.setKey, ["zoom-in", 1]) self.accept("wheel_down", self.setKey, ["zoom-out", 1]) # self.accept("wheel_up-up",self.setKey, ["zoom-in",0]) # self.accept("wheel_down-up",self.setKey, ["zoom-out",0]) self.accept("a", self.setKey, ["cam-left", 1]) self.accept("d", self.setKey, ["cam-right", 1]) self.accept("w", self.setKey, ["cam-up", 1]) self.accept("s", self.setKey, ["cam-down", 1]) self.accept("+", self.setKey, ["zoom-in", 1]) self.accept("-", self.setKey, ["zoom-out", 1]) self.accept("a-up", self.setKey, ["cam-left", 0]) self.accept("d-up", self.setKey, ["cam-right", 0]) self.accept("w-up", self.setKey, ["cam-up", 0]) self.accept("s-up", self.setKey, ["cam-down", 0]) self.accept("+-up", self.setKey, ["zoom-in", 0]) self.accept("--up", self.setKey, ["zoom-out", 0]) self.accept("mouse1", self.ObjectClick) def UnSetupEvents(self): self.ignore("a") self.ignore("s") self.ignore("w") self.ignore("s") self.ignore("+") self.ignore("-") self.ignore("enter") self.ignore("wheel_up") self.ignore("wheel_down") taskMgr.remove("CameraControl") def setKey(self, key, value): self.keyMap[key] = value def MoveCamera(self, task): mpos = base.mouseWatcherNode.getMouse() elapsed = globalClock.getDt() self.dt = elapsed self.mx = mpos.getX() self.my = mpos.getY() if self.keyMap["cam-left"] != 0: base.camera.setX(base.camera, -(self.dt * 20)) if self.keyMap["cam-right"] != 0: base.camera.setX(base.camera, +(self.dt * 20)) if self.keyMap["zoom-in"] != 0: base.camera.setY(base.camera, -(self.dt * 20)) if self.keyMap["zoom-out"] != 0: base.camera.setY(base.camera, +(self.dt * 20)) if self.keyMap["cam-down"] != 0: base.camera.setZ(base.camera, -(self.dt * 20)) if self.keyMap["cam-up"] != 0: base.camera.setZ(base.camera, +(self.dt * 20)) if self.mx > 0.95: if base.camera.getX() < MAPLIMIT: base.camera.setX(base.camera, +(self.dt * SCROLLSPEED)) if self.mx < -0.95: if base.camera.getX() > -MAPLIMIT: base.camera.setX(base.camera, -(self.dt * SCROLLSPEED)) if self.my > 0.95: if base.camera.getY() < MAPLIMIT: base.camera.setZ(base.camera, +(self.dt * SCROLLSPEED)) if self.my < -0.95: if base.camera.getY() > -MAPLIMIT: base.camera.setZ(base.camera, -(self.dt * SCROLLSPEED)) return task.cont def chooseHero(self): if self.hero1 == None: self.BTNnode = aspect2d.attachNewNode("buttons") for i in range(0, 3): for j in range(0, 4): self.index += 1 if icons[self.index] == None: continue if self.hpicked[self.index] == self.index: continue self.worldHeroButton(-1.8 + j * 0.1, -i * 0.1, self.index) def worldHeroButton(self, x, y, arg): DirectButton( text="", parent=self.BTNnode, text_font=font, image=MYDIRICONS + icons[arg] + ".tga", frameColor=(0, 0, 0, 0), pad=(-0.1, -0.1), image_scale=(IconSx + 0.2, 0, IconSy + 0.2), pos=(posx - 0.5 + x, 0, posy + y), scale=(0.20, 0, 0.20), command=self.SetupHero, extraArgs=[arg], ) def SetupCreeps(self): self.creeps = Unit1() def SetupHero(self, no): self.hpicked.insert(self.hindex, no) self.hindex += 1 self.BTNnode.detachNode() self.hero1 = Hero(no) self.hero1.getModel().setTag("Hero1", "1") def Timer(self, task): self.task = task self.sec += 1 if self.hero1 != None: self.hero1.sendTime(self.min, self.sec) if self.sec >= 60: self.sec = 0 self.min += 1 self.timemin.setText(str(self.min)) self.timesec.setText(str(self.sec)) return task.again def MsgBox(self): if self.open == False: self.DEntry.reparentTo(aspect2d) self.open = True else: self.DEntry.detachNode() self.open = False def Parser(self, text): Text = text # Within 120 seconds on the game if self.hero1 == None: self.BTNnode.detachNode() if Text == "-random": self.hero1 = Hero(random.randint(0, 96)) elif Text == "-random int": self.hero1 = Hero(random.randint(66, 96)) elif Text == "-random str": self.hero1 = Hero(random.randint(0, 36)) elif Text == "-random agi": self.hero1 == Hero(random.randint(36, 66)) if Text == "-repick": if self.rindex == False: if self.hero1 != None: self.hero1.destroy() self.hero1 = None self.index = -1 self.chooseHero() self.rindex = True else: Error("Cannot Repick") elif Text == "-": pass else: pass # self.Chat(Text,self.task) # taskMgr.add(self.Chat,"nn",extraArgs=[Text]) # this sends text to allies def ChatTimer(self, task, chat, i): chat.destroy() self.chat.insert(i, 0) self.chatindex -= 1 return task.done def Chat(self, text, task): for i in range(1, 15): if self.chat[i] == 0: self.text[i] = OnscreenText(text=text, pos=(-1.3, -0.4), fg=(0, 0, 0, 1), scale=0.07) self.chat.insert(self.chatindex, 1) taskMgr.doMethodLater(5, self.ChatTimer, "chat", [task, self.text[i], i]) self.chatindex += 1 break else: self.text[i].setY(-(0.1 * i) + 0.4) return task.done def Pause(self): if self.pindex != 0: self.pindex -= 1 time.sleep(2) self.pausebtn["text"] = "Pause (%d)" % (self.pindex) else: Error("Pause Limits Used") def destroy(self): if self.hero1 != None: self.hero1.destroy() self.minimap.destroy() self.btn.detachNode() self.BTNnode.detachNode() taskMgr.remove("timer") self.terrain.detachNode() del self.LightHandler del self.creeps self.UnSetupEvents() def MousePos(self, task): # This Took me 1.5 Months to Learn if base.mouseWatcherNode.hasMouse(): mpos = base.mouseWatcherNode.getMouse() self.pos3d = Point3() self.nearPoint = Point3() self.farPoint = Point3() base.camLens.extrude(mpos, self.nearPoint, self.farPoint) if self.plane.intersectsLine( self.pos3d, render.getRelativePoint(camera, self.nearPoint), render.getRelativePoint(camera, self.farPoint) ): pass return task.again
def StageThree(hero, winstyle = 0): # Initialize screen pygame.init() bestdepth = pygame.display.mode_ok(SCREENRECT.size, winstyle, 32) screen = pygame.display.set_mode(SCREENRECT.size, winstyle, bestdepth) pygame.display.set_caption('Cyborg-Fu!') # Creating Background bgdtile = load_image('rivers.png') background = pygame.Surface(SCREENRECT.size) background.blit(bgdtile, (0,0)) #Missle & Attack object groups must be determined before characters. shots = pygame.sprite.Group() pshots = pygame.sprite.Group() ashots = pygame.sprite.Group() fakeshots = pygame.sprite.Group() shadows = pygame.sprite.Group() blade = pygame.sprite.Group() blood = pygame.sprite.Group() #Scoreboard score = Score() scoresprite = pygame.sprite.RenderPlain(score) assassin = Assassin([100, 100], ashots) Shadow([100,300], fakeshots, "left", [0,0]) #Text TEXT = "They sent an 'The Assassin' for me! Please, defeat him!" text = Text(TEXT) #Create Characters global tesi global gunner if hero == "tesi": tesi = Tesi(blade) life = Life(tesi) Mana(tesi) lifesprite = pygame.sprite.RenderPlain(life) heroes = pygame.sprite.Group(tesi) objects = pygame.sprite.Group(tesi, assassin, score, life, text) if hero == "gunner": gunner = Hero(shots) life = Life(gunner) Mana(gunner) lifesprite = pygame.sprite.RenderPlain(life) heroes = pygame.sprite.Group(gunner) objects = pygame.sprite.Group(gunner, assassin, score, life, text) #Creating an impassable block! Excitement abounds! #Block works! Now to map out the river! middle = Block([420, 10]) middle1 = Block([420, 40]) middle2 = Block([420, 80]) middle3 = Block([420, 120]) middle4 = Block([430, 160]) middle5 = Block([430, 200]) middle6 = Block([460, 240]) middle7 = Block([430, 280]) middle8 = Block([420, 310]) middle9 = Block([413, 400]) middle10 = Block([435, 434]) middle11 = Block([455, 456]) middle12 = Block([488, 488]) middle13 = Block([520, 496]) middle14 = Block([557, 503]) middle15 = Block([575, 536]) middle16 = Block([588, 564]) east1 = Block([464, 153]) east2 = Block([504, 175]) east3 = Block([543, 181]) east4 = Block([574, 210]) east5 = Block([575, 303]) east6 = Block([570, 351]) east7 = Block([544, 371]) east8 = Block([524, 404]) east9 = Block([495, 421]) west1 = Block([376, 188]) west2 = Block([323, 202]) west3 = Block([290, 213]) west4 = Block([240, 220]) west5 = Block([141, 209]) west6 = Block([108, 163]) west7 = Block([72, 148]) west8 = Block([42, 133]) west9 = Block([3, 121]) #Checkmarks to avoid repeating text CHECKMARK1 = 0 CHECKMARK2 = 0 #Create Game Groups gassassin = pygame.sprite.Group(assassin) blocks = pygame.sprite.Group(middle, middle1, middle2, middle3, middle4, middle5, middle6, middle7, middle8, middle9, middle10, middle11, middle12, middle13, middle14, middle15, middle16, east1, east2, east3, east4, east5, east6, east7, east8, east9, west1, west2, west3, west4, west5, west6, west7, west8, west9) #Default groups for each sprite class Shot.containers = shots PowerShot.containers = pshots Shadow.containers = shadows # Blit everything to the screen screen.blit(background, (0, 0)) pygame.display.flip() #Tesi's blade BLADE = 1 COLLIDELATENCY = 0 #Assassin creates an illusional shadow shadowspawn = SHADOW_SPAWN SALIVE = 0 # Initialise clock clock = pygame.time.Clock() # Event loop while 1: clock.tick(60) COLLIDELATENCY = COLLIDELATENCY - 1 if hero == "tesi": loc = tesi.rect if hero == "gunner": loc = gunner.rect assassin.aim(loc) if SALIVE == 1: shadow.aim(loc) if shadowspawn > 0: shadowspawn = shadowspawn - 1 elif not int(random.random() * SHADOW_ODDS): shadowspawn = SHADOW_SPAWN loc = assassin.rect.center facing = assassin.facing running = assassin.movepos shadow = Shadow(loc, fakeshots, facing, running) shadows.add(shadow) SALIVE = 1 if hero == "tesi": for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return if event.type == KEYDOWN: if event.key == K_e: tesi.healing = 1 if event.key == K_SPACE: if BLADE == 1: tesi.throw(blade) BLADE = BLADE - 1 COLLIDELATENCY = 60 assassin.dodge() if event.key == K_w: tesi.moveup() if event.key == K_s: tesi.movedown() if event.key == K_a: tesi.moveleft() if event.key == K_d: tesi.moveright() if event.key == K_l: if BLADE == 1: tesi.swing(blade) COLLIDELATENCY = 150 elif event.type == KEYUP: if event.key == K_e: tesi.healing = 0 if event.key == K_a or event.key == K_d or event.key == K_w or event.key == K_s: tesi.state = "still" # Tesi gets his blade back if COLLIDELATENCY <= 0: if pygame.sprite.spritecollide(tesi, blade, dokill): BLADE = BLADE + 1 if pygame.sprite.spritecollide(tesi, ashots, dokill): tesi.bleed(blood) tesi.life = tesi.life - 6 if hero == "gunner": for event in pygame.event.get(): if event.type == QUIT: pygame.quit() return if event.type == KEYDOWN: if event.key == K_e: gunner.powershot(pshots) if event.key == K_SPACE: gunner.doublefire(shots) assassin.dodge() if event.key == K_w: gunner.moveup() if event.key == K_s: gunner.movedown() if event.key == K_a: gunner.moveleft() if event.key == K_d: gunner.moveright() elif event.type == KEYUP: if event.key == K_a or event.key == K_d or event.key == K_w or event.key == K_s: gunner.state = "still" if pygame.sprite.spritecollide(gunner, ashots, dokill): gunner.bleed(blood) gunner.life = gunner.life - 10 gunner.knockback() if pygame.sprite.groupcollide(shadows, blade, dokill, dontkill) or pygame.sprite.groupcollide(shadows, shots, dokill, dokill): a = "Assassin: What's the matter? Can't hit me? Haha!" b = "Assassin: Come on, stop trying to hit me and hit me!" c = "Assassin: What are you swinging at? I'm right here!" d = "Assassin: Bwahahahaha!" e = "Assassin: Super ketchup, premio tomato, catfish tuna." msg = random.choice((a, b, c, d, e)) newText = Text(msg) objects.add(newText) shadows.empty() SALIVE = 0 if pygame.sprite.spritecollide(assassin, blade, dontkill): assassin.bleed(blood) assassin.life = assassin.life - 2 score.plus(1) if pygame.sprite.spritecollide(assassin, shots, dokill): assassin.bleed(blood) assassin.life = assassin.life - 5 score.plus(1) if pygame.sprite.spritecollide(assassin, pshots, dontkill): assassin.bleed(blood) assassin.life = assassin.life - 8 score.plus(1) if pygame.sprite.groupcollide(blocks, heroes, dontkill, dontkill): if hero == "tesi": middle.collision(tesi) if hero == "gunner": middle.collision(gunner) if pygame.sprite.groupcollide(blocks, gassassin, dontkill, dontkill): middle.collision(assassin) if assassin.life <= 0: if CHECKMARK1 == 0: msg = "Professor: Incredible, you defeated 'The Assassin'! Yippie!" newText = Text(msg) objects.add(newText) CHECKMARK1 = 1 shadows.clear(screen, background) shadows.update() shadows.draw(screen) blood.clear(screen, background) blood.update() blood.draw(screen) shots.clear(screen, background) shots.update() shots.draw(screen) pshots.clear(screen, background) pshots.update() pshots.draw(screen) ashots.clear(screen, background) ashots.update() ashots.draw(screen) fakeshots.clear(screen, background) fakeshots.update() fakeshots.draw(screen) blade.clear(screen, background) blade.update() blade.draw(screen) objects.clear(screen, background) objects.update() objects.draw(screen) blocks.clear(screen, background) blocks.update() blocks.draw(screen) pygame.display.flip()
#sprite sheets ssBottom = Spritesheet('tiles-bottom.png') ssTop = Spritesheet('tiles-top.png') background = None #some state random.seed(time.time()) lastEnemyCreation = 0 lastBlockLoad = 0 lastShot = -1 lastHeli = 0 gameStarted = False gameOver = True titleTimeout = 2000.0 hero = Hero() active.add(hero) actors.add(hero) hero.rect.center = (SCREEN_WIDTH/2, SCREEN_HEIGHT/2) hb = HealthBar(target=hero) active.add(hb) actors.add(hb) fps = Text("") fps.rect.topleft = (0,0) fps.maxArea = Rect((0,0), (100, 300)) fps.bgColor = (255,255,255,0) gui.add(fps) pygame.mouse.set_visible(False) crosshair = pygame.sprite.Sprite()