As practice, and as a precursor to a more complex, larger project I have in mind, I have created a random walk script using the Turtle module. I realize that there are simpler ways to do the random walk without having to find the neighboring coordinates, but as far as I can tell this is necessary for the larger implementation.
The problem I am having is that python is reaching its maximum recursion depth when it finds that it has visited every adjacent cell in the getnext()
function. I'm not sure how I would escape that loop and continue on as normal should that occur.
import turtle
import random
class cell(object):
def __init__(self, pos, visited = False):
开发者_开发问答 self.xCoord = pos[0]
self.yCoord = pos[1]
self.visited = visited
self.neigh = []
self.neighbors = self.getneighbors()
def getneighbors(self):
for j in (-1, 0, 1):
for i in (-1, 0, 1):
self.neigh.append((self.xCoord+i, self.yCoord+j))
def getnext():
nextindex = random.randint(0, len(c.neigh)-1)
nextcoordt = c.neigh[nextindex]
nextcoord = list(c.neigh[nextindex])
if nextcoordt in coords:
getnext()
else:
turtle.goto(nextcoord[0], nextcoord[1])
coords = {}
turtle.setup(width =200, height = 200, startx = 0, starty = 0)
turtle.trace = False
for i in range(1000):
c = cell(list(turtle.pos()))
coords[turtle.pos()] = (c)
getnext()
Furthermore this is actually my first true application of OOP and I was wondering if this was a good way to use it.
Thanks a lot!
If your random walk finds that it has visited every adjacent cell, it would loop forever. Since you're using recursion it quickly exceeds the maximum recursion limit.
I'm sure this could be written in an OOP way, but the problems are more in your use of recursion than whether the cell
class is useful. For example, I've simplified your code to run in a linear fashion. The changes are:
- Eliminate the (0, 0) direction since it makes no forward progress. (optional depending on your goal, i.e. if you consider "staying put" a valid move or not).
- Uses
random.choice()
to pick the direction of the next move. - Removes recursion in favor of calculating the next coordinate by adding the direction vector to the current position. A simple loop suffices.
- Doesn't check the next position against a recent history of positions, since a move back to a previous space is perfectly valid for randomness.
Code:
import itertools
import random
import turtle
# change step size if you like
STEP = 1
PTS = [-STEP, 0, STEP]
DIRS = [(x, y) for x in PTS for y in PTS if x or y]
turtle.setup(width=400, height=400, startx=0, starty=0)
turtle.trace = False
pos = turtle.pos()
for i in range(1000):
px, py = turtle.pos()
# direction of next move
xd, yd = random.choice(DIRS)
# set pos to current pos + direction vector
turtle.goto(px + xd, py + yd)
精彩评论