Skip to content

Instantly share code, notes, and snippets.

@tyrcho
Last active September 4, 2017 16:41
Show Gist options
  • Save tyrcho/d02aca0ec27589852728 to your computer and use it in GitHub Desktop.
Save tyrcho/d02aca0ec27589852728 to your computer and use it in GitHub Desktop.
Langton's ant
val antSize=3
var direction: Direction = North
val delayMillis=1 // increase this to slow down
val loopSize=1000 // increase this to accelerate
val infinite=false
Fiddle.draw.fillStyle = "blue"
Fiddle.draw.font= "20px Georgia"
val (h, w) = (Fiddle.canvas.height, Fiddle.canvas.width)
val (maxX, maxY) = (h / antSize, w / antSize)
var (x, y) = (maxX/2, maxY / 2)
var i = 0
val blackSpots = collection.mutable.Map.empty[(Int, Int), Boolean].withDefaultValue(false)
Fiddle.schedule(delayMillis) {
for (i<- 1 to loopSize) {
drawIter()
drawAnt()
nextIter()
}
}
def nextIter():Unit={
i += 1
direction =
if (blackSpots((x, y))) direction.left
else direction.right
blackSpots.update((x, y), !blackSpots((x, y)))
val (nx, ny) = checkBounds(direction.next(x, y))
x = nx
y = ny
}
def checkBounds(xy:(Int,Int)) : (Int,Int) =
if(infinite) xy
else {
val (x,y)=xy
(
if(x>maxX) 0 else if (x<0) maxX else x,
if(y>maxY) 0 else if (y<0) maxY else y
)
}
def drawIter():Unit={
Fiddle.draw.clearRect(0, 0, 100, 30)
Fiddle.draw.fillText(i.toString, 20, 20)
}
def drawAnt() :Unit= {
val antX=x*antSize
val antY=y*antSize
if (blackSpots((x, y)))
Fiddle.draw.clearRect(antX,antY, antSize,antSize)
else
Fiddle.draw.fillRect(antX,antY, antSize,antSize)
}
}
trait Direction {
def left: Direction
def right: Direction
def next(x: Int, y: Int): (Int, Int)
}
object North extends Direction {
val left = West
val right = East
def next(x: Int, y: Int) = (x, y - 1)
}
object South extends Direction {
val left = East
val right = West
def next(x: Int, y: Int) = (x, y + 1)
}
object West extends Direction {
val left = South
val right = North
def next(x: Int, y: Int) = (x - 1, y)
}
object East extends Direction {
val left = North
val right = South
def next(x: Int, y: Int) = (x + 1, y)
} // $FiddleEnd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment