I have made Langtons Ant in Python and I want to create a perimeter around the window so the "ant" cannot move or print outside of. How would I do this (I have already drawn a box using stamps).
I have made Langtons Ant in Python and I want to create a perimeter around the window so the "ant" cannot move or print outside of. How would I do this (I have already drawn a box using stamps).
The Langton's Ant sequence never ends, hence it is impossible to contain the entire image in a turtle graphics window.
If you have a fixed number of steps you intend to allow the ant to make, then you can use this class that simulates the Langton's Ant sequence, and returns the dimensions of the grid you will need:
import turtle
SCREEN_WIDTH = 600 # You can customize this
SCREEN_HEIGHT = 600 # You can customize this
steps = 1000 # You can customize this
class LangtonsAnt:
def __init__(self, steps):
self.grid = [["AW"]]
self.facing = 0
self.steps = steps
def current_index(self):
for i, row in enumerate(self.grid):
for j, cell in enumerate(row):
if "A" in cell:
return i, j
def switch_color(self, i, j):
if "W" in self.grid[i][j]:
self.grid[i][j] = "B"
else:
self.grid[i][j] = "W"
def turn_cw(self):
self.facing += 1
if self.facing > 3:
self.facing = 0
def turn_ccw(self):
self.facing -= 1
if self.facing < 0:
self.facing = 3
def forward(self):
i, j = self.current_index()
self.switch_color(i, j)
if self.facing == 0:
if len(self.grid[i]) > j + 1:
self.grid[i][j + 1] = "A" + self.grid[i][j + 1]
else:
self.grid[i].append("AW")
for idx, row in enumerate(self.grid):
if idx != i:
row.append("W")
elif self.facing == 1:
if len(self.grid) > i + 1:
self.grid[i + 1][j] = "A" + self.grid[i + 1][j]
else:
self.grid.append(["AW" if idx == j else "W" for idx in range(len(self.grid[i]))])
elif self.facing == 2:
if j:
self.grid[i][j - 1] = "A" + self.grid[i][j - 1]
else:
self.grid[i] = ["AW"] + self.grid[i]
for idx, row in enumerate(self.grid):
if idx != i:
row.insert(0, "W")
elif self.facing == 3:
if i:
self.grid[i - 1][j] = "A" + self.grid[i - 1][j]
else:
self.grid.append(["AW" if idx == j else "W" for idx in range(len(self.grid[i]))])
def current_color(self):
for row in self.grid:
for cell in row:
if "A" in cell:
return cell[1]
def dimensions(self):
for _ in range(self.steps):
self.forward()
if self.current_color() == "W":
self.turn_cw()
else:
self.turn_ccw()
return len(self.grid[0]), len(self.grid)
wn = turtle.setup(SCREEN_WIDTH, SCREEN_HEIGHT)
test = LangtonsAnt(steps)
turtle.speed("fastest")
turtle.shape("square")
s = min(SCREEN_WIDTH, SCREEN_HEIGHT) / max(test.dimensions())
turtle.shapesize(s / 20, s / 20)
turtle.penup()
for i, v in enumerate(test.grid):
for j, w in enumerate(v):
turtle.goto((-SCREEN_WIDTH + s)/ 2 + j * s, (SCREEN_HEIGHT - s) / 2 - i * s)
if "B" in w:
turtle.stamp()
Output: