Langton's ant: Difference between revisions

Content added Content deleted
(add swift)
Line 4,497: Line 4,497:
let HEIGHT = 100
let HEIGHT = 100


class Point {
struct Point {
var x:Int
var x:Int
var y:Int
var y:Int
init(_ x:Int, _ y:Int) {
self.x = x
self.y = y
}
}
}


Line 4,516: Line 4,511:
let xInc = [0, 1,-1, 0]
let xInc = [0, 1,-1, 0]
let yInc = [-1, 0, 0, 1]
let yInc = [-1, 0, 0, 1]
var isBlack:[[Bool]]!
var isBlack:[[Bool]]
var origin:Point!
var origin:Point
var antPosition = Point(0, 0)
var antPosition = Point(x:0, y:0)
var outOfBounds = false
var outOfBounds = false
var antDirection = Direction.East
var antDirection = Direction.East
init(width:Int, height:Int) {
init(width:Int, height:Int) {
self.origin = Point(width / 2, height / 2)
self.origin = Point(x:width / 2, y:height / 2)
self.isBlack = Array(count: width, repeatedValue: Array(count: height, repeatedValue: false))
self.isBlack = Array(count: width, repeatedValue: Array(count: height, repeatedValue: false))
}
}
Line 4,533: Line 4,528:
func step() -> Point {
func step() -> Point {
if (self.outOfBounds) {
if self.outOfBounds {
println("Ant tried to move while out of bounds.")
println("Ant tried to move while out of bounds.")
exit(0)
exit(0)
}
}
var ptCur = Point(self.antPosition.x + self.origin.x, self.antPosition.y + self.origin.y)
var ptCur = Point(x:self.antPosition.x + self.origin.x, y:self.antPosition.y + self.origin.y)
let black = self.isBlack[ptCur.x][ptCur.y]
let black = self.isBlack[ptCur.x][ptCur.y]
let direction = self.antDirection.rawValue
let direction = self.antDirection.rawValue
self.antDirection = (black ? self.leftTurn : self.rightTurn)[direction]
if (black) {
self.antDirection = self.leftTurn[direction]
} else {
self.antDirection = self.rightTurn[direction]
}


self.isBlack[ptCur.x][ptCur.y] = !self.isBlack[ptCur.x][ptCur.y]
self.isBlack[ptCur.x][ptCur.y] = !self.isBlack[ptCur.x][ptCur.y]
self.moveAnt()
self.moveAnt()
ptCur = Point(self.antPosition.x + self.origin.x, self.antPosition.y + self.origin.y)
ptCur = Point(x:self.antPosition.x + self.origin.x, y:self.antPosition.y + self.origin.y)
self.outOfBounds =
self.outOfBounds =
ptCur.x < 0 ||
ptCur.x < 0 ||
Line 4,564: Line 4,555:


let ant = Langton(width: WIDTH, height: HEIGHT)
let ant = Langton(width: WIDTH, height: HEIGHT)
while (!ant.outOfBounds) {
while !ant.outOfBounds {
ant.step()
ant.step()
}
}


for (var row = 0; row < WIDTH; row++) {
for row in 0 ..< WIDTH {
for (var col = 0; col < HEIGHT; col++) {
for col in 0 ..< HEIGHT {
print((ant.isBlack[col][row] ? "#" : " "))
print((ant.isBlack[col][row] ? "#" : " "))
}
}