Pygame Rotate Sprite

Pygame Rotate Sprite

Use left and right arrow keys.

import math
import pygame
from statemachine import State
from pygame.sprite import Sprite, Group

class RotateSprite(Sprite):
    def __init__(self, image, position, center=False):
        Sprite.__init__(self)
        self.original_image = image
        # Lower is faster
        self.rotate_speed = 10
        self.image = image
        self.angle = 0
        if center:
            self.rect = self.image.get_rect(center=position)
        else:
            self.rect = self.image.get_rect(topleft=position)

    def rotate_on_angle(self, angle):
        center = self.rect.center
        self.image = pygame.transform.rotate(self.original_image, angle)
        self.rect = self.image.get_rect(center=center)

    def rotate_left(self, delta, angle=1):
        angle = (angle / self.rotate_speed) * delta
        self.angle = (self.angle + angle) % 360
        self.rotate_on_angle(self.angle)

    def rotate_right(self, delta, angle=1):
        angle = (angle / self.rotate_speed) * delta
        self.angle = (self.angle - angle) % 360
        self.rotate_on_angle(self.angle)

class Example(State):
    def __init__(self):
        self.create_images()
        self.sprites = Group()

        self.ship = RotateSprite(self.images['triangle'], 
                                 State.machine.rect.center, True)
        # Add sprite to group
        self.ship.add(self.sprites)


    def create_images(self):
        self.images = {}
        surface = pygame.Surface((30, 30), pygame.SRCALPHA)
        points = (0, 0), (15, 30), (30, 0)
        pygame.draw.polygon(surface, pygame.Color("orange"), points)
        self.images['triangle'] = surface

    def on_draw(self, surface):
        surface.fill(pygame.Color('black'))
        self.sprites.draw(surface)

    def on_update(self, delta):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.ship.rotate_left(delta)
        elif keys[pygame.K_RIGHT]:
            self.ship.rotate_right(delta)

def main():
    pygame.init()
    # caption, width, height, center
    State.machine_setup("Rotate Sprite Example", 800, 600, True)
    State.machine.flip(Example())
    State.machine.mainloop()

if __name__ == '__main__':
    main()