/
ShipDestroyViewController.swift
82 lines (66 loc) · 2.54 KB
/
ShipDestroyViewController.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
//
// ShipDestroyViewController.swift
// Battleship
//
// Created by Samuel Burnstone on 18/07/2016.
// Copyright © 2016 ShinobiControls. All rights reserved.
//
import UIKit
class ShipDestroyViewController: UIViewController {
@IBOutlet weak var gameBoard: GameBoardView!
@IBOutlet weak var attemptsLabel: UILabel!
@IBOutlet weak var shipsLabel: UILabel!
var model: GameModel!
var onGameCompletion: ((GameModel, Bool, UIImage) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
if model.isComplete {
let alert = UIAlertController(title: "Game Complete!", message: "The game's already finished!", preferredStyle: .alert)
present(alert, animated: true)
gameBoard.isHidden = true
attemptsLabel.isHidden = true
shipsLabel.isHidden = true
return
}
updateLabels()
gameBoard.onCellSelection = {
[unowned self]
cellLocation in
if self.model.shipLocations.contains(cellLocation) {
self.gameBoard.alterCell(at: cellLocation, applying: .selectedGreen)
}
else {
self.gameBoard.alterCell(at: cellLocation, applying: .selectedRed)
}
self.updateLabels()
self.checkGameCompletion()
}
}
}
extension ShipDestroyViewController {
func updateLabels() {
shipsLabel.text = "Hit: \(shipsHitCount())/\(GameConstants.totalShipCount)"
let livesRemaining = GameConstants.incorrectAttemptsAllowed - incorrectAttemptsCount()
attemptsLabel.text = "Lives: \(livesRemaining)/\(GameConstants.incorrectAttemptsAllowed)"
}
}
// Kick to main screen when game complete
extension ShipDestroyViewController {
func checkGameCompletion() {
let snapshot = UIImage.snapshot(from: gameBoard)
if incorrectAttemptsCount() >= GameConstants.incorrectAttemptsAllowed {
model.isComplete = true
onGameCompletion?(model, false, snapshot)
}
else if shipsHitCount() == GameConstants.totalShipCount {
model.isComplete = true
onGameCompletion?(model, true, snapshot)
}
}
func incorrectAttemptsCount() -> Int {
return gameBoard.selectedCells.filter { !model.shipLocations.contains($0) }.count
}
func shipsHitCount() -> Int {
return gameBoard.selectedCells.filter { model.shipLocations.contains($0) }.count
}
}