Skip to content

Instantly share code, notes, and snippets.

@thara
Last active April 10, 2020 16:54
Show Gist options
  • Save thara/0b711a2206e1afc1f0405a2debc36094 to your computer and use it in GitHub Desktop.
Save thara/0b711a2206e1afc1f0405a2debc36094 to your computer and use it in GitHub Desktop.
Conway's Game of Life written in Swift, except classes; ported from https://gist.github.com/thara/ded6dd880ba95580088ef8875abb05e5
import Foundation
let height = 30
let width = 60
struct Point : Hashable {
var x: Int
var y: Int
}
func neighbers(around point: Point) -> [Point] {
let x = point.x
let y = point.y
return [
(x - 1, y - 1), (x , y - 1), (x + 1, y - 1),
(x - 1, y ), (x + 1, y ),
(x - 1, y + 1), (x , y + 1), (x + 1, y + 1),
].map(Point.init)
}
func living(at point: Point, in board: Set<Point>) -> Bool {
let count = neighbers(around: point).filter { board.contains($0) }.count
return count == 3 || (count == 2 && board.contains(point))
}
func advance(board: Set<Point>) -> Set<Point> {
let recalc = board.union(board.flatMap(neighbers))
return Set(recalc.filter { living(at: $0, in: board) })
}
func printBoard(_ board: Set<Point>) {
for y in 0..<height {
for x in 0..<width {
let mark = board.contains(Point(x: x, y: y)) ? "*" : "-"
print(mark, terminator: "")
}
print("")
}
}
var state = Set([(0, 1), (1, 2), (2, 0), (2, 1), (2, 2)].map(Point.init))
printBoard(state)
while true {
usleep(100 * 1000)
print("\u{1b}[\(height)A\r", terminator: "")
state = advance(board: state)
printBoard(state)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment