2. 模拟图形绘制

case class Point(var x:Double,var y:Double) extends Drawable{
  def shift(deltaX:Double,deltaY:Double): Unit = {
    x+=deltaX;
    y+=deltaY
  }
}

trait Drawable{
  def draw(): Unit = {
    println(this.toString)
  }
}

abstract class Shape(val position: Point){
  def moveTo(newPosition: Point): Unit
  def zoom(factor: Double): Unit
}

class Line(start: Point, end: Point) extends Shape(start) with Drawable{
  private var endPoint: Point = end

  override def moveTo(newPosition: Point): Unit = {
    //这里所使用的position其实是start 用完之后在进行更新 这样的话就实现了可以从移动后的点继续进行移动
    val deltaX = newPosition.x - position.x
    val deltaY = newPosition.y - position.y
    position.x = newPosition.x
    position.y = newPosition.y
    endPoint.shift(deltaX, deltaY)
  }

  override def zoom(factor: Double): Unit = {
    val deltaX = endPoint.x - position.x
    val deltaY = endPoint.y - position.y
    endPoint.x = position.x + deltaX * factor
    endPoint.y = position.y + deltaY * factor
  }

  override def draw(): Unit = {
    println(s"Line:(${position.x},${position.y})--(${endPoint.x},${endPoint.y})")
  }
}

class Circle(center: Point, radius: Double) extends Shape(center) with Drawable{
  private var r: Double = radius

  override def moveTo(newPosition: Point): Unit = {
    position.x = newPosition.x
    position.y = newPosition.y
  }

  override def zoom(factor: Double): Unit = {
    r *= factor
  }

  override def draw(): Unit = {
    println(s"Circle center:(${position.x},${position.y}),R=${r}")
  }
}

object test2{
  def main(args: Array[String]): Unit = {
    val p=new Point(10,30)
    p.draw()
    val line1 = new Line(Point(0,0),Point(20,20))
    line1.draw()
    line1.moveTo(Point(5,5)) //移动到一个新的点
    line1.draw()
    line1.zoom(2) //放大两倍
    line1.draw()
    val cir= new Circle(Point(10,10),5)
    cir.draw()
    cir.moveTo(Point(30,20))
    cir.draw()
    cir.zoom(0.5)
    cir.draw()
  }
}

posted @ 2024-02-01 17:28  会秃头的小白  阅读(16)  评论(0编辑  收藏  举报