import Foundation
//DDA 画线算法
/*
设画起始端点source(x,y) 到结束端点destination(x/y)的直线段为L(source,destination),则直线段L的斜率为
k= (destination.y-source.y)/(destination.x-source.x)
因为像素是整数值,所以需要找到最佳逼近L的像素的集合。
从L的起点source 的横坐标向L的终点destination一步一步前进,
用L的直线方程y=kx + b 来计算响应的y坐标,并取像素点(x,round(y))作为当前点的坐标。
*/
let rows = 20
let cols = 20
var g : Array<String>=[]
func gameInit(color:String)
for in 0..<rows (
for _in 0..<cols (
g.append(color)
func display() (
for i in 0..<rows (
for j in 0..<cols (
print(g[i*cols+j], separator: "", terminator: "")
print()
print(" 分割线----
func ddaLine(source:(x:Int,y:Int),destination:(x:Int,y:Int),color:String)
//两个端点重合
if(source==destination){
return
/1两个端点的x坐标相等
else if (source.x==destination.x)(
for newy in source.y...destination.y (
g[cols * newY + source.x] = color
/1两个端点的y坐标相等
else if (source.y==destination.y)(
for newX in source.x...destination.x (
g[cols ★ source.y + newX ] = color
//起始点的x坐标大于终点的x坐标
else if (source.x<destination.x)(
var dx:Float = 0, dy:Float = 0
var newY :Float = 0
var k : Float = 0
dx = Float(destination.x - source.x)
dy = Float(destination.y - source.y)
k=dy / dx
newY = Float(source.y)
for x in source.x...destination.x(
g[cols ★ Int(round(Double(newY)))+x] = color newY += k
else (
let nDestination = source
let nSource = destination
var dx:Float = 0, dy:Float =0
var newy : Float= 0
var k : Float = 0
dx = Float(nDestination.x - nSource.x)
dy = Float(nDestination.y - nSource.y)
k=dy / dx
newY = Float(nSource.y)
for x in nSource.x...nDestination.x (
g[cols ★ Int(round(Double(newY)))+x] = color newY += k
//-- 调用程序开始--
gameInit(color:"")
display()
ddaLine(source: (2,3), destination: (17,12), color: "★")display()
//-- 调用程序结束 --