Langton's ant: Difference between revisions

m
(add swift)
Line 4,497:
let HEIGHT = 100
 
classstruct Point {
var x:Int
var y:Int
init(_ x:Int, _ y:Int) {
self.x = x
self.y = y
}
}
 
Line 4,516 ⟶ 4,511:
let xInc = [0, 1,-1, 0]
let yInc = [-1, 0, 0, 1]
var isBlack:[[Bool]]!
var origin:Point!
var antPosition = Point(x:0, y:0)
var outOfBounds = false
var antDirection = Direction.East
init(width:Int, height:Int) {
self.origin = Point(x:width / 2, y:height / 2)
self.isBlack = Array(count: width, repeatedValue: Array(count: height, repeatedValue: false))
}
Line 4,533 ⟶ 4,528:
func step() -> Point {
if (self.outOfBounds) {
println("Ant tried to move while out of bounds.")
exit(0)
}
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 direction = self.antDirection.rawValue
self.antDirection = (black ? self.antDirectionleftTurn =: 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.moveAnt()
ptCur = Point(x:self.antPosition.x + self.origin.x, y:self.antPosition.y + self.origin.y)
self.outOfBounds =
ptCur.x < 0 ||
Line 4,564 ⟶ 4,555:
 
let ant = Langton(width: WIDTH, height: HEIGHT)
while (!ant.outOfBounds) {
ant.step()
}
 
for (var row =in 0; row ..< WIDTH; row++) {
for (var col =in 0; col ..< HEIGHT; col++) {
print((ant.isBlack[col][row] ? "#" : " "))
}
Anonymous user