Skip to content

Commit

Permalink
More accurate and smart handling of the unused keys
Browse files Browse the repository at this point in the history
  • Loading branch information
SpaiR committed Jul 14, 2019
1 parent fab8c48 commit 78e2a84
Showing 1 changed file with 41 additions and 30 deletions.
71 changes: 41 additions & 30 deletions src/main/kotlin/io/github/spair/strongdmm/logic/map/save/SaveMap.kt
Original file line number Diff line number Diff line change
Expand Up @@ -99,41 +99,52 @@ class SaveMap(private val dmm: Dmm) {

// Fill remaining tiles (use unused keys or generate a new one)
private fun fillRemainingTiles() {
if (outputDmmData.tileContentsWithKeys.size != outputDmmData.tileContentsWithLocations.size) {
for (y in outputDmmData.maxY downTo 1) {
for (x in 1..outputDmmData.maxX) {
val location = TileLocation.of(x, y)
val tileContent = dmm.getTileContentByLocation(location)

if (!outputDmmData.hasKeyByTileContent(tileContent)) {
var key: String? = null

if (unusedKeys.isEmpty()) {
key = keyGenerator.createKey()
} else {
// from all unused keys we will try to find the most appropriate
for (unusedKey in unusedKeys) {
if (dmm.initialDmmData.getKeyByLocation(location) == unusedKey) {
key = unusedKey
unusedKeys.remove(key)
break
}
}

// if no appropriate key found use first available
if (key == null) {
val it = unusedKeys.iterator()
key = it.next()
it.remove()
}
}
if (outputDmmData.tileContentsWithKeys.size == outputDmmData.tileContentsWithLocations.size) {
unusedKeys.clear()
return // All locations have its own key
}

outputDmmData.addKeyAndTileContent(key, tileContent)
}
val locsWithoutKey = mutableListOf<TileLocation>()

// Collect all locs without keys
for (y in outputDmmData.maxY downTo 1) {
for (x in 1..outputDmmData.maxX) {
val location = TileLocation.of(x, y)
val tileContent = dmm.getTileContentByLocation(location)

if (!outputDmmData.hasKeyByTileContent(tileContent)) {
locsWithoutKey.add(location)
}
}
}

// Try to find the most appropriate key to the location
for (unusedKey in unusedKeys.toSet()) {
for (location in locsWithoutKey) {
if (dmm.initialDmmData.getKeyByLocation(location) == unusedKey) {
unusedKeys.remove(unusedKey)
outputDmmData.addKeyAndTileContent(unusedKey, dmm.getTileContentByLocation(location))
locsWithoutKey.remove(location)
break
}
}
}

// Handle remaining locations
for (location in locsWithoutKey) {
var key: String?

if (unusedKeys.isEmpty()) {
key = keyGenerator.createKey()
} else {
val it = unusedKeys.iterator()
key = it.next()
it.remove()
}

outputDmmData.addKeyAndTileContent(key, dmm.getTileContentByLocation(location))
}

// Drop down all unused keys for sure.
unusedKeys.clear()
}
Expand Down

0 comments on commit 78e2a84

Please sign in to comment.