def dict2Character(d): if (d == "Empty"): return None name = d["Name"] style = d["Style"] weapon = d["Weapon"]["Name"] weaponbonus = (d["Weapon"]["Health"], d["Weapon"]["Attack"], d["Weapon"]["Defense"], d["Weapon"]["Speed"], d["Weapon"]["Type"]) maxhealth = d["MaxHealth"] health = d["Health"] attack = d["Attack"] defense = d["Defense"] speed = d["Speed"] exp = d["Experience"] money = d["Money"] stash = d["Stash"] loc = [d["location"][0], d["location"][1], d["location"][2]] character = Character(Name=name, Style=style, Weapon=weapon, WeaponBonus=weaponbonus, Health=health, Attack=attack, Defense=defense, Speed=speed, Money=money, Stash=stash, location=loc, Experience=exp) character.MaxHealth = maxhealth return character
def test_gets_correct_id(self): expected_1 = 1 expected_2 = 2 sut_1 = Character(char_id=expected_1) sut_2 = Character(char_id=expected_2) self.assertEqual(expected_1, sut_1.char_id) self.assertEqual(expected_2, sut_2.char_id)
def decision(self, enemy, game_round): self.mana_regen(5) loop = True if self.alive and enemy.alive: if not self.frozen: while loop: os.system('clear') print(f"Round {game_round}") self.info("Mana", self.mana, self.maxMana) x = input("Wand(1) Fireball(2) Ice shard(3) Pass(4)\n>").replace(" ", "").lower() if x == "1": self.attack(enemy, "wand") break elif x == "2": self.fire_ball(enemy) break elif x == "3": self.ice_shard(enemy) break elif x == "4": Character.pass_turn() break elif x == "wand": Tooltips.tip_wand() elif x == "fireball": Tooltips.tip_fire_ball() elif x == "iceshard": Tooltips.tip_ice_shard() else: self.info("Mana", self.mana, self.maxMana) print("You are frozen this turn and can't move...") self.frozen = False
def __init__(self, display, name, mass=1.0, position=Vector(), is_dummy=False, **kwargs): Character.__init__(self, display, name, is_dummy=is_dummy, mass=mass, position=copy.copy(position), running_acceleration_cap=2000, **kwargs) self.width = 90 self.height = 70 self.bounding_shapes[0] = BoundingShape( [self.position.x, self.position.y, self.width, self.height]) self.attacks = [] self.manager = None
def decision(self, enemy, game_round): loop = True if self.alive and enemy.alive: if not self.frozen: while loop: os.system('clear') print(f"Round {game_round}") self.info("Armor", self.defense, self.maxDefense) x = input( "Sword swing(1) Armor up(2) Armor bash(3) Pass(4)\n>" ).replace(" ", "").lower() if x == "1": self.attack(enemy, "sword") break elif x == "2": self.armor_up() break elif x == "3": self.armor_bash(enemy) break elif x == "4": Character.pass_turn() break elif x == "swordswing": Tooltips.tip_sword_swing() elif x == "armorup": Tooltips.tip_armor_up() elif x == "armorbash": Tooltips.tip_armor_bash() else: self.info("Armor", self.defense, self.maxDefense) print("You are frozen this turn and can't move...") self.frozen = False
def __init__(self): pygame.init() self.screen = pygame.display.set_mode((1280, 800)) self.area = self.screen.get_rect() self.walls = Wall.gather_walls() self.my_clock = pygame.time.Clock() # Utility object self.background = Background() # Objects we put on screen self.character = Character(self.area) self.all_but_background = PgGroup((self.character, self.walls)) self.monsters = Monster.spawn_monsters(self.character, self.walls, ((ChampionMeleeMonster, 15), (Monster, 30), (RangeMonster, 25))) # So we can call each monster's attack method. self.monster_group = PgGroup(self.monsters) # Used to update everything to screen. self.all_sprites = PgGroup((self.character, self.monsters, self.background, self.walls)) # Used to draw. We separate background so we can ensure it gets pictured before other things. self.all_but_background.add(self.monsters) self.time_test = False # Changed things in while loop so need to recreate timetest. self.time_dict = {'drawmove': 0, 'abilitydraw': 0, 'eventloop': 0, 'attacks': 0, 'collisions': 0, 'move': 0, 'clear/recover': 0, 'drawbars': 0} self.loop_counter = 0 self.find_key = {K_LSHIFT: 0, K_SPACE: 1, LEFT: 2, RIGHT: 3}
def __init__(self): """ Constructor function """ Character.__init__(self) self.jump_l_image, self.jump_l_image_rect = routines.load_png( 'hero_2/jump_l.png') self.jump_r_image, self.jump_r_image_rect = routines.load_png( 'hero_2/jump_r.png') self.idle_l_image, self.idle_l_image_rect = routines.load_png( 'hero_2/idle_l.png') self.idle_r_image, self.idle_r_image_rect = routines.load_png( 'hero_2/idle_r.png') self.move_1_r_image, self.move_1_r_image_rect = routines.load_png( 'hero_2/move_1_r.png') self.move_1_l_image, self.move_1_l_image_rect = routines.load_png( 'hero_2/move_1_l.png') self.move_2_r_image, self.move_2_r_image_rect = routines.load_png( 'hero_2/move_2_r.png') self.move_2_l_image, self.move_2_l_image_rect = routines.load_png( 'hero_2/move_2_l.png') self.dead_image, self.dead_image_rect = routines.load_png( 'hero_2/death.png') #load sounds self.sounds = {} self.sounds['jump'] = pygame.mixer.Sound('data/sound/jump.wav') self.image = self.idle_l_image self.rect = self.idle_l_image_rect # Set a referance to the image rect. #Setup status self.status = 'idle_r' #idle,move,jump, self.location = 'ground' #ground,air,block Character.set_options(self, 10, 2, 1.2)
def setUp(self): sword = Weapon('Spartan Sword', 1, 20) bow = Weapon('Long Bow', 5, 60) self.leonidas = Character('King Leonidas', 10, sword, 200) self.legolas = Character('Elf Legolas', 5, bow, 100, 4) self.hulk = Character('Incredible Hulk', 100, None, 800, 2)
def update(self): Character.update(self) if self.attack_time > 0: self.image = self.attack_anim[self.attack_time//12] self.rect.x += 23 self.attack_time -= 1
def __init__(self): """ Constructor function """ Character.__init__(self) #Load images and rectangles self.jump_l_image, self.jump_l_image_rect = routines.load_png('hero_3/jump_l.png') self.jump_r_image, self.jump_r_image_rect = routines.load_png('hero_3/jump_r.png') self.idle_l_image, self.idle_l_image_rect = routines.load_png('hero_3/idle_l.png') self.idle_r_image, self.idle_r_image_rect = routines.load_png('hero_3/idle_r.png') self.move_1_r_image, self.move_1_r_image_rect = routines.load_png('hero_3/move_1_r.png') self.move_1_l_image, self.move_1_l_image_rect = routines.load_png('hero_3/move_1_l.png') self.move_2_r_image, self.move_2_r_image_rect = routines.load_png('hero_3/move_2_r.png') self.move_2_l_image, self.move_2_l_image_rect = routines.load_png('hero_3/move_2_l.png') self.dead_image, self.dead_image_rect = routines.load_png('hero_3/death.png') #load sounds self.sounds={} self.sounds['jump']=pygame.mixer.Sound('data/sound/jump.wav') self.image = self.idle_l_image self.rect = self.idle_l_image_rect # Set a referance to the image rect. #Setup status self.status = 'idle_r' #idle,move,jump, self.location = 'ground' #ground,air,block Character.set_options(self, 13, 0, 1)
def dict2Character(d): name = d["Name"] style = d["Style"] weapon = d["Weapon"]["Name"] weaponbonus = (d["Weapon"]["Health"], d["Weapon"]["Attack"], d["Weapon"]["Defense"], d["Weapon"]["Speed"], d["Weapon"]["Type"]) maxhealth = d["MaxHealth"] health = d["Health"] attack = d["Attack"] defense = d["Defense"] speed = d["Speed"] money = d["Money"] stash = d["Stash"] character = Character(Name=name, Style=style, Weapon=weapon, WeaponBonus=weaponbonus, Health=health, Attack=attack, Defense=defense, Speed=speed, Money=money, Stash=stash) character.MaxHealth = maxhealth return character
def next_stage(self): self.ship = Animation(frames_path['ship'], ((self.w/16)*14, 200), self.screen) self.ship.reduce_scale(4) self.ship.centralize() self.sound_queue.append(sounds['stage']) self.played_sections += 1 self.last_dig = None self.curr_dig = None self.show_item = False self.stage_done = False self.treasure_found = False self.stage_begin = True self.block_index = 0 self.stage_map = Map(3 + self.played_sections, self.screen, self.w, self.h) self.char = Character(self.screen, Gameplay.char_sex, self.stage_map.blocks[self.block_index]) self.char.reduce_scale(4) self.char.centralize() self.elements = [self.bg, self.stage_map, self.ship, self.char]
def dummyCharacters ( self ): print ("Dummy Characters") #A dummy character created #This can be switched out with user control of some kind #This works because the Jade Runner is waiting for CharacterCreationCompletedEvent () #Send out Event that we are making a new Group called 0 #This will be the main group on screen. ev = Events.NewGroupEvent ( 0 ) self.mediator.post ( ev ) #Dummy Character char = Character ( self.mediator ) char.setName ( "Name" + str(self.count) ) print (char.getName ( )) ev = Events.NewCharacterEvent ( char ) self.mediator.post ( ev ) self.mediator.post ( Events.ClusterAddCharacterEvent ( 0 , char.getName ( ) ) ) self.count += 1 #Dummy Character char = Character ( self.mediator ) char.setName ( "Name" + str(self.count) ) print (char.getName ( )) ev = Events.NewCharacterEvent ( char ) self.mediator.post ( ev ) self.mediator.post ( Events.ClusterAddCharacterEvent ( 0 , char.getName ( ) ) ) self.count += 1 self.completedSelection ( )
def __init__(self, x, y, director): Character.__init__(self, x, y, "player-alt.png", -1, "coordPlayerAlt2.txt", [3, 3, 3, 3], magicNumbers=(-4, 10, 4, 6, -2, 4, 2, 8), director=director) self.controller = PlayerController(self, director) self.posIndex = POS_DOWN self.posImageIndex = 1 self.hp = 100 self.shield = 100 self.shieldRegenDelay = 0 self.atk = 20 self.director = director self.mask = pygame.mask.from_surface( self.sheet.subsurface( self.sheetCoord[self.posIndex][self.posImageIndex])) # Better collisions this way self.rect.inflate_ip(-4, -6) self.atk_speed = PLAYER_ATTACK_SPEED self.selectedWpnNum = 0 self.totalWpns = 0 self.weapons = []
def assign_to_taskgroup(self, Character): self.__task_group.append(Character) if self.__req_skills.count == 0: pass else: for i in range(0, len(self.__req_skills)): Character.get_skill(self.__req_skills[i])
def main(): player = Character(input('What is your name, slave?\n'), 15) orc = Character('Foul orc') troll = Character('Fetid troll') knight = Character( 'Knight', 10, 5, 1, None, Equipment(Weapon('Sword', '1hsw', 2), Armor('Shiny armor', 1))) arena = Arena() fight = FightManager(arena, [player, orc, troll, knight], player) print('You enter the arena.') print(knight.equipment.weapon) wageFight(fight) corpses = fight.arena.corpses if fight.hasPlayer(): print('You survived another fight.') #Loot and continue lootCorpses(player, corpses) elif len(fight.arena.fighters) > 0: winner = fight.arena.fighters.pop(0) print('%s won the fight !' % winner.name) else: print( 'Draw ! All fighters lost their lives, the crowd cheers to revive the most brutal.' ) #Continue if fought best print(player) print(player.inventory.items) print('End.')
def execute(self, data): try: self.name = data.getString() self.factionId = data.getInt32() print "new challenger" ralph = Actor("models/ralph", { "run": "models/ralph-run", "walk": "models/ralph-walk" }) ralph.reparentTo(render) ralph.setScale(.2) ralph.setPos(main.ralphStartPos) if main.name == self.name: main.character = Character(self.name, ralph, self.factionId) main.base.camera.setPos(main.character.actor.getX(), main.character.actor.getY() + 10, 2) # Try this out main.characters[self.name] = main.character else: main.characters[self.name] = Character(self.name, ralph, self.factionId) main.taskMgr.add(self.main.move, "moveTask") #main.taskMgr.doMethodLater(1, self.main.CPHandler, "CPHandlerTask") #self.log('Received [' + str(Constants.RAND_INT) + '] Int Response') except: self.log('Bad [' + str(Constants.RAND_INT) + '] Int Response') print_exc()
def populate(self, squadtype): st = self.squad_type = SquadTypeHandler.load(squadtype) self.squad_type_name = st.name self.leader_rank = st.leader_rank self.devotion = choice(CharInfo.devotions) self.loyalty = choice(CharInfo.loyalties) if st.choice != "False": options = st.choice.split("/") winner = choice(options) for group in options: for key in group.split("&"): if key not in winner: st.squadroles[key] = 0 for role, amount in st.squadroles.items(): for _ in range(int(amount)): context = { "legion": self.legion, "company": self.company, "role": SquadRole.load(role.title()), "squad": self } char = Character(**context) char.generate_fill() self.members.append(char) if len(self.members) == st.size: break
def execute(self, data): try: self.playerId = data.getString() self.type = data.getUint16() self.x = data.getFloat32() self.y = data.getFloat32() self.z = data.getFloat32() #print "q" char = Character(self.world, self.type) char.actor.setPos(self.x,self.y,0) char.setPlayerId(self.playerId) charPresent = False for charTemp in self.world.characters: if charTemp.getPlayerId() == char.playerId: charPresent = True break if not charPresent: self.world.characters.append(char) print "ResponseCreateCharacter - ", self.playerId, " x:", self.x, " y:", self.y," z:", self.z #self.log('Received [' + str(Constants.RAND_STRING) + '] String Response') except: self.log('Bad [' + str(Constants.RAND_STRING) + '] String Response') print_exc()
def createCharacter(): troy = Character("Troy", "Welsh", "Mesmer", 100, 100) troy.showDetails() # createa single item troysweapon = Item("Staff Of Ice", "Staff", 3, 4) troystunic = Item("Tunic Of Ice", "Armor", 10, 10) # add item to backpack dict troy.characterbackpack.addItemToBackpack(Backpack, troysweapon) troy.characterbackpack.addItemToBackpack(Backpack, troystunic) # get the entire Item Object by Item Class Name newweapon = troy.characterbackpack.getItemFromBackpack( Backpack, troysweapon) print("This is the name of my new item") print(newweapon.itemname) # get the entire Item Object by Item Class Name newarmor = troy.characterbackpack.getItemFromBackpack(Backpack, troystunic) print("This is the name of my new item") print(newarmor.itemname) # get the entire object by Dict index - a string value newitem = troy.characterbackpack.findItemInBackpack( Backpack, "Tunic Of Ice") print(newitem.itemname) print(newitem.itemsize)
class Game(object): def __init__(self): self.TITLE = "TEST (by zeeisl)" self.WIDTH = 800 self.HEIGHT = 600 self.controller = Controller() # game things self.char = Player("res//hero.png") self.map = Map() self.char1 = Character("res//hero.png", 100, 100, 32, 32) def key_input(self, event): self.controller.getButtonStates(event) self.char.key_input(event) def update(self, delta): self.map.update() self.char.update(self.char1) self.char1.update() def render(self, screen): self.map.render(screen) self.char.render(screen) self.char1.render(screen)
def __init__(self, name="Player", health=20, shield=10, dodge=0, parry=0, criticalHit=1, mana=10, damageMin=1, damageMax=2, armor=0, xp=0, inventory=Inventory()): Character.__init__(self, name, health, shield, dodge, parry, criticalHit, mana, damageMin, damageMax, armor, xp, inventory) self.statistics = Statistics() self.success = { "monster_hunter": Success(name="Monster hunter"), "commercial": Success(name="Commercial"), "lucky": Success(name="Lucky"), "compulsive_buyer": Success(name="Compulsive buyer"), "vendor": Success(name="Vendor on the run"), "consumer": Success(name="Consumer"), "the_end": Success(name="The End") }
def load_characters(neighbours, blur_scale, verbose=0): chars_file = 'characters_%s_%s.dat' % (blur_scale, neighbours) if exists(chars_file): print 'Loading characters...' chars = fload(chars_file) else: print 'Going to generate character objects...' chars = [] for char in sorted(listdir(IMAGES_FOLDER)): count = 0 for image in sorted(listdir(IMAGES_FOLDER + char)): image = GrayscaleImage(IMAGES_FOLDER + char + '/' + image) norm = NormalizedCharacterImage(image, blur=blur_scale, \ height=NORMALIZED_HEIGHT) character = Character(char, [], norm) character.get_single_cell_feature_vector(neighbours) chars.append(character) count += 1 if verbose: print 'Loaded character %s %d times' % (char, count) if verbose: print 'Saving characters...' fdump(chars, chars_file) return chars
def setUp(self): self.house = House() self.bathroom = self.house.bathrooms[0] self.bedroom = self.house.bedrooms[0] self.kitchen = self.house.kitchen self.livingroom = self.house.livingroom self.sim = Character('sim', 25, 'm', self.house) self.sim.needs_down()
def test_characters_know_each_other_after_socialization(self): alex = Character.random() alex.gender = 'male' amy = Character.random() amy.gender = 'female' self.assertFalse(amy.knows(alex)) amy.socialize(alex) self.assertTrue(amy.knows(alex))
def __init__(self, x, y): self.direction = Direction.WEST self.health = Zombie.START_HEALTH self.img = Zombie.ORIGINAL_ZOMBIE_IMAGE Character.__init__(self, x, y) Zombie.list_.append(self)
def __init__(self): Bomberman.__init__(self) Character.__init__(self) constructor = ConstructorPersonaje(FabricaBomberman()) self.Set_imagenes(constructor.Get_sprites()) self.images = self.imagenes self.image = self.images[self.dir][self.current] self.rect = self.image.get_rect()
def __init__(self, x, y): self.health = Survivor.START_HEALTH self.current_weapon = Weapon(Weapon.PISTOL) self.direction = Direction.WEST self.img = pygame.image.load('images/survivor/survivor_w.png') Character.__init__(self, x, y)
def run_command(self, op, cha: Character, cha2: Character): cha.desative_shield() return { 1: cha.weak_attack, 2: cha.strong_attack, 3: cha.magic_attack, 4: cha.active_shield }[op](cha2)
def leave_building(self, player_id, location_id): characterInst = Character() locInst = Location() charName = characterInst.get_char_name(player_id) townObj = locInst.get_location(charName) optionsInst.location_options(player_id, townObj["city_name"], townObj["town_description"], townObj["buildings"])
def __init__(self): self.character = Character() self.tuples = Character_Tuples() self.skillCount = 0 self.mainHandTuple = self.tuples.BARBARIAN_MAIN_HAND self.offHandTuple = self.tuples.BARBARIAN_OFF_HAND self.rangedTuple = self.tuples.BARBARIAN_RANGED_WEAPON self.armorTuple = self.tuples.BARBARIAN_ARMOR
def __init__(self, x, y): self.health = Survivor.START_HEALTH self.current_weapon = 0 # 0 -> pistol, 1 -> shotgun, 2 -> automatic self.direction = Direction.WEST self.img = pygame.image.load('images/survivor/survivor_w.png') Character.__init__(self, x, y)
def __init__(self,level, pName = None, pStr = None, pDex = None, pMnd = None, pLck = None, pWeapon = None, pArmor = None, pInventory = None, pHp = None, pLevel = None, pAp = None, pDescription = None, pAge = None, pMp = None, pPp = None, pManaEnabled = None): if (pName == None and pStr == None and pDex == None and pMnd == None and pLck == None and pWeapon == None and pArmor == None and pInventory == None and pHp == None and pLevel == None and pAp == None and pDescription == None and pAge == None and pMp == None and pPp == None and pManaEnabled == None): self.createEnemy(level) else: Character.__init__(self, pName, pStr, pDex, pMnd, pLck, pWeapon, pArmor, pInventory, pHp, pLevel, pAp, pDescription, pAge, pMp, pPp, pManaEnabled)
def display_char_inventory(self, player_id, loc_name, loc_type, building_types): characterInst = Character() loot = characterInst.fetch_loot(player_id) print("\nInventory (Type \"equip\" to begin equipping an item, \"C\" to Cancel')") i = 0 table = [] for item in loot: table.append([item['loot_id'], item['loot_name'], item['item_value'], item['item_desc'], item['equipped']]) print (tabulate(table, headers=['ID', 'Name', 'Item Value', 'Item Description', 'Equipped'])) choice = input("Select: ") if choice == 'C' or choice == 'c': self.location_options(player_id, loc_name, loc_type, building_types) elif choice == 'equip' or choice == 'Equip': while(True): lootInst = Loot.Loot() selection = input("Which item would you like to equip? (Type the ID) ") if selection == 'C': break loot_is_in = False for loot_item in loot: if int(selection) in loot_item.values(): loot_is_in = True if loot_is_in == False: #player doesn't have that loot item print("You don't have that item!") else: selectLoot = lootInst.get_loot_item(selection) equippedLoot = lootInst.get_equipped_items(player_id) #if we already have the same type of item equipped, #unequip that item item_in_equipped = False for item in equippedLoot: if item['loot_type'] == selectLoot['loot_type']: lootInst.unequip_item(player_id, item['loot_id'], item['loot_type']) lootInst.equip_item(player_id, int(selection), selectLoot['loot_type']) print("{} equipped!\n".format(selectLoot['loot_name'])) item_in_equipped = True break if item_in_equipped == True: break lootInst.equip_item(player_id, int(selection), selectLoot['loot_type']) print("{} equipped!\n".format(selectLoot['loot_name'])) break self.location_options(player_id, loc_name, loc_type, building_types) self.location_options(player_id, loc_name, loc_type, building_types)
def test_ifRollIs20CriticalHitDoubleDamage(self): testCharacter1 = Character() testCharacter2 = Character() roll = 20 attack = Attack(testCharacter1, testCharacter2, roll) attack.attemptAttack() self.assertEqual(3, testCharacter2.hitPoints)
def apply_def_buff(self): if not self._is_dead: health = Character.get_health(self) if self._def_buff == 1: Character.set_health(self, health * 1.1) Swordsman.MAX_HEALTH = Swordsman.MAX_HEALTH * 1.1 elif self._def_buff == 2: Character.set_health(self, health * 1.25) Swordsman.MAX_HEALTH = Swordsman.MAX_HEALTH * 1.25
def apply_def_buff(self): if not self._is_dead: health = Character.get_health(self) if self._def_buff==1: Character.set_health(self, health*1.1) Swordsman.MAX_HEALTH = Swordsman.MAX_HEALTH*1.1 elif self._def_buff==2: Character.set_health(self, health*1.25) Swordsman.MAX_HEALTH = Swordsman.MAX_HEALTH*1.25
def test_MinDmgAlwaysOne(self): testCharacter1 = Character() testCharacter2 = Character() testCharacter1.strength = 1 roll = 20 attack = Attack(testCharacter1, testCharacter2, roll) attack.attemptAttack() self.assertEqual(4, testCharacter2.hitPoints)
def test_ifTargetCharacterHitTakesOneDamage(self): testCharacter1 = Character() testCharacter2 = Character() roll = testCharacter2.armor attack = Attack(testCharacter1, testCharacter2, roll) attack.attemptAttack() self.assertEqual(4, testCharacter2.hitPoints)
def setUp(self): """Create a character for us to test with.""" c = Character() self.char = c # Some stat values. c.body = 6 c.mind = 8 c.soul = 7
def __init__(self, x): idle = SpriteSheet("art/pl_cid.png").images_at( [(0,0,300,400)],colourkey=(0,255,0)) walk = SpriteSheet("art/pl_cid_walk.png").images_at( [(0,0,300,400), (300,0,300,400)],colourkey=(0,255,0)) attack = SpriteSheet("art/pl_cid_attack1.png").images_at( [(0,0,250,400), (250,0,250,400), (500,0,250,400), (750,0,250,400)],colourkey=(0,255,0)) Character.__init__(self, x, idle, walk, attack) self.attack_time = -1
def __init__(self,model,run,walk,startPoint,scale): """Initialise the character. Initialises private fields used to control the character's behaviour. Also see Character.__init__(). Arguments: See Character.__init__(). """ Character.__init__(self, model, run, walk, startPoint, scale) self.prevTurnTime = 0 self.setControl('up',1)
def move(self,task): """Update the character for one frame. Pick a new direction for the character to turn in every second. Also see Character.move(). Arguments: See Character.move(). Return: See Character.move(). """ if task.time - self.prevTurnTime >= 1: import random direction = random.randint(1,3) if direction == 1: self.setControl('left',1) self.setControl('right',0) elif direction == 2: self.setControl('left',0) self.setControl('right',1) elif direction == 3: self.setControl('left',0) self.setControl('right',0) self.prevTurnTime = task.time return Character.move(self,task)
def load(self,filename): """Load existing game from file""" debug("loadgame...read data from saved file") debug("loadgame...loading clues") self.story.loadClues() savedData = open(filename) nextLine = savedData.readline() # Parsing saved file while (nextLine): line = nextLine.split() if (len(line) == 4 and self.loadIsValid(line)): x = int(line[0]) y = int(line[1]) numClues = int(line[2])+1 self.story._clueList = self.story._clueList[:numClues] self.story.score = int(line[3]) debug("x: " + `x` + " y: " + `y` + " numCLue: " + `len(self.story._clueList)` + \ " score is: " + `int(line[3])`) nextLine = savedData.readline() savedData.close() self.story.currClue = self.story._clueList.pop() debug("loadgame...loading initial character and places") self.character = Character((x,y), "Character", "Character") self.places.loadLoc() debug("end of load") self.places.addLoc(self.character) # FIXME if QTime and QTimer should be stored in certain way self.gameTime = QTime() #self.frameTimer = QTimer() # Create Frame Timer self.launch()
def draw(self, screen, camera): Character.draw(self, screen, camera) if self.damageCooldown > 0: damageRect = pygame.Rect(0, 0, self.sheetCoord[self.posIndex][self.posImageIndex][2], self.sheetCoord[self.posIndex][self.posImageIndex][3]) damageSurface = pygame.Surface((damageRect.w, damageRect.h)) damageSurface.fill((255, 0, 0)) damageSurface.set_alpha(self.damageCooldown) mask = pygame.transform.flip(pygame.transform.rotate(\ self.sheet.subsurface(self.sheetCoord[self.posIndex][self.posImageIndex]), self.angle), \ self.flipH, self.flipV).copy() mask = mask.convert_alpha(screen) blit_mask(damageSurface, screen, (self.rect.x + camera.state.x, self.rect.y + camera.state.y), mask, damageRect)
def add_to_inventory(self, *args): id = self.box_list.curselection() luku = int(id[0]) text = self.box_list.get(luku) if text=='Favor' or text=='Contact': x = Character() x.giveRandomName() name = x.get_attribute('Full name') text = text + '(' + name + ')' self.contr.set_to_ability_list(self.name, text, 1) #list = self.contr.get_from_ability_list(self.name) #value = self.contr.get_char_skill(text) value = self.contr.get_from_ability_list(self.name, text) text = text + '\t\t\t\t|' + str(value) + '\n' self.text_inventory.insert('end', text)
def __init__(self): self.__char = Character() # self.__char.setRandomStats() self.settings = Settings() self.datasets = {} self.max_cpoints = 60 self.max_opoints = 50 self.money = 2500 self.datasets["headers"] = []
def __init__(self, x, y, director): Character.__init__(self, x, y, "player-alt.png", -1, "coordPlayerAlt2.txt", [3, 3, 3, 3], director, (-4, 10, 4, 6, -2, 4, 2, 8)) self.controller = PlayerController(self, director) self.posIndex = POS_DOWN self.posImageIndex = 1 self.hp = 100 self.atk = 20 self.director = director self.mask = pygame.mask.from_surface(self.sheet.subsurface(self.sheetCoord[self.posIndex][self.posImageIndex])) # Better collisions this way self.rect.inflate_ip(-4, -6) self.atk_speed = PLAYER_ATTACK_SPEED self.selectedWpnNum = 0 self.totalWpns = 0 self.weapons = []
def move (self, walls): '''in - (self, list of walls) Determines what direction to move in and moves pacman.''' if self.moveUp and self.canMove (0, walls): Character.move (self, 0) if self.moveLeft and self.canMove (1, walls): Character.move (self, 1) if self.moveDown and self.canMove (2, walls): Character.move (self, 2) if self.moveRight and self.canMove (3, walls): Character.move (self, 3)
def testCharacterCanLevelUp(self): '''Does my Character's Level increase when his experience hits 1000?''' testCharacter = Character("John") firstLevel = testCharacter.getLevel() testCharacter.setExperience(990) testCharacter.updateExperience() secondLevel = testCharacter.getLevel() self.assertNotEqual(firstLevel, secondLevel)
def unapply_def_buff(self): if not self._is_dead: if self._def_buff==0: Swordsman.MAX_HEALTH = 100 elif Swordsman.MAX_HEALTH==125 and self._def_buff==1: Swordsman.MAX_HEALTH = 110 health = Character.get_health(self) if health > Swordsman.MAX_HEALTH: health = Swordsman.MAX_HEALTH
def init(self): """Método para iniciar o jogo completo""" #inicia a janela 'invisível' self.screen = pygame.display.set_mode((1,1),NOFRAME,32) #cria uma instancia para o mapa self.map = Map(self.screen) pygame.display.set_icon(self.map._getGraf('!')) #cria personagem self.person = Character(self.map,self.screen) #incia mapa self.fase self.mapInit() #Comeca o jogo self.screen = self.update() #laço principal do jogo while True: for event in pygame.event.get(): if event.type == QUIT: self.exit() if event.type == KEYDOWN: #movimentos do personagem if event.key == K_UP: #cima self.win,s = self.person.up() self.pushPilha(s) elif event.key == K_DOWN: #baixo self.win,s = self.person.down() self.pushPilha(s) elif event.key == K_LEFT: #esquerda self.win,s = self.person.left() self.pushPilha(s) elif event.key == K_RIGHT: #direita self.win,s = self.person.right() self.pushPilha(s) elif event.key == K_w: #ganha self.win = True elif event.key == K_r: #reincia o mapa self.mapInit() self.screen = self.update() elif event.key == K_z and pygame.key.get_mods() & KMOD_CTRL: #ctrl + z self.desfazer() self.screen = self.update() pygame.display.flip() if self.win: self.fase = (self.fase+1) % 16 self.mapInit() self.screen = self.update()
def unapply_def_buff(self): if not self._is_dead: if self._def_buff==0: Axeman.MAX_HEALTH = 100 elif Axeman.MAX_HEALTH==140 and self._def_buff==1: Axeman.MAX_HEALTH = 110 health = Character.get_health(self) if health > Axeman.MAX_HEALTH: health = Axeman.MAX_HEALTH pass
def __init__(self): self.TITLE = "TEST (by zeeisl)" self.WIDTH = 800 self.HEIGHT = 600 self.controller = Controller() # game things self.char = Player("res//hero.png") self.map = Map() self.char1 = Character("res//hero.png", 100, 100, 32, 32)
def execute(self, data): try: self.playerId = data.getInt32() self.type = data.getUint16() self.x = data.getFloat32() self.y = data.getFloat32() self.z = data.getFloat32() char = Character(self.world, self.type) char.actor.setPos(self.x,self.y,0) char.playerId = self.playerId self.world.characters.append(char) print "ResponseCreateCharacter - ", self.playerId, " x:", self.x, " y:", self.y," z:", self.z except: self.log('Bad [' + str(Constants.RAND_STRING) + '] String Response') print_exc()