I want to draw a rectangle with a button click , but the problem is with every loop it updates the display , display is filled with a color So the rectangle is only seen for a brief period of time. How to solve this.
JavaScript
x
19
19
1
while not run:
2
3
display.fill((130,190,255) )
4
5
for event in pygame.event.get():
6
if event.type == pygame.QUIT:
7
exit_game = True
8
9
if event.type == pygame.KEYDOWN:
10
if event.key == pygame.K_q:
11
p_x -= 30
12
13
if event.key == pygame.K_p:
14
p_x += 30
15
16
if event.key == pygame.K_g:
17
18
pygame.draw.rect(display , (0,0,0) ,((p_x + 25),1309 ,20,30))
19
Advertisement
Answer
You have to draw the rectangle in the application loop. For example add a new rectangle to a list when g is pressed. Draw each rectangles in the list in the application loop
JavaScript
1
24
24
1
rectangles = []
2
3
exit_game = False
4
while not exit_game:
5
for event in pygame.event.get():
6
if event.type == pygame.QUIT:
7
exit_game = True
8
9
if event.type == pygame.KEYDOWN:
10
if event.key == pygame.K_q:
11
p_x -= 30
12
if event.key == pygame.K_p:
13
p_x += 30
14
if event.key == pygame.K_g:
15
rectangles.append((p_x + 25, 1309, 20, 30))
16
17
display.fill((130,190,255))
18
19
pygame.draw.rect(display, (0,0,0), (p_x + 25, 1309, 20, 30), 1)
20
for rect in rectangles:
21
pygame.draw.rect(display, (0,0,0), rect)
22
23
pygame.display.update()
24