/
ShipLocationViewController.swift
58 lines (44 loc) · 1.79 KB
/
ShipLocationViewController.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
//
// ShipLocationViewController.swift
// Battleship
//
// Created by Sam Burnstone on 14/07/2016.
// Copyright © 2016 ShinobiControls. All rights reserved.
//
import UIKit
class ShipLocationViewController: UIViewController {
@IBOutlet weak var gameBoard: GameBoardView!
@IBOutlet weak var remainingLabel: UILabel!
@IBOutlet weak var finishedButton: UIButton!
var onLocationSelectionComplete: ((GameModel, UIImage) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
updateLabels()
gameBoard.onCellSelection = {
[unowned self]
cellLocation in
// Only alter the cell style if we have ships left to position or we're toggling a cell that currently contains a ship
guard self.shipsLeftToPosition > 0 ||
self.gameBoard.selectedCells.contains(cellLocation) else {
return
}
self.gameBoard.toggleCellStyle(at: cellLocation)
self.updateLabels()
}
}
@IBAction func completedShipLocationSelection(_ sender: AnyObject) {
let model = GameModel(shipLocations: gameBoard.selectedCells, isComplete: false)
// Clear screen for snapshot (we don't want to give away where we've located our ships!)
gameBoard.reset()
onLocationSelectionComplete?(model, UIImage.snapshot(from: gameBoard))
}
}
extension ShipLocationViewController {
fileprivate var shipsLeftToPosition: Int {
return GameConstants.totalShipCount - self.gameBoard.selectedCells.count
}
fileprivate func updateLabels() {
remainingLabel.text = "Ships to Place: \(shipsLeftToPosition)"
finishedButton.isEnabled = shipsLeftToPosition == 0
}
}