Beispiel #1
0
    def __init__(self, screen_size, resource_path):
        global _game
        _game = self

        self.mode = None
        self.running = False
        self.screen_size = screen_size

        pygame.mixer.pre_init(frequency=44100)
        pygame.init()
        pygame.display.set_caption('After You!')

        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(
            self.screen_size,
            pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE)

        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component(MovementComponent())
        self.component_manager.register_component(ExampleComponent())
        self.component_manager.register_component(AnimationComponent())
        self.component_manager.register_component(DrawComponent())
        self.component_manager.register_component(InputMovementComponent())
        self.component_manager.register_component(DrawHitBoxComponent())
        self.component_manager.register_component(DrawCircleComponent())
        self.component_manager.register_component(SmokeScreenComponent())
        self.component_manager.register_component(PlayerCollisionComponent())
        self.component_manager.register_component(DecoyMovementComponent())
        self.component_manager.register_component(SelfDestructComponent())
        self.component_manager.register_component(SpawnDecoyComponent())
        self.component_manager.register_component(DrawScoreComponent())
        self.component_manager.register_component(MinefieldComponent())
        self.component_manager.register_component(DrawTimerComponent())
        self.component_manager.register_component(UpdateTimerComponent())
        self.component_manager.register_component(SpeedBoostComponent())
        self.component_manager.register_component(ButtonInterpreterComponent())
        self.component_manager.register_component(DrawActionsComponent())
        self.component_manager.register_component(SpawnVortexComponent())
        self.component_manager.register_component(DrawVortextComponent())
        self.component_manager.register_component(GrowVortextComponent())
        self.component_manager.register_component(TrapComponent())
        self.component_manager.register_component(HideComponent())
        self.component_manager.register_component(AIActionComponent())
        self.component_manager.register_component(AIMovementComponent())

        self.entity_manager = EntityManager()

        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('data', LoadEntityData)
        self.resource_manager.register_loader('image', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)

        self.input_manager = InputManager()

        self.renderer = GLRenderer()
        self.renderer.resize(self.screen_size)

        self.view = View([SimpleLayer('draw'), SimpleLayer('ui')])
Beispiel #2
0
 def __init__(self, callback=None):
     if callback is not None:
         self.callback = callback
     self.resourceManager = ResourceManager()
     self.data = {}
     self.items = FormItems(None)
     # Forward to FormItems methods
     self.add = self.items.add
     self.getItemByName = self.items.getItemByName
Beispiel #3
0
    def init(self):
        ResourceManager.loadEverything()
        g.soundEngine = SoundEngine()
        g.soundEngine.loadSounds()

        self.initConfig(g.dataPath + '/config.cfg')

        self.setState(MENU_LOGIN)

        pygame.display.flip()
        self.gameLoop()
        reactor.run()
Beispiel #4
0
    def init(self):
        ResourceManager.loadEverything()
        g.soundEngine = SoundEngine()
        g.soundEngine.loadSounds()

        self.initConfig(g.dataPath + '/config.cfg')

        self.setState(MENU_LOGIN)

        pygame.display.flip()
        self.gameLoop()
        reactor.run()
Beispiel #5
0
    def __init__(self):
        self.width = 800
        self.height = 600
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.running = True
        self.clock = pygame.time.Clock()
        self.state_stack = []
        self.state_stack.append(MainMenuState(self))

        self.resources = ResourceManager()
        self.resources.loadResource("board", "assets/board.png", IMAGE_TYPE)
        self.resources.loadResource("red piece", "assets/red_piece.png", IMAGE_TYPE)
        self.resources.loadResource("black piece", "assets/black_piece.png", IMAGE_TYPE)
Beispiel #6
0
    def __init__(self):
        self.screen_size = (500,500)
        self.map_size = (128,128)
        self.tile_size = (5,5)
        self.world_size = (self.tile_size[0] * self.map_size[0], self.tile_size[1] * self.map_size[1])
        
        self.grid = Grid(self.world_size[0],self.world_size[1])
        GridGenerator(self.grid,Vec2(self.tile_size[0],self.tile_size[1]))
        pygame.init()
        
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((500,500))
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component('MovementComponent', MovementComponent())
        self.component_manager.register_component('ExampleComponent', ExampleComponent())
        self.component_manager.register_component('TileDraw', TileDraw())
        self.component_manager.register_component('InputMovementComponent', InputMovementComponent())

        self.entity_manager = EntityManager()
        
        self.resource_manager = ResourceManager(os.path.join(sys.path[0], 'res'))
        self.resource_manager.register_loader('definition', LoadEntityDefinition)
        self.resource_manager.register_loader('sprite', LoadImage)

        self.input_manager = InputManager()
        self.input_manager.init_joysticks()

        self.entities_to_update = []
        self.entities_to_input = []
        self.entities_to_draw_tiles = []
    def __init__(self, screen_size, resource_path):
        global _game
        _game = self
        
        self.mode = None
        self.running = False
        self.screen_size = screen_size
        
        pygame.mixer.pre_init(frequency=48000)
        pygame.init()
        pygame.display.set_caption("It's All Come to This")
                                   
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(self.screen_size, pygame.DOUBLEBUF | pygame.HWSURFACE)
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_module(component)
        self.component_manager.register_module(event)
        self.component_manager.register_module(locationcomponets)
        
        self.entity_manager = EntityManager()
            
        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('entity', LoadEntityData)
        self.resource_manager.register_loader('image', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)
        self.resource_manager.register_loader('text', LoadText)
        self.resource_manager.register_loader('event', LoadEvent)

        self.input_manager = InputManager()
        self.view = View(pygame.display.get_surface(), [SolidBackgroundLayer((128,192,128,255)), 
                                                        SimpleLayer('draw-location'),
                                                        SimpleLayer('draw-human'), 
                                                        SimpleLayer('draw-ui')])
Beispiel #8
0
Datei: weld.py Projekt: onze/Weld
    def __init__(self, parent=None):
        if Weld.__instance is None:
            Weld.__instance = self
        else:
            raise Exception('can\'t declare new Weld instance. Weld is a singleton.')
        Savable.__init__(self, savepath=os.path.join(user.home, '.weld', 'weld.cache'))
        self.savelist += ['current_project_path']
        # this is used to reload last opened project
        self.current_project_path = None

        Ui(self)

        # setup internal resource handlers
        self.project = None
        
        # list of resources we can ask steel to load
        self.resMan = ResourceManager(os.path.join(Config.instance().weld_data_path, 'resources'))
        self.resMan.attach_to_Ui(Ui.instance().res_browser['library'])

        # entity responsible for behavior trees manipulations
        self.BTMan = BTManager()

        # ready
        Ui.instance().show_status('ready', 1000)
        self.load()
        if Config.instance().on_weld_start_reopen_last_project:
            if self.current_project_path is not None:
                print 'auto reopening project \'%s\'.' % self.current_project_path
                p, f = os.path.split(self.current_project_path)
                self.open_project(self.current_project_path, f)
            else:
                print 'no project to reopen.'
        else:
            print 'skipping project reopening.'
Beispiel #9
0
    def __init__(self, screen_size, resource_path):
        global _game
        _game = self
        
        self.mode = None
        self.running = False
        self.screen_size = screen_size
        
        pygame.mixer.pre_init(frequency=44100)
        pygame.init()
        pygame.display.set_caption('After You!')
                                   
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(self.screen_size, pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE)
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component(MovementComponent())
        self.component_manager.register_component(ExampleComponent())
        self.component_manager.register_component(AnimationComponent())
        self.component_manager.register_component(DrawComponent())
        self.component_manager.register_component(InputMovementComponent())
        self.component_manager.register_component(DrawHitBoxComponent()) 
        self.component_manager.register_component(DrawCircleComponent())
        self.component_manager.register_component(SmokeScreenComponent())
        self.component_manager.register_component(PlayerCollisionComponent())
        self.component_manager.register_component(DecoyMovementComponent())
        self.component_manager.register_component(SelfDestructComponent())
        self.component_manager.register_component(SpawnDecoyComponent())
        self.component_manager.register_component(DrawScoreComponent())
        self.component_manager.register_component(MinefieldComponent())
        self.component_manager.register_component(DrawTimerComponent())
        self.component_manager.register_component(UpdateTimerComponent())
        self.component_manager.register_component(SpeedBoostComponent())
        self.component_manager.register_component(ButtonInterpreterComponent())
        self.component_manager.register_component(DrawActionsComponent())
        self.component_manager.register_component(SpawnVortexComponent())
        self.component_manager.register_component(DrawVortextComponent())
        self.component_manager.register_component(GrowVortextComponent())
        self.component_manager.register_component(TrapComponent())
        self.component_manager.register_component(HideComponent())
        self.component_manager.register_component(AIActionComponent())
        self.component_manager.register_component(AIMovementComponent())
        
        self.entity_manager = EntityManager()
            
        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('data', LoadEntityData)
        self.resource_manager.register_loader('image', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)

        self.input_manager = InputManager()
        
        self.renderer = GLRenderer()
        self.renderer.resize(self.screen_size)
       
        self.view = View([SimpleLayer('draw'), SimpleLayer('ui')])
Beispiel #10
0
    def attach_to_Ui(self):
        """
        Links the level with its views.
        """
        print '<Level \'%s\'>.attach_to_Ui():' % (self.name)

        self.resMan = ResourceManager(self.path, level=self)
        self.resMan.attach_to_Ui(Ui.instance().res_browser['level'])

        self.qsteelwidget = Ui.instance().qsteelwidget
        if self.qsteelwidget.isSteelReady():
            print 'loading now.'
            weld.Weld.instance().on_steel_ready()
        else:
            print 'will wait for steel to be ready before loading.'
            self.qsteelwidget.onSteelReady.connect(
                weld.Weld.instance().on_steel_ready)
        Ui.instance().level_name = self.name
Beispiel #11
0
    def __init__(self, parent=None):
        if Weld.__instance is None:
            Weld.__instance = self
        else:
            raise Exception(
                'can\'t declare new Weld instance. Weld is a singleton.')
        Savable.__init__(self,
                         savepath=os.path.join(user.home, '.weld',
                                               'weld.cache'))
        self.savelist += ['current_project_path']
        # this is used to reload last opened project
        self.current_project_path = None

        Ui(self)

        # setup internal resource handlers
        self.project = None

        # list of resources we can ask steel to load
        self.resMan = ResourceManager(
            os.path.join(Config.instance().weld_data_path, 'resources'))
        self.resMan.attach_to_Ui(Ui.instance().res_browser['library'])

        # entity responsible for behavior trees manipulations
        self.BTMan = BTManager()

        # ready
        Ui.instance().show_status('ready', 1000)
        self.load()
        if Config.instance().on_weld_start_reopen_last_project:
            if self.current_project_path is not None:
                print 'auto reopening project \'%s\'.' % self.current_project_path
                p, f = os.path.split(self.current_project_path)
                self.open_project(self.current_project_path, f)
            else:
                print 'no project to reopen.'
        else:
            print 'skipping project reopening.'
Beispiel #12
0
 def __init__(self, callback=None):
     if callback is not None:
         self.callback = callback
     self.resourceManager = ResourceManager()
     self.data = {}
     self.items = FormItems(None)
     self.errors = FormErrors()
     # Forward to FormItems methods
     self.add = self.items.add
     self.addLast = self.items.addLast
     self.addFirst = self.items.addFirst
     self.addBefore = self.items.addBefore
     self.addAfter = self.items.addAfter
     self.getItemByName = self.items.getItemByName
Beispiel #13
0
    def attach_to_Ui(self):
        """
        Links the level with its views.
        """
        print '<Level \'%s\'>.attach_to_Ui():' % (self.name)

        self.resMan = ResourceManager(self.path, level=self)
        self.resMan.attach_to_Ui(Ui.instance().res_browser['level'])
        
        self.qsteelwidget = Ui.instance().qsteelwidget
        if self.qsteelwidget.isSteelReady():
            print 'loading now.'
            weld.Weld.instance().on_steel_ready()
        else:
            print 'will wait for steel to be ready before loading.'
            self.qsteelwidget.onSteelReady.connect(weld.Weld.instance().on_steel_ready)
        Ui.instance().level_name = self.name
Beispiel #14
0
    def __init__(self, screen_size, resource_path):
        self.mode = None
        self.screen_size = screen_size
        self.map_size = (128,128)
        self.tile_size = (32,32)
        self.world_size = (self.tile_size[0] * self.map_size[0], self.tile_size[1] * self.map_size[1])
        self.world_rooms = (8,8)

        pygame.init()
        
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(self.screen_size)
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component('MovementComponent', MovementComponent())
        self.component_manager.register_component('ExampleComponent', ExampleComponent())
        self.component_manager.register_component('AnimationComponent', AnimationComponent())
        self.component_manager.register_component('DrawComponent', DrawComponent())
        self.component_manager.register_component('InputMovementComponent', InputMovementComponent())
        self.component_manager.register_component('PlayerCollisionComponent', PlayerCollisionComponent())
        self.component_manager.register_component('ZombieAIComponent', ZombieAIComponent())
        self.component_manager.register_component('ZombieAIComponent', ZombieAIComponent())
        self.component_manager.register_component('CarComponent', CarComponent())
        self.component_manager.register_component('DrawHitBoxComponent', DrawHitBoxComponent()) 
        self.component_manager.register_component('AttackComponent', AttackComponent())
        self.component_manager.register_component('ItemComponent', ItemComponent())
        self.component_manager.register_component('InputActionComponent', InputActionComponent())
        self.component_manager.register_component('DeadComponent', DeadComponent())
        self.component_manager.register_component('ZombieCollisionComponent', ZombieCollisionComponent())
        
        self.entity_manager = EntityManager()
            
        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('definition', LoadEntityData)
        self.resource_manager.register_loader('sprite', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)

        self.input_manager = InputManager()
        self.input_manager.init_joysticks()
Beispiel #15
0
class Game:
    def __init__(self):
        self.width = 800
        self.height = 600
        self.screen = pygame.display.set_mode((self.width, self.height))
        self.running = True
        self.clock = pygame.time.Clock()
        self.state_stack = []
        self.state_stack.append(MainMenuState(self))

        self.resources = ResourceManager()
        self.resources.loadResource("board", "assets/board.png", IMAGE_TYPE)
        self.resources.loadResource("red piece", "assets/red_piece.png", IMAGE_TYPE)
        self.resources.loadResource("black piece", "assets/black_piece.png", IMAGE_TYPE)

    def run(self):
        while(self.running):
            self.handleEvents()
            self.update()
            self.render()

            self.clock.tick()

        pygame.quit()

    def handleEvents(self):
        for event in pygame.event.get():
            if(event.type==pygame.QUIT):
                self.running = False
            self.state_stack[-1].handleEvent(event)
        self.state_stack[-1].checkInputs()
        
    def render(self):
        self.state_stack[-1].render()
        
    def update(self):
        self.state_stack[-1].update()
Beispiel #16
0
class Weld(Savable):
    """
    Main class of the editor.
    """
    """application version"""
    version = '0.1.0'

    #singleton
    __instance = None

    def __init__(self, parent=None):
        if Weld.__instance is None:
            Weld.__instance = self
        else:
            raise Exception(
                'can\'t declare new Weld instance. Weld is a singleton.')
        Savable.__init__(self,
                         savepath=os.path.join(user.home, '.weld',
                                               'weld.cache'))
        self.savelist += ['current_project_path']
        # this is used to reload last opened project
        self.current_project_path = None

        Ui(self)

        # setup internal resource handlers
        self.project = None

        # list of resources we can ask steel to load
        self.resMan = ResourceManager(
            os.path.join(Config.instance().weld_data_path, 'resources'))
        self.resMan.attach_to_Ui(Ui.instance().res_browser['library'])

        # entity responsible for behavior trees manipulations
        self.BTMan = BTManager()

        # ready
        Ui.instance().show_status('ready', 1000)
        self.load()
        if Config.instance().on_weld_start_reopen_last_project:
            if self.current_project_path is not None:
                print 'auto reopening project \'%s\'.' % self.current_project_path
                p, f = os.path.split(self.current_project_path)
                self.open_project(self.current_project_path, f)
            else:
                print 'no project to reopen.'
        else:
            print 'skipping project reopening.'

    def BT_export(self):
        """
        Called by the Ui. Exports filesystem BTrees as json files.
        """
        src = os.path.join(self.resMan.base_path,
                           Config.instance().weld_BT_root_folder)
        srcs = self.BTMan.get_subdirs(src)
        dst = os.path.join(self.project.rootdir,
                           Config.instance().weld_BT_root_folder)
        #this operation has lots of exceptions to output...
        try:
            for src in srcs:
                self.BTMan.export(src, dst)
        except Exception, e:
            print >> sys.__stderr, 'ERROR in Weld.BT_export():'
            print >> sys.__stderr, e.args[0]
            print >> sys.__stderr, 'export cancelled (some cleanup might be needed in %s)' % dst
Beispiel #17
0
class Level(Savable):

    def __init__(self, project, name, levelpath):
        """
        Holds material paths and keep the level browser sync with steel.
        params:
        name: level name
        levelpath: root path of resources used in the level (no sharing yet)
        """
        self.project = project
        self.name = name
        self.path = levelpath
        # list of AgentId's (int's)
        self.agents = []
        self.camera_position = QtGui.QVector3D()
        self.camera_rotation = QtGui.QVector4D()
        self.resMan = None
        self.qsteelwidget = None

        Savable.__init__(self, savepath=os.path.join(self.path, self.name + '.lvl.weld'))
        self.savelist += ['camera_position', 'camera_rotation']
        self.resources = {'meshes':[]}


    def __repr__(self):return self.__str__()
    def __str__(self):return '<Level \'%s\'@%s>' % (self.name, self.path)

    def attach_to_Ui(self):
        """
        Links the level with its views.
        """
        print '<Level \'%s\'>.attach_to_Ui():' % (self.name)

        self.resMan = ResourceManager(self.path, level=self)
        self.resMan.attach_to_Ui(Ui.instance().res_browser['level'])
        
        self.qsteelwidget = Ui.instance().qsteelwidget
        if self.qsteelwidget.isSteelReady():
            print 'loading now.'
            weld.Weld.instance().on_steel_ready()
        else:
            print 'will wait for steel to be ready before loading.'
            self.qsteelwidget.onSteelReady.connect(weld.Weld.instance().on_steel_ready)
        Ui.instance().level_name = self.name
        
    def close(self):
        """
        cleanly closes resources taken by the level.
        """
        if self.qsteelwidget:
            self.qsteelwidget.close()

    def instanciate(self, props, already_in=False):
        """
        Make Steel instanciate an object according to the given props.
        If already_in is set to False (default), the object is saved for reload.
        """
        print '<Level \'%s\'>.instanciate():\n%s' % (self.name, pp(props))
        if props['resource_type'] == 'meshes':
            self.resMan.inc_refcount(props)
            modelId = self.qsteelwidget.createOgreModel(props['meshName'] + '.' + props['ext'],
                                                        props['position'],
                                                        props['rotation'],
                                                        not already_in)
            print 'modelId: %(modelId)i' % locals()
            agentId = self.qsteelwidget.createAgent()
            print 'agentId: %(agentId)i' % locals()
            r = self.qsteelwidget.linkAgentToOgreModel(agentId, modelId)
            print 'could link: %s' % r
            props['agentId'] = agentId
            if not already_in:
                self.agents.append(dict(props))
        else:
            print >> sys.__stderr__, 'Level.instanciate(): unknown resource type'

    def on_steel_ready(self, qsteelwidget):
        """
        triggered by the qsteelwidget when steel is ready to process commands.
        """
        self.qsteelwidget = qsteelwidget
        print "<Level %s>.on_steel_ready()" % (self.name)
        self.resMan.qsteelwidget = self.qsteelwidget
        self.qsteelwidget.setLevel(self.project.rootdir, self.name)

        if self.camera_position != QtGui.QVector3D():
            self.qsteelwidget.cameraPosition(self.camera_position)
        if self.camera_rotation != QtGui.QVector4D():
            self.qsteelwidget.cameraRotation(self.camera_rotation)

    def load(self):
        """
        Overloads Savable.load, just to add sync with steel-sided level.
        """
        if self.qsteelwidget is not None:
            self.qsteelwidget.loadLevel()
        Savable.load(self)

    def save(self):
        """
        Retrieve some data before saving them.
        """
        self.camera_position = self.qsteelwidget.cameraPosition()
        self.camera_rotation = self.qsteelwidget.cameraRotation()
        Savable.save(self)
        if self.qsteelwidget.saveCurrentLevel():
            s='%(self)s saved successfuly'
        else:
            s='%(self)s failed to save'
        Ui.instance().show_status(s)
Beispiel #18
0
class Form(AddHelperMixin, object):

    implements(iformal.IForm)

    callback = None
    actions = None

    def __init__(self, callback=None):
        if callback is not None:
            self.callback = callback
        self.resourceManager = ResourceManager()
        self.data = {}
        self.items = FormItems(None)
        self.errors = FormErrors()
        # Forward to FormItems methods
        self.add = self.items.add
        self.getItemByName = self.items.getItemByName

    def addAction(self, callback, name="submit", validate=True, label=None):
        if self.actions is None:
            self.actions = []
        if name in [action.name for action in self.actions]:
            raise ValueError('Action with name %r already exists.' % name)
        self.actions.append(Action(callback, name, validate, label))

    def process(self, ctx):

        request = inevow.IRequest(ctx)
        charset = getPOSTCharset(ctx)

        # Get the request args and decode the arg names
        args = dict([(k.decode(charset), v) for k, v in request.args.items()])

        # Find the callback to use, defaulting to the form default
        callback, validate = self.callback, True
        if self.actions is not None:
            for action in self.actions:
                if action.name in args:
                    # Remove it from the data
                    args.pop(action.name)
                    # Remember the callback and whether to validate
                    callback, validate = action.callback, action.validate
                    break

        # IE does not send a button name in the POST args for forms containing
        # a single field when the user presses <enter> to submit the form. If
        # we only have one possible action then we can safely assume that's the
        # action to take.
        #
        # If there are 0 or 2+ actions then we can't assume anything because we
        # have no idea what order the buttons are on the page (someone might
        # have altered the DOM using JavaScript for instance). In that case
        # throw an error and make it a problem for the developer.
        if callback is None:
            if self.actions is None or len(self.actions) != 1:
                raise Exception(
                    'The form has no callback and no action was found.')
            else:
                callback, validate = self.actions[0].callback, \
                        self.actions[0].validate

        # Remember the args in case validation fails.
        self.errors.data = args

        # Iterate the items and collect the form data and/or errors.
        for item in self.items:
            item.process(ctx, self, args, self.errors)

        if self.errors and validate:
            return self.errors

        def _clearUpResources(r):
            if not self.errors:
                self.resourceManager.clearUpResources()
            return r

        d = defer.maybeDeferred(callback, ctx, self, self.data)
        d.addCallback(_clearUpResources)
        d.addErrback(self._cbFormProcessingFailed, ctx)
        return d

    def _cbFormProcessingFailed(self, failure, ctx):
        e = failure.value
        failure.trap(validation.FormError, validation.FieldError)
        self.errors.add(failure.value)
        return self.errors
Beispiel #19
0
class Game(object):
    
    def __init__(self):
        self.screen_size = (500,500)
        self.map_size = (128,128)
        self.tile_size = (5,5)
        self.world_size = (self.tile_size[0] * self.map_size[0], self.tile_size[1] * self.map_size[1])
        
        self.grid = Grid(self.world_size[0],self.world_size[1])
        GridGenerator(self.grid,Vec2(self.tile_size[0],self.tile_size[1]))
        pygame.init()
        
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((500,500))
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component('MovementComponent', MovementComponent())
        self.component_manager.register_component('ExampleComponent', ExampleComponent())
        self.component_manager.register_component('TileDraw', TileDraw())
        self.component_manager.register_component('InputMovementComponent', InputMovementComponent())

        self.entity_manager = EntityManager()
        
        self.resource_manager = ResourceManager(os.path.join(sys.path[0], 'res'))
        self.resource_manager.register_loader('definition', LoadEntityDefinition)
        self.resource_manager.register_loader('sprite', LoadImage)

        self.input_manager = InputManager()
        self.input_manager.init_joysticks()

        self.entities_to_update = []
        self.entities_to_input = []
        self.entities_to_draw_tiles = []
        
        
    def register_for_updates(self, entity):
        self.entities_to_update.append(entity)
        
    def register_for_input(self, entity):
        self.entities_to_input.append(entity)
    
    def register_for_draw_tiles(self,entity):
        self.entities_to_draw_tiles.append(entity)
        
    def run(self):
        
        
        #test_entity = Entity('test-include')
        character = Entity('character')
        self.characters = [character for m in xrange(4)]
        self.renderer = Render(self)

        
        
        self.current_camera = 0
        while True:
            dt = self.clock.tick() / 1000.0
            for e in pygame.event.get():
                if e.type == pygame.QUIT: sys.exit()
                elif e.type == pygame.KEYDOWN:
                    if e.key == pygame.K_TAB:
                        self.current_camera = (self.current_camera +1)%4
                    if e.key == pygame.K_a:
                        #self.cameras[self.current_camera].props.dx = 1
                        pass
                elif e.type == pygame.KEYUP:
                    if e.key == pygame.K_a:
                        #self.cameras[self.current_camera].props.dx = 0
                        pass
                if e.type == pygame.JOYAXISMOTION or \
                        e.type == pygame.JOYBALLMOTION or \
                        e.type == pygame.JOYBUTTONDOWN or \
                        e.type == pygame.JOYBUTTONUP or \
                        e.type == pygame.JOYHATMOTION or \
                        e.type == pygame.KEYDOWN or \
                        e.type == pygame.KEYUP:
                    event = InputEvent(e)

                    for entity in self.entities_to_update:
                        if e.type == pygame.JOYAXISMOTION:
                            entity.handle('move', event)
                        else:
                            entity.handle('input', event)

            for entity in self.entities_to_draw_tiles:
                entity.handle('draw-tiles',self.world_surface)
            
            for entity in self.entities_to_update:
                entity.handle('update', dt)
            self.renderer.render()
Beispiel #20
0
class Level(Savable):
    def __init__(self, project, name, levelpath):
        """
        Holds material paths and keep the level browser sync with steel.
        params:
        name: level name
        levelpath: root path of resources used in the level (no sharing yet)
        """
        self.project = project
        self.name = name
        self.path = levelpath
        # list of AgentId's (int's)
        self.agents = []
        self.camera_position = QtGui.QVector3D()
        self.camera_rotation = QtGui.QVector4D()
        self.resMan = None
        self.qsteelwidget = None

        Savable.__init__(self,
                         savepath=os.path.join(self.path,
                                               self.name + '.lvl.weld'))
        self.savelist += ['camera_position', 'camera_rotation']
        self.resources = {'meshes': []}

    def __repr__(self):
        return self.__str__()

    def __str__(self):
        return '<Level \'%s\'@%s>' % (self.name, self.path)

    def attach_to_Ui(self):
        """
        Links the level with its views.
        """
        print '<Level \'%s\'>.attach_to_Ui():' % (self.name)

        self.resMan = ResourceManager(self.path, level=self)
        self.resMan.attach_to_Ui(Ui.instance().res_browser['level'])

        self.qsteelwidget = Ui.instance().qsteelwidget
        if self.qsteelwidget.isSteelReady():
            print 'loading now.'
            weld.Weld.instance().on_steel_ready()
        else:
            print 'will wait for steel to be ready before loading.'
            self.qsteelwidget.onSteelReady.connect(
                weld.Weld.instance().on_steel_ready)
        Ui.instance().level_name = self.name

    def close(self):
        """
        cleanly closes resources taken by the level.
        """
        if self.qsteelwidget:
            self.qsteelwidget.close()

    def instanciate(self, props, already_in=False):
        """
        Make Steel instanciate an object according to the given props.
        If already_in is set to False (default), the object is saved for reload.
        """
        print '<Level \'%s\'>.instanciate():\n%s' % (self.name, pp(props))
        if props['resource_type'] == 'meshes':
            self.resMan.inc_refcount(props)
            modelId = self.qsteelwidget.createOgreModel(
                props['meshName'] + '.' + props['ext'], props['position'],
                props['rotation'], not already_in)
            print 'modelId: %(modelId)i' % locals()
            agentId = self.qsteelwidget.createAgent()
            print 'agentId: %(agentId)i' % locals()
            r = self.qsteelwidget.linkAgentToOgreModel(agentId, modelId)
            print 'could link: %s' % r
            props['agentId'] = agentId
            if not already_in:
                self.agents.append(dict(props))
        else:
            print >> sys.__stderr__, 'Level.instanciate(): unknown resource type'

    def on_steel_ready(self, qsteelwidget):
        """
        triggered by the qsteelwidget when steel is ready to process commands.
        """
        self.qsteelwidget = qsteelwidget
        print "<Level %s>.on_steel_ready()" % (self.name)
        self.resMan.qsteelwidget = self.qsteelwidget
        self.qsteelwidget.setLevel(self.project.rootdir, self.name)

        if self.camera_position != QtGui.QVector3D():
            self.qsteelwidget.cameraPosition(self.camera_position)
        if self.camera_rotation != QtGui.QVector4D():
            self.qsteelwidget.cameraRotation(self.camera_rotation)

    def load(self):
        """
        Overloads Savable.load, just to add sync with steel-sided level.
        """
        if self.qsteelwidget is not None:
            self.qsteelwidget.loadLevel()
        Savable.load(self)

    def save(self):
        """
        Retrieve some data before saving them.
        """
        self.camera_position = self.qsteelwidget.cameraPosition()
        self.camera_rotation = self.qsteelwidget.cameraRotation()
        Savable.save(self)
        if self.qsteelwidget.saveCurrentLevel():
            s = '%(self)s saved successfuly'
        else:
            s = '%(self)s failed to save'
        Ui.instance().show_status(s)
Beispiel #21
0
class Game(object):
    
    def __init__(self, screen_size, resource_path):
        self.mode = None
        self.screen_size = screen_size
        self.map_size = (128,128)
        self.tile_size = (32,32)
        self.world_size = (self.tile_size[0] * self.map_size[0], self.tile_size[1] * self.map_size[1])
        self.world_rooms = (8,8)

        pygame.init()
        
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(self.screen_size)
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component('MovementComponent', MovementComponent())
        self.component_manager.register_component('ExampleComponent', ExampleComponent())
        self.component_manager.register_component('AnimationComponent', AnimationComponent())
        self.component_manager.register_component('DrawComponent', DrawComponent())
        self.component_manager.register_component('InputMovementComponent', InputMovementComponent())
        self.component_manager.register_component('PlayerCollisionComponent', PlayerCollisionComponent())
        self.component_manager.register_component('ZombieAIComponent', ZombieAIComponent())
        self.component_manager.register_component('ZombieAIComponent', ZombieAIComponent())
        self.component_manager.register_component('CarComponent', CarComponent())
        self.component_manager.register_component('DrawHitBoxComponent', DrawHitBoxComponent()) 
        self.component_manager.register_component('AttackComponent', AttackComponent())
        self.component_manager.register_component('ItemComponent', ItemComponent())
        self.component_manager.register_component('InputActionComponent', InputActionComponent())
        self.component_manager.register_component('DeadComponent', DeadComponent())
        self.component_manager.register_component('ZombieCollisionComponent', ZombieCollisionComponent())
        
        self.entity_manager = EntityManager()
            
        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('definition', LoadEntityData)
        self.resource_manager.register_loader('sprite', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)

        self.input_manager = InputManager()
        self.input_manager.init_joysticks()
        
    def run(self, mode):
        #pygame.display.toggle_fullscreen()
        self.mode = mode
        self.music = self.resource_manager.get('sound', 'Teamawesome_zombies_LOOP.wav')
        self.music.play(loops=-1)
        self.entity_manager.add_entity(Entity('car'))
        for e in [Entity('character1'), Entity('character2'), Entity('character3'), Entity('character4')]:
            self.entity_manager.add_entity(e)
        self.item_names = ["engine", "gas-can", "radiator", "steering-wheel-2", "tire", "steering-wheel", "toolbox", "tire", "tire", "tire"]

        for i in self.item_names:
            x_pos = (self.world_size[0]/self.world_rooms[0] * randint(0, self.world_rooms[0]-1)) + self.world_size[0]/self.world_rooms[0]/2
            y_pos = (self.world_size[1]/self.world_rooms[1] * randint(0, self.world_rooms[1]-1)) + self.world_size[1]/self.world_rooms[1]/2
            self.entity_manager.add_entity(Entity(i, x=x_pos, y=y_pos))
        
        self.entity_manager.add_entity(Entity('splashscreen'))

        self.renderer = Render(self)

        self.zombies = []
        for _ in range(50):
            x_pos = (self.world_size[0]/self.world_rooms[0] * randint(0, self.world_rooms[0]-1)) + self.world_size[0]/self.world_rooms[0]/2
            y_pos = (self.world_size[1]/self.world_rooms[1] * randint(0, self.world_rooms[1]-1)) + self.world_size[1]/self.world_rooms[1]/2
            self.entity_manager.add_entity(Entity("zombie", x=x_pos, y=y_pos))

        while True:
            dt = self.clock.tick(60) / 1000.0
            
            events = self.input_manager.process_events()
            for event in events:
                if event.target == 'GAME':
                    if event.action == 'QUIT' and event.value > 0:
                        sys.exit()
                    elif event.action == 'FULLSCREEN' and event.value > 0:
                        pygame.display.toggle_fullscreen()
                    elif event.action == 'RELOAD' and event.value > 0:
                        self.resource_manager.clear()
                else:
                    self.mode.handle_event(event)
            
            self.mode.update(dt)
            self.mode.draw()
            
            pygame.display.flip()
            pygame.display.set_caption('fps: %.0d' % self.clock.get_fps())
Beispiel #22
0
class Game(object):
    def __init__(self, screen_size, resource_path):
        global _game
        _game = self

        self.mode = None
        self.running = False
        self.screen_size = screen_size

        pygame.mixer.pre_init(frequency=44100)
        pygame.init()
        pygame.display.set_caption('After You!')

        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(
            self.screen_size,
            pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE)

        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component(MovementComponent())
        self.component_manager.register_component(ExampleComponent())
        self.component_manager.register_component(AnimationComponent())
        self.component_manager.register_component(DrawComponent())
        self.component_manager.register_component(InputMovementComponent())
        self.component_manager.register_component(DrawHitBoxComponent())
        self.component_manager.register_component(DrawCircleComponent())
        self.component_manager.register_component(SmokeScreenComponent())
        self.component_manager.register_component(PlayerCollisionComponent())
        self.component_manager.register_component(DecoyMovementComponent())
        self.component_manager.register_component(SelfDestructComponent())
        self.component_manager.register_component(SpawnDecoyComponent())
        self.component_manager.register_component(DrawScoreComponent())
        self.component_manager.register_component(MinefieldComponent())
        self.component_manager.register_component(DrawTimerComponent())
        self.component_manager.register_component(UpdateTimerComponent())
        self.component_manager.register_component(SpeedBoostComponent())
        self.component_manager.register_component(ButtonInterpreterComponent())
        self.component_manager.register_component(DrawActionsComponent())
        self.component_manager.register_component(SpawnVortexComponent())
        self.component_manager.register_component(DrawVortextComponent())
        self.component_manager.register_component(GrowVortextComponent())
        self.component_manager.register_component(TrapComponent())
        self.component_manager.register_component(HideComponent())
        self.component_manager.register_component(AIActionComponent())
        self.component_manager.register_component(AIMovementComponent())

        self.entity_manager = EntityManager()

        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('data', LoadEntityData)
        self.resource_manager.register_loader('image', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)

        self.input_manager = InputManager()

        self.renderer = GLRenderer()
        self.renderer.resize(self.screen_size)

        self.view = View([SimpleLayer('draw'), SimpleLayer('ui')])

    def run(self, mode):
        p1 = Entity("player1")
        p2 = Entity("player2")
        self.entity_manager.add_entity(p1)
        self.entity_manager.add_entity(p2)
        self.entity_manager.add_entity(Entity("scoreui-player1"))
        self.entity_manager.add_entity(Entity("scoreui-player2"))
        self.entity_manager.add_entity(Entity("actionui-player1"))
        self.entity_manager.add_entity(Entity("actionui-player2"))
        self.entity_manager.add_entity(Entity("timerui"))

        self.renderer.createBackground()

        self.change_mode(mode)
        self.running = True

        self.entity_manager.commit_changes()

        while self.running:
            dt = self.clock.tick(60) / 1000.0

            events = self.input_manager.process_events()
            for event in events:
                if event.target == 'GAME':
                    if event.action == 'QUIT' and event.value > 0:
                        self.running = False
                    elif event.action == 'FULLSCREEN' and event.value > 0:
                        pygame.display.toggle_fullscreen()
                    elif event.action == 'RELOAD' and event.value > 0:
                        self.resource_manager.clear()
                else:
                    self.mode.handle_event(event)

            self.mode.update(dt)
            self.mode.draw()

            self.entity_manager.commit_changes()
            pygame.display.flip()

    def change_mode(self, new_mode):
        if self.mode:
            self.mode.leave()
        self.mode = new_mode
        self.mode.enter()
Beispiel #23
0
class Form(AddHelperMixin, object):

    implements( iformal.IForm )

    callback = None
    actions = None

    def __init__(self, callback=None):
        if callback is not None:
            self.callback = callback
        self.resourceManager = ResourceManager()
        self.data = {}
        self.items = FormItems(None)
        self.errors = FormErrors()
        # Forward to FormItems methods
        self.add = self.items.add
        self.addLast = self.items.addLast
        self.addFirst = self.items.addFirst
        self.addBefore = self.items.addBefore
        self.addAfter = self.items.addAfter
        self.getItemByName = self.items.getItemByName


    def addAction(self, callback, name="submit", validate=True, label=None):
        if self.actions is None:
            self.actions = []
        if name in [action.name for action in self.actions]:
            raise ValueError('Action with name %r already exists.' % name)
        self.actions.append( Action(callback, name, validate, label) )

    def process(self, ctx):

        request = inevow.IRequest(ctx)
        charset = getPOSTCharset(ctx)

        # Get the request args and decode the arg names
        args = dict([(k.decode(charset),v) for k,v in request.args.items()])

        # Find the callback to use, defaulting to the form default
        callback, validate = self.callback, True
        if self.actions is not None:
            for action in self.actions:
                if action.name in args:
                    # Remove it from the data
                    args.pop(action.name)
                    # Remember the callback and whether to validate
                    callback, validate = action.callback, action.validate
                    break

        # IE does not send a button name in the POST args for forms containing
        # a single field when the user presses <enter> to submit the form. If
        # we only have one possible action then we can safely assume that's the
        # action to take.
        #
        # If there are 0 or 2+ actions then we can't assume anything because we
        # have no idea what order the buttons are on the page (someone might
        # have altered the DOM using JavaScript for instance). In that case
        # throw an error and make it a problem for the developer.
        if callback is None:
            if self.actions is None or len(self.actions) != 1:
                raise Exception('The form has no callback and no action was found.')
            else:
                callback, validate = self.actions[0].callback, \
                        self.actions[0].validate

        # Remember the args in case validation fails.
        self.errors.data = args

        def _cbProcessingDone(_):
            if self.errors and validate:
                return self.errors

            def _clearUpResources( r ):
                if not self.errors:
                    self.resourceManager.clearUpResources()
                return r

            d = defer.maybeDeferred(callback, ctx, self, self.data)
            d.addCallback( _clearUpResources )
            d.addErrback(self._cbFormProcessingFailed, ctx)
            return d

        # Iterate the items and collect the form data and/or errors.
        dl = []
        for item in self.items:
            dl.append(defer.maybeDeferred(item.process, ctx, self, args, self.errors))

        d = defer.gatherResults(dl)
        d.addCallback(_cbProcessingDone)
        return d

    def _cbFormProcessingFailed(self, failure, ctx):
        e = failure.value
        failure.trap(validation.FormError, validation.FieldError)
        self.errors.add(failure.value)
        return self.errors
class Game(object):
    
    def __init__(self, screen_size, resource_path):
        global _game
        _game = self
        
        self.mode = None
        self.running = False
        self.screen_size = screen_size
        
        pygame.mixer.pre_init(frequency=48000)
        pygame.init()
        pygame.display.set_caption("It's All Come to This")
                                   
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(self.screen_size, pygame.DOUBLEBUF | pygame.HWSURFACE)
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_module(component)
        self.component_manager.register_module(event)
        self.component_manager.register_module(locationcomponets)
        
        self.entity_manager = EntityManager()
            
        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('entity', LoadEntityData)
        self.resource_manager.register_loader('image', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)
        self.resource_manager.register_loader('text', LoadText)
        self.resource_manager.register_loader('event', LoadEvent)

        self.input_manager = InputManager()
        self.view = View(pygame.display.get_surface(), [SolidBackgroundLayer((128,192,128,255)), 
                                                        SimpleLayer('draw-location'),
                                                        SimpleLayer('draw-human'), 
                                                        SimpleLayer('draw-ui')])
        
    def run(self, mode):
        self.entity_manager.add_entity(Entity('camp'))
        self.entity_manager.add_entity(Entity('report'))
        
        origin = Vec2d(600, 200)
        num_humans = 6
        
        names = self.resource_manager.get('text','names.txt').split('\n')
        
        for i in range(num_humans):
            pos = Vec2d(100,0).rotated(360.0*i/(num_humans)) + origin
            image = random.choice(('male.png', 'female.png'))
            self.entity_manager.add_entity(Entity('human', name=random.choice(names), home_x=pos.x, home_y=pos.y, image=image))
        
        self.entity_manager.add_entity(Entity('mouse'))
        
        self.entity_manager.add_entity(Entity('farm'))
        self.entity_manager.add_entity(Entity('wall'))
        self.entity_manager.add_entity(Entity('well'))
        self.entity_manager.add_entity(Entity('rest-camp'))
        self.entity_manager.add_entity(Entity('work-camp'))
        self.entity_manager.add_entity(Entity('explore'))
        self.entity_manager.add_entity(Entity('infirmary'))
        
        self.entity_manager.add_entity(Entity('construction-site'))
        self.entity_manager.add_entity(Entity('dump'))
        self.entity_manager.add_entity(Entity('hospital'))
        self.entity_manager.add_entity(Entity('rival-camp'))
        self.entity_manager.add_entity(Entity('water-tower'))
        self.entity_manager.add_entity(Entity('forest'))
        
        self.entity_manager.add_entity(Entity("camp"))
        
        self.entity_manager.add_entity(Entity('camp-food-meter-ui'))
        self.entity_manager.add_entity(Entity('camp-defense-meter-ui'))
        self.entity_manager.add_entity(Entity('camp-shelter-meter-ui'))
        self.entity_manager.add_entity(Entity('camp-water-meter-ui'))
        self.entity_manager.add_entity(Entity('camp-medicine-meter-ui'))
        
        self.entity_manager.add_entity(Entity('button'))
        self.entity_manager.add_entity(Entity('info-window'))

        self.entity_manager.commit_changes()
        

        self.change_mode(mode)
        self.running = True

        self.entity_manager.commit_changes()
        
        while self.running:
            dt = self.clock.tick(60) / 1000.0
            
            events = self.input_manager.process_events()
            for event in events:
                if event.target == 'GAME':
                    if event.action == 'QUIT' and event.value > 0:
                        self.running = False
                    elif event.action == 'FULLSCREEN' and event.value > 0:
                        pygame.display.toggle_fullscreen()
                    elif event.action == 'RELOAD' and event.value > 0:
                        self.resource_manager.clear()
                else:
                    self.mode.handle_event(event)
            
            self.mode.update(dt)
            self.mode.draw()
            
            self.entity_manager.commit_changes()
            pygame.display.flip()
            
    def change_mode(self, new_mode):
        print self.mode, '->', new_mode
        if self.mode:
            self.mode.leave()
        self.mode = new_mode
        self.mode.enter()
        self.entity_manager.commit_changes()
Beispiel #25
0
class Game(object):
    
    def __init__(self, screen_size, resource_path):
        global _game
        _game = self
        
        self.mode = None
        self.running = False
        self.screen_size = screen_size
        
        pygame.mixer.pre_init(frequency=44100)
        pygame.init()
        pygame.display.set_caption('After You!')
                                   
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(self.screen_size, pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE)
        
        self.component_manager = componentmanager.ComponentManager()
        self.component_manager.register_component(MovementComponent())
        self.component_manager.register_component(ExampleComponent())
        self.component_manager.register_component(AnimationComponent())
        self.component_manager.register_component(DrawComponent())
        self.component_manager.register_component(InputMovementComponent())
        self.component_manager.register_component(DrawHitBoxComponent()) 
        self.component_manager.register_component(DrawCircleComponent())
        self.component_manager.register_component(SmokeScreenComponent())
        self.component_manager.register_component(PlayerCollisionComponent())
        self.component_manager.register_component(DecoyMovementComponent())
        self.component_manager.register_component(SelfDestructComponent())
        self.component_manager.register_component(SpawnDecoyComponent())
        self.component_manager.register_component(DrawScoreComponent())
        self.component_manager.register_component(MinefieldComponent())
        self.component_manager.register_component(DrawTimerComponent())
        self.component_manager.register_component(UpdateTimerComponent())
        self.component_manager.register_component(SpeedBoostComponent())
        self.component_manager.register_component(ButtonInterpreterComponent())
        self.component_manager.register_component(DrawActionsComponent())
        self.component_manager.register_component(SpawnVortexComponent())
        self.component_manager.register_component(DrawVortextComponent())
        self.component_manager.register_component(GrowVortextComponent())
        self.component_manager.register_component(TrapComponent())
        self.component_manager.register_component(HideComponent())
        self.component_manager.register_component(AIActionComponent())
        self.component_manager.register_component(AIMovementComponent())
        
        self.entity_manager = EntityManager()
            
        self.resource_manager = ResourceManager(resource_path)
        self.resource_manager.register_loader('data', LoadEntityData)
        self.resource_manager.register_loader('image', LoadImage)
        self.resource_manager.register_loader('inputmap', LoadInputMapping)
        self.resource_manager.register_loader('sound', LoadSound)

        self.input_manager = InputManager()
        
        self.renderer = GLRenderer()
        self.renderer.resize(self.screen_size)
       
        self.view = View([SimpleLayer('draw'), SimpleLayer('ui')])
        
    def run(self, mode):
        p1 = Entity("player1")
        p2 = Entity("player2")
        self.entity_manager.add_entity(p1)
        self.entity_manager.add_entity(p2)
        self.entity_manager.add_entity(Entity("scoreui-player1"))
        self.entity_manager.add_entity(Entity("scoreui-player2"))
        self.entity_manager.add_entity(Entity("actionui-player1"))
        self.entity_manager.add_entity(Entity("actionui-player2"))
        self.entity_manager.add_entity(Entity("timerui"))
        
        
        
        self.renderer.createBackground()

        self.change_mode(mode)
        self.running = True

        self.entity_manager.commit_changes()
        
        while self.running:
            dt = self.clock.tick(60) / 1000.0
            
            events = self.input_manager.process_events()
            for event in events:
                if event.target == 'GAME':
                    if event.action == 'QUIT' and event.value > 0:
                        self.running = False
                    elif event.action == 'FULLSCREEN' and event.value > 0:
                        pygame.display.toggle_fullscreen()
                    elif event.action == 'RELOAD' and event.value > 0:
                        self.resource_manager.clear()
                else:
                    self.mode.handle_event(event)
            
            self.mode.update(dt)
            self.mode.draw()
            
            self.entity_manager.commit_changes()
            pygame.display.flip()
            
    def change_mode(self, new_mode):
        if self.mode:
            self.mode.leave()
        self.mode = new_mode
        self.mode.enter()
Beispiel #26
0
Datei: weld.py Projekt: onze/Weld
class Weld(Savable):
    """
    Main class of the editor.
    """

    """application version"""
    version = '0.1.0'
    
    #singleton
    __instance = None

    def __init__(self, parent=None):
        if Weld.__instance is None:
            Weld.__instance = self
        else:
            raise Exception('can\'t declare new Weld instance. Weld is a singleton.')
        Savable.__init__(self, savepath=os.path.join(user.home, '.weld', 'weld.cache'))
        self.savelist += ['current_project_path']
        # this is used to reload last opened project
        self.current_project_path = None

        Ui(self)

        # setup internal resource handlers
        self.project = None
        
        # list of resources we can ask steel to load
        self.resMan = ResourceManager(os.path.join(Config.instance().weld_data_path, 'resources'))
        self.resMan.attach_to_Ui(Ui.instance().res_browser['library'])

        # entity responsible for behavior trees manipulations
        self.BTMan = BTManager()

        # ready
        Ui.instance().show_status('ready', 1000)
        self.load()
        if Config.instance().on_weld_start_reopen_last_project:
            if self.current_project_path is not None:
                print 'auto reopening project \'%s\'.' % self.current_project_path
                p, f = os.path.split(self.current_project_path)
                self.open_project(self.current_project_path, f)
            else:
                print 'no project to reopen.'
        else:
            print 'skipping project reopening.'

    def BT_export(self):
        """
        Called by the Ui. Exports filesystem BTrees as json files.
        """
        src = os.path.join(self.resMan.base_path, Config.instance().weld_BT_root_folder)
        srcs=self.BTMan.get_subdirs(src)
        dst = os.path.join(self.project.rootdir, Config.instance().weld_BT_root_folder)
        #this operation has lots of exceptions to output...
        try:
            for src in srcs:
                self.BTMan.export(src, dst)
        except Exception, e:
            print >> sys.__stderr, 'ERROR in Weld.BT_export():'
            print >> sys.__stderr, e.args[0]
            print >> sys.__stderr, 'export cancelled (some cleanup might be needed in %s)' % dst