Skip to content

Instantly share code, notes, and snippets.

@lpraat
Last active September 27, 2017 18:37
Show Gist options
  • Select an option

  • Save lpraat/8705e5a4f0fbb9499c00218cfa126654 to your computer and use it in GitHub Desktop.

Select an option

Save lpraat/8705e5a4f0fbb9499c00218cfa126654 to your computer and use it in GitHub Desktop.
Langton's Ant
import turtle
import sys
def update_maps(graph, turtle, color):
graph[turtle_pos(turtle)] = color
def turtle_pos(turtle):
return (round(turtle.xcor()), round(turtle.ycor()))
def langton_move(turtle, pos, maps, step):
if pos not in maps or maps[pos] == "white":
turtle.fillcolor("black")
turtle.stamp()
update_maps(maps, turtle, "black")
turtle.right(90)
turtle.forward(step)
pos = turtle_pos(turtle)
elif maps[pos] == "black":
turtle.fillcolor("white")
update_maps(maps, turtle, "white")
turtle.stamp()
turtle.left(90)
turtle.forward(step)
pos = turtle_pos(turtle)
return pos
def move():
# Screen
BACKGROUND_COLOR = "white"
WIDTH = 2000
HEIGHT = 2000
# Ant
SHAPE = "square"
SHAPE_SIZE = 0.5
SPEED = 0
STEP = 11
# Data structure ex. {(x, y): "black", ..., (x_n, y_n): "white"}
# to store all the ant's positions
maps = {}
# Initialize Window
window = turtle.Screen()
window.bgcolor(BACKGROUND_COLOR)
window.screensize(WIDTH, HEIGHT)
# Initialize Ant
ant = turtle.Turtle()
ant.shape(SHAPE)
ant.shapesize(SHAPE_SIZE)
ant.penup()
ant.speed(SPEED)
ant.right(180)
pos = turtle_pos(ant)
moves = 0
try:
while True:
pos = langton_move(ant, pos, maps, STEP)
moves += 1
print "Movements:", moves
except KeyboardInterrupt:
sys.exit()
if __name__ == '__main__':
move()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment