Home > Software design >  How do i use timer function properly
How do i use timer function properly

Time:08-24

I have been trying to make an easy incremental game, just to learn, and i couldnt figure out how to use timer to give the user "coins" every second. This question might have been asked a lot but all the solutions tutorials etc i read were too hard/outdated/not valid for my case.

edit: current code

import Foundation
import Darwin
//vars
var copperCoins = 0
var copperGrowth = 1

//intro
print("Simple incremental game!")

print("Copper coins: \(copperCoins)")
//while runs
while true
{
    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
        copperCoins  = copperGrowth
    }
}

CodePudding user response:

Darwin is not needed, and the while loop is not needed either

Create a strong reference to the timer to be able to modify it for example to stop and recreate the timer.

This runs 20 times and then invalidates the timer.

import Foundation

var copperCoins = 0
var copperGrowth = 1

//intro
print("Simple incremental game!")

print("Copper coins: \(copperCoins)")
var timer: Timer?

timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    copperCoins  = copperGrowth
    print(copperCoins)
    if copperCoins >= 20 { timer.invalidate() }
}

CodePudding user response:

First, you've got a forever-loop which creates loads of timers but never uses them - this might not be good. You only need to create it once, then use it.

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    copperCoins  = copperGrowth
    print(copperCoins)
}

Second, a timer needs to be started: timer.fire(), which should go outside.

But the last one - timers are usually used in apps to... time stuff. if you're doing this in a playground or just one script, the code will probably fire the timer once and just stop, since it's finished executing.

This I'm not sure but I think you can use a loop at the end to keep the code going:

while true {
    if copperCoins > 100 { break }
}

At the end, which means your code will only stop once copperCoins reaches 100. Probably not the best way to test timers in playground, but in any case this might be a problem.

Hope this helps.

  • Related