package snake /** m04 spawn: placing apples with the Random from Random.scala. */ object Spawn: def freeCells(state: GameState): List[Point] = for y <- Util.range(state.height) x <- Util.range(state.width) p = Point(x, y) if !Util.contains(state.snake, p, _ == _) yield p def spawnApple(state: GameState): GameState = if state.apple.isDefined || state.status != Status.Playing then state else val cells = freeCells(state) if cells.isEmpty then state.copy(status = Status.Won) else val (i, seed) = Random.intBelow(cells.length).run(state.seed) state.copy(apple = Some(cells(i)), seed = seed) def tick(state: GameState): GameState = spawnApple(Rules.advance(state)) def newGame(seed: Long): GameState = spawnApple(Model.initialState(seed))