Swift开发井字棋游戏无法重置问题求助
井字棋游戏重置功能失效问题修复
你的重置功能失效的核心原因是未重置currentPlayer变量,同时初始页面加载时缺少对currentPlayer的初始化,导致重置后玩家状态混乱,进而影响后续游戏逻辑。以下是具体修复方案:
修复步骤
- 初始化先手玩家
在viewDidLoad中添加currentPlayer的初始化代码,确保游戏启动时有明确的先手:
override func viewDidLoad() { super.viewDidLoad() loadBoard() currentPlayer = "X" // 设置先手为X }
- 重置玩家状态
在reset函数中,同步重置currentPlayer到初始状态:
func reset() { board.removeAll() loadBoard() currentPlayer = "X" // 恢复初始玩家 for button in buttons { button.setTitle(nil, for: .normal) } }
- 可选优化:修正获胜提示文本
当前whoWins函数中的提示文本使用了player3,逻辑上可以直接用player1(三者已判定相等),让提示更准确:
showAlert(msg: "恭喜 \(player1) 获胜!")
完整修复代码
import UIKit class ViewController: UIViewController { @IBOutlet var buttons: [UIButton]! var currentPlayer = "" var board = [String]() var rules = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]] override func viewDidLoad() { super.viewDidLoad() loadBoard() currentPlayer = "X" // 初始化先手玩家 } @IBAction func buttonPressed(_ sender: UIButton) { guard let index = buttons.index(of: sender) else { return } // 用guard提升代码安全性 if !board[index].isEmpty { return } if currentPlayer == "X" { sender.setTitle("X", for: .normal) currentPlayer = "O" board[index] = "X" } else { sender.setTitle("O", for: .normal) currentPlayer = "X" board[index] = "O" } whoWins() } func whoWins() { for rule in rules { let player1 = board[rule[0]] let player2 = board[rule[1]] let player3 = board[rule[2]] if player1 == player2, player2 == player3, !player1.isEmpty { print("Winner is \(player2)") showAlert(msg: "恭喜 \(player1) 获胜!") return } } if !board.contains("") { showAlert(msg: "平局!") } } func showAlert(msg : String) { let alert = UIAlertController(title: "游戏结束", message: msg, preferredStyle: .alert) let action = UIAlertAction(title: "再来一局", style: .default) { _ in self.reset() } alert.addAction(action) present(alert, animated: true, completion: nil) } func reset() { board.removeAll() loadBoard() currentPlayer = "X" // 重置玩家状态 for button in buttons { button.setTitle(nil, for: .normal) } } func loadBoard(){ for _ in 0..<buttons.count { board.append("") } } }
内容的提问来源于stack exchange,提问作者David Dahl
相关产品推荐
相关产品推荐

