Windows10 、Python3.8、一个用了快20年的脑子…
用Python写了个Bresenham算法的demo,写的比较简单,不喜勿喷,天下程序员是一家
主要是针对计算机图形学留的作业写的,结果忘了写针对斜率小于等于0的部分!
import math #好像没有用到???
#求斜率
def slope(x1,y1,x2,y2):
x_1 = float(x1)
y_1 = float(y1)
x_2 = float(x2)
y_2 = float(y2)
slope = (y_2-y_1)/(x_2-x_1)
return slope
#求方程式,啰啰嗦嗦了一大堆,其实不如把转换类型搞到主函数
def Linear_equation(x1,y1,x2,y2,x,y):
k = slope(x1,y1,x2,y2)
x_1 = float(x1)
y_1 = float(y1)
x_2 = float(x2)
y_2 = float(y2)
f = y-y_1-k*(x-x_1)
return f
def judge(slope):
if slope>=1:
print("k>=1")
elif slope>=0 and slope<1:
print("k属于0-1")
else:
print("k<0")
#算法主体,只能测算出斜率大于零的情况
#因为我是小小年纪就健忘的带学生
def Bresenhan(x1,y1,x2,y2):
a = float(x1)
b = float(y1)
c = float(x2)
d = float(y2)
slope = (d - b) / (c - a)
if slope>1:
while a<=c and b<=d:
x = a+0.5
y = b+1.0
print("(",a,b,")")
f = Linear_equation(x1,y1,x2,y2,x,y)
if f>0:
a += 1
b += 1
elif f<=0:
a += 0
b += 1
elif slope>0 and slope<1:
while a<=c and b<=d:
x = a + 1.0
y = b + 0.5
print("(", a, b, ")")
f = Linear_equation(x1,y1,x2,y2,x,y)
if f>0:
a += 1
b += 0
elif f<=0:
a += 1
b += 1
else:
exit()
def main():
#try一下
try:
x1 = input("请输入x1:")
y1 = input("请输入y1:")
x2 = input("请输入x2:")
y2 = input("请输入y2:")
k = slope(x1,y1,x2,y2)
judge(k)
Bresenhan(x1, y1, x2, y2)
#这部分主要就是监控一下异常
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.请确认输入的数据为数字")
except:
print("Unexpected error:发生未知错误,导致程序崩溃")
raise
if __name__ == '__main__':
main()
import math #好像没有用到???
#求斜率
def slope(x1,y1,x2,y2):
x_1 = float(x1)
y_1 = float(y1)
x_2 = float(x2)
y_2 = float(y2)
slope = (y_2-y_1)/(x_2-x_1)
return slope
#求方程式,啰啰嗦嗦了一大堆,其实不如把转换类型搞到主函数
def Linear_equation(x1,y1,x2,y2,x,y):
k = slope(x1,y1,x2,y2)
x_1 = float(x1)
y_1 = float(y1)
x_2 = float(x2)
y_2 = float(y2)
f = y-y_1-k*(x-x_1)
return f
#判断斜率大小,这就是刚开始写伪代码的一个产物
def judge(slope):
if slope>=1:
print("k>=1")
elif slope>=0 and slope<1:
print("k属于0-1")
else:
print("k<0")
#算法主体,只能测算出斜率大于零的情况
def Bresenhan(x1,y1,x2,y2):
a = float(x1)
b = float(y1)
c = float(x2)
d = float(y2)
slope = (d - b) / (c - a)
if slope>1:
while a<=c and b<=d:
x = a+0.5
y = b+1.0
print("(",a,b,")")
f = Linear_equation(x1,y1,x2,y2,x,y)
if f>0:
a += 1
b += 1
elif f<=0:
a += 0
b += 1
elif slope>0 and slope<1:
while a<=c and b<=d:
x = a + 1.0
y = b + 0.5
print("(", a, b, ")")
f = Linear_equation(x1,y1,x2,y2,x,y)
if f>0:
a += 1
b += 0
elif f<=0:
a += 1
b += 1
else:
exit()
def main():
#try一下
try:
x1 = input("请输入x1:")
y1 = input("请输入y1:")
x2 = input("请输入x2:")
y2 = input("请输入y2:")
k = slope(x1,y1,x2,y2)
judge(k)
Bresenhan(x1, y1, x2, y2)
#这部分主要就是监控一下异常
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.请确认输入的数据为数字")
except:
print("Unexpected error:发生未知错误,导致程序崩溃")
raise
if __name__ == '__main__':
main()