I have just started looking into Scala, and I decided to make a roguelike to get my feet wet. I come from a Java background, and I am having trouble working with the Scala Arrays.
When I try to make a level, what I call a room, I picture a two dimensional array with # as walls. I try to use, as I understand it, a Scala nested for-loop to place the # wall characters when i || j are 0, or when i || j is at the end of the array. Inside the braces of the for-loop, I have temp(i, j) = '#' which is giving me the error "Expression of type Char doesn't conform to expected type, Nothing" in my IDE, IntelliJ.
I have posted my code below, and if you could help me format and/or work with my Array correctly, that would be great.
class Room
{
val room = generate
def generate: Array[Char] =
{
var temp = Array[Char](10, 10)
for (i: Int <- 0 to temp.length; j: Int <- 0 to temp.length)
{
if (i == 0 || j == 0 || i == temp.length-1 || j == temp.length-1)
temp(i, j) = '#'
}
return temp
}
def print: Unit =
{
for (i <- 0 to 10)
{
var line: String = ""
for (j <- 0 to 10)
{
line += room(i, j)
}
println(line)
}
}
}
var temp = Array[Char](10, 10) creates a 1-dimension Array containing two linefeed characters (10 being its value in ascii).
You'll want to use var temp = Array.ofDim[Char](10,10) instead. You can then access a cell using temp(i)(j) (and not temp(i, j)).
Also note that for (i <- 0 to 10) {} will cause an ArrayIndexOutOfBoundsException. You'll want to use for (i <- 0 until 10) {} instead.
You could also use the Array.tabulate method :
// Dummy implementation
scala> def calculateCellValue(i: Int, j: Int) =
if (i == 0 || j == 0 || i == 9 || j == 9) '#' else 'x'
scala> val temp = Array.tabulate(10,10)(calculateCellValue)
temp: Array[Array[Char]] = Array(Array(#, #, #, #, #, #, #, #, #, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, x, x, x, x, x, x, x, x, #),
Array(#, #, #, #, #, #, #, #, #, #))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With