Attribute error on twisted
This question has already given me the reason WHY this error is happening now I want to know how to solve this issue.
Here is the code for main.py
from twisted.internet import reactor
import pygame
from networking import run, construct_factory
class GameEngine(object):
def __init__(self, client):
pygame.init()
self.screen = pygame.display.set_mode((640, 400))
self.FPS = 60
self.client = client.connectedProtocol
reactor.callWhenRunning(self.grab_all_sprites)
def grab_all_sprites(self):
with open('sprites.txt') as sprites:
for sprite in sprites:
sprite_file = self.client.download_sprite(sprite)
with open(r'resources\%s.png' % sprite, 'wb') as out:
out.write(sprite_file)
def spin(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
reactor.stop()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
print "spacebar!"
#update the player
pygame.display.flip()
reactor.callLater((1/self.FPS), self.spin)
if __name__ in '__main__':
client = construct_factory()
game = GameEngine(client)
run(game, client)
here is the code for networking.py
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from twisted.protocols import amp
import sys
from ampcommands import TransferSprite
class GameClient(amp.AMP):
def download_sp开发者_StackOverflow社区rite(self, sprite):
self.callRemote(TransferSprite, sprite)
class GameClientFactory(ClientFactory):
protocol = GameClient
def buildProtocol(self, address):
proto = ClientFactory.buildProtocol(self, address)
self.connectedProtocol = proto
return proto
def construct_factory():
return GameClientFactory()
def run(game, factory, verbose=True):
if verbose:
from twisted.python import log
log.startLogging(sys.stdout)
reactor.connectTCP("localhost", 1234, factory)
reactor.callWhenRunning(game.spin)
reactor.run()
I have no idea in the slightest how to get game.spin
to be called AFTER the connection is made so that GameClientFactory.connectedProtocol
. I'm getting confused and tired can anyone spot a better way?
This seems like a case where your question is your answer. Remove your existing GameEngine
instantiation code and change your GameClientFactory
to have a buildProtocol
like this:
def buildProtocol(self, address):
proto = ClientFactory.buildProtocol(self, address)
GameEngine(proto).spin()
return proto
Change GameEngine.__init__
to just accept the protocol, too, since it's easier to just pass it in rather than make it an attribute of another object and then pass in that other object.
精彩评论