why this code is not letting me draw using the rectangle but just moving the rectangle?

Viewed 30
import pygame

pygame.init()

win = pygame.display.set_mode((800, 600))

Listing all pixels in pygame window in an array

pts = pygame.PixelArray(win)

Creating some color constants

# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
RED = (255, 0, 0)
GREY = (128, 128, 128)

clicked = False

clock = pygame.time.Clock()

# GAME LOOP

while True:
    win.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

Checking if left mousebutton if clicked and held

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                clicked = True

Checking if mousebutton released

        elif event.type == pygame.MOUSEBUTTONUP:
            clicked = False

I don't know if something is wrong down here.

    if clicked:
        mouse_X, mouse_Y = pygame.mouse.get_pos()
        for a in range(mouse_X, mouse_X + 79):
            pts[a][mouse_Y:mouse_Y + 60] = GREEN

    pygame.display.update()
    clock.tick(250)
1 Answers

This is a problem of your logic. The rectangle is not drawn permanently.
pts[a][mouse_Y:mouse_Y + 60] = GREEN changes a pixel in the win Surface. However win.fill(BLACK) turns all the pixel in win into BLACK.

Copy the "win" surface as soon as a rectangle has been placed on a permanant_win Surface. blit the Surface as the background of the window at the beginning of the application loop:

import pygame
pygame.init()
win = pygame.display.set_mode((800, 600))

BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
clicked = False
clock = pygame.time.Clock()
permanant_win = win.copy()

while True:
    win.blit(permanant_win, (0, 0))

    make_permanent = False
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                clicked = True
        elif event.type == pygame.MOUSEBUTTONUP:
            make_permanent = True

    if clicked:
        mouse_X, mouse_Y = pygame.mouse.get_pos()
        pts = pygame.PixelArray(win)
        for a in range(mouse_X, mouse_X + 79):
            pts[a][mouse_Y:mouse_Y + 60] = GREEN
        pts = None
        if make_permanent:
            permanant_win = win.copy()

    pygame.display.update()
    clock.tick(250)
Related