-
Notifications
You must be signed in to change notification settings - Fork 1
/
concentrationModel.swift
71 lines (62 loc) · 1.94 KB
/
concentrationModel.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
//
// concentrationModel.swift
// Concentration
//
// Created by BHAVANASINGH on 04/01/19.
// Copyright © 2019 Stanford University. All rights reserved.
//
import Foundation
class Concentration
{
private var score = 0
var cards = [Card]()
private var oneAndOnlyOneCardFaceUp : Int?{
get{
return cards.indices.filter{ cards[$0].isFaceUp }.oneAndOnly
}
set{
for index in cards.indices{
cards[index].isFaceUp = (newValue == index)
}
}
}
init(numberOfPairOfCards: Int){
assert(numberOfPairOfCards > 0, "Concentration.numberOfPairOfCards: = Should be atleast 1")
for _ in 1...numberOfPairOfCards{
let card = Card()
cards += [card, card]
}
cards.shuffle()
}
func chooseCard(at index: Int){
assert(cards.indices.contains(index), "Concentration.chooseCard.index:\(index) = Not a valid index in cards array")
if !cards[index].isMatched{
if let matchIndex = oneAndOnlyOneCardFaceUp, matchIndex != index{
//If cards match and only ONE card is FACEUP
if cards[matchIndex] == cards[index] {
cards[matchIndex].isMatched = true
cards[index].isMatched = true
score += 2
}else{
if cards[index].isTouched == 1 {
score -= 1
}else {
cards[index].isTouched = 1
}
}
cards[index].isFaceUp = true
}else{
//If NO card faceup or TWO cards face up
oneAndOnlyOneCardFaceUp = index
}
}
}
func updateScoreValue() -> Int {
return score
}
}
extension Collection {
var oneAndOnly : Element? {
return count == 1 ? first : nil
}
}