我的代码中包含以下代码main.swift
:
let strategist = GKMinmaxStrategist() strategist.gameModel = position strategist.maxLookAheadDepth = 1 strategist.randomSource = nil let move = strategist.bestMoveForActivePlayer()
... position
我的GKGameModel
子类的实例在哪里Position
.运行此代码后,move
是nil
.bestMoveForPlayer(position.activePlayer!)
也导致nil
(但position.activePlayer!
导致一个Player
对象).
然而,
let moves = position.gameModelUpdatesForPlayer(position.activePlayer!)!
导致非空的可能移动数组.从Apple的文档(关于bestMoveForPlayer(_:)
):
如果玩家无效,玩家不是游戏模型的一部分,或玩家没有有效的移动,则返回nil.
据我所知,这种情况都不是这样,但功能仍然存在nil
.这可能会发生什么?
如果它可以有任何帮助,这是我的GKGameModel
协议的实现:
var players: [GKGameModelPlayer]? = [Player.whitePlayer, Player.blackPlayer] var activePlayer: GKGameModelPlayer? { return playerToMove } func setGameModel(gameModel: GKGameModel) { let position = gameModel as! Position pieces = position.pieces ply = position.ply reloadLegalMoves() } func gameModelUpdatesForPlayer(thePlayer: GKGameModelPlayer) -> [GKGameModelUpdate]? { let player = thePlayer as! Player let moves = legalMoves(ofPlayer: player) return moves.count > 0 ? moves : nil } func applyGameModelUpdate(gameModelUpdate: GKGameModelUpdate) { let move = gameModelUpdate as! Move playMove(move) } func unapplyGameModelUpdate(gameModelUpdate: GKGameModelUpdate) { let move = gameModelUpdate as! Move undoMove(move) } func scoreForPlayer(thePlayer: GKGameModelPlayer) -> Int { let player = thePlayer as! Player var score = 0 for (_, piece) in pieces { score += piece.player == player ? 1 : -1 } return score } func isLossForPlayer(thePlayer: GKGameModelPlayer) -> Bool { let player = thePlayer as! Player return legalMoves(ofPlayer: player).count == 0 } func isWinForPlayer(thePlayer: GKGameModelPlayer) -> Bool { let player = thePlayer as! Player return isLossForPlayer(player.opponent) } func copyWithZone(zone: NSZone) -> AnyObject { let copy = Position(withPieces: pieces.map({ $0.1 }), playerToMove: playerToMove) copy.setGameModel(self) return copy }
如果还有我应该展示的其他代码,请告诉我.