Apart from the draw module, pygame has another drawing module which is the gfxdraw module and this time we will use this module to draw lines on the screen.
Here is a program that will draw three lines using the three different line-drawing functions of gfxdraw!
# Import and initialize the pygame library
import pygame
import pygame.gfxdraw
pygame.display.init()
# set the caption on the panel
pygame.display.set_caption("Draw Some Drawing")
# windows height and width
windowwidth = 600
windowheight = 600
# Print this line on output panel if the initialize process is successful
if(pygame.display.get_init() == True):
print("Success initialize the game!")
# Initialize a window or screen for display
screen = pygame.display.set_mode([windowwidth, windowheight])
# Print the x, y size of the game display window
print("The windows size is " + str(pygame.display.get_window_size()))
# coordinate for the straight line, horizontal and vertical lines
pixel_x = 300
pixel_x1 = 350
pixel_y = 300
pixel_y1 = 350
# Run the game until the user asks to quit
running = True
while running:
# If the user clicks on the 'x' button on pygame display window then set running to false
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Fill the rectangles with blue color
screen.fill((0,0,255))
pygame.gfxdraw.line(screen, pixel_x, pixel_y1, pixel_x1, pixel_y1, pygame.Color(0, 0, 0)) # Draw a line
pygame.gfxdraw.hline(screen, pixel_x, pixel_x1, pixel_y, pygame.Color(0, 0, 0)) # Draw horizontal line on screen
pygame.gfxdraw.vline(screen, pixel_x, pixel_y, pixel_y1, pygame.Color(0, 0, 0)) # Draw vertical line on screen
pygame.display.flip() # refresh the screen
# Quit the game
pygame.display.quit()
We use pygame.gfxdraw.line, pygame.gfxdraw.hline and pygame.gfxdraw.vline to paint three lines like the above!