Swift 2 Counter and reset - swift

I am trying to create a very simple counter where the user taps a button and the text box displays in sequence 1 followed by 2 followed by 3 then resets to 1 and then counts again all using the same button.
My code so far:
class Counter: UIViewController {
var count = 1
#IBOutlet weak var sectors: UITextField!
#IBAction func numberSectors(sender: UIButton) {
if count < 3 {
count+=1
sectors.text = "\(count)"
}
else {
sectors.text = "0"
}
}
}

#IBAction func numberSectors(sender: UIButton) {
if count < 3 {
count += 1
} else {
count = 1
}
sectors.text = "\(count)"
}

Related

Swift var score does not increase

var players : [Player]?
var currentplayerIndex = 0
var currentQuestion : QuestionObject!
var questions = Questions()
var score = 0
var currentQuestionPos = 0
func updateUi() {
if let score = players?[currentplayerIndex].score {
playerPoints.text = "Points: \(score)"
}
}
func loadnextQuestion () {
if(currentQuestionPos < questions.questions.count) {
currentQuestionPos += 1
if currentplayerIndex < players!.count - 1 {
currentplayerIndex += 1
} else {
currentplayerIndex = 0
}
playerTurn.text = (players?[currentplayerIndex].name)
currentQuestion = questions.questions[currentQuestionPos]
questionText.text = currentQuestion.question
}
}
#IBAction func submitButtonPressed(_ sender: UIButton) {
let i = pickerView.selectedRow(inComponent: 0)
if(currentQuestion.answer == i) {
players?[currentplayerIndex].score += 1
loadnextQuestion()
updateUi()
} else {
updateUi()
loadnextQuestion()
}
}
}
My score displays only 0 all the time.
Does not increase when the answer is right.
All the added players get 1 question each but the sore is still 0 for all the players.
Your code doesn't work because you are doing this series of things when the answer is correct:
players?[currentplayerIndex].score += 1
loadnextQuestion()
updateUi()
The player's score is indeed incremented. But notice that the next thing you do is loadnextQuestion(), which increments currentplayerIndex. This causes updateUi to update the label's text to the score of the next player, not of the player that just answered the question correctly.
One way to fix this is to swap the last two lines:
players?[currentplayerIndex].score += 1
updateUi()
loadnextQuestion()
Notice that this is the same order as in the else branch, which you wrote correctly.
This causes the label to always display the score of the last player, which might not be desirable. Assuming there's not like 100 players or something crazy like that, I think it would be a much better UX if you display all the player's scores:
func updateUi() {
if let scores = players?.map({ "\($0.score)" }) {
playerPoints.text = "Points: \(scores.joined(separator: ", "))"
}
}
You can replace the button action work
#IBAction func submitButtonPressed(_ sender: UIButton) {
let i = pickerView.selectedRow(inComponent: 0)
if(currentQuestion.answer == i) {
players?[currentplayerIndex].score += 1
updateUi()
loadnextQuestion()
} else {
updateUi()
loadnextQuestion()
}
}

How to keep track of items answered on in a label?

In my quiz app, if I wanted to keep track of the question number the user was on and display it, how would I do so with my following code? So if the user has answered two questions when the third appears I want it to display "question number 3". Basically I want the user to know what number question they are on and it should be equivalent to the number of questions they've answered plus one.
Here's my code:
import UIKit
class ViewController: UIViewController {
var questionList = [String]()
func updateCounter() {
counter -= 1
questionTimer.text = String(counter)
if counter == 0 {
timer.invalidate()
wrongSeg()
}
}
func randomQuestion() {
//random question
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
}
let rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]
//matching answer values to go with question keys
var choices = QADictionary[questionList[rand]]!
questionList.remove(at: rand)
//create button
var button:UIButton = UIButton()
//variables
var x = 1
rightAnswerBox = arc4random_uniform(4)+1
for index in 1...4
{
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox))
{
button.setTitle(choices[0], for: .normal)
}
else {
button.setTitle(choices[x], for: .normal)
x += 1
}
}
randomImage()
}
let QADictionary = ["Who is Thor's brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"], "What is the name of Thor's hammer?" : ["Mjolinr", "Uru", "Stormbreaker", "Thundara"], "Who is the father of Thor?" : ["Odin", "Sif", "Heimdall", "Balder"]]
//wrong view segue
func wrongSeg() {
performSegue(withIdentifier: "incorrectSeg", sender: self)
}
//proceed screen
func rightSeg() {
performSegue(withIdentifier: "correctSeg", sender: self)
}
//variables
var rightAnswerBox:UInt32 = 0
var index = 0
//Question Label
#IBOutlet weak var questionLabel: UILabel!
//Answer Button
#IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox))
{
rightSeg()
timer.invalidate()
print ("Correct!")
}
if counter != 0 {
counter = 15
}
else if (sender.tag != Int(rightAnswerBox)) {
wrongSeg()
print ("Wrong!")
timer.invalidate()
questionList = []
}
}
override func viewDidAppear(_ animated: Bool)
{
randomQuestion()
questionTimer.text = String(counter)
timer = Timer.scheduledTimer(timeInterval: 1, target:self, selector: #selector(ViewController.updateCounter), userInfo: nil, repeats: true)
}
//variables
var counter = 15
var timer = Timer()
#IBOutlet weak var questionTimer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
Take counter for total number of question globally and update it in random question like
var answerdQuestion = 1;
func randomQuestion() {
//random question
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
}
lblQuestionNumber.text = Strint(answerdQuestion)
answerdQuestion += 1
:
:
}

How stop a loop swift 3

I'm trying to create a ticking noise what continues till you hit the minus button. The only problem I have is that I can't click on the minus button because the plus button stays pressed. It probably stays pressed because of the loop it can't get out of. Already thanks for the answers!
import UIKit
import AVFoundation
import AudioToolbox
import Foundation
class ViewController: UIViewController {
#IBOutlet weak var telLabel: UILabel!
var number = 0
var timeline = "no"
#IBAction func plus(_ sender: Any) {
number += 1
telLabel.text = "\(number)"
timeline = "yes"
tijdlijn()
}
func tijdlijn(){
while timeline == "yes"{
AudioServicesPlaySystemSound(SystemSoundID(1103))
sleep(2)
}
}
/* if timeline = "yes"{
repeat{
AudioServicesPlaySystemSound(SystemSoundID(1103))
sleep(3)
} while timeline == "yes"
*/
//4095
#IBAction func min(_ sender: Any) {
number -= 1
telLabel.text = "\(number)"
timeline = "no"
}
}
I suggest you to use Timer for tasks like this. Try to use this:
#IBOutlet weak var telLabel: UILabel!
var number = 0
var timeline = false
var timer: Timer!
#IBAction func plus(_ sender: Any) {
timeline = !timeline
if timeline {
number += 1
timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(self.tijdlijn), userInfo: nil, repeats: true)
} else {
number -= 1
timer.invalidate()
}
telLabel.text = "\(number)"
}
func tijdlijn(){
AudioServicesPlaySystemSound(SystemSoundID(1103))
}
And use only one action touchupinside - func plus. Remove minus touchupinside action.
You can make timeline a property of your class. And access it by self.timeline. This make it can be accessed in the class. When the timeline become unmatched, the loop will stoped.

Switch for rock-paper-scissors

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.

Expected declaration of a conditional statement

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. :)