Ejemplo n.º 1
0
 def __init__(self,
              heading,
              radius,
              mouseObj,
              statueObj,
              arena,
              fill=red,
              **style):
     angle = pi * heading / 180
     self.heading = heading
     #Initial position
     self.radius = radius  # real raidius
     # radius after scale, which corresponds on the screen
     position = statueObj.position + Vector(radius * cos(angle),
                                            radius * sin(angle))
     self.originalRadius = radius
     self.originalHeading = heading
     self.originalPosition = position
     self.originalColor = fill
     self.color = fill
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.mouseObj = mouseObj
     self.statueObj = statueObj
     self.arena = arena
     self.time = 0  # 1 frame is 1s, 60s is one minute
Ejemplo n.º 2
0
 def __init__(self, position, heading, mouse, arena, fill=red, **style):
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.arena = arena
     self.mouse = mouse
     self.radius = (self.position - self.origin).length()
     self.theta = (self.m * 1.25 / self.radius) * 180 / pi
     self.angle = (self.position - self.origin).direction()
Ejemplo n.º 3
0
 def __init__(self,
              position,
              heading,
              arenaObj,
              statueObj,
              mouseObj,
              outline=grey,
              fill=grey,
              width=1):
     heading = (position - statueObj.position).direction(
     ) + 180  # initialize heading to be facing statue
     Turtle.__init__(self,
                     position,
                     float(heading),
                     outline=outline,
                     fill=fill,
                     width=width)
     self.arena = arenaObj
     self.statue = statueObj
     self.mouse = mouseObj
     self.state = 'start'  # string to keep track of state
     self.angle = self.getangle()
     self.heading = heading
     self.radius = self.getradius()
     self.origRadius, self.origAngle = self.radius, self.angle
     self.origPosition, self.origHeading = position, heading
     self.arena.catRadiusSV.set(round(self.origRadius, 2))  # update label
     self.arena.catAngleSV.set(round(self.origAngle, 1))  # update label
Ejemplo n.º 4
0
 def __init__(self, position, heading, angle, fill=blue, **style):
     '''
     init the mouse
     '''
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.angle = float(angle) / 60
     self.dead = False
     self.degree = 0
Ejemplo n.º 5
0
Archivo: Mouse.py Proyecto: xyhu/Python
 def __init__(self, position, heading, center, angle, pPerM, cat=None, fill=blue, **style):
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.center = center
     # in degree
     self.angle = angle
     self.pPerM = pPerM
     # in degree
     self.cat = cat
Ejemplo n.º 6
0
 def __init__(self, position, heading, arenaObj, statueObj, outline=myRed, fill=myRed, width=1):
   heading = (position - statueObj.position).direction() - 90 # initialize heading to be in direction of travel
   Turtle.__init__(self, position, float(heading), outline=outline, fill=fill, width=width)
   self.arena = arenaObj
   self.statue = statueObj
   self.angle = self.getangle()
   self.heading = heading
   self.origAngle = self.angle
   self.origPosition, self.origHeading = position, heading
   self.arena.mouseAngleSV.set(round(self.origAngle,1)) # update label
Ejemplo n.º 7
0
def interpret_Lsytem2(path, forward=7, angle=60, filename=''):
# goes through the path and draws 

    turtle = Turtle(filename)
    turtle.left(90)
    states = []
    instr  = { 'A' : ['forward', forward],
               'F' : ['forward', forward],
               'B' : ['forward', forward],
               'x' : ['forward', 0],
               'y' : ['forward', 0],
               '-' : ['left', angle],
               '+' : ['right', angle]}

    for step in path:
        if step == '[':
            states.append(turtle.serialize())
        elif step == ']':
            #state = states.pop()
            turtle.deserialize(states.pop())
        else:
            getattr(turtle, instr[step][0])( instr[step][1])

    if filename:
        turtle.save()

    return
Ejemplo n.º 8
0
 def __init__(self, heading, statueObj, fill=blue):
     angle = pi * heading / 180
     #Initial mouse position
     self.heading = heading
     position = statueObj.position + Vector(scalar * cos(angle),
                                            scalar * sin(angle))
     # self.position = position #REVISION
     self.originalPosition = position
     self.originalHeading = heading
     Turtle.__init__(self, position, heading, fill=fill)
     self.statueObj = statueObj
Ejemplo n.º 9
0
Archivo: Cat.py Proyecto: xyhu/Python
    def __init__(self, position, heading, center, cAngle, mouse, cRad, pPerM,
                 fill=red, **style):
        Turtle.__init__(self, position, heading, fill=fill, **style)
        self.center = center
        self.cAngle = cAngle
        self.mAngle = mouse.angle

        # pixel per meter, note that statue's radius is 1m
        self.pPerM = pPerM
        self.radius = cRad
        self.oldAngle = cAngle
Ejemplo n.º 10
0
 def __init__(self, heading, statueObj, fill=blue, **style):
     """
     Create mouse with given heading. Calls turtle init function.
     """
     self.heading = heading
     self.originalHeading = heading
     self.originalColor = fill
     # coordinate formula is ( r * cos(angle), r * sin(angle) )
     position = Vector(200 + scale_factor * math.cos(heading*pi/180), 200 + scale_factor * math.sin(heading*pi/180))
     self.originalPosition = position
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.statueObj = statueObj
Ejemplo n.º 11
0
    def __init__(self, statue, initial_angle, initial_radius, pace, **style):
        assert isinstance(statue, Statue)
        self.statue = statue
        Circle.__init__(self, statue.position, initial_radius)
        self.theta = initial_angle % 360
        self.pace = pace
        if self.dtheta < 0:
            heading = self.theta - 90
        else:
            heading = self.theta + 90

        Turtle.__init__(self, self.point_at(initial_angle), heading, **style)
Ejemplo n.º 12
0
 def __init__(self, position, speed, orbit, mouse, arena, radius, debug_flag, degree, fill=yellow, **style):
     heading = (position - orbit.position).direction() - 90  # set degree of mouse to face direction it's heading
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.speed = speed
     self.orbit = orbit
     self.degree = degree  # the degree of location of cat relative to orbit
     self.debug = debug_flag
     self.mouse = mouse
     self.cat_rad = radius  # + self.orbit.radius
     self.moved = -1  # state represents wheter mouse is seen
     self.arena = arena
     self.iter = 0
Ejemplo n.º 13
0
 def __init__(self, heading, radius, mouseObj, fill=red, **style):
     """Create cat with given heading and radius. Call turtle init function."""
     self.heading = heading
     self.originalHeading = heading
     self.radius = radius
     self.originalRadius = radius
     self.originalColor = fill
     self.color = fill
     position = Vector(200 + radius * math.cos(heading*pi/180), 200 + radius * math.sin(heading*pi/180))
     self.originalPosition = position
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.mouseObj = mouseObj
     self.time = 0 # 1 frame is 1 second
Ejemplo n.º 14
0
 def __init__(self,
              position,
              heading,
              outline=lightGrey,
              fill=lightGrey,
              width=1):
     Turtle.__init__(self,
                     position,
                     heading,
                     outline=outline,
                     fill=fill,
                     width=width)
     self.radius = 1  # in meters
Ejemplo n.º 15
0
 def __init__(self, heading, statueObj, fill=blue, **style):
     """
     Create mouse with given heading. Calls turtle init function.
     """
     self.heading = heading
     self.originalHeading = heading
     self.originalColor = fill
     # coordinate formula is ( r * cos(angle), r * sin(angle) )
     position = Vector(200 + scale_factor * math.cos(heading * pi / 180),
                       200 + scale_factor * math.sin(heading * pi / 180))
     self.originalPosition = position
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.statueObj = statueObj
Ejemplo n.º 16
0
def polycircle(n=12):
    t = Turtle('polycircle')

    for x in xrange(n):
        t.polygon(n, 20)
        t.left(360/n)
    t.save()
Ejemplo n.º 17
0
 def __init__(self, position, heading, arenaObj, statueObj, mouseObj, outline=grey, fill=grey, width=1):
   heading = (position - statueObj.position).direction() + 180 # initialize heading to be facing statue
   Turtle.__init__(self, position, float(heading), outline=outline, fill=fill, width=width)
   self.arena = arenaObj
   self.statue = statueObj
   self.mouse = mouseObj
   self.state = 'start' # string to keep track of state
   self.angle = self.getangle()
   self.heading = heading
   self.radius = self.getradius()
   self.origRadius, self.origAngle = self.radius, self.angle
   self.origPosition, self.origHeading = position, heading
   self.arena.catRadiusSV.set(round(self.origRadius,2)) # update label
   self.arena.catAngleSV.set(round(self.origAngle,1)) # update label
Ejemplo n.º 18
0
 def __init__(self, heading, radius, mouseObj, fill=red, **style):
     """Create cat with given heading and radius. Call turtle init function."""
     self.heading = heading
     self.originalHeading = heading
     self.radius = radius
     self.originalRadius = radius
     self.originalColor = fill
     self.color = fill
     position = Vector(200 + radius * math.cos(heading * pi / 180),
                       200 + radius * math.sin(heading * pi / 180))
     self.originalPosition = position
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.mouseObj = mouseObj
     self.time = 0  # 1 frame is 1 second
Ejemplo n.º 19
0
def star():

    step  = 20
    side  = 250
    shift = side + 1j*side
    draw  = Turtle("star")

    for x, y in product([1, -1], [1, -1]):
        for i in xrange(0, side + 1, step):
            a = x*i             + shift
            b = y*1j*(side - i) + shift
            draw.addLine(a, b)

    draw.dumpImage()
 def create_organism_by_name(self, organism_species, x, y, cooldown=-1):
     organism_position = Position(x, y)
     if organism_species == "Antelope":
         self.add_organism_to_world(Antelope(self, organism_position))
     if organism_species == "SosnowskyBorscht":
         self.add_organism_to_world(
             SosnowskyBorscht(self, organism_position))
     if organism_species == "Guarana":
         self.add_organism_to_world(Guarana(self, organism_position))
     if organism_species == "Fox":
         self.add_organism_to_world(Fox(self, organism_position))
     if organism_species == "Thistle":
         self.add_organism_to_world(Thistle(self, organism_position))
     if organism_species == "Sheep":
         self.add_organism_to_world(Sheep(self, organism_position))
     if organism_species == "Grass":
         self.add_organism_to_world(Grass(self, organism_position))
     if organism_species == "WolfBerries":
         self.add_organism_to_world(WolfBerries(self, organism_position))
     if organism_species == "Wolf":
         self.add_organism_to_world(Wolf(self, organism_position))
     if organism_species == "Turtle":
         self.add_organism_to_world(Turtle(self, organism_position))
     if organism_species == "CyberSheep":
         self.add_organism_to_world(CyberSheep(self, organism_position))
     if organism_species == "Human":
         self.create_human(organism_position, cooldown)
 def create_organism(self, organism_creator, x, y):
     organism_position = Position(x, y)
     if 50 - organism_creator < 2:
         self.add_organism_to_world(Antelope(self, organism_position))
     elif 50 - organism_creator < 4:
         self.add_organism_to_world(
             SosnowskyBorscht(self, organism_position))
     elif 50 - organism_creator < 6:
         self.add_organism_to_world(Guarana(self, organism_position))
     elif 50 - organism_creator < 8:
         self.add_organism_to_world(Fox(self, organism_position))
     elif 50 - organism_creator < 9:
         self.add_organism_to_world(Thistle(self, organism_position))
     elif 50 - organism_creator < 13:
         self.add_organism_to_world(Sheep(self, organism_position))
     elif 50 - organism_creator < 17:
         self.add_organism_to_world(Grass(self, organism_position))
     elif 50 - organism_creator < 19:
         self.add_organism_to_world(WolfBerries(self, organism_position))
     elif 50 - organism_creator < 22:
         self.add_organism_to_world(Wolf(self, organism_position))
     elif 50 - organism_creator < 24:
         self.add_organism_to_world(Turtle(self, organism_position))
     elif 50 - organism_creator < 25:
         self.add_organism_to_world(CyberSheep(self, organism_position))
Ejemplo n.º 22
0
def ModelAnalyse(data, paraDict):
    """Analysis data starting from generating trading signals from trade model"""
    # Default Settings
    highFreqMA = 7
    lowFreqMA = 25
    addPositionCondition = 1

    outWindow = 20
    inWindow = 10
    # Get trade Model and trade Signal
    if paraDict['tradeType'] == 'Jai':
        model = JaiTrader(data, 'EMA', highFreqMA, 1, 'EMA', lowFreqMA, 1, 1,
                          1)
    elif paraDict['tradeType'] == 'DoubleMA':
        model = DoubleMA(data, 'EMA', highFreqMA, 1, 'EMA', lowFreqMA, 1, 1)
    elif paraDict['tradeType'] == 'MA':
        model = DoubleMA(data, 'SMA', highFreqMA, 1, 'SMA', lowFreqMA, 1, 1)
    elif paraDict['tradeType'] == 'Turtle':
        model = Turtle(data, outWindow, inWindow)
    # Analyse with stop loss and take profit choices
    Types = [paraDict['stopType'], paraDict['takeProfitType']]
    stopLevel = paraDict['stop']
    takeProfitLevel = paraDict['takeProfitRule']
    takeProfitPnL = paraDict['takeProfitPnLRule']
    tradeModel = paraDict['tradeType']
    maxPositionSize = int(paraDict['maxRiskUnits'])

    rr = SlTpComb(Types, model, takeProfitLevel, takeProfitPnL, stopLevel,
                  tradeModel, addPositionCondition, maxPositionSize)
    return rr
Ejemplo n.º 23
0
def compiling_txt(file_name):
    file = open(file_name, 'rt', encoding='utf-8')
    l = file.readlines()
    for i in range(len(l)):
        if l[i][-1] == '\n':
            l[i] = l[i][:len(l[i]) - 1]
    operator = l[0]
    f = False
    for i in range(1, len(l)):
        t = formatted_command(l[i])
        if (t in op_dict[operator].command_list) or ('нц' in t) or (
                'пока' in t) or ('кц' in t):
            f = True
        else:
            f = False
            raise MySyntaxError('Синтаксическая ошибка в строке {}'.format(i +
                                                                           1))
    if f:
        op = l[0]
        if op == 'Чертежник':
            op = Blueprinter()
        elif op == 'Черепаха':
            op = Turtle()
        elif op == 'Робот':
            op = Robot()
        elif op == 'Вычислитель':
            op = Calculator()
        core_alg(l[1:], op)
        if isinstance(op, Turtle) or isinstance(
                op, Blueprinter) or op == (op, Robot):
            canvas.pack()
            main.mainloop()
Ejemplo n.º 24
0
 def createNewOrganism(self, code, posX, posY, world):
     if (code == 0 or code == 'F'):
         return Fox(posX, posY, world)
     elif (code == 1 or code == 'W'):
         return Wolf(posX, posY, world)
     elif (code == 2 or code == 'H'):
         return Human(posX, posY, world)
     elif (code == 3 or code == 'A'):
         return Antelope(posX, posY, world)
     elif (code == 4 or code == 'C'):
         return CyberSheep(posX, posY, world)
     elif (code == 5 or code == 'S'):
         return Sheep(posX, posY, world)
     elif (code == 6 or code == 'T'):
         return Turtle(posX, posY, world)
     elif (code == 7 or code == 'b'):
         return Belladonna(posX, posY, world)
     elif (code == 8 or code == 's'):
         return HeracleumSosnowkyi(posX, posY, world)
     elif (code == 9 or code == 'o'):
         return Sonchus(posX, posY, world)
     elif (code == 10 or code == 'u'):
         return Guarana(posX, posY, world)
     elif (code == 11 or code == 'g'):
         return Grass(posX, posY, world)
     else:
         return None
Ejemplo n.º 25
0
    def randSpawn(self):
        index = 0
        isHuman = False
        for i in range(0, self.height):
            for j in range(0, self.width):
                chance = randint(0, 99)
                if chance < 15:
                    uni = randint(0, 10)

                    if uni == 0:
                        self.organisms[index] = Sheep(self, Point(i, j))
                    elif uni == 1:
                        self.organisms[index] = Wolf(self, Point(i, j))
                    elif uni == 2:
                        self.organisms[index] = Fox(self, Point(i, j))
                    elif uni == 3:
                        self.organisms[index] = Turtle(self, Point(i, j))
                    elif uni == 4:
                        self.organisms[index] = Antelope(self, Point(i, j))
                    elif uni == 5:
                        self.organisms[index] = Cybersheep(self, Point(i, j))
                    elif uni == 6:
                        self.organisms[index] = Grass(self, Point(i, j))
                    elif uni == 7:
                        self.organisms[index] = Dandelion(self, Point(i, j))
                    elif uni == 8:
                        self.organisms[index] = Belladonna(self, Point(i, j))
                    elif uni == 9:
                        self.organisms[index] = Hogweed(self, Point(i, j))
                    index += 1
                elif not isHuman:
                    self.organisms[index] = Human(self, Point(i, j))
                    isHuman = True
                    index += 1
Ejemplo n.º 26
0
def randomPolygon(
        n=3,
        r=1 / 2.,
        n_iter=100000,
        a=400,
        size=450,
        center=(50, 50),
        rect=False,
        path="img/randomSierpinski.png",
):

    if rect:
        vertices = [50 + 50j, 250 + 50j, 250 + 250j]
    else:
        vertices = regularPolygon(Turtle("randomPolygon", center), a, n)
    img = Image.new('RGB', (size, size), 'white')

    point = 10
    for k, i in enumerate(WeightedRandom(n_iter, [1] * n)):
        vect = vertices[i] - point
        point = point + (1 - r) * vect
        if k > 1000:
            img.putpixel((int(point.real), int(point.imag)),
                         (255 - int(255 * float(k) / n_iter), 0,
                          int(255 * float(k) / n_iter)))

    img.save(path)
Ejemplo n.º 27
0
def drawPoints(points, title, clr='green'):

    draw = Turtle(title, background=True)
    if isinstance(points[0], PointGroup):
        for pointGroup in points:
            draw.connectPoints(pointGroup.points)
    else:
        for point in points:
            draw.addPoint((500 * point[0] + 200, 500 * point[1] + 200), clr)
    draw.dumpImage()
Ejemplo n.º 28
0
def applyTransformDraw(points, transform, rec):

    draw = Turtle("Square", start_coord=[100, 100])
    l = len(points)
    draw.connectPoints(points)

    for _ in xrange(rec):
        for i in xrange(l):
            points[i] = dot(transform, points[i])
        draw.connectPoints(points)
    draw.dumpImage()
Ejemplo n.º 29
0
class Polygon():
    def __init__(self, vertices):

        self.n = len(vertices)
        self.vert = [np.array(vortex) for vortex in vertices]
        self.edges = [
            self.vert[(i + 1) % self.n] - self.vert[i] for i in xrange(self.n)
        ]

    # Calculation using Ray casting method. Ray in direction of S-P.
    def testIn(self, P):

        S = np.array((-1 * pi, -1))
        P = np.array(P)
        n_intersections = 0

        for vertex in self.vert:
            if (vertex == P).all():
                return True

        PS = S - P
        for i in xrange(self.n):
            A = self.vert[i]
            B = self.vert[(i + 1) % self.n]

            PA = A - P
            PB = B - P

            det_PS_PA = np.linalg.det(np.column_stack((PS, PA)))
            det_PS_PB = np.linalg.det(np.column_stack((PS, PB)))
            det_PB_PA = np.linalg.det(np.column_stack((PB, PA)))

            # Compare vectors orientation
            if 0 >= det_PS_PA * det_PS_PB and \
               0 <  det_PS_PA * det_PB_PA:
                n_intersections += 1
        return bool(n_intersections % 2)

    def drawPolygon(self):

        self.draw = Turtle("Polygon")

        for i in xrange(self.n):
            self.draw.addLineNumpy(self.vert[i], self.vert[(i + 1) % self.n])
Ejemplo n.º 30
0
    def __init__(self, card_string):
        """Initialisation d'une carte avec des tortues
        Ordre => North, East, South, West
        Exemple : CRCVTVTJ
        North : Corps Rouge
        East  : Corps Vert
        South : Tete Verte
        West  : Tete Jaune
        """

        if len(card_string) != 8:
            raise CardException

        self.card_string = card_string

        self.turtle_north = Turtle(card_string[0:2])
        self.turtle_east = Turtle(card_string[2:4])
        self.turtle_south = Turtle(card_string[4:6])
        self.turtle_west = Turtle(card_string[6:8])
Ejemplo n.º 31
0
def triangulateRandom(n, uniform=True):

    if uniform:
        points = np.random.uniform(0, 500, [n, 2])
        draw = Turtle("triangulation_uniform_points")
    else:
        mean, sigma = 200, 70
        points = np.random.normal(mean, sigma, [n, 2])
        draw = Turtle("triangulation_normal_points")

    for edge in triangulation(points):
        draw.addLineNumpy(edge.array[0, :], edge.array[1, :])
    draw.dumpImage()
Ejemplo n.º 32
0
def wrapRandomGift(n, uniform=True):

    if uniform:
        draw   = Turtle("Gift_Wrapping_uniform")
        points = list(np.random.uniform(0,500,[n,2]))
    else:
        draw   = Turtle("Gift_Wrapping_normal")
        mean, sigma = 200, 70
        points = list(np.random.normal(mean,sigma,[n,2]))

    for point in points:
        draw.addPoint(point)

    while len(points) >= 3:
        wraping = wrapGift(points)
        wr_len  = len(wraping)
        for i in xrange(wr_len):
            draw.addLineNumpy(wraping[i], wraping[(i+1) % wr_len])

    draw.dumpImage()
Ejemplo n.º 33
0
	def __init__(self):
		super(Case2, self).__init__()
		# key
		self.index = 'sh001'

		# tutle
		self.tutle = Turtle()
		self.tutle.original = 100000
		self.tutle.all = 100000
		self.tutle.nKey = '20'
		self.inputLock = False
Ejemplo n.º 34
0
class Polygon:
    def __init__(self, vertices):

        self.n = len(vertices)
        self.vert = [np.array(vortex) for vortex in vertices]
        self.edges = [self.vert[(i + 1) % self.n] - self.vert[i] for i in xrange(self.n)]

    # Calculation using Ray casting method. Ray in direction of S-P.
    def testIn(self, P):

        S = np.array((-1 * pi, -1))
        P = np.array(P)
        n_intersections = 0

        for vertex in self.vert:
            if (vertex == P).all():
                return True

        PS = S - P
        for i in xrange(self.n):
            A = self.vert[i]
            B = self.vert[(i + 1) % self.n]

            PA = A - P
            PB = B - P

            det_PS_PA = np.linalg.det(np.column_stack((PS, PA)))
            det_PS_PB = np.linalg.det(np.column_stack((PS, PB)))
            det_PB_PA = np.linalg.det(np.column_stack((PB, PA)))

            # Compare vectors orientation
            if 0 >= det_PS_PA * det_PS_PB and 0 < det_PS_PA * det_PB_PA:
                n_intersections += 1
        return bool(n_intersections % 2)

    def drawPolygon(self):

        self.draw = Turtle("Polygon")

        for i in xrange(self.n):
            self.draw.addLineNumpy(self.vert[i], self.vert[(i + 1) % self.n])
def drawPoints(points, title, clr='green'):

    draw = Turtle(title, background=True)
    if isinstance(points[0], PointGroup):
        for pointGroup in points:
            draw.connectPoints(pointGroup.points)
    else:
        for point in points:
            draw.addPoint((500*point[0] + 200, 500*point[1] + 200), clr)
    draw.dumpImage()
Ejemplo n.º 36
0
    def loadFile(self):
        self.organisms = None
        self.allocOrganisms()
        savefile = open("savefile.wsf", "r")
        index = 0
        ptr = 0
        string = savefile.read().split(' ')
        while True:
            if string[ptr] == "END":
                break
            typee = string[ptr]
            ptr += 1
            power = int(string[ptr])
            ptr += 1
            age = int(string[ptr])
            ptr += 1
            x = int(string[ptr])
            ptr += 1
            y = int(string[ptr])
            ptr += 1
            position = Point(x, y)

            if typee == "Grass":
                self.organisms[index] = Grass(self, position)
            elif typee == "Dandelion":
                self.organisms[index] = Dandelion(self, position)
            elif typee == "Guarana":
                self.organisms[index] = Guarana(self, position)
            elif typee == "Belladonna":
                self.organisms[index] = Belladonna(self, position)
            elif typee == "Hogweed":
                self.organisms[index] = Hogweed(self, position)
            elif typee == "Wolf":
                self.organisms[index] = Wolf(self, position)
            elif typee == "Sheep":
                self.organisms[index] = Sheep(self, position)
            elif typee == "Fox":
                self.organisms[index] = Fox(self, position)
            elif typee == "Turtle":
                self.organisms[index] = Turtle(self, position)
            elif typee == "Antelope":
                self.organisms[index] = Antelope(self, position)
            elif typee == "Human":
                self.organisms[index] = Human(self, position)
            elif typee == "Cybersheep":
                self.organisms[index] = Cybersheep(self, position)

            self.organisms[index].power = power
            self.organisms[index].age = age
            index += 1

        if savefile is not None:
            savefile.close()
Ejemplo n.º 37
0
def main(stdscr):
    curses.curs_set(0)
    curses.start_color()
    curses.use_default_colors()
    stdscr.nodelay(True)
    colorless = False

    # Check for disable color
    for arg in sys.argv[1:]:
        if arg == "colorless":
            colorless = True

    # Initialize color pairs
    '''
    0-128 are for text color
    129-244 are for background color
    245-255 are dynamic based on what the program needs for merging
  '''
    for i in range(0, curses.COLORS / 2):
        curses.init_pair(i + 1, 2 * i, -1)
    for i in range(0, (curses.COLORS / 2) - 11):
        curses.init_pair(i + 1 + (curses.COLORS / 2), 0, 2 * i)

    random.seed(time.time())

    rows, cols = getTerminalSize()
    grid = [[" " for y in range(0, cols)] for x in range(0, rows)]
    animalX = cols / 2
    animalY = rows - 12
    # rows, cols
    #  turtle = Turtle(animalX, animalY-6, "turtle", colorless)
    turtle = Turtle(animalX, animalY, "turtle", colorless)
    if colorless is True:
        tank = SimpleTankWithWater(cols, rows, animalY + len(turtle.getArr()),
                                   155, 132, 0, colorless)
    else:
        tank = SimpleTankWithWater(cols, rows, animalY + len(turtle.getArr()),
                                   155, 132, 50, colorless)
    while True:
        # Draw animals then tank so that tank will fill blank space of animals
        turtle.getAction(rows, cols, tank, stdscr)
        tank.drawGround(stdscr)
        # Refresh screen
        stdscr.refresh()
        time.sleep(1)
        # Check for feeding animal
        input = stdscr.getch()
        if input == ord("f"):
            turtle.feed()
            input = ''
def applyTransformDraw(points, transform, rec):

    draw = Turtle("Square", start_coord=[100,100])
    l    = len(points)
    draw.connectPoints(points)

    for _ in xrange(rec):
        for i in xrange(l):
            points[i] = dot(transform, points[i])
        draw.connectPoints(points)
    draw.dumpImage()
Ejemplo n.º 39
0
 def __init__(self,
              position,
              heading,
              arenaObj,
              statueObj,
              outline=myRed,
              fill=myRed,
              width=1):
     heading = (position - statueObj.position).direction(
     ) - 90  # initialize heading to be in direction of travel
     Turtle.__init__(self,
                     position,
                     float(heading),
                     outline=outline,
                     fill=fill,
                     width=width)
     self.arena = arenaObj
     self.statue = statueObj
     self.angle = self.getangle()
     self.heading = heading
     self.origAngle = self.angle
     self.origPosition, self.origHeading = position, heading
     self.arena.mouseAngleSV.set(round(self.origAngle, 1))  # update label
def compiling_txt(file_name):
    global output
    flag = False
    output = open('output.txt', 'wt', encoding='utf-8')
    canvas = tkinter.Canvas(height=800, width=800, bg='blue')
    file = open(file_name, 'rt', encoding='utf-8')
    l = file.readlines()
    for i in range(len(l)):
        if l[i][-1] == '\n':
            l[i] = l[i][:len(l[i]) - 1]
    operator = no_space_string(l[0])
    if operator in op_dict:
        flag = True
    f = False
    if flag:
        op = op_dict[operator]
        for i in range(1, len(l)):
            t = formatted_command(l[i])
            if (t in op.command_list) or ('нц' in t) or ('пока' in t) or (
                    'кц' in t) or ('=' in t) or ('ввод' in t) or ('вывод'
                                                                  in t):
                f = True
            else:
                f = False
                os.chdir('')
                output.write('Синтаксическая ошибка в строке {}: {}\n'.format(
                    i, t))
    else:
        f = False
        output.write(
            'Синтаксическая ошибка в строке 0: некорректный оператор\n')
    if f:
        op = l[0]
        if op == 'Чертежник':
            op = Blueprinter()
        elif op == 'Черепаха':
            op = Turtle()
        elif op == 'Вычислитель':
            op = Calculator(0, 1)
        elif op == 'Файлик':
            op = Failik()
        elif op == 'Редактор':
            op = PhotoEdit()
        core_alg(l[1:], op, canvas)
        if isinstance(op, Turtle) or isinstance(op, Blueprinter):
            canvas.pack()
            main.mainloop()
    print('Программа успешно завершена\n', file=output)
    output.close()
Ejemplo n.º 41
0
    def __init__(self,
                 emptyMaterial=block.AIR,
                 floorMaterial=block.STONE_BRICK,
                 wallMaterial=block.MOSS_STONE,
                 ceilingMaterial=block.AIR,
                 carvingMaterial=block.AIR,
                 penMaterial=block.GOLD_BLOCK,
                 delay=0.1,
                 cellSize=3,
                 cellCount=Vec3(5, 1, 5),
                 withRoof=False):
        mc = Minecraft.create()
        self._mc = mc
        self._cellSize = cellSize
        self._turtle = Turtle(material=carvingMaterial,
                              penMaterial=penMaterial,
                              ceilingMaterial=ceilingMaterial,
                              floorMaterial=floorMaterial,
                              size=cellSize,
                              delay=delay,
                              mc=mc,
                              position=Vec3(0, 0, 0))

        # account for wall
        margin = cellSize + 1
        clearSize = Vec3(cellCount.x * cellSize, cellCount.y * cellSize,
                         cellCount.z * cellSize)

        # Empty out a large space
        self._mc.setBlocks(0 - margin, -10, 0 - margin, clearSize.x + margin,
                           clearSize.y + margin, clearSize.z + margin,
                           emptyMaterial)
        # Build a floor
        self._mc.setBlocks(0 - margin, -10, 0 - margin, clearSize.x + margin,
                           -1, clearSize.z + margin, floorMaterial)

        # Build the block out of which the maze will be carved
        self._mc.setBlocks(-1, 0, -1, clearSize.x, clearSize.y, clearSize.z,
                           wallMaterial)

        # Build a roof
        self._mc.setBlocks(-1, clearSize.y, -1, clearSize.x, clearSize.y,
                           clearSize.z, ceilingMaterial)

        # Place the player some way away on a plinth
        self._mc.setBlock(-math.floor(clearSize.x / 2), margin * 3, 0,
                          block.STONE)
        self._mc.player.setTilePos(-math.floor(clearSize.x / 2), margin * 5, 0)
Ejemplo n.º 42
0
def plotMaze(grid, d=20, name="SquareMaze"):

    dirs = ((1, 1+1j), (1j, 1+1j), (0, 1j), (0, 1))
    draw = Turtle(name, background=True)
    for square in grid:
        walls = grid[square]
        for i, dir_ in enumerate(dirs):
            if walls[1j**i]:
                draw.addLine((square + dir_[0])*d, (square + dir_[1])*d)

    draw.dumpImage()
Ejemplo n.º 43
0
 def Create(self):
     switcher = {
         0 : lambda : Antelope(),
         1 : lambda : CyberSheep(),
         2 : lambda : Fox(),
         3 : lambda : Sheep(),
         4 : lambda : Turtle(),
         5 : lambda : Wolf(),
         6 : lambda : Belladonna(),
         7 : lambda : Dandelion(),
         8 : lambda : Grass(),
         9 : lambda : Guarana(),
         10: lambda : HeracleumSosnowskyi(),
         }
     
     func = switcher.get(self.value, None)
     return func()
Ejemplo n.º 44
0
def triangulateRandom(n, uniform=True):

    if uniform:
        points = np.random.uniform(0,500,[n,2])
        draw   = Turtle("triangulation_uniform_points")
    else:
        mean, sigma = 200, 70
        points = np.random.normal(mean,sigma,[n,2])
        draw   = Turtle("triangulation_normal_points")

    for edge in triangulation(points):
        draw.addLineNumpy(edge.array[0,:], edge.array[1,:])
    draw.dumpImage()
Ejemplo n.º 45
0
 def __init__(self, position, radius, **style):
     #Makes a statue centered at position with the radius specified.
     Turtle.__init__(self, position, 0, **style)
     Circle.__init__(self, position, radius)
 def __init__(self, position, heading, speed, fill=blue, **style):
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.speed = speed
Ejemplo n.º 47
0
 def __init__(self, position, heading, pPerM, fill=blue, **style):
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.pixelperm = pPerM
Ejemplo n.º 48
0
Archivo: kvet.py Proyecto: durcak/v122
from Turtle import Turtle
import math

turtle = Turtle('kvet')

def step(dist, depth):
    if depth == 0: return

    turtle.forward(dist)

    turtle.left(45)
    step(2*dist//3, depth - 1)

    turtle.right(90)
    step(2*dist//3, depth - 1)

    turtle.left(45)
    turtle.pen_up()
    turtle.back(dist)
    turtle.pen_down()


turtle.left(180)
step(100, 7)

turtle.save()
Ejemplo n.º 49
0
from Turtle import Turtle

turtl = Turtle('c_hilbert')


def step(angle = 90, dist = 10, level = 5):
    if level == 0:
        return

    turtl.right(angle)
    step(-angle, dist, level - 1)
    turtl.forward(dist)
    turtl.left(angle)
    step(angle, dist, level - 1)
    turtl.forward(dist)
    step(angle, dist, level - 1)
    turtl.left(angle)
    turtl.forward(dist)
    step(-angle, dist, level - 1)
    turtl.right(angle)

step(90,15, 5)

turtl.save()
Ejemplo n.º 50
0
            V = (cos_*V.real + sin_*V.imag) + \
                1j*(sin_*V.real - cos_*V.imag)
            V = V - norm

            if V_tmp == vortex:
                vortex_new = V
            e_tmp.append(V)

        new_edges.append(e_tmp)
    return new_edges, vortex_new


if __name__ == "__main__":


    draw = Turtle("Tree", [5, 80])
    tree(draw, 10, 100.)
    draw.dumpImage()

    draw = Turtle("Koch_Flake", [15, 80])
    kochFlake(draw, 5, 100)
    draw.dumpImage()

    draw = Turtle("Sierpinski_Triangle")
    sierpinskiTriangle(draw, 7, 200)
    draw.dumpImage()

    draw = Turtle("Hilbert_Curve",[5, 5])
    hilbertCurve(draw, 7, 300)
    draw.dumpImage()
Ejemplo n.º 51
0
from Turtle import Turtle
import math

turtl = Turtle('sierpinsky')

def sierpinsky(side, level):
    if level == 0:
        for a in [1,2,3]:
            turtl.forward(side)
            turtl.left(120)
    else:
        sierpinsky(side / 2, level - 1)
        turtl.forward(side/2)

        sierpinsky(side / 2, level - 1)
        for d in [side/2, side, side/2]:
            turtl.forward(d)
            turtl.left(120)

        sierpinsky(side / 2, level - 1)
        turtl.right(120)
        turtl.forward(side/2)
        turtl.left(120)

turtl.left(90)
sierpinsky(800, 5)

turtl.save()
Ejemplo n.º 52
0
    def addTurtleParams(
        self,
        who,
        color,
        heading,
        xcor,
        ycor,
        shape,
        label,
        labelColor,
        breed,
        isHidden,
        size,
        penSize,
        penMode,
        additionalParams,
        columnTypes,
    ):
        rex_string = re.compile(r"\"(.*)\"")

        turtle = Turtle()
        turtle.who = int(who)
        turtle.color = float(color)
        turtle.heading = heading
        turtle.xcor = float(xcor)
        turtle.ycor = float(ycor)

        turtle.additionalParams = additionalParams
        turtle.columnTypes = columnTypes

        match = rex_string.search(shape)
        if match != None:
            turtle.shape = match.group(1)
        else:
            turtle.shape = shape

        match = rex_string.search(label)
        if match != None:
            turtle.label = match.group(1)
        else:
            turtle.label = label

        turtle.labelColor = float(labelColor)
        turtle.breed = breed
        turtle.isHidden = isHidden == "true"
        turtle.size = float(size)
        turtle.penSize = float(penSize)

        match = rex_string.search(penMode)
        if match != None:
            turtle.penMode = match.group(1)
        else:
            turtle.penMode = penMode

        self.addTurtle(turtle)
        return turtle
Ejemplo n.º 53
0
def interpret_Lsytem(path, forward=7, angle=60, filename='', ignore = None):
    """
    @param turtle The turtle to guide
    @param dist   Distance to be made with each 'forward'
    @param angle  Angle for 'left' and 'right'
    """
    turtle = Turtle(filename)
    turtle.left(180)

    if ignore == None: ignore = []
    stack = []

    for c in path:
        if c == '+':
            turtle.right(angle)
        elif c == '-':
            turtle.left(angle)
        elif c == '[':
            stack.append(turtle.serialize())
        elif c == ']':
            turtle.deserialize(stack.pop())
        elif c not in ignore:
            turtle.forward(forward)

    if filename:
        turtle.save()

    return
Ejemplo n.º 54
0
 def __init__(self, position, heading, outline=lightGrey, fill=lightGrey, width=1):
   Turtle.__init__(self, position, heading, outline=outline, fill=fill, width=width)
   self.radius = 1 # in meters
Ejemplo n.º 55
0
def rose(draw, a=20, n = 12):

    angle = (n-2) * 180. / n
    k = 18
    for _ in xrange(k):
        for i in xrange(n):
            draw.forward(a)
            draw.right(180 - angle)
        draw.right(360./k)



if __name__ == "__main__":

    draw = Turtle("Various_pictures")

    draw.setCoord(10, 10)
    draw.resetDir()

    draw.penDown()
    square(draw, 200)

    draw.resetDir()
    draw.setCoord(210, 70)
    barredCircle(draw, r=50, shift=5)

    draw.setCoord(75, 200)
    triangle(draw, 10, 5, 15)

    draw.setCoord(225, 210)
Ejemplo n.º 56
0
 def __init__(self, position, heading, scale, fill=blue, **style):
     Turtle.__init__(self, position, heading, fill=fill, **style)
     self.scale = scale * 100 #default scaling is 100