Created
May 29, 2012 03:23
-
-
Save ajford/2822345 to your computer and use it in GitHub Desktop.
Simple implementation of Langston's Ants
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
class Board(object): | |
def __init__(self,x,y, ant_count=1, blank=True, random_factor=0): | |
self.width = x | |
self.height = y | |
self.board = [ [ False for i in range(x)] for j in range(y) ] | |
self.ants = [ Ant(self) for i in range(ant_count) ] | |
if not blank: | |
self._randomize(random_factor) | |
def get(self, coords): | |
try: | |
return self.board[coords[1]][coords[0]] | |
except IndexError: | |
print "ERROR: "+str(coords) | |
def toggle(self, coords): | |
self.board[coords[1]][coords[0]] = not self.board[coords[1]][coords[0]] | |
def iterate(self): | |
for i in range(len(self.ants)): | |
self.ants[i].walk() | |
def __repr__(self): | |
ret = '+' + '-'*self.width + '+\n' | |
for row in self.board: | |
ret+='|' | |
for cell in row: | |
if cell: | |
ret+='#' | |
else: | |
ret+=' ' | |
ret+='|\n' | |
ret += '+'+ '-'*self.width + '+\n' | |
return ret | |
class Ant(object): | |
_orientation_dict = {'N':(0,1), 'E':(1,0), 'S':(0,-1), 'W':(-1,0)} | |
_orientations = ['N', 'E', 'S', 'W'] | |
def __init__(self, board): | |
self.board = board | |
self.coords = self.randomize_position() | |
self.orientation = self.randomize_orientation() | |
def randomize_position(self): | |
return [random.randrange(self.board.width), | |
random.randrange(self.board.height)] | |
def randomize_orientation(self): | |
return random.randrange(len(self._orientations)) | |
def rotate(self, state): | |
if state: | |
self.orientation = (self.orientation-1)%len(self._orientations) | |
else: | |
self.orientation = (self.orientation+1)%len(self._orientations) | |
def walk(self): | |
self.rotate(self.board.get(self.coords)) | |
self.board.toggle(self.coords) | |
self.advance() | |
def advance(self): | |
movement = self._orientation_dict[self._orientations[self.orientation]] | |
self.coords[0]= (self.coords[0]+movement[0])%self.board.width | |
self.coords[1]= (self.coords[1]+movement[1])%self.board.height | |
def RUN(loops, ants=1, x=50, y=15, sleep=.125): | |
import time | |
brd = Board(x, y, ants) | |
for i in range(loops): | |
brd.iterate() | |
print brd | |
time.sleep(sleep) | |
if __name__ == '__main__': | |
RUN(1000, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment