UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Project 12 challenge 2 Hi all did someone of you guys manage to solve this?

Forums > 100 Days of Swift

I'm still trying to solve this challenge I have had a look at some code on GitHub but the logic it just doesn't make sense how they solved this challenge.

This is my current code, I'm still trying to figure out the logic, because we want to show an alert when the current score is greater and the previous high score, but also i was thinking that what if the highest score can only be 10, then I think game ends and everything need to be reseted to 0 to start fresh.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var button1: UIButton!
    @IBOutlet weak var button2: UIButton!
    @IBOutlet weak var button3: UIButton!

    // Hold the all countries of type "String"
    var countries = [String]()
    // Holds the current score
    var score = 0
    // Holds the correct answer
    var correctAnswer = 0
    // Holds the number of questions asked
    var questionsAsked = 0
    // Holds highest score
    var highScore = 0

    // Saves and loads data
    var defaults = UserDefaults.standard

    override func viewDidLoad() {
        super.viewDidLoad()

        countries += [
            "estonia", "france", "germany", "ireland",
            "italy", "monaco", "nigeria", "poland",
            "russia", "spain", "uk", "us"
        ]

        // Puts a border line around the buttons
        button1.layer.borderWidth = 1.5
        button2.layer.borderWidth = 1.5
        button3.layer.borderWidth = 1.5

        // Changes the border line color for the buttons
        button1.layer.borderColor = UIColor.lightGray.cgColor
        button2.layer.borderColor = UIColor.lightGray.cgColor
        button3.layer.borderColor = UIColor.lightGray.cgColor

        askQuestion(action: nil)

        // Share button is added to grey navigation bar to let users share different data types to different apps
        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .pause, target: self, action: #selector(showFinalScore))

        // Load's saved high score
        loadHighScore()

    }

    func askQuestion(action: UIAlertAction!) { // Each time this function is called will put different images into the buttons

        countries.shuffle() // Mixes up the order of the countries array in-place
        // Holds the correct answer within this range
        correctAnswer = Int.random(in: 0...2)

        button1.setImage(UIImage(named: countries[0]), for: .normal)
        button2.setImage(UIImage(named: countries[1]), for: .normal)
        button3.setImage(UIImage(named: countries[2]), for: .normal)

        // Reads out the selected String from the "countries" array than upper case it
        title = "Question:\(questionsAsked)|Score:\(score)|New Score:\(highScore)  \(countries[correctAnswer].uppercased())"

    }

    @IBAction func buttonTapped(_ sender: UIButton) {
        var title: String
        questionsAsked += 1

        // Shows two alerts to the user
        if sender.tag == correctAnswer {
            title = "Correct!"
            score += 1
        } else {
            title = "Wrong! That's the flag of \(countries[sender.tag].uppercased())"
            score -= 1

        }
        showAlert(title: title)

    }

    func showAlert(title: String) {

            // Shows a final alert message to the user with a final score after 10 questions answered
        if questionsAsked == 10 { // Display the final score once the user answered 10 questions
            showResult()

        }  else  {

            let ac = UIAlertController(title: title, message: "Your score is \(score)", preferredStyle: .alert)
            ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: askQuestion))
            present(ac, animated: true)

        }
    }

    @objc func showFinalScore() {

            let currentScoreAlert = UIAlertController(title: "Current score", message: "Your current score is \(score)", preferredStyle: .alert)
            currentScoreAlert.addAction(UIAlertAction(title: "Return to game", style: .cancel))
            present(currentScoreAlert, animated: true)

            print("There's no title here") // print this message in the debug consule if this fail
    }

    // Saves highest score
    @objc func saveHighScore() {
        defaults.set(highScore, forKey: "highScore")
    }

    // Loads highest score
    func loadHighScore() {
        highScore = defaults.object(forKey: "highScore") as? Int ?? 0

    }

    func showResult() {

        if score > highScore {
            highScore = score
            saveHighScore()

            let ac3 = UIAlertController(title: "NEW SCORE!", message: "Your new high score is \(highScore) out of 10!", preferredStyle: .alert)
            ac3.addAction(UIAlertAction(title: "Restart game", style: .default, handler: askQuestion))

            score = 0
            highScore = 0
            questionsAsked = 0

            present(ac3, animated: true)

        }
    }
}

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.