Beispiel #1
0
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
Beispiel #2
0
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()
Beispiel #4
0
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()
Beispiel #5
0
    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()
Beispiel #6
0
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
Beispiel #7
0
def Rank():
    root = TK.Tk()
    cv1 = TK.Canvas(root, width=400, height=200)
    cv1.pack()
    s1 = TurtleScreen(cv1)
    s1.bgcolor("#42f4ad")
    t = RawTurtle(s1)
    t.hideturtle()
    t.penup()
    t.goto(-50,70)
    t.write("내가 예측한 1등: "+ guess)
    t.goto(-50,50)
    if PlayerNumber>=1:
        t.write("1등 : "+PlayerRank[0])
        t.goto(-50,40)
    if PlayerNumber>=2:
        t.write("2등 : "+PlayerRank[1])
        t.goto(-50,30)
    if PlayerNumber>=3:
        t.write("3등 : "+PlayerRank[2])
        t.goto(-50,20)
    if PlayerNumber>=4:
        t.write("4등 : "+PlayerRank[3])
        t.goto(-50,10)
    if PlayerNumber>=5:
        t.write("5등 : "+PlayerRank[4])
    t.goto(-100,-20)
    if(guess==PlayerRank[0]):
        t.write("축하드립니다. 1등을 맞추셨습니다.")
    else:
        t.write("1등을 맞추지 못했습니다.")
Beispiel #8
0
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)
Beispiel #9
0
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)
Beispiel #10
0
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)
Beispiel #11
0
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(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()
Beispiel #13
0
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()
Beispiel #14
0
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 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()
Beispiel #16
0
class Robot:

    def __init__(self, scene, robot_id):
        self.robot_id = robot_id
        self.done = False
        self.signal = None

        self.turtle = RawTurtle(scene.canvas)
        self.scene = scene

        self.scr = self.turtle.getscreen()
        self.scr.setworldcoordinates(0, scene.height, scene.width, 0)

        self.turtle.penup()
        self.reset()

    def reset(self):
        positions = [((15,15), 45), 
                    ((self.scene.width-15, 15), 135),
                    ((15, self.scene.height-15), 315),
                    ((self.scene.height-15, self.scene.width-15), 135)]

        self.turtle.speed(0)
        self.turtle.setpos(positions[self.robot_id][0])
        print positions[self.robot_id]
        self.turtle.left(positions[self.robot_id][1])
        self.turtle.forward(20)
        self.turtle.speed("normal")

    def process(self):
        ##sets variables for checking collision
        turtle_x = self.turtle.xcor()
        turtle_y = self.turtle.ycor()
        t_heading = self.turtle.heading()
        ##variables used to check right
        xr = turtle_x + 15*math.cos(math.radians(self.turtle.heading()+30))
        yr = turtle_y + 15*math.sin(math.radians(self.turtle.heading()+30))
        ##variables used to check left
        xl = turtle_x + 15*math.cos(math.radians(self.turtle.heading()-30))
        yl = turtle_y + 15*math.sin(math.radians(self.turtle.heading()-30))
        ##turns the robot at window boundries
        st_orient = [0, 90, 180, 270]
        bounce_d = 20
        if turtle_x - bounce_d < 0:
            self.turtle.setheading(180-t_heading)
        if turtle_x + bounce_d > self.scene.width:
            self.turtle.setheading(180-t_heading)
        if turtle_y - bounce_d < 0:
            self.turtle.setheading(360-t_heading)
        if turtle_y + bounce_d > self.scene.height:
            self.turtle.setheading(360-t_heading)
        ##check collisions
        left = self.scene.canvas.find_overlapping(xl-1,yl-1,xl+1,yl+1)
        right = self.scene.canvas.find_overlapping(xr-1,yr-1,xr+1,yr+1)
        if self.goal_id in left + right:
            self.done = True
        elif left:
            ##turn away
            self.turtle.left(10)
        elif right:
            ##turn away
            self.turtle.right(10)
        else:
            ##else move forward
            self.turtle.forward(5)
        ##if goal not reached:
        if self.signal:
            if self.signal == "STOP":
                self.signal = None
                return
        elif not self.done:
            self.scene.master.after(20, self.process)
Beispiel #17
0
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 Robot:
    def __init__(self, scene, robot_id):
    #sets variables                     
        self.robot_id = robot_id
        self.turtle = RawTurtle(scene.canvas)
        self.scene = scene
        self.scr = self.turtle.getscreen()
        self.scr.setworldcoordinates(0, scene.height, scene.width, 0)
        self.turtle.penup()
        if robot_id == 1:
            self.turtle.color("blue")
        else:
            self.turtle.color("red")
    #create turtles sprite
##        self.turtle.register_shape("ship",((-7,-2),(-6,-1),(-3,0),(-3,1),(-2,5),
##                                           (0,7),(2,5),(3,1),(3,0),(6,-1),(7,-2),
##                                           (3,-1),(3,-2),(2,-7),(-2,-7),(-3,-2),
##                                           (-3,-1),(-2,-1),(-2,-2),(-1,-6),(1,-6),
##                                           (2,-2),(2,-1),(-2,-1),(-2,0),(2,0),
##                                           (2,1),(1,4),(0,5),(-1,4),(-2,1),
##                                           (-2,-1),(-3,-1))
##                         )
##        self.turtle.shape("ship")
##        self.turtle.shapesize(2,2)
    #place robot using reset
        self.reset()

    def reset(self):
    #set start positions for robots
        positions = [((15,15), 45), 
                    ((self.scene.width-15, 15), 135),
                    ((15, self.scene.height-15), 315),
                    ((self.scene.height-15, self.scene.width-15), 135)]
    #move robot to starting possition
        self.turtle.speed(0)
        self.turtle.setpos(positions[self.robot_id][0])
        #print positions[self.robot_id]
        self.turtle.left(positions[self.robot_id][1])
        self.turtle.forward(20)
        self.turtle.speed(0)
        self.turtle.screen.bgcolor("sky blue")

    def orientate(self, landmarks, canvas, goal):
##sd = shortest distance
##x1,x2,y1,y2 = circles corners
##lx,ly = length x/y
##h = hypothinus
##ln = landmark number
        sd = 40000000
        ln = 0
        
        for ID in landmarks:
            if canvas.itemcget(ID, "fill") == "dark green":
                ln+=1
                x1,y1,x2,y2 = canvas.coords(ID)
                lx = ((x1+x2)/2) - self.turtle.xcor()
                ly = ((y1+y2)/2) - self.turtle.ycor()
                h = math.sqrt(lx*lx + ly*ly)
                if h < sd:
                    sd = h
                    stored_ID = ID
                    stored_x = lx
                    stored_y = ly
        
        if ln == 0:
            stored_ID = goal
            x1,y1,x2,y2 = canvas.coords(goal)
            lx = ((x1+x2)/2) - self.turtle.xcor()
            ly = ((y1+y2)/2) - self.turtle.ycor()
            sd = math.sqrt(lx*lx + ly*ly)
            stored_x = ((x1+x2)/2) - self.turtle.xcor()
            stored_y = ((y1+y2)/2) - self.turtle.ycor()
        
        if sd < 37:
            return stored_ID
        
        if stored_x < 0:
            if stored_y < 0:
                new_heading = 180 + math.degrees(math.atan((-stored_y)/(-stored_x)))
            else:
                new_heading = 180 - math.degrees(math.atan(stored_y/(-stored_x)))
        elif stored_y < 0:
            new_heading = 360 - math.degrees(math.atan((-stored_y)/stored_x))
        else:
            new_heading = math.degrees(math.atan(stored_y/stored_x))

        self.turtle.seth(new_heading)
        return False

    def collisions_move(self, speed, depth):
    ##breaks the recursion if the robots get to close
        if depth > 10:
            return
    ##sets variables for checking collision
        turtle_x = self.turtle.xcor()
        turtle_y = self.turtle.ycor()
        t_heading = self.turtle.heading()
    ##variables used to check right
        xr = turtle_x + 15*math.cos(math.radians(self.turtle.heading()+30))
        yr = turtle_y + 15*math.sin(math.radians(self.turtle.heading()+30))
    ##variables used to check left
        xl = turtle_x + 15*math.cos(math.radians(self.turtle.heading()-30))
        yl = turtle_y + 15*math.sin(math.radians(self.turtle.heading()-30))
    ##check for the collision
        left = self.scene.canvas.find_overlapping(xl-1,yl-1,xl+1,yl+1)
        right = self.scene.canvas.find_overlapping(xr-1,yr-1,xr+1,yr+1)
        if left:
            ##turn away
            self.turtle.left(20)
            self.collisions_move(speed, depth+1)
            #self.turtle.forward(speed/5)
        elif right:
            ##turn away
            self.turtle.right(20)
            self.collisions_move(speed, depth+1)
            #self.turtle.forward(speed/5)
        else:
            ##else move forward
            self.turtle.forward(speed)
        return
Beispiel #19
0
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
Beispiel #20
0
master.overrideredirect(True)
master.after(2000, lambda: master.destroy())
WIDTH, HEIGHT = 450, 450
canvas = Canvas(master, width=WIDTH, height=HEIGHT, bg="green")
canvas.pack(ipadx=30)
root = TurtleScreen(canvas)
turtle = RawTurtle(root, visible=False)
root.bgcolor("white")

turtle.color('#F09F13')
turtle.pensize(4)
turtle.speed(15)
turtle.hideturtle()

turtle.penup()
turtle.setposition(70, 90)
turtle.pendown()
turtle.fillcolor("#F09F13")
turtle.begin_fill()
turtle.circle(40)
turtle.end_fill()

turtle.hideturtle()

turtle.color('#fe7d96')
turtle.pensize(4)
turtle.speed(15)
turtle.hideturtle()
turtle.penup()
turtle.setposition(15, -20)
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
Beispiel #22
0
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
Beispiel #23
0
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 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
Beispiel #25
0
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."""
        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
Beispiel #27
0
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
Beispiel #28
0
 def basiliskFeeded(self, window, shape):
     oneBodyBlock = RawTurtle(window)
     oneBodyBlock.speed(0)
     oneBodyBlock.shape(shape)
     oneBodyBlock.penup()
     self.body.append(oneBodyBlock)
Beispiel #29
0
for side in range(185):
    pen2.forward(1)
    pen1.forward(1)
    pen2.left(1)
    pen1.right(1)

# Filling the figure
pen2.end_fill()
pen1.end_fill()

# Deleting the arrows of the pens when the figure is finished
pen2.hideturtle()
pen1.hideturtle()

# Third and forth pen that write the sentence after the figure is finished
pen3 = RawTurtle(turtle_screen)
pen3.speed(0)
pen3.color("deep pink")
pen3.width(3)
pen3.penup()
pen3.goto(0, 150)
pen3.pendown()
pen3.write('I Love You!', font=('Courier', 40, 'bold'), align='center')
pen3.penup()
pen3.goto(0, -150)
pen3.pendown()
pen3.write('Facciapi!', font=('Courier', 40, 'bold'), align='center')
pen3.hideturtle()

# This prevent the window to be closed after it finishs the drawing
root.mainloop()
Beispiel #30
0
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()