I’m a fairly new coder which is trying to push my limits, I’m trying to make an adventure capalist clone. If you’re not too familiar it’s practically just a tycoon game in the form of a UI. Anyways I’ve gotten stuck on how to get the money to multiple every few seconds.
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var cash: UILabel!
@IBOutlet weak var applePrice: UILabel!
@IBOutlet weak var tomatoPrice: UILabel!
@IBOutlet weak var berryPrice: UILabel!
var cashTotal = 100
var appletotal = 5
var berrytotal = 10
var tomatoTotal = 15
var applemultiplier = 1
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func buyapple(_ sender: Any) {
if cashTotal >= appletotal {
cashTotal = cashTotal - tomatoTotal
applemultiplier = applemultiplier + 1
appletotal = appletotal * applemultiplier
cash.text = "Cash: (cashTotal)"
applePrice.text = "Price: (appletotal)"
}
while 0 == 0 {
sleep(20)
cashTotal = 5 * applemultiplier
cash.text = "(cashTotal)"
}
}
@IBAction func buyberry(_ sender: Any) {
}
@IBAction func buytomato(_ sender: Any) {
}
}
2
Answers
You should edit your question to explain what you mean by "…how to get the money to multiple every few seconds".
It looks like you want to increase the value in your
cashTotal
variable every 20 seconds.You currently use
sleep()
. Don’t ever usesleep()
on the main thread of an interactive app. It causes your entire UI to freeze, and will likely cause the system to think your app has crashed and kill it.You want to create a repeating
Timer
. Take a look at theTimer
class reference, and in particular the methodscheduledTimer(withTimeInterval:repeats:block:)
. That will let you create a repeating timer that fires every X seconds, and invokes the code in a closure that you provide.Your current code, in addition to being used in a never-ending while loop (bad) with a sleep command (bad), also sets
cashTotal = 5 * applemultiplier
If applemultiplier never changes, then that code will set
cashTotal
to the same value every time it fires.Don’t you really want to add some amount to
cashTotal
every time the timer fires? If you multiply it by an amount greater than one, you’ll get exponential growth, which you probably don’t want. (Say you have 10 dollars. Every 20 seconds you multiply that by 2. After 2 minutes (6 doublings) you’ll have 10×2⁶, or 640 dollars. After 10 minutes (30 doublings) you’ll have 10*2³⁰, or almost 11 billion dollars.)This is a great project to learn from, and you’re asking a good question. As others have said, you’ll want to use a timer to update your game state periodically. Add a property to your view controller (or whatever class manages the game):
and set it up when your game starts:
Finally, add a function to actually do the updating:
(You could do the updating right in the closure that the timer runs, but it’s good style to break it out into its own function.)
Now the timer will run
updateGameState()
everyupdateInterval
seconds.