I want to display a 500x500 image in the middle of the 500x500 window in the Pygame and in the rect.center.

Asked 1 years ago, Updated 1 years ago, 356 views

It's very long, so it's an excerpt, but as the title says
I want to display a 500x500 image in the middle of the 500x500 window in the Pygame and in the rect.center.
However, I couldn't find a good idea and I didn't know much about programming, so I couldn't search for it
I'm in trouble. What should I do?


#About game over screen display
   if gameover:
       mixer.music.load('musics/carcrush.wav')
       mixer.music.play()
       
       screen.blit(crash, crash_rect)

       
       gvgamen = pygame.image.load("gameovermoto2-3.png")
       gvgamen_rect = gvgamen.get_rect()
       gvgamen_rect.center = ("")
       screen.blit(gvgamen, gvgamen_rect)
       

   pygame.display.update()

python pygame

2023-03-28 19:04

1 Answers

By aligning gvgamen_rect.center with screen.get_rect().center, you can center the image to the center of the screen.

Change the gvgamen_rect.center = ("") in the code you are asking to gvgamen_rect.center = screen.get_rect().center.

Sample Code

import pygame
import sys

pygame.init()
screen = pygame.display.set_mode((500, 500))
gvgamen = pygame.image.load("gameovermoto2-3.png")

while True:
    screen.fill((0,0,0))
    # draw an image in the center of the screen
    gvgamen_rect = gvgamen.get_rect()
    gvgamen_rect.center = screen.get_rect().center
    screen.blit(gvgamen, gvgamen_rect)
    # One-liner code for drawing images in the center of the screen (equivalent to the code in the three lines above)
    #screen.blit(gvgamen, gvgamen.get_rect(center = screen.get_rect().center))

    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()


2023-03-28 20:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.