Alex Rivera | Logout

Coroutines for game design?

Asked 2009-08-08T03:31:01.367
16

I've heard that coroutines are a good way to structure games (e.g., PEP 342: "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.

I see from this article that coroutines can represent states in a state machine which transition to each other using a scheduler, but it's not clear to me how this applies to a game where the game state is changing based on moves from multiple players.

Is there any simple example of a game written using coroutines available? Or can someone offer a sketch of how it might be done?

Edit
Report

2 Answers

10

Coroutines allow for creating large amounts of very-lightweight "microthreads" with cooperative multitasking (i.e. microthreads suspending themselves willfully to allow other microthreads to run). Read up in Dave Beazley's article on this subject.

Now, it's obvious how such microthreads can be useful for game programming. Consider a realtime strategy game, where you have dozens of units - each with a mind of its own. It may be a convenient abstraction for each unit's AI to run as such a microthread in your simulated multitasking environment. This is just one example, I'm sure there are more.

The "coroutine game programming" search on Google seems to bring up interesting results.

answered 2009-08-08T04:35:05.260
7

One way coroutines can be used in games is as light weight threads in an actor like model, like in Kamaelia.

Each object in your game would be a Kamaelia 'component'. A component is an object that can pause execution by yielding when it's allowable to pause. These components also have a messaging system that allows them to safely communicate to each other asynchronously.

All the objects would be concurrently doing their own thing, with messages sent to each other when interactions occur.

So, it's not really specific to games, but anything when you have a multitude of communicating components acting concurrently could benefit from coroutines.

answered 2009-08-08T04:37:30.623

Your Answer