img = pg.ImageItem(screen)
view.addItem(img)img.setImage(screen)from PyQt5 import QtCore, QtGui, QtWidgetsfrom pyqtgraph.Qt import QtCore, QtGuiimport numpy as npimport pyqtgraph as pgimport sys
class AntDemo(QtWidgets.QWidget):
def __init__(self): super().__init__() self.initUI()
def initUI(self):
# Manually lay out display area and controls for the widget # Could also use Qt Designer .ui file and uic module/pyuic5 utility self.horizontalLayout = QtWidgets.QHBoxLayout(self) self.horizontalLayout.setObjectName("horizontalLayout") self.plot = pg.GraphicsView(self) self.horizontalLayout.addWidget(self.plot) self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.pushButton = QtWidgets.QPushButton(self) self.pushButton.setObjectName("pushButton") self.verticalLayout.addWidget(self.pushButton) spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem) self.horizontalLayout.addLayout(self.verticalLayout) self.pushButton.setText("&Clear")
# Connect signals self.pushButton.clicked.connect(self.clear)
# Set up the plot and image buffer self.screen = np.zeros((500, 500)) self.x = 250 self.y = 250 self.direction = 1 self.img = pg.ImageItem(self.screen) self.plot.addItem(self.img) self.plot.setMinimumSize(*self.screen.shape)
# Configure the update timer self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update) self.timer.start(0)
def update(self):
if self.screen[self.x, self.y] == 1: self.direction += 1 self.screen[self.x, self.y] = 0 else: self.direction -= 1 self.screen[self.x, self.y] = 1
if self.direction == 0: self.direction = 4 if self.direction == 5: self.direction = 1
if self.direction == 1: self.y -= 1 elif self.direction == 2: self.x += 1 elif self.direction == 3: self.y += 1 elif self.direction == 4: self.x -= 1
# Wrap coordinates around the image box self.x = self.x % self.screen.shape[0] self.y = self.y % self.screen.shape[1] self.img.setImage(self.screen)
def clear(self): self.screen = np.zeros((500, 500))
if __name__ == '__main__': app = QtGui.QApplication(sys.argv) ex = AntDemo() ex.show() sys.exit(app.exec_())
This was a nice surprise btw.
I added a few lines to have it update the screen every 60 cycles (for speed):
self.x = self.x % self.screen.shape[0]
self.y = self.y % self.screen.shape[1]