Advertisement
ollikolli

Wave function collapse SQUARE

Nov 5th, 2023
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.98 KB | None | 0 0
  1. import scala.collection.mutable.{ArrayBuffer, Buffer}
  2. import scala.util.Random
  3.  
  4. class Square(grid: WaveFunctionCollapse, val location: GridPos):
  5.   var tile: Option[String] = None
  6.   val boundary       = Buffer.fill[Option[Char]](8)(None)
  7.   var plausibleTiles = ArrayBuffer[String]() ++ AllTiles.allStrings
  8.  
  9.  
  10.   /**
  11.     * Fixes a single element in the boundary and removes incompatible tiles.
  12.     * @param placeOnBoundary index of the element on the boundary
  13.     * @param value value to be set in the boundary
  14.     */
  15.   def fix(placeOnBoundary: Int, value: Char): Unit =
  16.     this.boundary(placeOnBoundary) = Some(value)
  17.     this.plausibleTiles = this.plausibleTiles.filter( _(placeOnBoundary) == value)
  18.   end fix
  19.  
  20.   /**
  21.    * Calculates the entropy of the tile, that is - the number of plausible tiles.
  22.    * @return the number of plausible tiles
  23.    */
  24.   def entropy: Int = plausibleTiles.size
  25.  
  26.   /**
  27.   * Selects a random tile from all plausible tiles. Updates neighboring tiles if necessary.
  28.   */
  29.   def collapse(): Unit =
  30.     val chosenTile = Random.shuffle(this.plausibleTiles).head
  31.     this.tile = Some(chosenTile)
  32.     var index = 0
  33.     while index <= 7 do
  34.       propagateChange(index, this.tile.get(index))
  35.       index += 1
  36.      
  37.   end collapse
  38.  
  39.   /**
  40.    * Propagates the change in this square's boundary to boundaries and plausible tiles of neighboring squares.
  41.    * @param boundaryIndex index in this squares boundary
  42.    * @param fixedValue the value to be set in the boundary
  43.    */
  44.  
  45.   def propagateChange(boundaryIndex: Int, fixedValue: Char): Unit =
  46.     for neighbor <- neighborBoundaries do
  47.       if neighbor.mine == boundaryIndex && !(this.location.x == 0 && neighbor.dir == West) && !(this.location.x == 9 && neighbor.dir == East) && !(this.location.y == 0 && neighbor.dir == North) && !(this.location.y == 9 && neighbor.dir == South) then
  48.         this.grid.elementAt(this.location.neighbor(neighbor.dir)).fix(neighbor.theirs, fixedValue)
  49.   end propagateChange
  50.  
  51. end Square
  52.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement