Skip to content

Instantly share code, notes, and snippets.

@cocomoff
Created May 28, 2015 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cocomoff/99eba40ca6e4eb3f6878 to your computer and use it in GitHub Desktop.
Save cocomoff/99eba40ca6e4eb3f6878 to your computer and use it in GitHub Desktop.
Build png files for a GIF anime of Langton's ant
# -*- coding: utf-8 -*-
# date: 2015/05/28
# author: @taki__taki__
# packages
import numpy as np
import matplotlib.pyplot as plt
# direction (N=0, E=1, S=2, W=3)
class Direction(object):
def __init__(self, d):
self.d = d
def turn_right(self): self.d = (self.d + 1) % 4
def turn_left(self): self.d = (self.d - 1) % 4
def __str__(self):
if self.d == 0: return "N"
elif self.d == 1: return "E"
elif self.d == 2: return "S"
elif self.d == 3: return "W"
else: return "X"
def get_next(x, y, direction):
if direction.d == 0: return (x, y+1)
elif direction.d == 1: return (x+1, y)
elif direction.d == 2: return (x, y-1)
elif direction.d == 3: return (x-1, y)
else: return (x, y)
if __name__ == '__main__':
# parameters
X, Y, x0, y0 = 100, 100, 50, 50
max_iter = 50000
# initialize the board
board = np.zeros((X, Y), dtype=np.bool)
direction = Direction(0)
# iteration (png)
x, y = x0, y0
for i in range(max_iter):
print(i, x, y)
if x >= X or y >= Y or x < 0 or y < 0: break # out of the board
# Black: turn right / White: turn left
if board[x][y]: direction.turn_right()
else: direction.turn_left()
board[x][y] = not board[x][y] # flip
x, y = get_next(x, y, direction) # move 1 step
plt.figure(figsize=(3,3))
plt.imshow(board, interpolation='nearest', cmap='Greys')
plt.savefig("pngtmp/png_%05d" % i)
plt.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment