def test_RemoveWinner(self): c1 = Battle.Contestant("1") c2 = Battle.Contestant("2") c3 = Battle.Contestant("3") main = Battle.GenerateBattles([c1, c2, c3]) # c1 vs. c2 c = main.GetNextUndecided() # c1 winner c.WinnerIsA() # c1 vs. c3 d = main.GetNextUndecided() # c1 winner d.WinnerIsA() self.assertTrue(main.IsDecided()) self.assertEqual(main.getWinner(), c1) main = main.RemoveWinner() self.assertFalse(main.IsDecided()) # winner is c3 main.WinnerIsB() self.assertTrue(main.IsDecided()) self.assertEqual(main.getWinner(), c2) self.assertTrue(main.IsDecided()) main = main.RemoveWinner() self.assertTrue(main.IsDecided()) self.assertEqual(main.getWinner(), c3)
def mainloop(self): if (GlobalData.displayInitialized==0): self.initDisplay() self.initPlayer() pygame.key.set_repeat(75, 75) TextBox.loadTextImages(3, 3, -1) Battle.loadBattleTextures() Creature.loadCreatureImages() Map.loadTileSet("Exterior_Town1.png", 30, 16) Map.loadTileSet("Interior_Town1.png", 30, 16) Map.loadTileSet("Interior_Cave1.png", 30, 16) self.map = Map.Map("Exterior_Town1", "Exterior_Town1-6", 30, 30) self.maps["Exterior_Town1"] = [self.map] #timer = pygame.time.get_ticks() #timeOffset = 0.00 while not GlobalData.quitFlag: for e in pygame.event.get(): if e.type == QUIT: GlobalData.quitFlag = 1 return self.playerInput(e) pygame.event.pump() self.drawWorld() self.printFPS() self.flipScreenBuffer() self.timer.tick(12)
def fight(monster): order = Battle.fight_order(Hero.initiative, monster.initiative) current_health_hero = Hero.endurance current_health_monster = monster.endurance knight_count = 0 while True: print("hero hp:", current_health_hero) print("monster hp:", current_health_monster) if current_health_hero > 0 and current_health_monster > 0: if order == "hero": battle_choice = int(input("1: Attack\n2: Escape\n")) if battle_choice == 1: current_health_monster = Battle.attack_hero( choice, Hero.attack, monster.agility, current_health_monster) order = "monster" elif battle_choice == 2: if Battle.escape(choice, Hero.agility): break else: order = "monster" elif order == "monster": current_health_hero = Battle.attack_monster( monster.attack, Hero.agility, current_health_hero, choice, knight_count) order = "hero" knight_count = knight_count + 1 else: print("Invalid Choice") elif current_health_monster <= 0: print("monster died") break elif current_health_hero <= 0: print("you died") break
def test_IsLeaf(self): a = Battle.GenerateBattles([Battle.Contestant("0")]) self.assertTrue(a.IsLeaf()) b = Battle.GenerateBattles( [Battle.Contestant("1"), Battle.Contestant("2")]) self.assertFalse(b.IsLeaf())
def start(): global running while running: if player.data['name'] is None: print( 'Type one of the following commands: save, load, create, exit') cmd = str(input()) if cmd == 'load': player.data = PlayerData.load() print(player.data) if cmd == 'create': create_account() if cmd == 'exit': running = False else: if player.data['current_room'] == 'shop': print( 'Type one of the following commands: inspect item_name, heal, battle, shop, save, exit' ) else: print( 'Type one of the following commands: heal, battle, shop, save, exit' ) cmd = str(input()) if cmd == 'save': PlayerData.save(player) if cmd == 'exit': running = False if cmd == 'heal': player.restore_hp(1000) if cmd == 'battle': enemy = Enemy() enemy.data['current_hp'] = enemy.data['max_hp'] enemy.data['name'] = 'Skeleton' print(enemy.data) Battle.render_battle(player, enemy) # del enemy # print('test') if cmd == 'shop': player.data['current_room'] = 'shop' shop.get_items() if 'inspect' in cmd: cmds = cmd.split() item = cmds[1] shop_items = [item.name for item in shop.items] if item in shop_items: print(item) player.clamp_hp() render(player) if player.data['current_xp'] >= player.data['req_xp']: player.level_up() print('You leveled up!')
def checkEnemyCollisions(self): for enemy in self.active_enemies.sprites(): if pygame.sprite.collide_rect(self.player, enemy) == True: self.battle = True self.battleEvent = Battle(self, self.player, enemy, 0, 150) self.battleEvent.add(self.active_battle) ANIMATE_KEYSTROKES = pygame.USEREVENT + 1 pygame.time.set_timer(ANIMATE_KEYSTROKES, 125) ANIMATE_ENEMY = pygame.USEREVENT + 3 pygame.time.set_timer(ANIMATE_ENEMY, 125)
def test_IsDecided(self): a = Battle.GenerateBattles([Battle.Contestant("0")]) self.assertTrue(a.IsDecided()) b = Battle.GenerateBattles( [Battle.Contestant("1"), Battle.Contestant("2")]) self.assertFalse(b.IsDecided()) b.WinnerIsA() self.assertTrue(b.IsDecided())
def test_GetWinner(self): c1 = Battle.Contestant("1") c2 = Battle.Contestant("2") c3 = Battle.Contestant("3") a = Battle.GenerateBattles([c1, c2, c3]) c = a.GetNextUndecided() c.WinnerIsA() self.assertEqual(c.getWinner(), c1)
def test_GetNextUndecided(self): a = Battle.GenerateBattles([Battle.Contestant("0")]) self.assertTrue(a.GetNextUndecided() is None) b = Battle.GenerateBattles( [Battle.Contestant("1"), Battle.Contestant("2")]) self.assertEqual(b.GetNextUndecided(), b) b.WinnerIsA() self.assertTrue(b.GetNextUndecided() is None) self.assertTrue(b.IsDecided())
def generateBattle(self, path): """ Generate the main battle structure with the different Contestants and the associated images """ contestants = [] for file_name in glob.glob(os.path.join(path, "*.jpg")): im = Image.open(file_name) fullIm = im.copy() im.thumbnail(PREVIEW_SIZE, Image.ANTIALIAS) contestants.append(Battle.Contestant(file_name, im, fullIm)) self.setLabel("Number of images loaded: %d" % (len(contestants), )) self.currentBest = Battle.GenerateBattles(contestants) self.currentBattle = self.currentBest.GetNextUndecided()
def test_Workflow_ordered(self): """Check the workflow, from Battle creation to the end, for ordered data""" # The list is ordered, odd number listOfContestantsO = [Battle.Contestant(str(i)) for i in range(13)] listOfResultsO = startBattle(listOfContestantsO) self.assertListEqual(listOfContestantsO, listOfResultsO) # The list is ordered, even number listOfContestantsE = [Battle.Contestant(str(i)) for i in range(12)] listOfResultsE = startBattle(listOfContestantsE) self.assertListEqual(listOfContestantsE, listOfResultsE)
def test_GenerateBattles(self): contestantList = [] for i in range(5): contestantList.append(Battle.Contestant(str(i))) mainBattle = Battle.GenerateBattles(contestantList) # Check Topology self.assertFalse(mainBattle.IsDecided()) self.assertFalse(mainBattle.a.IsLeaf()) self.assertFalse(mainBattle.a.a.IsLeaf()) self.assertTrue(mainBattle.a.a.a.IsLeaf()) self.assertTrue(mainBattle.b.IsLeaf())
def runBattle(self, enemyNames, background, canFlee=True): combatants = list(self.partyManager.team) enemyElements = self.enemiesFile.getElementsByTagName("enemy") for name in enemyNames: found = filter(lambda e: str(e.getAttribute("name")) == name, enemyElements) if len(found): combatants += [Enemy.Enemy(found[0])] else: self.logManager.error("No enemy called " + name + " found in " + self.enemiesLocation + ".") # Choose a nice battle music. playingMusic = self.audioManager.getPlayingMusic() self.audioManager.playMusic("music/battle" + str(self.mathManager.randInt(1, 4)) + ".ogg") battle = Battle.Battle(combatants, background, canFlee) self.battleIntro() battle.run() self.audioManager.playMusic(playingMusic) return battle.won
def FireEmblem(screen): inGame = True nbSave = 0 state = ["Title", "Scene1", 1] characters = [] while inGame: if state[0] == "Dialogue": state = DialogueScene.Dialogue(screen, state[1], state[2]) elif state[0] == "Battle": infosBattle = utils.loadBattle(state[1], nbSave) endBattle = Battle.battle(screen, infosBattle[0], infosBattle[1], infosBattle[2], infosBattle[3]) state = endBattle[0] characters = endBattle[1] if state[0] not in ["Quit", "Title"]: utils.save("auto", state[0], state[1], state[2], pygame.Surface((600, 600)), characters) elif state[0] == "Title": state = TitleScreen.TitleScreen(screen) elif state[0] == "Load": state = LoadMenu.loadMenu(screen) elif state[0] == "Save": state = SaveMenu.SaveMenu(screen, state[1], state[2], state[3], state[4], characters) elif state[0] == "Options": state = Options.Options(screen) elif state[0] == "Quit": inGame = False
def get_iteration(self, iteration): Side = Battle.Side() i = 0 for unit in self.allowed_units: unit = Unit.ImportUnit(self.file_units, name=self.allowed_units[i], amount=iteration[i]) Side.add_unit(unit) i += 1
def startBattle(contestants): """ This is a typical workflow for the Battle class: 1. Generate a Battle using a list of contestants 2. As long as the Current battle is not a Single contestant (a Leaf in the graph) : a. check if there is any undecided battle between contestant before we can select a winner for the current battle b. if there is one, fetch it and elect the winner for the battle using WinnerIsA() or WinnerIsB() c. If the current battle is decided (ie a winner has been elected), fetch the winner and create a new graph battle without him. This become the new current battle """ listOfResults = [] battle = Battle.GenerateBattles(contestants) while not battle.IsLeaf(): undec = battle.GetNextUndecided() if (undec != None): a = undec.a.getWinner() b = undec.b.getWinner() # decide which contestant is stronger depending on its number if int(a.id) < int(b.id): undec.WinnerIsA() else: undec.WinnerIsB() if battle.IsDecided(): listOfResults.append(battle.getWinner()) battle = battle.RemoveWinner() # append the last element, when b is leaf listOfResults.append(battle.getWinner()) return listOfResults
def check_new_tile(self, tile_grid): battle = None # Checks new location of hero to see if it is a combat area boolean = tile_grid.check_combat_area((self.x_loc, self.y_loc), self.width, self.height) if boolean is True: number = random.randint(0, 99) if number < self.combat_chance: battle = Battle.Battle(self, Enemy.Wolf(100, 100, 100, 1, 1, 1)) self.combat_chance = 0 else: self.combat_chance += 1 # Checks new location of hero to see if it is a load point boolean, tile = tile_grid.check_load_points((self.x_loc, self.y_loc), self.width, self.height) # Returns hero sprite, hero_loc, and map_name / None if boolean is True: self.x_loc = tile.new_loc_x * tile_grid.tile_size self.y_loc = (tile.new_loc_y * tile_grid.tile_size) - ( self.height - self.width) # Extra hero height return tile.new_map, battle else: return None, battle
def enemy_encounter(self, event, button): self.enter_room(button, "battle") battle_window = Toplevel(self.board) app = Battle(self.party, self.cheat_mode, self.text_log, self.party_text_log, self.random_event_gen.get_enemy(), battle_window, self)
def setUp(self): self.Side = Battle.Side() self.file_path = "./Adventures/CN/units.json" self.unit_cav = Unit.ImportUnit(self.file_path, abbrev="Cava", amount=100) self.unit_sol = Unit.ImportUnit(self.file_path, abbrev="S", amount=100) self.unit_arc = Unit.ImportUnit(self.file_path, abbrev="Arc", amount=100) self.Side.add_unit(self.unit_arc) self.Side.add_unit(self.unit_sol) self.Side.add_unit(self.unit_cav)
def test_Workflow_limit(self): """Check the workflow, from Battle creation to the end, for limit case""" # Only one contestant listOfContestants1 = [Battle.Contestant(str(i)) for i in range(1)] listOfResults1 = startBattle(listOfContestants1) self.assertListEqual(listOfContestants1, listOfResults1) # Only two contestants listOfContestants2 = [Battle.Contestant(str(i)) for i in range(2)] listOfResults2 = startBattle(listOfContestants2) self.assertListEqual(listOfContestants2, listOfResults2) # lots of contestants listOfContestants200 = [Battle.Contestant(str(i)) for i in range(200)] listOfResults200 = startBattle(listOfContestants200) self.assertListEqual(listOfContestants200, listOfResults200)
def doBattle(self, teamOne, teamTwo): # create instance of battle, pick a random pokemon from each team, # and have them fight battle = Battle.Battle(teamOne, teamTwo) battle.setFighterOne(battle.getTeamOne().chooseRandomFighter()) battle.setFighterTwo(battle.getTeamTwo().chooseRandomFighter()) # perform battle, print results. battle.startBattle() self.addBattle(battle)
def create_game(self) : client, team = self.ask_to_play.pop(0) game_id = free_game_ids.pop(0) new_battle = Battle.Battle(game_id, client, team) # To MODIFY self.games[game_id] = new_battle new_battle.step = "new_game" msg = {"gid" : game_id, "step" : "new_game", "grid" : new_battle.grid.get_serializable_grid(), "state" : new_battle.get_state()} client.send(msg)
def yesNo(*groups): box = pygame.sprite.Sprite() box.image = pygame.image.load("yesno.png") box.image = pygame.transform.scale(box.image, (TILE_SIZE * 3, int(TILE_SIZE * 1.5))) box.rect = box.image.get_rect(topleft=(TILE_SIZE * 6, int(TILE_SIZE * 7.5))) for group in groups: group.add(box) yes = Battle.TextImage((int(TILE_SIZE * 6.5), TILE_SIZE * 8), "YES", *groups) no = Battle.TextImage((int(TILE_SIZE * 7.5), TILE_SIZE * 8), "NO", *groups) arrow = pygame.sprite.Sprite() arrow.image = pygame.image.load("selectarrow.png") arrow.image = pygame.transform.scale( arrow.image, (int(TILE_SIZE / 2), int(TILE_SIZE / 2))) arrow.rect = arrow.image.get_rect(topleft=(int(TILE_SIZE * 6.125), TILE_SIZE * 8)) location = True while 1: groups.draw(screen) pygame.display.update() for e in pygame.event.get(): if e.type == QUIT: pygame.quit() sys.exit() if e.type == KEYDOWN and e.key == K_ESCAPE: return if e.type == KEYDOWN: if e.key == K_x: return location if e.key == K_LEFT or e.key == K_RIGHT: if location == True: location = False arrow.rect.left += TILE_SIZE else: location = True arrow.rect.left -= TILE_SIZE timer.tick(30)
def initBattle(surface, player, enemyGrp, enemySubGrp): toBattle = [["TeamA", []], ["TeamB", []]] for i in player.getTeam(): toBattle[0][1] += [[i[0], i[1], i[2], i[3]]] toBattle[1][1] = loadRandomEnemyGroup(enemyGrp, enemySubGrp) if Battle.startBattle(toBattle, surface) == "TeamA": if toBattle[0][0]: xp = 0 for i in toBattle[1][1]: xp += int(i[1]) xp /= len(toBattle[0][1]) player.giveXP(xp) player.checkEvolutions(surface, toBattle[1][1]) player.save()
def test_Workflow_unordered(self): """Check the workflow, from Battle creation to the end, for unordered data""" # The list is ordered, odd number listOfContestantsO = [Battle.Contestant(str(i)) for i in range(15)] # copy the list and shuffle it shuffledlistOfContestantsO = listOfContestantsO[:] random.shuffle(shuffledlistOfContestantsO) listOfResultsO = startBattle(shuffledlistOfContestantsO) self.assertListEqual(listOfContestantsO, listOfResultsO) # The list is ordered, even number listOfContestantsE = [Battle.Contestant(str(i)) for i in range(14)] # copy the list and shuffle it shuffledlistOfContestantsE = listOfContestantsE[:] random.shuffle(shuffledlistOfContestantsE) listOfResultsE = startBattle(shuffledlistOfContestantsE) self.assertListEqual(listOfContestantsE, listOfResultsE)
def initiatebattle(enemy): variables.settings.state = "battle" classvar.player.change_of_state() enemy.sethealth() enemy.enterbattle() classvar.player.heal() classvar.battle = Battle.Battle(enemy) variables.dirtyrects = [Rect(0,0,variables.width,variables.height)] play_effect("engagebattle") stop_music() if variables.settings.autosavep: save(False); variables.saved = True
def launch_game(): StoryGenerator.create_story() button_height = 50 battlefield = Battlefield(Battlefield.build("Battlefield/" + chosen_field + ".txt")) shop_state = ShopState(units, button_height, difficulty, gold, battlefield.get_enemy_spawn_count()) shopping_screen = pygame.display.set_mode((shop_state.window_width, shop_state.window_height)) shop_result = Shop.run(shopping_screen, shop_state) for unit in shop_result[0]: if unit not in units: units.append(unit) game_state = GameState(battlefield, button_height, units) battle_screen = pygame.display.set_mode((game_state.get_window_width(), game_state.get_window_height())) survivors = Battle.run(battle_screen, game_state) if is_game_over(survivors): return False, shop_result[1] return True, shop_result[1]
def getCollision(self, collision_mask, back_image, gates, camera, music, backgrounds): "Check player's position against mask to see if it collides" check_x = self.hit_box[0] + self.hit_box[2]/2 - self.bx check_y = self.hit_box[1] + self.hit_box[3]/2 - self.by if self.direction.find("up") != -1: check_y -= self.hit_box[3]/2 if self.direction.find("left") != 1: check_x -= self.hit_box[2]/2 if self.direction.find("down") != -1: check_y += self.hit_box[3]/2 if self.direction.find("right") != 1: check_x += self.hit_box[2]/2 # Left and right checking is weird, this compensates for that if self.direction.find("right") != -1: mask_col = collision_mask.get_at((int(check_x) + 9, int(check_y))) elif self.direction.find("left") != -1: mask_col = collision_mask.get_at((int(check_x) - 9, int(check_y))) else: mask_col = collision_mask.get_at((int(check_x), int(check_y))) for i in range(len(self.blob_list)): if self.blob_list[i].getRect().collidepoint((check_x, check_y)): self.battle = Battle(self, Enemy(self.difficulty), self.location) result = self.battle.battleControl(camera, music) self.del_num = i music[self.location + " battle"].halt() music[self.location].execute() if self.del_num != False: del self.blob_list[self.del_num] self.del_num = False self.kills += 1 # Check for wall collisions if mask_col == (255, 0, 0, 255): return True # Check for door collisions elif mask_col == (255, 255, 0, 255): self.interactDoor(gates, camera, music, backgrounds) else: return False
def DragonBall(): screen = pygame.display.set_mode((600, 600)) continuer = True gameState = ["TitleScreen"] while continuer: if gameState[0] == "TitleScreen": screen.fill((0, 0, 0)) gameState = EcranTitre.ecranTitre(screen) elif gameState[0] == "PlayMenu": screen.fill((0, 0, 0)) gameState = PlayMenu.playMenu(screen) elif gameState[0] == "SelectChar": screen.fill((0, 0, 0)) gameState = SelecChar.selectChar(screen) elif gameState[0] == "Battle": screen.fill((0, 0, 0)) gameState = Battle.battle(screen, gameState[1]) elif gameState[0] == "WinScreen": screen.fill((0, 0, 0)) gameState = WinScreen.WinScreen(screen, gameState[1]) elif gameState[0] == "Quit": continuer = False
def generateRandom(additionalAIUnits): def generateUnit(faction): unitTemplates = ['archer1', 'fighter1', 'defender1', 'rogue1', 'healer1', 'mage1'] unitTemplate = random.choice(unitTemplates) u = Resources.unit(unitTemplate) u.setFaction(faction) #u.setFaction(0) return u def generateMapAndUnits(): map_ = Resources.map('random') units = [] nUnits = random.randint(4, 8) startColumn = random.randint(0, map_.width - (nUnits + 1) / 2) for i in xrange(0, nUnits): u = generateUnit(PLAYER_FACTION) if i < nUnits / 2: row = map_.height-1 column = startColumn + i else: row = map_.height-2 column = startColumn + (i - nUnits/2) map_.squares[column][row].setUnit(u) units.append(u) nUnits += additionalAIUnits startColumn = random.randint(0, map_.width - (nUnits + 1) / 2) for i in xrange(0, nUnits): u = generateUnit(NPC_HOSTILE_FACTION) if i < nUnits / 2: row = 0 column = startColumn + i else: row = 1 column = startColumn + (i - nUnits/2) map_.squares[column][row].setUnit(u) units.append(u) return (map_, units) def verifyMap(map_, units): for unit in units: map_.fillDistances(unit, unit.posn()) for other in units: (x, y) = other.posn() if map_.squares[x][y].search == None: return False return True validMap = False while not validMap: (map_, units) = generateMapAndUnits() validMap = verifyMap(map_, units) endingConditions = [Battle.PLAYER_DEFEATED, Battle.DEFEAT_ALL_ENEMIES] battle = Battle.Battle(endingConditions, units, map_) lighting = Light.randomEnvironment(map_.width, map_.height) music = random.choice(['barbieri-lyta', 'barbieri-battle', 'barbieri-army-march']) return Scenario(map_, units, lighting, battle, None, music)
def blankMap(map): return Scenario(map, [], Light.defaultEnvironment(), Battle.Battle([Battle.NEVER_ENDING], [], map), None, '')
def load(scenarioFilename): scenarioFile = file(scenarioFilename, "rU") scenarioText = scenarioFile.read() scenarioFile.close() globalVars = {} localVars = {} module = compile("from engine.Unit import MALE, FEMALE, NEUTER", "Unit.py", "exec") eval(module, globalVars) module = compile("from engine.Faction import Faction", "Faction.py", "exec") eval(module, globalVars) for m in ["Light", "Battle"]: module = compile("import engine.%s as %s" % (m, m), m, "exec") eval(module, globalVars) compiled = compile(scenarioText, scenarioFilename, 'exec') eval(compiled, globalVars, localVars) scenarioData = localVars if scenarioData['VERSION'] != 1: raise Exception("Scenario version %d not supported" % scenarioData["VERSION"]) # Required fields: map m = Resources.map(scenarioData['MAP']) # Load ending conditions endingConditions = [Battle.NEVER_ENDING] if scenarioData.has_key('ENDING_CONDITIONS'): endingConditions = scenarioData['ENDING_CONDITIONS'] # Load lights if scenarioData.has_key('LIGHTING'): lightEnv = scenarioData['LIGHTING'] else: lightEnv = Light.defaultEnvironment() # Load units units = [] if scenarioData.has_key('FACTIONS'): for f in scenarioData['FACTIONS']: faction = f.faction() for u in f.units(): (unitFile, (x, y)) = u u = Resources.unit(unitFile) m.squares[x][y].setUnit(u) u.setFaction(faction) units.append(u) # Music music = 'barbieri-battle' if scenarioData.has_key('MUSIC'): music = scenarioData['MUSIC'] # Create battle battle = Battle.Battle(endingConditions, units, m) return Scenario(m, units, lightEnv, battle, None, music)
import random from Battle import * class RandTrainer(Trainer): def Act(self): return random.randint(0, 3) if __name__ == "__main__": print("Let's get ready to Battle!") bulba = AllPokemon.MakeNewPokemon(1, 50) bulba.SetMoves(["Vine Whip", "Tackle"]) pika = AllPokemon.MakeNewPokemon(25, 50) pika.SetMoves(["Thunder Shock", "Tackle"]) gary = RandTrainer("Gary", bulba) ash = RandTrainer("Ash", pika) randBattle = Battle(gary, ash) randBattle.Battle(20)
class Player: def __init__(self, health, house, xp, level, spell_level, potion_level, spell_energy, stamina, speed, x, y, bx, by, backgrounds, difficulty, location): # initialize all variables #these variables store self-explanatory things self.health = health self.max_health = health self.xp = xp self.house = house self.level = level self.spell_level = spell_level self.spell_energy = spell_energy self.max_spell_energy = spell_energy self.potion_level = potion_level self.stamina = stamina self.max_stamina = stamina self.angle_speed = speed * cos(radians(45)) self.straight_speed = speed self.x = x self.y = y self.bx = bx self.by = by self.playerRect = Rect(x, y, 22, 45) self.width = self.playerRect[2] self.height = self. playerRect[3] self.spell_list = [] self.attack_spells = [] self.difficulty = difficulty self.kills = 0 #there are 3 spells availible in total, player starts off with 2, needs to unlock the third self.spell_list.append(self.learnSpell("lumos", "Illuminate the tip of the caster's wand", 0, 1, 0)) self.spell_list.append(self.learnSpell("wingardium leviosa", "Make objects fly or levitate", 0, 1, 0)) #The values of "house" are obtained after clicking on the house in the menu ##The following if tree assigns the values for the player's attackes based on which house was chosen #Eg. some attacks are more powerful while other attacks drain more energy #arguments (name,description,damage,level,drain) if self.house == "slytherin": self.attack_spells.append(self.learnSpell("Expulso", "Light dameage, no energy drain", 15, 1, 5)) self.attack_spells.append(self.learnSpell("Imerio", "Moderate damage, low energy", 20, 1, 10)) self.attack_spells.append(self.learnSpell("Crucio", "Heavy damage, costs more energy", 30, 1, 35)) self.attack_spells.append(self.learnSpell("Stupefy", "Weakens next enemy attack", 5, 1, 15)) if self.house == "hufflepuff": self.attack_spells.append(self.learnSpell("Expulso", "Light dameage, no energy drain", 5, 1, 0)) self.attack_spells.append(self.learnSpell("Imerio", "Moderate damage, low energy", 10, 1, 5)) self.attack_spells.append(self.learnSpell("Crucio", "Heavy damage, costs more energy", 10, 1, 10)) self.attack_spells.append(self.learnSpell("Stupefy", "Weakens next enemy attack", 0, 1, 10)) if self.house == "ravenclaw": self.attack_spells.append(self.learnSpell("Expulso", "Light dameage, no energy drain", 10, 1, 0)) self.attack_spells.append(self.learnSpell("Imerio", "Moderate damage, low energy", 10, 1, 5)) self.attack_spells.append(self.learnSpell("Crucio", "Heavy damage, costs more energy", 15, 1, 10)) self.attack_spells.append(self.learnSpell("Stupefy", "Weakens next enemy attack", 0, 1, 10)) if self.house == "gryffindor": self.attack_spells.append(self.learnSpell("Expulso", "Light dameage, no energy drain", 10, 1, 5)) self.attack_spells.append(self.learnSpell("Imerio", "Moderate damage, low energy", 13, 1, 10)) self.attack_spells.append(self.learnSpell("Crucio", "Heavy damage, costs more energy", 15, 1, 13)) self.attack_spells.append(self.learnSpell("Stupefy", "Weakens next enemy attack", 2, 1, 10)) self.selected_spell = self.spell_list[0] #for the inventory system, player clicks the spell that they choose #defaults self.direction = "left" self.location = location self.attacking = False self.sprint_multiplyer = 2 self.hit_box = Rect(self.x, self.y + 26, self.width, 20) self.del_num = False #stores the attributes of the blue blobs that spawn on the ground self.blob_list = [] for i in range(50): self.blob_list.append(Blob(self, backgrounds)) def analyzeInput(self, camera, pressed, sprite, gates, background, collision_mask, music): "Centralized method that analyzes inputs and calls adequate functions" self.hit_box = Rect(self.x, self.y + 26, self.width, 20) sprite.showBackground(background[self.location], self.bx, self.by, camera) for i in range(len(self.blob_list)): #if self.hit_box.colliderect(self.blob_list[i].getRect()): # print("fight") # self.battle = Battle(self, Enemy(self.difficulty), self.location) self.blob_list[i].show(camera, collision_mask) # coordinates to check players location relative to the map, not screen check_x = self.x + self.width/2 - self.bx check_y = self.y + self.height/2 - self.by # draw door depending on player's location for i in range(len(gates)): gates[i].idle(camera, self) if self.attacking == False: if self.direction == "": sprite.displayIdle(self, camera) else: sprite.changeSprite(self, camera) else: self.attacking = sprite.inGameAttack(self, camera, self.attacking) self.changeDirection(pressed) if not self.getCollision(collision_mask[self.location], background[self.location], gates, camera, music, background): self.move(pressed, camera, sprite, background[self.location]) self.regenerate() def changeDirection(self, pressed): "Change the direction used to affect player" self.direction = "" #controlled with WASD if pressed[K_w]: self.direction += "up" if pressed[K_a]: self.direction += "left" if pressed[K_s]: self.direction += "down" if pressed[K_d]: self.direction += "right" if pressed[K_a] and pressed[K_d] or pressed[K_w] and pressed[K_s]: self.direction = "" if len(self.direction) >= 6: self.speed = self.angle_speed else: self.speed = self.straight_speed def move(self, pressed, camera, sprite, back_image): "Move player" # Moving left and right if self.bx > 0 or self.x < 415: if self.bx >= 0: self.bx = 0 #shift and WASD sprints if pressed[K_LSHIFT] and self.stamina > 1.0: if self.direction.find("left") != -1: self.x -= self.speed * self.sprint_multiplyer self.stamina -= 0.05 if self.direction.find("right") != -1: self.x += self.speed * self.sprint_multiplyer self.stamina -= 0.05 else: if self.direction.find("left") != -1: self.x -= self.speed if self.direction.find("right") != -1: self.x += self.speed elif self.bx < -back_image.get_width()+camera.get_width() or self.x > 435: if self.bx <= -back_image.get_width()+camera.get_width(): self.bx = -back_image.get_width()+camera.get_width() if pressed[K_LSHIFT] and self.stamina > 1.0: if self.direction.find("left") != -1: self.x -= self.speed * self.sprint_multiplyer self.stamina -= 0.05 if self.direction.find("right") != -1: self.x += self.speed * self.sprint_multiplyer self.stamina -= 0.05 else: if self.direction.find("left") != -1: self.x -= self.speed if self.direction.find("right") != -1: self.x += self.speed else: if pressed[K_LSHIFT] and self.stamina > 1.0: if self.direction.find("left") != -1: self.bx += self.speed * self.sprint_multiplyer self.stamina -= 0.05 if self.direction.find("right") != -1: self.bx -= self.speed * self.sprint_multiplyer self.stamina -= 0.05 else: if self.direction.find("left") != -1: self.bx += self.speed if self.direction.find("right") != -1: self.bx -= self.speed # Moving up and down if self.by > 0 or self.y < 290: if self.by >= 0: self.by = 0 if pressed[K_LSHIFT] and self.stamina > 1.0: if self.direction.find("up") != -1: self.y -= self.speed * self.sprint_multiplyer self.stamina -= 0.05 if self.direction.find("down") != -1: self.y += self.speed * self.sprint_multiplyer self.stamina -= 0.05 else: if self.direction.find("up") != -1: self.y -= self.speed if self.direction.find("down") != -1: self.y += self.speed elif self.by < -back_image.get_height()+camera.get_height() or self.y > 310: if self.by <= -back_image.get_height()+camera.get_height(): self.by = -back_image.get_height()+camera.get_height() if pressed[K_LSHIFT] and self.stamina > 1.0: if self.direction.find("up") != -1: self.y -= self.speed * self.sprint_multiplyer self.stamina -= 0.05 if self.direction.find("down") != -1: self.y += self.speed * self.sprint_multiplyer self.stamina -= 0.05 else: if self.direction.find("up") != -1: self.y -= self.speed if self.direction.find("down") != -1: self.y += self.speed else: if pressed[K_LSHIFT] and self.stamina > 1.0: if self.direction.find("up") != -1: self.by += self.speed * self.sprint_multiplyer self.stamina -= 0.05 if self.direction.find("down") != -1: self.by -= self.speed * self.sprint_multiplyer self.stamina -= 0.05 else: if self.direction.find("up") != -1: self.by += self.speed if self.direction.find("down") != -1: self.by -= self.speed def getCollision(self, collision_mask, back_image, gates, camera, music, backgrounds): "Check player's position against mask to see if it collides" check_x = self.hit_box[0] + self.hit_box[2]/2 - self.bx check_y = self.hit_box[1] + self.hit_box[3]/2 - self.by if self.direction.find("up") != -1: check_y -= self.hit_box[3]/2 if self.direction.find("left") != 1: check_x -= self.hit_box[2]/2 if self.direction.find("down") != -1: check_y += self.hit_box[3]/2 if self.direction.find("right") != 1: check_x += self.hit_box[2]/2 # Left and right checking is weird, this compensates for that if self.direction.find("right") != -1: mask_col = collision_mask.get_at((int(check_x) + 9, int(check_y))) elif self.direction.find("left") != -1: mask_col = collision_mask.get_at((int(check_x) - 9, int(check_y))) else: mask_col = collision_mask.get_at((int(check_x), int(check_y))) for i in range(len(self.blob_list)): if self.blob_list[i].getRect().collidepoint((check_x, check_y)): self.battle = Battle(self, Enemy(self.difficulty), self.location) result = self.battle.battleControl(camera, music) self.del_num = i music[self.location + " battle"].halt() music[self.location].execute() if self.del_num != False: del self.blob_list[self.del_num] self.del_num = False self.kills += 1 # Check for wall collisions if mask_col == (255, 0, 0, 255): return True # Check for door collisions elif mask_col == (255, 255, 0, 255): self.interactDoor(gates, camera, music, backgrounds) else: return False def interactDoor(self, gates, camera, music, backgrounds): "Check which door the player has collided with and act accordingly" for i in range(len(gates)): if self.x > gates[i].getX() and self.x < gates[i].getX()+gates[i].getWidth(): gates[i].open(camera, self, backgrounds) self.location = gates[i].getNewLocation() self.bx = -(gates[i].getNewX() - 425) self.by = -(gates[i].getNewY() - 300) music[self.location].halt() music[self.location].execute() self.createBlobs(backgrounds) def createBlobs(self, backgrounds): self.blob_list = [] for i in range(50): self.blob_list.append(Blob(self, backgrounds)) def learnSpell(self, name, description, power, level, energy): "Add spell to the player's spell list" #the inventory spells return (Spells(name, description, power, level, energy)) def regenerate(self): "regenerate health, stamina, and energy over time" if self.stamina < self.max_stamina: self.stamina += 0.04 if self.spell_energy < self.max_spell_energy: self.spell_energy += 0.09 # get meathods def getSpeed(self): "get speed of object" return self.speed def getX(self): "get x position of object" return self.x def getY(self): "get y position of object" return self.y def getWidth(self): "get width of player" return self.width def getBX(self): "get bx of player" return self.bx def getBY(self): "get by of player" return self.by def getHeight(self): "get length of player" return self.height def getRect(self): "get the rect of object" return self.playerRect def getHealth(self): "get health of player" return self.health def getSpellList(self): "get the list possible spells player can currently cast" return self.spell_list def getAttackSpells(self): "get list of spells player can use in battle" return self.attack_spells def getSelectedSpell(self): "get the current spell the user has selected" return self.selected_spell def getStamina(self): "get the player's stamina" return self.stamina def getSpellEnergy(self): "get the spell energy of player" return self.spell_energy def getDirection(self): "get the direction of the player" return self.direction def getHouse(self): "get the house of player" return self.house def getLocation(self): "get the current location of the player" return self.location def getLevel(self): "level of player" return self.level def getPotionLevel(self): "inventory spells" return self.potion_level def getSpellLevel(self): return self.spell_level def getXP(self): return self.xp def getDifficulty(self): return self.difficulty def getKills(self): return self.kills # set methods def setSelectedSpell(self, spell): "changes the spell chooses" self.selected_spell = spell def drainEnergy(self, energy): "drains the users energy when an attack is used" self.spell_energy -= energy def takeDamage(self, damage): "Reduce player health based on attack used" self.health -= damage
def player_popup_menu(widget, event, self): if event.type == gtk.gdk._2BUTTON_PRESS: if event.button == 1: treeselection = self.player_treeview.get_selection() (model, iter) = treeselection.get_selected() # TODO menu = gtk.Menu() menu.show() side_item = gtk.MenuItem("Side") team_item = gtk.MenuItem("Army") ally_item = gtk.MenuItem("Ally") colour_item = gtk.MenuItem("Colour") kick_item = gtk.MenuItem("Kick") menu.append(side_item) menu.append(team_item) menu.append(ally_item) menu.append(colour_item) menu.append(kick_item) side_item.show() team_item.show() ally_item.show() colour_item.show() kick_item.show() menu.popup(None, None, None, event.button, event.time) kick_item.connect("button_press_event", Battle.kick_player, self, iter) # Side -> Sub Menu menu_select_side = gtk.Menu() menu_select_side.show() p = 0 while p <= ( len(self.old_sides) - 1 ): select_side_item = gtk.MenuItem(self.old_sides[p]) select_side_item.connect("button_press_event", Battle.change_value, self, iter, 3, self.old_sides[p]) select_side_item.show() menu_select_side.append(select_side_item) p = p + 1 side_item.set_submenu(menu_select_side) # Team(Army) -> Sub Menu menu_select_team = gtk.Menu() menu_select_team.show() for i in range(0,GLOBAL.MAX_TEAMS): select_team_item = gtk.MenuItem(str(i)) select_team_item.connect("button_press_event", Battle.change_value, self, iter, 2, i) select_team_item.show() menu_select_team.append(select_team_item) team_item.set_submenu(menu_select_team) # Ally -> Sub Menu menu_select_ally = gtk.Menu() menu_select_ally.show() for i in range(0,GLOBAL.MAX_ALLIES): select_ally_item = gtk.MenuItem(str(i)) select_ally_item.connect("button_press_event", Battle.change_value, self, iter, 4, i) select_ally_item.show() menu_select_ally.append(select_ally_item) ally_item.set_submenu(menu_select_ally) # Add Code for Sub Menu for Team # Add Code for Sub Menu for Ally # Add Code for Sub Menu for Colour # Add Code for to kick player menu_add_bot = gtk.Menu() menu_add_bot.show() elif event.type == gtk.gdk.BUTTON_PRESS: if event.button == 3: # Main Menu menu = gtk.Menu() menu.show() ai_item = gtk.MenuItem("Add AI") player_item = gtk.MenuItem("Join Fight") menu.append(ai_item) menu.append(player_item) ai_item.show() player_item.show() # TODO temp solution for player_item # till code a sub-menu for picking side player_item.connect("button_press_event", Battle.add_player, self, self.old_sides[0]) menu.popup(None, None, None, event.button, event.time) ai, ai_location = Battle.find_ai(self.platform, self.datadirs) i = 0 menu_select_ai = gtk.Menu() menu_select_ai.show() for i in range(0,len(ai)): select_ai_item = gtk.MenuItem(ai[i]) select_ai_item.show() menu_select_ai.append(select_ai_item) menu_select_ai_side = gtk.Menu() menu_select_ai_side.show() # TODO add folowing code to def # So Join Fight can use similar sub Menu for picks Sides p = 0 while p <= ( len(self.old_sides) - 1 ): select_ai_side_item = gtk.MenuItem(self.old_sides[p]) select_ai_side_item.connect("button_press_event", Battle.add_bot, self, ai[i], ai_location[i], self.old_sides[p]) select_ai_side_item.show() menu_select_ai_side.append(select_ai_side_item) p = p + 1 select_ai_item.set_submenu(menu_select_ai_side) i = i + 2 ai_item.set_submenu(menu_select_ai)