Ejemplo n.º 1
0
    def start(self, firstPlayer):

        self.GameState = 0

        EventManager.notify("GameStarting")

        # move counter init
        self.moveCounter = 0

        # generate fresh state
        self.HexBoard = HexBoard(self.size[0], self.size[1])
        self.HexBoard.setReferenceToGame(self)

        # current player depending on decision
        self._currentPlayer = firstPlayer

        if self.mode == "ki":
            self.KI = MonteCarloTreeSearch(self, 2)  # TODO: ki_player_id == 2?
            # self.KI = HexKI(self.size[0], self.size[1])

        if self.mode == "inter" or self.mode == "machine":

            self.KI = []
            self.KI.append(HexKI(self.size[0], self.size[1]))
            self.KI.append(HexKI(self.size[0], self.size[1]))

            self._currentPlayerType = "ki"

        # if random number wanted, generate one
        if firstPlayer == 0:
            self.chooseFirst()

        EventManager.notify("GameStarted")
Ejemplo n.º 2
0
    def __init__(self, score, time):
        "Initialises resources and start level"

        self.background = pygame.image.load("sprites/sky.jpg")
        self.background.convert()  #for blitting more faster

        self.screen = Constants.SCREEN
        self.score = score
        self.display_items = pygame.sprite.Group()
        self.timeclock = GameTime((0.05, 0.05), time)
        self.display_items.add(self.timeclock, self.score)

        self.time_speed = pygame.time.Clock()
        self.time = 0.0

        self.quit = False
        self.pause = False
        self.start = False
        self.completed = False
        self.gameover = False
        self.message = None

        self.polygon = Polygon(self)
        self.event_manager = EventManager(self)
        self.on_enter()
Ejemplo n.º 3
0
    def callbackVerschiebe(self, event):
        from EventManager import EventManager
        from TimeManager import TimeManager
        if event.keysym == "Return":
            nach = Zeit.fromString(self.text)
            self.unfokusiere()
            self.aktualisiereText(
            )  #setzt den Text auf die gespeicherte Zeit, wird nur überschrieben falls nach passt
            if nach is not None:
                if self.event is not None:
                    EventManager.verschiebeZeitNach(self.event,
                                                    self.istStartzeit(), nach)
                    self.text = nach.text

                    # überprüft ob die Zeit die Start oder Endzeit ist wenn sie einem Event zugeordnet ist
                    assert (self.istStartzeit() or self.istEndzeit())
                    assert not (self.istStartzeit() and self.istEndzeit())
                else:
                    TimeManager.verschiebeZeit(self, nach)
            self.zeichne()
        elif event.keysym == "BackSpace":
            self.text = self.text[:-1]
        elif event.keysym == "Delete":
            self.unfokusiere()
        else:
            self.text += event.char
        self.zeichneMarkiert()
Ejemplo n.º 4
0
    def __init__(self,
                 messageManager,
                 iface,
                 settingsPrefix="/SeismicRisk",
                 organizationName=None,
                 applicationName=None):
        QObject.__init__(self)
        self.msg = messageManager
        self.settings = QSettings(
            organizationName, applicationName
        ) if organizationName and applicationName else QSettings()
        self.dictAutoFields = OrderedDict()
        self.settingsPrefix = settingsPrefix
        self.eventManager = EventManager(self.msg, iface, settingsPrefix)
        self.eventManager.layersAddedCheckIfAutoFields.connect(
            self.checkAndEnableAutoFieldsForLayers)
        self.eventManager.autoFieldsReadyToBeDisabled.connect(
            self.disableAutoFields)
        self.eventManager.attributesAddedCheckIfAutoFields.connect(
            self.checkAndEnableAutoFieldsForLayerFields)
        self.eventManager.attributesDeletedCheckIfAutoFields.connect(
            self.checkAndDisableAutoFieldsForLayer)

        self.eventManager.setAFM(self)

        self.fieldCalculator = FieldCalculator(self.msg, iface)
Ejemplo n.º 5
0
def main():
    ScreenManager.init()
    TM.ladeZeiten()
    EM.ladeEvents()
    ScreenManager.zeichneHintergrund()
    ScreenManager.root.protocol("WM_DELETE_WINDOW", beenden)
    ScreenManager.run()
Ejemplo n.º 6
0
    def receiveMove(self, move):
        
        
        # first store the last move
        self.lastMove = move
        
        # get the vertex the move pointed on
        vertex = self.getVertex(move[1], move[0])
        
        # mark it
        vertex.player = self.Game.currentPlayer()
        
        # first add it to a new group (later on merge them)
        vertex.group = self._groupCounter
        
        # increment the group counter to avoid conflicts
        self._groupCounter = self._groupCounter +1
        
        # the following lines manipulate the groups of
        # vertices at the border of the gameboard
        # red: left 0, right -1
        # blue: top 0, right -1
        
        if self.Game.currentPlayer() == 1:
            if move[1] == 0:
                vertex.group = 0
            if move[1] == self.size[0]-1:
                vertex.group = -1

        else:
            if move[0] == 0:
                vertex.group = 0
            if move[0] == self.size[1]-1:
                vertex.group = -1
            
        # get the adjacent vertices to that one, which is marked
        adjVertices = self.getSurroundingVertices(move[1], move[0])
        
        # any neightbours?:
        if len(adjVertices) > 0:
            
            # put the marked one to the list
            adjVertices.append(vertex)
            
            # only concentrate on the groups
            groups = [x.group for x in adjVertices]
            
            # WIN Condition
            # either within the gameboard
            # or the last vertex marked has been at the borders
            if (-1 in groups and 0 in groups):
                EventManager.notify("GameFinished")
                
            # get the minimum group
            minGroup = min(groups)
                        
            # set all neighbours to the minimum of the group       
            for key, value in self.Vertices.items():
                if value.group in groups:
                    value.group = minGroup
Ejemplo n.º 7
0
def setupEnv():
    em = EventManager()
    em.listVpns()
    em.createVpn(vpnName)
    em.createQ(vpnName, "q1")
    em.addQSubscription(vpnName, "q1", "a/b")
    em.addQSubscription(vpnName, "q1", "d/>")
Ejemplo n.º 8
0
    def test_fire_global(self):
        em = EventManager()
        em.test = Event(test_func)
        em.got_event.add_handler(test_func_global)

        with self.assertRaises(TestError):
            em.test()
Ejemplo n.º 9
0
def main():
    # initializing and drawing background UI elements
    background = UIBox(g_const.screen_size, (0, 0, 0), (0, 0))
    arena = UIBox(g_const.arena_size, (50, 50, 50), g_const.arena_pos)
    sidebar = UIBox(g_const.sidebar_size, (50, 50, 50), g_const.sidebar_pos)
    background.draw()
    sidebar.draw()

    evt_man = EventManager()
    terrain = Terrain()
    game_state = GameState(terrain)

    start = time.time()
    evt_man.start_world_update()

    while True:
        dt = time.time() - start

        if dt >= frame_length:
            start = time.time()  # reset start tick

            events = evt_man.processEvents()  # handle events

            game_state.update(events)  # update game state

            # draw objects
            arena.draw()
            game_state.curr_shape.draw()
            terrain.draw()

            # update display
            pyg.display.update()
Ejemplo n.º 10
0
def beenden():
    EM.speichereEvents()
    TM.speichereZeiten()
    try:
        ScreenManager.root.destroy()
    except:
        exit()
Ejemplo n.º 11
0
    def receiveMove(self, move):

        # first store the last move
        self.lastMove = move

        # get the vertex the move pointed on
        vertex = self.getVertex(move[1], move[0])

        # mark it
        vertex.player = self.Game.currentPlayer()

        # first add it to a new group (later on merge them)
        vertex.group = self._groupCounter

        # increment the group counter to avoid conflicts
        self._groupCounter = self._groupCounter + 1

        # the following lines manipulate the groups of
        # vertices at the border of the gameboard
        # red: left 0, right -1
        # blue: top 0, right -1

        if self.Game.currentPlayer() == 1:
            if move[1] == 0:
                vertex.group = 0
            if move[1] == self.size[0] - 1:
                vertex.group = -1

        else:
            if move[0] == 0:
                vertex.group = 0
            if move[0] == self.size[1] - 1:
                vertex.group = -1

        # get the adjacent vertices to that one, which is marked
        adjVertices = self.getSurroundingVertices(move[1], move[0])

        # any neightbours?:
        if len(adjVertices) > 0:

            # put the marked one to the list
            adjVertices.append(vertex)

            # only concentrate on the groups
            groups = [x.group for x in adjVertices]

            # WIN Condition
            # either within the gameboard
            # or the last vertex marked has been at the borders
            if (-1 in groups and 0 in groups):
                EventManager.notify("GameFinished")

            # get the minimum group
            minGroup = min(groups)

            # set all neighbours to the minimum of the group
            for key, value in self.Vertices.items():
                if value.group in groups:
                    value.group = minGroup
Ejemplo n.º 12
0
    def onUITick(self):

        if not self.Game._pause:
            # notify subscripts
            EventManager.notify("UITick")

        # redo this step every nth seconds
        self.tkInstance.after(200, self.onUITick)
Ejemplo n.º 13
0
 def onUITick(self):
     
     if not self.Game._pause:
         # notify subscripts
         EventManager.notify("UITick")
     
     
     # redo this step every nth seconds
     self.tkInstance.after(200, self.onUITick)
Ejemplo n.º 14
0
 def __init__(self, screenRes=(640, 480)):
     self.running = True
     self.surfaceManager = SurfaceManager(
     )  #Handles the drawing of a scene, managers that have draw functions are added at the bottom of init using .setObjects()
     self.uiManager = UIManager(
     )  #UI managers keep all the buttons and text together, and position them
     self.eventHandlers = EventHandlers()  #Event Handlers
     self.eventManager = EventManager()  #Manages event handlers
     self.surfaceManager.setObjects()  #Sets objects that need drawn
Ejemplo n.º 15
0
 def openPage(self, page):
     
     if page == "menu":
         self._GUIMenu.show()
         self._GUIGameBoard.hide()
     elif page == "game":
         self._GUIMenu.hide()
         self._GUIGameBoard.show()
         EventManager.notify("GameUILoaded")
Ejemplo n.º 16
0
    def test_addEvent(self):
        EM.events = []
        SM.init()
        event1 = Event(Zeit(14, 30), Zeit(15, 00))
        event2 = Event(Zeit(16, 30), Zeit(17, 00))
        event3 = Event(Zeit(14, 45), Zeit(17, 00))
        lsg1 = Event(Zeit(15, 0), Zeit(16, 30))

        EM.addEvent(event1)
        EM.addEvent(event2)
        # hinzufügen ohne Überlapp
        self.assertEqual(
            str(EM.events[0]),
            f"Start 14:30 Ende 15:00 am {EM.events[0].startzeit.erhalteDatum()}"
        )
        self.assertEqual(
            str(EM.events[1]),
            f"Start 16:30 Ende 17:00 am {EM.events[1].startzeit.erhalteDatum()}"
        )

        # mit überlapp
        EM.addEvent(event3)

        self.assertTrue(EM.hatEvent(lsg1))
        self.assertTrue(EM.hatEvent(event1))
        self.assertTrue(EM.hatEvent(event2))
Ejemplo n.º 17
0
 def __init__(self, m, n, game):
     self.size = [m,n]
     self.Game = game
     
     EventManager.subscribe("GameFinished", self.onGameFinished)
     
     self._finished = False
     
     self.targetIterations = 100   
     self.q = 0 
     
     print("MachineGUI loaded")
Ejemplo n.º 18
0
    def __init__(self, m, n, game):
        self.size = [m, n]
        self.Game = game

        EventManager.subscribe("GameFinished", self.onGameFinished)

        self._finished = False

        self.targetIterations = 100
        self.q = 0

        print("MachineGUI loaded")
Ejemplo n.º 19
0
 def entferne(self):
     from EventManager import EventManager
     from ScreenManager import ScreenManager
     self.unfokusiere()
     #rufe entferne für die Zeiten auf, damit diese vom Canvas gelöscht werden können
     self.startzeit.entferne()
     self.endzeit.entferne()
     #entferne das events aus events[]
     EventManager.removeEvent(self)
     #lösche das Event vom Canvas
     for form in self.form:
         ScreenManager.canvas.delete(form)
     self.form = []
Ejemplo n.º 20
0
    def makeMove(self, move):

        # Notify
        EventManager.notify("MoveBegan")

        # if already marked dont do anything
        if self.HexBoard.isMarked(move[1], move[0]):
            EventManager.notify("MoveDenied")

        else:

            # otherwise count the click
            self.moveCounter = self.moveCounter + 1

            # notify Model
            self.HexBoard.receiveMove(move)

            # notify View
            self.changePlayer()
            EventManager.notify("PlayerChanged")

            if not self.isPlayerHuman():
                move = self.KI.getMove()
                self.makeMove(move)

        EventManager.notify("MoveFinished")
Ejemplo n.º 21
0
    def makeMove(self, move):

        # Notify
        EventManager.notify("MoveBegan")

        # if already marked dont do anything
        if self.HexBoard.isMarked(move[0], move[1]):
            EventManager.notify("MoveDenied")
            assert False

        else:

            # otherwise count the click
            self.moveCounter = self.moveCounter + 1

            # notify Model
            self.HexBoard.receiveMove(move)

            if self.mode == "inter":
                self.KI[0].receiveMove(move)
                self.KI[1].receiveMove(move)
            elif self.mode == "ki":
                self.KI.receiveMove(move)

            # notify View
            self.changePlayer()
            EventManager.notify("PlayerChanged")

        EventManager.notify("MoveFinished")
Ejemplo n.º 22
0
 def test_removeElement(self):
     EM.events = []
     event1 = Event(Zeit(11, 30), Zeit(15, 00))
     event2 = Event(Zeit(16, 30), Zeit(22, 00))
     event3 = Event(Zeit(14, 45), Zeit(17, 00))
     EM.addEvent(event1)
     EM.addEvent(event2)
     EM.addEvent(event3)
     EM.removeEvent(event1)
     self.assertIsNone(EM.findeEvent(Zeit(12, 0)))
     self.assertEqual(len(EM.events), 2)
Ejemplo n.º 23
0
    def openPage(self, page):

        if page == "splash":
            self._GUIMenu.hide()
            self._GUIGameBoard.hide()
            self._GUISplashScreen.show()
        elif page == "menu":
            self._GUIMenu.show()
            self._GUIGameBoard.hide()
            self._GUISplashScreen.hide()
        elif page == "game":
            self._GUIMenu.hide()
            self._GUIGameBoard.show()
            self._GUISplashScreen.hide()
            EventManager.notify("GameUILoaded")
Ejemplo n.º 24
0
    def __init__(self, config):
        self.logger = logging.getLogger("SmartHome")
        self.config = config

        httpThreadsNumber = int(config['http_threads_number'])
        self.httpDispatcher = MultiThreadingDispatcher("HttpDispatcher",
                                                       httpThreadsNumber)

        self.httpHandler = HTTPCommandHandler()

        self.httpHandler.setHandler('ping', self.pingHandler)
        self.httpHandler.setHandler('status', self.statusHandler)

        self.videoController = VideoController(config['VideoController'])
        self.videoCommandHandler = VideoCommandHandler(self.videoController)
        self.httpHandler.setHandler('video',
                                    self.videoCommandHandler.handleCommand)

        self.controlManager = ControlManager(config['ControlManager'])
        self.controlCommandHandler = ControlCommandHandler(self.controlManager)
        self.httpHandler.setHandler('control',
                                    self.controlCommandHandler.handleCommand)

        self.sensorManager = SensorManager(config['SensorManager'])
        self.sensorCommandHandler = SensorCommandHandler(self.sensorManager)
        self.httpHandler.setHandler('sensor',
                                    self.sensorCommandHandler.handleCommand)

        self.http_port = int(config['http_port'])
        self.httpServer = DispatchedBackgroundHTTPServer(
            ('', self.http_port), self.httpHandler.getRequestHandlerClass(),
            self.httpDispatcher)
        self.httpServer.allow_reuse_address = True

        self.arduinoController = ArduinoController(config['ArduinoController'])

        self.shellSensorProvider = ShellSensorProvider(
            config['ShellSensorProvider'])
        self.shellControlProvider = ShellControlProvider(
            config['ShellControlProvider'])

        self.eventManager = EventManager(config['EventManager'])
        self.eventCommandHandler = EventCommandHandler(self.eventManager)

        self.shellEventHandlerProvider = ShellEventHandlerProvider(
            config['ShellEventHandlerProvider'])
        self.httpHandler.setHandler('event',
                                    self.eventCommandHandler.handleCommand)
Ejemplo n.º 25
0
Archivo: test.py Proyecto: Qipccc/pyPLC
def test():
    # 实例化监听器
    # listner1 = Listener("thinkroom") #订阅者1
    # listner2 = Listener("steve")     #订阅者2
    gh_port = 8849
    ghclient = GhClient("127.0.0.1", gh_port)

    # 实例化事件操作函数
    eventManager = EventManager()
    eventManager.AddEventListener(EVENT_ARTICAL, ghclient.receiveData)

    #绑定事件和监听器响应函数(新文章)
    # eventManager.AddEventListener(EVENT_ARTICAL, listner1.ReadArtical)
    # eventManager.AddEventListener(EVENT_ARTICAL, listner2.ReadArtical)
    # 启动事件管理器,# 启动事件处理线程
    eventManager.Start()
Ejemplo n.º 26
0
 def borrowBook(self, cloudDB, userName, bookID = -1):
     
     if bookID == -1:
         print('Please enter the ISBN number of the book you want to borrow:')
         bookID = TakeInput.inputInteger(1,cloudDB.getBookQuantity())
     availabale = cloudDB.checkBookStatus(bookID)
     if availabale == False:
         print("Sorry, this book is current not availabale, please borrow another one..")
     else:
         
         borrowDate = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
         returnDate = (datetime.now() + timedelta(days = 7)).strftime("%Y-%m-%d %H:%M:%S")          
         userID = cloudDB.getUserID(userName)           
         bookName = cloudDB.getBookName(bookID)
         eid = EventManager.insert(bookName,userName)
         
         print("")
         print('Book borrow detail')
         print("Borrow Date: "+borrowDate)
         print("Return Date: "+returnDate)
         print("Book detail:")
         cloudDB.printABookDetail(bookID)
         cloudDB.insertBookBorrowed(userID,bookID,borrowDate,eid)
         print("")
         print('Book Borrowed Successfull! Please return it within 7 days!')
         print("")
         
     return
Ejemplo n.º 27
0
    def __init__(self, m, n, Game):
        self.size = [m, n]
        self.Game = Game

        self.screenSize = [800, 600]

        EventManager.subscribe("MoveFinished", self.onMoveFinished)

        # init Tkinter
        self.tkInstance = Tk()

        self._GUISplashScreen = SplashScreenView(self.tkInstance, self)
        self._GUIMenu = MenuView(self.tkInstance, self)
        self._GUIGameBoard = GameView(self.tkInstance, self, Game)

        self._GUIMenu.show()
Ejemplo n.º 28
0
	def __init__(self,score,time):
		"Initialises resources and start level"
		
		self.background=pygame.image.load("sprites/sky.jpg")
		self.background.convert() #for blitting more faster
		
		self.screen=Constants.SCREEN
		self.score = score
		self.display_items = pygame.sprite.Group()
		self.timeclock = GameTime((0.05,0.05),time)		
		self.display_items.add(self.timeclock,self.score)
		
		self.time_speed=pygame.time.Clock()
		self.time=0.0
		
		self.quit = False
		self.pause = False
		self.start = False
		self.completed = False
		self.gameover = False
		self.message = None
		
		self.polygon=Polygon(self)
		self.event_manager = EventManager(self)
		self.on_enter()
Ejemplo n.º 29
0
 def __init__(self, m, n, Game):
     self.size = [m,n]
     self.Game = Game
     
     self.screenSize = [800, 600]
     
     EventManager.subscribe("MoveFinished", self.onMoveFinished)
     
     # init Tkinter
     self.tkInstance = Tk()
     
     self._GUISplashScreen = SplashScreenView(self.tkInstance, self)
     self._GUIMenu = MenuView(self.tkInstance, self)
     self._GUIGameBoard = GameView(self.tkInstance, self, Game)
     
     
     self._GUIMenu.show()
Ejemplo n.º 30
0
def main():
    pg.init()
    ev_manager = EventManager()
    model      = GameEngine(ev_manager)
    controller = Controller(ev_manager, model)
    view       = GraphicalView(ev_manager, model)

    model.run()
Ejemplo n.º 31
0
class Scene(object):
    """A scene is like a level, or one section of the program. There will be an intro scene, the sokoban scene and an ending scene displaying the users score. This is a TEMPLATE class"""
    def __init__(self, screenRes=(640, 480)):
        self.running = True
        self.surfaceManager = SurfaceManager(
        )  #Handles the drawing of a scene, managers that have draw functions are added at the bottom of init using .setObjects()
        self.uiManager = UIManager(
        )  #UI managers keep all the buttons and text together, and position them
        self.eventHandlers = EventHandlers()  #Event Handlers
        self.eventManager = EventManager()  #Manages event handlers
        self.surfaceManager.setObjects()  #Sets objects that need drawn

    #events are handled and draw managers draw to main display
    def run(self, surface, events):
        #Events
        self.eventManager.run(events)
        #Draw
        self.surfaceManager.draw()
Ejemplo n.º 32
0
 def __init__(self, m, n, Game):
     self.size = [m,n]
     self.Game = Game
     
     self.screenSize = [800, 600]
     
     EventManager.subscribe("MoveFinished", self.onMoveFinished)
     
     # init Tkinter
     self.tkInstance = Tk()
     self.tkInstance.title("HexGame by Daniel, Jannis and Mats")
     self.tkInstance.after(1000, self.onUITick)
     
     self._GUIMenu = MenuView(self.tkInstance, self)
     self._GUIGameBoard = GameView(self.tkInstance, self, Game)
     
     
     self._GUIMenu.show()
Ejemplo n.º 33
0
    def start(self, firstPlayer):

        EventManager.notify("GameStarting")

        # move counter init
        self.moveCounter = 0

        # generate fresh state
        self.HexBoard = HexBoard(self.size[0], self.size[1])
        self.HexBoard.setReferenceToGame(self)

        # current player depending on decision
        self._currentPlayer = firstPlayer

        # if random number wanted, generate one
        if firstPlayer == 0:
            self.chooseFirst()

        EventManager.notify("GameStarted")
Ejemplo n.º 34
0
 def handle_raw_event(self, event):
     result = '\t' + pygame.event.event_name(event.type)
     if EventManager.is_keyboard_event(event.type):
         result += '\t' + pygame.key.name(event.key)
     elif event.type in EventManager.JOYSTICK_BUTTON_EVENTS:
         result += '\t' + str(event.button)
     elif event.type in EventManager.JOYSTICK_AXIS_EVENTS:
         result += '\tjoy: ' + \
             str(event.joy) + '\taxis: ' + str(event.axis) + \
             '\tvalue: ' + '%.3f' % (event.value)
     elif event.type in EventManager.JOYSTICK_HAT_EVENTS:
         result += '\tjoy: ' + \
             str(event.joy) + '\that: ' + str(event.hat) + \
             '\tvalue: ' + str(event.value)
     elif EventManager.is_joystick_event(event.type):
         result = '\t' + str(event)
     else:
         return
     print result
Ejemplo n.º 35
0
 def start(self, firstPlayer):
     
     EventManager.notify("GameStarting")
     
     # move counter init
     self.moveCounter = 0
     
     # generate fresh state
     self.HexBoard = HexBoard(self.size[0], self.size[1])
     self.HexBoard.setReferenceToGame(self)
     
     # current player depending on decision
     self._currentPlayer = firstPlayer
     
     # if random number wanted, generate one
     if firstPlayer == 0:
         self.chooseFirst()
     
     EventManager.notify("GameStarted")
Ejemplo n.º 36
0
    def run_app(self):
        print('gui')
        Process(target=gui.run_app,
                args=(self.cfg, self.GuiRecvMsg, self.CtrlRecvMsg)).start()

        print('ctrl')
        # Process(target = Controller.run_app, args = ( self.cfg, self.GuiRecvMsg, self.CtrlRecvMsg )).start()
        funMap = ServiceEvent(self.cfg, self.GuiRecvMsg)
        handlers = ['tumblr', 'sys']
        EventManager(self.CtrlRecvMsg, handlers, funMap).Start()
        print('exitApp')
Ejemplo n.º 37
0
    def test_findeEvent(self):
        EM.events = []
        event1 = Event(Zeit(14, 30), Zeit(15, 00))
        event2 = Event(Zeit(16, 30), Zeit(17, 00))
        event3 = Event(Zeit(14, 45), Zeit(17, 00))

        EM.addEvent(event1)
        EM.addEvent(event2)
        EM.addEvent(event3)

        lsg1 = EM.findeEvent(Zeit(14, 45))
        lsg2 = EM.findeEvent(Zeit(15, 00))
        lsg3 = EM.findeEvent(Zeit(16, 30))

        self.assertEqual(event1, lsg1)
        self.assertEqual(event3, lsg2)
        self.assertEqual(event2, lsg3)
Ejemplo n.º 38
0
    def __init__(self, m, n):

        self.size = [m, n]

        # subscribe to certain events
        EventManager.subscribe("GameFinished", self.onGameFinished)

        # keep track, increment on each added vertex
        self._groupCounter = 2

        # bool to determine machine state
        self._finished = False

        # dictionary for all vertices
        self.Vertices = {}

        for i in range(m):
            for j in range(n):
                # add Hexagon instance to the dict
                # with key => i;j
                self.Vertices[str(i) + "," + str(j)] = Hexagon(i, j)
Ejemplo n.º 39
0
 def __init__(self, m, n):
     
     self.size = [m, n]
     
     # subscribe to certain events
     EventManager.subscribe("GameFinished", self.onGameFinished)
     
     # keep track, increment on each added vertex
     self._groupCounter = 2
     
     # bool to determine machine state
     self._finished = False
     
     # dictionary for all vertices
     self.Vertices = {}
     
     for i in range(m):
         for j in range(n):
             # add Hexagon instance to the dict
             # with key => i;j
             self.Vertices[str(i) + "," + str(j)] = Hexagon(i, j)
Ejemplo n.º 40
0
    def callbackRightClick(clickEvent):
        from EventManager import EventManager
        from TimeManager import TimeManager
        from Event import Event

        if ScreenManager.ausgewaehlt is not None:  # auswahl für altes Element aufheben
            ScreenManager.ausgewaehlt.zeichne()
            ScreenManager.ausgewaehlt.unfokusiere()

        pixel = (clickEvent.x, clickEvent.y)
        # x_root ist realtiv zum canvas

        zeit = ScreenManager.pixelZuZeit(pixel[1]).runde(
            TimeManager.genauigkeit)  # ausgewählte Zeit, gerundet
        event = EventManager.findeEvent(zeit)
        if event is not None:
            pause = EventManager.addPause(zeit, EventManager.pausenLaenge)
            pause.zeichne()
            ScreenManager.ausgewaehlt = pause.endzeit
            ScreenManager.ausgewaehlt.zeichneMarkiert()
            ScreenManager.ausgewaehlt.fokusiere()
Ejemplo n.º 41
0
 def __init__(self, m, n, mode):
     
     # init all events
     EventManager.initEvents()
     
     EventManager.subscribe("GameFinished", self.onGameFinished)
     EventManager.subscribe("GameStarted", self.onGameStarted)
     
     # save size and mode
     self.size = [m,n]
     self.mode = mode
     
     # just to init the value
     self._currentPlayer = 1
     
     # instantiate model and view
     self.HexBoard = HexBoard(self.size[0], self.size[1])
     self.HexBoard.setReferenceToGame(self)
     
     if self.UIRequired():
         self.HexGUI = HexGUI(self.size[0], self.size[1], self)
     else:
         self.MachineGUI = MachineGUI(self.size[0], self.size[1], self)
     
     # set the game to entry point
     self.start(self._currentPlayer)
     
     if self.UIRequired():
         # main loop starts for event receiving
         self.HexGUI.mainloop()
     
     if self.UIRequired() == False:
         self.MachineGUI.gameLoop()
Ejemplo n.º 42
0
 def __init__( self, messageManager, iface, settingsPrefix="/AutoFields", organizationName=None, applicationName=None ):
     QObject.__init__( self )
     self.msg = messageManager
     self.settings = QSettings( organizationName, applicationName ) if organizationName and applicationName else QSettings()
     self.dictAutoFields = OrderedDict()
     self.settingsPrefix = settingsPrefix
     self.eventManager = EventManager( self.msg, iface, settingsPrefix )
     self.eventManager.layersAddedCheckIfAutoFields.connect( self.checkAndEnableAutoFieldsForLayers )
     self.eventManager.autoFieldsReadyToBeDisabled.connect( self.disableAutoFields )
     self.eventManager.attributesAddedCheckIfAutoFields.connect( self.checkAndEnableAutoFieldsForLayerFields )
     self.eventManager.attributesDeletedCheckIfAutoFields.connect( self.checkAndDisableAutoFieldsForLayer )
     
     self.eventManager.setAFM( self )
     
     self.fieldCalculator = FieldCalculator( self.msg, iface )
Ejemplo n.º 43
0
    def __init__(self, videoMode=sf.VideoMode(800, 600, 32), \
            title="window", parent=0, framerateLimit=60,\
            backgroundColor = sf.Color.BLACK, backgroundImage = Image()):

        sf.RenderWindow.__init__(self, videoMode, title)
        Render.__init__(self, parent, sf.Rectangle(sf.Vector2(),\
                videoMode.size), backgroundColor, backgroundImage)

        self._isStaticToView = False
        self.position = (0,0)
        self.framerate_limit = framerateLimit
        self._framerate = framerateLimit
        self._event = EventManager(self)
        self.resetView()
        self.clear(backgroundColor)
Ejemplo n.º 44
0
    def __init__(self,arguments):
        self.debug = False
        self.capturing = False
        self.captureFPSWait = 0
        self.running = True
        self.fullscreen = False
        self.paused = False
        self.cachedScenes = {}
        self.currentScene = None
        self.currentElement = None
        self.currentWindow = None
        self.currentWidget = None
        
        self.values = {}

        self.Loader = Loader(self)
        self.setupScreen()
        self.setupAudio()
        self.displayTitle()
        self.Loader.preload()

        self.TitleManager = TitleManager(self)
        self.Cursor = Cursor(self)
        self.Renderer = Renderer(self)
        self.AudioController = AudioController(self)
        
        
        self.Inventory = Inventory(self)
        self.TopicMenu = TopicMenu(self)

        self.ScriptManager = ScriptManager(self)
        self.Player = Player(self)
        self.EventManager = EventManager(self)
        self.parseArguments(arguments)

        self.loadScene("blacksmith")
        self.run()
Ejemplo n.º 45
0
 def onGameFinished(self):
     if not self._eventsSuppressed:
         EventManager.notify("GameFinished")
     self._finished = True
Ejemplo n.º 46
0
	def __init__(self):
		EventManager.__init__(self)
Ejemplo n.º 47
0
 def onGameFinished(self):
     EventManager.notify("GameFinished")
     self._finished = True
Ejemplo n.º 48
0
 def __init__(self):
     """ Constructor of an output pin. This constructor takes a referece to
         the event-manager. """
     self._d_inputs = list()
     self._d_event_manager = EventManager()
     self._d_logger = logging.getLogger("edef.core")
Ejemplo n.º 49
0
class Battle:

    def __init__(self):
        self.attackers_list = [];
        self.defenders_list = [];
        self.frame = 0;
        self.msg_manager = MsgManager();
        self.event_manager = EventManager();

    def add_msg(self,msg):
        self.msg_manager.add_msg(msg);

    """
        战斗中的存活对象执行自己的操作
    """
    def execute_actors(self):
        alive_attack_actors = list(Battle.get_all_alive(self.attackers_list));
        alive_defend_actors = list(Battle.get_all_alive(self.defenders_list));

        for attacker in alive_attack_actors:
            attacker.run();
        for defender in alive_defend_actors:
            defender.run();

    def add_event(self,event):
        self.event_manager.get_event_list_by_key(event.event_type).append(event);

        """
        让怪物进入战场
    """
    def enter_battle(self,monsters,is_attackers):
        if is_attackers:
            self.attackers_list.extend(monsters);
        else:
            self.defenders_list.extend(monsters);

    @staticmethod
    def is_one_side_all_dead(side_list):
        for one in side_list:
            if one.hp > 0:
                    return False;
        return True;

    """
        检查比赛是否真的结束了
    """
    def is_end(self):
        if Battle.is_one_side_all_dead(self.defenders_list):
            self.msg_manager.add_msg("defenders all dead");
            return True;
        if Battle.is_one_side_all_dead(self.attackers_list):
            self.msg_manager.add_msg("attackers all dead");
            return True;
        return False;


    @staticmethod
    def get_all_alive(monster_list):
        return filter(lambda  attack:attack.hp > 0, monster_list);

    def do_one_frame(self):
        self.msg_manager.clear_one_round_msg();
        # 处理帧开始的事件,例如时间注册函数(buff到期,dot的执行和到期)
        self.event_manager.handle_event_list(EventManager.FRAME_EVENT_KEY);

        if self.is_end():
            print(self.msg_manager.send_msg());
            self.msg_manager.send_msg();
            return False;

        #执行玩家操作
        self.execute_actors();

        if self.is_end():
            self.msg_manager.send_msg();
            self.msg_manager.send_msg();
            return False;

        # 处理玩家操作使得使用的技能的事件
        self.event_manager.handle_event_list(EventManager.ACTION_EVENT_KEY);

        # 处理技能释放出来未经过处理的伤害增益buff等
        self.event_manager.handle_event_list(EventManager.FILTER_EFFECT_EVENT_KEY);

        # 处理实际最后增减释放过的伤害buff等
        self.event_manager.handle_event_list(EventManager.REAL_EFFECT_EVENT_KEY);

        if self.is_end():
            self.msg_manager.send_msg();
            self.msg_manager.send_msg();
            return False;
        self.msg_manager.send_msg();
        print("frame" + str(self.frame) + ":===================")
        time.sleep(2);
        return True;

    def all_run(self):
        while self.do_one_frame():
            self.frame += 1;
Ejemplo n.º 50
0
class Window(Render, sf.RenderWindow):
    """This class create a window
    Cette classe créé une fenêtre"""

    def __init__(self, videoMode=sf.VideoMode(800, 600, 32), \
            title="window", parent=0, framerateLimit=60,\
            backgroundColor = sf.Color.BLACK, backgroundImage = Image()):

        sf.RenderWindow.__init__(self, videoMode, title)
        Render.__init__(self, parent, sf.Rectangle(sf.Vector2(),\
                videoMode.size), backgroundColor, backgroundImage)

        self._isStaticToView = False
        self.position = (0,0)
        self.framerate_limit = framerateLimit
        self._framerate = framerateLimit
        self._event = EventManager(self)
        self.resetView()
        self.clear(backgroundColor)

    def update(self):
        """Update the Window. It Update all event, and update framerate.
        It Draw and display also all widgets child"""
        if self.canUpdate:
            self._event.update()
            self._framerate = 1/(self._event.elapsedTime*10**-6)

            if self._event.isResize:
                Render._setSize(self,self.size)

            if self.event._mouseMoved:
                Widget.widgetFocus = None
    
            if self.event._mouseMoved and self.event.isMouseInRect(self.rect):
                Updatable._focusIsChecked= False
                Updatable.updateFocus(self)
            Widget.update(self, self)
            self.display()
            self.clear(self.backgroundColor)

    def getEventFromRootParent(self):
        return self._event

    def _setSize(self, size):
        sf.RenderWindow.size.__set__(self, size)
        Widget.size.__set__(self,size)
        self._event._defaultWindowSize = size

    def getPosOnScreen(self, *args):
        return sf.Vector2(0,0)

    def setPos(self, position, *args):
        Widget.setPos(position, False)
        self.position = position

    def getSizeOnScreen(self, *args):
        return self.size

    def _setView(self,view):
        sf.RenderWindow.view.__set__(self, view)
        Render._setView(self,view)

    size = sf.RenderWindow.size
    event = property(lambda self:self._event)
    framerate = property(lambda self:self._framerate)
    setPosOnScreen = setPos
    draw = sf.RenderWindow.draw
    sizeOnScreen = sf.RenderWindow.size
Ejemplo n.º 51
0
class Game:
    def __init__(self,arguments):
        self.debug = False
        self.capturing = False
        self.captureFPSWait = 0
        self.running = True
        self.fullscreen = False
        self.paused = False
        self.cachedScenes = {}
        self.currentScene = None
        self.currentElement = None
        self.currentWindow = None
        self.currentWidget = None
        
        self.values = {}

        self.Loader = Loader(self)
        self.setupScreen()
        self.setupAudio()
        self.displayTitle()
        self.Loader.preload()

        self.TitleManager = TitleManager(self)
        self.Cursor = Cursor(self)
        self.Renderer = Renderer(self)
        self.AudioController = AudioController(self)
        
        
        self.Inventory = Inventory(self)
        self.TopicMenu = TopicMenu(self)

        self.ScriptManager = ScriptManager(self)
        self.Player = Player(self)
        self.EventManager = EventManager(self)
        self.parseArguments(arguments)

        self.loadScene("blacksmith")
        self.run()
        
    def setupScreen(self,fullscreen=False):
        #There seems to be no way to make this work right other than doing this:
        pygame.display.set_icon(pygame.image.load(os.path.join('Resources','Icons','gameicon.png')))
        if fullscreen:
            self.window = pygame.display.set_mode((0,0),pygame.FULLSCREEN)
        else:
            self.window = pygame.display.set_mode((1024,768))
        pygame.display.set_caption('Subterranean')
        
    def displayTitle(self):
        #Temporary but neat
        logo = pygame.image.load(os.path.join('Resources','Graphics','Misc','logo.png'))
        self.window.blit(logo,(self.window.get_rect().centerx - logo.get_width()/2,self.window.get_rect().centery - logo.get_height()/2))
        pygame.display.flip()
    
    def setupAudio(self):
        pygame.mixer.init(44100)
        
    def parseArguments(self,arguments):
        avalibleArguments = {
            '--fullscreen':self.toggleFullscreen,
            '--nomusic':self.AudioController.disableMusic,
            '--nosound':self.AudioController.disableSound,
            '--debug':self.activateDebug
        }
        
        for argument in avalibleArguments.keys():
            if argument in arguments:
                argumentMethod = avalibleArguments.get(argument)
                argumentMethod()

    def pause(self):
        self.paused = True

    def unpause(self):
        self.paused = False
    
    def loop(self):
        while self.running:
            self.EventManager.checkEvents()
            self.Renderer.draw()
            self.Renderer.Timer.tick()

    def loadScene(self,sceneName):
        if sceneName in self.cachedScenes:
            self.log("Got",sceneName,"from cache")
            self.currentScene = self.cachedScenes.get(sceneName)
            #Run the enter method if it is not the first time we do
            self.currentScene.enter()
        else:
            self.log("Loaded",sceneName,"from file")
            scene = imp.load_source(sceneName,os.path.join('Assets','Scenes',sceneName+'.py'))
            sceneClass = getattr(scene,'Room');
            self.currentScene = sceneClass(self)
            self.cacheScene(self.currentScene,sceneName)

    def loadAsset(self,assetType,assetName):
        try:
            module = imp.load_source(assetName,os.path.join('Assets',assetType,assetName+'.py'))
            assetClass = getattr(module,assetName); 
            asset = assetClass(self)
            return asset
        except IOError:
            print "Fatal error: Could not load",assetName,"from",assetType
            exit()
        
    def cacheScene(self,sceneObject,sceneName):
        self.cachedScenes[sceneName] = sceneObject
        
    def quit(self,event=None):
        self.running = False
        sys.exit()

    def run(self):
        self.loop()
        
    def toggleFullscreen(self):
        if self.fullscreen == False:
            self.fullscreen = True
            self.setupScreen(True)
        else:
            self.fullscreen = False
            self.setupScreen(False)

    def activateDebug(self):
        self.debug = True
                   
    def log(self,*values):
        if self.debug:
            logValues = []
            for value in values:
                logValues.append(str(value)+" ")
            print "".join(logValues)
        
    def setValue(self,key,value):
        self.values[key] = value
    
    def getValue(self,key):
        return self.values.get(key)
        
    def dump(self):
        if self.debug:
            self.debug = False
        else:
            self.debug = True
                        
    def get(self,key):
        return self.Loader.get(key)
Ejemplo n.º 52
0
class Level:
	"Level Base class"

	def __init__(self,score,time):
		"Initialises resources and start level"
		
		self.background=pygame.image.load("sprites/sky.jpg")
		self.background.convert() #for blitting more faster
		
		self.screen=Constants.SCREEN
		self.score = score
		self.display_items = pygame.sprite.Group()
		self.timeclock = GameTime((0.05,0.05),time)		
		self.display_items.add(self.timeclock,self.score)
		
		self.time_speed=pygame.time.Clock()
		self.time=0.0
		
		self.quit = False
		self.pause = False
		self.start = False
		self.completed = False
		self.gameover = False
		self.message = None
		
		self.polygon=Polygon(self)
		self.event_manager = EventManager(self)
		self.on_enter()

	def get_score_object(self):
		return self.score
	
	def set_score_object(self, score_object):
		self.score = score_object
	
	def on_enter(self):
		self.screen.blit(self.background, (0, 0))
		pygame.display.flip()
		self.start = True
		self.pause = True
		self.timeclock.delete_timer()
		self.message = MessageBox(self,3000)
		self.display_items.add(self.message)


		
	def on_exit(self):
		self.display_items.remove(self.timeclock)
		del self.polygon
		del self.timeclock
		if self.completed == False: #end of game, so music fadeout
			pygame.mixer.music.fadeout(500)
		f = FadeTransition(500,Constants.FADECOLOR,"to")
		del f
		
	
	def run(self):
		
		while 1:
			
			self.time+=self.time_speed.tick(Constants.FPS)
			
			if self.gameover and (not self.pause):				
				self.pause = True
				self.polygon.reset()
				self.timeclock.delete_timer()
				self.message = MessageBox(self,4000)
				self.display_items.add(self.message)
			
			if self.completed and (not self.pause):
				self.pause = True
				self.polygon.reset()
				self.timeclock.delete_timer()
				self.message = MessageBox(self,4000)
				self.display_items.add(self.message)
				self.polygon.set_alive(False)
				self.polygon.reset()
			
			if self.quit:
				self.on_exit()
				if self.gameover == True:
					h = HighScores()
					h.insert_HighScores(Constants.PLAYERNAME,str(self.score.get_score()))
					hlist = HighScores().get_HighScores()
					if len(hlist)<5 or self.score.get_score() > hlist[4].get_points():
						h.flush()
					pygame.event.clear()
					highscores = HighScoresMenu("sprites/sky.jpg")
					highscores.run()
					return False
				else:
					return
			
			
			self.event_manager.run()
			self.screen.blit(self.background, (0, 0))
			self.display_items.update()			
			self.display_items.draw(self.screen)
			self.atoms.update()			
			self.atoms.draw(self.screen)
			
			if self.start == True  and self.pause == False:
				self.display_items.remove(self.message)
				self.message = None
				self.start = False
				self.polygon.set_alive(False)
				self.polygon.reset()
				self.timeclock.add_timer()
				
			if not self.pause:
				self.polygon.draw()					
			pygame.display.flip()
Ejemplo n.º 53
0
 def handle_raw_event(self, event):
     if event.type in SetJoystickKeyState.ALLOWED_TYPES and \
             EventManager.is_keydown(event):
         self.set_event(event)
Ejemplo n.º 54
0
 def __init__(self):
     self.attackers_list = [];
     self.defenders_list = [];
     self.frame = 0;
     self.msg_manager = MsgManager();
     self.event_manager = EventManager();
Ejemplo n.º 55
0
class BaseOutput:
    """ This is the base class for all output types. Please do not use this
        output directly. Use one of L{ValueOutput}, L{StreamOutput} or
        L{FrameOutput} instead. 
        
        All other types are subclassed from this one. But they provide some 
        additional functions or other behavior like this."""
    _d_inputs           = None # List of inputs connected to this output
    _d_event_manager    = None
    _d_logger           = None


    def __init__(self):
        """ Constructor of an output pin. This constructor takes a referece to
            the event-manager. """
        self._d_inputs = list()
        self._d_event_manager = EventManager()
        self._d_logger = logging.getLogger("edef.core")


    def __call__(self, value):
        """ This method will be used to set the value of this output. Simply
            call o_out(value) to set the value """
        self.set_value(value)


    def __rshift__(self, inp):
        """ This operatior is used to add this putput as an event-source to 
            the other input. The usage is ModA.o_out >> ModB.i_in
            inp should be a callable."""
        self.add_input(inp)


    def __iadd__(self, inp):
        """ Does the same like __rshift__() but can be used otherwise:
            ModA.o_out += ModB.i_in """
        self.add_input(inp)
        return self

    
    def __isub__(self, inp):
        """ Removes the given input from this output.
            Usage: ModA.o_out -= ModB.i_in """
        self.rem_input(inp)
        return self


    def __contains__(self, inp):
        """ This method should return true if the give input is connected to 
            this output.
            
            Usage: if ModB.i_in in ModB.o_out: pass
            
            inp should be a callable. """
        return self.has_input(inp)


    def set_value(self, value):
        """ This method will be called by the __call__ special method to set 
            the value of the output. Please use the __call__ method instead of
            calling this method directly. Also the __call__method will provide
            some eye-candy for you. Simple do C{output(new_value)} to set the 
            new value to the output. """
        self._d_logger.debug("Set output %s => %s"%(getattr(self,"__name__",self),value))

        for inp in self._d_inputs:
            self._d_event_manager.add_event(inp, value)


    def add_input(self, callback):
        """ This method will add an input to the output. This input will be
            called if the value of the output changes. Please use the 
            overwritten operator C{+=} or C{>>} to add new inputs to an 
            output instead of calling this method direct. Example:
            C{output += new_input} or C{output >> another_input}. The imput 
            should be a I{callable} that takes only one argument, may be a 
            function or a method of a class. """
        if not callback in self._d_inputs:
            self._d_logger.debug("Adding input %s (%s) to list"%(callback, id(callback)))
            self._d_inputs.append(callback)


    def rem_input(self, callback):
        """ This method will remove the given input from this output. But 
            PLEASE do not call this method direct! Use the overwritten 
            operator C{-=} instead. 
            Example: C{output -= any_input_added_first}
            If the given input was not added to the output first, this method
            will raise an exception. """
        self._d_logger.debug("Remove input %s (%s) from list"%(callback, id(callback)))
        del self._d_inputs[self._d_inputs.index(callback)]


    def has_input(self, callback):
        """ This method will return True if the given input was added to this 
            output and False otherwise. Please do not use this method direct. 
            Use the overwritten operator C{in} instead: 
            C{if any_input in output: do_somethin()} """
        return callback in self._d_inputs
Ejemplo n.º 56
0
 def handle_raw_event(self, event):
     if EventManager.is_keyboard_event(event.type) and \
             event not in SettingsManager.EVENTS_ESCAPE and \
             event not in SettingsManager.EVENTS_RETURN and \
             event not in SettingsManager.EVENTS_ACTION:
         self.handle_return()
Ejemplo n.º 57
0
class AutoFieldManager( QObject ):
    """ Class in charge of the AutoFields administration. 
        Main class of the plugin, as AutoFields can only be created, removed, 
          and overwritten from it.
    """    
    
    autoFieldCreated = pyqtSignal( str ) 
    autoFieldRemoved = pyqtSignal( str )
    autoFieldEnabled = pyqtSignal( str )
    autoFieldDisabled = pyqtSignal( str ) 

    def __init__( self, messageManager, iface, settingsPrefix="/AutoFields", organizationName=None, applicationName=None ):
        QObject.__init__( self )
        self.msg = messageManager
        self.settings = QSettings( organizationName, applicationName ) if organizationName and applicationName else QSettings()
        self.dictAutoFields = OrderedDict()
        self.settingsPrefix = settingsPrefix
        self.eventManager = EventManager( self.msg, iface, settingsPrefix )
        self.eventManager.layersAddedCheckIfAutoFields.connect( self.checkAndEnableAutoFieldsForLayers )
        self.eventManager.autoFieldsReadyToBeDisabled.connect( self.disableAutoFields )
        self.eventManager.attributesAddedCheckIfAutoFields.connect( self.checkAndEnableAutoFieldsForLayerFields )
        self.eventManager.attributesDeletedCheckIfAutoFields.connect( self.checkAndDisableAutoFieldsForLayer )
        
        self.eventManager.setAFM( self )
        
        self.fieldCalculator = FieldCalculator( self.msg, iface )
    
    
    def createAutoField( self, layer, fieldName, expression, layer2="", field2="", calculateOnExisting=True ):
        """ Add AutoField properties to both QSettings and dictAutoFields """    
        if not layer or not type(layer) is QgsVectorLayer:
            self.msg.show( 
                QApplication.translate( "AutoFieldManager", "[Error] A 'layer' parameter of type QgsVectorLayer must be given." ),
                'warning' )
            return False
        if not layer.hasGeometryType(): 
            self.msg.show( QApplication.translate( "AutoFieldManager", 
                "[Error] The layer has an unknown geometry, but AutoFieds does not support alphanumeric tables." ),
            'warning' )
            return False       
        
        capabilities = layer.dataProvider().capabilities()
        if not ( capabilities & QgsVectorDataProvider.ChangeAttributeValues ):
            self.msg.show( QApplication.translate( "AutoFieldManager",
                "[Error] The vector layer provider does not allow to change attribute values.\nYou would need to export the data to another format for adding AutoFields." ), 
                'warning' )
            return False    
        if not ( capabilities & QgsVectorDataProvider.AddFeatures ):
            self.msg.show( "[Warning] The vector layer provider does not allow to add features.", 'warning', True ) 
        if not ( capabilities & QgsVectorDataProvider.ChangeGeometries ):
            self.msg.show( "[Warning] The vector layer provider does not allow to change geometries.", 'warning', True )
        
        if layer.isReadOnly():
            self.msg.show( QApplication.translate( "AutoFieldManager", 
                "[Error] The vector layer is read only, so no AutoFields can be created on it." ),
                'warning' )
            return False       
            
        if not fieldName or type(fieldName) != unicode:
            self.msg.show( QApplication.translate( "AutoFieldManager",
                "[Error] A 'fieldName' parameter of type unicode must be given." ), 
                'warning' )
            return False
        if not fieldName.strip():
            self.msg.show( QApplication.translate( "AutoFieldManager", 
                "[Error] 'fieldName' variable has not a valid value." ), 'warning' )
            return False
            
        if layer.fieldNameIndex( fieldName ) == -1:
            self.msg.show( QApplication.translate( "AutoFieldManager", 
                "[Error] Layer " ) + layer.name() + \
                QApplication.translate( "AutoFieldManager", " has no field called " ) + \
                fieldName + QApplication.translate( "AutoFieldManager",
                ". You need to create it beforehand." ), 'warning' )
            return False
            
        #if layer.fields[layer.fieldNameIndex( field )].isEditable():
        #    print "Error: Field",field,"is not editable! It won't be possible to write in it."
        #    return False
            
        if not expression or type(expression) != unicode:
            self.msg.show( QApplication.translate( "AutoFieldManager",
                "[Error] An 'expression' parameter of type unicode must be given." ),
                'warning' )
            return False
        elif not expression.strip():
            self.msg.show( QApplication.translate( "AutoFieldManager",
                "[Error] 'expression' variable has not a valid value." ),
                'warning' )
            return False        
        
        autoFieldId = self.buildAutoFieldId( layer, fieldName )
        
        self.msg.show( "Create AutoField with Id: " + autoFieldId, 'info', True )

        if self.isFieldAnAutoField( layer, fieldName ):
            self.msg.show( QApplication.translate( "AutoFieldManager", 
                "[Error] This field is already an AutoField. You cannot create another AutoField on the same field, but you can use overwriteAutoField(), which supports the same parameters." ),
                'warning' )
            return False
        

        if calculateOnExisting: 
            self.fieldCalculator.calculate( layer, fieldName, expression )

        
        # Create AutoField in dictionary
        if not self.dictAutoFields:
            order = 1
        else:
            order = max( self.dictAutoFields.iteritems(), 
                        key=lambda d: d[1]['order'] )[1]['order'] + 1
            
        self.dictAutoFields[autoFieldId] = { 'layer':layer.publicSource(), 
            'field':fieldName, 'expression':expression, 'layer2':layer2, 
            'field2':field2, 'layerId': layer.id(), 'order': order }
        self.dictAutoFields[autoFieldId]['enabled'] = self.validateAutoField( self.dictAutoFields[autoFieldId] )
               
        # Create AutoField in QSettings and set corresponding events
        self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )
        self.eventManager.setEventsForAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )

        self.msg.show( QApplication.translate( "AutoFieldManager", "The AutoField (" ) + \
            layer.name() + "." + fieldName + ": " + expression + \
            QApplication.translate( "AutoFieldManager", ") was created properly!" ), 'info' )
        self.autoFieldCreated.emit( autoFieldId )
        return autoFieldId
    
    
    def overwriteAutoField( self, layer, fieldName, expression, layer2="", field2="", calculateOnExisting=True ):
        """ Logic to overwrite an existing AutoField in both QSettings and dictAutoFields """ 
        autoFieldId = self.buildAutoFieldId( layer, fieldName ) 
        if autoFieldId in self.dictAutoFields:
            self.removeAutoField( autoFieldId )        
            return self.createAutoField( layer, fieldName, expression, layer2, field2, calculateOnExisting )

        return False
        
    
    def removeAutoField( self, autoFieldId ):
        """ Get rid of AutoField from both QSettings and dictAutoFields """
        if not autoFieldId in self.dictAutoFields:
            self.msg.show( QApplication.translate( "AutoFieldManager",
                "[Warning] AutoField with Id " ) + autoFieldId + \
                QApplication.translate( "AutoFieldManager",
                    " was not found, so it couldn't be removed." ), 'warning' )
            return False
        
        self.settings.beginGroup( self.settingsPrefix + "/data" )
        self.settings.remove( autoFieldId )
        self.settings.endGroup()
        self.settings.sync()
        
        # Disconnect SIGNAL/SLOTS for this AutoField
        if 'layerId' in self.dictAutoFields[autoFieldId]:
            if self.dictAutoFields[autoFieldId]['enabled']:
                layer = QgsMapLayerRegistry.instance().mapLayer( self.dictAutoFields[autoFieldId]['layerId'] )
                self.eventManager.removeEventsForAutoField( autoFieldId, layer, self.dictAutoFields[autoFieldId]['expression'] )
        
        del self.dictAutoFields[autoFieldId]
        self.autoFieldRemoved.emit( autoFieldId )
       
       
    def readAutoFields( self ):
        """ Read AutoFields from QSettings, overwriting dictAutoFields """
        self.dictAutoFields = OrderedDict()
        dictTempAutoFields = {} # We will sort it when everything is read
        self.settings.beginGroup( self.settingsPrefix + "/data" )
        autoFieldsIds = self.settings.childGroups()
        self.settings.endGroup()
        for autoFieldId in autoFieldsIds:
            dictTmpProperties = {}
            self.settings.beginGroup( self.settingsPrefix + "/data/" + autoFieldId )
            dictTmpProperties['layer'] = self.settings.value( "layer", u"", type=unicode )
            dictTmpProperties['field'] = self.settings.value( "field", u"", type=unicode )
            dictTmpProperties['expression'] = self.settings.value( "expression", u"", type=unicode )
            dictTmpProperties['layer2'] = self.settings.value( "layer2", "", type=str )
            dictTmpProperties['field2'] = self.settings.value( "field2", "", type=str )            
            dictTmpProperties['order'] = self.settings.value( "order", 0, type=int )  
            self.settings.endGroup()
            
            # Check whether the AutoField must be enabled or not
            layer = self.getLayer( dictTmpProperties['layer'] )
            if layer:
                dictTmpProperties['layerId'] = layer.id()

            dictTmpProperties['enabled'] = self.validateAutoField( dictTmpProperties )
            
            dictTempAutoFields[autoFieldId] = dictTmpProperties
        
        
        # We need to set events in order of creation, so that the use case of
        #   AutoFields depending on other AutoFields becomes predictable    
        self.dictAutoFields = OrderedDict( sorted( dictTempAutoFields.items(), 
                                            key=lambda d: d[1]['order'] ) )
        
        for autoFieldId in self.dictAutoFields.keys():
            self.eventManager.setEventsForAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )
    
    
    def writeAutoField( self, autoFieldId, dictProperties ):
        """ Write an AutoField from dictAutoFields to QSettings """
        self.settings.beginGroup( self.settingsPrefix + "/data/" + autoFieldId )
        self.settings.setValue( "layer", dictProperties['layer'] )
        self.settings.setValue( "field", dictProperties['field'] )
        self.settings.setValue( "expression", dictProperties['expression'] )
        self.settings.setValue( "layer2", dictProperties['layer2'] )
        self.settings.setValue( "field2", dictProperties['field2'] )
        self.settings.setValue( "enabled", dictProperties['enabled'] )
        self.settings.setValue( "order", dictProperties['order'] )
        self.settings.endGroup()
        self.settings.sync()
    
    
    def listAutoFields( self ):
        return self.dictAutoFields
    
    
    def validateAutoField( self, dictProperties ):
        """ Check whether this AutoField is ready or if there is something missing """
        if not 'layerId' in dictProperties:
            self.msg.show( "[Warning] A layer that is part of an AutoField was not found in QGIS registry.", 'warning', True )
            return False
            
        layer = QgsMapLayerRegistry.instance().mapLayer( dictProperties['layerId'] )
        if not layer:
            self.msg.show( "[Warning] Layer id " + dictProperties['layerId'] + " was not found in QGIS registry.", 'warning', True )
            return False
            
        if layer.fieldNameIndex( dictProperties['field'] ) == -1:
            self.msg.show( "[Warning] Field was not found in layer "+layer.name()+".", 'warning', True )
            return False
            
        # TODO add checks for layer2 and field2
            
        return True        
        
        
    def normalizeSource( self, source ):
        """ Avoid issues with spaces and other weird characters for AutoField ids """
        pieces = source.split(" ")
        newPieces = [ piece for piece in pieces if not (piece.startswith("type=") or piece.startswith("srid=")) ]
        source = "".join( newPieces )
        return source.replace("\"","").replace("'","").replace("/","|").replace("\\","|")
           
           
    def buildAutoFieldId( self, layer, fieldName ):
        """ Centralizes the definition of AutoField identifiers """
        if not layer or not type(layer) is QgsVectorLayer:
            self.msg.show( "[Error] A 'layer' parameter of type QgsVectorLayer must be given.", 'warning', True )
            return None
        if not fieldName or type(fieldName) != unicode:
            self.msg.show( "[Error] A 'fieldName' parameter of type unicode must be given.", 'warning', True )
            return None
        
        return self.normalizeSource( layer.publicSource() ) + '@@' + fieldName


    def isFieldAnAutoField( self, layer, fieldName ):
        """ Returns whether a layer field is an AutoField or not """
        autoFieldId = self.buildAutoFieldId( layer, fieldName )
        return autoFieldId in self.dictAutoFields

                 
    def getFieldExpression( self, layer, fieldName ):
        """ If the given field is an AutoField, it returns its expression """
        autoFieldId = self.buildAutoFieldId( layer, fieldName ) 
        if autoFieldId in self.dictAutoFields:
            return self.dictAutoFields[autoFieldId]['expression']

        return ''
           
            
    def getLayer( self, autoFieldLayerSource ):
        """ Iterate layers and get one, comparing sources """
        for tmpLayer in QgsMapLayerRegistry.instance().mapLayers().values():
            if self.compareLayersPublicSources( tmpLayer.publicSource(), autoFieldLayerSource ):
                return tmpLayer
        return None 
            
            
    def compareLayersPublicSources( self, source1, source2 ):
        """ Normalize sources before comparing them.
            On Windows, adding a layer from the Add Layer button and from 
              QGIS Browser give different directory separators (/ vs \\), which 
              hampers comparison.            
        """
        return self.normalizeSource( source1 ) == self.normalizeSource( source2 )
    
    
                   
    def checkAndEnableAutoFieldsForLayers( self, mapLayers ):
        """ After a notification on layers being added, check and enable AutoFields if needed.
            1. Check if added layers are part of currently disabled AutoFields
            2. Enable it in Dict
            3. Enable it in QSettings
            4. Connect its SIGNALS / SLOTS
        """
        for layer in mapLayers:
            for autoFieldId in self.dictAutoFields:
                if self.dictAutoFields[autoFieldId]['enabled'] == False: # Don't check enabled AutoFields
                    if self.compareLayersPublicSources( layer.publicSource(), self.dictAutoFields[autoFieldId]['layer'] ): #1
                        self.dictAutoFields[autoFieldId]['layerId'] = layer.id()
                        if self.validateAutoField( self.dictAutoFields[autoFieldId] ):
                            self.dictAutoFields[autoFieldId]['enabled'] = True #2
                            self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] ) #3
                            self.eventManager.setEventsForAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )#4   
                            self.autoFieldEnabled.emit( autoFieldId )
        
        
    def disableAutoFields( self, layerId ):
        """ After a notification on layers being removed, disable all their AutoFields """ 
        #for layerId in layerIds:
        for autoFieldId in self.dictAutoFields:
            if 'layerId' in self.dictAutoFields[autoFieldId]:
                if layerId == self.dictAutoFields[autoFieldId]['layerId']:       
                    self.dictAutoFields[autoFieldId]['enabled'] = False
                    self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )
                    del self.dictAutoFields[autoFieldId]['layerId'] # layerId is meaningless now
                    self.autoFieldDisabled.emit( autoFieldId )
               
                   
    def checkAndEnableAutoFieldsForLayerFields( self, layerId, fields ):
        """ After a notification on fields being added, check and enable AutoFields if needed.
            1. Check if added fields are part of currently disabled AutoFields
            2. Enable it in Dict
            3. Enable it in QSettings
            4. Connect its SIGNALS / SLOTS 
        """
        for autoFieldId in self.dictAutoFields: 
            if self.dictAutoFields[autoFieldId]['enabled'] == False: # Don't check enabled AutoFields
                if 'layerId' in self.dictAutoFields[autoFieldId]: 
                    if layerId == self.dictAutoFields[autoFieldId]['layerId']: #1
                        for field in fields:
                            if field.name() == self.dictAutoFields[autoFieldId]['field']: 
                                if self.validateAutoField( self.dictAutoFields[autoFieldId] ):
                                    self.dictAutoFields[autoFieldId]['enabled'] = True #2
                                    self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] ) #3
                                    self.eventManager.setEventsForAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )#4   
                                    self.autoFieldEnabled.emit( autoFieldId )
        
                   
    def checkAndDisableAutoFieldsForLayer( self, layerId ):
        """ After a notification on fields being removed, check and disable AutoFields if needed.
            1. Check if any field is missing in AutoFields set for this layer.
            2. Disable it in Dict
            3. Disable it in QSettings
            4. Disconnect its SIGNAL / SLOTS   
         """
        for autoFieldId in self.dictAutoFields:
            if self.dictAutoFields[autoFieldId]['enabled'] == True: # Don't check disabled AutoFields
                if layerId == self.dictAutoFields[autoFieldId]['layerId']:       
                    layer = QgsMapLayerRegistry.instance().mapLayer( layerId )    
                    if layer.fieldNameIndex( self.dictAutoFields[autoFieldId]['field'] ) == -1: #1
                        self.dictAutoFields[autoFieldId]['enabled'] = False #2
                        self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] ) #3
                        self.eventManager.removeEventsForAutoField( autoFieldId, layer, self.dictAutoFields[autoFieldId]['expression'] ) #4
                        self.autoFieldDisabled.emit( autoFieldId )


    def disconnectAll( self ):
        """ Terminates all SIGNAL/SLOT connections created by this class """
        self.eventManager.layersAddedCheckIfAutoFields.disconnect( self.checkAndEnableAutoFieldsForLayers )
        self.eventManager.autoFieldsReadyToBeDisabled.disconnect( self.disableAutoFields )
        self.eventManager.attributesAddedCheckIfAutoFields.disconnect( self.checkAndEnableAutoFieldsForLayerFields )
        self.eventManager.attributesDeletedCheckIfAutoFields.disconnect( self.checkAndDisableAutoFieldsForLayer )
        
        # Disconnect all SIGNAL/SLOT connections created by eventManager
        self.eventManager.disconnectAll()
        
        # Disconnect all events for each enabled AutoField
        for autoFieldId in self.dictAutoFields:
            if self.dictAutoFields[autoFieldId]['enabled'] == True: # Don't check disabled AutoFields
                layerId = self.dictAutoFields[autoFieldId]['layerId']
                layer = QgsMapLayerRegistry.instance().mapLayer( layerId )
                self.eventManager.removeEventsForAutoField( autoFieldId, layer, self.dictAutoFields[autoFieldId]['expression'] )