def mainLoop(self): print("This would be the intro to the game... enter something...") print(self.world.look(True)) while 1: command = self.command('>') print(command) #after command #check location for monster room = self.world.room[self.world.location] #print "\n debug :: %s \n" % (room.name) if room.monster: print "\nYou see a %s and it attacks you." % ( room.monster.name) combat = Combat(self.player, room.monster) result = combat.main() if result == "death": sys.exit() if result == "quit": sys.exit() if result == "error": print "\nSomething weird just happened. Hopefully it wont happen again.\n" if result == "monster dead": # add monster inv to room inv along with x drops y self.player.health = self.player.max_health self.world.room[self.world.location].monster = None if result == "ran": print "\nYou better choose somewhere to go quick!\n" if result == "monster ran": print "\nThe %s ran away from you\n" % (room.monster.name) self.world.room[self.world.location].monster = None
def look_for_monster(self): if self.current_room.monster == None: return else: monster: Monster = self.current_room.monster new_combat = Combat() new_combat.fight(self, monster)
def as_leader(batter_name): while 1: battle = Combat(batter_name) battle.start(auto_ready=True) time.sleep(2) start_loc = wait_for_color(PartyColor.StartFight) utilities.random_sleep(0.5, 2) click(start_loc, random_range=3, tired_check=True)
def run(self): self.server.hello() self.combat = Combat(self.server) while True: self.players = self.server.get_players(self.players) if self.players: self.combat.update(self.players) self.algorithm() self.server.send_command(self.command)
def __init__(self, x, y, player, enemy): self.enemy = enemy self.enemyCombat = Combat(player, self.enemy) super().__init__(x, y, player) self.combat = True self.room_type = 3 self.update_available_actions = True
def test_do_start(self): _rot = Rotation() _round = (Counterweight(), (TacticDefense(), )) _rot.add(_round) Combat.do_start() self.assertTrue(Combat.workers_exist()) self.assertEqual(Combat._round, 1) self.assertEqual(len(Combat._keys), 1)
def parseInput(input): args = input.split(' ') if args[0] == 'kill': Combat.fight(PC, goblin) else: try: commands[args[0]].perform(PC, *args) except KeyError: print('Invalid command: {}'.format(args[0]))
def options(narritive_list_link): if narritive_list_link == '{store}': store = storeClass() store.createStore() return '' elif narritive_list_link == '{combat}': combat = Combat() combat.combat() return '' else: return narritive_list_link
def move_to(self, i, j): move = self.game_map[i][j] if move == '#': print "You run into a wall and take 1 damage." self.hero.take_damage(1, False) else: self.i = i self.j = j self.encounter_odd += 0.05 if move == 'E': print "Congratulations! You've reached the end of this floor!" exit(0) elif move == 'T': self.find_treasure() self.game_map[i][j] = ' ' #Removes the treasure chest from the game elif move == "S": print "Back to start! What now?" else: #Move into corridor, generate random fight here. dice_roll = random.random() if dice_roll < self.encounter_odd: #BATTLE! Combat(self.hero, [NPC("Goblin", 1, 10, 1, 2, 0, 20)]) self.encounter_odd = 0.0 elif dice_roll > 0.95: print "Surprise! You found something." else: #Move normally print "All is good, keep going!" pass """
def move(self, hor, vert): ''' Moves the player, given a keypress. Also evaluates if the player needs to fight or pick up some treasure. ''' self.old_row, self.old_col = self.map.player row = self.old_row + hor col = self.old_col + vert if row > (ROWS - 1) * TILE_SIZE or row < 0 or col > ( COLUMNS - 1) * TILE_SIZE or col < 0: return if self.map.has_wall(row, col): return if self.map.has_monster(row, col): Combat(self.player_stats, self.map.monsters[row / TILE_SIZE][col / TILE_SIZE]) if self.map.monsters[row / TILE_SIZE][col / TILE_SIZE].current_hp <= 0: pass #put death throes here if self.player_stats.current_hp <= 0: self.end_game() self.move(0, 0) return self.map.player = (row, col) self.map.player = (row, col) self.map.clear_block(self.map.player) self.map.set_current_position(self.map.player) treasure = self.map.clear_treasure(self.map.player) if treasure: self.add_treasure(treasure) self.screen.draw_inventory(self.inventory) self.screen.draw_equipment(self.player_stats.equipped)
def main_yaoqi(times, target_monster): count = 0 while count < times: yaoqi_loc = wait_for_state(img.party_img.YAOQIFENGYIN) click(yaoqi_loc) refresh_location = wait_for_state(img.party_img.REFRESH) parties.yaoqifengyin.find_monster(target_monster, refresh_location) combat = Combat('妖气封印') combat_result = combat.start() party_loc = wait_for_state(img.party_img.MAIN_PARTY, 15) time.sleep(1) click_to_leaving_state(img.party_img.MAIN_PARTY, rand_offset=10, location=party_loc) count += 1
def __init__(self): self.in_combat = False self.free = True self.action = Action.nothing self.queue = [] self.combat = Combat(self.scoundrel_print, self.add_action, self.remove_action, self.queue, self.free, self.action) self.combat_enabled = tk.BooleanVar() self.alert = Alert(self.scoundrel_print) self.chat = Chat(self.scoundrel_print_with_tag) self.alert_enabled = tk.BooleanVar()
def engage(data): #first argument should be person/character speaker = data["speaker"] args = data["args"] command = data["mapped"] if len(args) < 2: speaker.send_line(command.title() + " what?") return engagee = character_in_room(args[1], speaker.location, speaker) if not engagee: speaker.send_line("They're not here.") return if engagee == speaker: speaker.send_line("You cannot initiate combat with yourself.") return for flag in engagee.flags: if flag == "peaceful": speaker.send_line("You can't attack that!") return if speaker.engaged: if speaker.engaged.combatant1 == engagee or speaker.engaged.combatant2 == engagee: speaker.send_line("You are already engaged in combat with " + engagee.name + "!") else: for co in speaker.combats: if co.combatant1 == engagee or co.combatant2 == engagee: speaker.send_line("You turn your attention toward " + engagee.name + "!") report( ROOM, "$actor $verb " + pronoun_possessive[speaker.gender] + " attention toward $direct!", speaker, ("turn", "turns"), engagee) speaker.engaged = co for co2 in speaker.combats: co2.in_range_set_action() return speaker.send_line("You are too busy to fight anything else!") return w = World() c = Combat(speaker, engagee) w.combats.append(c) speaker.combats.append(c) engagee.combats.append(c) report(SELF | ROOM, "$actor $verb ready to engage $direct in combat!", speaker, ("appear", "appears"), engagee) return
def new_pvm_combat(self, enemy, location): from combat import Combat c = Combat(location=location) c.save() oldcombat = self.combat self.combat = c enemy.new_combatant(combat=c) self.save() if oldcombat: oldcombat.delete() c.init_combat() c.next_round() return c
def test_do_round(self): _rot = Rotation() _round = (Counterweight(), (TacticDefense(), )) _rot.add(_round) Combat.start_workers() Combat.do_round() Combat.stop() # test output keys = [kp.get("key") for kp in _globals.KEY_PRESSES] self.assertEqual(''.join(keys), "req")
def __init__(self, display_surface, settings): self.display = display_surface self.display_rect = self.display.get_rect() self.display_center = self.display_rect.center self.settings = settings self.key_map = settings.get_key_map() self.delayed_functions = [] self.state = 'ift' self.prev_state = 'game' self.Saver = gss.Saver('./saves/') self.Loader = gss.Loader('./saves/') self.interface = Interface(self) self.interface.menu.store_action('new_game', self.new_game) self.interface.menu.store_action('load_game', self.load_game) self.interface.menu.store_action('save_game', self.save_game) self.interface.show_menu('start') self.combat = Combat(self) self.input = Input.I2d2axis(self.key_map) self.step = 10 self.image = pygame.Surface((0, 0)) self.ground = pygame.Surface((0, 0)) self.rect = self.image.get_rect() self.player = loadPlayer('Yves.ani.gz') self.player.world = self self.deq_handler = handler.DEQHandler(self.player) self.Actors = [] self.Objects = [] self.MainGroup = pygame.sprite.Group(self.player) self.map_maker = MapMaker(self.MainGroup, self.Actors, self.Objects) self.loops = { 'game' : self.game_loop, 'itf' : self.itf_loop, 'combat': self.combat_loop}
def as_leader(batter_name, chaoguiwang=False): while 1: if chaoguiwang: battle = Combat(batter_name, combat_time_limit=99999) else: battle = Combat(batter_name) battle.start(auto_ready=True) if chaoguiwang: time.sleep(5) else: time.sleep(2) logging.debug("waiting for start combat") start_loc = wait_for_color(PartyColor.StartFight, max_time=99999) utilities.random_sleep(0.5, 2) click(start_loc, random_range=3, tired_check=True)
def encounter(player): monster = Monster(player.get_level()) monster_name = monster.get_name() player_name = player.get_name() print(f"\nfind... a {monster_name}! The {monster_name} attacks you!") time.sleep(1) combat_turns = Combat(players=[player, monster]) combat_turns.randomise_first_turn() print_coloured_text(Fore.YELLOW, COMBAT_DIVIDER) while not monster.is_dead() and not player.is_dead(): atk, defnd = combat_turns.get_current_turn() amount_of_damage = atk.attack(defnd.get_defense_rating()) if amount_of_damage: defnd.decrease_health(amount_of_damage) print(atk.colour + SUCCESFUL_ATTACK.format( atk.get_name(), defnd.get_name(), amount_of_damage)) else: print(defnd.colour + FAILED_ATTACK.format(atk.get_name(), defnd.get_name())) print(Fore.RESET) combat_turns.swap_sides() time.sleep(2) print_coloured_text(Fore.YELLOW, COMBAT_DIVIDER) if not player.is_dead(): player.set_xp(monster.get_xp()) print(PLAYER_WINS.format(player_name, monster_name)) time.sleep(1) return PLAYER_REWARD.format(player_name, monster.get_xp(), player.get_health()) else: return PLAYER_DEFEATED.format(player_name, monster_name)
def __init__(self): # init pygame and abstract classes self.clock = pygame.time.Clock() self.screen = Screen() self.gamemap = GameMap() # init game state self.game_state = 'PREPARING' # create player paddle and inventory self.player = Player(100, 50, 50) self.inventory = Inventory() # create sprite Groups for game logic self.player_list = pygame.sprite.Group() self.weapon_list = pygame.sprite.Group() self.expReward_list = pygame.sprite.Group() self.player_list.add(self.player) # sword swing int self.sword_count = 0 # invulnerability timer self.invuln_count = 0 # create rooms # there has to be a better way self.rooms = self.gamemap.get_rooms() self.current_room_num = 0 self.current_room = self.rooms[self.current_room_num] # define default weapon type self.combat = Combat(self.player,self.weapon_list,self.current_room.wall_list, self.current_room.enemy_list, self.current_room.treasure_list, self.expReward_list) self.run()
def enterGame(self): # Set up important game logic variables self.parent.level = None self.parent.units = {} self.parent.inactive_units = {} self.parent.players = {} self.parent.sel_unit_id = None self.parent.turn_number = None # task chain for threaded tasks taskMgr.setupTaskChain('thread_1', numThreads = 2, tickClock = None, threadPriority = TP_normal, frameBudget = None, frameSync = None, timeslicePriority = None) # Init SceneGraph manager self.parent.sgm = SceneGraph(self.parent) # Init Movement self.parent.movement = Movement(self.parent) # Init Camera self.parent.camera = AppCamera(self.parent, 20, 20) # Init Interface self.parent.interface = Interface(self.parent) # All of our graphics components are initialized, request graphics init self.parent.sgm.initLights() # Init combat self.parent.combat = Combat() # Turn number and player on turn self.parent.turn_number = 0 self.parent.turn_player = None self.parent._game_initialized = True
def move_player(self, direction): """ Moves the player in a certain direction given a keypress :param direction: direction to move in :return: """ oldx, oldy = self.map.player_loc x, y = oldx + direction[0], oldy + direction[1] x_limit = (ROW - 1) * TILE_SIZE y_limit = (COLUMN - 1) * TILE_SIZE #don't do anything if the location is too much if x > x_limit or x < 0 or y > y_limit or y < 0: return ret_move_player = self.map.set_player_location((x, y)) self.player.set_location((x, y)) if ret_move_player is True: self.map.player.add_to_inventory(self.treasure.item) self.treasure = Treasure() self.map.treasure_loc = self.treasure.x_y print(self.map.player.inventory.get_items()) self.map.add_item(self.treasure.x_y) elif ret_move_player is 2: print("COMBAT") hp = Combat(self.map.player, self.monster, self.view).init_combat() print(hp) if hp[0] <= 0: self.end_game() return False #self.quit() else: self.map.player.hp = hp[0] self.monster = Monster() while self.map.set_monster_location(self.monster.loc) is False: self.monster.set_location() self.map.monster_loc = self.monster.loc self.map.add_monster(self.monster.loc)
class GameEngine(threading.Thread): def __init__(self,world=None,queue=None,outqueue=None): super(GameEngine,self).__init__(target=self) self.world = world self.world.loadRooms() self.world.loadCharacters() self.world.loadDialogues() self.request_queue = queue self.out_queue = outqueue self.status = 'STARTING' self.current_room = self.world.rooms['testroom'] self.DEBUG = True self.starting_wep = Weapon() self.player = Player(self.starting_wep) self.queue = queue self.exit = False #constructed at 'talk' time self.dialogue_processor = None self.combat_processor = None self.currentCharacterMap = {} self.current_state = ['loading'] def run(self): last_move_time = time.mktime(time.localtime()) move_timer = 90 while True: time.sleep(0.09) curr_time = time.mktime(time.localtime()) self.processMessages() if 'combat' not in self.current_state: if curr_time > last_move_time + move_timer: print('updating mobs') self.updateMonsters() last_move_time = time.mktime(time.localtime()) if self.exit: return True def updateCharacterMap(self): self.currentCharacterMap = {} for roomname, room in self.world.rooms.items(): if room.characters: for character in room.characters: if self.world.characters.get(character).isMovable: self.currentCharacterMap[character] = room def updateMonsters(self): self.updateCharacterMap() for character, room in self.currentCharacterMap.items(): if room.exits: for exit_name,exit in room.exits.items(): print(exit) exit_room = self.world.rooms.get(exit) print(exit_room) if exit_room.mobsAllowed: room.characters.remove(character) exit_room.characters.append(character) if character in self.current_room.characters: if self.world.characters.get(character).attack_on_sight: self.start_combat(character) break def processMessages(self): try: request = self.request_queue.get(block=False) for command,s in request.items(): func = getattr(self, command) func(s) self.queue.task_done() except Empty: pass def do_exit(self,s): self.current_state = 'idle' self.out_queue.put(('exit',True)) def do_look(self,s): log.debug(self.current_room.roomname) log.debug(self.current_room.looktargets) if(s): thing = self.current_room.looktargets.get(s) if thing: self.cout(thing) else: self.cout("Try as you might, you can't see much more about %s\n\n" % s) else: self.cout(self.current_room.roomdesc) def do_go(self,s): exits = self.current_room.exits if s in exits.keys(): self.current_room = self.world.rooms.get(exits[s]) for character in self.current_room.characters: if self.world.characters.get(character).attack_on_sight: self.start_combat(character) self.do_look(None) def do_talk(self,s): if s in self.current_room.talktargets.keys(): self.start_dialogue(self.current_room.talktargets.get(s)) def prompt(self,s): self.out_queue.put(('prompt',self.current_room.roomname + '>')) def cout(self,message): ''' cout: prints output to player console ''' self.out_queue.put(('display' , message + '\n' )) def start_dialogue(self,s): ''' start_dialogue: starts a dialogue ''' #prepare processor self.current_state = ['dialogue'] self.dialogue_processor = DialogueProcessor(world = self.world,dialogue_name = s,game_engine=self) self.dialogue_processor.startDialogue() self.out_queue.put(('dialogue',s)) def dialogue_choice(self,s): self.dialogue_processor.choice(s) def start_combat(self,s): self.current_state = ['combat'] self.combat_processor = Combat(player = self.world.player,character=self.world.characters.get(s),game_engine=self) self.out_queue.put(('combat',s)) def player_attack(self,s): done = self.combat_processor.player_attack(s) if done: self.do_exit(True)
def startcombat(self, *enemies): self.combat = Combat(self, enemies) self.combat.start()
class Plugin: def __init__(self): self.in_combat = False self.free = True self.action = Action.nothing self.queue = [] self.combat = Combat(self.scoundrel_print, self.add_action, self.remove_action, self.queue, self.free, self.action) self.combat_enabled = tk.BooleanVar() self.alert = Alert(self.scoundrel_print) self.chat = Chat(self.scoundrel_print_with_tag) self.alert_enabled = tk.BooleanVar() def set_send_command(self, send_command): self.send_command = send_command self.combat.set_send_command(send_command) def set_echo(self, echo): self.echo = echo self.combat.set_echo(echo) def fatigue_update(self, value): if self.alert_enabled.get(): self.alert.fatigue_update(value) def post_process(self, line): if self.alert_enabled.get(): self.alert.post_process(line) if self.in_combat and self.combat_enabled.get(): self.combat.handle_combat_line(line) elif "You are no longer busy" in line: self.free = True # self.perform_action() elif ("] A" in line) and "You retrieve the line" not in line: self.scoundrel_print("Combat") self.in_combat = True elif "retreat" in line and "You retreat." not in line and "retreat first" not in line and "retreats." not in line: self.scoundrel_print("Retreating") self.add_action(Action.retreat) def add_action(self, action): if action not in self.queue: self.queue.append(action) self.queue.sort() def remove_action(self, action): if action in self.queue: self.queue.remove(action) self.queue.sort() def draw(self, plugin_area): label_frame = tk.LabelFrame(plugin_area, text="Scoundrel") label_frame.grid(row=0, column=0, sticky=tk.N + tk.W + tk.S) self.draw_toggles(label_frame) self.draw_text(label_frame) def draw_toggles(self, label_frame): combat_toggle = tk.Checkbutton(label_frame, text="Combat", variable=self.combat_enabled, command=lambda enabled=self.combat_enabled: self.combat.toggle(enabled)) combat_toggle.grid(row=0, column=0, sticky=tk.N) alert_toggle = tk.Checkbutton(label_frame, text="Alert", variable=self.alert_enabled, command=lambda enabled=self.alert_enabled: self.alert.toggle(enabled)) alert_toggle.grid(row=0, column=3, sticky=tk.N) def draw_text(self, label_frame): scrollbar = tk.Scrollbar(label_frame) scrollbar.grid(row=1, column=4, sticky=tk.N + tk.S) self.scoundrel_output = tk.Text( label_frame, name="scoundrel_output", yscrollcommand=scrollbar.set, wrap=tk.WORD ) self.scoundrel_output.tag_configure('think', fill='blue') scrollbar.config(command=self.scoundrel_output.yview) self.scoundrel_output.scrollbar = scrollbar self.scoundrel_output.grid(row=1, column=0, columnspan=5, sticky=tk.N + tk.W + tk.S) def scroll_output(self): self.scoundrel_output.see(tk.END) def scoundrel_print(self, line): self.scoundrel_print_with_tag(line, None) def scoundrel_print_with_tag(self, line, tag): self.scoundrel_output.insert(tk.END, line + "\n", tag) self.scroll_output() def perform_action(self): if self.in_combat and self.combat_enabled.get(): self.combat.perform_action()
def Bleeding_method(self, target, magnitude): Combat.modifyResource(target, "HP", float(target.HP) * magnitude / -100)
def Damage_over_time_method(self, target, magnitude): dam = Combat.calcDamage(None, target, magnitude, magnitude, self.element, "Normal Hit") Combat.lowerHP(target, dam)
from combat import Combat from warrior import Warrior from mage import Mage from ranger import Ranger if __name__ == "__main__": testPlayer = Warrior() testMonster = Warrior() print "You attack a testMonster" Combat(Warrior(), testMonster) print "You attack a mage" Combat(Mage(), Mage()) print "You attack a Ranger" Combat(Mage(), Ranger())
def tearDown(self): Combat.stop()
from random import randint from combat import Combat # Liste contenant les pokémons listPokemons = [] Salameche = Combat('Salameche', 'Feu', ['Flammèche', 'Griffe', 'Charge', 'Poing de feu'], { 'ATTACK': 4, 'DEFENSE': 2 }) Reptincel = Combat('Reptincel', 'Feu', ['Flammèche', 'Griffe', 'Lance-flammes', 'Poing de feu'], { 'ATTACK': 6, 'DEFENSE': 5 }) Dracaufeu = Combat('Dracaufeu', 'Feu', ['Lance-flammes', 'Vol', 'Rafale Feu', 'Poing de feu'], { 'ATTACK': 12, 'DEFENSE': 8 }) Carapuce = Combat('Carapuce', 'Eau', ['Bulles d\'O', 'Charge', 'Coup d\'Boule', 'Surf'], { 'ATTACK': 3, 'DEFENSE': 3 }) Carabaffe = Combat('Carabaffe', 'Eau', ['Bulles d\'O', 'Pistolet à O', 'Coup d\'Boule', 'Surf'], { 'ATTACK': 5, 'DEFENSE': 5
class Game(object): ## MAIN GAME CLASS def __init__(self): # init pygame and abstract classes self.clock = pygame.time.Clock() self.screen = Screen() self.gamemap = GameMap() # init game state self.game_state = 'PREPARING' # create player paddle and inventory self.player = Player(100, 50, 50) self.inventory = Inventory() # create sprite Groups for game logic self.player_list = pygame.sprite.Group() self.weapon_list = pygame.sprite.Group() self.expReward_list = pygame.sprite.Group() self.player_list.add(self.player) # sword swing int self.sword_count = 0 # invulnerability timer self.invuln_count = 0 # create rooms # there has to be a better way self.rooms = self.gamemap.get_rooms() self.current_room_num = 0 self.current_room = self.rooms[self.current_room_num] # define default weapon type self.combat = Combat(self.player,self.weapon_list,self.current_room.wall_list, self.current_room.enemy_list, self.current_room.treasure_list, self.expReward_list) self.run() def terminate(self): pygame.quit() sys.exit() def run(self): self.screen.to_screen(self.current_room.wall_list, self.screen.mapSurf) self.game_state = 'RUNNING' while 1: self.clock.tick(60) # event processing for event in pygame.event.get(): if event.type == pygame.QUIT: self.terminate() if event.type == pygame.KEYDOWN: self.keyboardDown(event) if event.type == pygame.KEYUP: self.keyboardUp(event) # game logic if self.game_state == 'RUNNING': self.gameplay_modelUpdate() self.gameplay_viewerUpdate(self.screen) pygame.quit() def add_treasure(self, treasure): text = 'You found %s. %s' % (treasure.title, treasure.desc) self.inventory.add_to_inventory(treasure, self.player) # self.screen.draw_alert(text) def blit_alpha(self, target, source, location, opacity): x = location[0] y = location[1] temp = pygame.Surface((source.get_width(), source.get_height())).convert() temp.blit(target, (-x, -y)) temp.blit(source, (0, 0)) temp.set_alpha(opacity) target.blit(temp, location) def keyboardDown(self, evt): if evt.key == pygame.K_ESCAPE: self.doMenu() if self.game_state == 'RUNNING': if evt.key == pygame.K_LCTRL: self.combat.weaponSelect() if evt.key == pygame.K_LEFT: self.player.change_speed(-5, 0) if evt.key == pygame.K_RIGHT: self.player.change_speed(5, 0) if evt.key == pygame.K_UP: self.player.change_speed(0, -5) if evt.key == pygame.K_DOWN: self.player.change_speed(0, 5) if self.combat.weapon_type == 'ranged': self.combat.weaponAttack(evt,self.player.rect,'arrah',3) if self.combat.weapon_type == 'melee': self.combat.weaponAttack(evt,self.player.rect,'swadia',40) def doMenu(self): if self.game_state == 'RUNNING': self.game_state = 'PAUSED' else: self.game_state = 'RUNNING' def keyboardUp(self, evt): if evt.key == pygame.K_LEFT: self.player.change_speed(5, 0) if evt.key == pygame.K_RIGHT: self.player.change_speed(-5, 0) if evt.key == pygame.K_UP: self.player.change_speed(0, 5) if evt.key == pygame.K_DOWN: self.player.change_speed(0, -5) def gameplay_modelUpdate(self): self.player.move(self.current_room.wall_list) for w in self.weapon_list: self.combat.weaponLogic(w) for m in self.current_room.enemy_list: self.monsterLogic(m) for l in self.current_room.treasure_list: self.lootLogic(l) for r in self.expReward_list: r.counter -= 1 if r.counter == 0: self.expReward_list.remove(r) def swingSword(self, evt): if evt.key == pygame.K_w: sword = Weapon('up',self.player.rect.centerx, self.player.rect.centery-50,'swadia',40) sword.attk(0,1) self.sword_count = 5 self.sword_list.add(sword) elif evt.key == pygame.K_a: sword = Weapon('left',self.player.rect.centerx-55, self.player.rect.centery,'swadia',40) sword.attk(-1,0) self.sword_count = 5 self.sword_list.add(sword) elif evt.key == pygame.K_s: sword = Weapon('down',self.player.rect.centerx, self.player.rect.centery+6,'swadia',40) sword.attk(0,-1) self.sword_count = 5 self.sword_list.add(sword) elif evt.key == pygame.K_d: sword = Weapon('right',self.player.rect.centerx+6, self.player.rect.centery,'swadia',40) sword.attk(1,0) self.sword_count = 5 self.sword_list.add(sword) def gameplay_viewerUpdate(self, screen): # updates visual elements screen.screen.fill(BLK) screen.spriteSurf.fill(screen.bgcolor); screen.GUISurf.fill(screen.bgcolor); if self.game_state == 'RUNNING': screen.to_screen(self.current_room.enemy_list, screen.spriteSurf) screen.to_screen(self.current_room.treasure_list, screen.spriteSurf) screen.to_screen(self.expReward_list, screen.spriteSurf) screen.to_screen(self.weapon_list, screen.spriteSurf) screen.to_screen(self.player_list, screen.spriteSurf) screen.GUI_.render() screen.update() pygame.display.flip() def monsterLogic(self, m): m.move(self.current_room.wall_list) enemy_hit_player = pygame.sprite.spritecollide(self.player, self.current_room.enemy_list, False) for enemy in enemy_hit_player: # deal damage to player if self.invuln_count == 0: self.player.take_damage(enemy.damage, enemy.rect.x, enemy.rect.y) self.invuln_count = 1000 if self.player.health <= 0: pass else: self.invuln_count -= 1 def lootLogic(self, l): treasure_picked_up = pygame.sprite.spritecollide(self.player, self.current_room.treasure_list, True) for treasure in treasure_picked_up: # pick up loot! self.add_treasure(treasure)
class Bot(object): server = None players = [] command = 0 commands = [] combat = None connected = False reloading = False counter = 0 ammo = settings.AMMO def __init__(self, server): self.server = server def handle_commands(self): self.command = 0 for i in self.commands: try: result = i[0](*i[1]) if isinstance(result, int): self.command |= result else: self.commands[:] = [x for x in self.commands if x != i] except ActionFinished as e: self.commands[:] = [x for x in self.commands if x != i] if settings.DEBUG or DEBUG_BOT: print(e) except AttributeError: self.commands[:] = [x for x in self.commands if x != i] def is_there(self, command, args=None): for i in xrange(len(self.commands)): if args: if [command, args] == self.commands[i]: return i else: if self.commands[i][0] == command: return i return -1 def move(self, direction, percentage=1.0): assert isinstance(direction, str) assert isinstance(percentage, float) if self.is_there(self.combat.move, [direction.upper(), percentage]) == -1: self.commands.append([self.combat.move, [direction.upper(), percentage]]) def kill_some_player(self): if self.is_there(self.combat.kill) == -1: player = settings.MY_NR while player == settings.MY_NR or not self.players[player].alive: player = random.randint(0, len(self.players) - 1) self.commands.append([self.combat.kill, [player]]) def algorithm(self): #self.move("RIGHT", 0.5) self.kill_some_player() self.handle_commands() def run(self): self.server.hello() self.combat = Combat(self.server) while True: self.players = self.server.get_players(self.players) if self.players: self.combat.update(self.players) self.algorithm() self.server.send_command(self.command)
elif direction == "help": show_help() continue elif direction == "quit": exit_immediatly = True break else: print("Command not recognized and/or you aren't allowed to go there.") continue player.pos = player.pos_x, player.pos_y counter += 1 for monster in monster_spawner.monster_list: if player.pos == monster.pos: print("You have encountered a {}".format(monster)) battle = Combat() while player.hit_points > 0 and monster.hit_points > 0: battle.weapon_attack(player, monster) battle.weapon_attack(monster, player) if player.hit_points <= 0: print("You have been defeated by {}".format(monster)) game_over = True break elif monster.hit_points <= 0: player.experience += monster.experience print("Player has defeated {}, earning {} experience".format(monster, monster.experience)) monster_spawner.monster_list.remove(monster) if game_over: break
def start_combat(self,s): self.current_state = ['combat'] self.combat_processor = Combat(player = self.world.player,character=self.world.characters.get(s),game_engine=self) self.out_queue.put(('combat',s))
class AdventureGame: def __init__(self, gamefile, sheet): self.player = Player(self) # pass self as controller - access to gameworld for Player.move() self.parser = Parser(self) self.initialize_world(gamefile, sheet) # load game dict, and define player start location self.valid_player_movements = [] # Assigned by generate valid movements. self.gamestate = 'normal' # Normal or Combat self.action_log = deque(maxlen=5) self.combat = None def get_command(self): # TODO: error check; if invalid choice, prompt again with valid choices. usrinput = input('>> ').lower().strip() # TODO: implement 'help' command. selected_action = self.parser.parse_input(usrinput) while not selected_action: print(self.parser.error_message) usrinput = input('>> ').lower().strip() selected_action = self.parser.parse_input(usrinput) return (selected_action) # A method or tuple of method, target obj def execute_action(self, method_or_tuple): logging.debug('Arg is of type {}'.format(type(method_or_tuple))) if isinstance(method_or_tuple, tuple): method, target = method_or_tuple method = getattr(self.player, method.__name__) method(target) consequences = self.player.current_location.trigger_actions.get(method.__name__, {}).get(target, None) # Consequences? if consequences: logging.debug('CONSEQUENCES: {}'.format(consequences)) for func in consequences: func() else: method = getattr(self.player, method_or_tuple.__name__, None) or getattr(self, method_or_tuple.__name__) method() def print_actions_and_objects(self): print('\n' + '*' * 15) for m in self.valid_player_movements: print('\t\t{}'.format(m.name.title())) print('\t\tView Inventory') print("OBJECTS IN ROOM:\n") if not self.player.current_location.objects: print('\t\t None') else: for obj in self.player.current_location.objects: print('\t\t{}'.format(obj.name.title())) def check_location_exists(self,dx,dy): curr_x, curr_y = self.player.current_location.coords new = (curr_x + dx, curr_y + dy) if self.gameworld.get(new, None): return True return False def generate_valid_player_movements(self): movements = [actions.MoveNorth, actions.MoveEast, actions.MoveSouth, actions.MoveWest] directions = [(0,-1), (1,0), (0,1), (-1,0)] valid_movements = [m for (m,delta) in zip(movements,directions) if self.check_location_exists(*delta)] return valid_movements def run(self): while self.player.isalive(): # Separate combat vs. normal game state here? command = self.get_command() self.execute_action(command) def initialize_world(self, file, sheet): wb = xlrd.open_workbook(file) sheet = wb.sheet_by_name(sheet) self.gameworld = {} starting_location_found = False for rown in range(0,sheet.nrows): for coln in range(0,sheet.ncols): locname = sheet.cell(rown,coln).value if locname.startswith('!START'): if starting_location_found: # Duplicate starting declarations in game file print("""Game file {} contains multiple starting declarations! Please edit your file to include only a single starting location, declared with a "!START" location prefix""".format(file)) sys.exit(1) starting = (coln, rown) starting_location_found = True locname = locname[6:] # Strip !STARTING declaration location = getattr(importlib.import_module('locations'), locname, None) self.gameworld[coln, rown] = location(xcoord=coln, ycoord=rown, controller=self, name=locname) if location else None try: starting except NameError: print("""Game file {}, sheet {} does not include a starting location! Add declaration prefix "!START" to the location you wish player to begin in.""".format(file, sheet)) sys.exit(1) self.player.setlocation(self.gameworld[starting]) def quit(self): y_n = input("Are you sure you want to quit?").lower() if y_n in ('yes','y'): sys.exit() def log(self): for a in self.action_log: print(a+'\n') def help(self): print("Helping you! :)") def save(self): print('Saving game...') def startcombat(self, *enemies): self.combat = Combat(self, enemies) self.combat.start()
continue elif direction == "quit": exit_immediatly = True break else: print( "Command not recognized and/or you aren't allowed to go there." ) continue player.pos = player.pos_x, player.pos_y counter += 1 for monster in monster_spawner.monster_list: if player.pos == monster.pos: print("You have encountered a {}".format(monster)) battle = Combat() while player.hit_points > 0 and monster.hit_points > 0: battle.weapon_attack(player, monster) battle.weapon_attack(monster, player) if player.hit_points <= 0: print("You have been defeated by {}".format(monster)) game_over = True break elif monster.hit_points <= 0: player.experience += monster.experience print( "Player has defeated {}, earning {} experience".format( monster, monster.experience)) monster_spawner.monster_list.remove(monster) if game_over:
def Set_movement_AP_cost_method_reverse(self, target, magnitude): Combat.setMovementCost(target, -1)
def startCombat(self, combatants, surprised=[]): for character in self.world.characters: if character.visual: character.visual.idle() self.combat = Combat(self, combatants, surprised=surprised) self.combat.beginTurn()
def as_member(batter_name): while 1: battle = Combat(batter_name) battle.start(auto_ready=True) time.sleep(2)
class Application(CEGUIApplicationBase, PychanApplicationBase): def __init__(self, settings): #self.ar = [] #for i in xrange(512): # self.ar.append(' ' * memtest.MEGA) #self.a = ' ' * memtest.MEGA * 1024 #memtest.alloc_max_str() #memtest.alloc_max_array() print("* Initializing application...") super(Application, self).__init__(settings) self.settings = settings self.model = self.engine.getModel() self.mapLoader = fife.MapLoader(self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getRenderBackend()) self.objectLoader = fife.ObjectLoader( self.model, self.engine.getVFS(), self.engine.getImageManager(), self.engine.getAnimationManager()) # self.atlasLoader = fife.AtlasLoader(self.model, # self.engine.getVFS(), # self.engine.getImageManager()) self.map = None self.world = None self.view = None self.change_res = False self.eventmanager = self.engine.getEventManager() self.mouselistener = MouseListener(self) self.keylistener = KeyListener(self) self.eventmanager.addMouseListenerFront(self.mouselistener) self.eventmanager.addKeyListenerFront(self.keylistener) self.soundmanager = self.engine.getSoundManager() self.soundmanager.init() self.imagemanager = self.engine.getImageManager() print("* Application initialized!") self.gui = GUI(self) self.real_timeline = RealTimeline() self.engine.getTimeManager().registerEvent(self.real_timeline) self.game_speed = 1 #print self.engine.getRenderBackend().isDepthBufferEnabled() # self.loadAtlas("objects/nature.xml") print("* Loading objects...") for import_object in importobjects.import_list: self.loadObject(import_object) if self.settings.get("gameplay", "PreloadSprites", True): self.imagemanager.reloadAll() print("* Objects loaded!") self.sounds = {} self.music = None self.music_name = "" #self.music = self.soundmanager.createSoundEmitter("music/SFT-Two Mapple Inn.ogg") # self.sound_attack = self.soundmanager.createSoundEmitter("sfx/attack-1.ogg") #self.music.looping = True if not self.settings.get("FIFE", "PlaySounds"): self.soundmanager.setVolume(0.0) #self.music.play() self.cursor = self.imagemanager.load("gui/cursors/Mousecursor01.png") self.cursor.setXShift(-4) #self.imagemanager.free("gui/cursors/Mousecursor01.png") #self.imagemanager.reload("gui/cursors/Mousecursor01.png") self.map_cursor = self.imagemanager.load( "gui/cursors/Mousecursor02.png") self.map_cursor.setXShift(-29) self.map_cursor.setYShift(-29) #self.null_image = self.imagemanager.loadBlank(1, 1) #self.engine.getCursor().set(self.null_image) #self.engine.getCursor().setDrag(self.cursor, -4, 0) self.engine.getCursor().set(self.cursor) self.unloadMap() self.lastmem = 0 def createListener(self): self._listener = Listener(self) return self._listener def playSound(self, sound): if sound not in self.sounds: self.sounds[sound] = self.soundmanager.createEmitter("sfx/" + sound + ".ogg") self.sounds[sound].play() def loadObject(self, filename, pingpong=False, object_name=""): if self.objectLoader.isLoadable(filename): self.objectLoader.load(filename) else: print("WARNING: Can't load", filename) def loadAtlas(self, filename): if self.atlasLoader.isLoadable(filename): self.atlasLoader.load(filename) else: print("WARNING: Can't load", filename) def loadMap(self, map_name): print("* Loading objects for map", map_name) for import_object in importobjects.import_by_map.get(map_name, ()): self.loadObject(import_object) if self.settings.get("gameplay", "PreloadSprites", True): self.imagemanager.reloadAll() print("* Objects loaded!") filename = str("maps/" + map_name + ".xml") if self.mapLoader.isLoadable(filename): print("* Loading map", map_name) self.map = self.mapLoader.load(filename) self.camera = self.map.getCamera("main_camera") self.maplayer = self.map.getLayer("buildings_layer") #print "imagemanager.reloadAll()" #self.imagemanager.reloadAll() print("* Map loaded!") else: print("WARNING: Can't load map") if music.music_by_map.get(map_name, self.music_name) != self.music_name: self.music_name = music.music_by_map[map_name] if self.music: self.music.stop() self.music = self.soundmanager.createEmitter("music/" + self.music_name + ".ogg") self.music.setLooping(True) self.music.play() def unloadMap(self): self.real_timeline.clear() if self.world: self.world.visual.cleanUp() if self.map: self.model.deleteMap(self.map) if self.imagemanager.getMemoryUsed() > 700000000: self.imagemanager.freeUnreferenced() print("Memory used by the image manager:", "{:,}".format(self.imagemanager.getMemoryUsed())) self.map = None self.world = None self.view = None self.change_map_name = None self.combat = None self.cutscene = None self.exploration = None def gameOver(self): self.unloadMap() self.gui.showMainMenu() def newGame(self): self.loadMap(self.world.current_map_name) self.world.visual = WorldVisual(self, self.maplayer, self.world) self.view = View(self) camera_loc = self.view.camera.getLocation() camera_loc.setLayerCoordinates(self.world.camera_coords) self.view.camera.setLocation(camera_loc) self.gui.showHUD() self.unpause(True) self.change_map_name = None self.exploration = Exploration(self) print("* Game started!") def loadMapTest(self, map_name, pc_coords, pc_sprite): print("* Loading map test...") self.unloadMap() self.world = World(self) #self.world = World(self, "Ashgrove") #campaign.init(self.world) self.world.current_map_name = map_name if not pc_sprite.endswith(".xml"): print("Incorrect sprite file name", pc_sprite) return pc_sprite_name = pc_sprite.split("\\")[-1][:-4] print(pc_sprite, pc_sprite_name) pc = self.world.addCharacterAt(pc_coords, map_name, "test_character", "test character", str(pc_sprite_name)) self.world.enablePlayerCharacter(pc) self.loadObject("objects\\Sprites - Characters\\" + str(pc_sprite)) self.loadMap(self.world.current_map_name) self.world.visual = WorldVisual(self, self.maplayer, self.world) self.view = View(self) #self.view.camera.getLocationRef().setLayerCoordinates( # fife.ModelCoordinate(40, 0, 0)) self.gui.showHUD() self.unpause(True) self.change_map_name = None self.exploration = Exploration(self) print("* Map loaded!") def saveGame(self, save_name): self.world.refresh() serializer.save(self.world, "saves/" + save_name + ".sav") print("* Game saved!") def loadGame(self, save_name): self.loadMap(self.world.current_map_name) self.world.application = self self.world.visual = WorldVisual(self, self.maplayer, self.world) self.view = View(self) self.gui.showHUD() self.unpause(True) self.change_map_name = None self.exploration = Exploration(self) print("* Game loaded!") def changeMap(self, map_name): self.real_timeline.clear() self.world.visual.cleanUp() self.world.visual = None self.world.current_map_name = map_name if self.map: self.model.deleteMap(self.map) if self.imagemanager.getMemoryUsed() > 700000000: self.imagemanager.freeUnreferenced() print("Memory used by the image manager:", "{:,}".format(self.imagemanager.getMemoryUsed())) self.loadMap(self.world.current_map_name) self.world.visual = WorldVisual(self, self.maplayer, self.world) self.view = View(self) self.gui.showHUD() self.unpause(True) self.exploration = Exploration(self) def prepareChangeMap(self, map_name): if map_name == self.world.current_map_name: return print("* Changing map...") self.pause(True) self.gui.loading.showFade(lambda: self.prepareChangeMap2(map_name), map=map_name) def prepareChangeMap2(self, map_name): self.change_map_name = map_name def prepareNewGame(self): print("* Starting new game...") self.unloadMap() self.world = World(self) #self.world = World(self, "Ashgrove") Campaign.init(self.world) #self.real_timeline.addTimer(Timer("new game", 50, 1, self.newGame)) self.gui.loading.showFade(self.newGame, map=self.world.current_map_name) def prepareLoadGame(self, save_name): self.unloadMap() self.world = serializer.load("saves/" + save_name + ".sav") #self.real_timeline.addTimer(Timer("load game", 50, 1, self.loadGame, args=save_name)) self.gui.loading.showFade(lambda: self.loadGame(save_name), map=self.world.current_map_name) def prepareLoadMapTest(self, map_name, pc_coords, pc_sprite): self.gui.loading.showFade( lambda: self.loadMapTest(map_name, pc_coords, pc_sprite), map=map_name) def setTimeMultiplier(self, multiplier): self.real_timeline.multiplier = multiplier self.model.setTimeMultiplier(multiplier) def unpause(self, init=False): if init: self._paused = False self.force_paused = False self.world.visual.game_timeline.paused = False self.setTimeMultiplier(self.game_speed) def pause(self, override=False): if override: self._paused = True self.world.visual.game_timeline.paused = True self.setTimeMultiplier(0) def togglePause(self): if self.force_paused: return if self._paused: self._paused = False self.unpause() else: self._paused = True self.pause() @property def paused(self): return self._paused or self.force_paused def forcePause(self): gui_pause = (self.gui.dialogue.window.isVisible() or self.gui.game_menu.window.isVisible() or self.gui.preferences.window.isVisible() or self.gui.help.window.isVisible() or self.gui.save_load.window.isVisible() or self.gui.book.window.isVisible() or self.gui.journal.window.isVisible() or self.gui.character_sheet.window.isVisible() or self.gui.inventory.window.isVisible() or self.gui.looting.window.isVisible() or self.gui.weapon_info.window.isVisible() or self.gui.loading.window.isVisible()) #if gui_pause and not self.force_paused: if gui_pause or self._paused: self.pause() #if not gui_pause and self.force_paused and not self._paused: else: self.unpause() self.force_paused = gui_pause # obsolete? @property def current_character(self): return self.world.player_character def startCombat(self, combatants, surprised=[]): for character in self.world.characters: if character.visual: character.visual.idle() self.combat = Combat(self, combatants, surprised=surprised) self.combat.beginTurn() def startCutscene(self, Cutscene): self.cutscene = Cutscene(self) self.gui.hideAll() def startDialogue(self, dialogue, npc=None, pc=None): if isinstance(dialogue, str): dialogue = loadDialogue(dialogue) self.gui.dialogue.start( DialogueState(dialogue, self.world, npc=npc, pc=pc)) def changeRes(self): self.change_res = True self.engine.getCursor().setNativeImageCursorEnabled( self.settings.get("FIFE", "NativeImageCursor", False)) def changeRes2(self): #PyCEGUIOpenGLRenderer.OpenGLRenderer.grabTextures( # PyCEGUI.System.getSingleton().getRenderer()) self.change_res = False old_mode = self.engine.getRenderBackend().getCurrentScreenMode() new_mode = self.engine.getDeviceCaps().getNearestScreenMode( int( self.settings.get("FIFE", "ScreenResolution", "1024x768").split("x")[0]), int( self.settings.get("FIFE", "ScreenResolution", "1024x768").split("x")[1]), self.settings.get("FIFE", "BitsPerPixel", "0"), self.settings.get("FIFE", "RenderBackend", "OpenGL"), self.settings.get("FIFE", "FullScreen", False)) if (old_mode.getWidth() == new_mode.getWidth() and old_mode.getHeight() == new_mode.getHeight() and old_mode.isFullScreen() == new_mode.isFullScreen() and self.engine.getRenderBackend().isVSyncEnabled() == self.settings.get("FIFE", "VSync", True)): return self.engine.getRenderBackend().setVSyncEnabled( self.settings.get("FIFE", "VSync", True)) self.engine.changeScreenMode(new_mode) if not self.view: return self.camera.setViewPort( fife.Rect(0, 0, self.engine.getRenderBackend().getScreenWidth(), self.engine.getRenderBackend().getScreenHeight())) self.camera.refresh() #PyCEGUIOpenGLRenderer.OpenGLRenderer.restoreTextures( # PyCEGUI.System.getSingleton().getRenderer()) #PyCEGUI.System.getSingleton().notifyDisplaySizeChanged(PyCEGUI.Sizef( # int(self.settings.get("FIFE", "ScreenResolution", "1024x768").split("x")[0]), # int(self.settings.get("FIFE", "ScreenResolution", "1024x768").split("x")[1]))) def _pump(self): if self.change_res: self.changeRes2() return if self.imagemanager.getMemoryUsed() != self.lastmem: print("Memory used by the image manager:", "{:,}".format(self.imagemanager.getMemoryUsed())) #memtest.alloc_max_str() #memtest.alloc_max_array() self.lastmem = self.imagemanager.getMemoryUsed() #if self.imagemanager.getMemoryUsed() > 800000000: # self.imagemanager.freeUnreferenced() self.gui.pump() #if self.world: if self.view: self.forcePause() if self.change_map_name and (self.world.current_map_name != self.change_map_name): self.changeMap(self.change_map_name) #memtest.alloc_max_str() #memtest.alloc_max_array() elif self.cutscene: if not self.cutscene.pump(): self.cutscene = None self.gui.hud.show() #try: # self.cutscene.pump() #except StopIteration: # self.cutscene = None # self.gui.hud.show() elif self.combat: self.combat.pump() elif self.exploration and not self.paused: self.exploration.pump(self.real_timeline.last_frame_time) #if self.world: # if self.world.visual: if self.view: self.view.pump() self.gui.pump2() if self._listener.quitrequested: self.quit()
class EnemyRoom(MapTile): """ A subclass of the MapTile Variables: Inherited from MapTile: x <int> y <int> player <Player> room_type <int> adjacent_movements [<Actions>] all_moves [<Actions>] combat <bool> enemy <Enemy> Methods: Inherited from MapTile: get_combat() Returns combat variable intro_text() Returns string describing the room modify_player() Enemy attacks the player adjacent_moves() Returns a list of possible directions the player can move set_available_actions () Appends actions to all_moves """ def __init__(self, x, y, player, enemy): self.enemy = enemy self.enemyCombat = Combat(player, self.enemy) super().__init__(x, y, player) self.combat = True self.room_type = 3 self.update_available_actions = True def modify_player(self): """ Continually attacks the player with the enemy while the enemy is alive """ if self.enemy.is_alive(): self.enemyCombat.enemy_attack() combat_string = self.enemyCombat.combat_description() else: self.room_type = 4 if (self.update_available_actions): self.set_available_actions() self.update_available_actions = False self.combat = False def set_available_actions(self): """ Changes the base available actions, if the enemy is alive only allow the player to attack or flee otherwise the default moves """ if self.enemy.is_alive(): self.all_moves = [ Actions.Flee(tile=self), Actions.Attack(combatClass=self.enemyCombat) ] self.all_moves.append(Actions.ViewInventory()) self.all_moves.append(Actions.Equip()) self.all_moves.append(Actions.ViewCharacter()) # self.all_moves.append(Actions.Quit()) else: self.all_moves = self.adjacent_movements self.all_moves.append(Actions.ViewInventory()) self.all_moves.append(Actions.Equip()) self.all_moves.append(Actions.ViewCharacter())
def fight(): Combat.fightEnemy()
def runningDonjon(self): look_level = False look_level2 = False look_level3 = False mp = 0 while self.listekey[pygame.K_SPACE] == False: self.__checkEvent() if (self.deplacement() == 1): return 1 #print '{}: tick={}, fps={}'.format(i+1, clock.tick(fps), clock.get_fps()) clock.tick(32) monstre = None for x in self.liste_monstre[self.actuel]: if x.collide_box_interact.mask.overlap( self.perso.donjon_mask, ((self.perso.pos_x + 10) - x.collide_box_interact.pos_x, (self.perso.pos_y + 90) - x.collide_box_interact.pos_y)): #self.cam.screen.blit(x.collide_box_interact.img_collide,(x.collide_box_interact.pos_x,x.collide_box_interact.pos_y)) #pygame.display.update() #self.pieces[self.actuel].wait() self.perso.monstre_near = True monstre = x if self.perso.monstre_near and monstre != None: for i in monstre.group_monster: i.img = list_img_monstre[i.type - 1] f = Combat(self.game, monstre.group_monster) f.affichage() if f.player.crew_mate[0].hp > 0 or f.player.crew_mate[ 1].hp > 0 or f.player.hp > 0: inv_chest = Inventaire(7, 7) nbre_max_loot_possibles = 3 * len(monstre.group_monster) items_dropable = [] for x in monstre.group_monster: items_dropable.append(key[x.armor[1]]) items_dropable.append(key[x.armor[4]]) self.liste_monstre[self.actuel].remove(x) self.perso.xp += x.xp self.perso.crew_mate[0].xp += x.xp self.perso.crew_mate[1].xp += x.xp if self.perso.levelupchange(): look_level = True if self.perso.crew_mate[0].levelupchange(): look_level2 = True if self.perso.crew_mate[1].levelupchange(): look_level3 = True nbre_loot = random.randint(0, nbre_max_loot_possibles) for i in range(nbre_loot): chance_drop = random.randint(1, 20) if chance_drop == 1: num_item_drop = random.randint( 0, len(items_dropable) - 1) inv_chest.ajouteritems( items_dropable[num_item_drop]) try: items_dropable.remove( items_dropable[num_item_drop]) except: pass self.cam.liste_coffre.append( Chest(self.perso.pos_x, self.perso.pos_y, pygame.transform.scale(monstre_loot, (32, 32)), "Coffre", "Coffre", inv_chest)) self.cam.liste_coffre[-1].update_pos_collide() else: return -1 monstre = None if look_level: mp += 1 if mp >= 50 and mp <= 200: self.cam.screen.blit( pygame.transform.scale( pygame.image.load( path.join(path_addon, 'Image/lvl_up.png')), (WINDOWS_SIZE[0] // 20, WINDOWS_SIZE[1] // 20)), (self.player.pos_x + 100 + center_x, self.player.pos_y + center_y)) elif mp > 200: look_level = False mp = 0 if look_level2: mp += 1 if mp >= 50 and mp <= 200: self.cam.screen.blit( pygame.transform.scale( pygame.image.load( path.join(path_addon, 'Image/lvl_up.png')), (WINDOWS_SIZE[0] // 20, WINDOWS_SIZE[1] // 20)), (self.player.crew_mate[0].pos_x + 100 + center_x, self.player.crew_mate[0].pos_y + center_y)) elif mp > 200: look_level2 = False mp = 0 if look_level3: mp += 1 if mp >= 50 and mp <= 200: self.cam.screen.blit( pygame.transform.scale( pygame.image.load( path.join(path_addon, 'Image/lvl_up.png')), (WINDOWS_SIZE[0] // 20, WINDOWS_SIZE[1] // 20)), (self.player.crew_mate[1].pos_x + 100 + center_x, self.player.crew_mate[1].pos_y + center_y)) elif mp > 200: look_level3 = False mp = 0 self.cam.afficher() self.listekey[pygame.K_SPACE] = False
class World(object): # I added it only there for fun load_image = loadImage def __init__(self, display_surface, settings): self.display = display_surface self.display_rect = self.display.get_rect() self.display_center = self.display_rect.center self.settings = settings self.key_map = settings.get_key_map() self.delayed_functions = [] self.state = 'ift' self.prev_state = 'game' self.Saver = gss.Saver('./saves/') self.Loader = gss.Loader('./saves/') self.interface = Interface(self) self.interface.menu.store_action('new_game', self.new_game) self.interface.menu.store_action('load_game', self.load_game) self.interface.menu.store_action('save_game', self.save_game) self.interface.show_menu('start') self.combat = Combat(self) self.input = Input.I2d2axis(self.key_map) self.step = 10 self.image = pygame.Surface((0, 0)) self.ground = pygame.Surface((0, 0)) self.rect = self.image.get_rect() self.player = loadPlayer('Yves.ani.gz') self.player.world = self self.deq_handler = handler.DEQHandler(self.player) self.Actors = [] self.Objects = [] self.MainGroup = pygame.sprite.Group(self.player) self.map_maker = MapMaker(self.MainGroup, self.Actors, self.Objects) self.loops = { 'game' : self.game_loop, 'itf' : self.itf_loop, 'combat': self.combat_loop} def new_game(self): self.load_map('01_test.map.xml') self.player.prev_dir = 'down' self.player.image = self.player.animations['down'][3] self.player.events = [] self.player.quests = {} self.state = 'game' def save_game(self, filename): self.Saver.prepare(self.map_maker.map_filename, 'map_filename') self.Saver.prepare(self.player.events, 'events') self.Saver.prepare(self.player.quests, 'quest_events') self.Saver.prepare(self.player.rect.center, 'position') self.Saver.prepare(self.player.animations[ \ self.player.prev_dir].index(self.player.image), 'image_id') self.Saver.prepare(self.player.prev_dir, 'previous_direction') self.Saver.save(filename) self.state = 'game' def load_game(self, filename): self.Loader.load(filename) self.player.events = self.Loader.get('events') self.player.quests = self.Loader.get('quest_events') self.player.prev_dir = self.Loader.get('previous_direction') self.player.image = self.player.animations[self.player.prev_dir] \ [self.Loader.get('image_id')] self.load_map(self.Loader.get('map_filename'), \ self.Loader.get('position')) self.state = 'game' def load_map(self, map_name, position=None): self.map_maker.make(map_name) if position: self.map_maker.start_position = position self.ground = self.map_maker.ground_image self.rect = self.ground.get_rect() self.image = pygame.Surface(self.rect.size) self.rect.topleft = \ (self.display_rect.width/2-self.map_maker.start_position[0], \ self.display_rect.height/2 - self.map_maker.start_position[1]) self.player.set_center(self.map_maker.start_position) self.combat.init_map(self.ground) def focus(self): """New function to set the focus on the player""" center = self.player.rect.center self.rect.topleft = (self.display_rect.width/2-center[0], \ self.display_rect.height/2-center[1]) # Keeps the screen inside the ground rect if self.rect.x > 0: self.rect.x = 0 elif self.rect.x - self.display_rect.width < -self.rect.width: self.rect.x = -(self.rect.width - self.display_rect.width) if self.rect.y > 0: self.rect.y = 0 elif self.rect.y - self.display_rect.height < -self.rect.height: self.rect.y = -(self.rect.height - self.display_rect.height) def clamp(self, rect): return rect.clamp(self.ground.get_rect()) def check_collision(self, user, old_rect, new_rect): self.MainGroup.remove(user) collide = False for sprite in self.MainGroup.sprites(): if new_rect.colliderect(sprite.crect): collide = True self.MainGroup.add(user) if collide: return old_rect else: return new_rect def add_delayed_function(self, function): """Store a function to be called in the next main loop.""" self.delayed_functions.append(function) def draw(self): group = zOrder(self.MainGroup) self.image.blit(self.ground, (0, 0)) group.draw(self.image) #for sprite in self.MainGroup.sprites(): # sprite.drawRects(self.image) self.display.blit(self.image, self.rect.topleft) #group.empty() def key_loop(self): for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: self.interface.show_menu() elif event.key == self.key_map['action']: self.action() elif event.key == K_f: for actor in self.Actors: if actor.name == "Duster": self.prev_state = "game" self.combat.Fight(self.player, [actor]) def action(self): max_dist = 100 nearest = None _player_center = self.player.rect.center self.MainGroup.remove(self.player) for sprite in self.MainGroup.sprites(): _dist = getDistance(_player_center, sprite.rect.center) if _dist < max_dist: nearest = sprite max_dsit = _dist if nearest is not None: if nearest in self.Actors: self.player.facing(nearest) nearest.facing(self.player) self.interface.show_dialog(nearest, \ self.player, self.deq_handler) self.MainGroup.add(self.player) def move(self): direction = self.input(self.step) new_rect, old_rect = self.player.move(direction) self.player.crect = \ self.check_collision(self.player, old_rect, new_rect) if direction[0] < 0: direction[0] = -1 elif direction[0] > 0: direction[0] = 1 if direction[1] < 0: direction[1] = -1 elif direction[1] > 0: direction[1] = 1 if direction[0] != 0 or direction[1] != 0: self.player.animate(str(direction)) def game_loop(self): self.key_loop() self.move() for sprite in self.Actors: sprite.loop(self) self.player.loop() self.focus() self.draw() def itf_loop(self): self.draw() self.interface.draw() def combat_loop(self): self.combat.loop() self.combat.draw() def loop(self): if len(self.delayed_functions) > 0: for func in self.delayed_functions: self.delayed_functions.remove(func) func() self.loops[self.state]()