使用pygame旋转图像

Pra*_*hal 7 python pygame python-2.7

我是pygame的新手,想要编写一些代码,只需每10秒将图像旋转90度.我的代码看起来像这样:

    import pygame
    import time
    from pygame.locals import *
    pygame.init()
    display_surf = pygame.display.set_mode((1200, 1200))
    image_surf = pygame.image.load("/home/tempuser/Pictures/desktop.png").convert()
    imagerect = image_surf.get_rect() 
    display_surf.blit(image_surf,(640, 480))
    pygame.display.flip()
    start = time.time()
    new = time.time()
    while True:
        end = time.time()
        if end - start > 30:
            break
        elif end - new  > 10:
            print "rotating"
            new = time.time()
            pygame.transform.rotate(image_surf,90)
            pygame.display.flip()
Run Code Online (Sandbox Code Playgroud)

此代码不起作用,即图像不旋转,尽管每10秒钟在终端中打印"旋转".有人能告诉我我做错了什么吗?

slo*_*oth 13

pygame.transform.rotate不会旋转Surface到位,而是返回一个新的,旋转的Surface.即使它会改变现有的Surface,你也必须再次在显示器表面上进行blit.

你应该做的是跟踪变量中的角度,90每隔10秒增加一次,然后将新的blit Surface加到屏幕上,例如

angle = 0
...
while True:
    ...
    elif end - new  > 10:
        ...
        # increase angle
        angle += 90
        # ensure angle does not increase indefinitely
        angle %= 360 
        # create a new, rotated Surface
        surf = pygame.transform.rotate(image_surf, angle)
        # and blit it to the screen
        display_surf.blit(surf, (640, 480))
        ...
Run Code Online (Sandbox Code Playgroud)