# Importing required modules
import pygame
import sys
# Function to swap two numbers
def swap(a, b):
return b, a
# Function to return absolute value of number
def absolute(x):
return abs(x)
# Function to return integer part of a floating point number
def iPartOfNumber(x):
return int(x)
# Function to round off a number
def roundNumber(x):
return round(x)
# Function to return fractional part of a number
def fPartOfNumber(x):
return x - iPartOfNumber(x)
# Function to return 1 - fractional part of number
def rfPartOfNumber(x):
return 1 - fPartOfNumber(x)
# Function to draw a pixel on screen of given brightness
def drawPixel(screen, x, y, brightness):
c = int(255 * brightness)
pygame.draw.line(screen, (c, c, c), (x, y), (x+1, y))
# Function to draw an anti-aliased line
def drawAALine(screen, x0, y0, x1, y1):
steep = absolute(y1 - y0) > absolute(x1 - x0)
if steep:
x0, y0 = swap(x0, y0)
x1, y1 = swap(x1, y1)
if x0 > x1:
x0, x1 = swap(x0, x1)
y0, y1 = swap(y0, y1)
dx = x1 - x0
dy = y1 - y0
gradient = dy / dx if dx != 0 else 1
xpxl1 = x0
xpxl2 = x1
intersectY = y0
if steep:
for x in range(xpxl1, xpxl2 + 1):
drawPixel(screen, iPartOfNumber(intersectY), x, rfPartOfNumber(intersectY))
drawPixel(screen, iPartOfNumber(intersectY) - 1, x, fPartOfNumber(intersectY))
intersectY += gradient
else:
for x in range(xpxl1, xpxl2 + 1):
drawPixel(screen, x, iPartOfNumber(intersectY), rfPartOfNumber(intersectY))
drawPixel(screen, x, iPartOfNumber(intersectY) - 1, fPartOfNumber(intersectY))
intersectY += gradient
# Main function
def main():
pygame.init()
# Creating a window
screen = pygame.display.set_mode((640, 480))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Setting background color to white
screen.fill((255, 255, 255))
# Drawing a black anti-aliased line
drawAALine(screen, 80, 200, 550, 150)
# Updating the window
pygame.display.flip()
if __name__ == "__main__":
main()