Exemple #1
0
def short(request):
    retorno = ''
    
    if request.GET.get('target',''):
        param = request.GET.get('target','')
        
        if 'http://localhost:8080/oshtr' in param:
            retorno = "URL já encurtada pelo serviço."
        
        else:    
            pair = Map.objects(url_tgt = param)
            
            if pair.count() > 0:
                #implementar o retorno
                retorno = pair.get().url_sht
                retorno = '<a href=''http://localhost:8080/oshtr/%s''> http://localhost:8080/oshtr/%s </a>' %(str(retorno), str(retorno))
            else:
                try:
                    novo = Map(url_tgt = param)
                    novo.url_sht = geraChave()
                    novo.save()
                    retorno = novo.url_sht
                    retorno = '<a href=''http://localhost:8080/oshtr/%s''> http://localhost:8080/oshtr/%s </a>' %(str(retorno), str(retorno))
                except ValidationError:
                    retorno = "<font color='red'>URL inválida!</font>"
         
    return HttpResponse(retorno)
Exemple #2
0
def new(request):
    """
    Funkcja zwraca stronę z formularzem do dodania nowej mapy lub zapisuje mapę
    w zależności od typus żądania: GET (utwórz formularz) lub POST (zapisz formularz).
    """
    formpoint = NewPointForm()
    if request.method == 'POST':
        form = NewMapForm(request.POST)
        if form.is_valid():
            map = Map()
            southwest  = LatLng()
            northeast  = LatLng()
            map.name = form.cleaned_data['name']
            map.tags = form.cleaned_data['tags']
            map.latlngs = form.cleaned_data['latlngs']
            map.city = form.cleaned_data['city']
            map.distance = form.cleaned_data['distance']
	    southwest.latit = form.cleaned_data['swlat']
	    southwest.longi = form.cleaned_data['swlng']
	    northeast.latit = form.cleaned_data['nelat']
	    northeast.longi = form.cleaned_data['nelng']
	    southwest.save()
	    northeast.save()
	    map.southwest = southwest
	    map.northeast = northeast
	    map.save()
            messages.success(request, ADDED)
            return redirect('map', slug=map.slug, map_id=map.id)
    elif request.method == 'GET':
        form = NewMapForm()
    return direct_to_template(request, 'maps/new.html', { 'form': form, 'formp': formpoint })
Exemple #3
0
def show_large_map(key):
    kwargs = get_template_hash()

    if re.search('^\d+$', key):
        kwargs['map'] = Map.all().filter("id =", int(key)).get()
    elif re.search('^(\d+,)*\d+$', key):
        kwargs['map_id_list'] = ",".join(str(x) for x in key.split(','))
    else:
        map = Map.all().filter("tag =", key).fetch(1000)
        kwargs['map_id_list'] = ",".join(str(x.id) for x in map)

    return render_template('show_large_map.html', **kwargs)
def maps():
    if request.method == 'POST':
        if ('bbox' not in request.json):
            abort(400)

        m = Map(request.json['bbox'])
        if 'name' in request.json:
            m.name = request.json['name']
        db.session.add(m)
        db.session.commit()
        return jsonify(m.to_dict())
    return jsonify([m.to_dict() for m in db.session.query(Map).all()])
Exemple #5
0
 def test_pool_use_lease(self):
     ip = self.sub.network.host(2).dq
     map = Map(subnet=self.sub)
     map.save()
     lease = Lease(map=map, ip=ip)
     lease.save()
     pool_entry = Pool.objects.get(ip=ip)
     self.assertEqual(pool_entry.used, True)
     self.assertEqual(pool_entry.map, map)
     lease.delete()
     pool_entry = Pool.objects.get(ip=ip)
     self.assertEqual(pool_entry.used, False)
     self.assertEqual(pool_entry.map, None)
Exemple #6
0
def xml(map_id):
    if re.search('^\d+$', map_id):
        maps = Map.all().filter("id = ", int(map_id)).fetch(1)
    else:
        map_id_list = [int(x) for x in map_id.split(',')]
        maps = Map.all().filter("id IN", map_id_list).fetch(1000)

    for map in maps:
        map.polylines = Polyline.all().filter("map =", map).fetch(1000)
        map.markers = Marker.all().filter("map =", map).fetch(1000)

    xml = render_template('map.xml', maps=maps)

    resp = app.make_response(xml)
    resp.headers['Content-Type'] = 'application/xml; charset=UTF-8'
    return resp
Exemple #7
0
 def test_values_created_map(self):
     maps = Map("46B E59 EA C1F")
     expected_human_grid = [[1131, 3673], [234, 3103]]
     human_grid = maps.grid
     for expected_results, results in zip(expected_human_grid, human_grid):
         for result, expected_result in (results, expected_results):
             self.assertTrue(result, expected_result)
Exemple #8
0
 def init_grid(self):
     """Create map list with nest loop"""
     for points in self.cord_list:
         column_grid_list = []
         for point in points:
             grid = Map(point[0] * 80, point[1] * 80)
             column_grid_list.append(grid)
         self.grid_list.append(column_grid_list)
Exemple #9
0
 def from_db_object(self, db_object):
     floor = [
         self.parse_point(point) for point in db_object['floor_polygon']
     ]
     walls = [[self.parse_point(wall[0]),
               self.parse_point(wall[1])] for wall in db_object['walls']]
     name = db_object["name"]
     _id = db_object.get("_id")
     return Map(name, floor, walls, _id)
Exemple #10
0
def setMap(request, mid, name, description):
    if request.user.is_authenticated():
        try :
            newName = replace(name, "_", " ")
            newDescription = replace(description, "_", " ")
            if int(mid) > 0:
                m = Map.objects.get(mid=mid)
                m.name = newName
                m.description = newDescription
                m.save()
                return success()
            else:
                m = Map(description=newDescription, name=newName)
                m.save()
                return HttpResponse("insert_"+str(m.mid))
        except:
            return HttpResponse("Erreur "+traceback.format_exc())
    return failure()
Exemple #11
0
    def show_path_up_righ_down_left(self):

        maps = Map(
            "1 20 1 1 1 1 1 1 20 1 20 20 20 1 1 20 20 20 1 20 20 20 20 1 1")
        start = (0, 0)
        end = (4, 4)
        robot = Robot(maps, start, end, "Optimal")
        print("Map with up down right left")
        print(robot.maps)
        print("Optimal path from file {}".format(robot.get_min_path()))
Exemple #12
0
    def __init__(self, filename=None):

        available_grid = "46B E59 EA C1F 45E 63 899 FFF 926 7AD C4E FFF E2E 323 6D2 976 83F C96 9E9 A8B 9C1 461 F74 D05 EDD E94 5F4 D1D D03 DE3 89 925 CF9 CA0 F18 4D2"
        if filename:
            available_grid = self._read_file(filename)
        else:
            print(
                "Supporting default grid: 46B E59 EA C1F 45E 63 899 FFF 926 7AD C4E FFF E2E 323 6D2 976 83F C96 9E9 A8B 9C1 461 F74 D05 EDD E94 5F4 D1D D03 DE3 89 925 CF9 CA0 F18 4D2"
            )
        self.map = Map(available_grid)
Exemple #13
0
def list_tags():
    kwargs = get_template_hash()

    kwargs['tags'] = {}
    for map in Map.all().fetch(1000):
        for tag in map.tag:
            if tag not in kwargs['tags']:
                kwargs['tags'][tag] = 0

            kwargs['tags'][tag] += 1

    return render_template('list_tags.html', **kwargs)
Exemple #14
0
def setup():  # Setup objects for the level from module courses
    global level, line, par, hole, power, ball, level_map, stickyPower, superPower, mullagain
    ball.color = (255,255,255)
    stickyPower = False
    superPower = False
    mullagain = False
    if level >= 10:
        endScreen()  # Completed the course
    else:
        list = courses.getPar(1)
        par = list[level - 1]
        pos = courses.getStart(level, 1)
        ball.set_coordinates(*pos)

        level_map = Map(courses.getLvl(level))

        # Create the borders if sand is one of the objects
        for flag in level_map.flags():
            hole = MapHole(flag.x1 + 2, flag.y1 + flag.y2)

        line = None
        power = 1
 def getMapById(self, id):
     try:
         data = self.getOneElementById('maps', id)
         if data:
             print("Successfully retrieved map")
             from models import Map
             return Map(*data)
         else:
             print("Failed to retrieve map: no map")
             return None
     except:
         print("Failed to retrieve map: no connection", sys.exc_info()[1])
         return None
Exemple #16
0
def convert_maps_file_to_mongo(maps_in, json_out, map_type):
  """
  Convert a maps file to the mongo format so it can be
  imported with mongoimport.
  """
  report_interval = 1000

  map_gen = (Map.from_line(l, map_type) for l in maps_in)
  for i, m in enumerate(map_gen):
    
    json_out.write(m.to_json() + '\n')

    if (i+1) % report_interval == 0:
      sys.stderr.write("Converted %i maps\n"%(i+1))
Exemple #17
0
def get(request):
    param = request.get_full_path()
    param = param.replace("/oshtr/", "")
    
    pair = Map.objects(url_sht = param)
    
    if pair.count() > 0:
        #implementar o retorno
        target = pair.get().url_tgt
        retorno =  HttpResponseRedirect(target)
    else:
        retorno = HttpResponse("Página não encontrada")
        
    return retorno
Exemple #18
0
def index():
    page = int(request.args.get('page', 0))
    kwargs = get_template_hash()

    maps = Map.all().order('-id').fetch(PAGESIZE + 1, page * PAGESIZE)
    kwargs['page'] = page
    if len(maps) == PAGESIZE + 1:
        kwargs['maps'] = maps[:PAGESIZE]
        kwargs['nextpage'] = True
    else:
        kwargs['maps'] = maps
        kwargs['nextpage'] = False

    return render_template('list.html', **kwargs)
def createMap(name, background, difficulty, mod1, mod1Amt, mod2, mod2Amt, mod3,
              mod3Amt):
    newMap = Map(name=name,
                 background=background,
                 difficulty=difficulty,
                 modifier1Name=mod1,
                 modifier1Amount=mod1Amt,
                 modifier2Name=mod2,
                 modifier2Amount=mod2Amt,
                 modifier3Name=mod3,
                 modifier3Amount=mod3Amt)
    db.session.add(newMap)
    db.session.commit()
    print('New Map Created: ', name, 'background:', background, 'difficulty:',
          difficulty, 'modifier1Name:', mod1, 'modifier1Amount', mod1Amt,
          'modifier2Name:', mod2, 'modifier2Amount', mod2Amt, 'modifier3Name:',
          mod3, 'modifier3Amount', mod3Amt)
def addMapWithCells(db, mapData, zonesRadius, cellList):
	map_ = Map(id=mapData[0], name=mapData[1], maxX=mapData[2], maxY=mapData[3])
	db.session.add(map_)
	db.session.flush()

	for i in range(0, len(cellList)):
		for j in range(0, len(cellList[0])):
			if cellList[i][j] == 0:
				continue

			r = 0 if (cellList[i][j] == -1 or cellList[i][j] == 0) else zonesRadius[cellList[i][j]]
			cell = Cell(map=mapData[0], value=cellList[i][j], radius=r, posX=j, posY=i)
			db.session.add(cell)
			db.session.flush()

	db.session.commit()

	print ('Added map {0}'.format(mapData[1]))
Exemple #21
0
def list(tag=None):
    mode = request.args.get('mode')
    page = int(request.args.get('page', 0))
    kwargs = get_template_hash()

    query = Map.all().order('-id')
    if tag:
        query = query.filter("tag =", tag)

    maps = query.fetch(PAGESIZE + 1, page * PAGESIZE)
    kwargs['page'] = page
    if len(maps) == PAGESIZE + 1:
        kwargs['maps'] = maps[:PAGESIZE]
        kwargs['nextpage'] = True
    else:
        kwargs['maps'] = maps
        kwargs['nextpage'] = False

    return render_template('list.html', **kwargs)
Exemple #22
0
def game():

    # Create Temp Map for Standard Game
    thisMap = Map(name="Temp",
                  background="space1.png",
                  difficulty=1,
                  modifier1Name="",
                  modifier1Amount=0,
                  modifier2Name="",
                  modifier2Amount=0,
                  modifier3Name="",
                  modifier3Amount=0)

    if 'id' in session:
        loggedInUser = Users.query.get(session['id'])
    else:
        print('NO LOGGED IN USER -- GAME ROUTE')
        loggedInUser = False

    return render_template("game.html", thisUser=loggedInUser, thisMap=thisMap)
Exemple #23
0
    def post(self, group_id):
        args = map_parser.parse_args()

        # get group by id
        group = read_group(current_user, group_id)

        logger.debug(
            "User '%s' (%i) adding map: '%s' to group '%s'" %
            (current_user.name, current_user.id, args["name"], group.name))

        # create new map
        mapobj = Map(args["name"])

        # make group relation
        group.maps.append(mapobj)

        # commit transaction
        db.session.add(mapobj)
        db.session.commit()
        return mapobj
Exemple #24
0
 def test_create_valid_map(self):
     maps_size_x, maps_size_y = 6, 6
     maps = Map(get_str_map())
     self.assertTrue(len(maps.grid), maps_size_x)
     self.assertTrue(len(maps.grid[0]), maps_size_y)
Exemple #25
0
# SET ICON
pygame.display.set_icon(icon)

# GLOBAL VARIABLES
angle = 0
rollVel = 0
strokes = 0
par = 0
level = 1
coins = 0
shootPos = ()
ball = Ball(0, 0, (255,255,255))
line = None
power = 0
level_map = Map([])
put = False
shoot = False

# LOAD MUSIC
if SOUND:
    wrong = pygame.mixer.Sound(os.path.join('sounds', 'wrong12.wav'))
    puttSound = pygame.mixer.Sound(os.path.join('sounds', 'putt.wav'))
    inHole = pygame.mixer.Sound(os.path.join('sounds', 'inHole.wav'))
    song = pygame.mixer.music.load(os.path.join('sounds', 'music.mp3'))
    splash = pygame.mixer.Sound(os.path.join('sounds', 'splash.wav'))
    pygame.mixer.music.play(-1)

# POWER UP VARS
powerUps = 7
hazard = False
Exemple #26
0
def set_flag():
    if request.form.get('type'):
        type = int(request.form.get('type', 0))
        latitude = float(request.form.get('latitude', 0))
        longitude = float(request.form.get('longitude', 0))
        name = request.form.get('name', '')
    if not request.form.get('id'):
        m = Map(type, name, latitude, longitude)
        m.save()
        return success('成功创建')
    else:
        id = int(request.form.get('id'))
        m = Map.query.get(id)
        if request.form.get('delete'):
            m.delete()
            return success('成功删除')
        else:
            m.type = type
            m.name = name
            m.latitude = latitude
            m.longitude = longitude
            m.save()
            return success('成功更新')
    return success('参数错误')
Exemple #27
0
def show_map(map_id):
    kwargs = get_template_hash()

    kwargs['map'] = Map.all().filter("id =", map_id).get()
    return render_template('show_map.html', **kwargs)
Exemple #28
0
def sitemap():
    maps = Map.all().order('-id').fetch(1000)
    return render_template('sitemap.xml', maps=maps)
Exemple #29
0
 def test_delete_map(self):
     '''
     Usuwa mapę po utworzeniu.
     '''
     form = NewMapForm({
         'name': 'Test',
         'tags': 'test1, test2',
         'city': 'Warszawa',
         'latlngs': '0.1,0.2;0.3,0.4;',
         'distance': '120.5',
         'swlat': '0.1',
         'swlng': '0.2',
         'nelat': '0.3',
         'nelng': '0.4',
         })
     self.assertTrue(form.is_valid(), 'Formularz jest niepoprawny')
     map = Map()
     southwest  = LatLng()
     northeast  = LatLng()
     map.name = form.cleaned_data['name']
     map.tags = form.cleaned_data['tags']
     map.latlngs = form.cleaned_data['latlngs']
     map.city = form.cleaned_data['city']
     map.distance = form.cleaned_data['distance']
     southwest.latit = form.cleaned_data['swlat']
     southwest.longi = form.cleaned_data['swlng']
     northeast.latit = form.cleaned_data['nelat']
     northeast.longi = form.cleaned_data['nelng']
     southwest.save()
     northeast.save()
     map.southwest = southwest
     map.northeast = northeast
     map.save()
     map.delete()
     self.assertTrue(map.pk is None, 'Nieprawidłowo usunięta mapa')
    def parse_xml(self, path, module):
        logger.debug("parsing xml: %s", path)

        # lookup tables
        lookup = {}
        lookup["encounter"] = {}
        lookup["page"] = {}
        lookup["map"] = {}
        lookup["image"] = {}
        lookup["npc"] = {}
        lookup["quest"] = {}

        # arrays
        pages = []
        maps = []
        groups = []
        encounters = []

        # xml tree
        tree = ElementTree.parse(path)
        root = tree.getroot()

        # NPCS
        logger.info("parsing npcs")

        for category in root.findall("./npc/category"):
            for node in category.findall("*"):
                tag = node.tag
                name = node.find("name").text

                npc = NPC()
                npc.name = name
                lookup["npc"][tag] = npc

        # PAGES
        logger.info("parsing pages")

        parent = Group()
        parent.name = "Story"
        parent.slug = slugify(parent.name)
        groups.append(parent)

        for category in root.findall("./encounter/category"):

            group = Group()
            group.name = category.get("name")
            group.slug = slugify(group.name)
            group.parent = parent

            if group.name == None or group.name == "":
                group = parent
            else:
                groups.append(group)

            # get all pages
            for node in category.findall("*"):
                # tag
                tag = node.tag

                # create page
                page = Page()
                page.meta["tag"] = tag
                page.name = node.find("name").text
                page.slug = slugify(page.name)
                page.content = ElementTree.tostring(
                    node.find("text"), encoding='utf-8',
                    method='xml').decode('utf-8')
                page.parent = group

                pages.append(page)
                lookup["page"][tag] = page

        # QUESTS
        logger.info("parsing quests")

        parent = Group()
        parent.name = "Quests"
        parent.slug = slugify(parent.name)
        groups.append(parent)

        # some modules got, so use this instead
        for node in root.findall("./quest/*/*"):
            # for node in root.findall("./quest/*"):
            # tag
            tag = node.tag

            # create quest
            page = Page()
            page.meta["tag"] = id
            page.name = node.find("name").text
            page.slug = slugify(page.name)

            page.content = ElementTree.tostring(node.find("description"),
                                                encoding='utf-8',
                                                method='xml').decode('utf-8')

            cr = node.find("cr").text if node.find("cr") else ""
            xp = node.find("xp").text if node.find("xp") else ""

            page.content += '<p><strong>CR:</strong> ' + cr + ' <strong>XP:</strong> ' + xp + '</p>'
            page.parent = parent

            pages.append(page)
            lookup["quest"][tag] = page

        # sort
        pages_sorted = humansorted(pages, key=lambda x: x.name)

        # MAPS & IMAGES
        logger.info("parsing images and maps")

        parent = Group()
        parent.name = "Maps & Images"
        parent.slug = slugify(parent.name)
        groups.append(parent)

        for category in root.findall("./image/category"):
            group = Group()
            group.name = category.get("name")
            group.slug = slugify(group.name)
            group.parent = parent

            if group.name == None or group.name == "":
                group = parent
            else:
                groups.append(group)

            for node in category.findall("*"):
                # tag
                tag = node.tag

                # create image
                image = Image()
                image.tag = tag
                image.bitmap = node.find("./image/bitmap").text.replace(
                    "\\", "/")
                image.name = node.find("name").text

                lookup["image"][tag] = image

                markers = []

                # get shortcouts (markers)
                for shortcut in node.findall("./image/shortcuts/shortcut"):
                    # create marker
                    marker = Marker()
                    marker.x = shortcut.find("x").text
                    marker.y = shortcut.find("y").text

                    shortcut_ref = shortcut.find("recordname").text.replace(
                        "encounter.", "").replace("@*", "")
                    page = None
                    if shortcut_ref in lookup["page"]:
                        page = lookup["page"][shortcut_ref]

                        # remove chapter numbers from page name
                        # maybe use a regex?
                        name = page.name
                        if " " in page.name:
                            first, second = page.name.split(' ', 1)
                            if "." in first:
                                name = second

                        marker.name = name
                        marker.contentRef = "/page/" + page.slug

                    markers.append(marker)

                if markers:
                    # if markers not empty, its a map
                    map = Map()
                    map.parent = group
                    map.meta["tag"] = tag
                    map.name = image.name
                    map.slug = slugify(map.name)
                    map.image = image.bitmap
                    if node.find("./image/gridsize") != None:
                        map.gridSize = node.find("./image/gridsize").text
                    if node.find("./image/gridoffset") != None:
                        gridOffset = node.find("./image/gridoffset").text
                        map.gridOffsetX = gridOffset.split(",")[0]
                        map.gridOffsetY = gridOffset.split(",")[1]
                    map.markers = markers

                    maps.append(map)
                    lookup["map"][tag] = map
                else:
                    # otherwise, its a image
                    page = Page()
                    page.parent = group
                    page.meta["tag"] = tag
                    page.name = image.name
                    page.slug = slugify(page.name)
                    page.content = '<p><img class="size-full" src="' + image.bitmap + '" /></p>'

                    pages_sorted.append(page)
                    # do not add to lookup tables

        # sort
        maps_sorted = humansorted(maps, key=lambda x: x.name)

        # ENCOUNTERS
        logger.info("parsing encounters")

        parent = Group()
        parent.name = "Encounters"
        parent.slug = slugify(parent.name)
        groups.append(parent)

        for category in root.findall("./battle/category"):
            group = Group()
            group.name = category.get("name")
            group.slug = slugify(group.name)
            group.parent = parent

            if group.name == None or group.name == "":
                group = parent
            else:
                groups.append(group)

            for node in category.findall("*"):
                # tag
                tag = node.tag

                # create encounter
                encounter = Encounter()
                encounter.meta["tag"] = tag
                encounter.parent = group

                encounter.name = node.find("name").text
                encounter.slug = slugify(encounter.name)

                encounters.append(encounter)
                lookup["encounter"][tag] = encounter

                # get combatants
                for npcnode in node.find("npclist").findall("*"):

                    # get positions
                    maplinks = npcnode.findall("./maplink/*")

                    # combatants count
                    count = int(npcnode.find("count").text)

                    # iterate
                    for x in range(count):
                        combatant = Combatant()
                        combatant.name = npcnode.find("name").text
                        encounter.combatants.append(combatant)

                        # if position on map
                        if len(maplinks) == count:
                            maplinknode = maplinks[x]

                            if maplinknode.find("./imagex") != None:
                                combatant.x = maplinknode.find("./imagex").text

                            if maplinknode.find("./imagey") != None:
                                combatant.y = maplinknode.find("./imagey").text

        encounters_sorted = humansorted(encounters, key=lambda x: x.name)

        # custom regex for processing links
        def href_replace(match):
            key = str(match.group(2)).split("@")[0]

            type = match.group(1)

            if type == "image" and key in lookup["map"]:
                return 'href="/map/' + lookup["map"][key].slug
            elif type == "image" and key in lookup["image"]:
                return 'href="' + lookup["image"][key].bitmap
            elif type == "encounter" and key in lookup["page"]:
                return 'href="' + lookup["page"][key].slug
            elif type == "battle" and key in lookup["encounter"]:
                return 'href="/encounter/' + lookup["encounter"][key].slug
            elif type == "quest" and key in lookup["quest"]:
                return 'href="' + lookup["quest"][key].slug
            else:
                return key

        # fix content tags in pages
        for page in pages_sorted:
            content = page.content
            # maybe regex
            content = content.replace('<text type="formattedtext">',
                                      '').replace('<text>',
                                                  '').replace('</text>', '')
            content = content.replace('<description type="formattedtext">',
                                      '').replace('<description>', '').replace(
                                          '</description>', '')
            content = content.replace('<frame>',
                                      '<blockquote class="read">').replace(
                                          '</frame>', '</blockquote>')
            content = content.replace('<frameid>DM</frameid>', '')
            content = content.replace('\r', '<br />')
            content = content.replace('<h>', '<h3>').replace('</h>', '</h3>')
            content = content.replace('<list>',
                                      '<ul>').replace('</list>', '</ul>')
            # content = content.replace("<linklist>", "<ul>").replace("</linklist>", "</ul>")
            content = content.replace('<linklist>',
                                      '').replace('</linklist>', '')
            content = content.replace('<link',
                                      '<p><a').replace('</link>', '</a></p>')
            content = content.replace(' recordname', ' href')
            content = content.strip()

            # fix links
            content = re.sub(
                r'href=[\'"]?(encounter|battle|image|quest)\.([^\'">]+)',
                href_replace, content)

            # add title
            if content.startswith('<h3>'):
                page.content = content.replace('<h3>', '<h2>',
                                               1).replace('</h3>', '</h2>', 1)
            else:
                page.content = '<h2>' + page.name + '</h2>' + content

        # assign data to module
        module.groups = groups
        module.pages = pages_sorted
        module.maps = maps_sorted
        module.encounters = encounters_sorted

        return module
Exemple #31
0
    def test_create_string_map(self):
        with self.assertRaises(ValueError) as context:
            maps = Map("1312 1231 312312")

        self.assertTrue(context, "Invalid map generation")
Exemple #32
0
 def getMapInfo(self):
     return Map()
Exemple #33
0
def home(email):
    id = request.args.get('idUser')
    listaRefuerzos = []
    sizeTiles = [16,32]
    if request.method == 'GET':
        mapasUsuario = []
        mapas = Map.query.filter(Map.idUser==id).all()
        for mapa in mapas:
            mapasUsuario.append(mapa.nombreMapa)
        return render_template('carga.html',name=email,idUser = id,mapasUsuario = mapasUsuario)
    else:
        tipoCarga = request.form.get('tipoCarga')
        if tipoCarga == "Abrir nuevo mapa":
            mapaInput = request.files['mapaJson']
            tileSetInput = request.files['tileSet']
            if mapaInput.filename == '':
                flash('MAPA NO SELECCIONADO')
                return redirect(request.url)
            elif mapaInput.filename.split('.')[1] != "json":
                flash('EL MAPA NO ES ARCHIVO JSON')
                return redirect(request.url)
            elif tileSetInput.filename == '':
                flash('PATRONES NO SELECCIONADOS')
                return redirect(request.url)
            else:
                textJsonMap = mapaInput.read()
                mapa = Map.query.filter(Map.mapa==textJsonMap,Map.idUser==id).first()
                nombreMapa = Map.query.filter(Map.nombreMapa==mapaInput.filename,Map.idUser==id).first()
                if mapa:
                    flash('YA EXISTE ESTE MAPA')
                    return redirect(request.url)
                elif nombreMapa:
                    flash('YA EXITE UN MAPA CON ESTE NOMBRE')
                    return redirect(request.url)
                else:
                    capaObjetos = ''
                    capasBackground = []
                    nombreTileSet = tileSetInput.filename.split('.')[0]
                    mapaJson = json.loads(textJsonMap)
                    if mapaJson["tilesets"][0]["name"] != nombreTileSet:
                        flash('EL CONJUNTO DE PATRONES NO COINCIDE CON EL ASOCIADO AL MAPA')
                        return redirect(request.url)
                    for layer in mapaJson["layers"]:
                        if "objects" in layer.keys():
                            capaObjetos = layer["name"]
                            for object in layer["objects"]:
                                listaRefuerzos.append(object["properties"]["type"])
                        else:
                            capasBackground.append(layer["name"])

                    listaRefuerzos = list(set(listaRefuerzos))
                    refuerzos = "-".join(listaRefuerzos)
                    capasBackground = "-".join(capasBackground)
                    nCeldasAncho = mapaJson["width"]
                    nCeldasAlto = mapaJson["height"]
                    tileWidth = mapaJson["tilewidth"]
                    tileHeight = mapaJson["tileheight"]
                    width = nCeldasAncho*tileWidth
                    height = nCeldasAlto*tileHeight
                    if ((tileWidth not in sizeTiles) or (tileHeight not in sizeTiles)) and (tileWidth != tileHeight):
                        flash('ERROR EN LAS CELDAS')
                        return redirect(request.url)
                    elif (width > 480) or (height > 480):
                        flash('EL MAPA ES DEMASIADO GRANDE')
                        return redirect(request.url)

                    if tileWidth == sizeTiles[0]:
                        urlCirculo = url_for('static', filename='assets/circuloAmarillo16.png')
                        urlTesoro = url_for('static', filename='assets/tesoro16.png')
                        urlBot = url_for('static', filename='assets/bot16.png')
                    else:
                        urlCirculo = url_for('static', filename='assets/circuloAmarillo32.png')
                        urlTesoro = url_for('static', filename='assets/tesoro32.png')
                        urlBot = url_for('static', filename='assets/bot32.png')

                    map = Map(textJsonMap,id,mapaInput.filename,tileSetInput.read(),nombreTileSet,refuerzos,capaObjetos,capasBackground,width,height)
                    db_session.add(map)
                    db_session.commit()
                    urlMapa = url_for('getMap',id = id, nombreMapa = mapaInput.filename)
                    urlTileset = url_for('getTileset',id = id, nombreMapa = mapaInput.filename)
                    return render_template('index.html',name=email,urlMapa = urlMapa,urlCirculo = urlCirculo, urlTesoro = urlTesoro, urlBot = urlBot, urlTileset = urlTileset, listaRefuerzos = listaRefuerzos, nombreTileSet = nombreTileSet,capaObjetos = capaObjetos, capasBackground = capasBackground,x=width,y=height)

        else:
            nombreMapa = request.form.get('listaMapas')
            mapa = Map.query.filter(Map.idUser==id,Map.nombreMapa==nombreMapa).first()
            listaRefuerzos = mapa.refuerzos.split('-')
            nombreTileSet = mapa.nombreTileSet
            capaObjetos = mapa.capaObjetos
            capasBackground = mapa.capasBackground
            tileWidth = json.loads(mapa.mapa)["tilewidth"]
            if tileWidth == sizeTiles[0]:
                urlCirculo = url_for('static', filename='assets/circuloAmarillo16.png')
                urlTesoro = url_for('static', filename='assets/tesoro16.png')
                urlBot = url_for('static', filename='assets/bot16.png')
            else:
                urlCirculo = url_for('static', filename='assets/circuloAmarillo32.png')
                urlTesoro = url_for('static', filename='assets/tesoro32.png')
                urlBot = url_for('static', filename='assets/bot32.png')

            urlMapa = url_for('getMap',id = id, nombreMapa = nombreMapa)
            urlTileset = url_for('getTileset',id = id, nombreMapa = nombreMapa)
            return render_template('index.html',name=email,urlMapa = urlMapa,urlCirculo = urlCirculo, urlTesoro = urlTesoro, urlBot = urlBot, urlTileset = urlTileset, listaRefuerzos = listaRefuerzos,nombreTileSet=nombreTileSet,capaObjetos = capaObjetos, capasBackground = capasBackground,x=mapa.width,y=mapa.height)
Exemple #34
0
    def test_create_invalid_map(self):
        with self.assertRaises(ValueError) as context:
            maps = Map(1321321)

        self.assertTrue(context, "A valid str map should be provided")