Skip to content

Instantly share code, notes, and snippets.

@hikilaka
Created March 13, 2017 20:15
Show Gist options
  • Save hikilaka/cb9bb53c4ac70fd27d72f914037ce46f to your computer and use it in GitHub Desktop.
Save hikilaka/cb9bb53c4ac70fd27d72f914037ce46f to your computer and use it in GitHub Desktop.
//
// ViewController.swift
// Guess the Flag
//
// Created by Zack Penn on 3/12/17.
// Copyright © 2017 Zack Penn. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var topFlag: UIButton!
@IBOutlet weak var middleFlag: UIButton!
@IBOutlet weak var bottomFlag: UIButton!
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var textLabel: UILabel!
@IBOutlet weak var button: UIButton!
var countries = [String:String]()
var score = 0
var answer = 0
override func viewDidLoad() {
super.viewDidLoad()
loadCountries()
randomizeFlags()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func flagTapped(_ sender: UIButton) {
if sender.tag == answer {
score += 1
randomizeFlags()
} else {
topFlag.isEnabled = false
middleFlag.isEnabled = false
bottomFlag.isEnabled = false
textLabel.text = "Incorrect! Game Over!"
button.setTitle("Try Again", for: .normal)
button.isHidden = false
}
}
@IBAction func buttonClicked() {
score = 0
randomizeFlags()
}
func randomizeFlags() {
let choices = randomCountries()
answer = Int(arc4random_uniform(UInt32(choices.count)))
topFlag.setImage(UIImage(named: choices[0][1]), for: .normal)
middleFlag.setImage(UIImage(named: choices[1][1]), for: .normal)
bottomFlag.setImage(UIImage(named: choices[2][1]), for: .normal)
topFlag.isEnabled = true
middleFlag.isEnabled = true
bottomFlag.isEnabled = true
scoreLabel.text = "Score: \(score)"
textLabel.text = "Which country's flag is \(choices[answer][0])?"
title = choices[answer][0]
button.isHidden = true
}
func randomCountries() -> [[String]] {
var results = [[String]]()
var copy = countries
for _ in 1...3 {
let index = Int(arc4random_uniform(UInt32(copy.count)))
let key = Array(copy.keys)[index]
let value = copy[key]!
results.append([key, value])
copy.removeValue(forKey: key)
}
return results
}
func loadCountries() {
if let path = Bundle.main.path(forResource: "countries", ofType: "txt") {
let lines = try! String(contentsOfFile: path).components(separatedBy: .newlines)
for line in lines {
let tokens = line.components(separatedBy: ": ")
if tokens.count < 2 {
continue
}
countries[tokens[0]] = tokens[1]
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment