How to flip the entire screen in pygame (including sprites)?

157 views Asked by At

Fairly new to pygame, creating chess to practise it. I want the screen to flip after each move including all the sprites, is there a way to do this?

I've tried window.blit(pygame.transform.rotate(window, 90), (0, 0)) but that only flips the screen and not the sprites Any help is appreciated, thanks in advance!

1

There are 1 answers

0
import random On

You need to blit the flipped surface after you've drawn your sprites.

Here is a minimal example, pressing Space flips the board.

import pygame

class Stone(pygame.sprite.Sprite):
    """Circle sprite"""

    def __init__(self, color, pos, radius=32):
        super().__init__()
        self.image = pygame.Surface((radius * 2, radius * 2), pygame.SRCALPHA)
        pygame.draw.circle(self.image, color, (radius, radius), radius)
        self.rect = self.image.get_rect(center=pos)

    def update(self):
        pass


FPS = 60
flipped = False
pygame.init()

window = pygame.display.set_mode((800, 800))
width, height = window.get_size()
square = width // 8
# set the titlebar
pygame.display.set_caption(f"Chessboard")

stones = pygame.sprite.Group()
# create a line of stones along the top row
pos = [square // 2, square // 2]
for x in range(8):
    stone = Stone("saddlebrown", pos)
    stones.add(stone)
    pos[0] += square  # move to the next square

clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_SPACE:
                flipped = not flipped

    # draw surface - fill background
    window.fill(pygame.color.Color("black"))
    ## draw board, white is top left
    white = True
    for x in range(8):
        for y in range(8):
            if white:
                tile_rect = pygame.Rect(x * square, y * square, square, square)
                pygame.draw.rect(window, "white", tile_rect)
            white = not white
        white = not white  # end of row, toggle color again.
    ## update game state
    stones.update()
    ## draw sprites
    stones.draw(window)

    if flipped:
        # flip in Y direction
        flip_surface = pygame.transform.flip(window, False, True)
        # draw over the original surface
        window.blit(flip_surface, (0, 0))

    # show surface
    pygame.display.update()
    # limit frames
    clock.tick(FPS)
pygame.quit()