-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathWorld.swift
102 lines (85 loc) · 2.5 KB
/
World.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// World.swift
// gameoflife
//
// Created by Yonatan Bergman on 6/4/14.
// Copyright (c) 2014 Yonatan Bergman. All rights reserved.
//
import Foundation
class World {
var aliveCells:Array<Point> = []
func addCell(point:Point){
self.aliveCells.append(point)
}
func tick(){
var cellsWithNeighbours = countCellsWithNeighbours()
var newCells:Array<Point> = []
for cell in aliveCells{
var count:Int? = cellsWithNeighbours.removeValueForKey(cell)
if count && (count == 2 || count == 3){
newCells.append(cell)
}
}
for (cell, count) in cellsWithNeighbours {
if count == 3 {
newCells.append(cell)
}
}
self.aliveCells = newCells;
}
func countCellsWithNeighbours() -> Dictionary<Point, Int> {
var counterHash = initEmptyCounterHash()
for cell in aliveCells{
for neighbour in cell.neighbours(){
if let currentCount = counterHash[neighbour]{
counterHash[neighbour] = currentCount + 1
} else {
counterHash[neighbour] = 1
}
}
}
return counterHash
}
func initEmptyCounterHash() -> Dictionary<Point, Int>{
var counter:Dictionary<Point, Int> = [:]
for cell in aliveCells{
counter[cell] = 0
}
return counter
}
// ###### pragma mark - printing to console ######
func isCellAlive(point: Point) -> Bool{
for cell in aliveCells {
if cell == point {
return true
}
}
return false
}
var bounds: Rect {
let yPoints = aliveCells.map{$0.y}
let minY = minElement(yPoints)
let maxY = maxElement(yPoints)
let xPoints = aliveCells.map{$0.x}
let minX = minElement(xPoints)
let maxX = maxElement(xPoints)
return Rect(top: minY, left: minX, bottom: maxY, right: maxX)
}
func printWorld(){
let b = self.bounds
for y in (b.top...b.bottom){
var line = ""
for x in (b.left...b.right){
line += self.printCell(Point(x: x, y: y))
}
println(line)
}
}
func printCell(point: Point) -> String{
if self.isCellAlive(point){
return "X"
} else {
return "-"
}
}
}