1

Here I, have am tying to simply make 2 rectangles using pygame module. I have made them using 2 methods but they don't seem to work. Please suggest some that could work. (I am using Python 3.8.3)

Here is the code:

import pygame
pygame.init()

screen = pygame.display.set_mode((100, 100))

box_color = (255, 0, 0)
color = (0, 150, 100)

ybox = 20
xbox = 20

running = True
while running:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
        
    if event.type == pygame.KEYDOWN:
                                                             
        ybox += 5


    if (ybox >= 45):
        ybox = 45                                                               
pygame.draw.rect(screen, box_color, pygame.Rect(xbox, ybox, 50, 50), 2)
pygame.display.flip()

pygame.draw.rect(screen, box_color, pygame.Rect(20, 95, 50, 50), 2)
pygame.display.flip()

screen.fill(color)
pygame.display.update()
Tushar Singh
  • 209
  • 5
  • 7

1 Answers1

3

Your game is flickering because of the multiple calls of pygame.display.flip() and pygame.display.update(). One update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering.

Remove all calls of pygame.display.update() and pygame.display.flip() from your code, but call it once at the end of the application loop. However, clear the display before drawing the objects:

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            ybox += 5
        if (ybox >= 45):
            ybox = 45                                                               

    # clear disaply
    screen.fill(color)

    # draw objects
    pygame.draw.rect(screen, box_color, pygame.Rect(xbox, ybox, 50, 50), 2)
    pygame.draw.rect(screen, box_color, pygame.Rect(20, 95, 50, 50), 2)

    # update dispaly
    pygame.display.update()

The typical PyGame application loop has to:

Rabbid76
  • 202,892
  • 27
  • 131
  • 174