コード例 #1
0
ファイル: characters.py プロジェクト: saluk/erik-errand-boy
 def init(self):
     self.hotspot = [16,32]
     self.facing = [-1,0]
     self.next_frame = 10
     self.animdelay = 5
     self.frame = 0
     self.anim = None
     self.animating = False
     self.walk_speed = 2
     self.vector = [0,0]
     
     self.radius = 14   #collision radius around hotspot
     
     self.last_hit = None
     
     self.following = None
     self.following_points = []
     
     self.last_random_point = None
     self.next_random_point = 0
     
     self.items = []
     names = Item.names[:]
     for i in range(random.randint(1,4)):
         name = random.choice(names)
         names.remove(name)
         item = Item()
         item.name = name
         self.items.append(item)
     
     self.menu = None
     self.texter = None
     
     self.pickpocketing = None
コード例 #2
0
    def gen_items(self,special,item = None):
        #print("What")
        image_files = glob.glob('items/*.PNG')
        if not special:
            num_items = random.randrange(2,3)
        else:
            num_items = 1
            image_files = glob.glob(item)

        while num_items:
            if not special:
                rand_x_pos = random.randrange(0,self.screen[0])
                rand_y_pos = random.randrange(0,self.screen[1])
            else:
                rand_x_pos = 100
                rand_y_pos = 300
            #print(rand_x_pos,rand_y_pos)
            new_item = Item(rand_x_pos,rand_y_pos,image_files,self.all_sprite)
            colid_test = pygame.sprite.spritecollide(new_item,
                                                     self.colids,
                                                     False)
            if colid_test:
                continue
            else:
                new_item.group_add(self.all_sprite)
                self.items.add(new_item)
                self.all_sprite.change_layer(new_item,3)
                num_items -= 1
コード例 #3
0
ファイル: enemy.py プロジェクト: direin13/MegamanPygame
   def check_pshooter_contact(self, reflect=False, drop_item=True, randint_drop_offset=0):
      collision = False
      pshooter_collisions = self.check_collision_lst(p_shooter.P_shooter.all_p_lst, universal_var.hitbox, universal_var.hitbox, quota=1)

      if pshooter_collisions.is_empty() != True and self.is_alive():
         collision = True
         p = pshooter_collisions.pop()
         if p.reflected == False and reflect == False:
            self.reduce_hp(p.damage_points)
            p.is_active = False
            p.launched = False
            play_sound('impact_p', universal_var.megaman_sounds, channel=2, volume=universal_var.sfx_volume - 0.2)
            if self.is_alive() and self.all_timers.is_finished('no_display'):
                  self.all_timers.replenish_timer('no_display')
            elif drop_item == True and self.is_alive() == False:
               Item.drop_item(self.x+self.width//2, self.y+self.height//2, randint_drop_offset)


         elif p.reflected == False:
            if p.x < self.x:
               projectile.Projectile.set(p, p.x, p.y, vel=90, angle=130)
            else:
               projectile.Projectile.set(p, p.x, p.y, vel=90, angle=70)
            p.reflected = True
            play_sound('p_reflected', universal_var.megaman_sounds, channel=1, volume=universal_var.sfx_volume + 0.1)

      return collision
コード例 #4
0
    def gen_items(self, special, item=None):
        #print("What")
        image_files = glob.glob('items/*.PNG')
        if not special:
            num_items = random.randrange(2, 3)
        else:
            num_items = 1
            image_files = glob.glob(item)

        while num_items:
            if not special:
                rand_x_pos = random.randrange(0, self.screen[0])
                rand_y_pos = random.randrange(0, self.screen[1])
            else:
                rand_x_pos = 100
                rand_y_pos = 300
            #print(rand_x_pos,rand_y_pos)
            new_item = Item(rand_x_pos, rand_y_pos, image_files,
                            self.all_sprite)
            colid_test = pygame.sprite.spritecollide(new_item, self.colids,
                                                     False)
            if colid_test:
                continue
            else:
                new_item.group_add(self.all_sprite)
                self.items.add(new_item)
                self.all_sprite.change_layer(new_item, 3)
                num_items -= 1
コード例 #5
0
class LoadingDock(Actor):
    """Accepts packaged goods for delivery to customers."""
    def __init__(self, game, grid_x, grid_y, item_type, loading_time, *args,
                 **kwargs):
        self.grid_x = grid_x
        self.grid_y = grid_y
        self.name = "loading_dock"
        self.game = game
        image_name = 'machines/loading_dock'
        super().__init__(image_name, *args, **kwargs)
        self.x, self.y = game.convert_from_grid(grid_x, grid_y)
        self.item_type = item_type
        self.loading_time = loading_time
        self.next_load = loading_time
        self.number_loaded = 0

        # icon
        thing = self.item_type
        new_scale = data.items[thing]['scale'] * 0.5
        new_anchor = data.items[thing]['anchor']
        new_anchor = (new_anchor[0] * 0.5, new_anchor[1] * 0.5)
        self.icon = Item(thing,
                         anchor=new_anchor,
                         scale=new_scale,
                         from_direction=1)
        self.icon.pos = (self.x + 25, self.y - 45)

    def __str__(self):
        return "<Loading Dock, position: {}, item_type: {}>".format(
            self.pos, self.item_type)

    __repr__ = __str__

    def draw(self):
        super().draw()
        #self.game.point(self.pos, (255,255,0))
        self.icon.draw()
        self.game.text(str(self.number_loaded), (self.x + 5, self.y - 60),
                       fontname="kenney space",
                       fontsize=13)

    def update(self, dt):
        self.next_load -= dt
        #print("Next load in", self.next_load)
        if self.next_load <= 0:
            self.next_load = 0

    def receive_item_push(self, item, from_direction):
        """Receive an item from another machine, or return False."""
        #print(item.name, item, self.next_load)
        if item.name == self.item_type and self.next_load <= 0:
            self.number_loaded += 1
            self.next_load = self.loading_time
            self.game.products_required[self.item_type] -= 1
            print("{} loaded a {} - {} more to go".format(
                self, item.name, self.game.products_required[item.name]))
            return True
        else:
            return False
コード例 #6
0
ファイル: enemy.py プロジェクト: LiDucky/october_game
 def drop_stuff(self, all_items):  # Drop on defeat
     random_num = random.randrange(1, 100)
     if 50 < random_num < 76:  # 25 % chance to drop coin
         item_drop = Item(self.x, self.y, "coin")
         all_items.append(item_drop)
     elif 75 < random_num < 101:  # 25 % chance to drop health
         item_drop = Item(self.x, self.y, "health")
         all_items.append(item_drop)
コード例 #7
0
ファイル: test.py プロジェクト: ArseAssassin/PyF2
class test_xml(unittest.TestCase):
	def setUp(self):
		self.item = Item()
		
		xml = "<Item />"
		node = minidom.parseString(xml).firstChild
		
		self.item.initXML(node)
コード例 #8
0
    def __init__(self):
        """
        PyBreak, a clone of Breakout.
        :return:
        """

        pygame.init()

        # game settings

        self.display = pygame.display.Info()

        self.window_width = 640
        self.window_height = 640

        # border helper
        self.window_border_top = 0
        self.window_border_left = 0
        self.window_border_right = self.window_width
        self.window_border_bottom = self.window_height

        self.grid_size = 40
        self.grid_x = self.window_width / self.grid_size
        self.grid_y = self.window_height / self.grid_size

        self.fps = 60

        self.screen = pygame.display.set_mode((self.window_width, self.window_height))
        self.caption = pygame.display.set_caption("PyBreak - @edkotkas")

        # paddle settings
        self.paddle = Item()

        self.paddle_width = 9

        # change the single number up to half of the paddle width
        self.paddle_divert_range = self.grid_x * 3

        self.paddle.size(self.grid_x * self.paddle_width, self.grid_y)
        self.paddle.velocity(15)
        self.paddle.position(self.window_width/2 - self.paddle.size()[0]/2, self.grid_y * 34)
        self.paddle.colour((150, 75, 25))

        # ball settings
        self.ball = Item()
        self.ball.size(self.grid_x, self.grid_y)
        self.ball.velocity(4)
        self.ball.position(
            self.paddle.position()[0] + self.paddle.size()[0]/2 - self.ball.size()[0]/2,
            self.paddle.top - self.ball.size()[0]
        )
        self.ball.colour((255, 0, 100))

        # level settings
        self.level = Level()

        # text box
        self.text_box = TextBox
コード例 #9
0
ファイル: actor.py プロジェクト: jiiieff/pyf
	def __init__(self):
		Item.__init__(self)
		self.pronouns = {}
		
		self.state = states.Running(self)
		'''State to handle any input for this actor.'''
		
		self.output = None
		'''Output object last associated with this actor.'''
コード例 #10
0
    def test_eq_true(self):

        itema = Item(name='itema',
                     item_type=ItemType.CRITICAL,
                     narration='Its a beautiful day in the neighborhood')
        itema2 = Item(name='itema',
                      item_type=ItemType.CRITICAL,
                      narration='Its a beautiful day in the neighborhood')
        self.assertTrue(itema == itema2)
コード例 #11
0
ファイル: actor.py プロジェクト: tomviner/text-game
    def __init__(self):
        Item.__init__(self)
        self.pronouns = {}

        self.state = states.Running(self)
        '''State to handle any input for this actor.'''

        self.output = None
        '''Output object last associated with this actor.'''
コード例 #12
0
ファイル: test.py プロジェクト: ArseAssassin/PyF2
	def setUp(self):
		def f(event):
			self.moveHandler.l.append(1)
			
		self.moveHandler = Mock(side_effect=f)
		self.moveHandler.l = []
		
		self.item = Item()
		self.item.noun = "item"
		self.destination = Item()
		self.destination.noun = "destination"
コード例 #13
0
 def test_update_quality_increases_quality_backstage_tickets(self):
     items = [
         Item("Backstage passes to a TAFKAL80ETC concert", 10, 10),
         Item("Backstage passes to a TAFKAL80ETC concert", 4, 10),
         Item("Backstage passes to a TAFKAL80ETC concert", 0, 10)
     ]
     gilded_rose = GildedRose(items)
     gilded_rose.update_quality()
     self.assertEqual(12, items[0].quality)
     self.assertEqual(13, items[1].quality)
     self.assertEqual(0, items[2].quality)
コード例 #14
0
def enemy_generator(pLevel): #takes enemys from the enemy file and gives them stats
	enemy_name = open(r"enemy_names.py")
	random_name = enemy_name.readlines()
	enemy_name.close()
	name_roll = random.randint(0, 4)
	name = random_name[name_roll].rstrip()
	if name == "crawling claw":
		archetype = "tiny evil undead"
		attack = random.randint(1, 4)
		loot = Item("nothing", 0, None, 0, None, 0, 0, 0, "literally nothing.")
		xp_amount = 1
		crit_chance = 50
		hit_rate = 1
		health = 15 * pLevel
		description = "The severed hands of a past murderer animated via dark magic. Due to the fact that they require very little skill to create and are bound completly to the will of thier their creator, they are commonly used by fledgling necromancers."
	elif name == "lemure":
		archetype = "medium evil devil"
		attack = random.randint(1, 4)
		loot = Item("lemure fat", 0, None, 0, None, 2, 0, 0, "Fat from a lemure. Can be used to make a bad healing potion.")
		xp_amount = 2
		crit_chance = 50
		hit_rate = 1
		health = 25 * pLevel
		description = "A devil in the form of a molten, stinking blob of flesh. They are among the weakest devils in existance, and only their only abilty a slow, weak regeneration ability. Due to the fact that they are almost completly mindless and cannot make decisions for themselves, lemures are often exploited as shock troops or slave labor by summoners or other devils. They can also be harvested for their fat, which can be used to make a weak healing potion."
	elif name == "goblin skeleton":
		archetype = "small evil undead humaniod"
		attack = random.randint(1, 6)
		loot = Item("nothing", 0, None, 0, None, 0, 0, 0, "literally nothing.")
		xp_amount = 2
		crit_chance = 50
		hit_rate = 1
		health = 20 * pLevel
		description = "The reanimated bones of a goblin. The same dark magic that infuses its bones and binds joints together also gives the goblins rudimentery intelligence and decision making skills, alhough these are mainly reactionary behaviors in battle. Though dead, goblin skeletons retain their malicious nature, and have been known to turn on weaker masters."
	elif name == "homunculus":
		archetype = "tiny evil construct"
		attack = random.randint(1, 6)
		loot = Item("nothing", 0, None, 0, None, 0, 0, 0, "literally nothing.")
		xp_amount = 1
		crit_chance = 2
		hit_rate = 1
		health = 25 * pLevel
		description = "A tiny humaniod doll made of a mixture of clay, ash, mandrake root, and blood. Ordered by it's creator to complete a task, the homunculus will not stop trying untill it completes it's goal. It seems this one has been charged with a fire spell..."
	elif name == "grey ooze":
		archetype = "small mindless slime"
		attack = random.randint(3, 9)
		loot = Item("nothing", 0, None, 0, None, 0, 0, 0, "literally nothing.")
		xp_amount = 3
		crit_chance = 15
		hit_rate = 1
		health = 20 * pLevel
		description = "Stone turned liquid and by chaos magic. Thriving in darkness and attracted to movement and warmth, reckless adventurers often fall to its acidic attacks. It's body can dissove most organtic materials with relavitive ease. I wonder if that can be used for something..."

	enemy = Enemy(name, health, archetype, attack, loot, xp_amount, crit_chance, hit_rate, description) #spell/attack list out
	return enemy
コード例 #15
0
    def __init__(self):
        super().__init__("bull", "Land")
        self.exits = [["garden_right"]]
        self.items = [Item("bull", "Bull",
                           onCheck=onBullCheck
                           ),
                      Item("ladder", "Ladder",
                           description="Ladder which will reach heavens. If there isn't of course a bull sleeping on it",
                           onpick=onLadderPick,
                           onUse=onLadderUse

                           ),
                     ]
コード例 #16
0
ファイル: tiles.py プロジェクト: saluk/erik-errand-boy
 def init_properties(self):
     if hasattr(self,"chest"):
         self.items = []
         if not self.chest:
             names = Item.names[:]
             random.sort(names)
             names = names[:4]
         else:
             names = self.chest.split(",")
         for name in names:
             item = Item()
             item.name = name
             self.items.append(item)
コード例 #17
0
    def test_legendary_item(self):
        items_input = [
            Item(name="Sulfuras, Hand of Ragnaros", sell_in=10, quality=80),
            Item(name="Sulfuras, Hand of Ragnaros", sell_in=-10, quality=80),
        ]

        items_expected = [
            Item(name="Sulfuras, Hand of Ragnaros", sell_in=10, quality=80),
            Item(name="Sulfuras, Hand of Ragnaros", sell_in=-10, quality=80),
        ]

        gilded_rose = GildedRose(items_input)
        gilded_rose.update_quality()
        self._assert_item_lists_equality(gilded_rose.inventory, items_expected)
コード例 #18
0
ファイル: actor.py プロジェクト: tomviner/text-game
    def handlePrivate(self, sentence, output):
        Item.handlePrivate(self, sentence, output)
        self.handleMove(sentence, output)

        if sentence == self.LOOK:
            self.lookAround(output)
        elif sentence == 'save':
            self.game.pickle()
            self.write(output, 'saved')
        elif sentence == "restore":
            self.game.unpickle()
            self.write(output, 'loaded')
        elif sentence == 'score':
            self.score(output)
コード例 #19
0
ファイル: actor.py プロジェクト: jiiieff/pyf
	def handlePrivate(self, sentence, output):
		Item.handlePrivate(self,sentence,output)
		self.handleMove(sentence, output)
		
		if sentence == self.LOOK:
			self.lookAround(output)
		elif sentence == 'save':
			self.game.pickle()
			self.write(output, 'saved')
		elif sentence == "restore":
			self.game.unpickle()
			self.write(output, 'loaded')
		elif sentence == 'score':
			self.score(output)
コード例 #20
0
 def __init__(self):
     super().__init__("workshop", "In front of the Workshop", otherName="Workshop")
     self.exits = [["bicycle"], ["garden_left"],["inside_workshop","To Workshop",0]]
     self.items = [Item("work_door", "Door",
                        description="The key is required to unlock it",
                        onUse=onDoorUse
                        ),
                   Item("work_window", "Window",
                        onCheck=onWinCheck
                        ),
                   Item("trapdoor", "Attic door",
                        onUse=onTrapdoorUse,
                        onCheck=onTrapCheck
                        ), ]
コード例 #21
0
ファイル: player.py プロジェクト: moroma/DalekRL
    def __init__(self, pos=None):
        Mappable.__init__(self, pos, '@', libtcod.white)
        StatusEffect.__init__(self)
        TurnTaker.__init__(self, 1)
        HasInventory.__init__(
            self, 3,
            (SlotItem.HEAD_SLOT, SlotItem.BODY_SLOT, SlotItem.FEET_SLOT))
        LightSource.__init__(self, 2, 0.1)
        self.items = [None, None, None]
        self.slot_items = {
            SlotItem.HEAD_SLOT: None,
            SlotItem.BODY_SLOT: None,
            SlotItem.FEET_SLOT: None,
        }
        self.turns = 0
        self.evidence = []
        self.levels_seen = 1

        # init items (must be done this way to invoke any pickup triggers)
        #  - inv items
        self.pickup(Item.random(None, self, 2, 1.5))
        self.pickup(Item.random(None, self, 1))
        #  - slot items
        self.pickup(NightVisionGoggles(self))
        self.pickup(NinjaSuit(self))
        self.pickup(RunningShoes(self))

        self.KEYMAP = {
            'k': self.move_n,
            'j': self.move_s,
            'h': self.move_w,
            'l': self.move_e,
            'y': self.move_nw,
            'u': self.move_ne,
            'b': self.move_sw,
            'n': self.move_se,
            '.': self.do_nothing,
            '1': self.use_item1,
            '2': self.use_item2,
            '3': self.use_item3,
            '4': self.use_head,
            '5': self.use_body,
            '6': self.use_feet,
            'Q': sys.exit,
            'R': self.reset_game,
            ' ': self.interact,
            'd': self.drop,
            'L': self.debug_lighting,
        }
コード例 #22
0
def browse_catalog():
    from db_manager import ItemsDbManager
    from db_manager import ItemTypesDbManager
    from items import Item
    from tipos_item import ItemType

    catalog = {}

    item_db = ItemsDbManager()
    item_db.connectToDB()

    for id, tipo_item, descripcion, valor_unidad in item_db.read_db().fetchall(
    ):
        item_type_db = ItemTypesDbManager()
        item_type_db.connectToDB()

        item_type = ItemType(str(item_type_db.read_db(int(tipo_item))))

        item_type_db.closeConnectionToDB()

        item = Item(int(id), item_type.nombre, descripcion, valor_unidad)
        catalog[int(id)] = item

    for product in catalog:
        print(catalog[product].codigo, catalog[product].tipo,
              catalog[product].descripcion, catalog[product].valor)

    return catalog
コード例 #23
0
ファイル: maze.py プロジェクト: Melissendra/MacGyverProject
 def add_items(self, symbols):
     """ addition randomly of items """
     available_symbols = symbols
     items_pos = random.sample(self.free_place(), 3)
     self.items = {}
     for pos, symbol in zip(items_pos, available_symbols):
         self.items[pos] = Item(pos, symbol)
コード例 #24
0
 def test_update_quality_v1_deducts_more_quality_of_degradable_item_when_sell_date_is_reached(
         self):
     items = [Item("foo", 0, 4)]
     gilded_rose_v1 = GildedRose(items)
     gilded_rose_v1.update_quality()
     self.assertEqual(2, items[0].quality)
     self.assertEqual(-1, items[0].sell_in)
コード例 #25
0
 def __init__(self):
     super().__init__("living_room", "Living Room")
     self.exits = [["kitchen"], ["hall"], ["fisherman", 0]]
     self.items = [Item("picture_item", "Picture",
                        description="My photo when I was younger and on a fishing trip",
                        onCheck=onPictureCheck
                        ), ]
コード例 #26
0
ファイル: test.py プロジェクト: ArseAssassin/PyF2
	def setUp(self):
		self.item = Item()
		
		xml = "<Item />"
		node = minidom.parseString(xml).firstChild
		
		self.item.initXML(node)
コード例 #27
0
ファイル: maze.py プロジェクト: dducluzeaud/Maze
    def __init__(self):
        self.file = "map.txt"
        self.coord = {}
        """Open and read the file containing the maze. Each char in the file
        will get the coordinates in a dictionnary
        """
        with open(self.file, "r") as map_file:
            id_line = 0
            for line in map_file:
                id_column = 0
                for char in line:
                    self.coord[(id_line, id_column)] = char
                    id_column += 1
                id_line += 1

        self.mac = McGyver()

        # load all images needed to display the maze
        self.wall = self.path_to_img(WALL_PICTURE)
        self.background = self.path_to_img(BACKGROUND_PICTURE)
        self.mcgyver = self.path_to_img_alpha(MCGYVER)
        self.guardian = self.path_to_img_alpha(GUARDIAN)

        self.items = {'E': ETHER, 'N': NEEDLE, 'T': TUBE}

        # Create the object on the maze
        for obj in self.items.keys():
            Item(obj, self)
        # Change the constants in the dictionnary in image
        for char, item in self.items.items():
            item = self.path_to_img_alpha(item)
            self.items[char] = item
コード例 #28
0
ファイル: player.py プロジェクト: SteveMcKoy/text_based_game
    def __init__(self, name, role, health, max_health, mana, max_mana, stamina,
                 max_stamina, crit_chance, max_damage, hit_rate, alignment):
        self.name = name
        self.role = role
        self.health = health
        self.max_health = max_health
        self.mana = mana
        self.max_mana = max_mana
        self.stamina = stamina
        self.max_stamina = max_stamina
        self.max_damage = 20
        self.crit_chance = crit_chance
        self.hit_rate = hit_rate
        self.level = 1
        self.xp = 0
        self.xp_cap = 20  #amount of xp needed before leveling up, should increase upon leveling up
        self.alignment = 0
        self.weapon = "iron shortsword"
        self.offhand = "glowing glove of magic arrows"
        self.head_gear = "tin plate helmet"
        self.body_armour = "tin plate armour"
        self.attacks = ["[|(2)]sword swing", "[*(2)]magic arrow"]
        compendium = ["magic", "mushroom wood"]

        minor_health_potion = Item(
            "minor health potion", 0, None, 0, None, 15, 0, 0,
            "An opaque, rust collored mixture. It has no taste, but has a consistancy disgustingly similar to mucus. It's dull color is a reflection of its poor quality due to cheap materials."
        )
        self.items = [
            minor_health_potion, minor_health_potion, minor_health_potion
        ]
コード例 #29
0
 def update(self):
     self.x = self.startx + self.offx
     self.y = self.starty + self.offy
     if self.destruction < 1:
         if self.terrain == 4:
             self.terrain = 1
             self.item = Item(3)
コード例 #30
0
 def __init__(self, room, name, items=[]):
     self.inventory = []
     for element in items:
         self.inventory.append(Item(element["name"],
                                    element["description"]))
     self.name = name
     self.room = room
コード例 #31
0
    def __init__(self):
        #window setup
        pygame.display.set_caption('Necromonster')
        path = ['rec', 'misc', 'icon.png']
        os.path.sep.join(path)
        pygame.display.set_icon(pygame.image.load(os.path.sep.join(path)))
        #pygame.display.set_icon(pygame.image.load('rec\\misc\\icon.png'))
        self.main_path = os.getcwd()

        # initiate the clock and screen
        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)
        self.DEBUG = 1

        #Init custom game classes
        self.Player = Player(self)
        self.Monsters = Monster(self)
        self.ItemHandler = Item(self)
        self.Invent = Invent(self)
        self.HUD = HUD(self)

        # load fonts, create font list
        self.text_list = []
        self.default_font = pygame.font.SysFont(None, 20)

        # get the map that you are on
        self.blit_list = mapLoader.load('home', self)

        self.Monsters.create('goop', [300, 300], 2, 'neutral')

        while 1:
            self.Loop()
コード例 #32
0
    def update_input_outputs(self):
        """check production - do we have all our inputs?"""
        self.input_machines = [m for m in self.machines if m.item_input]
        self.output_machines = [m for m in self.machines if m.item_output]
        empty_inputs = [m for m in self.input_machines if m.item is None]
        full_outputs = [m for m in self.output_machines if m.item]
        if empty_inputs:
            # don't start production without all the parts
            self.time = self.production_time
            return
        if full_outputs:
            # don't start production without room to put the product
            self.time = self.production_time
            return
        if self.time < 0:
            print("MM", self.name, "is producing...")
            print("  input:", [m.item for m in self.input_machines])
            #print("  output:", [m.item for m in self.output_machines])
            #print("0>", self.machines)
            #print("A>", self.input_machines, self.output_machines)
            #print ("B>", empty_inputs, full_outputs, self.time)

            # can make a thing!
            for m in self.input_machines:
                m.item = None
            for m in self.output_machines:
                m.item = Item(m.item_output,
                              anchor=data.items[m.item_output]['anchor'],
                              scale=data.items[m.item_output]['scale'])
                # the output machine part handles pushing
            print("  output:", [m.item for m in self.output_machines])

            self.time = self.production_time
コード例 #33
0
ファイル: adventure.py プロジェクト: 10755373/adventure.py
 def load_items(self, filename):
     """
     Load items from filename.
     Place them into the inventory of a room.
     """
     # Create playes inventory.
     self.player_inventory = Inventory()
     # Read file
     with open(filename, "r") as f:
         # make list and iterate over each part
         self.items_data = []
         for text in f:
             # split text
             text.split()
             if text.isupper():
                 name = text
             elif text.islower():
                 description = text
             elif text.isdigit():
                 initial_room_id = text
                 # look for same id and place item in that specific room
                 for room in self.room_data:
                     if initial_room_id == room.id:
                         room.inventory.add(
                             Item(name, description, initial_room_id))
コード例 #34
0
def extract_post_page(fatitem_table: bs4.Tag, post_tr: bs4.Tag,
                      post_td: bs4.Tag,
                      comment_tree_table: bs4.Tag) -> Tuple[Item, Dict]:
    """Process HTML for a post page."""

    # extract main post info
    main_item_id = int(post_tr['id'])
    content = extract_post_item_main(post_tr)
    item = Item(main_item_id, content=content)

    # extract subtext info
    _, subtext_info = extract_post_item_subtext(post_td)
    item.content.update(subtext_info)

    # extract text content of the post based on the type
    # of the post (Story, Job, Poll)
    text, pollopts = extract_post_item_text(item.content['type'],
                                            fatitem_table)
    item.content.update({'text': text})
    # add polloptions to the 'parts' member of this item
    if pollopts:
        item.content.update({'parts': pollopts})

    # extract comment tree, if applicable
    comment_tree = None
    if item.content['type'] != ITEM_TYPE[
            'JOB'] and comment_tree_table is not None:
        comment_tree_ds = extract_comment_tree_ds(comment_tree_table)
        comment_tree = extract_comment_tree(main_item_id, comment_tree_ds)
        item.content.update({'kids': comment_tree})

    return item, comment_tree
コード例 #35
0
ファイル: FronEnd.py プロジェクト: jfbahamondes/PYQT5-Game
 def aparicion_coins(self):
     if self.started:
         if f.prob_uniforme(1/30):
             item = Item(self, 18, image_coin, "coin")
             self.coins_list.append(item)
             self.jugador.items.append(item)
             self.coins_list[-1].start(100)
コード例 #36
0
ファイル: FronEnd.py プロジェクト: jfbahamondes/PYQT5-Game
 def aparicion_food(self):
     if self.started:
         if f.prob_uniforme(1/20):
             item = Item(self, 10, image_food[self.tipo_player], "food")
             self.food_list.append(item)
             self.jugador.items.append(item)
             self.food_list[-1].start(100)
コード例 #37
0
ファイル: world.py プロジェクト: jpmarno/TwistedBot
 def on_entity_equipment(self, slot, slotdata, eid):
     entity = self.entities.get(eid, None)
     if entity is None:
         msg = "Equipment for unkown entity %s, slot %s:  %s"
         log.msg((msg % eid, slot, Item(slotdata)))
         return
     entity.equipment[slot] = Item.from_slotdata(slotdata)
コード例 #38
0
def extract_news_page(t: bs4.Tag) -> Tuple[Dict, Dict]:
    """Process HTML for a news page."""
    items = OrderedDict()
    ranks = dict()

    for child in t.children:
        if child == '\n' or bool(child.contents) is False:
            continue
        # <tr> tags with class 'athing' are posts
        if child.has_attr('class') and child['class'][0] == 'athing':
            # post title with story URL, rank, and site string
            item_id = int(child['id'])
            content = extract_post_item_main(child)
            ranks[item_id] = extract_rank(child)
            items[item_id] = Item(item_id, content=content)
        else:
            # most of the other <tr> tags are subtexts under the post
            subtext_td = child.find('td', attrs={'class': 'subtext'})
            if subtext_td is not None:
                item_id, subtext_info = extract_post_item_subtext(subtext_td)
                # find the appropriate Item and update its content
                i = items[item_id]
                i.content.update(subtext_info)

    return ranks, items
コード例 #39
0
ファイル: manager.py プロジェクト: Lrizika/Intro-Python-II
def create_rooms():
	# Declare all the rooms

	room = {
		'outside': Room(
			"Outside Cave Entrance",
			"North of you, the cave mount beckons"
		),
		'foyer': Room(
			"Foyer",
			"Dim light filters in from the south. Dusty passages run north and east."
		),
		'overlook': Room(
			"Grand Overlook",
			"A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."
		),
		'narrow': Room(
			"Narrow Passage",
			"The narrow passage bends here from west to north. The smell of gold permeates the air."
		),
		'treasure': Room(
			"Treasure Chamber",
			"You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."
		),
	}

	# Link rooms together

	room['outside'].connect_to(room['foyer'], 'n')
	room['foyer'].connect_to(room['overlook'], 'n')
	room['foyer'].connect_to(room['narrow'], 'e')
	room['narrow'].connect_to(room['treasure'], 'n')

	room['foyer'].add_items(
		item=Item('rock', 'A fist-sized rock. Could be used as a weapon in a pinch.'),
		count=3,
	)
	room['outside'].add_items(
		item=Item('stick', 'A fairly thin branch. Not much use on its own.'),
		count=8,
	)
	room['treasure'].add_items(
		item=Item('coin', 'The scattered remnants of a once-vast hoard.'),
		count=41,
	)

	return room
コード例 #40
0
ファイル: player.py プロジェクト: frogbotherer/DalekRL
    def __init__(self,pos=None):
        Mappable.__init__(self,pos,'@',libtcod.white)
        StatusEffect.__init__(self)
        TurnTaker.__init__(self,1)
        HasInventory.__init__(self,3,(SlotItem.HEAD_SLOT,SlotItem.BODY_SLOT,SlotItem.FEET_SLOT))
        LightSource.__init__(self,2,0.1)
        self.items = [None,None,None]
        self.slot_items = {
            SlotItem.HEAD_SLOT: None,
            SlotItem.BODY_SLOT: None,
            SlotItem.FEET_SLOT: None,
            }
        self.turns = 0
        self.evidence = []
        self.levels_seen = 1
        
        # init items (must be done this way to invoke any pickup triggers)
        #  - inv items
        self.pickup(Item.random(None,self,2,1.5))
        self.pickup(Item.random(None,self,1))
        #  - slot items
        self.pickup(NightVisionGoggles(self))
        self.pickup(NinjaSuit(self))
        self.pickup(RunningShoes(self))

        self.KEYMAP = {
            'k': self.move_n,
            'j': self.move_s,
            'h': self.move_w,
            'l': self.move_e,
            'y': self.move_nw,
            'u': self.move_ne,
            'b': self.move_sw,
            'n': self.move_se,
            '.': self.do_nothing,
            '1': self.use_item1,
            '2': self.use_item2,
            '3': self.use_item3,
            '4': self.use_head,
            '5': self.use_body,
            '6': self.use_feet,
            'Q': sys.exit,
            'R': self.reset_game,
            ' ': self.interact,
            'd': self.drop,
            'L': self.debug_lighting,
            }
コード例 #41
0
ファイル: bbackpack.py プロジェクト: ptylczynski/plecaki
    def shuffle(self):
        items = list()
        for i in range(self.amount):
            items.append(Item(random.randint(0, self.max_weight),
                              random.randint(0, self.max_weight)
            ))

        return items
コード例 #42
0
ファイル: inventory.py プロジェクト: eode/TwistedBot
 def window_slot(self, slot, wid, slotdata):
     try:
         window = self[wid]
     except KeyError:
         msg = "Could not find window for window ID " + str(wid)
         log.msg("ERROR: " + msg)
         return
     window[slot] = Item.from_slotdata(slotdata)
     log.msg("Updated %s slot %s with %s" % (window.name, slot,
                                             str(window[slot])))
コード例 #43
0
ファイル: inventory.py プロジェクト: eode/TwistedBot
 def set_window_items(self, length, slotdata, window_id):
     try:
         window = self[window_id]
     except KeyError:
         msg = "Could not find window for window ID " + str(window_id)
         log.msg("ERROR: " + msg)
         return
     assert len(window) == length == len(slotdata)
     window[:] = [Item.from_slotdata(slot) for slot in slotdata]
     log.msg("set_window_items: " + str(window))
コード例 #44
0
ファイル: potions.py プロジェクト: eeue56/realrpg
 def __init__(self, name, strength):
     Item.__init__(self, name, 1)
     self.strength = strength
コード例 #45
0
ファイル: test.py プロジェクト: ArseAssassin/PyF2
class test_Item(unittest.TestCase):
	def setUp(self):
		def f(event):
			self.moveHandler.l.append(1)
			
		self.moveHandler = Mock(side_effect=f)
		self.moveHandler.l = []
		
		self.item = Item()
		self.item.noun = "item"
		self.destination = Item()
		self.destination.noun = "destination"
		
	def test_movement(self):
		self.item.addEventListener(game_events.MOVE, self.moveHandler)
		self.destination.addEventListener(game_events.ACQUIRE, self.moveHandler)
		
		self.item.move(self.destination)
		self.assertRaises(MoveError, lambda: self.destination.move(self.item))
		
		self.assertEqual(self.moveHandler.l, [1, 1])
		self.assertEqual(self.item.owner, self.destination)
		self.assertEqual(self.destination.inventory, [self.item])
		
		self.item.move(None)

		self.assertEqual(self.moveHandler.l, [1, 1, 1])
		self.assertEqual(self.item.owner, None)
		self.assertEqual(self.destination.inventory, [])

	def test_childAccess(self):
		self.item.move(self.destination)
		self.assertTrue(self.destination.has(self.item))
		self.assertEqual(self.destination.get(self.item), self.item)
		self.assertEqual(self.destination.get(self.item), "item")
		
	def test_comparison(self):
		self.assertEqual(self.item, "item")
		self.assertEqual(self.destination, "destination")
		
	def getMockProp(self):
		mockProp = Mock(spec=Property)
		mockProp._handle = Mock()
		return mockProp
		
	def test_props(self):
		self.item.addProp(self.getMockProp())
		self.item.addProp(self.getMockProp())
		self.item.addProp(self.getMockProp())
		self.assertEqual(len(self.item.props), 3)
		
		i, o = Mock(), Mock()
		
		self.item.owner = Mock()
		self.item._handle(i, o)
		self.item.owner = None
		
		for prop in self.item.props:
			prop._handle.assert_called_once_with(i, o)
			
		self.item.removeProp(self.item.props[0])
		self.assertEqual(len(self.item.props), 2)
		
		while self.item.props:
			self.item.props.pop()
			
	def test_propertyAccess(self):
		self.item.addProp(Property())
		self.assertNotEqual(self.item.props.Property, None)
コード例 #46
0
ファイル: weapons.py プロジェクト: eeue56/realrpg
 def __init__(self, name,  uses, strength):
     Item.__init__(self, name, uses)
     self.strength = strength
コード例 #47
0
class Necro():
    def __init__(self):
        #window setup
        pygame.display.set_caption('Necromonster')
        path = ['rec', 'misc', 'icon.png']
        os.path.sep.join(path)
        pygame.display.set_icon(pygame.image.load(os.path.sep.join(path)))
        #pygame.display.set_icon(pygame.image.load('rec\\misc\\icon.png'))
        self.main_path = os.getcwd()

        # initiate the clock and screen
        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)
        self.DEBUG = 1

        #Init custom game classes
        self.Player = Player(self)
        self.Monsters = Monster(self)
        self.ItemHandler = Item(self)
        self.Invent = Invent(self)
        self.HUD = HUD(self)

        # load fonts, create font list
        self.text_list = []
        self.default_font = pygame.font.SysFont(None, 20)

        # get the map that you are on
        self.blit_list = mapLoader.load('home', self)

        self.Monsters.create('goop', [300, 300], 2, 'neutral')

        while 1:
            self.Loop()

    def Loop(self):
        # main game loop
        self.eventLoop()
        if pygame.time.get_ticks() - self.last_tick > 20:
            self.Tick()
            self.Draw()
        pygame.display.update()

    def eventLoop(self):
        # the main event loop, detects keypresses
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_e:
                    self.Invent.toggleView()
            elif event.type == MOUSEBUTTONDOWN:
                if self.Invent.in_hand:
                    self.Invent.testThrow(pygame.mouse.get_pos())
                if self.Invent.shown:
                    self.Invent.inventClick(pygame.mouse.get_pos())

    def Tick(self):
        # updates to player location and animation frame
        self.keys_pressed = pygame.key.get_pressed()
        self.clock.tick()
        self.Player.update()
        self.Monsters.update()
        self.ItemHandler.update()
        self.Invent.update()
        for index, text in enumerate(self.text_list):
            if text[2] < time():
                self.text_list.pop(index)

        self.last_tick = pygame.time.get_ticks()

    def off(self, coords):
        newx = coords[0] - self.Player.player_r.x + 450
        newy = coords[1] - self.Player.player_r.y + 325
        return [newx, newy]

    def Draw(self):
        #Responsible for calling all functions that draw to the screen
        tile_width = self.tile[1][0]
        tile_height = self.tile[1][1]
        tile_extrax = self.Player.player_r.x % tile_width
        tile_extray = self.Player.player_r.y % tile_height
        y = 0

        for i in xrange(self.screen_res[1] / tile_height + 3):
            for i in xrange(self.screen_res[0] / tile_width + 3):
                self.screen.blit(self.tile[0], [i * tile_width - tile_width - tile_extrax, y - tile_height - tile_extray])
            y += self.tile[1][1]
        for surf in self.blit_list:
            if 'player' in surf:
                self.Player.blitPlayer()
                self.Monsters.blitMonsters()
            else:
                self.screen.blit(surf[0], self.off(surf[1]))
        for text in self.text_list:
            self.screen.blit(text[0], text[1])
        self.ItemHandler.blitItems()
        if self.Invent.shown:
            self.Invent.draw()
        if self.DEBUG:
            self.screen.blit(self.default_font.render(str(round(self.clock.get_fps())), True, (255, 255, 255)), [0, 0])
            self.screen.blit(self.default_font.render(str('%s, %s' % (self.Player.player_r.x, self.Player.player_r.y)), True, (255, 255, 255)), [0, 12])
            self.screen.blit(self.default_font.render(str(pygame.mouse.get_pos()), True, (255, 255, 255)), [0, 24])
        self.HUD.blitHUD()
コード例 #48
0
ファイル: spider.py プロジェクト: lvshuchengyin/mycode
 def parse(self,response):
     '''分析网页内容'''
     response.url = response.url.strip()
     ext=funcs.get_url_ext(response.url)                     #获取文件扩展名
     #wiki 的css页面为http://bits.wikimedia.org开头的php,不分析
     #if (ext not in settings.S_img_ext) and (ext not in ('css','js')) and not response.url.startswith('http://bits.wikimedia.org'):
     if funcs.is_need_modify(response.url):
         data,coding=funcs.decode_data(response.body)
         soup=BeautifulSoup(str(data),'lxml',from_encoding='utf-8')
         soup,urls,css_urls,js_urls,img_urls=self.get_link(soup)
         all_urls=css_urls+js_urls+urls+img_urls
         
         for url in all_urls:
             vurl=funcs.valid_url(response.url,url).strip()      #判断是否有效链接
             if vurl != '':
                 #下载简体中文的网页
                 vurl = funcs.translate_simplify( vurl )
                 _url=funcs.decode_data(vurl)[0].encode('utf-8')
                 print _url
                 if _url:
                     vurl=_url
                 yield Request(vurl)
                 
         item=Item()
         item.url=response.url
         item.soup=soup
         item.content=str(soup)                      #使用修改后的数据
         item.coding=coding                          #内容编码
         item.file_length=int(len(response.body))    #原始文件大小
         yield item
     else:
         item=Item()
         item.url=response.url
         item.soup=None
         item.content=response.body                  #使用修改后的数据
         item.coding=''                              #内容编码
         item.file_length=int(len(response.body))    #原始文件大小
         yield item
コード例 #49
0
ファイル: game.py プロジェクト: edkotkas/PyBreak
class PyBreak:

    def __init__(self):
        """
        PyBreak, a clone of Breakout.
        :return:
        """

        pygame.init()

        # game settings

        self.display = pygame.display.Info()

        self.window_width = 640
        self.window_height = 640

        # border helper
        self.window_border_top = 0
        self.window_border_left = 0
        self.window_border_right = self.window_width
        self.window_border_bottom = self.window_height

        self.grid_size = 40
        self.grid_x = self.window_width / self.grid_size
        self.grid_y = self.window_height / self.grid_size

        self.fps = 60

        self.screen = pygame.display.set_mode((self.window_width, self.window_height))
        self.caption = pygame.display.set_caption("PyBreak - @edkotkas")

        # paddle settings
        self.paddle = Item()

        self.paddle_width = 9

        # change the single number up to half of the paddle width
        self.paddle_divert_range = self.grid_x * 3

        self.paddle.size(self.grid_x * self.paddle_width, self.grid_y)
        self.paddle.velocity(15)
        self.paddle.position(self.window_width/2 - self.paddle.size()[0]/2, self.grid_y * 34)
        self.paddle.colour((150, 75, 25))

        # ball settings
        self.ball = Item()
        self.ball.size(self.grid_x, self.grid_y)
        self.ball.velocity(4)
        self.ball.position(
            self.paddle.position()[0] + self.paddle.size()[0]/2 - self.ball.size()[0]/2,
            self.paddle.top - self.ball.size()[0]
        )
        self.ball.colour((255, 0, 100))

        # level settings
        self.level = Level()

        # text box
        self.text_box = TextBox

    def main_loop(self):
        """
        Main game loop.
        :return:
        """
        paddle_direction = None
        paddle_move_allowed = True
        ball_direction_y = self.ball.direction.UP
        ball_direction_x = random.choice([self.ball.direction.LEFT, self.ball.direction.RIGHT])

        game_started = False
        score = 0
        level = 1
        deaths = 0

        while True:
            self.screen.fill((10, 10, 10))

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    sys.exit()

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        sys.exit()

                    if event.key == pygame.K_RIGHT:
                        paddle_direction = self.paddle.direction.RIGHT
                    if event.key == pygame.K_LEFT:
                        paddle_direction = self.paddle.direction.LEFT
                    if event.key == pygame.K_SPACE and game_started is False:
                        game_started = True

                if event.type == pygame.KEYUP:
                    paddle_direction = None

            pygame.time.Clock().tick(self.fps)

            if GRID_ENABLED is True:
                for grid_x in range(self.grid_size):
                    for grid_y in range(self.grid_size):
                        pygame.draw.rect(self.screen, (100, ) * 3, (
                            0 + self.grid_x * grid_x, 0 + self.grid_y * grid_y,
                            self.grid_x, self.grid_y
                        ), 1)

            # renders the paddle
            pygame.draw.rect(self.screen, *self.paddle.render())

            # paddle movement control
            if paddle_move_allowed is True:
                self.paddle.move(paddle_direction)

            # paddle boundary detection
            if self.paddle.left > self.window_border_left \
                    and paddle_direction is self.paddle.direction.LEFT \
                    or self.paddle.right < self.window_border_right \
                    and paddle_direction is self.paddle.direction.RIGHT:
                paddle_move_allowed = True
            else:
                paddle_move_allowed = False

            # move the ball with the paddle while game is not on
            if game_started is False:
                    self.ball.position(
                        self.paddle.position()[0] + self.paddle.size()[0]/2 - self.ball.size()[0]/2,
                        self.paddle.top - self.ball.size()[0]
                    )

            # ball movement control
            if game_started is True:
                self.ball.move(ball_direction_y)
                self.ball.move(ball_direction_x)

            # ball/boundary collision control
            # left / right of border
            if self.ball.left <= self.window_border_left:
                ball_direction_x = self.ball.direction.RIGHT
            if self.ball.right >= self.window_border_right:
                ball_direction_x = self.ball.direction.LEFT
            if self.ball.top <= self.window_border_top:
                ball_direction_y = self.ball.direction.DOWN
            # bottom of border
            if self.ball.bottom >= self.window_border_bottom:
                deaths += 1
                game_started = False

            # ball/paddle collision control
            if self.ball.bottom + self.ball.velocity()/2 >= self.paddle.top and self.ball.top < self.paddle.bottom \
                    and ball_direction_y == self.ball.direction.DOWN:

                if self.ball.left >= self.paddle.left and self.ball.right <= self.paddle.right:
                    ball_direction_y = self.ball.direction.opposite(ball_direction_y)

                if self.ball.left >= self.paddle.left \
                        and self.ball.right <= self.paddle.left + self.paddle_divert_range \
                        and ball_direction_x == self.ball.direction.RIGHT \
                        or self.ball.right <= self.paddle.right \
                        and self.ball.left >= self.paddle.right - self.paddle_divert_range \
                        and ball_direction_x == self.ball.direction.LEFT:
                    ball_direction_x = self.ball.direction.opposite(ball_direction_x)

            # ball/block collision control
            for block in self.level.map():

                # go to the next level once map is cleared
                if self.level.cleared():
                    game_started = False

                block_rect = pygame.Rect(block[1])
                if self.ball.top >= block_rect.top \
                        and self.ball.bottom <= block_rect.bottom \
                        and self.ball.left - self.ball.velocity() <= block_rect.right < self.ball.right:
                    ball_direction_x = self.ball.direction.opposite(ball_direction_x)
                    self.level.hit(block)

                    score += 1

                    if score % 4 == 0 and level != 5:
                        level += 1
                        self.ball.velocity(self.ball.velocity() + 2)

                if self.ball.top >= block_rect.top \
                        and self.ball.bottom <= block_rect.bottom \
                        and self.ball.right + self.ball.velocity() >= block_rect.left > self.ball.left:
                    ball_direction_x = self.ball.direction.opposite(ball_direction_x)
                    self.level.hit(block)

                    score += 1

                    if score % 4 == 0 and level != 3:
                        level += 1
                        self.ball.velocity(self.ball.velocity() + 2)

                # bottom of block, top of ball
                if self.ball.right <= block_rect.right \
                        and self.ball.left >= block_rect.left \
                        and self.ball.top - self.ball.velocity() <= block_rect.bottom < self.ball.bottom:
                    ball_direction_y = self.ball.direction.opposite(ball_direction_y)
                    self.level.hit(block)

                    score += 1

                    if score % 4 == 0 and level != 5:
                        level += 1
                        self.ball.velocity(self.ball.velocity() + 2)

                # top of block, bottom of ball
                if self.ball.right <= block_rect.right \
                        and self.ball.left >= block_rect.left \
                        and self.ball.bottom + self.ball.velocity() >= block_rect.top > self.ball.top:
                    ball_direction_y = self.ball.direction.opposite(ball_direction_y)
                    self.level.hit(block)

                    score += 1

                    if score % 4 == 0 and level != 5:
                        level += 1
                        self.ball.velocity(self.ball.velocity() + 1)

            # render blocks
            for render_block in self.level.map():
                pygame.draw.rect(self.screen, *render_block)

            # renders the ball
            pygame.draw.rect(self.screen, *self.ball.render())

            # renders the score text
            level_text = self.text_box("Level: " + str(level), 21)
            self.screen.blit(level_text.make(), (self.grid_x * 1, self.grid_y * 38))

            stage_text = self.text_box("Stage: " + str(0), 21)
            self.screen.blit(stage_text.make(), (self.grid_x * 10, self.grid_y * 38))

            score_text = self.text_box("Score: " + str(score), 21)
            self.screen.blit(score_text.make(), (self.grid_x * 20, self.grid_y * 38))

            death_text = self.text_box("Deaths: " + str(deaths), 21)
            self.screen.blit(death_text.make(), (self.grid_x * 30, self.grid_y * 38))

            pygame.display.flip()