def __init__(self): # Library initialization. pygame.init() # Window creation. self.window = pygame.display.set_mode( (cons.WINDOW_SIZE, cons.WINDOW_SIZE)) pygame.display.set_caption("Mac Gyver") # Maze setting. self.maze = Maze(cons.MAZE) self.maze.initialize_maze() self.maze.display(self.window) # MacGyver setting. self.mc_gyver = Player(cons.IMAGE_MG) self.mc_gyver.show(self.window) # objects setting. self.ether = Item(cons.IMAGE_ETHER) self.ether.position = self.ether.init_position(self.maze) self.ether.show(self.window) self.needle = Item(cons.IMAGE_NEEDLE) self.needle.position = self.needle.init_position(self.maze) self.needle.show(self.window) self.plastic_pipe = Item(cons.IMAGE_PLASTIC_PIPE) self.plastic_pipe.position = self.plastic_pipe.init_position(self.maze) self.plastic_pipe.show(self.window) self.syringe = Item(cons.IMAGE_SYRINGE) # Screen refresh. pygame.display.flip()
def visual_representation(self): """" This method allow us to display the main screen of the game at the beginning with the maze, its structure,the items at their original position, the guardian and the player """ # now that we exit the lobby we have to create the game structure # background loading self.background = pygame.image.load(BACKGROUND_IMAGE).convert() # lvl generation self.maze = Maze('data/maze_structure.csv') self.maze.creation() # hero generation self.macgyver = Player(HERO_IMAGE, self.maze) # items generation self.needle = Item(self.maze, NEEDLE_SPRITE) self.plastic_tube = Item(self.maze, PLASTIC_TUBE_SPRITE) self.ether = Item(self.maze, ETHER_SPRITE) self.ether.placing() self.needle.placing() self.plastic_tube.placing() # display of the created world self.maze.display(self.window, WALL_IMAGE, GARDIAN_IMAGE) self.ether.display_item(self.window) self.needle.display_item(self.window) self.plastic_tube.display_item(self.window) # Display the inventory counter self.inventory = pygame.image.load(INVENTORY_LIST[0]) self.window.blit(self.inventory, (0, 900))
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)
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 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)
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
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)
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 ), ]
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 ), ]
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)
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)
def _parse(self, raw_html): root = etree.HTML(raw_html) divs = root.xpath( '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[contains(@class,"jsx-3209043686")]' ) temp_timestamp = int(time.time() / 86400) * 86400 for div in divs: item = Item() abstract = "".join( div.xpath(".//span[contains(@class,'jsx-3209043686')]/text()")) # print abstract if not abstract: print 'no abstract' continue title, abstract = my_utils.split_title_content(abstract) item.set('abstract', abstract) item.set('title', title) item.set('timestamp', time.time()) roll_str = "".join(div.xpath(".//a//@href")).strip() roll_id = roll_str.split('/')[-1] nid = roll_id.split('&')[0] #nid = int('%s%s'%(temp_timestamp,roll_id)) item.set('nid', nid) item.set('url', 'https://www.cls.cn/roll/' + str(nid)) item.set('status', 1) self._add_to_data(item) print 'status', item.get('status')
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
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)
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 ), ]
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)
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
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)
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)
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
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
def register_item(): global id_count # Here you are importing the global variable into the function scope print("\n\n\n") print_header('Register new item') title = input('Please type the title: ') category = input('Please type the category: ') price = float(input('Please type the price: ')) stock = int(input('Please type the number of stock: ')) # Validations new_item = Item() new_item.id = id_count new_item.title = title new_item.category = category new_item.price = price new_item.stock = stock id_count += 1 items.append(new_item) log_line = get_time().ljust(11) + "| Register Item".ljust(23) + "| " + str( id_count) logs.append(log_line) save_logs() print('Item created')
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
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
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
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 ]
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))
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
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
def aparicion_safe(self): if self.started: if f.prob_uniforme(1/30): if len(self.cuevas_list) < 4: item = Item(self, 2, image_safe_zone, "safe_zone") self.cuevas_list.append(item) self.jugador.items.append(item) self.cuevas_list[-1].start(1000)