我在Xcode
创建了一个井字游戏,但需要帮助实现记分板以及显示用户名和当前分数的功能。
我刚刚进入Xcode
,我想了解更多信息,希望得到任何帮助和建议。这就是我所做的。我已经添加了我的整个代码,谢谢:)
import UIKit
class ViewController: UIViewController {
var PlayerTurn = 1 //cross
var BoardStatus = [0, 0, 0, 0, 0, 0, 0, 0, 0,]
var GameisActive = true
let WinningCombos = [[0, 1, 2], [0, 3, 6], [0, 4, 8], [3, 4, 5], [6, 7, 8], [1, 4, 7], [2, 5, 8], [2, 4, 6]]
@IBOutlet weak var Label: UILabel!
@IBAction func action(_ sender: AnyObject)
{
if (BoardStatus[sender.tag-1] == 0 && GameisActive == true)
{
BoardStatus[sender.tag-1] = PlayerTurn
if(PlayerTurn == 1)
{
sender.setImage(UIImage(named: "crossimage.png"), for: UIControlState())
PlayerTurn = 2
}
else
{
sender.setImage(UIImage(named: "noughtimage.png"), for: UIControlState())
PlayerTurn = 1
}
}
for combination in WinningCombos
{
if BoardStatus[combination[0]] != 0 && BoardStatus[combination[0]] == BoardStatus[combination[1]] && BoardStatus[combination[1]] == BoardStatus[combination[2]]
{
GameisActive = false
if BoardStatus[combination[0]] == 1
{
//cross wins
print ("cross")
Label.text = "CROSS HAS WON!"
}
else
{
//Nought has won
print ("nought")
Label.text = "NOUGHTS HAS WON!"
}
PlayAgainButton.isHidden = false
Label.isHidden = false
}
}
GameisActive = false
for i in BoardStatus
{
if i == 0
{
GameisActive = true
break
}
}
if GameisActive == false
{
Label.text = "It was a Draw!"
Label.isHidden = false
PlayAgainButton.isHidden = false
}
}
@IBOutlet weak var PlayAgainButton: UIButton!
@IBAction func PlayAgain(_ sender: Any)
{
BoardStatus = [0, 0, 0, 0, 0, 0, 0, 0, 0]
GameisActive = true
PlayerTurn = 1
PlayAgainButton.isHidden = true
Label.isHidden = true
for i in 1...9
{
let button = view.viewWithTag(i) as! UIButton
button.setImage(nil, for: UIControlState())
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor(red: 184/255, green: 184/255, blue: 184/255, alpha: 1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
要显示当前分数,只需在您的故事链接中添加一个标签,就像您所做的那样:
@IBOutlet weak var Label: UILabel!
建议:尽量命名不那么通用嘿
嘿嘿嘿之后只需使用 .text 属性,但如果您需要此问题的逻辑,swift 可能不是您要查找的主题。
https://freecontent.manning.com/classic-computer-science-problems-in-swift-tic-tac-toe/