Where to start with GKMinmaxStrategist?

747 views Asked by At

I was wondering if anyone here has had any luck using GKMinmaxStrategist. This class/feature was showed off at the WWDC, but most of the sample code was in Objective-C, which was a disappointment.

The WWDC videos for GameplayKit featured another game, Stone Flipper (Reversi/Othello), but they haven't published the code (yet?).

Has anyone had any luck with this? I was hoping to try this out with just a simple tic-tac-toe game, but am not at all sure how to start.

2

There are 2 answers

6
TwoStraws On BEST ANSWER

I agree that it's a tricky framework to learn – I just finished writing a tutorial about GameplayKit and GKMinmaxStrategist and it was no mean feat. If you follow the tutorial it builds a complete game from scratch, explaining how it all fits together. You might find it useful as a starting point, at the very least.

I'm hopeful that Apple will improve its documentation before iOS 9 is final!

If you want to dive straight in, here's the least you need to know:

  • Ensure your game model (data) and view (layouts) are kept separate.
  • Make your model implement the NSCopying protocol, because it will be copied many times as the AI runs.
  • You should also make it implement the GKGameModel protocol, which requires that you be able to enumerate the available moves, apply a move on a board copy (virtually, not for real), then judge the players scores afterwards.
  • Each "move" (for whatever that means in your game) needs to conform to the GKGameModelUpdate protocol, so it'll be a class you create that defines a particular move. You'll be given this back when you the best move has been chosen, so it will contain something like "move the knight to E4".
  • If your game does not have a score (in my tutorial I used Four in a Row, which has exactly this problem) then you need to come up with a heuristic estimating roughly how good a move was.
  • Run the AI on a background thread to ensure your UI remains responsive, then push the result back to the foreground thread when you're ready to make UI changes.

If you find the AI is running slowly, either restrict the number of moves it can make or reduce its look ahead depth.

3
CodeSmile On

Here's the GKMinmaxStrategist TicTacToe tutorial in Swift.

This should explain how things work and gives some pointers on how to make a good AI. The strategist surely isn't a template to create any kind of board game AI, it just provides a framework. 95% of the work still rests on your shoulders. ;)

The code is available here. Note that it not only requires Xcode 7 but also OS X 10.11. Though it should be straightforward to adapt to iOS 9.