def create_chase(): p = Creature(pacman, (+30, 0)) p.dx = -0.4 creatures.append(p) g = Creature(ghost, (+50, 0)) g.dx = -0.4 creatures.append(g)
class CreatureAttachTest(unittest.TestCase): # Make the things and do the setup that every test # in the TestCase need. def setUp(self): """Create an instance of the Creature class that we can leverage it's functions in our tests. """ self.creature = Creature() # Undos everything that your setUp function did def tearDown(self): """Delete the Creature instamce we made in the setUp. """ del self.creature def test_attack_return_int(self): """Ensure that when attack is called, an int is returned. """ # Call the attack function of our creature, # and catch what it returns in value. value = self.creature.attack() self.assertIsInstance(value, int, "Returned attack value is not an int") def test_no_weapon_return_base_damage(self): """Ensure that with no weapon equipped, the creature does its base damage. """ # Manually set the base damage to 2 self.creature.attack_points = 2 # Get the creature's attack value value = self.creature.attack() self.assertEqual(value, 2, "Expected base attack value not given") def test_with_weapon_return_damage(self): """Ensure that with a weapon, the creature does base damage + weapon damage. """ # Make a weapon to give to the creature weapon = Weapon(3) # Give the weapon to the creature self.creature.weapon = weapon # Set the creature's base attack value self.creature.attack_points = 2 # Get the creature's total attack value value = self.creature.attack() # Assert the attack value is the base + weapon damage self.assertEqual(value, 5, "Computed attack value is not correct.")
def __init__(self, **kwargs): Creature.__init__(self, movable = True, **kwargs) self.moves = { 'Stop': self.set_velocity_xy, 'Jump': self.set_vertical_velocity, 'Fall': self.set_vertical_velocity, 'Left': self.set_horizontal_velocity, 'Right': self.set_horizontal_velocity, 'Stop_horizontaly':self.set_horizontal_velocity }
def randomiseCreatures(self, mother=None, father=None): self.creatures = [] for i in range(10): if (mother==None) or (father==None): c = Creature(DNA=brainUtils.randBinary((5 + 6*5+3*5)*8)) else: c = mother.breed(father) c.x = (random.random()*(self.ARENA_WIDTH-50) + 50) c.y = (random.random()*(self.ARENA_HEIGHT-50) + 50) self.creatures.append(c)
def __init__(self, name): Creature.__init__(self, name, 11, 20, 1, 1, 1) self.inventory = [] self._equipped = {"Sword": None, "Shield": None} self.xp = 0 self.max_hp = 11 self.level = 1 self._core_strength = 1 self._core_intelligence = 1 self._core_dexterity = 1
def generate_dungeon(w, h, difficulty=1): level = Level(w, h) new_map = [[0 for _ in xrange(h)] for _ in xrange(w)] # initialize new_map to noise (0.43% filled) for x,y in range2d(w, h): if random.random() < 0.43: new_map[x][y] = 1 # apply cellular automation for i in xrange(2): temp_map = [[0 for _ in xrange(h)] for _ in xrange(w)] for x,y in range2d(w, h): wall_count = 0 for i,j in box2d(x-1, y-1, 3, 3): if 0 <= i < w and 0 <= j < h: wall_count += new_map[i][j] else: # sides = instawall wall_count += 3 if wall_count >= 5: temp_map[x][y] = 1 new_map = temp_map # apply changes to actual map for x,y in range2d(w, h): tile = level.tiles[x][y] if new_map[x][y] == 1: tile.img = spr.ROCK tile.blocking = True tile.transparent = False else: tile.img = spr.MUD_FLOOR tile.blocking = False tile.transparent = True # spawn treasures and creatures mr = level.get_main_region() treasures = random.sample(mr, difficulty) for loc in treasures: level.add_item(loc, Item(spr.GOLD_NUGGET, name="gold nugget", value=50+difficulty*25)) mobs = random.sample(mr, difficulty) for loc in mobs: c = Creature(level, *loc, hp=difficulty*10, maxhp=difficulty*10, name="malicious slime", gold=10+difficulty*5) c.min_atk = difficulty c.max_atk = difficulty*2 level.creatures.append(c) return level
class CreatureAttackTest(unittest.TestCase): def setUp(self): # built in Python setUp function """Create an instance of the Creature class so that we can leverage its functions in our tests. """ self.creature = Creature() def tearDown(self): # undoes everything that your setUp function did # built in Python tearDown function """Delete the Creature instance we made in the setUp. """ del self.creature def test_attack_return_int(self): # begin every test function name with test_ """Ensure that when attack is called, an int is returned. """ # Call the attack function of our creature and return an integer value = self.creature.attack() self.assertIsInstance( value, int, "Returned Attack value is not an int" ) # wrote comment here to personalize error message def test_no_weapon_return_base_damage(self): """Ensure that with no weapon equipped, the creature does its base damage. """ # Manually set the base damage to something we know (in this case: 3) self.creature.attack_points = 2 # Get the creature's attack value value = self.creature.attack() self.assertEqual(value, 2, "Expected base attack value not given.") def test_with_weapon_return_damage(self): """Ensure that with a weapon, the creature does base damage + Weapon damage. """ # Make a weapon to give creature weapon = Weapon(3) # Give the weapon to the creature self.creature.weapon = weapon # Set creature's base attack value self.creature.attack_points = 2 # Get the creature's total attack value value = self.creature.attack() # Assert the attack value is the base + weapon damage self.assertEqual(value, 5, "Computed attack value is not correct.")
def make_army(size, menagerie): army = [] for col in range(size): for row in range(size): creature_type = menagerie[randint(0, len(menagerie)-1)] x = (col+0.5)*16 - size * 8 y = (row+0.5)*16 - size * 8 creature = Creature(creature_type, (x, y)) creature.da = uniform(-0.1, +0.1) creature.velocity = uniform(0, +0.5) army.append(creature) return army
class CreatureAttackTest(unittest.TestCase): #make the things and so the setUp that every test in the test case needs def setUp (self): """Creature an instance of the creature class that we can leverage its functin in our test """ self.creature = Creature() #undoes everhting that your setup function did. def tearDown(self): """Delete the creature """ del self.creature def test_attack_return_int(self): """Ensure that when attack is called, an int is returned. """ #call the attack function of our creature, and catch what it returns #in value value = self.creature.attack() self.assertIsInstance(value, int, "Returned atk value is not an int") def test_no_weapon_return_base_damage(self): """Ensure that with no weapon equiped, the creature does its base damage """ #manually set the base damge to 3 self.creature.attack_points = 2 #get the creatures attack value value = self.creature.attack() self.assertEqual(value, 2, "Excepted based attack value") def test_with_weapon_return_damage(self): """Ensure that with a weapon, the creature does base damage = weapon damage """ #make a weapon and give to creature weapon = Weapon(3) #give the weapon to the creature self.creature.weapon = weapon #set creature's base attack value self.creature.attack_points =2 #get the creature's total attack value value = self.creature.attack() #Assert the attack value is the base + weapon damage self.assertEqual (value,5, "computed attack value is not correct")
def __init__(self, g_player, team, enemy, pos, layer, when, main, inActiveLayer, maxHitPoints = 8): """ Creates a new scout creature (including the libAVG nodes). g_player: the global player instance. team: the team, the creature should belong to. pos: the initial position. layer: the layer to put the creature on. when: the moment, the creation has been started. """ Creature.__init__(self, g_player, team, enemy, pos, layer, when, main, inActiveLayer, maxHitPoints) self.speed = self.speed * 2 if self.team.name == "Team2": self.creature.filltexhref = os.path.join(getMediaDir(__file__, "resources"), "triangleEvil.png") else: self.creature.filltexhref = os.path.join(getMediaDir(__file__, "resources"), "triangleGood.png")
class CreatureAttackTest(unittest.TestCase): def setUp(self): """Required.""" self.creature = Creature() def tearDown(self): """Required.""" del self.creature """Do we get an int returned? Without weapon do wedo base damage? With weapon do we do expected damage? When weakend do we do 1/2 damage? Same for weapon?""" def test_attack_return_int(self): #Call and catch value = self.creature.attack() #use python's assertIs to make sure the value is an integer self.assertIsInstance(value, int, "Returned attack value is not an int.") def test_no_weapon_return_base_damage(self): """Ensure a weaponless creature does only base damage.""" self.creature.attack_points = 2 value = self.creature.attack() self.assertEqual(value, 2, "Excepted base attack value not given") def test_with_weapon_return_damage(self): """Ensure that with a weapon the creature does the base damage + weapon damage.""" # Make a weapon weapon = Weapon(3) # Give it self.creature.weapon = weapon # Set base attack self.creature.attack_points = 3 # Get total attack value an_attack = self.creature.attack() # Assert the attack value is base + weapon self.assertEqual(an_attack, 6, "Expected attack value wrong.")
def move (self, dx = 0, dy = 0): """ Move the player object Attempting to move into the same space as another object will attempt to push it out of the way """ x, y = self.x + dx, self.y + dy # If there is an object in the location the player # attempts to move to, try and push it target = self.map.is_blocked_by_object(x,y) if target and hasattr(target, 'push'): try: return target.push(dx, dy) except CouldNotMove: print "Can't shove the target in this direction." except AttributeError: print "The target cannot be pushed." # Otherwise, move normally Creature.move(self, dx, dy)
def __init__(self, g_player, team, enemy, pos, layer, when, main, inActiveLayer, maxHitPoints = 8): """ Creates a new wizard creature (including the libAVG nodes). g_player: the global player instance. team: the team, the creature should belong to. pos: the initial position. layer: the layer to put the creature on. when: the moment, the creation has been started. """ self.maxJumpDistance = util.halfwidth // 2 self.goalXPos = self.maxJumpDistance self.freezed = False self.shouldDie = False self.firstJump = True self.appearAnim = None self.disappearAnim = None Creature.__init__(self, g_player, team, enemy, pos, layer, when, main, inActiveLayer, maxHitPoints) if self.team.name == "Team2": self.creature.filltexhref = os.path.join(getMediaDir(__file__, "resources"), "circleEvil.png") else: self.creature.filltexhref = os.path.join(getMediaDir(__file__, "resources"), "circleGood.png")
def __init__(self, base, position, cid=None): Creature.__init__(self, base.data.copy(), position, cid) self.base = base self.creatureType = 1 self.spawnPosition = position.copy() self.lastStep = 0 self.speed = float(base.speed) self.lastMelee = 0 self.lastDistance = 0 self.walkPer = base.walkPer self.brainEvent = None self.spawnTime = None self.radius = 5 self.master = None self.respawn = True self.skull = base.skull # We make a copy of the int so we might set a skull in scripts later. self.canWalk = base.walkable self.intervals = {} self.defaultSpeakType = MSG_SPEAK_MONSTER_SAY self.defaultYellType = MSG_SPEAK_MONSTER_YELL self.lastRetarget = 0
class CreatureAttackTest(unittest.TestCase): #Make the things and do the setup that every test in the TestCase #two functions recommended that you do: set up and tear down #when python runs the test file, it will run each test in the test file, #it will run the set up before every test and tear down after every test def setUp(self): """Create an instance of the Creature class that we can leverage its functions in our tests. """ self.creature = Creature() def tearDown(self): """ Delete the Creature instance we made in the setUp.""" del self.creature #attack():int (<-damage) #do we get an intager back? #without weapon, does it do base damamge? #with weapon, does it do expected damage? #when WEAKENED, does it do half damage? #when WEAKENED with weapon, does it do half damage def test_attack_return_int(self): """Ensure that when attack is called, an int is returned.""" # Call the attack function of our creature, and catch what it returns in value value = self.creature.attack() #assertIS -> testing that the first & second is the same type of object #tried self.assertIs(value, 2, "Return Atk value is not an int"), did not work. self.assertIsInstance(value, int, "Return Atk value is not an int") def test_no_weapon_return_base_damage(self): """Ensure that with no weapon equiped, the creature does it base damage""" #manually set the base damage to 2 self.creature.attack_points = 2 #get the creature's attack value value = self.creature.attack() self.assertEqual(value, 2, "Expected base attack value not given.") def test_with_weapon_return_damage(self): """Ensure that with weapon, the creature does base damage + Weapon damage.""" #Make a weapon to give to creature weapon = Weapon(3) #Give the weapon to the creature self.creature.weapon = weapon #set creature's base attack value self.creature.attack_points = 3 #Get the creature's total attack value value = self.creature.attack() #Assert the attack value is the base + weapon damage self.assertEqual(value, 3 + 3)
def __init__ (self): Creature.__init__(self, '@', libtcod.red)
def __init__(self, x, y,): stat_sheet = StatSheet(hp=15, defense=1, power=4) Creature.__init__(self, x, y, 't', libtcod.darker_green, 'Troll', stats=stat_sheet, ai=FighterAI())
best = 0 # index of creature with closest distance distance = 0 # distance to target target = Target(screen, 200, 200) # target show_best = True # toggle for showing entire population vs only the winner def dislpay_instructions(): font = pygame.font.Font(None, 26) txt = "Press [SPACE] to move target. Press [W] to toggle showing the only winner vs. the entire population" render = font.render(txt, 0, WHITE, BLACK) screen.blit(render, (110, 730)) # create creatures and target for i in range(population): creatures.append(Creature(screen)) # Main loop while not done: screen.fill(BLACK) n_gens += 1 # reset breeding variables best_distance = BEST_D_RESET best = 0 # Creature wins if it is closest to target for i in range(len(creatures)): distance = math.sqrt(abs(creatures[i].get_loc()[1] - target.get_loc()[1]) ** 2 + abs(creatures[i].get_loc()[0] - target.get_loc()[0]) ** 2) if distance < best_distance:
# Brace for the java import random as rng # Our classes from coordinate import Coordinate from entity import Entity from creature import Creature from tree import * from world import World # Display configuration VISION_WIDTH = 30 # Width of "nearby" 2D map to print out, in tiles VISION_HEIGHT = 10 # Height of "nearby" 2D map to print out # Main world = World() # Create an infinite world to live in creature = Creature() # And create a creature to watch in it # Add the creature to the world at (0, 0) creature.set_location(world, Coordinate(0, 0)) while True: world.update() world.print2d(creature, VISION_WIDTH, VISION_HEIGHT) # Let the viewer progress turn-by-turn input()
#add a named plot event to the player def AddPlotEvent(self, name, done = False): self.plotEvents[name] = done; #make the player 'accomplish' a plot event def FinishPlotEvent(self, name): self.plotEvents[name] = True; if (__name__ == "__main__"): # for testing the GetNextMove method """from board import Board b = Board("test") n = NPC("hobo",[0,0],b) n.AddCreature(Creature("Programmer")) n.AddCreature(Creature("Programmer")) n._creatures[0]._currentStats[2] = n._creatures[0]._attributes[2] print n.GetNextMove(n._creatures[0],Creature("Dog")) print n._creatures[0]""" #for testing the Apply method of items c = Creature("Programmer") c._currentStats[2] = 1.0 print c print "" print POSSIBLE_INVENTORY_ITEMS["speed"][0].Apply(c, False) print "" print c print "" print POSSIBLE_INVENTORY_ITEMS["speed"][0].Apply(c, True)
def test____repr__(self): c = Creature() self.assertEqual("Dummymon (HP: 100)", f"{c}")
def __init__(self, size): self.size = size self.creatures = [Creature(self) for _ in range((size // 2)**2)] self.all_creatures = list(self.creatures) self.init_board() self.moves_count = 0
def setUp(self): """Required.""" self.creature = Creature()
def __init__ (self, *args, **kwargs): Creature.__init__(self, *args, **kwargs)
def orc(x, y): return Creature(x, y, Symbol('o', colors.ORC))
def setUp(self): """Create an instance of the Creature class that we can leverage its functions in our tests. """ self.creature = Creature()
def get_generic_ac_calc(): return [i+14 for i in range(1,21)] def get_generic_ac_real(): return [i+16 for i in range(1,21)] def get_generic_hp(): return [i*7 for i in range(1,21)] #set a creature's AC to match generic AC def normalize_ac(creature): creature.armor_class.misc.add_circumstance( get_generic_ac_calc()[creature.level-1] - creature.armor_class.normal()) if __name__ == "__main__": args = initialize_argument_parser() if args['function'] == CHARACTER: creature = Creature.from_creature_name(args['creature_input'], args['level']) print creature if args['output'] is not None: latex_string = creature.to_latex() output_file = open(args['output'], 'w') output_file.write(latex_string) elif args['function'] == MONSTER: creature = Monster.from_monster_name(args['creature_input'], args['level']) print creature.to_latex() if args['output'] is not None: latex_string = creature.to_latex() output_file = open(args['output'], 'w') output_file.write(latex_string) elif args['function'] == COMBAT: for i in xrange(20):
from pyglet.window.key import symbol_string from army import Army, rand_point from camera import Camera from data import all_ghosts, pacman from creature import Creature from keyboard import on_key_press, key_handlers from renderer import Renderer win = Window(fullscreen=True, visible=False) camera = Camera((0, 0), 10) renderer = Renderer() army_shape = Army.MakeShape(400, 1500, all_ghosts) armies = [] for i in range(20, 0, -1): army = Creature(army_shape, rand_point(500), uniform(-pi, pi)) army.dx = uniform(-0.4, +0.4) army.dy = uniform(-0.4, +0.4) armies.append(army) def update(dt): for army in armies: army.update(dt) camera.zoom(1.003) clock.schedule(update) key_handlers[key.ESCAPE] = win.close win.on_draw = lambda: renderer.on_draw(armies, camera, win.width, win.height) win.on_key_press = on_key_press
def test_basic_init(self): c = Creature() self.assertEqual("Dummymon", c.name)
def test_creatures_3(): ''' The student keep using pycharm during lab, and it was caught by the tutor at school. The tutor ask student not using pycharm anymore, but tutor has lower terror rating than student. So that tutor is trying to make student not to use pycharm, but he can do nothing to abandon. The student is still not being caught, and he is still able to use pycharm. So that the times that tutor catch student about not using pycharm is only once. ''' USYD = Location("USYD") me = Creature("Me", 5, USYD, "INFO1110 student") USYD.add_creature(me) pycharm = Item("pycharm", "powerful pycharm", "A powerful tool such as pycharm can help you debug", 100) USYD.add_item(pycharm) me.get_location().remove_item(pycharm) me.take(pycharm) tutor = Creature("Tutor", 2, USYD, "INFO1110 tutor") USYD.add_creature(tutor) tutor.catch() assert me.get_terror_rating() == 105 and tutor.get_catch_time( ) == 1, "Test 3 failed." print("Test 3 passed!")
def setUp(self): # built in Python setUp function """Create an instance of the Creature class so that we can leverage its functions in our tests. """ self.creature = Creature()
def test_creatures_2(): """ This student is taught to use terminal with atom to write code. But after he uses terminal with atom, he find the interface is not very good. Cannot compare with pycharm. So that he decide not to listen to teachers, but keep using pycharm. Therefore, the student should still have a terror rating of 105 after he decides not to use terminal. """ USYD = Location("USYD") me = Creature("Me", 5, USYD, "INFO1110 student") USYD.add_creature(me) pycharm = Item("pycharm", "powerful pycharm", "A powerful tool such as pycharm can help you debug", 100) USYD.add_item(pycharm) me.get_location().remove_item(pycharm) me.take(pycharm) terminal = Item("terminal", "Mac terminal", "A console to execute commands directly", 1) USYD.add_item(terminal) me.take(terminal) me.get_location().remove_item(terminal) me.drop(terminal) me.get_location().add_item(pycharm) assert me.get_terror_rating() == 105, "Test 2 failed." print("Test 2 passed!")
def __init__(self, x, y): stat_sheet = StatSheet(hp=30, defense=2, power=5, max_volume=10, max_carry_weight=100) Creature.__init__(self, x, y, '@', libtcod.white, c.player_name, stats=stat_sheet, death_function=self.player_death)
def test_is_fainted(self): c = Creature() self.assertFalse(c.is_fainted) c.current_health = -1 self.assertTrue(c.is_fainted)