[Twisted-Python] Soon to be not-a-newbie?
Nitro
nitro at dr-code.org
Sat Jan 26 09:42:52 EST 2008
Am 26.01.2008, 13:01 Uhr, schrieb Tristan Seligmann
<mithrandi at mithrandi.za.net>:
> In the vast majority of network applications, I believe deferred
> operations are not sequenced in a linear fashion;
Deferreds are not network application specific. They're related to
asynchronous things in general. For example I make good use of them for
some GUI things, too. I have cut and pasted some examples from my code
below.
Examples:
Ex. 1: This waits for things to arrive over network then displays it.
@inlineCallbacks
def onLoadSceneButton(self, evt):
worlds = yield self.app.client.getAvailableWorlds()
dlg = SimpleListBoxDialog(self.gui, worlds)
try:
name = yield dlg.showModal()
except EmptySelectionException:
print 'Not setting a new world!'
else:
self.app.sendEvent( Events.setGameWorld(name) )
Ex. 2: A simple GUI based game where you have to guess a number between 0
and 999
class GuessNumberGame(Minigame.Minigame):
name = 'Guess the number'
@inlineCallbacks
def start(self):
#'Ok. The number I chose is between 0-999. Now you have to guess.
I will'
#'tell you if your number is lower or higher than mine. If you
need more'
#'than 10 attempts you lost.'
player = self.players[0]
number = random.randint(0,999)
won = False
result = ''
for i in range(0,10):
guess = yield player.getNextMove( (i, result) ) # here we wait
for the user to enter something into the GUI
if guess > number:
result = 'too high'
player.setMessage('too high')
elif guess < number:
result = 'too low'
player.setMessage('too low')
else:
won = True
player.setMessage( "You've won! %d was the magic number" %
number )
break
if not won:
player.setMessage( "You've lost! %d was the magic number" %
number )
More information about the Twisted-Python
mailing list