Skip to content

Commit 7e50d85

Browse files
committed
Finished with center points
1 parent b66f055 commit 7e50d85

File tree

1 file changed

+27
-5
lines changed

1 file changed

+27
-5
lines changed

SnakeGame/GameModel.swift

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ class GameBrain {
3333
}
3434
}
3535

36-
private var headPoint: CGPoint! = CGPointZero
36+
private var headPoint: CGPoint!
3737

3838
private var screen: CGSize!
3939

@@ -96,16 +96,31 @@ class GameBrain {
9696

9797
let height32 = (fRect.height - side * 2).toUInt32()
9898

99-
let randomMultiX = arc4random_uniform(width32 / side32 - side.toUInt32())
99+
let randomMultiX = arc4random_uniform(width32 / side32) + 1
100100

101-
let randomMultiY = arc4random_uniform(height32 / side32 - side.toUInt32())
101+
let randomMultiY = arc4random_uniform(height32 / side32) + 1
102102

103103
let newX: CGFloat = CGFloat(randomMultiX) * side + fRect.origin.x
104104
let newY: CGFloat! = CGFloat(randomMultiY) * side + fRect.origin.y
105105

106106
return CGPoint(x: newX, y: newY)
107107
}
108108

109+
private func centerPoint() -> CGPoint {
110+
111+
let x = calculatedMultiplier(fRect.width) * side + fRect.origin.x
112+
let y = calculatedMultiplier(fRect.height) * side + fRect.origin.y
113+
114+
return CGPoint(x: x, y: y)
115+
}
116+
117+
private func calculatedMultiplier(value: CGFloat) -> CGFloat{
118+
119+
let multiplier = value / side
120+
121+
return floor(multiplier / 2)
122+
}
123+
109124
private var direction: (CGPoint)!
110125

111126
func setDefaults(viewSize: CGSize){
@@ -118,7 +133,7 @@ class GameBrain {
118133
//prepare segments
119134
segments = []
120135
//main default point for the head
121-
headPoint = randomPoint()
136+
headPoint = centerPoint()
122137

123138
//setting default direction
124139
setDirection("Up")
@@ -137,7 +152,14 @@ class GameBrain {
137152
headPoint.x += direction.x
138153
headPoint.y += direction.y
139154

140-
moveHead()
155+
let outX = self.headPoint.x == fRect.origin.x || self.headPoint.x == fRect.origin.x - side + fRect.width
156+
let outY = self.headPoint.y == fRect.origin.y || self.headPoint.y == fRect.origin.y - side + fRect.height
157+
158+
if outX || outY {
159+
headPoint = centerPoint()
160+
}else{
161+
moveHead()
162+
}
141163
}
142164

143165
private func moveHead() {

0 commit comments

Comments
 (0)