示例#1
0
    def from_dict(request_dict):

        id = request_dict.get('id', generate_uuid())
        request = TaskRequest(id=id)

        request.load_type = request_dict["loadType"]
        request.load_id = request_dict["loadId"]
        request.user_id = request_dict["userId"]
        request.earliest_pickup_time = TimeStamp.from_str(
            request_dict["earliestPickupTime"])
        request.latest_pickup_time = TimeStamp.from_str(
            request_dict["latestPickupTime"])

        pickup_area_dict = request_dict.get('pickup_pose', None)
        if pickup_area_dict:
            request.pickup_pose = Area.from_dict(pickup_area_dict)
        else:  # when the provided dict is from json schema
            request.pickup_pose = Area()
            request.pickup_pose.name = request_dict.get("pickupLocation", '')
            request.pickup_pose.floor_number = request_dict.get(
                "pickupLocationLevel", 0)

        delivery_area_dict = request_dict.get('delivery_pose', None)
        if delivery_area_dict:
            request.delivery_pose = Area.from_dict(delivery_area_dict)
        else:  # when the provided dict is from json schema
            request.delivery_pose = Area()
            request.delivery_pose.name = request_dict.get(
                "deliveryLocation", '')
            request.delivery_pose.floor_number = request_dict.get(
                "deliveryLocationLevel", 0)

        request.priority = request_dict["priority"]

        return request
示例#2
0
    def test_area_calculateDistances(self):
        area = Area(5)
        area.saveArea()
        testArea = Area('file')

        self.assertEqual(testArea.numberOfBlocks, 5)
        self.assertEqual(testArea.cords.shape, (5, 2))
        self.assertEqual(testArea.sizes.shape, (5, ))
        self.assertEqual(testArea.distances.shape, (5, 5))
示例#3
0
 def __init__(self, id=''):
     if not id:
         self.id = generate_uuid()
     else:
         self.id = id
     self.pickup_pose = Area()
     self.delivery_pose = Area()
     self.earliest_pickup_time = TimeStamp()
     self.latest_pickup_time = TimeStamp()
     self.user_id = ''
     self.load_type = ''
     self.load_id = ''
     self.priority = -1
示例#4
0
 def __init__(self):
     self.area = Area()
     self.ant_num = 20
     self.ant_list = []
     self.add_number = 0
     for i in range(self.ant_num):
         self.ant_list.append(Ant(self.area.area))
示例#5
0
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.screen = None

        self.toolbarbox = ToolbarBox(self)
        self.toolbarbox.connect("show-simulation", self._show_simulation_cb)
        self.toolbarbox.connect("show-info", self._show_info_cb)
        self.toolbarbox.connect("go-back", self._go_back_cb)
        self.toolbarbox.connect("go-forward", self._go_forward_cb)
        self.toolbarbox.connect("show-orbits", self._show_orbits_cb)
        self.toolbarbox.connect("show-body", self._show_body_cb)
        self.toolbarbox.connect("speed-changed", self._speed_changed_cb)
        self.toolbarbox.connect("zoom-changed", self._zoom_changed_cb)
        self.set_toolbar_box(self.toolbarbox)

        self.box = Gtk.VBox()
        self.set_canvas(self.box)

        self.area = Area()
        self.area.connect("body-selected", self._body_selected)

        self.info_view = InfoView()
        self.info_view.connect("change-cursor", self._change_cursor)
        self.info_view.connect("can-go-back", self._can_go_back_cb)
        self.info_view.connect("can-go-forward", self._can_go_forward_cb)

        self.set_screen(Screen.SOLAR_SYSTEM)
        self.show_all()
示例#6
0
    def __init__(self):
        Gtk.VBox.__init__(self)

        self.screen = None

        self.area = Area()
        self.area.connect("body-selected", self._body_selected)

        self.info_view = InfoView()
        self.info_view.connect("change-cursor", self._change_cursor)

        adj = Gtk.Adjustment(10, 0.2, 100, 0.5, 1)
        s = Gtk.HScale()
        s.set_draw_value(False)
        s.set_adjustment(adj)
        s.connect("value-changed", self.change_zoom)
        self.pack_start(s, False, False, 0)

        adj = Gtk.Adjustment(1, 0.1, 5, 0.1, 1)
        s = Gtk.HScale()
        s.set_draw_value(False)
        s.set_adjustment(adj)
        s.connect("value-changed", self.change_speed)
        self.pack_start(s, False, False, 0)

        self.set_screen(Screen.SOLAR_SYSTEM)
        self.show_all()
示例#7
0
    def test_area_size(self):
        area = Area('draw', 10)

        self.assertEqual(area.numberOfBlocks, 10)
        self.assertEqual(area.cords.shape, (10, 2))
        self.assertEqual(area.sizes.shape, (10, ))
        self.assertEqual(area.distances.shape, (10, 10))
 def __init__(self):
     self.area_number = 1
     self.area = Area()
     self.hero = Hero()
     self.characters = self.create_characters()
     self.monsters = self.characters[1:]
     self.kill_count = 0
示例#9
0
    def __call__(self, area):
        start = self.getStart(area)
        end = self.getEnd(area)

        a = Area(start.x, start.y, end.x, end.y)

        for (x, y, orientation) in self.algorithm(a):
            yield Coords(x, y, orientation)
示例#10
0
	def __call__(self, c):
		start = self.area.startFrom(c)
		end = self.area.endFrom(c)
		
		a = Area(start.x, start.y, end.x, end.y)
		
		for x in self.feature(a):
			yield x
示例#11
0
    def canSee(self, other):
        cursor = self.cell.getCursor()

        l = list(algorithms.line(Area(self.x, self.y, other.x, other.y)))
        l = l[1:-1]
        for (x, y, _) in l:
            if cursor.move(x, y).isSolid:
                return False

        return True
示例#12
0
 def next_area(self, canvas):
     self.area_number += 1
     self.area = Area()
     self.hero.restore_health()
     self.characters = self.create_characters()
     self.monsters = self.characters[1:]
     self.area.draw_map(canvas)
     canvas.delete(self.hero.name)
     self.hero.direction = 'hero-down'
     self.spawn_characters(canvas)
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        self.make_toolbar()

        hbox = Gtk.HBox()
        self.set_canvas(hbox)

        self.area = Area()
        hbox.pack_start(self.area, True, False, 0)

        self.show_all()
示例#14
0
 def convert_unit(self, value, input_unit, output_unit):
     if self.measurement is 'length':
         return Length(value, input_unit, output_unit).convert()
     if self.measurement is 'temperature':
         return Temperature(value, input_unit, output_unit).convert()
     if self.measurement is 'area':
         return Area(value, input_unit, output_unit).convert()
     if self.measurement is 'volume':
         return Volume(value, input_unit, output_unit).convert()
     if self.measurement is 'weight':
         return Weight(value, input_unit, output_unit).convert()
     return "Not a valid measurement is entered! Select from : length, temperature, volume, area, weight"
示例#15
0
def test_getAdjacent():

    # Put two areas in a zone
    a = Area(name="A",
             desc="area_desc",
             domain=[8],
             action=lambda: 5,
             resource_id="a_id")
    b = Area(name="B",
             desc="area_desc",
             domain=[9],
             action=lambda: 5,
             resource_id="b_id")
    z = Zone([a, b])
    for x in z.areas:
        x.zone = z

    assert a.zone == z
    assert b.zone == z

    # Test adjacency
    assert a.getAdjacent() == b
    assert b.getAdjacent() == a
示例#16
0
def test_fields():

    # sample areas
    a1 = Area(name="area1",
              desc="area desc",
              domain=[8],
              action=lambda: 1,
              resource_id="r_id")
    a2 = Area(name="area2",
              desc="area desc",
              domain=[9],
              action=lambda: 0,
              resource_id="r_id")

    # test initialization
    areas = [a1, a2]
    z = Zone(areas)

    # test fields
    assert z.areas == areas

    # test dump
    assert z.dump() == [a1.dump(), a2.dump()]
示例#17
0
文件: game.py 项目: alkk94/sixteen
 def get_board():
     numbers = []
     for i in range(1, NUMBER_X * NUMBER_Y + 1):
         numbers.append(i)
     board = []
     for i in range(NUMBER_X):
         areas = []
         for j in range(NUMBER_Y):
             x = random.randint(0, len(numbers) - 1)
             position = i * ELEMENT_SIZE, j * ELEMENT_SIZE
             areas.append(Area(position, numbers[x]))
             numbers.pop(x)
         board.append(areas)
     return board
示例#18
0
  def __init__(self, env):
    self.env = env
    self.actor_moved = [i for i in range(3)]
    self.areas = [Area(i, "area %d" %i, 100, env) for i in range(3)]

    self.actors = [Actor(i, self.areas[i], env) for i in range(self.ACTOR_COUNT)]

    self.actor_wait_event_procs = [env.process(self.actors[i].process_event()) for i in range(3)]

    # self.actor_procs = env.process(self.trigger_actor_events())
    self.check_actors_procs = env.process(self.check_actors())

    self.area_move_in_procs = [env.process(self.areas[i].move_in()) for i in range(self.AREA_COUNT)]
    self.area_move_out_procs = [env.process(self.areas[i].move_out()) for i in range(self.AREA_COUNT)]
示例#19
0
    def test_generateBasePopulation(self):
        area = Area('draw', numberOfBlocks)
        ga = GeneticAlgorithm(area, populationSize, mutationPercent,
                              successionRate, diversityRate, time, solution,
                              secondStage, progress)

        basePopulation = ga.createBasePopulation()

        self.assertEqual(basePopulation.shape,
                         (ga.populationSize, ga.area.numberOfBlocks + 1))
        self.assertEqual(sum(basePopulation[-1, :-1]),
                         sum(basePopulation[0, :-1]))
        self.assertEqual(sum(basePopulation[0, :-1]),
                         sum(range(0, ga.area.numberOfBlocks)))
        self.assertEqual(
            sum(np.sum(basePopulation[:, :-1], axis=1)),
            sum(range(0, ga.area.numberOfBlocks)) * ga.populationSize)
示例#20
0
def frame(area):
    startX = area.left
    startY = area.top
    endX = area.right
    endY = area.bottom

    yield (startX, startY, "stationary")
    yield (startX, endY, "stationary")
    yield (endX, endY, "stationary")
    yield (endX, startY, "stationary")

    for coords in ((startX + 1, startY, endX - 1, startY), (startX, startY + 1,
                                                            startX, endY - 1),
                   (startX + 1, endY, endX - 1, endY), (endX, startY + 1, endX,
                                                        endY - 1)):
        for point in line(Area(*coords)):
            yield point
示例#21
0
    def select_area(epsg_code: str, areas_json: [dict],
                    point_json: dict) -> dict:
        epsg_code = 'epsg:' + epsg_code
        areas = [
            Area(json['name'],
                 Geometry.from_geojson(json['geometry'], epsg_code))
            for json in areas_json
        ]
        point = Geometry.from_geojson(point_json, epsg_code)

        selected_area = Model(areas).select_area(point)

        selected_area.boundary_distance(point)

        if selected_area is None:
            return None

        return {
            'selected_area': selected_area.representation(),
            'boundary_distance': selected_area.boundary_distance(point)
        }
示例#22
0
    def reset(self):
        # This ensures that the traffic arrays (which size is dynamic)
        # are all reset as well, so all lat,lon,sdp etc but also objects adsb
        super(Traffic, self).reset()
        self.ntraf = 0

        # Reset models
        self.wind.clear()

        # Build new modules for area and turbulence
        self.area       = Area()
        self.Turbulence = Turbulence()

        # Noise (turbulence, ADBS-transmission noise, ADSB-truncated effect)
        self.setNoise(False)

        # Default: BlueSky internal performance model.
        # Insert your BADA files to the folder "BlueSky/data/coefficients/BADA"
        # for working with EUROCONTROL`s Base of Aircraft Data revision 3.12
        self.perf    = Perf()
        self.trails.reset()
示例#23
0
def test_fields():

    # test initialization
    a = Area(name="area_name",
             desc="area_desc",
             domain=[9],
             action=lambda: 5,
             resource_id="r_id")

    # test fields
    assert a.name == "area_name"
    assert a.desc == "area_desc"
    assert len(a.domain) == 1 and a.domain[0] == 9
    assert a.action() == 5
    assert a.resource_id == "r_id"

    # test dump
    dump = a.dump()
    assert dump['name'] == "area_name"
    assert dump['desc'] == "area_desc"
    assert dump['domain'] == "[9]"
    assert str(dump) == str(a)
示例#24
0
    def __init__(self, size):
        self.perf = 0
        self.size = size
        self.grid = [[Area(x, y) for x in range(self.size)]
                     for y in range(self.size)]

        self.situate_portal()
        for i in range(0, self.size):
            for j in range(0, self.size):
                self.grid[i][j].left_neighbour = self.get_area_at_position(
                    j - 1, i)
                self.grid[i][j].right_neighbour = self.get_area_at_position(
                    j + 1, i)
                self.grid[i][j].up_neighbour = self.get_area_at_position(
                    j, i - 1)
                self.grid[i][j].down_neighbour = self.get_area_at_position(
                    j, i + 1)
                self.grid[i][j].onNeighborsSet()
                if not (i == 0 & j == 0):
                    if not (self.grid[i][j].get_portal()):
                        if not (self.generate_monster(j, i)):
                            self.generate_hole(j, i)
示例#25
0
from area import Area
from item import Item
from player import Player

start = Area(
    "You find yourself stranded in the middle of a road.  Looking to either "
    "side you see nothing but nondescript forest.  It appears your only "
    "path is either forward, farther down to where you were apparently "
    "going, or backwards, from where you apparently came. ",
    "A barren stretch of road.  How did you end up there? "
    )

keychain = Item(
    frozenset(["keys", "keychain", "key"]),
    "The keychain is made up of three keys and a key fob with the word "
    "\"TESIN\" inscribed on a tiny, rubber computer mouse.  Two of the keys "
    "are rather plain but the third has a Toyota symbol on it. ",
    "There is a keychain at your feet. "
    )

wallet = Item(
    frozenset(["wallet", "billfold", "pocketbook"]),
    "Looking inside the wallet, you find a small photo of yourself with your "
    "arm around someone's sholders.  There's a couple fives as well as an old "
    "library card. ",
    "There is a wallet laying on the road to your left. "
    )

forward = Area(
    "After a few hours of walking you notice it's starting to get dark. You "
    "decide it would be better to set up camp before night falls, so you "
示例#26
0
from area import Area
from zodiaco import Zodiaco
from euler import Euler

while True:
    print("1. Calcular areas")
    print("2. Saber signo Zodiacal")
    print("3. Numero e")
    opc = input("Elige una opcion: ")

    if opc == "1":
        a = Area()
        while True:
            print("\n1. Area cuadrado")
            print("2. Area triangulo")
            print("3. Area circulo")
            op = input("Elige una opcion: ")

            if op == "1":
                a.areaCuadrado()
            elif op == "2":
                a.areaTriangulo()
            elif op == "3":
                a.areaCirculo()
            elif op == "0":
                break

    elif opc == "2":
        print("\n")
        z = Zodiaco()
        z.signo()
示例#27
0
def index2(receipt_id):
    # takes in the click coords and receipt id and returns the text value if it exists within one of the box coords

    # clicked_coords = request.form.get('coords')
    # clicked_coords = [1500, 1600] #test case
    # #should output RM15.09

    #obtains click coordinates from the user
    clicked_coords = request.get_data()
    clicked_coords = clicked_coords.decode('utf-8')
    clicked_coords = clicked_coords.split(',')
    clicked_coords_x = int(clicked_coords[0])
    clicked_coords_y = int(clicked_coords[1])

    receipt = Receipt.get_by_id(receipt_id)

    if receipt:
        receipt_details = Receipt_details.select().where(
            Receipt_details.receipt == receipt)
        for i in receipt_details:
            # check each item in receipt_details to see if the CC is in the box
            tuple_coords = eval(i.coords)
            TL_x = tuple_coords[0][0]
            TL_y = tuple_coords[0][1]
            BR_x = tuple_coords[1][0]
            BR_y = tuple_coords[1][1]

            if BR_x - TL_x < 20:
                TL_x -= 25
                BR_x += 25

            TL_y -= 10
            BR_y += 10
            '''
test code, should return True, and i.text = RM15.09

when receipt_id = 17

clicked_coords = [1500, 1600] 
clicked_coords_x = clicked_coords[0]
clicked_coords_y = clicked_coords[1] 
TL_x = 1448
TL_y = 1578
BR_x = 1699
BR_y = 1637
            '''

            test2 = Area(TL_x, TL_y, BR_x, BR_y)

            if test2.inside(clicked_coords_x, clicked_coords_y) == True:
                # if the clicked coords are inside of a bound box of a certain item, then return the items that exist on the same row, in a list
                line_list = []
                height = BR_y - TL_y
                var_factor = 0.30
                y_low = TL_y - height * var_factor
                y_high = height * var_factor + BR_y
                for i in receipt_details:
                    # searching through receipt details to see what items exist in the range of these y coords y_low to y_high
                    tuple_coords = eval(i.coords)
                    TL_y = tuple_coords[0][1]
                    BR_y = tuple_coords[1][1]
                    line_instance = Line(TL_y, BR_y)
                    if line_instance.inside_line(y_low, y_high) == True:
                        line_list.append(i)
                largest_BR_x = 0
                for i in line_list:
                    tuple_coords = eval(i.coords)
                    BR_x = tuple_coords[1][0]
                    if BR_x > largest_BR_x:
                        largest_BR_x = BR_x
                        subtotal = i.text
                        i_subtotal = i
                    #   want the largest_BR_x to be set as subtotal in the JSON
                    if RepresentsInt(i.text):
                        quantity = i.text
                        i_quantity = i
                    #remove the subtotal and qty from the list, join the remaining stuff and call it description
                subtotal_value = float((re.findall(r"(\d+[\,\.]\d{0,2})",
                                                   subtotal))[0])
                # regex to extract price as a float out ex. RM15.09 -> 15.09

                quantity_value = float(quantity)

                line_list.remove(i_subtotal)
                line_list.remove(i_quantity)
                description_list = []
                for item in line_list:
                    description_list.append(item.text)
                # description_list = description_list[::-1]
                description = ' '.join(description_list)

                unit_price = subtotal_value / quantity_value
                unit_price = round(unit_price, 2)
                # find out the unit price by diving subtotal by quantity

                # if BR_x is the biggest, then it is the subtotal
                # if i.text == an integer, then it is the quantity
                # the remaining elements are the description. the unit price might be thrown into the description
                # calculate the unit price by dividing the subtotal by the qty

                return jsonify(description=description,
                               quantity=quantity_value,
                               unit_price=unit_price,
                               subtotal=subtotal_value)
                # returns json with a list of all the items that exist in the row
                # want to output QTY, description, subtotal

    # takes clicked coords, runs it through the query with the receipt_id and returns the text value, else return none
    return 'not found'
    def genrate_ds(self, data, all_paths, folder_id, years):
        # years=[(((int(data['Year']))-3)-x) for x in range(0,10)][::-1]
        # flag for compeletion of main csv data
        flag2 = False
        #create path
        # get dataation coordinates
        area = data['Co-ordinate']
        # genrate 4*4 grid of the coordinates
        elements = self.gc.grid(area)
        # calculate the total area of the gird
        total_area = Area({'type': 'Polygon', 'coordinates': area}) / 1000000
        # create dict for new row in main df
        new_row_common = {
            'AREA': [data['Area'].replace(" ", "_")],
            'REGION': [data['Region'].replace(" ", "_")]
        }
        new_main_df_row = self.merge_two_dicts(new_row_common, {
            'CO-ORDINATES': [data['Co-ordinate']],
            'TOTAL_AREA': [total_area]
        })
        new_forest_row,new_crop_row,new_builtup_row, \
        new_burn_row,new_lst_row,new_airtemp_row, \
        new_ndvi_row,new_runoff_row, \
        new_pdsi_row,\
        new_vpd_row,new_water_defict_row=self.create_empty_dict_rows(new_row_common)
        df_dict = {
            0: new_forest_row,
            1: new_crop_row,
            2: new_builtup_row,
            3: new_airtemp_row,
            4: new_lst_row,
            5: new_burn_row,
            6: new_ndvi_row,
            7: new_runoff_row,
            8: new_pdsi_row,
            9: new_vpd_row,
            10: new_water_defict_row
        }
        year_loop = tqdm(years)
        for year in year_loop:

            if year < 2013:
                #landsat 7
                isl8 = False
                # define limits for calculations
                forest_limit = 0.22
                crop_limit1 = 0.09
                crop_limit2 = 0.15
                builtup_limit_1 = 0
                builtup_limit_2 = 0
            else:
                #landsat 8
                isl8 = True
                # define limits for calculations
                forest_limit = 0.18
                crop_limit1 = 0.07
                crop_limit2 = 0.17
                builtup_limit_1 = 0.2
                builtup_limit_2 = 0

            flag1 = False

            print(f"{data['Region']}_{data['Area']}_{year}")
            sys.stdout.flush()
            for i in range(0, len(elements)):

                # calculate the total grid area
                grid_area = Area({
                    'type': 'Polygon',
                    'coordinates': [elements[i]]
                }) / 1000000
                new_main_df_row[f'G{i}_AREA'] = []
                new_main_df_row[f'G{i}_AREA'].append(grid_area)

                green,red,nir,swir,thermal,\
                tmmx,pdsi,vpd,ro,def_=self.readImages(region=data['Region'],area=data['Area'],year=year,grid=i,isl8=isl8,folder_id=folder_id)
                # if area per pixel is not calculated then calculate it
                if not flag1:
                    # calculate the area per pixel
                    area_per_pixel = grid_area / (green.shape[0] *
                                                  green.shape[1])
                    # set the flag to true
                    flag1 = True
                # calculate the required features
                forest, crops, builtup, burn, lst, ndvi = self.calculation_of_domain(
                    island8=isl8,
                    red=red,
                    nir=nir,
                    thermal=thermal,
                    green=green,
                    swir=swir,
                    forest_limit=forest_limit,
                    crop_limit1=crop_limit1,
                    crop_limit2=crop_limit2,
                    builtup_limit_1=builtup_limit_1,
                    builtup_limit_2=builtup_limit_2)
                feature_data = [
                    forest, crops, builtup, tmmx, lst, burn, ndvi, ro, pdsi,
                    vpd, def_
                ]
                features = {
                    0: 'FOREST',
                    1: 'CROP',
                    2: 'BUILTUP',
                    3: 'AIRTEMP',
                    4: 'LST',
                    5: 'BURN',
                    6: "NDVI",
                    7: "RUNOFF",
                    8: "PDSI",
                    9: "VPD",
                    10: "WATER_DEFICIT"
                }
                for (k, df), (_, feature) in zip(df_dict.items(),
                                                 features.items()):
                    if k in range(3, 11):
                        if f'{year}_{feature}_MEAN_G{i}' not in df:
                            df[f'{year}_{feature}_MEAN_G{i}'] = []
                        df[f'{year}_{feature}_MEAN_G{i}'].append(
                            np.mean(feature_data[k]))

                        if f'{year}_{feature}_MEDIAN_G{i}' not in df:
                            df[f'{year}_{feature}_MEDIAN_G{i}'] = []
                        df[f'{year}_{feature}_MEDIAN_G{i}'].append(
                            np.median(feature_data[k]))

                        if f'{year}_{feature}_MIN_G{i}' not in df:
                            df[f'{year}_{feature}_MIN_G{i}'] = []
                        df[f'{year}_{feature}_MIN_G{i}'].append(
                            np.min(feature_data[k]))

                        if f'{year}_{feature}_MAX_G{i}' not in df:
                            df[f'{year}_{feature}_MAX_G{i}'] = []
                        df[f'{year}_{feature}_MAX_G{i}'].append(
                            np.max(feature_data[k]))
                    else:
                        if f'{year}_{feature}_G{i}' not in df:
                            df[f'{year}_{feature}_G{i}'] = []
                        df[f'{year}_{feature}_G{i}'].append(
                            self.calculate_area(feature_data[k],
                                                area_per_pixel))
            if not flag2:
                self.add_to_df(new_main_df_row, all_paths[0])
                flag2 = True
        for df, path in zip(df_dict.values(), all_paths[1:]):
            self.add_to_df(df, path)
from grid import Grid
from hero import Hero
from enemies import *
from area import Area
import random

image_size = 72
board_size = 10
root = Tk()
canvas = Canvas(root,
                width=image_size * board_size,
                height=image_size * board_size + 100)

grid = Grid(board_size)
hero = Hero()
area = Area(grid)
background = Resource()
level = 1


def on_key_press(e):
    # When the keycode is 111 (up arrow) we move the position of our box higher
    is_tile_occupied = hero.is_tile_occupied(area.enemy_list)
    if e.keycode == 65:
        hero.erase(canvas, background, image_size)
        if grid.grid[hero.x - 1][
                hero.
                y].cell_type == "floor" and hero.x - 1 >= 0 and not is_tile_occupied:
            hero.x = hero.x - 1
        hero.image = "hero_left"
        hero.draw(canvas, background, image_size)
示例#30
0
    def __init__(self,
                 id=None,
                 robot_actions=dict(),
                 team_robot_ids=list(),
                 earliest_start_time=-1,
                 latest_start_time=-1,
                 estimated_duration=-1,
                 pickup_pose=Area(),
                 delivery_pose=Area(),
                 **kwargs):
        """Constructor for the Task object

        Args:
            id (str): A string of the format UUID
            robot_actions (dict): A dictionary with robot IDs as keys, and the list of actions to execute as values
            loadType (str): Valid values are "MobiDik", "Sickbed". Defaults to MobiDik
            loadId (str): A string of the format UUID
            team_robot_ids (list): A list of strings containing the UUIDs of the robots in the task
            earliest_start_time (TimeStamp): The earliest a task can start
            latest_start_time (TimeStamp): The latest a task can start
            estimated_duration (timedelta): A timedelta object specifying the duration
            pickup_pose (Area): The location where the robot should collect the load
            delivery_pose (Area): The location where the robot must drop off its load
            priority (constant): The task priority as defined by the constants EMERGENCY, HIGH, NORMAL, LOW
            hard_constraints (bool): False if the task can be
                                    scheduled ASAP, True if the task is not flexible. Defaults to True
        """

        if not id:
            self.id = generate_uuid()
        else:
            self.id = id
        self.robot_actions = robot_actions
        self.loadType = kwargs.get('loadType', 'MobiDik')
        self.loadId = kwargs.get('loadId', generate_uuid())
        self.team_robot_ids = team_robot_ids
        self.earliest_start_time = earliest_start_time
        self.latest_start_time = latest_start_time
        self.estimated_duration = estimated_duration
        self.earliest_finish_time = earliest_start_time + estimated_duration
        self.latest_finish_time = latest_start_time + estimated_duration
        self.start_time = kwargs.get('start_time', None)
        self.finish_time = kwargs.get('finish_time', None)
        self.hard_constraints = kwargs.get('hard_constraints', True)

        if isinstance(pickup_pose, Area):
            self.pickup_pose = pickup_pose
        else:
            raise Exception('pickup_pose must be an object of type Area')

        if isinstance(delivery_pose, Area):
            self.delivery_pose = delivery_pose
        else:
            raise Exception('delivery_pose must be an object of type Area')

        self.status = TaskStatus(self.id)

        priority = kwargs.get('priority', self.NORMAL)
        if priority in (self.EMERGENCY, self.NORMAL, self.HIGH, self.LOW):
            self.priority = priority
        else:
            raise Exception("Priority must have one of the following values:\n"
                            "0) Urgent\n"
                            "1) High\n"
                            "2) Normal\n"
                            "3) Low")