コード例 #1
0
class AStarApplication(QWidget):
    def __init__(self):
        super(AStarApplication, self).__init__()
        self.close = self.cleanup

        self.layout = QVBoxLayout(self)
        self.setLayout(self.layout)

        self.canvas = QGraphicsView()
        self.canvas.setViewportUpdateMode(QGraphicsView.FullViewportUpdate)

        self.grid = Grid(24, 20)
        self.tiles = []
        for x in range(self.grid.w):
            for y in range(self.grid.h):
                tile = Tile(self.grid.get_node(x, y), self)
                self.tiles.append(tile)

        self.scene = QGraphicsScene()
        self.scene.setBackgroundBrush(QBrush(Qt.lightGray, Qt.SolidPattern))

        for t in self.tiles:
            self.scene.addItem(t)

        self.canvas.setScene(self.scene)
        self.layout.addWidget(self.canvas)

        self.refresh_timer = QTimer()
        self.refresh_timer.setInterval(1000 / 60)
        self.refresh_timer.timeout.connect(self.refresh)
        self.refresh_timer.start()

        self.AStar = AStar(self.grid)
        self.focusPolicy = Qt.StrongFocus
        self.keyPressEvent = self.kbdHandler

    # Avoid the segfault caused by some obscure GC stuff.
    @pyqtSlot()
    def cleanup(self, obj):
        pass

    @pyqtSlot()
    def refresh(self):
        self.scene.invalidate()

    @pyqtSlot()
    def kbdHandler(self, e):
        if e.key() == Qt.Key_Space:
            self.AStar.step()

    # Called when a tile changes type, so all tiles can be updated
    def update_tiles(self, caller):
        for t in self.tiles:
            if self.grid.target is not None:
                t.subtext = t.node.heuristic(self.grid.target)
            else:
                t.subtext = ''
            if t != caller and t.type != 'clear' and t.type != 'wall' and t.type == caller.type:
                t.set_type('clear')
        self.AStar.reset()