Question

Here is my problem: In Swift I, you used your knowledge at the time to create...

Here is my problem:

In Swift I, you used your knowledge at the time to create a High / Low Guessing Game.  

This week, you will update (or create a new version of) the game using the knowledge you've now attained.

You will be creating a High/Low guessing game as outlined below:

In this game:

  • Your app will think of a random number between 0 and 999, and you (the player) will have to guess the number.
    • You can use the following code to generate a random number:
      var number = Int.random(in: 0...999)
  • With every guess you enter, the app will tell you whether your guess is too high or too low.
    • Your app will need to safely unwrap an Optional (i.e. the user's input via your interface's textField).
      • To convert your textField input to an integer, at the top of your code, include:import Foundation
    • Your app should make use of Enumeration to process each possible case (i.e. Too High, Too Low, Correct Guess, Invalid Guess / Error).
    • Your app should make use of Guard instead of if statements throughout.
  • The app should should not break if a user attempts to enter something other than a number (making use of Enums and Guard to catch errors).
  • The game will continue until you've guessed the number correctly.
  • Once you guess correctly:
    • The app will tell you that you've won
    • Tell you how many guesses it took for you.
    • Start over again with a different random number.

Here is code I have from the original assignment, I need help converting it to match the conditions listed above

import UIKit

import Foundation

class ViewController: UIViewController {

override func viewDidLoad() {

super.viewDidLoad()

consoleOutput.isHidden = true

// Do any additional setup after loading the view.

}

//var guess: Int = (question as NSString).integerValue

@IBOutlet weak var consoleOutput: UITextView!

@IBOutlet weak var userGuess: UITextField!

@IBAction func guess(_ sender: Any) {

consoleOutput.isHidden = false

  

let userInput = Int(userGuess.text!)

var number = Int.random(in: 0...999)

  

if userInput == number {

consoleOutput.text = "You guessed the right number!"}

if userInput! > number {

consoleOutput.text = "You guessed too high, try again"}

if userInput! < number {

consoleOutput.text = "You guessed too low, try again"}

}

  

  

}

Homework Answers

Answer #1

swift code

import UIKit
import Foundation

class ViewController: UIViewController {
  
    var number = Int.random(in: 0...999)
    var guess = 0

    @IBOutlet weak var userGuess: UITextField!
    @IBOutlet weak var consoleOutput: UILabel!
  
  
    enum GuessError: ErrorType {
        case Empty
        case NotInt
        case OutOfBounds
    }
  
    enum GuessCase {
        case TooHigh
        case TooLow
        case CorrectGuess
        case InvalidGuess
    }
  
    func reset() {
        consoleOutput.text = ""
        userGuess.text = nil
        number = Int.random(in: 0...999)
        guess = 0
    }
  
    func checkError(guessedNumberText: String?, generatedNumber: Int) throws -> String {
        guard guessedNumberText != nil else {
            throw GuessError.Empty
        }
        guard guessedNumberText != "" else {
            throw GuessError.Empty
        }
      
        guard let guessedNumber = Int(guessedNumberText!) else {
            throw GuessError.NotInt
        }
     
        guard case 0 ... 999 = guessedNumber else {
            throw GuessError.OutOfBounds
        }
     
        return "No error"
  
    }
  
    func checkGuess(guessedNumberText: String?, generatedNumber: Int) -> GuessCase {
        guard generatedNumber >= guessedNumber else {
            return .TooHigh
        }
        guard generatedNumber <= guessedNumber else {
            return .TooLow
        }
        guard generatedNumber != guessedNumber else {
            return .CorrectGuess
        }
        return .InvalidGuess
    }  

    @IBAction func guess(_ sender: Any) {
        ++guess
        switch checkGuess(userGuess.text, generatedNumber: number) {
            case .TooHigh:
                   consoleOutput.text = "Your guess is too high."
            case .TooLow:
                   consoleOutput.text = "Your guess is too low."
            case .CorrectGuess:
                   consoleOutput.text = "You've Won! You guessed"+ String(guess) + " times!!!"
                   reset()
            case .InvalidGuess:    
                let statusMessage: String?
                do {
                    try statusMessage = checkError(userGuess.text, generatedNumber: number)
                } catch GuessError.Empty {
                     statusMessage = "You have to guess to play."
                } catch GuessError.NotInt {
                        statusMessage = "That's not a whole number between 0 and 999"
                } catch GuessError.OutOfBounds {
                        statusMessage = "That's a whole number, but it isn't between 0 and 999"
                } catch {
                        statusMessage = "Something went wrong."
                }
                consoleOutput.text = statusMessage
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        number = Int.random(in: 0...999)
        guess = 0
     
        // Do any additional setup after loading the view, typically from a nib.
      
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
}

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Create a very simple TCP Application in JAVA. You will create a client and a server....
Create a very simple TCP Application in JAVA. You will create a client and a server. The client must execute after you start the server. Here is what they will do. The client will read from the console a string that the users enters. This string will be the name of the user, let's say Bob. The client then sends the name, Bob, in an Object Stream, to the server. The server will receive this Object Stream and send to...
Goal: Write a simple number guessing game in java. The game picks a number between bounds...
Goal: Write a simple number guessing game in java. The game picks a number between bounds input by the user, then user has to guess the number. The game will tell you if your guess is too high or too low. When you guess it, the game will tell you how many guesses it took Run multiple games and print statistics (# games, # guesses, avg) when all done. Sample Run: G U E S S I N G G...
I wrote the following java code with the eclipse ide, which is supposed to report the...
I wrote the following java code with the eclipse ide, which is supposed to report the number of guesses it took to guess the right number between one and five. Can some repost the corrected code where the variable "guess" is incremented such that the correct number of guesses is displayed? please test run the code, not just look at it in case there are other bugs that exist. import java.util.*; public class GuessingGame {    public static final int...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g,...
For a C program hangman game: Create the function int setup_game [int setup_game ( Game *g, char wordlist[][MAX_WORD_LENGTH], int numwords)] for a C program hangman game. (The existing code for other functions and the program is below, along with what the function needs to do) What int setup_game needs to do setup_game() does exactly what the name suggests. It sets up a new game of hangman. This means that it picks a random word from the supplied wordlist array and...
(Sure, take your time. would you like me to post this again?) Thanks in advance !...
(Sure, take your time. would you like me to post this again?) Thanks in advance ! Write the following methods in java class ARM that represent state information as well as functional blocks of the ARM platform. [Go through the following 5 classes then write methods for the instructions: mov, str, ldr, add in class ARM, finally, write a print method for ARM that can display the registers and the memory locations that have been used. (make sure to make...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML...
Homework Draw class diagrams for your HW4 - the Tetris Game shown below: Part 1: UML As a review, Here are some links to some explanations of UML diagrams if you need them. • https://courses.cs.washington.edu/courses/cse403/11sp/lectures/lecture08-uml1.pdf (Links to an external site.) • http://creately.com/blog/diagrams/class-diagram-relationships/ (Links to an external site.) • http://www.cs.bsu.edu/homepages/pvg/misc/uml/ (Links to an external site.) However you ended up creating the UML from HW4, your class diagram probably had some or all of these features: • Class variables: names, types, and...
I've posted this question like 3 times now and I can't seem to find someone that...
I've posted this question like 3 times now and I can't seem to find someone that is able to answer it. Please can someone help me code this? Thank you!! Programming Project #4 – Programmer Jones and the Temple of Gloom Part 1 The stack data structure plays a pivotal role in the design of computer games. Any algorithm that requires the user to retrace their steps is a perfect candidate for using a stack. In this simple game you...
Introduction Purpose Your goal is to create a design for a software interface. You will experience...
Introduction Purpose Your goal is to create a design for a software interface. You will experience the scope of the design process from brainstorming ideas and gathering information about users’ needs to storyboarding, prototyping, and finally, testing and refining your product. As you work on the software interface, you will demonstrate your ability to apply fundamental Human-Computer Interaction principles to interface analysis, design, and implementation. You will be responsible for delivering project components to your professor at several points during...
Read the attached articles about the proposed merger of Xerox and Fujifilm. Utilizing your knowledge of...
Read the attached articles about the proposed merger of Xerox and Fujifilm. Utilizing your knowledge of external and internal analysis, business and corporate strategy, and corporate governance, please discuss the following questions: 1. What is the corporate strategy behind the merger of Xerox and Fujifilm? 2. Why did Xerox agree to the merger? Is this a good deal for Xerox? Discuss the benefits and challenges they face with the merger. 3. Why did Fujifilm agree to the merger? Discuss the...
Sign In INNOVATION Deep Change: How Operational Innovation Can Transform Your Company by Michael Hammer From...
Sign In INNOVATION Deep Change: How Operational Innovation Can Transform Your Company by Michael Hammer From the April 2004 Issue Save Share 8.95 In 1991, Progressive Insurance, an automobile insurer based in Mayfield Village, Ohio, had approximately $1.3 billion in sales. By 2002, that figure had grown to $9.5 billion. What fashionable strategies did Progressive employ to achieve sevenfold growth in just over a decade? Was it positioned in a high-growth industry? Hardly. Auto insurance is a mature, 100-year-old industry...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT