I want to write a program where if I click, a circle is drawn on the pygame screen. If I click again, another circle is drawn as well as a line connecting it to the previous circle drawn. Is there any way to track the coordinates of where you last clicked?
ps. I want to create like a star constellation effect after many clicks (to help you visualize)
Add a list for the mouse positions:
points = []
Add the position to list when the mouse is clicked:
if e.type == MOUSEBUTTONDOWN:
if e.button == 1:
points.append(e.pos)
Draw the points in a loop:
for pos in points:
draw.circle(screen,GREEN, pos, 10)
If there are at least 2 points, then the lines between the points can be drawn by pygame.draw.lines():
if len(points) > 1:
draw.lines(screen, GREEN, False, points)
Based on your previous question, I suggest the following:

from pygame import *
init()
size = width, height = 650, 650
screen = display.set_mode(size)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
running = True
myClock = time.Clock()
points = []
# Game Loop
while running:
for e in event.get():
if e.type == QUIT:
running = False
if e.type == MOUSEBUTTONDOWN:
if e.button == 1:
points.append(e.pos)
if e.button == 3:
points = []
screen.fill(BLACK)
if len(points) > 1:
draw.lines(screen, GREEN, False, points)
for pos in points:
draw.circle(screen,GREEN, pos, 10)
display.flip()
myClock.tick(60)
quit()
Alternatively the clicked position can be stored (prev_pos) and used the next time, when the mouse is clicked to draw a line.
I do not recommend this, because you'll lose the information about the clicked positions:
from pygame import *
init()
size = width, height = 650, 650
screen = display.set_mode(size)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
running = True
myClock = time.Clock()
prev_pos = None
# Game Loop
while running:
for e in event.get():
if e.type == QUIT:
running = False
if e.type == MOUSEBUTTONDOWN:
if e.button == 1:
if prev_pos != None:
draw.line(screen, GREEN, prev_pos, e.pos)
prev_pos = e.pos
draw.circle(screen, GREEN, e.pos, 10)
if e.button == 3:
prev_pos = None
screen.fill(BLACK))
display.flip()
myClock.tick(60)
quit()
I think that this will solve your problem: https://www.pygame.org/docs/ref/mouse.html
" pygame.mouse.get_pos() get the mouse cursor position get_pos() -> (x, y)
Returns the X and Y position of the mouse cursor. The position is relative to the top-left corner of the display. The cursor position can be located outside of the display window, but is always constrained to the screen."
You can use pygame.draw.circle() to draw a circle with a center at the point where the mouse is, and a polygon or lines if you'd like to connect them.
I hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With