我认为您必须使用一些模型结构,您可以在其中添加分数或任何其他数据并轻松操作它:
struct GameData{
var totalScore: Int = 0
var currentGameScore: Int = 0
func invalidateCurrentScore(){
totalScore += currentGameScore
currentGameScore = 0
//call this method when you need to set your current score to 0, and pass all the accumulated points to your total score (f.ex. in the end of the game)
}
//some other data like player's name and etc...
}
您还需要创建一个委托协议,以便在 ShopViewController 中使用其方法并将游戏数据返回给 GameViewController:
protocol ShopViewControllerDelegate{
func updateGameData(by gameData: GameData)
}
带有新部件的 GameViewController:
class GameViewConroller: UIViewController, ShopViewControllerDelegate{
@IBOutlet weak var scoreLabel: UILabel!
var gameData: GameData!
override func viewDidLoad(){
super.viewDidLoad()
gameData = GameData()
updateScoreLabel()
}
private func updateScoreLabel(){ //call it anyTime when you manipulate the score of current game
scoreLabel.text = "Score: \(gameData.currentGameScore)"
}
func updateGameData(by gameData: GameData){ //This is the delegate's method that ShopViewController needs to trigger when you buy something in the shop
self.gameData = gameData
updateScoreLabel()
}
override func prepare(for segue: UIStoryboardSegue,
sender: Any?){
if let shopViewController = segue.destination as? ShopViewController{
//passing game data to ShopViewController
shopViewController.gameData = self.gameData
shopViewController.delegate = self //!IMPORTANT
}
}
}
这些是您的 ShopViewController 应该具有的一些属性和方法:
class ShopViewController{
@IBOutlet weak var totalScoreLabel: UILabel!
var gameData: GameData!
var delegate: ShopViewControllerDelegate?
override func viewDidLoad(){
super.viewDidLoad()
updateTotalScoreLabel()
}
private func updateTotalScoreLabel(){
totalScoreLabel.text = "Total Score: \(gameData.totalScore + gameData.currentGameScore)"
}
private func purchasingSomething(){
//logic of getting price of an item
gameData.currentGameScore -= price
if gameData.currentGameScore < 0{
gameData.totalScore += gameData.currentGameScore
gameData.currentGameScore = 0
//if your current score is less than 0 after some purchase, your total score decreases and the current score becomes 0
}
updateTotalScoreLabel()
delegate?.updateGameData(by gameData: gameData) //Pass refreshed gameData back to the GameViewController
}
}
Swift 也有静态变量,但它非常易于使用。代表带来更多乐趣,并使代码更漂亮。
struct GameData{
static var totalScore: Int = 0
static var currentGameScore: Int = 0
}
祝你好运,与游戏开发者一起玩得开心:)