编辑代码

import Foundation
//DDA 画线算法
/*
设画起始端点 souroe((x,y) 到结束端点 destination (x.y)的直线段为工(source,
destination),则直线段L的斜率为
k
= (destination. y-source. y) / (destinat ion.x-source . x)
因为像素是整数值,所以需要找到最佳逼近L的像素的集合。从工的起点source 的横坐标台
L的終点 destination一步一步前进,用L的直线方程y=kx+b来计算响应的y坐标,并取修
素点 (x,round(y))作为当前点的坐标。
*/
let rows = 20
let cols = 20

var q : 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 adaLine (source: (x: Int, y: Int), destination: (x: Int, y: Int) , color: String){
    //两个端点重合
if (source==destination){
    return
 }

//两个端点的X坐标相等。
else if(source.x==destination.x) {
    for hewY in source.y...destination.y {
        g[cols * newY + source.x) = color
    }
}


//两个端点的y坐标相等。
e1se if(source.y==destination.y) {
    for newX in source.x...destinaticn.x {
        g[cols * aource,y + newX ] = sclor
    }
}

//起始点的X坐标大于终点的x坐标。
else if (sourve.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 = Ploat(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()
//结束