A question about Pygame. Time synchronization of events
def draw_pixel(position):
global SIZE
global COLOR
SCREEN.fill(COLOR, (position, SIZE))
while True: # main loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
FLAG = True
if event.type == MOUSEBUTTONUP:
FLAG = False
if FLAG:
pos = pygame.mouse.get_pos()
draw_pixel(pos)
change_brush_size_button.draw_button()
pygame.display.update()
The usual drawing machine. Hold down the left button - you draw a line in one pixel. But the line turns out to be jerky, because, as I understood, some time passes between getting the current mouse position and drawing the pixel. I may be wrong about the reason, but I still think that somehow the whole thing should be properly tied to time. When it comes to moving a character's sprite in a game, I understand how to do it. There's just a need to update the time at the beginning of each cycle and multiply the time by the speed of the character. But that's where I got confused. I know that instead of drawing individual pixels, you can draw lines (pygame. draw. line ()). But it doesn't suit me in this situation. You need to make the drawing of individual pixels smooth and continuous, if possible. As a result, this should turn out to be an editor for pixel art graphics, so I need control over individual pixels. Can someone tell me which direction to dig in?
1 answers
In short, I found the solution myself. Maybe it's clumsy and cyclical, but it works the way I originally needed it. I googled the line drawing algorithm, sawed it in Python. Now I draw with lines, but I have control over the rendering of each individual pixel. The algorithm is called the "Bresenham Algorithm", if anyone is interested or needs it.
def draw_line(x1, y1, x2, y2):
delta_x = abs(x2 - x1)
delta_y = abs(y2 - y1)
if x1 < x2:
sign_x = 1
else:
sign_x = -1
if y1 < y2:
sign_y = 1
else:
sign_y = -1
error = delta_x - delta_y
draw_pixel([x2, y2])
while (x1 != x2 or y1 != y2):
draw_pixel([x1, y1])
error_2 = error * 2
if error_2 > -delta_y:
error -= delta_y
x1 += sign_x
if error_2 < delta_x:
error += delta_x
y1 += sign_y
while True: # main loop
pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
FLAG = True
if event.type == MOUSEBUTTONUP:
FLAG = False
if FLAG:
new_pos = pygame.mouse.get_pos()
draw_line(pos[0], pos[1], new_pos[0], new_pos[1])
pygame.display.flip()