Code inspection and other general fixes - gotta clean up when there are guests ;)

This commit is contained in:
Yair Morgenstern
2018-12-04 23:21:57 +02:00
parent 7410cb8efe
commit c706fa455a
31 changed files with 92 additions and 112 deletions

View File

@ -21,8 +21,8 @@ android {
applicationId "com.unciv.game"
minSdkVersion 14
targetSdkVersion 28
versionCode 173
versionName "2.10.10"
versionCode 174
versionName "2.10.11"
}
// Had to add this crap for Travis to build, it wanted to sign the app

Binary file not shown.

View File

@ -10,7 +10,7 @@ import com.unciv.ui.NewGameScreen
import com.unciv.ui.utils.getRandom
import java.util.*
class GameStarter(){
class GameStarter{
fun startNewGame(newGameParameters: NewGameScreen.NewGameParameters): GameInfo {
val gameInfo = GameInfo()

View File

@ -9,7 +9,7 @@ import com.unciv.OldGameSettings
class GameSaver {
private val saveFilesFolder = "SaveFiles"
fun json() = Json().apply { setIgnoreDeprecated(true); setIgnoreUnknownFields(true) } // Json() is NOT THREAD SAFE so we need to create a new one for each function
fun json() = Json().apply { setIgnoreDeprecated(true); ignoreUnknownFields = true } // Json() is NOT THREAD SAFE so we need to create a new one for each function
fun getSave(GameName: String): FileHandle {
return Gdx.files.local("$saveFilesFolder/$GameName")

View File

@ -8,7 +8,7 @@ import com.unciv.models.gamebasics.GameBasics
import com.unciv.ui.utils.getRandom
import kotlin.math.min
class NextTurnAutomation(){
class NextTurnAutomation{
fun automateCivMoves(civInfo: CivilizationInfo) {
chooseTechToResearch(civInfo)
@ -102,9 +102,11 @@ class NextTurnAutomation(){
}
val unitType = unit.type
if (unitType.isRanged()) rangedUnits.add(unit)
else if (unitType.isMelee()) meleeUnits.add(unit)
else civilianUnits.add(unit)
when {
unitType.isRanged() -> rangedUnits.add(unit)
unitType.isMelee() -> meleeUnits.add(unit)
else -> civilianUnits.add(unit)
}
}
for (unit in civilianUnits) UnitAutomation().automateUnitMoves(unit) // They move first so that combat units can accompany a settler

View File

@ -143,7 +143,8 @@ class WorkerAutomation(val unit: MapUnit) {
return GameBasics.TileImprovements[improvementString]!!
}
// todo: is this neccesary? Worker automation does something else to build roads.
// Either generalize or delete
fun constructRoadTo(destination:TileInfo) {
val currentTile = unit.getTile()
if (currentTile.roadStatus == RoadStatus.None) {

View File

@ -39,7 +39,7 @@ class CityConstructions {
val stats = Stats()
for (building in getBuiltBuildings())
stats.add(building.getStats(cityInfo.civInfo.policies.adoptedPolicies))
stats.science += (cityInfo.getBuildingUniques().count({ it == "+1 Science Per 2 Population" }) * cityInfo.population.population / 2).toFloat()
stats.science += (cityInfo.getBuildingUniques().count { it == "+1 Science Per 2 Population" } * cityInfo.population.population / 2).toFloat()
return stats
}

View File

@ -139,7 +139,7 @@ class CivilizationInfo {
cost = cost.pow(1+gameProgress/3) // Why 3? To spread 1 to 1.33
if(!isPlayerCivilization())
cost *= gameInfo.getPlayerCivilization().getDifficulty().aiUnitMaintenanceModifier
if(policies.isAdopted("Autocracy")) cost = cost*0.66f
if(policies.isAdopted("Autocracy")) cost *= 0.66f
return cost.toInt()
}
@ -174,7 +174,8 @@ class CivilizationInfo {
if (getBuildingUniques().contains("Provides 1 happiness per social policy")) {
if(!statMap.containsKey("Policies")) statMap["Policies"]=0f
statMap["Policies"] = statMap["Policies"]!! + policies.getAdoptedPolicies().count { !it.endsWith("Complete") }.toFloat()
statMap["Policies"] = statMap["Policies"]!! +
policies.getAdoptedPolicies().count { !it.endsWith("Complete") }.toFloat()
}
return statMap
@ -187,7 +188,7 @@ class CivilizationInfo {
val civResources = Counter<TileResource>()
for (city in cities) civResources.add(city.getCityResources())
for (dip in diplomacy.values) civResources.add(dip.resourcesFromTrade())
for(resource in getCivUnits().map { it.baseUnit.requiredResource }.filterNotNull().map { GameBasics.TileResources[it] })
for(resource in getCivUnits().mapNotNull { it.baseUnit.requiredResource }.map { GameBasics.TileResources[it] })
civResources.add(resource,-1)
return civResources
}

View File

@ -24,7 +24,7 @@ class GreatPersonManager {
}
fun getNewGreatPerson(): String? {
var greatPerson: String? = null
val greatPerson: String? = null
val greatPersonPointsHashmap = greatPersonPoints.toHashMap()
for(entry in statToGreatPersonMapping){
if(greatPersonPointsHashmap[entry.key]!!>pointsForNextGreatPerson){

View File

@ -8,7 +8,7 @@ class Notification {
var location: Vector2? = null
var color:Color = Color.BLACK
internal constructor()
internal constructor() // Needed for json deserialization
constructor(text: String, location: Vector2?,color: Color) {
this.text = text

View File

@ -29,8 +29,6 @@ class TechManager {
return toReturn
}
private fun getCurrentTechnology(): Technology = GameBasics.Technologies[currentTechnology()]!!
fun costOfTech(techName: String): Int {
return (GameBasics.Technologies[techName]!!.cost * civInfo.getDifficulty().researchCostModifier).toInt()
}

View File

@ -9,7 +9,7 @@ class BFS(val startingPoint: TileInfo, val predicate : (TileInfo) -> Boolean){
init{
tilesToCheck.add(startingPoint)
tilesReached.put(startingPoint,startingPoint)
tilesReached[startingPoint] = startingPoint
}
fun stepToEnd(){

View File

@ -281,8 +281,5 @@ open class TileInfo {
turnsToImprovement = improvement.getTurnsToBuild(civInfo)
}
fun stopWorkingOnImprovement() {
improvementInProgress = null
}
//endregion
}

View File

@ -119,15 +119,4 @@ class TileMap {
}
}
fun getShortestPathBetweenTwoTiles(from:TileInfo, to:TileInfo): ArrayList<TileInfo> {
val path = ArrayList<TileInfo>()
var currentTile = from
while(currentTile!=to){
path += currentTile
currentTile = currentTile.neighbors.minBy { it.arialDistanceTo(to) }!!
}
path+=to
return path
}
}

View File

@ -72,7 +72,7 @@ class UnitMovementAlgorithms(val unit:MapUnit) {
fun getShortestPath(destination: TileInfo): List<TileInfo> {
val currentTile = unit.getTile()
if (currentTile.position.equals(destination)) return listOf(currentTile) // edge case that's needed, so that workers will know that they can reach their own tile. *sig
if (currentTile.position == destination) return listOf(currentTile) // edge case that's needed, so that workers will know that they can reach their own tile. *sig
var tilesToCheck: List<TileInfo> = listOf(currentTile)
val movementTreeParents = HashMap<TileInfo, TileInfo?>() // contains a map of "you can get from X to Y in that turn"

View File

@ -62,7 +62,7 @@ class Building : NamedStats(), IConstruction{
}
if(requiredNearbyImprovedResources!=null)
infoList += "requires worked "+requiredNearbyImprovedResources!!.joinToString("/")+" near city"
if(uniques.isNotEmpty()) infoList += uniques.map { it.tr() }.joinToString()
if(uniques.isNotEmpty()) infoList += uniques.joinToString { it.tr() }
if(cityStrength!=0) infoList+="{City strength} +".tr()+cityStrength
if(cityHealth!=0) infoList+="{City health} +".tr()+cityHealth
if(xpForNewUnits!=0) infoList+= "+$xpForNewUnits {XP for new units}".tr()

View File

@ -25,7 +25,7 @@ class Technology : ICivilopedia {
it.requiredTech == name &&
(it.uniqueTo == null || it.uniqueTo == playerCiv)
}
val replacedUnits = enabledUnits.map { it.replaces }.filterNotNull()
val replacedUnits = enabledUnits.mapNotNull { it.replaces }
enabledUnits = enabledUnits.filter { it.name !in replacedUnits }
if (enabledUnits.isNotEmpty()) {
lineList += "{Units enabled}: "
@ -37,7 +37,7 @@ class Technology : ICivilopedia {
it.requiredTech == name &&
(it.uniqueTo == null || it.uniqueTo == playerCiv)
}
val replacedBuildings = enabledBuildings.map { it.replaces }.filterNotNull()
val replacedBuildings = enabledBuildings.mapNotNull { it.replaces }
enabledBuildings = enabledBuildings.filter { it.name !in replacedBuildings }
val regularBuildings = enabledBuildings.filter { !it.isWonder }
if (regularBuildings.isNotEmpty()) {
@ -57,9 +57,9 @@ class Technology : ICivilopedia {
val tileImprovements = GameBasics.TileImprovements.values.filter { it.techRequired == name }
if (tileImprovements.isNotEmpty())
lineList += "{Tile improvements enabled}: " + tileImprovements.map { it.name.tr() }.joinToString()
lineList += "{Tile improvements enabled}: " + tileImprovements.joinToString { it.name.tr() }
return lineList.map { it.tr() }.joinToString("\n")
return lineList.joinToString("\n") { it.tr() }
}
lateinit var name: String

View File

@ -10,6 +10,6 @@ class Promotion : ICivilopedia, INamed{
return effect
}
var prerequisites = listOf<String>()
lateinit var effect:String;
lateinit var effect:String
var unitTypes = listOf<String>() // The json parser woulddn't agree to deserialize this as a list of UnitTypes. =(
}

View File

@ -18,7 +18,7 @@ class CivilopediaScreen : CameraStageBaseScreen() {
buttonTable.pad(15f)
val entryTable = Table()
val splitPane = SplitPane(buttonTable, entryTable, true, CameraStageBaseScreen.skin)
splitPane.setSplitAmount(0.2f)
splitPane.splitAmount = 0.2f
splitPane.setFillParent(true)
stage.addActor(splitPane)

View File

@ -0,0 +1,47 @@
package com.unciv.ui
import com.badlogic.gdx.utils.Base64Coder
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStreamReader
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
object Gzip {
fun compress(data: String): ByteArray {
val bos = ByteArrayOutputStream(data.length)
val gzip = GZIPOutputStream(bos)
gzip.write(data.toByteArray())
gzip.close()
val compressed = bos.toByteArray()
bos.close()
return compressed
}
fun decompress(compressed: ByteArray): String {
val bis = ByteArrayInputStream(compressed)
val gis = GZIPInputStream(bis)
val br = BufferedReader(InputStreamReader(gis, "UTF-8"))
val sb = StringBuilder()
var line: String? = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()
gis.close()
bis.close()
return sb.toString()
}
fun encoder(bytes:ByteArray): String{
return String(Base64Coder.encode(bytes))
}
fun decoder(base64Str: String): ByteArray{
return Base64Coder.decode(base64Str)
}
}

View File

@ -129,7 +129,7 @@ class NewGameScreen: PickerScreen(){
newGameOptionsTable.add("{Number of enemies}:".tr())
val enemiesSelectBox = SelectBox<Int>(skin)
val enemiesArray = Array<Int>()
(1..GameBasics.Nations.size-1).forEach { enemiesArray.add(it) }
(0..GameBasics.Nations.size).forEach { enemiesArray.add(it) }
enemiesSelectBox.items = enemiesArray
enemiesSelectBox.selected = newGameParameters.numberOfEnemies

View File

@ -5,22 +5,14 @@ import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Table
import com.badlogic.gdx.scenes.scene2d.ui.TextButton
import com.badlogic.gdx.scenes.scene2d.ui.TextField
import com.badlogic.gdx.utils.Base64Coder
import com.badlogic.gdx.utils.Json
import com.unciv.UnCivGame
import com.unciv.logic.GameSaver
import com.unciv.ui.pickerscreens.PickerScreen
import com.unciv.ui.utils.onClick
import com.unciv.ui.utils.enable
import com.unciv.ui.utils.getRandom
import com.unciv.ui.utils.onClick
import com.unciv.ui.utils.tr
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStreamReader
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
import kotlin.text.Charsets.UTF_8
class SaveScreen : PickerScreen() {
@ -76,49 +68,3 @@ class SaveScreen : PickerScreen() {
}
object Gzip {
fun compress(data: String): ByteArray {
val bos = ByteArrayOutputStream(data.length)
val gzip = GZIPOutputStream(bos)
gzip.write(data.toByteArray())
gzip.close()
val compressed = bos.toByteArray()
bos.close()
return compressed
}
fun decompress(compressed: ByteArray): String {
val bis = ByteArrayInputStream(compressed)
val gis = GZIPInputStream(bis)
val br = BufferedReader(InputStreamReader(gis, "UTF-8"))
val sb = StringBuilder()
var line: String? = br.readLine()
while (line != null) {
sb.append(line)
line = br.readLine()
}
br.close()
gis.close()
bis.close()
return sb.toString()
}
fun gzip(content: String): ByteArray {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(UTF_8).use { it.write(content) }
return bos.toByteArray()
}
fun ungzip(content: ByteArray): String =
GZIPInputStream(content.inputStream()).bufferedReader(UTF_8).use { it.readText() }
fun encoder(bytes:ByteArray): String{
return String(Base64Coder.encode(bytes))
}
fun decoder(base64Str: String): ByteArray{
return Base64Coder.decode(base64Str)
}
}

View File

@ -41,7 +41,7 @@ open class PickerScreen : CameraStageBaseScreen() {
scrollPane.setSize(stage.width, stage.height * screenSplit)
splitPane = SplitPane(scrollPane, bottomTable, true, CameraStageBaseScreen.skin)
splitPane.setSplitAmount(screenSplit)
splitPane.splitAmount = screenSplit
splitPane.setFillParent(true)
stage.addActor(splitPane)
}

View File

@ -83,7 +83,7 @@ class PolicyPickerScreen(internal val civInfo: CivilizationInfo) : PickerScreen(
var policyText = policy.name.tr() + "\r\n" + policy.description.tr() + "\r\n"
if (!policy.name.endsWith("Complete")){
if(policy.requires!!.isNotEmpty())
policyText += "{Requires} ".tr() + policy.requires!!.map { it.tr() }.joinToString()
policyText += "{Requires} ".tr() + policy.requires!!.joinToString { it.tr() }
else
policyText += "{Unlocked at} ".tr()+(policy.getBranch().era.toString()+" era").tr()
}

View File

@ -196,7 +196,7 @@ open class TileGroup(var tileInfo: TileInfo) : Group() {
// This is some crazy voodoo magic so I'll explain.
val images = mutableListOf<Image>()
borderImages.put(neighbor, images)
borderImages[neighbor] = images
for (i in -2..2) {
val image = ImageGetter.getImage("OtherIcons/Circle.png")
image.setSize(5f, 5f)
@ -330,9 +330,8 @@ open class TileGroup(var tileInfo: TileInfo) : Group() {
protected fun newUnitImage(unit: MapUnit?, currentImage: Group?, isViewable: Boolean, yFromCenter: Float): Group? {
var newImage: Group? = null
if (currentImage != null) { // The unit can change within one update - for instance, when attacking, the attacker replaces the defender!
currentImage.remove()
}
// The unit can change within one update - for instance, when attacking, the attacker replaces the defender!
currentImage?.remove()
if (unit != null && isViewable) { // Tile is visible
newImage = ImageGetter.getUnitImage(unit, 25f)

View File

@ -5,7 +5,7 @@ import com.badlogic.gdx.scenes.scene2d.ui.*
import com.unciv.UnCivGame
import com.unciv.ui.utils.*
class DiplomacyScreen():CameraStageBaseScreen(){
class DiplomacyScreen:CameraStageBaseScreen(){
val leftSideTable = Table().apply { defaults().pad(10f) }
val rightSideTable = Table()
@ -13,7 +13,7 @@ class DiplomacyScreen():CameraStageBaseScreen(){
init{
onBackButtonClicked { UnCivGame.Current.setWorldScreen(); dispose() }
val splitPane = SplitPane(ScrollPane(leftSideTable),rightSideTable,false, skin)
splitPane.setSplitAmount(0.2f)
splitPane.splitAmount = 0.2f
updateLeftSideTable()

View File

@ -15,7 +15,7 @@ import com.unciv.models.gamebasics.GameBasics
import com.unciv.models.gamebasics.tile.ResourceType
object ImageGetter {
const private val whiteDotLocation = "OtherIcons/whiteDot.png"
private const val whiteDotLocation = "OtherIcons/whiteDot.png"
// When we used to load images directly from different files, without using a texture atlas,
// The draw() phase of the main screen would take a really long time because the BatchRenderer would

View File

@ -17,7 +17,7 @@ import kotlin.collections.set
class Tutorials{
class Tutorial(var name: String, var texts: ArrayList<String>) {}
class Tutorial(var name: String, var texts: ArrayList<String>)
private val tutorialTexts = mutableListOf<Tutorial>()

View File

@ -45,7 +45,7 @@ class Minimap(val tileMapHolder: TileMapHolder) : ScrollPane(null){
setScrollToTileMapHolder()
}
allTiles.addActor(hex)
tileImages.put(tileInfo,hex)
tileImages[tileInfo] = hex
topX = Math.max(topX, hex.x + groupSize)
topY = Math.max(topY, hex.y + groupSize)
@ -87,7 +87,7 @@ class Minimap(val tileMapHolder: TileMapHolder) : ScrollPane(null){
}
}
class MinimapHolder(val tileMapHolder: TileMapHolder): Table(){
class MinimapHolder(tileMapHolder: TileMapHolder): Table(){
val minimap = Minimap(tileMapHolder)
val worldScreen = tileMapHolder.worldScreen

View File

@ -60,10 +60,10 @@ class WorldScreenTopBar(val screen: WorldScreen) : Table() {
.filter { it.resourceType == ResourceType.Strategic } // && civInfo.tech.isResearched(it.revealedBy!!) }
for (resource in revealedStrategicResources) {
val resourceImage = ImageGetter.getResourceImage(resource.name,20f)
resourceImages.put(resource.name, resourceImage)
resourceImages[resource.name] = resourceImage
resourceTable.add(resourceImage)
val resourceLabel = Label("0", labelSkin)
resourceLabels.put(resource.name, resourceLabel)
resourceLabels[resource.name] = resourceLabel
resourceTable.add(resourceLabel)
}
resourceTable.pack()

View File

@ -10,7 +10,7 @@ import com.unciv.ui.utils.CameraStageBaseScreen
import com.unciv.ui.utils.center
import com.unciv.ui.worldscreen.WorldScreen
class WorldScreenDisplayOptionsTable() : PopupTable(){
class WorldScreenDisplayOptionsTable : PopupTable(){
init {
update()
}
@ -49,7 +49,7 @@ class WorldScreenDisplayOptionsTable() : PopupTable(){
add(languageSelectBox).pad(10f).row()
languageSelectBox.addListener(object : ChangeListener() {
override fun changed(event: ChangeEvent?, actor: Actor?) {
UnCivGame.Current.settings.language = languageSelectBox.selected.language;
UnCivGame.Current.settings.language = languageSelectBox.selected.language
UnCivGame.Current.settings.save()
UnCivGame.Current.worldScreen = WorldScreen()
UnCivGame.Current.setWorldScreen()