patternMinor
Generating a game board with squares in a rectangle
Viewed 0 times
withrectanglesquaresgeneratinggameboard
Problem
I am trying to generate a game board (similar to a Monopoly board). I am new to Scala and am thinking that there may be a better way to do this. But improvements to the code are also welcome.
class BoardGenerator(squaresPerPlayer: Int, numberOfPlayers: Int) {
val directionTuples = Array((1, 0), (0, 1), (-1, 0), (0, -1))
def generate: List[Square] = {
val squaresPerSide = squaresPerPlayer * numberOfPlayers / 4
def generateBoard(squaresLeft: Int, direction: Int, x: Int, y: Int): List[Square] = {
if (direction == 4)
Nil
else if (squaresLeft > 1)
Square(x, y) :: generateBoard(squaresLeft - 1, direction,
x + directionTuples(direction)._1, y + directionTuples(direction)._2)
else
Square(x, y) :: generateBoard(squaresPerSide, direction + 1,
x + directionTuples(direction)._1, y + directionTuples(direction)._2)
}
generateBoard(squaresPerSide, 0, 0, 0)
}
}Solution
-
-
Instead of having a bunch of
-
Instead of passing
directions as a variable name instead of directionTuples. -
Instead of having a bunch of
ifs in generateBoard, use pattern matching.-
Instead of passing
x: Int, y: Int in generateBoard, just pass a tuple which you could call currentPos. You could define a function to add the direction tuple with the currentPos tuple instead of typing x + directionTuples(direction)._1, y + directionTuples(direction)._2 twice. (There might actually be a very easy way to add (Int, Int) + (Int, Int) in Scala, but I can't think of it right now.)Context
StackExchange Code Review Q#73593, answer score: 2
Revisions (0)
No revisions yet.