Trying to make a line follow a random path

242 Views Asked by At

I am trying to make a line follow a random path in Python. I have to use SimpleGUI to do it. So far I have done enough to make the line follow a random path but after the for loop, the code restarts. I am not that familiar with SimpleGUI, so I am sure there is a good reason for the code restarting but I have no idea how to fix it. I have provided the code below, thanks in advance!

import simplegui
import random

def draw_handler(canvas):
    x=300 #Should be the center; this is the center of 600x600
    y=300
    for i in range(1000):
        direction=random.randint(1,4) #1=up,2=left,3=down,4=right
        if (direction==1):
            canvas.draw_line([x,y],[x,y-3],3,"Black")
            y=y-3
        if (direction==2):
            canvas.draw_line([x,y],[x-3,y],3,"Black")
            x=x-3
        if (direction==3):
            canvas.draw_line([x,y],[x,y+3],3,"Black")
            y=y+3
        if (direction==4):
            canvas.draw_line([x,y],[x+3,y],3,"Black")
            x=x+3


frame = simplegui.create_frame('Testing', 600, 600)
frame.set_canvas_background("White")
frame.set_draw_handler(draw_handler)
frame.start() 
1

There are 1 best solutions below

0
On

The drawing handler function is called 60 times by second, to redraw completely the canvas. I precise that on the documentation of SimpleGUICS2Pygame that reimplements SimpleGUI in the standard Python implementation.

You need to accumulate the path, adding one point at each call of the drawing handler function, and then draw all the path. See this example:

#!/usr/bin/env python3
"""
Random path
"""
import random

try:
    import simplegui
except ImportError:
    # SimpleGUICS2Pygame: https://simpleguics2pygame.readthedocs.io/
    import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


def main():
    width = 600
    height = 600

    points = [(width // 2, height // 2)]

    def draw_handler(canvas):
        last_x, last_y = points[-1]
        new_x = last_x
        new_y = last_y
        direction = random.choice((-1, 1))
        if random.randrange(2) == 0:
            new_y += direction * 3
        else:
            new_x += direction * 3

        points.append((new_x, new_y))

        a = points[0]
        for b in points[1:]:
            canvas.draw_line(a, b, 1, 'Black')
            a = b

    frame = simplegui.create_frame('Random path', width, height)
    frame.set_canvas_background('White')
    frame.set_draw_handler(draw_handler)
    frame.start()


if __name__ == '__main__':
    main()