Найти в Дзене

Добавляю в кликер стоимость улучшения

Итак! Теперь мне нужно, чтобы стоимость кнопки улучшения тапов (вместо +1 очка за клик, добавить +2, +3 И так далее)

Задаем соответствующий запрос нейронке, она сама "додумала" то, чего мне не пришло в голову:

Чтобы добавить стоимость для кнопки “Улучшить” и сделать так, чтобы стоимость увеличивалась вдвое после каждой покупки, можно изменить код следующим образом:

  1. Добавить переменную для хранения текущей стоимости улучшения.
  2. Проверить, достаточно ли очков для покупки улучшения.
  3. Списать очки и увеличить стоимость улучшения после каждой покупки.

Собственно код:

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}

// MARK: UISceneSession Lifecycle

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
}

class ViewController: UIViewController {

var scoreLabel: UILabel!
var tapButton: UIButton!
var upgradeButton: UIButton!
var score = 0
var pointsPerTap = 1
var upgradeCost = 10

override func viewDidLoad() {
super.viewDidLoad()

// Настройка метки для отображения очков
scoreLabel = UILabel()
scoreLabel.text = "Очки: \(score)"
scoreLabel.font = UIFont.systemFont(ofSize: 24)
scoreLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scoreLabel)

// Настройка кнопки для тапов
tapButton = UIButton(type: .system)
tapButton.setTitle("Тапни меня!", for: .normal)
tapButton.titleLabel?.font = UIFont.systemFont(ofSize: 24)
tapButton.translatesAutoresizingMaskIntoConstraints = false
tapButton.addTarget(self, action: #selector(tapButtonTapped), for: .touchUpInside)
view.addSubview(tapButton)

// Настройка кнопки для улучшений
upgradeButton = UIButton(type: .system)
upgradeButton.setTitle("Улучшить (+1 очко за тап, стоимость: \(upgradeCost))", for: .normal)
upgradeButton.titleLabel?.font = UIFont.systemFont(ofSize: 24)
upgradeButton.translatesAutoresizingMaskIntoConstraints = false
upgradeButton.addTarget(self, action: #selector(upgradeButtonTapped), for: .touchUpInside)
view.addSubview(upgradeButton)

// Установка ограничений для элементов интерфейса
NSLayoutConstraint.activate([
scoreLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
scoreLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 100),

tapButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
tapButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),

upgradeButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
upgradeButton.topAnchor.constraint(equalTo: tapButton.bottomAnchor, constant: 20)
])
}

@objc func tapButtonTapped() {
score += pointsPerTap
scoreLabel.text = "Очки: \(score)"
}

@objc func upgradeButtonTapped() {
if score >= upgradeCost {
score -= upgradeCost
pointsPerTap += 1
upgradeCost *= 2
scoreLabel.text = "Очки: \(score)"
upgradeButton.setTitle("Улучшить (+1 очко за тап, стоимость: \(upgradeCost))", for: .normal)
} else {
let alert = UIAlertController(title: "Недостаточно очков", message: "Вам нужно больше очков для улучшения!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
}

-2

Работает! Это прекрасно)))

Следующий этап- это добавление "пассивного дохода"

То есть по принципу хомяка: пока ты не в игре, капает небольшое количество очков)

Поехали!