iDevGames Forums
Should my board game be multi-threaded? - Printable Version

+- iDevGames Forums (http://www.idevgames.com/forums)
+-- Forum: Development Zone (/forum-3.html)
+--- Forum: Game Programming Fundamentals (/forum-7.html)
+--- Thread: Should my board game be multi-threaded? (/thread-3954.html)



Should my board game be multi-threaded? - Tasnu Arakun - Aug 24, 2006 12:09 PM

I'm working on a board game written in Cocoa/Obj-C. It's not the first time since I have previously helped writing a command line checkers game in Java. I've come to realise that Cocoa behaves slightly different.

I've been thinking of how to structure the game and come to the conclusion that it needs to be multithreaded. Maybe this is just Java talking, but i want a "game loop" like this:

Code:
while( ![ game hasEnded ] ) {
    move = [ player[ turn ] makeMoveForState:[ game state ] ];
    [ game performeMove:move ];
    [ view redraw ];
    turn = ( turn == BLACK ? WHITE : BLACK );
}

In Java this is fine - the game will still accept user input, as well as output information about the current game state. In Cocoa this is a big no since the loop will block the main thread and thus its run-loop. That's why it looks to me as if I need a special "game thread".

To make things more difficult the two players, Ai and Human, behave quite differently from each other.
The AI player performs a series of calculations then returns an answer. Here I'm thinking of starting yet another "AI thread" having the "game thread" periodically poll the AI for an answer.
The human player sits around waiting for user input. In this case I need to put the "game thread" to rest, waking it up when the user has made its choices.

I've written a few arcade games in Cocoa using one or two NSTimers to control physics and graphics. This however is different. So, am I on the right track? Is this the Cocoa way and what tools should I use?


Should my board game be multi-threaded? - OneSadCookie - Aug 24, 2006 01:57 PM

If the AI takes a long time to think, you should put that on a secondary thread. I would *not* put the game loop on a secondary thread. That just unnecessarily complicates matters.

You should be *very* sure you understand the pitfalls of multithreaded programming (no, Java experience doesn't really count; garbage collection alone fixes lots of problems) before you begin. That includes the particular pitfalls of Cocoa (much less is thread-safe than in Java). You'll find documentation on threading Cocoa in your Developer Documentation folder.


Should my board game be multi-threaded? - Tasnu Arakun - Aug 25, 2006 07:14 AM

Okay, I understand. Thanks for the advice.