@@ -56,7 +56,11 @@ class GameBrain {
5656 var segments : [ GameSegment ] ! {
5757 get {
5858 var array = snake + borders
59- array. append ( food)
59+
60+ if food != nil {
61+ array. append ( food)
62+ }
63+
6064 return array
6165 }
6266 }
@@ -85,7 +89,7 @@ class GameBrain {
8589 snake. append ( headSegment ( ) )
8690
8791 //create segment to eat
88- food = newSegment ( )
92+ food = newSegment ( . Food )
8993 }
9094
9195 private func createBorders( ) {
@@ -128,8 +132,9 @@ class GameBrain {
128132 return segment
129133 }
130134
131- private func newSegment( ) -> GameSegment {
132- let segment = GameSegment ( point: randomPoint ( ) , type: . Food)
135+ private func newSegment( type: SegmentType ) -> GameSegment {
136+
137+ let segment = GameSegment ( point: randomPoint ( ) , type: type)
133138
134139 return segment
135140 }
@@ -153,7 +158,16 @@ class GameBrain {
153158 return CGFloat ( multiplier) * side + coord
154159 }
155160
156- return CGPoint ( x: multiplier ( field. width, field. origin. x) , y: multiplier ( field. height, field. origin. y) )
161+ let newPoint = CGPoint ( x: multiplier ( field. width, field. origin. x) , y: multiplier ( field. height, field. origin. y) )
162+
163+ for segment in segments {
164+
165+ if segment. rect. contains ( newPoint) {
166+ return randomPoint ( )
167+ }
168+ }
169+
170+ return newPoint
157171 }
158172
159173 private func centerPoint( ) -> CGPoint {
@@ -168,7 +182,13 @@ class GameBrain {
168182 return CGPoint ( x: multiplier ( field. width, field. origin. x) , y: multiplier ( field. height, field. origin. y) )
169183 }
170184
171- private var score : Int !
185+ private var score : Int ! {
186+ didSet{
187+ if score % 3 == 0 {
188+ borders. append ( newSegment ( . Border) )
189+ }
190+ }
191+ }
172192
173193 func updateHead( ) {
174194
@@ -183,8 +203,6 @@ class GameBrain {
183203 }
184204 }
185205
186- moveHead ( )
187-
188206 if food. rect. contains ( headPoint) {
189207
190208 score = score + 1
@@ -193,9 +211,10 @@ class GameBrain {
193211
194212 snake. insert ( food, atIndex: snake. endIndex)
195213
196- food = newSegment ( )
214+ food = newSegment ( . Food )
197215 }
198216
217+ moveHead ( )
199218 }
200219
201220 private func directionByPoint( current: CGPoint , next: CGPoint ) -> Direction {
0 commit comments