我目前正在关注The Swift Guy的Tic Tac Toe游戏教程(https://www.youtube.com/watch?v=rD3uqeLdal8),而且我真的遇到了代码问题。
虽然游戏确定是否有平局(平局),但有时当所有空间都被放在棋盘上并且赢得胜利时,游戏会说它真的是一个平局,十字架或者应该获胜。它没有注册胜利。如果有人能帮助我,我将不胜感激。
var activePlayer = 1 //Cross
var gameState = [0, 0, 0, 0, 0, 0, 0, 0, 0]
let winningCombinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
var gameIsActive = true
@IBOutlet weak var label: UILabel!
@IBAction func action(_ sender: AnyObject)
{
if (gameState[sender.tag-1] == 0 && gameIsActive == true)
{
gameState[sender.tag-1] = activePlayer
if (activePlayer == 1)
{
sender.setImage(UIImage(named: "Cross.png"), for: UIControlState())
activePlayer = 2
}
else
{
sender.setImage(UIImage(named: "Nought.png"), for: UIControlState())
activePlayer = 1
}
}
for combination in winningCombinations
{
if gameState[combination[0]] != 0 && gameState[combination[0]] == gameState[combination[1]] && gameState[combination[1]] == gameState[combination[2]]
{
gameIsActive = false
if gameState[combination[0]] == 1
{
label.text = "CROSS HAS WON!"
}
else
{
label.text = "NOUGHT HAS WON!"
}
playAgainButton.isHidden = false
label.isHidden = false
}
}
gameIsActive = false
for i in gameState
{
if i == 0
{
gameIsActive = true
break
}
}
if gameIsActive == false
{
label.text = "IT WAS A DRAW"
label.isHidden = false
playAgainButton.isHidden = false
}
}
答案 0 :(得分:0)
由于获胜组合的数组,我发现获胜检测的代码有点过载。 我在大学的iOS课程上也有同样的任务,并想出了这个。 我的游戏场都设置为0 Player1 = X. Player2 = O
当他们找到这篇文章时,也许它会帮助一些人。
func checkRow(theRow: Int) -> String {
if gameField[theRow][0] != "0" {
let checkThisPlayer: String = gameField[theRow][0]
if gameField[theRow][1] == checkThisPlayer &&
gameField[theRow][2] == checkThisPlayer {
return checkThisPlayer
}
}
return "0"
}
func checkColumn(theColumn: Int) -> String {
if gameField[0][theColumn] != "0" {
let checkThisPlayer: String = gameField[0][theColumn]
if gameField[1][theColumn] == checkThisPlayer &&
gameField[2][theColumn] == checkThisPlayer {
return checkThisPlayer
}
}
return "0"
}
func checkDiagonal() -> String {
if gameField[0][0] != "0" {
let checkThisPlayer: String = gameField[0][0]
if gameField[1][1] == checkThisPlayer &&
gameField[2][2] == checkThisPlayer {
return checkThisPlayer
}
} else if gameField[0][2] != "0" {
let checkThisPlayer: String = gameField[0][2]
if gameField[1][1] == checkThisPlayer &&
gameField[2][0] == checkThisPlayer {
return checkThisPlayer
}
}
return "0"
}
func playerWon() -> String {
//TODO Implement Draw check
var winner: String = "0"
for index in 0...gameField.count - 1 {
winner = checkRow(theRow: index)
if (winner != "0") {
break
}
winner = checkColumn(theColumn: index)
if (winner != "0") {
break
}
}
if winner == "0" {
winner = checkDiagonal()
}
return winner
}