-
Notifications
You must be signed in to change notification settings - Fork 92
/
Contents.swift
139 lines (104 loc) · 2.83 KB
/
Contents.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
//: Playground - noun: a place where people can play
import UIKit
protocol TurnBasedGame{
var turn: Int{get set}
func play()
}
@objc protocol TurnBasedGameDelegate{
func gameStart()
func playerMove()
func gameEnd()
optional func turnStart()
optional func turnEnd()
func gameOver() -> Bool
}
class SinglePlayerTurnBasedGame: NSObject, TurnBasedGame{
var turn = 0
var delegate:TurnBasedGameDelegate!
func play(){
delegate.gameStart()
while !delegate.gameOver(){
if let turnStart = delegate.turnStart{
turnStart()
}
else{
print("ROUND",turn,":")
}
delegate.playerMove()
delegate.turnEnd?()
turn += 1
}
delegate.gameEnd()
}
}
class RockPaperScissors: SinglePlayerTurnBasedGame, TurnBasedGameDelegate{
enum Shape: Int{
case Rock
case Scissors
case Papper
func beat(shape: Shape) -> Bool{
return (self.rawValue + 1)%3 == shape.rawValue
}
}
var wins = 0
var otherWins = 0
override init() {
super.init()
delegate = self
}
static func go() -> Shape{
return Shape(rawValue: Int(arc4random())%3)!
}
func show( hand: Shape) -> String{
switch(hand){
case .Papper: return "Paper"
case .Rock: return "Rock"
case .Scissors: return "Scissors"
}
}
func gameStart() {
wins = 0
otherWins = 0
print("== Rock Paper Scissor ==")
}
func gameOver() -> Bool {
return wins >= 2 || otherWins >= 2
}
func gameEnd() {
if( wins >= 2 ){
print("You win!")
}
else{
assert( otherWins >= 2 , "game end with wins < 2 && otherWins < 2" )
print("You lose...")
}
}
func playerMove() {
let yourShape = RockPaperScissors.go()
let otherShape = RockPaperScissors.go()
print("Your:",show(yourShape))
print("Other:",show(otherShape))
if yourShape.beat(otherShape){
print("You win this round")
wins += 1
}
else if otherShape.beat(yourShape){
print("You lose this round")
otherWins += 1
}
else if yourShape == otherShape{
print("Tie in this round")
}
else{
assertionFailure("Impossible Shapes")
}
}
func turnStart() {
print("== ROUND START ==")
}
func turnEnd() {
print("=================")
}
}
let rockPaperScissors = RockPaperScissors()
rockPaperScissors.play()