Skip to content

Instantly share code, notes, and snippets.

@nuclearace
Last active October 23, 2015 21:13
Show Gist options
  • Select an option

  • Save nuclearace/a75c7bd06421cd4a926b to your computer and use it in GitHub Desktop.

Select an option

Save nuclearace/a75c7bd06421cd4a926b to your computer and use it in GitHub Desktop.
import Foundation
enum Coin: Int, CustomStringConvertible {
case Tails, Heads
var description: String {
if self == .Tails {
return "T"
} else {
return "H"
}
}
init?(string: String) {
if string.uppercaseString == "T" {
self.init(rawValue: 0)
} else if string.uppercaseString == "H" {
self.init(rawValue: 1)
} else {
return nil
}
}
static func flip() -> Coin {
return Coin(rawValue: Int(arc4random_uniform(2)))!
}
}
let input = NSFileHandle.fileHandleWithStandardInput()
func checkQuit() -> Bool {
print("Play again? ")
let data = input.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
return String(str.lowercaseString.characters.dropLast()) == "y"
}
func getComputerSequence(rand: Bool) -> [Coin] {
let seq: [Coin]
if !rand {
seq = [human[1] == .Heads ? .Tails : .Heads] + human[0...1]
} else {
seq = [Coin.flip(), Coin.flip(), Coin.flip()]
}
print("Computer's sequence is: ", seq[0], seq[1], seq[2])
return seq
}
func getHumanSequence() -> [Coin] {
var ret = [Coin]()
print("Enter sequence of three: ")
let data = input.availableData
let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
let seq = str.characters.dropLast().map {Coin(string: String($0))}
for case let coin? in seq {
ret.append(coin)
}
if ret.count != 3 {
print("You can only pick three")
exit(0)
}
return ret
}
var human = [Coin]()
var computer = [Coin]()
var win = false
var play = true
while play {
win = false
switch Coin.flip() {
case .Heads:
human = getHumanSequence()
computer = getComputerSequence(false)
case .Tails:
computer = getComputerSequence(true)
human = getHumanSequence()
}
while !win {
let seq = [Coin.flip(), Coin.flip(), Coin.flip()]
print(seq[0], seq[1], seq[2], separator: "", terminator: "")
if seq == human {
print("\nYou win!")
win = true
} else if seq == computer {
print("\nComputer wins!")
win = true
}
}
play = checkQuit()
}
Copy link

ghost commented Oct 23, 2015

it seems that you are not licensing your code. Have you ever heard of the GPLv3 License ? GPL is the only license that truly respects users freedom. I urge you to read http://www.gnu.org/licenses/gpl-3.0.en.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment