Search code examples
pythonpygameattributeerror

Python : Pygame error : AttributeError: module 'pygame.image' has no attribute 'rotate' when trying to rotate image of an in game character


import pygame
import os

WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("First Game!")

WHITE = (255, 255, 255)
FPS = 60
SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 55, 40

YELLOW_SPACESHIP_IMAGE = pygame.image.load(
    os.path.join('Assets', 'spaceship_yellow.png'))

YELLOW_SPACESHIP = pygame.image.rotate(pygame.transform.scale(
    YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90)


RED_SPACESHIP_IMAGE = pygame.image.load(
    os.path.join('Assets', 'spaceship_red.png'))

RED_SPACESHIP = pygame.transform.scale(
    RED_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT))


def draw_window():
    WIN.fill(WHITE)
    WIN.blit(YELLOW_SPACESHIP, (300, 100))

    pygame.display.update()


def main():
    clock = pygame.time.Clock()
    run = True
    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        draw_window()

    pygame.quit()


if __name__ == "__main__":
    main()

I have been carefully following an introduction video to making games using pygame and have reached the point when running the code the error

Traceback (most recent call last):
  File "C:\Users\morle\PycharmProjects\pythonProject\first game test.py", line 15, in <module>
    YELLOW_SPACESHIP = pygame.image.rotate(pygame.transform.scale(
AttributeError: module 'pygame.image' has no attribute 'rotate'

the line in question is

YELLOW_SPACESHIP = pygame.image.rotate(pygame.transform.scale(
    YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90)

I dont understand why this is happening any help would be much appreciated.

here is the link for the video 27:08 text


Solution

  • pygame.image.rotate does not actualy exists.
    To rotate an image, you have to do the same as to scale :

    pygame.transform.rotate(surface, angle)
    

    In your case, that would be:

    YELLOW_SPACESHIP = pygame.transform.rotate(pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT)), 90)  
    

    Please acknowledge that this function will rotate counterclockwise, and you can put negative angles to go clockwise.

    Here is the full documentation : https://www.pygame.org/docs/ref/transform.html#pygame.transform.rotate