How to create MS Paint clone with Python and pygame

后端 未结 4 1380
花落未央
花落未央 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:09

    Here's a simplified version of Matthew's example which is unfortunately not runnable.

    When the mouse is moved, pygame.MOUSEMOTION events are added to the event queue which contain the position and the relative movement. You can use these to calculate the previous position and then pass the two points to pygame.draw.line.

    pygame.MOUSEMOTION events also have a buttons attribute which you can use to check which mouse button is currently down.

    import os
    import random
    
    import pygame as pg
    
    
    class App:
    
        def __init__(self):
            os.environ['SDL_VIDEO_CENTERED'] = '1'
            pg.init()
            self.w, self.h = 800, 600
            self.screen = pg.display.set_mode((self.w, self.h))
            self.screen.fill(pg.Color('white'))
            self.clock = pg.time.Clock()
            self.drawcolor = (0, 0, 0)
    
        def mainloop(self):
            while True:
                for event in pg.event.get():
                    if event.type == pg.QUIT:
                        return
                    elif event.type == pg.MOUSEBUTTONDOWN:
                        if event.button == 2:  # Color picker (middle mouse button).
                            self.drawcolor = self.screen.get_at(pos)
                            # Pick a random color.
                            # self.drawcolor = [random.randrange(256) for _ in range(3)]
                    elif event.type == pg.MOUSEMOTION:
                        pos, rel = event.pos, event.rel
                        if event.buttons[0]:  # If the left mouse button is down.
                            # Draw a line from the pos to the previous pos.
                            pg.draw.line(self.screen, self.drawcolor, pos, (pos[0]-rel[0], pos[1]-rel[1]), 5)
                        elif event.buttons[2]:  # If the right mouse button is down.
                            # Erase by drawing a circle.
                            pg.draw.circle(self.screen, (255, 255, 255), pos, 30)
    
                pg.display.flip()
                self.clock.tick(30)
    
    
    if __name__ == '__main__':
        app = App()
        app.mainloop()
        pg.quit()
    

提交回复
热议问题