当前位置: 首页>>代码示例>>Python>>正文


Python Inventory.add方法代码示例

本文整理汇总了Python中inventory.Inventory.add方法的典型用法代码示例。如果您正苦于以下问题:Python Inventory.add方法的具体用法?Python Inventory.add怎么用?Python Inventory.add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在inventory.Inventory的用法示例。


在下文中一共展示了Inventory.add方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add [as 别名]
class Player:
  """The Player"""
  def __init__(self):
    self.inventory = Inventory()
    self.life = 100
    self.alive = True
    self.damage = 25

  def take_damage(self, amount):
    self.life -= amount
    if self.life <= 0:
      self.die()

  def die(self):
    print "You died!"
    exit(0)

  def add_item(self, item):
    self.inventory.add(item)

  def add_weapon(self, weapon):
    self.inventory.add(weapon)
    self.damage += weapon.damage

  def check_inventory(self):
    return(self.inventory)

  def equip_weapon(self, weapon):
    for item in inventory:
      if item.name == weapon:
        self.weapon = item
      else:
        return(False)
开发者ID:LeakyBucket,项目名称:LPTHW,代码行数:35,代码来源:player.py

示例2: from_disk

# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add [as 别名]
    def from_disk(self,path,url_prefix,inventory=None):
        """Create or extend inventory with resources from disk scan

        Assumes very simple disk path to URL mapping: chop path and
        replace with url_path. Returns the new or extended Inventory
        object.

        If a inventory is specified then items are added to that rather
        than creating a new one.

        mb = InventoryBuilder()
        m = inventory_from_disk('/path/to/files','http://example.org/path')
        """
        num=0
        # Either use inventory passed in or make a new one
        if (inventory is None):
            inventory = Inventory()
        # for each file: create Resource object, add, increment counter
        for dirpath, dirs, files in os.walk(path,topdown=True):
            for file_in_dirpath in files:
                try:
                    if self.exclude_file(file_in_dirpath):
                        continue
                    # get abs filename and also URL
                    file = os.path.join(dirpath,file_in_dirpath)
                    if (not os.path.isfile(file) or not (self.include_symlinks or not os.path.islink(file))):
                        continue
                    rel_path=os.path.relpath(file,start=path)
                    if (os.sep != '/'):
                        # if directory path sep isn't / then translate for URI
                        rel_path=rel_path.replace(os.sep,'/')
                    url = url_prefix+'/'+rel_path
                    file_stat=os.stat(file)
                except OSError as e:
                    sys.stderr.write("Ignoring file %s (error: %s)" % (file,str(e)))
                    continue
                mtime = file_stat.st_mtime
                lastmod = datetime.fromtimestamp(mtime).isoformat()
                r = Resource(uri=url,lastmod=lastmod)
                if (self.do_md5):
                    # add md5
                    r.md5=compute_md5_for_file(file)
                if (self.do_size):
                    # add size
                    r.size=file_stat.st_size
                inventory.add(r)
            # prune list of dirs based on self.exclude_dirs
            for exclude in self.exclude_dirs:
                if exclude in dirs:
                    dirs.remove(exclude)
        return(inventory)
开发者ID:edsu,项目名称:resync-simulator,代码行数:53,代码来源:inventory_builder.py

示例3: inventory

# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add [as 别名]
 def inventory(self):
     """Returns an inventory snapshot of all resources in the repo"""
     inventory = Inventory()
     for resource in self.resources:
         inventory.add(resource)
     return inventory
开发者ID:edsu,项目名称:resync-simulator,代码行数:8,代码来源:source.py

示例4: Character

# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add [as 别名]
class Character(object):
    """
    Define a character and its abilities
    """

    def __init__(self, reference=None, **custom):
        if reference:
            try:
                data = get_character_data(reference)
            except ValueError:
                raise UnexistingCharacterException(
                    "The reference \"{}\" doesn't exist".format(reference))
            else:
                for key in LIST_CARAC:
                    if not key in data:
                        data[key] = get_character_data("unknown")[key]
        else:
            data = get_character_data("unknown")
        self._health = 0
        self._inventory = inventory.Inventory()
        self.name = self.operations(custom.get("name", data["name"]))
        self.maxhealth = self.operations(custom.get(
            "maxhealth", data["maxhealth"]))
        self.health = custom.get("health", self.maxhealth)
        self.range_attack = self.operations(custom.get(
            "range_attack", data["range_attack"]))
        self.attack = self.operations(custom.get(
            "attack", data["attack"]))
        self.defense = self.operations(custom.get(
            "defense", data["defense"]))
        self.initiative = self.operations(custom.get(
            "initiative", data["initiative"]))
        self.inventory = Inventory(custom.get("inventory", data.get("inventory", None)))
        self.abilities = self.operations(custom.get(
            "abilities", data["abilities"]))  # Not used in this version
        self.ref = reference
        self.weapon = self.inventory.weapons[0]  # Take the first
                                                 # weapon found

    @property
    def inventory(self):
        return self._inventory

    @inventory.setter
    def inventory(self, value):
        self._inventory = value
        if not self.inventory.ref_in(inventory.create_item("bare_hands")):
            self.inventory.add(inventory.create_item("bare_hands"))

    @property
    def is_alive(self):
        return self.health > 0

    @property
    def is_dead(self):
        return not self.is_alive

    @property
    def health(self):
        return max(0, min(self._health, self.maxhealth))

    @health.setter
    def health(self, value):
        self._health = max(0, min(value, self.maxhealth))

    def operations(self, caract):
        """Calcule les valeurs aléatoire d'un Character"""
        if isinstance(caract, dict) and "_random_" in caract:
            if caract["_random_"] == "gauss":
                result = -1
                while not(caract.get("min", 0) <= result
                          and result <= caract.get("max", 10 ** 5)):
                    result = int(gauss(caract["mean"],
                                       caract["deviation"]) / 10) * 10
            elif caract["random"] == "choice":
                if caract["max_items"] < 1:
                    result = caract["items"][randint(0, len(caract["items"]))]
                else:
                    item = None
                    result = None
                    for i in caract["max_items"]:
                        while not item or item in result:
                            item = caract["items"][randint(
                                0, len(caract["items"]))]
                        result.append(item)
            elif caract["random"] == "equiproba":
                caract = int(randint(caract["min"], caract["max"]) / 10) * 10
            return result
        else:
            return caract

    def __str__(self):
        return str(self.__dict__)
开发者ID:PaulEcoffet,项目名称:stonewallsgate,代码行数:95,代码来源:character.py

示例5: Player

# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add [as 别名]
class Player(Character):

    def __init__(self, start_pos, graphics, start_space, pet=None):

	self.name = 'Player'

	self.pet = pet

	self.view_distance_y = VIEW_DISTANCE_Y
	self.view_distance_x = VIEW_DISTANCE_X

	self.inventory = Inventory(self.name)
	
	self.actions = {
	    KEY_INTERACT,
	    KEY_PLANT,
	    KEY_HARVEST,
	    KEY_INVENTORY,
	    KEY_CALL_PET
	    }

	Character.__init__(self, start_pos, graphics, start_space)


    # Moves another character if it is the way of the Player
    def displace(self, character, dir): 
	character.move(dir)

    
    def interact(self):

	for key in self.current_space.contents:
	    for obj in self.current_space.contents.get(key):
		if self.pos in obj.vicinity:

		    game.get_instance().msg_win.clear()
		    game.get_instance().msg_win.refresh()
		    obj.interact(self)


    def plant(self):

	game.get_instance().msg_win.clear()

	game.get_instance().msg_win.addstr(1, 20, "In which direction? [wasd] ")
	ans = game.get_instance().msg_win.getch()

	game.get_instance().msg_win.clear()
	game.get_instance().msg_win.refresh()

	if ans == KEY_UP:
	    ypos = self.pos[0] - 1
	    xpos = self.pos[1]

	elif ans == KEY_DOWN:
	    ypos = self.pos[0] + 1
	    xpos = self.pos[1]

	elif ans == KEY_LEFT:
	    ypos = self.pos[0]
	    xpos = self.pos[1] - 1

	elif ans == KEY_RIGHT:
	    ypos = self.pos[0]
	    xpos = self.pos[1] + 1

	else:
	    return
	
	if self.obstructed(ans):
	    return

	else:
	    Crop.create(ypos, xpos, 'GRAPHICS/crop1', self.current_space)

        game.get_instance().msg_win.clear()
        game.get_instance().msg_win.refresh()


    def harvest(self):

	try:

	    for crop in self.current_space.contents['Crop']:

	    	# if there is a crop directly above the player
	        if [(self.pos[0] - 1), self.pos[1]] in crop.boundaries:

		    if crop.stage == 3:

			temp = []

		        i = self.current_space.contents['Crop'].index(crop)
	
		        plant = self.current_space.contents['Crop'].pop(i)
			temp.append(plant)

		        self.inventory.add(temp)

		    else:
#.........这里部分代码省略.........
开发者ID:jvasilakes,项目名称:farm-game,代码行数:103,代码来源:character.py

示例6: Shipbox

# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add [as 别名]
class Shipbox(Node):


    def __init__(self, Ystart, Xstart, graphics_file, space):

	self.name = 'Shipbox'

	self.inventory = Inventory(self.name)

	Node.__init__(self, Ystart, Xstart, graphics_file, space)

	self.visible = True

	self.vicinity = find_vicinity(self.boundaries)


    def interact(self, player):

	game.get_instance().msg_win.clear()
	game.get_instance().msg_win.addstr(0, 5, "Shipping box: ")
	game.get_instance().msg_win.addstr(0, 25, "1. Add items.")
	game.get_instance().msg_win.addstr(1, 25, "2. Remove items.")
	game.get_instance().msg_win.addstr(2, 25, "3. Nevermind.")
	game.get_instance().msg_win.refresh()

	ans = game.get_instance().msg_win.getch()
	
	while ans != ord('1') and ans != ord('2') and ans != ord('3'):
	    ans = game.get_instance().msg_win.getch()

	game.get_instance().msg_win.clear()

	if ans == ord('1'):

	    game.get_instance().msg_win.addstr(1, 10, "What would you like to add?")
	    game.get_instance().msg_win.refresh()
	    game.get_instance().msg_win.getch()

	    game.get_instance().msg_win.clear()
	    game.get_instance().msg_win.refresh()

	    item_list = player.inventory.view()

	    if item_list == 'None':
		return

	    else:
	        self.inventory.add(item_list)

	elif ans == ord('2'):

	    game.get_instance().msg_win.addstr(1, 10, "What would you like to remove?")
	    game.get_instance().msg_win.refresh()
	    game.get_instance().msg_win.getch()

	    game.get_instance().msg_win.clear()
	    game.get_instance().msg_win.refresh()
	    item_list = ship_box.inventory.view()

	    if item_list == 'None':
		return

	    else:
	        player.inventory.add(item_list)

	elif ans == ord('3'):

	    return


    def sell(self, player):
	
	earnings = 0
	for key in self.inventory.contents:

	    for item in reversed(self.inventory.contents[key]):

		earnings += item.value
		self.inventory.contents[key].remove(item)

	player.inventory.money += earnings

	if earnings > 0:
	    game.get_instance().msg_win.clear()
	    game.get_instance().msg_win.refresh() 
	    game.get_instance().msg_win.addstr(1, 5, "Total shipment value:")
	    game.get_instance().msg_win.addstr(2, 5, "$")
	    game.get_instance().msg_win.addstr(2, 6, str(earnings))
	    game.get_instance().msg_win.refresh()

	else:
	    pass 
开发者ID:jvasilakes,项目名称:farm-game,代码行数:94,代码来源:environment.py

示例7: Player

# 需要导入模块: from inventory import Inventory [as 别名]
# 或者: from inventory.Inventory import add [as 别名]
class Player(Actor):
    def __init__(
        self,
        xpos,
        ypos,
        level,
        *,
        playerName=None,
        title=None,
        worshipping=None,
        healCost=10,
        healValue=30,
        collideType={},
        **kwargs
    ):
        # EQUIPPING SHIT MUST CHANGE SELF.ATTACKCOST,
        # SELF.POISE, .POISEREGEN, .POISEDAMAGE, .STAGGERCOST
        # ATTACKCOST, MOVECOST, POISERECOVERY, ETC.
        defaults = {
            "damage": 1,
            "description": "It's you.",
            "display": "@",
            "displayColor": "player",
            "displayPriority": 3,
            "health": 100,
            "moveCost": 10,
            "name": "player",
            "collideType": {"isPlayer": True, "initiatesCombat": True, "blocksWalking": True},
            "canOpenDoors": True,
            "poiseRegen": 1,
            "damage": 15,
        }
        defaults.update(kwargs)
        super().__init__(xpos, ypos, level, **defaults)
        # default name/class
        self.title = "Chosen of Brand"
        self.playerName = "Roderick"
        self.worshipping = worshipping
        self.lastObelisk = None
        self.shardCount = 0
        self.inventory = Inventory(self, self.level)
        self.boonList = []
        self.healCost = healCost
        self.healValue = healValue

    def act(self):
        self.level.draw()
        temp = masterInputParser(self, self.level)
        self.poise = min(self.poise + self.poiseRegen * temp, self.maxPoise)

    def heal(self):
        if self.shardCount > 0 and self.health != self.maxHealth:
            self.health = min(self.maxHealth, self.health + self.healValue)
            self.shardCount = self.shardCount - 1
            self.andWait(self.healCost)
            self.level.output_buffer.add("You heal.")
            return self.healCost
        elif self.shardCount == 0:
            self.andWait(0)
            self.level.output_buffer.add("You don't have any shards!")
            return 0
        elif self.health == self.maxHealth and self.shardCount > 0:
            self.andWait(0)
            self.level.output_buffer.add("You're already at max health.")
            return 0

    def move(self, direction):
        temp = config.collideType.copy()
        config.temp = temp
        for entity in self.level.grid.get(
            self.xpos + config.directions[direction][0], self.ypos + config.directions[direction][1]
        ):
            collideType = entity.collide()
            for key in collideType:
                if collideType[key]:
                    temp[key] = collideType[key]
        if temp["isPortal"]:
            return 0
        if temp["isObelisk"]:
            return self.andWait(0)
        if temp["isDoor"] and not temp["isOpen"]:
            self.openDoor(config.directions[direction][0], config.directions[direction][1])
            return 0
        if not temp["blocksWalking"] and not temp["isEnemy"]:
            tempNum = self.doMove(config.directions[direction][0], config.directions[direction][1])
            self.postMoveDescribe()
            return tempNum
        elif temp["isEnemy"] and temp["initiatesCombat"]:
            return self.doAttack(config.directions[direction][0], config.directions[direction][1])
        else:
            return self.andWait(0)

    def postMoveDescribe(self):
        # generalize this!
        cell = self.level.grid.getCell(self.xpos, self.ypos)
        for content in cell.getContents():
            if isinstance(content, Item):
                if content.name[0] in "aeiouy":
                    self.level.output_buffer.add("You're standing on an " + content.name + ".")
                else:
#.........这里部分代码省略.........
开发者ID:Trial-In-Error,项目名称:raidlike,代码行数:103,代码来源:entity.py


注:本文中的inventory.Inventory.add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。