-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameScene.swift
471 lines (360 loc) · 15.1 KB
/
GameScene.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//
// GameScene.swift
// SwiftyNinja
//
// Created by Julian Moorhouse on 17/08/2019.
// Copyright © 2019 Mindwarp Consultancy Ltd. All rights reserved.
//
import AVFoundation
import GameplayKit
import SpriteKit
enum ForceBomb {
case never, always, random
}
enum SequenceType: CaseIterable {
case oneNoBomb, one, twoWithOneBomb, two, three, four, chain, fastChain
}
class GameScene: SKScene {
var gameScore: SKLabelNode!
var score = 0 {
didSet {
gameScore.text = "Score: \(score)"
}
}
var livesImages = [SKSpriteNode]()
var lives = 3
var activeSliceBG: SKShapeNode!
var activeSliceFG: SKShapeNode!
var activeSlicePoints = [CGPoint]()
var isSwooshSoundActive = false
var activeEnemies = [SKSpriteNode]()
var bombSoundEffect: AVAudioPlayer?
// time between last enemy being destroyed and new one created
var popupTime = 0.9
// which enemy is going to be created
var sequence = [SequenceType]()
// where we are in game, relative to sequence array
var sequencePosition = 0
// how long to wait to before creating a new enemy when the sequence type is chained or fast chained
var chainDelay = 3.0
// so we know when all enemies are destoryed and we know to create more
var nextSequenceQueued = true
var isGameEnded = false
override func didMove(to view: SKView) {
let background = SKSpriteNode(imageNamed: "sliceBackground")
background.position = CGPoint(x: 512, y: 384)
background.blendMode = .replace
background.zPosition = -1
addChild(background)
// less gravity
physicsWorld.gravity = CGVector(dx: 0, dy: -6)
// slower
physicsWorld.speed = 0.85
createScore()
createLives()
createSlices()
// slow warm up to the game
sequence = [.oneNoBomb, .oneNoBomb, .twoWithOneBomb, .twoWithOneBomb, .three, .one, .chain]
for _ in 0...1000 {
if let nextSequence = SequenceType.allCases.randomElement() {
sequence.append(nextSequence)
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in self?.tossEnemies() }
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard isGameEnded == false else { return }
guard let touch = touches.first else { return }
let location = touch.location(in: self)
activeSlicePoints.append(location)
redrawActiveSlice()
if !isSwooshSoundActive {
playSwooshSound()
}
let nodesAtPoint = nodes(at: location)
for case let node as SKSpriteNode in nodesAtPoint {
if node.name == "enemy" {
// destroy the penguin
if let emitter = SKEmitterNode(fileNamed: "sliceHitEnemy") {
emitter.position = node.position
addChild(emitter)
}
node.name = ""
node.physicsBody?.isDynamic = false
let scaleOut = SKAction.scale(to: 0.001, duration: 0.2)
let fadeOut = SKAction.fadeOut(withDuration: 0.2)
let group = SKAction.group([scaleOut, fadeOut])
let seq = SKAction.sequence([group, .removeFromParent()])
node.run(seq)
score += 1
if let index = activeEnemies.firstIndex(of: node) {
activeEnemies.remove(at: index)
}
run(SKAction.playSoundFileNamed("whack.caf", waitForCompletion: false))
} else if node.name == "bomb" {
// destroy the bomb
guard let bombContainer = node.parent as? SKSpriteNode else { continue }
if let emitter = SKEmitterNode(fileNamed: "sliceHitBomb") {
emitter.position = bombContainer.position
addChild(emitter)
}
node.name = ""
bombContainer.physicsBody?.isDynamic = false
let scaleOut = SKAction.scale(to: 0.001, duration: 0.2)
let fadeOut = SKAction.fadeOut(withDuration: 0.2)
let group = SKAction.group([scaleOut, fadeOut])
let seq = SKAction.sequence([group, .removeFromParent()])
bombContainer.run(seq)
if let index = activeEnemies.firstIndex(of: bombContainer) {
activeEnemies.remove(at: index)
}
run(SKAction.playSoundFileNamed("explosion.caf", waitForCompletion: false))
endGame(triggeredByBomb: true)
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
activeSliceBG.run(SKAction.fadeOut(withDuration: 0.25))
activeSliceFG.run(SKAction.fadeOut(withDuration: 0.25))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
activeSlicePoints.removeAll(keepingCapacity: true)
let location = touch.location(in: self)
activeSlicePoints.append(location)
redrawActiveSlice()
activeSliceBG.removeAllActions()
activeSliceFG.removeAllActions()
activeSliceBG.alpha = 1
activeSliceFG.alpha = 1
}
override func update(_ currentTime: TimeInterval) {
if activeEnemies.count > 0 {
for (index, node) in activeEnemies.enumerated().reversed() {
if node.position.y < -140 {
node.removeAllActions()
if node.name == "enemy" {
node.name = ""
subtractLife()
node.removeFromParent()
activeEnemies.remove(at: index)
} else if node.name == "bombContainer" {
node.name = ""
node.removeFromParent()
activeEnemies.remove(at: index)
}
}
}
} else {
if !nextSequenceQueued {
DispatchQueue.main.asyncAfter(deadline: .now() + popupTime) {
[weak self] in
self?.tossEnemies()
}
nextSequenceQueued = true
}
}
var bombCount = 0
for node in activeEnemies {
if node.name == "bombContainer" {
bombCount += 1
break
}
}
if bombCount == 0 {
// no bombs - stop the fuse sound!
bombSoundEffect?.stop()
bombSoundEffect = nil
}
}
func createScore() {
gameScore = SKLabelNode(fontNamed: "Chalkduster")
gameScore.horizontalAlignmentMode = .left
gameScore.fontSize = 48
addChild(gameScore)
gameScore.position = CGPoint(x: 8, y: 8)
score = 0
}
func createLives() {
for i in 0..<3 {
let spriteNode = SKSpriteNode(imageNamed: "sliceLife")
spriteNode.position = CGPoint(x: CGFloat(834 + (i * 70)), y: 720)
addChild(spriteNode)
livesImages.append(spriteNode)
}
}
func createSlices() {
activeSliceBG = SKShapeNode()
activeSliceBG.zPosition = 2
activeSliceFG = SKShapeNode()
activeSliceFG.zPosition = 3
activeSliceBG.strokeColor = UIColor(red: 1, green: 0.9, blue: 0, alpha: 1)
activeSliceBG.lineWidth = 9
activeSliceFG.strokeColor = .white
activeSliceFG.lineWidth = 5
addChild(activeSliceBG)
addChild(activeSliceFG)
}
func redrawActiveSlice() {
if activeSlicePoints.count < 2 {
activeSliceBG.path = nil
activeSliceFG.path = nil
return
}
if activeSlicePoints.count > 12 {
activeSlicePoints.removeFirst(activeSlicePoints.count - 12)
}
let path = UIBezierPath()
path.move(to: activeSlicePoints[0])
for i in 1..<activeSlicePoints.count {
path.addLine(to: activeSlicePoints[i])
}
activeSliceBG.path = path.cgPath
activeSliceFG.path = path.cgPath
}
func playSwooshSound() {
isSwooshSoundActive = true
let randomNumber = Int.random(in: 1...3)
let soundName = "swoosh\(randomNumber).caf"
let swooshSound = SKAction.playSoundFileNamed(soundName, waitForCompletion: true)
run(swooshSound) { [weak self] in
self?.isSwooshSoundActive = false
}
}
func createEnemy(forceBomb: ForceBomb = .random) {
let enemy: SKSpriteNode
var enemyType = Int.random(in: 0...6)
if forceBomb == .never {
enemyType = 1
} else if forceBomb == .always {
enemyType = 0
}
if enemyType == 0 {
enemy = SKSpriteNode()
enemy.zPosition = 1
enemy.name = "bombContainer"
let bombImage = SKSpriteNode(imageNamed: "sliceBomb")
bombImage.name = "bomb"
enemy.addChild(bombImage)
if bombSoundEffect != nil {
bombSoundEffect?.stop()
bombSoundEffect = nil
}
if let path = Bundle.main.url(forResource: "sliceBombFuse", withExtension: "caf") {
if let sound = try? AVAudioPlayer(contentsOf: path) {
bombSoundEffect = sound
sound.play()
}
}
if let emitter = SKEmitterNode(fileNamed: "sliceFuse") {
emitter.position = CGPoint(x: 76, y: 64)
enemy.addChild(emitter)
}
} else {
enemy = SKSpriteNode(imageNamed: "penguin")
run(SKAction.playSoundFileNamed("launch.caf", waitForCompletion: false))
enemy.name = "enemy"
}
let randomPosition = CGPoint(x: Int.random(in: 64...960), y: -128)
enemy.position = randomPosition
let randomAngularVelocity = CGFloat.random(in: -3...3)
var randomXVelocity: Int
// way to the left of our screen
if randomPosition.x < 256 {
randomXVelocity = Int.random(in: 8...15)
// left side of out screen, not extreme left
} else if randomPosition.x < 512 {
// move to the right gently
randomXVelocity = Int.random(in: 3...5)
// right part of our screen, but not extreme right
} else if randomPosition.x < 768 {
// move to the left
randomXVelocity = -Int.random(in: 3...5)
} else {
// if it's the far right of the screen, move to the left very quickly
randomXVelocity = -Int.random(in: 8...15)
}
var randomYVelocity = Int.random(in: 24...32)
randomXVelocity *= 40
randomYVelocity *= 40
enemy.physicsBody = SKPhysicsBody(circleOfRadius: 64)
enemy.physicsBody?.velocity = CGVector(dx: randomXVelocity, dy: randomYVelocity)
enemy.physicsBody?.angularVelocity = randomAngularVelocity
// bounce off nothing in the game
enemy.physicsBody?.collisionBitMask = 0
addChild(enemy)
activeEnemies.append(enemy)
}
func tossEnemies() {
guard isGameEnded == false else { return }
popupTime *= 0.991
chainDelay *= 0.99
physicsWorld.speed *= 1.02
let sequenceType = sequence[sequencePosition]
switch sequenceType {
case .oneNoBomb:
createEnemy(forceBomb: .never)
case .one:
createEnemy()
case .twoWithOneBomb:
createEnemy(forceBomb: .never)
createEnemy(forceBomb: .always)
case .two:
createEnemy()
createEnemy()
case .three:
createEnemy()
createEnemy()
createEnemy()
case .four:
createEnemy()
createEnemy()
createEnemy()
createEnemy()
case .chain:
createEnemy()
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 5.0)) { [weak self] in self?.createEnemy() }
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 5.0 * 2)) { [weak self] in self?.createEnemy() }
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 5.0 * 3)) { [weak self] in self?.createEnemy() }
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 5.0 * 4)) { [weak self] in self?.createEnemy() }
case .fastChain:
createEnemy()
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 10.0)) { [weak self] in self?.createEnemy() }
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 10.0 * 2)) { [weak self] in self?.createEnemy() }
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 10.0 * 3)) { [weak self] in self?.createEnemy() }
DispatchQueue.main.asyncAfter(deadline: .now() + (chainDelay / 10.0 * 4)) { [weak self] in self?.createEnemy() }
}
sequencePosition += 1
nextSequenceQueued = false
}
func endGame(triggeredByBomb: Bool) {
guard isGameEnded == false else { return }
isGameEnded = true
physicsWorld.speed = 0
isUserInteractionEnabled = false
bombSoundEffect?.stop()
bombSoundEffect = nil
if triggeredByBomb {
livesImages[0].texture = SKTexture(imageNamed: "sliceLifeGone")
livesImages[1].texture = SKTexture(imageNamed: "sliceLifeGone")
livesImages[2].texture = SKTexture(imageNamed: "sliceLifeGone")
}
}
func subtractLife() {
lives -= 1
run(SKAction.playSoundFileNamed("wrong.caf", waitForCompletion: false))
var life: SKSpriteNode
if lives == 2 {
life = livesImages[0]
} else if lives == 1 {
life = livesImages[1]
} else {
life = livesImages[2]
endGame(triggeredByBomb: false)
}
life.texture = SKTexture(imageNamed: "sliceLifeGone")
life.xScale = 1.3
life.yScale = 1.3
life.run(SKAction.scale(to: 1, duration: 0.1))
}
}