How to create MS Paint clone with Python and pygame

后端 未结 4 1379
花落未央
花落未央 2020-12-13 15:50

As I see it, there are two ways to handle mouse events to draw a picture.

The first is to detect when the mouse moves and draw a line to where the mouse is, shown he

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 16:24

    Not blitting at each loop step can improve the speed of the drawing (using this code adapted from the previous one allow to remove lag problem on my machine)

    import pygame, random
    
    screen = pygame.display.set_mode((800,600))
    
    draw_on = False
    last_pos = (0, 0)
    color = (255, 128, 0)
    radius = 10
    
    def roundline(srf, color, start, end, radius=1):
        dx = end[0]-start[0]
        dy = end[1]-start[1]
        distance = max(abs(dx), abs(dy))
        for i in range(distance):
            x = int( start[0]+float(i)/distance*dx)
            y = int( start[1]+float(i)/distance*dy)
            pygame.display.update(pygame.draw.circle(srf, color, (x, y), radius))
    
    try:
        while True:
            e = pygame.event.wait()
            if e.type == pygame.QUIT:
                raise StopIteration
            if e.type == pygame.MOUSEBUTTONDOWN:
                color = (random.randrange(256), random.randrange(256), random.randrange(256))
                pygame.draw.circle(screen, color, e.pos, radius)
                draw_on = True
            if e.type == pygame.MOUSEBUTTONUP:
                draw_on = False
            if e.type == pygame.MOUSEMOTION:
                if draw_on:
                    pygame.display.update(pygame.draw.circle(screen, color, e.pos, radius))
                    roundline(screen, color, e.pos, last_pos,  radius)
                last_pos = e.pos
            #pygame.display.flip()
    
    except StopIteration:
        pass
    
    pygame.quit()
    

提交回复
热议问题