Example #1
0
    def __init__(self, eng, unit):
        Item.__init__(self)
        self.erating = int(eng.attributes["rating"].value)
        self.e_base = int(eng.attributes["techbase"].value)
        self.etype = gettext(eng.childNodes)
        self.speed = self.erating / unit.weight
        self.unit = unit  # Reference to parent unit
        # A note on primitive engines:
        # It seems like using engine rating directly does give
        # the right speed, even if rules says otherwise
        # This looks like an internal SSW issue, so
        # assume that the weight of these engines are incorrect

        # Check for legal engine type, save data
        ident = False
        for i in ENGINE:
            if (i[0] == self.etype and i[1] == self.e_base):
                ident = True
                self.eng_bv = i[2]
                if self.unit.type == "CV":
                    self.eweight = i[3](ceil_5(self.erating -
                                               self.get_suspension_factor()))
                else:
                    self.eweight = i[3](ceil_5(self.erating))
                self.r_level = i[4]
                self.cost = i[5]
                self.short = i[6]
        if not ident:
            error_exit((self.etype, self.e_base))
Example #2
0
    def __init__(self, gyr, etype, erating):
        Item.__init__(self)
        # We need engine info for calculations
        self.gtype = gettext(gyr.childNodes)
        self.g_base = int(gyr.attributes["techbase"].value)

        # Check for legal gyro type, save data
        ident = False
        for i in GYRO:
            if (i[0] == self.gtype and i[1] == self.g_base):
                ident = True
                self.gyro_bv = i[2]
                gweightm = i[3]
                self.r_level = i[4]
                self.cost = i[5]
        if not ident:
            error_exit((self.gtype, self.g_base))

        # Calculate weight
        rating = erating
        # Hack: Make sure Primitive Engines get right gyro weight
        if etype == "Primitive Fusion Engine":
            rating *= 1.2
            rating = ceil_5(rating)
        base_weight = ceil(float(rating) / 100.0)
        self.weight = gweightm * base_weight
Example #3
0
 def __init__(self, level, pos, colour):
     Item.__init__(self, level, pos)
     
     self.tile = 6, colour + 2
     self.size = 0.5
     
     self.colour = colour
Example #4
0
    def __init__(self, arm, weight):
        Item.__init__(self)
        self.tech_base = int(arm.attributes["techbase"].value)
        self.atype = get_child_data(arm, "type")
        self.front = int(get_child_data(arm, "front"))
        self.left = int(get_child_data(arm, "left"))
        self.right = int(get_child_data(arm, "right"))
        self.rear = int(get_child_data(arm, "rear"))
        self.p_turret = int(get_child_data(arm, "primaryturret"))
        self.s_turret = int(get_child_data(arm, "secondaryturret"))
        self.rotor = int(get_child_data(arm, "rotor"))

        # Check for legal armor type, save data
        ident = False
        for i in ARMOR:
            if (i[0] == self.atype and i[1] == self.tech_base):
                ident = True
                self.armor_bv = i[2]
                self.armor_multipler = i[3]
                self.r_level = i[4]
                self.cost = i[5]
                self.short = i[6]
        if not ident:
            error_exit((self.atype, self.tech_base))

        # Last sum up total
        armortotal = (self.front + self.left + self.right + self.rear +
                      self.p_turret + self.s_turret + self.rotor)
        maxtotal = floor(3.5 * weight + 40)

        self.total = ArmorLoc("Total", armortotal, (maxtotal - 9) / 2 + 3,
                              maxtotal)
Example #5
0
    def __init__(self, cpt, unit):
        Item.__init__(self)
        cnode = cpt.getElementsByTagName("type")[0]
        self.type = gettext(cnode.childNodes)
        if self.type != "Torso-Mounted Cockpit":
            self.console = cnode.attributes["commandconsole"].value
        else:
            self.console = "FALSE"
        self.c_weight = 0
        self.unit = unit  # Reference to parent unit

        # Check for legal cockpit type, save data
        ident = False
        for i in COCKPIT:
            if (i[0] == self.type):
                ident = True
                self.wgt = i[1]
                self.r_level = i[2]
                self.cost = i[3]
        if not ident:
            error_exit((self.type))

        # Hack: Add console weight
        if self.console == "TRUE":
            self.c_weight = 3
Example #6
0
    def __init__(self, service, parent_fid=None, resp_node=None):
        Item.__init__(self, service, parent_fid, resp_node, tag="Contact")

        self.file_as = FileAs()
        self.alias = Alias()
        self.complete_name = CompleteName()
        self.display_name = DisplayName()
        self.spouse_name = SpouseName()

        self.job_title = JobTitle()
        self.company_name = CompanyName()
        self.department = Department()
        self.manager = Manager()
        self.assistant_name = AssistantName()

        self.birthday = Birthday()
        self.anniversary = WeddingAnniversary()

        self.notes = Notes()
        self.emails = EmailAddresses()
        self.ims = ImAddresses()
        self.phones = PhoneNumbers()
        self.business_home_page = BusinessHomePage()

        self.gender = Gender()
        self.personal_home_page = PersonalHomePage()

        self._init_from_resp()
Example #7
0
 def __init__(self, parent, apoddir):
     Item.__init__(self, parent, skin_type='image')
     self.name = _( 'APOD' )
     self.title = _( 'APOD' )
     self.apoddir = apoddir
     self.info = { 'name' : 'APOD', 'description' : 'Astronomy Picture of the day', 'title' : 'APOD' }
     self.type = 'image'
Example #8
0
 def __init__(self):
     Item.__init__(self)
     self.title = None
     self.artist = None
     self.album = None
     self.image = None
     self.length = 0
Example #9
0
    def set_url(self, url, info=True):
        """
        Sets a new url to the item. Always use this function and not set 'url'
        directly because this functions also changes other attributes, like
        filename, mode and network_play.
        WARNING: This is called whenever self.url is set, therefor it is
        strictly forbidden to set self.url directly in this function
        (infinit recursion!). Use self.__dict__['url'] instead!
        """
        Item.set_url(self, url, info)

        # Look for audio cover image by ID3 tags
        if info:
            filename_array = { 'album'  : self.info['album'],
                               'artist' : self.info['artist'] }
            for format_string in config.AUDIO_COVER_FORMAT_STRINGS:
                filemask = format_string % filename_array
                if format_string.startswith('/'):
                    audiocover = util.getimage(filemask)
                else:
                    audiocover = os.path.dirname(self.filename)
                    audiocover = os.path.join(audiocover, String(filemask))
                    audiocover = util.getimage(audiocover)
                if audiocover:
                    self.image = audiocover
                    self.files.image = audiocover
                    break;

        # additional url types
        if url and url.startswith('cdda://'):
            self.network_play = False
            self.mode = 'cdda'
            self.mimetype = 'cdda'
Example #10
0
 def __init__(self, *args, **kwargs):
     # Pass arguments straight to the superclass constructor.
     Item.__init__(self, *args, **kwargs)
     self.parent = None
     self.children = None # Will optionally get pointed to a CircularDLL.
     self.marked = False
     self.degree = 0
Example #11
0
    def __init__(self, parent, prog, context='menu'):
        Item.__init__(self, parent, skin_type='video')
        logger.log( 9, '__init__(parent=%r, prog=%r, context=%r)', parent, prog, context)
        # prog is a TvProgram object as we get it from the recordserver
        self.prog = prog
        self.context= context

        if hasattr(prog, 'name'): self.name = self.title = prog.name
        if hasattr(prog, 'title'): self.title = self.name = Unicode(prog.title)
        if hasattr(prog, 'sub_title'): self.sub_title = prog.sub_title
        if hasattr(prog, 'desc'): self.description = prog.desc
        if hasattr(prog, 'categories'):self.categories = prog.categories
        if hasattr(prog, 'ratings'): self.ratings = prog.ratings
        if hasattr(prog, 'advisories'): self.advisories = prog.advisories

        self.channel = tv_util.get_chan_displayname(prog.channel_id)
        if hasattr(prog, 'scheduled'):
            self.scheduled = prog.scheduled
        else:
            self.scheduled = False

        self.favorite = False
        self.allowDuplicates = prog.allowDuplicates
        self.onlyNew = prog.onlyNew
        self.overlap = prog.overlap

        self.start = time.strftime(config.TV_DATETIME_FORMAT, time.localtime(prog.start))
        self.stop = time.strftime(config.TV_DATETIME_FORMAT, time.localtime(prog.stop))
        self.recordclient = RecordClient()
Example #12
0
def main():
    """
    Get all questions, for each question get all the answers.
    :return:
    """

    print '|Getting questions from Stackoverflow. Please wait...|'
    items = list()
    questions = get_questions()
    print '|Total questions: {} |'.format(len(questions))
    if questions:
        for question in questions:
            formatter = Formatter()
            question.body = get_question_body(question.id)
            question.body_clean = formatter.beautify(question.body)
            question.answers = get_answers(question.id)             # Iterate over each question and get all answers

    print '|Display information'
    for question in questions:
        item = Item()
        if question.title and question.body_clean:
            item.text = question.title + ' ' + question.body_clean

        if question.answers:
            for answer in question.answers:
                item.text += ' ' + answer.body_clean
                item.text.rstrip('\r\n')
        items.append(item)
        print '<<'
        print item.text
Example #13
0
    def __init__(self, file, cmd=None, args=None, imgpath=None, parent=None):
        logger.log( 9, 'GenericItem.__init__(file=%r, cmd=%r, args=%r, imgpath=%r, parent=%r)', file, cmd, args, imgpath, parent)

        Item.__init__(self, parent)
        self.type  = 'generic'            # fix value
        self.set_url(file, info=True)
        self.parent = parent

        self.name = os.path.splitext(os.path.basename(file))[0]

        # find image for this file
        shot = imgpath + '/' + os.path.splitext(os.path.basename(file))[0] + ".png"
        if os.path.isfile(shot):
            self.image = shot
        elif os.path.isfile(os.path.splitext(file)[0] + ".png"):
            self.image = os.path.splitext(file)[0] + ".png"

        command = ['--prio=%s' % config.GAMES_NICE, cmd]
        command.extend(args.split())
        if os.path.getsize(file) > 0:
            command.append(file)

        self.command = command

        self.game_player = game.get_singleton()
Example #14
0
 def mkdir(self, path, mode):
     logging.info("Creating directory at path "+path)
     item = Item(mode | stat.S_IFDIR, self.uid, self.gid)
     self.mongo.addFile(path,item.getMetadata())
     self.kv.addFile(path,item.getData())
     self.kv.commit()
     self._add_to_parent_dir(path)
Example #15
0
    def __init__(self, **kwargs):
        '''initialize and insert root entry'''
	#for key, value in globals().iteritems():
	#	print "%s ==> %s" % (key, value)

	logging.basicConfig(filename=kwargs['log'],level=logging.DEBUG)
        logging.info("Initializing MetaFS")

        self.uid = os.getuid()
        self.gid = os.getgid()

	self.attributes = kwargs['attributes']
	self.extensions = kwargs['extensions']

       	self.defaultMode = int(kwargs['mode'])

        #initialize data and metadata stores
        self.kv = bsddbWrapper(kwargs['db_loc'])
        self.mongo = mongoWrapper(kwargs['host'], kwargs['port'])
	 
        item = Item(self.defaultMode | stat.S_IFDIR, self.uid, self.gid)
        
        self.mongo.addFile('/', item.getMetadata())
        self.kv.addFile('/', item.getData())
        self.kv.commit()
Example #16
0
 def __init__(self, parent):
     logger.log( 9, 'FlickImage.__init__(parent=%r)', parent)
     Item.__init__(self, parent, skin_type='image')
     self.name = _('Flickr pictures')
     self.title = _('Flickr pictures')
     self.type = 'flickr'
     self.info = { 'name' : 'Flickr', 'description' : 'Flickr pictures', 'title' : 'Flickr' }
Example #17
0
 def __init__(self, parent):
     Item.__init__(self, parent)
     self.name = 'Apple Trailers'
     self.type = 'trailers'
     self.image = config.IMAGE_DIR + '/apple-trailers.png'
     self.trailers = None
     self.inprogress = kaa.ThreadCallable(self.download_trailers)()
Example #18
0
    def __getitem__(self, key):
        """
        returns the specific attribute as string or an empty string
        """
        #_debug_("__getitem__(self=%s, key=%s)" % (self.filename, key), 2)
        if key == "geometry":
            if self['width'] and self['height']:
                return config.IMAGE_GEOMETRY_FORMAT % (self['width'], self['height'])
            return ''

        if key == "date":
            try:
                t = str(Item.__getitem__(self, key))
                if t and t != '':
                    return time.strftime(config.IMAGE_DATETIME_FORMAT,
                                         time.strptime(str(t), '%Y:%m:%d %H:%M:%S'))
                else:
                    # last resort, try timestamp
                    t = Item.__getitem__(self, 'timestamp')
                    return datetime.datetime.fromtimestamp(t)
            except:
                pass

        logger.log( 9, "__getitem__(self=%s, key=%s, res=%r)", self.filename, key, Item.__getitem__(self, key))
        return Item.__getitem__(self, key)
Example #19
0
    def __init__ (self, folder, con=None):
        """Constructor for the abstract base class Contact. If con is not
        None, this behaves like pseudo copy constructor, copying all the
        contact properties from the pass contact. Note, in particular that all
        the 'object attributes' of con are left untouched, and are populated
        as per the general rules of creating a new contact."""

        Item.__init__(self, folder)

        self.props.update({'firstname'    : None, 'company'      : None,
                           'lastname'     : None, 'postal'       : {},
                           'middlename'   : None, 'notes'        : [],
                           'name'         : None, 'phone_home'   : [],
                           'suffix'       : None, 'phone_work'   : [],
                           'title'        : None, 'phone_mob'    : [],
                           'gender'       : None, 'phone_other'  : [],
                           'nickname'     : None, 'phone_prim'   : None,
                           'birthday'     : None, 'fax_home'     : [],
                           'anniv'        : None, 'fax_work'     : [],
                           'web_home'     : [],   'fax_prim'     : None,
                           'web_work'     : [],   'email_home'   : [],
                           'web_prim'     : None, 'email_work'   : [],
                           'dept'         : None, 'email_other'  : [],
                           'fileas'       : None, 'email_prim'   : None,
                           'prefix'       : None, 'im_prim'      : None,
                           'im'           : {},   'custom'       : {},
                           'postal_prim_label' : None,
                           })

        if con:
            self.init_props_from_con(con)
Example #20
0
    def items(self, parent):
        """
        return the list of rom drives
        """
        items = []
        for media in config.REMOVABLE_MEDIA:
            if media.item:
                if parent.display_type == 'video' and media.videoitem:
                    m = media.videoitem
                    # FIXME: how to play video is maybe subdirs?

                else:
                    if media.item.type == 'dir':
                        media.item.display_type = parent.display_type
                        media.item.skin_display_type = parent.display_type
                        media.item.create_metainfo()
                    m = media.item

            else:
                m = Item(parent)
                m.name = _('Drive %s (no disc)') % media.drivename
                m.type = media.type
                m.media = media
                media.item = m

            m.parent = parent
            m.eventhandler_plugins.append(self.items_eventhandler)
            items.append(m)

        return items
Example #21
0
def nearby_items():
    response.content_type = 'application/json'
    
    if (nearby_param_validate(request) == False):
        return {'status':'error-query-paras'}
    
    try:
        if (request.query.type == 'box'):
            bounds = geotypes.Box(float(request.query.north), float(request.query.east),
                                  float(request.query.south), float(request.query.west))
        elif (request.query.type == 'center'):
            center = geotypes.Point(float(request.query.lat), float(request.query.lon))
    except:
        return {'status':'invalid-query-paras'}
    
    max_results = int(request.query.maxresults or '100')
    max_distance = float(request.query.maxdistance or '80000')  # 80 km ~ 50 mi
    
    try:
        base_query = Item.all()
        if (request.query.type == 'box'):
            results = Item.bounding_box_fetch(base_query, bounds, max_results = max_results)
        elif (request.query.type == 'center'):
            results = Item.proximity_fetch(base_query, center, max_results = max_results, max_distance=max_distance)
        return results_dump(results)
    except:
      return {'status':'error-database-query'}
Example #22
0
def getGoalsString():
    value = ""
    latSpan = 2* metricDistanceToLatitudeDistance(centerLat, halfAreaSize)
    lngSpan = 2* metricDistanceToLongditudeDistance(centerLat, halfAreaSize)

    global mapGoals
    
    
    if goalAmount<5:
        goalSpanID = random.sample([0,2,6,8],goalAmount)
    if goalAmount>4:
        goalSpanID = [0,2,6,8] + random.sample([1,3,5,7],goalAmount-4)
    
    
    for x in range(goalAmount):
 #       lat = areaBottom + (0.1 +0.8*random())*latSpan
  #      lng = areaLeft + (0.1 +0.8*random())*lngSpan
        lat = areaBottom + (0.05 +0.3*random.random()+0.3*(goalSpanID[x]/3))*latSpan
        lng = areaLeft + (0.05 +0.3*random.random()+0.3*(goalSpanID[x]%3))*lngSpan   
        goal = Item(int(lat*float(10**6)), int( lng*float(10**6)), 0, "I'm a goal state!")
        goal.crownClaimRadius = crownClaimRadius
        value = value + goal.toString()+ ","
        
        #Add the item to the list of items
        mapGoals[goal.id] = goal
    
    return value[0:-2]
Example #23
0
 def __init__(self, parent):
     Item.__init__(self, parent, skin_type='skype')
     self.name = _('Skype')
     self.skype = SkypeApi()
     self.parent = parent
     self.arg = ('Skype', 0)
     self.type='main'
Example #24
0
def getItemsString():
    value = ""
    latSpan = 2* metricDistanceToLatitudeDistance(centerLat, halfAreaSize)
    lngSpan = 2* metricDistanceToLongditudeDistance(centerLat, halfAreaSize)
    global mapItems
    
    global itemSpanID 
    
    for x in range(int(itemAmount/9)):
        itemSpanID = itemSpanID + spanID
    
    itemSpanID = itemSpanID + random.sample(spanID,itemAmount%9)
    
    for x in range(itemAmount):
   #     lat = areaBottom + (0.1 +0.8*random())*latSpan
    #    lng = areaLeft + (0.1 +0.8*random())*lngSpan
        lat = areaBottom + (0.05 +0.3*random.random()+0.3*(itemSpanID[x]/3))*latSpan
        lng = areaLeft + (0.05 +0.3*random.random()+0.3*(itemSpanID[x]%3))*lngSpan
        
        item = Item(int(lat*float(10**6)), int( lng*float(10**6)), 1+int(random.random()*6), "I'm an item!")
        #item = Item(int(lat*float(10**6)), int( lng*float(10**6)),5, "I'm an item!")
        value = value + item.toString()+ ","
        
        #Add the item to the list of items
        mapItems[item.id] = item
    
    return value[0:-2]
Example #25
0
    def get_item(self, hash_key, range_key=None,
                 attributes_to_get=None, consistent_read=False):
        """
        Retrieve an existing item from the table.

        :type hash_key: int|long|float|str|unicode
        :param hash_key: The HashKey of the requested item.  The
            type of the value must match the type defined in the
            schema for the table.
        
        :type range_key: int|long|float|str|unicode
        :param range_key: The optional RangeKey of the requested item.
            The type of the value must match the type defined in the
            schema for the table.
            
        :type attributes_to_get: list
        :param attributes_to_get: A list of attribute names.
            If supplied, only the specified attribute names will
            be returned.  Otherwise, all attributes will be returned.

        :type consistent_read: bool
        :param consistent_read: If True, a consistent read
            request is issued.  Otherwise, an eventually consistent
            request is issued.
        """
        key = self.schema.build_key_from_values(hash_key, range_key)
        response = self.layer1.get_item(self.name, key,
                                        attributes_to_get, consistent_read,
                                        object_hook=item_object_hook)
        item = Item(self, hash_key, range_key, response['Item'])
        if 'ConsumedCapacityUnits' in response:
            item.consumed_units = response['ConsumedCapacityUnits']
        return item
Example #26
0
    def __init__(self, parent):
        logger.log( 9, 'manual_record.ManualRecordItem.__init__(parent)')
        Item.__init__(self, parent, skin_type='video')

        self.name = _("Manual Record")

        self.recordclient = RecordClient()

        # maxinum number of days we can record
        self.MAXDAYS = 7

        # minimum amount of time it would take record_server.py
        # to pick us up in seconds by default it is one minute plus
        # a few seconds just in case
        self.MINPICKUP = 70

        self.months = [
            _('Jan'), _('Feb'), _('Mar'), _('Apr'), _('May'), _('Jun'),
            _('Jul'), _('Aug'), _('Sep'), _('Oct'), _('Nov'), _('Dec')
        ]

        now = time.time()
        now += 300
        self.startnow = now
        self.starttime = time.localtime(now)
        now += 1900
        self.stopnow = now
        self.stoptime = time.localtime(now)
Example #27
0
    def __init__(self, parent):
        """
        Sets up the configuration variables
        """
        if not config.SYS_USE_NETWORK:
            self.reason = _('SYS_USE_NETWORK not enabled')
            return

        Item.__init__(self, parent, skin_type = 'audio')
        self.name = ( _('Icecast Radio') )

        self.min_bitrate = int(config.ICECAST_MIN_BITRATE)
        self.cache_ttl = int(config.ICECAST_TTL)
        self.max_bitrate = int(config.ICECAST_MAX_BITRATE)
        self.max_bitrate = 0
        self.yellowpages = config.ICECAST_YPS
        self.audiotypes = config.ICECAST_AUDIOTYPES
        self.genremapping = config.ICECAST_GENRE_MAP

        self.cacheFolder = str(config.FREEVO_CACHEDIR) + '/icecast/'
        if not os.path.isdir(self.cacheFolder):
            os.mkdir(self.cacheFolder)

        self.stations = {}
        self.genres = {}
        self.bitrates = {}
Example #28
0
    def __init__(self, nation, tv, parent):
        Item.__init__(self, parent)
        self.name = nation

        self.description = "Channels available: %d" % len(tv)

        self._tv = tv
Example #29
0
 def __init__(self, parent):
     Item.__init__(self, parent)
     self.skin_display_type = "video"
     self.mainArray = {}
     self.nation_list = []
     self.nation_tv = {}
     self.categories_tv = {}
     self.__load()
Example #30
0
 def mknod(self, path, mode, dev):
     logging.info("Create mknod at path "+path)
     item = Item(mode | stat.S_IFREG, self.uid, self.gid)
     item.dev = dev
     self.mongo.addFile(path,item.getMetadata())
     self.kv.addFile(path,item.getData())
     self.kv.commit()
     self._add_to_parent_dir(path)
 def setUp(self):
     self.item=Item(1,'chips',3.75, 'med')
Example #32
0
 def __init__(self, theatre, parent):
     Item.__init__(self, parent)
     self.theatre = theatre
     self.name = theatre['name']
     self.type = 'theatre'
Example #33
0
 def add_item_to_room(self, name, desc):
     item = Item(name, desc)
     self.items.append(item)
Example #34
0
 def pick_up(self, item):
     self.inventory.append(Item(item.name, item.description))
     print(f"\n(͡° ͜ʖ ͡°)\n\nPicked up {item.name}.")
     self.current_room.items.remove(item)
Example #35
0
import sys
import colorama

from object import Object
from character import Character
from player import Player
from item import Item
from area import Area
from game_frame import GameFrame
from colors import Colors

colorama.init()

player = Player(0, 5, colorama.Fore.GREEN + colorama.Style.BRIGHT, "Lajja")
npc = Character(5, 5, '@', colorama.Fore.YELLOW, "NPC", 2, 50, items = [ Item("Magical Amulet", 20), Item("Magical Pie", 10000) ])

starting_village = Area("Starting Village", 10, 10)
starting_village.characters.append(player)
starting_village.characters.append(npc)

g = GameFrame(player, starting_village)

while(True):
    g.run_frame()
Example #36
0
}

# Link rooms together

room['cargo'].n_to = room['corridor']
room['corridor'].s_to = room['cargo']
room['corridor'].n_to = room['holodeck']
room['corridor'].e_to = room['narrow']
room['holodeck'].s_to = room['corridor']
room['narrow'].w_to = room['corridor']
room['narrow'].n_to = room['incinerator']
room['incinerator'].s_to = room['narrow']

# items

item = Item("screwdriver", "A screwdriver, but it does extra space stuff too")
room['cargo'].contents.append(item)

item = Item("shield", "A small, broken shield")
room['cargo'].contents.append(item)

item = Item("cat skull", "The skull of a cat")
room['incinerator'].contents.append(item)

item = Commodity("platinum", "raw platinum ore", 500)
room['cargo'].contents.append(item)

item = Commodity("mithril", "raw mithril ore", 700)
room['incinerator'].contents.append(item)

item = Commodity(
Example #37
0
from room import Room
from player import Player
from item import Item
# Declare all the rooms

weapons = {
    'outside':
    Item([{
        "Sword": "Strongest steal alloy, killer blade"
    }, {
        "Machete": "Regular blade, killer knife"
    }, {
        "Rock": "Regular blade, killer knife"
    }], [{
        "Fire": "Strongest steal alloy, killer blade"
    }, {
        "Spear": "Regular blade, killer knife"
    }, {
        "Pen": "Regular blade, killer knife"
    }]),
    'foyer':
    Item([{
        "Paper": "Strongest steal alloy, killer blade"
    }, {
        "Fork": "Regular blade, killer knife"
    }], [{
        "Spoon": "Strongest steal alloy, killer blade"
    }, {
        "Plate": "Regular blade, killer knife"
    }]),
    'overlook':
Example #38
0
 def __init__(self, movie, parent):
     Item.__init__(self, parent)
     self.movie = movie
     self.name = _('Watch Trailer')
Example #39
0
 def __init__(self, theatre, showtime, parent):
     Item.__init__(self, parent)
     self.name = theatre
     self.description = showtime
     self.type = 'showtime'
Example #40
0
 def __init__(self, movie, parent):
     Item.__init__(self, parent)
     self.movie = movie
     self.name = _('Showtimes')
Example #41
0
def create_item(item: Item) -> Item:
    db.put_item(TableName=TABLE, Item=item.to_record())
    return item
Example #42
0
def newlist(item):
    logger.info("[tumejortv.py] movielist")

    url = item.url
    # Descarga la página
    data = scrapertools.cachePage(url)
    #logger.info(data)

    # Extrae las películas
    patron = '<div class="item " style="clear:both;">[^<]+'
    patron += '<div class="covershot[^<]+'
    patron += '<a href="([^"]+)"[^<]+<img src="([^"]+)"[^<]+</a>[^<]+'
    patron += '</div>[^<]+'
    patron += '<div class="post-title">[^<]+'
    patron += '<h3><a[^<]+>(.*?)</a>'
    matches = re.compile(patron, re.DOTALL).findall(data)
    if DEBUG: scrapertools.printMatches(matches)

    itemlist = []
    for match in matches:
        scrapedtitle = match[2]
        scrapedtitle = scrapedtitle.replace("<span class=\'smallTitle'>", "(")
        scrapedtitle = scrapedtitle.replace("</span>", ")")
        scrapedurl = match[0]
        scrapedthumbnail = match[1]
        scrapedplot = ""
        if (DEBUG):
            logger.info("title=[" + scrapedtitle + "], url=[" + scrapedurl +
                        "], thumbnail=[" + scrapedthumbnail + "]")

        itemlist.append(
            Item(channel=CHANNELNAME,
                 action="findvideos",
                 title=scrapedtitle,
                 url=scrapedurl,
                 thumbnail=scrapedthumbnail,
                 plot=scrapedplot))

    # Extrae la página siguiente
    patron = '<a href="([^"]+)" >&raquo;</a>'
    matches = re.compile(patron, re.DOTALL).findall(data)
    if DEBUG:
        scrapertools.printMatches(matches)

    if len(matches) > 0:
        scrapedtitle = "!Pagina siguiente"
        scrapedurl = matches[0]
        scrapedthumbnail = ""
        scrapeddescription = ""
        if (DEBUG):
            logger.info("title=[" + scrapedtitle + "], url=[" + scrapedurl +
                        "], thumbnail=[" + scrapedthumbnail + "]")

        itemlist.append(
            Item(channel=CHANNELNAME,
                 action="newlist",
                 title=scrapedtitle,
                 url=scrapedurl,
                 thumbnail=scrapedthumbnail,
                 plot=scrapedplot))

    return itemlist
Example #43
0
from room import Room
from player import Player
from item import Item
# Utility func to clear screen on all platforms
from utils import clear_terminal

import sys

# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons", [
        Item("Stick", "It's a stick..."),
        Item("Rock", "What did you expect, it's a rock.")
    ]),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
    'overlook':
    Room(
        "Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm. """, [
            Item("Rope",
                 "A length of rope that you found tied to edge of the chasm")
        ]),
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
 def setUp(self): 
     self.item=Item(1,'chips',3.75, 'med')
     self.quantity=2
     self.special='none'
     self.orderitem=OrderItem(self.item, self.quantity, self.special) 
Example #45
0
# Link rooms together

room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']

# Add items to rooms
# Note: item names (first param) must be all lowercase

room['treasure'].items.append(
    Item('coin', 'A gold coin, leftover from the treasure taken long ago.'))

#
# Main
#

# Make a new player object that is currently in the 'outside' room.

# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
Example #46
0
    def minima_taxacao(self, orcamento):
        return orcamento.valor * 0.06

    def __tem_item_maior_que_100_reais(self, orcamento):

        for item in orcamento.obter_itens():
            if item.valor > 100:
                return True
        return False


class Calculador_de_impostos(object):
    def realiza_calculo(self, orcamento, imposto):
        imposto_calculado = imposto.calcula(orcamento)

        print(imposto_calculado)


if __name__ == '__main__':

    calculador = Calculador_de_impostos()

    orcamento = Orcamento()
    orcamento.adiciona_item(Item('ITEM 1', 50))
    orcamento.adiciona_item(Item('ITEM 2', 100))
    orcamento.adiciona_item(Item('ITEM 3', 50))

    calculador.realiza_calculo(orcamento, ICPP())
    calculador.realiza_calculo(orcamento, IKCV())
Example #47
0
to north. The smell of gold permeates the air."""),
    'treasure':
    Room(
        "Treasure Chamber", """You've found the long-lost treasure
chamber! Sadly, it has already been completely emptied by
earlier adventurers. The only exit is to the south."""),
}

item = {
    'gumdrop':
    Item(
        'gumdrop',
        'A plump, delicious-looking gumdrop candy.', {
            'Eat the gumdrop.': {
                'default':
                "You pop the gumdrop your mouth. It's not too bad, if a bit stale.",
                'hungry':
                "You gobble down the gumdrop without even chewing. But it doesn't satisfy your hunger."
            }
        },
        takeable=True)
}

# Link rooms together

room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
import random
from item import Item
import networkx as nx

##########################################################################################
# Codigo del Problema de la mochila tomado de: https://github.com/edmilsonrobson
##########################################################################################
#

ITEMS = [
    Item(random.randint(0, 30), random.randint(0, 30)) for x in range(0, 30)
]

CAPACITY = 10 * len(ITEMS)

POP_SIZE = 50

GEN_MAX = 200

START_POP_WITH_ZEROES = False

rewiring = 0.3

G = nx.generators.random_graphs.watts_strogatz_graph(POP_SIZE, 3, rewiring)


def fitness(target):
    total_value = 0
    total_weight = 0
    index = 0
    for i in target:
Example #49
0
for doc in retrieved_items:
    data = doc.to_dict()
    itemName = data['name']
    # itemURL = data['imageURL'] if 'imageURL' in data else None
    # TODO: Rework this - probably a hasImage attribute in each item
    itemURL = ''
    itemBlob = bucket.get_blob('item-images/' + itemName)
    if itemBlob:
        metadata = itemBlob.metadata
        itemURL = 'https://firebasestorage.googleapis.com/v0/b/monumenta-item-index.appspot.com/o/item-images%2F' + itemName.replace(
            ' ', '%20') + '?alt=media' + '&token=' + metadata[
                'firebaseStorageDownloadTokens']

    itemTags = data['tags'] if 'tags' in data else None
    # print(itemTags)
    items.append(Item(itemName, itemURL, itemTags))

    count += 1

    if count % 10 == 0:
        print("Loaded " + str(count) + "...")

    # if count >= limit :
    #     break

print("Done loading!")

bot.remove_command("help")

cogs = ['cogs.kaul', 'cogs.help', 'cogs.wiki', 'cogs.stats']
def bitwarden_to_keepass(args):
    global kp
    try:
        kp = PyKeePass(args.database_path,
                       password=args.database_password,
                       keyfile=args.database_keyfile)
    except FileNotFoundError:
        logging.info('KeePass database does not exist, creating a new one.')
        kp = create_database(args.database_path,
                             password=args.database_password,
                             keyfile=args.database_keyfile)
    except CredentialsError as e:
        logging.error(f'Wrong password for KeePass database: {e}')
        return

    folders = subprocess.check_output(
        f'{quote(args.bw_path)} list folders --session {quote(args.bw_session)}',
        shell=True,
        encoding='utf8')
    folders = json.loads(folders)
    groups_by_id = load_folders(folders)
    logging.info(f'Folders done ({len(groups_by_id)}).')

    items = subprocess.check_output(
        f'{quote(args.bw_path)} list items --session {quote(args.bw_session)}',
        shell=True,
        encoding='utf8')
    items = json.loads(items)
    logging.info(f'Starting to process {len(items)} items.')
    for item in items:
        if item['type'] in [ItemTypes.CARD, ItemTypes.IDENTITY]:
            logging.warning(
                f'Skipping credit card or identity item "{item["name"]}".')
            continue

        bw_item = Item(item)

        is_duplicate_title = False
        try:
            while True:
                entry_title = bw_item.get_name(
                ) if not is_duplicate_title else '{name} - ({item_id}'.format(
                    name=bw_item.get_name(), item_id=bw_item.get_id())
                try:
                    entry = kp.add_entry(destination_group=groups_by_id[
                        bw_item.get_folder_id()],
                                         title=entry_title,
                                         username=bw_item.get_username(),
                                         password=bw_item.get_password(),
                                         notes=bw_item.get_notes())
                    break
                except Exception as e:
                    if 'already exists' in str(e):
                        is_duplicate_title = True
                        continue
                    raise

            totp_secret, totp_settings = bw_item.get_totp()
            if totp_secret and totp_settings:
                entry.set_custom_property('TOTP Seed', totp_secret)
                entry.set_custom_property('TOTP Settings', totp_settings)

            for uri in bw_item.get_uris():
                entry.url = uri['uri']
                break  # todo append additional uris to notes?

            for field in bw_item.get_custom_fields():
                entry.set_custom_property(field['name'], field['value'])

            for attachment in bw_item.get_attachments():
                attachment_tmp_path = f'/tmp/attachment/{attachment["fileName"]}'
                attachment_path = subprocess.check_output(
                    f'{quote(args.bw_path)} get attachment'
                    f' --raw {quote(attachment["id"])} '
                    f'--itemid {quote(bw_item.get_id())} '
                    f'--output {quote(attachment_tmp_path)} --session {quote(args.bw_session)}',
                    shell=True,
                    encoding='utf8').rstrip()
                attachment_id = kp.add_binary(
                    open(attachment_path, 'rb').read())
                entry.add_attachment(attachment_id, attachment['fileName'])
                os.remove(attachment_path)

        except Exception as e:
            logging.warning(
                f'Skipping item named "{item["name"]}" because of this error: {repr(e)}'
            )
            continue

    logging.info('Saving changes to KeePass database.')
    kp.save()
    logging.info('Export completed.')
Example #51
0
kitchen.link_room(dining_hall, "south")
dining_hall.link_room(kitchen, "north")
dining_hall.link_room(ballroom, "west")
ballroom.link_room(dining_hall, "east")

dave = Enemy("Dave", "A smelly zombie")
dave.set_conversation("What's up, dude! I'm hungry.")
dave.set_weakness("cheese")
dining_hall.set_character(dave)

tabitha = Enemy("Tabitha", "An enormous spider with countless eyes and furry legs.")
tabitha.set_conversation("Sssss....I'm so bored...")
tabitha.set_weakness("book")
ballroom.set_character(tabitha)

cheese = Item("cheese")
cheese.set_description("A large and smelly block of cheese")
ballroom.set_item(cheese)

book = Item("book")
book.set_description("A really good book entitled 'Knitting for dummies'")
dining_hall.set_item(book)

current_room = kitchen
backpack = []

dead = False

while dead == False:

    print("\n")
Example #52
0
from room import Room
from player import Player
from item import Item

item = {
    "SWORD":
    Item("SWORD",
         "Old and rusted, but it'll get the job done if you have to use it."),
    "SHIELD":
    Item(
        "SHIELD",
        """Makeshift shield someone made from flimsy wood. Might withstand a 
couple strikes before breaking apart"""),
}
# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mouth beckons"),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north and east."""),
    'overlook':
    Room(
        "Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm."""),
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
Example #53
0
from room import Room
from player import Player
from item import Item
import random

#Declare all the items.

# Declare all the rooms

room = {
    'outside':
    Room("Outside Cave Entrance", "North of you, the cave mount beckons.", [
        Item('flail', 'it can be used to fight off enemies.'),
        Item('sword', 'it will give you magical powers.'),
        Item('hammer', 'it can break through the walls.')
    ]),
    'foyer':
    Room(
        "Foyer", """Dim light filters in from the south. Dusty
passages run north and east.""",
        [Item('flashlight', 'this flashlight can help you see in dark rooms')
         ]),
    'overlook':
    Room(
        "Grand Overlook", """A steep cliff appears before you, falling
into the darkness. Ahead to the north, a light flickers in
the distance, but there is no way across the chasm."""),
    'narrow':
    Room(
        "Narrow Passage", """The narrow passage bends here from west
to north. The smell of gold permeates the air.""",
class VendingMachine:
    def __init__(self):
        super().__init__()
        self._cashInventory = CashInventory()
        self._itemInventory = ItemInventory()
        self._totalSales = 0
        self._currentItem = None
        self._currentBalance = 0
        self._currentlyInsertedCoins = []
        self._initilizeItemInventory()
        self._initilizeCashInventory()

    def _initilizeItemInventory(self):
        """initilize item inventory by 5 items of each type"""
        for itemName in itemPrice.keys():
            for j in range(5):
                self._itemInventory.add(itemName)

    def _initilizeCashInventory(self):
        """initilize cash inventory by 5 coins of each type"""
        for coinName in coinValue.keys():
            for j in range(5):
                self._cashInventory.add(coinName)

    def _refund(self):
        """refund change if change not available"""
        refund = self._currentlyInsertedCoins
        self._updateCashInventory(refund)
        return refund

    def _collectChange(self):
        """collect change after buy"""
        changeAmount = self._currentBalance - self._currentItem.getPrice()
        change = self._getChange(changeAmount)
        self._updateCashInventory(change)
        return change

    def _getChange(self, amount):
        """return change of input amount"""
        changes = []
        if amount > 0:
            balance = amount
            currentlyDeducted = {"penny": 0,
                                 "nickel": 0, "dime": 0, "quarter": 0}
            while balance > 0:
                change_coin = Coin()
                if balance >= coinValue.get("quarter") and self._cashInventory.hasCoin("quarter"):
                    balance = balance - coinValue.get("quarter")
                    change_coin.setName("quarter")
                    change_coin.setValue(coinValue.get("quarter"))
                    changes.append(change_coin)
                    self._cashInventory.remove("quarter")
                    currentlyDeducted["quarter"] = currentlyDeducted.get(
                        "quarter")+1
                    continue
                elif balance >= coinValue.get("dime") and self._cashInventory.hasCoin("dime"):
                    balance = balance - coinValue.get("dime")
                    change_coin.setName("dime")
                    change_coin.setValue(coinValue.get("dime"))
                    changes.append(change_coin)
                    self._cashInventory.remove("dime")
                    currentlyDeducted["dime"] = currentlyDeducted.get(
                        "dime")+1
                    continue
                elif balance >= coinValue.get("nickel") and self._cashInventory.hasCoin("nickel"):
                    balance = balance - coinValue.get("nickel")
                    change_coin.setName("nickel")
                    change_coin.setValue(coinValue.get("nickel"))
                    changes.append(change_coin)
                    self._cashInventory.remove("nickel")
                    currentlyDeducted["nickel"] = currentlyDeducted.get(
                        "nickel")+1
                    continue
                elif balance >= coinValue.get("penny") and self._cashInventory.hasCoin("penny"):
                    balance = balance - coinValue.get("penny")
                    change_coin.setName("penny")
                    change_coin.setValue(coinValue.get("penny"))
                    changes.append(change_coin)
                    self._cashInventory.remove("penny")
                    currentlyDeducted["penny"] = currentlyDeducted.get(
                        "penny")+1
                    continue
                else:
                    changes.clear()
                    changes.append(None)
                    break

            # Since this function is for checking the change,
            # I am putting back the currently deducted coin to
            # cash inventory
            for coinName in currentlyDeducted.keys():
                self._cashInventory.addBulk(
                    coinName, currentlyDeducted.get(coinName))

        return changes

    def _isFullyPaid(self):
        """check the amount is fully paid or not"""
        if self._currentBalance >= self._currentItem.getPrice():
            return True
        return False

    def _hasSufficentChangeForAmount(self, amount):
        """check whether the machine has sufficient change or not"""
        withChange = self._getChange(amount)
        if len(withChange) == 0:
            return True
        if withChange[0] == None:
            return False
        return True

    def _hasSufficentChange(self):
        """return false if machine has sufficent change otherwise return false"""
        return self._hasSufficentChangeForAmount(self._currentBalance - self._currentItem.getPrice())

    def _collectItem(self):
        """buy item from machine"""
        if self._isFullyPaid():
            if self._hasSufficentChange():
                self._itemInventory.remove(self._currentItem.getName())
                return True
            else:
                print(
                    "Sorry! Sufficient change is not available in machine!", flush=True)
                return False

        remaining_balance = self._currentItem.getPrice() - self._currentBalance
        print("Price is not fully paid, Remaining: " +
              str(remaining_balance), flush=True)
        return False

    def _updateCashInventory(self, change):
        """update cash in cash inventory"""
        for coin in change:
            self._cashInventory.remove(coin.getName())

    def reset(self):
        """reset the vending machine"""
        self._cashInventory = CashInventory()
        self._itemInventory = ItemInventory()
        self._totalSales = 0
        self._currentItem = None
        self._currentBalance = 0

    def putItem(self, inputItem, quantity):
        self._itemInventory.put(inputItem, quantity)

    def putCoin(self, inputCoin, quantity):
        self._cashInventory.put(inputCoin, quantity)

    def displayStats(self):
        """display the current stat of machine"""
        print("Items: available number: ", flush=True)
        self._itemInventory.display()
        print("Coin: available number: ", flush=True)
        self._cashInventory.display()

    def getCurrentBalance(self):
        """return current balance inserted"""
        return self._currentBalance

    def selectItemAndGetPrice(self, itemName):
        """return price of input item"""
        if self._itemInventory.hasItem(itemName):
            self._currentItem = Item()
            self._currentItem.setName(itemName)
            self._currentItem.setPrice(itemPrice.get(itemName))
            return self._currentItem.getPrice()
        print("Item sold out! Please try other item.")
        return -1

    def insertCoin(self, coinName):
        """insert coins and calculate current balance"""
        value = coinValue.get(coinName)
        iCoin = Coin()
        iCoin.setName(coinName)
        iCoin.setValue(value)
        self._currentlyInsertedCoins.append(iCoin)
        self._currentBalance = self._currentBalance + value
        self._cashInventory.add(coinName)

    def getTotalSales(self):
        """return total sales amount"""
        return self._totalSales

    def collectItemAndChange(self):
        """collect item and change after buy in bucket"""
        bucket = Bucket()
        if self._collectItem():
            self._totalSales = self._totalSales + self._currentItem.getPrice()
            bucket.setItem(self._currentItem)
            returnedChanges = self._collectChange()
            bucket.setChanges(returnedChanges)
        else:
            bucket.setItem(None)
            refund_changes = self._refund()
            bucket.setChanges(refund_changes)
        self._currentBalance = 0
        self._currentItem = None
        self._currentlyInsertedCoins = []
        return bucket

    def displayBucket(self, bucket):
        """print bucket value"""
        if bucket.getItem() == None:
            print("item: "+str(None))
        else:
            print("Item: "+str(bucket.getItem().getName()))
        print("Change: ", end='')
        for change in bucket.getChanges():
            if(change != None):
                print(str(change.getName()) +
                      "(value = "+str(change.getValue())+"), ", end='')
        print("", flush=True)
Example #55
0
room['outside'].n_to = room['foyer']
room['foyer'].s_to = room['outside']
room['foyer'].n_to = room['overlook']
room['foyer'].e_to = room['narrow']
room['overlook'].s_to = room['foyer']
room['narrow'].w_to = room['foyer']
room['narrow'].n_to = room['treasure']
room['treasure'].s_to = room['narrow']

#
# Main
#

# Food
apple = Item('apple', 'Red and juicy.')
steak = Item('steak', 'Cold, but could help.')

# Weapon
sword = Item('sword', 'It is incredibly shiny.')

# Loot
coin = Item('gold', 'Preciouss.. so shiny...')
ruby = Item('ruby', "Is it red because it's a ruby? Or is red from blood...")

items_list = [coin, ruby, sword, apple, steak]

## Initialize items

roomList = ['narrow', 'outside', 'foyer', 'overlook', 'treasure']
Example #56
0
 def __init__(self, parent):
     Item.__init__(self, parent)
     self.name = 'Movie Listings'
     self.type = 'video' # ?
Example #57
0
# Write a loop that:
#
# * Prints the current room name
# * Prints the current description (the textwrap module might be useful here).
# * Waits for user input and decides what to do.
#
# If the user enters a cardinal direction, attempt to move to the room there.
# Print an error message if the movement isn't allowed.
#
# If the user enters "q", quit the game.
directions = {'w': 'north', 's': 'south', 'a': 'west', 'd': 'east'}

items = {
    'Sword':
    Item('Sword', 'A sharp sword that can be use to cut down the monster'),
    'Shield':
    Item('Shield',
         'If you don\'t like to attack the monster, you can defend yourself'),
}

# Generate some items in each rooms:

room['outside'].add_items(items['Sword'])
room['foyer'].add_items(items['Shield'])


def start_game():
    name = input('Enter your name here: ')
    player_1 = Player(name, room['outside'])
    print(f'''
Example #58
0
    "A room with four-legged Chiefs being fed every 6 hours or so.")

bedroom = Room("Bedroom")
bedroom.set_description("You get to live your dreams here.")

kitchen.link_room(dining_hall, "south")
dining_hall.link_room(kitchen, "north")
dining_hall.link_room(bedroom, "west")
bedroom.link_room(dining_hall, "east")

dave = Enemy("Dave", "A smelly zombie")
dave.set_conversation("Hey, what's up?")
dave.set_weakness("cheese")
dining_hall.set_character(dave)

cheese = Item("cheese")
cheese.set_description("A large and smelly block of cheese")
bedroom.set_item(cheese)

#Add new character

catrina = Character("Catrina", " A friendly Skeleton")

catrina.set_conversation("Why hello there!")

esu = Enemy("Esu", "The devil himself,weak at heart but appears to be evil")
esu.set_conversation("Who wants to die today?")
esu.set_weakness("love")
bedroom.set_character(esu)

love = Item("love")
Example #59
0
def parse_bp_api(arg):
    return [Item(i['typeName'][:-10], runs=int(i['runs']), mats_mod=0.99, top_level=True) for i in bps_api() if i['typeName'].endswith("Blueprint") and re.search(arg, i['typeName'][:-10])]
Example #60
0
    def __init__(self, master):
        """Constructor

        Parameters:
            master (tk.Tk): tkinter root widget
        """

        self._master = master
        self._world = World((GRID_WIDTH, GRID_HEIGHT), BLOCK_SIZE)
        self._master.title("Ninedraft")
        load_simple_world(self._world)

        self._player = Player(max_health=40.0)
        self._world.add_player(self._player, 250, 150)

        self._world.add_collision_handler(
            "player", "item", on_begin=self._handle_player_collide_item)
        self._world.add_collision_handler(
            "player", "mob", on_post_solve=self._handle_player_collide_mob)
        self._hot_bar = SelectableGrid(rows=1, columns=10)
        self._hot_bar.select((0, 0))

        starting_hotbar = [
            Stack(create_item("dirt"), 20),
            Stack(create_item("crafting_table"), 1),
            Stack(create_item("furnace"), 1),
            Stack(create_item('axe', 'wood'), 1),
            Stack(create_item('pickaxe', 'golden'), 1),
        ]

        for i, item in enumerate(starting_hotbar):
            self._hot_bar[0, i] = item

        self._hands = create_item('hands')

        starting_inventory = [
            ((1, 5), Stack(Item('dirt'), 10)),
            ((0, 2), Stack(Item('wood'), 10)),
            ((0, 4), Stack(Item('stone'), 20)),
        ]
        self._inventory = Grid(rows=3, columns=10)
        for position, stack in starting_inventory:
            self._inventory[position] = stack

        self._crafting_window = None
        self._master.bind("e", lambda e: self.run_effect(
            ('crafting', 'basic')))

        self._view = GameView(master, self._world.get_pixel_size(),
                              WorldViewRouter(BLOCK_COLOURS, ITEM_COLOURS))
        self._view.pack()

        # Task 1.2 Mouse Controls: Bind mouse events here
        self._master.bind("<Motion>", self._mouse_move)
        self._master.bind("<1>", self._left_click)
        self._master.bind("<3>", self._right_click)

        # Task 1.3: Create instance of StatusView here
        self.status_view = StatusView(self._master)
        self.status_view.pack()
        self.status_view.set_food(self._player.get_food())
        self.status_view.set_health(self._player.get_health())

        self._hot_bar_view = ItemGridView(master, self._hot_bar.get_size())
        self._hot_bar_view.pack(side=tk.TOP, fill=tk.X)

        # Task 1.5 Keyboard Controls: Bind to space bar for jumping here
        self._master.bind("<space>", lambda x: self._jump())

        self._master.bind("a", lambda e: self._move(-1, 0))
        self._master.bind("<Left>", lambda e: self._move(-1, 0))
        self._master.bind("d", lambda e: self._move(1, 0))
        self._master.bind("<Right>", lambda e: self._move(1, 0))
        self._master.bind("s", lambda e: self._move(0, 1))
        self._master.bind("<Down>", lambda e: self._move(0, 1))
        self._master.bind("w", lambda e: self._move(0, -1))
        self._master.bind("<Up>", lambda e: self._move(0, -1))
        # Task 1.5 Keyboard Controls: Bind numbers to hotbar activation here
        for i in range(10):
            self._master.bind(str((i + 1) % 10),
                              (lambda x: lambda e: self._activate_item(x))(i))

        # Task 1.6 File Menu & Dialogs: Add file menu here
        self.menu = tk.Menu(self._master)
        file_bar = tk.Menu(self.menu)
        file_bar.add_command(label="New Game", command=self._restart)
        file_bar.add_command(label="Exit", command=self._quit)

        self.menu.add_cascade(label='File', menu=file_bar)
        self._master.config(menu=self.menu)

        self._target_in_range = False
        self._target_position = 0, 0

        self.redraw()

        self.step()