Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)
edited by

A few days ago I've started learning pygame. So, now I've got the code which allows me to draw different curves with the help of a mouse. My task is to fill the curve with a color. I know for sure that the curve is close

import pygame as py

import sys

py.init()

White = (255,255,255)

Black = (0,0,0)

clock = py.time.Clock()

H = 400

W = 600

sc = py.display.set_mode((W,H))

sc.fill(White)

py.display.set_caption('Curve drawing')

py.display.update()

draw = False

while 1:

    for i in py.event.get():

        if i.type == py.QUIT:

            py.image.save(sc,r'C:/Users/Xiaomi' + '/temporary.png')

            py.quit()

            sys.exit()

        elif i.type == py.MOUSEBUTTONDOWN:

            if i.button == 1:

                draw = True

            elif i.button == 2:

                sc.fill(White)

                py.display.update()

        elif i.type == py.MOUSEBUTTONUP:

            if i.button == 1:

                draw = False

    if draw == True:

        py.draw.circle(sc,Black,i.pos,7)

        py.display.update()

1 Answer

0 votes
by (36.8k points)
edited by

You could use the PyGame polygon drawing function to create a filled area bounded by all the mouse points.

So instead of drawing the circle at each point, keep adding a mouse position to the list of co-ordinates as a mouse moves. When a button is released, draw the filled polygon around all these points.

fill_coords = []    # points to make filled polygon

while 1:

    for i in py.event.get():

        if i.type == py.QUIT:

            py.image.save(sc,r'C:/Users/Xiaomi' + '/temporary.png')

            py.quit()

            sys.exit()

        elif i.type == py.MOUSEBUTTONDOWN:

            if i.button == 1:

                draw = True

                fill_coords = []                              # restart the polygon

            elif i.button == 2:

                sc.fill(White)

                py.display.update()

        elif i.type == py.MOUSEBUTTONUP:

            if i.button == 1:

                draw = False

                pygame.draw.polygon( sc, Black, fill_coords ) # filled polygon

        elif i.type == pygame.MOUSEMOTION:                    # when the mouse moves

            if ( draw ):

                fill_coords.append( i.pos )                   # remember co-ordinate

    mouse_position = pygame.mouse.get_pos()

    if draw == True:

        py.draw.circle(sc,Black,i.pos,7)

        py.display.update()

If you are a beginner and want to know more about Python the do check out the Data Science with Python Course

Browse Categories

...