-
Notifications
You must be signed in to change notification settings - Fork 145
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding plain MVC example (non-reactive) #356
Open
monishsyed
wants to merge
4
commits into
uber:master
Choose a base branch
from
monishsyed:ms/plain-MVC-example
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
00a38ab
Attempting to remove rx
monishsyed 0b7cc9c
- Created a sample that showcases Needle usage in a plain MVC based a…
monishsyed fd9c49f
Update sample app paths in travis.yml
monishsyed 339dd90
Fixing sampleapp path in Needle generator tests
monishsyed File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
github "SnapKit/SnapKit" ~> 4.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
github "SnapKit/SnapKit" "4.2.0" |
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
45 changes: 45 additions & 0 deletions
45
Sample/MVC-plain/TicTacToe/Sources/Game/GameComponent.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// | ||
// Copyright (c) 2018. Uber Technologies | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
|
||
import NeedleFoundation | ||
import UIKit | ||
|
||
protocol GameDependency: Dependency { | ||
var mutableScoreStore: MutableScoreStore { get } | ||
var playersStore: PlayersStore { get } | ||
} | ||
|
||
class GameComponent: Component<GameDependency>, GameBuilder { | ||
|
||
var gameViewController: UIViewController { | ||
return GameViewController(mutableScoreStore: dependency.mutableScoreStore, playersStore: dependency.playersStore, scoreSheetBuilder: scoreSheetBuilder) | ||
} | ||
|
||
var scoreSheetBuilder: ScoreSheetBuilder { | ||
return ScoreSheetComponent(parent: self) | ||
} | ||
|
||
// This should not be used as the provider for GameDependency. | ||
var mutableScoreStore: MutableScoreStore { | ||
return ScoreStoreImpl() | ||
} | ||
} | ||
|
||
// Use a builder protocol to allow mocking for unit tests. At the same time, | ||
// this allows GameViewController to be initialized lazily. | ||
protocol GameBuilder { | ||
var gameViewController: UIViewController { get } | ||
} |
302 changes: 302 additions & 0 deletions
302
Sample/MVC-plain/TicTacToe/Sources/Game/GameViewController.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,302 @@ | ||||||
// | ||||||
// Copyright (c) 2018. Uber Technologies | ||||||
// | ||||||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||||||
// you may not use this file except in compliance with the License. | ||||||
// You may obtain a copy of the License at | ||||||
// | ||||||
// http://www.apache.org/licenses/LICENSE-2.0 | ||||||
// | ||||||
// Unless required by applicable law or agreed to in writing, software | ||||||
// distributed under the License is distributed on an "AS IS" BASIS, | ||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||
// See the License for the specific language governing permissions and | ||||||
// limitations under the License. | ||||||
// | ||||||
|
||||||
import SnapKit | ||||||
import UIKit | ||||||
|
||||||
private let rowCount = 3 | ||||||
private let colCount = 3 | ||||||
private let sectionCount = 1 | ||||||
private let cellSize: CGFloat = UIScreen.main.bounds.width / CGFloat(colCount) | ||||||
private let cellIdentifier = "TicTacToeCell" | ||||||
|
||||||
private enum Players: Int { | ||||||
case player1 = 1 | ||||||
case player2 | ||||||
|
||||||
var color: UIColor { | ||||||
switch self { | ||||||
case .player1: | ||||||
return UIColor.red | ||||||
case .player2: | ||||||
return UIColor.blue | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
class GameViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, ScoreSheetListener { | ||||||
|
||||||
private let mutableScoreStore: MutableScoreStore | ||||||
private let playersStore: PlayersStore | ||||||
private let scoreSheetBuilder: ScoreSheetBuilder | ||||||
private let collectionView: UICollectionView = { | ||||||
let layout = UICollectionViewFlowLayout() | ||||||
layout.minimumLineSpacing = 0 | ||||||
layout.minimumInteritemSpacing = 0 | ||||||
layout.itemSize = CGSize(width: cellSize, height: cellSize) | ||||||
return UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) | ||||||
}() | ||||||
|
||||||
init(mutableScoreStore: MutableScoreStore, playersStore: PlayersStore, scoreSheetBuilder: ScoreSheetBuilder) { | ||||||
self.mutableScoreStore = mutableScoreStore | ||||||
self.playersStore = playersStore | ||||||
self.scoreSheetBuilder = scoreSheetBuilder | ||||||
super.init(nibName: nil, bundle: nil) | ||||||
} | ||||||
|
||||||
required init?(coder aDecoder: NSCoder) { | ||||||
fatalError("init(coder:) has not been implemented") | ||||||
} | ||||||
|
||||||
override func viewDidLoad() { | ||||||
super.viewDidLoad() | ||||||
|
||||||
view.backgroundColor = UIColor.purple | ||||||
|
||||||
buildCollectionView() | ||||||
buildScoerButton() | ||||||
initBoard() | ||||||
} | ||||||
|
||||||
private func buildCollectionView() { | ||||||
collectionView.dataSource = self | ||||||
collectionView.delegate = self | ||||||
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier) | ||||||
view.addSubview(collectionView) | ||||||
collectionView.snp.makeConstraints { (maker: ConstraintMaker) in | ||||||
maker.center.equalTo(self.view.snp.center) | ||||||
maker.size.equalTo(CGSize(width: CGFloat(colCount) * cellSize, height: CGFloat(rowCount) * cellSize)) | ||||||
} | ||||||
} | ||||||
|
||||||
private func announce(_ winner: Players, withCompletionHandler handler: @escaping () -> ()) { | ||||||
performOnPlayerNames { [weak self] (player1Name: String, player2Name: String) in | ||||||
let winnerName: String | ||||||
switch winner { | ||||||
case .player1: | ||||||
winnerName = player1Name | ||||||
case .player2: | ||||||
winnerName = player2Name | ||||||
} | ||||||
self?.showAlert(with: "\(winnerName) Won!", completionHandler: handler) | ||||||
} | ||||||
} | ||||||
|
||||||
private func announceDraw(withCompletionHandler handler: @escaping () -> ()) { | ||||||
showAlert(with: "It's a Tie", completionHandler: handler) | ||||||
} | ||||||
|
||||||
private func showAlert(with title: String, completionHandler handler: @escaping () -> ()) { | ||||||
let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) | ||||||
let closeAction = UIAlertAction(title: "Close Game", style: UIAlertAction.Style.default) { _ in | ||||||
handler() | ||||||
} | ||||||
alert.addAction(closeAction) | ||||||
present(alert, animated: true, completion: nil) | ||||||
} | ||||||
|
||||||
private func performOnPlayerNames(with handler: @escaping (String, String) -> ()) { | ||||||
if let names = playersStore.names { | ||||||
handler(names.0, names.1) | ||||||
} | ||||||
} | ||||||
|
||||||
// MARK: - High Scores | ||||||
|
||||||
private func buildScoerButton() { | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
let scoreButton = UIButton() | ||||||
view.addSubview(scoreButton) | ||||||
scoreButton.snp.makeConstraints { (maker: ConstraintMaker) in | ||||||
maker.bottom.equalTo(self.view.snp.bottom).offset(-70) | ||||||
maker.leading.trailing.equalTo(self.view).inset(40) | ||||||
maker.height.equalTo(50) | ||||||
} | ||||||
scoreButton.setTitle("High Scores", for: .normal) | ||||||
scoreButton.setTitleColor(UIColor.white, for: .normal) | ||||||
scoreButton.backgroundColor = UIColor.black | ||||||
scoreButton.addTarget(self, action: #selector(didTapScoreButton), for: .touchUpInside) | ||||||
} | ||||||
|
||||||
@objc | ||||||
private func didTapScoreButton() { | ||||||
if let scoreSheetVC = scoreSheetBuilder.scoreSheetViewController as? ScoreSheetViewController { | ||||||
scoreSheetVC.listener = self | ||||||
present(scoreSheetVC, animated: true) | ||||||
} | ||||||
} | ||||||
|
||||||
func done() { | ||||||
dismiss(animated: true, completion: nil) | ||||||
} | ||||||
|
||||||
// MARK: - Game Logic | ||||||
|
||||||
private var currentPlayer = Players.player1 | ||||||
private var board = [[Players?]]() | ||||||
|
||||||
private func initBoard() { | ||||||
for _ in 0 ..< rowCount { | ||||||
board.append([nil, nil, nil]) | ||||||
} | ||||||
} | ||||||
|
||||||
private func placeCurrentPlayerMark(at row: Int, col: Int) { | ||||||
guard board[row][col] == nil else { | ||||||
return | ||||||
} | ||||||
|
||||||
let currentPlayer = getAndFlipCurrentPlayer() | ||||||
board[row][col] = currentPlayer | ||||||
setCell(at: row, col: col, withPlayerType: currentPlayer) | ||||||
|
||||||
let endGame = checkEndGame() | ||||||
if endGame.didEnd { | ||||||
if let winner = endGame.winner { | ||||||
performOnPlayerNames { [weak self] (player1Name: String, player2Name: String) in | ||||||
let winnerName = winner == .player1 ? player1Name : player2Name | ||||||
let loserName = winner != .player1 ? player1Name : player2Name | ||||||
self?.announce(winner) { [weak self] in | ||||||
self?.mutableScoreStore.updateScore(withWinner: winnerName, loser: loserName) | ||||||
} | ||||||
} | ||||||
} else { | ||||||
announceDraw { [weak self] in | ||||||
self?.mutableScoreStore.updateDraw() | ||||||
} | ||||||
} | ||||||
} | ||||||
} | ||||||
|
||||||
private func setCell(at row: Int, col: Int, withPlayerType playerType: Players) { | ||||||
let indexPathRow = row * colCount + col | ||||||
let cell = collectionView.cellForItem(at: IndexPath(row: indexPathRow, section: sectionCount - 1)) | ||||||
cell?.backgroundColor = playerType.color | ||||||
} | ||||||
|
||||||
private func getAndFlipCurrentPlayer() -> Players { | ||||||
let currentPlayer = self.currentPlayer | ||||||
self.currentPlayer = currentPlayer == .player1 ? .player2 : .player1 | ||||||
return currentPlayer | ||||||
} | ||||||
|
||||||
private func checkEndGame() -> (winner: Players?, didEnd: Bool) { | ||||||
let winner = checkWinner() | ||||||
if let winner = winner { | ||||||
return (winner, true) | ||||||
} | ||||||
let isDraw = checkDraw() | ||||||
if isDraw { | ||||||
return (nil, true) | ||||||
} | ||||||
|
||||||
return (nil, false) | ||||||
} | ||||||
|
||||||
private func checkWinner() -> Players? { | ||||||
// Rows. | ||||||
for row in 0 ..< rowCount { | ||||||
guard let assumedWinner = board[row][0] else { | ||||||
continue | ||||||
} | ||||||
var winner: Players? = assumedWinner | ||||||
for col in 1 ..< colCount { | ||||||
if assumedWinner.rawValue != board[row][col]?.rawValue { | ||||||
winner = nil | ||||||
break | ||||||
} | ||||||
} | ||||||
if let winner = winner { | ||||||
return winner | ||||||
} | ||||||
} | ||||||
|
||||||
// Cols. | ||||||
for col in 0 ..< colCount { | ||||||
guard let assumedWinner = board[0][col] else { | ||||||
continue | ||||||
} | ||||||
var winner: Players? = assumedWinner | ||||||
for row in 1 ..< rowCount { | ||||||
if assumedWinner.rawValue != board[row][col]?.rawValue { | ||||||
winner = nil | ||||||
break | ||||||
} | ||||||
} | ||||||
if let winner = winner { | ||||||
return winner | ||||||
} | ||||||
} | ||||||
|
||||||
// Diagnals. | ||||||
guard let p11 = board[1][1] else { | ||||||
return nil | ||||||
} | ||||||
if let p00 = board[0][0], let p22 = board[2][2] { | ||||||
if p00.rawValue == p11.rawValue && p11.rawValue == p22.rawValue { | ||||||
return p11 | ||||||
} | ||||||
} | ||||||
|
||||||
if let p02 = board[0][2], let p20 = board[2][0] { | ||||||
if p02.rawValue == p11.rawValue && p11.rawValue == p20.rawValue { | ||||||
return p11 | ||||||
} | ||||||
} | ||||||
|
||||||
return nil | ||||||
} | ||||||
|
||||||
private func checkDraw() -> Bool { | ||||||
for row in 0 ..< rowCount { | ||||||
for col in 0 ..< colCount { | ||||||
if board[row][col] == nil { | ||||||
return false | ||||||
} | ||||||
} | ||||||
} | ||||||
return true | ||||||
} | ||||||
|
||||||
// MARK: - UICollectionViewDataSource | ||||||
|
||||||
func numberOfSections(in collectionView: UICollectionView) -> Int { | ||||||
return sectionCount | ||||||
} | ||||||
|
||||||
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { | ||||||
return rowCount * colCount | ||||||
} | ||||||
|
||||||
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { | ||||||
let reusedCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) | ||||||
reset(cell: reusedCell) | ||||||
return reusedCell | ||||||
} | ||||||
|
||||||
private func reset(cell: UICollectionViewCell) { | ||||||
cell.backgroundColor = UIColor.white | ||||||
cell.contentView.layer.borderWidth = 2 | ||||||
cell.contentView.layer.borderColor = UIColor.lightGray.cgColor | ||||||
} | ||||||
|
||||||
// MARK: - UICollectionViewDelegate | ||||||
|
||||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { | ||||||
let row = indexPath.row / colCount | ||||||
let col = indexPath.row - row * rowCount | ||||||
placeCurrentPlayerMark(at: row, col: col) | ||||||
} | ||||||
} |
File renamed without changes.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.