I now set up my system of putting the answer in 1 of 4 choices but a weird error appeared:
var optionAnswer:UInt32 = arc4random_uniform(4)
if optionAnswer == 0 { // Expected declaration
optionA.text = secretAnsarrrrr.text
}
if optionAnswer == 1 {
optionB.text = secretAnsarrrrr.text
}
if optionAnswer == 2 {
optionC.text = secretAnsarrrrr.text
}
if optionAnswer == 3 {
optionD.text = secretAnsarrrrr.text
}
the error only appeared on the first conditional and it didn't specify what I needed to do. How do I fix this?
full code:
import UIKit
class ViewController: UIViewController {
#IBOutlet var numA: UILabel!
#IBOutlet var operation: UILabel!
#IBOutlet var numB: UILabel!
#IBOutlet var secretAnsarrrrr: UILabel!
#IBOutlet var optionA: UILabel!
#IBOutlet var optionB: UILabel!
#IBOutlet var optionC: UILabel!
#IBOutlet var optionD: UILabel!
#IBOutlet var level: UILabel!
#IBAction func startTest(sender: UIButton) {
var question:Int = 1
func generateQuestion() {
var answer:Float = 0.0
var randomoperation:UInt32 = arc4random_uniform(4)
if randomoperation == 0 {
operation.text = "+"
}
if randomoperation == 1 {
operation.text = "-"
}
if randomoperation == 2 {
operation.text = "X"
}
if randomoperation == 3 {
operation.text = "/"
}
var randomNumber:UInt32 = arc4random_uniform(1000)
var randomNumber2:UInt32 = arc4random_uniform(1000)
// 1000 is my maximum number for now.
randomNumber += 1
randomNumber2 += 1
func identifyVal() {
if randomNumber < randomNumber2 {
var between:UInt32 = 1000 - randomNumber2
randomNumber = randomNumber2 + arc4random_uniform(between - 1)
//making sure that randomNumber is not smaller than randomNumber2, therefore all results are positive.
}
}
if operation.text == "/" {
identifyVal()
answer = round(Float(randomNumber)/Float(randomNumber2))
}
if operation.text == "+" {
answer = Float(randomNumber + randomNumber2)
}
if operation.text == "-" {
identifyVal()
answer = Float(randomNumber - randomNumber2)
}
if operation.text == "x" {
answer = Float(randomNumber * randomNumber2)
}
secretAnsarrrrr.text = "\(answer)"
numA.text = String(Int(randomNumber))
numB.text = String(Int(randomNumber2))
}
generateQuestion()
}
var optionAnswer:UInt32 = arc4random_uniform(4)
if optionAnswer == 0 {
optionA.text = secretAnsarrrrr.text
}
if optionAnswer == 1 {
optionB.text = secretAnsarrrrr.text
}
if optionAnswer == 2 {
optionC.text = secretAnsarrrrr.text
}
if optionAnswer == 3 {
optionD.text = secretAnsarrrrr.text
}
var correct:Bool?
#IBAction func answerA(sender: UIButton) {
if optionAnswer == 0 {
correct = true
} else {
correct = false
}
}
#IBAction func answerB(sender: UIButton) {
if optionAnswer == 1 {
correct = true
} else {
correct = false
}
}
#IBAction func answerC(sender: UIButton) {
if optionAnswer == 2 {
correct = true
} else {
correct = false
}
}
#IBAction func answerD(sender: UIButton) {
if optionAnswer == 3 {
correct = true
} else {
correct = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
}
Long shot- but did you erase a function on that line earlier? If so, comment out the first line, and then erase the "//". Xcode sometimes gets confused.
Side Note: using a switch may work better. Also, consider putting this inside a struct, this would allow you to define a method randomAnswer() that acts on the questions, and then just reference the method in your view. You could also put the different options as Enums as theres only ever 4 of them. :)
Related
Here is the error that I am seeing.
The "cardButton" is responsible for showing the next question. This is a small card app game that I am trying to make and as you can see from the image this is where I am having the issue with the code.
Here is the code:
import UIKit
class MultipleViewController: UIViewController {
#IBOutlet weak var questionLabel2: UILabel!
#IBOutlet var answerButtons: [UIButton]!
#IBOutlet weak var cardButton: UIButton!
#IBAction func cardButtonHandle(_ sender: Any) {
cardButton.isEnabled = true
if questionIdx < count(mcArray) - 1 { // There are still more questions
questionIdx += 1 //
} else {
questionIdx = 0
}
nextQuestion()
}
#IBAction func answerButtonHandle(_ sender: UIButton) {
if sender.titleLabel?.text == correctAnswer{
sender.backgroundColor = UIColor.green
print("Correct!")
} else {
sender.backgroundColor = UIColor.red
print("Wrong Answer")
}
for button in answerButtons{
button.isEnabled = false
if button.titleLabel?.text == correctAnswer {
button.backgroundColor = UIColor.green
}
}
cardButton.isEnabled = true // next question
}
var correctAnswer: String? // correct answers
var answers = [String]() // answers
var question : String? // Questions
var questionIdx = 0 // not sure what this is ?
override func viewDidLoad() {
super.viewDidLoad()
// titleForButtons() // call buttons as soon its loaded..
cardButton.isEnabled = false
nextQuestion()
}
func nextQuestion (){
let currentQuestion = mcArray![questionIdx]
answers = currentQuestion["Answers"] as! [String]
correctAnswer = currentQuestion["CorrectAnswer"] as? String
question = currentQuestion["Question"] as? String
titleForButtons ()
}
func titleForButtons (){
for (idx,button) in answerButtons .enumerated() {
button.titleLabel?.lineBreakMode = .byWordWrapping
button.setTitle(answers[idx],for:.normal)
button.isEnabled = true
}
questionLabel2.text = question
}
}
The following should work, you did not have the correct syntax for the length of the array. Note that if you have not initialized your questions array, this would cause a crash. Therefore you might want to add a guard into your code. Perhaps use the following
#IBAction func cardButtonHandle(_ sender: Any) {
cardButton.isEnabled = true
if questionIdx < (mcArray!.count) - 1 { // There are still more questions
questionIdx += 1 //
} else {
questionIdx = 0
}
nextQuestion()
}
My code is supposed to use a tuple to sort a string and int. String is supposed to be in order from a- z and int is supposed to be in order from 9-1. Right now no order is being kept and its not being sorted.
import UIKit
class ViewController: UIViewController {
var number = [Int]()
var yourArray = [String]()
#IBOutlet var txtb: UITextField!
#IBOutlet var txta: UITextField!
#IBAction func move(_ sender: Any) {
yourArray.append((txta.text!))
number.append(Int(txtb.text!)!)
let tuples = zip(yourArray,number)
let sorted = tuples.sorted(by: { this, next in
if this.0 < next.0 {
return true
} else if this.0 == next.0 {
return this.1 < next.1
} else {
return false
}})
bad.mm.append(String(describing: sorted.map { " \($0)" }.joined(separator:"\n")))
}}
struct bad {
static var mm = [String]()}
This looks like working?.
let tuples:[(String,Int)] = [("baa",2), ("abc",50),("a",10)]
let result = tuples.sorted(by: { this, next in
if this.0 < next.0 {
return true
} else if this.0 == next.0 {
return this.1 < next.1
} else {
return false
}})
print(result)
so I'm new to coding and I've been doing practice games a such to build my skills. I've created this word guessing game and I'm trying to make the game show the word after all guesses have been used up. However, the program doesn't read the code I write to set the label to display the answer. Here is the code I've written so far:
class ViewController: UIViewController {
var listOfWords = ["ladybug", "program", "computer", "language", "glorious", "incandescent"]
let incorrectMovesAllowed = 7
var totalWins = 0 {
didSet {
newRound()
}
}
var totalLosses = 0 {
didSet {
newRound()
}
}
#IBOutlet var letterButtons: [UIButton]!
#IBAction func buttonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)!
let letter = Character(letterString.lowercased())
currentGame.playerGuessed(letter: letter)
updateUI()
updateGameState()
}
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var correctWordLabel: UILabel!
#IBOutlet weak var treeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
newRound()
// Do any additional setup after loading the view, typically from a nib.
}
func enableLetterButtons (_enable: Bool){
for button in letterButtons {
button.isEnabled = _enable
}
}
var currentGame : Game!
func newRound() {
if !listOfWords.isEmpty{
let newWord = listOfWords.removeFirst()
currentGame = Game (word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
enableLetterButtons(_enable: true)
updateUI()
} else {
enableLetterButtons (_enable: false)
}
}
func updateUI() {
var letters = [String] ()
for letter in currentGame.formattedWord.characters {
letters.append(String(letter))
}
let wordWithSpacing = letters.joined(separator: " ")
correctWordLabel.text = wordWithSpacing
scoreLabel.text = "Wins: \(totalWins), Losses:\(totalLosses)"
treeImageView.image = UIImage (named: "Tree \(currentGame.incorrectMovesRemaining)")
}
func updateGameState(){
var letters = [String] ()
for letter in currentGame.word.characters {
letters.append(String(letter))
}
let theAnswer = letters.joined(separator: " ")
if currentGame.incorrectMovesRemaining == 0 {
correctWordLabel.text = theAnswer
Thread.sleep(forTimeInterval: 3)
totalLosses += 1
} else if currentGame.word == currentGame.formattedWord {
totalWins += 1
} else {
updateUI()
}
}
}
In addition, I have a structure that is written like this:
import Foundation
struct Game {
var word : String
var incorrectMovesRemaining : Int
var guessedLetters: [Character]
mutating func playerGuessed (letter: Character){
guessedLetters.append(letter)
if !word.characters.contains(letter){
incorrectMovesRemaining -= 1
}
}
var formattedWord: String {
var guessedWord = ""
for letter in word.characters {
if guessedLetters.contains(letter) {
guessedWord += "\(letter)"
} else {
guessedWord += "_"
}
}
return guessedWord
}
}
You need to redraw your UI, this is done with self.setNeedsDisplay(). It notifies the system that the view's contents needs to be redrawn. In your updateUI() you can add this.
Regarding setNeedsDisplay you can get more information here
class ViewController: UIViewController {
var listOfWords = ["ladybug", "program", "computer", "language", "glorious", "incandescent"]
let incorrectMovesAllowed = 7
var totalWins = 0 {
didSet {
newRound()
}
}
var totalLosses = 0 {
didSet {
newRound()
}
}
#IBOutlet var letterButtons: [UIButton]!
#IBAction func buttonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)!
let letter = Character(letterString.lowercased())
currentGame.playerGuessed(letter: letter)
updateUI()
updateGameState()
}
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var correctWordLabel: UILabel!
#IBOutlet weak var treeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
newRound()
// Do any additional setup after loading the view, typically from a nib.
}
func enableLetterButtons (_enable: Bool){
for button in letterButtons {
button.isEnabled = _enable
}
}
var currentGame : Game!
func newRound() {
if !listOfWords.isEmpty{
let newWord = listOfWords.removeFirst()
currentGame = Game (word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
enableLetterButtons(_enable: true)
updateUI()
} else {
enableLetterButtons (_enable: false)
}
}
func updateUI() {
var letters = [String] ()
for letter in currentGame.formattedWord.characters {
letters.append(String(letter))
}
let wordWithSpacing = letters.joined(separator: " ")
correctWordLabel.text = wordWithSpacing
scoreLabel.text = "Wins: \(totalWins), Losses:\(totalLosses)"
treeImageView.image = UIImage (named: "Tree \(currentGame.incorrectMovesRemaining)")
self.setNeedsDisplay()
}
func updateGameState(){
var letters = [String] ()
for letter in currentGame.word.characters {
letters.append(String(letter))
}
let theAnswer = letters.joined(separator: " ")
if currentGame.incorrectMovesRemaining == 0 {
correctWordLabel.text = theAnswer
Thread.sleep(forTimeInterval: 3)
totalLosses += 1
} else if currentGame.word == currentGame.formattedWord {
totalWins += 1
} else {
updateUI()
}
}
}
Create a variable that will keep track of how many times you have guessed wrong. Then you can do this:
Use a while statement:
while numberOfTimesGuessedWrong <= 7{
}
//when you have guessed incorrectly 7 times, the compiler will move here:
wordLabel.text = "\(correctAnswer)"
So when you guess incorrectly 7 times, on the 8th time, it will then show the correct answer.
I am currently building a calculator app with swift.
I want the calculation to be automatic instead of me pressing = button.
EQLabel is where i want the calculation to be
and inputLabel is where the user can see there equation for example 1 + 5
Below is my calculator code.
// Start of Calculator
#IBOutlet weak var EQLabel: UITextField!
#IBOutlet weak var inputLabel: UITextField!
var numberOnScreen = 0;
var previousNumber = 0;
var performingMath = false
var operation = 0;
#IBAction func numbers(_ sender: UIButton) {
if performingMath == true {
inputLabel.text = String(sender.tag-1)
numberOnScreen = Int(Double(inputLabel.text!)!)
performingMath = false
}
else {
inputLabel.text = String(sender.tag-1)
numberOnScreen = Int(Double(inputLabel.text!)!)
}
}
#IBAction func multiButtons(_ sender: UIButton) {
if inputLabel.text != "" && sender.tag != 15 {
previousNumber = Int(Double(inputLabel.text!)!)
// Plus
if sender.tag == 11 {
inputLabel.text! = "+"
}
// Times
if sender.tag == 12 {
inputLabel.text = "x"
}
// Minus
if sender.tag == 13 {
inputLabel.text = "-"
}
// Divide
if sender.tag == 14 {
inputLabel.text = "/"
}
operation = sender.tag
performingMath = true
}
else if sender.tag == 15 {
if operation == 11 {
EQLabel.text = String(previousNumber + numberOnScreen)
}
if operation == 12 {
EQLabel.text = String(previousNumber * numberOnScreen)
}
if operation == 13 {
EQLabel.text = String(previousNumber - numberOnScreen)
}
if operation == 14 {
EQLabel.text = String(previousNumber / numberOnScreen)
}
}
}
Hope this helps. Should do exactly what you want.
override func viewDidLoad() {
yourTextField.addTarget(self, action: #selector(self.calculateTotal(_:)), forControlEvents: UIControlEvents.EditingChanged)
}
func calculateTotal() {
let totalInt = Int(firstTextField.text!) + Int(secondTextField.text!)
totalLabel.text = String(totalInt)
}
Do let me know if you have any doubts.
Try using addTarget on your button. But your calculator needs to know when you have finished typing in the second number, unless you are only using numbers of a certain length?. If you want it to update the answer as you type id go with something like.
inputLabel.addTarget(self, action: #selector(yourCaculateMethod), for: .editingChanged)
then have your equalsLabel.text equal the result. this will update it as you go.
Id think about naming your inputLabel to inputTextField too as its a little missleading
I'm trying to make a simple rock-paper-scissors game. To do it I used a switch statement but for some reason it doesn't work properly.
This is the structure I thought of to make this little game:
There are three buttons for Rock,Scissors,Paper, and you have to choose one.
There is a Label that tells what the opponent (computer) chose, and I named it opponentLabel.
There is a Label that tells what the result is ("you won" for example) and I named it resultLabel
and it works like this (this just the way it's structured):
var a = Int()
if the player chooses Rock ---> a = 0
if the player chooses Paper ---> a = 1
if the player chooses Scissors ---> a = 2
For the opponent (computer, not a person) there is a randomNumber which
could be 0,1,2, and same here, if 0->opponent chose rock, if
1->opponent chose paper, if 2-> opponent chose scissors
and then I wrote a switch statement that puts it all together.
The problem is that for some reason, when I run the app, if I choose rock everything works fine, but when I choose paper or scissors the results are wrong.
For example if I choose Paper (a = 1) and the opponent has paper (which means that the random number happened to be randomNumber = 1), the resultLabel is not "DRAW" as it would be supposed to be, but it is "You Lost": paper and scissors don't work !! What am I doing wrong?
Here is the full code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var opponentLabel: UILabel!
#IBOutlet weak var resultLabel: UILabel!
#IBOutlet weak var rockButton: UIButton!
#IBOutlet weak var paperButton: UIButton!
#IBOutlet weak var scissorsButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
Hide()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func Hide() {
opponentLabel.hidden = true
resultLabel.hidden = true
}
func unHide() {
opponentLabel.hidden = false
resultLabel.hidden = false
}
var a = Int()
var randomNumber = Int()
func randomChoice() {
randomNumber = Int(arc4random() % 3)
NSLog("randomNumber%ld", randomNumber)
}
func gameOn() {
switch(randomNumber) {
case 0:
opponentLabel.text = "The opponent chose : ROCK"
if a == 0 {
resultLabel.text = "DRAW"
} else {
if a == 1 {
resultLabel.text = "YOU WON!"
}
if a == 2 {
resultLabel.text = "YOU LOST!"
}
}
unHide()
break
case 1:
opponentLabel.text = "The opponent chose: PAPER"
if a == 0 {
resultLabel.text = "YOU LOST!"
} else {
if a == 1 {
resultLabel.text = "DRAW"
}
if a == 2 {
resultLabel.text = "YOU WON!"
}
}
unHide()
break
case 2:
opponentLabel.text = "The opponent chose: SCISSORS"
if a == 0 {
resultLabel.text = "YOU WON!"
} else {
if a == 1 {
resultLabel.text = "YOU LOST!"
}
if a == 2 {
resultLabel.text = "DRAW"
}
}
unHide()
break
default:
break
}
}
#IBAction func rockButton(sender: AnyObject) {
a == 0
randomChoice()
gameOn()
}
#IBAction func paperButton(sender: AnyObject) {
a == 1
randomChoice()
gameOn()
}
#IBAction func scissorsButton(sender: AnyObject) {
a == 2
randomChoice()
gameOn()
}
}
In your #IBAction functions, you are comparing 'a' with 0, 1 or 2 instead of giving 'a' that value.
Change your code so instead of a == 0, it's a = 0. Do this for the 3 #IBActions and try it again and it should work.