A general interface for objects that provide artificial intelligence for use in turn-based (and similar) games.
- iOS 9.1+
- macOS 10.11.2+
- Mac Catalyst 13.0+
- tvOS 9.0+
GameplayKit provides two strategist classes, and you can also use this protocol to implement your own. You provide information about your game model to a strategist by implementing the
GKGame protocols in your custom classes, then use the strategist’s methods to find optimal moves.
Choosing a Strategist
GameplayKit provides two strategist classes:
GKMinmaxclass uses a numeric score for each possible game model state, and performs an exhaustive tree search to find moves that maximize the player’s score while minimizing opponent scores. This strategy can result in optimal gameplay, but requires a scoring method for game models and has a performance cost that increases greatly with game complexity.
GKMonteclass performs a randomized, probabilistic search for winning end states. This strategy doesn’t always choose the best possible move, but is likely to choose good moves, and has a low performance cost even for very complex games. In addition, the Monte Carlo strategy is concerned only with whether a game model state represents a win, so you don’t need to implement a scoring method.
Using a Strategist
Using a strategist in a game requires the following steps:
Choose a strategist class (one that adopts the
GKStrategistprotocol), create an instance of that class, and configure its properties to determine its gameplay behavior.
Point the strategist’s
gameproperty at the instance of your game model class representing the current state of the game in play.
bestmethod to select the best possible move for the current player. This method returns a move object (that is, an instance of the custom class you create to adopt the
Move For Active Player()
Examine the move object to make use of the move selected by the strategist. You created this instance in the
gamemethod of your game model class to describe a possible move in your game, so examining the object gives you the information needed to perform that move.