示例#1
0
    def __init__(self):

        BE_Object.__init__(self)
        self._type = self.CANVASOBJECT_FLANK

        self.year = 0
        self.standDistance = None
        self.origin = Geometry.Point2D()
        self.target = Geometry.Point2D()

        self.battalions = {}
        self.battalions['Infantry'] = {
            'Number': None,
            'BattalionSize': None,
            'GroupSize': None,
            'GroupDistance': None
        }
        self.battalions['Archers'] = {
            'Number': None,
            'BattalionSize': None,
            'GroupSize': None,
            'GroupDistance': None
        }
        self.battalions['Cannons'] = {
            'Number': None,
            'BattalionSize': None,
            'GroupSize': None,
            'GroupDistance': None
        }
        self.battalions['SiegeTowers'] = {
            'Number': None,
            'BattalionSize': None,
            'GroupSize': None,
            'GroupDistance': None
        }
示例#2
0
    def __init__(self):

        BE_Object.__init__(self)
        self._type = self.CANVASOBJECT_CITYEVOLUTION
        self.timeRange = [0, 0]
        self.baseSegment = Geometry.Segment2D()
        self.arrow = Geometry.Segment2D()
        self.housesPerYear = 1
        self.groupID = 0
        self.__colorDB = wx.ColourDatabase()
示例#3
0
    def __init__(self, mainwindow):

        BE_HandlerCanvas.__init__(self, mainwindow)

        self.__extraStatus = self.STATUS_EXT_NONE

        self.__baseSegment = Geometry.Segment2D()
        self.__arrowEndPoint = Geometry.Point2D()

        self.__XORflag = False  # internal flag to control the draw xor issues for the first arrow drawing time
示例#4
0
    def Draw(self, dc):

        if (self._status == self.STATUS_FINISHED):
            return
        if (self._status == self.STATUS_NOTSTARTED):
            return

        canvas = self.GetCanvas()
        lastpen = dc.GetPen()

        if (self._status == self.STATUS_STARTED):

            if (self._prevMousePos and self._curMousePos):

                dc.SetPen(wx.Pen(wx.Colour(0, 0, 0, wx.ALPHA_OPAQUE), 2))

                dc.SetLogicalFunction(wx.INVERT)

                start = canvas.UserToScreenCoord(self.__startPos.x,
                                                 self.__startPos.y)
                prev = canvas.UserToScreenCoord(self._prevMousePos.x,
                                                self._prevMousePos.y)
                curr = canvas.UserToScreenCoord(self._curMousePos.x,
                                                self._curMousePos.y)

                dc.DrawLine(start.x, start.y, prev.x, prev.y)

                if (self.__XORflag):
                    seg = Geometry.Segment2D(self.__startPos,
                                             self._prevMousePos)
                    arrow = seg.GetArrow(atEnd=True, size=30, arrowangle=20)
                    plist = []
                    for p in arrow:
                        parrow = canvas.UserToScreenCoord(p.x, p.y)
                        plist.append([parrow.x, parrow.y])
                    dc.DrawPolygon(plist)

                self.__XORflag = True

                dc.DrawLine(start.x, start.y, curr.x, curr.y)

                seg = Geometry.Segment2D(self.__startPos, self._curMousePos)
                arrow = seg.GetArrow(atEnd=True, size=30, arrowangle=20)
                plist = []
                for p in arrow:
                    parrow = canvas.UserToScreenCoord(p.x, p.y)
                    plist.append([parrow.x, parrow.y])
                dc.DrawPolygon(plist)

        dc.SetPen(lastpen)
示例#5
0
    def GetBoundingBox(self):
        bbox = Geometry.BoundingQuad()

        p = self.center.Copy()
        p.Move(Geometry.Vector2D(-1, -1), self.__size / 2.0)
        bbox.InsertPoint(p)
        p = self.center.Copy()
        p.Move(Geometry.Vector2D(-1, 1), self.__size / 2.0)
        bbox.InsertPoint(p)
        p = self.center.Copy()
        p.Move(Geometry.Vector2D(1, -1), self.__size / 2.0)
        bbox.InsertPoint(p)
        p = self.center.Copy()
        p.Move(Geometry.Vector2D(1, 1), self.__size / 2.0)
        bbox.InsertPoint(p)

        return bbox
示例#6
0
    def ScreenToUserCoord(self, x, y):
        # See at header for more information

        scale = [
            float(self.__viewportSize[0]) / float(self.__windowSize[0]),
            float(self.__viewportSize[0]) / float(self.__windowSize[0])
        ]
        return Geometry.Point2D(x * scale[0], y * scale[1])
示例#7
0
    def GetBoundingBox(self):

        bbox = Geometry.BoundingQuad()

        bbox.InsertPoint(self.baseSegment.p1)
        bbox.InsertPoint(self.baseSegment.p2)
        bbox.InsertPoint(self.arrow.p2)

        return bbox
示例#8
0
    def GetBoundingBox(self):
        bbox = Geometry.BoundingQuad()

        for p in self.__polyline:
            bbox.InsertPoint(p)

        bbox.Expand(self.__width)

        return bbox
示例#9
0
    def Select(self, point):
        # Since river is a nonclosed polyline, we need to check the selection over each polyline segment

        i = 1
        while (i < len(self.__polyline)):
            seg = Geometry.Segment2D(self.__polyline[i - 1],
                                     self.__polyline[i])
            poly = seg.GetBounding(self.__width / 2.0)
            bbox = Geometry.BoundingQuad()
            for p in poly.shape:
                bbox.InsertPoint(p.p1)
            if (len(poly.shape) > 0):
                bbox.InsertPoint(poly.shape[-1].p2)
            if (bbox.IsInside(point)):
                return True

            i += 1

        return False
示例#10
0
    def GetBoundingBox(self):

        # TODO: Improve bounding over arrow (not box)

        bbox = Geometry.BoundingQuad()

        bbox.InsertPoint(self.origin)
        bbox.InsertPoint(self.target)
        bbox.Expand(20)

        return bbox
示例#11
0
    def GetBoundingBox(self):
        bbox = Geometry.BoundingQuad()

        for p in self.__shape:
            bbox.InsertPoint(p)

        for p in self.__shape:
            if (p.data):
                bbox.Expand(p.data.size)
                break

        return bbox
示例#12
0
    def Draw(self, dc, document, canvas):

        towerdata = document.GetDefaultSettings().castle.towers
        self.size = towerdata.squareSide / 2.0

        lastpen = dc.GetPen()
        dc.SetPen(wx.Pen(wx.Colour(100, 100, 100, wx.ALPHA_OPAQUE), 1))

        if (self.__towertype == self.TOWERTYPE_SQUARED):
            center = self.__center.Copy()
            center.Move(Geometry.Vector2D(-1, -1), towerdata.squareSide / 2.0)
            center = canvas.UserToScreenCoord(center.x, center.y)
            side = canvas.UserToScreenValue(
                towerdata.squareSide
            )  # NOTE: This sould be changed if window/viewport are not squared
            dc.DrawRectangle(center.x, center.y, side, side)

        if (self.__towertype == self.TOWERTYPE_ROUNDED):
            center = self.__center.Copy()
            center.Move(Geometry.Vector2D(-1, -1),
                        towerdata.circleRadius / 2.0)
            center = canvas.UserToScreenCoord(center.x, center.y)
            radius = canvas.UserToScreenValue(
                towerdata.circleRadius
            )  # NOTE: This sould be changed if window/viewport are not squared
            dc.DrawEllipse(center.x, center.y, radius * 2, radius * 2)

        if (self.__towertype == self.TOWERTYPE_RANDOM):
            lastfont = dc.GetFont()
            currfont = wx.Font(pointSize=25,
                               family=wx.FONTFAMILY_DEFAULT,
                               style=wx.FONTSTYLE_NORMAL,
                               weight=wx.FONTWEIGHT_BOLD)
            dc.SetFont(currfont)
            center = canvas.UserToScreenCoord(self.__center.x, self.__center.y)
            dc.DrawText("?", center.x, center.y)
            dc.SetFont(lastfont)

        dc.SetPen(lastpen)
示例#13
0
    def Draw(self, dc, document, canvas):

        battle = document.GetGameData().battles.GetBattle(self.year)
        if (not battle):
            return
        if (not battle.color):
            return

        lastpen = dc.GetPen()
        lastbrush = dc.GetBrush()
        dc.SetPen(wx.Pen(battle.color, 1))
        dc.SetBrush(wx.Brush(battle.color, wx.BDIAGONAL_HATCH))

        plist = []
        axis = Geometry.Segment2D(self.origin, self.target)
        length = axis.GetLength()
        direction = axis.GetDirection()
        normal = axis.GetNormal()

        arrowwidth = 20
        arrowcapheight = 50
        arrowcapwidth = 50

        p = self.origin.Copy()
        p.Move(normal, arrowwidth / 2.0)
        plist.append([p.x, p.y])
        p.Move(direction, length - arrowcapheight)
        plist.append([p.x, p.y])
        p.Move(normal, (arrowcapwidth / 2.0) - (arrowwidth / 2.0))
        plist.append([p.x, p.y])
        plist.append([self.target.x, self.target.y])
        p.Move(normal, -arrowcapwidth)
        plist.append([p.x, p.y])
        p.Move(normal, (arrowcapwidth / 2.0) - (arrowwidth / 2.0))
        plist.append([p.x, p.y])
        p = self.origin.Copy()
        p.Move(normal, -arrowwidth / 2.0)
        plist.append([p.x, p.y])

        plistcanvas = []
        for pl in plist:
            pc = canvas.UserToScreenCoord(pl[0], pl[1])
            plistcanvas.append([pc.x, pc.y])

        dc.DrawPolygon(plistcanvas)

        dc.SetBrush(lastbrush)
        dc.SetPen(lastpen)
示例#14
0
def defineTarget(data):
    # Start the simulation
    angle = 270.
    newPos = initCircularPoint(angle)
    global showGraphics
    showGraphics = True
    detailedResults = doBattle(newPos, data)
    showGraphics = False
    newDist = 0
    newBreach = None
    for r in detailedResults:
        # newDist = comparePositions(targetPos, getClimbingPos(r))
        newBreach = getClimbingPos(r)
    # targetPos = geom.Point2D(153, 234) #this is the result from angle 270
    targetPos = geom.Point2D(newBreach.x, newBreach.y)
    print "Objective:", newBreach.x, newBreach.y, newBreach.z
    print "From:", angle, "=>", [newPos[0], newPos[1]]
    pointsToShow.extend([[newPos[0], newPos[1], 'G', 'red'],
                         [newBreach.x, newBreach.y, 'W', 'red']
                         ])
    return targetPos
示例#15
0
    def Draw(self, dc, document, canvas):

        citydata = document.GetDefaultSettings().city
        self.__size = citydata.housesSize

        lastpen = dc.GetPen()
        lastbrush = dc.GetBrush()
        dc.SetPen(wx.Pen(wx.Colour(141, 114, 71, wx.ALPHA_OPAQUE), 1))
        dc.SetBrush(wx.Brush(wx.Colour(234, 207, 160), wx.SOLID))

        p = self.center.Copy()
        p.Move(Geometry.Vector2D(-1, -1), citydata.housesSize / 2.0)

        p = canvas.UserToScreenCoord(p.x, p.y)
        size = canvas.UserToScreenValue(
            citydata.housesSize
        )  # NOTE: This sould be changed if window/viewport are not squared. A polygon should be calculated instead
        dc.DrawRectangle(p.x, p.y, size, size)

        dc.SetBrush(lastbrush)
        dc.SetPen(lastpen)
示例#16
0
    def ImportXML(self, root, document):

        main = root.find("Battlefield")
        if (not main):
            return

        try:
            self.__bounding = int(main.find("Bounding").text)
        except:
            pass

        try:
            self.__cellsize = int(main.find("CellSize").text)
        except:
            pass

        rivers = main.find("Rivers")
        if (rivers):
            for trace in rivers:
                try:
                    if (trace.tag == "Trace"):
                        width = float(trace.find("Width").text)
                        pol = []
                        polyline = trace.find("Polyline")
                        if (polyline):
                            for v in polyline:
                                if (v.tag == "Vertex"):
                                    array = ast.literal_eval(v.text)
                                    pol.append(
                                        Geometry.Point2D(array[0], array[1]))

                        river = BE_Objects.BE_River()
                        river.SetShape(pol, width)
                        document.AddCanvasObject(river)
                except:
                    print "WARNING: Wrong river data"
示例#17
0
    def ImportXML(self, root, document):

        main = root.find("BattleEvents")
        if (not main):
            return

        for battlexml in main:
            if (battlexml.tag == "Battle"):
                battle = BE_BattleData()

                try:
                    battle.year = int(battlexml.find("Year").text)
                except:
                    print "ERROR: Battle year not specified in a battle of the  BattleEvents category"
                    continue

                try:
                    battle.nSimulations = int(
                        battlexml.find("Simulations").text)
                except:
                    print "WARNING: Wrong battle simulations number in a battle of the  BattleEvents category"

                try:
                    battle.repeatUntil = (
                        battlexml.find("RepeatUntilDefendersWin").text
                        in ['True', 'true', 'yes', 'YES', '1', 'Yes', 'TRUE'])

                except:
                    print "WARNING: RepeatUntilDefendersWin tag not found in a battle of the  BattleEvents category"

                # Defenders
                defendersxml = battlexml.find("Defenders")
                if (defendersxml != None):
                    try:
                        archersxml = defendersxml.find("Archers")
                        if (archersxml != None):
                            battle.defenders['Archers'] = int(archersxml.text)
                        else:
                            battle.defenders['Archers'] = 0
                        cannonsxml = defendersxml.find("Cannons")
                        if (cannonsxml != None):
                            battle.defenders['Cannons'] = int(cannonsxml.text)
                        else:
                            battle.defenders['Cannons'] = 0

                    except:
                        print "WARNING: Wrong defenders data in a battle of the BattleEvents category"
                else:
                    print "WARNING: None defenders has been specified in a battle of the BattleEvents category"

                # Attackers
                attackersxml = battlexml.find("Attackers")
                if (attackersxml != None):
                    # Flanks
                    for flankxml in attackersxml:
                        if (flankxml.tag == "Flank"):

                            flank = BE_Objects.BE_Flank()
                            flank.year = battle.year

                            try:

                                dist = flankxml.find("StandDistance")
                                if (dist != None):
                                    flank.standDistance = float(
                                        dist.text)  # Optional

                                # TODO: Place the arrow flank considering the standdistance

                                dirxml = ast.literal_eval(
                                    flankxml.find("Direction").text)
                                direction = Geometry.Vector2D(
                                    float(dirxml[0]), float(dirxml[1]))
                                direction.Normalize()

                                originxml = flankxml.find("origin")
                                if (originxml != None):
                                    origin = ast.literal_eval(originxml.text)
                                    flank.origin = Geometry.Point2D(
                                        float(origin[0]), float(origin[1]))
                                else:
                                    # Directional flank (no origin)
                                    # Place the arrow at the viewport edges
                                    viewsize = document.GetDefaultSettings(
                                    ).game.viewportSize
                                    origin = Geometry.Point2D(
                                        viewsize / 2.0, viewsize / 2.0)
                                    origin.Move(direction.Copy().Invert(),
                                                viewsize / 2.0)
                                    flank.origin = origin.Copy()

                                    # TODO : Improve this to work with standdistance

                                # Since arrow length is not used in the simulation, it could not be found in the incoming xml (except it is created by the editor, see ExportXML)
                                # If it is not present, use a default value
                                arrowlengthxml = flankxml.find(
                                    "BE_Editor_ArrowLength")
                                if (arrowlengthxml == None):
                                    arrowlength = 200.0
                                else:
                                    arrowlength = float(arrowlengthxml.text)

                                flank.target = flank.origin.Copy()
                                flank.target.Move(direction, arrowlength)

                            except:
                                print "WARNING: Wrong flank data of a battle in BattleEvents category"

                            # Flank battalions
                            battalionsxml = flankxml.find("Battalions")
                            if (battalionsxml != None):
                                for battalionxml in battalionsxml:

                                    try:
                                        type = battalionxml.find("Type").text
                                        number = int(
                                            battalionxml.find("Number").text)

                                        batsizexml = battalionxml.find(
                                            "BattalionSize")
                                        if (batsizexml != None):
                                            battalionsize = int(
                                                batsizexml.text)
                                        else:
                                            battalionsize = None

                                        groupsizexml = battalionxml.find(
                                            "GroupSize")
                                        if (groupsizexml != None):
                                            groupsize = int(groupsizexml.text)
                                        else:
                                            groupsize = None

                                        groupdistxml = battalionxml.find(
                                            "GroupDistance")
                                        if (groupdistxml != None):
                                            groupdist = int(groupdistxml.text)
                                        else:
                                            groupdist = None

                                        flank.battalions[type] = {
                                            'Number': number,
                                            'BattalionSize': battalionsize,
                                            'GroupSize': groupsize,
                                            'GroupDistance': groupdist
                                        }

                                    except:
                                        print "WARNING: Wrong battalion data in a flank of the BattleEvents category"

                            else:
                                print "WARNING: None battalion has found in a flank of the BattleEvents category"

                            battle.flanks.append(flank)
                            document.AddCanvasObject(flank)

                else:
                    print "WARNING: None attackers has been specified in a battla of the BattleEvents category"

                battle.SetColor()
                self.__battles[battle.year] = battle
示例#18
0
    def ExportXML(self, root, document):

        main = ET.SubElement(root, "BattleEvents")

        for k, v in self.__battles.items():

            battlexml = ET.SubElement(main, "Battle")

            ET.SubElement(battlexml, "Year").text = str(v.year)
            ET.SubElement(battlexml, "Simulations").text = str(v.nSimulations)
            ET.SubElement(battlexml,
                          "RepeatUntilDefendersWin").text = str(v.repeatUntil)

            defendersxml = ET.SubElement(battlexml, "Defenders")
            if (v.defenders['Archers'] > 0):
                ET.SubElement(defendersxml,
                              "Archers").text = str(v.defenders['Archers'])
            if (v.defenders['Cannons'] > 0):
                ET.SubElement(defendersxml,
                              "Cannons").text = str(v.defenders['Cannons'])

            flanks = self.GetBattleFlanks(v.year, document)
            if (len(flanks) > 0):
                attackersxml = ET.SubElement(battlexml, "Attackers")

                for f in flanks:
                    flankxml = ET.SubElement(attackersxml, "Flank")

                    if (f.standDistance):
                        ET.SubElement(flankxml, "StandDistance").text = str(
                            f.standDistance)
                    ET.SubElement(flankxml, "Origin").text = "[" + str(
                        f.origin.x) + "," + str(f.origin.y) + "]"

                    seg = Geometry.Segment2D(f.origin, f.target)
                    dir = seg.GetDirection()
                    ET.SubElement(flankxml, "Direction").text = "[" + str(
                        dir.val[0]) + "," + str(dir.val[1]) + "]"

                    # This is an extra field that only will be used by the Editor. It justs stores the user arrow length defined to reconstruct it on ImportXML function
                    # It does not change anything in the simulation, and is used only for visual purposes
                    arrowlength = ET.SubElement(flankxml,
                                                "BE_Editor_ArrowLength")
                    arrowlength.text = str(seg.GetLength())

                    battalionsxml = ET.SubElement(flankxml, "Battalions")
                    for bk, bv in f.battalions.items():
                        if (bv['Number'] and (bv['Number'] > 0)):
                            bxml = ET.SubElement(battalionsxml, "Battalion")
                            ET.SubElement(bxml, "Type").text = str(bk)
                            ET.SubElement(bxml,
                                          "Number").text = str(bv['Number'])
                            if (bv['BattalionSize']):
                                ET.SubElement(bxml,
                                              "BattalionSize").text = str(
                                                  bv['BattalionSize'])
                            if (bv['GroupSize']):
                                ET.SubElement(bxml, "GroupSize").text = str(
                                    bv['GroupSize'])
                            if (bv['GroupDistance']):
                                ET.SubElement(bxml,
                                              "GroupDistance").text = str(
                                                  bv['GroupDistance'])
示例#19
0
 def propose_move(r):
     d = np.random.normal(size=2)
     rn = r + d
     # print 'proposing move:',
     counter = 0
     # print "debug propose move:", isInsideCastle(rn), isOutsideBattlefield(rn)
     while isInsideCastle(rn) or isOutsideBattlefield(rn) or not start_area.IsInside(geom.Point2D(rn[0], rn[1])):
         rn = r + 2.0*np.random.normal(size=2)
         counter += 1
         # print '.',
     print 'proposed:', counter, "moves around", r
     return rn
示例#20
0
    def ImportXML(self, root, document):

        main = root.find("CityEvolutions")
        if (not main):
            return

        for groupxml in main:
            if (groupxml.tag == "Group"):
                try:
                    groupid = int(groupxml.find("ID").text)

                    evolutionsxml = groupxml.find("Evolutions")
                    for evxml in evolutionsxml:

                        cityevolution = BE_Objects.BE_CityEvolution()
                        cityevolution.groupID = groupid

                        arr = ast.literal_eval(evxml.find("TimeRange").text)
                        cityevolution.timeRange = [int(arr[0]), int(arr[1])]
                        cityevolution.housesPerYear = float(
                            evxml.find("HousesPerYear").text)

                        # Reconstruct the base segment and arrow
                        arrdir = ast.literal_eval(evxml.find("Direction").text)
                        direction = Geometry.Vector2D(float(arrdir[0]),
                                                      float(arrdir[1]))
                        direction.Normalize()
                        basexml = evxml.find("SegmentBase")
                        arrp1 = ast.literal_eval(basexml.find("P1").text)
                        arrp2 = ast.literal_eval(basexml.find("P2").text)
                        cityevolution.baseSegment.p1 = Geometry.Point2D(
                            float(arrp1[0]), float(arrp1[1]))
                        cityevolution.baseSegment.p2 = Geometry.Point2D(
                            float(arrp2[0]), float(arrp2[1]))

                        # Since arrow length is not used in the simulation, it could not be found in the incoming xml (except it is created by the editor, see ExportXML)
                        # If it is not present, use the base segment length as the default one

                        arrowlengthxml = evxml.find("BE_Editor_ArrowLength")
                        if (arrowlengthxml == None):
                            arrowlength = cityevolution.baseSegment.GetLength()
                        else:
                            arrowlength = float(arrowlengthxml.text)

                        mid = cityevolution.baseSegment.GetMidPoint()
                        mid.Move(direction, arrowlength)
                        cityevolution.arrow.p1 = cityevolution.baseSegment.GetMidPoint(
                        )
                        cityevolution.arrow.p2 = mid

                        document.AddCanvasObject(cityevolution)

                except:
                    print "WARNING: Wrong city evolution data in CityEvolutions category"

        # Parse the city expansion checkings
        cityexpandxml = root.find("CityExpansion")

        try:
            walldims = ast.literal_eval(
                cityexpandxml.find("WallDimensions").text)
            self.__wallsDimensions[0] = float(walldims[0])
            self.__wallsDimensions[1] = float(walldims[1])
        except:
            pass  # Optional

        try:
            self.__yearsBetweenExpansions = int(
                cityexpandxml.find("YearsBetweenExpansions").text)
        except:
            pass  # Optional

        if (cityexpandxml != None):
            for expxml in cityexpandxml:
                if (expxml.tag == "Expansion"):
                    try:
                        year = int(expxml.find("Year").text)
                        groupid = int(expxml.find("GroupID").text)
                        wxml = expxml.find("WallHeight")
                        if (wxml != None):  # Optional
                            wheight = float(wxml.text)
                        else:
                            wheight = None
                        txml = expxml.find("TowerHeight")
                        if (txml != None):  # Optional
                            theight = float(txml.text)
                        else:
                            theight = None

                        self.__expansions[str(groupid)] = {
                            'Year': year,
                            'WallsHeight': wheight,
                            'TowersHeight': theight
                        }

                    except:
                        print "WARNING: Wrong city expansion data in CityExpansions category"
示例#21
0
    def ImportXML(self, root, document):

        main = root.find("Castle")
        if (not main):
            return

        try:
            arr = ast.literal_eval(main.find("Orientation").text)
            document.GetDefaultSettings().castle.orientationVector = {
                'X': arr[0],
                'Y': arr[1]
            }
        except:
            print "WARNING: Orientation tag not found in Castle category"

        # Old city / houses
        housesxml = main.find("OldCity")
        if (housesxml != None):
            for hxml in housesxml:
                try:
                    arr = ast.literal_eval(hxml.text)
                    house = BE_Objects.BE_House(
                        Geometry.Point2D(arr[0], arr[1]))
                    document.AddCanvasObject(house)
                except:
                    print "WARNING: Wrong house data in Castle category"

        castle = BE_Objects.BE_Castle()

        # Moat
        moatxml = main.find("Moat")
        if (moatxml != None):
            try:
                if (moatxml.find("HasWater").text == "True"):
                    water = True
                else:
                    water = False

                castle.SetMoat(active=True, haswater=water)
            except:
                print "WARNING: Moat/HasWater tag not found in Castle category"
        else:
            castle.SetMoat(active=False)

        # Castle shape
        shapexml = main.find("Shape")
        if (shapexml != None):
            for vertxml in shapexml:
                try:
                    arr = ast.literal_eval(vertxml.find("Point").text)
                    p = Geometry.Point2D(arr[0], arr[1])
                    towerxml = vertxml.find("TowerType")
                    if (towerxml != None):
                        towertype = None
                        if (towerxml.text == "SquaredTower"):
                            towertype = BE_Objects.BE_Tower.TOWERTYPE_SQUARED
                        elif (towerxml.text == "RoundedTower"):
                            towertype = BE_Objects.BE_Tower.TOWERTYPE_ROUNDED
                        elif (towerxml.text == "Tower"):
                            towertype = BE_Objects.BE_Tower.TOWERTYPE_RANDOM

                        if (towertype != None):
                            tower = BE_Objects.BE_Tower(towertype=towertype,
                                                        center=p.Copy())
                            p.data = tower
                    castle.AddVertex(p)

                except:
                    print "ERROR: Wrong castle shape in Castle category"

        castle.Close()
        document.AddCanvasObject(castle)
示例#22
0
 def AddVertex(self, vertex=Geometry.Point2D()):
     self.__shape.append(vertex)
示例#23
0
    def Draw(self, dc):

        if (self._status == self.STATUS_FINISHED):
            return
        if (self._status == self.STATUS_NOTSTARTED):
            return

        canvas = self.GetCanvas()
        lastpen = dc.GetPen()

        if ((self._status == self.STATUS_STARTED)
                and (self.__extraStatus == self.STATUS_EXT_BASESEGMENT)):

            dc.SetPen(wx.Pen(wx.Colour(0, 0, 0, wx.ALPHA_OPAQUE), 2))
            dc.SetLogicalFunction(wx.INVERT)

            base1 = canvas.UserToScreenCoord(self.__baseSegment.p1.x,
                                             self.__baseSegment.p1.y)
            prev = canvas.UserToScreenCoord(self._prevMousePos.x,
                                            self._prevMousePos.y)
            curr = canvas.UserToScreenCoord(self._curMousePos.x,
                                            self._curMousePos.y)
            dc.DrawLine(base1.x, base1.y, prev.x, prev.y)
            dc.DrawLine(base1.x, base1.y, curr.x, curr.y)

        elif ((self._status == self.STATUS_STARTED)
              and (self.__extraStatus == self.STATUS_EXT_ARROW)):

            if (self._prevMousePos and self._curMousePos):
                dc.SetPen(wx.Pen(wx.Colour(0, 0, 0, wx.ALPHA_OPAQUE), 2))

                base1 = canvas.UserToScreenCoord(self.__baseSegment.p1.x,
                                                 self.__baseSegment.p1.y)
                base2 = canvas.UserToScreenCoord(self.__baseSegment.p2.x,
                                                 self.__baseSegment.p2.y)
                dc.DrawLine(base1.x, base1.y, base2.x, base2.y)

                mid = self.__baseSegment.GetMidPoint()

                dc.SetPen(wx.Pen(wx.Colour(0, 0, 0, wx.ALPHA_OPAQUE), 2))
                dc.SetLogicalFunction(wx.INVERT)

                pmid = canvas.UserToScreenCoord(mid.x, mid.y)
                prev = canvas.UserToScreenCoord(self._prevMousePos.x,
                                                self._prevMousePos.y)
                dc.DrawLine(pmid.x, pmid.y, prev.x, prev.y)

                # Draw the arrow

                if (self.__XORflag):
                    seg = Geometry.Segment2D(mid, self._prevMousePos)
                    arrow = seg.GetArrow(atEnd=True, size=30, arrowangle=20)
                    plist = []
                    for p in arrow:
                        parrow = canvas.UserToScreenCoord(p.x, p.y)
                        plist.append([parrow.x, parrow.y])
                    dc.DrawPolygon(plist)

                self.__XORflag = True

                curr = canvas.UserToScreenCoord(self._curMousePos.x,
                                                self._curMousePos.y)
                dc.DrawLine(pmid.x, pmid.y, curr.x, curr.y)

                seg = Geometry.Segment2D(mid, self._curMousePos)
                arrow = seg.GetArrow(atEnd=True, size=30, arrowangle=20)
                plist = []
                for p in arrow:
                    parrow = canvas.UserToScreenCoord(p.x, p.y)
                    plist.append([parrow.x, parrow.y])
                dc.DrawPolygon(plist)

        dc.SetPen(lastpen)
示例#24
0
    def Click(self, x, y):

        if (self._status == self.STATUS_NOTSTARTED):

            self.__baseSegment.p1 = self.GetCanvas().ScreenToUserCoord(x, y)

            self._status = self.STATUS_STARTED
            self.__extraStatus = self.STATUS_EXT_BASESEGMENT
            self._mainWindow.Refresh()
            self._mainWindow.SetCanvasCursor(wx.StockCursor(wx.CURSOR_CROSS))

        elif ((self._status == self.STATUS_STARTED)
              and (self.__extraStatus == self.STATUS_EXT_BASESEGMENT)):

            self.__baseSegment.p2 = self.GetCanvas().ScreenToUserCoord(x, y)

            self.__extraStatus = self.STATUS_EXT_ARROW
            self._mainWindow.Refresh()
            self._mainWindow.SetCanvasCursor(wx.StockCursor(wx.CURSOR_CROSS))

        elif ((self._status == self.STATUS_STARTED)
              and (self.__extraStatus == self.STATUS_EXT_ARROW)):

            self.__arrowEndPoint = self.GetCanvas().ScreenToUserCoord(x, y)

            dlg = BE_Dialogs.BE_CityEvolutionDlg.BE_CityEvolutionDlg(
                self._mainWindow)

            defdata = self._mainWindow.GetDocument().GetDefaultSettings()
            gamedata = self._mainWindow.GetDocument().GetGameData()
            dlg.textHousesYear.SetValue(str(
                defdata.city.housesCreationPerYear))
            dlg.textTimeRangeStart.SetValue(
                str((gamedata.timeRange[0] - 1) * 100))
            dlg.textTimeRangeEnd.SetValue(
                str((gamedata.timeRange[1] - 1) * 100))
            dlg.textGroupID.SetValue("0")

            if (dlg.ShowModal() == wx.ID_OK):

                self._receiver = BE_Objects.BE_CityEvolution()
                self._receiver.baseSegment = self.__baseSegment.Copy()
                self._receiver.arrow = Geometry.Segment2D(
                    self.__baseSegment.GetMidPoint(), self.__arrowEndPoint)

                try:
                    self._receiver.timeRange[0] = int(
                        dlg.textTimeRangeStart.GetValue())
                    self._receiver.timeRange[1] = int(
                        dlg.textTimeRangeEnd.GetValue())
                except:
                    pass

                try:
                    self._receiver.housesPerYear = float(
                        dlg.textHousesYear.GetValue())
                except:
                    pass

                try:
                    self._receiver.groupID = int(dlg.textGroupID.GetValue())
                except:
                    pass

                self.Finish()

            else:
                self.Cancel()

            dlg.Destroy()

            self.__extraStatus = self.STATUS_EXT_NONE
示例#25
0
    def Draw(self, dc, document, canvas):

        castledata = document.GetDefaultSettings().castle

        lastpen = dc.GetPen()

        # Draw the moat
        if (self.__moat['Active']):

            moatwidth = canvas.UserToScreenValue(
                castledata.moat.width
            )  # NOTE: This sould be changed if window/viewport are not squared

            if (self.__moat['HasWater']):
                dc.SetPen(
                    wx.Pen(wx.Colour(162, 215, 245, wx.ALPHA_OPAQUE),
                           moatwidth))
            else:
                dc.SetPen(
                    wx.Pen(wx.Colour(128, 181, 72, wx.ALPHA_OPAQUE),
                           moatwidth))

            # Expand the castle shape to cover it
            pol = Geometry.Polygon2D()
            pol.SetPointsList(self.__shape)

            gpc = Geometry.GPCWrapper()
            if (not gpc.IsCCW(self.__shape)):
                pol.SwitchOrientation()

            pol.Expand((castledata.walls.thickness / 2.0) +
                       (castledata.moat.width / 2))
            plist = pol.GetPointsList()

            i = 1
            while (i < len(plist)):
                p1 = canvas.UserToScreenCoord(plist[i - 1].x, plist[i - 1].y)
                p2 = canvas.UserToScreenCoord(plist[i].x, plist[i].y)
                dc.DrawLine(p1.x, p1.y, p2.x, p2.y)
                i += 1
            if (len(plist) > 2):
                p1 = canvas.UserToScreenCoord(plist[-1].x, plist[-1].y)
                p2 = canvas.UserToScreenCoord(plist[0].x, plist[0].y)
                dc.DrawLine(p1.x, p1.y, p2.x, p2.y)

        thickness = canvas.UserToScreenValue(
            castledata.walls.thickness
        )  # NOTE: This sould be changed if window/viewport are not squared

        dc.SetPen(wx.Pen(wx.Colour(130, 130, 130, wx.ALPHA_OPAQUE), thickness))

        # Draw the walls
        i = 1
        while (i < len(self.__shape)):
            p1 = canvas.UserToScreenCoord(self.__shape[i - 1].x,
                                          self.__shape[i - 1].y)
            p2 = canvas.UserToScreenCoord(self.__shape[i].x, self.__shape[i].y)
            dc.DrawLine(p1.x, p1.y, p2.x, p2.y)
            i += 1
        if (self.__isClosed and (len(self.__shape) > 2)):
            p1 = canvas.UserToScreenCoord(self.__shape[-1].x,
                                          self.__shape[-1].y)
            p2 = canvas.UserToScreenCoord(self.__shape[0].x, self.__shape[0].y)
            dc.DrawLine(p1.x, p1.y, p2.x, p2.y)

        # Draw the towers
        i = 0
        while (i < len(self.__shape)):
            tower = self.__shape[i].data
            if (tower):
                tower.Draw(dc, document, canvas)
            i += 1

        dc.SetPen(lastpen)
示例#26
0
 def __init__(self, mainwindow):
     self._status = self.STATUS_NOTSTARTED
     self._mainWindow = mainwindow
     self._curMousePos = Geometry.Point2D()
     self._prevMousePos = Geometry.Point2D()
     self._receiver = None
示例#27
0
    def __init__(self, mainwindow):

        BE_HandlerCanvas.__init__(self, mainwindow)
        self.__lastPoint = Geometry.Point2D()
示例#28
0
 def __init__(self, towertype, center=Geometry.Point2D()):
     BE_Object.__init__(self)
     self._type = self.CANVASOBJECT_TOWER
     self.__towertype = towertype
     self.__center = center
     self.size = 0.0
示例#29
0
 def GetBoundingBox(self):
     # Returns a BoundingBox object for current object
     return Geometry.BoundingQuad()