CC calculation: _draw_line - arnthor89/pygame GitHub Wiki
CC calculation _draw_line
Function
def _draw_line(surf, color, x1, y1, x2, y2):
'''draw a non-horizontal line (without anti-aliasing).'''
# Variant of https://en.wikipedia.org/wiki/Bresenham's_line_algorithm
#
# This strongly differs from craw.c implementation, because we use a
# "slope" variable (instead of delta_x and delta_y) and a "error" variable.
# And we can not do pointer-arithmetic with "BytesPerPixel", like in
# the C-algorithm.
if x1 == x2:
# This case should not happen...
raise ValueError
slope = abs((y2 - y1) / (x2 - x1))
error = 0.0
if slope < 1:
# Here, it's a rather horizontal line
# 1. check in which octants we are & set init values
if x2 < x1:
x1, x2 = x2, x1
y1, y2 = y2, y1
y = y1
dy_sign = 1 if (y1 < y2) else -1
# 2. step along x coordinate
for x in range(x1, x2 + 1):
set_at(surf, x, y, color)
error += slope
if error >= 0.5:
y += dy_sign
error -= 1
else:
# Case of a rather vertical line
# 1. check in which octants we are & set init values
if y1 > y2:
x1, x2 = x2, x1
y1, y2 = y2, y1
x = x1
slope = 1 / slope
dx_sign = 1 if (x1 < x2) else -1
# 2. step along y coordinate
for y in range(y1, y2 + 1):
set_at(surf, x, y, color)
error += slope
if error >= 0.5:
x += dx_sign
error -= 1
Control flow graph
def _draw_line(surf, color, x1, y1, x2, y2):
#1
if x1 == x2:
#3
raise ValueError
#2
slope = abs((y2 - y1) / (x2 - x1))
error = 0.0
if slope < 1:
#5
if x2 < x1:
#8
x1, x2 = x2, x1
y1, y2 = y2, y1
#7
y = y1
##dy_sign = 1 if (y1 < y2) else -1
if (y1 < y2):
#10
dy_sign = 1
else:
#11
dy_sign = -1
#9
for x in range(x1, x2 + 1):
#13
set_at(surf, x, y, color)
error += slope
if error >= 0.5:
#15
y += dy_sign
error -= 1
#14
#12
else:
#6
if y1 > y2:
#17
x1, x2 = x2, x1
y1, y2 = y2, y1
#16
x = x1
slope = 1 / slope
##dx_sign = 1 if (x1 < x2) else -1
if (x1 < x2):
#19
dx_sign = 1
else:
#20
dx_sign = -1
#18
for y in range(y1, y2 + 1):
#22
set_at(surf, x, y, color)
error += slope
if error >= 0.5:
#24
x += dx_sign
error -= 1
#23
#21
#4
https://i.imgur.com/fBuIwBF.png
Calculation
- Edges = 34
- Nodes = 24
- Connected components = 1
34 - 24 + 2*1 = 12