class HanoiEngine: def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0, -80); self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('yellow') for x in -140, 0, 140: self.designer.goto(x, -5); self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Pole(-140) self.towerB = Pole(0) self.towerC = Pole(140) self.ts.tracer(True)
def draw_polygon(self, node, screen): pen = RawTurtle(screen) pen.speed(0) pen.hideturtle() pen.penup() try: linecolor = node.attrs['color'] except KeyError: linecolor = None try: fillcolor = node.attrs['fillcolor'] except KeyError: fillcolor = None if linecolor is not None: pen.pencolor(*linecolor) else: pen.pencolor(*(0, 0, 0)) polygon = node.data polygon = [self.translate_coords(screen, x) for x in polygon] points = to_tups(polygon) pen.goto(*(points[0])) pen.pendown() if fillcolor: pen.fillcolor(*fillcolor) pen.pencolor(*fillcolor) pen.begin_fill() for point in points[::-1]: pen.goto(*point) if fillcolor: pen.end_fill()
class HanoiEngine: """Play the Hanoi-game on a given TurtleScreen.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0,-80); self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('darkgreen') for x in -140, 0, 140: self.designer.goto(x,-5); self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Tower(-140) self.towerB = Tower(0) self.towerC = Tower(140) self.ts.tracer(True) def setspeed(self): for disc in self.discs: disc.speed(self.speed) def move(self, src_tower, dest_tower): """move uppermost disc of source tower to top of destination tower.""" dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): """Setup of (a new) game.""" self.ts.tracer(False) self.moveCnt = 0 self.moveDisplay(0) for t in self.towerA, self.towerB, self.towerC: while t != []: t.pop(200) for k in range(self.nrOfDiscs-1,-1,-1): self.discs[k].config(k, self.nrOfDiscs) self.towerA.push(self.discs[k]) self.ts.tracer(True) def run(self): """run game ;-) return True if game is over, else False""" self.running = True ex7.play_hanoi(self, self.nrOfDiscs, self.towerA, self.towerC, self.towerB) return True
class Sugar: def __init__(self, turtle_window, id_number): # comment here self.turtle_window = turtle_window self.id_number = id_number self.name = 'Sugar' # comment here self.turtle_object = RawTurtle(self.turtle_window.wn) self.turtle_object.hideturtle() self.turtle_object.shape('square') self.turtle_object.penup() self.turtle_object.color("black", "white") self.place() self.turtle_object.showturtle() # comment here self.turtle_object.ondrag(self.drag) def place(self): # comment here self.turtle_object.goto(random.randint(-MAX_LOCATION, MAX_LOCATION), random.randint(-MAX_LOCATION, MAX_LOCATION)) def drag(self, x, y): # comment here self.turtle_object.goto(x, y) self.turtle_window.wn.update()
def juhuslikud_konnad(n=100, t=100): """ Tekitab n juhuslikult liikuvat konna """ ekraan = Screen() konnad = [] for i in range(n): # Paigutame konna i juhuslikele koordinaatidele konn_i = RawTurtle(ekraan) konn_i.up() x = randint(-100, 100) y = randint(-100, 100) konn_i.goto(x, y) konn_i.down() # Värvime konna juhusliku värviga varv = choice(['green', 'brown', 'black', 'red', 'blue']) konn_i.color(varv) # Lisame konna i konnade hulka konnad.append(konn_i) # Teeme t juhuslikku liikumist juhusliku konnaga for ti in range(t): suunamuutus = randint(-60, 60) konn = choice(konnad) konn.left(suunamuutus) konn.fd(20)
def juhuslikud_konnad(n=10, t=10000): """ tekitab n juhuslike konne """ ekraan = Screen() konnad = [] for i in range(n): #paigutame konna i juhuslikudele koordinaatidele konn_i = RawTurtle(ekraan) konn_i.up() x = randint(-100, 100) y = randint(-100, 100) konn_i.goto(x, y) konn_i.down() #lisame konna i konnade hulka konnad.append(konn_i) #varvilised konnad varv = choice(['green', 'brown', 'black', 'blue', 'red', 'yellow']) konn_i.color(varv) #lisame varvilisi konne konnad.append(konn_i) #teeme tee juhuslikku liikumist juhusliku konnaga for ti in range(t): suunamuutus = randint(-61, 61) juhuslikk_indeks = randint(0, n - 1) konn = choice(konnad) konn.left(suunamuutus) konn.fd(20)
class HanoiEngine: """Play the Hanoi-game on a given TurtleScreen.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0,-80); self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('darkgreen') for x in -140, 0, 140: self.designer.goto(x,-5); self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Tower(-140) self.towerB = Tower(0) self.towerC = Tower(140) self.ts.tracer(True) def setspeed(self): for disc in self.discs: disc.speed(self.speed) def move(self, src_tower, dest_tower): """move uppermost disc of source tower to top of destination tower.""" dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): """Setup of (a new) game.""" self.ts.tracer(False) self.moveCnt = 0 self.moveDisplay(0) for t in self.towerA, self.towerB, self.towerC: while t != []: t.pop(200) for k in range(self.nrOfDiscs-1,-1,-1): self.discs[k].config(k, self.nrOfDiscs) self.towerA.push(self.discs[k]) self.ts.tracer(True) def run(self): """run game ;-) return True if game is over, else False""" self.running = True ex7.play_hanoi(self, self.nrOfDiscs, self.towerA, self.towerC, self.towerB) return True
def DrawGeometry(self,_turtle: t.RawTurtle): self.angle = self.angle % 360 planes = copy.deepcopy(self.plane) p = copy.deepcopy(self.pos) a = copy.deepcopy(self.getRadAngle()) for pl in planes: vertexs = pl[0] _turtle.color(pl[1]) for i,v in enumerate(vertexs): v = np.dot(v,rotx(a[0])) v = np.dot(v,roty(a[1])) v = np.dot(v,rotz(a[2])) vertexs[i] = v + p avec = vertexs[1]-vertexs[0] bvec = vertexs[2]-vertexs[1] cross = np.cross(avec,bvec) _d = np.mean(vertexs,axis = 0) d = np.array([_d[0],_d[1],-(_d[2]+30)]) _turtle.goto(vertexs[0][0]*(vertexs[0][2]+30)/2,vertexs[0][1]*(vertexs[0][2]+30)/2) if np.dot(cross,d) > 0: _turtle.pendown() _turtle.begin_fill() for v in vertexs: _turtle.goto(v[0]*(v[2]+30)/2,v[1]*(v[2]+30)/2) _turtle.end_fill() _turtle.penup()
class Object: """Die Klasse Beschreibt wie ein Obst oder Gift aussieht""" def __init__(self, window, shape): self.obj = RawTurtle(window) self.obj.speed(0) self.obj.shape(shape) self.obj.penup() self.obj.goto(0, 100) def getObj(self): return self.obj def getYPos(self): return self.obj.ycor() def getXPos(self): return self.obj.xcor() # In Dieser Methode wird ein Obst oder ein Gift genau auf die Stelle gesetzt, an der der Schlangenkopf es genau im richtige Pixel treffen kann. def setPos(self, x, y): self.obj.goto(x, y) self.obj.sety(self.obj.ycor() - (self.obj.ycor() % 20)) self.obj.setx(self.obj.xcor() - (self.obj.xcor() % 20)) return def hideObj(self): self.obj.hideturtle() def randomPos(self): x = random.randint(-280, 280) y = random.randint(-280, 280) self.setPos(x, y)
def draw_dots(turt: RawTurtle) -> None: penstate = turt.pen() turt.penup() for x, y in DIGIT2POS.values(): turt.setheading(turt.towards(x, y)) turt.goto(x, y) turt.dot() turt.pen(pen = penstate)
def pen(self): turt = RawTurtle(self.screen) turt.ht() turt.speed(0) turt.up() turt.goto(-self.width, self.height) turt.down() return turt
def draw_pattern(turt: RawTurtle, pattern: str) -> None: penstate = turt.pen() turt.penup() for x, y in map(lambda digit: DIGIT2POS[digit], pattern): turt.setheading(turt.towards(x, y)) turt.goto(x, y) turt.pendown() turt.dot() turt.pen(pen = penstate)
def getReady(): for i in [ 5, 4, 3, 2, 1 ,0]: time.sleep(1) line = RawTurtle(myGameField.getRootWindow()) line.speed(0) line.shape("square") line.color("white") line.penup() line.hideturtle() # Versteckte Überschrift line.goto(0,0) line.write("Get ready %s" % i , align= "center", font=("Courier", 18 ,"normal")) line.clear()
def draw(ans): """Вывод топологической схемы""" global xax, moves, oboz, window turx, tury = xax - int(xax*0.3), int(yax*0.25) bg_def = window.cget('bg') canvas = Canvas(window, relief='sunken', borderwidth=5, width=turx, height=tury, background=bg_def) canvas.place(relx=0.5, rely=0.1, y=int(yax*0.19), anchor=CENTER) screen = TurtleScreen(canvas) global turtle turtle = RawTurtle(canvas) turtle.speed(5) turtle.hideturtle() allen = (turx - int(xax*0.2)) global let if len(ans) > 7: if ans[5] == 1 and ans[8] == 1: let = allen // 3 else: if ans[5] == 1: let = allen // 4 elif ans[8] == 1: let = allen // 4 else: let = allen // 5 if ans[5] == 2: allen -= let//2 if ans[8] == 2: allen -= let//2 else: if ans[5] == 1: let = allen // 2 else: let = allen // 3 if ans[5] == 2: allen -= let//2 turtle.color('white') turtle.up() turtle.goto(x=-allen // 2, y=-int(yax*0.09)) turtle.down() turtle.color('black') turtle.dot(5, 'black') turtle.write('A') for i in [moves[k + 1][x] for k, x in enumerate(ans) if k + 1 in moves]: print(i) eval(i)
def draw(list_rectangles, list_squares): """ Opens a window and draws all the Rectangles and Squares using turtle module Args: list_rectangles (list): list of rectangles to draw list_squares (list): list of squares to draw """ screen = Screen() screen.setup() screen.bgcolor("black") colors = ["cyan", "red", "blue", "white", "purple", "green", "brown", "#285078"] square = RawTurtle(screen) rectangle = RawTurtle(screen) # square.speed(10) # rectangle.speed(10) for sq in list_squares: square.penup() square.home() square.color(random.choice(colors)) square.goto(sq.x, sq.y) square.pendown() square.begin_fill() i = 0 while i < 4: square.forward(sq.size) square.left(90) i += 1 square.end_fill() square.hideturtle() for rect in list_rectangles: rectangle.penup() rectangle.home() rectangle.color(random.choice(colors)) rectangle.goto(rect.x, rect.y) rectangle.pendown() i = 0 while i < 2: rectangle.forward(rect.width) rectangle.left(90) rectangle.forward(rect.height) rectangle.left(90) i += 1 rectangle.hideturtle() done()
class HeatSource: ############################################################################################################### def __init__(self, turtle_window, id_number): self.turtle_window = turtle_window self.id_number = id_number self.heat_source = RawTurtle(self.turtle_window.wn) self.heat_source.hideturtle() self.heat_source.shape('circle') self.heat_source.penup() self.heat_source.color("orange") self.place() self.heat_source.showturtle() self.heat_source.ondrag(self.drag_heat_source) def place(self): max_location = self.turtle_window.screen_size / 2 - 10 self.heat_source.goto(random.randint(-max_location, max_location), random.randint(-max_location, max_location)) def drag_heat_source(self, x, y): self.heat_source.goto(x, y) self.turtle_window.wn.update()
class Headline: """Die Klasse beschreibt das Aussehen einer Headline zum Anzeigen des Scores, HighScores, und der HighScoreListe.""" def __init__(self, window, content, x, y): self.headline = RawTurtle(window) self.headline.speed(0) self.headline.shape("square") self.headline.color("white") self.headline.penup() self.headline.hideturtle() self.headline.goto(x, y) self.headline.write(content, align="center", font=("Courier", 18, "normal")) def setPos(self, x, y): self.headline.goto(x, y) def writeHeadlineForGameOver(self): self.headline.clear() self.headline.write("Game Over", align="center", font=("Courier", 18, "normal")) def writeNewHeadline(self, score, newScore): self.headline.clear() self.headline.write("Score:{} High Score: {}".format(score, newScore), align="center", font=("Courier", 18, "normal")) def clearHideline(self): self.headline.clear() def writeNewHeadlineForBestList(self, content): self.headline.clear() self.headline.write(content, align="center", font=("Courier", 18, "normal"))
def draw(lines): from tkinter import Tk, LEFT from turtle import Canvas, RawTurtle, TurtleScreen # set up the environment root = Tk() canvas = Canvas(root, width=800, height=800) canvas.pack() s = TurtleScreen(canvas) t = RawTurtle(canvas) t.speed(0) t.width(1) for line in lines: x, y = line[0] t.up() t.goto(x * 800 / 1024 - 400, -(y * 800 / 1024 - 400)) for point in line: t.down() t.goto(point[0] * 800 / 1024 - 400, -(point[1] * 800 / 1024 - 400)) s.mainloop()
def drawGrid(): screen.clear() screen.tracer(1000000) screen.setworldcoordinates(screenMin, screenMin, screenMax, screenMax) screen.bgcolor("white") screen.tracer(0) t = RawTurtle(canvas) t.hideturtle() t.penup() t.width(10) t.color("black") for i in range(2): t.penup() t.goto(i * 100 + 100, 10) t.pendown() t.goto(i * 100 + 100, 290) t.penup() t.goto(10, i * 100 + 100) t.pendown() t.goto(290, i * 100 + 100) screen.update()
class HanoiEngine: def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.4, 25) self.designer.goto(0, -81) self.designer.stamp() self.designer.shapesize(4, 0.5) self.designer.fillcolor('Black') for x in -150, 0, 150: self.designer.goto(x, -5) self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Tower(-150) self.towerB = Tower(0) self.towerC = Tower(150) self.ts.tracer(True) def setspeed(self): for disc in self.discs: disc.speed(self.speed) def hanoi(self, n, src, dest, temp): #use of recurssion for movement if n > 0: for x in self.hanoi(n - 1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n - 1, temp, dest, src): yield None def move(self, src_tower, dest_tower): #movement of upper disks dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): # start a new game self.ts.tracer(False) self.moveCnt = 0 self.moveDisplay(0) for t in self.towerA, self.towerB, self.towerC: while t != []: t.pop(200) for k in range(self.nrOfDiscs - 1, -1, -1): self.discs[k].config(k, self.nrOfDiscs) self.towerA.push(self.discs[k]) self.ts.tracer(True) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): #true if game is over else false self.running = True try: while self.running: result = self.step() return result # True iff done except StopIteration: # game over return True def step(self): """perform one single step of the game, returns True if finished, else False""" try: next(self.HG) return 2**self.nrOfDiscs - 1 == self.moveCnt except TclError: return False def stop(self): """ ;-) """ self.running = False
class HanoiEngine: def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0, -80) self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('yellow') for x in -140, 0, 140: self.designer.goto(x, -5) self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Pole(-140) self.towerB = Pole(0) self.towerC = Pole(140) self.ts.tracer(True) def setspeed(self): for disc in self.discs: disc.speed(self.speed) def hanoi(self, n, src, dest, temp): if n > 0: for x in self.hanoi(n - 1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n - 1, temp, dest, src): yield None def move(self, src_tower, dest_tower): dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): self.ts.tracer(False) self.moveCnt = 0 self.moveDisplay(0) for t in self.towerA, self.towerB, self.towerC: while t != []: t.pop(200) for k in range(self.nrOfDiscs - 1, -1, -1): self.discs[k].config(k, self.nrOfDiscs) self.towerA.push(self.discs[k]) self.ts.tracer(True) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): self.running = True try: while self.running: result = self.step() return result # True iff done except StopIteration: # game over return True def step(self): try: next(self.HG) return 2**self.nrOfDiscs - 1 == self.moveCnt except TclError: return False def stop(self): self.running = False
class Stage: @classmethod def create(cls, screen): stage = cls(screen) start = screen.start blocks = screen.blocks for i in range(blocks): stop = start + screen.blockwidth stage.positions.append((start,stop)) base = -screen.base height = screen.increment * (i+1) color = next(screen.gradient) block = Block(screen, base=base, index=i, height=height, parent=stage, color=color) stage.blocks.append(block) block.draw() start = stop + 1 stage.get_pen() return stage def append(self, other): if other.index: other.clear() l = len(self) other.index = (l) self.blocks.append() def slice(self, *args): if len(args) > 2: raise Exception if len(args) == 2: start, stop = args if len(args) == 1: start, stop = 0, args[0] if len(args) == 0: start, stop = 0, len(self.blocks) stage = Stage(self.screen) for idx, i in enumerate(range(start,stop)): stage.positions.append(self.positions[i]) block = self.blocks[i].new() block.index = idx stage.blocks.append(block) return stage def __init__(self, screen): self.screen = screen self.positions = [] self.blocks = [] self.operations = 0 self.pen = None def get_pen(self): self.pen = RawTurtle(self.screen) self.pen.color("#f0d1bf") xpos = 0 ypos = self.screen.height - 30 self.pen.up() self.pen.ht() self.pen.goto(xpos, ypos) self.pen.down() def __getitem__(self, idx): return self.blocks[idx] def __setitem__(self, idx, other): if other.index not in [idx, None]: other.clear() self.blocks[other.index] = None if self.blocks[idx] != None: self.blocks[idx].clear() self.blocks[idx].delindex() self.blocks[idx] = other self.blocks[idx].setindex(idx) other.draw() def __str__(self): return str([i.value for i in self.blocks]) def __repr__(self): return str(self) def __len__(self): return len(self.blocks) def __iter__(self): self.iterable = iter(self.blocks) return self.iterable def __next__(self): try: block = next(self.iterable) return block except StopIteration: raise StopIteration
class HanoiEngine: """Play the Hanoi-game on a given TurtleScreen.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0, -80) self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('darkgreen') for x in -140, 0, 140: self.designer.goto(x, -5) self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Tower(-140) self.towerB = Tower(0) self.towerC = Tower(140) self.ts.tracer(True) def setspeed(self): for disc in self.discs: disc.speed(self.speed) def hanoi(self, n, src, dest, temp): """The classical recursive Towers-Of-Hanoi algorithm, implemented as a recursive generator, yielding always None plus an 'important' side effect - the next Hanoi move.""" if n > 0: for x in self.hanoi(n - 1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n - 1, temp, dest, src): yield None def move(self, src_tower, dest_tower): """move uppermost disc of source tower to top of destination tower.""" dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): """Setup of (a new) game.""" self.ts.tracer(False) self.moveCnt = 0 self.moveDisplay(0) for t in self.towerA, self.towerB, self.towerC: while t != []: t.pop(200) for k in range(self.nrOfDiscs - 1, -1, -1): self.discs[k].config(k, self.nrOfDiscs) self.towerA.push(self.discs[k]) self.ts.tracer(True) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): """run game ;-) return True if game is over, else False""" self.running = True try: while self.running: result = self.step() return result # True iff done except StopIteration: # game over return True def step(self): """perform one single step of the game, returns True if finished, else False""" try: next(self.HG) return 2**self.nrOfDiscs - 1 == self.moveCnt except TclError: return False def stop(self): """ ;-) """ self.running = False
class Vehicle: ############################################################################################################### def __init__(self, turtle_window, id_number): self.speed_params = [20, 0.2, 6] self.turn_parameters = [20] self.turtle_window = turtle_window self.max_location = self.turtle_window.screen_size / 2 - 10 self.vehicle = RawTurtle(self.turtle_window.wn) self.vehicle.hideturtle() self.id_number = id_number self.type = random.choice(["crossed", "direct"]) self.vehicle.shape('turtle') self.vehicle.turtlesize(1) self.vehicle.penup() if self.type == 'crossed': self.vehicle.color("red", (1, 0.85, 0.85)) else: self.vehicle.color("blue", (0.85, 0.85, 1)) self.place() self.vehicle.showturtle() def place(self): self.vehicle.goto( random.randint(-self.max_location, self.max_location), random.randint(-self.max_location, self.max_location)) self.vehicle.right(random.randint(0, 360)) ############################################################################################################### def move(self): cumulative_speed = 0 cumulative_turn_amount = 0 for heat_source in self.turtle_window.heat_source_list: input_distance = self.vehicle.distance( heat_source.heat_source.pos()) input_angle = self.vehicle.heading() - self.vehicle.towards( heat_source.heat_source.pos()) sin_angle = math.sin(math.radians(input_angle)) left_sensor_distance = input_distance - sin_angle right_sensor_distance = input_distance + sin_angle left_speed, right_speed, combined_speed = self.compute_speed( left_sensor_distance, right_sensor_distance) turn_amount = self.turn_parameters[0] * (right_speed - left_speed) cumulative_speed += combined_speed cumulative_turn_amount += turn_amount if isinstance(cumulative_turn_amount, complex): cumulative_turn_amount = 0 if cumulative_speed < 0: cumulative_speed = 0 self.vehicle.right(cumulative_turn_amount) self.vehicle.forward(cumulative_speed) self.check_border_collision() def check_border_collision(self): if self.vehicle.xcor() > self.max_location: self.vehicle.goto(self.max_location, self.vehicle.ycor()) if self.vehicle.xcor() < -self.max_location: self.vehicle.goto(-self.max_location, self.vehicle.ycor()) if self.vehicle.ycor() > self.max_location: self.vehicle.goto(self.vehicle.xcor(), self.max_location) if self.vehicle.ycor() < -self.max_location: self.vehicle.goto(self.vehicle.xcor(), -self.max_location) if self.vehicle.ycor() <= -self.max_location: if 0 <= self.vehicle.heading() <= 180: turn_angle = 180 - self.vehicle.heading() self.vehicle.setheading(turn_angle) else: turn_angle = abs(360 - self.vehicle.heading()) self.vehicle.setheading(turn_angle) if self.vehicle.ycor() >= self.max_location: if 0 <= self.vehicle.heading() <= 180: turn_angle = 360 - self.vehicle.heading() self.vehicle.setheading(turn_angle) else: turn_angle = 360 - (self.vehicle.heading() - 180) self.vehicle.setheading(turn_angle) if self.vehicle.xcor() <= -self.max_location: if 0 <= self.vehicle.heading() <= 90: turn_angle = 360 - self.vehicle.heading() self.vehicle.setheading(turn_angle) if 270 < self.vehicle.heading() <= 360: turn_angle = 360 - self.vehicle.heading() self.vehicle.setheading(turn_angle) if 90 < self.vehicle.heading() < 180: turn_angle = self.vehicle.heading() - 90 self.vehicle.setheading(turn_angle) if 180 <= self.vehicle.heading() <= 360: turn_angle = self.vehicle.heading() + 90 self.vehicle.setheading(turn_angle) if self.vehicle.xcor() >= self.max_location: if 0 <= self.vehicle.heading() <= 180: turn_angle = self.vehicle.heading() + 90 self.vehicle.setheading(turn_angle) else: turn_angle = self.vehicle.heading() - 90 self.vehicle.setheading(turn_angle) ############################################################################################################### def compute_speed(self, left_distance, right_distance): if self.type == 'crossed': left_speed = ( self.speed_params[0] / (right_distance**self.speed_params[1])) - self.speed_params[2] right_speed = ( self.speed_params[0] / (left_distance**self.speed_params[1])) - self.speed_params[2] else: left_speed = ( self.speed_params[0] / (left_distance**self.speed_params[1])) - self.speed_params[2] right_speed = ( self.speed_params[0] / (right_distance**self.speed_params[1])) - self.speed_params[2] combined_speed = (left_speed + right_speed) / 2 return left_speed, right_speed, combined_speed
pen2 = RawTurtle(turtle_screen) # Configuring the first pen # The first color is the color of the pen # The second is color we want to use to fill the figure pen1.color("misty rose", "violet") pen1.width(3) # Configuring the second pen pen2.color("violet", "misty rose") pen2.width(3) # Drawing the figure pen1.begin_fill() pen2.begin_fill() pen1.goto(0, 100) pen2.goto(0, 100) pen1.goto(0, -50) pen2.goto(0, -50) pen2.left(40) pen1.left(140) pen2.forward(100) pen1.forward(100) for side in range(185): pen2.forward(1) pen1.forward(1) pen2.left(1) pen1.right(1) # Filling the figure pen2.end_fill()
class HanoiEngine: def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): self.ts = canvas self.ts.tracer(False) self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0,-80); self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('black') for x in -140, 0, 140: self.designer.goto(x,-5); self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Tower(-140) self.towerB = Tower(0) self.towerC = Tower(140) self.ts.tracer(True) def setspeed(self): for disc in self.discs: disc.speed(self.speed) def hanoi(self, n, src, dest, temp): if n > 0: for x in self.hanoi(n-1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n-1, temp, dest, src): yield None def move(self, src_tower, dest_tower): dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): self.ts.tracer(False) self.moveCnt = 0 self.moveDisplay(0) for t in self.towerA, self.towerB, self.towerC: while t != []: t.pop(200) for k in range(self.nrOfDiscs-1,-1,-1): self.discs[k].config(k, self.nrOfDiscs) self.towerA.push(self.discs[k]) self.ts.tracer(True) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): self.running = True try: while self.running: result = self.step() return result except StopIteration: return True def step(self): try: next(self.HG) return 2**self.nrOfDiscs-1 == self.moveCnt except TclError: return False def stop(self): self.running = False
class HanoiEngine: """Play the Hanoi-game on a given TurtleScreen.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" global gameStatus self.highScoreArray = [] self.combinedArray = [] self.universalArray = [] self.setCanvas = canvas self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0, -80) self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('pink') for x in -140, 0, 140: self.designer.goto(x, -5) self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.winCondition = False ''' elson code ''' gameStatus = "withoutTurtle" self.currentStatus = "AI" self.samplemoves = [] # The set of move generate by AI self.usermoves = [] # The set of move user move self.finalmoves = [] # The final set of move self.minmoves = 0 self.totalmoves = 0 self.startsource = Tower(-140) self.starthelper = Tower(0) self.starttarget = Tower(140) self.goaltarget = Tower(140) self.AISource = Tower(-140) self.AIHelper = Tower(0) self.AITarget = Tower(140) self.goalMoves = [] self.playerMoves = [] ''' elson code ''' self.numValue = 0 self.discs = [] self.towerA = Tower(-140) self.towerB = Tower(0) self.towerC = Tower(140) print "A:", self.towerA.size(), "value:", self.towerA.peek() print "B:", self.towerB.size(), "value:", self.towerB.peek() print "C:", self.towerC.size(), "value:", self.towerC.peek() self.ts.tracer(True) def getGameStatus(self): return self.gameStatus #elson code def savestate(self, stack): self.newstack = Tower(0) self.newstack.copyFrom(stack) return self.newstack #elson code # Restore the stack to start state def startstate(self): self.towerA.copyFrom(self.startsource) self.towerB.copyFrom(self.starthelper) self.towerC.copyFrom(self.starttarget) #elson code def moveTower(self, disc, Beg, Aux, End): global gameStatus if disc == 1: self.moveDisk(Beg, End) if getGameStatus() is "turtle": self.moveCnt += 1 self.moveDisplay(self.moveCnt) self.samplemoves.append(self.savestate(self.towerA)) self.samplemoves.append(self.savestate(self.towerB)) self.samplemoves.append(self.savestate(self.towerC)) #print (Beg, Aux, End) else: self.moveTower(disc - 1, Beg, End, Aux) self.moveTower(1, Beg, Aux, End) self.moveTower(disc - 1, Aux, Beg, End) '''elson code''' # Move disk from the src stack to dest stack def moveDisk(self, frompole, topole): # print("moving disk from",frompole.gettitle(),"to",topole.gettitle()) #if self.checkvalid(frompole, topole) is True: #if getGameStatus() is "turtle": if self.currentStatus is "AI": self.goalMoves.append(MyMoves(frompole, topole)) else: self.playerMoves.append(MyMoves(frompole, topole)) self.moveCnt += 1 self.moveDisplay(self.moveCnt) print("moving disk from ", frompole.peek(), " to ", topole.peek()) topole.push(frompole.pop()) #self.moveCnt += 1 #self.moveDisplay(self.moveCnt) '''elson code''' # generate the sample set of solutions def gensamplemove(self, source, helper, target): self.moveTower(source.size(), source, helper, target) '''elson code''' # Check of the rules of Hanoi def checkvalid(self, frompole, topole): if (frompole.size() == 0 or frompole == topole): # frompole is empty or frompole and topole is same return False else: if (topole.peek() is None or frompole.peek() < topole.peek() ): # topole is empty or from is smaller than to self.moveDisk(frompole, topole) self.usermoves.append(self.savestate(self.towerA)) self.usermoves.append(self.savestate(self.towerB)) self.usermoves.append(self.savestate(self.towerC)) self.finalmoves.append(self.savestate(self.towerA)) self.finalmoves.append(self.savestate(self.towerB)) self.finalmoves.append(self.savestate(self.towerC)) return True elif frompole.peek() > topole.peek(): return False '''elson code''' # Conver the string input to the variable of stack '''def convert(self, word): if(word == "a"): return source elif(word == "b"): return helper elif(word == "c"): return target''' '''elson code''' def findmatch(self): for i in range(len(self.usermoves) - 1, 0, -3): #print (self.usermoves[i-2], self.usermoves[i-1], self.usermoves[i]) if (i != len(self.usermoves) - 1 ): # append the backtrack state, only add after first i loop self.finalmoves.append(self.usermoves[i - 2]) self.finalmoves.append(self.usermoves[i - 1]) self.finalmoves.append(self.usermoves[i]) for j in range(0, len(self.samplemoves), 3): #print (self.samplemoves[i-2], self.samplemoves[i-1], self.samplemoves[i]) if (self.usermoves[i - 2].isEqual(self.samplemoves[j]) and self.usermoves[i - 1].isEqual(self.samplemoves[j + 1]) and self.usermoves[i].isEqual( self.samplemoves[j + 2])): index = j return j '''elson code''' def solve(self): global gameStatus gameStatus = "turtle" ''' index = self.findmatch() for j in range(index+3,len(self.samplemoves),3): # append state after the match self.finalmoves.append(self.samplemoves[j]) self.finalmoves.append(self.samplemoves[j+1]) self.finalmoves.append(self.samplemoves[j+2]) ''' newArray = [] num = len(self.playerMoves) - 1 for q in range(0, len(self.playerMoves)): temp = self.playerMoves[q].srcTower self.playerMoves[q].srcTower = self.playerMoves[q].destTower self.playerMoves[q].destTower = temp newArray.append(self.playerMoves[num]) num -= 1 #print len(newArray) self.speed = 8 % 10 self.setspeed() for w in range(0, len(newArray)): #print newArray[w] self.move(newArray[w].srcTower, newArray[w].destTower) self.speed = 3 % 10 self.setspeed() for v in range(0, len(self.goalMoves)): self.move(self.goalMoves[v].srcTower, self.goalMoves[v].destTower) del newArray[:] gameStatus = "turtle" self.currentStatus = "AI" return True def getTowerA(self): return self.towerA def getTowerB(self): return self.towerB def getTowerC(self): return self.towerC def setspeed(self): for disc in self.discs: disc.speed(self.speed) def move(self, src_tower, dest_tower): """move uppermost disc of source tower to top of destination tower.""" self.winCondition = False dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): """Setup of (a new) game.""" self.ts.tracer(False) global gameStatus, currentStatus gameStatus = "turtle" Hanoi.state = "START" del self.playerMoves[:] del self.goalMoves[:] self.moveCnt = 0 self.moveDisplay(0) self.resetTowers(self.towerA) self.resetTowers(self.towerB) self.resetTowers(self.towerC) self.numValue = 0 del self.discs[:] for x in range(self.nrOfDiscs): self.numValue += 1 self.discs.append(Disc(self.setCanvas, self.numValue)) print self.numValue for k in range(self.nrOfDiscs - 1, -1, -1): self.discs[k].config(k, self.nrOfDiscs) # self.towerA.push(self.discs[k]) gameStatus = "withoutTurtle" ''' elson code ''' self.startsource.copyFrom(self.towerA) # Save the start state self.starthelper.copyFrom(self.towerB) self.starttarget.copyFrom(self.towerC) # Include the start state in sample moves set self.samplemoves.append(self.startsource) self.samplemoves.append(self.starthelper) self.samplemoves.append(self.starttarget) ''' elson code ''' """ AI attempt to solve """ self.gensamplemove(self.towerA, self.towerB, self.towerC) # Printing for checking sample moves set purpose # print "Number of element:",len(samplemoves) # print "Number of minimum steps:",minmoves # for i in range(0, len(samplemoves), 3): # printprogess(samplemoves[i], samplemoves[i+1], samplemoves[i+2]) """ Restore start state """ self.startstate() # Include the start state in user moves set self.usermoves.append(self.startsource) self.usermoves.append(self.starthelper) self.usermoves.append(self.starttarget) self.finalmoves.append(self.startsource) self.finalmoves.append(self.starthelper) self.finalmoves.append(self.starttarget) gameStatus = "turtle" self.currentStatus = "user" #for k in range(self.nrOfDiscs - 1, -1, -1): # self.discs[k].config(k, self.nrOfDiscs) # self.towerA.push(self.discs[k]) # self.AISource.push(self.discs[k]) print "A:", self.towerA.size() print "B:", self.towerB.size() print "C:", self.towerC.size() self.ts.tracer(True) #self.HG = self.hanoi(self.nrOfDiscs, # self.towerA, self.towerC, self.towerB) def resetTowers(self, tower): if tower.size() > 0: for x in range(0, tower.size()): tower.pop(200) def checkWin(self): if self.towerC.size() is self.nrOfDiscs: self.winCondition = True Hanoi.state = "DONE" return self.winCondition def storeHighScore(self): self.highScoreArray.append(WinData(self.nrOfDiscs, self.moveCnt)) for j in range(1, 11): for i in range(0, len(self.highScoreArray)): if self.highScoreArray[i].getNumOfDiscs() is j: self.universalArray.append(self.highScoreArray[i]) if len(self.universalArray) > 0: self.doSelectionSort(self.universalArray) self.combinedArray = self.combinedArray + self.universalArray del self.universalArray[:] del self.highScoreArray[:] for w in range(0, len(self.combinedArray)): self.highScoreArray.append(self.combinedArray[w]) del self.combinedArray[:] return self.highScoreArray def doSelectionSort(self, universalArray): n = len(universalArray) for fillslot in range(n - 1, 0, -1): positionOfMax = 0 for location in range(1, fillslot + 1): if universalArray[location].getNumOfMove( ) > universalArray[positionOfMax].getNumOfMove(): positionOfMax = location tmp = universalArray[fillslot] universalArray[fillslot] = universalArray[positionOfMax] universalArray[positionOfMax] = tmp def stop(self): """ ;-) """ self.running = False def checkIfMoveValid(self, sourceTower, destTower): if sourceTower.peek() < destTower.peek() or destTower.peek() is None: #pop from sourceTower and push into destTower return True elif sourceTower.peek() > destTower.peek(): #return error message, do not pop from srcTower return False
class Vehicle: def __init__(self, turtle_window, id_number): # comment here self.turtle_window = turtle_window self.id_number = id_number # comment here self.speed_params = [20, 0.2, 6] self.turn_parameters = [20] # comment here self.turtle_object = RawTurtle(self.turtle_window.wn) self.turtle_object.hideturtle() self.turtle_object.shape('turtle') self.turtle_object.turtlesize(1) self.turtle_object.penup() # comment here self.likes_food_dict = {'Sugar': random.choice([True, False])} # comment here if self.likes_food_dict['Sugar']: self.turtle_object.color("red", (1, 0.85, 0.85)) else: self.turtle_object.color("blue", (0.85, 0.85, 1)) # comment here self.place() self.turtle_object.showturtle() def place(self): # comment here self.turtle_object.goto(random.randint(-MAX_LOCATION, MAX_LOCATION), random.randint(-MAX_LOCATION, MAX_LOCATION)) self.turtle_object.right(random.randint(0, 360)) def move(self): # comment here cumulative_speed = 0 cumulative_turn_amount = 0 # comment here for food_source in self.turtle_window.food_source_list: # comment here likes_food = self.likes_food_dict[food_source.name] # comment here input_distance = self.turtle_object.distance( food_source.turtle_object.pos()) # comment here input_angle = self.turtle_object.heading( ) - self.turtle_object.towards(food_source.turtle_object.pos()) # comment here sin_angle = math.sin(math.radians(input_angle)) # comment here left_sensor_distance = input_distance - sin_angle right_sensor_distance = input_distance + sin_angle # comment here left_speed, right_speed, combined_speed = self.compute_speed( left_sensor_distance, right_sensor_distance, likes_food) # comment here turn_amount = self.turn_parameters[0] * (right_speed - left_speed) # comment here cumulative_speed += combined_speed cumulative_turn_amount += turn_amount # comment here if isinstance(cumulative_turn_amount, complex): cumulative_turn_amount = 0 # comment here if cumulative_speed < 0: cumulative_speed = 0 # comment here self.turtle_object.right(cumulative_turn_amount) self.turtle_object.forward(cumulative_speed) # comment here self.check_border_collision() def check_border_collision(self): ''' comment here. Make one big comment for the function, but it must be more specific and detailed then just repeating the function name... ''' if self.turtle_object.xcor() > MAX_LOCATION: self.turtle_object.goto(MAX_LOCATION, self.turtle_object.ycor()) if self.turtle_object.xcor() < -MAX_LOCATION: self.turtle_object.goto(-MAX_LOCATION, self.turtle_object.ycor()) if self.turtle_object.ycor() > MAX_LOCATION: self.turtle_object.goto(self.turtle_object.xcor(), MAX_LOCATION) if self.turtle_object.ycor() < -MAX_LOCATION: self.turtle_object.goto(self.turtle_object.xcor(), -MAX_LOCATION) if self.turtle_object.ycor() <= -MAX_LOCATION: if 0 <= self.turtle_object.heading() <= 180: turn_angle = 180 - self.turtle_object.heading() self.turtle_object.setheading(turn_angle) else: turn_angle = abs(360 - self.turtle_object.heading()) self.turtle_object.setheading(turn_angle) if self.turtle_object.ycor() >= MAX_LOCATION: if 0 <= self.turtle_object.heading() <= 180: turn_angle = 360 - self.turtle_object.heading() self.turtle_object.setheading(turn_angle) else: turn_angle = 360 - (self.turtle_object.heading() - 180) self.turtle_object.setheading(turn_angle) if self.turtle_object.xcor() <= -MAX_LOCATION: if 0 <= self.turtle_object.heading() <= 90: turn_angle = 360 - self.turtle_object.heading() self.turtle_object.setheading(turn_angle) if 270 < self.turtle_object.heading() <= 360: turn_angle = 360 - self.turtle_object.heading() self.turtle_object.setheading(turn_angle) if 90 < self.turtle_object.heading() < 180: turn_angle = self.turtle_object.heading() - 90 self.turtle_object.setheading(turn_angle) if 180 <= self.turtle_object.heading() <= 360: turn_angle = self.turtle_object.heading() + 90 self.turtle_object.setheading(turn_angle) if self.turtle_object.xcor() >= MAX_LOCATION: if 0 <= self.turtle_object.heading() <= 180: turn_angle = self.turtle_object.heading() + 90 self.turtle_object.setheading(turn_angle) else: turn_angle = self.turtle_object.heading() - 90 self.turtle_object.setheading(turn_angle) ############################################################################################################### def compute_speed(self, left_distance, right_distance, likes_food): ''' comment here. Make one big comment for the function, but it must be more specific and detailed then just repeating the function name... explain this in Braitenberg's terms ''' if likes_food: left_speed = ( self.speed_params[0] / (right_distance**self.speed_params[1])) - self.speed_params[2] right_speed = ( self.speed_params[0] / (left_distance**self.speed_params[1])) - self.speed_params[2] else: left_speed = ( self.speed_params[0] / (left_distance**self.speed_params[1])) - self.speed_params[2] right_speed = ( self.speed_params[0] / (right_distance**self.speed_params[1])) - self.speed_params[2] combined_speed = (left_speed + right_speed) / 2 return left_speed, right_speed, combined_speed
class Basilisk: """Die Klasse Basilisk beschreibt die Eigenschaften und das Verhalten einer Schlange auf dem Spielfeld""" def __init__(self, window, shape): self.speed = 0.1 self.score = 0 self.highScore = 0 self.mouth = RawTurtle(window) self.mouth.speed(0) self.mouth.shape(shape) self.mouth.home() self.mouth.direction = "stop" self.mouth.penup() self.deadFromPoison = False self.tempScore = 1 self.body = [] def getMouth(self): return self.mouth def getBodyList(self): return self.body def getTempScore(self): return self.tempScore def setTempScore(self, tempScore): self.tempScore = tempScore def getBodyLen(self): return len(self.body) def getYPos(self): return self.mouth.ycor() def getXPos(self): return self.mouth.xcor() def setMouthPos(self, x, y): self.mouth.goto(x, y) def getSpeed(self): return self.speed def getScore(self): return self.score def getHighScore(self): return self.highScore def setSpeed(self, speed): self.speed = speed def setScore(self, score): self.score = score def setHighScore(self, highScore): self.highScore = highScore def getMouthDirection(self): return self.mouth.direction # Mit der setMouthDirection Methode bewegt sich die Schlange in eine bestimmte Richtung. def setMouthDirection(self, mouthDirection): if mouthDirection == "left": self.moveLeftwards() elif mouthDirection == "right": self.moveRightwards() elif mouthDirection == "up": self.moveUpwards() else: self.moveDownwards() # Mit der moveUpwards Methode bewegt sich die Schlange nach oben. def moveUpwards(self): gifUp = "model/resources/up.gif" if self.mouth.direction != "down": self.mouth.direction = "up" self.mouth.shape(gifUp) # Mit der moveDownwards Methode bewegt sich die Schlange nach unten. def moveDownwards(self): gifDown = "model/resources/down.gif" if self.mouth.direction != "up": self.mouth.direction = "down" self.mouth.shape(gifDown) # Mit der moveLeftwards Methode bewegt sich die Schlange nach links. def moveLeftwards(self): gifLeft = "model/resources/left.gif" if self.mouth.direction != "right": self.mouth.direction = "left" self.mouth.shape(gifLeft) # Mit der moveRightwards Methode bewegt sich die Schlange nach rechts. def moveRightwards(self): gifRight = "model/resources/right.gif" if self.mouth.direction != "left": self.mouth.direction = "right" self.mouth.shape(gifRight) # Mit der move Methode wird beschrieben, wie groß ein Sritt der Schlange in alle Richtungen ist. def move(self): if self.mouth.direction == "up": self.mouth.sety(self.mouth.ycor() + 20) if self.mouth.direction == "down": self.mouth.sety(self.mouth.ycor() - 20) if self.mouth.direction == "left": self.mouth.setx(self.mouth.xcor() - 20) if self.mouth.direction == "right": self.mouth.setx(self.mouth.xcor() + 20) def bodyFollowMouth(self): for index in range(len(self.body) - 1, 0, -1): self.body[index].goto(self.body[index - 1].xcor(), self.body[index - 1].ycor()) if len(self.body) > 0: self.body[0].goto(self.mouth.xcor(), self.mouth.ycor()) # Erweitere den Körper um einen Teil. def basiliskFeeded(self, window, shape): oneBodyBlock = RawTurtle(window) oneBodyBlock.speed(0) oneBodyBlock.shape(shape) oneBodyBlock.penup() self.body.append(oneBodyBlock) # Gib ein Dictionary mit der Position von jedem Teil des Körpers zurück. def getBodyPosInListOfDic(self): if len(self.body) > 0: allBlockskPos = [] for i in range(0, len(self.body)): x = self.body[i].xcor() y = self.body[i].ycor() allBlockskPos.append({"bodyBlock" + str(i): {'x': x, 'y': y}}) return allBlockskPos def setBodyBlockPos(self, i, x, y): self.body[i].goto(x, y) def basiliskPoisoned(self): if len(self.body) > 0: self.body[-1].goto(1000, 1000) self.body.pop() return else: self.deadFromPoison = True def basiliskLives(self): self.deadFromPoison = False # Die Schlange darf durch Wände laufen. def basiliskPushTheWall(self): if self.mouth.xcor() > 290: self.mouth.setx(self.mouth.xcor() - 580) elif self.mouth.xcor() < -290: self.mouth.setx(self.mouth.xcor() + 580) elif self.mouth.ycor() > 290: self.mouth.sety(self.mouth.ycor() - 580) elif self.mouth.ycor() < -290: self.mouth.sety(self.mouth.ycor() + 580) # Die Schlange ist tod, wenn sie gegen ihre Körperteile stößt. def basiliskIsDead(self): if self.deadFromPoison: return True for item in self.body: basiliskEatsHerself = item.distance(self.mouth) < 20 if basiliskEatsHerself: return True def basiliskEats(self, obj): return self.mouth.distance(obj) < 20 def basiliskGoHome(self): self.mouth.home() self.mouth.direction = "stop" def basiliskDeleteBody(self): for item in self.body: item.goto(1000, 1000) self.body.clear() def hideMouth(self): self.mouth.hideturtle() def isVisible(self): return self.mouth.isvisible() def showMouth(self): self.mouth.showturtle()
def loadAndDraw(load, draw, indicatorList, trades): def get_mouse_click_coor(x, y): print(x, y) barNumber = round(x / 10) barNumber = max(1, barNumber) print("Bar Number: ", barNumber, " ", d[startPt + barNumber - 1], " ", o[startPt + barNumber - 1], " ", highestHigh) # tkMessageBox("Information",str(barNumber) # # trtl.write('Vivax Solutions', font=("Arial", 20, "bold")) # chosing the font ## trtl.goto(10,highestHigh-.05*(highestHigh - lowestLow)) ## trtl.pendown() indexVal = startPt + barNumber - 1 outPutStr = str(d[indexVal]) + " " + str(o[indexVal]) + " " + str( h[indexVal]) + " " + str(l[indexVal]) + " " + str( c[indexVal]) # chosing the font root.focus_set() T.focus_set() T.insert(tk.END, outPutStr + "\n") ## trtl.goto(20,highestHigh-60) ## trtl.write(str(o[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## trtl.goto(20,highestHigh-80) ## trtl.write(str(h[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## trtl.goto(20,highestHigh-100) ## trtl.write(str(l[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## trtl.goto(20,highestHigh-120) ## trtl.write(str(c[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font ## ## #root.withdraw() if load == True: cnt = 0 file = askopenfilename( filetypes=(('CSV files', '*.csv'), ('TXT files', '*.txt'), ('POR files', '*.por')), title='Select Markets or Ports. To Test- CSV format only!') with open(file) as f: f_csv = csv.reader(f) numDecs = 0 for row in f_csv: numCols = len(row) cnt += 1 d.append(int(row[0])) dt.append(datetime.datetime.strptime(row[0], '%Y%m%d')) o.append(float(row[1])) h.append(float(row[2])) l.append(float(row[3])) c.append(float(row[4])) v.append(float(row[5])) oi.append(float(row[6])) oString = str(o[-1]) if '.' in oString: decLoc = oString.index('.') numDecs = max(numDecs, len(oString) - decLoc - 1) xDate = list() yVal = list() zVal = list() w.Button5.configure(state="normal") w.Entry1.insert(0, str(d[-1])) if draw == True: startDrawDateStr = w.Entry1.get() startDrawDate = int(startDrawDateStr) cnt = -1 for x in range(0, len(d)): cnt += 1 if startDrawDate >= d[x]: startPt = x numBarsPlot = 60 if startPt + numBarsPlot > len(d): startPt = len(d) - (numBarsPlot + 1) print(startPt, " ", len(d), " ", numBarsPlot) indicCnt = 0 screen = TurtleScreen(w.Canvas1) trtl = RawTurtle(screen) screen.tracer(False) screen.bgcolor('white') clr = ['red', 'green', 'blue', 'yellow', 'purple'] trtl.pensize(6) trtl.penup() trtl.color("black") highestHigh = 0 lowestLow = 99999999 # scaleMult = 10**numDecs scaleMult = 1 for days in range(startPt, startPt + numBarsPlot): if h[days] * scaleMult > highestHigh: highestHigh = h[days] * scaleMult if l[days] * scaleMult < lowestLow: lowestLow = l[days] * scaleMult hhllDiffScale = (highestHigh - lowestLow) / 1.65 hhllDiff = highestHigh - lowestLow botOfChart = lowestLow screen.setworldcoordinates(-10, highestHigh - hhllDiffScale, 673, highestHigh) print(highestHigh, " ", lowestLow) m = 0 trtl.setheading(0) trtl.penup() for i in range(startPt, startPt + numBarsPlot + 1): m = m + 1 trtl.goto(m * 10, h[i] * scaleMult) trtl.pendown() trtl.goto(m * 10, l[i] * scaleMult) trtl.penup() trtl.goto(m * 10, c[i] * scaleMult) trtl.pendown() trtl.goto(m * 10 + 5, c[i] * scaleMult) trtl.penup() trtl.goto(m * 10, o[i] * scaleMult) trtl.pendown() trtl.goto(m * 10 - 5, o[i] * scaleMult) trtl.penup() trtl.goto(10, highestHigh) print("Indicator List: ", indicatorList) if len(indicatorList) != 0: movAvgParams = list([]) if "movAvg" in indicatorList: movAvgVal = 0 movAvgParamIndexVal = indicatorList.index("movAvg") movAvgParams.append(indicatorList[movAvgParamIndexVal + 1]) movAvgParams.append(indicatorList[movAvgParamIndexVal + 2]) movAvgParams.append(indicatorList[movAvgParamIndexVal + 3]) for j in range(0, 3): n = 0 trtl.penup() if j == 0: trtl.color("red") if j == 1: trtl.color("green") if j == 2: trtl.color("blue") for i in range(startPt, startPt + numBarsPlot): n = n + 1 movAvgVal = 0 for k in range(i - movAvgParams[j], i): movAvgVal = movAvgVal + c[k] * scaleMult if movAvgParams[j] != 0: movAvgVal = movAvgVal / movAvgParams[j] if i == startPt: trtl.goto(n * 10, movAvgVal) trtl.pendown() trtl.goto(n * 10, movAvgVal) trtl.penup() # print("PlotTrades : ",plotTrades) if trades.draw: debugTradeDate = tradeDate[0] debugDate = d[startPt] n = 0 while debugTradeDate <= debugDate: n += 1 debugTradeDate = tradeDate[n] m = 0 for i in range(startPt, startPt + numBarsPlot): m = m + 1 debugDate = d[i] if debugDate == debugTradeDate: trtl.penup() tradeValue = tradePrice[n] if tradeType[n] == "buy": trtl.color("Green") trtl.goto(m * 10 - 5, tradeValue - hhllDiff * .03) trtl.pensize(3) trtl.pendown() trtl.goto(m * 10, tradeValue) trtl.goto(m * 10 + 5, tradeValue - hhllDiff * .03) trtl.penup() if tradeType[n] == "sell": trtl.color("Red") trtl.goto(m * 10 - 5, tradeValue + hhllDiff * .03) trtl.pensize(3) trtl.pendown() trtl.goto(m * 10, tradeValue) trtl.goto(m * 10 + 5, tradeValue + hhllDiff * .03) trtl.penup() if tradeType[n] == "longLiq": trtl.color("Blue") trtl.penup() trtl.goto(m * 10 - 5, tradeValue) trtl.pensize(3) trtl.pendown() trtl.goto(m * 10 + 5, tradeValue) trtl.penup() trtl.pensize(1) print("Found a trade: ", tradeValue, " ", debugTradeDate, " m= ", m, " ", tradeValue - hhllDiff * .05) n += 1 if n < len(tradeDate): debugTradeDate = tradeDate[n] trtl.color("black") trtl.goto(-10, botOfChart) trtl.pendown() trtl.goto(673, botOfChart) trtl.penup() trtl.goto(-10, botOfChart) m = 0 for i in range(startPt, startPt + numBarsPlot): if i % 10 == 0: m = m + 1 trtl.pendown() trtl.write(str(d[i]), font=("Arial", 8, "bold")) # chosing the font trtl.penup() trtl.goto(m * 100, botOfChart) trtl.penup() trtl.goto(628, highestHigh) trtl.pendown() trtl.goto(628, botOfChart) trtl.penup() m = 0 vertIncrement = hhllDiff / 10 for i in range(0, 11): trtl.goto(630, highestHigh - m * vertIncrement) trtl.pendown() trtl.write(str(highestHigh - m * vertIncrement), font=("Arial", 8, "bold")) trtl.penup() m += 1 # turtle.done() screen.onscreenclick(get_mouse_click_coor)
class HanoiEngine: """Play the Hanoi-game on a given TurtleScreen.""" def __init__(self, canvas, nrOfDiscs, speed, moveCntDisplay=None): """Sets Canvas to play on as well as default values for number of discs and animation-speed. moveCntDisplay is a function with 1 parameter, which communicates the count of the actual move to the GUI containing the Hanoi-engine-canvas.""" self.ts = canvas self.ts.tracer(False) # setup scene self.designer = RawTurtle(canvas, shape="square") self.designer.penup() self.designer.shapesize(0.5, 21) self.designer.goto(0,-80); self.designer.stamp() self.designer.shapesize(7, 0.5) self.designer.fillcolor('darkgreen') for x in -140, 0, 140: self.designer.goto(x,-5); self.designer.stamp() self.nrOfDiscs = nrOfDiscs self.speed = speed self.moveDisplay = moveCntDisplay self.running = False self.moveCnt = 0 self.discs = [Disc(canvas) for i in range(10)] self.towerA = Tower(-140) self.towerB = Tower(0) self.towerC = Tower(140) self.ts.tracer(True) def setspeed(self): for disc in self.discs: disc.speed(self.speed) def hanoi(self, n, src, dest, temp): """The classical recursive Towers-Of-Hanoi algorithm, implemented as a recursive generator, yielding always None plus an 'important' side effect - the next Hanoi move.""" if n > 0: for x in self.hanoi(n-1, src, temp, dest): yield None yield self.move(src, dest) for x in self.hanoi(n-1, temp, dest, src): yield None def move(self, src_tower, dest_tower): """move uppermost disc of source tower to top of destination tower.""" dest_tower.push(src_tower.pop()) self.moveCnt += 1 self.moveDisplay(self.moveCnt) def reset(self): """Setup of (a new) game.""" self.ts.tracer(False) self.moveCnt = 0 self.moveDisplay(0) for t in self.towerA, self.towerB, self.towerC: while t != []: t.pop(200) for k in range(self.nrOfDiscs-1,-1,-1): self.discs[k].config(k, self.nrOfDiscs) self.towerA.push(self.discs[k]) self.ts.tracer(True) self.HG = self.hanoi(self.nrOfDiscs, self.towerA, self.towerC, self.towerB) def run(self): """run game ;-) return True if game is over, else False""" self.running = True try: while self.running: result = self.step() return result # True iff done except StopIteration: # game over return True def step(self): """perform one single step of the game, returns True if finished, else False""" try: next(self.HG) return 2**self.nrOfDiscs-1 == self.moveCnt except TclError: return False def stop(self): """ ;-) """ self.running = False
class Board: """ Area of the screen dedicated to the connect 4 game board. """ def __init__(self,screen,corners,width,height,x,y): self.corners = corners self.screen = screen self.pen = RawTurtle(screen) self.pen.speed(8) self.width = width self.height = height self.x = x self.y = y self.spaces = [] self.draw() self.draw_spaces() def draw(self): self.pen.up() self.pen.goto(self.corners[-1]) self.pen.color("#ddd") self.pen.down() self.pen.begin_fill() for i in self.corners: self.pen.goto(i) self.pen.ht() self.pen.end_fill() return def check_winner(self,space): r, c = space.idx if self.check_row(space,r,c) or \ self.check_column(space,r,c) or \ self.check_direction(space,r,c): return True return False def check_row(self,space,r,c): if space.state*4 in "".join([str(i.state) for i in self.spaces[r]]): return True def check_column(self,space,r,c): if space.state*4 in "".join([str(i[c].state) for i in self.spaces]): return True def check_direction(self,space,r,c): direct,score = [(-1,-1),(-1,1),(1,1),(1,-1)],[0,0] for i,(x,y) in enumerate(direct): idx = 0 if i % 2 == 0 else 1 score[idx] += self.check_angle(space,r,c,x,y,(x,y)) if max(score) >= 3: return True return False def check_angle(self,space,r,c,x,y,i): if r+x >= 0 and r+x < 6 and c+y >= 0 and c+y < 7: if self.spaces[r+x][c+y].state == space.state: return 1 + self.check_diag(space,r,c,x+i[0],y+i[1],i) return 0 return 0 def animate_drop(self,space): r,c = space.idx for i in range(r): self.spaces[i][c].draw() self.spaces[i][c].remove() return def space_empty(self,space): r,c = space.idx if r == len(self.spaces)-1 or self.spaces[r+1][c].state: return space for row in range(r+1,len(self.spaces)): if self.spaces[row][c].state: return self.spaces[row-1][c] return self.spaces[len(self.spaces)-1][c] def find_space(self,x,y): for row in self.spaces: cent,rad = row[0].center, row[0].radius if y > cent[1] - rad and y < cent[1] + rad: return self.search_column(row,x) return False def search_column(self,row,x): for space in row: x2 = space.center[0] if x > x2-space.radius and x < x2 + space.radius: return space return False def draw_spaces(self): row,size = [],self.width/7 radius = (size*.9)/2 x,y = self.corners[0] for j in range(6): for i in range(7): space_x = x + (size*i) space_y = y - (size*j) center = space_x+(size/2),space_y-(size/2) color = "#643" idx = (j,i) space = Space(self,center,radius,color,idx) row.append(space) self.spaces.append(row) row = [] return
class Window(Screen): """Class to generate game window, tkcanvas subclass. """ def __init__(self, color="#643", mode=1): """ Constructor for TK window. color {str} -- hex color string (default: {None}) """ super().__init__() self.player_mode = mode self.new_game(color) def new_game(self, color): """ Starts a New Game, Draws game board and creates Players. Args: color{str} - Hex-Color passed along from constructor. """ self.setup(.8, .9, 1000, 0) self.width = (self.window_width() * .9) self.height = (self.window_height() * .9) self.x = self.width / 2 self.y = self.height / 2 # ^ dimensions of game board self.font = ('Arial', 20, 'bold'), "#f50" # ^ Game Status Messages written above Game Board self.winner = None # ^ slot is adjusted once a winner is established. self.bgcolor(color) self.start_message() self.delay(8) self.tracer(2) # functions for controlling animation speed self.game_board() self.create_players() self.player.turn() def start_message(self): """ Creates Pen for drawing game update messages above the board. """ self.pen = RawTurtle(self) self.pen.ht() self.pen.up() self.pen.color(self.font[1]) self.pen.goto(0, self.y) self.pen.write("New Game", align="center", font=self.font[0]) return def create_players(self): """ Creates 2 player objects. Either AI controlled of User controlled Player_mode 1 = User vs User Player_mode 2 = User vs AI Player_mode 3 = AI vs AI """ if self.player_mode in [1, 2]: player_1 = Player(1, "#f00") if self.player_mode == 1: player_2 = Player(2, "#000") else: player_2 = Ai(2, "#000", self.board, self) else: player_1 = Ai(1, "#f00", self.board, self) player_2 = Ai(2, "#000", self.board, self) self.player = player_1 self.players = (player_1, player_2) def activate_space(self, x, y): """ Onclick callback: assigns the bottom most space to active player. Arguements: (x{int},y{int}) = window coordinates for click position. """ space = self.board.find_space(x, y) #find the space associated with the position given by onclick method if space and not space.state: space = self.board.space_empty(space) self.board.animate_drop(space) """ if space is valid... check if it is the bottommost empty space in column or return the bottom space and render dropping animation """ space.draw(color=self.player.color) space.state = self.player.name """ fill bottommost empty space with players color set space state to filled by active player """ if self.board.check_winner(space): # check if game over self.draw_message(f"GAME OVER {self.player} WINS") return # switch active players self.player = self.players[ 0] if self.players[0] != self.player else self.players[1] self.draw_message(str(self.player) + " Turn") self.player.turn() else: # if click is not in valid empty space player turn continues self.draw_message("Try Again") self.player.turn() def draw_message(self, msg): """ Write game state update messages to top of the window """ self.pen.clear() self.pen.write(msg, align="center", font=self.font[0]) return def play(self): self.onclick(self.activate_space) def game_board(self): """ Calculates and generates the board object. """ board_height = (self.height // 42) * 42 board_width = (board_height * 7) / 6 bx = board_width / 2 by = board_height / 2 board_corners = [(-bx, by), (-bx, -by), (bx, -by), (bx, by)] self.board = Board(self, board_corners, board_width, board_height, bx, by) return