random_walk.py

Created by vnap0v

Created on June 29, 2025

709 Bytes

Two-dimensional Lattice random walk

This script shows random walks on a 2D lattice. When the walk goes beyond limits the process starts over.

The script uses the turtle library for drawing and the random library to choose a random heading at each step


# Two-dimensional Lattice random walk
import turtle as tl
from random import *

#parameters
step=15 # length of one step
maxx=150;maxy=100 #limits of walk
c=("red","blue","green","purple")

# settings for turle
def init_ẗurtle(): 
  tl.reset()
  tl.speed(0)
  tl.pensize(4)

init_ẗurtle() # first time intialise turtle

for k in range(8000):
  h=randint(0,3) #random heading as number from 0..3
  tl.color(c[h]) # color determined by heading
  tl.setheading(h*90) # set turtle heading in degrees
  tl.forward(step) # one step in chozen heading
  x,y=tl.position() # get current position
  if abs(x)>maxx or abs(y)>maxy: #reset if too far
    init_ẗurtle() # initializse turle again
    

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.