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()
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
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()
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
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
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))
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 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
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)
def polycircle(n=12): t = Turtle('polycircle') for x in xrange(n): t.polygon(n, 20) t.left(360/n) t.save()
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
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()
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()
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()
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()
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
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()
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 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 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()
def triangles(side=100, step=20, n=10): t = Turtle('triangles') d = 300 for i in xrange(n): side += (3*step) t.polygon(3, side) t.right(120) t.pen_up() t.forward(step) t.left(120) t.back(step) t.pen_down() t.save()
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)
def squares(max_levels = 15): t = Turtle('squares') d = 300 for i in range(max_levels): for i in range(4): t.forward(d) t.right(90) t.forward(d/4) t.right(90/5) d = sqrt((d/4)**2 + (d - d/4)**2) t.save()
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()
def CreateChar(t): switcher = { 'A' : lambda : Antelope(), 'C' : lambda : CyberSheep(), 'F' : lambda : Fox(), 'S' : lambda : Sheep(), 'T' : lambda : Turtle(), 'W' : lambda : Wolf(), 'B' : lambda : Belladonna(), 'D' : lambda : Dandelion(), 'G' : lambda : Grass(), 'U' : lambda : Guarana(), 'H' : lambda : HeracleumSosnowskyi(), 'P' : lambda : Human() } func = switcher.get(t, None) return func()
def CreateString(s): switcher = { "Antelope" : lambda : Antelope(), "CyberSheep" : lambda : CyberSheep(), "Fox" : lambda : Fox(), "Sheep" : lambda : Sheep(), "Turtle" : lambda : Turtle(), "Wolf" : lambda : Wolf(), "Belladonna" : lambda : Belladonna(), "Dandelion" : lambda : Dandelion(), "Grass" : lambda : Grass(), "Guarana" : lambda : Guarana(), "Heracleum" : lambda : HeracleumSosnowskyi(), "Player" : lambda : Human() } func = switcher.get(s, None) return func()
def __init__(self): super(Case1, self).__init__() # key # self.index = 'SZ159915' # 创业板ETF # self.index = 'SH510300' # 300ETF self.index = 'SH510050' # 50ETF # self.index = 'SZ159902' # 中小板 # self.index = 'SZ159901' # 深100ETF # self.index = 'SZ150153' # 创业板分级B self.beginAsset = 100000 # tutle self.assetCtrl = Turtle() # self.assetCtrl = Elephant() self.assetCtrl.original = self.beginAsset self.assetCtrl.all = self.beginAsset self.assetCtrl.nKey = '20' self.inputLock = False self.mmax = '10' self.mmin = '20' self.ma = '20' self.beginIndex = 20
def randomSegments(n, l=150): points = np.random.uniform(0, 300, [n, 2]) vector = np.array([[l, 0]]) pairs = [] for i in xrange(n): A = points[i, :] while True: B = A + randomVector(l) if B[0, 0] >= 0 and B[0, 1] >= 0: # is it within first quadrant? pairs.append(np.row_stack((A, B))) break return pairs if __name__ == '__main__': draw = Turtle("Intersection") segments = randomSegments(15) for i, seg1 in enumerate(segments): for seg2 in segments[i + 1:]: intersect = segmentIntersect(seg1, seg2) if intersect != None: draw.addPoint(intersect) for seg in segments: draw.addLineNumpy(seg[0], seg[1]) draw.dumpImage()
from Turtle import Turtle import argparse from math import sin, radians import random if __name__ == "__main__": parser = argparse.ArgumentParser( description='Drunken turtle : study of brownian motion') parser.add_argument('step_size', type=float, help='size of each step') parser.add_argument('nb_steps', type=int, help='number of steps') parser.add_argument('nb_turtles', type=int, help='number of turtles') args = parser.parse_args() step_size = args.step_size nb_steps = args.nb_steps nb_turtles = args.nb_turtles turtles = [None] * nb_turtles for t in range(nb_turtles): turtles[t] = Turtle(random.random(), random.random(), 0) for i in range(nb_steps): for j in range(nb_turtles): turtles[j].turn_left(random.random() * 360) turtles[j].go_forward(step_size) tur = Turtle(0, 0, 0) for t in range(nb_turtles): tur.merge(turtles[t]) tur.draw()
from Turtle import Turtle import argparse from math import sin, radians if __name__ == "__main__": parser = argparse.ArgumentParser(description='Draw a pointed start') parser.add_argument('n', type=int, help='number of sides of the star : odd number') args = parser.parse_args() n = args.n # t = Turtle(0.5,0.1, 180/n) t = Turtle(0.5, 0.1, 180 / n * 6) size = sin(radians(180 / n)) for i in range(n): t.go_forward(size) t.turn_left(-360 / n * 2) print(t._lines) t.draw()