Skip to content

Instantly share code, notes, and snippets.

@tganzarolli
Created March 4, 2019 23:03
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 tganzarolli/0ba6b86e5485655aa56dce412d18cbf8 to your computer and use it in GitHub Desktop.
Save tganzarolli/0ba6b86e5485655aa56dce412d18cbf8 to your computer and use it in GitHub Desktop.
Langton's ant
#!/usr/bin/python
class Langton(object):
def __init__(self):
self.ant = ((0,0), 'E')
self.black_squares = set()
self.next = {'E':'S', 'S': 'W', 'W':'N', 'N':'E'}
self.previous = {'E':'N', 'N': 'W', 'W':'S', 'S':'E'}
self.max_y,self.max_x,self.min_y,self.min_x = 0,0,0,0
self.transf = {'E':(1,0), 'S': (0,1), 'W':(-1,0) , 'N':(0,-1)}
def move(self):
if self.ant[0] in self.black_squares:
direct = self.previous[self.ant[1]]
self.black_squares.remove(self.ant[0])
else:
direct = self.next[self.ant[1]]
self.black_squares.add(self.ant[0])
new_pos = (self.ant[0][0] + self.transf[direct][0], self.ant[0][1] + self.transf[direct][1])
self.max_x = max(self.max_x, new_pos[0])
self.max_y = max(self.max_y, new_pos[1])
self.min_x = min(self.min_x, new_pos[0])
self.min_y = min(self.min_y, new_pos[1])
self.ant = (new_pos, direct)
def play(self,k):
while k > 0:
self.move()
k -= 1
for i in range(self.min_x,self.max_x+1):
row = []
for j in range(self.min_y,self.max_y+1):
if (i,j) == self.ant[0]:
row.append(self.ant[1])
elif (i,j) in self.black_squares:
row.append('#')
else:
row.append(' ')
print ','.join(row)
import sys
if __name__== "__main__":
simulation = 100
if len(sys.argv) > 1:
simulation = int(sys.argv[1])
l = Langton()
l.play(simulation)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment