實驗 2 Scala 程式設計初級實踐

喝着农药吐泡泡o發表於2024-05-25

一實驗目的

二實驗平臺

三實驗內容和要求

1、計算級數

2、模擬圖形繪製

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

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

abstract class Shape(var location: Point) {
def moveTo(newLocation: Point): Unit = {
location = newLocation
}

def zoom(scale: Double): Unit
}

class Line(beginPoint: Point, var endPoint: Point) extends Shape(beginPoint) with Drawable {
override def draw(): Unit = {
println(s"Line:(${location.x},${location.y})--(${endPoint.x},${endPoint.y})")
}

override def moveTo(newLocation: Point): Unit = {
endPoint.shift(newLocation.x - location.x, newLocation.y - location.y)
location = newLocation
}

override def zoom(scale: Double): Unit = {
val midPoint = Point((endPoint.x + location.x) / 2, (endPoint.y + location.y) / 2)
location.x = midPoint.x + scale * (location.x - midPoint.x)
location.y = midPoint.y + scale * (location.y - midPoint.y)
endPoint.x = midPoint.x + scale * (endPoint.x - midPoint.x)
endPoint.y = midPoint.y + scale * (endPoint.y - midPoint.y)
}
}

class Circle(center: Point, var radius: Double) extends Shape(center) with Drawable {
override def draw(): Unit = {
println(s"Circle center:(${location.x},${location.y}),R=$radius")
}

override def zoom(scale: Double): Unit = {
radius = radius * scale
}
}

object MyDraw {
def main(args: Array[String]): Unit = {
val p = 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 circle = new Circle(Point(10, 10), 5)
circle.draw()
circle.moveTo(Point(30, 20))
circle.draw()
circle.zoom(0.5)
circle.draw()
}
}

3、統計學生成績

四實驗報告

相關文章