# Kim Todd, CSE 142 Autumn 2008 # This program performs a graphical "random walk" on a DrawingPanel. from random import * from drawingpanel import * from math import * RADIUS = 75 # Moves by one step in a random direction; returns new position. def step(x, y): dir = randint(0, 3) if dir == 0: x += 1 elif dir == 1: x -= 1 elif dir == 2: y += 1 else: y -= 1 return (x, y) # Returns the distance between the given two points. def distance((x1, y1), (x2, y2)): return sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) # main panel = DrawingPanel(RADIUS * 2, RADIUS * 2) panel.canvas.create_oval(0, 0, RADIUS * 2, RADIUS * 2) center = (RADIUS, RADIUS) x, y = (RADIUS, RADIUS) # loop until walker has exited the circle while distance((x, y), center) < RADIUS: x, y = step(x, y) panel.canvas.create_rectangle(x, y, x + 1, y + 1, fill = "green") panel.sleep(10)