How can I get the game to show the word after all guesses have been used up? - swift

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.

Related

reduce the cell background based on time swift

I would like to make sure that my cell has a background related to the remaining time. in the sense that the closer I get to 0, the more I would like it to be reduced, so that we understand that the timer is about to expire.
according to the elapsed time it automatically reduces from right to left.
this is the code I use in managing the Cell
class TimerCell: UITableViewCell {
#IBInspectable var defaultBackgroundColor: UIColor = .white
#IBInspectable var runningBackgroundColor: UIColor = .white
#IBInspectable var pausedBackgroundColor: UIColor = .white
#IBInspectable var animationDuration: Double = 0
#IBOutlet var timeLabel: UILabel!
#IBOutlet var nameLabel: UILabel!
#IBOutlet var startButton: UIButton!
#IBOutlet var pauseButton: UIButton!
#IBOutlet var stopButton: UIButton!
weak var timer: Timer? {
didSet {
guard let timer = timer else {
updater?.invalidate()
return
}
if case .running = timer.state {
startUpdater()
}
configure(animated: false)
}
}
private weak var updater: Foundation.Timer?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setEditing(_ editing: Bool, animated: Bool) {
print("*** \(Date()) setEditing(\(editing), animated: \(animated)) (timer?.name: \(String(describing: timer?.name)))")
super.setEditing(editing, animated: animated)
configure(animated: animated)
}
func configure(animated: Bool = true) {
guard let timer = timer else {
return
}
UIView.animate(withDuration: animated ? animationDuration : 0) {
guard !self.isEditing else {
self.timeLabel.text = timer.initialTime.hmsString
self.startButton.safelySetIsHidden(true)
self.pauseButton.safelySetIsHidden(true)
self.stopButton.safelySetIsHidden(true)
self.backgroundColor = self.defaultBackgroundColor
return
}
self.timeLabel.text = ceil(timer.timeForState).hmsString
self.nameLabel.text = timer.name
switch timer.state {
case .stopped:
self.stopButton.safelySetIsHidden(true)
self.pauseButton.safelySetIsHidden(true)
self.startButton.safelySetIsHidden(false)
self.backgroundColor = self.defaultBackgroundColor
case .running:
self.startButton.safelySetIsHidden(true)
self.stopButton.safelySetIsHidden( ceil(timer.timeForState) == 0 ? true : false )
self.pauseButton.safelySetIsHidden( ceil(timer.timeForState) == 0 ? true : false )
self.backgroundColor = self.runningBackgroundColor
case .paused:
self.pauseButton.safelySetIsHidden(true)
self.startButton.safelySetIsHidden(false)
self.stopButton.safelySetIsHidden(false)
self.backgroundColor = self.pausedBackgroundColor
}
}
}
#IBAction private func startTimer() {
timer?.state = .running
configure()
startUpdater()
}
#IBAction private func pauseTimer() {
timer?.state = .paused
configure()
}
#IBAction private func stopTimer() {
timer?.state = .stopped
configure()
}
private func startUpdater() {
guard let timer = timer else {
return
}
let date = Date(timeIntervalSinceNow: timer.timeForState.truncatingRemainder(dividingBy: 1))
let updater = Foundation.Timer(fire: date, interval: 1, repeats: true) {
[weak timer] updater in
self.configure()
if timer?.state != .running {
updater.invalidate()
}
}
self.updater = updater
RunLoop.main.add(updater, forMode: .common)
}
}
I think you're after something like this:
That's not trivial to achieve. I did it by adding a CAGradientLayer to the view and animating its locations property. At the same time, I ran the timer to change the label value.
So you might do it that way; you would probably want to tweak the values, of course. This is just a proof-of-concept demo.

Unresolved Identifier 'count'

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()
}

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
:
:
}

AVPlayer loads multiple times before playing - long delay before streaming

I'm facing a very unique situation, AVPlayer is trying to stream a URL that it loads multiple times (I see in control centre) before eventually playing it, after a long delay of about 120 seconds or so (sometimes more). I don't know why that is happening. I use a singleton instance of KDEAudioPlayer - any help would be appreciated.
KDEAudioPlayer Code:
import UIKit
import KDEAudioPlayer
var urlToPlay : NSURL!
var titleTrackBeingPlayed = String?()
class MediaPlayerViewController: FXBlurView, AudioPlayerDelegate {
//MARK: Variables
var seekToTime = NSTimeInterval()
var streaming = true
var timer:NSTimer?
var change:CGFloat = 0.01
//MARK: Connections
#IBOutlet weak var loadingActivityIndicator: UIActivityIndicatorView!
#IBOutlet weak var streamingFromServerLabel: UILabel!
#IBOutlet weak var timelineSlider: UISlider!
#IBOutlet weak var totalTimeLabel: UILabel!
#IBOutlet weak var nowTimeLabel: UILabel!
#IBOutlet weak var toggleButton: UIButton!
#IBOutlet weak var volumeControlSlider: UISlider!
#IBOutlet weak var titleLabel: UILabel!
//MARK: Actions
#IBAction func endTrackPlayerButtonPressed(sender: UIButton) {
//TODO: R&D how to dismiss.
print("media player view to be dismissed")
if let viewWithTag = self.viewWithTag(1089) {
print("Tag 1089")
Singleton.stop()
viewWithTag.removeFromSuperview()
}
}
#IBAction func timelineSliderValueChanged(sender: UISlider) {
Singleton.pause()
Singleton.seekToTime(NSTimeInterval(sender.value))
timelineSlider?.setValue(sender.value, animated: true)
Singleton.resume()
}
#IBAction func playPauseButtonPressed(sender: UIButton) {
toggle()
}
//MARK: Initializer for Class
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
self.tintColor = UIColor.clearColor()
if Singleton.isPlaying {
Singleton.isPlaying = false
}
playerSetup()
toggle()
}
//MARK: Setup for Audio Player
func playerSetup() {
Singleton.playItemWithUrl(urlToPlay)
Singleton.player.delegate = self
timelineSlider?.continuous = true
self.titleLabel?.text = titleTrackBeingPlayed
}
internal func refreshAudioView(_ :NSTimer) {
}
func toggle(){
if Singleton.isPlaying {
pauseTrack()
toggleButton.setImage(UIImage(named: "Play"), forState: .Normal)
}
else if !Singleton.isPlaying {
playTrack()
toggleButton?.setImage(UIImage(named: "Pause"), forState: .Normal)
}
}
func audioPlayer(audioPlayer: AudioPlayer, willStartPlayingItem item: AudioItem) {
titleLabel.text = titleTrackBeingPlayed
}
func audioPlayer(audioPlayer: AudioPlayer, didFindDuration duration: NSTimeInterval, forItem item: AudioItem) {
totalTimeLabel?.text = makeTimeString(Float(duration))
timelineSlider?.maximumValue = Float(duration)
timelineSlider?.minimumValue = 0.0
self.titleLabel?.text = titleTrackBeingPlayed
}
func audioPlayer(audioPlayer: AudioPlayer, didUpdateProgressionToTime time: NSTimeInterval, percentageRead: Float) {
timelineSlider?.setValue(Float(time), animated: true)
nowTimeLabel?.text = makeTimeString(Float(time))
Singleton.player.volume = volumeControlSlider.value
seekToTime = time
}
override func remoteControlReceivedWithEvent(event: UIEvent?) {
if let event = event {
Singleton.player.remoteControlReceivedWithEvent(event)
self.canBecomeFirstResponder()
}
}
func audioPlayer(audioPlayer: AudioPlayer, didChangeStateFrom from: AudioPlayerState, toState to: AudioPlayerState) {
if to == .Playing {
if streaming {
streamingFromServerLabel.hidden = false
loadingActivityIndicator.hidden = true
toggleButton?.setImage(UIImage(named: "Pause"), forState: .Normal)
}
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: #selector(TrackMediaPlayerViewController.refreshAudioView(_:)), userInfo: nil, repeats: true)
}
else if to == .Buffering || to == .WaitingForConnection {
loadingActivityIndicator.hidden = false
}
else {
streamingFromServerLabel.hidden = true
}
}
func playTrack() {
if seekToTime > 0.0 {
Singleton.resume()
} else {
Singleton.play()
}
Singleton.isPlaying = true
}
func pauseTrack() {
Singleton.pause()
Singleton.isPlaying = false
}
//MARK: Convert NSTime to String
func makeTimeString(value:Float) -> String
{
if value == 0 || value.isNaN
{
return "00:00"
}
let hr = (Int)(value / 3600)
let min = (Int)((value % 3600) / 60)
let sec = (Int)((value % 3600) % 60)
let timestamp = String(format:"%d:%02d.%02d", hr, min, sec)
return timestamp
}
}
Singleton Code:
import Foundation
import UIKit
import KDEAudioPlayer
class Singleton: AudioPlayerDelegate {
static let shareInstance = DarsPlayerSingleton()
static let player = AudioPlayer()
static var isPlaying = Bool()
private init (){
}
static func playItemWithUrl(url: NSURL) {
let item = AudioItem(mediumQualitySoundURL: url)
player.playItem(item!)
}
static func play() {
player.resume()
isPlaying = true
}
static func pause() {
player.pause()
isPlaying = false
}
static func stop() {
player.stop()
}
static func seekToTime(time: NSTimeInterval){
player.seekToTime(time)
}
static func resume() {
player.resume()
}
}

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