def Search(self, frame): frame.withdraw() SFrame = Tk.Toplevel(bg="#000000", bd=5) SFrame.geometry("800x800") SFrame.title("Search") button1 = Tk.Button( SFrame, text="Search by Author", bg='black', fg='white', command=lambda: Inventory.searcha(SFrame, self.root)) button1.place(relx=0.28, rely=0.05, relwidth=0.45, relheight=0.15) button2 = Tk.Button( SFrame, text="Search by Genre", bg='black', fg='white', command=lambda: Inventory.searchg(SFrame, self.root)) button2.place(relx=0.28, rely=0.20, relwidth=0.45, relheight=0.15) button3 = Tk.Button( SFrame, text="Search by Title", bg='black', fg='white', command=lambda: Inventory.searcht(SFrame, self.root)) button3.place(relx=0.28, rely=0.35, relwidth=0.45, relheight=0.15) btn = Tk.Button(SFrame, text="Exit", command=lambda: self.exitbuttonclick(SFrame, frame)) btn.place(relx=0.48, rely=0.58) SFrame.protocol("WM_DELETE_WINDOW", self.root.destroy)
def IRL(self, frame): frame.withdraw() IRLFrame = Tk.Toplevel(bg="#000000", bd=5) IRLFrame.geometry("800x800") IRLFrame.title("Issues/Return/Lost") button1 = Tk.Button( IRLFrame, text="Issue a Book", bg='black', fg='white', command=lambda: Inventory.issueb(IRLFrame, self.root)) button1.place(relx=0.28, rely=0.05, relwidth=0.45, relheight=0.15) button2 = Tk.Button( IRLFrame, text="Return a Book", bg='black', fg='white', command=lambda: Inventory.returnb(IRLFrame, self.root)) button2.place(relx=0.28, rely=0.20, relwidth=0.45, relheight=0.15) button3 = Tk.Button( IRLFrame, text="Report a Lost Book", bg='black', fg='white', command=lambda: Inventory.lostb(IRLFrame, self.root)) button3.place(relx=0.28, rely=0.35, relwidth=0.45, relheight=0.15) btn = Tk.Button(IRLFrame, text="Exit", command=lambda: self.exitbuttonclick(IRLFrame, frame)) btn.place(relx=0.48, rely=0.58) IRLFrame.protocol("WM_DELETE_WINDOW", self.root.destroy)
def fastclone(self, theState): newBoard = None # For speed, preallocate the lists at their eventual size ants1 = [] ants2 = [] cons1 = [None] * len(theState.inventories[PLAYER_ONE].constrs) cons2 = [None] * len(theState.inventories[PLAYER_TWO].constrs) cons3 = [None] * len(theState.inventories[NEUTRAL].constrs) antIndex1 = 0 antIndex2 = 0 conIndex1 = 0 conIndex2 = 0 conIndex3 = 0 # clone all the entries in the inventories # deleted the fillers for the ants for constr in theState.inventories[PLAYER_ONE].constrs: cons1[conIndex1] = constr.clone() conIndex1 += 1 for constr in theState.inventories[PLAYER_TWO].constrs: cons2[conIndex2] = constr.clone() conIndex2 += 1 for constr in theState.inventories[NEUTRAL].constrs: cons3[conIndex3] = constr.clone() conIndex3 += 1 # clone the list of inventory objects food1 = theState.inventories[PLAYER_ONE].foodCount food2 = theState.inventories[PLAYER_TWO].foodCount newInventories = [Inventory(PLAYER_ONE, ants1, cons1, food1), Inventory(PLAYER_TWO, ants2, cons2, food2), Inventory(NEUTRAL, [], cons3, 0)] return GameState(newBoard, newInventories, theState.phase, theState.whoseTurn)
def play(): start_game() while True: Chef.prepare_orders() Inventory.order_low_stock() Inventory.restock() Chef.clear_plates()
def locate(img_file): """locates item in inventory Args: img_file (str): Description Returns: Tuple: Position of the item (x,y), None if not found """ img_name = img_file.split('/')[-1] log.debug('Trying to locate %s in inventory', img_name) items = Imging.locate_with_region( img_file, region=(982, 342, 331, 321), locate_all=True) if len(items) > 1: log.debug('Found multiple instances of the item, organizing to stack them') Inventory.organize_inventory() return Util.center(Imging.locate_with_region(img_file, region=(982, 342, 331, 321), locate_all=False)) if len(items) > 0: pos = Util.center(items[0]) log.debug('Found %s at %s', img_name, str(pos)) return pos else: log.error('Could not locate %s in inventory', img_name) return None
class Gui(pygame.sprite.Sprite): def __init__(self, player): self.player = player self.inventory = Inventory(self.player) self.inventoryToggle = True self.playerImage = pygame.image.load("./assets/pirate_left.png") self.playerMoney = pygame.image.load("./assets/money.png") def update(self, event): pass def draw(self, screen, fontrenderer): if self.inventoryToggle: self.inventory.draw(screen) surface = fontrenderer.render(str(self.inventory.pistol.currentAmmo), False, (0, 0, 0)) health = fontrenderer.render(str(self.player.health), False, (0, 0, 0)) money = fontrenderer.render( str(self.player.gui.inventory.get_money_amount()), False, (0, 0, 0)) screen.blit(surface, (45, 0)) screen.blit(self.playerImage, (SCREEN_WIDTH - 100, 0)) screen.blit(self.playerMoney, (SCREEN_WIDTH - 100, 50)) screen.blit(money, (SCREEN_WIDTH - 50, 50)) screen.blit(health, (SCREEN_WIDTH - 50, 0))
def __init__(self): Player.playerPos = [ Helper.RESOLUTION[0] * 0.5 - Player.playerSurf.get_width() * 0.5, Helper.RESOLUTION[1] * 0.2 - Player.playerSurf.get_height() * 0.5 + 600 ] Player.playerRect.x = Player.playerPos[0] Player.playerRect.y = Player.playerPos[1] Player.moveSpeed = Helper.MOVE_SPEED Player.moveDistance = Helper.MOVE_DISTANCE if Player.playerInstances == 0: Player.playerInstances += 1 else: raise ValueError('Attempted to create another instance of Player') Entity.Entity.__init__(self) self.exp_to_level_up = Helper.EXP_REQUIRED self.exp = 0 Player.max_health = Entity.Entity.defaultHealth * 100 Player.health = Player.max_health Player.healthBar = Entity.HealthBar(self) Player.playerInstance = self Player.Inventory = Inventory.Inventory() Player.Backpack = Inventory.Backpack()
def inventory_added(request,sid): if 'product_id' in request.GET and request.GET['product_id'] and 'qty' in request.GET and request.GET['qty'] and 'cp' in request.GET and request.GET['cp'] and 'sp' in request.GET and request.GET['sp'] and 'minqty' in request.GET and request.GET['minqty']: product_id = request.GET['product_id'] qty = request.GET['qty'] minqty = request.GET['minqty'] sp = request.GET['sp'] cp = request.GET['cp'] if request.GET['ed']: ex = request.GET['ed'] else: ex=None inv = Inventory.objects.filter(store_id=sid,product_id_id=product_id) batchid = random.randint(1,99999) ids = [] for i in inv: ids.append(i.batch_id) while(batchid in ids): batchid = random.randint(1,99999) batch = Inventory(product_id_id=product_id,batch_id=batchid,store_id_id=sid,qty=qty,minimum_qty=minqty,selling_price=sp,cost_price=cp,expiry_date=ex) batch.save() messageadd = 'New inventory has been successfully added' store = Store.objects.get(store_id=sid) batches = Inventory.objects.filter(store_id=sid) context = {'store':store,'messageadd':messageadd,'batches':batches} return render(request,'inventory_control.html',context)
def test_player_creation(s): with s.assertRaises(ValueError): p = Unit.Player('Nome', Inventory.Inventory(), 0, -1, -3, -4, -5, 6, 7, 8) with s.assertRaises(ValueError): p = Unit.Player('Nome', Inventory.Inventory(), 1, 2, 3, 4, 5, 0, 7, -8) with s.assertRaises(ValueError): p = Unit.Player('Nome', Inventory.Inventory(), 1, 2, 3, 4, 5, 6, 8, 8) p = Unit.Player('Nome', Inventory.Inventory(), 1, 2, 3, 4, 5, 6, 7, 8) s.assertEqual(p.name, 'Nome') s.assertEqual(p.max_health, 1) # health tem que ser no máximo max_health s.assertEqual(p.health, 1) s.assertEqual(p.attack, 3) s.assertEqual(p.defense, 4) s.assertEqual(p.agility, 5) s.assertEqual(p.level, 6) s.assertEqual(p.exp, 7) s.assertEqual(p.exp_to_next, 8) s.assertFalse(p.max_health <= 0) s.assertFalse(p.health <= 0) s.assertFalse(p.attack <= 0) s.assertFalse(p.defense <= 0) s.assertFalse(p.agility <= 0) s.assertFalse(p.level <= 0) s.assertFalse(p.exp < 0) s.assertFalse(p.exp_to_next <= 0)
def Display(self, frame): frame.withdraw() DisFrame = Tk.Toplevel(bg="#000000", bd=5) DisFrame.geometry("800x800") DisFrame.title("Display") button1 = Tk.Button( DisFrame, text="Display All Students", bg='black', fg='white', command=lambda: Inventory.displays(DisFrame, self.root)) button1.place(relx=0.28, rely=0.05, relwidth=0.45, relheight=0.15) button2 = Tk.Button( DisFrame, text="Display Students department wise", bg='black', fg='white', command=lambda: Inventory.displaysc(DisFrame, self.root)) button2.place(relx=0.28, rely=0.20, relwidth=0.45, relheight=0.15) button3 = Tk.Button( DisFrame, text="Display Personal Information of Students", bg='black', fg='white', command=lambda: Inventory.memberinfo(DisFrame, self.root)) button3.place(relx=0.28, rely=0.35, relwidth=0.45, relheight=0.15) btn = Tk.Button(DisFrame, text="Exit", command=lambda: self.exitbuttonclick(DisFrame, frame)) btn.place(relx=0.48, rely=0.58) DisFrame.protocol("WM_DELETE_WINDOW", self.root.destroy)
def locate(img_file): """locates item in inventory Args: img_file (str): Description Returns: Tuple: Position of the item (x,y), None if not found """ img_name = img_file.split('/')[-1] log.debug('Trying to locate %s in inventory', img_name) items = Imging.locate_with_region(img_file, region=(982, 342, 331, 321), locate_all=True) if len(items) > 1: log.debug( 'Found multiple instances of the item, organizing to stack them') Inventory.organize_inventory() return Util.center( Imging.locate_with_region(img_file, region=(982, 342, 331, 321), locate_all=False)) if len(items) > 0: pos = Util.center(items[0]) log.debug('Found %s at %s', img_name, str(pos)) return pos else: log.error('Could not locate %s in inventory', img_name) return None
def _get_creature_items(s, c): inventory = Inventory() for i in c.findall('inventory/item'): inventory.put(( i.get('quantity'), i.get('name'), )) return inventory
def _get_player_items(s, p): inventory = Inventory() for i in p.findall('inventory/item'): inventory.put(( i.get('quantity'), i.get('name'), )) return inventory
def test_inventorygetIndexOf(self): inventory = Inventory() pre = Presets() inventory.invCards = [pre.gic("Ether")] # healtpotion2 is in the inventory number zero self.assertEqual(inventory.getIndexOf("Ether"), 0) # hundur is not in the inventory self.assertEqual(inventory.getIndexOf("Hundur"), -1)
def do_generate_inventory_management_for_adventure(should_grind, should_sell): # At this point we're at the victory screen. We need to click the Inventory button on the # left side. This involves a loading screen and can take quite some time, so wait 15 seconds. nox.click_loc((80, 230), 25000) Inventory.manage_inventory(should_grind, should_sell) # Exit back to Orvel map nox.click_button('exit', 3500)
def setUp(self): self.Store = Inventory(store_name) for year in years: for week in weeks: for item in items_upper: self.Store.item_count(item, randint(1, 100), week, year) for week in list(range(1, current_week + 1)): for item in items_upper: self.Store.item_count(item, randint(1, 100), week, current_year)
def checkSScoin(): if Inventory.GetItemCount(4310235) == (SCLib.GetVar("SpiritCoin"+CharName)+30)\ or Inventory.GetItemCount(4310235) == (SCLib.GetVar("SpiritCoin"+CharName)+60): print("You earned daily cap for spirit coin") print("Finished Spirit Savior Daily") RestoreSetting() SCLib.UpdateVar("SpiritDone" + CharName, True) return True else: return False
def __init__(self, sprites, animations, current_sprite, world_i, name): Entity.__init__(self, sprites, animations, world_i, name) self.position = (150, 300) self.current_sprite = current_sprite self.sprite = None self.command = None self.active = False self.inventory = Inventory(self.entity_i) self.add_hero_listeners()
def __init__(self, x, y): super().__init__() self.image = pygame.Surface([32, 32]) self.image.fill((255, 128, 128)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.movex = 0 self.movey = 0 self.inventory = Inventory()
class testInventory(unittest.TestCase) : def setUp (self) : """setup for the tests to run""" self.item1 = Item('mouse') self.item2 = Item('bat', 2, 5.00) self.testInventory = Inventory() def test_addItem (self) : """ tests that an item is added to the inventory correctly """ self.testInventory.addItem(self.item1) self.assertIn(self.item1, self.testInventory._items)
def gen_grindhouse(): # The generated macro assumes you are on the Buy screen, Tier 3 is already selected, and an item is # highlighted. print() items_to_buy = nox.prompt_user_for_int( "How many items should be purchased each cycle?\n" "If you don't have at least this much inventory space the macro will de-sync.\n" "Number of items to purchase: ") print() buy_delay = nox.prompt_user_for_int( "Enter the number of milliseconds between each click while purchasing\n" "items. A lower number will make the macro run faster, but could cause\n" "the macro to get out of sync on slower machines. If the macro doesn't\n" "register clicks properly while buying items, run the generator again\n" "and choose a higher number until you find what works.\n\n" "Milliseconds (Default=325): ", default=325) Common.confirm( properties={ 'Items to buy': items_to_buy, 'Delay': buy_delay }, start_condition='The macro should be started from the forge shop.') # Click on first item in forge shop nox.click_button('forge_first_item', 1500) # Buy 300 items for i in range(0, items_to_buy): nox.click_button('buy', buy_delay) # Exit twice (to Orvel map) nox.click_button('exit', 1500) nox.click_button('exit', 1500) # Open inventory nox.click_button('inventory', 1500) Inventory.grind_or_sell_all(True) # Exit back to Orvel world map nox.click_button('exit', 1500) # Re-enter the shop. Delay set to 2500 here since there's an animated transition # that takes a little extra time nox.click_button('enter_node', 5000) # Click Use Shop button nox.click_button('use_shop', 1500)
def create_inventory(): print('Enter the product number:: ') prod_num = int(input()) print('Enter the product name:: ') prod_name = input() print('Enter the product type [Grocery/Dairy/Cosmetics] ::') prod_type = input() print('Enter the product price ::') price = float(input()) print('Enter the number of products ::') quantity = int(input()) inv.add_product(prod_num=prod_num, prod_name=prod_name, prod_type=prod_type, price=price, quantity=quantity)
def __determineChoice__(self): isBad = True returned = True while (isBad): while (isBad): try: userChoice = int(input(">>>>:")) isBad = False #break loop except: print("Please enter a valid input") #Router if (userChoice == 1): Rec = Recievables(self.server) Rec.start() elif (userChoice == 2): IM = Inventory.InventoryMenu(self.server) IM.start() elif (userChoice == 3): CustM = CustomerManagement(self.server) CustM.start() elif (userChoice == 4): EmpM = EmployeeManagement(self.server) EmpM.start() elif (userChoice == 5): PC = PartsCounter.PartsCounterMenu(self.server) PC.start() elif (userChoice == 0): returned = False #exit out of current menu else: print("Please enter valid menu choice\n") isBad = True #needs to ask again return returned
def GetCoin(npc): print("Receiving coins from", npc) retry=0 while SCLib.GetVar("DDCoin") == Inventory.GetItemCount(4310227) and retry<3: Character.TalkToNpc(npc) time.sleep(3) retry+=1
def start(self): '''Start a game''' #create some weapons phaser = Weapon.Weapon("Phaser", 100.00, "pistol", "energy", 1, 12, True) shredder = Weapon.Weapon("Shredder", 1000.00, "smg", "9mm", 120, 120, False) weapons = [phaser, shredder] #create the inventory inventory = Inventory.Inventory(weapons=[], ammo=10) inventory.addWeapons(weapons) #create the player player = Player.Player("Shadow", 18, inventory) player.description() print(Weapon.Weapon.isEquipped(phaser)) print(Weapon.Weapon.isEquipped(shredder)) Weapon.Weapon.fireWeapon(phaser) Weapon.Weapon.fireWeapon(phaser) Weapon.Weapon.reloadWeapon(phaser, inventory) print("rounds = {0}".format(phaser.numRounds)) print("ammo = {0}".format(inventory.ammo))
def use_expansion_packet(): item = Inventory.FindItemByID(2350003) if item.valid: usePacket = Packet.COutPacket(useExpansionHeader) usePacket.EncodeBuffer("[{}00B3DB2300]".format( hex(item.pos).split('x')[1].zfill(2))) Packet.SendPacket(usePacket)
def __init__(self, window, map): self.x = 0 self.y = WINDOW_HEIGHT - 6 * TILE_SIZE Globals.window = window self.velocity = 0 self.map = map self.maxHealth = 100 self.health = 0 self.dead = False self.showDamage = False self.DamageTaken = "" self.CountDownShowDamage = 0 self.CountDownRegen = 0 self.lastSprite = Player.Player_left self.CanMoveLeft = True self.CanMoveRight = True self.inventory = Inventory(5) self.attack = 25 self.ActiveWeapon = None self.draw()
def finishChuChu(): chuchuSymbol = Inventory.FindItemByID(1712002) if not useSymbol(chuchuSymbol): if SCLib.GetVar("UsingWhitelist"): Terminal.SetPushButton("Whitelist", True) SCLib.UpdateVar("CurDaily", "DD") SCLib.UpdateVar("CurStep", "StartingDD")
def __init__(self, game): # Normal game overlay self.health_bar = HealthBar(game) self.mana_bar = ManaBar(game) self.hud_elements = [self.health_bar, self.mana_bar] self.mouse_image = pygame.image.load( "Resources/SinglePhotos/MouseCursor.png") # Pause menu self.pause_menu_background = GUIImage( "Resources/SinglePhotos/PauseMenuBackground.png", 0, 0) self.pause_menu_background.XCenter(game.screen_width) self.pause_menu_background.YCenter(game.screen_height) self.continue_button = ContinueButton(game) self.settings_button = SettingsButton(game) self.exit_button = ExitButton(game) self.pause_menu_elements = [ self.pause_menu_background, self.continue_button, self.settings_button, self.exit_button ] # Inventory menu self.inventory_gui = Inventory.InventoryGUI(game) # Resources for creating message boxes self.font = pygame.font.Font("Resources/Fonts/Ringbearer.ttf", 30) self.dialogue_frame_image = pygame.image.load( "Resources/SinglePhotos/MessageBoxFrame.png") self.message_box_shown = False
def process_file(): #Create empty dictionary inventory_dict = {} #Open inventory data inventory_data = open("Inventory.txt", "r") value = [] #Read data from file for line in inventory_data: value.append(line.strip()) if len(value) == 4: #Store information in separate variable item_id = value[0] name = value[1] quantity = int(value[2]) price = float(value[3]) #Create an instance inventory_item = Inventory.Inventory(item_id, name, quantity, price) #Add item to dictionary inventory_dict[item_id] = inventory_item value.clear() #Close file inventory_data.close() #Return dictionary return inventory_dict
def Student(self): self.root.withdraw() StudentFrame = Tk.Toplevel(bg="#000000", bd=5) StudentFrame.geometry("800x800") StudentFrame.title("Student") button1 = Tk.Button(StudentFrame, text="Display", bg='black', fg='white', command=lambda: self.Sdisplay(StudentFrame)) button1.place(relx=0.28, rely=0.05, relwidth=0.45, relheight=0.15) button2 = Tk.Button(StudentFrame, text="Issue/Return/Lost", bg='black', fg='white', command=lambda: self.IRL(StudentFrame)) button2.place(relx=0.28, rely=0.20, relwidth=0.45, relheight=0.15) button3 = Tk.Button(StudentFrame, text="Search", bg='black', fg='white', command=lambda: self.Search(StudentFrame)) button3.place(relx=0.28, rely=0.35, relwidth=0.45, relheight=0.15) button4 = Tk.Button( StudentFrame, text="Enquiries and Comments", bg='black', fg='white', command=lambda: Inventory.addenqco(StudentFrame, self.root)) button4.place(relx=0.28, rely=0.5, relwidth=0.45, relheight=0.15) handler = lambda: self.onCloseOtherFrame(StudentFrame) btn = Tk.Button(StudentFrame, text="Exit", command=handler) btn.place(relx=0.48, rely=0.78) StudentFrame.protocol("WM_DELETE_WINDOW", self.root.destroy)
def __init__(self): #Print starting screen print("\n\n") print(" !@#$% & ! $ / ^ {+%# !#}{? =+> & ! ") print(" * $# @ % } & @ @ ^ ` - $# @ ") print(" % % $ # ( ? ; - + >&^# % ~ } % $ # ") print(" # ^ ( $ = ` - $ ~ # * | ^ ( $ ") print(" ^*(%# * +$ # * # )+!? !??<+ $<[ * +$ ") print(" ") print("\n\n\n\n\n\n") input(" Press Enter to start the game \n \n ") #Set game variables self.health = 100 self.name = "" self.chapter = 0 self.finished = False self.chapters = [1, 2, 3, 4] self.companions = [] self.inv = Inventory() #Give the player a small boost in the beginning i1 = Food("apple", 1, 15, 3) i2 = Food("sandwich", 3, 30, 1) i3 = Weapon("shotgun", 10, 25) self.inv.items.append(i1) self.inv.items.append(i2) self.inv.items.append(i3) #Prepare screen for game os.system('cls')
def doVJ(): if dailyVJ: initVJ() counter = -1 if SCLib.GetVar("CurStep") == "StartingVJ": print("Starting Vanishing Journey") acceptVJ() elif SCLib.GetVar("CurStep") == "DoingVJ": counter = 0 for q in vjQuests: if q.IsActive(): counter += 1 if SCLib.GetVar("CurQuest") == None or SCLib.GetVar( "CurQuest") == q.quest: q.DoQuest() if counter == 0: SCLib.UpdateVar("CurStep", "FinishedVJ") elif SCLib.GetVar("CurStep") == "FinishedVJ": print("Finishing VJ") if not Quest.CheckCompleteDemand(34129, vjNPC): Quest.CompleteQuest(34129, vjNPC) vjSymbol = Inventory.FindItemByID(1712001) if not useSymbol(vjSymbol): print("Finished VJ") SCLib.UpdateVar("CurDaily", "ChuChu") SCLib.UpdateVar("CurStep", "InitChuChu") else: print("Skipping VJ") SCLib.UpdateVar("CurDaily", "ChuChu") SCLib.UpdateVar("CurStep", "InitChuChu")
class SSHInventory: _interval = 3600 def __init__(self): self._tmp_conf = OssimConf(Const.CONFIG_FILE) self.inv = Inventory() # Implement cache with timeout????? self.cache = [] # threading.Thread.__init__(self) def connectDB(self): self.db = OssimDB() self.db.connect( self._tmp_conf["ossim_host"], self._tmp_conf["ossim_base"], self._tmp_conf["ossim_user"], self._tmp_conf["ossim_pass"], ) def closeDB(self): self.db.close() def run(self): while True: self.process() time.sleep(self._interval) def process(self): # Check host with local credentials hosts = self.inv.getHostWithCredentials("SSH")
def CheckSymbol(symbolid): items = Inventory.GetItems(1) symbolCount = 0 for item in items: if item.id == symbolid: symbolCount += 1 return symbolCount
def __init__(self, center_x, center_y, animation_images, saved_params=None): super().__init__(center_x, center_y, animation_images) self._max_health = self._max_mana = self._max_stamina = 100 self._speed_changing = 3 self._amount_damage = random.randint(140, 200) self._passive_regeneration = 0.1 self._regeneration_interval = 10 self._last_attack_time = 250 self._animation_interval = 150 self._experience_up_level = 1000 * pow(1.1, self._level) self._selected_attack = GameEnums.AttackTypes.FIREBALL.value self._inventory = Inventory.Inventory() self._health_bar = Bar.Bar(Constants.GAME_WINDOW_WIDTH // 2 - 250, Constants.GAME_WINDOW_HEIGHT - 96, 'resources/images/bars/health_bar.png') self._mana_bar = Bar.Bar(Constants.GAME_WINDOW_WIDTH // 2 + 155, Constants.GAME_WINDOW_HEIGHT - 96, 'resources/images/bars/mana_bar.png') if saved_params is None: self._level = 1 self._current_experience = 0 self._current_health = 100 self._current_stamina = self._max_stamina self._current_mana = self._max_mana else: self._level = saved_params['level'] self._current_experience = saved_params['current_experience'] self._current_health = saved_params['current_health'] self._current_stamina = saved_params['current_stamina'] self._current_mana = saved_params['current_mana']
def __init__(self,parentWorld,colRow): super().__init__(parentWorld,colRow,15,1,255) self.durability = 20 self.physical = False self.inv = Inventory.objectInventory(self.parentWorld.itemList,9) self.selectedSlot = 0 self.drop = 9 self.updatePic() self.tool = "axe"
def run_function_on_multiple_items(items): """Runs function per item , for multiple items Args: items (dict): Item dict , that represent the item , and the function. The proper form is : { "item_img": Path to image , (Use Util.image_path_main or Util.image_path_module), "function": Items.ItemFunctions.* Function to execute, "index_of_function": index of function in the context menu , "section": Inventory.InventorySections.* Section of the inventory the item is in } """ current_section = items[0]['section'] Inventory.go_to_inventory(current_section) for item in items: if item['section'] != current_section: current_section = items['section'] Inventory.go_to_section(current_section) run_function( item_img=item['item_img'], function=item['function'], index_of_function=item['index_of_function'] ) Inventory.exit_inventory() sleep(1)
def test_inventoryisFull(self): inventory = Inventory() inventory2 = Inventory() inventory.invCards = [1,2,3] inventory2.invCards = [1,2] self.assertTrue(inventory.isFull()) self.assertFalse(inventory2.isFull())
def run_function_on_item(item_img, function, index_of_function, section): """Uses function on item Args: item_img (str): file name of item's image function (ItemFunctions): function to execute index_of_function (int): index of function in the item's context menu - When using batch_empty_prefered , leave it at -1 section (InventorySections, optional): Section of inventory the item is at """ Inventory.go_to_inventory(section) sleep(1) log.debug('Running %s on %s', item_img.split('/')[-1], convert(function)) run_function( item_img=item_img, function=function, index_of_function=index_of_function ) Inventory.exit_inventory() sleep(1)
def test_inventoryRemove(self): inventory = Inventory() inventory.invCards = [0,1,2,3] i = 0 self.assertEqual(inventory.remove(0), i) i += 1 # To check if a card was acctually removed self.assertEqual(inventory.remove(0), i) with self.assertRaises(IndexError): # Index = -100 not valid inventory.remove(-100)
class Bank: # TODO!!! Think придумать как будет выглядеть взаимодействие с банком # TODOlater Если будут вещь в кол-вом (4 шт. напр.) то спрашивать сколько хотите взять # Question Если тут есть removeGold() который будет вызываться, то видимо нужно сделать такойже для hero? def __init__(self): self.storage = Inventory() self.money = Money() ## Добавляет money денег в банк def addMoney(self, money): self.money += money ## Убирает money денег из банка, если хватит золота def removeMoney(self, money): if self.isEnoughMoney(money): self.money -= money return True else: print("Money is not enough.\nBank stores only {0}".format(self.money)) return False ## Возвращает true если в банке есть столько денег def isEnoughMoney(self, money): if self.money >= money: return True else: return False ## Добавляет item в банк def addItem(self, item): self.storage.addItem(item) ## Убирает item из банка def removeItem(self, item): self.storage.removeItem(item) ## Возвращает список всех вещей в банке def items(self): return self.storage.items() ## Возвращает Кол-во денег и список всех вещей в банке в виде строки def __str__(self): result = "{0}\n".format(self.money) result += self.storage.__str__() return result
def __init__(self): # First I load my chosen screen size and use it to override the default one, while initializing the engine. self.w = 1240 self.h = 960 Engine.__init__(self, size=(self.w, self.h), fill=(255, 255, 255)) self.screen_rect = pygame.Rect(0, 0, self.w, self.h) # Here we set up an image file for the mouse cursor # (making sure to convert it and keep transparency) self.mouse_over = MouseOver() self.mouse_image = self.mouse_over.mouse_img() self.mouse_rect = self.mouse_image.get_rect() self.mouse_pos = (0, 0) self.player = Player() self.player.level_init() self.inventory = Inventory() self.current_level = 0 self.game = False self.start_menu = StartMenu((self.w, self.h)) self.start_menu.update()
class Game(Engine): def __init__(self): # First I load my chosen screen size and use it to override the default one, while initializing the engine. self.w = 1240 self.h = 960 Engine.__init__(self, size=(self.w, self.h), fill=(255, 255, 255)) self.screen_rect = pygame.Rect(0, 0, self.w, self.h) # Here we set up an image file for the mouse cursor # (making sure to convert it and keep transparency) self.mouse_over = MouseOver() self.mouse_image = self.mouse_over.mouse_img() self.mouse_rect = self.mouse_image.get_rect() self.mouse_pos = (0, 0) self.player = Player() self.player.level_init() self.inventory = Inventory() self.current_level = 0 self.game = False self.start_menu = StartMenu((self.w, self.h)) self.start_menu.update() def game_init(self): # Some colors, these will change. blackColor = (0, 0, 0) white_color = (255, 255, 255) sgidarkgray = (85, 85, 85) yellowColor = (255, 255, 0) # Setting up the background surface (the game map). self.blocksize = 32 self.background = GameSurface((8000, 8000), (0, 0), blackColor) self.bg = pygame.sprite.LayeredDirty(self.background) # Here we start making the map. (This takes the longest time to load) self.rooms = self.generate_levels(self.blocksize, self.background.levelsize) self.add_exit(self.rooms, self.blocksize) # Here I load up the player, and the variables necessary # for movement and rotation. self.cp = pygame.Rect(0, 0, self.player.rect.width, self.player.rect.height) self.player.set_collide(self.rooms) # Here we mage the Gui self.gui = GUI((self.w, self.h), self.player) self.player_window = PlayerWindow((self.w, self.h), self.player) self.power_window = PowerWindow((self.w, self.h), self.player) self.power_window.update() self.test_text = [] # Some Timer variables. self.time_passed = self.clock.get_fps() self.cd1 = 0.0 self.cd2 = 0.0 self.cd3 = 0.0 self.cd4 = 0.0 # Then we need to set up the rooms, placing the player in the first one. # (and centering the screen on him) self.background.rect.x, self.background.rect.y = self.set_rooms( self.rooms, self.player, self.background.rect.x, self.background.rect.y, self.cp, self.w, self.h ) # Time to add some mobs. self.mobs = self.add_mobs((random.randint(1, 10)), self.rooms, self.player, self.background) self.l_mobs = [] # And we set up the players powers self.powergroup = pygame.sprite.LayeredDirty() self.b3 = False self.game = True def generate_levels(self, block, size): if self.current_level == 0: rooms = self.generate_room(block, (size[0] / 4, size[1] / 4)) self.current_level += 1 elif self.current_level == 1: rooms = self.generate_room(block, (size[0] / 2.5, size[1] / 2.5)) self.current_level += 1 elif self.current_level == 2: rooms = self.generate_room(block, (size[0] / 2, size[1] / 2)) self.current_level += 1 elif self.current_level == 3: rooms = self.generate_room(block, size) return rooms # the update method. This one is called in the game_loop (from the engine) # but it must be run in this file. def update(self): self.mouse_image = self.mouse_over.mouse_img() if self.game == True: if self.player.nextlevel == True: self.player.nextlevel = False self.game_init() # Updating the gui. self.gui.update(self.player) # This is the rectangle for our screen. self.screen_rect.topleft = (-self.background.rect.x, -self.background.rect.y) # We then use that rectangle to cut away anything we do not need to render. self.limit_rooms(self.rooms, self.screen_rect) self.l_mobs = self.limit_mobs(self.screen_rect, self.mobs) # Adding the cut down sprites to the draw group. self.wallsprites = self.add_rooms() self.mobgroup = pygame.sprite.LayeredDirty() self.mobgroup.add(self.player) self.mobgroup.add(self.l_mobs) self.inventory.update(self.player) # Movement for the player. self.player.move(self.player.dir, self.cp, (self.w, self.h)) self.cp.x, self.cp.y = self.find_position( self.player.rect.x, self.player.rect.y, self.background.rect.x, self.background.rect.y ) # Here we scroll the map using the mouse pointer. self.map_move(self.background, self.cp, self.w, self.h) if self.b3 == True: self.cone.effect.fire(self.player.rect.center, self.b_pos, self.delta_time) self.greenbars = [] self.redbars = [] for mob in self.l_mobs: mob.run(self.rooms, self.l_mobs, self.player, self.delta_time) redbar, greenbar = mob.health_bar() self.redbars.append(redbar) self.greenbars.append(greenbar) if mob.state == "DEAD": self.inventory.spawn_item(mob) self.mouse_over.check_mobs(self.l_mobs, self.background) self.mouse_over.check_tiles(self.wallsprites, self.background) if self.player.state == "DEAD": self.game = False self.current_level = 0 self.start_menu.select(2) self.start_menu.update() # The draw function. This is where things are actually drawn to screen. # Its called in the engines mainloop, but must be run in this file. def draw(self): if self.game == True: # Here we clip to the clipping rectangle. self.wallsprites.set_clip(self.screen_rect) # And run the necesary updates. self.wallsprites.update() self.mobgroup.update(self.delta_time) self.powergroup.update(self.delta_time) # Now we draw things in order. # First we draw the levels. self.wallsprites.draw(self.background.image) # Then we draw the Player and mobs. self.mobgroup.draw(self.background.image) for mob in self.mobgroup: if mob.state == "SHOUTING": self.background.image.blit(mob.mssg, mob.mssg_rect) # Then we draw the Inventory items self.inventory.draw(self.background.image) # Then we draw the powers. self.powergroup.draw(self.background.image) for power in self.powergroup: if power.state == "EXPLODING": pygame.draw.circle(self.background.image, (255, 255, 255), power.pos.inttup(), power.radius, 1) elif power.state == "CONE": pygame.draw.aalines(self.background.image, (255, 255, 255), True, power.vectorlist) # Here we draw the healthbars of the mobs. for bars in self.redbars: pygame.draw.rect(self.background.image, pygame.Color("red"), bars) for bars in self.greenbars: pygame.draw.rect(self.background.image, pygame.Color("green"), bars) pygame.draw.rect(self.background.image, (255, 255, 255), self.screen_rect, -1) # Then we draw the everything to the screen. self.bg.draw(self.screen) # Everything below this line is drawn directly to the Screen # not the Background Surface # Then we draw the GUI. self.gui.draw(self.screen) if self.player_window.state == True: self.player_window.draw(self.screen) if self.player_window.powerstate == True: self.player_window.state = False self.power_window.draw_window(self.screen) else: self.start_menu.draw(self.screen) # Then we draw the mousepointer. self.mouse_over.draw(self.screen) self.screen.blit(self.mouse_image, self.mouse_pos) pygame.display.update() def user_event(self, event): pass # An event method giving us all key down presses. def key_down(self, key): if self.game == True: if key in (K_w, K_UP): self.player.dir[0] = 1 if key in (K_a, K_LEFT): self.player.dir[1] = 1 if key in (K_s, K_DOWN): self.player.dir[2] = 1 if key in (K_d, K_RIGHT): self.player.dir[3] = 1 if key == K_ESCAPE: pygame.quit() if key == K_2: if self.cd2 < self.delta_time: self.ball = Powers(self.player.level, self.player.rect.center) self.ball.fire_ball() if self.player.mana >= self.ball.manacost: self.ball.set_collision(self.rooms, self.l_mobs) self.powergroup.add(self.ball.effect) self.ball.effect.fire(self.player.rect.center, self.b_pos) self.player.shout_spell(self.ball.name) self.player.mana -= self.ball.manacost self.cd2 = self.delta_time + self.ball.cooldown else: print "Not enough Mana" if key == K_3: if self.cd3 < self.delta_time: self.cone = Powers(self.player.level, self.player.rect.center) self.cone.cone_of_frost() if self.player.mana >= self.cone.manacost: self.b3 = True self.cone.set_collision(None, self.l_mobs) self.powergroup.add(self.cone.effect) self.player.shout_spell(self.cone.name) self.player.mana -= self.cone.manacost self.cd3 = self.delta_time + self.cone.cooldown else: print "Not enough Mana" if key == K_4: if self.cd4 < self.delta_time: self.ring = Powers(self.player.level, self.player.rect.center) self.ring.ring_of_fire() if self.player.mana >= self.ring.manacost: self.ring.set_collision(None, self.l_mobs) self.powergroup.add(self.ring.effect) self.ring.effect.fire(self.player.rect.center, None) self.player.shout_spell(self.ring.name) self.player.mana -= self.ring.manacost self.cd4 = self.delta_time + self.ring.cooldown else: print "Not enough Mana" if key == K_p: if self.player_window.state == False: self.player_window.update() self.player_window.state = True elif self.player_window.state == True: self.player_window.state = False if key == K_LSHIFT: self.mouse_over.state = 2 # An event method giving us all key up presses. def key_up(self, key): if self.game == True: if key in (K_w, K_UP): self.player.dir[0] = 0 if key in (K_a, K_LEFT): self.player.dir[1] = 0 if key in (K_s, K_DOWN): self.player.dir[2] = 0 if key in (K_d, K_RIGHT): self.player.dir[3] = 0 if key == K_3: self.b3 = False self.cone.effect.state = "DEAD" if key == K_LSHIFT: self.mouse_over.state = 1 # Two event Methods for the mouse keys (down and up). buttons are 1=left , 2=middle, 3=right. def mouse_down(self, button, pos): if self.game == True: if button == 1: if self.player_window.state == True: self.player_window.mouse_button(button) if self.cd1 < self.delta_time: self.missile = Powers(self.player.level, self.player.rect.center) self.missile.magic_missile() if self.player.mana >= self.missile.manacost: self.missile.set_collision(self.rooms, self.l_mobs) self.powergroup.add(self.missile.effect) self.missile.effect.fire(self.player.rect.center, self.b_pos) self.player.shout_spell(self.missile.name) self.player.mana -= self.missile.manacost self.cd1 = self.delta_time + self.missile.cooldown else: print "Not enough Mana" else: if button == 1: menu_button = self.start_menu.mouse_press() if menu_button == 1: self.player = Player() self.player.level_init() self.game_init() elif menu_button == 3: self.running = False def mouse_up(self, button, pos): pass # Event method for mouse motion. def mouse_motion(self, buttons, pos, rel): self.mouse_pos = pos self.mouse_over.update_pos(pos) if self.game == True: if self.player_window.state == True: self.player_window.mouse_mov(pos, buttons) b_pos_x = pos[0] - self.background.rect.x b_pos_y = pos[1] - self.background.rect.y self.b_pos = (b_pos_x, b_pos_y) # Here we call the method to rotate the mouse. self.player.rot = self.rotate( (self.cp.centerx, self.cp.centery), (self.mouse_pos[0] + (self.mouse_rect.width / 2), self.mouse_pos[1] + (self.mouse_rect.height / 2)), ) self.player.image = self.rotate_image(self.player.base_img, (self.player.rot)) self.map_scroll(self.mouse_pos, self.w, self.h) else: self.start_menu.mouse_mov(self.mouse_pos) def screen_message(self, text): pass
class OCSInventory(): _interval = 3600 def __init__(self): self._tmp_conf = OssimConf (Const.CONFIG_FILE) self.inv = Inventory() #Implement cache with timeout????? self.cache = [] #threading.Thread.__init__(self) def connectDB(self): self.db = OssimDB() self.db.connect (self._tmp_conf["ossim_host"], self._tmp_conf["ossim_base"], self._tmp_conf["ossim_user"], self._tmp_conf["ossim_pass"]) def closeDB(self): self.db.close() def run(self): while True: self.process() time.sleep(self._interval) def process(self): self.ossimHosts = self.inv.getListOfHosts() #print self.ossimHosts ocsHosts = self.getOCSHosts() for host in ocsHosts: ip = host['ipaddr'] #Check if host is valid if self.inv.validateIp(ip): #Check if host exists if not ip in self.ossimHosts: #Add host to ossim Database logger.debug("Adding %s" % ip) self.inv.insertHost(ip, None, host['name'], host['description']) mac = self.getMACfromHost(host['id'], ip) self.inv.insertProp(ip, "macAddress", "OCS", mac, None) self.inv.insertProp(ip, "workgroup", "OCS", host['workgroup'], None) self.inv.insertProp(ip, "operating-system", "OCS", host['osname'], None) else: #Host previously discovered #OCS has the highest priority to replace properties props = self.inv.getProps(ip) if self.inv.properties["macAddress"] not in props: mac = self.getMACfromHost(host['id'], ip) self.inv.insertProp(ip, "macAddress", "OCS", mac, None) else: mac = self.getMACfromHost(host['id'], ip) self.inv.updateProp(ip, "macAddress", "OCS", mac, None) if self.inv.properties["workgroup"] not in props: self.inv.insertProp(ip, "workgroup", "OCS", host['workgroup'], None) else: self.inv.updateProp(ip, "workgroup", "OCS", host['workgroup'], None) #OS cpe = self.inv.generateCPE(host['osname'], host['osversion'], host['oscomments']) if not cpe: cpe = host['oscomments'] if self.inv.properties["operating-system"] not in props: self.inv.insertProp(ip, "operating-system", "OCS", host['osname'], cpe) else: self.inv.updateProp(ip, "operating-system", "OCS", host['osname'], cpe) def getOCSHosts(self): self.connectDB() sql = "select id,name,osname,osversion,ipaddr,workgroup,description,oscomments from ocsweb.hardware;" data = self.db.exec_query(sql) self.closeDB() return data def getSoftware(self, ip): pass def getMACfromHost(self, id, ip): self.connectDB() sql = "select MACADDR from ocsweb.networks where HARDWARE_ID = %d and IPADDRESS = '%s';" % (id, ip) data = self.db.exec_query(sql) if data: self.closeDB() return data[0]["macaddr"]
class Hero(Entity): def __init__(self, sprites, animations, current_sprite, world_i, name): Entity.__init__(self, sprites, animations, world_i, name) self.position = (150, 300) self.current_sprite = current_sprite self.sprite = None self.command = None self.active = False self.inventory = Inventory(self.entity_i) self.add_hero_listeners() def save(self, db): super(Hero, self).save(db) db('INSERT INTO hero(rowid, name, x, y) VALUES(?, ?, ?, ?)', self.entity_i, self.name, self.position[0], self.position[1]) def load(self, db): super(Hero, self).load(db) x=db('SELECT name, x, y FROM hero WHERE rowid=?', self.entity_i)[0] def init_hero_inventory(self, db): for item, amount in HERO_START.STARTING_ITEMS.iteritems(): db('INSERT INTO inventory(rowid, item, amount) VALUES(?, ?, ?)', self.entity_i, item, amount) self.inventory.add_item(item, amount) def set_position(self, position): self.position = position self.current_sprite.set_position(self.position[0], self.position[1]) def set_current_sprite(self, sprite): self.current_sprite = self.sprites[sprite] self.sprite = sprite self.current_sprite.set_position(self.position[0], self.position[1]) def set_animation(self, sprite): self.animation.set_animation(self.animations[sprite]) self.set_current_sprite(sprite) def start_level_up(self): return False def set_clickable(self): pass def add_hero_listeners(self): self.add_change_listener(self.check_health) self.add_change_listener(self.check_mana) def check_health(self): #print('health') pass def check_mana(self): #print('mana') pass def turn_start(self): self.command.execute(self) def turn_end(self): self.command.reset(self) self.command = None def draw(self): self.animation.draw_animation(self.current_sprite)
class Player(GameObject): def __init__(self, x, y): super().__init__() self.image = pygame.Surface([32, 32]) self.image.fill((255, 128, 128)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.movex = 0 self.movey = 0 self.inventory = Inventory() def move(self, x, y): self.movex = x * 5 self.movey = y * 5 def update(self, gameobjects): self.rect.x += self.movex self.rect.y += self.movey collide, collider = self.checkCollision(gameobjects) if collide: self.inventory.addItem(collider) def checkCollision(self, gameobjects): for gameobject in gameobjects: if gameobject is not self: if self.rect.colliderect(gameobject.rect): return True, gameobject return False, None def printInventory(self): self.inventory.printInventory() def craftItem(self, item): canCraft = True for k in item.craftList: if not self.inventory.checkItem(k) > item.craftList[k]: canCraft = False print('Missing %d %s' % (item.craftList[k] - self.inventory.checkItem(k), k.name)) if canCraft: for k in item.craftList: self.inventory.removeItem(k, item.craftList[k]) print('Removed %d %ss' % (item.craftList[k], k.name)) self.inventory.addItem(item) print('Created %s' % item.name) def canCraft(self, item): canCraft = True for k in item.craftList: if not self.inventory.checkItem(k) > item.craftList[k]: canCraft = False return canCraft
def __init__(self): self.storage = Inventory() self.money = Money()
def __init__(self): self._tmp_conf = OssimConf(Const.CONFIG_FILE) self.inv = Inventory() # Implement cache with timeout????? self.cache = []
def show_loadscreen(self): if (os.path.isfile("savefile.txt") and not self.finished): print("\n\n") print("A savefile was found. Load this file? (yes/no)".center(80)) result = input(" \n ") #If the player wants to load a savefile: if result in ('y','yes'): #Retrieve all info from savefile.txt with open("savefile.txt", "r") as save_file: game_state = [] for line in save_file: values = line.split("=") game_state.append({'var': values[0], 'value': values[1].rstrip()}) #Create temporary Inventory, fill this inv with items from savefile. tmp_inv = Inventory() #Create temporary Companion list, fill this list with companions from savefile. tmp_comps = [] #Load values into game for entry in game_state: if entry['var'] == 'name': self.name = entry['value'] elif entry['var'] == 'health': self.health = int(entry['value']) elif entry['var'] == 'chapter': self.chapter = int(entry['value']) elif entry['var'] == 'finished': if entry['value'] == 'True': self.finished = True else: self.finished = False #Loop through chapters and split where necessary elif entry['var'] == 'chapters': temp_arr = re.split(",", entry['value']) self.chapters[:] = [] for item in temp_arr: try: self.chapters.append(int(item)) except ValueError: pass elif entry['var'] == 'invsize': tmp_inv.size = int(entry['value']) #Loop through all items in inventory and split where necessary elif entry['var'] == 'items': temp_items = re.split("/", entry['value']) #An item can be of 3 types (Regular, food, weapon) #Each one needs to be loaded differently, check for this. for item in temp_items: itm = re.split(",", item) if itm[0] == 'w': temp_wpn = Weapon(itm[1],int(itm[2]),int(itm[3])) tmp_inv.items.append(temp_wpn) elif itm[0] == 'f': temp_food = Food(itm[1], int(itm[2]), int(itm[3]), int(itm[4])) tmp_inv.items.append(temp_food) elif itm[0] == 'i': temp_itm = Item(itm[1], int(itm[2])) tmp_inv.items.append(temp_itm) else: pass self.inv = tmp_inv #Loop through all companions in list and split where necessary elif entry['var'] == 'companions': temp_comps = re.split("/", entry['value']) for comp in temp_comps: cmp = re.split(",", comp) temp_cmp = Person(cmp[0],int(cmp[1]),int(cmp[2]),cmp[3],cmp[4]) tmp_comps.append(temp_cmp) self.companions = tmp_comps else: pass #Notify user that savefile has been loaded. self.clr() print("\n\n") print("Your savefile was loaded.".center(80)) input("") self.clr() return True #If the player chooses to play new game or input is incorrect: elif result in ('n', 'no'): self.clr() print("\n\n") print("No savefile was loaded.".center(80)) input("") self.clr() return False else: self.clr() self.show_loadscreen() return True #Savefile doesn't exist, skip to introduction directly. else: return False
class Invasion: def __init__(self): #Print starting screen print("\n\n") print(" !@#$% & ! $ / ^ {+%# !#}{? =+> & ! ") print(" * $# @ % } & @ @ ^ ` - $# @ ") print(" % % $ # ( ? ; - + >&^# % ~ } % $ # ") print(" # ^ ( $ = ` - $ ~ # * | ^ ( $ ") print(" ^*(%# * +$ # * # )+!? !??<+ $<[ * +$ ") print(" ") print("\n\n\n\n\n\n") input(" Press Enter to start the game \n \n ") #Set game variables self.health = 100 self.name = "" self.chapter = 0 self.finished = False self.chapters = [1, 2, 3, 4] self.companions = [] self.inv = Inventory() #Give the player a small boost in the beginning i1 = Food("apple", 1, 15, 3) i2 = Food("sandwich", 3, 30, 1) i3 = Weapon("shotgun", 10, 25) self.inv.items.append(i1) self.inv.items.append(i2) self.inv.items.append(i3) #Prepare screen for game os.system('cls') #Method for clearing def clr(self): os.system('cls') #Getter for player status def is_alive(self): return self.alive #Method for displaying loading screen def show_loadscreen(self): if (os.path.isfile("savefile.txt") and not self.finished): print("\n\n") print("A savefile was found. Load this file? (yes/no)".center(80)) result = input(" \n ") #If the player wants to load a savefile: if result in ('y','yes'): #Retrieve all info from savefile.txt with open("savefile.txt", "r") as save_file: game_state = [] for line in save_file: values = line.split("=") game_state.append({'var': values[0], 'value': values[1].rstrip()}) #Create temporary Inventory, fill this inv with items from savefile. tmp_inv = Inventory() #Create temporary Companion list, fill this list with companions from savefile. tmp_comps = [] #Load values into game for entry in game_state: if entry['var'] == 'name': self.name = entry['value'] elif entry['var'] == 'health': self.health = int(entry['value']) elif entry['var'] == 'chapter': self.chapter = int(entry['value']) elif entry['var'] == 'finished': if entry['value'] == 'True': self.finished = True else: self.finished = False #Loop through chapters and split where necessary elif entry['var'] == 'chapters': temp_arr = re.split(",", entry['value']) self.chapters[:] = [] for item in temp_arr: try: self.chapters.append(int(item)) except ValueError: pass elif entry['var'] == 'invsize': tmp_inv.size = int(entry['value']) #Loop through all items in inventory and split where necessary elif entry['var'] == 'items': temp_items = re.split("/", entry['value']) #An item can be of 3 types (Regular, food, weapon) #Each one needs to be loaded differently, check for this. for item in temp_items: itm = re.split(",", item) if itm[0] == 'w': temp_wpn = Weapon(itm[1],int(itm[2]),int(itm[3])) tmp_inv.items.append(temp_wpn) elif itm[0] == 'f': temp_food = Food(itm[1], int(itm[2]), int(itm[3]), int(itm[4])) tmp_inv.items.append(temp_food) elif itm[0] == 'i': temp_itm = Item(itm[1], int(itm[2])) tmp_inv.items.append(temp_itm) else: pass self.inv = tmp_inv #Loop through all companions in list and split where necessary elif entry['var'] == 'companions': temp_comps = re.split("/", entry['value']) for comp in temp_comps: cmp = re.split(",", comp) temp_cmp = Person(cmp[0],int(cmp[1]),int(cmp[2]),cmp[3],cmp[4]) tmp_comps.append(temp_cmp) self.companions = tmp_comps else: pass #Notify user that savefile has been loaded. self.clr() print("\n\n") print("Your savefile was loaded.".center(80)) input("") self.clr() return True #If the player chooses to play new game or input is incorrect: elif result in ('n', 'no'): self.clr() print("\n\n") print("No savefile was loaded.".center(80)) input("") self.clr() return False else: self.clr() self.show_loadscreen() return True #Savefile doesn't exist, skip to introduction directly. else: return False #Method for displaying infoscreen def show_infoscreen(self): print("\n\n\n") tmp_name = input("What is your name?\n ".center(80)) while not tmp_name: self.clr() print("\n\n\n") tmp_name = input("What is your name?\n ".center(80)) self.name = tmp_name self.clr() print("\n\n\n") print(("Okay, " + self.name + ", welcome to this game!").center(80)) print("") print(("You can always continue by pressing the Enter key. Try it!").center(80)) input("") print("") print(("Good job, let's get started!").center(80)) input("") self.clr() #Method for saving progress after each chapter def save_progress(self): self.clr() print("\n\n") print("Do you want to save the game at this point? (yes/no)".center(80)) print("Note: Game can only be saved after finishing a chapter.".center(80)) res = input(" \n ") if res in ('y', 'yes'): #Clear savefile. open("savefile.txt", 'w').close() #Write new data to file. with open("savefile.txt", 'w') as save_file: save_file.write("name=" + self.name + "\n") save_file.write("health=" + str(self.health) + "\n") save_file.write("chapter=" + str(self.chapter) + "\n") #Write finished if self.finished == True: save_file.write("finished=True\n") else: save_file.write("finished=False\n") #Write chapters (list format) ch_string = "" try: ch_string = str(self.chapters[0]) except IndexError: pass for i in range(1, len(self.chapters)): ch_string += ("," + str(self.chapters[i])) save_file.write("chapters=" + ch_string + "\n") #Write inventory save_file.write("invsize=" + str(self.inv.size) + "\n") inv_string = "" item_string = "" for i in range(0, len(self.inv.items)): item = self.inv.items[i] if isinstance(item, Weapon): item_string = ("w,"+item.save_wpn()) elif isinstance(item, Food): item_string = ("f,"+item.save_food()) else: item_string = ("i,"+item.name+","+str(item.weight)+"/") inv_string += item_string inv_string = inv_string[:-1] save_file.write("items=" + inv_string + "\n") #Write companions list_string = "" comp_string = "" for i in range(0, len(self.companions)): comp = self.companions[i] comp_string = (comp.name+","+str(comp.health)+","+str(comp.eff)+","+comp.status+","+comp.bonus+"/") list_string += comp_string comp_string = comp_string[:-1] save_file.write("companions=" + comp_string + "\n") #Don't save, notify user. elif res in ('n', 'no'): self.clr() print("\n\n") print("Progress was not saved.".center(80)) input("") else: self.clr() self.save_progress() #Method for printing option screen with 1 line of description def option_1(self, desc, opt): self.clr() print("\n\n\n") print(desc.center(80)) print("\n\n\n\n\n\n\n\n\n\n\n\n\n") result = input(" Enter command (" + opt + "): ") return result #Method for printing option screen with 2 lines of description def option_2(self, desc1, desc2, opt): self.clr() print("\n\n\n") print(desc1.center(80)) print(desc2.center(80)) print("\n\n\n\n\n\n\n\n\n\n\n\n\n") result = input(" Enter command (" + opt + "): ") return result #Method for printing story information with 2 lines def story_2(self, line1, line2): self.clr() print("\n\n\n") print(line1.center(80)) print(line2.center(80)) #Method for printing story information with 3 lines def story_3(self, line1, line2, line3): self.clr() print("\n\n\n\n") print(line1.center(80)) print(line2.center(80)) print(line3.center(80)) #Check if input is correct. def is_valid(self, x): if x in ('y', 'yes', 'n', 'no'): return True else: return False #Method for apologizing :) def sorry_Peter_LG(self): print("\n") print(" Unfortunately, this section has not been fully developed.") print(" The programmer, Daniel, had to do all of the project on his own.") print("") print(" All of the functionality and technical aspects are there,") print(" but the game lacks in content.") print("") print(" He sincerely apologises for this fact.") print(" He is going to finish this game back home (NL), when he has a lot of time.") print(" If the player is interested in playing the full game,") print(" send the programmer an email.") print("\n") input("") self.clr() #Method for introduction chapter def intro_chapter(self): print("\n\n") print("----- Introduction -----".center(80)) input("") print("This story is set in the United States of America.".center(80)) input("") print("You and Tyler are best friends.".center(80)) input("") print("Together with Tyler and your brother Evan,".center(80), end="") print("you are going to see a movie in the cinema.".center(80)) print("\n\n\n\n") input("") self.clr() #Subchapter 0.1 q_string = self.option_1("You are sitting in the cinema. The movie hasn't started yet.", "talk/walk/wait") while not(self.a_1(q_string)): q_string = self.option_1("You are sitting in the cinema. The movie hasn't started yet.", "talk/walk/wait") input("") self.clr() #Subchapter 0.2 q_string = self.option_2("Suddenly, the lights go out and the ground starts shaking!", "Evan: Help, what is going on?!", "talk/run") while not(self.a_2(q_string)): q_string = self.option_2("Suddenly, the lights go out and the ground starts shaking!", "Evan: Help, what is going on?!", "talk/run") self.health -= 90 input("") self.clr() self.chapter = 1 #Methods for choices in intro chapter def a_1(self, opt): if opt == "talk": self.story_2((self.name.title() + ": Damn, this is taking long. I wish this movie would start already!"), "Tyler: Dude, be patient. It will probably start in 5 minutes.") return True elif opt == "walk": self.story_3((self.name.title() + ": I'm going around for a walk now, I'll be right back."), "You find a box of popcorn. After that, you walk over to the door.", "Huh? The doors are locked!") f1 = Food("popcorn", 2, 25, 1) if self.inv.fits(f1): self.inv.items.append(f1) print("\n\n") print(" Item ("+f1.name+") has been added to inventory.") else: print("\n\n") print(" Item ("+f1.name+") doesn't fit in inventory.") return True elif opt == "wait": self.story_2("You decide to be patient, good choice.", "After all, you are not in a rush, right?") return True else: return False def a_2(self, opt): if opt == "talk": self.story_3((self.name.title() + ": What the hell is going on?!"), "And what is that guy on the front row even doing?", "Tyler: I didn't even notice him until now. Sir. SIR! EXCUSE ME!") self.story_3("Alex: Hi! Do you kids have any idea what's going on?", (self.name.title() + ": No, but let's find that out later!"), "Alex: Smart idea. I'll join you guys!") p1 = Person("Alex", 80, 10, "good", "dmg") self.companions.append(p1) return True elif opt == "run": self.story_2((self.name.title() + ": Guys, let's get out of here ASAP."), "Tyler: Smart words, this seems unsafe!") return True else: return False #Method for mall chapter def mall_chapter(self): self.clr() print("\n\n") print("----- The Shopping Mall -----".center(80)) input("") print("After a long walk, you arrive at a shopping mall.".center(80)) input("") print("The mall looks abandoned.".center(80)) input("") print("Tyler: We can probably find some clothing and weapons in there!".center(80)) input("") print("However, something seems off..".center(80)) print("\n\n\n") input("") self.clr() #Subchapter 2.1 q_string = self.option_1("You enter the mall. Where do you want to go? (Left for more gameplay)", "left/right") while not(self.b_1(q_string)): q_string = self.option_1("You enter the mall. Where do you want to go? (Left for more gameplay)", "left/right") self.clr() self.chapter = 2 #Methods for choices in mall_chapter def b_1(self, opt): if opt in ('l', 'left'): self.story_2("You go to the left.", "Suddenly, a mysterious figure shows up!") input("") self.clr() p2 = Person("Alison", 50, 10, "good", "healing") def b_1_1(opt2): if opt2 in ('y', 'yes'): self.story_2("You slowly approach the mysterious figure.", (self.name.title() + ": Ahem. Excuse me?")) input("") self.story_3("The figure slowly walks towards your group.", "As the figure comes closer, you see that it is a crying woman!", "She seems very sad.") input("") self.story_3("Alison: C-Can you guys h-help me?", (self.name.title() + ": Yes, of course! What's going on?"), "Alison: I was j-just buying some clothes!") input("") self.story_3("Alison: When I went into a changing booth, everyone suddenly disappeared!", "Alison: While I was changing, I heard some loud monster-like noises.", "Evan: And did you notice the earthquake?") input("") self.story_3("Alison: Earthquake? No?!", "Alex: ..Something bad happened for sure.", "Tyler: Let's figure this stuff out soon.") input("") self.story_3("Alison: I will join your group, if that's ok.", "Alison: I used to be a nurse, maybe I can be helpful.", (self.name.title() + ": Sure, you can join us!")) self.companions.append(p2) return True elif opt2 in ('n','no'): self.story_2("As your group slowly tries to walk away, Evan steps on broken glass.", "The mysterious figure turns around and charges you!") input("") self.clr() p2.status = "evil" fight = Fight(self.name, self.health, self.inv, self.companions, p2) if (fight.start() == True): self.finished = True else: self.story_2((self.name.title() + ": Wow, that was crazy!"), (self.name.title() + ": Is everyone OK?")) input("") alex = False for ally in self.companions: if ally.name == 'Alex': alex = True ally.health -= 80 if ally.health < 1: self.story_2("Evan: Oh no.. Alex.. ALEX!", "Tyler: Sorry guys, Alex is gone.") for i in range(0, len(self.companions)): if self.companions[i].name == "Alex": self.companions.pop(i) else: self.story_2("Evan: Alex, are you allright?", "Alex: Well, I'm alive, but I took some serious damage.") break if not alex: self.story_2("Evan: Yeah, I'm good.", "Tyler: I'm fine as well!") return True else: return False #Trigger next event. q_string = self.option_1("Do you approach the figure?", "yes/no") while not(b_1_1(q_string)): q_string = self.option_1("Do you approach the figure?", "yes/no") input("") self.clr() return True elif opt in ('r', 'right'): self.story_2("Evan: It's so dark here, I can't see anything!", "Tyler: Guys, let's check out that box over there!") input("") self.story_2((self.name.title() + ": Is that what I think it is?"), "Evan: Oh yes! A loot crate!") input("") self.clr() print("\n\n") print(" Congratulations, you found a loot crate!") print(" The crate contains the following items: ") print(" 1. M16, damage: 35", end="") input("") print(" 2. Knife, damage: 20", end="") input("") print(" 3. Healing kit, heals: 50", end="") input("") print("") print(" The items that fit have been added to your inventory!") input("") i1 = Weapon("M16", 3, 35) i2 = Weapon("Knife", 2, 20) i3 = Food("Healing kit", 0, 50, 1) if self.inv.fits(i1): self.inv.items.append(i1) if self.inv.fits(i2): self.inv.items.append(i2) if self.inv.fits(i3): self.inv.items.append(i3) return True else: return False #Method for supermarket chapter def supermarket_chapter(self): self.clr() print("\n\n") print("----- The Supermarket -----".center(80)) self.sorry_Peter_LG() #Method for gas station chapter def gas_chapter(self): self.clr() print("\n\n") print("----- The Gas Station -----".center(80)) self.sorry_Peter_LG() #Method for chapter in the woods def woods_chapter(self): self.clr() print("\n\n") print("----- The Woods -----".center(80)) self.sorry_Peter_LG() #Method for final chapter of the story def final_chapter(self): self.clr() print("\n\n") print("----- The Final Chapter -----".center(80)) print("") input("") print("After a long journey, you finally make it to the research centre.".center(80)) input("") print((self.name.title()+": Well guys, this is it. I'm going in alone.").center(80)) input("") print("Evan: No, don't leave us!".center(80)) input("") print((self.name.title()+": I have to, it's just too dangerous!").center(80)) input("") self.story_2("As you walk through the door, the noise increases in volume.", "You slowly walk towards the sound.") input("") self.story_3("In the distance, you see a large item on the ground.", "It looks like a powerful weapon!", (self.name.title()+": Better pick it up!")) input("") print("Plasma Rifle (125) has been added to your inventory.".center(80)) input("") rifle = Weapon("Plasma Rifle", 2, 125) if self.inv.fits(rifle): self.inv.items.append(rifle) self.story_3("You slowly open the door..", (self.name.title()+": ......."), (self.name.title()+": Oh. Shit.")) input("") self.save_progress() self.story_2("A huge alien monster stands in the middle of the room.", "Get ready to fight!") input("") final_boss = NPC("Budalt",250,35,"evil") fight = Fight(self.name, self.health, self.inv, self.companions, final_boss) if (fight.start() == True): self.clr() print("\n\n") print((self.name.title()+": Ouch..! I guess this was it..").center(80)) input("") self.clr() print("\n\n") print(("Too bad "+self.name.title()+", Budalt proved to be too strong for you.").center(80)) input("") print("I still hope you enjoyed the game 'Invasion' by Daniel Hartgers.".center(80)) input("") self.finished = True else: self.clr() print("\n\n") print((self.name.title()+": Holy shit..! I did it?!").center(80)) input("") self.clr() print("\n\n") print(("Congratulations, "+self.name.title()+", you did it!").center(80)) input("") print("I hope you enjoyed the game 'Invasion' by Daniel Hartgers.".center(80)) input("") self.finished = True #Method for end screen def end_screen(self): self.clr() print("\n\n") print(" !@#$% & ! $ / ^ {+%# !#}{? =+> & ! ") print(" * $# @ % } & @ @ ^ ` - $# @ ") print(" % % $ # ( ? ; - + >&^# % ~ } % $ # ") print(" # ^ ( $ = ` - $ ~ # * | ^ ( $ ") print(" ^*(%# * +$ # * # )+!? !??<+ $<[ * +$ ") print(" ") print("\n\n") print(("Dear "+self.name.title()+",").center(80)) print("\n") print("Thank you for playing this game!".center(80)) print("You can replay this game if you want to,".center(80)) print("there is probably a lot more to explore!".center(80)) input("") #Main method for running the game def start(self): #Check for savefiles. if not (self.show_loadscreen()): self.show_infoscreen()
def __init__(self): self._tmp_conf = OssimConf (Const.CONFIG_FILE) self.inv = Inventory() self.vlans = []
class nediDiscovery(threading.Thread): _interval = 3600 def __init__(self): self._tmp_conf = OssimConf (Const.CONFIG_FILE) self.inv = Inventory() self.vlans = [] def connectDB(self): self.db = OssimDB() self.db.connect (self._tmp_conf["ossim_host"], self._tmp_conf["ossim_base"], self._tmp_conf["ossim_user"], self._tmp_conf["ossim_pass"]) def closeDB(self): self.db.close() def checkDevices(self): sql = "select name,ip,os,description from nedi.devices;" data = self.db.exec_query(sql) for d in data: ip = self.inet_ntoa(d['ip']) name = d['name'] os = d['os'] sensorIp = self.getOssimSensor() sensorName = 'opensourcesim' descr = d['description'] if ip != "" and name != "" and self.inv.validateIp(ip) and not self.inv.hostExist(ip): self.inv.insertHost(ip, sensorName, name, descr) self.insertOS(ip, os, sensorIp) def chekNodes(self): sql = "select name, ip, mac, device, vlanid from nedi.nodes;" data = self.db.exec_query(sql) for node in data: ip = self.inet_ntoa(node['ip']) print "*** %s %s" % (ip, node['ip']) name = node['name'] mac = node['mac'] device = node['device'] vlanId = node['vlanid'] if not self.inv.hostExist(ip): if ip != "0.0.0.0" and ip != 0 and ip != "0": if name == "-" or name == "": name = ip self.inv.insertHost(ip, self.getOssimSensor(), name, "") #Check if the host is in some hostgroup based on vlan and device for vlan in self.vlans: if device == vlan['device'] and node['vlanid'] == vlan['vlanid']: self.insertHostIntoHostGroup(ip, "%s_%s"%(vlan['vlanname'], vlan['device'])) else: nmac = self.convertMac(mac) ip = self.inv.getIpFromMac(nmac) if ip and not self.inv.hostExist(ip): print ip, nmac if name == "-" or name == "": name = ip self.inv.insertHost(ip, self.getOssimSensor(), name, "") for vlan in self.vlans: if device == vlan['device'] and node['vlanid'] == vlan['vlanid']: self.insertHostIntoHostGroup(ip, "%s_%s"%(vlan['vlanname'], vlan['device'])) def convertMac(self, mac): #080087808f4a #00:0C:29:AD:DA:78 data = "" for i in range(0, len(mac)): if i % 2 == 1: data = data + mac[i].upper() + ":" else: data = data + mac[i].upper() i = i + 1 return data[0:len(data)-1] def insertHostIntoHostGroup(self, ip, hostGroupName): sql = "REPLACE INTO host_group_reference(host_group_name, host_ip) values ('%s', '%s')" % (hostGroupName, ip) self.db.exec_query(sql) logger.debug(sql) def insertOS(self, ip, osStr, sensor): os = None if osStr.find('IOS') != -1: os = 'Cisco' if os: sql = "insert into host_os(ip,os,date,sensor) values (inet_aton('%s'), '%s', now(), inet_aton('%s'))" % (ip, os, sensor) self.db.exec_query(sql) logger.info(sql) def getOssimSensor(self): #FIXXXXX HOW TO GET THE LOCAL SENSOR???????? sql = "select ip from sensor where name = 'opensourcesim';" data = self.db.exec_query(sql) return data[0]['ip'] def vlanToHostGroup(self): #{'device': 'NA_SSEEARGUELLESL4', 'vlanname': 'PROTECCIONES', 'vlanid': 9}] for vlan in self.vlans: name = vlan['vlanname'] if not self.hostGroupExist("%s_%s" % (name, vlan['device'])) and name.find('-default') == -1 and name != "default": logger.info('HostGroup %s doesnt exists' % name) sql = "INSERT INTO ossim.host_group(name, threshold_c, threshold_a) values ('%s_%s', 30, 30)" % (vlan['vlanname'], vlan['device']) data = self.db.exec_query(sql) logger.debug(sql) #FIXME!!!!!!! INSERT host_group_sensor_reference def hostGroupExist(self, name): sql = "select name from ossim.host_group where name = '%s'" % name data = self.db.exec_query(sql) logger.debug(sql) if data == []: return False return True def start(self): while True: self.connectDB() self.launchNediDiscovery() self.getVlans() self.vlanToHostGroup() self.checkDevices() self.chekNodes() self.closeDB() time.sleep(self._interval) #TODO def launchNediDiscovery(self): #Feed nedi seedlist file with device information ip/community self.feedSeedList() #Launch nedi os.system('%s -u %s -U %s' % (nedi_script_file, nedi_seedlist_file, nedi_config_file)) def feedSeedList(self): #sql = "select inet_ntoa(ip) as ip,community from ossim.network_device;" sql = "select ip,community from ossim.network_device;" data = self.db.exec_query(sql) logger.debug(sql) f = open('/etc/nedi/seedlist', 'w') for device in data: logger.info("Detected %s with community %s" % (device['ip'], device['community'])) f.write("%s\t%s\n" % (device['ip'], device['community'])) f.close() def inet_ntoa(self, ip): return socket.inet_ntoa(struct.pack('!L',int(ip))) def getVlans(self): sql = "select * from nedi.vlans;" self.vlans = self.db.exec_query(sql)
class Party : def __init__ (self) : """ initializes the size then creates a party list and inventory """ self._size = 5 # may be subject to change self._party = [] self._backpack = Inventory() def setUpParty (self) : """Sets up a party for x in range(self._size) : self._party.append(Person(self.getName())) """ self._party.append(Person("Iowa Smith")) self._party.append(Person("Dorthy")) self._party.append(Person("Larry Fills")) self._party.append(Person("Laureen Kraft")) self._party.append(Person("Jeb the Forest Man")) def getName (self) : """ Get a name for each party person""" name = raw_input("Enter Name: ") return name def getInitialSize (self) : """returns the initial size of the party""" return self._size def getSize (self) : """returns the current amount of live party members""" count = 0 for person in self.generatePerson (): if not person.deadPerson () : count += 1 return count def getPartyMember(self, num) : """ returns the person in the party """ return self._party[num] def displayParty (self) : """ iterates through the party, displaying each person """ for person in self.generatePerson() : person.displayPerson() def generatePerson (self) : """ a generator to iterate through the list of persons""" for person in self._party : yield person def setPartyHealth (self, num) : """ sets health of all party members to the number passed in """ for person in self.generatePerson () : person.setHealth (num) def incrPartyHealth (self, num) : """ increments health of all party members to the number passed in """ for person in self.generatePerson () : if not person.deadPerson () : person.incrHealth (num) def decrPartyHealth (self, num) : """ decrements health of all party members to the number passed in """ for person in self.generatePerson () : if not person.deadPerson () : person.decrHealth (num) def updateHealth (self) : """ updates health of all party members to the number passed in """ for person in self.generatePerson () : if not person.deadPerson () : person.updateHealth () def updatePartyHealthEffect (self, num) : """ updates the health effect of all party members to the number passed in """ for person in self.generatePerson() : person.updateHealthEffect(num) def death (self) : """sets every person who is dead to a Dead health title""" for person in self.generatePerson () : if person.deadPerson () : person.setHealthTitle ("Dead") def setInventory (self, inventory) : """sets the backpack to the passed in value """ self._backpack = inventory def addToInventory (self, item) : """adds an item to the backpack """ self._backpack.addItem (item) def removeFromInventory (self, item) : """removes an item from the backpack """ self._backpack.removeItem (item) def getCash (self) : """ returns the amount of cash in the backpack""" return self._backpack.getCash() def updateCash (self, num) : """ updates the amount of cash in the backpack""" self._backpack.updateCash(num) def getFood (self) : """ returns the amount of cash in the backpack""" return self._backpack.getFood() def updateFood (self, num) : """ update the amount of food in the backpack""" self._backpack.updateFood(num) def setFood (self, num) : self._backpack.setFood (num) def getInventory (self) : """ returns backpack or the inventory of the party""" return self._backpack def addPerson (self, person) : """ adds a person to the party""" #currently for unittest self._party.append(person) def checkPartyDead(self): for person in self.generatePerson () : if not person.deadPerson () : return False return True def setDead(self) : for person in self.generatePerson () : person.setHealthTitle ("Dead") person.setHealth (0)
def __init__ (self) : """ initializes the size then creates a party list and inventory """ self._size = 5 # may be subject to change self._party = [] self._backpack = Inventory()
from Inventory import * from InstrumentSpec import * from InstrumentType import * from Builder import * from Type import * from Wood import * from Style import * inventory = Inventory() # add guitar spec = {} spec['instrument_type'] = InstrumentType.GUITAR spec['builder'] = Builder.FENDER spec['type'] = Type.ELECTRIC spec['back_wood'] = Wood.ALDER spec['top_wood'] = Wood.ALDER spec['num_strings'] = 6 spec['model'] = "Stratocastor" instrument_spec = InstrumentSpec(spec) inventory.add_instrument("V95693", 1499.95, instrument_spec) del spec, instrument_spec spec = {} spec['instrument_type'] = InstrumentType.GUITAR spec['builder'] = Builder.OLSON spec['model'] = "Stratocastor" spec['type'] = Type.ACOUSTIC spec['top_wood'] = Wood.MAPLE
def __init__(self,world, name, arm, helm, leg, body, team='Green', AI=None, health=100, player=False):#construct requires name, arm pic, helm pic, leg pic, body pic, with options team, AI function, health and wheter or its a player self.over = world.over self.world = world self.body = BodyPart.bodyPart(body,world)#creates the necessary limbs self.armLeft = BodyPart.bodyPart(arm,world) self.armRight = BodyPart.bodyPart(arm,world) self.helm = BodyPart.bodyPart(helm,world) self.legLeft = BodyPart.bodyPart(leg,world) self.legRight = BodyPart.bodyPart(leg,world) self.body.x = self.helm.x#sets the body parts to the proper co-ordinates self.body.y = self.helm.y + self.helm.size[1] self.armLeft.x = self.body.x - (self.body.size[0]//2) self.armLeft.y=self.body.y self.legLeft.x = self.body.x self.legLeft.y = self.body.y + self.body.size[1] self.legRight.x = self.legLeft.x + (self.legLeft.size[0] // 2) self.legRight.y = self.legLeft.y self.armRight.x = self.armLeft.x + self.body.size[0] self.armRight.y = self.armLeft.y self.name = name self.xVel = 0#x and y velocity self.yVel = 0 self.x = self.armLeft.x#initializes x to the left arm x self.y = self.helm.y# and y to the helm's y co ordinate self.size = ((self.armLeft.size[0]//2) + self.body.size[0] + (self.armRight.size[0]//2), self.helm.size[1] + self.body.size[1] + self.legLeft.size[1])# calculates the size of the character self.level = 1# initializes the character's level to one self.speedLimit = 5#maximum speedlimit self.faceRight = True#facing right self.isJump = False#jumping self.jumpSpeed = self.size[1]//3#jump speed is a third of the objects's size self.attackSpeed = 5#rotation factor for attacks self.health = health#sets the health self.maxHealth = health self.weapon = None#stores a weapon object self.attacking = False#bool for attacking self.team = team self.invincible = False#used for after taking damage self.flashDelay = 0#amount of flashes after taking damage self.flashAmount = 0 self.damage = 5#initializes damage to 5 self.baseDamage = 5#damage without level modifiers self.damage = self.damage + (self.damage * (self.level / 10))#modifies damage to be based on the characters level self.player = player self.headingToPoint = False#boolean for if the character is heading to a point in the world self.goal = (0,0)#the goal they are trying to get to self.activeSpell = False#if they have a spell flying/doing whatever in the game self.spellDelay = 0#delay for shooting spells, dependant on the spell type, Spells.py self.faceTile = False#if the character is walking into a tile self.dead = False#self explanitory, but if the player is dead self.exp = 0#current experience, influences when the character goes up a level self.expToLevel = 50#the experience to the next level self.moveRight = True#wheter or not the character can move right, unused probably self.moveLeft = True self.target = False#unused also i think self.row = self.x//32#current row in the game world self.column = self.y//32 self.fleeing = False#if they are fleeing(AI.villager) self.money = 0#current money self.spell = None#current spell function self.AI = AI#current AI function self.control = True#if the character can be controlled(only used fo the player) self.ID = genID()#calculates the character specific ID self.AIGoal = None#the goal for the AI, used by AI.py self.inv = Inventory.objectInventory(self.world.itemList) self.selectedSlot = 0 self.weaponID = None self.tileHitTime = time.time() self.tileHitDelay = 0.4 self.baseTileHitPower = 5 self.damagedTile = (0,0,0) self.drawCrack = None self.hitRad = (3,5) self.openInv = False self.skills = [] self.mining = Mining.mining(self,self.over) self.woodcutting = Woodcutting.woodcutting(self,self.over) self.skills.append(self.mining) self.skills.append(self.woodcutting) self.AIPlaceGoals = [] self.villageRole = None self.mustBuild = None self.placeDelay = 0.3 self.placeTime = time.time() self.crafting = Crafting.crafting(self.inv,self.world.itemList) self.craftable = [] self.toCraft = (None,None) self.lastCraft = None self.toGive = None self.toTake = (None,None) self.currentBuildingProject =None self.requiredResources = []