Kotlin 1.5 new warnings - the rest (#5151)

This commit is contained in:
SomeTroglodyte 2021-09-09 05:21:44 +02:00 committed by GitHub
parent 9ff8435a21
commit 8b210fb798
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 143 additions and 149 deletions

View File

@ -208,7 +208,7 @@ object HexMath {
val top = height / 2 - (x + y) / 2
// kotlin's Int division rounds in different directions depending on sign! Thus 1 extra `-1`
val bottom = (x + y - 1) / 2 + (height - 1) / 2
return min(min(left, right), min(top, bottom))
return minOf(left, right, top, bottom)
} else {
val radius = mapParameters.mapSize.radius
if (mapParameters.worldWrap) {

View File

@ -170,7 +170,7 @@ object BattleDamage {
} else if (attacker is CityCombatant) {
if (attacker.city.getCenterTile().militaryUnit != null) {
val garrisonBonus = attacker.city.getMatchingUniques("+[]% attacking strength for cities with garrisoned units")
.sumBy { it.params[0].toInt() }
.sumOf { it.params[0].toInt() }
if (garrisonBonus != 0)
modifiers["Garrisoned unit"] = garrisonBonus
}

View File

@ -57,7 +57,7 @@ class CityCombatant(val city: CityInfo) : ICombatant {
if (cityTile.militaryUnit != null)
strength += cityTile.militaryUnit!!.baseUnit().strength * (cityTile.militaryUnit!!.health / 100f) * 0.2f
var buildingsStrength = city.cityConstructions.getBuiltBuildings().sumBy { it.cityStrength }.toFloat()
var buildingsStrength = city.cityConstructions.getBuiltBuildings().sumOf { it.cityStrength }.toFloat()
if (getCivInfo().hasUnique("Defensive buildings in all cities are 25% more effective"))
buildingsStrength *= 1.25f
strength += buildingsStrength

View File

@ -3,7 +3,6 @@ package com.unciv.logic.city
import com.badlogic.gdx.math.Vector2
import com.unciv.logic.battle.CityCombatant
import com.unciv.logic.civilization.CivilizationInfo
import com.unciv.logic.civilization.GreatPersonManager
import com.unciv.logic.civilization.ReligionState
import com.unciv.logic.civilization.diplomacy.DiplomacyFlags
import com.unciv.logic.map.RoadStatus
@ -15,10 +14,7 @@ import com.unciv.models.ruleset.tile.ResourceSupplyList
import com.unciv.models.ruleset.tile.ResourceType
import com.unciv.models.ruleset.unit.BaseUnit
import com.unciv.models.stats.Stat
import com.unciv.models.translations.equalsPlaceholderText
import com.unciv.models.translations.getPlaceholderParameters
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.HashSet
import kotlin.math.ceil
@ -27,6 +23,7 @@ import kotlin.math.pow
import kotlin.math.roundToInt
class CityInfo {
@Suppress("JoinDeclarationAndAssignment")
@Transient
lateinit var civInfo: CivilizationInfo
@ -87,7 +84,7 @@ class CityInfo {
this.civInfo = civInfo
foundingCiv = civInfo.civName
turnAcquired = civInfo.gameInfo.turns
this.location = cityLocation
location = cityLocation
setTransients()
setNewCityName(civInfo)
@ -250,8 +247,7 @@ class CityInfo {
.filter { it.uniques.contains("Indicates the capital city") }
val civSpecificBuilding = indicatorBuildings.firstOrNull { it.uniqueTo == civInfo.civName }
if (civSpecificBuilding != null) return civSpecificBuilding.name
else return indicatorBuildings.first().name
return civSpecificBuilding?.name ?: indicatorBuildings.first().name
}
fun isConnectedToCapital(connectionTypePredicate: (Set<String>) -> Boolean = { true }): Boolean {
@ -382,7 +378,7 @@ class CityInfo {
buildingsCounter.add(building.greatPersonPoints)
sourceToGPP["Buildings"] = buildingsCounter
for ((source, gppCounter) in sourceToGPP) {
for ((_, gppCounter) in sourceToGPP) {
for (unique in civInfo.getMatchingUniques("[] is earned []% faster")) {
val unitName = unique.params[0]
if (!gppCounter.containsKey(unitName)) continue
@ -437,7 +433,7 @@ class CityInfo {
}
internal fun getMaxHealth() =
200 + cityConstructions.getBuiltBuildings().sumBy { it.cityHealth }
200 + cityConstructions.getBuiltBuildings().sumOf { it.cityHealth }
override fun toString() = name // for debug
//endregion
@ -498,7 +494,7 @@ class CityInfo {
if (isBeingRazed) {
val removedPopulation =
1 + civInfo.getMatchingUniques("Cities are razed [] times as fast")
.sumBy { it.params[0].toInt() - 1 }
.sumOf { it.params[0].toInt() - 1 }
population.addPopulation(-1 * removedPopulation)
if (population.population <= 0) {
civInfo.addNotification(

View File

@ -80,7 +80,7 @@ class CityInfoConquestFunctions(val city: CityInfo){
/** This happens when we either puppet OR annex, basically whenever we conquer a city and don't liberate it */
fun puppetCity(conqueringCiv: CivilizationInfo) {
// Gain gold for plundering city
val goldPlundered = getGoldForCapturingCity(conqueringCiv)
val goldPlundered = getGoldForCapturingCity(conqueringCiv) // todo: use this val
city.apply {
val oldCiv = civInfo
@ -111,7 +111,7 @@ class CityInfoConquestFunctions(val city: CityInfo){
private fun diplomaticRepercussionsForConqueringCity(oldCiv: CivilizationInfo, conqueringCiv: CivilizationInfo) {
val currentPopulation = city.population.population
val percentageOfCivPopulationInThatCity = currentPopulation * 100f /
oldCiv.cities.sumBy { it.population.population }
oldCiv.cities.sumOf { it.population.population }
val aggroGenerated = 10f + percentageOfCivPopulationInThatCity.roundToInt()
// How can you conquer a city but not know the civ you conquered it from?!
@ -169,7 +169,7 @@ class CityInfoConquestFunctions(val city: CityInfo){
private fun diplomaticRepercussionsForLiberatingCity(conqueringCiv: CivilizationInfo, conqueredCiv: CivilizationInfo) {
val foundingCiv = conqueredCiv.gameInfo.civilizations.first { it.civName == city.foundingCiv }
val percentageOfCivPopulationInThatCity = city.population.population *
100f / (foundingCiv.cities.sumBy { it.population.population } + city.population.population)
100f / (foundingCiv.cities.sumOf { it.population.population } + city.population.population)
val respectForLiberatingOurCity = 10f + percentageOfCivPopulationInThatCity.roundToInt()
// In order to get "plus points" in Diplomacy, you have to establish diplomatic relations if you haven't yet
@ -190,10 +190,10 @@ class CityInfoConquestFunctions(val city: CityInfo){
}
}
val otherCivsRespecForLiberating = (respectForLiberatingOurCity / 10).roundToInt().toFloat()
val otherCivsRespectForLiberating = (respectForLiberatingOurCity / 10).roundToInt().toFloat()
for (thirdPartyCiv in conqueringCiv.getKnownCivs().filter { it.isMajorCiv() && it != conqueredCiv }) {
thirdPartyCiv.getDiplomacyManager(conqueringCiv)
.addModifier(DiplomaticModifiers.LiberatedCity, otherCivsRespecForLiberating) // Cool, keep at at! =D
.addModifier(DiplomaticModifiers.LiberatedCity, otherCivsRespectForLiberating) // Cool, keep at at! =D
}
}
@ -252,5 +252,4 @@ class CityInfoConquestFunctions(val city: CityInfo){
}
}
}

View File

@ -520,7 +520,7 @@ class CityStats(val cityInfo: CityInfo) {
// AFTER we've gotten all the gold stats figured out, only THEN do we plonk that gold into Science
if (cityInfo.getRuleset().modOptions.uniques.contains(ModOptionsConstants.convertGoldToScience)) {
val amountConverted = (newFinalStatList.values.sumByDouble { it.gold.toDouble() }
val amountConverted = (newFinalStatList.values.sumOf { it.gold.toDouble() }
* cityInfo.civInfo.tech.goldPercentConvertedToScience).toInt().toFloat()
if (amountConverted > 0) // Don't want you converting negative gold to negative science yaknow
newFinalStatList["Gold -> Science"] = Stats(science = amountConverted, gold = -amountConverted)

View File

@ -10,7 +10,6 @@ import com.unciv.models.stats.Stat
import com.unciv.models.translations.getPlaceholderParameters
import com.unciv.models.translations.getPlaceholderText
import com.unciv.ui.victoryscreen.RankingType
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.LinkedHashMap
import kotlin.math.max
@ -281,12 +280,12 @@ class CityStateFunctions(val civInfo: CivilizationInfo) {
val bullyRange = max(5, civInfo.gameInfo.tileMap.tileMatrix.size / 10) // Longer range for larger maps
val inRangeTiles = civInfo.getCapital().getCenterTile().getTilesInDistanceRange(1..bullyRange)
val forceNearCity = inRangeTiles
.sumBy { if (it.militaryUnit?.civInfo == demandingCiv)
.sumOf { if (it.militaryUnit?.civInfo == demandingCiv)
it.militaryUnit!!.getForceEvaluation()
else 0
}
val csForce = civInfo.getCapital().getForceEvaluation() + inRangeTiles
.sumBy { if (it.militaryUnit?.civInfo == civInfo)
.sumOf { if (it.militaryUnit?.civInfo == civInfo)
it.militaryUnit!!.getForceEvaluation()
else 0
}
@ -337,9 +336,9 @@ class CityStateFunctions(val civInfo: CivilizationInfo) {
if (!civInfo.isCityState()) throw Exception("You can only demand workers from City-States!")
val buildableWorkerLikeUnits = civInfo.gameInfo.ruleSet.units.filter {
it.value.uniqueObjects.any { it.placeholderText == Constants.canBuildImprovements }
&& it.value.isBuildable(civInfo)
it.value.uniqueObjects.any { unique -> unique.placeholderText == Constants.canBuildImprovements }
&& it.value.isCivilian()
&& it.value.isBuildable(civInfo)
}
if (buildableWorkerLikeUnits.isEmpty()) return // Bad luck?
demandingCiv.placeUnitNearTile(civInfo.getCapital().location, buildableWorkerLikeUnits.keys.random())
@ -356,7 +355,7 @@ class CityStateFunctions(val civInfo: CivilizationInfo) {
val allyBonuses = eraInfo.allyBonus[civInfo.cityStateType.name]
if (allyBonuses != null) {
// Defined city states in json
val bonuses = allyBonuses + eraInfo!!.friendBonus[civInfo.cityStateType.name]!!
val bonuses = allyBonuses + eraInfo.friendBonus[civInfo.cityStateType.name]!!
for (bonus in bonuses) {
if (statType == Stat.Happiness && bonus.getPlaceholderText() == "Provides [] Happiness")
return true

View File

@ -74,7 +74,7 @@ class CivInfoStats(val civInfo: CivilizationInfo) {
for (city in civInfo.cities) {
for (tile in city.getTiles()) {
if (tile.isCityCenter()) continue
if (tile.roadStatus == RoadStatus.None) continue // Cheap checks before pricy checks
if (tile.roadStatus == RoadStatus.None) continue // Cheap checks before pricey checks
if (ignoredTileTypes.any { tile.matchesFilter(it, civInfo) }) continue
transportationUpkeep += tile.roadStatus.upkeep
@ -193,7 +193,7 @@ class CivInfoStats(val civInfo: CivilizationInfo) {
)// Leave at least 1
statMap["Treasury deficit"] = Stats(science = scienceDeficit)
}
val goldDifferenceFromTrade = civInfo.diplomacy.values.sumBy { it.goldPerTurn() }
val goldDifferenceFromTrade = civInfo.diplomacy.values.sumOf { it.goldPerTurn() }
if (goldDifferenceFromTrade != 0)
statMap["Trade"] = Stats(gold = goldDifferenceFromTrade.toFloat())
@ -218,7 +218,7 @@ class CivInfoStats(val civInfo: CivilizationInfo) {
val happinessBonusForCityStateProvidedLuxuries =
civInfo.getMatchingUniques("Happiness from Luxury Resources gifted by City-States increased by []%")
.sumBy { it.params[0].toInt() } / 100f
.sumOf { it.params[0].toInt() } / 100f
val luxuriesProvidedByCityStates = civInfo.getKnownCivs().asSequence()
.filter { it.isCityState() && it.getAllyCiv() == civInfo.civName }
@ -240,7 +240,7 @@ class CivInfoStats(val civInfo: CivilizationInfo) {
statMap["Traded Luxuries"] =
luxuriesAllOfWhichAreTradedAway.count() * happinessPerUniqueLuxury *
civInfo.getMatchingUniques("Retain []% of the happiness from a luxury after the last copy has been traded away")
.sumBy { it.params[0].toInt() } / 100f
.sumOf { it.params[0].toInt() } / 100f
for (city in civInfo.cities) {
// There appears to be a concurrency problem? In concurrent thread in ConstructionsTable.getConstructionButtonDTOs

View File

@ -1,25 +1,21 @@
package com.unciv.logic.civilization
import com.badlogic.gdx.math.Vector2
import com.unciv.Constants
import com.unciv.UncivGame
import com.unciv.logic.GameInfo
import com.unciv.logic.UncivShowableException
import com.unciv.logic.automation.NextTurnAutomation
import com.unciv.logic.automation.WorkerAutomation
import com.unciv.logic.city.CityInfo
import com.unciv.logic.civilization.RuinsManager.RuinsManager
import com.unciv.logic.civilization.diplomacy.DiplomacyFlags
import com.unciv.logic.civilization.diplomacy.DiplomacyManager
import com.unciv.logic.civilization.diplomacy.DiplomaticStatus
import com.unciv.logic.civilization.diplomacy.RelationshipLevel
import com.unciv.logic.map.MapUnit
import com.unciv.logic.map.TileInfo
import com.unciv.logic.map.UnitMovementAlgorithms
import com.unciv.logic.trade.TradeEvaluation
import com.unciv.logic.trade.TradeRequest
import com.unciv.models.Counter
import com.unciv.models.metadata.GameSpeed
import com.unciv.models.ruleset.*
import com.unciv.models.ruleset.tile.ResourceSupplyList
import com.unciv.models.ruleset.tile.ResourceType
@ -27,16 +23,15 @@ import com.unciv.models.ruleset.tile.TileResource
import com.unciv.models.ruleset.unit.BaseUnit
import com.unciv.models.stats.Stat
import com.unciv.models.stats.Stats
import com.unciv.models.translations.getPlaceholderParameters
import com.unciv.models.translations.getPlaceholderText
import com.unciv.models.translations.tr
import com.unciv.ui.utils.toPercent
import com.unciv.ui.victoryscreen.RankingType
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.collections.LinkedHashMap
import kotlin.math.*
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.math.sqrt
class CivilizationInfo {
@ -128,7 +123,7 @@ class CivilizationInfo {
*/
val temporaryUniques = ArrayList<Pair<Unique, Int>>()
/** Maps the name of the construction to the amount of times bouhgt */
/** Maps the name of the construction to the amount of times bought */
val boughtConstructionsWithGloballyIncreasingPrice = HashMap<String, Int>()
// if we only use lists, and change the list each time the cities are changed,
@ -501,11 +496,11 @@ class CivilizationInfo {
fun getStatForRanking(category: RankingType): Int {
return when (category) {
RankingType.Population -> cities.sumBy { it.population.population }
RankingType.Population -> cities.sumOf { it.population.population }
RankingType.Crop_Yield -> statsForNextTurn.food.roundToInt()
RankingType.Production -> statsForNextTurn.production.roundToInt()
RankingType.Gold -> gold
RankingType.Territory -> cities.sumBy { it.tiles.size }
RankingType.Territory -> cities.sumOf { it.tiles.size }
RankingType.Force -> getMilitaryMight()
RankingType.Happiness -> getHappiness()
RankingType.Technologies -> tech.researchedTechnologies.size
@ -842,7 +837,7 @@ class CivilizationInfo {
val unit = getEquivalentUnit(unitName)
val placedUnit = placeUnitNearTile(cityToAddTo.location, unit.name)
// silently bail if no tile to place the unit is found
if (placedUnit == null) return null
?: return null
if (unit.isGreatPerson()) {
addNotification("A [${unit.name}] has been born in [${cityToAddTo.name}]!", placedUnit.getTile().position, unit.name)
}

View File

@ -118,7 +118,7 @@ class MapUnit {
}
fun shortDisplayName(): String {
return if (instanceName != null) "[$instanceName]"!!
return if (instanceName != null) "[$instanceName]"
else "[$name]"
}
@ -344,8 +344,7 @@ class MapUnit {
}
fun maxAttacksPerTurn(): Int {
var maxAttacksPerTurn = 1 + getMatchingUniques("[] additional attacks per turn").sumOf { it.params[0].toInt() }
return maxAttacksPerTurn
return 1 + getMatchingUniques("[] additional attacks per turn").sumOf { it.params[0].toInt() }
}
fun canAttack(): Boolean {

View File

@ -34,7 +34,7 @@ class Building : NamedStats(), INonPerpetualConstruction, ICivilopediaText {
// Could have old specialist values of "gold", "science" etc - change them to the new specialist names
val counter = Counter<String>()
for ((entry, amount) in specialistSlots!!) {
val equivalentStat = Stat.values().firstOrNull { it.name.toLowerCase(Locale.ENGLISH) == entry }
val equivalentStat = Stat.values().firstOrNull { it.name.lowercase() == entry }
if (equivalentStat != null)
counter[Specialist.specialistNameByStat(equivalentStat)] = amount

View File

@ -415,11 +415,11 @@ class Ruleset {
fun getPrereqTree(technologyName: String): Set<String> {
if (prereqsHashMap.containsKey(technologyName)) return prereqsHashMap[technologyName]!!
val technology = technologies[technologyName]
if (technology == null) return emptySet()
?: return emptySet()
val techHashSet = HashSet<String>()
techHashSet += technology.prerequisites
for (prereq in technology.prerequisites)
techHashSet += getPrereqTree(prereq)
for (prerequisite in technology.prerequisites)
techHashSet += getPrereqTree(prerequisite)
prereqsHashMap[technologyName] = techHashSet
return techHashSet
}

View File

@ -9,7 +9,13 @@ import com.unciv.ui.tilegroups.TileGroup
import kotlin.math.max
import kotlin.math.min
class TileGroupMap<T: TileGroup>(tileGroups: Collection<T>, private val leftAndRightPadding: Float, private val topAndBottomPadding: Float, worldWrap: Boolean = false, tileGroupsToUnwrap: Collection<T>? = null): Group(){
class TileGroupMap<T: TileGroup>(
tileGroups: Collection<T>,
private val leftAndRightPadding: Float,
private val topAndBottomPadding: Float,
worldWrap: Boolean = false,
tileGroupsToUnwrap: Collection<T>? = null
): Group() {
var topX = -Float.MAX_VALUE
var topY = -Float.MAX_VALUE
var bottomX = Float.MAX_VALUE
@ -20,6 +26,7 @@ class TileGroupMap<T: TileGroup>(tileGroups: Collection<T>, private val leftAndR
init {
if (worldWrap) {
for (tileGroup in tileGroups) {
@Suppress("UNCHECKED_CAST") // T is constrained such that casting these TileGroup clones to T should be OK
mirrorTileGroups[tileGroup.tileInfo] = Pair(tileGroup.clone() as T, tileGroup.clone() as T)
}
}

View File

@ -87,11 +87,11 @@ class CityOverviewTable(private val viewingPlayer: CivilizationInfo, private val
.minWidth(iconSize) //we need the min width so we can align the different tables
cityInfoTableTotal.add("Total".toLabel())
cityInfoTableTotal.add(viewingPlayer.cities.sumBy { it.population.population }.toString().toLabel()).myAlign(Align.center)
cityInfoTableTotal.add(viewingPlayer.cities.sumOf { it.population.population }.toString().toLabel()).myAlign(Align.center)
for (column in columnsNames.filter { it.isStat() }) {
val stat = Stat.valueOf(column)
if (stat == Stat.Food || stat == Stat.Production) cityInfoTableTotal.add() // an intended empty space
else cityInfoTableTotal.add(viewingPlayer.cities.sumBy { getStatOfCity(it, stat) }.toLabel()).myAlign(Align.center)
else cityInfoTableTotal.add(viewingPlayer.cities.sumOf { getStatOfCity(it, stat) }.toLabel()).myAlign(Align.center)
}
cityInfoTableTotal.pack()
@ -111,7 +111,7 @@ class CityOverviewTable(private val viewingPlayer: CivilizationInfo, private val
private fun getStatOfCity(cityInfo: CityInfo, stat: Stat): Int {
return if (stat == Stat.Happiness)
cityInfo.cityStats.happinessList.values.sum().roundToInt()
else cityInfo.cityStats.currentCityStats.get(stat).roundToInt()
else cityInfo.cityStats.currentCityStats[stat].roundToInt()
}
private fun fillCitiesTable(citiesTable: Table, sortType: String, descending: Boolean) {

View File

@ -16,7 +16,6 @@ class ResourcesOverviewTable (
viewingPlayer: CivilizationInfo,
overviewScreen: EmpireOverviewScreen
) : Table() {
//val game = overviewScreen.game
init {
defaults().pad(10f)
@ -79,7 +78,7 @@ class ResourcesOverviewTable (
add("Total".toLabel())
for (resource in resources) {
val sum = resourceDrilldown.filter { it.resource == resource }.sumBy { it.amount }
val sum = resourceDrilldown.filter { it.resource == resource }.sumOf { it.amount }
add(sum.toLabel())
}
}

View File

@ -104,14 +104,14 @@ class TechPickerScreen(internal val civInfo: CivilizationInfo, centerOnTech: Tec
if (!erasNamesToColumns[era]!!.contains(columnNumber)) erasNamesToColumns[era]!!.add(columnNumber)
}
var i = 0
for ((era, columns) in erasNamesToColumns) {
val columnSpan = columns.size
for ((era, eraColumns) in erasNamesToColumns) {
val columnSpan = eraColumns.size
val color = if (i % 2 == 0) Color.BLUE else Color.FIREBRICK
i++
techTable.add(era.toLabel().addBorder(2f, color)).fill().colspan(columnSpan)
}
for (rowIndex in 0..rows - 1) {
for (rowIndex in 0 until rows) {
techTable.row().pad(5f).padRight(40f)
for (columnIndex in techMatrix.indices) {
@ -206,13 +206,13 @@ class TechPickerScreen(internal val civInfo: CivilizationInfo, centerOnTech: Tec
}
}
private fun selectTechnology(tech: Technology?, center: Boolean = false, switchfromWorldScreen: Boolean = true) {
private fun selectTechnology(tech: Technology?, center: Boolean = false, switchFromWorldScreen: Boolean = true) {
val previousSelectedTech = selectedTech
selectedTech = tech
descriptionLabel.setText(tech?.getDescription(civInfo.gameInfo.ruleSet))
if (!switchfromWorldScreen)
if (!switchFromWorldScreen)
return
if (tech == null)
@ -264,8 +264,8 @@ class TechPickerScreen(internal val civInfo: CivilizationInfo, centerOnTech: Tec
}
private fun getTechProgressLabel(techs: List<String>): String {
val progress = techs.sumBy { tech -> civTech.researchOfTech(tech) }
val techCost = techs.sumBy { tech -> civInfo.tech.costOfTech(tech) }
val progress = techs.sumOf { tech -> civTech.researchOfTech(tech) }
val techCost = techs.sumOf { tech -> civInfo.tech.costOfTech(tech) }
return "(${progress}/${techCost})"
}