Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Create MS Paint Clone with Python and PyGame



It is a python script that enables the users to draw on the screen through the Pygame library. It records mouse events to enable you draw on it and each new draw may be of a random color and the brush size is also selectable. In the script the main ideas of block-based programming, such as event handling, drawing, and the utilization of the concept of randomness to control visuals are illustrated clearly and without unnecessary complexity.

Required Libraries

To run this script, you need to install the following library −

Pygame

This library is applied for the development of video games and graphical interface in Python. It deals within managing the windows and capturing the inputs from the user and even drawing things on the screen.

Go to your terminal and run this code −

pip install pygame

Steps to Create MS Paint Clone

Step 1: Importing Necessary Modules

You need to import the pygame − It provides the necessary functionality for creating the drawing interface

And, random − It is used to generate random colors for each new drawing stroke.

import pygame, random

Step 2: Initialize Pygame

To initialize pygame, use the init() method. The following code statement is used to initialize the pygame −

pygame.init()

Step 3: Setting Up the Display

Use the following code statements to create a window of size 1024x768 pixels where the drawing will occur −

screen = pygame.display.set_mode((1024, 768))

Step 4: Initializing Drawing Settings

To initialize drawing settings, use the following variables −

  • draw_on − A boolean flag that tracks whether the mouse button is held down.
  • last_pos − Keeps track of the last mouse position to draw continuous lines
  • color − Initial brush color, set to a shade of blue.
  • radius − Size of the brush, set to 15 pixels.

The following code statements are initializing drawing settings −

draw_on = False
last_pos = (0, 0)
color = (0, 128, 255)
radius = 15

Step 5: Defining the Round Line Function

Here is the code for defining the round line function −

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.draw.circle(srf, color, (x, y), radius)

Step 6: Handling the Quit Event

To handle the quit event, use the following code −

e = pygame.event.wait()
if e.type == pygame.QUIT:
   raise StopIteration

Step 7: Handling Mouse Button Down

To handle mouse button down event, use the following code −

if e.type == pygame.MOUSEBUTTONDOWN:
   color = (random.randrange(100, 256), random.randrange(100, 256), random.randrange(100, 256))
   pygame.draw.circle(screen, color, e.pos, radius)
   draw_on = True

Step 8: Handling Script Termination

Use the following code to handle script termination −

except StopIteration:
   pass
pygame.quit()

Code to Create MS Paint Clone with Python and PyGame

import pygame, random

# Initialize Pygame
pygame.init()

# Set up the display
screen = pygame.display.set_mode((1024, 768))  # Changed resolution to 1024x768

# Initialize drawing settings
draw_on = False
last_pos = (0, 0)
color = (0, 128, 255)  # Changed initial color to a blue shade
radius = 15  # Increased the brush size to 15

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.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(100, 256), random.randrange(100, 256), random.randrange(100, 256))  # Restricted color range to brighter colors
         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.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()

OUTPUT

When you execute this script a window will be created with background color white and nothing else. When you use the mouse to click and drag, paths in the colors appear as if they are virtually trailing the cursor. Every time you set off a new brush stroke, the colour selected from within the bright spectrum will be different from the previous one and so you actively drawing.

Pygame

Use your right click button in your mouse, you can also draw like this.

Code Explanation

  • The script starts from the importing of some modules for graphics and input control − Pygame; for random color creation − random.
  • It only starts Pygame and opens the drawing window with the desired resolution.
  • First, the aspect of the drawing is set like color selection and size of the brush used to draw.
  • A helper function roundline is made to make the line drawn more smooth whenever needed.
  • The idea of the main loop is to deal with different incidents such as mouse clicks and movements and draw on the canvas.

Still, the display to which the drawing is drawn is update frequently to reflect the drawing in real-time.

  • The script also stops running when the user closes the window, thus no abrupt actions are implemented in the termination of the script.
  • With every new mouse click, it gives off new colors making this a fun drawing tool.
  • The drawing is interactivity based on movements of the cursor with the help of the continuous event handling.
  • Last, the script exits Pygame, which also closes the window in which Shapes was being drawn.
  • Although very fundamental − this script provides a good example of accepting user input, as well as drawing graphical images using Python and Pygame.
python_reference.htm
Advertisements