Pygame drawing 2

In the last post about pygame we’ve seen how to make a sort of drawing app. Now we want to make it better… In the first code the app draws circles when you move the mouse, but you cannot choose to not draw… so the lines are countinuous. Now we want to make the user able to draw when he presses a button. Let’s see how to do it using pygame.mouse.get_pressed method. This one returns a tuple with tre booleans, one for each button of the mouse so

1,0,0 means you clicked the 1st button

0,1,0 means you click the middle button

0,0,1 meand you click the 2nd button

Draw only when you click (but one rectangle at the time)

import pygame

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()

loop = True
press = False
while loop:
    try:
        #pygame.mouse.set_visible(False)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop = False
    
        px, py = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN:
            pygame.draw.rect(screen, (128,128,128), (px,py,10,10))

        if event.type == pygame.MOUSEBUTTONUP:
            press == False
        pygame.display.update()
        clock.tick(1000)
    except Exception as e:
        print(e)
        pygame.quit()
        
pygame.quit()

Draw continuosly when you click

import pygame

pygame.init()
screen = pygame.display.set_mode((600,400))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()

loop = True
press = False
while loop:
    try:
        #pygame.mouse.set_visible(False)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                loop = False
    
        px, py = pygame.mouse.get_pos()
        if pygame.mouse.get_pressed() == (1,0,0):
            pygame.draw.rect(screen, (128,128,128), (px,py,10,10))

        if event.type == pygame.MOUSEBUTTONUP:
            press == False
        pygame.display.update()
        clock.tick(1000)
    except Exception as e:
        print(e)
        pygame.quit()
        
pygame.quit()

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.