def setUp(self): self.i1 = Item() self.i2 = Item(name='axe', weight=1000) self.c1 = Container() self.c2 = Container(name='backpack', weight=2000)
def throw(self): """Throwing item from eq""" thrown = self.equipment.remove_item("active") if thrown: thrown.position = vector(self.position.x + 80 * self.facing + 15, self.position.y - 50) Item.scale_item(thrown, BLOCK_SIZE // 1.6) self.game.items.add(thrown)
def build_item(name, item_data, actor=None, is_player=False): # Build a new item and return finished item item = Item(name, item_data[name]['image'], item_data[name]['color_fg'], 1, item_data[name]['stackable'], item_data[name]['targeting'], item_data[name]['range']) item.action = build_action(name, item, item_data, actor, is_player) return item
class TestItem(unittest.TestCase): def setUp(self): self.item = Item('Generic Item', 1.99) def test_is_item(self): self.assertIsInstance(self.item, Item) def test_has_name(self): self.assertEqual(self.item.name, 'Generic Item') def test_has_price(self): self.assertEqual(self.item.price, 1.99) def test_set_price(self): self.item.price = 1.50 self.assertEqual(self.item.price, 1.50) def test_set_name(self): self.item.name = "Common Item" self.assertEqual(self.item.name, "Common Item") def test_can_sell(self): self.item.quantity = 6 self.assertEqual(self.item.quantity, 6) sold = self.item.sell(5) self.assertTrue(sold) self.assertEqual(self.item.quantity, 1) def test_can_sell_to_zero(self): self.item.quantity = 6 sold = self.item.sell(6) self.assertTrue(sold) self.assertEqual(self.item.quantity, 0) def test_no_sell_past_zero(self): self.item.quantity = 6 sold = self.item.sell(7) self.assertFalse(sold) # quantity should be unaffected if the sale doesn't go through. self.assertEqual(self.item.quantity, 6) def test_no_sell_after_zero(self): self.item.quantity = 6 first_sale = self.item.sell(6) self.assertTrue(first_sale) # quantity should go to zero. self.assertEqual(self.item.quantity, 0) # no more sales should be made. second_sale = self.item.sell(1) self.assertFalse(second_sale) # quantity should stay at zero. self.assertEqual(self.item.quantity, 0)
def setUp(self): from items.item import Item from items.item_set import ItemSet sword = Item("sword", "made by elves", 2) helmet = Item("helmet", "made by men", 1) potion = Item("potion", "restores health", 1) self._itemList = [sword, helmet, potion] self._items = ItemSet([sword, helmet, potion])
def test_inventory_add(self): inventory = Inventory() cool_item_1 = Item(uid="cool_item_1", name="Very Cool Item") cool_item_2 = Item(uid="cool_item_2", name="Very Cool Item Too") inventory.add_item(cool_item_1) inventory.add_item(cool_item_2) self.assertEqual( inventory.get_items("cool_item_1", pop=True)[0], cool_item_1) self.assertGreater(len(inventory.get_items("cool_item_1")), 0) self.assertEqual(inventory.get_items("cool_item_2")[0], cool_item_2)
def testItems(self): from space import Space from items.item import Item #Prepare items blade = Item("blade", "appears to be dull", 1) bow = Item("bow", "long bow", 2) #Create space space = Space("shire", "Home of the Hobbits.") items = space.getItemSet() #Assert space initially empty errorMsg = "New space contains items; should be empty" self.assertEqual(items.count(), 0, errorMsg) errorMsg = "Space claims to contain item even though it is empty." self.assertFalse(space.containsItem(blade), errorMsg) self.assertFalse(space.containsItem(bow), errorMsg) #Add blade space.addItem(blade) errorMsg = "Space failed to report that it contained item known to exist." self.assertTrue(space.containsItem(blade), errorMsg) #Add bow space.addItem(bow) self.assertTrue(space.containsItem(bow), errorMsg) #Get room's items. Assert blade and bow exist items = space.getItemSet() self.assertEqual(items.count(), 2, "Room should contain exactly two items.") self.assertTrue(items.containsItem(blade), "Could not find blade in room's set of items.") self.assertTrue(items.containsItem(bow), "Could not find bow in room's set of items.") #Remove blade space.removeItem(blade) errorMsg = "Space claims to have item that was removed." self.assertFalse(space.containsItem(blade), errorMsg) errorMsg = "Space missing item that should still exist." self.assertTrue(space.containsItem(bow), errorMsg) #Get room's items. Assert only bow exists items = space.getItemSet() self.assertEqual(items.count(), 1, "Room should contain exactly one item.") self.assertFalse(items.containsItem(blade), "Blade found in room (even though it was removed).") self.assertTrue(items.containsItem(bow), "Could not find bow in room's set of items.")
def __init__(self, name, description, weight, defense, cost): """ Initializes armor class. @param name: The name of the item. @param description: Armor description. @param weight: Armor weight. @param defense: The defense stat of the piece of armor. Reduces the amount of damage that player receives by this amount. """ Item.__init__(self, name, description, weight) self._defense = defense self._cost = cost
def __init__(self, name, description, weight, healing, cost): """ Initializes potions class. @param name: Name of portion. @param description: Description of potion. @param weight: Weight of weapon. @param healing: Healing stat of weapon. Player heals by the maximum of this amount when player uses potion. """ Item.__init__(self, name, description, weight) self._healing = healing self._cost = cost
def __init__(self, name, description, weight, cost, defense): """ Initializes armor class. @param name: The name of the piece of armor. @param description: Armor description. @param weight: Armor weight. @param cost: The cost of the armor. @param defense: The defense stat of the piece of armor. """ Item.__init__(self, name, description, weight, cost) self._defense = defense
def __init__(self, name, description, weight, attack, cost): """ Initializes weapon class. @param name: Name of weapon. @param description: Description of weapon. @param weight: Weight of weapon. @param attack: Attack stat of weapon. Player damage increases by this amount when weapon is equipped. """ Item.__init__(self, name, description, weight) self._attack = attack self._cost = cost
def update(self, game: List[List[int]]) -> None: """Loop through the game list and mirror it to a list of objects such that the objects represent visually what is going on in the game. Both lists are iterated on in parallel, if the object list contains an item where the new game list is empty remove that item. If they are different change it to the new one. """ wall_color = (0, 0, 255) player_color = (0, 255, 0) food_color = (255, 0, 0) temp_list = [] for row in range(len(game)): temp_col = [] # Create a object based on the item in the list for col in range(len(game[row])): current = game[row][col] # Check which item is in the spot if current == 0: temp_col.append(None) # add player object elif current == 1: item = Item((row * self.SCALE, col * self.SCALE), player_color) temp_col.append(item) # add food object elif current == 2: item = Item((row * self.SCALE, col * self.SCALE), food_color) temp_col.append(item) # add wall object elif current == 3: # add green item item = Item((row * self.SCALE, col * self.SCALE), wall_color) temp_col.append(item) else: temp_col.append(None) temp_list.append(temp_col) self.objects = temp_list
def __init__(self, name, description, weight, cost, healing): """ Initializes potions class. @param name: Name of portion. @param description: Description of potion. @param weight: Weight of weapon. @param cost: The cost of the potion. @param healing: Healing stat of potion. Player may heal at most this amount upon use. """ Item.__init__(self, name, description, weight, cost) self._healing = healing
def testItem(self): from items.item import Item name = "Generic item" description = "Generic description" weight = 9 item = Item(name, description, weight) errorMsg = "Expected item name to be '%s'." % name self.assertEqual(item.getName(), name, errorMsg) errorMsg = "Expected item description to be '%s'." % description self.assertEqual(item.getDescription(), description, errorMsg) errorMsg = "Expected item weight to be '%s'." % weight self.assertEqual(item.getWeight(), weight, errorMsg)
def load(self): with open("savefile", "rb") as f: loaddata = pickle.load(f) self.all_sprites = pg.sprite.LayeredUpdates() self.walls = pg.sprite.Group() self.mobs = pg.sprite.Group() self.mobslist = [] self.ghostlist = [] self.bullets = pg.sprite.Group() self.items = pg.sprite.Group() self.itemslist = [] self.map = TiledMap(path.join(map_folder, 'Fase1.tmx')) self.map_img = self.map.make_map() self.map.rect = self.map_img.get_rect() self.player = Player(self, loaddata[0][2][0], loaddata[0][2][1]) self.player.health = loaddata[0][0] self.player.weapon = loaddata[0][1] for zombie in loaddata[1]: M = Mob(self, zombie[0], zombie[1]) self.mobslist.append(M) for ghost in loaddata[3]: G = Ghost(self, ghost[0], ghost[1]) self.ghostlist.append(G) for item in loaddata[2]: I = Item(self, item[0], item[1]) self.itemslist.append(I) for tile_object in self.map.tmxdata.objects: if tile_object.name == 'wall': Obstacle(self, tile_object.x, tile_object.y, tile_object.width, tile_object.height) self.camera = Camera(self.map.width, self.map.height) self.draw_debug = False self.paused = False
def test_inventory_keybound(self): inventory = KeyBoundInventory() cool_item_1 = Item(uid="cool_item_1", name="Very Cool Item") cool_item_2 = Item(uid="cool_item_2", name="Very Cool Item Too") cool_item_1_symbol = inventory.add_item(cool_item_1) cool_item_2_symbol = inventory.add_item(cool_item_2) self.assertEqual(inventory.pop_item_from_symbol(cool_item_1_symbol), cool_item_1) self.assertEqual(inventory.pop_item_from_symbol(cool_item_2_symbol), cool_item_2) symbols = [] for kek in range(0, 1000): symbols.append(inventory.add_item(cool_item_1)) print(symbols)
def __init__(self, name, description, weight, cost, attack, defense, hp): """ Initializes charm class. @param name: The name of the item. @param description: Charm description. @param weight: Charm weight. @param attack: Attack bonus given by charm. @param defense: The defense stat of the charm. Reduces the amount of damage that player receives by this amount. @param hp: The hp bonus of the charm. """ Item.__init__(self, name, description, weight, cost) self._attack = attack self._defense = defense self._hp = hp
def convert_to_object(entity): item_id = entity.key.id_or_name return Item(item_id, entity['title'], entity['daily_price'], entity['weekly_price'], entity['monthly_price'], entity['description'], entity['retail_price'], entity['kind'], entity['rented'], entity['rentee'], entity['renter'], entity['past_rented'], entity['category'], entity['location'], entity['blob_url'])
def spawn_energy_orbs(self, quantity: int): image_file = "misc/energy_orb.png" for _ in range(quantity): chosen = choice(list(self.floors)) position = (chosen.rect.left, chosen.rect.top) self.energy_orbs.add( Item(self.surface, position, (20, 20), image_file, 0))
def spawn_hearts(self, quantity: int): image_file = "misc/heart.png" for _ in range(quantity): chosen = choice(list(self.floors)) position = (chosen.rect.left, chosen.rect.top) self.hearts.add( Item(self.surface, position, (30, 30), image_file, 0))
def build_leather_hood(): _item = Item( uid="hood", name="hood", description="A leather hood.", display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"), ) _item.register_component(data.python_templates.material.Leather.copy()) _item.register_component(Stats(health=10, size=Size.Medium, weight=2)) _item.register_component( Armor(base_armor_class=2, armor_category=item_enums.ArmorCategory.Medium, wearable_body_parts_uid=["humanoid_head"], worn_layer=item_enums.WornLayer.Outer)) return _item
def build_long_sword(): _long_sword = Item( uid="long_sword", name="Longsword", description="A longsword.", display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"), ) _long_sword.register_component(data.python_templates.material.Iron.copy()) _long_sword.register_component(Stats(health=1, size=Size.Medium)) _long_sword.register_component( Weapon(weapon_category=item_enums.WeaponCategory.Martial, weapon_type=item_enums.WeaponType.Melee, size=Size.Medium, melee_damage_type=DamageType.Slash, damage_dice=DiceStack(1, Dice(8)))) return _long_sword
def build_boot(): _boot = Item( uid="boot", name="Boot", description="An iron boot", display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"), ) _boot.register_component(data.python_templates.material.Iron.copy()) _boot.register_component(Stats(health=10, size=Size.Medium, weight=0.5)) _boot.register_component( Armor(base_armor_class=0.5, armor_category=item_enums.ArmorCategory.Medium, wearable_body_parts_uid=["humanoid_foot"], worn_layer=item_enums.WornLayer.Outer, maximum_dexterity_bonus=2)) return _boot
def create_player(self, name, address=None): players = self.players for plr in players: if plr.name == name: return None room1 = self.rooms[0] name = str(name) id_player = len(players) + 1 new_player = Player(id_player, name, address=address) new_player.inventory.append(Item('Map', command='map')) self.add_to_room(new_player, room1) players.append(new_player) return id_player
def build_leather_pants(): # TODO Some items need to take two slots rather than one. item = Item( uid="pants", name="pants", description="Leather pants", display=Display(Colors.DARK_GRAY, Colors.BLACK_COLOR, "!"), ) item.register_component(data.python_templates.material.Leather.copy()) item.register_component(Stats(health=10, size=Size.Medium, weight=0.5)) item.register_component( Armor(base_armor_class=1, armor_category=item_enums.ArmorCategory.Medium, wearable_body_parts_uid=["humanoid_leg"], worn_layer=item_enums.WornLayer.Outer, maximum_dexterity_bonus=2)) return item
def testAddRemoveContainsItems(self): from items.item import Item antidote = Item("antidote", "cures poison", 1) #Verify item not included in collection errorMsg = "ItemSet.containsItem() claimed to contain item not present." self.assertFalse(self._items.containsItem(antidote), errorMsg) #Add item self._items.addItem(antidote) errorMsg = "ItemSet.containsItem() failed to identify existing item." self.assertTrue(self._items.containsItem(antidote), errorMsg) #Remove item self._items.removeItem(antidote) errorMsg = "ItemSet.containsItem() claimed to contain item not present." self.assertFalse(self._items.containsItem(antidote), errorMsg)
def testExecute(self): from player import Player from space import Space from items.item import Item from items.weapon import Weapon from commands.unequip_command import UnequipCommand #Attempting to unequip item not currently equipped space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) unequipCmd = UnequipCommand("unequip", "Unequips currently equipped item", player) item = Item("Charm", "Unknown effects", 1) weapon = Weapon("Dagger", "A trusty blade", 2, 2) rawInputMock = MagicMock(return_value="Dagger") with patch('commands.unequip_command.raw_input', create=True, new=rawInputMock): unequipCmd.execute() ###TODO: FIND SOME WAY TO MAKE SURE THAT PRINT STATEMENT PRINTED #Attempting to unequip item that may be unequipped space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) unequipCmd = UnequipCommand("unequip", "Unequips currently equipped item", player) weapon = Weapon("Dagger", "A trusty blade", 2, 2) player.equip(weapon) rawInputMock = MagicMock(return_value="Dagger") with patch('commands.unequip_command.raw_input', create=True, new=rawInputMock): unequipCmd.execute() equipped = player.getInventory() self.assertFalse(equipped.containsItem(weapon), "Failed to unequip item that it should have.")
def testExecute(self): from space import Space from player import Player from items.item import Item from commands.pick_up_command import PickUpCommand space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) item = Item("Dagger", "A trusty blade", 2) pickUpCmd = PickUpCommand("pick up", "Picks up an object", player) space.addItem(item) #Assert item in space but not in inventory and not in equipment self.assertTrue(space.containsItem(item), "Space should have item but does not.") inventory = player.getInventory() self.assertFalse(inventory.containsItem(item), "Player should not have item but does in inventory.") equipped = player.getEquipped() self.assertFalse(equipped.containsItem(item), "Player should not have item but does in equipment.") #Assert item in player inventory but not in space and not in equipment rawInputMock = MagicMock(return_value="Dagger") with patch('commands.pick_up_command.raw_input', create=True, new=rawInputMock): pickUpCmd.execute() self.assertFalse(space.containsItem(item), "Space should not have item but does.") equipped = player.getEquipped() self.assertFalse(equipped.containsItem(item), "Player should not have item in equipment.") inventory = player.getInventory() self.assertTrue(inventory.containsItem(item), "Player should have item but does not.")
def new(self): # Criando grupos de sprites self.all_sprites = pg.sprite.Group() self.walls = pg.sprite.Group() self.mobs = pg.sprite.Group() self.mobslist = [] self.ghostlist = [] self.bullets = pg.sprite.Group() self.items = pg.sprite.Group() self.itemslist = [] # Usando a biblioteca Pytween para criar um mapa em tiles, usando o editor de mapas self.map = TiledMap( path.join(path.join(path.dirname(__file__), 'maps'), 'fase1.tmx')) self.map_img = self.map.make_map() self.map.rect = self.map_img.get_rect() # loop que lê os objetos posicionados no editor de mapas e cria eles for tile_object in self.map.tmxdata.objects: obj_center = vec(tile_object.x + tile_object.width / 2, tile_object.y + tile_object.height / 2) if tile_object.name == 'player': self.player = Player(self, obj_center.x, obj_center.y) if tile_object.name == 'zombie': M = Mob(self, obj_center.x, obj_center.y) self.mobslist.append(M) if tile_object.name == 'ghost': G = Ghost(self, obj_center.x, obj_center.y) self.ghostlist.append(G) if tile_object.name == 'wall': Obstacle(self, tile_object.x, tile_object.y, tile_object.width, tile_object.height) if tile_object.name in ['health', 'shotgun', 'staff']: I = Item(self, obj_center, tile_object.name) self.itemslist.append(I) self.camera = Camera(self.map.width, self.map.height) self.paused = False
def testEquipUnequip(self): from player import Player from space import Space from items.item import Item from items.weapon import Weapon from items.armor import Armor space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) newItem = Item("Chainik Reakettle", "Makes good tea", 1) newWeapon = Weapon("Gun of Hurlocker", "Oppressive, but friendly", 2, 3) newArmor = Armor("Cookies of Miles", "Defends against sadness", 2, 4) player.addToInventory(newItem) player.addToInventory(newWeapon) player.addToInventory(newArmor) #Attempt to equip new items player.equip(newItem) self.assertFalse(newItem in player.getEquipped(), "Equipped %s and should not have." % newItem) player.equip(newWeapon) self.assertTrue(newWeapon in player.getEquipped(), "Failed to equip %s" % newWeapon) player.equip(newArmor) self.assertTrue(newArmor in player.getEquipped(), "Failed to equip %s" % newArmor) #Attempt to unequip items player.unequip(newWeapon) self.assertFalse(newWeapon in player.getEquipped(), "Failed to unequip %s" % newWeapon) player.unequip(newArmor) self.assertFalse(newArmor in player.getEquipped(), "Failed to unequip %s" % newArmor)
def testItemsWeight(self): from items.item import Item errorMsg = "Initial weight of ItemSet object incorrect." expectedWeight = ItemSetTest.INITIAL_WEIGHT actualWeight = self._items.weight() self.assertEqual(expectedWeight, actualWeight, errorMsg) heavyRock = Item("heavy rock", "weighs a ton", 2000) #Add item self._items.addItem(heavyRock) errorMsg = "ItemSet.weight() reported incorrect weight." expectedWeight += 2000 actualWeight = self._items.weight() self.assertEqual(expectedWeight, actualWeight, errorMsg) #Remove item self._items.removeItem(heavyRock) expectedWeight -= 2000 actualWeight = self._items.weight() self.assertEqual(expectedWeight, actualWeight, errorMsg)
def __init__(self): Item.__init__(self, "Dragon's Claw", "+40 Magic Resistance, Gain 83% resistance to magic damage", True)
def testExecute(self): from player import Player from space import Space from items.item import Item from items.weapon import Weapon from commands.equip_command import EquipCommand #Tests default states space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) #Trying to equip item not in inventory space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) equipCmd = EquipCommand("Equip", "Equips item in inventory to player", player) item = Item("Charm", "Unknown effects", 1) weapon = Weapon("Dagger", "A trusty blade", 2, 2) rawInputMock = MagicMock(return_value="Dagger") with patch('commands.equip_command.raw_input', create=True, new=rawInputMock): equipCmd.execute() equipped = player.getEquipped() self.assertFalse(equipped.containsItem(weapon), "Player equipped item not in inventory.") #Trying to equip item that cannot be equipped (e.g. item is not instance of Armor or Weapon) space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) equipCmd = EquipCommand("Equip", "Equips item in inventory to player", player) item = Item("Charm", "Unknown effects", 1) inventory = player.getInventory() inventory.addItem(item) rawInputMock = MagicMock(return_value="Charm") with patch('commands.equip_command.raw_input', create=True, new=rawInputMock): equipCmd.execute() equipped = player.getEquipped() self.assertFalse(equipped.containsItem(item), "Player equipped item of Item class.") #Equipping item that can be equipped space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) equipCmd = EquipCommand("Equip", "Equips item in inventory to player", player) weapon = Weapon("Dagger", "A trusty blade", 2, 2) inventory = player.getInventory() inventory.addItem(weapon) rawInputMock = MagicMock(return_value="Dagger") with patch('commands.equip_command.raw_input', create=True, new=rawInputMock): equipCmd.execute() equipped = player.getEquipped() self.assertTrue(equipped.containsItem(weapon), "Player failed to equip equipable item.") #Equipping an item that is already equipped space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) equipCmd = EquipCommand("Equip", "Equips item in inventory to player", player) weapon = Weapon("Dagger", "A trusty blade", 2, 2) inventory = player.getInventory() inventory.addItem(weapon) equipped = player.getEquipped() equipped.addItem(weapon) rawInputMock = MagicMock(return_value="Dagger") with patch('commands.equip_command.raw_input', create=True, new=rawInputMock): equipCmd.execute() numberInInventory = 0 numberInEquipped = 0 for item in inventory._items: if item == weapon: numberInInventory += 1 for item in equipped._items: if item == weapon: numberInEquipped += 1 self.assertEqual( inventory.count(), 1, "Equipping an item that is already equipped failed -- inventory problem." ) self.assertEqual( equipped.count(), 1, "Equipping an item that is already equipped failed -- equipment problem." )