Reputation: 110969
After yesterdays poorly chosen question I'm trying again.
I have a tic tac toe program in the works purely for the purpose of learning network play.
My understanding of twisted was that I should have a server class run the reactor and then have each player connect to it as a client (the server being a separate entity). Given the comments in my last question I suspect that I'm going about this in completely the wrong way.
What should I be looking to do and which tutorials or documentation should I be focusing on?
Upvotes: 3
Views: 3383
Reputation: 16326
The difficulty of combining pygame with twisted is the issue of who controls the mainloop. This usually comes up with wanting to combine any sort of UI (GTK, Tkinter, etc) mainloop with Twisted, and PyGame is no different.
What I would suggest, is that since network latency is important and since twisted has a very good scheduling framework, is that you let the twisted reactor run and take control of the mainloop, and then use a LoopingCall to allow you to process events from pygame.
At the very basic:
from twisted.internet.task import LoopingCall
DESIRED_FPS = 30.0 # 30 frames per second
def game_tick():
events = pygame.events.get()
for event in events:
# Process input events
redraw()
# Set up a looping call every 1/30th of a second to run your game tick
tick = LoopingCall(game_tick)
tick.start(1.0 / DESIRED_FPS)
# Set up anything else twisted here, like listening sockets
reactor.run() # Omit this if this is a tap/tac file
While this seems simple at first, it comes with dangers. If you spend a lot of time doing processing in your game tick, then you run the risk of starving the twisted reactor, making it unable to process events. If you need to have timed events, don't block, but instead make use of twisted tools like reactor.callLater
. The more you can avoid blocking, the more responsive your application will be. This is far too many things to describe in a few paragraphs, as programming for twisted is a mindset that really takes some getting used to if you've never done programming for asynchronous or non-blocking libraries.
For a more complete example, check out "gam3" for a game library for interfacing with twisted (including a world clock for simulation events) and a sample game made by one of the twisted developers to show how to integrate twisted and pygame.
Upvotes: 12