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) {
}
}
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
cashTotalvariable 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 theTimerclass 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 * applemultiplierIf applemultiplier never changes, then that code will set
cashTotalto the same value every time it fires.Don't you really want to add some amount to
cashTotalevery 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 10x2⁶, or 640 dollars. After 10 minutes (30 doublings) you'll have 10*2³⁰, or almost 11 billion dollars.)