Пример #1
0
 def preloadContent(self):
   Item.preloadContent(self)
   for reply in self.children['replies']:
     if reply.posttime > self.lastreply:
       self.lastreply = reply.posttime
     if reply.lastreply > self.lastreply:
       self.lastreply = reply.lastreply
Пример #2
0
def loop(e):
	global player, itemLayer, addItemSpeed, addItemSpeedIndex

	player.loop()

	for o in itemLayer.childList:
		o.loop()

	# control the speed of adding a item
	if addItemSpeedIndex < addItemSpeed:
		addItemSpeedIndex += 1

		return

	addItemSpeedIndex = 0

	# get random item
	randomNum = random.randint(0, 7)

	# add a item
	item = Item(dataList["item" + str(randomNum)])
	item.index = randomNum
	item.x = int(random.randint(30, stage.width - 100))
	itemLayer.addChild(item)
	# add ourselves events
	item.addEventListener(Item.EVENT_ADD_SCORE, addScore)
	item.addEventListener(Item.EVENT_GAME_OVER, gameOver)
Пример #3
0
 def preloadContent(self):
   Item.preloadContent(self)
   #weed out children not on date, if date is set:
   if self.date[0] != None:
     temp = []
     for child in self.children['stories']:
       if int(child.yr) == self.date[0]:
         if self.date[1] == None or self.date[1] == int(child.mo_num):
           if self.date[2] == None or self.date[2] == int(child.da):
             temp.append(child)
     self.children['stories'] = temp
   #reverse sort order
   self.num_stories = len(self.children['stories'])
   self.children['stories'] = self.children['stories'][-(self.start+self.item_limit):(self.num_stories-self.start)]
   self.children['stories'].reverse()
   #set last update time
   if len(self.children['stories']) > 0:
     import datetime
     import time
     import Globals
     self.posttime = self.children['stories'][0].posttime
     date = datetime.datetime.fromtimestamp(self.posttime, Local.Local)
     self.ISOtime = date.isoformat() #TODO: no time set if no stories!
     self.yr = "%0.4d"%(date.year,)
     self.mo_num = "%0.2d"%(date.month,)
     self.mo = Globals.months[date.month]
     self.da = "%0.2d"%(date.day,)
     self.dw = Globals.days[time.localtime(self.posttime)[6]]
     self.hr = "%0.2d"%(date.hour,)
     self.min = "%0.2d"%(date.minute,)
     self.timezone = date.tzname()
Пример #4
0
 def loadTemplate(self):
   for update in self.children['updates']:
     update.blog = self.blog
     update.story = self
   for comment in self.children['comments']:
     comment.blog = self.blog
     comment.story = self
   Item.loadTemplate(self)
Пример #5
0
 def start ( self ):
     """Creates all game object instances. No return.
     
     This is where specific Rooms, Items, Cotrollers, and pygame essentials are
     created.
     
     """
     if(DEBUG):print("Starting");
     pygame.init()
     #Create display
     self.DISPLAY_SURF = pygame.display.set_mode(self.SIZE)
     self.DISPLAY_SURF.fill((0,0,0))
     #Create Pygame objects here
     self.clock = pygame.time.Clock()
     #Player
     self.player = Character(initial_position = [40,600])
     #Veiw Manager
     self.veiwMan = ViewManager([255,255,255], [5,5], [self.WIDTH-10, self.HEIGHT-10], self.player) #Puts a white VeiwManager on screen
     #Control Manager
     self.conMan = ControlManager()
     self.conMan.setAvatar(self.player)
     #Creating Rooms
     greenRoom = pygame.sprite.Sprite()
     greenRoom.image = pygame.Surface([1000, 640])
     greenRoom.rect = greenRoom.image.get_rect()
     greenRoom.image.fill([0,255,0])
     self.room1 = Room(greenRoom, self.player) #Sets background to greenRoom and avatar to self.player
     
     grayRoom = pygame.sprite.Sprite()
     grayRoom.image = pygame.Surface([1000, 640])
     grayRoom.rect = grayRoom.image.get_rect()
     grayRoom.image.fill([100,100,100])
     self.room2 = Room(grayRoom, self.player)
     
     #Creating items
     self.box = Item([400, 600])
     self.box.setTouchEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room2}))
     self.box2 = Item([200, 600])
     self.box2.setInteractEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room1}))
     self.room1.addObject(self.box)
     self.room2.addObject(self.box2)
     self.itemGroup = pygame.sprite.RenderPlain(self.box,self.box2)
     
     #Making Text
     #This is not critical code
     if(pygame.font.get_init):
         hello = pygame.font.Font(None,64)
         hello = hello.render("Press Space", False, [0,0,0])
         x,y = self.veiwMan.rect.center
         x = x - (hello.get_width()/2)
         y = y - (hello.get_height()/2)
         self.veiwMan.image.blit(hello, [x,y])
     
     pygame.display.flip()
     self.RUNNING = True
Пример #6
0
 def loadContent(self):
   Item.loadContent(self)
   if not self.__dict__.has_key('title'): #if it hasn't already been loaded
     f = file(os.path.join(os.path.join(Config.update_path, self.path), self.filename))
     self.title = f.readline().strip()
     self.body = ''
     line = f.readline()
     while(line != ''):
       self.body += line
       line = f.readline()
     f.close()
Пример #7
0
 def preloadContent(self):
   Item.preloadContent(self)
   #get last comment and update from children:
   self.lastupdate = self.lastcomment = 0
   for update in self.children['updates']:
     if update.posttime > self.lastupdate:
       self.lastupdate = update.posttime
   for comment in self.children['comments']:
     if comment.posttime > self.lastcomment:
       self.lastcomment = comment.posttime
     if comment.lastreply > self.lastcomment:
       self.lastcomment = comment.lastreply
Пример #8
0
def parse_html(html_page, DPid):
    soup = BeautifulSoup(html_page)
    if soup == None:
        return

    title = soup.h1
    goodname = ""
    for div in title.findAll("div"):
        if len(div.findAll("a")) > 0:
            goodname = div.find("a").string

    tbl = soup.find("table", id="productReviews")
    if tbl == None:
        print goodname + ",pageid:" + DPid + ", DO NOT HAVE COMMENTS"
        return False

    for div in tbl.findAll("div", style="margin-left:0.5em;"):
        # get star rank
        spritespan = div.find("span", attrs={"class": re.compile("swSprite s_star_\d_\d")})
        star_search = re.search("swSprite s_star_(.*)_(.*)", spritespan.get("class"), re.IGNORECASE)
        star = 5.0
        if star_search:
            star = float(star_search.group(1)) + 0.1 * float(star_search.group(2))

        # get userlink, username and user comment
        userlnk = div.find("a").get("href")
        username = div.find("span", style="font-weight: bold;").renderContents()
        comment = div.find(
            "div", attrs={"class": "reviewText"}
        ).renderContents()  # .decode('utf-8')#.replace('<br />', '\r\n')

        it = Item(DPid, goodname, username, userlnk, comment, star)
        print it.to_string().encode("utf-8")

        if TEST:
            with open("tmp.txt", "a") as ftmp:
                ftmp.write(it.to_string().encode("utf-8"))
                ftmp.write("\r\n")
        else:
            store_item(it)

    pagespan = soup.find("span", attrs={"class": "paging"})
    if pagespan == None:
        return False

    for a in pagespan.findAll("a"):
        if "下一页" in a.string.encode("utf-8"):
            print "Has next page"
            return True
    return False
Пример #9
0
	def main(self):
		# 1)  #init
		pygame.init()
		pygame.key.set_repeat(25,25)
		self.slowmotion = 100
		# self.screen = screen
		self.size = self.width, self.height = 640, 480
		self.black = 0, 0, 0
		self.counter = 0
		#screen size
		self.screen = pygame.display.set_mode(self.size)
		#create game clock
		#self.clock = pygame.time.Clock()

		#2) set up game objects
		self.level = 1
		self.hearts = 5
		self.fire_count = 0
		self.health_pickup_array = []
		self.laser_array = []
		self.enemies_spawned = False
		self.enemy_array = []
		self.enemy_laser_array = []
		self.player = Player(self)
		self.background = Background(self)
		self.healthbar = Healthbar(self)
		self.gameover = GameOver(self)
		self.cat = Sushi_Cat(self)
		self.octoking = OctoKing(self)
		self.item = Item(self)
Пример #10
0
 def __init__(self, path, filename, flavour=None, opts=None):
   Item.__init__(self, path, filename, flavour, opts)
   self.classType = 'comment'
   self.child_count = 1 #count yerself
   #a Comment has children: threads
   self.children['replies'] = []
   #find children, if any.
   root, ext = os.path.splitext(filename)
   dir = os.listdir(os.path.join(Config.comment_path, path))
   for item in dir:
     i_root, i_ext = os.path.splitext(item)
     i_ext = i_ext[1:] #remove initial '.'
     i_suf, tmp = os.path.splitext(i_root)
     if (i_ext == Config.comment_extension) and (root ==i_suf) and (item != filename):
       self.children['replies'].append(Comment(path, item, flavour, opts))
       self.child_count += self.children['replies'][-1].child_count
   self.lastreply = 0
Пример #11
0
  def loadContent(self):
    Item.loadContent(self)
    if not self.__dict__.has_key('title'): #if it hasn't already been loaded
      f = file(os.path.join(os.path.join(Config.comment_path, self.path), self.filename))
#      self.title = self.makesafe(f.readline().strip())
      self.title = f.readline().strip()
      self.author = f.readline().strip()
      self.link = f.readline().strip()
      self.body = ''
      self.blog_name = ''
      lines = f.readlines()
      f.close()
      p = CommentParser()
      for line in lines:
        p.feed(line)
      self.body = p.parsedbuffer
      p.close()
Пример #12
0
  def loadContent(self):
    Item.loadContent(self)
    if not self.__dict__.has_key('title'): #if it hasn't already been loaded
      #might be a comment that's being referred to...need to guess at story name
      #by stripping off extensions
      try:
        f = file(os.path.join(os.path.join(Config.story_path, self.path), self.filename))
      except:
        self.template = ''
        return
      self.title = f.readline().strip()
      self.body = ''
#      p = CommentParser()
      lines = f.readlines()
      f.close()
      for line in lines:
        self.body += line
Пример #13
0
 def parse_options(cls, **kwargs):
     result = Item.parse_options(** kwargs)
     kw_defaults = {'loadOnDemand': True}
     for key, value in kw_defaults.iteritems():
         if kwargs.has_key(key):
             result[key] = kwargs[key]
         else:
             result[key] = value
     return result
Пример #14
0
  def __init__(self, path, filename, flavour=None, opts=None):
    Item.__init__(self, path, filename, flavour, opts)
    self.category = self.path
    self.classType = 'story'
    self.num_comments = 0
    #a Story has children: updates and comments
    self.children['updates'] = []
    self.children['comments'] = []
    #first, see if URL is pointing to an extant story. if not, see if
    #we've been pointed to a comment/reply.
    if not os.path.exists(os.path.join(os.path.join(Config.story_path, self.path), self.filename)):
      found = False
      temp = os.path.splitext(self.filename)[0]
      while temp != self.filename.split('.')[0]:
        temp = os.path.splitext(temp)[0]
        if os.path.exists(os.path.join(os.path.join(Config.story_path, self.path), temp+'.'+Config.story_extension)):
          found = True
          self.filename = temp+'.'+Config.story_extension
          self.name, self.ext = os.path.splitext(self.filename)
          self.path_name = os.path.join(self.path, self.name)
          break
      if found == False:
        self.name = None
        return

    #find children, if any.
    root, ext = os.path.splitext(self.filename)
    if os.path.exists(os.path.join(Config.comment_path, path)):
      dir = os.listdir(os.path.join(Config.comment_path, path))
      for item in dir:
        i_root, i_ext = os.path.splitext(item)
        i_ext = i_ext[1:] #remove initial '.'
        if (i_ext == Config.comment_extension) and (root == os.path.splitext(i_root)[0]):
          self.children['comments'].append(Comment(path, item, flavour, opts))
          self.num_comments += self.children['comments'][-1].child_count

    if os.path.exists(os.path.join(Config.update_path, path)):
      dir = os.listdir(os.path.join(Config.update_path, path))
      for item in dir:
        i_root, i_ext = os.path.splitext(item)
        i_ext = i_ext[1:] #remove initial '.'
        if (i_ext == Config.update_extension) and (root == os.path.splitext(i_root)[0]):
          self.children['updates'].append(Update(path, item, flavour, opts))
Пример #15
0
    def getPage(self, url, shop_home_url):
        position = 1
        i = 1
        max_page = 0
       
        asyn_url = ''
        i_url = url
        refers = shop_home_url
        result_s = self.get_asyn_data(i_url, refers, shop_home_url)
        m = re.search(r'<b class="ui-page-s-len">\d+/(\d+)</b>', result_s, flags=re.S) 
        if m:
            max_page = int(m.group(1))
        print '# page num:', max_page
        while i <= max_page:
            m = re.search(r'<div class="J_TItems">(.+?)<div class="pagination">', result_s, flags=re.S)
            if m:
                items_s = m.group(1)
                p = re.compile(r'<dl class=".+?".+?data-id="(.+?)">.+?<dd class="detail">\s*<a class="item-name".+?href="(.+?)".+?>(.+?)</a>\s*<div class="attribute">\s*<div class="cprice-area">\s*<span class="symbol">(.+?)</span>\s*<span\s*class="c-price">(.+?)</span>\s*</div>.+?</dl>')
                j = 1
                for item in p.finditer(items_s):
                    item_id, url_s, item_name, price_symbol, price = item.group(1), item.group(2), Common.htmlDecode(item.group(3).strip()), item.group(4).strip(), item.group(5).strip()
                    if url_s.find('http') == -1:
                        item_url = 'http:' + url_s
                    else:
                        item_url = url_s
                    print '### item ###'
                    print '# item val:', item_id, item_name, price, item_url
                    item = Item()
                    item.parserTM((item_id, item_name, price, item_url, i_url, self.begin_time))
                    print '# item info:',item.outItemSql()
                    self.mysqlAccess.insert_parser_item_info(item.outItemSql())
                    time.sleep(2)
            
            refers = i_url
            if i_url.find('pageNo=') == -1:
                i_url = re.sub(r'&tsearch=y','&pageNo=%d&tsearch=y#anchor' % i, refers)
            else:
                i_url = re.sub(r'&pageNo=\d+&','&pageNo=%d&' % i, refers)

            i += 1
            time.sleep(2)
            result_s = self.get_asyn_data(i_url, refers, shop_home_url)
Пример #16
0
 def __init__(self):
     self.item_list = []
     for file_ref in FILE_LIST:
         config = ConfigParser.ConfigParser()
         config.readfp(open(file_ref))
         name = config.get('item', 'name')
         image = config.get('item', 'image')
         special = config.getboolean('item', 'special')
         desc = config.get('item', 'desc')
         effect = config.get('item', 'effects')
         slot = config.get('item', 'slot')
         item = Item(name, image, special)
         item.slot = slot
         item.desc = desc
         if effect != "None":
             effect_list = effect.split(',')
             for e in effect_list:
                 key, value = e.split(':')
                 item.effects[key] = value
         self.item_list.append(item)
Пример #17
0
class PlotTest(unittest.TestCase):

    def setUp(self):
        self.customer = Customer("Vesa", "Kuoppala")
        self.item = Item("Ball")
        self.quantities = np.arange(0, 8, 1)

    def tearDown(self):
        None

    def test_customer_creates_table_for_quantities(self):

        # Add data to list
        data = []

        for i in self.quantities:
            data_row = []
            data_row.append(i)
            self.item.set_price(i)
            data_row.append(self.item.price)
            data_row.append(self.customer.buy(self.item, i))
            data.append(data_row)

        # Define column and row labels for table
        columns = ('Q', 'P', 'T')

        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)

        the_table = ax.table(
            cellText=data,
            colLabels=columns,
            loc='center'
        )

        plt.show()
Пример #18
0
  def __init__(self, path='', filename=None, flavour=None, opts=None):
    Item.__init__(self, path, filename, flavour, opts)
    self.classType = 'blog'
    self.children['stories'] = []
    #check if a specific date was specified:
    if opts != None and opts.has_key('date'): self.date = opts['date']
    else: self.date = [None,None,None]
    #find children, if any
    if filename != None and filename != 'index.'+Config.story_extension:
      s = Story(self.path, filename, flavour, opts)
      if s.name != None:
        self.children['stories'].append(s)
    else:
      lenp = len(Config.story_path)+1
      for root, dirs, files in os.walk(os.path.join(Config.story_path,self.path)):
        for file in files:
          i_root, i_ext = os.path.splitext(file)
          i_ext = i_ext[1:] #remove initial '.'
          if (i_ext == Config.story_extension):
            self.children['stories'].append(Story(root[lenp:], file, flavour, opts))

    self.item_limit = Config.item_limit
    if opts != None and opts['form'].getfirst('item_limit', '') != '':
      self.item_limit = int(opts['form'].getfirst('item_limit',''))
    self.start = 0
    if opts != None and opts['form'].getfirst('start', '') != '':
      self.start = int(opts['form'].getfirst('start', ''))
    self.post_str = ''
    self.post_str2 = ''
    if opts != None and len(opts['form'].keys()) >0:
      key = opts['form'].keys()[0]
      self.post_str += '?'+key+'='+opts['form'].getfirst(key)
      self.post_str2 += '&'+key+'='+opts['form'].getfirst(key)
      for key in opts['form'].keys()[1:]:
        self.post_str += '&amp;'+key+'='+opts['form'].getfirst(key)
        self.post_str2 += '&amp;'+key+'='+opts['form'].getfirst(key)
Пример #19
0
 def on_client_itemlist(self, client, item_list):
     if not self.hasitems:
         self.items = []
         i = 0
         for item_dict in item_list:
             n = item_dict['item_index']
             while i < n:
                 self.items.append(Item(i, 0, -1))
                 i += 1
             
             spawndelay = Item.spawn_delay(item_dict['item_type'], len(self.clients))
             
             self.items.append(Item(n, item_dict['item_type'], spawndelay))
             i += 1
             
         self.hasitems = True
    def __init__(self):
        """ Room creation """
        self.rooms = Rooms()
        
        """ Player and Enemy creation """
        self.player = Player(100, 100, 1, 0, 100)
        Utils.read_json(self.ENEMY_REL_PATH)
        self.enemies = Enemy.create_from_filedata()

        """ Item creation """
        Utils.read_json(self.ITEM_REL_PATH)
        self.items = Item.create_from_filedata()

        """ Room creation """
        Utils.read_json(self.ITEM_REL_PATH)
        self.rooms = Rooms()
        Rooms.create_from_filedata(self.rooms)
Пример #21
0
	def SubmitClicked(self):
		
		if self.NameEntry.get() != '' and self.PriceEntry.get() != '':
			newItem = Item(self.NameEntry.get(), self.PriceEntry.get())
			print self.NameEntry.get() + self.PriceEntry.get()
			for entryElement in self.EntryDict.keys():
				if self.EntryDict[entryElement].get() != '':
					print self.EntryDict[entryElement].get()
					newItem.addAttr(entryElement.lower(), self.EntryDict[entryElement].get())
			if self.MiscAttrEntry.get() != '':
				newItem.addAttr(self.MiscAttrEntry.get().lower(), self.MiscValueEntry.get())
				if 'description' == self.MiscAttrEntry.get().lower():
					self.Redis.setAddAllDescriptionKeywords(newItem.tokenizeDescription(),newItem._attributes['name'])
		self.Redis.hashAddItem(newItem)
Пример #22
0
    def getItem(self, nameMD5, owner, category):
        try:
            with self.connection.cursor() as cursor:
                sql = "SELECT `nameMD5`, `owner`, `category`, `price`, `quantity` FROM `items_light` WHERE `nameMD5`=%s AND `owner`=%s AND `category`=%s"
                cursor.execute(sql, (nameMD5, owner, category,))
                result = cursor.fetchone()
                if result is None:
                    return None

                item = Item()
                item.name = self.getItemName(result['nameMD5'])
                item.owner = result['owner']
                item.category = result['category']
                item.price = result['price']
                item.quantity = result['quantity']
                return item

        except Exception as error:
            print(error)
            return None
Пример #23
0
    def getAllItems(self):
        allItems = {}
        allNames = self.getAllItemNames()
        try:
            sql = "SELECT `nameMD5`, `owner`, `category`, `price`, `quantity` FROM `items_light`"
            cursor = self.connection.cursor()
            cursor.execute(sql)
            for result in cursor:
                item = Item()
                item.name = allNames.get(result['nameMD5'], None)
                item.owner = result['owner']
                item.category = result['category']
                item.price = result['price']
                item.quantity = result['quantity']
                item.nameMD5 = result['nameMD5']
                allItems[str(result['owner']) + '_' + result['nameMD5']] = item

            cursor.close()

            return allItems

        except Exception as error:
            print(error)
            return None
Пример #24
0
 def setUp(self):
     self.customer = Customer("Vesa", "Kuoppala")
     self.item = Item("Ball")
     self.quantities = np.arange(0, 8, 1)
Пример #25
0
 def afterEditRow(self, fname, rfname, rownr):
     afterEditRow(self, fname, rfname, rownr)
     record = self.getRecord()
     if (fname == "Concepts"):
         if (rfname in ("Price","Qty","RowTotal")):
             row = record.Concepts[rownr]
             row.sumUp(record)
             record.sumUp()
         elif (rfname == "ArtCode"):
             row = record.Concepts[rownr]
             if (row.ArtCode):
                 from Item import Item
                 itm = Item.bring(row.ArtCode)
                 if (not itm):
                     #Codigo
                     res = getString("Artículo Inexistente, Ingrese Codigo")
                     if (not res): return
                     if (len(res) != 13):
                         if (not " " in res):
                             message("Codigo Inválido")
                             return
                         prefix,code = res.split(" ")
                         icode = prefix+code.rjust(12,"0")
                     else:
                         icode = res
                     #Descripcion
                     res = getString("Ingrese Descripción")
                     if (not res): return
                     iname = res
                     #Grupo
                     gquery = Query()
                     gquery.sql  = "SELECT * FROM ItemGroup ORDER BY Name "
                     if (gquery.open()):
                         glist = []
                         for gline in gquery:
                             glist.append("%s:%s" %(gline.Name,gline.Code))
                         res = getSelection("Grupo de Articulos", tuple(glist))
                         if (not res): return
                         igroup = res.split(":")[1]
                     #Unidad de Medida
                     uquery = Query()
                     uquery.sql  = "SELECT * FROM Unit ORDER BY Name "
                     if (uquery.open()):
                         ulist = []
                         for uline in uquery:
                             ulist.append("%s:%s" %(uline.Name,uline.Code))
                         res = getSelection("Unidad de Medida", tuple(ulist))
                         if (not res): return
                         iunit = res.split(":")[1]
                     #Precio
                     res = getString("Precio")
                     if (not res): return res
                     iprice = float(res)
                     ###
                     itm = Item()
                     itm.Code = icode
                     itm.Name = iname
                     itm.ItemGroup = igroup
                     itm.Unit = iunit
                     res = itm.save()
                     if (not res): 
                         message("No se pudo crear Artículo. %s" %(res))
                         return res
                     else:
                         commit()
                     icost = itm.getItemCost()
                     icost.SubCost = iprice
                     res = icost.save()
                     if (not res):
                         message("No se pudo crear Costo de Artículo. %s" %(res))
                         return res
                     else:
                         commit()
                     row.ArtCode = icode
                     row.pasteArtCode(record)
     elif (fname == "Payments"):
         row = record.Payments[rownr]
         if (rfname in ("Amount")):
             record.sumUp()
Пример #26
0
from Game import Game
from Map import Map
from Item import Item
from Character import Character

my_map = Map()
game = Game()
my_item = Item()
my_character = Character()

game.play(my_map, my_character, my_item)
Пример #27
0
 def render(self):
   return Item.render(self)
Пример #28
0
import UI
from Place import Place
from Item import Item
from Player import Player

# all init for rooms/items goes here
place1 = Place(name='Place', description='A nice place')
item1 = Item(name='Item', description='An item')

# you can also create things inline to put them inside of rooms
# however, they will no longer be available to the debugger without a
# prefix if you choose to do this (of course you can still access them
# from .get()ing them from the place)
place2 = Place(name='Place2',
               description='A very nice place',
               things_here=[Item(name='Item2', description='Item in a room!')])


def start_adventure(player):
    '''
    You should do any one-time prints here and set the initial location of
    the player. Suggested code is below.
    '''
    UI.println('Game beginning')

    # this line is important if you want debugging to work
    player.globals = globals()

    # set initial location of player
    player.location = place1
if __name__ == "__main__":
    lista: List = List(3)

    # This will throw an exception
    # lista.go_ahead_positions(3)

    # This will print None
    print(lista.access_actual())

    # This will print True
    print(lista.is_empty())

    # This will print False
    print(lista.is_full())

    item1 = Item(123)
    lista.insert_at_the_start(item1)
    # This will print 123
    print(lista.access_actual().value)

    item2 = Item(456)
    lista.insert_at_the_end(item2)
    lista.go_to_last()
    # This will print 456
    print(lista.access_actual().value)

    item3 = Item(789)
    lista.insert_at_the_start(item3)
    lista.go_to_first()
    # This will print 789
    print(lista.access_actual().value)
Пример #30
0
            self.data = data
        c.update(self)
        return c

    def keys(self):
        return self.data.keys()

    def items(self):
        return self.data.items()

    def iteritems(self):
        return self.data.iteritems()

    def iterkeys(self):
        return self.data.iterkeys()

    def itervalues(self):
        return self.data.itervalues()

    def values(self):
        return self.data.values()

    def has_key(self, key):
        return key in self.data

    def pop(self, key, *args):
        return self.data.pop(key, *args)


Item.Register(Dict)
Пример #31
0
    def test_xmlBuilder(self):
        item1 = Item("id", 1)
        item1.append("lastName", "Muster")
        item1.append("firstName", "Max")

        item2 = Item("id", 2)
        item2.append("lastName", "Müller")
        item2.append("firstName", "Ute")

        builder = XmlBuilder()
        builder.append(item1)
        builder.append(item2)

        director = Director(builder)
        xml = director.construct()
        self.assertEqual(
            "<list><item><id>1</id><lastName>Muster</lastName><firstName>Max</firstName></item><item><id>2</id><lastName>Müller</lastName><firstName>Ute</firstName></item></list>",
            xml)
Пример #32
0
    def keyPressed(self, keyCode, modifier):
        if self.isKeyPressed(pygame.K_i):
            #show player stats
            self.p.printStats()

       
        if self.isKeyPressed(pygame.K_PERIOD):
            #show instructions
            self.showInstructions = not self.showInstructions
            self.gameStart = True
            
        if self.isKeyPressed(pygame.K_RETURN):
            #start game
            self.gameStart = True
        
        if self.isKeyPressed(pygame.K_l):
            #buff stats and level for demo
            self.p.lvlNum = 10
            self.p.str = 100
            self.p.hpBar.max = 1000
            self.p.hpBar.curr = 1000


        
        if self.isKeyPressed(pygame.K_o):
            #creates boss
            x = random.randint(0,self.width//self.size*self.size)
            y = random.randint(0,self.height//self.size*self.size)
            self.b = Boss(x,y,self.size,self.grid, self.p.lvlNum)
            self.monsters.add(self.b)
            self.bossAppear = True

        
        if self.isKeyPressed(pygame.K_t):
            #add stick
            x = random.randint(0,self.width)//self.size*self.size
            y = random.randint(0,self.height- self.menuSize)//self.size*self.size
            self.items.add(Item(x, y))
            
        if self.isKeyPressed(pygame.K_y):
            #add potion
            x = random.randint(0,self.width)//self.size*self.size
            y = random.randint(0,self.height- self.menuSize)//self.size*self.size
            self.items.add(Potion(x, y))
        
        if self.isKeyPressed(pygame.K_f):
            #pick up items
            for item in self.items:
                if self.p.x == item.x and self.p.y == item.y:
                    self.bag.addItem(item)
                    if not self.bag.isFull:
                        item.onMap = False
            
        if self.isKeyPressed(pygame.K_r) and self.gameOver:
            print(True)
            #restart
            self.init()

        #Keypressed wasd controls player movement and scrolling
        if self.isKeyPressed(pygame.K_a):
            if self.p.x - self.p.speed < self.width/4 and self.map.rect.left != 0:
                if self.grid[(self.p.x//self.size) - self.scrollX - 1][int(self.p.y //self.size) - self.scrollY + 0][2] == 0:
                    self.scrollX += 1
                    self.isScroll[2] = True
                    
                        
        elif self.isKeyPressed(pygame.K_d):
            if self.p.x + self.p.speed > self.width * 3/4 and self.map.rect.right != self.width:
                if self.grid[(self.p.x//self.size) - self.scrollX + 1][int(self.p.y //self.size) - self.scrollY + 0][2] == 0:
                    self.scrollX -= 1
                    self.isScroll[3] = True
                    
     
        elif self.isKeyPressed(pygame.K_w):
            if self.p.y < self.height/4 and self.map.rect.top != 0:
                if self.grid[(self.p.x//self.size) - self.scrollX + 0][int(self.p.y //self.size) - self.scrollY - 1][2] == 0:
                    self.scrollY  += 1
                    self.isScroll[0] = True
                    

        elif self.isKeyPressed(pygame.K_s):
            if self.p.y > self.height//2 and self.map.rect.bottom != self.height - self.menuSize:
                if self.grid[(self.p.x//self.size) - self.scrollX + 0][int(self.p.y //self.size) - self.scrollY + 1][2] == 0:
                    self.scrollY -= 1
                    self.isScroll[1] = True
Пример #33
0
from Item import Item
item1 = Item(13, 12, 2020, "monitor", 93.0, "college")

item1.print_item()

# I want to save each month as a text file

# item_file = open('item_file.txt', 'r')
# item_file.close()

from datetime import datetime

current_year = datetime.today().year
current_day = datetime.today().day
current_month = datetime.today().month

print(current_year)
print(current_day)
print(current_month)

# Python project to keep better track of my finances and become a more experienced programmer.
Пример #34
0
 def test_basic(self):
     item = Item('product1', 100.5, type='red')
     self.assertEqual(item.name, 'product1')
     self.assertEqual(item.price, 100.5)
     self.assertEqual(item.type, 'red')
Пример #35
0
 def test_skip_optional(self):
     item = Item('product1', 100.5, size='M')
     self.assertFalse(hasattr(item, 'size'))
Пример #36
0
    def test_jsonBuilder(self):
        item1 = Item("id", 1)
        item1.append("lastName", "Muster")
        item1.append("firstName", "Max")

        item2 = Item("id", 2)
        item2.append("lastName", "Müller")
        item2.append("firstName", "Ute")

        builder = JsonBuilder()
        builder.append(item1)
        builder.append(item2)

        director = Director(builder)
        json = director.construct()
        self.assertEqual(
            '{{"id":"1", "lastName":"Muster", "firstName":"Max"},{"id":"2", "lastName":"Müller", "firstName":"Ute"}}',
            json)
Пример #37
0
def GetAsos(Flag: bool):
    if Flag == True:
        Url: str = "https://www.asos.com/ru/men/rasprodazha/tufli-i-sportivnaya-obuv/cat/?cid=1935&currentpricerange=390-16390&nlid=mw|%D0%B0%D1%83%D1%82%D0%BB%D0%B5%D1%82|%D1%81%D0%BE%D1%80%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D1%82%D1%8C%20%D0%BF%D0%BE%20%D1%82%D0%B8%D0%BF%D1%83%20%D0%BF%D1%80%D0%BE%D0%B4%D1%83%D0%BA%D1%82%D0%B0&refine=attribute_1047:8606|brand:17,15723,18,16346,15565,12136,13688,298,105,14513,131,156,3060,2943,15139,12664,391,401,13073,499,2986,15176,13623,15177,589,2988,16284,3672,3029,765"
    else:
        Url: str = "https://www.asos.com/ru/men/autlet/cat/?cid=27396&currentpricerange=190-47290&nlid=mw|аутлет|сортировать%20по%20типу%20продукта&refine=attribute_10992:61380,61382,61377|attribute_1047:8405,8401,8407,8415,8391|brand:17,18,16346,15565,12111,12136,13688,298,15672,15955,15155,105,15488,12507,15926,3682,14513,15059,131,14990,13838,156,3180,14722,14116,3060,202,2943,14644,15139,12461,15591,14269,14508,391,12984,15497,396,401,15503,16033,13073,15127,499,3182,2986,15176,13623,15177,3115,14096,3309,3336,3594,589,13621,2988,16284,3312,3672,3029,15631,16099,15489,765,15233,3062"
    item_list = []
    params: dict = {"page": "0"}
    headers: dict = {
        "user-agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    }
    try:
        response = requests.get(Url, headers=headers)
    except:
        with open("log.txt", "a") as f:
            f.write(str(time.ctime()) + " Connection error to " + Url + "\n")
        return item_list
    if response.status_code == 200:
        sp = bs(response.content, "lxml")
        try:
            pages = int(
                sp.find("progress", attrs={
                    "class": "_2hirsSG"
                }).get("max")) // 72
            params["page"] = random.randint(0, pages)
        except:
            with open("log.txt", "a") as f:
                f.write(str(time.ctime()) + " parsing error to " + Url + "\n")
            return item_list
    else:
        with open("log.txt", "a") as f:
            f.write(str(time.ctime()) + " Connection error to " + Url + "\n")
        return item_list

    try:
        request = requests.get(Url, headers=headers, params=params)
    except:
        with open("log.txt", "a") as f:
            f.write(str(time.ctime()) + " Connection error to " + Url + "\n")
        return item_list
    if request.status_code == 200:
        soup = bs(request.content, "lxml")
        try:
            ass = soup.find_all("a", attrs={"class": "_3x-5VWa"})
            if len(ass) == 0:
                raise ParsingError
        except:
            with open("log.txt", "a") as f:
                f.write(str(time.ctime()) + " parsing error to " + Url + "\n")
            return item_list
        for a in ass:
            try:
                info = a.get("aria-label").split(",", maxsplit=1)
            except:
                continue
            try:
                link = a.get("href")
            except:
                continue
            name = info[0]
            price = info[1].split(".")
            try:
                old_price = re.sub(", Начальная цена: ", "", price[1])
            except:
                continue
            try:
                new_price = re.sub(" Текущая цена: ", "", price[0])
            except:
                continue
            try:
                img_link = "http:" + a.findChildren(
                    "img", attrs={"data-auto-id": "productTileImage"
                                  })[0].get("src")
            except:
                continue
            item_list.append(Item(name, link, img_link, old_price, new_price))

    else:
        with open("log.txt", "a") as f:
            f.write(str(time.ctime()) + " Connection error to " + Url + "\n")
        return item_list
    done_list = []
    for i in range(10):
        done_list.append(item_list.pop(random.randint(0, len(item_list) - 1)))
    return done_list
Пример #38
0
 def newItemClicked(self):
     newItem = Item("NewItem")
     self.items.append(newItem)
     self.ui.itemEditView.addItem(newItem.name)
Пример #39
0
    def display(self):
        self.ipqMin.display()
        self.ipqMax.display()

    def verifyHeapOrder(self):
        if not self.ipqMin.verifyHeapOrder():
            mnmxPQ.ipqMin.display()
        if not self.ipqMax.verifyHeapOrder():
            mnmxPQ.ipqMax.display()

if __name__ == "__main__":
    import random
    VALUE_RANGE = 40
    TEST_SIZE = 20
    arr = random.sample(range(0, VALUE_RANGE), TEST_SIZE)
    items = [Item(x) for x in zip(range(1, TEST_SIZE + 1), arr)]
    mnmxPQ = MinMaxPQ(items)
    # NEED TO ADD TEST
    mnmxPQ.display()
    mnmxPQ.verifyHeapOrder()
    while not mnmxPQ.ipqMax.isEmpty() and not mnmxPQ.ipqMin.isEmpty():
        v = mnmxPQ.delMax()
        print("Max: {}".format(v))
        mnmxPQ.verifyHeapOrder()
        v = mnmxPQ.delMin()
        print("Min: {}".format(v))
        mnmxPQ.verifyHeapOrder()


Пример #40
0
def dvd():
    return Item("Fellowship of the Ring",
                "Lord of the Rings, Fellowship of the Ring", "DVD_FotR_1",
                9.99)
def for_multi(primary_info, user, wechat_SCKEY):
    modified_item = Item(primary_info)
    modified_item.operate(user=user, wechat_SCKEY=wechat_SCKEY)
Пример #42
0
def book():
    return Item("Of Mice and Men", "Paperback, Of Mice and Men, Steinbeck",
                "book_OMaM_01", 8.99)
Пример #43
0
from ActionDebianSpeakOpenPage import ActionDebianSpeakOpenPage
from Item import Item

items = [
    Item.from_url(
        'https://www.komputronik.pl/product/700067/asus-geforce-rtx-3080-strix-gaming-10gb-oc.html'
    ),
    Item.from_url(
        'https://www.komputronik.pl/product/702274/gigabyte-geforce-rtx-3080-aorus-master-10g.html'
    ),
    Item.from_url(
        'https://www.komputronik.pl/product/700075/gigabyte-geforce-rtx-3080-gaming-oc-10g.html'
    ),
    Item.from_url(
        'https://www.komputronik.pl/product/699241/asus-geforce-rtx-3080-tuf-gaming-10gb-oc.html'
    ),
    Item.from_url(
        'https://www.komputronik.pl/product/699084/asus-geforce-rtx-3080-tuf-gaming-10gb.html'
    ),
    Item.from_url(
        'https://www.komputronik.pl/product/700429/msi-geforce-rtx-3080-gaming-x-trio-10g.html'
    ),
    Item.from_url(
        'https://www.euro.com.pl/karty-graficzne/msi-karta-gragiczna-msi-rtx-3080-gaming-x-tr.bhtml'
    ),
    Item.from_url(
        'https://www.mediaexpert.pl/komputery-i-tablety/podzespoly-komputerowe/karty-graficzne/karta-graficzna-asus-geforce-rog-strix-rtx-3080-o10g-gaming'
    ),
    Item.from_url(
        'https://www.mediaexpert.pl/komputery-i-tablety/podzespoly-komputerowe/karty-graficzne/karta-graficzna-asus-geforce-tuf-rtx-3080-o10g-gaming'
    ),
from descontos import DescontoPorCincoItens, DescontoPorMaisDeQuinhentosReais, SemDesconto


class CalculadorDeDescontos(object):
    def calcula(self, orcamento):
        desconto = DescontoPorCincoItens(
            DescontoPorMaisDeQuinhentosReais(SemDesconto()))

        return desconto.calcula(orcamento)


if __name__ == '__main__':
    from Orcamento import Orcamento
    from Item import Item

    orcamento = Orcamento()
    orcamento.adiciona_item(Item('Item A', 100.0))
    orcamento.adiciona_item(Item('Item B', 50.0))
    orcamento.adiciona_item(Item('Item C', 400.0))
    # orcamento.adiciona_item(Item('Item D', 200.0))
    # orcamento.adiciona_item(Item('Item E', 150.0))
    # orcamento.adiciona_item(Item('Item F', 100.0))

    calculador_de_descontos = CalculadorDeDescontos()
    desconto = calculador_de_descontos.calcula(orcamento)
    # print(f'Desconto calculado : {desconto}')
    print(f'Desconto calculado : {desconto}')
    # imprime 38.5
Пример #45
0
 def loadTemplate(self):
   for child in self.children['replies']:
     child.blog = self.blog
     child.story = self.story
     child.parent = self
   Item.loadTemplate(self)
Пример #46
0
# This includes fixes done with Yuliya and Vera Jan 8. Not the final version we will submit as Yuliya wants to
# work on the items Brendan raised.

from Item import Item
from Order import Order

a1 = Item(12345678, "first item", 2.00, True)  # instantiating the first item
a2 = Item(23456789, "second item", 3.00,
          False)  # instantiating the second item
a3 = Item(34567891, "third item", 10.00, True)  # instantiating the third item

print("print item 1 ", a1.print_item())
print("print item 2 ", a2.print_item())
print("print item 3 ", a3.print_item())
print("\nbase price 1 = ", a1.get_item_base_price())
print("GST 1 = ", a1.calculate_gst())
print("PST 1 = ", a1.calculate_qst())
print("\nbase price 2 = ", a2.get_item_base_price())
print("GST 2 = ", a2.calculate_gst())
print("PST 2 = ", a2.calculate_qst())
print("\nTotal 1 = ", a1.get_item_total())
print("\nTotal 2 = ", a2.get_item_total())
print("\nTotal 3 = ", a3.get_item_total())

new_order1 = Order()
new_order2 = Order()
new_order3 = Order()

new_order1.add_item(a1)  # adding the first item to the first order
new_order2.add_item(a1)  # adding the first item to the second order
new_order2.add_item(a2)  # adding the second item to the second order
Пример #47
0
from flask import Flask, render_template, redirect, url_for, request
from Item import Item

app = Flask(__name__)
app.secret_key = 'secret'
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024
app.config['ALLOWED_EXTENSIONS'] = set(['jpg', 'png'])

post_blog = [Item('Este lunes Marc se perderá la clase de SQL',
                  'El pasado viernes el alumno Marc, de la escuela Idecrea, ha decidido irse de fiesta a Madrid y volver el día lunes, perdiendo la clase final de SQL donde Andros enseñara a concadenar las bases de datos con nuesta pagina web',
                  'img/post1.jpg'),
             Item('He comprado leche XD',
                  'Ayer fui al mercadona a comprar leche y volvi a casa como si nada porque yo lo valgo.',
                  'img/post2.jpg'),
             Item('¿Baila tu cuerpo alegría macarena?',
                  'Que tu cuerpo fragante alegría cosa buena, baila tu cuerpo alegría macarena EHHHHHHHHHHHHH macarena aaaaAAAAHH',
                  'img/post3.jpg')]

@app.route("/")
def index():
    return render_template('items/blog.html', blog=post_blog)

if __name__ == "__main__":
    app.debug = True
    app.run()
Пример #48
0
def add_list(update, context):
    # extract message text
    text = update.message.text[9:].strip()

    # split by newline to get the items - first item is title
    lines = text.split("\n")

    # remove all empty strings
    lines = list(filter(None, lines))

    # throw error, if no arguments are passed
    if (len(lines) == 0):
        ptbh.reply(update, msg.LIST_NO_ARGS)
        return

    # set title and other data
    title = lines.pop(0)
    created_at = datetime.datetime.utcnow().isoformat()
    created_by = ptbu.getUsername(update, True)
    chat_id = update.message.chat.id
    lists = get_lists_from_storage(chat_id)
    list_id = len(get_lists_from_storage(chat_id))
    while (str(list_id) in lists):
        list_id += 1

    # create new list
    new_list = List(list_id, title, created_by, created_at, chat_id)

    # check for items on list
    if (len(lines) > 0):
        items = {}

        # add items to list
        for index, line in enumerate(lines, 1):
            new_item = Item(index, list_id, line)
            items[index] = new_item
        new_list.add_items(items)

    # check if the list is below the TELEGRAM limit for messages
    text = new_list.show_list()

    if (len(text) > c.MESSAGE_MAX_LENGTH * 0.8):
        ptbh.reply(update, msg.NEW_LIST_TOO_LONG)
        return

    # send list to user + retrieve the message_Id
    message_object = update.message.reply_html(text, quote=False)

    # finalize new list with last data
    new_list.add_message_id(message_object.message_id)

    # store list in storage
    add_list_to_storage(chat_id, new_list)

    if (not pin_message(update, context, message_object)):
        is_admin, can_pin, _ = check_bot_rights(update)
        if (not is_admin):
            mod_message = "\n\n" + msg.NOT_ADMIN
        elif (not can_pin):
            mod_message = "\n\n" + msg.NO_PIN_RIGHTS
        if (not is_admin or not can_pin):
            edit_list_message(context, new_list,
                              new_list.show_list() + mod_message)
Пример #49
0
from Knapsack import Knapsack
from Item import Item

import matplotlib.pyplot as plt

def draw_plot(index, list):
    plt.figure(index)
    plt.plot(list)
    plt.plot()
    plt.ylabel('average fitness')
    plt.xlabel('index')

#  Вхідні дані
items = [
    Item(3, 1),
    Item(4, 6),
    Item(5, 4),
    Item(8, 7),
    Item(9, 6)
]

w = 13

items2 = [
    Item(6, 5),
    Item(4, 3),
    Item(3, 1),
    Item(2, 3),
    Item(5, 6)
]
Пример #50
0
def copy_worlds(worlds):
    worlds = [world.copy() for world in worlds]
    Item.fix_worlds_after_copy(worlds)
    return worlds
Пример #51
0
 def setUp(self):
     self.customer = Customer("Vesa", "Kuoppala")
     self.item = Item("Ball")
Пример #52
0
        print("Total QST : ${:0,.2f}".format(self.get_total_qst()).center(50))
        print("Grand Total: ${:0,.2f}".format(self.grand_total()).center(50))


New_Order = Order()
cont = "y"

while cont != "n" and cont != "N":
    item_sku = input("What is the sku of the item to add? >>")
    item_name = input("What is the name of the item to add? >>")
    item_cost = input("How much does the item cost? >>")
    item_tax_p = input("Is the item taxable? (Y/N) >>")
    cont = input("Add another item? (Y/N) >>")
    if item_tax_p == "y":
        item_tax = True
    else:
        item_tax = False
    try:
        item_cost = float(item_cost)
        item_cost = "{:0,.2f}".format(item_cost)
        new_item = Item(item_sku, item_name, item_cost, item_tax)
        New_Order.add_item(new_item)
        create_receipt = True
    except:
        print("The last item could not be create, please try again")
        create_receipt = False
        cont = "y"
if create_receipt != False:
    New_Order.generate_receipt()

Пример #53
0
printS = Write()

menu = StartScreen(surface.get_width(),surface.get_height())

tup = ["tankPic.png",surface.get_rect(),(0,0)]
menu.placeAt("background",tup)

tup=["buttons.png","game",(0,30,117,25),(0,0,120,30),(250,200)]
menu.placeAt("button",tup)

tup = ["falloutBox.jpeg",(0,0,320,150),(50,10)]
menu.placeAt("background",tup)

menu.makeBasicScreen()

fruit = Item(200,100)
fruit.setImage("items.png",pygame.Rect(0,0,31,31))


button = Button()
button.setOffImage("buttons.png",(0,0,120,20))
button.setOnImage("buttons.png",(0,32,115,25))
button.setLoc(130,50)
button.setName("exit")

bar = Button()
bar.setOffImage("userBar.png",(0,0,349,17))
bar.setOnImage("userBar.png",(0,0,349,17)) # note: you may want to have 2 different bars. One clicked, one not clicked. 
bar.setLoc(0,0)
bar.setName("userBar")
Пример #54
0
 def makeLeaf(self, string, number):
     leaf = Item.fill(string, number)
     return leaf
Пример #55
0
def genoutputs(items):
 	
	v = ''
	k = 0
	rows = ''
	for x in items:
		rows +=  x.ToHtmlRow();

	text = "<html>  <head>  <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">  <title>МСС-М</title>  </head> <body>  <table border=\"1\">   <caption>ИКСС</caption>   <tr>  <th>Пакет</th>    <th>Primary Packet Header</th>    <th>Идентификатор сегмента упакованных данных</th>   </tr>"\
	 + rows + '</body> </html>'
	return text

l= []
for x in range(1,10):
	i = Item()
	i.number = random.randint(1, 5)
	i.pheader = random.randint(1, 5)
	i.sigment = random.randint(1, 5)
	l.append(i)

#Выводит [Decode error - output not utf-8] Это ошибка сублайма.
#Решение тут https://toster.ru/q/158563


print(genoutputs(l))
mtext = genoutputs(l)

f = open('o.html', 'w', encoding='utf8')
f.write(mtext)
f.close()
Пример #56
0
        hash_key = hash(item.get_key()) % self.size
        bucket = self.hashmap[hash_key]
        if self.get_load_factor() <= 0.75:
            bucket.insert(item)
        else:
            self.re_create_hash()

    def get_load_factor(self):
        hash_size = 0
        for i in self.hashmap:
            hash_size += i.size()
        return hash_size / (self.size)

    def re_create_hash(self):
        old_hashmap = self.hashmap[:]
        self.size = self.size * 2
        self.hashmap = [LinkedList() for i in range(self.size)]
        for bucket in old_hashmap:
            if bucket.size():
                current = bucket.get_head()
                while current:
                    self.insert_item(current.get_item())
                    current = current.get_next()


hm = HashMap(10)
hm.insert_item(Item("001", "test"))
print(hm.get_load_factor())
hm.re_create_hash()
print(hm.get_load_factor())
Пример #57
0
 def timerFired(self, dt):  
 
     if self.gameStart and not self.showInstructions:
         if self.p.hpBar.curr == 0:
             self.gameOver = True
             self.win = False  
             
         if self.bossAppear:
             if self.b.hpBar.curr == 0:
                 self.gameOver = True
                 self.win = True
         self.tic += 1
         
         if self.p.lvlNum == 10 and not self.bossAppear:
             #generate boss at lvl 10
             x = random.randint(0,self.width//self.size*self.size)
             y = random.randint(0,self.height//self.size*self.size)
             self.b = Boss(x,y,self.size,self.grid,self.p.lvlNum)
             self.monsters.add(self.b)
             self.bossAppear = True
           
         #scrolls items and attacks
         for item in self.items:
             item.shift(self.isScroll, self.scrollX,self.scrollY, self.size)
         self.map.sideScroll(self.scrollX,self.scrollY)
         self.mAttacks.update(self.width, self.height - self.menuSize, self.grid, self.size, self.scrollX, self.scrollY)
         self.pAttacks.update(self.width, self.height - self.menuSize, self.grid, self.size, self.scrollX, self.scrollY)
     
         #update player and monsters
         if self.tic%5 == 0:
             self.play.update(self.isKeyPressed,self.width, self.height- self.menuSize, self.grid, self.scrollX,  self.scrollY, self.isScroll, self.tic)
         for monster in self.monsters:
             monster.shift(self.isScroll, self.scrollX, self.scrollY, self.p.x, self.p.y)
         self.isScroll = [False,False,False,False]
         if self.tic%10 ==0:
             self.monsters.update((self.p.x,self.p.y), self.scrollX, self.scrollY)
             self.boss.update((self.p.x,self.p.y), self.scrollX, self.scrollY)
 
 
         if self.tic%50 == 0:
             if len(self.monsters) <= 1:
                 # generates monsters every couple of seconds
                 x = random.randint(0,self.width)//self.size*self.size
                 y = random.randint(0,self.height- self.menuSize)//self.size*self.size
                 monster = Monster(x,y, self.size, self.grid, self.p.lvlNum)
                 self.monsters.add(monster)   
                 
             for monster in self.monsters:
                 #updates monster's path
                 monster.updatePath(self.p.x,self.p.y, self.scrollX, self.scrollY)
         for monster in self.monsters:
             #checks if monster died/give exp pts/item drops
             if monster.y == self.p.y and monster.x == self.p.x:
                 monster.kill()
                 self.p.hpBar.curr = 0
             if monster.hpBar.curr == 0:
                 self.p.lvlBar.affect(10)
                 createItem = random.randint(0,6)
                 if createItem > 3:
                     self.items.add(Item(monster.x, monster.y))
                 if createItem < 2:
                     self.items.add(Potion(monster.x, monster.y))
                 monster.kill()
 
         if self.tic%100 == 0: 
         #detecting attack collisions/ deal damage               
             if len(self.monsters) > 0:
                 for m in self.monsters:
                     if type(m) == Boss:
                         attk = self.createSpell(m.x,m.y, self.p.x,self.p.y, m.r, m.str, True)
                     else:
                         attk = self.createSpell(m.x,m.y, self.p.x,self.p.y, m.r, m.str, False)
                     self.mAttacks.add(attk)
         
         pAttkLanded = pygame.sprite.groupcollide(self.monsters,self.pAttacks, False, True)
         mAttkLanded = pygame.sprite.groupcollide(self.mAttacks,self.play, True, False)
         for attk in mAttkLanded:
             if type(attk) == SpAttack:
                 y = random.randint(0,len(self.scrn.orbScrn) - 1)
                 x = random.randint(0,len(self.scrn.orbScrn[y]) - 1)
                 self.scrn.orbScrn[x][y][4] = 1 
             self.p.hpBar.affect(-1*attk.pow)
         for mon in pAttkLanded:
             mon.hpBar.affect(-self.p.str)
         self.scrn.removeMatches()
Пример #58
0
def get(machine_xml, check_machine_description, soft_item):
    global ini_data
    if Config.ini_file is not None:
        if ini_data is None:
            ini_data = configparser.ConfigParser(allow_no_value=True)
            ini_data.read(Config.ini_file)

        if Config.include is not None:
            found = False
            for i in Config.include.split(','):
                if machine_xml.attrib['name'] in ini_data[i]:
                    found = True
                    break
            if found is False:
                return None
        if Config.exclude is not None:
            try:
                for e in Config.exclude.split(','):
                    if machine_xml.attrib['name'] in ini_data[e]:
                        return None
            except KeyError:
                pass

    if Config.force_driver is not None:
        found = False
        drivers = Config.force_driver.split(',')
        for d in drivers:
            if machine_xml.attrib['name'] == d:
                found = True

        if found is False:
            return None

    if "isdevice" in machine_xml.attrib:
        if machine_xml.attrib["isdevice"] == "yes":
            # print("Skip device ", machine.attrib["name"])
            return None
    if "isbios" in machine_xml.attrib:
        if machine_xml.attrib["isbios"] == "yes":
            # print("Skip bios ", machine.attrib["name"])
            return None
    if "runnable" in machine_xml.attrib:
        if machine_xml.attrib["runnable"] == "no":
            # print("Skip non runnable ", machine.attrib["name"])
            return None
    # if "ismechanical" in machine.attrib:
    #    if machine.attrib["ismechanical"] == "yes":
    # print("Skip mechanical ", machine.attrib["name"])
    #        return None

    if Config.allow_preliminary is False:
        machine_driver = machine_xml.find("driver")
        if machine_driver is not None:
            if "status" in machine_driver.attrib:
                if machine_driver.attrib["status"] == "preliminary":
                    # print("Skip preliminary driver machine ", machine.attrib["name"])
                    return None

    if soft_item is None:
        year = machine_xml.find("year").text
        if Config.year_min is not None:
            try:
                if int(year) < Config.year_min:
                    return None
            except ValueError:
                return None

        if Config.year_max is not None:
            try:
                if int(year) > Config.year_max:
                    return None
            except ValueError:
                return None

    if Config.description is not None and check_machine_description is True:
        if strict_search_machine(machine_xml) is False:
            return None

    if Config.manufacturer is not None:
        current_manuf = machine_xml.find("manufacturer").text
        manuf_list = Config.manufacturer.split(',')
        is_found = False
        for manuf in manuf_list:
            if re.search(manuf, current_manuf, re.IGNORECASE) is not None:
                is_found = True
                break

        if is_found is False:
            return None

    if Config.no_manufacturer is not None:
        current_manuf = machine_xml.find("manufacturer").text
        manuf_list = Config.no_manufacturer.split(',')
        is_found = True
        for manuf in manuf_list:
            if re.search(manuf, current_manuf, re.IGNORECASE) is not None:
                is_found = False
                break

        if is_found is False:
            return None

    if Config.source_file is not None:
        source_file_list = Config.source_file.split(',')
        is_found = False
        for source_file in source_file_list:
            if machine_xml.attrib['sourcefile'] == source_file:
                is_found = True
                break
        if is_found is False:
            return None

    if Config.no_clone is True and "cloneof" in machine_xml.attrib:
        return None

    if Config.device is not None:
        is_found = False
        machine_device = machine_xml.findall("device_ref")
        if machine_device is not None:
            for md in machine_device:
                for d in Config.device:
                    if md.attrib["name"] == d:
                        is_found = True
                        break

                if is_found is True:
                    break

        if is_found is False:
            return None

    if Config.slot_option is not None:
        is_found = False
        all_slots = machine_xml.findall("slot")
        if all_slots is not None:
            for slot in all_slots:
                all_slotoptions = slot.findall("slotoption")
                if all_slotoptions is not None:
                    for slotoption in all_slotoptions:
                        for s in Config.slot_option:
                            if slotoption.attrib["devname"] == s:
                                is_found = True
                                break

                if is_found is True:
                    break

        if is_found is False:
            return None

    if Config.display_min is not None:
        all_displays = machine_xml.findall("display")
        if len(all_displays) < Config.display_min:
            return None

    # Search for coinage
    coinage = False

    machine_input = machine_xml.find("input")
    if machine_input is not None:
        if "coins" in machine_input.attrib:
            coinage = True

    if coinage is False:
        machine_dipswitch = machine_xml.findall("dipswitch")
        if machine_dipswitch is not None:
            for ds in machine_dipswitch:
                if "name" in ds.attrib:
                    if ds.attrib["name"] == "Coinage":
                        coinage = True
                        break

    # Search for payout
    payout = False

    machine_dipswitch = machine_xml.findall("dipswitch")
    if machine_dipswitch is not None:
        for ds in machine_dipswitch:
            if "name" in ds.attrib:
                if re.search("payout", ds.attrib["name"],
                             re.IGNORECASE) is not None:
                    payout = True
                    break
                if re.search("antifraud", ds.attrib["name"],
                             re.IGNORECASE) is not None:
                    payout = True
                    break

    # Search for gambling
    gambling = False
    machine_input = machine_xml.find("input")
    if machine_input is not None:
        input_control = machine_input.findall("control")
        if input_control is not None:
            for ctrl in input_control:
                if "type" in ctrl.attrib:
                    if ctrl.attrib["type"] == "gambling":
                        gambling = True
                        break

    # Filter by mode
    if Config.mode == 'arcade':
        if coinage is False:
            return None

        if payout is True:
            return None

        if gambling is True:
            return None

    elif Config.mode == 'standalone':
        if coinage is True:
            return None

        if payout is True:
            return None

        if gambling is True:
            return None

        softlist = machine_xml.find("softwarelist")
        if softlist is not None:
            # Skip software based machines
            return None

    elif Config.mode == 'slotmachine':
        if payout is False and gambling is False:
            return None

    # compatibility filter
    if soft_item is not None:
        is_compatible = True
        soft_xml = soft_item.get_soft_xml()
        shared_feat = soft_xml.findall('sharedfeat')
        for s in shared_feat:
            if s.attrib['name'] == 'compatibility':
                is_compatible = False
                all_machine_softlist = machine_xml.findall('softwarelist')
                for machine_softlist in all_machine_softlist:
                    if machine_softlist.attrib[
                            'name'] == soft_item.get_softlist_name():
                        if 'filter' in machine_softlist.attrib:
                            filter_machine_softlist = machine_softlist.attrib[
                                'filter']
                            all_filter_soft = s.attrib['value'].split(',')
                            for filter_soft in all_filter_soft:
                                if filter_machine_softlist[0] == '!':
                                    if filter_soft != filter_machine_softlist[
                                            1:]:
                                        is_compatible = True
                                        break
                                else:
                                    if filter_soft == filter_machine_softlist:
                                        is_compatible = True
                                        break

                    if is_compatible is True:
                        break
            if is_compatible is True:
                break

        if is_compatible is False:
            return None

    item = Item()

    item.set_machine_xml(machine_xml)

    return item
Пример #59
0
 def pasteArtCode(self, record):
     from Item import Item
     itm = Item.bring(self.ArtCode)
     if (itm):
         self.Description = itm.Name
         self.Price = itm.getCost()
Пример #60
0
# The Object / KeyValue Class:
# obj = Object.LoadFrom(path='test', key='myobj')
# obj.myattr

from Item import Item
from Dict import Dict


class Object(Dict):
    def __getattr__(self, name):
        if name <> 'data' and isinstance(self.data,
                                         dict) and self.data.has_key(name):
            return self.__getitem__(name)

    def __setattr__(self, name, value):
        if name <> 'data' and isinstance(self.data,
                                         dict) and self.data.has_key(name):
            return self.__setitem__(name, value)
        else:
            super(Object, self).__setattr__(name, value)


Item.Register(Object)