本文整理汇总了Python中inventory.Inventory.add_item方法的典型用法代码示例。如果您正苦于以下问题:Python Inventory.add_item方法的具体用法?Python Inventory.add_item怎么用?Python Inventory.add_item使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类inventory.Inventory
的用法示例。
在下文中一共展示了Inventory.add_item方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_add_2
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
def test_add_2(self):
inv = Inventory(slot_count=20)
block = random.choice(G.BLOCKS_DIR.keys())
max_items = G.BLOCKS_DIR[block].max_stack_size * 20
for i in xrange(0, max_items):
self.assertTrue(inv.add_item(block))
item = random.choice(G.ITEMS_DIR.keys())
inv2 = Inventory(slot_count=20)
max_items2 = G.ITEMS_DIR[item].max_stack_size * 20
for i in xrange(0, max_items2):
self.assertTrue(inv2.add_item(item))
self.assertNotIn(None, inv.slots)
self.assertNotIn(None, inv2.slots)
for slot in inv.slots:
self.assertEqual(slot.type, block)
self.assertEqual(slot.amount, G.BLOCKS_DIR[block].max_stack_size)
for slot in inv2.slots:
self.assertEqual(slot.type, item)
self.assertEqual(slot.amount, G.ITEMS_DIR[item].max_stack_size)
示例2: test_remove
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
def test_remove(self):
inv = Inventory(slot_count=20)
block = random.choice(G.BLOCKS_DIR.keys())
max_items = G.BLOCKS_DIR[block].max_stack_size * 20
for i in xrange(0, max_items):
self.assertTrue(inv.add_item(block))
self.assertFalse(inv.remove_item(block, quantity=0))
for i in xrange(0, 20):
self.assertTrue(inv.remove_item(block, quantity=G.BLOCKS_DIR[block].max_stack_size))
self.assertEqual(inv.slots, [None] * 20)
for i in xrange(0, max_items):
self.assertTrue(inv.add_item(block))
for i in xrange(0, 20):
self.assertTrue(inv.remove_by_index(i, quantity=G.BLOCKS_DIR[block].max_stack_size))
self.assertEqual(inv.slots, [None] * 20)
for i in xrange(0, 20):
inv.slots[i] = ItemStack(block, amount=1)
inv.slots[i].change_amount(-1)
inv.remove_unnecessary_stacks()
self.assertEqual(inv.slots, [None] * 20)
示例3: test_add_1
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
def test_add_1(self):
for size in [0, 9, random.randint(3, 100)]:
inv = Inventory(slot_count=size)
item = random.choice(G.ITEMS_DIR.keys())
block = random.choice(G.BLOCKS_DIR.keys())
result = inv.add_item(item)
result2 = inv.add_item(block)
if size == 0:
self.assertFalse(result)
self.assertFalse(result2)
else:
self.assertTrue(result)
self.assertTrue(result2)
foundItem = False
foundBlock = False
for slot in inv.slots:
if slot:
if slot.type == item and slot.amount == 1:
foundItem = True
elif slot.type == block and slot.amount == 1:
foundBlock = True
self.assertTrue(foundItem)
self.assertTrue(foundBlock)
self.assertEqual(result, result2)
示例4: Player
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
class Player(Entity):
local_player = True
def __init__(self, position=(0,0,0), rotation=(-20, 0), flying=False,
game_mode=G.GAME_MODE, username="", local_player=True):
super(Player, self).__init__(position, rotation, health=7,
max_health=10, attack_power=2.0 / 3,
attack_range=4)
self.inventory = Inventory(27)
self.quick_slots = Inventory(9)
self.armor = Inventory(4)
self.flying = flying
self.game_mode = game_mode
self.strafe = [0, 0]
self.dy = 0
self.current_density = 1 # Current density of the block we're colliding with
self._position = position
self.last_sector = None
self.last_damage_block = 0, 100, 0 # dummy temp value
self.username = username
self.local_player = local_player
# for debug
initial_items = [cake_block, torch_block, bed_item]
for item in initial_items:
self.inventory.add_item(item.id, item.max_stack_size)
if not local_player:
self.model = PlayerModel(position)
self.momentum = (0,0,0)
def add_item(self, item_id, quantity=1):
if self.quick_slots.add_item(item_id, quantity=quantity):
return True
elif self.inventory.add_item(item_id, quantity=quantity):
return True
return False
def change_health(self, change):
self.health += change
if self.health > self.max_health:
self.health = self.max_health
@property
def position(self):
return self._position
@position.setter
def position(self, value):
self._position = value
if not self.local_player: self.model.update_position(value)
def on_deactivate(self):
self.strafe = [0, 0]
def on_key_release(self, symbol, modifiers):
if symbol == G.MOVE_FORWARD_KEY:
self.strafe[0] += 1
elif symbol == G.MOVE_BACKWARD_KEY:
self.strafe[0] -= 1
elif symbol == G.MOVE_LEFT_KEY:
self.strafe[1] += 1
elif symbol == G.MOVE_RIGHT_KEY:
self.strafe[1] -= 1
elif (symbol == G.JUMP_KEY
or symbol == G.CROUCH_KEY) and self.flying:
self.dy = 0
def on_key_press(self, symbol, modifiers):
if symbol == G.MOVE_FORWARD_KEY:
self.strafe[0] -= 1
elif symbol == G.MOVE_BACKWARD_KEY:
self.strafe[0] += 1
elif symbol == G.MOVE_LEFT_KEY:
self.strafe[1] -= 1
elif symbol == G.MOVE_RIGHT_KEY:
self.strafe[1] += 1
elif symbol == G.JUMP_KEY:
if self.flying:
self.dy = 0.045 # jump speed
elif self.dy == 0:
self.dy = 0.016 # jump speed
G.CLIENT.send_jump()
elif symbol == G.CROUCH_KEY:
if self.flying:
self.dy = -0.045 # inversed jump speed
elif symbol == G.FLY_KEY and self.game_mode == G.CREATIVE_MODE:
self.dy = 0
self.flying = not self.flying
def get_motion_vector(self, multiplier=1):
if any(self.strafe):
x, y = self.rotation
y_r = radians(y)
x_r = radians(x)
strafe = atan2(*self.strafe)
if self.flying:
m = cos(y_r)
dy = sin(y_r)
if self.strafe[1]:
dy = 0.0
#.........这里部分代码省略.........
示例5: Player
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
class Player(Entity):
def __init__(self, position, rotation, flying=False,
game_mode=G.GAME_MODE):
super(Player, self).__init__(position, rotation, health=7,
max_health=10, attack_power=2.0 / 3,
attack_range=4)
self.inventory = Inventory()
self.quick_slots = Inventory(9)
self.armor = Inventory(4)
self.flying = flying
self.game_mode = game_mode
self.strafe = [0, 0]
self.dy = 0
self.current_density = 1 # Current density of the block we're colliding with
self.last_sector = None
self.damage_block = 0, 100, 0
initial_items = [torch_block, stick_item]
for item in initial_items:
quantity = random.randint(2, 10)
if random.choice((True, False)):
self.inventory.add_item(item.id, quantity)
#else:
# self.quick_slots.add_item(item.id, quantity)
def add_item(self, item_id):
if self.quick_slots.add_item(item_id):
return True
elif self.inventory.add_item(item_id):
return True
return False
def change_health(self, change):
self.health += change
if self.health > self.max_health:
self.health = self.max_health
def on_deactivate(self):
self.strafe = [0, 0]
def on_key_release(self, symbol, modifiers):
if symbol == G.MOVE_FORWARD_KEY:
self.strafe[0] += 1
G.BIOME_BLOCK_COUNT +=1
#print ('north' + str(G.BIOME_BLOCK_COUNT))
elif symbol == G.MOVE_BACKWARD_KEY:
self.strafe[0] -= 1
G.BIOME_BLOCK_COUNT -=1
elif symbol == G.MOVE_LEFT_KEY:
self.strafe[1] += 1
G.BIOME_BLOCK_COUNT +=1
elif symbol == G.MOVE_RIGHT_KEY:
self.strafe[1] -= 1
G.BIOME_BLOCK_COUNT +=1
elif (symbol == G.JUMP_KEY
or symbol == G.CROUCH_KEY) and self.flying:
self.dy = 0
def on_key_press(self, symbol, modifiers):
if symbol == G.MOVE_FORWARD_KEY:
self.strafe[0] -= 1
G.BIOME_BLOCK_COUNT +=1
elif symbol == G.MOVE_BACKWARD_KEY:
self.strafe[0] += 1
G.BIOME_BLOCK_COUNT -=1
elif symbol == G.MOVE_LEFT_KEY:
self.strafe[1] -= 1
G.BIOME_BLOCK_COUNT +=1
elif symbol == G.MOVE_RIGHT_KEY:
self.strafe[1] += 1
G.BIOME_BLOCK_COUNT -=1
elif symbol == G.JUMP_KEY:
if self.flying:
self.dy = 0.045 # jump speed
elif self.dy == 0:
self.dy = 0.016 # jump speed
elif symbol == G.CROUCH_KEY:
if self.flying:
self.dy = -0.045 # inversed jump speed
elif symbol == G.FLY_KEY and self.game_mode == G.CREATIVE_MODE:
self.dy = 0
self.flying = not self.flying
def get_motion_vector(self):
if any(self.strafe):
x, y = self.rotation
y_r = radians(y)
x_r = radians(x)
strafe = atan2(*self.strafe)
if self.flying:
m = cos(y_r)
dy = sin(y_r)
if self.strafe[1]:
dy = 0.0
m = 1
if self.strafe[0] > 0:
dy *= -1
x_r += strafe
dx = cos(x_r) * m
#.........这里部分代码省略.........
示例6: Player
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
class Player(GameImage):
def __init__(self, world):
GameImage.__init__(self)
self.party = []
self.add_party_member(BERNARD)
self.world_image = Surface((16, 16))
self.rect = Rect(0, 0, 16, 16)
self.world_image.fill(Color("#FF0000"))
self.image = Surface((16, 16))
self.image.blit(self.world_image, (0, 0))
self.mask = pygame.mask.from_surface(self.image)
self.world = world
self.button_press_map = DEFAULT_BUTTON_PRESS_MAP
self.summons = []
self.xvel, self.yvel = 0, 0
self.inventory = Inventory()
self.reset_encounter_timer()
self.totem_contact = False
def update(self):
self.xvel, self.yvel = 0, 0
up, down, left, right = self.button_press_map[UP], self.button_press_map[DOWN], self.button_press_map[LEFT], self.button_press_map[RIGHT]
if up and not down: self.yvel = -1
if down and not up: self.yvel = 1
if left and not right: self.xvel = -1
if right and not left: self.xvel = 1
self.rect.top += self.yvel
self.rect.left += self.xvel
tile = self.current_tile()
self.check_entity_collisions(tile)
#TODO: collision checks go here
if self.xvel != 0 or self.yvel != 0: self.encounter_update(tile)
def deactivate(self):
self.button_press_map[UP], self.button_press_map[DOWN], self.button_press_map[LEFT], self.button_press_map[RIGHT] = False, False, False, False
def add_party_member(self, key):
spell_factory = SpellFactory()
self.party.append(PartyMember(key, PARTY_MEMBER_MAP, spell_factory))
def remove_summons(self):
self.summons = []
def encounter_update(self, tile):
self.encounter_timer -= tile.base_encounter_rate
if self.encounter_timer <= 0:
monster_party = tile.roll_monster_party()
self.begin_encounter(monster_party)
self.reset_encounter_timer()
def reset_encounter_timer(self):
self.encounter_timer = random.gauss(ENCOUNTER_MEAN, ENCOUNTER_SD)
def begin_encounter(self, monsters, battle_data = None):
self.deactivate()
self.world.screen_manager.switch_to_battle_screen(self, monsters, self.current_tile(), battle_data)
def refresh_tile_flags(self):
self.totem_contact = False
def reset_flags(self):
self.refresh_tile_flags()
for p in self.party: p.reset_flags()
def check_entity_collisions(self, tile):
if tile.entity:
self.refresh_mask()
tile.entity.refresh_mask()
if pygame.sprite.collide_rect(self, tile.entity): self.collide_with(tile.entity)
else: self.refresh_tile_flags()
else: self.refresh_tile_flags()
def collide_with(self, entity):
entity.take_effect(self)
def begin_heal_flash(self):
if self.totem_contact: return
self.totem_contact = True
self.world.begin_flash(LIGHT_BLUE, 100)
def current_tile(self):
x, y = self.rect.centerx/TILE_SIZE, self.rect.centery/TILE_SIZE
return self.world.tile_at(x, y)
def enqueue_action(self, index, key, target = None):
if index >= len(self.party): actor = self.summons[index - len(self.party)]
else: actor = self.party[index]
actor.enqueue_action(key, target)
def party_member_count(self):
return len(self.party)
def summon_count(self):
return len(self.summons)
def obtain_item(self, item):
self.inventory.add_item(item)
示例7: InventoryTest
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
class InventoryTest(unittest.TestCase):
def setUp(self):
"""Create inventory instance."""
self.inv = Inventory()
def tearDown(self):
"""Close database opened by self.inv."""
self.inv.close()
def test_add_record_to_database(self):
nrecords = self.count_records()
self.inv.add_item('test_item', 15.00, 200)
self.assertEqual(self.count_records(), nrecords+1)
def test_remove_record_from_database(self):
nrecords = self.count_records()
self.inv.remove_item('test_item')
self.assertEqual(self.count_records(), nrecords-1)
def test_query_sort(self):
for field in ['item', 'price', 'qty', 'updated']:
for direction in ['ascending', 'descending']:
count = 0
for row in self.inv.query_sort(field, direction):
count += 1
self.assertEqual(count, 100)
def test_count_records(self):
self.assertEqual(self.count_records(), self.inv.nrecords)
def test_next_page(self):
pass
def test_update_qty(self):
self.inv.update_qty('item000', 250)
self.inv.c.execute('SELECT qty FROM inventory WHERE item=?', ('item000',))
self.assertEqual(self.inv.c.fetchone()[0], 250)
self.inv.update_qty('item000', 500)
def test_update_price(self):
original_price = self.inv.c.execute('SELECT price FROM inventory WHERE item=?', ('item000',)).fetchone()[0]
self.inv.update_price('item000', 10)
self.inv.c.execute('SELECT price FROM inventory WHERE item=?', ('item000',))
self.assertEqual(self.inv.c.fetchone()[0], 10)
self.inv.update_price('item000', original_price)
def test_query_by_price(self):
original_price1 = self.inv.c.execute('SELECT price FROM inventory WHERE item=?', ('item050',)).fetchone()[0]
original_price2 = self.inv.c.execute('SELECT price FROM inventory WHERE item=?', ('item150',)).fetchone()[0]
self.inv.update_price('item050', 50)
self.inv.update_price('item150', 70)
# Check with low and high price range
count = 0
for row in self.inv.query_by_price(40,80):
count += 1
self.assertEqual(count, 2)
# Check with only low price
count = 0
for row in self.inv.query_by_price(40):
count += 1
self.assertEqual(count, 2)
# We also expect all records to be returned with no prices set
count = 0
for row in self.inv.query_by_price():
count += 1
self.assertEqual(count, self.count_records())
def test_query_by_name(self):
# Test should return same number of results regardless of sort
count = 0
for row in self.inv.query_by_name('item0', 0, 100, 'item'):
count += 1
self.assertEqual(count, 100)
count = 0
for row in self.inv.query_by_name('item0', 0, 100, 'price'):
count += 1
self.assertEqual(count, 100)
count = 0
for row in self.inv.query_by_name('item0', 0, 100):
count += 1
self.assertEqual(count, 100)
count = 0
for row in self.inv.query_by_name('item0'):
count += 1
self.assertEqual(count, 100)
def test_get_qty(self):
self.inv.update_qty('item100', 1000)
self.assertEqual(self.inv.view_qty('item100'), 1000)
self.inv.update_qty('item100', 1000)
def count_records(self):
return self.inv.c.execute('SELECT Count(*) FROM inventory').fetchone()[0]
示例8: Human
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
class Human(Entity):
"""Human entity."""
#
# __init__()
#
def __init__(self, name, gender, view_radius, inventory_size):
"""Create new human entity instance.
Arguments:
name - name of entity
gender - either "Male" or "Female"
view_radius - number of tiles they can see into the distance
inventory_size - size of their inventory, in game weight units
"""
super(Human, self).__init__(name, "Human", '@', libtcod.white)
self.gender = gender
self.view_radius = view_radius
self.inventory = Inventory(inventory_size)
self.report = ReportType.VISIBLE_NPC
# Add actions
self.action_drop = ea.action_drop
self.action_get = ea.action_get
self.action_consume = ea.action_consume
#
# __str__()
#
def __str__(self):
"""Overridden from base class to include gender and name."""
return "{0} human named {1}".format(self.gender.lower(), self.name)
#
# add_entity_to_inventory()
#
def add_entity_to_inventory(self, entity):
"""Helper method to add an entity to inventory.
Arguments:
entity - entity to add.
"""
entity.x = -1
entity.y = -1
entity.owner = self
self.inventory.add_item(entity)
#
# remove_entity_from_inventory()
#
def remove_entity_from_inventory(self, entity):
"""Helper method to remove an entity from inventory.
Arguments:
entity - entity to remove.
"""
entity.owner = None
self.inventory.remove_item(entity)
示例9: Player
# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add_item [as 别名]
#.........这里部分代码省略.........
self.search_skill = SearchSkill(self)
self.inventory = Inventory(self)
def move(self, dx, dy):
newx, newy = self.x + dx, self.y + dy
if not self.map.coords_okay(newx, newy):
return False, False, None
if self.map.has_critter_at((newx, newy)):
cost = self.attack(self.map.get_critter_at(newx, newy))
return True, False, cost
next_tile = self.map.tile_at(newx, newy)
move_to, take_turn, fov_recalc = next_tile.player_move_into(self, newx, newy, self.map)
if move_to:
#todo move cost should be changed by the type of tile we're entering
self.x, self.y = newx, newy
self.search(self.map, 4)
return take_turn, fov_recalc, self.action_cost.move
elif next_tile.is_wall():
gl.message("You bump into wall")
return take_turn, fov_recalc, None
def search(self, map, range=None):
if not range:
range = self.fov_range
map.iterate_fov(self.x, self.y, range, self.see)
return self.action_cost.search
def descend(self, map):
if map.descend_or_ascend(True):
return self.action_cost.stairsdown / 2
return None
def ascend(self, map):
if map.descend_or_ascend(False):
return self.action_cost.stairsdown / 2
return None
def die(self, killer):
gl.message( 'You die...', 'CRITICAL')
gl.__game_state__ = "died"
def earn_exp(self, src):
self.xp += src.xp
if self.xp > util.xp_for_lvl(self.xl):
self.lvl_up()
def lvl_up(self):
self.xl += 1
gl.message ("Congratulations! Level up", 'INFO')
def see(self, tile, tilex, tiley, map):
if tile.items and len(tile.items):
item = tile.items[0]
if not getattr(item, 'seen', False):
gl.message('You see %s' % item)
item.seen = True
if getattr(tile, 'has_hidden', False):
self.search_skill.observe(tile)
def take_damage(self, mob, dmgs, attack):
#take evasion into account
super(Player, self).take_damage(mob, dmgs, attack)
if self.hitpoints <= self.base_hp * gl.__hp_warning__:
gl.message('Low HP!!!', 'WARN')
def gethp(self):
return self.hitpoints
def sethp(self, value):
self.hitpoints = value
gl.require_hud_update()
hp = property(gethp, sethp)
def get_inventory_categorized(self):
""" get_inventory_categorized() => {category :[items]}
Returns list of items divided by category
"""
return self.inventory.categorized_view()
def _item_pickup(self, item):
self.inventory.add_item(item)
gl.message('You pick up ' + str(item))
item.on_pickup(self)
def pickup(self, map, multi_select_handler=None):
tile = self.map.tile_at(self.x, self.y)
items = tile.items
if not items:
gl.message('There is nothing to pick up here')
if len(items) == 1:
item = items.pop()
self._item_pickup(item)
elif multi_select_handler:
selected_items = multi_select_handler(categorize_items(items))
if selected_items:
for item in selected_items:
items.remove(item)
self._item_pickup(item)