DEADSOFTWARE

Closes #5: Reimplement world generator in kotlin
[cavedroid.git] / core / src / ru / deadsoftware / cavedroid / game / GameWorldGenerator.kt
1 package ru.deadsoftware.cavedroid.game
3 import com.badlogic.gdx.utils.TimeUtils
4 import kotlin.math.abs
5 import kotlin.random.Random
7 private fun generateHeights(width: Int, min: Int, max: Int, random: Random) = IntArray(width).apply {
8 set(0, (min + max) / 2)
9 for (x in 1 until width) {
10 val previous = get(x - 1)
11 var d = random.nextInt(-5, 6).let { if (it !in -4..4) it / abs(it) else 0 }
13 if (previous + d !in min..max) { d = -d }
14 if (lastIndex - x < abs(get(0) - previous) * 3) {
15 d = get(0).compareTo(previous).let { if (it != 0) it / abs(it) else 0 }
16 }
18 set(x, get(x - 1) + d)
19 }
20 }
22 /**
23 * Generates world of given width and height with given seed
24 * @param width world width
25 * @param height world height
26 * @param seed seed for random number generator
27 * @return pair of foreground and background layers
28 */
29 fun generate(width: Int, height: Int, seed: Long = TimeUtils.millis()): Pair<Array<IntArray>, Array<IntArray>> {
30 val random = Random(seed)
31 val foreMap = Array(width) { IntArray(height) }
32 val backMap = Array(width) { IntArray(width) }
33 val heightsMap = generateHeights(width, height / 2, height * 3 / 4, random)
35 for (x in 0 until width) {
36 val xHeight = heightsMap[x]
38 foreMap[x][xHeight] = GameItems.getBlockId("grass")
39 foreMap[x][height - 1] = GameItems.getBlockId("bedrock")
40 backMap[x][xHeight] = GameItems.getBlockId("grass")
41 backMap[x][height - 1] = GameItems.getBlockId("bedrock")
43 for (y in xHeight + 1 until height - 1) {
44 foreMap[x][y] = when {
45 y < xHeight + random.nextInt(5, 8) -> GameItems.getBlockId("dirt")
46 else -> GameItems.getBlockId("stone")
47 }
48 backMap[x][y] = foreMap[x][y]
49 }
50 }
51 return Pair(foreMap, backMap)
52 }