Пример #1
0
    def __init__(self, feed_layer, *args, **kwargs):
        super().__init__(*args, **kwargs)

        uic.loadUi(os.path.join(os.path.dirname(__file__), "MainWindow.ui"),
                   self)

        jsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=4)
        jsonpickle.set_encoder_options('json', sort_keys=True, indent=4)
        jsonpickle.set_preferred_backend("simplejson")

        self.__tabs = {}

        self.uiMainTabWidget = self.findChild(QTabWidget, "tabWidget")
        self.uiMainTabWidget.tabCloseRequested.connect(self.closeView)

        nodes = self.__loadConfigFromFile(MainWindow.FILENAME_CONFIG_NODES, {})
        self.nodes = NodeManager(nodes)

        views = self.__loadConfigFromFile(MainWindow.FILENAME_CONFIG_VIEWS, {})
        self.views = ViewManager(views)

        self.sensorManager = SensorManager(self.views.callbackUpdate,
                                           self.nodes.addId)

        nodeConfigTab = NodeConfigTab(
            self.nodes, callbackModified=self.callbackModifiedNodes)
        self.nodes.setCallbackNodeAdded(nodeConfigTab.add)
        self.uiMainTabWidget.addTab(nodeConfigTab, "Konfiguration")
        self.uiMainTabWidget.tabBar().setTabButton(0, QTabBar.RightSide, None)

        viewConfigTab = ViewConfigTab(
            self.views,
            self.nodes,
            self.showView,
            callbackModified=self.callbackModifiedViews)
        self.uiMainTabWidget.addTab(viewConfigTab, "Ansichten")
        self.uiMainTabWidget.tabBar().setTabButton(1, QTabBar.RightSide, None)

        self.__updateTimer = QtCore.QTimer(self)
        self.__updateTimer.setInterval(1000)
        self.__updateTimer.timeout.connect(self.views.updateWidgets)
        self.__updateTimer.start()

        if feed_layer is not None:
            self.link = feed_layer
            self.readAllEvents()
            self.link.subscribe_sensor_feed(self.parseSensorFeedEventNoId)
        else:
            self.link = None
            self.demoTimer = None
Пример #2
0
 def start ( self ):
     """Creates all game object instances. No return.
     
     This is where specific Rooms, Items, Cotrollers, and pygame essentials are
     created.
     
     """
     if(DEBUG):print("Starting");
     pygame.init()
     #Create display
     self.DISPLAY_SURF = pygame.display.set_mode(self.SIZE)
     self.DISPLAY_SURF.fill((0,0,0))
     #Create Pygame objects here
     self.clock = pygame.time.Clock()
     #Player
     self.player = Character(initial_position = [40,600])
     #Veiw Manager
     self.veiwMan = ViewManager([255,255,255], [5,5], [self.WIDTH-10, self.HEIGHT-10], self.player) #Puts a white VeiwManager on screen
     #Control Manager
     self.conMan = ControlManager()
     self.conMan.setAvatar(self.player)
     #Creating Rooms
     greenRoom = pygame.sprite.Sprite()
     greenRoom.image = pygame.Surface([1000, 640])
     greenRoom.rect = greenRoom.image.get_rect()
     greenRoom.image.fill([0,255,0])
     self.room1 = Room(greenRoom, self.player) #Sets background to greenRoom and avatar to self.player
     
     grayRoom = pygame.sprite.Sprite()
     grayRoom.image = pygame.Surface([1000, 640])
     grayRoom.rect = grayRoom.image.get_rect()
     grayRoom.image.fill([100,100,100])
     self.room2 = Room(grayRoom, self.player)
     
     #Creating items
     self.box = Item([400, 600])
     self.box.setTouchEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room2}))
     self.box2 = Item([200, 600])
     self.box2.setInteractEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room1}))
     self.room1.addObject(self.box)
     self.room2.addObject(self.box2)
     self.itemGroup = pygame.sprite.RenderPlain(self.box,self.box2)
     
     #Making Text
     #This is not critical code
     if(pygame.font.get_init):
         hello = pygame.font.Font(None,64)
         hello = hello.render("Press Space", False, [0,0,0])
         x,y = self.veiwMan.rect.center
         x = x - (hello.get_width()/2)
         y = y - (hello.get_height()/2)
         self.veiwMan.image.blit(hello, [x,y])
     
     pygame.display.flip()
     self.RUNNING = True
Пример #3
0
def run_game():
    # 初始化游戏
    pygame.init()
    # 创建ViewManager对象
    screen = pygame.display.set_mode((1024, 768))
    view_manager = ViewManager()
    block = pygame.time.Clock()
    # 设置显示屏幕,返回Surface对象
    p1 = []
    # 设置标题
    pygame.display.set_caption('pvz')
    p2 = []

    #是否进入点击状态
    is_pick = False
    while 1:
        block.tick(30)
        screen.blit(view_manager.background, (0, 0))
        screen.blit(view_manager.cards, (120, 15))
        press = pygame.mouse.get_pressed()
        x, y = pygame.mouse.get_pos()

        # 处理游戏事件
        for event in pygame.event.get():
            # 处理游戏退出
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.MOUSEMOTION:
                if not is_pick:
                    if press[0]:
                        if 120 <= x < 120 + view_manager.cards.get_rect(
                        ).width and 15 <= y <= 15 + view_manager.cards.get_rect(
                        ).height:
                            p = plant(view_manager)
                            p1.append(p)
                            is_pick = True
                if is_pick:
                    if not (120 <= x <
                            120 + view_manager.cards.get_rect().width and 15 <=
                            y <= 15 + view_manager.cards.get_rect().height):
                        if press[2]:
                            p1.clear()
                            is_pick = False
                        if press[0]:
                            p.x = x - 50
                            p.y = y - 80
                            p.motivated = True
                            p2.append(p)
                            p1.clear()
                            is_pick = False
        for i in p1:
            screen.blit(i.images, (x - 50, y - 80))
        for i in p2:
            if i.motivated and i.shoot_time <= 0:
                i.add_bullet(view_manager)
            i.draw_bullet(screen)
            screen.blit(i.images, (i.x, i.y))
            # print((str(len(i.bullet_list))), str(i.shoot_time))
        if press[1]:
            print(len(p2))

        del_monster = []
        for i in mm.monster_list:
            for j in p2:
                for k in j.bullet_list:
                    if(i.is_hurt(k.x+50,k.y+26)):
                        j.bullet_list.remove(k)
                        i.life -= 1
                        if i.life <= 0:
                            del_monster.append(i)
        mm.monster_list.remove(del_monster)
        del_monster.clear()
        update_screen(screen, view_manager, mm)
Пример #4
0
class Fey ( ):
    def __init__ ( self ):
        """Sets game instance fields and sets RUNNING to True. No return."""
        
        if(DEBUG):print("Initializing");
        self.RUNNING = True
        self.DISPLAY_SURF = None
        self.SIZE = self.WIDTH, self.HEIGHT = 800, 640
        
    def start ( self ):
        """Creates all game object instances. No return.
        
        This is where specific Rooms, Items, Cotrollers, and pygame essentials are
        created.
        
        """
        if(DEBUG):print("Starting");
        pygame.init()
        #Create display
        self.DISPLAY_SURF = pygame.display.set_mode(self.SIZE)
        self.DISPLAY_SURF.fill((0,0,0))
        #Create Pygame objects here
        self.clock = pygame.time.Clock()
        #Player
        self.player = Character(initial_position = [40,600])
        #Veiw Manager
        self.veiwMan = ViewManager([255,255,255], [5,5], [self.WIDTH-10, self.HEIGHT-10], self.player) #Puts a white VeiwManager on screen
        #Control Manager
        self.conMan = ControlManager()
        self.conMan.setAvatar(self.player)
        #Creating Rooms
        greenRoom = pygame.sprite.Sprite()
        greenRoom.image = pygame.Surface([1000, 640])
        greenRoom.rect = greenRoom.image.get_rect()
        greenRoom.image.fill([0,255,0])
        self.room1 = Room(greenRoom, self.player) #Sets background to greenRoom and avatar to self.player
        
        grayRoom = pygame.sprite.Sprite()
        grayRoom.image = pygame.Surface([1000, 640])
        grayRoom.rect = grayRoom.image.get_rect()
        grayRoom.image.fill([100,100,100])
        self.room2 = Room(grayRoom, self.player)
        
        #Creating items
        self.box = Item([400, 600])
        self.box.setTouchEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room2}))
        self.box2 = Item([200, 600])
        self.box2.setInteractEvent(pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room1}))
        self.room1.addObject(self.box)
        self.room2.addObject(self.box2)
        self.itemGroup = pygame.sprite.RenderPlain(self.box,self.box2)
        
        #Making Text
        #This is not critical code
        if(pygame.font.get_init):
            hello = pygame.font.Font(None,64)
            hello = hello.render("Press Space", False, [0,0,0])
            x,y = self.veiwMan.rect.center
            x = x - (hello.get_width()/2)
            y = y - (hello.get_height()/2)
            self.veiwMan.image.blit(hello, [x,y])
        
        pygame.display.flip()
        self.RUNNING = True


    def handleEvent(self, event):
        """Pipes given event to relivant reciver. No return.
        
        This method handles event calls and sorts them either to the main game instance,
        to the game's ControlManager, or the game's VeiwManager. It may be better to put
        this functionality into a standalone class.
        
        """
        if(DEBUG):print("Event check");
        if event.type == pygame.QUIT:
            self.RUNNING = False
        #Events are handled here
        if event.type == pygame.KEYDOWN and event.key == K_ESCAPE:
            self.RUNNING = False
        elif event.type == pygame.KEYDOWN and event.key == K_SPACE:
            callChange = pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room1})
            pygame.event.post(callChange)
        elif event.type == pygame.KEYDOWN and event.key == K_DOWN:
            callChange = pygame.event.Event(Events.ROOM_CHANGE, {"room":self.room2})
            pygame.event.post(callChange)
        elif(event.type == Events.ROOM_CHANGE):
            self.veiwMan.setCurrentView(event.room)
        else:
            self.conMan.handle(event)

    def update(self):
        """Main update function. Should be called every cicle. No return.
        
        This function calls the update functions of all active game objects.
        
        """
        if(DEBUG):print("Updating");
        #Objects will update themselves (movement, calculation, etc)
        self.veiwMan.update()

    def render(self):
        """Draws the final frame onto the display. No return.
        
        This function calls the ViewManager to blit (draw) all active objects 
        to itself, then blits itself onto the main display, and then calls the
        display to flip the changes to the screen.
        
        """
        if(DEBUG):print("Rendering");
        #ViewManager draws apropriate surfaces to itself
        self.veiwMan.drawView()
        self.DISPLAY_SURF.blit(self.veiwMan.image, self.veiwMan.rect) #Dependant on VeiwManager
        pygame.display.flip()
        pass

    def cleanup(self):
        """Runs the pygame.quit() function, which closes the display safely."""
        if(DEBUG):print("Cleaning up");
        pygame.quit()

    def run(self):
        """Starts the game's main loop."""
        if(DEBUG):print("Attempting to run");
        if self.start() == False:
            self.RUNNING = False

        if(DEBUG):print("Running");
        while(self.RUNNING):
            self.clock.tick(30)
            for event in pygame.event.get():
                self.handleEvent(event)
            self.update()
            self.render()
        self.cleanup()
Пример #5
0
class MainWindow(QMainWindow):
    FILENAME_CONFIG_VIEWS = "views"
    FILENAME_CONFIG_NODES = "nodes"

    NODE_DEMO_ID = "2"

    def __init__(self, feed_layer, *args, **kwargs):
        super().__init__(*args, **kwargs)

        uic.loadUi(os.path.join(os.path.dirname(__file__), "MainWindow.ui"),
                   self)

        jsonpickle.set_encoder_options('simplejson', sort_keys=True, indent=4)
        jsonpickle.set_encoder_options('json', sort_keys=True, indent=4)
        jsonpickle.set_preferred_backend("simplejson")

        self.__tabs = {}

        self.uiMainTabWidget = self.findChild(QTabWidget, "tabWidget")
        self.uiMainTabWidget.tabCloseRequested.connect(self.closeView)

        nodes = self.__loadConfigFromFile(MainWindow.FILENAME_CONFIG_NODES, {})
        self.nodes = NodeManager(nodes)

        views = self.__loadConfigFromFile(MainWindow.FILENAME_CONFIG_VIEWS, {})
        self.views = ViewManager(views)

        self.sensorManager = SensorManager(self.views.callbackUpdate,
                                           self.nodes.addId)

        nodeConfigTab = NodeConfigTab(
            self.nodes, callbackModified=self.callbackModifiedNodes)
        self.nodes.setCallbackNodeAdded(nodeConfigTab.add)
        self.uiMainTabWidget.addTab(nodeConfigTab, "Konfiguration")
        self.uiMainTabWidget.tabBar().setTabButton(0, QTabBar.RightSide, None)

        viewConfigTab = ViewConfigTab(
            self.views,
            self.nodes,
            self.showView,
            callbackModified=self.callbackModifiedViews)
        self.uiMainTabWidget.addTab(viewConfigTab, "Ansichten")
        self.uiMainTabWidget.tabBar().setTabButton(1, QTabBar.RightSide, None)

        self.__updateTimer = QtCore.QTimer(self)
        self.__updateTimer.setInterval(1000)
        self.__updateTimer.timeout.connect(self.views.updateWidgets)
        self.__updateTimer.start()

        if feed_layer is not None:
            self.link = feed_layer
            self.readAllEvents()
            self.link.subscribe_sensor_feed(self.parseSensorFeedEventNoId)
        else:
            self.link = None
            self.demoTimer = None

    def readAllEvents(self):
        fid = self.link.get_sensor_feed_fid()
        eventCount = self.link.get_feed_length(fid)

        for seq in range(eventCount):
            self.parseSensorFeedEventNoId(self.link.get_event_content(
                fid, seq))

    def pushInterval(self, interval):
        fid = self.link.get_control_feed_fid()
        self.link.create_event(fid, f"{int(interval)}")

    def stopTimer(self):
        self.readTimer.cancel()

    def callbackModifiedNodes(self):
        if self.nodes.containsId(MainWindow.NODE_DEMO_ID):
            self.pushInterval(self.nodes.get(MainWindow.NODE_DEMO_ID).interval)
        self.__saveConfigToFile(self.nodes.getAll(),
                                MainWindow.FILENAME_CONFIG_NODES)

    def callbackModifiedViews(self):
        self.__saveConfigToFile(self.views.getAll(),
                                MainWindow.FILENAME_CONFIG_VIEWS)

    def addSensorDataSet(self, nodeId, timestamp, t, p, h, b):
        # T=1 P=2 rH=3 J=%
        # d/m/Y
        time = timestamp.timestamp()
        self.sensorManager.addData(nodeId, "T_celcius", float(t), time)
        self.sensorManager.addData(nodeId, "P_bar", float(p), time)
        self.sensorManager.addData(nodeId, "rH", float(h), time)
        self.sensorManager.addData(nodeId, "J_lumen", float(b), time)

    def parseSensorFeedEventNoId(self, feedEvent):
        print("DATA: {}".format(feedEvent))
        data = ast.literal_eval(feedEvent)
        if len(data) != 5:
            return
        self.addSensorDataSet(
            MainWindow.NODE_DEMO_ID,
            datetime.datetime.strptime(data[0], '%d/%m/%y %H:%M:%S'), data[1],
            data[2], data[3], data[4])

    def parseSensorFeedEvent(self, feedEvent):
        data = ast.literal_eval(feedEvent)
        if len(data) != 6:
            return
        self.addSensorDataSet(
            data[0], datetime.datetime.strptime(data[1], '%d/%m/%y %H:%M:%S'),
            data[2], data[3], data[4], data[5])

    def readSensorFeed(self):
        sensorFid = self.link.get_sensor_feed_fid()
        feedLength = self.link.get_feed_length(sensorFid)
        feedEvent = self.link.get_event_content(sensorFid, feedLength - 1)
        self.parseSensorFeedEvent(feedEvent)

    def periodicRead(self, interval):
        self.readSensorFeed()
        self.readTimer = threading.Timer(interval,
                                         self.periodicRead,
                                         args=[interval])
        self.readTimer.start()

    '''
        View Methods
    '''

    def showView(self, view):
        if view is None:
            return

        widget = self.views.open(view.id)

        for yAxis in view.getYAxes():
            if not yAxis.active:
                continue
            for nodeId, sensorId in yAxis.sensors.items():
                widget.setData(
                    yAxis.id, nodeId, sensorId,
                    self.sensorManager.dataReference(nodeId, sensorId))

        index = self.uiMainTabWidget.indexOf(widget)
        if index >= 0:
            self.uiMainTabWidget.setCurrentIndex(index)
        else:
            self.uiMainTabWidget.addTab(widget, view.name)
            self.uiMainTabWidget.setCurrentWidget(widget)
        widget.setOpen(True)

    def closeView(self, tabIndex):
        if tabIndex > 1:
            widget = self.uiMainTabWidget.widget(tabIndex)
            if isinstance(widget, ViewWidget):
                widget.setOpen(False)
            self.uiMainTabWidget.removeTab(tabIndex)

    '''
        General Methods
    '''

    def __saveConfigToFile(self, config, filename):
        if config is None or not isinstance(filename, str):
            return False
        with open(filename + ".json", "w") as f:
            f.write(jsonpickle.encode(config))

    def __loadConfigFromFile(self, filename, default=None):
        if not isinstance(filename,
                          str) or not os.path.isfile(filename + ".json"):
            return default
        with open(filename + ".json", "r") as f:
            config = jsonpickle.decode(f.read())

        return config

    def demo(self, interval):
        if interval < 1 or not self or not self.isVisible():
            print(self.isVisible())
            if self.demoTimer is not None:
                self.demoTimer.cancel()
            return
        self.parseSensorFeedEvent(
            f"['1','{datetime.datetime.now().strftime('%d/%m/%y %H:%M:%S')}','{random.random() * 3 + 20}','{random.randrange(10000) + 95000}','{random.random() * 30 + 30}','{random.random() * 10 + 50}']"
        )
        self.demoTimer = threading.Timer(interval, self.demo, args=[interval])
        self.demoTimer.start()

    def show(self):
        super().show()
        if self.link is None:
            self.demo(2)
Пример #6
0
import xml.etree.ElementTree as ET
from ViewManager import ViewManager

# https://docs.python.org/3.6/library/xml.etree.elementtree.html
views_root = ET.parse('../xml_conf/views.xml').getroot()

view_managers = {}
for id, xml_view_child in enumerate(views_root):
    vm = ViewManager(id, xml_view_child)
    view_managers[str(id)] = vm
    vm.update_view()

view_chain_mapping = {}
for id, vm in view_managers.items():
    view_chain_mapping[vm.id] = [r.split("/")[0] for r in vm.get_refs()]
    print("Plot refs for view {}: {}".format(vm.id, view_chain_mapping[vm.id]))

transformations = []
for id, vm in view_managers.items():
    transformations += vm.get_transformations()
    print("Transformations for view {}: {}".format(vm.id, transformations))
transformations = list(dict.fromkeys(transformations))
"""
Plot refs for view 0: ['lst_dl1', '']
Transformations for view 0: ['tailcuts_clean']
"""