我是Scala的新成员,正在使用Scala中的处理库,我在这里有2个问题:
val grid: Array[Cell] = Array()
val w = 60
val rows = height/w
val cols = width /w
override def setup(): Unit = {
for(j <- 0 until rows;
i <- 0 until cols){
val cell = new Cell(i,j)
grid :+ cell
println(s"at row : $j, at col: $i") //it compiles only once (at row : 0,
} //at col: 0 )
}
override def draw(): Unit = {
background(0)
grid.foreach(cell => cell.display())//nothing happens
}
但是如果我在嵌套循环中将变量rows
和cols
替换为height/w
和width/w
,则如下所示:
for(j <- 0 until height/w;
i <- 0 until width/w){
val cell = new Cell(i,j)
grid :+ cell
println(s"at row : $j, at col: $i") //it compiles ordinary as nested
} //for loop
第二个问题在Cell
类中,
class Cell(i: Int,j:Int){
def display(): Unit = {
val x = this.i * w
val y = this.j * w
println("it works")//doesn't work
//creating a square
stroke(255)
line(x,y,x+w,y)//top
line(x+w,y,x+x,y+w)//right
line(x,y+w,x+w,y+w)//bottom
line(x,y,x,y+w)//left
}
}
在函数draw()
上调用时,方法显示不起作用,但没有错误显示
答案 0 :(得分:1)
使用tabulate
初始化您的Array
:
val grid = Array.tabulate(rows * cols) { i => new Cell(i % cols, i / cols) }
如果您对display
函数仍然有疑问,请将其作为单独的问题发布。