Skip to content

Instantly share code, notes, and snippets.

@joelforjava
Created October 12, 2018 00:43
Show Gist options
  • Save joelforjava/283d00c611f964b91daf5ae0a17bf921 to your computer and use it in GitHub Desktop.
Save joelforjava/283d00c611f964b91daf5ae0a17bf921 to your computer and use it in GitHub Desktop.
My basic attempt at a two-up game in Swift. Essentially a copy from the Groovy version found here: http://groovy-lang.org/design-patterns.html#_abstract_factory_pattern
class TwoUp {
private var money = 1000
func tossWasHeads() -> Bool {
let next = randomNumber()
return next % 2 == 0
}
func moreTurns() -> Bool {
if (money > 0) {
print("You have \(money), how much would you like to bet?")
return true
}
return false
}
func play(amount: Int) {
let coin1 = tossWasHeads()
let coin2 = tossWasHeads()
if (coin1 && coin2) {
money += amount
print("You Win")
} else if (!coin1 && !coin2) {
money -= amount
print("You Lose")
} else {
print("Draw")
}
}
func randomNumber() -> Int {
return Int.random(in: 0..<2)
}
}
let tu = TwoUp()
while(tu.moreTurns()) {
tu.play(amount: 50)
}
print("Sorry, you have no money left. Thanks for playing!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment