spritesheets in pyqt 1

spritesheets in pyqt

class PowerUp(QtGui.QGraphicsRectItem):
    def __init__(self):
        QtGui.QGraphicsRectItem.__init__(self)
        self.images = ['data/images/objects/bonus_block/full-0.png',
                       'data/images/objects/bonus_block/full-1.png',
                       'data/images/objects/bonus_block/full-2.png',
                       'data/images/objects/bonus_block/full-3.png',
                       'data/images/objects/bonus_block/full-4.png']
        self.image = self.images[0]
        self.current = 0
        self.position()
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.animation_step)
        self.timer.start(175)
        #random.choice([slide(), ghost()])

    def position(self):
        self.pos_x = random.randint(-300, 300)
        self.pos_y = random.randint(-200, 200)

    def boundingRect(self):
        return QtCore.QRectF(0, 0, 32, 32)

    def paint(self, painter, option, widget):
        painter.setBrush(QtGui.QBrush(self.image))
        painter.setPen(QtGui.QPen(QtCore.Qt.NoPen))
        painter.drawRect(0, 0, 32, 32)
        self.setPos(self.pos_x, self.pos_y)

    def animation_step(self):
        self.image = QtGui.QPixmap(self.images[self.current])
        self.current += 1
        if self.current == len(self.images):
            self.current = 0

Here is what the above code is Doing:
1. We create a class called PowerUp that inherits from QGraphicsRectItem.
2. We create a list of images that we want to use for the animation.
3. We set the image to the first image in the list.
4. We set the current image to 0.
5. We call the position() method to set the position of the power-up.
6. We create a timer that will call the animation_step() method every 175 milliseconds.
7. We create a boundingRect() method that returns a QRectF object.
8. We create a paint() method that draws the image.
9. We create an animation_step() method that changes the image.

Similar Posts