diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index c2e988349..c4c0e2018 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -14,6 +14,8 @@ jobs: - name: Verify tests run: | sh scripts/verify-test-files.sh + - name: Ktfmt + run: ./gradlew ktfmtCheck - name: Detekt - main run: ./gradlew detektMain - name: Detekt - tests diff --git a/build.gradle.kts b/build.gradle.kts index 9689e0f6f..dad1f9f15 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,11 +5,12 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile import java.net.URI plugins { - kotlin("jvm") version "1.8.21" + kotlin("jvm") version "1.9.22" id("java-library") id("com.github.ben-manes.versions") version "0.44.0" id("io.gitlab.arturbosch.detekt") version "1.23.0" id("org.jetbrains.kotlinx.kover") version "0.6.1" + id("com.ncorti.ktfmt.gradle") version "0.15.1" } repositories { @@ -26,6 +27,10 @@ detekt { config.setFrom("$projectDir/detekt-config.yml") } +ktfmt { + kotlinLangStyle() +} + dependencies { implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.8.0") implementation("org.apache.commons:commons-math3:3.6.1") diff --git a/scripts/verify-test-files.sh b/scripts/verify-test-files.sh index 430b9c3bf..ec55e53f0 100755 --- a/scripts/verify-test-files.sh +++ b/scripts/verify-test-files.sh @@ -1,7 +1,7 @@ #!/bin/bash set -eu -badTestFiles=$(grep -r "class Test[^\:]*$" src/test || true) +badTestFiles=$(grep -r "class Test [^\:]*$" src/test || true) if [ ! -z "$badTestFiles" ]; then echo "The following test files do not correctly extend AbstractTest:" echo $badTestFiles diff --git a/src/main/kotlin/dartzee/achievements/AbstractAchievement.kt b/src/main/kotlin/dartzee/achievements/AbstractAchievement.kt index d57aed353..9deadd1f5 100644 --- a/src/main/kotlin/dartzee/achievements/AbstractAchievement.kt +++ b/src/main/kotlin/dartzee/achievements/AbstractAchievement.kt @@ -18,18 +18,17 @@ import java.net.URL import javax.imageio.ImageIO import javax.swing.table.DefaultTableModel -abstract class AbstractAchievement -{ - abstract val name : String - abstract val desc : String - abstract val achievementType : AchievementType - abstract val redThreshold : Int - abstract val orangeThreshold : Int - abstract val yellowThreshold : Int - abstract val greenThreshold : Int - abstract val blueThreshold : Int - abstract val pinkThreshold : Int - abstract val maxValue : Int +abstract class AbstractAchievement { + abstract val name: String + abstract val desc: String + abstract val achievementType: AchievementType + abstract val redThreshold: Int + abstract val orangeThreshold: Int + abstract val yellowThreshold: Int + abstract val greenThreshold: Int + abstract val blueThreshold: Int + abstract val pinkThreshold: Int + abstract val maxValue: Int abstract val gameType: GameType? abstract val allowedForTeams: Boolean @@ -41,19 +40,17 @@ abstract class AbstractAchievement var gameIdEarned = "" var localGameIdEarned = -1L var dtLatestUpdate = DateStatics.START_OF_TIME - var player : PlayerEntity? = null + var player: PlayerEntity? = null - var tmBreakdown : DefaultTableModel? = null + var tmBreakdown: DefaultTableModel? = null - fun runConversion(playerIds: List, database: Database = mainDatabase) - { + fun runConversion(playerIds: List, database: Database = mainDatabase) { val sb = StringBuilder() sb.append(" DELETE FROM Achievement") sb.append(" WHERE AchievementType = '$achievementType'") appendPlayerSql(sb, playerIds, null) - if (!database.executeUpdate("" + sb)) - { + if (!database.executeUpdate("" + sb)) { return } @@ -61,21 +58,20 @@ abstract class AbstractAchievement } abstract fun populateForConversion(playerIds: List, database: Database = mainDatabase) + abstract fun getIconURL(): URL? - /** - * Basic init will be the same for most achievements - get the value from the single row - */ - open fun initialiseFromDb(achievementRows : List, player: PlayerEntity?) - { - if (achievementRows.isEmpty()) - { + /** Basic init will be the same for most achievements - get the value from the single row */ + open fun initialiseFromDb(achievementRows: List, player: PlayerEntity?) { + if (achievementRows.isEmpty()) { return } - if (achievementRows.size > 1) - { - logger.error(CODE_SQL_EXCEPTION, "Got ${achievementRows.size} rows (expected 1) for achievement $achievementType and player ${achievementRows.first().playerId}") + if (achievementRows.size > 1) { + logger.error( + CODE_SQL_EXCEPTION, + "Got ${achievementRows.size} rows (expected 1) for achievement $achievementType and player ${achievementRows.first().playerId}" + ) } val achievementRow = achievementRows.first() @@ -87,11 +83,9 @@ abstract class AbstractAchievement this.player = player } - fun getScore() : Int - { + fun getScore(): Int { val color = getColor(false) - return when (color) - { + return when (color) { Color.MAGENTA -> 6 Color.CYAN -> 5 Color.GREEN -> 4 @@ -102,39 +96,34 @@ abstract class AbstractAchievement } } - fun getColor(highlighted : Boolean) : Color - { - val col = if (isDecreasing()) - { - when (attainedValue) - { - -1 -> Color.GRAY - in redThreshold+1..Int.MAX_VALUE -> Color.GRAY - in orangeThreshold+1 until redThreshold+1 -> Color.RED - in yellowThreshold+1 until orangeThreshold+1 -> DartsColour.COLOUR_ACHIEVEMENT_ORANGE - in greenThreshold+1 until yellowThreshold+1 -> Color.YELLOW - in blueThreshold+1 until greenThreshold+1 -> Color.GREEN - in pinkThreshold+1 until blueThreshold+1 -> Color.CYAN - else -> Color.MAGENTA - } - } - else - { - when (attainedValue) - { - in Int.MIN_VALUE until redThreshold -> Color.GRAY - in redThreshold until orangeThreshold -> Color.RED - in orangeThreshold until yellowThreshold -> DartsColour.COLOUR_ACHIEVEMENT_ORANGE - in yellowThreshold until greenThreshold -> Color.YELLOW - in greenThreshold until blueThreshold -> Color.GREEN - in blueThreshold until pinkThreshold -> Color.CYAN - else -> Color.MAGENTA + fun getColor(highlighted: Boolean): Color { + val col = + if (isDecreasing()) { + when (attainedValue) { + -1 -> Color.GRAY + in redThreshold + 1..Int.MAX_VALUE -> Color.GRAY + in orangeThreshold + 1 until redThreshold + 1 -> Color.RED + in yellowThreshold + 1 until orangeThreshold + 1 -> + DartsColour.COLOUR_ACHIEVEMENT_ORANGE + in greenThreshold + 1 until yellowThreshold + 1 -> Color.YELLOW + in blueThreshold + 1 until greenThreshold + 1 -> Color.GREEN + in pinkThreshold + 1 until blueThreshold + 1 -> Color.CYAN + else -> Color.MAGENTA + } + } else { + when (attainedValue) { + in Int.MIN_VALUE until redThreshold -> Color.GRAY + in redThreshold until orangeThreshold -> Color.RED + in orangeThreshold until yellowThreshold -> + DartsColour.COLOUR_ACHIEVEMENT_ORANGE + in yellowThreshold until greenThreshold -> Color.YELLOW + in greenThreshold until blueThreshold -> Color.GREEN + in blueThreshold until pinkThreshold -> Color.CYAN + else -> Color.MAGENTA + } } - } - if (highlighted - && !isLocked()) - { + if (highlighted && !isLocked()) { return col.darker() } @@ -142,19 +131,15 @@ abstract class AbstractAchievement } fun getAngle() = getAngle(attainedValue) - fun getAngle(attainedValue : Int) : Double - { - if (attainedValue == -1) - { + + fun getAngle(attainedValue: Int): Double { + if (attainedValue == -1) { return 0.0 } - return if (!isDecreasing()) - { + return if (!isDecreasing()) { 360 * attainedValue.toDouble() / maxValue - } - else - { + } else { val denom = redThreshold - maxValue + 1 val num = Math.max(redThreshold - attainedValue + 1, 0) @@ -162,34 +147,23 @@ abstract class AbstractAchievement } } - fun isLocked() : Boolean - { - if (attainedValue == -1) - { + fun isLocked(): Boolean { + if (attainedValue == -1) { return true } - return if (isDecreasing()) - { + return if (isDecreasing()) { attainedValue > redThreshold - } - else - { + } else { attainedValue < redThreshold } } - fun isClickable(): Boolean - { - return !gameIdEarned.isEmpty() - || tmBreakdown != null - } + fun isClickable() = gameIdEarned.isNotEmpty() || tmBreakdown != null - fun getIcon() : BufferedImage? - { + fun getIcon(): BufferedImage? { var iconURL = getIconURL() - if (isLocked()) - { + if (isLocked()) { iconURL = ResourceCache.URL_ACHIEVEMENT_LOCKED } @@ -198,16 +172,14 @@ abstract class AbstractAchievement return bufferedImage } - protected open fun changeIconColor(img : BufferedImage, newColor: Color) - { + + protected open fun changeIconColor(img: BufferedImage, newColor: Color) { img.paint { val current = Color(img.getRGB(it.x, it.y), true) if (current.red == current.blue && current.blue == current.green && current.red < 255) { val alpha = if (current.alpha == 255) 255 - current.red else current.alpha Color(newColor.red, newColor.green, newColor.blue, alpha) - } - else - current + } else current } } @@ -215,11 +187,9 @@ abstract class AbstractAchievement open fun isUnbounded() = false - fun getProgressDesc() : String - { + fun getProgressDesc(): String { var progressStr = "$attainedValue" - if (!isUnbounded()) - { + if (!isUnbounded()) { progressStr += "/$maxValue" } @@ -228,24 +198,21 @@ abstract class AbstractAchievement open fun isDecreasing() = false - fun getExtraDetails() : String - { - var ret = if (this is AbstractMultiRowAchievement) - { - "Last updated on ${dtLatestUpdate.formatAsDate()}" - } - else - { - "Earned on ${dtLatestUpdate.formatAsDate()}" - } + fun getExtraDetails(): String { + var ret = + if (this is AbstractMultiRowAchievement) { + "Last updated on ${dtLatestUpdate.formatAsDate()}" + } else { + "Earned on ${dtLatestUpdate.formatAsDate()}" + } - if (!gameIdEarned.isEmpty()) - { + if (!gameIdEarned.isEmpty()) { ret += " in Game #$localGameIdEarned" } return ret } - open fun retrieveAllRows() = AchievementEntity().retrieveEntities("AchievementType = '$achievementType'") + open fun retrieveAllRows() = + AchievementEntity().retrieveEntities("AchievementType = '$achievementType'") } diff --git a/src/main/kotlin/dartzee/achievements/AbstractAchievementBestGame.kt b/src/main/kotlin/dartzee/achievements/AbstractAchievementBestGame.kt index 30d94becc..83f886ebb 100644 --- a/src/main/kotlin/dartzee/achievements/AbstractAchievementBestGame.kt +++ b/src/main/kotlin/dartzee/achievements/AbstractAchievementBestGame.kt @@ -3,15 +3,15 @@ package dartzee.achievements import dartzee.utils.Database import dartzee.utils.doesHighestWin -abstract class AbstractAchievementBestGame : AbstractAchievement() -{ +abstract class AbstractAchievementBestGame : AbstractAchievement() { abstract val gameParams: String override val allowedForTeams = false - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() - sb.append(" SELECT pt.PlayerId, g.RowId AS GameId, pt.FinalScore, pt.DtFinished AS DtAchieved") + sb.append( + " SELECT pt.PlayerId, g.RowId AS GameId, pt.FinalScore, pt.DtFinished AS DtAchieved" + ) sb.append(" FROM Participant pt, Game g") sb.append(" WHERE pt.GameId = g.RowId") sb.append(" AND g.GameType = '$gameType'") @@ -27,13 +27,20 @@ abstract class AbstractAchievementBestGame : AbstractAchievement() sb.append(" AND g2.GameParams = g.GameParams") sb.append(" AND pt2.PlayerId = pt.PlayerId") sb.append(" AND pt2.FinalScore > -1") - sb.append(" AND (pt2.FinalScore < pt.FinalScore OR (pt2.FinalScore = pt.FinalScore AND pt2.DtFinished < pt.DtFinished))") + sb.append( + " AND (pt2.FinalScore < pt.FinalScore OR (pt2.FinalScore = pt.FinalScore AND pt2.DtFinished < pt.DtFinished))" + ) sb.append(")") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementCounterFn = { rs.getInt("FinalScore") }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementCounterFn = { rs.getInt("FinalScore") } + ) } } override fun isDecreasing() = !doesHighestWin(gameType) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/AbstractAchievementGamesWon.kt b/src/main/kotlin/dartzee/achievements/AbstractAchievementGamesWon.kt index 03768a149..c90c0fa18 100644 --- a/src/main/kotlin/dartzee/achievements/AbstractAchievementGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/AbstractAchievementGamesWon.kt @@ -3,8 +3,7 @@ package dartzee.achievements import dartzee.db.AchievementEntity import dartzee.utils.Database -abstract class AbstractAchievementGamesWon : AbstractMultiRowAchievement() -{ +abstract class AbstractAchievementGamesWon : AbstractMultiRowAchievement() { override val redThreshold = 1 override val orangeThreshold = 10 override val yellowThreshold = 25 @@ -14,10 +13,11 @@ abstract class AbstractAchievementGamesWon : AbstractMultiRowAchievement() override val maxValue = 200 override val allowedForTeams = false - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() - sb.append(" SELECT pt.PlayerId, pt.GameId, pt.FinalScore AS Score, pt.DtFinished AS DtAchieved") + sb.append( + " SELECT pt.PlayerId, pt.GameId, pt.FinalScore AS Score, pt.DtFinished AS DtAchieved" + ) sb.append(" FROM Participant pt, Game g") sb.append(" WHERE pt.GameId = g.RowId") sb.append(" AND g.GameType = '$gameType'") @@ -26,10 +26,17 @@ abstract class AbstractAchievementGamesWon : AbstractMultiRowAchievement() appendPlayerSql(sb, playerIds) database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementDetailFn = { rs.getInt("Score").toString() }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementDetailFn = { rs.getInt("Score").toString() } + ) } } override fun getBreakdownColumns() = listOf("Game", "Score", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) } diff --git a/src/main/kotlin/dartzee/achievements/AbstractAchievementTeamGamesWon.kt b/src/main/kotlin/dartzee/achievements/AbstractAchievementTeamGamesWon.kt index e4f770abf..3e06cab70 100644 --- a/src/main/kotlin/dartzee/achievements/AbstractAchievementTeamGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/AbstractAchievementTeamGamesWon.kt @@ -3,8 +3,7 @@ package dartzee.achievements import dartzee.db.AchievementEntity import dartzee.utils.Database -abstract class AbstractAchievementTeamGamesWon : AbstractMultiRowAchievement() -{ +abstract class AbstractAchievementTeamGamesWon : AbstractMultiRowAchievement() { override val redThreshold = 1 override val orangeThreshold = 10 override val yellowThreshold = 25 @@ -15,10 +14,11 @@ abstract class AbstractAchievementTeamGamesWon : AbstractMultiRowAchievement() override val allowedForTeams = true override val allowedForIndividuals = false - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() - sb.append(" SELECT pt.PlayerId, pt.GameId, t.FinalScore AS Score, t.DtFinished AS DtAchieved") + sb.append( + " SELECT pt.PlayerId, pt.GameId, t.FinalScore AS Score, t.DtFinished AS DtAchieved" + ) sb.append(" FROM Participant pt, Team t, Game g") sb.append(" WHERE pt.GameId = g.RowId") sb.append(" AND g.GameType = '$gameType'") @@ -27,10 +27,17 @@ abstract class AbstractAchievementTeamGamesWon : AbstractMultiRowAchievement() appendPlayerSql(sb, playerIds) database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementDetailFn = { rs.getInt("Score").toString() }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementDetailFn = { rs.getInt("Score").toString() } + ) } } override fun getBreakdownColumns() = listOf("Game", "Score", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) } diff --git a/src/main/kotlin/dartzee/achievements/AbstractMultiRowAchievement.kt b/src/main/kotlin/dartzee/achievements/AbstractMultiRowAchievement.kt index 850c2b1b1..b78c427ac 100644 --- a/src/main/kotlin/dartzee/achievements/AbstractMultiRowAchievement.kt +++ b/src/main/kotlin/dartzee/achievements/AbstractMultiRowAchievement.kt @@ -4,18 +4,15 @@ import dartzee.core.util.TableUtil import dartzee.db.AchievementEntity import dartzee.db.PlayerEntity -abstract class AbstractMultiRowAchievement: AbstractAchievement() -{ +abstract class AbstractMultiRowAchievement : AbstractAchievement() { override fun isUnbounded() = true - override fun initialiseFromDb(achievementRows: List, player: PlayerEntity?) - { + override fun initialiseFromDb(achievementRows: List, player: PlayerEntity?) { this.player = player attainedValue = calculateAttainedValue(achievementRows) - if (achievementRows.isNotEmpty()) - { + if (achievementRows.isNotEmpty()) { val sortedRows = achievementRows.sortedBy { it.dtAchieved } val last = sortedRows.last() @@ -24,7 +21,7 @@ abstract class AbstractMultiRowAchievement: AbstractAchievement() val tm = TableUtil.DefaultModel() tm.setColumnNames(getBreakdownColumns()) - tm.addRows(sortedRows.map{ getBreakdownRow(it) }) + tm.addRows(sortedRows.map { getBreakdownRow(it) }) tmBreakdown = tm } @@ -36,5 +33,6 @@ abstract class AbstractMultiRowAchievement: AbstractAchievement() open fun useCounter() = false abstract fun getBreakdownColumns(): List + abstract fun getBreakdownRow(a: AchievementEntity): Array -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/AchievementSqlUtil.kt b/src/main/kotlin/dartzee/achievements/AchievementSqlUtil.kt index 04c19f917..7d7418b3f 100644 --- a/src/main/kotlin/dartzee/achievements/AchievementSqlUtil.kt +++ b/src/main/kotlin/dartzee/achievements/AchievementSqlUtil.kt @@ -14,8 +14,7 @@ const val X01_ROUNDS_TABLE = "X01Rounds" const val LAST_ROUND_FROM_PARTICIPANT = "CEIL(CAST(pt.FinalScore AS DECIMAL)/3)" const val LAST_ROUND_FROM_TEAM = "CEIL(CAST(t.FinalScore AS DECIMAL)/3)" -fun getGolfSegmentCases(): String -{ +fun getGolfSegmentCases(): String { val sb = StringBuilder() sb.append(" WHEN drt.SegmentType = '${SegmentType.DOUBLE}' THEN 1") sb.append(" WHEN drt.SegmentType = '${SegmentType.TREBLE}' THEN 2") @@ -26,10 +25,12 @@ fun getGolfSegmentCases(): String return sb.toString() } -fun getPlayerSql(playerIds: List, alias: String? = "pt", whereOrAnd: String = "AND"): String -{ - if (playerIds.isEmpty()) - { +fun getPlayerSql( + playerIds: List, + alias: String? = "pt", + whereOrAnd: String = "AND" +): String { + if (playerIds.isEmpty()) { return "" } @@ -38,27 +39,35 @@ fun getPlayerSql(playerIds: List, alias: String? = "pt", whereOrAnd: Str return "$whereOrAnd $column IN $keys" } -fun appendPlayerSql(sb: StringBuilder, playerIds: List, alias: String? = "pt", whereOrAnd: String = "AND") -{ +fun appendPlayerSql( + sb: StringBuilder, + playerIds: List, + alias: String? = "pt", + whereOrAnd: String = "AND" +) { sb.append(" ${getPlayerSql(playerIds, alias, whereOrAnd)}") } -fun ensureX01RoundsTableExists(playerIds: List, database: Database) -{ - val created = database.createTableIfNotExists( - X01_ROUNDS_TABLE, - "PlayerId VARCHAR(36), GameId VARCHAR(36), ParticipantId VARCHAR(36), StartingScore INT, RoundNumber INT, " + - "TotalDartsThrown INT, RemainingScore INT, LastDartScore INT, LastDartMultiplier INT, DtRoundFinished TIMESTAMP") +fun ensureX01RoundsTableExists(playerIds: List, database: Database) { + val created = + database.createTableIfNotExists( + X01_ROUNDS_TABLE, + "PlayerId VARCHAR(36), GameId VARCHAR(36), ParticipantId VARCHAR(36), StartingScore INT, RoundNumber INT, " + + "TotalDartsThrown INT, RemainingScore INT, LastDartScore INT, LastDartMultiplier INT, DtRoundFinished TIMESTAMP" + ) - if (!created) - { + if (!created) { return } - val tmp1 = database.createTempTable("X01RoundsPt1", - "PlayerId VARCHAR(36), GameId VARCHAR(36), ParticipantId VARCHAR(36), StartingScore INT, RoundNumber INT, LastDartOrdinal INT") + val tmp1 = + database.createTempTable( + "X01RoundsPt1", + "PlayerId VARCHAR(36), GameId VARCHAR(36), ParticipantId VARCHAR(36), StartingScore INT, RoundNumber INT, LastDartOrdinal INT" + ) - database.executeUpdate(""" + database.executeUpdate( + """ INSERT INTO $tmp1 SELECT pt.PlayerId, pt.GameId, pt.RowId, drtFirst.StartingScore, drtFirst.RoundNumber, MAX(drt.Ordinal) FROM ${EntityName.Dart} drtFirst, ${EntityName.Participant} pt, ${EntityName.Game} g, ${EntityName.Dart} drt @@ -72,9 +81,12 @@ fun ensureX01RoundsTableExists(playerIds: List, database: Database) AND drtFirst.RoundNumber = drt.RoundNumber ${getPlayerSql(playerIds)} GROUP BY pt.PlayerId, pt.GameId, pt.RowId, drtFirst.StartingScore, drtFirst.RoundNumber - """.trimIndent()) + """ + .trimIndent() + ) - database.executeUpdate(""" + database.executeUpdate( + """ INSERT INTO $X01_ROUNDS_TABLE SELECT zz.PlayerId, @@ -92,16 +104,23 @@ fun ensureX01RoundsTableExists(playerIds: List, database: Database) AND zz.ParticipantId = drt.ParticipantId AND zz.RoundNumber = drt.RoundNumber AND zz.LastDartOrdinal = drt.Ordinal - """.trimIndent()) + """ + .trimIndent() + ) } -fun buildQualifyingDartzeeGamesTable(database: Database): String? -{ - val dartzeeGames = database.createTempTable("DartzeeGames", "GameId VARCHAR(36), RoundCount INT, TemplateName VARCHAR(1000)") +fun buildQualifyingDartzeeGamesTable(database: Database): String? { + val dartzeeGames = + database.createTempTable( + "DartzeeGames", + "GameId VARCHAR(36), RoundCount INT, TemplateName VARCHAR(1000)" + ) val sb = StringBuilder() sb.append(" INSERT INTO $dartzeeGames") - sb.append(" SELECT g.RowId, COUNT(1) + 1, CASE WHEN dt.Name IS NULL THEN '' ELSE dt.Name END AS TemplateName") + sb.append( + " SELECT g.RowId, COUNT(1) + 1, CASE WHEN dt.Name IS NULL THEN '' ELSE dt.Name END AS TemplateName" + ) sb.append(" FROM ${EntityName.DartzeeRule} dr, ${EntityName.Game} g") sb.append(" LEFT OUTER JOIN ${EntityName.DartzeeTemplate} dt ON (g.GameParams = dt.RowId)") sb.append(" WHERE dr.EntityId = g.RowId") @@ -115,29 +134,38 @@ fun buildQualifyingDartzeeGamesTable(database: Database): String? return dartzeeGames } -fun bulkInsertFromResultSet(rs: ResultSet, - database: Database, - achievementType: AchievementType, - achievementDetailFn: (() -> String)? = null, - achievementCounterFn: (() -> Int)? = null, - oneRowPerPlayer: Boolean = false) -{ +fun bulkInsertFromResultSet( + rs: ResultSet, + database: Database, + achievementType: AchievementType, + achievementDetailFn: (() -> String)? = null, + achievementCounterFn: (() -> Int)? = null, + oneRowPerPlayer: Boolean = false +) { val playerIdsSeen = mutableSetOf() val entities = mutableListOf() - while (rs.next()) - { + while (rs.next()) { val playerId = rs.getString("PlayerId") val gameId = rs.getString("GameId") val dtAchieved = rs.getTimestamp("DtAchieved") val detail = achievementDetailFn?.invoke().orEmpty() val counter = achievementCounterFn?.invoke() ?: -1 - if (!oneRowPerPlayer || playerIdsSeen.add(playerId)) - { - entities.add(AchievementEntity.factory(achievementType, playerId, gameId, counter, detail, dtAchieved, database)) + if (!oneRowPerPlayer || playerIdsSeen.add(playerId)) { + entities.add( + AchievementEntity.factory( + achievementType, + playerId, + gameId, + counter, + detail, + dtAchieved, + database + ) + ) } } BulkInserter.insert(entities, database = database) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/AchievementType.kt b/src/main/kotlin/dartzee/achievements/AchievementType.kt index f5190bf75..892feeb9d 100644 --- a/src/main/kotlin/dartzee/achievements/AchievementType.kt +++ b/src/main/kotlin/dartzee/achievements/AchievementType.kt @@ -1,7 +1,6 @@ package dartzee.achievements -enum class AchievementType -{ +enum class AchievementType { X01_BEST_FINISH, X01_BEST_THREE_DART_SCORE, X01_CHECKOUT_COMPLETENESS, @@ -36,4 +35,4 @@ enum class AchievementType GOLF_IN_BOUNDS, X01_STYLISH_FINISH, DUMMY_TOTAL -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/AchievementUtil.kt b/src/main/kotlin/dartzee/achievements/AchievementUtil.kt index 36992dbdd..826e24732 100644 --- a/src/main/kotlin/dartzee/achievements/AchievementUtil.kt +++ b/src/main/kotlin/dartzee/achievements/AchievementUtil.kt @@ -57,49 +57,62 @@ const val MAX_ACHIEVEMENT_SCORE = 6 fun getAchievementMaximum() = getAllAchievements().size * MAX_ACHIEVEMENT_SCORE -fun getPlayerAchievementScore(allAchievementRows: List, player: PlayerEntity): Int -{ - val myAchievementRows = allAchievementRows.filter{ it.playerId == player.rowId } +fun getPlayerAchievementScore( + allAchievementRows: List, + player: PlayerEntity +): Int { + val myAchievementRows = allAchievementRows.filter { it.playerId == player.rowId } return getAllAchievements().sumOf { achievement -> - val myRelevantRows = myAchievementRows.filter { it.achievementType == achievement.achievementType } + val myRelevantRows = + myAchievementRows.filter { it.achievementType == achievement.achievementType } achievement.initialiseFromDb(myRelevantRows, player) achievement.getScore() } } -fun convertEmptyAchievements() -{ - val emptyAchievements = getAllAchievements().filter{ !rowsExistForAchievement(it) } - if (emptyAchievements.isNotEmpty()) - { +fun convertEmptyAchievements() { + val emptyAchievements = getAllAchievements().filter { !rowsExistForAchievement(it) } + if (emptyAchievements.isNotEmpty()) { runConversionsWithProgressBar(emptyAchievements, mutableListOf()) } } -fun runConversionsWithProgressBar(achievements: List, - playerIds: List, - database: Database = mainDatabase): Thread -{ +fun runConversionsWithProgressBar( + achievements: List, + playerIds: List, + database: Database = mainDatabase +): Thread { val r = Runnable { runConversionsInOtherThread(achievements, playerIds, database) } val t = Thread(r, "Conversion thread") t.start() return t } -private fun runConversionsInOtherThread(achievements: List, playerIds: List, database: Database) -{ - val dlg = ProgressDialog.factory("Populating Achievements", "achievements remaining", achievements.size) +private fun runConversionsInOtherThread( + achievements: List, + playerIds: List, + database: Database +) { + val dlg = + ProgressDialog.factory( + "Populating Achievements", + "achievements remaining", + achievements.size + ) dlg.setVisibleLater() val playerCount = if (playerIds.isEmpty()) "all" else "${playerIds.size}" - logger.info(CODE_ACHIEVEMENT_CONVERSION_STARTED, "Regenerating ${achievements.size} achievements for $playerCount players", - KEY_PLAYER_IDS to playerIds, KEY_ACHIEVEMENT_TYPES to achievements.map { it.achievementType }) + logger.info( + CODE_ACHIEVEMENT_CONVERSION_STARTED, + "Regenerating ${achievements.size} achievements for $playerCount players", + KEY_PLAYER_IDS to playerIds, + KEY_ACHIEVEMENT_TYPES to achievements.map { it.achievementType } + ) val timings = mutableMapOf() - try - { + try { database.dropUnexpectedTables() achievements.forEach { achievement -> @@ -111,27 +124,30 @@ private fun runConversionsInOtherThread(achievements: List, dlg.incrementProgressLater() } - } - finally - { + } finally { database.dropUnexpectedTables() } val totalTime = timings.values.sum() - logger.info(CODE_ACHIEVEMENT_CONVERSION_FINISHED, "Done in $totalTime", KEY_ACHIEVEMENT_TIMINGS to timings) + logger.info( + CODE_ACHIEVEMENT_CONVERSION_FINISHED, + "Done in $totalTime", + KEY_ACHIEVEMENT_TIMINGS to timings + ) dlg.disposeLater() } -private fun rowsExistForAchievement(achievement: AbstractAchievement) : Boolean -{ - val sql = "SELECT COUNT(1) FROM Achievement WHERE AchievementType = '${achievement.achievementType}'" +private fun rowsExistForAchievement(achievement: AbstractAchievement): Boolean { + val sql = + "SELECT COUNT(1) FROM Achievement WHERE AchievementType = '${achievement.achievementType}'" val count = mainDatabase.executeQueryAggregate(sql) return count > 0 } -fun getAchievementsForGameType(gameType: GameType) = getAllAchievements().filter { it.gameType == gameType } +fun getAchievementsForGameType(gameType: GameType) = + getAllAchievements().filter { it.gameType == gameType } fun getAllAchievements() = listOf( @@ -173,13 +189,13 @@ fun getAllAchievements() = fun getAchievementForType(achievementType: AchievementType) = getAllAchievements().find { it.achievementType == achievementType } -fun getBestGameAchievement(gameType : GameType) : AbstractAchievementBestGame? -{ - val ref = getAllAchievements().find { it is AbstractAchievementBestGame && it.gameType == gameType } +fun getBestGameAchievement(gameType: GameType): AbstractAchievementBestGame? { + val ref = + getAllAchievements().find { it is AbstractAchievementBestGame && it.gameType == gameType } return ref as AbstractAchievementBestGame? } -fun getWinAchievementType(gameType : GameType) = +fun getWinAchievementType(gameType: GameType) = getAllAchievements() .first { it is AbstractAchievementGamesWon && it.gameType == gameType } .achievementType @@ -189,13 +205,20 @@ fun getTeamWinAchievementType(gameType: GameType) = .first { it is AbstractAchievementTeamGamesWon && it.gameType == gameType } .achievementType -fun unlockThreeDartAchievement(playerIds: List, x01RoundWhereSql: String, - achievementScoreSql : String, achievementType: AchievementType, database: Database) -{ +fun unlockThreeDartAchievement( + playerIds: List, + x01RoundWhereSql: String, + achievementScoreSql: String, + achievementType: AchievementType, + database: Database +) { ensureX01RoundsTableExists(playerIds, database) - val tempTable = database.createTempTable("PlayerResults", - "PlayerId VARCHAR(36), GameId VARCHAR(36), DtAchieved TIMESTAMP, Score INT") + val tempTable = + database.createTempTable( + "PlayerResults", + "PlayerId VARCHAR(36), GameId VARCHAR(36), DtAchieved TIMESTAMP, Score INT" + ) var sb = StringBuilder() sb.append(" INSERT INTO $tempTable") @@ -205,7 +228,8 @@ fun unlockThreeDartAchievement(playerIds: List, x01RoundWhereSql: String if (!database.executeUpdate(sb)) return - val zzPlayerToScore = database.createTempTable("PlayerToThreeDartScore", "PlayerId VARCHAR(36), Score INT") + val zzPlayerToScore = + database.createTempTable("PlayerToThreeDartScore", "PlayerId VARCHAR(36), Score INT") sb = StringBuilder() sb.append(" INSERT INTO $zzPlayerToScore") @@ -223,53 +247,78 @@ fun unlockThreeDartAchievement(playerIds: List, x01RoundWhereSql: String sb.append(" ORDER BY DtAchieved") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, oneRowPerPlayer = true, achievementCounterFn = { rs.getInt("Score") }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + oneRowPerPlayer = true, + achievementCounterFn = { rs.getInt("Score") } + ) } } -fun retrieveAchievementForDetail(achievementType: AchievementType, playerId: String, achievementDetail: String): AchievementEntity? -{ - val whereSql = "AchievementType = '$achievementType' AND PlayerId = '$playerId' AND AchievementDetail = '$achievementDetail'" +fun retrieveAchievementForDetail( + achievementType: AchievementType, + playerId: String, + achievementDetail: String +): AchievementEntity? { + val whereSql = + "AchievementType = '$achievementType' AND PlayerId = '$playerId' AND AchievementDetail = '$achievementDetail'" return AchievementEntity().retrieveEntity(whereSql) } fun getGamesWonIcon(gameType: GameType): URL? = - when (gameType) - { + when (gameType) { GameType.X01 -> ResourceCache.URL_ACHIEVEMENT_X01_GAMES_WON GameType.GOLF -> ResourceCache.URL_ACHIEVEMENT_GOLF_GAMES_WON GameType.ROUND_THE_CLOCK -> ResourceCache.URL_ACHIEVEMENT_CLOCK_GAMES_WON GameType.DARTZEE -> ResourceCache.URL_ACHIEVEMENT_DARTZEE_GAMES_WON } -fun paintMedalCommon(g: Graphics2D, achievement: AbstractAchievement, size: Int, highlighted: Boolean) -{ +fun paintMedalCommon( + g: Graphics2D, + achievement: AbstractAchievement, + size: Int, + highlighted: Boolean +) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) - //Draw the track + // Draw the track g.color = Color.DARK_GRAY.brighter() g.fillArc(0, 0, size, size, 0, 360) - //Mark the levels + // Mark the levels markThreshold(g, achievement, size, Color.MAGENTA, achievement.pinkThreshold) markThreshold(g, achievement, size, Color.CYAN, achievement.blueThreshold) markThreshold(g, achievement, size, Color.GREEN, achievement.greenThreshold) markThreshold(g, achievement, size, Color.YELLOW, achievement.yellowThreshold) - markThreshold(g, achievement, size, DartsColour.COLOUR_ACHIEVEMENT_ORANGE, achievement.orangeThreshold) + markThreshold( + g, + achievement, + size, + DartsColour.COLOUR_ACHIEVEMENT_ORANGE, + achievement.orangeThreshold + ) markThreshold(g, achievement, size, Color.RED, achievement.redThreshold) - //Draw the actual progress + // Draw the actual progress val angle = achievement.getAngle() g.color = achievement.getColor(highlighted).darker() g.fillArc(0, 0, size, size, 90, -angle.toInt()) - //Inner circle + // Inner circle g.color = achievement.getColor(highlighted) - g.fillArc(15, 15, size -30, size -30, 0, 360) + g.fillArc(15, 15, size - 30, size - 30, 0, 360) } -private fun markThreshold(g: Graphics2D, achievement: AbstractAchievement, size: Int, color: Color, threshold: Int) -{ + +private fun markThreshold( + g: Graphics2D, + achievement: AbstractAchievement, + size: Int, + color: Color, + threshold: Int +) { g.color = color val thresholdAngle = achievement.getAngle(threshold) g.fillArc(0, 0, size, size, 90 - thresholdAngle.toInt(), 3) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/DummyAchievementTotal.kt b/src/main/kotlin/dartzee/achievements/DummyAchievementTotal.kt index 452e75677..6c491acfb 100644 --- a/src/main/kotlin/dartzee/achievements/DummyAchievementTotal.kt +++ b/src/main/kotlin/dartzee/achievements/DummyAchievementTotal.kt @@ -1,13 +1,12 @@ package dartzee.achievements import dartzee.db.AchievementEntity -import dartzee.game.GameType import dartzee.db.PlayerEntity +import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache.URL_ACHIEVEMENT_LOCKED -class DummyAchievementTotal: AbstractAchievement() -{ +class DummyAchievementTotal : AbstractAchievement() { override val name = "Total Achievements" override val desc = "" override val achievementType = AchievementType.DUMMY_TOTAL @@ -24,13 +23,12 @@ class DummyAchievementTotal: AbstractAchievement() override fun getIconURL() = URL_ACHIEVEMENT_LOCKED - override fun populateForConversion(playerIds: List, database: Database){} + override fun populateForConversion(playerIds: List, database: Database) {} - override fun initialiseFromDb(achievementRows: List, player: PlayerEntity?) - { + override fun initialiseFromDb(achievementRows: List, player: PlayerEntity?) { this.player = player attainedValue = getPlayerAchievementScore(achievementRows, player!!) } override fun retrieveAllRows() = AchievementEntity().retrieveEntities("") -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBestGame.kt b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBestGame.kt index 82ad4f16f..4ed721b2c 100644 --- a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBestGame.kt +++ b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBestGame.kt @@ -12,11 +12,8 @@ import dartzee.utils.ResourceCache const val DARTZEE_ACHIEVEMENT_MIN_ROUNDS = 5 -/** - * Measured as average-per-round, to prevent "gaming" it by having a massive set of easy rules - */ -class AchievementDartzeeBestGame: AbstractAchievement() -{ +/** Measured as average-per-round, to prevent "gaming" it by having a massive set of easy rules */ +class AchievementDartzeeBestGame : AbstractAchievement() { override val name = "Yahtzee!" override val desc = "Best round average in Dartzee (at least 5 rounds)" override val achievementType = AchievementType.DARTZEE_BEST_GAME @@ -30,11 +27,14 @@ class AchievementDartzeeBestGame: AbstractAchievement() override val gameType = GameType.DARTZEE override val allowedForTeams = false - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val dartzeeGames = buildQualifyingDartzeeGamesTable(database) ?: return - val allScores = database.createTempTable("DartzeeScores", "PlayerId VARCHAR(36), DtAchieved TIMESTAMP, GameId VARCHAR(36), ComputedScore INT") + val allScores = + database.createTempTable( + "DartzeeScores", + "PlayerId VARCHAR(36), DtAchieved TIMESTAMP, GameId VARCHAR(36), ComputedScore INT" + ) var sb = StringBuilder() sb.append(" INSERT INTO $allScores") @@ -53,9 +53,15 @@ class AchievementDartzeeBestGame: AbstractAchievement() sb.append(" ORDER BY ComputedScore DESC, DtAchieved") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, oneRowPerPlayer = true, achievementCounterFn = { rs.getInt("ComputedScore") }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + oneRowPerPlayer = true, + achievementCounterFn = { rs.getInt("ComputedScore") } + ) } } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_DARTZEE_BEST_GAME -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBingo.kt b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBingo.kt index 5b73bd4c6..64c8c0b33 100644 --- a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBingo.kt +++ b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeBingo.kt @@ -11,8 +11,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementDartzeeBingo: AbstractMultiRowAchievement() -{ +class AchievementDartzeeBingo : AbstractMultiRowAchievement() { override val name = "Bingo!" override val desc = "Total unique last 2 digits of Dartzee scores" override val achievementType = AchievementType.DARTZEE_BINGO @@ -26,16 +25,20 @@ class AchievementDartzeeBingo: AbstractMultiRowAchievement() override val gameType = GameType.DARTZEE override val allowedForTeams = false - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val dartzeeGames = buildQualifyingDartzeeGamesTable(database) ?: return - val playerBingos = database.createTempTable("PlayerBingos", "PlayerId VARCHAR(36), BingoScore INT, Score INT, GameId VARCHAR(36), DtAchieved TIMESTAMP") - ?: return + val playerBingos = + database.createTempTable( + "PlayerBingos", + "PlayerId VARCHAR(36), BingoScore INT, Score INT, GameId VARCHAR(36), DtAchieved TIMESTAMP" + ) ?: return var sb = StringBuilder() sb.append(" INSERT INTO $playerBingos") - sb.append(" SELECT pt.PlayerId, mod(pt.FinalScore, 100), pt.FinalScore, pt.GameId, pt.DtFinished") + sb.append( + " SELECT pt.PlayerId, mod(pt.FinalScore, 100), pt.FinalScore, pt.GameId, pt.DtFinished" + ) sb.append(" FROM ${EntityName.Participant} pt, $dartzeeGames zz") sb.append(" WHERE pt.GameId = zz.GameId") appendPlayerSql(sb, playerIds) @@ -56,7 +59,10 @@ class AchievementDartzeeBingo: AbstractMultiRowAchievement() sb.append(")") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, + bulkInsertFromResultSet( + rs, + database, + achievementType, achievementCounterFn = { rs.getInt("BingoScore") }, achievementDetailFn = { rs.getInt("Score").toString() } ) @@ -65,7 +71,11 @@ class AchievementDartzeeBingo: AbstractMultiRowAchievement() override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_DARTZEE_BINGO - override fun getBreakdownColumns() = listOf("Bingo Score", "Game", "Full Score", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.achievementCounter, a.localGameIdEarned, a.achievementDetail, a.dtAchieved) + override fun getBreakdownColumns() = + listOf("Bingo Score", "Game", "Full Score", "Date Achieved") + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.achievementCounter, a.localGameIdEarned, a.achievementDetail, a.dtAchieved) + override fun isUnbounded() = false -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeFlawless.kt b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeFlawless.kt index 62bbc598b..5e181cad4 100644 --- a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeFlawless.kt +++ b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeFlawless.kt @@ -11,8 +11,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementDartzeeFlawless: AbstractMultiRowAchievement() -{ +class AchievementDartzeeFlawless : AbstractMultiRowAchievement() { override val name = "Flawless" override val desc = "Games where all rules were passed (at least 5 rounds)" override val achievementType = AchievementType.DARTZEE_FLAWLESS @@ -28,12 +27,13 @@ class AchievementDartzeeFlawless: AbstractMultiRowAchievement() override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_DARTZEE_FLAWLESS - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val dartzeeGames = buildQualifyingDartzeeGamesTable(database) ?: return val sb = StringBuilder() - sb.append(" SELECT pt.PlayerId, pt.DtFinished AS DtAchieved, zz.GameId, pt.FinalScore, zz.TemplateName") + sb.append( + " SELECT pt.PlayerId, pt.DtFinished AS DtAchieved, zz.GameId, pt.FinalScore, zz.TemplateName" + ) sb.append(" FROM ${EntityName.Participant} pt, $dartzeeGames zz") sb.append(" WHERE pt.GameId = zz.GameId") sb.append(" AND pt.FinalScore > -1") @@ -47,10 +47,18 @@ class AchievementDartzeeFlawless: AbstractMultiRowAchievement() sb.append(" )") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementCounterFn = { rs.getInt("FinalScore") }, achievementDetailFn = { rs.getString("TemplateName")}) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementCounterFn = { rs.getInt("FinalScore") }, + achievementDetailFn = { rs.getString("TemplateName") } + ) } } override fun getBreakdownColumns() = listOf("Game", "Score", "Template", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.achievementCounter, a.achievementDetail, a.dtAchieved) -} \ No newline at end of file + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.achievementCounter, a.achievementDetail, a.dtAchieved) +} diff --git a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeGamesWon.kt b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeGamesWon.kt index 8aa038a0d..532c223ff 100644 --- a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeGamesWon.kt @@ -5,12 +5,11 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementDartzeeGamesWon : AbstractAchievementGamesWon() -{ +class AchievementDartzeeGamesWon : AbstractAchievementGamesWon() { override val achievementType = AchievementType.DARTZEE_GAMES_WON override val gameType = GameType.DARTZEE override val name = "Dartzee Winner" override val desc = "Total number of wins in Dartzee" override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_DARTZEE_GAMES_WON -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeHalved.kt b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeHalved.kt index 5f735ce0c..bf0d1cdd1 100644 --- a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeHalved.kt +++ b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeHalved.kt @@ -9,8 +9,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementDartzeeHalved: AbstractAchievement() -{ +class AchievementDartzeeHalved : AbstractAchievement() { override val name = "Halved" override val desc = "Biggest loss of points in a single round of Dartzee" override val achievementType = AchievementType.DARTZEE_HALVED @@ -24,11 +23,14 @@ class AchievementDartzeeHalved: AbstractAchievement() override val gameType = GameType.DARTZEE override val allowedForTeams = true - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() - sb.append(" SELECT drr.DtCreation as DtAchieved, drr.Score * -1 AS Score, pt.PlayerId, pt.GameId") - sb.append(" FROM ${EntityName.DartzeeRoundResult} drr, ${EntityName.Participant} pt, ${EntityName.Game} g") + sb.append( + " SELECT drr.DtCreation as DtAchieved, drr.Score * -1 AS Score, pt.PlayerId, pt.GameId" + ) + sb.append( + " FROM ${EntityName.DartzeeRoundResult} drr, ${EntityName.Participant} pt, ${EntityName.Game} g" + ) sb.append(" WHERE drr.Success = false") sb.append(" AND drr.ParticipantId = pt.RowId") sb.append(" AND pt.GameId = g.RowId") @@ -37,10 +39,17 @@ class AchievementDartzeeHalved: AbstractAchievement() sb.append(" ORDER BY drr.Score, drr.DtCreation") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, oneRowPerPlayer = true, achievementCounterFn = { rs.getInt("Score") }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + oneRowPerPlayer = true, + achievementCounterFn = { rs.getInt("Score") } + ) } } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_DARTZEE_HALVED + override fun isUnbounded() = true -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeTeamGamesWon.kt b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeTeamGamesWon.kt index fa3b69069..e1baf70ee 100644 --- a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeTeamGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeTeamGamesWon.kt @@ -5,12 +5,11 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementDartzeeTeamGamesWon : AbstractAchievementTeamGamesWon() -{ +class AchievementDartzeeTeamGamesWon : AbstractAchievementTeamGamesWon() { override val name = "Dartzee Winners" override val desc = "Total number of team wins in Dartzee" override val achievementType = AchievementType.DARTZEE_TEAM_GAMES_WON override val gameType = GameType.DARTZEE override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_DARTZEE_WINNERS -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeUnderPressure.kt b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeUnderPressure.kt index 5da1576a0..d602d5c11 100644 --- a/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeUnderPressure.kt +++ b/src/main/kotlin/dartzee/achievements/dartzee/AchievementDartzeeUnderPressure.kt @@ -13,8 +13,7 @@ import dartzee.utils.Database import dartzee.utils.ResourceCache import java.sql.ResultSet -class AchievementDartzeeUnderPressure: AbstractMultiRowAchievement() -{ +class AchievementDartzeeUnderPressure : AbstractMultiRowAchievement() { override val name = "Under Pressure" override val desc = "Games finished by passing the hardest rule (at least 5 rounds)" override val achievementType = AchievementType.DARTZEE_UNDER_PRESSURE @@ -28,14 +27,14 @@ class AchievementDartzeeUnderPressure: AbstractMultiRowAchievement() override val gameType = GameType.DARTZEE override val allowedForTeams = true - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val dartzeeGames = buildQualifyingDartzeeGamesTable(database) ?: return - val dartzeeGamesHardestRule = database.createTempTable( - "DartzeeGamesHardestRule", - "GameId VARCHAR(36), RuleId VARCHAR(36), RuleNumber INT" - ) + val dartzeeGamesHardestRule = + database.createTempTable( + "DartzeeGamesHardestRule", + "GameId VARCHAR(36), RuleId VARCHAR(36), RuleNumber INT" + ) var sb = StringBuilder() sb.append(" INSERT INTO $dartzeeGamesHardestRule") @@ -54,8 +53,12 @@ class AchievementDartzeeUnderPressure: AbstractMultiRowAchievement() if (!database.executeUpdate(sb)) return sb = StringBuilder() - sb.append(" SELECT pt.PlayerId, drr.DtCreation AS DtAchieved, zz.GameId, zz.RuleId, drr.Score") - sb.append(" FROM $dartzeeGamesHardestRule zz, ${EntityName.DartzeeRoundResult} drr, ${EntityName.Participant} pt") + sb.append( + " SELECT pt.PlayerId, drr.DtCreation AS DtAchieved, zz.GameId, zz.RuleId, drr.Score" + ) + sb.append( + " FROM $dartzeeGamesHardestRule zz, ${EntityName.DartzeeRoundResult} drr, ${EntityName.Participant} pt" + ) sb.append(" LEFT OUTER JOIN ${EntityName.Team} t ON (pt.TeamId = t.RowId)") sb.append(" WHERE pt.GameId = zz.GameId") sb.append(" AND (pt.FinalScore > -1 OR t.FinalScore > -1)") @@ -67,15 +70,17 @@ class AchievementDartzeeUnderPressure: AbstractMultiRowAchievement() sb.append(" AND drr.RoundNumber = zz.RuleNumber + 1") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, + bulkInsertFromResultSet( + rs, + database, + achievementType, achievementCounterFn = { rs.getInt("Score") }, achievementDetailFn = { extractAchievementDetail(database, rs) } ) } } - private fun extractAchievementDetail(database: Database, rs: ResultSet): String - { + private fun extractAchievementDetail(database: Database, rs: ResultSet): String { val ruleId = rs.getString("RuleId") val rule = DartzeeRuleEntity(database).retrieveForId(ruleId) ?: return "" @@ -86,5 +91,7 @@ class AchievementDartzeeUnderPressure: AbstractMultiRowAchievement() override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_DARTZEE_UNDER_PRESSURE override fun getBreakdownColumns() = listOf("Game", "Score", "Rule", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.achievementCounter, a.achievementDetail, a.dtAchieved) -} \ No newline at end of file + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.achievementCounter, a.achievementDetail, a.dtAchieved) +} diff --git a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfBestGame.kt b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfBestGame.kt index 062eb1abf..4f3aca2df 100644 --- a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfBestGame.kt +++ b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfBestGame.kt @@ -5,21 +5,20 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementGolfBestGame : AbstractAchievementBestGame() -{ +class AchievementGolfBestGame : AbstractAchievementBestGame() { override val achievementType = AchievementType.GOLF_BEST_GAME override val name = "Career Round" override val desc = "Best game of golf (18 holes)" override val gameType = GameType.GOLF override val gameParams = "18" - override val redThreshold = 81 //4.5 per hole - override val orangeThreshold = 72 //4 per hole - override val yellowThreshold = 63 //3.5 per hole - override val greenThreshold = 54 //3 hole - override val blueThreshold = 45 //2.5 per hole - override val pinkThreshold = 36 //2 per hole + override val redThreshold = 81 // 4.5 per hole + override val orangeThreshold = 72 // 4 per hole + override val yellowThreshold = 63 // 3.5 per hole + override val greenThreshold = 54 // 3 hole + override val blueThreshold = 45 // 2.5 per hole + override val pinkThreshold = 36 // 2 per hole override val maxValue = 18 override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_GOLF_BEST_GAME -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfCourseMaster.kt b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfCourseMaster.kt index 862708156..52188d8f1 100644 --- a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfCourseMaster.kt +++ b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfCourseMaster.kt @@ -10,8 +10,7 @@ import dartzee.`object`.SegmentType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementGolfCourseMaster : AbstractMultiRowAchievement() -{ +class AchievementGolfCourseMaster : AbstractMultiRowAchievement() { override val name = "Course Master" override val desc = "Unique holes where a hole-in-one has been achieved" override val achievementType = AchievementType.GOLF_COURSE_MASTER @@ -28,13 +27,18 @@ class AchievementGolfCourseMaster : AbstractMultiRowAchievement() override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_GOLF_COURSE_MASTER override fun getBreakdownColumns() = listOf("Hole", "Game", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.achievementDetail.toInt(), a.localGameIdEarned, a.dtAchieved) + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.achievementDetail.toInt(), a.localGameIdEarned, a.dtAchieved) + override fun isUnbounded() = false - override fun populateForConversion(playerIds: List, database: Database) - { - val tempTable = database.createTempTable("PlayerHolesInOne", "PlayerId VARCHAR(36), Score INT, GameId VARCHAR(36), DtAchieved TIMESTAMP") - ?: return + override fun populateForConversion(playerIds: List, database: Database) { + val tempTable = + database.createTempTable( + "PlayerHolesInOne", + "PlayerId VARCHAR(36), Score INT, GameId VARCHAR(36), DtAchieved TIMESTAMP" + ) ?: return var sb = StringBuilder() @@ -63,7 +67,12 @@ class AchievementGolfCourseMaster : AbstractMultiRowAchievement() sb.append(")") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementDetailFn = { rs.getInt("Score").toString() }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementDetailFn = { rs.getInt("Score").toString() } + ) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfGamesWon.kt b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfGamesWon.kt index 7217af175..4f588dd81 100644 --- a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfGamesWon.kt @@ -5,12 +5,11 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementGolfGamesWon : AbstractAchievementGamesWon() -{ +class AchievementGolfGamesWon : AbstractAchievementGamesWon() { override val achievementType = AchievementType.GOLF_GAMES_WON override val gameType = GameType.GOLF override val name = "Golf Winner" override val desc = "Total number of wins in Golf" override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_GOLF_GAMES_WON -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfInBounds.kt b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfInBounds.kt index 9922519de..6eb4fdee7 100644 --- a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfInBounds.kt +++ b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfInBounds.kt @@ -10,8 +10,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementGolfInBounds : AbstractMultiRowAchievement() -{ +class AchievementGolfInBounds : AbstractMultiRowAchievement() { override val name = "In Bounds" override val desc = "Games of 18 holes where no hole scored a 5" override val achievementType = AchievementType.GOLF_IN_BOUNDS @@ -26,13 +25,19 @@ class AchievementGolfInBounds : AbstractMultiRowAchievement() override val allowedForTeams = false override fun getBreakdownColumns() = listOf("Game", "Score", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) - override fun populateForConversion(playerIds: List, database: Database) - { - val relevantParticipants = database.createTempTable("GolfParticipants", "ParticipantId VARCHAR(36), PlayerId VARCHAR(36), GameId VARCHAR(36), DtFinished TIMESTAMP, FinalScore INT") ?: return + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) - database.executeUpdate(""" + override fun populateForConversion(playerIds: List, database: Database) { + val relevantParticipants = + database.createTempTable( + "GolfParticipants", + "ParticipantId VARCHAR(36), PlayerId VARCHAR(36), GameId VARCHAR(36), DtFinished TIMESTAMP, FinalScore INT" + ) ?: return + + database.executeUpdate( + """ INSERT INTO $relevantParticipants SELECT pt.RowId, pt.PlayerId, pt.GameId, pt.DtFinished, pt.FinalScore FROM ${EntityName.Participant} pt, ${EntityName.Game} g @@ -42,11 +47,18 @@ class AchievementGolfInBounds : AbstractMultiRowAchievement() AND pt.FinalScore > -1 AND pt.TeamId = '' ${getPlayerSql(playerIds)} - """.trimIndent()) + """ + .trimIndent() + ) - val rounds = database.createTempTable("GolfRounds", "ParticipantId VARCHAR(36), RoundNumber INT, LastDartOrdinal INT") ?: return + val rounds = + database.createTempTable( + "GolfRounds", + "ParticipantId VARCHAR(36), RoundNumber INT, LastDartOrdinal INT" + ) ?: return - database.executeUpdate(""" + database.executeUpdate( + """ INSERT INTO $rounds SELECT zz.ParticipantId, drtFirst.RoundNumber, MAX(drt.Ordinal) FROM $relevantParticipants zz, ${EntityName.Dart} drtFirst, ${EntityName.Dart} drt @@ -57,11 +69,18 @@ class AchievementGolfInBounds : AbstractMultiRowAchievement() AND drtFirst.PlayerId = drt.PlayerId AND drtFirst.RoundNumber = drt.RoundNumber GROUP BY zz.ParticipantId, drtFirst.RoundNumber - """.trimIndent()) + """ + .trimIndent() + ) - val roundScores = database.createTempTable("GolfRoundScores", "ParticipantId VARCHAR(36), RoundNumber INT, Hit BOOLEAN") ?: return + val roundScores = + database.createTempTable( + "GolfRoundScores", + "ParticipantId VARCHAR(36), RoundNumber INT, Hit BOOLEAN" + ) ?: return - database.executeUpdate(""" + database.executeUpdate( + """ INSERT INTO $roundScores SELECT zz.ParticipantId, zz.RoundNumber, CASE WHEN drt.Multiplier = 0 THEN FALSE @@ -71,9 +90,13 @@ class AchievementGolfInBounds : AbstractMultiRowAchievement() WHERE zz.ParticipantId = drt.ParticipantId AND zz.RoundNumber = drt.RoundNumber AND zz.LastDartOrdinal = drt.Ordinal - """.trimIndent()) + """ + .trimIndent() + ) - database.executeQuery(""" + database + .executeQuery( + """ SELECT pt.PlayerId, pt.GameId, pt.DtFinished AS DtAchieved, pt.FinalScore FROM $relevantParticipants pt WHERE NOT EXISTS ( @@ -81,10 +104,18 @@ class AchievementGolfInBounds : AbstractMultiRowAchievement() WHERE pt.ParticipantId = rs.ParticipantId AND rs.Hit = FALSE ) - """.trimIndent()).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementDetailFn = { rs.getInt("FinalScore").toString() }) - } + """ + .trimIndent() + ) + .use { rs -> + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementDetailFn = { rs.getInt("FinalScore").toString() } + ) + } } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_GOLF_IN_BOUNDS -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfOneHitWonder.kt b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfOneHitWonder.kt index f836d26e7..2a329ce33 100644 --- a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfOneHitWonder.kt +++ b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfOneHitWonder.kt @@ -10,8 +10,7 @@ import dartzee.`object`.SegmentType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementGolfOneHitWonder : AbstractAchievement() -{ +class AchievementGolfOneHitWonder : AbstractAchievement() { override val name = "One Hit Wonder" override val desc = "Most holes-in-one in a single game of Golf" override val achievementType = AchievementType.GOLF_ONE_HIT_WONDER @@ -25,10 +24,12 @@ class AchievementGolfOneHitWonder : AbstractAchievement() override val gameType = GameType.GOLF override val allowedForTeams = true - override fun populateForConversion(playerIds: List, database: Database) - { - val tempTable = database.createTempTable("GameHolesInOne", "PlayerId VARCHAR(36), GameId VARCHAR(36), DtAchieved TIMESTAMP, HoleInOneCount INT") - ?: return + override fun populateForConversion(playerIds: List, database: Database) { + val tempTable = + database.createTempTable( + "GameHolesInOne", + "PlayerId VARCHAR(36), GameId VARCHAR(36), DtAchieved TIMESTAMP, HoleInOneCount INT" + ) ?: return var sb = StringBuilder() sb.append(" INSERT INTO $tempTable") @@ -52,13 +53,20 @@ class AchievementGolfOneHitWonder : AbstractAchievement() sb.append(" SELECT 1") sb.append(" FROM $tempTable zz2") sb.append(" WHERE zz1.PlayerId = zz2.PlayerId") - sb.append(" AND (zz2.HoleInOneCount > zz1.HoleInOneCount OR (zz2.HoleInOneCount = zz1.HoleInOneCount AND zz2.DtAchieved < zz1.DtAchieved))") + sb.append( + " AND (zz2.HoleInOneCount > zz1.HoleInOneCount OR (zz2.HoleInOneCount = zz1.HoleInOneCount AND zz2.DtAchieved < zz1.DtAchieved))" + ) sb.append(")") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementCounterFn = { rs.getInt("HoleInOneCount") }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementCounterFn = { rs.getInt("HoleInOneCount") } + ) } } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_GOLF_ONE_HIT_WONDER -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfPointsRisked.kt b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfPointsRisked.kt index a84b97ff9..e76625774 100644 --- a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfPointsRisked.kt +++ b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfPointsRisked.kt @@ -10,8 +10,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementGolfPointsRisked : AbstractMultiRowAchievement() -{ +class AchievementGolfPointsRisked : AbstractMultiRowAchievement() { override val name = "Gambler" override val desc = "Total number of points risked (by continuing to throw) in Golf" override val gameType = GameType.GOLF @@ -27,14 +26,22 @@ class AchievementGolfPointsRisked : AbstractMultiRowAchievement() override val allowedForTeams = true override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_POINTS_RISKED + override fun isUnbounded() = true override fun getBreakdownColumns() = listOf("Game", "Round", "Points risked", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.achievementCounter, a.dtAchieved) + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf( + a.localGameIdEarned, + a.achievementDetail.toInt(), + a.achievementCounter, + a.dtAchieved + ) + override fun useCounter() = true - private fun buildPointsRiskedSql(): String - { + private fun buildPointsRiskedSql(): String { val sb = StringBuilder() sb.append("5 - CASE") sb.append(getGolfSegmentCases()) @@ -43,11 +50,12 @@ class AchievementGolfPointsRisked : AbstractMultiRowAchievement() return sb.toString() } - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() - sb.append(" SELECT pt.PlayerId, pt.GameId, drt.RoundNumber, SUM(${buildPointsRiskedSql()}) AS PointsRisked, MAX(drt.DtCreation) AS DtAchieved") + sb.append( + " SELECT pt.PlayerId, pt.GameId, drt.RoundNumber, SUM(${buildPointsRiskedSql()}) AS PointsRisked, MAX(drt.DtCreation) AS DtAchieved" + ) sb.append(" FROM Dart drt, Participant pt, Game g") sb.append(" WHERE drt.ParticipantId = pt.RowId") sb.append(" AND drt.PlayerId = pt.PlayerId") @@ -66,7 +74,8 @@ class AchievementGolfPointsRisked : AbstractMultiRowAchievement() sb.append(" GROUP BY pt.PlayerId, pt.GameId, drt.RoundNumber") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, + bulkInsertFromResultSet( + rs, database, achievementType, achievementCounterFn = { rs.getInt("PointsRisked") }, @@ -74,4 +83,4 @@ class AchievementGolfPointsRisked : AbstractMultiRowAchievement() ) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfTeamGamesWon.kt b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfTeamGamesWon.kt index be3afd935..851cb4de3 100644 --- a/src/main/kotlin/dartzee/achievements/golf/AchievementGolfTeamGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/golf/AchievementGolfTeamGamesWon.kt @@ -5,12 +5,11 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementGolfTeamGamesWon : AbstractAchievementTeamGamesWon() -{ +class AchievementGolfTeamGamesWon : AbstractAchievementTeamGamesWon() { override val name = "Golf Winners" override val desc = "Total number of team wins in Golf" override val achievementType = AchievementType.GOLF_TEAM_GAMES_WON override val gameType = GameType.GOLF override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_GOLF_WINNERS -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestGame.kt b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestGame.kt index 38c56ee6c..702356ebe 100644 --- a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestGame.kt +++ b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestGame.kt @@ -7,8 +7,7 @@ import dartzee.game.GameType import dartzee.game.RoundTheClockConfig import dartzee.utils.ResourceCache -class AchievementClockBestGame : AbstractAchievementBestGame() -{ +class AchievementClockBestGame : AbstractAchievementBestGame() { override val achievementType = AchievementType.CLOCK_BEST_GAME override val name = "Stop the Clock!" override val desc = "Best game of Round the Clock (Standard)" @@ -24,4 +23,4 @@ class AchievementClockBestGame : AbstractAchievementBestGame() override val maxValue = 20 override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_CLOCK_BEST_GAME -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestStreak.kt b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestStreak.kt index 85511f306..4849b6c8d 100644 --- a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestStreak.kt +++ b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBestStreak.kt @@ -11,8 +11,7 @@ import dartzee.utils.Database import dartzee.utils.ResourceCache.URL_ACHIEVEMENT_CLOCK_BEST_STREAK import dartzee.utils.getLongestStreak -class AchievementClockBestStreak: AbstractAchievement() -{ +class AchievementClockBestStreak : AbstractAchievement() { override val achievementType = AchievementType.CLOCK_BEST_STREAK override val name = "Like Clockwork" override val desc = "Longest streak of hits in Round the Clock" @@ -29,10 +28,11 @@ class AchievementClockBestStreak: AbstractAchievement() override fun getIconURL() = URL_ACHIEVEMENT_CLOCK_BEST_STREAK - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() - sb.append(" SELECT pt.PlayerId, g.RowId AS GameId, pt.RowId AS ParticipantId, drt.Ordinal, drt.Score, drt.Multiplier, drt.StartingScore, drt.DtLastUpdate") + sb.append( + " SELECT pt.PlayerId, g.RowId AS GameId, pt.RowId AS ParticipantId, drt.Ordinal, drt.Score, drt.Multiplier, drt.StartingScore, drt.DtLastUpdate" + ) sb.append(" FROM Game g, Participant pt, Dart drt") sb.append(" WHERE g.GameType = '${GameType.ROUND_THE_CLOCK}'") sb.append(" AND pt.GameId = g.RowId") @@ -44,8 +44,7 @@ class AchievementClockBestStreak: AbstractAchievement() val hmPlayerIdToDarts = HashMapList() database.executeQuery(sb).use { rs -> - while (rs.next()) - { + while (rs.next()) { val playerId = rs.getString("PlayerId") val gameId = rs.getString("GameId") val participantId = rs.getString("ParticipantId") @@ -66,11 +65,19 @@ class AchievementClockBestStreak: AbstractAchievement() } } - hmPlayerIdToDarts.forEach{ playerId, darts -> + hmPlayerIdToDarts.forEach { playerId, darts -> val streak = getLongestStreak(darts) val lastDart = streak.last() - AchievementEntity.factoryAndSave(achievementType, playerId, lastDart.gameId, streak.size, "", lastDart.dtThrown, database) + AchievementEntity.factoryAndSave( + achievementType, + playerId, + lastDart.gameId, + streak.size, + "", + lastDart.dtThrown, + database + ) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBruceyBonuses.kt b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBruceyBonuses.kt index f4a8219dd..864caef12 100644 --- a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBruceyBonuses.kt +++ b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockBruceyBonuses.kt @@ -10,8 +10,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementClockBruceyBonuses : AbstractMultiRowAchievement() -{ +class AchievementClockBruceyBonuses : AbstractMultiRowAchievement() { override val name = "Didn't he do well!?" override val desc = "Total number of 'Brucey Bonuses' executed in Round the Clock" override val achievementType = AchievementType.CLOCK_BRUCEY_BONUSES @@ -29,10 +28,11 @@ class AchievementClockBruceyBonuses : AbstractMultiRowAchievement() override fun isUnbounded() = true override fun getBreakdownColumns() = listOf("Game", "Round", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) - override fun populateForConversion(playerIds: List, database: Database) - { + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.achievementDetail.toInt(), a.dtAchieved) + + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() sb.append(" SELECT pt.PlayerId, pt.GameId, drt.RoundNumber, drt.DtCreation AS DtAchieved") sb.append(" FROM Dart drt, Participant pt, Game g") @@ -50,9 +50,14 @@ class AchievementClockBruceyBonuses : AbstractMultiRowAchievement() appendPlayerSql(sb, playerIds) database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementDetailFn = { rs.getInt("RoundNumber").toString() }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementDetailFn = { rs.getInt("RoundNumber").toString() } + ) } } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_CLOCK_BRUCEY_BONUSES -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockGamesWon.kt b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockGamesWon.kt index 725e7c9ae..2f4947c89 100644 --- a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockGamesWon.kt @@ -1,16 +1,15 @@ package dartzee.achievements.rtc -import dartzee.achievements.AchievementType import dartzee.achievements.AbstractAchievementGamesWon +import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementClockGamesWon : AbstractAchievementGamesWon() -{ +class AchievementClockGamesWon : AbstractAchievementGamesWon() { override val achievementType = AchievementType.CLOCK_GAMES_WON override val gameType = GameType.ROUND_THE_CLOCK override val name = "Clock Winner" override val desc = "Total number of wins in Round the Clock" override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_CLOCK_GAMES_WON -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockTeamGamesWon.kt b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockTeamGamesWon.kt index 00203ef33..77dc1efaa 100644 --- a/src/main/kotlin/dartzee/achievements/rtc/AchievementClockTeamGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/rtc/AchievementClockTeamGamesWon.kt @@ -5,12 +5,11 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementClockTeamGamesWon : AbstractAchievementTeamGamesWon() -{ +class AchievementClockTeamGamesWon : AbstractAchievementTeamGamesWon() { override val name = "Clock Winners" override val desc = "Total number of team wins in Round the Clock" override val achievementType = AchievementType.CLOCK_TEAM_GAMES_WON override val gameType = GameType.ROUND_THE_CLOCK override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_CLOCK_WINNERS -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AbstractAchievementX01ScoreVariants.kt b/src/main/kotlin/dartzee/achievements/x01/AbstractAchievementX01ScoreVariants.kt index cdd263fe2..e70bbc833 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AbstractAchievementX01ScoreVariants.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AbstractAchievementX01ScoreVariants.kt @@ -8,20 +8,24 @@ import dartzee.db.AchievementEntity import dartzee.game.GameType import dartzee.utils.Database -abstract class AbstractAchievementX01ScoreVariants : AbstractMultiRowAchievement() -{ +abstract class AbstractAchievementX01ScoreVariants : AbstractMultiRowAchievement() { abstract val targetScore: Int override val gameType = GameType.X01 override val allowedForTeams = true override fun getBreakdownColumns() = listOf("Method", "Game", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.achievementDetail, a.localGameIdEarned, a.dtAchieved) - override fun populateForConversion(playerIds: List, database: Database) - { + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.achievementDetail, a.localGameIdEarned, a.dtAchieved) + + override fun populateForConversion(playerIds: List, database: Database) { ensureX01RoundsTableExists(playerIds, database) - val roundWithTargetScore = database.createTempTable("RoundsScored$targetScore", "PlayerId VARCHAR(36), ParticipantId VARCHAR(36), GameId VARCHAR(36), RoundNumber INT") + val roundWithTargetScore = + database.createTempTable( + "RoundsScored$targetScore", + "PlayerId VARCHAR(36), ParticipantId VARCHAR(36), GameId VARCHAR(36), RoundNumber INT" + ) var sb = StringBuilder() sb.append(" INSERT INTO $roundWithTargetScore") @@ -33,13 +37,21 @@ abstract class AbstractAchievementX01ScoreVariants : AbstractMultiRowAchievement if (!database.executeUpdate(sb)) return - val tempTable = database.createTempTable("RoundsScored${targetScore}NoMisses", "PlayerId VARCHAR(36), ParticipantId VARCHAR(36), GameId VARCHAR(36), Ordinal INT, Score INT, Multiplier INT, RoundNumber INT, DtCreation TIMESTAMP") + val tempTable = + database.createTempTable( + "RoundsScored${targetScore}NoMisses", + "PlayerId VARCHAR(36), ParticipantId VARCHAR(36), GameId VARCHAR(36), Ordinal INT, Score INT, Multiplier INT, RoundNumber INT, DtCreation TIMESTAMP" + ) tempTable ?: return sb = StringBuilder() sb.append(" INSERT INTO $tempTable") - sb.append(" SELECT zz.PlayerId, zz.ParticipantId, zz.GameId, d.Ordinal, d.Score, d.Multiplier, d.RoundNumber, d.DtCreation") - sb.append(" FROM Dart d, Dart drtFirst, Dart drtSecond, Dart drtLast, $roundWithTargetScore zz") + sb.append( + " SELECT zz.PlayerId, zz.ParticipantId, zz.GameId, d.Ordinal, d.Score, d.Multiplier, d.RoundNumber, d.DtCreation" + ) + sb.append( + " FROM Dart d, Dart drtFirst, Dart drtSecond, Dart drtLast, $roundWithTargetScore zz" + ) sb.append(" WHERE drtFirst.ParticipantId = zz.ParticipantId") sb.append(" AND drtFirst.PlayerId = zz.PlayerId") sb.append(" AND drtFirst.RoundNumber = zz.RoundNumber") @@ -61,12 +73,20 @@ abstract class AbstractAchievementX01ScoreVariants : AbstractMultiRowAchievement if (!database.executeUpdate(sb)) return - database.executeUpdate("CREATE INDEX ${tempTable}_PlayerId_ParticipantId_RoundNumber ON $tempTable(PlayerId, ParticipantId, RoundNumber)") - val tempTableTwo = database.createTempTable("RoundsScored${targetScore}Flat", "PlayerId VARCHAR(36), GameId VARCHAR(36), DtAchieved TIMESTAMP, Method VARCHAR(100)") + database.executeUpdate( + "CREATE INDEX ${tempTable}_PlayerId_ParticipantId_RoundNumber ON $tempTable(PlayerId, ParticipantId, RoundNumber)" + ) + val tempTableTwo = + database.createTempTable( + "RoundsScored${targetScore}Flat", + "PlayerId VARCHAR(36), GameId VARCHAR(36), DtAchieved TIMESTAMP, Method VARCHAR(100)" + ) sb = StringBuilder() sb.append(" INSERT INTO $tempTableTwo") - sb.append(" SELECT highestDart.PlayerId, highestDart.GameId, highestDart.DtCreation, ${getThreeDartMethodSqlStr()} AS Method") + sb.append( + " SELECT highestDart.PlayerId, highestDart.GameId, highestDart.DtCreation, ${getThreeDartMethodSqlStr()} AS Method" + ) sb.append(" FROM $tempTable highestDart, $tempTable mediumDart, $tempTable lowestDart") sb.append(" WHERE highestDart.ParticipantId = mediumDart.ParticipantId") sb.append(" AND highestDart.PlayerId = mediumDart.PlayerId") @@ -76,7 +96,9 @@ abstract class AbstractAchievementX01ScoreVariants : AbstractMultiRowAchievement sb.append(" AND mediumDart.RoundNumber = lowestDart.RoundNumber") sb.append(" AND (${getDartHigherThanSql("highestDart", "mediumDart")})") sb.append(" AND (${getDartHigherThanSql("mediumDart", "lowestDart")})") - sb.append(" GROUP BY highestDart.PlayerId, highestDart.GameId, highestDart.DtCreation, ${getThreeDartMethodSqlStr()}") + sb.append( + " GROUP BY highestDart.PlayerId, highestDart.GameId, highestDart.DtCreation, ${getThreeDartMethodSqlStr()}" + ) if (!database.executeUpdate(sb)) return @@ -93,17 +115,27 @@ abstract class AbstractAchievementX01ScoreVariants : AbstractMultiRowAchievement sb.append(" )") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementDetailFn = { rs.getString("Method") } ) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementDetailFn = { rs.getString("Method") } + ) } } - private fun getDartHigherThanSql(hAlias: String, lAlias: String): String - { + private fun getDartHigherThanSql(hAlias: String, lAlias: String): String { val sb = StringBuilder() - sb.append("($hAlias.Score * $hAlias.Multiplier) > ($lAlias.Score * $lAlias.Multiplier)") //Higher score outright - sb.append(" OR (($hAlias.Score * $hAlias.Multiplier) = ($lAlias.Score * $lAlias.Multiplier) AND $hAlias.Multiplier > $lAlias.Multiplier)") - sb.append(" OR ($hAlias.Score = $lAlias.Score AND $hAlias.Multiplier = $lAlias.Multiplier AND $hAlias.Ordinal > $lAlias.Ordinal)") + sb.append( + "($hAlias.Score * $hAlias.Multiplier) > ($lAlias.Score * $lAlias.Multiplier)" + ) // Higher score outright + sb.append( + " OR (($hAlias.Score * $hAlias.Multiplier) = ($lAlias.Score * $lAlias.Multiplier) AND $hAlias.Multiplier > $lAlias.Multiplier)" + ) + sb.append( + " OR ($hAlias.Score = $lAlias.Score AND $hAlias.Multiplier = $lAlias.Multiplier AND $hAlias.Ordinal > $lAlias.Ordinal)" + ) return sb.toString() } @@ -119,4 +151,4 @@ abstract class AbstractAchievementX01ScoreVariants : AbstractMultiRowAchievement private fun getDartScoreStrSql(alias: String) = "RTRIM(CAST(CASE WHEN $alias.Multiplier = 0 THEN 0 ELSE $alias.Score END AS CHAR(5)))" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestFinish.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestFinish.kt index e364e1466..76ed083aa 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestFinish.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestFinish.kt @@ -8,8 +8,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementX01BestFinish : AbstractAchievement() -{ +class AchievementX01BestFinish : AbstractAchievement() { override val name = "Finisher" override val desc = "Highest checkout in X01" override val achievementType = AchievementType.X01_BEST_FINISH @@ -26,8 +25,7 @@ class AchievementX01BestFinish : AbstractAchievement() override val usesTransactionalTablesForConversion = false - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() sb.append(" SELECT GameId, PlayerId, Finish, DtCreation AS DtAchieved") sb.append(" FROM X01Finish") @@ -35,9 +33,15 @@ class AchievementX01BestFinish : AbstractAchievement() sb.append(" ORDER BY Finish DESC, DtCreation") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, oneRowPerPlayer = true, achievementCounterFn = { rs.getInt("Finish") }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + oneRowPerPlayer = true, + achievementCounterFn = { rs.getInt("Finish") } + ) } } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_BEST_FINISH -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestGame.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestGame.kt index 1fadd2aa5..93e8efd8f 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestGame.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestGame.kt @@ -5,8 +5,7 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementX01BestGame : AbstractAchievementBestGame() -{ +class AchievementX01BestGame : AbstractAchievementBestGame() { override val achievementType = AchievementType.X01_BEST_GAME override val name = "Leg-up" override val desc = "Best game of 501" @@ -22,4 +21,4 @@ class AchievementX01BestGame : AbstractAchievementBestGame() override val maxValue = 9 override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_X01_BEST_GAME -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestThreeDarts.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestThreeDarts.kt index 3b04ff76d..28dbbd9a8 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestThreeDarts.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01BestThreeDarts.kt @@ -7,8 +7,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementX01BestThreeDarts : AbstractAchievement() -{ +class AchievementX01BestThreeDarts : AbstractAchievement() { override val name = "Three Darter" override val desc = "Best three dart score in X01" override val achievementType = AchievementType.X01_BEST_THREE_DART_SCORE @@ -23,11 +22,17 @@ class AchievementX01BestThreeDarts : AbstractAchievement() override val maxValue = 180 override val allowedForTeams = true - override fun populateForConversion(playerIds: List, database: Database) - { - val dartSql = "TotalDartsThrown = 3 AND (RemainingScore > 0 OR (RemainingScore = 0 AND LastDartMultiplier = 2))" - unlockThreeDartAchievement(playerIds, dartSql, "StartingScore - RemainingScore", achievementType, database) + override fun populateForConversion(playerIds: List, database: Database) { + val dartSql = + "TotalDartsThrown = 3 AND (RemainingScore > 0 OR (RemainingScore = 0 AND LastDartMultiplier = 2))" + unlockThreeDartAchievement( + playerIds, + dartSql, + "StartingScore - RemainingScore", + achievementType, + database + ) } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_BEST_SCORE -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01Btbf.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01Btbf.kt index 7902754ef..66da2345e 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01Btbf.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01Btbf.kt @@ -10,8 +10,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache.URL_ACHIEVEMENT_X01_BTBF -class AchievementX01Btbf: AbstractMultiRowAchievement() -{ +class AchievementX01Btbf : AbstractMultiRowAchievement() { override val achievementType = AchievementType.X01_BTBF override val name = "BTBF" override val desc = "Number of games of X01 finished on D1" @@ -29,10 +28,11 @@ class AchievementX01Btbf: AbstractMultiRowAchievement() override fun getIconURL() = URL_ACHIEVEMENT_X01_BTBF override fun getBreakdownColumns() = listOf("Game", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.dtAchieved) - override fun populateForConversion(playerIds: List, database: Database) - { + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.dtAchieved) + + override fun populateForConversion(playerIds: List, database: Database) { ensureX01RoundsTableExists(playerIds, database) val sb = StringBuilder() @@ -44,4 +44,4 @@ class AchievementX01Btbf: AbstractMultiRowAchievement() database.executeQuery(sb).use { bulkInsertFromResultSet(it, database, achievementType) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01CheckoutCompleteness.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01CheckoutCompleteness.kt index ce81bc42a..be81bb578 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01CheckoutCompleteness.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01CheckoutCompleteness.kt @@ -15,8 +15,7 @@ import dartzee.utils.ResourceCache import java.awt.Color import java.awt.image.BufferedImage -class AchievementX01CheckoutCompleteness : AbstractMultiRowAchievement() -{ +class AchievementX01CheckoutCompleteness : AbstractMultiRowAchievement() { override val name = "Completionist" override val desc = "Total unique doubles checked out on in X01" override val achievementType = AchievementType.X01_CHECKOUT_COMPLETENESS @@ -36,15 +35,20 @@ class AchievementX01CheckoutCompleteness : AbstractMultiRowAchievement() override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_CHECKOUT_COMPLETENESS override fun getBreakdownColumns() = listOf("Double", "Game", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.achievementCounter, a.localGameIdEarned, a.dtAchieved) + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.achievementCounter, a.localGameIdEarned, a.dtAchieved) + override fun isUnbounded() = false - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { ensureX01RoundsTableExists(playerIds, database) - val tempTable = database.createTempTable("PlayerCheckouts", "PlayerId VARCHAR(36), Score INT, GameId VARCHAR(36), DtAchieved TIMESTAMP") - ?: return + val tempTable = + database.createTempTable( + "PlayerCheckouts", + "PlayerId VARCHAR(36), Score INT, GameId VARCHAR(36), DtAchieved TIMESTAMP" + ) ?: return var sb = StringBuilder() @@ -54,8 +58,7 @@ class AchievementX01CheckoutCompleteness : AbstractMultiRowAchievement() sb.append(" WHERE LastDartMultiplier = 2") sb.append(" AND RemainingScore = 0") - if (!database.executeUpdate("" + sb)) - return + if (!database.executeUpdate("" + sb)) return sb = StringBuilder() sb.append(" SELECT PlayerId, Score, GameId, DtAchieved") @@ -69,34 +72,34 @@ class AchievementX01CheckoutCompleteness : AbstractMultiRowAchievement() sb.append(")") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementCounterFn = { rs.getInt("Score") }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementCounterFn = { rs.getInt("Score") } + ) } } - override fun initialiseFromDb(achievementRows: List, player: PlayerEntity?) - { + override fun initialiseFromDb(achievementRows: List, player: PlayerEntity?) { super.initialiseFromDb(achievementRows, player) hitDoubles = achievementRows.map { it.achievementCounter }.toMutableList() } - override fun changeIconColor(img : BufferedImage, newColor: Color) - { - if (isLocked()) - { + override fun changeIconColor(img: BufferedImage, newColor: Color) { + if (isLocked()) { super.changeIconColor(img, newColor) return } img.paint { val current = Color(img.getRGB(it.x, it.y), true) - when - { + when { current == Color.BLACK -> newColor.darker() hitDoubles.contains(current.red) -> newColor else -> DartsColour.TRANSPARENT } } } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01Chucklevision.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01Chucklevision.kt index 75c39a2ee..71e2cbae5 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01Chucklevision.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01Chucklevision.kt @@ -3,8 +3,7 @@ package dartzee.achievements.x01 import dartzee.achievements.AchievementType import dartzee.utils.ResourceCache -class AchievementX01Chucklevision : AbstractAchievementX01ScoreVariants() -{ +class AchievementX01Chucklevision : AbstractAchievementX01ScoreVariants() { override val targetScore = 69 override val name = "Chucklevision" override val desc = "Number of distinct ways the player has scored 69 (\"Chucklevision\")" @@ -19,4 +18,4 @@ class AchievementX01Chucklevision : AbstractAchievementX01ScoreVariants() override val maxValue = 69 override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_X01_CHUCKLEVISION -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01GamesWon.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01GamesWon.kt index ee6ec0c1b..33253115b 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01GamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01GamesWon.kt @@ -5,12 +5,11 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementX01GamesWon : AbstractAchievementGamesWon() -{ +class AchievementX01GamesWon : AbstractAchievementGamesWon() { override val achievementType = AchievementType.X01_GAMES_WON override val gameType = GameType.X01 override val name = "X01 Winner" override val desc = "Total number of games won in X01" override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_X01_GAMES_WON -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01HighestBust.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01HighestBust.kt index 64e5cde4d..f82dcac9e 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01HighestBust.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01HighestBust.kt @@ -7,8 +7,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementX01HighestBust : AbstractAchievement() -{ +class AchievementX01HighestBust : AbstractAchievement() { override val name = "Bognor" override val desc = "Highest number busted from in X01" override val achievementType = AchievementType.X01_HIGHEST_BUST @@ -23,12 +22,12 @@ class AchievementX01HighestBust : AbstractAchievement() override val pinkThreshold = 100 override val maxValue = 181 - override fun populateForConversion(playerIds: List, database: Database) - { - val whereSql = "RemainingScore < 0 OR RemainingSCore = 1 OR (RemainingScore = 0 AND LastDartMultiplier <> 2)" + override fun populateForConversion(playerIds: List, database: Database) { + val whereSql = + "RemainingScore < 0 OR RemainingSCore = 1 OR (RemainingScore = 0 AND LastDartMultiplier <> 2)" unlockThreeDartAchievement(playerIds, whereSql, "StartingScore", achievementType, database) } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_HIGHEST_BUST -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01HotelInspector.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01HotelInspector.kt index d4b9ffd39..2ab7c2b74 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01HotelInspector.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01HotelInspector.kt @@ -3,8 +3,7 @@ package dartzee.achievements.x01 import dartzee.achievements.AchievementType import dartzee.utils.ResourceCache.URL_ACHIEVEMENT_X01_HOTEL_INSPECTOR -class AchievementX01HotelInspector : AbstractAchievementX01ScoreVariants() -{ +class AchievementX01HotelInspector : AbstractAchievementX01ScoreVariants() { override val targetScore = 26 override val name = "Hotel Inspector" override val desc = "Number of distinct ways the player has scored 26 (\"Bed and Breakfast\")" diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01NoMercy.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01NoMercy.kt index d4ea6a0e0..6141f840d 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01NoMercy.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01NoMercy.kt @@ -11,8 +11,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache -class AchievementX01NoMercy: AbstractMultiRowAchievement() -{ +class AchievementX01NoMercy : AbstractMultiRowAchievement() { override val name = "No Mercy" override val desc = "Finishes from 3, 5, 7 or 9 in X01" override val achievementType = AchievementType.X01_NO_MERCY @@ -27,8 +26,7 @@ class AchievementX01NoMercy: AbstractMultiRowAchievement() override val pinkThreshold = 10 override val maxValue = 10 - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { val sb = StringBuilder() sb.append(" SELECT drt.StartingScore, pt.PlayerId, pt.GameId, drt.DtCreation AS DtAchieved") sb.append(" FROM Game g, Dart drt, Participant pt") @@ -36,7 +34,9 @@ class AchievementX01NoMercy: AbstractMultiRowAchievement() sb.append(" WHERE pt.GameId = g.RowId") sb.append(" AND g.GameType = '${GameType.X01}'") sb.append(" AND (pt.FinalScore > -1 OR t.FinalScore > -1)") - sb.append(" AND ($LAST_ROUND_FROM_PARTICIPANT = drt.RoundNumber OR $LAST_ROUND_FROM_TEAM = drt.RoundNumber)") + sb.append( + " AND ($LAST_ROUND_FROM_PARTICIPANT = drt.RoundNumber OR $LAST_ROUND_FROM_TEAM = drt.RoundNumber)" + ) sb.append(" AND pt.RowId = drt.ParticipantId") sb.append(" AND drt.PlayerId = pt.PlayerId") sb.append(" AND drt.Ordinal = 1") @@ -44,12 +44,19 @@ class AchievementX01NoMercy: AbstractMultiRowAchievement() appendPlayerSql(sb, playerIds) database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementDetailFn = { rs.getInt("StartingScore").toString() }) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementDetailFn = { rs.getInt("StartingScore").toString() } + ) } } override fun getBreakdownColumns() = listOf("Checkout", "Game", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.achievementDetail, a.localGameIdEarned, a.dtAchieved) + + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.achievementDetail, a.localGameIdEarned, a.dtAchieved) override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_X01_NO_MERCY -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01Shanghai.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01Shanghai.kt index bd87f254b..32c8fcec7 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01Shanghai.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01Shanghai.kt @@ -10,8 +10,7 @@ import dartzee.game.GameType import dartzee.utils.Database import dartzee.utils.ResourceCache.URL_ACHIEVEMENT_X01_SHANGHAI -class AchievementX01Shanghai : AbstractMultiRowAchievement() -{ +class AchievementX01Shanghai : AbstractMultiRowAchievement() { override val name = "Shanghai" override val desc = "Total number of times player has scored T20, D20, 20 (in any order)" override val achievementType = AchievementType.X01_SHANGHAI @@ -29,14 +28,18 @@ class AchievementX01Shanghai : AbstractMultiRowAchievement() override fun getIconURL() = URL_ACHIEVEMENT_X01_SHANGHAI override fun getBreakdownColumns() = listOf("Game", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.localGameIdEarned, a.dtAchieved) + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.localGameIdEarned, a.dtAchieved) - override fun populateForConversion(playerIds: List, database: Database) - { + override fun populateForConversion(playerIds: List, database: Database) { ensureX01RoundsTableExists(playerIds, database) - val tempTable = database.createTempTable("Shanghai", "RoundNumber INT, ParticipantId VARCHAR(36), PlayerId VARCHAR(36), GameId VARCHAR(36)") + val tempTable = + database.createTempTable( + "Shanghai", + "RoundNumber INT, ParticipantId VARCHAR(36), PlayerId VARCHAR(36), GameId VARCHAR(36)" + ) var sb = StringBuilder() sb.append(" INSERT INTO $tempTable") @@ -47,7 +50,8 @@ class AchievementX01Shanghai : AbstractMultiRowAchievement() if (!database.executeUpdate("" + sb)) return - //Cut down to where there is precisely 1 double, 1 treble and 1 single. Get the date achieved too. + // Cut down to where there is precisely 1 double, 1 treble and 1 single. Get the date + // achieved too. sb = StringBuilder() sb.append(" SELECT zz.PlayerId, zz.GameId, drtDouble.DtCreation AS DtAchieved") sb.append(" FROM $tempTable zz, Dart drtDouble, Dart drtTreble, Dart drtSingle") @@ -69,4 +73,4 @@ class AchievementX01Shanghai : AbstractMultiRowAchievement() database.executeQuery(sb).use { bulkInsertFromResultSet(it, database, achievementType) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01StylishFinish.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01StylishFinish.kt index d93374fac..d0f2c7b7c 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01StylishFinish.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01StylishFinish.kt @@ -12,8 +12,7 @@ import dartzee.utils.Database import dartzee.utils.ResourceCache import java.sql.ResultSet -class AchievementX01StylishFinish : AbstractMultiRowAchievement() -{ +class AchievementX01StylishFinish : AbstractMultiRowAchievement() { override val name = "Stylish Finish" override val desc = "Finishes that involved hitting another double or treble" override val achievementType = AchievementType.X01_STYLISH_FINISH @@ -28,13 +27,19 @@ class AchievementX01StylishFinish : AbstractMultiRowAchievement() override val allowedForTeams = true override fun getBreakdownColumns() = listOf("Finish", "Method", "Game", "Date Achieved") - override fun getBreakdownRow(a: AchievementEntity) = arrayOf(a.achievementCounter, a.achievementDetail, a.localGameIdEarned, a.dtAchieved) - override fun populateForConversion(playerIds: List, database: Database) - { - val tmp1 = database.createTempTable("MultiDartFinishes", "PlayerId VARCHAR(36), GameId VARCHAR(36), ParticipantId VARCHAR(36), RoundNumber INT, DtAchieved TIMESTAMP") ?: return + override fun getBreakdownRow(a: AchievementEntity) = + arrayOf(a.achievementCounter, a.achievementDetail, a.localGameIdEarned, a.dtAchieved) - database.executeUpdate(""" + override fun populateForConversion(playerIds: List, database: Database) { + val tmp1 = + database.createTempTable( + "MultiDartFinishes", + "PlayerId VARCHAR(36), GameId VARCHAR(36), ParticipantId VARCHAR(36), RoundNumber INT, DtAchieved TIMESTAMP" + ) ?: return + + database.executeUpdate( + """ INSERT INTO $tmp1 SELECT pt.PlayerId, pt.GameId, pt.RowId, drt.RoundNumber, drt.DtCreation FROM ${EntityName.Dart} drt, ${EntityName.Participant} pt, ${EntityName.Game} g @@ -46,22 +51,33 @@ class AchievementX01StylishFinish : AbstractMultiRowAchievement() AND drt.Multiplier = 2 AND drt.StartingScore = (drt.Score * drt.Multiplier) ${getPlayerSql(playerIds)} - """.trimIndent()) + """ + .trimIndent() + ) - val drtTmp = database.createTempTable("RelevantDarts", "StartingScore INT, Score INT, Multiplier INT, ParticipantId VARCHAR(36), RoundNumber INT, Ordinal INT") ?: return + val drtTmp = + database.createTempTable( + "RelevantDarts", + "StartingScore INT, Score INT, Multiplier INT, ParticipantId VARCHAR(36), RoundNumber INT, Ordinal INT" + ) ?: return - database.executeUpdate(""" + database.executeUpdate( + """ INSERT INTO $drtTmp SELECT StartingScore, Score, Multiplier, drt.ParticipantId, drt.RoundNumber, drt.Ordinal FROM ${EntityName.Dart} drt, $tmp1 zz WHERE zz.ParticipantId = drt.ParticipantId AND zz.PlayerId = drt.PlayerId AND zz.RoundNumber = drt.RoundNumber - """.trimIndent()) + """ + .trimIndent() + ) database.executeUpdate("CREATE INDEX PtId_RoundNo ON $drtTmp (ParticipantId, RoundNumber)") - database.executeQuery(""" + database + .executeQuery( + """ SELECT zz.PlayerId, zz.GameId, zz.ParticipantId, drt.StartingScore, zz.DtAchieved, drt.Score AS DartOneScore, drt.Multiplier AS DartOneMultiplier, drt2.Score AS DartTwoScore, drt2.Multiplier AS DartTwoMultiplier, @@ -76,22 +92,25 @@ class AchievementX01StylishFinish : AbstractMultiRowAchievement() AND zz.RoundNumber = drt2.RoundNumber AND drt2.Ordinal = 2 AND (drt.Multiplier > 1 OR (drt2.Multiplier > 1 AND drt3.Multiplier IS NOT NULL)) - """.trimIndent()).use { rs -> - bulkInsertFromResultSet( - rs, - database, - achievementType, - achievementCounterFn = { rs.getInt("StartingScore") }, - achievementDetailFn = { extractMethodStr(rs) } + """ + .trimIndent() ) - } + .use { rs -> + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementCounterFn = { rs.getInt("StartingScore") }, + achievementDetailFn = { extractMethodStr(rs) } + ) + } } private fun extractMethodStr(rs: ResultSet) = - listOfNotNull(extractDart(rs, "One"), extractDart(rs, "Two"), extractDart(rs, "Three")).joinToString() + listOfNotNull(extractDart(rs, "One"), extractDart(rs, "Two"), extractDart(rs, "Three")) + .joinToString() - private fun extractDart(rs: ResultSet, numberDesc: String): Dart? - { + private fun extractDart(rs: ResultSet, numberDesc: String): Dart? { val score = rs.getInt("Dart${numberDesc}Score") if (rs.wasNull()) return null val multiplier = rs.getInt("Dart${numberDesc}Multiplier") @@ -100,4 +119,4 @@ class AchievementX01StylishFinish : AbstractMultiRowAchievement() } override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_X01_STYLISH_FINISH -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01SuchBadLuck.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01SuchBadLuck.kt index b939e057b..af34a5896 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01SuchBadLuck.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01SuchBadLuck.kt @@ -10,8 +10,7 @@ import dartzee.utils.ResourceCache.URL_ACHIEVEMENT_X01_SUCH_BAD_LUCK import dartzee.utils.getAdjacentNumbers import dartzee.utils.getCheckoutScores -class AchievementX01SuchBadLuck: AbstractAchievement() -{ +class AchievementX01SuchBadLuck : AbstractAchievement() { override val name = "Such Bad Luck" override val desc = "Most adjacent doubles hit when on a checkout in a game of X01" override val achievementType = AchievementType.X01_SUCH_BAD_LUCK @@ -26,16 +25,18 @@ class AchievementX01SuchBadLuck: AbstractAchievement() override val pinkThreshold = 10 override val maxValue = 10 - override fun populateForConversion(playerIds: List, database: Database) - { - val cols = "PlayerId VARCHAR(36), GameId VARCHAR(36), Score INT, Multiplier INT, StartingScore INT, DtLastUpdate TIMESTAMP" + override fun populateForConversion(playerIds: List, database: Database) { + val cols = + "PlayerId VARCHAR(36), GameId VARCHAR(36), Score INT, Multiplier INT, StartingScore INT, DtLastUpdate TIMESTAMP" val tempTable = database.createTempTable("CheckoutDarts", cols) ?: return val checkoutsStr = getCheckoutScores().joinToString() var sb = StringBuilder() sb.append(" INSERT INTO $tempTable") - sb.append(" SELECT pt.PlayerId, pt.GameId, d.Score, d.Multiplier, d.StartingScore, d.DtLastUpdate") + sb.append( + " SELECT pt.PlayerId, pt.GameId, d.Score, d.Multiplier, d.StartingScore, d.DtLastUpdate" + ) sb.append(" FROM Dart d, Participant pt, Game g") sb.append(" WHERE d.ParticipantId = pt.RowId") sb.append(" AND d.PlayerId = pt.PlayerId") @@ -47,12 +48,13 @@ class AchievementX01SuchBadLuck: AbstractAchievement() if (!database.executeUpdate(sb)) return sb = StringBuilder() - sb.append(" SELECT PlayerId, GameId, COUNT(1) AS GameTotal, MAX(DtLastUpdate) AS DtAchieved") + sb.append( + " SELECT PlayerId, GameId, COUNT(1) AS GameTotal, MAX(DtLastUpdate) AS DtAchieved" + ) sb.append(" FROM $tempTable") sb.append(" WHERE StartingScore = 50 AND Multiplier = 1 AND Score = 25") - for (i in 1..20) - { + for (i in 1..20) { val adjacents = getAdjacentNumbers(i).joinToString() sb.append(" OR StartingScore = ${2*i} AND Multiplier = 2 AND Score IN ($adjacents)") } @@ -61,10 +63,17 @@ class AchievementX01SuchBadLuck: AbstractAchievement() sb.append(" ORDER BY COUNT(1) DESC, DtAchieved") database.executeQuery(sb).use { rs -> - bulkInsertFromResultSet(rs, database, achievementType, achievementCounterFn = { rs.getInt("GameTotal") }, oneRowPerPlayer = true) + bulkInsertFromResultSet( + rs, + database, + achievementType, + achievementCounterFn = { rs.getInt("GameTotal") }, + oneRowPerPlayer = true + ) } } override fun getIconURL() = URL_ACHIEVEMENT_X01_SUCH_BAD_LUCK + override fun isUnbounded() = true -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/achievements/x01/AchievementX01TeamGamesWon.kt b/src/main/kotlin/dartzee/achievements/x01/AchievementX01TeamGamesWon.kt index 54589ec1f..ce8b7f7de 100644 --- a/src/main/kotlin/dartzee/achievements/x01/AchievementX01TeamGamesWon.kt +++ b/src/main/kotlin/dartzee/achievements/x01/AchievementX01TeamGamesWon.kt @@ -5,12 +5,11 @@ import dartzee.achievements.AchievementType import dartzee.game.GameType import dartzee.utils.ResourceCache -class AchievementX01TeamGamesWon : AbstractAchievementTeamGamesWon() -{ +class AchievementX01TeamGamesWon : AbstractAchievementTeamGamesWon() { override val name = "X01 Winners" override val desc = "Total number of team wins in X01" override val achievementType = AchievementType.X01_TEAM_GAMES_WON override val gameType = GameType.X01 override fun getIconURL() = ResourceCache.URL_ACHIEVEMENT_X01_WINNERS -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/ai/AbstractDartsSimulation.kt b/src/main/kotlin/dartzee/ai/AbstractDartsSimulation.kt index 86e17341c..5d2a8c315 100644 --- a/src/main/kotlin/dartzee/ai/AbstractDartsSimulation.kt +++ b/src/main/kotlin/dartzee/ai/AbstractDartsSimulation.kt @@ -10,10 +10,8 @@ import dartzee.`object`.DartsClient import dartzee.stats.GameWrapper import dartzee.utils.getDartForSegment -abstract class AbstractDartsSimulation(val player: PlayerEntity, - val model: DartsAiModel) -{ - //Transient things +abstract class AbstractDartsSimulation(val player: PlayerEntity, val model: DartsAiModel) { + // Transient things protected var currentRound = -1 protected val dartsThrown = mutableListOf() @@ -23,18 +21,19 @@ abstract class AbstractDartsSimulation(val player: PlayerEntity, abstract val gameType: GameType abstract fun shouldPlayCurrentRound(): Boolean + abstract fun startRound() + abstract fun getTotalScore(): Int + abstract fun dartThrown(dart: Dart) - fun simulateGame(gameId: Long): GameWrapper - { + fun simulateGame(gameId: Long): GameWrapper { resetVariables() val dtStart = getSqlDateNow() - while (shouldPlayCurrentRound()) - { + while (shouldPlayCurrentRound()) { startRound() } @@ -43,35 +42,40 @@ abstract class AbstractDartsSimulation(val player: PlayerEntity, val totalRounds = currentRound - 1 val totalScore = getTotalScore() - val wrapper = GameWrapper(gameId, gameParams, dtStart, dtFinish, totalScore, false, totalRounds, hmRoundNumberToDarts) - - if (DartsClient.devMode) - { + val wrapper = + GameWrapper( + gameId, + gameParams, + dtStart, + dtFinish, + totalScore, + false, + totalRounds, + hmRoundNumberToDarts + ) + + if (DartsClient.devMode) { wrapper.generateRealEntities(gameType, player) } return wrapper } - protected open fun resetVariables() - { + protected open fun resetVariables() { dartsThrown.clear() hmRoundNumberToDarts = HashMapList() currentRound = 1 } - protected fun resetRound() - { + protected fun resetRound() { dartsThrown.clear() } - protected fun confirmRound() - { + protected fun confirmRound() { hmRoundNumberToDarts[currentRound] = dartsThrown.toMutableList() } - protected fun dartThrown(aiPt: ComputedPoint) - { + protected fun dartThrown(aiPt: ComputedPoint) { dartThrown(getDartForSegment(aiPt.segment)) } } diff --git a/src/main/kotlin/dartzee/ai/AiDartboard.kt b/src/main/kotlin/dartzee/ai/AiDartboard.kt index a710bd557..872123bc4 100644 --- a/src/main/kotlin/dartzee/ai/AiDartboard.kt +++ b/src/main/kotlin/dartzee/ai/AiDartboard.kt @@ -3,9 +3,10 @@ package dartzee.ai import dartzee.`object`.ComputationalDartboard /** - * Arbitrary-seeming width and height values taken from the size the Dartboard used to be fixed at during gameplay + * Arbitrary-seeming width and height values taken from the size the Dartboard used to be fixed at + * during gameplay */ const val AI_DARTBOARD_WIDTH = 520 const val AI_DARTBOARD_HEIGHT = 555 -val AI_DARTBOARD = ComputationalDartboard(AI_DARTBOARD_WIDTH, AI_DARTBOARD_HEIGHT) \ No newline at end of file +val AI_DARTBOARD = ComputationalDartboard(AI_DARTBOARD_WIDTH, AI_DARTBOARD_HEIGHT) diff --git a/src/main/kotlin/dartzee/ai/AimDart.kt b/src/main/kotlin/dartzee/ai/AimDart.kt index 8e740e917..fa64ddd19 100644 --- a/src/main/kotlin/dartzee/ai/AimDart.kt +++ b/src/main/kotlin/dartzee/ai/AimDart.kt @@ -3,30 +3,25 @@ package dartzee.ai import com.fasterxml.jackson.annotation.JsonIgnoreProperties import dartzee.`object`.SegmentType - -interface IDart -{ +interface IDart { val score: Int val multiplier: Int fun getTotal() = score * multiplier + fun isDouble() = multiplier == 2 + fun isTreble() = multiplier == 3 - fun format(): String - { - if (multiplier == 0) - { + fun format(): String { + if (multiplier == 0) { return "0" } var ret = "" - if (isDouble()) - { + if (isDouble()) { ret += "D" - } - else if (isTreble()) - { + } else if (isTreble()) { ret += "T" } @@ -37,16 +32,19 @@ interface IDart } @JsonIgnoreProperties("segmentType", "total", "double", "treble") -data class AimDart(override val score: Int, override val multiplier: Int, val segment: SegmentType? = null): IDart -{ - fun getSegmentType() = segment ?: - when (multiplier) - { - 0 -> SegmentType.MISS - 1 -> SegmentType.OUTER_SINGLE - 2 -> SegmentType.DOUBLE - else -> SegmentType.TREBLE - } +data class AimDart( + override val score: Int, + override val multiplier: Int, + val segment: SegmentType? = null +) : IDart { + fun getSegmentType() = + segment + ?: when (multiplier) { + 0 -> SegmentType.MISS + 1 -> SegmentType.OUTER_SINGLE + 2 -> SegmentType.DOUBLE + else -> SegmentType.TREBLE + } override fun toString() = format() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/ai/DartsAiModel.kt b/src/main/kotlin/dartzee/ai/DartsAiModel.kt index 469687c88..7d689afe4 100644 --- a/src/main/kotlin/dartzee/ai/DartsAiModel.kt +++ b/src/main/kotlin/dartzee/ai/DartsAiModel.kt @@ -13,9 +13,9 @@ import dartzee.utils.InjectedThings.logger import dartzee.utils.generateRandomAngle import dartzee.utils.getAngleForPoint import dartzee.utils.translatePoint -import org.apache.commons.math3.distribution.NormalDistribution import java.awt.Point import kotlin.math.abs +import org.apache.commons.math3.distribution.NormalDistribution enum class DartzeePlayStyle { CAUTIOUS, @@ -24,36 +24,34 @@ enum class DartzeePlayStyle { val DELIBERATE_MISS = Point(Int.MAX_VALUE, Int.MAX_VALUE) -data class DartsAiModel(val standardDeviation: Double, - val standardDeviationDoubles: Double?, - val standardDeviationCentral: Double?, - val maxRadius: Int, - val scoringDart: Int, - val hmScoreToDart: Map, - val mercyThreshold: Int?, - val hmDartNoToSegmentType: Map, - val hmDartNoToStopThreshold: Map, - val dartzeePlayStyle: DartzeePlayStyle) -{ - //Modelling +data class DartsAiModel( + val standardDeviation: Double, + val standardDeviationDoubles: Double?, + val standardDeviationCentral: Double?, + val maxRadius: Int, + val scoringDart: Int, + val hmScoreToDart: Map, + val mercyThreshold: Int?, + val hmDartNoToSegmentType: Map, + val hmDartNoToStopThreshold: Map, + val dartzeePlayStyle: DartzeePlayStyle +) { + // Modelling private val mean = 0 private val distribution = NormalDistribution(mean.toDouble(), standardDeviation) - /** - * X01 - */ - fun throwX01Dart(score: Int): ComputedPoint - { - //Check for a specific dart to aim for. It's possible to override any value for a specific AI strategy. + /** X01 */ + fun throwX01Dart(score: Int): ComputedPoint { + // Check for a specific dart to aim for. It's possible to override any value for a specific + // AI strategy. val drtToAimAt = getOveriddenDartToAimAt(score) - if (drtToAimAt != null) - { + if (drtToAimAt != null) { val ptToAimAt = getPointForScore(drtToAimAt) return throwDartAtPoint(ptToAimAt) } - //No overridden strategy, do the default thing + // No overridden strategy, do the default thing return if (score > 60) { throwScoringDart() } else { @@ -63,48 +61,42 @@ data class DartsAiModel(val standardDeviation: Double, } } - fun throwScoringDart(): ComputedPoint - { + fun throwScoringDart(): ComputedPoint { val ptToAimAt = calculateScoringPoint() return throwDartAtPoint(ptToAimAt.pt) } - fun calculateScoringPoint(): ComputedPoint - { + fun calculateScoringPoint(): ComputedPoint { val segmentType = if (scoringDart == 25) SegmentType.DOUBLE else SegmentType.TREBLE return getComputedPointForScore(scoringDart, segmentType) } private fun getOveriddenDartToAimAt(score: Int) = hmScoreToDart[score] - /** - * Golf - */ - fun throwGolfDart(targetHole: Int, dartNo: Int): ComputedPoint - { + /** Golf */ + fun throwGolfDart(targetHole: Int, dartNo: Int): ComputedPoint { val segmentTypeToAimAt = getSegmentTypeForDartNo(dartNo) val ptToAimAt = getPointForScore(targetHole, segmentTypeToAimAt) return throwDartAtPoint(ptToAimAt) } - /** - * Clock - */ - fun throwClockDart(clockTarget: Int, clockType: ClockType): ComputedPoint - { + /** Clock */ + fun throwClockDart(clockTarget: Int, clockType: ClockType): ComputedPoint { val segmentType = getSegmentTypeForClockType(clockType) val ptToAimAt = getPointForScore(clockTarget, segmentType) return throwDartAtPoint(ptToAimAt) } - /** - * Dartzee - */ - fun throwDartzeeDart(dartsThrownSoFar: Int, segmentStatuses: SegmentStatuses): ComputedPoint - { + /** Dartzee */ + fun throwDartzeeDart(dartsThrownSoFar: Int, segmentStatuses: SegmentStatuses): ComputedPoint { val aggressive = (dartsThrownSoFar < 2 || dartzeePlayStyle == DartzeePlayStyle.AGGRESSIVE) - val ptToAimAt = InjectedThings.dartzeeAimCalculator.getPointToAimFor(AI_DARTBOARD, segmentStatuses, aggressive) + val ptToAimAt = + InjectedThings.dartzeeAimCalculator.getPointToAimFor( + AI_DARTBOARD, + segmentStatuses, + aggressive + ) return throwDartAtPoint(ptToAimAt) } @@ -114,16 +106,13 @@ data class DartsAiModel(val standardDeviation: Double, fun throwAtDouble(double: Int) = throwDartAtPoint(getPointForScore(double, SegmentType.DOUBLE)) - private fun throwDartAtPoint(aiDartboardPoint: Point): ComputedPoint - { - if (standardDeviation == 0.0) - { + private fun throwDartAtPoint(aiDartboardPoint: Point): ComputedPoint { + if (standardDeviation == 0.0) { logger.error(CODE_AI_ERROR, "Gaussian model with SD of 0 - this shouldn't be possible!") return AI_DARTBOARD.toComputedPoint(aiDartboardPoint) } - if (aiDartboardPoint == DELIBERATE_MISS) - { + if (aiDartboardPoint == DELIBERATE_MISS) { return AI_DARTBOARD.getDeliberateMissPoint() } @@ -133,33 +122,31 @@ data class DartsAiModel(val standardDeviation: Double, } data class DistributionSample(val radius: Double, val theta: Double) - fun calculateRadiusAndAngle(pt: Point): DistributionSample - { - //Averaging logic + + fun calculateRadiusAndAngle(pt: Point): DistributionSample { + // Averaging logic val radius = sampleRadius(pt) - //Generate the angle + // Generate the angle val theta = generateAngle(pt) val sanitisedAngle = sanitiseAngle(theta) return DistributionSample(radius, sanitisedAngle) } - private fun sampleRadius(pt: Point): Double - { + + private fun sampleRadius(pt: Point): Double { val distribution = getDistributionToUse(pt) var radius = distribution.sample() - while (abs(radius) > maxRadius) - { + while (abs(radius) > maxRadius) { radius = distribution.sample() } return radius } - private fun sanitiseAngle(angle: Double): Double - { - return when - { + + private fun sanitiseAngle(angle: Double): Double { + return when { angle < 0 -> angle + 360 angle > 360 -> angle - 360 else -> angle @@ -167,50 +154,49 @@ data class DartsAiModel(val standardDeviation: Double, } private fun getDistributionToUse(pt: Point) = - if (standardDeviationDoubles != null && AI_DARTBOARD.isDouble(pt)) NormalDistribution(mean.toDouble(), standardDeviationDoubles) else distribution + if (standardDeviationDoubles != null && AI_DARTBOARD.isDouble(pt)) + NormalDistribution(mean.toDouble(), standardDeviationDoubles) + else distribution - private fun generateAngle(pt: Point): Double - { - if (standardDeviationCentral == null || AI_DARTBOARD.isDouble(pt)) - { - //Just pluck a number from 0-360. + private fun generateAngle(pt: Point): Double { + if (standardDeviationCentral == null || AI_DARTBOARD.isDouble(pt)) { + // Just pluck a number from 0-360. return generateRandomAngle() } - //Otherwise, we have a Normal Distribution to use to generate an angle more likely to be into the dartboard (rather than out of it) + // Otherwise, we have a Normal Distribution to use to generate an angle more likely to be + // into the dartboard (rather than out of it) val angleToAvoid = getAngleForPoint(pt, AI_DARTBOARD.computeCenter()) val angleTowardsCenter = (angleToAvoid + 180) % 360 val angleDistribution = NormalDistribution(angleTowardsCenter, standardDeviationCentral) return angleDistribution.sample() } - fun getProbabilityWithinRadius(radius: Double): Double? - { + fun getProbabilityWithinRadius(radius: Double): Double? { if (radius > maxRadius) return null return distribution.probability(-radius, radius) } - fun computeProbabilityDensityDivisor(): Double - { + fun computeProbabilityDensityDivisor(): Double { val maxPossible = maxRadius.toDouble() return distribution.probability(-maxPossible, maxPossible) } fun toJson(): String = jsonMapper().writeValueAsString(this) - companion object - { - val DEFAULT_GOLF_SEGMENT_TYPES = mapOf(1 to SegmentType.DOUBLE, 2 to SegmentType.TREBLE, 3 to SegmentType.TREBLE) + companion object { + val DEFAULT_GOLF_SEGMENT_TYPES = + mapOf(1 to SegmentType.DOUBLE, 2 to SegmentType.TREBLE, 3 to SegmentType.TREBLE) val DEFAULT_GOLF_STOP_THRESHOLDS = mapOf(1 to 2, 2 to 3) fun fromJson(json: String) = jsonMapper().readValue(json) - fun new(): DartsAiModel - { + fun new(): DartsAiModel { val hmDartNoToSegmentType = DEFAULT_GOLF_SEGMENT_TYPES.toMutableMap() val hmDartNoToStopThreshold = DEFAULT_GOLF_STOP_THRESHOLDS.toMutableMap() - return DartsAiModel(50.0, + return DartsAiModel( + 50.0, null, null, 150, @@ -219,7 +205,8 @@ data class DartsAiModel(val standardDeviation: Double, null, hmDartNoToSegmentType, hmDartNoToStopThreshold, - DartzeePlayStyle.CAUTIOUS) + DartzeePlayStyle.CAUTIOUS + ) } } } diff --git a/src/main/kotlin/dartzee/ai/DartsAiSimulator.kt b/src/main/kotlin/dartzee/ai/DartsAiSimulator.kt index 0c3644ebb..cf3422924 100644 --- a/src/main/kotlin/dartzee/ai/DartsAiSimulator.kt +++ b/src/main/kotlin/dartzee/ai/DartsAiSimulator.kt @@ -11,19 +11,19 @@ import java.util.* private const val SCORING_DARTS_TO_THROW = 20000 private const val DOUBLE_DARTS_TO_THROW = 20000 -object DartsAiSimulator -{ - fun runSimulation(model: DartsAiModel, dartboard: PresentationDartboard): SimulationWrapper - { +object DartsAiSimulator { + fun runSimulation(model: DartsAiModel, dartboard: PresentationDartboard): SimulationWrapper { logger.info(CODE_SIMULATION_STARTED, "Simulating scoring and doubles throws") val scoringPoints = throwScoringDarts(model) - val hmPointToCount = scoringPoints.groupBy { dartboard.interpretPoint(it) }.mapValues { it.value.size } + val hmPointToCount = + scoringPoints.groupBy { dartboard.interpretPoint(it) }.mapValues { it.value.size } val scoringSegments = scoringPoints.map { it.segment } val totalScore = scoringSegments.sumOf { it.getTotal() } val misses = scoringSegments.count { it.getTotal() == 0 } - val trebles = scoringSegments.count { it.type == SegmentType.TREBLE && it.score == model.scoringDart } + val trebles = + scoringSegments.count { it.type == SegmentType.TREBLE && it.score == model.scoringDart } val avgScore = totalScore.toDouble() / SCORING_DARTS_TO_THROW val missPercent = MathsUtil.getPercentage(misses, SCORING_DARTS_TO_THROW) @@ -34,16 +34,19 @@ object DartsAiSimulator logger.info(CODE_SIMULATION_FINISHED, "Finished simulating throws") val doublePercent = MathsUtil.getPercentage(doubles, DOUBLE_DARTS_TO_THROW) - return SimulationWrapper(avgScore, missPercent, doublePercent, treblePercent, hmPointToCount) + return SimulationWrapper( + avgScore, + missPercent, + doublePercent, + treblePercent, + hmPointToCount + ) } private fun throwScoringDarts(model: DartsAiModel) = - (0 until SCORING_DARTS_TO_THROW).map { - model.throwScoringDart() - } + (0 until SCORING_DARTS_TO_THROW).map { model.throwScoringDart() } - private fun throwAtDoubles(model: DartsAiModel): Double - { + private fun throwAtDoubles(model: DartsAiModel): Double { val rand = Random() return (0 until DOUBLE_DARTS_TO_THROW).fold(0.0) { hits, _ -> @@ -57,4 +60,4 @@ object DartsAiSimulator } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/ai/DartsSimulationGolf.kt b/src/main/kotlin/dartzee/ai/DartsSimulationGolf.kt index 6f90db887..f3133ad93 100644 --- a/src/main/kotlin/dartzee/ai/DartsSimulationGolf.kt +++ b/src/main/kotlin/dartzee/ai/DartsSimulationGolf.kt @@ -6,24 +6,22 @@ import dartzee.`object`.Dart private const val ROUNDS = 18 -class DartsSimulationGolf(player: PlayerEntity, model: DartsAiModel) : AbstractDartsSimulation(player, model) -{ +class DartsSimulationGolf(player: PlayerEntity, model: DartsAiModel) : + AbstractDartsSimulation(player, model) { override val gameType = GameType.GOLF override val gameParams = "$ROUNDS" var score = 0 override fun shouldPlayCurrentRound() = currentRound <= ROUNDS - override fun resetVariables() - { + override fun resetVariables() { super.resetVariables() score = 0 } override fun getTotalScore() = score - override fun startRound() - { + override fun startRound() { resetRound() val dartNo = dartsThrown.size + 1 @@ -31,8 +29,7 @@ class DartsSimulationGolf(player: PlayerEntity, model: DartsAiModel) : AbstractD dartThrown(pt) } - private fun finishedRound() - { + private fun finishedRound() { confirmRound() val drt = dartsThrown.last() @@ -42,18 +39,17 @@ class DartsSimulationGolf(player: PlayerEntity, model: DartsAiModel) : AbstractD currentRound++ } - override fun dartThrown(dart: Dart) - { + override fun dartThrown(dart: Dart) { dartsThrown.add(dart) val noDarts = dartsThrown.size - if (noDarts == 3 || dart.getGolfScore(currentRound) <= model.getStopThresholdForDartNo(noDarts)) - { + if ( + noDarts == 3 || + dart.getGolfScore(currentRound) <= model.getStopThresholdForDartNo(noDarts) + ) { finishedRound() - } - else - { + } else { val dartNo = dartsThrown.size + 1 val pt = model.throwGolfDart(currentRound, dartNo) dartThrown(pt) diff --git a/src/main/kotlin/dartzee/ai/DartsSimulationX01.kt b/src/main/kotlin/dartzee/ai/DartsSimulationX01.kt index ada2e0d92..f8c3be236 100644 --- a/src/main/kotlin/dartzee/ai/DartsSimulationX01.kt +++ b/src/main/kotlin/dartzee/ai/DartsSimulationX01.kt @@ -8,36 +8,32 @@ import dartzee.utils.shouldStopForMercyRule private const val X01 = 501 -/** - * Simulate a single game of X01 for an AI - */ -class DartsSimulationX01(player: PlayerEntity, model: DartsAiModel) : AbstractDartsSimulation(player, model) -{ - //Transient things +/** Simulate a single game of X01 for an AI */ +class DartsSimulationX01(player: PlayerEntity, model: DartsAiModel) : + AbstractDartsSimulation(player, model) { + // Transient things private var startingScore = -1 private var currentScore = -1 override val gameParams = "$X01" override val gameType = GameType.X01 - override fun getTotalScore(): Int - { + override fun getTotalScore(): Int { val totalRounds = currentRound - 1 return (totalRounds - 1) * 3 + dartsThrown.size } override fun shouldPlayCurrentRound() = currentScore > 0 - override fun resetVariables() - { + override fun resetVariables() { super.resetVariables() startingScore = X01 currentScore = X01 } - override fun startRound() - { - //Starting a new round. Need to keep track of what we started on so we can reset if we bust. + override fun startRound() { + // Starting a new round. Need to keep track of what we started on so we can reset if we + // bust. startingScore = currentScore resetRound() @@ -45,35 +41,31 @@ class DartsSimulationX01(player: PlayerEntity, model: DartsAiModel) : AbstractDa dartThrown(pt) } - private fun finishedRound() - { + private fun finishedRound() { confirmRound() - //If we've bust, then reset the current score back - if (isBust(dartsThrown.last())) - { + // If we've bust, then reset the current score back + if (isBust(dartsThrown.last())) { currentScore = startingScore } currentRound++ } - override fun dartThrown(dart: Dart) - { + override fun dartThrown(dart: Dart) { dartsThrown.add(dart) dart.startingScore = currentScore val dartTotal = dart.getTotal() currentScore -= dartTotal - if (currentScore <= 1 - || dartsThrown.size == 3 - || shouldStopForMercyRule(model, startingScore, currentScore)) - { + if ( + currentScore <= 1 || + dartsThrown.size == 3 || + shouldStopForMercyRule(model, startingScore, currentScore) + ) { finishedRound() - } - else - { + } else { val pt = model.throwX01Dart(currentScore) dartThrown(pt) } diff --git a/src/main/kotlin/dartzee/ai/SimulationRunner.kt b/src/main/kotlin/dartzee/ai/SimulationRunner.kt index c5bc14753..5d93a06b9 100644 --- a/src/main/kotlin/dartzee/ai/SimulationRunner.kt +++ b/src/main/kotlin/dartzee/ai/SimulationRunner.kt @@ -23,68 +23,77 @@ import javax.swing.JFrame import javax.swing.JOptionPane import javax.swing.SwingUtilities -class SimulationRunner -{ - fun runSimulation(sim: AbstractDartsSimulation, numberOfGames: Int, modal: Boolean) - { +class SimulationRunner { + fun runSimulation(sim: AbstractDartsSimulation, numberOfGames: Int, modal: Boolean) { val simulationRunnable = Runnable { runSimulationThreadily(sim, numberOfGames, modal) } val t = Thread(simulationRunnable, "Simulation Thread") t.start() } - private fun runSimulationThreadily(sim: AbstractDartsSimulation, - numberOfGames: Int, - modal: Boolean) - { + private fun runSimulationThreadily( + sim: AbstractDartsSimulation, + numberOfGames: Int, + modal: Boolean + ) { val dialog = ProgressDialog.factory("Simulating games...", "games remaining", numberOfGames) dialog.showCancel(true) dialog.setVisibleLater() - InjectedThings.logger.info(CODE_SIMULATION_STARTED, "Starting simulation for $numberOfGames games") + InjectedThings.logger.info( + CODE_SIMULATION_STARTED, + "Starting simulation for $numberOfGames games" + ) val timer = DurationTimer() val hmGameIdToWrapper = mutableMapOf() - for (i in 1..numberOfGames) - { - try - { + for (i in 1..numberOfGames) { + try { val wrapper = sim.simulateGame((-i).toLong()) hmGameIdToWrapper[-i.toLong()] = wrapper dialog.incrementProgressLater() - InjectedThings.logger.logProgress(CODE_SIMULATION_PROGRESS, i.toLong(), numberOfGames.toLong()) + InjectedThings.logger.logProgress( + CODE_SIMULATION_PROGRESS, + i.toLong(), + numberOfGames.toLong() + ) - if (dialog.cancelPressed()) - { + if (dialog.cancelPressed()) { InjectedThings.logger.info(CODE_SIMULATION_CANCELLED, "Simulation Cancelled") hmGameIdToWrapper.clear() dialog.disposeLater() return } - } - catch (t: Throwable) - { + } catch (t: Throwable) { hmGameIdToWrapper.clear() - InjectedThings.logger.error(CODE_SIMULATION_ERROR, "Caught $t running simulation", t) + InjectedThings.logger.error( + CODE_SIMULATION_ERROR, + "Caught $t running simulation", + t + ) DialogUtil.showErrorLater("A serious problem has occurred with the simulation.") } } - InjectedThings.logger.info(CODE_SIMULATION_FINISHED, "Simulation completed in ${timer.getDuration()} millis") + InjectedThings.logger.info( + CODE_SIMULATION_FINISHED, + "Simulation completed in ${timer.getDuration()} millis" + ) dialog.disposeLater() - if (hmGameIdToWrapper.isNotEmpty()) - { - //The simulation finished successfully, so show it + if (hmGameIdToWrapper.isNotEmpty()) { + // The simulation finished successfully, so show it SwingUtilities.invokeLater { simulationFinished(hmGameIdToWrapper, sim, modal) } } } - private fun simulationFinished(hmGameIdToWrapper: Map, sim: AbstractDartsSimulation, modal: Boolean) - { - if (DartsClient.devMode) - { + private fun simulationFinished( + hmGameIdToWrapper: Map, + sim: AbstractDartsSimulation, + modal: Boolean + ) { + if (DartsClient.devMode) { val ans = DialogUtil.showQuestionOLD("Save real entities?") handleSavingEntities(ans == JOptionPane.YES_OPTION, hmGameIdToWrapper) } @@ -101,11 +110,9 @@ class SimulationRunner parentWindow.isVisible = true } - private fun handleSavingEntities(save: Boolean, hmGameIdToWrapper: Map) - { + private fun handleSavingEntities(save: Boolean, hmGameIdToWrapper: Map) { val wrappers = hmGameIdToWrapper.values - if (save) - { + if (save) { val games = mutableListOf() val participants = mutableListOf() val darts = mutableListOf() @@ -125,10 +132,8 @@ class SimulationRunner } } - private fun getParentWindowForResults(title: String, modal: Boolean): Window - { - if (modal) - { + private fun getParentWindowForResults(title: String, modal: Boolean): Window { + if (modal) { val dlg = JDialog() dlg.isModal = true dlg.title = title @@ -137,4 +142,4 @@ class SimulationRunner return JFrame(title) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/ai/SimulationWrapper.kt b/src/main/kotlin/dartzee/ai/SimulationWrapper.kt index 82417843a..bc3e21872 100644 --- a/src/main/kotlin/dartzee/ai/SimulationWrapper.kt +++ b/src/main/kotlin/dartzee/ai/SimulationWrapper.kt @@ -2,8 +2,10 @@ package dartzee.ai import java.awt.Point -data class SimulationWrapper(val averageDart: Double, - val missPercent: Double, - val finishPercent: Double, - val treblePercent: Double, - val hmPointToCount: Map) +data class SimulationWrapper( + val averageDart: Double, + val missPercent: Double, + val finishPercent: Double, + val treblePercent: Double, + val hmPointToCount: Map +) diff --git a/src/main/kotlin/dartzee/ai/StrategyUtils.kt b/src/main/kotlin/dartzee/ai/StrategyUtils.kt index 85c1b9238..5e408e1bd 100644 --- a/src/main/kotlin/dartzee/ai/StrategyUtils.kt +++ b/src/main/kotlin/dartzee/ai/StrategyUtils.kt @@ -6,10 +6,10 @@ import dartzee.`object`.SegmentType import java.awt.Point /** - * Given the single/double/treble required, calculate the physical coordinates of the optimal place to aim + * Given the single/double/treble required, calculate the physical coordinates of the optimal place + * to aim */ -fun getPointForScore(drt: AimDart): Point -{ +fun getPointForScore(drt: AimDart): Point { val score = drt.score val segmentType = drt.getSegmentType() return getPointForScore(score, segmentType) @@ -21,35 +21,28 @@ fun getPointForScore(score: Int, type: SegmentType): Point = fun getComputedPointForScore(score: Int, type: SegmentType): ComputedPoint = AI_DARTBOARD.getPointToAimAt(DartboardSegment(type, score)) -/** - * Get the application-wide default thing to aim for, which applies to any score of 60 or less - */ -fun getDefaultDartToAimAt(score: Int): AimDart -{ - //Aim for the single that puts you on double top - if (score > 40) - { +/** Get the application-wide default thing to aim for, which applies to any score of 60 or less */ +fun getDefaultDartToAimAt(score: Int): AimDart { + // Aim for the single that puts you on double top + if (score > 40) { val single = score - 40 return AimDart(single, 1) } - //Aim for the double - if (score % 2 == 0) - { + // Aim for the double + if (score % 2 == 0) { return AimDart(score / 2, 2) } - //On an odd number, less than 40. Aim to put ourselves on the highest possible power of 2. + // On an odd number, less than 40. Aim to put ourselves on the highest possible power of 2. val scoreToLeaveRemaining = getHighestPowerOfTwoLessThan(score) val singleToAimFor = score - scoreToLeaveRemaining return AimDart(singleToAimFor, 1) } -private fun getHighestPowerOfTwoLessThan(score: Int): Int -{ +private fun getHighestPowerOfTwoLessThan(score: Int): Int { var i = 2 - while (i < score) - { + while (i < score) { i *= 2 } diff --git a/src/main/kotlin/dartzee/bean/AbstractDartzeeRuleSelector.kt b/src/main/kotlin/dartzee/bean/AbstractDartzeeRuleSelector.kt index e5c197bbe..163184412 100644 --- a/src/main/kotlin/dartzee/bean/AbstractDartzeeRuleSelector.kt +++ b/src/main/kotlin/dartzee/bean/AbstractDartzeeRuleSelector.kt @@ -17,16 +17,15 @@ import javax.swing.JComboBox import javax.swing.JLabel import javax.swing.JPanel -abstract class AbstractDartzeeRuleSelector(val desc: String): JPanel(), ActionListener -{ +abstract class AbstractDartzeeRuleSelector(val desc: String) : + JPanel(), ActionListener { val lblDesc = JLabel(desc) val cbDesc = JCheckBox(desc) val comboBoxRuleType = JComboBox() var listener: DartzeeRuleCreationDialog? = null - init - { + init { layout = FlowLayout() populateComboBox() @@ -38,32 +37,27 @@ abstract class AbstractDartzeeRuleSelector(va } abstract fun getRules(): List + open fun isOptional() = false - private fun populateComboBox() - { + private fun populateComboBox() { val rules = getRules() val model = DefaultComboBoxModel() - rules.forEach{ - model.addElement(it) - } + rules.forEach { model.addElement(it) } comboBoxRuleType.model = model } fun getSelection() = comboBoxRuleType.selectedItemTyped() - fun setSelected(selected: Boolean) - { + fun setSelected(selected: Boolean) { cbDesc.isSelected = selected } - open fun populate(rule: BaseRuleType?) - { - if (rule != null) - { + open fun populate(rule: BaseRuleType?) { + if (rule != null) { val item = comboBoxRuleType.findByConcreteClass(rule.javaClass)!! item.populate(rule.toDbString()) @@ -75,11 +69,9 @@ abstract class AbstractDartzeeRuleSelector(va updateComponents() } - fun valid(): Boolean - { + fun valid(): Boolean { val errorStr = getSelection().validate() - if (errorStr.isNotEmpty()) - { + if (errorStr.isNotEmpty()) { DialogUtil.showErrorOLD("$desc: $errorStr") return false } @@ -87,13 +79,11 @@ abstract class AbstractDartzeeRuleSelector(va return true } - override fun actionPerformed(e: ActionEvent?) - { + override fun actionPerformed(e: ActionEvent?) { updateComponents() } - fun addActionListener(listener: DartzeeRuleCreationDialog) - { + fun addActionListener(listener: DartzeeRuleCreationDialog) { this.listener = listener addActionListenerToAllChildren(listener) addChangeListenerToAllChildren(listener) @@ -101,8 +91,7 @@ abstract class AbstractDartzeeRuleSelector(va open fun shouldBeEnabled() = true - private fun updateComponents() - { + private fun updateComponents() { val rule = getSelection() removeAll() @@ -111,8 +100,7 @@ abstract class AbstractDartzeeRuleSelector(va add(comboBoxRuleType) - if (rule is IDartzeeRuleConfigurable) - { + if (rule is IDartzeeRuleConfigurable) { add(rule.configPanel) } @@ -125,4 +113,4 @@ abstract class AbstractDartzeeRuleSelector(va revalidate() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/AbstractPlayerSelector.kt b/src/main/kotlin/dartzee/bean/AbstractPlayerSelector.kt index 659be31c7..923b40ac3 100644 --- a/src/main/kotlin/dartzee/bean/AbstractPlayerSelector.kt +++ b/src/main/kotlin/dartzee/bean/AbstractPlayerSelector.kt @@ -5,7 +5,6 @@ import dartzee.core.bean.ScrollTable import dartzee.db.PlayerEntity import dartzee.logging.CODE_SWING_ERROR import dartzee.utils.InjectedThings -import net.miginfocom.swing.MigLayout import java.awt.Component import java.awt.Dimension import java.awt.event.ActionEvent @@ -14,27 +13,25 @@ import java.awt.event.KeyEvent import javax.swing.ImageIcon import javax.swing.JButton import javax.swing.JPanel +import net.miginfocom.swing.MigLayout -class PlayerSelector: AbstractPlayerSelector() -{ +class PlayerSelector : AbstractPlayerSelector() { override val tablePlayersSelected = ScrollTable() - init - { + init { super.render() } } -abstract class AbstractPlayerSelector : JPanel(), ActionListener, IDoubleClickListener -{ +abstract class AbstractPlayerSelector : + JPanel(), ActionListener, IDoubleClickListener { abstract val tablePlayersSelected: S val tablePlayersToSelectFrom = ScrollTable() private val btnSelect = JButton("") private val btnUnselect = JButton("") - protected fun render() - { + protected fun render() { layout = MigLayout("", "[452px][100px][452px]", "[407px]") val panelMovementOptions = JPanel() @@ -43,11 +40,13 @@ abstract class AbstractPlayerSelector : JPanel(), ActionListener add(panelMovementOptions, "cell 1 0,grow") panelMovementOptions.layout = MigLayout("al center center, wrap, gapy 20") btnSelect.name = "Select" - btnSelect.icon = ImageIcon(AbstractPlayerSelector::class.java.getResource("/buttons/rightArrow.png")) + btnSelect.icon = + ImageIcon(AbstractPlayerSelector::class.java.getResource("/buttons/rightArrow.png")) btnSelect.preferredSize = Dimension(40, 40) panelMovementOptions.add(btnSelect, "cell 0 0,alignx left,aligny top") btnUnselect.name = "Unselect" - btnUnselect.icon = ImageIcon(AbstractPlayerSelector::class.java.getResource("/buttons/leftArrow.png")) + btnUnselect.icon = + ImageIcon(AbstractPlayerSelector::class.java.getResource("/buttons/leftArrow.png")) btnUnselect.preferredSize = Dimension(40, 40) panelMovementOptions.add(btnUnselect, "cell 0 1,alignx left,aligny top") add(tablePlayersSelected, "cell 2 0,alignx left,growy") @@ -62,66 +61,70 @@ abstract class AbstractPlayerSelector : JPanel(), ActionListener addKeyListener(tablePlayersToSelectFrom) } - open fun init() - { + open fun init() { val allPlayers = PlayerEntity.retrievePlayers("") tablePlayersToSelectFrom.initPlayerTableModel(allPlayers) tablePlayersSelected.initPlayerTableModel() } - fun init(selectedPlayers: List) - { + fun init(selectedPlayers: List) { init() moveRows(tablePlayersToSelectFrom, tablePlayersSelected, selectedPlayers) } fun getSelectedPlayers(): List = tablePlayersSelected.getAllPlayers() - private fun addKeyListener(table: ScrollTable) - { + private fun addKeyListener(table: ScrollTable) { table.addKeyAction(KeyEvent.VK_ENTER) { moveRows(table) } } - private fun moveRows(source: ScrollTable, destination: ScrollTable) - { + private fun moveRows(source: ScrollTable, destination: ScrollTable) { moveRows(source, destination, source.getSelectedPlayers()) } - private fun moveRows(source: ScrollTable, destination: ScrollTable, selectedPlayers: List) - { + + private fun moveRows( + source: ScrollTable, + destination: ScrollTable, + selectedPlayers: List + ) { destination.addPlayers(selectedPlayers) var rowToSelect = source.selectedViewRow val allPlayers = source.getAllPlayers() - val availablePlayers = allPlayers.filter{ p -> selectedPlayers.none{ it.rowId == p.rowId} } + val availablePlayers = + allPlayers.filter { p -> selectedPlayers.none { it.rowId == p.rowId } } source.initPlayerTableModel(availablePlayers) - if (rowToSelect > availablePlayers.size - 1) - { + if (rowToSelect > availablePlayers.size - 1) { rowToSelect = 0 } - if (availablePlayers.isNotEmpty()) - { + if (availablePlayers.isNotEmpty()) { source.selectRow(rowToSelect) } } - private fun moveRows(source: Any) - { - when (source) - { - tablePlayersToSelectFrom, btnSelect -> moveRows(tablePlayersToSelectFrom, tablePlayersSelected) - tablePlayersSelected, btnUnselect -> moveRows(tablePlayersSelected, tablePlayersToSelectFrom) + private fun moveRows(source: Any) { + when (source) { + tablePlayersToSelectFrom, + btnSelect -> moveRows(tablePlayersToSelectFrom, tablePlayersSelected) + tablePlayersSelected, + btnUnselect -> moveRows(tablePlayersSelected, tablePlayersToSelectFrom) } } override fun actionPerformed(e: ActionEvent) { - when (e.source) - { - btnSelect, btnUnselect -> moveRows(e.source) - else -> InjectedThings.logger.error(CODE_SWING_ERROR, "Unexpected actionPerformed: ${e.source}") + when (e.source) { + btnSelect, + btnUnselect -> moveRows(e.source) + else -> + InjectedThings.logger.error( + CODE_SWING_ERROR, + "Unexpected actionPerformed: ${e.source}" + ) } } + override fun doubleClicked(source: Component) = moveRows(source) } diff --git a/src/main/kotlin/dartzee/bean/AchievementMedal.kt b/src/main/kotlin/dartzee/bean/AchievementMedal.kt index a9878a42b..c44b76b2b 100644 --- a/src/main/kotlin/dartzee/bean/AchievementMedal.kt +++ b/src/main/kotlin/dartzee/bean/AchievementMedal.kt @@ -19,35 +19,28 @@ import javax.swing.JLabel private const val SIZE = 132 -class AchievementMedal(val achievement : AbstractAchievement): JComponent(), IMouseListener -{ +class AchievementMedal(val achievement: AbstractAchievement) : JComponent(), IMouseListener { private var highlighted = false - init - { + init { preferredSize = Dimension(SIZE, SIZE) addMouseListener(this) addMouseMotionListener(this) } - override fun paint(g: Graphics?) - { - if (g is Graphics2D) - { + override fun paint(g: Graphics?) { + if (g is Graphics2D) { paintMedalCommon(g, achievement, SIZE, highlighted) - if (!highlighted || achievement.isLocked()) - { + if (!highlighted || achievement.isLocked()) { val y = (SIZE - 72) / 2 val icon = achievement.getIcon() icon?.let { val x = (SIZE / 2) - (icon.width / 2) g.drawImage(icon, null, x, y) } - } - else - { + } else { val y = (SIZE - 24) / 2 val label = JLabel(achievement.getProgressDesc()) label.setSize(SIZE, 24) @@ -61,56 +54,45 @@ class AchievementMedal(val achievement : AbstractAchievement): JComponent(), IMo } } - private fun updateForMouseOver(e : MouseEvent) - { + private fun updateForMouseOver(e: MouseEvent) { val pt = e.point - highlighted = pt.distance(Point(SIZE/2, SIZE/2)) < SIZE/2 + highlighted = pt.distance(Point(SIZE / 2, SIZE / 2)) < SIZE / 2 val currentScreen = ScreenCache.currentScreen() - if (currentScreen is PlayerAchievementsScreen) - { + if (currentScreen is PlayerAchievementsScreen) { currentScreen.toggleAchievementDesc(highlighted, achievement) } - cursor = if (highlighted && achievement.isClickable()) - { - Cursor(Cursor.HAND_CURSOR) - } - else - { - Cursor(Cursor.DEFAULT_CURSOR) - } + cursor = + if (highlighted && achievement.isClickable()) { + Cursor(Cursor.HAND_CURSOR) + } else { + Cursor(Cursor.DEFAULT_CURSOR) + } repaint() } - override fun mouseReleased(e: MouseEvent) - { - if (achievement.tmBreakdown != null) - { + override fun mouseReleased(e: MouseEvent) { + if (achievement.tmBreakdown != null) { val scrn = ScreenCache.get() scrn.setState(achievement) ScreenCache.switch(scrn) - } - else if (achievement.gameIdEarned.isNotEmpty()) - { + } else if (achievement.gameIdEarned.isNotEmpty()) { gameLauncher.loadAndDisplayGame(achievement.gameIdEarned) } } - override fun mouseEntered(e: MouseEvent) - { + override fun mouseEntered(e: MouseEvent) { updateForMouseOver(e) } - override fun mouseExited(e: MouseEvent) - { + override fun mouseExited(e: MouseEvent) { updateForMouseOver(e) } - override fun mouseMoved(e: MouseEvent) - { + override fun mouseMoved(e: MouseEvent) { updateForMouseOver(e) } } diff --git a/src/main/kotlin/dartzee/bean/AchievementUnlockedMedal.kt b/src/main/kotlin/dartzee/bean/AchievementUnlockedMedal.kt index 8bb087e48..a08d5b482 100644 --- a/src/main/kotlin/dartzee/bean/AchievementUnlockedMedal.kt +++ b/src/main/kotlin/dartzee/bean/AchievementUnlockedMedal.kt @@ -12,17 +12,13 @@ import javax.swing.JLabel private const val MEDAL_SIZE = 164 -class AchievementUnlockedMedal(val achievement : AbstractAchievement): JComponent() -{ - init - { +class AchievementUnlockedMedal(val achievement: AbstractAchievement) : JComponent() { + init { preferredSize = Dimension(MEDAL_SIZE, MEDAL_SIZE) } - override fun paint(g: Graphics?) - { - if (g is Graphics2D) - { + override fun paint(g: Graphics?) { + if (g is Graphics2D) { paintMedalCommon(g, achievement, MEDAL_SIZE, false) val icon = achievement.getIcon() @@ -41,4 +37,4 @@ class AchievementUnlockedMedal(val achievement : AbstractAchievement): JComponen label.paint(g) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/ComboBoxGameType.kt b/src/main/kotlin/dartzee/bean/ComboBoxGameType.kt index e63e34f3c..58ed6d040 100644 --- a/src/main/kotlin/dartzee/bean/ComboBoxGameType.kt +++ b/src/main/kotlin/dartzee/bean/ComboBoxGameType.kt @@ -6,15 +6,12 @@ import dartzee.game.GameType import javax.swing.DefaultComboBoxModel import javax.swing.JComboBox -class ComboBoxGameType : JComboBox>() -{ - init - { +class ComboBoxGameType : JComboBox>() { + init { val model = DefaultComboBoxModel>() val gameTypes = GameType.values() - for (gameType in gameTypes) - { + for (gameType in gameTypes) { val item = ComboBoxItem(gameType, gameType.getDescription()) model.addElement(item) } diff --git a/src/main/kotlin/dartzee/bean/DartLabel.kt b/src/main/kotlin/dartzee/bean/DartLabel.kt index c09a64232..b809c0d62 100644 --- a/src/main/kotlin/dartzee/bean/DartLabel.kt +++ b/src/main/kotlin/dartzee/bean/DartLabel.kt @@ -3,10 +3,8 @@ package dartzee.bean import dartzee.utils.ResourceCache import javax.swing.JLabel -class DartLabel : JLabel(ResourceCache.DART_IMG) -{ - init - { +class DartLabel : JLabel(ResourceCache.DART_IMG) { + init { setSize(76, 80) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/DartzeeAggregateRuleSelector.kt b/src/main/kotlin/dartzee/bean/DartzeeAggregateRuleSelector.kt index 6c2b746dc..94a718325 100644 --- a/src/main/kotlin/dartzee/bean/DartzeeAggregateRuleSelector.kt +++ b/src/main/kotlin/dartzee/bean/DartzeeAggregateRuleSelector.kt @@ -4,19 +4,20 @@ import dartzee.core.util.enableChildren import dartzee.dartzee.aggregate.AbstractDartzeeAggregateRule import dartzee.dartzee.getAllAggregateRules -class DartzeeAggregateRuleSelector(desc: String): AbstractDartzeeRuleSelector(desc) -{ +class DartzeeAggregateRuleSelector(desc: String) : + AbstractDartzeeRuleSelector(desc) { override fun getRules() = getAllAggregateRules() + override fun shouldBeEnabled() = cbDesc.isSelected + override fun isOptional() = true - override fun setEnabled(enabled: Boolean) - { + override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) enableChildren(enabled) - //Re-enable this if necessary + // Re-enable this if necessary cbDesc.isEnabled = true } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/DartzeeDartRuleSelector.kt b/src/main/kotlin/dartzee/bean/DartzeeDartRuleSelector.kt index 5b9353175..d5c8e5c92 100644 --- a/src/main/kotlin/dartzee/bean/DartzeeDartRuleSelector.kt +++ b/src/main/kotlin/dartzee/bean/DartzeeDartRuleSelector.kt @@ -3,7 +3,7 @@ package dartzee.bean import dartzee.dartzee.dart.AbstractDartzeeDartRule import dartzee.dartzee.getAllDartRules -class DartzeeDartRuleSelector(desc: String): AbstractDartzeeRuleSelector(desc) -{ +class DartzeeDartRuleSelector(desc: String) : + AbstractDartzeeRuleSelector(desc) { override fun getRules() = getAllDartRules() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/GameParamFilterPanel.kt b/src/main/kotlin/dartzee/bean/GameParamFilterPanel.kt index 89f495f02..aacedb1f3 100644 --- a/src/main/kotlin/dartzee/bean/GameParamFilterPanel.kt +++ b/src/main/kotlin/dartzee/bean/GameParamFilterPanel.kt @@ -2,25 +2,26 @@ package dartzee.bean import java.awt.BorderLayout import java.awt.event.ActionListener - import javax.swing.JPanel -abstract class GameParamFilterPanel : JPanel() -{ - init - { +abstract class GameParamFilterPanel : JPanel() { + init { layout = BorderLayout(0, 0) } abstract fun setGameParams(gameParams: String) + abstract fun getGameParams(): String + abstract fun getFilterDesc(): String + abstract fun enableChildren(enabled: Boolean) + abstract fun addActionListener(listener: ActionListener) + abstract fun removeActionListener(listener: ActionListener) - override fun setEnabled(enabled: Boolean) - { + override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) enableChildren(enabled) diff --git a/src/main/kotlin/dartzee/bean/GameParamFilterPanelDartzee.kt b/src/main/kotlin/dartzee/bean/GameParamFilterPanelDartzee.kt index 80d24d005..d6f00f6ab 100644 --- a/src/main/kotlin/dartzee/bean/GameParamFilterPanelDartzee.kt +++ b/src/main/kotlin/dartzee/bean/GameParamFilterPanelDartzee.kt @@ -9,21 +9,18 @@ import java.awt.event.ActionListener import javax.swing.JComboBox import javax.swing.JPanel -class GameParamFilterPanelDartzee: GameParamFilterPanel() -{ +class GameParamFilterPanelDartzee : GameParamFilterPanel() { private val panel = JPanel() val comboBox = JComboBox>() - init - { + init { add(panel, BorderLayout.CENTER) panel.add(comboBox) populateComboBox() } - private fun populateComboBox() - { + private fun populateComboBox() { val templates = DartzeeTemplateEntity().retrieveEntities() val divider = ComboBoxItem(null, "-----", false) @@ -32,15 +29,14 @@ class GameParamFilterPanelDartzee: GameParamFilterPanel() comboBox.addItem(divider) templates.forEach { comboBox.addItem(ComboBoxItem(it, it.name)) } - if (templates.isEmpty()) - { - val noTemplates = ComboBoxItem(null, "No templates configured", false) + if (templates.isEmpty()) { + val noTemplates = + ComboBoxItem(null, "No templates configured", false) comboBox.addItem(noTemplates) } } - override fun setGameParams(gameParams: String) - { + override fun setGameParams(gameParams: String) { val item = comboBox.items().find { it.hiddenData?.rowId == gameParams } comboBox.selectedItem = item } @@ -49,33 +45,25 @@ class GameParamFilterPanelDartzee: GameParamFilterPanel() fun getSelectedTemplate() = comboBox.selectedItemTyped().hiddenData - override fun getFilterDesc(): String - { + override fun getFilterDesc(): String { val template = getSelectedTemplate() - return if (template != null) - { + return if (template != null) { "games for template '${template.name}'" - } - else - { + } else { "custom games" } } - override fun enableChildren(enabled: Boolean) - { + override fun enableChildren(enabled: Boolean) { comboBox.isEnabled = enabled } - override fun addActionListener(listener: ActionListener) - { + override fun addActionListener(listener: ActionListener) { comboBox.addActionListener(listener) } - override fun removeActionListener(listener: ActionListener) - { + override fun removeActionListener(listener: ActionListener) { comboBox.removeActionListener(listener) } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/GameParamFilterPanelGolf.kt b/src/main/kotlin/dartzee/bean/GameParamFilterPanelGolf.kt index b8e344fc1..fd8350d43 100644 --- a/src/main/kotlin/dartzee/bean/GameParamFilterPanelGolf.kt +++ b/src/main/kotlin/dartzee/bean/GameParamFilterPanelGolf.kt @@ -5,55 +5,45 @@ import java.awt.BorderLayout import java.awt.event.ActionListener import javax.swing.JRadioButton -class GameParamFilterPanelGolf : GameParamFilterPanel() -{ +class GameParamFilterPanelGolf : GameParamFilterPanel() { private val panel = RadioButtonPanel() val rdbtn9 = JRadioButton("9 holes") val rdbtn18 = JRadioButton("18 holes") - init - { + init { add(panel, BorderLayout.CENTER) panel.add(rdbtn9) panel.add(rdbtn18) - rdbtn18.isSelected = true //Default to 18 + rdbtn18.isSelected = true // Default to 18 } - override fun getGameParams(): String - { + override fun getGameParams(): String { val selection = panel.getSelectionStr() return selection.replace(" holes", "") } - override fun setGameParams(gameParams: String) - { - if (gameParams == "9") - { + override fun setGameParams(gameParams: String) { + if (gameParams == "9") { rdbtn9.isSelected = true - } - else - { + } else { rdbtn18.isSelected = true } } override fun getFilterDesc() = "games of ${panel.getSelectionStr()}" - override fun enableChildren(enabled: Boolean) - { + override fun enableChildren(enabled: Boolean) { rdbtn9.isEnabled = enabled rdbtn18.isEnabled = enabled } - override fun addActionListener(listener: ActionListener) - { + override fun addActionListener(listener: ActionListener) { panel.addActionListener(listener) } - override fun removeActionListener(listener: ActionListener) - { + override fun removeActionListener(listener: ActionListener) { panel.removeActionListener(listener) } } diff --git a/src/main/kotlin/dartzee/bean/GameParamFilterPanelRoundTheClock.kt b/src/main/kotlin/dartzee/bean/GameParamFilterPanelRoundTheClock.kt index f4b73805a..2148fc415 100644 --- a/src/main/kotlin/dartzee/bean/GameParamFilterPanelRoundTheClock.kt +++ b/src/main/kotlin/dartzee/bean/GameParamFilterPanelRoundTheClock.kt @@ -9,8 +9,7 @@ import javax.swing.Box import javax.swing.JCheckBox import javax.swing.JRadioButton -class GameParamFilterPanelRoundTheClock : GameParamFilterPanel() -{ +class GameParamFilterPanelRoundTheClock : GameParamFilterPanel() { private val panel = RadioButtonPanel() private val rdbtnStandard = JRadioButton("${ClockType.Standard}") private val rdbtnDoubles = JRadioButton("${ClockType.Doubles}") @@ -18,8 +17,7 @@ class GameParamFilterPanelRoundTheClock : GameParamFilterPanel() private val separator = Box.createHorizontalStrut(20) private val checkBoxInOrder = JCheckBox("In order") - init - { + init { checkBoxInOrder.isSelected = true add(panel, BorderLayout.CENTER) @@ -28,47 +26,40 @@ class GameParamFilterPanelRoundTheClock : GameParamFilterPanel() panel.add(rdbtnStandard) panel.add(rdbtnDoubles) panel.add(rdbtnTrebles) - } override fun getGameParams() = getConfigFromSelection().toJson() - private fun getConfigFromSelection(): RoundTheClockConfig - { + private fun getConfigFromSelection(): RoundTheClockConfig { val selectedType = panel.getSelectionStr() val clockType = ClockType.valueOf(selectedType) return RoundTheClockConfig(clockType, checkBoxInOrder.isSelected) } - override fun setGameParams(gameParams: String) - { + override fun setGameParams(gameParams: String) { val config = RoundTheClockConfig.fromJson(gameParams) checkBoxInOrder.isSelected = config.inOrder panel.setSelection(config.clockType.toString()) } - override fun getFilterDesc(): String - { + override fun getFilterDesc(): String { val config = getConfigFromSelection() return "${config.clockType} games (${config.getOrderStr()})" } - override fun enableChildren(enabled: Boolean) - { + override fun enableChildren(enabled: Boolean) { rdbtnStandard.isEnabled = enabled rdbtnDoubles.isEnabled = enabled rdbtnTrebles.isEnabled = enabled checkBoxInOrder.isEnabled = enabled } - override fun addActionListener(listener: ActionListener) - { + override fun addActionListener(listener: ActionListener) { panel.addActionListener(listener) checkBoxInOrder.addActionListener(listener) } - override fun removeActionListener(listener: ActionListener) - { + override fun removeActionListener(listener: ActionListener) { panel.removeActionListener(listener) checkBoxInOrder.removeActionListener(listener) } diff --git a/src/main/kotlin/dartzee/bean/GameParamFilterPanelX01.kt b/src/main/kotlin/dartzee/bean/GameParamFilterPanelX01.kt index 4945ba188..a75258711 100644 --- a/src/main/kotlin/dartzee/bean/GameParamFilterPanelX01.kt +++ b/src/main/kotlin/dartzee/bean/GameParamFilterPanelX01.kt @@ -2,42 +2,34 @@ package dartzee.bean import java.awt.BorderLayout import java.awt.event.ActionListener - import javax.swing.JPanel -class GameParamFilterPanelX01 : GameParamFilterPanel() -{ +class GameParamFilterPanelX01 : GameParamFilterPanel() { private val panel = JPanel() val spinner = SpinnerX01() - init - { + init { add(panel, BorderLayout.CENTER) panel.add(spinner) } override fun getGameParams() = "${spinner.value}" - override fun setGameParams(gameParams: String) - { + override fun setGameParams(gameParams: String) { spinner.value = gameParams.toInt() } override fun getFilterDesc() = "games of ${getGameParams()}" - override fun enableChildren(enabled: Boolean) - { + override fun enableChildren(enabled: Boolean) { spinner.isEnabled = enabled } - override fun addActionListener(listener: ActionListener) - { + override fun addActionListener(listener: ActionListener) { spinner.addActionListener(listener) } - override fun removeActionListener(listener: ActionListener) - { + override fun removeActionListener(listener: ActionListener) { spinner.removeActionListener() } - } diff --git a/src/main/kotlin/dartzee/bean/GameSetupPlayerSelector.kt b/src/main/kotlin/dartzee/bean/GameSetupPlayerSelector.kt index 55e75eab1..7c14e31d1 100644 --- a/src/main/kotlin/dartzee/bean/GameSetupPlayerSelector.kt +++ b/src/main/kotlin/dartzee/bean/GameSetupPlayerSelector.kt @@ -7,13 +7,11 @@ import java.awt.event.ActionEvent import javax.swing.ImageIcon import javax.swing.JToggleButton -class GameSetupPlayerSelector: AbstractPlayerSelector() -{ +class GameSetupPlayerSelector : AbstractPlayerSelector() { override val tablePlayersSelected = ScrollTableOrdered() private val btnPairs = JToggleButton("") - init - { + init { super.render() btnPairs.icon = ImageIcon(javaClass.getResource("/buttons/teams.png")) @@ -23,8 +21,7 @@ class GameSetupPlayerSelector: AbstractPlayerSelector() btnPairs.addActionListener(this) } - override fun init() - { + override fun init() { super.init() val nimbusRenderer = tablePlayersSelected.getBuiltInRenderer() @@ -33,30 +30,24 @@ class GameSetupPlayerSelector: AbstractPlayerSelector() fun pairMode(): Boolean = btnPairs.isSelected - /** - * Is this selection valid for a game/match? - */ - fun valid(match: Boolean): Boolean - { + /** Is this selection valid for a game/match? */ + fun valid(match: Boolean): Boolean { val selectedPlayers = getSelectedPlayers() val rowCount = selectedPlayers.size - if (rowCount < 1) - { + if (rowCount < 1) { DialogUtil.showErrorOLD("You must select at least 1 player.") return false } val playerOrTeamDesc = if (btnPairs.isSelected) "teams" else "players" val matchMinimum = if (btnPairs.isSelected) 4 else 2 - if (match && rowCount < matchMinimum) - { + if (match && rowCount < matchMinimum) { DialogUtil.showErrorOLD("You must select at least 2 $playerOrTeamDesc for a match.") return false } val maxPlayers = if (btnPairs.isSelected) MAX_PLAYERS * 2 else MAX_PLAYERS - if (rowCount > maxPlayers) - { + if (rowCount > maxPlayers) { DialogUtil.showErrorOLD("You cannot select more than $MAX_PLAYERS $playerOrTeamDesc.") return false } @@ -64,12 +55,10 @@ class GameSetupPlayerSelector: AbstractPlayerSelector() return true } - override fun actionPerformed(e: ActionEvent) - { - when (e.source) - { + override fun actionPerformed(e: ActionEvent) { + when (e.source) { btnPairs -> tablePlayersSelected.repaint() else -> super.actionPerformed(e) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/IMouseListener.kt b/src/main/kotlin/dartzee/bean/IMouseListener.kt index 55c16d433..161071b94 100644 --- a/src/main/kotlin/dartzee/bean/IMouseListener.kt +++ b/src/main/kotlin/dartzee/bean/IMouseListener.kt @@ -4,13 +4,18 @@ import java.awt.event.MouseEvent import java.awt.event.MouseListener import java.awt.event.MouseMotionListener -interface IMouseListener : MouseListener, MouseMotionListener -{ +interface IMouseListener : MouseListener, MouseMotionListener { override fun mouseMoved(e: MouseEvent) {} + override fun mouseDragged(e: MouseEvent) {} + override fun mouseEntered(e: MouseEvent) {} + override fun mouseExited(e: MouseEvent) {} + override fun mouseClicked(e: MouseEvent) {} + override fun mousePressed(e: MouseEvent) {} + override fun mouseReleased(e: MouseEvent) {} -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/InteractiveDartboard.kt b/src/main/kotlin/dartzee/bean/InteractiveDartboard.kt index e57996acb..fb6dbaf78 100644 --- a/src/main/kotlin/dartzee/bean/InteractiveDartboard.kt +++ b/src/main/kotlin/dartzee/bean/InteractiveDartboard.kt @@ -10,79 +10,71 @@ import java.awt.Point import java.awt.event.MouseEvent class InteractiveDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs()) : - PresentationDartboard(colourWrapper, true), IMouseListener -{ + PresentationDartboard(colourWrapper, true), IMouseListener { private var hoveredSegment: DartboardSegment? = null private var allowInteraction = true - init - { + init { addMouseMotionListener(this) } - fun highlightDartboard(pt: Point) - { + fun highlightDartboard(pt: Point) { if (!allowInteraction) { return } val distance = pt.distance(computeCenter()) - val newHoveredSegment = if (distance > computeRadius() * UPPER_BOUND_OUTSIDE_BOARD_RATIO) { - null - } else getSegmentForPoint(pt) + val newHoveredSegment = + if (distance > computeRadius() * UPPER_BOUND_OUTSIDE_BOARD_RATIO) { + null + } else getSegmentForPoint(pt) - if (hoveredSegment == newHoveredSegment) - { - //Nothing to do + if (hoveredSegment == newHoveredSegment) { + // Nothing to do return } hoveredSegment?.let(::revertOverriddenSegmentColour) - if (newHoveredSegment != null && isValidSegmentForHover(newHoveredSegment)) - { + if (newHoveredSegment != null && isValidSegmentForHover(newHoveredSegment)) { hoveredSegment = newHoveredSegment - overrideSegmentColour(newHoveredSegment, getHighlightedColour(defaultColourForSegment(newHoveredSegment))) - } - else - { + overrideSegmentColour( + newHoveredSegment, + getHighlightedColour(defaultColourForSegment(newHoveredSegment)) + ) + } else { hoveredSegment = null } } private fun isValidSegmentForHover(segment: DartboardSegment): Boolean { val statuses = segmentStatuses - if (statuses != null) - { - return statuses.validSegments.contains(segment) || (statuses.allowsMissing() && segment.isMiss()) + if (statuses != null) { + return statuses.validSegments.contains(segment) || + (statuses.allowsMissing() && segment.isMiss()) } return !segment.isMiss() } - fun stopInteraction() - { + fun stopInteraction() { clearHover() allowInteraction = false } - fun allowInteraction() - { + fun allowInteraction() { allowInteraction = true } - fun clearHover() - { + fun clearHover() { hoveredSegment?.let(::revertOverriddenSegmentColour) hoveredSegment = null } - override fun mouseMoved(e: MouseEvent) - { - if (getParentWindow()?.isFocused == true) - { + override fun mouseMoved(e: MouseEvent) { + if (getParentWindow()?.isFocused == true) { highlightDartboard(e.point) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/ParticipantAvatar.kt b/src/main/kotlin/dartzee/bean/ParticipantAvatar.kt index 13147fa66..bac1e58ee 100644 --- a/src/main/kotlin/dartzee/bean/ParticipantAvatar.kt +++ b/src/main/kotlin/dartzee/bean/ParticipantAvatar.kt @@ -11,19 +11,18 @@ import javax.swing.SwingConstants import javax.swing.border.EtchedBorder import javax.swing.border.LineBorder -class ParticipantAvatar(private val pt: IWrappedParticipant) : JLabel(ResourceCache.AVATAR_UNSET) -{ - init - { +class ParticipantAvatar(private val pt: IWrappedParticipant) : JLabel(ResourceCache.AVATAR_UNSET) { + init { size = Dimension(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT) border = EtchedBorder(EtchedBorder.RAISED, null, null) horizontalAlignment = SwingConstants.CENTER icon = pt.getAvatar(1, selected = false, gameFinished = false) } - fun setSelected(selected: Boolean, roundNumber: Int, gameFinished: Boolean = false) - { - border = if (selected) LineBorder(Color.BLACK, 2) else EtchedBorder(EtchedBorder.RAISED, null, null) + fun setSelected(selected: Boolean, roundNumber: Int, gameFinished: Boolean = false) { + border = + if (selected) LineBorder(Color.BLACK, 2) + else EtchedBorder(EtchedBorder.RAISED, null, null) icon = pt.getAvatar(roundNumber, selected, gameFinished) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/PlayerAvatar.kt b/src/main/kotlin/dartzee/bean/PlayerAvatar.kt index 979fc7917..ebc0a0954 100644 --- a/src/main/kotlin/dartzee/bean/PlayerAvatar.kt +++ b/src/main/kotlin/dartzee/bean/PlayerAvatar.kt @@ -14,15 +14,13 @@ import javax.swing.JLabel import javax.swing.SwingConstants import javax.swing.border.EtchedBorder -class PlayerAvatar : JLabel(ResourceCache.AVATAR_UNSET) -{ +class PlayerAvatar : JLabel(ResourceCache.AVATAR_UNSET) { private var player: PlayerEntity? = null var avatarId = "" var readOnly = false - init - { + init { preferredSize = Dimension(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT) border = EtchedBorder(EtchedBorder.RAISED, null, null) horizontalAlignment = SwingConstants.CENTER @@ -30,27 +28,23 @@ class PlayerAvatar : JLabel(ResourceCache.AVATAR_UNSET) addMouseListener(AvatarClickListener()) } - fun init(player: PlayerEntity, saveChanges: Boolean) - { - //Only set the player variable if we want to allow the label to directly make changes to it. - if (saveChanges) - { + fun init(player: PlayerEntity, saveChanges: Boolean) { + // Only set the player variable if we want to allow the label to directly make changes to + // it. + if (saveChanges) { this.player = player } avatarId = player.playerImageId - icon = if (player.playerImageId.isNotEmpty()) player.getAvatar() else ResourceCache.AVATAR_UNSET + icon = + if (player.playerImageId.isNotEmpty()) player.getAvatar() + else ResourceCache.AVATAR_UNSET } - /** - * MouseListener - */ - private inner class AvatarClickListener : MouseAdapter() - { - override fun mouseClicked(arg0: MouseEvent?) - { - if (readOnly) - { + /** MouseListener */ + private inner class AvatarClickListener : MouseAdapter() { + override fun mouseClicked(arg0: MouseEvent?) { + if (readOnly) { return } @@ -58,8 +52,7 @@ class PlayerAvatar : JLabel(ResourceCache.AVATAR_UNSET) dlg.isVisible = true } - private fun imageSelected(imageId: String) - { + private fun imageSelected(imageId: String) { avatarId = imageId val newIcon = PlayerImageEntity.retrieveImageIconForId(avatarId) icon = newIcon @@ -70,18 +63,14 @@ class PlayerAvatar : JLabel(ResourceCache.AVATAR_UNSET) } } - override fun mouseEntered(arg0: MouseEvent?) - { - if (!readOnly) - { + override fun mouseEntered(arg0: MouseEvent?) { + if (!readOnly) { cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) } } - override fun mouseExited(arg0: MouseEvent?) - { - if (!readOnly) - { + override fun mouseExited(arg0: MouseEvent?) { + if (!readOnly) { cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) } } diff --git a/src/main/kotlin/dartzee/bean/PlayerImageRadio.kt b/src/main/kotlin/dartzee/bean/PlayerImageRadio.kt index 5eca416ad..6e03a2615 100644 --- a/src/main/kotlin/dartzee/bean/PlayerImageRadio.kt +++ b/src/main/kotlin/dartzee/bean/PlayerImageRadio.kt @@ -18,14 +18,13 @@ import javax.swing.event.ChangeListener /** * Wrap up a PlayerImage so we can render the icon, and store its ID to point a PlayerEntity at it */ -class PlayerImageRadio(pi: PlayerImageEntity) : JPanel(), ChangeListener, IMouseListener, FocusListener -{ +class PlayerImageRadio(pi: PlayerImageEntity) : + JPanel(), ChangeListener, IMouseListener, FocusListener { var playerImageId = "" val rdbtn = JRadioButton() val lblImg = JLabel() - init - { + init { setMargins(1) lblImg.icon = pi.asImageIcon() playerImageId = pi.rowId @@ -40,32 +39,27 @@ class PlayerImageRadio(pi: PlayerImageEntity) : JPanel(), ChangeListener, IMous fun isSelected() = rdbtn.isSelected - fun addToButtonGroup(bg: ButtonGroup) - { + fun addToButtonGroup(bg: ButtonGroup) { bg.add(rdbtn) } override fun stateChanged(arg0: ChangeEvent) = updateBorder() + override fun focusLost(e: FocusEvent?) = updateBorder() + override fun focusGained(e: FocusEvent?) = updateBorder() - private fun updateBorder() - { - if (rdbtn.isSelected) - { + + private fun updateBorder() { + if (rdbtn.isSelected) { border = LineBorder(Color.BLACK) - } - else if (rdbtn.hasFocus()) - { + } else if (rdbtn.hasFocus()) { border = BorderFactory.createDashedBorder(Color.GRAY) - } - else - { + } else { setMargins(1) } } - override fun mouseClicked(e: MouseEvent) - { + override fun mouseClicked(e: MouseEvent) { rdbtn.isSelected = true } } diff --git a/src/main/kotlin/dartzee/bean/PlayerTypeFilterPanel.kt b/src/main/kotlin/dartzee/bean/PlayerTypeFilterPanel.kt index 00c86fccc..564ae659b 100644 --- a/src/main/kotlin/dartzee/bean/PlayerTypeFilterPanel.kt +++ b/src/main/kotlin/dartzee/bean/PlayerTypeFilterPanel.kt @@ -3,23 +3,19 @@ package dartzee.bean import dartzee.core.bean.RadioButtonPanel import javax.swing.JRadioButton -class PlayerTypeFilterPanel : RadioButtonPanel() -{ +class PlayerTypeFilterPanel : RadioButtonPanel() { val rdbtnAll = JRadioButton("All") val rdbtnHuman = JRadioButton("Human") val rdbtnAi = JRadioButton("AI") - init - { + init { add(rdbtnAll) add(rdbtnHuman) add(rdbtnAi) } - fun getWhereSql(): String - { - return when - { + fun getWhereSql(): String { + return when { rdbtnHuman.isSelected -> "Strategy = ''" rdbtnAi.isSelected -> "Strategy <> ''" else -> "" diff --git a/src/main/kotlin/dartzee/bean/PresentationDartboard.kt b/src/main/kotlin/dartzee/bean/PresentationDartboard.kt index 4cbc1fcca..69c8c2bc0 100644 --- a/src/main/kotlin/dartzee/bean/PresentationDartboard.kt +++ b/src/main/kotlin/dartzee/bean/PresentationDartboard.kt @@ -39,30 +39,24 @@ import kotlin.math.roundToInt open class PresentationDartboard( private val colourWrapper: ColourWrapper = getColourWrapperFromPrefs(), private val renderScoreLabels: Boolean = false -) : JComponent(), IDartboard -{ +) : JComponent(), IDartboard { var segmentStatuses: SegmentStatuses? = null private val overriddenSegmentColours = mutableMapOf() private val dirtySegments = mutableSetOf() private var lastPaintImage: BufferedImage? = null override fun computeRadius() = computeRadius(width, height) + override fun computeCenter() = Point(width / 2, height / 2) - fun interpretPoint(pt: ComputedPoint): Point - { - val newPoint = translatePoint( - computeCenter(), - pt.radius * computeRadius(), - pt.angle - ) + fun interpretPoint(pt: ComputedPoint): Point { + val newPoint = translatePoint(computeCenter(), pt.radius * computeRadius(), pt.angle) rationalisePoint(newPoint) val desiredSegment = pt.segment val candidatePoints = mutableSetOf(newPoint) - while (candidatePoints.none { getSegmentForPoint(it) == desiredSegment }) - { + while (candidatePoints.none { getSegmentForPoint(it) == desiredSegment }) { val neighbours = candidatePoints.flatMap(::getNeighbours) candidatePoints.addAll(neighbours) } @@ -70,53 +64,48 @@ open class PresentationDartboard( return candidatePoints.first { getSegmentForPoint(it) == desiredSegment } } - private fun rationalisePoint(pt: Point) - { + private fun rationalisePoint(pt: Point) { val x = pt.x.coerceIn(0, width - 1) val y = pt.y.coerceIn(0, height - 1) pt.setLocation(x, y) } - fun overrideSegmentColour(segment: DartboardSegment, colour: Color) - { + fun overrideSegmentColour(segment: DartboardSegment, colour: Color) { overriddenSegmentColours[segment] = colour dirtySegments.add(segment) repaint() } - fun revertOverriddenSegmentColour(segment: DartboardSegment) - { + fun revertOverriddenSegmentColour(segment: DartboardSegment) { overriddenSegmentColours.remove(segment) dirtySegments.add(segment) repaint() } - fun updateSegmentStatus(segmentStatuses: SegmentStatuses?) - { + fun updateSegmentStatus(segmentStatuses: SegmentStatuses?) { val oldSegmentStatus = this.segmentStatuses this.segmentStatuses = segmentStatuses - val changed = getAllSegmentsForDartzee().filter { oldSegmentStatus.getSegmentStatus(it) != segmentStatuses.getSegmentStatus(it) } + val changed = + getAllSegmentsForDartzee().filter { + oldSegmentStatus.getSegmentStatus(it) != segmentStatuses.getSegmentStatus(it) + } dirtySegments.addAll(changed) repaint() } - override fun paintComponent(g: Graphics) - { + override fun paintComponent(g: Graphics) { super.paintComponent(g) val cachedImage = lastPaintImage - if (cachedImage != null && cachedImage.width == width && cachedImage.height == height) - { + if (cachedImage != null && cachedImage.width == width && cachedImage.height == height) { repaintDirtySegments(cachedImage) g.drawImage(cachedImage, 0, 0, this) - } - else - { + } else { val timer = DurationTimer() val bi = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) paintOuterBoard(bi.createGraphics()) @@ -126,38 +115,34 @@ open class PresentationDartboard( lastPaintImage = bi val duration = timer.getDuration() - if (duration > 500) - { + if (duration > 500) { logger.warn( - CODE_SLOW_DARTBOARD_RENDER, "Rendered dartboard[$width, $height] in ${duration}ms", - KEY_DURATION to duration) + CODE_SLOW_DARTBOARD_RENDER, + "Rendered dartboard[$width, $height] in ${duration}ms", + KEY_DURATION to duration + ) } } } - private fun repaintDirtySegments(cachedImage: BufferedImage) - { + private fun repaintDirtySegments(cachedImage: BufferedImage) { val dirtySegmentsCopy = dirtySegments.toList() - if (dirtySegmentsCopy.isNotEmpty()) - { + if (dirtySegmentsCopy.isNotEmpty()) { dirtySegmentsCopy.paintAll(cachedImage) dirtySegments.clear() } } - private fun List.paintAll(image: BufferedImage) - { + private fun List.paintAll(image: BufferedImage) { sortedBy { it.type }.forEach { paintSegment(it, image) } } - private fun paintSegment(segment: DartboardSegment, bi: BufferedImage) - { + private fun paintSegment(segment: DartboardSegment, bi: BufferedImage) { val colour = overriddenSegmentColours[segment] ?: defaultColourForSegment(segment) colourSegment(segment, colour, bi) } - protected fun defaultColourForSegment(segment: DartboardSegment): Color - { + protected fun defaultColourForSegment(segment: DartboardSegment): Color { val default = colourWrapper.getColour(segment) val status = segmentStatuses ?: return default return when { @@ -168,10 +153,8 @@ open class PresentationDartboard( } } - private fun colourSegment(segment: DartboardSegment, color: Color, bi: BufferedImage) - { - if (segment.isMiss()) - { + private fun colourSegment(segment: DartboardSegment, color: Color, bi: BufferedImage) { + if (segment.isMiss()) { paintOuterRing(bi.createGraphics(), color) return } @@ -186,15 +169,13 @@ open class PresentationDartboard( } } - private fun getEdgeColourForSegment(segment: DartboardSegment): Color? - { + private fun getEdgeColourForSegment(segment: DartboardSegment): Color? { val default = colourWrapper.edgeColour val status = segmentStatuses ?: return default return if (status.scoringSegments.contains(segment)) Color.GRAY else null } - private fun paintOuterBoard(g: Graphics2D) - { + private fun paintOuterBoard(g: Graphics2D) { g.paint = colourWrapper.missedBoardColour g.fillRect(0, 0, width, height) @@ -204,8 +185,7 @@ open class PresentationDartboard( g.fillOval(center.x - borderSize, center.y - borderSize, borderSize * 2, borderSize * 2) } - private fun paintOuterRing(g: Graphics2D, color: Color) - { + private fun paintOuterRing(g: Graphics2D, color: Color) { g.paint = color val ring = createOuterRing() g.fill(ring) @@ -213,31 +193,31 @@ open class PresentationDartboard( paintScoreLabels(g) } - private fun createOuterRing(): Shape - { + private fun createOuterRing(): Shape { val center = computeCenter() val outerRadius = computeRadius() * UPPER_BOUND_OUTSIDE_BOARD_RATIO val innerRadius = computeRadius() * UPPER_BOUND_DOUBLE_RATIO val thickness = outerRadius - innerRadius - val outer: Ellipse2D = Ellipse2D.Double( - center.x - outerRadius, - center.y - outerRadius, - outerRadius + outerRadius, - outerRadius + outerRadius - ) - val inner: Ellipse2D = Ellipse2D.Double( - center.x - outerRadius + thickness, - center.y - outerRadius + thickness, - outerRadius + outerRadius - (2 * thickness), - outerRadius + outerRadius - (2 * thickness) - ) + val outer: Ellipse2D = + Ellipse2D.Double( + center.x - outerRadius, + center.y - outerRadius, + outerRadius + outerRadius, + outerRadius + outerRadius + ) + val inner: Ellipse2D = + Ellipse2D.Double( + center.x - outerRadius + thickness, + center.y - outerRadius + thickness, + outerRadius + outerRadius - (2 * thickness), + outerRadius + outerRadius - (2 * thickness) + ) val area = Area(outer) area.subtract(Area(inner)) return area } - private fun paintScoreLabels(g: Graphics2D) - { + private fun paintScoreLabels(g: Graphics2D) { if (!renderScoreLabels) return val radius = computeRadius() @@ -245,23 +225,22 @@ open class PresentationDartboard( val lblHeight = ((outerRadius - radius) / 2).roundToInt() val fontToUse = getFontForDartboardLabels(lblHeight) - (1..20).forEach { paintScoreLabel(it, g, fontToUse, lblHeight)} + (1..20).forEach { paintScoreLabel(it, g, fontToUse, lblHeight) } } - private fun paintScoreLabel(score: Int, g: Graphics2D, fontToUse: Font, lblHeight: Int) - { - //Create a label with standard properties + private fun paintScoreLabel(score: Int, g: Graphics2D, fontToUse: Font, lblHeight: Int) { + // Create a label with standard properties val lbl = JLabel(score.toString()) lbl.foreground = Color.WHITE lbl.horizontalAlignment = SwingConstants.CENTER lbl.font = fontToUse - //Work out the width for this label, based on the text + // Work out the width for this label, based on the text val metrics = factoryFontMetrics(fontToUse) val lblWidth = metrics.stringWidth(score.toString()) + 5 lbl.setSize(lblWidth, lblHeight) - //Work out where to place the label + // Work out where to place the label val angle = getAnglesForScore(score).toList().average() val radiusForLabel = computeRadius() + lblHeight val avgPoint = translatePoint(computeCenter(), radiusForLabel, angle) @@ -274,4 +253,4 @@ open class PresentationDartboard( lbl.paint(g) g.translate(-lblX, -lblY) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/ScrollTableAchievements.kt b/src/main/kotlin/dartzee/bean/ScrollTableAchievements.kt index 7db867620..4980c24ea 100644 --- a/src/main/kotlin/dartzee/bean/ScrollTableAchievements.kt +++ b/src/main/kotlin/dartzee/bean/ScrollTableAchievements.kt @@ -4,11 +4,9 @@ import dartzee.core.bean.ScrollTableHyperlink import dartzee.db.PlayerEntity import dartzee.screen.ScreenCache -class ScrollTableAchievements : ScrollTableHyperlink("Player") -{ - override fun linkClicked(value: Any) - { +class ScrollTableAchievements : ScrollTableHyperlink("Player") { + override fun linkClicked(value: Any) { val player = value as PlayerEntity ScreenCache.switchToAchievementsScreen(player) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/ScrollTableDartsGame.kt b/src/main/kotlin/dartzee/bean/ScrollTableDartsGame.kt index 478638a13..9f185c8ad 100644 --- a/src/main/kotlin/dartzee/bean/ScrollTableDartsGame.kt +++ b/src/main/kotlin/dartzee/bean/ScrollTableDartsGame.kt @@ -5,19 +5,17 @@ import dartzee.core.util.DialogUtil import dartzee.db.GameEntity import dartzee.utils.InjectedThings.gameLauncher -class ScrollTableDartsGame(linkColumnName: String = "Game", testId: String = "") : ScrollTableHyperlink(linkColumnName, testId) -{ - override fun linkClicked(value: Any) - { +class ScrollTableDartsGame(linkColumnName: String = "Game", testId: String = "") : + ScrollTableHyperlink(linkColumnName, testId) { + override fun linkClicked(value: Any) { val localId = value as Long - if (localId > 0) - { + if (localId > 0) { val gameId = GameEntity.getGameId(localId) - gameId?.let{ gameLauncher.loadAndDisplayGame(gameId) } - } - else - { - DialogUtil.showErrorOLD("It isn't possible to display individual games from a simulation.") + gameId?.let { gameLauncher.loadAndDisplayGame(gameId) } + } else { + DialogUtil.showErrorOLD( + "It isn't possible to display individual games from a simulation." + ) } } diff --git a/src/main/kotlin/dartzee/bean/ScrollTablePlayers.kt b/src/main/kotlin/dartzee/bean/ScrollTablePlayers.kt index 9390fb04e..dbf90840f 100644 --- a/src/main/kotlin/dartzee/bean/ScrollTablePlayers.kt +++ b/src/main/kotlin/dartzee/bean/ScrollTablePlayers.kt @@ -4,18 +4,18 @@ import dartzee.core.bean.ScrollTable import dartzee.core.util.TableUtil import dartzee.db.PlayerEntity -fun ScrollTable.getSelectedPlayer(): PlayerEntity? -{ +fun ScrollTable.getSelectedPlayer(): PlayerEntity? { val row = table.selectedRow return if (row == -1) null else getPlayerEntityForRow(row) } fun ScrollTable.getAllPlayers() = (0 until table.rowCount).map(::getPlayerEntityForRow) + fun ScrollTable.getSelectedPlayers() = table.selectedRows.map(::getPlayerEntityForRow) + fun ScrollTable.getPlayerEntityForRow(row: Int) = table.getValueAt(row, 1) as PlayerEntity -fun ScrollTable.initPlayerTableModel(players: List = listOf()) -{ +fun ScrollTable.initPlayerTableModel(players: List = listOf()) { val model = TableUtil.DefaultModel() model.addColumn("") model.addColumn("Player") @@ -32,10 +32,10 @@ fun ScrollTable.initPlayerTableModel(players: List = listOf()) } fun ScrollTable.addPlayers(players: List) = players.forEach(::addPlayer) -private fun ScrollTable.addPlayer(player: PlayerEntity) -{ + +private fun ScrollTable.addPlayer(player: PlayerEntity) { val flag = player.getFlag() val row = arrayOf(flag, player) addRow(row) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/SliderAiSpeed.kt b/src/main/kotlin/dartzee/bean/SliderAiSpeed.kt index e4faeeade..1803d4d0a 100644 --- a/src/main/kotlin/dartzee/bean/SliderAiSpeed.kt +++ b/src/main/kotlin/dartzee/bean/SliderAiSpeed.kt @@ -7,20 +7,20 @@ import javax.swing.JSlider import javax.swing.border.EmptyBorder import javax.swing.event.ChangeListener -const val AI_SPEED_MINIMUM = 0 //0s -const val AI_SPEED_MAXIMUM = 2000 //2s +const val AI_SPEED_MINIMUM = 0 // 0s +const val AI_SPEED_MAXIMUM = 2000 // 2s -class SliderAiSpeed : JPanel() -{ +class SliderAiSpeed : JPanel() { private val labelMin = JLabel("Slow") private val labelMax = JLabel("Fast") private val slider = JSlider() var value get() = slider.value - set(value) { slider.value = value } + set(value) { + slider.value = value + } - init - { + init { layout = BorderLayout() add(slider, BorderLayout.CENTER) add(labelMin, BorderLayout.WEST) @@ -36,8 +36,7 @@ class SliderAiSpeed : JPanel() slider.inverted = true } - fun addChangeListener(listener: ChangeListener) - { + fun addChangeListener(listener: ChangeListener) { slider.addChangeListener(listener) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/SpinnerSingleSelector.kt b/src/main/kotlin/dartzee/bean/SpinnerSingleSelector.kt index 60d308bc6..e08e2238c 100644 --- a/src/main/kotlin/dartzee/bean/SpinnerSingleSelector.kt +++ b/src/main/kotlin/dartzee/bean/SpinnerSingleSelector.kt @@ -1,16 +1,13 @@ package dartzee.bean import java.awt.Dimension - import javax.swing.JSpinner import javax.swing.SpinnerNumberModel import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener -class SpinnerSingleSelector : JSpinner(), ChangeListener -{ - init - { +class SpinnerSingleSelector : JSpinner(), ChangeListener { + init { setSize(50, 25) preferredSize = Dimension(50, 25) model = SpinnerNumberModel(20, 1, 25, 1) @@ -19,18 +16,17 @@ class SpinnerSingleSelector : JSpinner(), ChangeListener /** * This looks a bit weird, but what we want is: - * * - Upping from 20 -> 25 * - Downing from 25 -> 20 * - Should not be able to enter 21-24 manually. */ - override fun stateChanged(arg0: ChangeEvent) - { + override fun stateChanged(arg0: ChangeEvent) { val intVal = value as Int - when (intVal) - { - 21, 22 -> value = 25 - 23, 24 -> value = 20 + when (intVal) { + 21, + 22 -> value = 25 + 23, + 24 -> value = 20 } } } diff --git a/src/main/kotlin/dartzee/bean/SpinnerX01.kt b/src/main/kotlin/dartzee/bean/SpinnerX01.kt index 330ac7651..14b62e5a6 100644 --- a/src/main/kotlin/dartzee/bean/SpinnerX01.kt +++ b/src/main/kotlin/dartzee/bean/SpinnerX01.kt @@ -2,40 +2,33 @@ package dartzee.bean import java.awt.event.ActionEvent import java.awt.event.ActionListener - import javax.swing.JSpinner import javax.swing.SpinnerNumberModel import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener -class SpinnerX01 : JSpinner(), ChangeListener -{ +class SpinnerX01 : JSpinner(), ChangeListener { private var listener: ActionListener? = null - init - { + init { model = SpinnerNumberModel(501, 101, 701, 100) addChangeListener(this) } - override fun stateChanged(arg0: ChangeEvent) - { + override fun stateChanged(arg0: ChangeEvent) { val intVal = value as Int - if (intVal % 100 != 1) - { + if (intVal % 100 != 1) { value = 501 } listener?.actionPerformed(ActionEvent(this, ActionEvent.ACTION_PERFORMED, null)) } - fun addActionListener(listener: ActionListener) - { + fun addActionListener(listener: ActionListener) { this.listener = listener } - fun removeActionListener() - { + fun removeActionListener() { this.listener = null } } diff --git a/src/main/kotlin/dartzee/bean/TableModelEntity.kt b/src/main/kotlin/dartzee/bean/TableModelEntity.kt index d28d205a6..dc8e2dd56 100644 --- a/src/main/kotlin/dartzee/bean/TableModelEntity.kt +++ b/src/main/kotlin/dartzee/bean/TableModelEntity.kt @@ -3,28 +3,23 @@ package dartzee.bean import dartzee.db.AbstractEntity import javax.swing.table.DefaultTableModel -class TableModelEntity(entities: List>) : DefaultTableModel() -{ - init - { - //Use the first entity to set up columns +class TableModelEntity(entities: List>) : DefaultTableModel() { + init { + // Use the first entity to set up columns val entity = entities.first() val cols = entity.getColumns() - for (col in cols) - { + for (col in cols) { addColumn(col) } - //Now create the rows + // Now create the rows addRows(entities, cols) } - private fun addRows(entities: List>, columns: List) - { + private fun addRows(entities: List>, columns: List) { entities.forEach { entity -> val row = arrayOfNulls(columns.size) - for (i in columns.indices) - { + for (i in columns.indices) { row[i] = entity.getField(columns[i]) } diff --git a/src/main/kotlin/dartzee/bean/TeamRenderer.kt b/src/main/kotlin/dartzee/bean/TeamRenderer.kt index 15b0c4d49..cc1924ca9 100644 --- a/src/main/kotlin/dartzee/bean/TeamRenderer.kt +++ b/src/main/kotlin/dartzee/bean/TeamRenderer.kt @@ -11,18 +11,41 @@ import javax.swing.border.EmptyBorder import javax.swing.border.MatteBorder import javax.swing.table.TableCellRenderer -class TeamRenderer(private val baseRenderer: TableCellRenderer, private val teamsEnabled: () -> Boolean): TableCellRenderer -{ - private val colors = listOf(Color.RED, Color.GREEN, Color.CYAN, Color.YELLOW, DartsColour.PURPLE, DartsColour.ORANGE) +class TeamRenderer( + private val baseRenderer: TableCellRenderer, + private val teamsEnabled: () -> Boolean +) : TableCellRenderer { + private val colors = + listOf( + Color.RED, + Color.GREEN, + Color.CYAN, + Color.YELLOW, + DartsColour.PURPLE, + DartsColour.ORANGE + ) - override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { - val c = baseRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) as JComponent + override fun getTableCellRendererComponent( + table: JTable?, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { + val c = + baseRenderer.getTableCellRendererComponent( + table, + value, + isSelected, + hasFocus, + row, + column + ) as JComponent - val inBounds = row/2 < colors.size - if (teamsEnabled() && inBounds) - { - val rawColour = colors[row/2] + val inBounds = row / 2 < colors.size + if (teamsEnabled() && inBounds) { + val rawColour = colors[row / 2] c.background = if (isSelected) rawColour else rawColour?.translucent() c.foreground = Color.BLACK @@ -30,12 +53,10 @@ class TeamRenderer(private val baseRenderer: TableCellRenderer, private val team val lineBorder = MatteBorder(0, 0, row % 2, 0, Color.BLACK) val padBorder = EmptyBorder(0, padding, 0, 0) c.border = CompoundBorder(lineBorder, padBorder) - } - else if (!isSelected) - { + } else if (!isSelected) { c.background = null } return c } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/bean/X01ScoreRenderer.kt b/src/main/kotlin/dartzee/bean/X01ScoreRenderer.kt index 77382c5c0..6f820ce54 100644 --- a/src/main/kotlin/dartzee/bean/X01ScoreRenderer.kt +++ b/src/main/kotlin/dartzee/bean/X01ScoreRenderer.kt @@ -4,18 +4,15 @@ import dartzee.core.bean.AbstractTableRenderer import dartzee.utils.DartsColour import java.awt.Color -class X01ScoreRenderer : AbstractTableRenderer() -{ +class X01ScoreRenderer : AbstractTableRenderer() { override fun getReplacementValue(value: Int) = value - override fun setCellColours(typedValue: Int?, isSelected: Boolean) - { + override fun setCellColours(typedValue: Int?, isSelected: Boolean) { val score = typedValue!! var fg = DartsColour.getScorerForegroundColour(score.toDouble()) var bg = DartsColour.getScorerBackgroundColour(score.toDouble()) - if (isSelected) - { + if (isSelected) { fg = Color.WHITE bg = DartsColour.getDarkenedColour(bg) } diff --git a/src/main/kotlin/dartzee/core/bean/AbstractDevScreen.kt b/src/main/kotlin/dartzee/core/bean/AbstractDevScreen.kt index fe3433194..f43074271 100644 --- a/src/main/kotlin/dartzee/core/bean/AbstractDevScreen.kt +++ b/src/main/kotlin/dartzee/core/bean/AbstractDevScreen.kt @@ -8,41 +8,32 @@ import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.KeyStroke -abstract class AbstractDevScreen(private val commandBar: CheatBar) : FocusableWindow() -{ - init - { +abstract class AbstractDevScreen(private val commandBar: CheatBar) : FocusableWindow() { + init { commandBar.setCheatListener(this) } - /** - * Abstract methods - */ + /** Abstract methods */ abstract fun commandsEnabled(): Boolean + abstract fun processCommand(cmd: String): String - /** - * Regular methods - */ - fun enableCheatBar(enable: Boolean) - { + /** Regular methods */ + fun enableCheatBar(enable: Boolean) { commandBar.isVisible = enable repaint() revalidate() } - - fun getKeyStrokeForCommandBar(): KeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SEMICOLON, InputEvent.CTRL_DOWN_MASK) - fun processCommandWithTry(cmd: String): String - { + fun getKeyStrokeForCommandBar(): KeyStroke = + KeyStroke.getKeyStroke(KeyEvent.VK_SEMICOLON, InputEvent.CTRL_DOWN_MASK) + + fun processCommandWithTry(cmd: String): String { logger.info(CODE_COMMAND_ENTERED, "Command entered: [$cmd]") - return try - { + return try { processCommand(cmd) - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_COMMAND_ERROR, "Error running command $cmd", t) "" } diff --git a/src/main/kotlin/dartzee/core/bean/AbstractTableRenderer.kt b/src/main/kotlin/dartzee/core/bean/AbstractTableRenderer.kt index 721d8e721..bd017316c 100644 --- a/src/main/kotlin/dartzee/core/bean/AbstractTableRenderer.kt +++ b/src/main/kotlin/dartzee/core/bean/AbstractTableRenderer.kt @@ -7,17 +7,21 @@ import javax.swing.JTable import javax.swing.table.DefaultTableCellRenderer /** - * Abstract extension of DefaultTableCellRenderer to allow parameterisation using generics. - * Also provides a place to do extra checks (e.g. null values). + * Abstract extension of DefaultTableCellRenderer to allow parameterisation using generics. Also + * provides a place to do extra checks (e.g. null values). */ -abstract class AbstractTableRenderer : DefaultTableCellRenderer() -{ +abstract class AbstractTableRenderer : DefaultTableCellRenderer() { abstract fun getReplacementValue(value: E): Any - override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { - try - { + override fun getTableCellRendererComponent( + table: JTable?, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { + try { @Suppress("UNCHECKED_CAST") val typedValue = value as E? val newValue = getReplacementValue(typedValue, row, column) @@ -27,35 +31,35 @@ abstract class AbstractTableRenderer : DefaultTableCellRenderer() setCellColours(typedValue, isSelected) val rowHeight = getRowHeight() - if (rowHeight > -1) - { + if (rowHeight > -1) { table?.rowHeight = rowHeight } - //For ButtonRenderer. If we're actually a component, then return the component itself (otherwise we just call toString() - //on w/e object it is, which doesn't work) - if (newValue is Component) - { + // For ButtonRenderer. If we're actually a component, then return the component itself + // (otherwise we just call toString() + // on w/e object it is, which doesn't work) + if (newValue is Component) { return newValue } - } - catch (t: Throwable) - { - logger.error(CODE_RENDER_ERROR, "Error rendering row [$row], col [$column]. Value [$value]", t) + } catch (t: Throwable) { + logger.error( + CODE_RENDER_ERROR, + "Error rendering row [$row], col [$column]. Value [$value]", + t + ) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) } return this } - - private fun getReplacementValue(typedValue: E?, row: Int, column: Int): Any? - { - if (typedValue == null) - { - if (!allowNulls()) - { - logger.error(CODE_RENDER_ERROR, "NULL element in table at row [$row] and column [$column]") + private fun getReplacementValue(typedValue: E?, row: Int, column: Int): Any? { + if (typedValue == null) { + if (!allowNulls()) { + logger.error( + CODE_RENDER_ERROR, + "NULL element in table at row [$row] and column [$column]" + ) } return "" @@ -64,19 +68,16 @@ abstract class AbstractTableRenderer : DefaultTableCellRenderer() return getReplacementValue(typedValue) } - - /** - * Default methods - */ + /** Default methods */ open fun allowNulls() = false + open fun getRowHeight() = -1 - open fun setCellColours(typedValue: E?, isSelected: Boolean) - { - //do nothing + + open fun setCellColours(typedValue: E?, isSelected: Boolean) { + // do nothing } - open fun setFontsAndAlignment() - { - //do nothing + open fun setFontsAndAlignment() { + // do nothing } } diff --git a/src/main/kotlin/dartzee/core/bean/ButtonColumn.kt b/src/main/kotlin/dartzee/core/bean/ButtonColumn.kt index 7ad748bd1..c93c00bd2 100644 --- a/src/main/kotlin/dartzee/core/bean/ButtonColumn.kt +++ b/src/main/kotlin/dartzee/core/bean/ButtonColumn.kt @@ -18,20 +18,17 @@ import javax.swing.table.TableCellEditor import javax.swing.table.TableCellRenderer /** - * The ButtonColumn class provides a renderer and an editor that looks like a - * JButton. The renderer and editor will then be used for a specified column - * in the table. The TableModel will contain the String to be displayed on - * the button. + * The ButtonColumn class provides a renderer and an editor that looks like a JButton. The renderer + * and editor will then be used for a specified column in the table. The TableModel will contain the + * String to be displayed on the button. * - * The button can be invoked by a mouse click or by pressing the space bar - * when the cell has focus. Optionally a mnemonic can be set to invoke the - * button. When the button is invoked the provided Action is invoked. The - * source of the Action will be the table. The action command will contain + * The button can be invoked by a mouse click or by pressing the space bar when the cell has focus. + * Optionally a mnemonic can be set to invoke the button. When the button is invoked the provided + * Action is invoked. The source of the Action will be the table. The action command will contain * the model row number of the button that was clicked. - * */ -class ButtonColumn(private val table: ScrollTable, private val action: Action, column: Int) : AbstractCellEditor(), TableCellRenderer, TableCellEditor, ActionListener, IMouseListener -{ +class ButtonColumn(private val table: ScrollTable, private val action: Action, column: Int) : + AbstractCellEditor(), TableCellRenderer, TableCellEditor, ActionListener, IMouseListener { private val originalBorder: Border private val renderButton = JButton() @@ -39,8 +36,7 @@ class ButtonColumn(private val table: ScrollTable, private val action: Action, c private var editorValue: Any? = null private var isButtonColumnEditor: Boolean = false - init - { + init { editButton.isFocusPainted = false editButton.addActionListener(this) originalBorder = editButton.border @@ -52,10 +48,14 @@ class ButtonColumn(private val table: ScrollTable, private val action: Action, c table.addMouseListener(this) } - override fun getTableCellEditorComponent(table: JTable, value: Any?, isSelected: Boolean, row: Int, column: Int): Component - { - when (value) - { + override fun getTableCellEditorComponent( + table: JTable, + value: Any?, + isSelected: Boolean, + row: Int, + column: Int + ): Component { + when (value) { null -> editButton.clear() is Icon -> editButton.icon = value else -> editButton.text = "$value" @@ -64,26 +64,27 @@ class ButtonColumn(private val table: ScrollTable, private val action: Action, c this.editorValue = value return editButton } - private fun JButton.clear() - { + + private fun JButton.clear() { text = "" icon = null } override fun getCellEditorValue() = editorValue - /** - * TableCellRenderer - */ - override fun getTableCellRendererComponent(table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { - if (isSelected) - { + /** TableCellRenderer */ + override fun getTableCellRendererComponent( + table: JTable, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { + if (isSelected) { renderButton.foreground = table.selectionForeground renderButton.background = table.selectionBackground - } - else - { + } else { renderButton.foreground = table.foreground renderButton.background = UIManager.getColor("Button.background") } @@ -92,8 +93,7 @@ class ButtonColumn(private val table: ScrollTable, private val action: Action, c table.rowHeight = 40 - when (value) - { + when (value) { null -> renderButton.clear() is Icon -> renderButton.icon = value else -> renderButton.text = "$value" @@ -102,11 +102,8 @@ class ButtonColumn(private val table: ScrollTable, private val action: Action, c return renderButton } - /** - * ActionListener - */ - override fun actionPerformed(e: ActionEvent) - { + /** ActionListener */ + override fun actionPerformed(e: ActionEvent) { val row = table.convertRowIndexToModel(table.editingRow) fireEditingStopped() @@ -115,22 +112,17 @@ class ButtonColumn(private val table: ScrollTable, private val action: Action, c action.actionPerformed(event) } - /** - * When the mouse is pressed the editor is invoked. If you then drag - * the mouse to another cell before releasing it, the editor is still - * active. Make sure editing is stopped when the mouse is released. + * When the mouse is pressed the editor is invoked. If you then drag the mouse to another cell + * before releasing it, the editor is still active. Make sure editing is stopped when the mouse + * is released. */ - override fun mousePressed(e: MouseEvent) - { - if (table.isEditing && table.cellEditor === this) - isButtonColumnEditor = true + override fun mousePressed(e: MouseEvent) { + if (table.isEditing && table.cellEditor === this) isButtonColumnEditor = true } - override fun mouseReleased(e: MouseEvent) - { - if (isButtonColumnEditor && table.isEditing) - table.cellEditor.stopCellEditing() + override fun mouseReleased(e: MouseEvent) { + if (isButtonColumnEditor && table.isEditing) table.cellEditor.stopCellEditing() isButtonColumnEditor = false } diff --git a/src/main/kotlin/dartzee/core/bean/CheatBar.kt b/src/main/kotlin/dartzee/core/bean/CheatBar.kt index d5b79577f..20085a67a 100644 --- a/src/main/kotlin/dartzee/core/bean/CheatBar.kt +++ b/src/main/kotlin/dartzee/core/bean/CheatBar.kt @@ -9,12 +9,10 @@ import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JTextField -class CheatBar : JTextField(), ActionListener -{ +class CheatBar : JTextField(), ActionListener { private lateinit var listener: AbstractDevScreen - init - { + init { border = null isOpaque = false isVisible = false @@ -23,8 +21,7 @@ class CheatBar : JTextField(), ActionListener addActionListener(this) } - fun setCheatListener(listener: AbstractDevScreen) - { + fun setCheatListener(listener: AbstractDevScreen) { this.listener = listener val triggerStroke = listener.getKeyStrokeForCommandBar() @@ -34,31 +31,27 @@ class CheatBar : JTextField(), ActionListener inputMap.put(triggerStroke, "showCheatBar") val actionMap = content.actionMap - actionMap.put("showCheatBar", object : AbstractAction() - { - override fun actionPerformed(e: ActionEvent) - { - if (listener.commandsEnabled()) - { - listener.enableCheatBar(true) - EventQueue.invokeLater { grabFocus() } + actionMap.put( + "showCheatBar", + object : AbstractAction() { + override fun actionPerformed(e: ActionEvent) { + if (listener.commandsEnabled()) { + listener.enableCheatBar(true) + EventQueue.invokeLater { grabFocus() } + } } } - }) + ) } - override fun actionPerformed(arg0: ActionEvent) - { + override fun actionPerformed(arg0: ActionEvent) { val text = text setText(null) val result = listener.processCommandWithTry(text) - if (result.isEmpty()) - { + if (result.isEmpty()) { listener.enableCheatBar(false) - } - else - { + } else { setText(result) } } diff --git a/src/main/kotlin/dartzee/core/bean/ColourPicker.kt b/src/main/kotlin/dartzee/core/bean/ColourPicker.kt index 43c29cda7..51258f462 100644 --- a/src/main/kotlin/dartzee/core/bean/ColourPicker.kt +++ b/src/main/kotlin/dartzee/core/bean/ColourPicker.kt @@ -11,29 +11,25 @@ import javax.swing.ImageIcon import javax.swing.JLabel import javax.swing.border.LineBorder -class ColourPicker : JLabel(), IMouseListener -{ +class ColourPicker : JLabel(), IMouseListener { var selectedColour: Color = Color.BLACK private set private var listener: ColourSelectionListener? = null private val img: BufferedImage = BufferedImage(45, 30, BufferedImage.TYPE_INT_ARGB) - init - { + init { border = LineBorder(Color(0, 0, 0)) setSize(45, 30) isOpaque = true addMouseListener(this) } - fun addColourSelectionListener(listener: ColourSelectionListener?) - { + fun addColourSelectionListener(listener: ColourSelectionListener?) { this.listener = listener } - fun updateSelectedColor(newColor: Color?, notify: Boolean = true) - { + fun updateSelectedColor(newColor: Color?, notify: Boolean = true) { newColor ?: return this.selectedColour = newColor @@ -49,19 +45,16 @@ class ColourPicker : JLabel(), IMouseListener fun getPrefString() = DartsColour.toPrefStr(selectedColour) - override fun mouseReleased(e: MouseEvent) - { + override fun mouseReleased(e: MouseEvent) { val newColour = InjectedDesktopCore.colourSelector.selectColour(selectedColour) updateSelectedColor(newColour) } - override fun mouseEntered(e: MouseEvent) - { + override fun mouseEntered(e: MouseEvent) { cursor = Cursor(Cursor.HAND_CURSOR) } - override fun mouseExited(e: MouseEvent) - { + override fun mouseExited(e: MouseEvent) { cursor = Cursor(Cursor.DEFAULT_CURSOR) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/ColourSelectionListener.kt b/src/main/kotlin/dartzee/core/bean/ColourSelectionListener.kt index 1fdcb536a..ad626ff12 100644 --- a/src/main/kotlin/dartzee/core/bean/ColourSelectionListener.kt +++ b/src/main/kotlin/dartzee/core/bean/ColourSelectionListener.kt @@ -2,7 +2,6 @@ package dartzee.core.bean import java.awt.Color -interface ColourSelectionListener -{ +interface ColourSelectionListener { fun colourSelected(colour: Color) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/ComboBoxItem.kt b/src/main/kotlin/dartzee/core/bean/ComboBoxItem.kt index 7b73efa29..e849558df 100644 --- a/src/main/kotlin/dartzee/core/bean/ComboBoxItem.kt +++ b/src/main/kotlin/dartzee/core/bean/ComboBoxItem.kt @@ -1,6 +1,6 @@ package dartzee.core.bean -data class ComboBoxItem(val hiddenData: E, val visibleData: Any, var isEnabled: Boolean = true) -{ - override fun toString() = if (isEnabled) "$visibleData" else "$visibleData" +data class ComboBoxItem(val hiddenData: E, val visibleData: Any, var isEnabled: Boolean = true) { + override fun toString() = + if (isEnabled) "$visibleData" else "$visibleData" } diff --git a/src/main/kotlin/dartzee/core/bean/ComboBoxNumberComparison.kt b/src/main/kotlin/dartzee/core/bean/ComboBoxNumberComparison.kt index 854fc2c25..a5f88db4a 100644 --- a/src/main/kotlin/dartzee/core/bean/ComboBoxNumberComparison.kt +++ b/src/main/kotlin/dartzee/core/bean/ComboBoxNumberComparison.kt @@ -1,29 +1,25 @@ package dartzee.core.bean import java.awt.Dimension - import javax.swing.DefaultComboBoxModel import javax.swing.JComboBox -class ComboBoxNumberComparison : JComboBox() -{ - private val filterModes = arrayOf(FILTER_MODE_EQUAL_TO, FILTER_MODE_GREATER_THAN, FILTER_MODE_LESS_THAN) +class ComboBoxNumberComparison : JComboBox() { + private val filterModes = + arrayOf(FILTER_MODE_EQUAL_TO, FILTER_MODE_GREATER_THAN, FILTER_MODE_LESS_THAN) private val comboModel = DefaultComboBoxModel(filterModes) - init - { + init { model = comboModel preferredSize = Dimension(40, 30) maximumSize = Dimension(40, 30) } - fun addOption(option: String) - { + fun addOption(option: String) { comboModel.addElement(option) } - companion object - { + companion object { const val FILTER_MODE_EQUAL_TO = "=" const val FILTER_MODE_GREATER_THAN = ">" const val FILTER_MODE_LESS_THAN = "<" diff --git a/src/main/kotlin/dartzee/core/bean/DateFilterPanel.kt b/src/main/kotlin/dartzee/core/bean/DateFilterPanel.kt index 08d2708d7..92d125278 100644 --- a/src/main/kotlin/dartzee/core/bean/DateFilterPanel.kt +++ b/src/main/kotlin/dartzee/core/bean/DateFilterPanel.kt @@ -9,8 +9,7 @@ import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants -class DateFilterPanel : JPanel() -{ +class DateFilterPanel : JPanel() { private val dtFormat = SimpleDateFormat("dd/MM/yyyy") val cbDateFrom = DatePicker(makeDatePickerSettings()) @@ -18,8 +17,7 @@ class DateFilterPanel : JPanel() private val lblFrom = JLabel("from") private val lblTo = JLabel("to") - init - { + init { add(lblFrom) lblFrom.horizontalAlignment = SwingConstants.LEFT add(cbDateFrom) @@ -28,15 +26,12 @@ class DateFilterPanel : JPanel() add(cbDateTo) } - fun valid(): Boolean - { - if (!cbDateFrom.isEnabled) - { + fun valid(): Boolean { + if (!cbDateFrom.isEnabled) { return true } - if (getDtFrom().isAfter(getDtTo())) - { + if (getDtFrom().isAfter(getDtTo())) { showErrorOLD("The 'date from' cannot be after the 'date to'") return false } @@ -44,17 +39,20 @@ class DateFilterPanel : JPanel() return true } - fun filterSqlDate(sqlDt: Timestamp) = !sqlDt.before(getSqlDtFrom()) && !sqlDt.after(getSqlDtTo()) + fun filterSqlDate(sqlDt: Timestamp) = + !sqlDt.before(getSqlDtFrom()) && !sqlDt.after(getSqlDtTo()) + fun getSqlDtFrom(): Timestamp = Timestamp.valueOf(getDtFrom()) + fun getSqlDtTo(): Timestamp = Timestamp.valueOf(getDtTo()) fun getFilterDesc() = "${dtFormat.format(getSqlDtFrom())} - ${dtFormat.format(getSqlDtTo())}" private fun getDtFrom() = cbDateFrom.date.atTime(0, 0) + private fun getDtTo() = cbDateTo.date.atTime(0, 0) - private fun makeDatePickerSettings(): DatePickerSettings - { + private fun makeDatePickerSettings(): DatePickerSettings { val settings = DatePickerSettings() settings.allowEmptyDates = false @@ -62,4 +60,4 @@ class DateFilterPanel : JPanel() return settings } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/FileUploader.kt b/src/main/kotlin/dartzee/core/bean/FileUploader.kt index ed0a6ef51..4050c6a48 100644 --- a/src/main/kotlin/dartzee/core/bean/FileUploader.kt +++ b/src/main/kotlin/dartzee/core/bean/FileUploader.kt @@ -13,8 +13,7 @@ import javax.swing.JTextField import javax.swing.border.EmptyBorder import javax.swing.filechooser.FileFilter -class FileUploader(ff: FileFilter) : JPanel(), ActionListener -{ +class FileUploader(ff: FileFilter) : JPanel(), ActionListener { private var selectedFile: File? = null private val listeners = mutableListOf() @@ -23,8 +22,7 @@ class FileUploader(ff: FileFilter) : JPanel(), ActionListener private val fc = JFileChooser() private val btnUpload = JButton("Upload") - init - { + init { layout = BorderLayout(0, 0) val filters = fc.choosableFileFilters @@ -48,43 +46,35 @@ class FileUploader(ff: FileFilter) : JPanel(), ActionListener btnUpload.addActionListener(this) } - fun addFileUploadListener(listener: IFileUploadListener) - { + fun addFileUploadListener(listener: IFileUploadListener) { listeners.add(listener) } - private fun selectFile() - { + private fun selectFile() { val returnVal = fc.showOpenDialog(this) val selectedFile = fc.selectedFile - if (returnVal == JFileChooser.APPROVE_OPTION && selectedFile != null) - { + if (returnVal == JFileChooser.APPROVE_OPTION && selectedFile != null) { this.selectedFile = fc.selectedFile textField.text = selectedFile.path } } - private fun uploadPressed() - { + private fun uploadPressed() { val file = selectedFile - if (file == null) - { + if (file == null) { DialogUtil.showErrorOLD("You must select a file to upload.") return } val success = listeners.all { it.fileUploaded(file) } - if (success) - { + if (success) { this.selectedFile = null textField.text = "" } } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnSelectFile -> selectFile() btnUpload -> uploadPressed() } diff --git a/src/main/kotlin/dartzee/core/bean/GhostText.kt b/src/main/kotlin/dartzee/core/bean/GhostText.kt index 5b4f26166..902d95af2 100644 --- a/src/main/kotlin/dartzee/core/bean/GhostText.kt +++ b/src/main/kotlin/dartzee/core/bean/GhostText.kt @@ -7,39 +7,33 @@ import javax.swing.event.DocumentEvent import javax.swing.event.DocumentListener import javax.swing.text.JTextComponent -class GhostText(ghostText: String, component: JTextComponent): JLabel(), DocumentListener -{ - private val document = component.document +class GhostText(ghostText: String, component: JTextComponent) : JLabel(), DocumentListener { + private val document = component.document - init - { + init { text = ghostText font = component.font - foreground = Color(foreground.red, foreground.green, foreground.blue, 127) + foreground = Color(foreground.red, foreground.green, foreground.blue, 127) border = EmptyBorder(component.insets) horizontalAlignment = LEADING - document.addDocumentListener(this) + document.addDocumentListener(this) - toggleVisibility() - } + toggleVisibility() + } - private fun toggleVisibility() - { - isVisible = document.length == 0 - } + private fun toggleVisibility() { + isVisible = document.length == 0 + } - /** - * DocumentListener - */ - override fun insertUpdate(e: DocumentEvent) - { - toggleVisibility() - } + /** DocumentListener */ + override fun insertUpdate(e: DocumentEvent) { + toggleVisibility() + } + + override fun removeUpdate(e: DocumentEvent) { + toggleVisibility() + } - override fun removeUpdate(e: DocumentEvent) - { - toggleVisibility() - } override fun changedUpdate(e: DocumentEvent?) {} -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/HyperlinkAdaptor.kt b/src/main/kotlin/dartzee/core/bean/HyperlinkAdaptor.kt index 8cea77755..be7312ee8 100644 --- a/src/main/kotlin/dartzee/core/bean/HyperlinkAdaptor.kt +++ b/src/main/kotlin/dartzee/core/bean/HyperlinkAdaptor.kt @@ -5,42 +5,32 @@ import java.awt.Cursor import java.awt.event.MouseAdapter import java.awt.event.MouseEvent -class HyperlinkAdaptor(private val listener: IHyperlinkListener) : MouseAdapter() -{ +class HyperlinkAdaptor(private val listener: IHyperlinkListener) : MouseAdapter() { private val listenerWindow = listener as Component override fun mouseClicked(arg0: MouseEvent) = listener.linkClicked(arg0) - override fun mouseMoved(arg0: MouseEvent) - { - if (listener.isOverHyperlink(arg0)) - { + override fun mouseMoved(arg0: MouseEvent) { + if (listener.isOverHyperlink(arg0)) { listenerWindow.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) - } - else - { + } else { listenerWindow.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) } } - override fun mouseEntered(e: MouseEvent) - { - if (listener.isOverHyperlink(e)) - { + override fun mouseEntered(e: MouseEvent) { + if (listener.isOverHyperlink(e)) { listenerWindow.cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) } } - override fun mouseDragged(e: MouseEvent?) - { - if (listenerWindow.cursor.type == Cursor.HAND_CURSOR) - { + override fun mouseDragged(e: MouseEvent?) { + if (listenerWindow.cursor.type == Cursor.HAND_CURSOR) { listenerWindow.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) } } - override fun mouseExited(arg0: MouseEvent?) - { + override fun mouseExited(arg0: MouseEvent?) { listenerWindow.cursor = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) } } diff --git a/src/main/kotlin/dartzee/core/bean/IColourSelector.kt b/src/main/kotlin/dartzee/core/bean/IColourSelector.kt index 024031b18..ecc61efcd 100644 --- a/src/main/kotlin/dartzee/core/bean/IColourSelector.kt +++ b/src/main/kotlin/dartzee/core/bean/IColourSelector.kt @@ -2,7 +2,6 @@ package dartzee.core.bean import java.awt.Color -interface IColourSelector -{ +interface IColourSelector { fun selectColour(initialColour: Color): Color -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/IDoubleClickListener.kt b/src/main/kotlin/dartzee/core/bean/IDoubleClickListener.kt index 03d04583a..cf1f09748 100644 --- a/src/main/kotlin/dartzee/core/bean/IDoubleClickListener.kt +++ b/src/main/kotlin/dartzee/core/bean/IDoubleClickListener.kt @@ -2,7 +2,6 @@ package dartzee.core.bean import java.awt.Component -interface IDoubleClickListener -{ +interface IDoubleClickListener { fun doubleClicked(source: Component) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/IFileUploadListener.kt b/src/main/kotlin/dartzee/core/bean/IFileUploadListener.kt index 1e7e34650..ef7b68fd4 100644 --- a/src/main/kotlin/dartzee/core/bean/IFileUploadListener.kt +++ b/src/main/kotlin/dartzee/core/bean/IFileUploadListener.kt @@ -2,7 +2,6 @@ package dartzee.core.bean import java.io.File -interface IFileUploadListener -{ +interface IFileUploadListener { fun fileUploaded(file: File): Boolean } diff --git a/src/main/kotlin/dartzee/core/bean/IHyperlinkListener.kt b/src/main/kotlin/dartzee/core/bean/IHyperlinkListener.kt index 69a3e7482..a9e31b4f1 100644 --- a/src/main/kotlin/dartzee/core/bean/IHyperlinkListener.kt +++ b/src/main/kotlin/dartzee/core/bean/IHyperlinkListener.kt @@ -2,8 +2,8 @@ package dartzee.core.bean import java.awt.event.MouseEvent -interface IHyperlinkListener -{ +interface IHyperlinkListener { fun linkClicked(arg0: MouseEvent) + fun isOverHyperlink(arg0: MouseEvent): Boolean -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/LinkLabel.kt b/src/main/kotlin/dartzee/core/bean/LinkLabel.kt index b88282aa2..17cd5626c 100644 --- a/src/main/kotlin/dartzee/core/bean/LinkLabel.kt +++ b/src/main/kotlin/dartzee/core/bean/LinkLabel.kt @@ -4,10 +4,9 @@ import java.awt.Color import java.awt.event.MouseEvent import javax.swing.JLabel -class LinkLabel(text: String, private val linkClicked: () -> Unit): JLabel("$text"), IHyperlinkListener -{ - init - { +class LinkLabel(text: String, private val linkClicked: () -> Unit) : + JLabel("$text"), IHyperlinkListener { + init { foreground = Color.BLUE val adaptor = HyperlinkAdaptor(this) @@ -16,5 +15,6 @@ class LinkLabel(text: String, private val linkClicked: () -> Unit): JLabel("() private val scrollPane = JScrollPane() - val table: JTable = object : JTable() { - override fun isCellEditable(arg0: Int, arg1: Int) = isEditable(arg0, arg1) - } + val table: JTable = + object : JTable() { + override fun isCellEditable(arg0: Int, arg1: Int) = isEditable(arg0, arg1) + } val lblRowCount = JLabel("") private val panelRowCount = JPanel() - private val tableFooter: JTable = object : JTable() { - override fun isCellEditable(row: Int, column: Int) = false - } + private val tableFooter: JTable = + object : JTable() { + override fun isCellEditable(row: Int, column: Int) = false + } private val panelCenter = JPanel() - init - { + init { layout = BorderLayout(0, 0) table.columnModel.addColumnModelListener(this) table.addMouseListener(this) @@ -81,9 +81,7 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList addKeyAction(KeyEvent.VK_DOWN) { val row = table.selectedRow - if (row == table.rowCount - 1 - && tableFooter.isVisible - ) { + if (row == table.rowCount - 1 && tableFooter.isVisible) { selectRow(TABLE_ROW_FOOTER) tableFooter.requestFocus() } else if (row < table.rowCount - 1) { @@ -97,7 +95,7 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList } } - //Initialise our footer model in preparation + // Initialise our footer model in preparation open var model: DefaultTableModel get() = table.model as DefaultTableModel set(model) { @@ -106,7 +104,7 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList rowSorter = TableRowSorter(model) table.rowSorter = rowSorter } - //Initialise our footer model in preparation + // Initialise our footer model in preparation val footerModel = DefaultModel() for (i in 0 until model.columnCount) { footerModel.addColumn("") @@ -115,61 +113,53 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList refreshRowCount() } - fun addRow(row: List<*>) - { + fun addRow(row: List<*>) { addRow(row.toTypedArray()) } - fun addRow(row: Array<*>) - { + + fun addRow(row: Array<*>) { model.addRow(row) refreshRowCount() } - fun insertRow(row: Array?, index: Int) - { + fun insertRow(row: Array?, index: Int) { model.insertRow(index, row) refreshRowCount() } - fun addColumn(columnName: String?) - { + fun addColumn(columnName: String?) { model.addColumn(columnName) val footerModel = tableFooter.model as DefaultTableModel footerModel.addColumn(columnName) } - private fun refreshRowCount() - { + private fun refreshRowCount() { val rows = table.rowCount val rowCountDesc = getRowCountDesc(rows) lblRowCount.text = rowCountDesc } - private fun getRowCountDesc(rows: Int): String - { - val rowName = when - { - rows == 1 -> rowNameSingular - rowNamePlural != null -> rowNamePlural - else -> "${rowNameSingular}s" - } + private fun getRowCountDesc(rows: Int): String { + val rowName = + when { + rows == 1 -> rowNameSingular + rowNamePlural != null -> rowNamePlural + else -> "${rowNameSingular}s" + } return "$rows $rowName" } - fun setRowName(rowNameSingular: String, rowNamePlural: String? = null) - { + fun setRowName(rowNameSingular: String, rowNamePlural: String? = null) { this.rowNameSingular = rowNameSingular this.rowNamePlural = rowNamePlural } - fun setShowRowCount(show: Boolean) - { + fun setShowRowCount(show: Boolean) { panelRowCount.isVisible = show } - fun setRowCountAlignment(alignment: Int) - { + fun setRowCountAlignment(alignment: Int) { lblRowCount.horizontalAlignment = alignment } @@ -192,12 +182,14 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList table.rowHeight = height } - fun getNonNullValueAt(row: Int, col: Int) = getValueAt(row, col) ?: throw Exception("NULL value at row $row, col $col") + fun getNonNullValueAt(row: Int, col: Int) = + getValueAt(row, col) ?: throw Exception("NULL value at row $row, col $col") - fun getValueAt(row: Int, col: Int): Any? = when (row) { - TABLE_ROW_FOOTER -> tableFooter.getValueAt(0, col) - else -> model.getValueAt(row, col) - } + fun getValueAt(row: Int, col: Int): Any? = + when (row) { + TABLE_ROW_FOOTER -> tableFooter.getValueAt(0, col) + else -> model.getValueAt(row, col) + } fun setPreferredScrollableViewportSize(dim: Dimension?) { table.preferredScrollableViewportSize = dim @@ -229,48 +221,39 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList fun convertRowIndexToModel(viewRowIndex: Int) = table.convertRowIndexToModel(viewRowIndex) - fun setTableFont(font: Font) - { + fun setTableFont(font: Font) { this.font = font table.font = font } - /** - * Helpers - */ - fun sortBy(columnIndex: Int, desc: Boolean) - { + /** Helpers */ + fun sortBy(columnIndex: Int, desc: Boolean) { rowSorter?.let { it.toggleSortOrder(columnIndex) if (desc) it.toggleSortOrder(columnIndex) } } - fun setTableRenderer(renderer: TableCellRenderer) - { + fun setTableRenderer(renderer: TableCellRenderer) { table.setDefaultRenderer(Object::class.java, renderer) } fun getBuiltInRenderer(): TableCellRenderer = table.getDefaultRenderer(Object::class.java) - fun setRenderer(columnIndex: Int, renderer: TableCellRenderer?) - { + fun setRenderer(columnIndex: Int, renderer: TableCellRenderer?) { val column = getColumn(columnIndex) column.cellRenderer = renderer val footerColumn = tableFooter.columnModel.getColumn(columnIndex) footerColumn.cellRenderer = renderer } - fun setComparator(columnIndex: Int, comp: Comparator) - { + fun setComparator(columnIndex: Int, comp: Comparator) { rowSorter?.setComparator(columnIndex, comp) } - fun setColumnWidths(colStr: String) - { + fun setColumnWidths(colStr: String) { val columnWidths = colStr.split(";") - for (i in columnWidths.indices) - { + for (i in columnWidths.indices) { val colWidthStr = columnWidths[i] val colWidth = getColWidthForString(colWidthStr) @@ -280,18 +263,19 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList setWidthForColumn(tableFooter.columnModel.getColumn(i), colWidth) } } - private fun setWidthForColumn(column: TableColumn, colWidth: Int) - { + + private fun setWidthForColumn(column: TableColumn, colWidth: Int) { column.preferredWidth = colWidth column.maxWidth = colWidth } - private fun getColWidthForString(colWidthStr: String) = when(colWidthStr) { - COL_WIDTH_STRING_DT -> COL_WIDTH_DT - else -> colWidthStr.toInt() - } - fun disableSorting() - { + private fun getColWidthForString(colWidthStr: String) = + when (colWidthStr) { + COL_WIDTH_STRING_DT -> COL_WIDTH_DT + else -> colWidthStr.toInt() + } + + fun disableSorting() { table.rowSorter = null sortingEnabled = false } @@ -329,21 +313,21 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList } val selectedViewRow: Int - get() = if (footerRowSelected()) { - TABLE_ROW_FOOTER - } else table.selectedRow + get() = + if (footerRowSelected()) { + TABLE_ROW_FOOTER + } else table.selectedRow fun selectFirstRow() { selectRow(0) } fun selectRow(row: Int) { - if (table.rowCount == 0) { //Nothing to select + if (table.rowCount == 0) { // Nothing to select return } - when (row) - { + when (row) { -1 -> table.clearSelection() TABLE_ROW_FOOTER -> tableFooter.setRowSelectionInterval(0, 0) else -> { @@ -368,19 +352,13 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList } fun scrollToBottom() { - SwingUtilities.invokeLater { - scrollPane.scrollToBottom() - } + SwingUtilities.invokeLater { scrollPane.scrollToBottom() } } - /** - * Default methods - */ + /** Default methods */ open fun isEditable(row: Int, col: Int) = false - /** - * TableColumnModelListener - */ + /** TableColumnModelListener */ override fun columnAdded(e: TableColumnModelEvent) {} override fun columnMarginChanged(e: ChangeEvent) { @@ -398,16 +376,14 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList } override fun columnMoved(e: TableColumnModelEvent) {} + override fun columnRemoved(e: TableColumnModelEvent) {} + override fun columnSelectionChanged(e: ListSelectionEvent) {} - /** - * ListSelectionListener - */ - override fun valueChanged(e: ListSelectionEvent) - { - when (e.source) - { + /** ListSelectionListener */ + override fun valueChanged(e: ListSelectionEvent) { + when (e.source) { table.selectionModel -> updateSelection(table, tableFooter) else -> updateSelection(tableFooter, table) } @@ -415,20 +391,22 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList listeners.forEach { it.selectionChanged(this) } } - private fun updateSelection(src: JTable, dest: JTable) - { + private fun updateSelection(src: JTable, dest: JTable) { val srcRow = src.selectedRow - if (srcRow > -1) { //We've selected something in the source, so need to clear the destination table's selection + if ( + srcRow > -1 + ) { // We've selected something in the source, so need to clear the destination table's + // selection dest.clearSelection() } } - fun addKeyAction(key: Int, fn: () -> Unit) - { - val fullFn = fun () { - if (selectedModelRows.isEmpty()) return - fn() - } + fun addKeyAction(key: Int, fn: () -> Unit) { + val fullFn = + fun() { + if (selectedModelRows.isEmpty()) return + fn() + } table.addKeyAction(key, fullFn) } @@ -441,8 +419,7 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList clickListeners.add(listener) } - fun setTableBorder(border: AbstractBorder) - { + fun setTableBorder(border: AbstractBorder) { scrollPane.border = border table.border = border } @@ -463,10 +440,9 @@ open class ScrollTable(val testId: String = "") : JPanel(), TableColumnModelList } } - companion object - { + companion object { const val TABLE_ROW_FOOTER = -2 private const val COL_WIDTH_STRING_DT = "DT" private const val COL_WIDTH_DT = 115 } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/ScrollTableButton.kt b/src/main/kotlin/dartzee/core/bean/ScrollTableButton.kt index 7ace27867..8a5d8a7a4 100644 --- a/src/main/kotlin/dartzee/core/bean/ScrollTableButton.kt +++ b/src/main/kotlin/dartzee/core/bean/ScrollTableButton.kt @@ -3,19 +3,16 @@ package dartzee.core.bean import javax.swing.Action import javax.swing.table.DefaultTableModel -class ScrollTableButton(tm: DefaultTableModel): ScrollTable() -{ +class ScrollTableButton(tm: DefaultTableModel) : ScrollTable() { private val buttonColumns = mutableListOf() - init - { + init { model = tm } override fun isEditable(row: Int, col: Int) = buttonColumns.contains(col) - fun setButtonColumn(column: Int, action: Action) - { + fun setButtonColumn(column: Int, action: Action) { buttonColumns.add(column) ButtonColumn(this, action, column) } diff --git a/src/main/kotlin/dartzee/core/bean/ScrollTableHyperlink.kt b/src/main/kotlin/dartzee/core/bean/ScrollTableHyperlink.kt index 25991b2c2..d39cecd26 100644 --- a/src/main/kotlin/dartzee/core/bean/ScrollTableHyperlink.kt +++ b/src/main/kotlin/dartzee/core/bean/ScrollTableHyperlink.kt @@ -11,11 +11,11 @@ import javax.swing.table.DefaultTableCellRenderer import javax.swing.table.DefaultTableModel /** - * A scroll table with a 'Game' column. - * Handles rendering this column as a hyperlink to launch it on click. + * A scroll table with a 'Game' column. Handles rendering this column as a hyperlink to launch it on + * click. */ -abstract class ScrollTableHyperlink(private val linkColumnName: String, testId: String = "") : ScrollTable(testId), IHyperlinkListener -{ +abstract class ScrollTableHyperlink(private val linkColumnName: String, testId: String = "") : + ScrollTable(testId), IHyperlinkListener { private var linkColumn = -1 private var adaptor: HyperlinkAdaptor? = null @@ -27,9 +27,8 @@ abstract class ScrollTableHyperlink(private val linkColumnName: String, testId: val linkIndex = model.findColumn(linkColumnName) if (linkIndex > -1) setLinkColumnIndex(linkIndex) - //Init the adaptor if we need to, but only once - if (adaptor == null) - { + // Init the adaptor if we need to, but only once + if (adaptor == null) { adaptor = HyperlinkAdaptor(this) table.addMouseListener(adaptor) @@ -38,26 +37,23 @@ abstract class ScrollTableHyperlink(private val linkColumnName: String, testId: } /** - * Allow direct setting of the game column index, so I can show game hyperlinks within the DartsScorers + * Allow direct setting of the game column index, so I can show game hyperlinks within the + * DartsScorers */ - fun setLinkColumnIndex(ix: Int) - { + fun setLinkColumnIndex(ix: Int) { linkColumn = ix setRenderer(linkColumn, HyperlinkRenderer(tableForeground)) } - override fun isOverHyperlink(arg0: MouseEvent): Boolean - { + override fun isOverHyperlink(arg0: MouseEvent): Boolean { val pt = arg0.point val col = table.columnAtPoint(pt) - if (col != linkColumn) - { + if (col != linkColumn) { return false } val row = table.rowAtPoint(pt) - if (row == -1) - { + if (row == -1) { return false } @@ -65,10 +61,8 @@ abstract class ScrollTableHyperlink(private val linkColumnName: String, testId: return table.getValueAt(actualRow, col) != null } - override fun linkClicked(arg0: MouseEvent) - { - if (!isOverHyperlink(arg0)) - { + override fun linkClicked(arg0: MouseEvent) { + if (!isOverHyperlink(arg0)) { return } @@ -82,38 +76,46 @@ abstract class ScrollTableHyperlink(private val linkColumnName: String, testId: } abstract fun linkClicked(value: Any) + open fun renderValue(value: Any) = "$value" - override fun setCursor(arg0: Cursor) - { + override fun setCursor(arg0: Cursor) { super.setCursor(arg0) table.cursor = arg0 } - private inner class HyperlinkRenderer(color: Color?) : DefaultTableCellRenderer() - { + private inner class HyperlinkRenderer(color: Color?) : DefaultTableCellRenderer() { private var fgColor: Color? = null - init - { - if (color != null) - { + init { + if (color != null) { this.fgColor = color - } else - { + } else { this.fgColor = Color.BLUE } } - override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { - if (value == null) - { + override fun getTableCellRendererComponent( + table: JTable?, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { + if (value == null) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) return this } - super.getTableCellRendererComponent(table, renderValue(value), isSelected, hasFocus, row, column) + super.getTableCellRendererComponent( + table, + renderValue(value), + isSelected, + hasFocus, + row, + column + ) val fontAttributes = HashMap() fontAttributes[TextAttribute.UNDERLINE] = TextAttribute.UNDERLINE_ON diff --git a/src/main/kotlin/dartzee/core/bean/ScrollTableOrdered.kt b/src/main/kotlin/dartzee/core/bean/ScrollTableOrdered.kt index f37105015..7b2f326a2 100644 --- a/src/main/kotlin/dartzee/core/bean/ScrollTableOrdered.kt +++ b/src/main/kotlin/dartzee/core/bean/ScrollTableOrdered.kt @@ -1,7 +1,6 @@ package dartzee.core.bean import dartzee.core.util.InjectedCore -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ActionEvent @@ -11,16 +10,15 @@ import javax.swing.ImageIcon import javax.swing.JButton import javax.swing.JPanel import javax.swing.ListSelectionModel +import net.miginfocom.swing.MigLayout -class ScrollTableOrdered(customButtons: Int = 0) : ScrollTable(), ActionListener -{ +class ScrollTableOrdered(customButtons: Int = 0) : ScrollTable(), ActionListener { val panelOrdering = JPanel() val btnMoveUp = JButton("") val btnMoveDown = JButton("") val btnRandomize = JButton("") - init - { + init { add(panelOrdering, BorderLayout.EAST) panelOrdering.layout = MigLayout("al center center, wrap, gapy 20") btnMoveUp.icon = ImageIcon(javaClass.getResource("/buttons/upArrow.png")) @@ -48,31 +46,24 @@ class ScrollTableOrdered(customButtons: Int = 0) : ScrollTable(), ActionListener btnRandomize.addActionListener(this) } - fun addButtonToOrderingPanel(btn: AbstractButton, row: Int) - { + fun addButtonToOrderingPanel(btn: AbstractButton, row: Int) { btn.preferredSize = Dimension(40, 40) panelOrdering.add(btn, "cell 0 $row") } - /** - * ActionListener - */ - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + /** ActionListener */ + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnMoveUp -> moveSelectedRowUp() btnMoveDown -> moveSelectedRowDown() btnRandomize -> scrambleOrder() } } - private fun moveSelectedRowUp() - { + private fun moveSelectedRowUp() { val row = selectedModelRow - if (row <= 0) - { - //Nothing to do + if (row <= 0) { + // Nothing to do return } @@ -80,12 +71,10 @@ class ScrollTableOrdered(customButtons: Int = 0) : ScrollTable(), ActionListener selectRow(row - 1) } - private fun moveSelectedRowDown() - { + private fun moveSelectedRowDown() { val row = selectedModelRow - if (row == rowCount - 1 || row == -1) - { - //Nothing to do + if (row == rowCount - 1 || row == -1) { + // Nothing to do return } @@ -93,21 +82,18 @@ class ScrollTableOrdered(customButtons: Int = 0) : ScrollTable(), ActionListener selectRow(row + 1) } - private fun scrambleOrder() - { + private fun scrambleOrder() { val shuffled = InjectedCore.collectionShuffler.shuffleCollection(getAllRows()) setNewOrder(shuffled) } - inline fun > reorderRows(crossinline selector: (Array) -> R?) - { + inline fun > reorderRows(crossinline selector: (Array) -> R?) { val newRows = getAllRows().sortedBy(selector) setNewOrder(newRows) } - fun setNewOrder(orderedRows: List>) - { + fun setNewOrder(orderedRows: List>) { removeAllRows() orderedRows.forEach { addRow(it) } @@ -115,8 +101,7 @@ class ScrollTableOrdered(customButtons: Int = 0) : ScrollTable(), ActionListener fun getAllRows(): List> = (0 until rowCount).map(::getRow) - private fun getRow(rowIx: Int): Array - { + private fun getRow(rowIx: Int): Array { val row = arrayOfNulls(columnCount) for (i in 0 until columnCount) { row[i] = getValueAt(rowIx, i) @@ -124,4 +109,4 @@ class ScrollTableOrdered(customButtons: Int = 0) : ScrollTable(), ActionListener return row } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/SwingExtensions.kt b/src/main/kotlin/dartzee/core/bean/SwingExtensions.kt index 66edac7a3..46d5e7f50 100644 --- a/src/main/kotlin/dartzee/core/bean/SwingExtensions.kt +++ b/src/main/kotlin/dartzee/core/bean/SwingExtensions.kt @@ -19,75 +19,74 @@ import javax.swing.JTextField import javax.swing.KeyStroke import javax.swing.text.JTextComponent - fun JComboBox.items() = (0 until model.size).map { model.getElementAt(it) } fun JComboBox.selectedItemTyped(): K = getItemAt(selectedIndex) @Suppress("UNCHECKED_CAST") -fun JComboBox<*>.findByConcreteClass(clazz: Class): T? = items().find { clazz.isInstance(it) } as T? +fun JComboBox<*>.findByConcreteClass(clazz: Class): T? = + items().find { clazz.isInstance(it) } as T? + inline fun JComboBox<*>.findByClass(): T? = items().find { it is T } as T? inline fun JComboBox<*>.selectByClass() = findByClass()?.also { selectedItem = it } -fun JTextField.addUpdateListener(actionListener: ActionListener) -{ +fun JTextField.addUpdateListener(actionListener: ActionListener) { val tf = this - addFocusListener(object: FocusListener - { - override fun focusLost(e: FocusEvent?) - { - val event = ActionEvent(tf, -1, "") - actionListener.actionPerformed(event) + addFocusListener( + object : FocusListener { + override fun focusLost(e: FocusEvent?) { + val event = ActionEvent(tf, -1, "") + actionListener.actionPerformed(event) + } + + override fun focusGained(e: FocusEvent?) {} } - override fun focusGained(e: FocusEvent?){} - }) + ) } fun JTable.addKeyAction(key: Int, fn: () -> Unit) { - val action = object : AbstractAction() { - override fun actionPerformed(e: ActionEvent?) { - fn() + val action = + object : AbstractAction() { + override fun actionPerformed(e: ActionEvent?) { + fn() + } } - } - inputMap.put(KeyStroke.getKeyStroke(key, JComponent.WHEN_FOCUSED),"ACTION_$key") + inputMap.put(KeyStroke.getKeyStroke(key, JComponent.WHEN_FOCUSED), "ACTION_$key") actionMap.put("ACTION_$key", action) } -fun JTextComponent.addGhostText(text: String) -{ +fun JTextComponent.addGhostText(text: String) { this.layout = BorderLayout() this.add(GhostText(text, this)) } -fun Image.toBufferedImage(width: Int, height: Int): BufferedImage -{ +fun Image.toBufferedImage(width: Int, height: Int): BufferedImage { val bi = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB) val g = bi.createGraphics() g.drawImage(this, 0, 0, null) g.dispose() return bi } -fun BufferedImage.paint(fn: (pt: Point) -> Color?) -{ + +fun BufferedImage.paint(fn: (pt: Point) -> Color?) { val pts = getPointList(width, height) val colors = pts.map { fn(it)?.rgb ?: 0 } setRGB(0, 0, width, height, colors.toIntArray(), 0, width) } -fun getPointList(width: Int, height: Int): List -{ + +fun getPointList(width: Int, height: Int): List { val yRange = 0 until height val xRange = 0 until width - return yRange.map { y -> xRange.map { x -> Point(x, y)} }.flatten() + return yRange.map { y -> xRange.map { x -> Point(x, y) } }.flatten() } fun AbstractButton.isSelectedAndEnabled() = isEnabled && isSelected -fun JScrollPane.scrollToBottom() -{ +fun JScrollPane.scrollToBottom() { val vertical = verticalScrollBar vertical.value = vertical.maximum -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/bean/WrapLayout.kt b/src/main/kotlin/dartzee/core/bean/WrapLayout.kt index 7e00f746a..28f599e1f 100644 --- a/src/main/kotlin/dartzee/core/bean/WrapLayout.kt +++ b/src/main/kotlin/dartzee/core/bean/WrapLayout.kt @@ -6,44 +6,38 @@ import java.awt.FlowLayout import javax.swing.JScrollPane import javax.swing.SwingUtilities -/** - * FlowLayout subclass that fully supports wrapping of components. - */ -class WrapLayout : FlowLayout() -{ +/** FlowLayout subclass that fully supports wrapping of components. */ +class WrapLayout : FlowLayout() { /** - * Returns the preferred dimensions for this layout given the - * *visible* components in the specified target container. + * Returns the preferred dimensions for this layout given the *visible* components in the + * specified target container. + * * @param target the component which needs to be laid out - * @return the preferred dimensions to lay out the - * subcomponents of the specified container + * @return the preferred dimensions to lay out the subcomponents of the specified container */ override fun preferredLayoutSize(target: Container) = layoutSize(target, true) /** - * Returns the minimum dimensions needed to layout the *visible* - * components contained in the specified target container. + * Returns the minimum dimensions needed to layout the *visible* components contained in the + * specified target container. + * * @param target the component which needs to be laid out - * @return the minimum dimensions to lay out the - * subcomponents of the specified container + * @return the minimum dimensions to lay out the subcomponents of the specified container */ - override fun minimumLayoutSize(target: Container): Dimension - { + override fun minimumLayoutSize(target: Container): Dimension { val minimum = layoutSize(target, false) minimum.width -= hgap + 1 return minimum } /** - * Returns the minimum or preferred dimension needed to layout the target - * container. + * Returns the minimum or preferred dimension needed to layout the target container. * * @param target target to get layout size for * @param preferred should preferred size be calculated * @return the dimension to layout the target container */ - private fun layoutSize(target: Container, preferred: Boolean): Dimension - { + private fun layoutSize(target: Container, preferred: Boolean): Dimension { synchronized(target.treeLock) { // Each row must fit with the width allocated to the containter. // When the container width = 0, the preferred width of the container @@ -91,9 +85,7 @@ class WrapLayout : FlowLayout() // make sure the preferred size is less than the size of the // target containter so shrinking the container size works // correctly. Removing the horizontal gap is an easy way to do this. - val scrollPane = SwingUtilities.getAncestorOfClass( - JScrollPane::class.java, target - ) + val scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane::class.java, target) if (scrollPane != null && target.isValid) { dim.width -= hgap + 1 } @@ -102,19 +94,18 @@ class WrapLayout : FlowLayout() } /** - * A new row has been completed. Use the dimensions of this row - * to update the preferred size for the container. + * A new row has been completed. Use the dimensions of this row to update the preferred size for + * the container. * * @param dim update the width and height when appropriate * @param rowWidth the width of the row to add * @param rowHeight the height of the row to add */ - private fun addRow(dim: Dimension, rowWidth: Int, rowHeight: Int) - { + private fun addRow(dim: Dimension, rowWidth: Int, rowHeight: Int) { dim.width = maxOf(dim.width, rowWidth) if (dim.height > 0) { dim.height += vgap } dim.height += rowHeight } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/obj/HashMapCount.kt b/src/main/kotlin/dartzee/core/obj/HashMapCount.kt index 8884a4bde..93eb04527 100644 --- a/src/main/kotlin/dartzee/core/obj/HashMapCount.kt +++ b/src/main/kotlin/dartzee/core/obj/HashMapCount.kt @@ -1,11 +1,9 @@ package dartzee.core.obj -class HashMapCount: HashMap() -{ +class HashMapCount : HashMap() { fun getTotalCount() = values.sum() - fun incrementCount(key: K, amount: Int = 1): Int - { + fun incrementCount(key: K, amount: Int = 1): Int { val newVal = getOrDefault(key, 0) + amount this[key] = newVal @@ -14,26 +12,18 @@ class HashMapCount: HashMap() fun getCount(key: K) = get(key) ?: 0 - /** - * Returns {1, 1, 1, 1, 1, 2, 2} from {1 -> 5, 2 -> 2} - */ - fun getFlattenedOrderedList(comparator: Comparator?): List - { + /** Returns {1, 1, 1, 1, 1, 2, 2} from {1 -> 5, 2 -> 2} */ + fun getFlattenedOrderedList(comparator: Comparator?): List { val ret = mutableListOf() val list = ArrayList>(entries) - if (comparator != null) - { - val entryComparator = Comparator>{e1, e2 -> comparator.compare(e1.key, e2.key)} + if (comparator != null) { + val entryComparator = + Comparator> { e1, e2 -> comparator.compare(e1.key, e2.key) } list.sortWith(entryComparator) } - list.forEach{ entry -> - repeat(entry.value) - { - ret.add(entry.key) - } - } + list.forEach { entry -> repeat(entry.value) { ret.add(entry.key) } } return ret } diff --git a/src/main/kotlin/dartzee/core/obj/HashMapList.kt b/src/main/kotlin/dartzee/core/obj/HashMapList.kt index cd193cdd2..957c6039e 100644 --- a/src/main/kotlin/dartzee/core/obj/HashMapList.kt +++ b/src/main/kotlin/dartzee/core/obj/HashMapList.kt @@ -1,14 +1,11 @@ package dartzee.core.obj - -class HashMapList, V> : HashMap>() -{ +class HashMapList, V> : HashMap>() { fun getFlattenedValuesSortedByKey() = entries.sortedBy { it.key }.flatMap { it.value } fun getAllValues() = values.flatten().toList() - fun putInList(key: K, value: V) - { + fun putInList(key: K, value: V) { val list = getOrPut(key, ::mutableListOf) list.add(value) } diff --git a/src/main/kotlin/dartzee/core/obj/LimitedDocument.kt b/src/main/kotlin/dartzee/core/obj/LimitedDocument.kt index a25c3c434..e39ee4af5 100644 --- a/src/main/kotlin/dartzee/core/obj/LimitedDocument.kt +++ b/src/main/kotlin/dartzee/core/obj/LimitedDocument.kt @@ -3,17 +3,14 @@ package dartzee.core.obj import javax.swing.text.AttributeSet import javax.swing.text.PlainDocument -class LimitedDocument(private val limit: Int) : PlainDocument() -{ - override fun insertString(offset: Int, str: String?, attr: AttributeSet?) - { +class LimitedDocument(private val limit: Int) : PlainDocument() { + override fun insertString(offset: Int, str: String?, attr: AttributeSet?) { str ?: return - if (length + str.length > limit) - { + if (length + str.length > limit) { return } super.insertString(offset, str, attr) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/screen/ColourChooserDialog.kt b/src/main/kotlin/dartzee/core/screen/ColourChooserDialog.kt index 304cc4875..c938049db 100644 --- a/src/main/kotlin/dartzee/core/screen/ColourChooserDialog.kt +++ b/src/main/kotlin/dartzee/core/screen/ColourChooserDialog.kt @@ -7,15 +7,13 @@ import java.awt.event.ActionListener import javax.swing.JColorChooser import javax.swing.colorchooser.DefaultColorSelectionModel -class ColourChooserDialog : SimpleDialog(), ActionListener, IColourSelector -{ +class ColourChooserDialog : SimpleDialog(), ActionListener, IColourSelector { var initialColour: Color = Color.BLACK var selectedColour: Color = Color.BLACK val colourChooser = JColorChooser(DefaultColorSelectionModel()) - init - { + init { title = "Choose Colour" setSize(660, 450) contentPane.add(colourChooser) @@ -25,20 +23,17 @@ class ColourChooserDialog : SimpleDialog(), ActionListener, IColourSelector btnCancel.addActionListener(this) } - override fun okPressed() - { + override fun okPressed() { selectedColour = colourChooser.color dispose() } - override fun cancelPressed() - { + override fun cancelPressed() { selectedColour = initialColour dispose() } - override fun selectColour(initialColour: Color): Color - { + override fun selectColour(initialColour: Color): Color { this.initialColour = initialColour colourChooser.color = initialColour @@ -47,4 +42,4 @@ class ColourChooserDialog : SimpleDialog(), ActionListener, IColourSelector return selectedColour } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/screen/LoadingDialog.kt b/src/main/kotlin/dartzee/core/screen/LoadingDialog.kt index 4ab515b9d..71ab484f5 100644 --- a/src/main/kotlin/dartzee/core/screen/LoadingDialog.kt +++ b/src/main/kotlin/dartzee/core/screen/LoadingDialog.kt @@ -1,19 +1,17 @@ package dartzee.core.screen -import net.miginfocom.swing.MigLayout import javax.swing.JDialog import javax.swing.JLabel import javax.swing.JProgressBar import javax.swing.SwingConstants import javax.swing.SwingUtilities import javax.swing.WindowConstants +import net.miginfocom.swing.MigLayout -class LoadingDialog : JDialog() -{ +class LoadingDialog : JDialog() { private val lblMessage = JLabel("Communicating with Server...") - init - { + init { layout = MigLayout("gapy 12px", "[grow]", "[]") setSize(250, 115) setLocationRelativeTo(null) @@ -30,8 +28,7 @@ class LoadingDialog : JDialog() contentPane.add(progressBar, "cell 0 1, alignx center") } - fun showDialog(textToShow: String) - { + fun showDialog(textToShow: String) { val showRunnable = Runnable { lblMessage.text = textToShow isVisible = true @@ -40,10 +37,9 @@ class LoadingDialog : JDialog() SwingUtilities.invokeLater(showRunnable) } - fun dismissDialog() - { + fun dismissDialog() { val hideRunnable = Runnable { isVisible = false } SwingUtilities.invokeLater(hideRunnable) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/screen/ProgressDialog.kt b/src/main/kotlin/dartzee/core/screen/ProgressDialog.kt index 0a6644705..5ba4023a8 100644 --- a/src/main/kotlin/dartzee/core/screen/ProgressDialog.kt +++ b/src/main/kotlin/dartzee/core/screen/ProgressDialog.kt @@ -13,15 +13,14 @@ import javax.swing.SwingUtilities import javax.swing.WindowConstants import javax.swing.border.EmptyBorder -class ProgressDialog(private var workToDo: Int, private var message: String) : JDialog(), ActionListener -{ +class ProgressDialog(private var workToDo: Int, private var message: String) : + JDialog(), ActionListener { private var cancelPressed = false private val progressBar = JProgressBar() private val btnCancel = JButton("Cancel") - init - { + init { val panel = JPanel() panel.border = EmptyBorder(10, 0, 0, 0) contentPane.add(panel, BorderLayout.CENTER) @@ -39,13 +38,11 @@ class ProgressDialog(private var workToDo: Int, private var message: String) : J btnCancel.isVisible = false } - fun setVisibleLater() - { + fun setVisibleLater() { SwingUtilities.invokeLater { isVisible = true } } - fun resetProgress() - { + fun resetProgress() { SwingUtilities.invokeLater { progressBar.minimum = 0 progressBar.maximum = workToDo @@ -54,8 +51,7 @@ class ProgressDialog(private var workToDo: Int, private var message: String) : J } } - fun incrementProgressLater(increment: Int = 1) - { + fun incrementProgressLater(increment: Int = 1) { SwingUtilities.invokeLater { val newValue = progressBar.value + increment progressBar.value = newValue @@ -64,31 +60,25 @@ class ProgressDialog(private var workToDo: Int, private var message: String) : J } } - fun cancelPressed() = cancelPressed - fun disposeLater() - { + fun disposeLater() { SwingUtilities.invokeLater { dispose() } } - override fun actionPerformed(arg0: ActionEvent) - { + override fun actionPerformed(arg0: ActionEvent) { cancelPressed = true } - fun showCancel(showCancel: Boolean) - { + fun showCancel(showCancel: Boolean) { btnCancel.isVisible = showCancel val height = if (showCancel) 120 else 90 setSize(300, height) } - companion object - { - fun factory(title: String, message: String, workToDo: Int): ProgressDialog - { + companion object { + fun factory(title: String, message: String, workToDo: Int): ProgressDialog { val dialog = ProgressDialog(workToDo, message) dialog.resetProgress() dialog.title = title diff --git a/src/main/kotlin/dartzee/core/screen/SimpleDialog.kt b/src/main/kotlin/dartzee/core/screen/SimpleDialog.kt index 1d259684d..9d929b9be 100644 --- a/src/main/kotlin/dartzee/core/screen/SimpleDialog.kt +++ b/src/main/kotlin/dartzee/core/screen/SimpleDialog.kt @@ -9,14 +9,12 @@ import javax.swing.JButton import javax.swing.JDialog import javax.swing.JPanel -abstract class SimpleDialog : JDialog(), ActionListener -{ +abstract class SimpleDialog : JDialog(), ActionListener { protected val panelOkCancel = JPanel() protected val btnOk = JButton("Ok") protected val btnCancel = JButton("Cancel") - init - { + init { contentPane.add(panelOkCancel, BorderLayout.SOUTH) panelOkCancel.add(btnOk) @@ -28,24 +26,18 @@ abstract class SimpleDialog : JDialog(), ActionListener btnCancel.addActionListener(this) } - /** - * Abstract methods - */ + /** Abstract methods */ abstract fun okPressed() - /** - * Default methods - */ + /** Default methods */ open fun allowCancel() = true - open fun cancelPressed() - { + + open fun cancelPressed() { dispose() } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnOk -> okPressed() btnCancel -> cancelPressed() else -> logger.error(CODE_SWING_ERROR, "Unexpected button pressed: ${arg0.source}") diff --git a/src/main/kotlin/dartzee/core/screen/TableModelDialog.kt b/src/main/kotlin/dartzee/core/screen/TableModelDialog.kt index 7c65ba307..410b1bb77 100644 --- a/src/main/kotlin/dartzee/core/screen/TableModelDialog.kt +++ b/src/main/kotlin/dartzee/core/screen/TableModelDialog.kt @@ -4,13 +4,9 @@ import dartzee.core.bean.ScrollTable import dartzee.utils.InjectedThings import java.awt.BorderLayout -/** - * Simple dialog to show a table - */ -class TableModelDialog(title: String, val table: ScrollTable) : SimpleDialog() -{ - init - { +/** Simple dialog to show a table */ +class TableModelDialog(title: String, val table: ScrollTable) : SimpleDialog() { + init { setTitle(title) setSize(600, 400) isModal = InjectedThings.allowModalDialogs @@ -18,11 +14,10 @@ class TableModelDialog(title: String, val table: ScrollTable) : SimpleDialog() contentPane.add(table, BorderLayout.CENTER) } - /** - * Configure things about the table - */ + /** Configure things about the table */ fun setColumnWidths(colWidthsStr: String) = table.setColumnWidths(colWidthsStr) override fun okPressed() = dispose() + override fun allowCancel() = false -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/CollectionShuffler.kt b/src/main/kotlin/dartzee/core/util/CollectionShuffler.kt index c73794c96..90ed07f7f 100644 --- a/src/main/kotlin/dartzee/core/util/CollectionShuffler.kt +++ b/src/main/kotlin/dartzee/core/util/CollectionShuffler.kt @@ -1,11 +1,9 @@ package dartzee.core.util -interface IShuffler -{ +interface IShuffler { fun shuffleCollection(collection: List): List } -class CollectionShuffler: IShuffler -{ +class CollectionShuffler : IShuffler { override fun shuffleCollection(collection: List) = collection.shuffled() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/ComponentUtil.kt b/src/main/kotlin/dartzee/core/util/ComponentUtil.kt index b69abed53..503ad3cd3 100644 --- a/src/main/kotlin/dartzee/core/util/ComponentUtil.kt +++ b/src/main/kotlin/dartzee/core/util/ComponentUtil.kt @@ -17,10 +17,10 @@ import javax.swing.text.SimpleAttributeSet import javax.swing.text.StyleConstants /** - * Recurses through all child components, returning an ArrayList of all children of the appropriate type + * Recurses through all child components, returning an ArrayList of all children of the appropriate + * type */ -inline fun Container.getAllChildComponentsForType(): List -{ +inline fun Container.getAllChildComponentsForType(): List { val ret = mutableListOf() val components = components @@ -30,116 +30,91 @@ inline fun Container.getAllChildComponentsForType(): List } @Suppress("UNCHECKED_CAST") -fun addComponents(ret: MutableList, components: Array, desiredClazz: Class) -{ - for (comp in components) - { - if (desiredClazz.isInstance(comp)) - { +fun addComponents(ret: MutableList, components: Array, desiredClazz: Class) { + for (comp in components) { + if (desiredClazz.isInstance(comp)) { ret.add(comp as T) } - if (comp is Container) - { + if (comp is Container) { val subComponents = comp.components addComponents(ret, subComponents, desiredClazz) } } } -fun Container.addActionListenerToAllChildren(listener: ActionListener) -{ +fun Container.addActionListenerToAllChildren(listener: ActionListener) { val children = getAllChildComponentsForType() children.forEach { - if (it is JComboBox<*>) - { - if (!it.actionListeners.contains(listener)) - { + if (it is JComboBox<*>) { + if (!it.actionListeners.contains(listener)) { it.addActionListener(listener) } } - if (it is AbstractButton) - { - if (!it.actionListeners.contains(listener)) - { + if (it is AbstractButton) { + if (!it.actionListeners.contains(listener)) { it.addActionListener(listener) } } } } -fun Container.addChangeListenerToAllChildren(listener: ChangeListener) -{ +fun Container.addChangeListenerToAllChildren(listener: ChangeListener) { val children = getAllChildComponentsForType() children.forEach { - if (it is JSpinner) - { - if (!it.changeListeners.contains(listener)) - { + if (it is JSpinner) { + if (!it.changeListeners.contains(listener)) { it.addChangeListener(listener) } } } } -fun Container.enableChildren(enable: Boolean) -{ - getAllChildComponentsForType().forEach{ - it.isEnabled = enable - } +fun Container.enableChildren(enable: Boolean) { + getAllChildComponentsForType().forEach { it.isEnabled = enable } } -fun Container.containsComponent(component: Component): Boolean -{ +fun Container.containsComponent(component: Component): Boolean { val list = getAllChildComponentsForType() return list.contains(component) } -fun createButtonGroup(vararg buttons: AbstractButton) -{ - if (buttons.isEmpty()) - { +fun createButtonGroup(vararg buttons: AbstractButton) { + if (buttons.isEmpty()) { throw Exception("Trying to create empty ButtonGroup.") } val bg = ButtonGroup() - buttons.forEach { - bg.add(it) - } + buttons.forEach { bg.add(it) } - //Enable the first button passed in by default + // Enable the first button passed in by default buttons[0].isSelected = true } -fun Container.getParentWindow(): Window? -{ +fun Container.getParentWindow(): Window? { val myParent = parent ?: return null return if (myParent is Window) myParent else myParent.getParentWindow() } -fun Component.setFontSize(size: Int) -{ +fun Component.setFontSize(size: Int) { font = Font(font.name, font.style, size) } -fun JComponent.setMargins(margin: Int) -{ +fun JComponent.setMargins(margin: Int) { setMargins(margin, margin, margin, margin) } -fun JComponent.setMargins(top: Int, left: Int, bottom: Int, right: Int) -{ +fun JComponent.setMargins(top: Int, left: Int, bottom: Int, right: Int) { border = EmptyBorder(top, left, bottom, right) } -fun JTextPane.append(str: String, bold: Boolean = false, italic: Boolean = false) -{ +fun JTextPane.append(str: String, bold: Boolean = false, italic: Boolean = false) { val style = SimpleAttributeSet() StyleConstants.setBold(style, bold) StyleConstants.setItalic(style, italic) val length = document.length document.insertString(length, str, style) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/CoreRegistry.kt b/src/main/kotlin/dartzee/core/util/CoreRegistry.kt index 0af6b3c57..a4d8ca1a8 100644 --- a/src/main/kotlin/dartzee/core/util/CoreRegistry.kt +++ b/src/main/kotlin/dartzee/core/util/CoreRegistry.kt @@ -2,8 +2,7 @@ package dartzee.core.util import java.util.prefs.Preferences -object CoreRegistry -{ +object CoreRegistry { val instance: Preferences = Preferences.userRoot().node("entropyInstance") const val INSTANCE_STRING_DEVICE_ID = "deviceId" } diff --git a/src/main/kotlin/dartzee/core/util/DartboardDodgyUtil.kt b/src/main/kotlin/dartzee/core/util/DartboardDodgyUtil.kt index c773e5d0f..68113bbda 100644 --- a/src/main/kotlin/dartzee/core/util/DartboardDodgyUtil.kt +++ b/src/main/kotlin/dartzee/core/util/DartboardDodgyUtil.kt @@ -17,76 +17,68 @@ import javax.sound.sampled.LineEvent import javax.swing.ImageIcon import javax.swing.JLabel -fun GameplayDartboard.doChucklevision() -{ +fun GameplayDartboard.doChucklevision() { val rand = Random() val chuckleSound = rand.nextInt(3) + 1 doDodgy(ResourceCache.IMG_CHUCKLE, 266, 279, "chucklevision$chuckleSound") } -fun GameplayDartboard.doFawlty() -{ +fun GameplayDartboard.doFawlty() { val rand = Random() val brucey = rand.nextInt(4) + 1 doDodgy(ResourceCache.IMG_BASIL, 576, 419, "basil$brucey") } -fun GameplayDartboard.doForsyth() -{ +fun GameplayDartboard.doForsyth() { val rand = Random() val brucey = rand.nextInt(4) + 1 doDodgy(ResourceCache.IMG_BRUCE, 300, 478, "forsyth$brucey") } -fun GameplayDartboard.doBadLuck() -{ +fun GameplayDartboard.doBadLuck() { val rand = Random() val ix = rand.nextInt(2) + 1 doDodgy(ResourceCache.IMG_BRUCE, 300, 478, "badLuck$ix") } -fun GameplayDartboard.doBull() -{ +fun GameplayDartboard.doBull() { doDodgy(ResourceCache.IMG_DEV, 400, 476, "bull") } -fun GameplayDartboard.doBadMiss() -{ +fun GameplayDartboard.doBadMiss() { val rand = Random() val miss = rand.nextInt(5) + 1 - //4-1 ratio because mitchell > spencer! - if (miss <= 4) - { + // 4-1 ratio because mitchell > spencer! + if (miss <= 4) { doDodgy(ResourceCache.IMG_MITCHELL, 300, 250, "badmiss$miss") - } - else - { + } else { doDodgy(ResourceCache.IMG_SPENCER, 460, 490, "damage") } } -fun GameplayDartboard.doGolfMiss() -{ +fun GameplayDartboard.doGolfMiss() { doDodgy(ResourceCache.IMG_DEV, 400, 476, "fourTrimmed") } -private fun GameplayDartboard.doDodgy(ii: ImageIcon, width: Int, height: Int, soundName: String) -{ - if (!PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS)) - { +private fun GameplayDartboard.doDodgy(ii: ImageIcon, width: Int, height: Int, soundName: String) { + if (!PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS)) { return } runOnEventThread { doDodgyOnEdt(ii, width, height, soundName) } } -private fun GameplayDartboard.doDodgyOnEdt(ii: ImageIcon, width: Int, height: Int, soundName: String) -{ +private fun GameplayDartboard.doDodgyOnEdt( + ii: ImageIcon, + width: Int, + height: Int, + soundName: String +) { removeDodgyLabels() val dodgyLabel = JLabel("") @@ -107,33 +99,27 @@ private fun GameplayDartboard.doDodgyOnEdt(ii: ImageIcon, width: Int, height: In playDodgySound(soundName) } -fun GameplayDartboard.playDodgySound(soundName: String) -{ - if (!PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS)) - { +fun GameplayDartboard.playDodgySound(soundName: String) { + if (!PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS)) { return } - try - { - if (ResourceCache.isInitialised) - { + try { + if (ResourceCache.isInitialised) { playDodgySoundCached(soundName) + } else { + logger.warn( + CODE_RESOURCE_CACHE_NOT_INITIALISED, + "Not playing [$soundName] - ResourceCache not initialised" + ) } - else - { - logger.warn(CODE_RESOURCE_CACHE_NOT_INITIALISED, "Not playing [$soundName] - ResourceCache not initialised") - } - } - catch (e: Throwable) - { + } catch (e: Throwable) { logger.error(CODE_AUDIO_ERROR, "Caught error playing sound [$soundName]", e) resetDodgy() } } -private fun GameplayDartboard.playDodgySoundCached(soundName: String) -{ +private fun GameplayDartboard.playDodgySoundCached(soundName: String) { val stream = ResourceCache.borrowInputStream(soundName) ?: return val clip = initialiseAudioClip(stream, soundName) @@ -141,18 +127,20 @@ private fun GameplayDartboard.playDodgySoundCached(soundName: String) clip.start() } -private fun GameplayDartboard.initialiseAudioClip(stream: AudioInputStream, soundName: String): Clip -{ +private fun GameplayDartboard.initialiseAudioClip( + stream: AudioInputStream, + soundName: String +): Clip { val myClip = AudioSystem.getLine(Line.Info(Clip::class.java)) as Clip - //Overwrite the 'latestClip' variable so this always stores the latest sound. - //Allows us to not dismiss the label until the final sound has finished, in the case of overlapping sounds. + // Overwrite the 'latestClip' variable so this always stores the latest sound. + // Allows us to not dismiss the label until the final sound has finished, in the case of + // overlapping sounds. latestClip = myClip myClip.addLineListener { event -> - if (event.type === LineEvent.Type.STOP) - { - //Always close or return our one + if (event.type === LineEvent.Type.STOP) { + // Always close or return our one myClip.stop() myClip.close() @@ -176,4 +164,4 @@ private fun GameplayDartboard.resetDodgy() { private fun GameplayDartboard.removeDodgyLabels() { getAllChildComponentsForType().filter { it.name == "DodgyLabel" }.forEach(::remove) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/DateStatics.kt b/src/main/kotlin/dartzee/core/util/DateStatics.kt index 39fe5923d..824ef401d 100644 --- a/src/main/kotlin/dartzee/core/util/DateStatics.kt +++ b/src/main/kotlin/dartzee/core/util/DateStatics.kt @@ -2,8 +2,7 @@ package dartzee.core.util import java.sql.Timestamp -object DateStatics -{ +object DateStatics { val END_OF_TIME: Timestamp = Timestamp.valueOf("9999-12-31 00:00:00") val START_OF_TIME: Timestamp = Timestamp.valueOf("1900-01-01 00:00:00") } diff --git a/src/main/kotlin/dartzee/core/util/DateUtil.kt b/src/main/kotlin/dartzee/core/util/DateUtil.kt index e20ea189e..66dc099d0 100644 --- a/src/main/kotlin/dartzee/core/util/DateUtil.kt +++ b/src/main/kotlin/dartzee/core/util/DateUtil.kt @@ -3,17 +3,14 @@ package dartzee.core.util import java.sql.Timestamp import java.text.SimpleDateFormat - fun getSqlDateNow() = Timestamp(System.currentTimeMillis()) fun getEndOfTimeSqlString() = DateStatics.END_OF_TIME.getSqlString() fun isEndOfTime(dt: Timestamp?) = dt?.equals(DateStatics.END_OF_TIME) ?: false -fun Timestamp.formatTimestamp(): String -{ - if (isEndOfTime(this)) - { +fun Timestamp.formatTimestamp(): String { + if (isEndOfTime(this)) { return "" } @@ -21,10 +18,8 @@ fun Timestamp.formatTimestamp(): String return dateFormat.format(this) } -fun Timestamp.formatAsDate() : String -{ - if (isEndOfTime(this)) - { +fun Timestamp.formatAsDate(): String { + if (isEndOfTime(this)) { return "" } @@ -32,16 +27,14 @@ fun Timestamp.formatAsDate() : String return dateFormat.format(this) } -fun Timestamp.getSqlString(): String -{ +fun Timestamp.getSqlString(): String { val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") val formatted = dateFormat.format(this) return "'$formatted'" } -fun getFileTimeString(): String -{ +fun getFileTimeString(): String { val dt = getSqlDateNow() val dateFormat = SimpleDateFormat("yyyyMMdd_HHmm") return dateFormat.format(dt) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/DialogUtil.kt b/src/main/kotlin/dartzee/core/util/DialogUtil.kt index 29e2a933b..9fc7bba2f 100644 --- a/src/main/kotlin/dartzee/core/util/DialogUtil.kt +++ b/src/main/kotlin/dartzee/core/util/DialogUtil.kt @@ -14,41 +14,45 @@ import java.io.File import javax.swing.JOptionPane import javax.swing.SwingUtilities -object DialogUtil -{ +object DialogUtil { private var loadingDialog: LoadingDialog? = null private var dialogFactory: IMessageDialogFactory = MessageDialogFactory() - fun init(implementation: IMessageDialogFactory) - { + fun init(implementation: IMessageDialogFactory) { dialogFactory = implementation } @Deprecated("Use showInfo") - fun showInfoOLD(infoText: String) - { + fun showInfoOLD(infoText: String) { logDialogShown("Info", "Information", infoText) dialogFactory.showInfo(infoText) logDialogClosed("Info", null) } - fun showInfo(infoText: String, parent: Component = ScreenCache.mainScreen) - { + fun showInfo(infoText: String, parent: Component = ScreenCache.mainScreen) { logDialogShown("Info", "Information", infoText) - JOptionPane.showMessageDialog(parent, infoText, "Information", JOptionPane.INFORMATION_MESSAGE) + JOptionPane.showMessageDialog( + parent, + infoText, + "Information", + JOptionPane.INFORMATION_MESSAGE + ) logDialogClosed("Info", null) } - fun showCustomMessage(message: Any, parent: Component = ScreenCache.mainScreen) - { + fun showCustomMessage(message: Any, parent: Component = ScreenCache.mainScreen) { logDialogShown("CustomInfo", "Information", "?") - JOptionPane.showMessageDialog(parent, message, "Information", JOptionPane.INFORMATION_MESSAGE) + JOptionPane.showMessageDialog( + parent, + message, + "Information", + JOptionPane.INFORMATION_MESSAGE + ) logDialogClosed("CustomInfo", null) } @Deprecated("Use showError") - fun showErrorOLD(errorText: String) - { + fun showErrorOLD(errorText: String) { dismissLoadingDialogOLD() logDialogShown("Error", "Error", errorText) @@ -56,8 +60,7 @@ object DialogUtil logDialogClosed("Error", null) } - fun showError(errorText: String, parent: Component? = ScreenCache.mainScreen) - { + fun showError(errorText: String, parent: Component? = ScreenCache.mainScreen) { dismissLoadingDialog() logDialogShown("Error", "Error", errorText) @@ -65,106 +68,116 @@ object DialogUtil logDialogClosed("Error", null) } - fun showErrorLater(errorText: String) - { + fun showErrorLater(errorText: String) { SwingUtilities.invokeLater { showErrorOLD(errorText) } } @Deprecated("Use showQuestion") - fun showQuestionOLD(message: String, allowCancel: Boolean = false): Int - { + fun showQuestionOLD(message: String, allowCancel: Boolean = false): Int { logDialogShown("Question", "Question", message) val selection = dialogFactory.showQuestion(message, allowCancel) logDialogClosed("Question", selection) return selection } - fun showQuestion(message: String, allowCancel: Boolean = false, parent: Component = ScreenCache.mainScreen): Int - { + fun showQuestion( + message: String, + allowCancel: Boolean = false, + parent: Component = ScreenCache.mainScreen + ): Int { logDialogShown("Question", "Question", message) - val option = if (allowCancel) JOptionPane.YES_NO_CANCEL_OPTION else JOptionPane.YES_NO_OPTION - val selection = JOptionPane.showConfirmDialog(parent, message, "Question", option, JOptionPane.QUESTION_MESSAGE) + val option = + if (allowCancel) JOptionPane.YES_NO_CANCEL_OPTION else JOptionPane.YES_NO_OPTION + val selection = + JOptionPane.showConfirmDialog( + parent, + message, + "Question", + option, + JOptionPane.QUESTION_MESSAGE + ) logDialogClosed("Question", selection) return selection } @Deprecated("Use showLoadingDialog / dismissLoadingDialog") - fun showLoadingDialogOLD(text: String) - { + fun showLoadingDialogOLD(text: String) { logDialogShown("Loading", "", text) dialogFactory.showLoading(text) } - fun showLoadingDialog(text: String) - { + fun showLoadingDialog(text: String) { logDialogShown("Loading", "", text) loadingDialog = LoadingDialog() loadingDialog?.showDialog(text) } - fun dismissLoadingDialog() - { + fun dismissLoadingDialog() { val wasVisible = loadingDialog?.isVisible ?: false loadingDialog?.dismissDialog() - if (wasVisible) - { + if (wasVisible) { logDialogClosed("Loading", null) } } @Deprecated("Use showLoadingDialog / dismissLoadingDialog") - fun dismissLoadingDialogOLD() - { + fun dismissLoadingDialogOLD() { val dismissed = dialogFactory.dismissLoading() - if (dismissed) - { + if (dismissed) { logDialogClosed("Loading", null) } } - fun showOption(title: String, message: String, options: List): String? - { + fun showOption(title: String, message: String, options: List): String? { logDialogShown("Option", title, message) val selectionStr = dialogFactory.showOption(title, message, options) logDialogClosed("Option", selectionStr) return selectionStr } - fun showInput(title: String, message: String, options: Array? = null, defaultOption: K? = null): K? - { + fun showInput( + title: String, + message: String, + options: Array? = null, + defaultOption: K? = null + ): K? { logDialogShown("Input", title, message) val selection = dialogFactory.showInput(title, message, options, defaultOption) logDialogClosed("Input", selection) return selection } - fun chooseDirectory(parent: Component?): File? - { + fun chooseDirectory(parent: Component?): File? { logDialogShown("File selector", "", "") val file = dialogFactory.chooseDirectory(parent) logDialogClosed("File selector", file?.absolutePath) return file } - - private fun logDialogShown(type: String, title: String, message: String) - { - InjectedThings.logger.info(CODE_DIALOG_SHOWN, "$type dialog shown: $message", KEY_DIALOG_TYPE to type, KEY_DIALOG_TITLE to title, KEY_DIALOG_MESSAGE to message) + private fun logDialogShown(type: String, title: String, message: String) { + InjectedThings.logger.info( + CODE_DIALOG_SHOWN, + "$type dialog shown: $message", + KEY_DIALOG_TYPE to type, + KEY_DIALOG_TITLE to title, + KEY_DIALOG_MESSAGE to message + ) } - private fun logDialogClosed(type: String, selection: Any?) - { + private fun logDialogClosed(type: String, selection: Any?) { var message = "$type dialog closed" selection?.let { message += " - selected ${translateOption(it)}" } InjectedThings.logger.info( - CODE_DIALOG_CLOSED, message, + CODE_DIALOG_CLOSED, + message, KEY_DIALOG_TYPE to type, - KEY_DIALOG_SELECTION to selection) + KEY_DIALOG_SELECTION to selection + ) } + private fun translateOption(option: Any?) = - when (option) - { + when (option) { JOptionPane.YES_OPTION -> "Yes" JOptionPane.NO_OPTION -> "No" JOptionPane.CANCEL_OPTION -> "Cancel" diff --git a/src/main/kotlin/dartzee/core/util/EdtMonitor.kt b/src/main/kotlin/dartzee/core/util/EdtMonitor.kt index 7cde25bcf..7ff901770 100644 --- a/src/main/kotlin/dartzee/core/util/EdtMonitor.kt +++ b/src/main/kotlin/dartzee/core/util/EdtMonitor.kt @@ -6,12 +6,9 @@ import javax.swing.SwingUtilities private const val EDT_WAIT_TIME = 10000L -class EdtMonitor(private val waitTime: Long) : Runnable -{ - override fun run() - { - while (checkEdtResponsive()) - { +class EdtMonitor(private val waitTime: Long) : Runnable { + override fun run() { + while (checkEdtResponsive()) { Thread.sleep(waitTime) } } @@ -19,14 +16,11 @@ class EdtMonitor(private val waitTime: Long) : Runnable private fun checkEdtResponsive(): Boolean { var updated = false - SwingUtilities.invokeLater { - updated = true - } + SwingUtilities.invokeLater { updated = true } Thread.sleep(waitTime) - if (!updated) - { + if (!updated) { logger.error(CODE_EDT_FROZEN, "EDT did not respond after ${waitTime}ms") dumpThreadStacks() } @@ -34,8 +28,8 @@ class EdtMonitor(private val waitTime: Long) : Runnable return updated } - companion object - { - fun start(waitTime: Long = EDT_WAIT_TIME) = Thread(EdtMonitor(waitTime), "EDT Monitor").also { it.start() } + companion object { + fun start(waitTime: Long = EDT_WAIT_TIME) = + Thread(EdtMonitor(waitTime), "EDT Monitor").also { it.start() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/ExtensionFunctions.kt b/src/main/kotlin/dartzee/core/util/ExtensionFunctions.kt index c1c8997d4..41808f9f6 100644 --- a/src/main/kotlin/dartzee/core/util/ExtensionFunctions.kt +++ b/src/main/kotlin/dartzee/core/util/ExtensionFunctions.kt @@ -1,40 +1,37 @@ package dartzee.core.util -fun MutableList.addUnique(element: E) -{ - if (!contains(element)) - { +fun MutableList.addUnique(element: E) { + if (!contains(element)) { add(element) } } -fun , V> Map.getSortedValues(): List = entries.sortedBy { it.key }.map { it.value } +fun , V> Map.getSortedValues(): List = + entries.sortedBy { it.key }.map { it.value } fun List.minOrZero() = minOrNull() ?: 0 + fun List.maxOrZero() = maxOrNull() ?: 0 -inline fun > Iterable.sortedBy(descending: Boolean, crossinline selector: (T) -> R?) = - if (descending) this.sortedByDescending(selector) else this.sortedBy(selector) +inline fun > Iterable.sortedBy( + descending: Boolean, + crossinline selector: (T) -> R? +) = if (descending) this.sortedByDescending(selector) else this.sortedBy(selector) -fun IntRange.getDescription(): String -{ - return when - { +fun IntRange.getDescription(): String { + return when { this.first == this.last -> "${this.first}" this.last == Integer.MAX_VALUE -> "${this.first}+" else -> "${this.first} - ${this.last}" } } -fun List.getAllPermutations(): List> -{ - if (size < 2) - { +fun List.getAllPermutations(): List> { + if (size < 2) { return listOf(this) } - if (size == 2) - { + if (size == 2) { return listOf(this, this.reversed()) } @@ -43,8 +40,7 @@ fun List.getAllPermutations(): List> val subList = this.toMutableList() subList.removeAt(ix) - for (permutation in subList.getAllPermutations()) - { + for (permutation in subList.getAllPermutations()) { allPermutations.add(listOf(obj) + permutation) } } @@ -60,18 +56,18 @@ inline fun Iterable.allIndexed(predicate: (index: Int, T) -> Boolean): Bo return true } -fun List.getLongestStreak(isHit: (item: T) -> Boolean): List -{ - val chains = fold(listOf(mutableListOf())) { currentChains, item -> - val latestChain = currentChains.last() - if (isHit(item)) { - latestChain.add(item) - } else if (latestChain.isNotEmpty()) { - return@fold currentChains + listOf(mutableListOf()) +fun List.getLongestStreak(isHit: (item: T) -> Boolean): List { + val chains = + fold(listOf(mutableListOf())) { currentChains, item -> + val latestChain = currentChains.last() + if (isHit(item)) { + latestChain.add(item) + } else if (latestChain.isNotEmpty()) { + return@fold currentChains + listOf(mutableListOf()) + } + + currentChains } - currentChains - } - return chains.maxBy { it.size } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/FileUtil.kt b/src/main/kotlin/dartzee/core/util/FileUtil.kt index 6d641f694..50825c3ca 100644 --- a/src/main/kotlin/dartzee/core/util/FileUtil.kt +++ b/src/main/kotlin/dartzee/core/util/FileUtil.kt @@ -11,83 +11,71 @@ import java.nio.file.Paths import javax.imageio.ImageIO import javax.imageio.stream.FileImageInputStream -object FileUtil -{ +object FileUtil { fun deleteFileIfExists(filePath: String) = - try - { + try { val path = Paths.get(filePath) Files.deleteIfExists(path) - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_FILE_ERROR, "Failed to delete file $filePath", t) false } - fun swapInFile(oldFilePath: String, newFilePath: String): String? - { + fun swapInFile(oldFilePath: String, newFilePath: String): String? { val oldFile = File(oldFilePath) val oldFileName = oldFile.name val newFile = File(newFilePath) val zzOldFile = File(oldFile.parent, "zz$oldFileName") logger.info(CODE_SWITCHING_FILES, "Rename current out of the way [$oldFile -> $zzOldFile]") - if (oldFile.exists() - && !oldFile.renameTo(zzOldFile)) - { + if (oldFile.exists() && !oldFile.renameTo(zzOldFile)) { return "Failed to rename old out of the way." } logger.info(CODE_SWITCHING_FILES, "Rename new to current [$newFile -> $oldFile]") - if (!newFile.renameTo(File(oldFile.parent, oldFileName))) - { + if (!newFile.renameTo(File(oldFile.parent, oldFileName))) { return "Failed to rename new file to $oldFileName" } logger.info(CODE_SWITCHING_FILES, "Delete zz'd file [$zzOldFile]") - if (!zzOldFile.deleteRecursively()) - { + if (!zzOldFile.deleteRecursively()) { return "Failed to delete zz'd old file: ${zzOldFile.path}" } return null } - fun getImageDim(file: File): Dimension? - { + fun getImageDim(file: File): Dimension? { val iter = ImageIO.getImageReadersBySuffix(file.extension) val reader = if (iter.hasNext()) iter.next() else null - if (reader != null) - { - try - { + if (reader != null) { + try { FileImageInputStream(file).use { stream -> reader.input = stream val width = reader.getWidth(reader.minIndex) val height = reader.getHeight(reader.minIndex) return Dimension(width, height) } + } catch (e: IOException) { + logger.error(CODE_FILE_ERROR, "Failed to get img dimensions for $file", e) + } finally { + reader.dispose() } - catch (e: IOException) { logger.error(CODE_FILE_ERROR, "Failed to get img dimensions for $file", e) } - finally { reader.dispose() } - } - else - { - logger.error(CODE_FILE_ERROR, "No reader found for file extension: ${file.extension} (full path: ${file.absolutePath})") + } else { + logger.error( + CODE_FILE_ERROR, + "No reader found for file extension: ${file.extension} (full path: ${file.absolutePath})" + ) } return null } fun getByteArrayForResource(resourcePath: String): ByteArray? = - try - { + try { javaClass.getResourceAsStream(resourcePath).use { stream -> stream?.readBytes() } - } - catch (ioe: IOException) - { + } catch (ioe: IOException) { logger.error(CODE_FILE_ERROR, "Failed to read classpath resource $resourcePath", ioe) null } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/IMessageDialogFactory.kt b/src/main/kotlin/dartzee/core/util/IMessageDialogFactory.kt index 627b4374c..4bfa94166 100644 --- a/src/main/kotlin/dartzee/core/util/IMessageDialogFactory.kt +++ b/src/main/kotlin/dartzee/core/util/IMessageDialogFactory.kt @@ -3,14 +3,20 @@ package dartzee.core.util import java.awt.Component import java.io.File -interface IMessageDialogFactory -{ +interface IMessageDialogFactory { fun showInfo(text: String) + fun showError(text: String) + fun showQuestion(text: String, allowCancel: Boolean = false): Int + fun showOption(title: String, message: String, options: List): String? + fun showLoading(text: String) + fun showInput(title: String, message: String, options: Array?, defaultOption: K?): K? + fun dismissLoading(): Boolean + fun chooseDirectory(parent: Component?): File? -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/InjectedCore.kt b/src/main/kotlin/dartzee/core/util/InjectedCore.kt index d78a1066c..2001e81f0 100644 --- a/src/main/kotlin/dartzee/core/util/InjectedCore.kt +++ b/src/main/kotlin/dartzee/core/util/InjectedCore.kt @@ -1,6 +1,5 @@ package dartzee.core.util -object InjectedCore -{ +object InjectedCore { var collectionShuffler: IShuffler = CollectionShuffler() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/InjectedDesktopCore.kt b/src/main/kotlin/dartzee/core/util/InjectedDesktopCore.kt index 815502bd3..3a3cfd5a6 100644 --- a/src/main/kotlin/dartzee/core/util/InjectedDesktopCore.kt +++ b/src/main/kotlin/dartzee/core/util/InjectedDesktopCore.kt @@ -3,7 +3,6 @@ package dartzee.core.util import dartzee.core.bean.IColourSelector import dartzee.core.screen.ColourChooserDialog -object InjectedDesktopCore -{ +object InjectedDesktopCore { var colourSelector: IColourSelector = ColourChooserDialog() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/JacksonUtil.kt b/src/main/kotlin/dartzee/core/util/JacksonUtil.kt index 8fcf22e5b..b9c0738f7 100644 --- a/src/main/kotlin/dartzee/core/util/JacksonUtil.kt +++ b/src/main/kotlin/dartzee/core/util/JacksonUtil.kt @@ -5,8 +5,9 @@ import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper -fun jsonMapper() = jacksonObjectMapper().apply { - registerModule(KotlinModule.Builder().build()) - disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - setSerializationInclusion(JsonInclude.Include.NON_NULL) -} \ No newline at end of file +fun jsonMapper() = + jacksonObjectMapper().apply { + registerModule(KotlinModule.Builder().build()) + disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + setSerializationInclusion(JsonInclude.Include.NON_NULL) + } diff --git a/src/main/kotlin/dartzee/core/util/MathsUtil.kt b/src/main/kotlin/dartzee/core/util/MathsUtil.kt index e4bcd12af..ac85430cf 100644 --- a/src/main/kotlin/dartzee/core/util/MathsUtil.kt +++ b/src/main/kotlin/dartzee/core/util/MathsUtil.kt @@ -3,7 +3,6 @@ package dartzee.core.util import kotlin.math.ceil import kotlin.math.pow - fun Int.ceilDiv(other: Int) = ceil(this.toDouble() / other).toInt() fun Pair.mapStepped(stepSize: Double, mapFunction: (Double) -> T): List { @@ -18,10 +17,8 @@ fun Pair.mapStepped(stepSize: Double, mapFunction: (Double) return ret } -object MathsUtil -{ - fun round(number: Double, decimalPlaces: Int): Double - { +object MathsUtil { + fun round(number: Double, decimalPlaces: Int): Double { val powerOfTen = 10.0.pow(decimalPlaces.toDouble()) val rounded = Math.round(powerOfTen * number) @@ -32,10 +29,8 @@ object MathsUtil fun getPercentage(count: Number, total: Number, digits: Int = 1) = getPercentage(count.toDouble(), total.toDouble(), digits) - fun getPercentage(count: Double, total: Double, digits: Int = 1): Double - { - return if (count == 0.0) - { + fun getPercentage(count: Double, total: Double, digits: Int = 1): Double { + return if (count == 0.0) { 0.0 } else round(100 * count / total, digits) } diff --git a/src/main/kotlin/dartzee/core/util/MessageDialogFactory.kt b/src/main/kotlin/dartzee/core/util/MessageDialogFactory.kt index fddcedc1b..07aab84d3 100644 --- a/src/main/kotlin/dartzee/core/util/MessageDialogFactory.kt +++ b/src/main/kotlin/dartzee/core/util/MessageDialogFactory.kt @@ -6,60 +6,80 @@ import java.io.File import javax.swing.JFileChooser import javax.swing.JOptionPane -class MessageDialogFactory: IMessageDialogFactory -{ +class MessageDialogFactory : IMessageDialogFactory { private val loadingDialog = LoadingDialog() - override fun showInfo(text: String) - { + override fun showInfo(text: String) { JOptionPane.showMessageDialog(null, text, "Information", JOptionPane.INFORMATION_MESSAGE) } @Suppress("UNCHECKED_CAST") - override fun showInput(title: String, message: String, options: Array?, defaultOption: K?): K? = - JOptionPane.showInputDialog(null, message, title, JOptionPane.PLAIN_MESSAGE, null, options, defaultOption) as K? + override fun showInput( + title: String, + message: String, + options: Array?, + defaultOption: K? + ): K? = + JOptionPane.showInputDialog( + null, + message, + title, + JOptionPane.PLAIN_MESSAGE, + null, + options, + defaultOption + ) as K? - override fun showError(text: String) - { + override fun showError(text: String) { JOptionPane.showMessageDialog(null, text, "Error", JOptionPane.ERROR_MESSAGE) } - override fun showOption(title: String, message: String, options: List): String? - { + override fun showOption(title: String, message: String, options: List): String? { val typedArray = options.toTypedArray() - val selection = JOptionPane.showOptionDialog( - null, message, title, JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, typedArray, options.first()) + val selection = + JOptionPane.showOptionDialog( + null, + message, + title, + JOptionPane.DEFAULT_OPTION, + JOptionPane.QUESTION_MESSAGE, + null, + typedArray, + options.first() + ) return if (selection > -1) typedArray[selection] else null } - override fun showQuestion(text: String, allowCancel: Boolean): Int - { - val option = if (allowCancel) JOptionPane.YES_NO_CANCEL_OPTION else JOptionPane.YES_NO_OPTION - return JOptionPane.showConfirmDialog(null, text, "Question", option, JOptionPane.QUESTION_MESSAGE) + override fun showQuestion(text: String, allowCancel: Boolean): Int { + val option = + if (allowCancel) JOptionPane.YES_NO_CANCEL_OPTION else JOptionPane.YES_NO_OPTION + return JOptionPane.showConfirmDialog( + null, + text, + "Question", + option, + JOptionPane.QUESTION_MESSAGE + ) } - override fun showLoading(text: String) - { + override fun showLoading(text: String) { loadingDialog.showDialog(text) } - override fun dismissLoading(): Boolean - { + override fun dismissLoading(): Boolean { val wasVisible = loadingDialog.isVisible loadingDialog.dismissDialog() return wasVisible } - override fun chooseDirectory(parent: Component?): File? - { + override fun chooseDirectory(parent: Component?): File? { val fc = JFileChooser() fc.fileSelectionMode = JFileChooser.DIRECTORIES_ONLY val option = fc.showDialog(parent, "Select") - if (option != JFileChooser.APPROVE_OPTION) - { + if (option != JFileChooser.APPROVE_OPTION) { return null } return fc.selectedFile } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/StringUtil.kt b/src/main/kotlin/dartzee/core/util/StringUtil.kt index 128e3b2a2..496652aef 100644 --- a/src/main/kotlin/dartzee/core/util/StringUtil.kt +++ b/src/main/kotlin/dartzee/core/util/StringUtil.kt @@ -1,16 +1,15 @@ package dartzee.core.util -object StringUtil -{ - fun convertOrdinalToText(position: Int): String - { +object StringUtil { + fun convertOrdinalToText(position: Int): String { if (position < 0) return "" val suffixes = listOf("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th") - return when (position % 100) - { - 11, 12, 13 -> "${position}th" + return when (position % 100) { + 11, + 12, + 13 -> "${position}th" else -> "${position}${suffixes[position % 10]}" } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/TableUtil.kt b/src/main/kotlin/dartzee/core/util/TableUtil.kt index b5bda2a56..d1c1927ba 100644 --- a/src/main/kotlin/dartzee/core/util/TableUtil.kt +++ b/src/main/kotlin/dartzee/core/util/TableUtil.kt @@ -9,25 +9,29 @@ import javax.swing.JTable import javax.swing.table.DefaultTableCellRenderer import javax.swing.table.DefaultTableModel -object TableUtil -{ - class TimestampRenderer: AbstractTableRenderer() - { +object TableUtil { + class TimestampRenderer : AbstractTableRenderer() { override fun getReplacementValue(value: Timestamp) = value.formatTimestamp() + override fun allowNulls() = true } - class SimpleRenderer(private val alignment: Int, private val tableFont: Font?) : DefaultTableCellRenderer() - { - override fun getTableCellRendererComponent(table: JTable?, value: Any, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { - val component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) - if (component is JLabel) - { + class SimpleRenderer(private val alignment: Int, private val tableFont: Font?) : + DefaultTableCellRenderer() { + override fun getTableCellRendererComponent( + table: JTable?, + value: Any, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { + val component = + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) + if (component is JLabel) { component.horizontalAlignment = alignment - if (tableFont != null) - { + if (tableFont != null) { this.font = tableFont } } @@ -36,44 +40,34 @@ object TableUtil } } - class DefaultModel : DefaultTableModel() - { + class DefaultModel : DefaultTableModel() { override fun isCellEditable(row: Int, column: Int) = false - override fun getColumnClass(arg0: Int): Class<*> - { - return if (rowCount > 0 && getValueAt(0, arg0) != null) - { + override fun getColumnClass(arg0: Int): Class<*> { + return if (rowCount > 0 && getValueAt(0, arg0) != null) { getValueAt(0, arg0).javaClass - } - else super.getColumnClass(arg0) + } else super.getColumnClass(arg0) } - fun getColumnValues(column: Int): List - { + fun getColumnValues(column: Int): List { val list = mutableListOf() - for (i in 0 until rowCount) - { + for (i in 0 until rowCount) { list.add(getValueAt(i, column)) } return list } - fun setColumnNames(cols: List) - { - cols.forEach{ addColumn(it) } + fun setColumnNames(cols: List) { + cols.forEach { addColumn(it) } } - fun addRows(rows: Collection>) - { + fun addRows(rows: Collection>) { rows.forEach { addRow(it) } } - fun clear() - { - while (rowCount > 0) - { + fun clear() { + while (rowCount > 0) { removeRow(0) } } diff --git a/src/main/kotlin/dartzee/core/util/ThreadUtil.kt b/src/main/kotlin/dartzee/core/util/ThreadUtil.kt index fd45d4ead..0f1fe05cf 100644 --- a/src/main/kotlin/dartzee/core/util/ThreadUtil.kt +++ b/src/main/kotlin/dartzee/core/util/ThreadUtil.kt @@ -7,51 +7,43 @@ import dartzee.logging.extractThreadStack import dartzee.utils.InjectedThings.logger import javax.swing.SwingUtilities -fun dumpThreadStacks() -{ +fun dumpThreadStacks() { logger.info(CODE_THREAD_STACKS, "Dumping thread stacks") val threads = Thread.getAllStackTraces() val it = threads.keys.iterator() - while (it.hasNext()) - { + while (it.hasNext()) { val thread = it.next() val stack = thread.stackTrace val state = thread.state - if (stack.isNotEmpty()) - { - logger.info(CODE_THREAD_STACK, "${thread.name} ($state)", KEY_STACK to extractThreadStack(stack)) + if (stack.isNotEmpty()) { + logger.info( + CODE_THREAD_STACK, + "${thread.name} ($state)", + KEY_STACK to extractThreadStack(stack) + ) } } } -fun runOnEventThread(r: (() -> Unit)) -{ - if (SwingUtilities.isEventDispatchThread()) - { +fun runOnEventThread(r: (() -> Unit)) { + if (SwingUtilities.isEventDispatchThread()) { r.invoke() - } - else - { + } else { SwingUtilities.invokeLater(r) } } -fun runOnEventThreadBlocking(r: (() -> Unit)) -{ - if (SwingUtilities.isEventDispatchThread()) - { +fun runOnEventThreadBlocking(r: (() -> Unit)) { + if (SwingUtilities.isEventDispatchThread()) { r.invoke() - } - else - { + } else { SwingUtilities.invokeAndWait(r) } } -fun runInOtherThread(r: (() -> Unit)): Thread -{ +fun runInOtherThread(r: (() -> Unit)): Thread { val t = Thread(r) t.start() return t -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/core/util/XmlUtil.kt b/src/main/kotlin/dartzee/core/util/XmlUtil.kt index 08a62e5c3..8e2ef6771 100644 --- a/src/main/kotlin/dartzee/core/util/XmlUtil.kt +++ b/src/main/kotlin/dartzee/core/util/XmlUtil.kt @@ -2,9 +2,6 @@ package dartzee.core.util import dartzee.logging.CODE_PARSE_ERROR import dartzee.utils.InjectedThings.logger -import org.w3c.dom.Document -import org.w3c.dom.Element -import org.xml.sax.InputSource import java.io.StringReader import java.io.StringWriter import javax.xml.parsers.DocumentBuilderFactory @@ -12,25 +9,24 @@ import javax.xml.transform.OutputKeys import javax.xml.transform.TransformerFactory import javax.xml.transform.dom.DOMSource import javax.xml.transform.stream.StreamResult +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.xml.sax.InputSource -//Cache one instance of the factories - I've seen from thread stacks that constructing it each time is really slow +// Cache one instance of the factories - I've seen from thread stacks that constructing it each time +// is really slow private val factory = DocumentBuilderFactory.newInstance() private val tf = TransformerFactory.newInstance() -object XmlUtil -{ - fun factoryNewDocument(): Document - { +object XmlUtil { + fun factoryNewDocument(): Document { val builder = factory.newDocumentBuilder() return builder.newDocument() } } -/** - * Extension fns - */ -fun Element.getAttributeInt(attributeName: String, defaultValue: Int = 0): Int -{ +/** Extension fns */ +fun Element.getAttributeInt(attributeName: String, defaultValue: Int = 0): Int { val attribute = getAttribute(attributeName) return if (attribute == "") defaultValue else attribute.toInt() } @@ -40,8 +36,7 @@ fun Element.setAttributeAny(key: String, value: Any) = setAttribute(key, "$value fun Document.createRootElement(name: String): Element = createElement(name).also { appendChild(it) } fun Document.toXmlString(): String = - try - { + try { val transformer = tf.newTransformer() transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes") val writer = StringWriter() @@ -49,22 +44,17 @@ fun Document.toXmlString(): String = val sb = writer.buffer sb.toString().replace("[\n\r]".toRegex(), "") - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_PARSE_ERROR, "Failed to convert xml doc to string", t) "" } @Suppress("SwallowedException") fun String.toXmlDoc() = - try - { + try { val builder = factory.newDocumentBuilder() builder.setErrorHandler(null) builder.parse(InputSource(StringReader(this))) - } - catch (t: Throwable) - { + } catch (t: Throwable) { null - } \ No newline at end of file + } diff --git a/src/main/kotlin/dartzee/dartzee/AbstractDartzeeRule.kt b/src/main/kotlin/dartzee/dartzee/AbstractDartzeeRule.kt index 7c73ff2f7..d6ccf8273 100644 --- a/src/main/kotlin/dartzee/dartzee/AbstractDartzeeRule.kt +++ b/src/main/kotlin/dartzee/dartzee/AbstractDartzeeRule.kt @@ -31,14 +31,12 @@ import dartzee.dartzee.dart.DartzeeDartRuleScore import org.w3c.dom.Document import org.w3c.dom.Element -abstract class AbstractDartzeeRule -{ +abstract class AbstractDartzeeRule { abstract fun getRuleIdentifier(): String open fun writeXmlAttributes(doc: Document, rootElement: Element) {} - fun populate(xmlStr: String) - { + fun populate(xmlStr: String) { val xmlDoc = xmlStr.toXmlDoc() xmlDoc ?: return @@ -55,8 +53,7 @@ abstract class AbstractDartzeeRule open fun randomise() {} - fun toDbString(): String - { + fun toDbString(): String { val xmlDoc = XmlUtil.factoryNewDocument() val rootElement = xmlDoc.createRootElement(getRuleIdentifier()) @@ -66,20 +63,21 @@ abstract class AbstractDartzeeRule } } -fun getAllDartRules(): List -{ - return listOf(DartzeeDartRuleAny(), - DartzeeDartRuleEven(), - DartzeeDartRuleOdd(), - DartzeeDartRuleInner(), - DartzeeDartRuleOuter(), - DartzeeDartRuleColour(), - DartzeeDartRuleScore(), - DartzeeDartRuleCustom(), - DartzeeDartRuleMiss()) +fun getAllDartRules(): List { + return listOf( + DartzeeDartRuleAny(), + DartzeeDartRuleEven(), + DartzeeDartRuleOdd(), + DartzeeDartRuleInner(), + DartzeeDartRuleOuter(), + DartzeeDartRuleColour(), + DartzeeDartRuleScore(), + DartzeeDartRuleCustom(), + DartzeeDartRuleMiss() + ) } -fun getAllAggregateRules(): List -{ + +fun getAllAggregateRules(): List { return listOf( DartzeeTotalRuleLessThan(), DartzeeTotalRuleGreaterThan(), @@ -93,14 +91,16 @@ fun getAllAggregateRules(): List DartzeeAggregateRuleSpread(), DartzeeAggregateRuleCluster(), DartzeeAggregateRuleDistinctScores(), - DartzeeAggregateRuleRepeats()) + DartzeeAggregateRuleRepeats() + ) } + fun parseDartRule(xmlStr: String) = parseRule(xmlStr, getAllDartRules()) + fun parseAggregateRule(xmlStr: String) = parseRule(xmlStr, getAllAggregateRules()) -fun parseRule(xmlStr: String, ruleTemplates: List): K? -{ - if (xmlStr.isEmpty()) - { + +fun parseRule(xmlStr: String, ruleTemplates: List): K? { + if (xmlStr.isEmpty()) { return null } @@ -109,10 +109,10 @@ fun parseRule(xmlStr: String, ruleTemplates: List): val rootElement = xmlDoc.documentElement - val rule = ruleTemplates.find{ it.getRuleIdentifier() == rootElement.tagName } + val rule = ruleTemplates.find { it.getRuleIdentifier() == rootElement.tagName } rule ?: return null rule.populate(rootElement) return rule -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeAimCalculator.kt b/src/main/kotlin/dartzee/dartzee/DartzeeAimCalculator.kt index 1bde08ebf..f7c7a07ad 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeAimCalculator.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeAimCalculator.kt @@ -10,69 +10,79 @@ import dartzee.utils.getAllNonMissSegments import dartzee.utils.translatePoint import java.awt.Point -class DartzeeAimCalculator -{ +class DartzeeAimCalculator { private val miniDartboard = ComputationalDartboard(350, 350) - fun getPointToAimFor(dartboard: ComputationalDartboard, segmentStatuses: SegmentStatuses, aggressive: Boolean): Point - { + fun getPointToAimFor( + dartboard: ComputationalDartboard, + segmentStatuses: SegmentStatuses, + aggressive: Boolean + ): Point { val scoringSegments = segmentStatuses.scoringSegments.filter { !it.isMiss() } val validSegments = segmentStatuses.validSegments.filter { !it.isMiss() } - val segmentsToConsiderAimingFor = if (aggressive && scoringSegments.isNotEmpty()) scoringSegments else validSegments - if (segmentsToConsiderAimingFor.isEmpty()) - { + val segmentsToConsiderAimingFor = + if (aggressive && scoringSegments.isNotEmpty()) scoringSegments else validSegments + if (segmentsToConsiderAimingFor.isEmpty()) { return DELIBERATE_MISS } - //Shortcut straight to the bullseye if all outer singles, inner singles, trebles and bull are valid - val innerSegments = getAllNonMissSegments().filter { it.type != SegmentType.DOUBLE || it.score == 25 } - if (segmentsToConsiderAimingFor.containsAll(innerSegments)) - { + // Shortcut straight to the bullseye if all outer singles, inner singles, trebles and bull + // are valid + val innerSegments = + getAllNonMissSegments().filter { it.type != SegmentType.DOUBLE || it.score == 25 } + if (segmentsToConsiderAimingFor.containsAll(innerSegments)) { return dartboard.computeCenter() } - val aimingPointSet = segmentsToConsiderAimingFor.flatMap(miniDartboard::getPointsForSegment).toSet() + val aimingPointSet = + segmentsToConsiderAimingFor.flatMap(miniDartboard::getPointsForSegment).toSet() val validPointSet = validSegments.flatMap(miniDartboard::getPointsForSegment).toSet() - val potentialPointsToAimFor = miniDartboard.getPotentialAimPoints().filter { aimingPointSet.contains(it.point) } + val potentialPointsToAimFor = + miniDartboard.getPotentialAimPoints().filter { aimingPointSet.contains(it.point) } val contendingPoints = getMaxCirclePoints(validPointSet, potentialPointsToAimFor) - val bestScore = contendingPoints.map { miniDartboard.getSegmentForPoint(it.point).getTotal() }.maxOrZero() - val contendingHighScorePoints = contendingPoints.filter { miniDartboard.getSegmentForPoint(it.point).getTotal() == bestScore } + val bestScore = + contendingPoints + .map { miniDartboard.getSegmentForPoint(it.point).getTotal() } + .maxOrZero() + val contendingHighScorePoints = + contendingPoints.filter { + miniDartboard.getSegmentForPoint(it.point).getTotal() == bestScore + } - //Prefer even angles to odd ones - val bestPoint = contendingHighScorePoints.minByOrNull { it.angle % 2 } !! + // Prefer even angles to odd ones + val bestPoint = contendingHighScorePoints.minByOrNull { it.angle % 2 }!! return dartboard.translateAimPoint(bestPoint) } /** - * Optimisation - rather than do a groupBy for all potential points, iterating the circle size up, instead loop - * over them and keep track of the max circle size so far. Iterate down from this -> 0 to rule out most points - * more quickly. + * Optimisation - rather than do a groupBy for all potential points, iterating the circle size + * up, instead loop over them and keep track of the max circle size so far. Iterate down from + * this -> 0 to rule out most points more quickly. */ - private fun getMaxCirclePoints(validPointSet: Set, potentialPointsToAimFor: List): List - { + private fun getMaxCirclePoints( + validPointSet: Set, + potentialPointsToAimFor: List + ): List { var currentMax = 1 val maxPoints = mutableListOf() potentialPointsToAimFor.forEach { candidatePt -> val myMax = candidatePt.getMaxCircleSize(validPointSet, currentMax) - if (myMax > currentMax) - { + if (myMax > currentMax) { currentMax = myMax maxPoints.clear() maxPoints.add(candidatePt) - } - else if (myMax == currentMax) - { + } else if (myMax == currentMax) { maxPoints.add(candidatePt) } } return maxPoints } - private fun AimPoint.getMaxCircleSize(validPoints: Set, currentMax: Int): Int - { + + private fun AimPoint.getMaxCircleSize(validPoints: Set, currentMax: Int): Int { val range = (currentMax downTo 1) val bigEnough = range.all { validPoints.containsAll(makeCircle(point, it)) } if (!bigEnough) { @@ -81,14 +91,14 @@ class DartzeeAimCalculator var radius = currentMax + 1 var pointsInCircle = makeCircle(this.point, radius) - while (validPoints.containsAll(pointsInCircle)) - { + while (validPoints.containsAll(pointsInCircle)) { radius += 1 pointsInCircle = makeCircle(this.point, radius) } return radius - 1 } + private fun makeCircle(centerPt: Point, radius: Int) = - (0..359).map { translatePoint(centerPt, radius.toDouble(), it.toDouble()) }.toSet() -} \ No newline at end of file + (0..359).map { translatePoint(centerPt, radius.toDouble(), it.toDouble()) }.toSet() +} diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeCalculator.kt b/src/main/kotlin/dartzee/dartzee/DartzeeCalculator.kt index 5deb399bb..b13ea5647 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeCalculator.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeCalculator.kt @@ -8,40 +8,46 @@ import dartzee.`object`.Dart import dartzee.`object`.DartboardSegment import dartzee.utils.getAllSegmentsForDartzee -interface IDartzeeCalculator -{ +interface IDartzeeCalculator { fun getValidSegments(rule: DartzeeRuleDto, dartsSoFar: List): DartzeeRuleCalculationResult } -class DartzeeCalculator: IDartzeeCalculator -{ +class DartzeeCalculator : IDartzeeCalculator { private val allPossibilities: List> = generateAllPossibilities() private fun isValidDartCombination(darts: List, rule: DartzeeRuleDto) = - isValidCombination(darts.map { DartboardSegment(it.segmentType, it.score) }, rule) - - fun isValidCombination(combination: List, - rule: DartzeeRuleDto, - cachedResults: MutableMap, Boolean> = mutableMapOf()): Boolean - { - return isValidCombinationForAggregateRule(combination, rule.aggregateRule) - && isValidFromMisses(combination, rule) - && isValidCombinationForDartRule(combination, rule.getDartRuleList(), rule.inOrder, cachedResults) + isValidCombination(darts.map { DartboardSegment(it.segmentType, it.score) }, rule) + + fun isValidCombination( + combination: List, + rule: DartzeeRuleDto, + cachedResults: MutableMap, Boolean> = mutableMapOf() + ): Boolean { + return isValidCombinationForAggregateRule(combination, rule.aggregateRule) && + isValidFromMisses(combination, rule) && + isValidCombinationForDartRule( + combination, + rule.getDartRuleList(), + rule.inOrder, + cachedResults + ) } - override fun getValidSegments(rule: DartzeeRuleDto, dartsSoFar: List): DartzeeRuleCalculationResult - { - if (dartsSoFar.size == 3) - { + override fun getValidSegments( + rule: DartzeeRuleDto, + dartsSoFar: List + ): DartzeeRuleCalculationResult { + if (dartsSoFar.size == 3) { val valid = isValidDartCombination(dartsSoFar, rule) - return if (valid) getValidSegments(rule, listOf(dartsSoFar[0], dartsSoFar[1])) else INVALID_CALCULATION_RESULT + return if (valid) getValidSegments(rule, listOf(dartsSoFar[0], dartsSoFar[1])) + else INVALID_CALCULATION_RESULT } val cachedCombinationResults = mutableMapOf, Boolean>() val allPossibilities = generateAllPossibilities(dartsSoFar) - val validCombinations = allPossibilities.filter { - isValidCombination(it, rule, cachedCombinationResults) } + val validCombinations = + allPossibilities.filter { isValidCombination(it, rule, cachedCombinationResults) } val validSegments = validCombinations.map { it[dartsSoFar.size] }.distinct() val scoringSegments = rule.getScoringSegments(dartsSoFar, validSegments) @@ -49,53 +55,51 @@ class DartzeeCalculator: IDartzeeCalculator val validPixelPossibility = validCombinations.sumOf { mapCombinationToProbability(it) } val allProbabilities = allPossibilities.sumOf { mapCombinationToProbability(it) } - return DartzeeRuleCalculationResult(scoringSegments, + return DartzeeRuleCalculationResult( + scoringSegments, validSegments, validCombinations.size, allPossibilities.size, validPixelPossibility, - allProbabilities) + allProbabilities + ) } + private fun isValidFromMisses(combination: List, rule: DartzeeRuleDto) = rule.allowMisses || combination.all { !it.isMiss() } - private fun isValidCombinationForAggregateRule(combination: List, aggregateRule: AbstractDartzeeAggregateRule?): Boolean - { - if (aggregateRule == null) - { + private fun isValidCombinationForAggregateRule( + combination: List, + aggregateRule: AbstractDartzeeAggregateRule? + ): Boolean { + if (aggregateRule == null) { return true } return aggregateRule.isValidRound(combination) } - private fun isValidCombinationForDartRule(combination: List, - dartRules: List?, - inOrder: Boolean, - cachedResults: MutableMap, Boolean> = mutableMapOf()): Boolean - { - if (dartRules == null) - { + + private fun isValidCombinationForDartRule( + combination: List, + dartRules: List?, + inOrder: Boolean, + cachedResults: MutableMap, Boolean> = mutableMapOf() + ): Boolean { + if (dartRules == null) { return true } - if (dartRules.size == 1) - { + if (dartRules.size == 1) { val rule = dartRules.first() return combination.any { rule.isValidSegment(it) } } - return if (inOrder) - { + return if (inOrder) { isValidCombinationForOrderedDartRule(dartRules, combination) - } - else - { - if (cachedResults.containsKey(combination)) - { + } else { + if (cachedResults.containsKey(combination)) { cachedResults[combination]!! - } - else - { + } else { val permutations = combination.getAllPermutations() val valid = permutations.any { isValidCombinationForOrderedDartRule(dartRules, it) } @@ -106,17 +110,18 @@ class DartzeeCalculator: IDartzeeCalculator } } } - private fun isValidCombinationForOrderedDartRule(rules: List, combination: List) = - rules.allIndexed { ix, rule -> rule.isValidSegment(combination[ix]) } - private fun mapCombinationToProbability(combination: List): Double - { + private fun isValidCombinationForOrderedDartRule( + rules: List, + combination: List + ) = rules.allIndexed { ix, rule -> rule.isValidSegment(combination[ix]) } + + private fun mapCombinationToProbability(combination: List): Double { val probabilities = combination.map { it.getRoughProbability() } return probabilities.reduce { acc, i -> acc * i } } - private fun generateAllPossibilities(): List> - { + private fun generateAllPossibilities(): List> { val segments = getAllSegmentsForDartzee() val allPossibilities: MutableList> = mutableListOf() @@ -132,10 +137,8 @@ class DartzeeCalculator: IDartzeeCalculator return allPossibilities.toList() } - fun generateAllPossibilities(dartsSoFar: List): List> - { - if (dartsSoFar.isEmpty()) - { + fun generateAllPossibilities(dartsSoFar: List): List> { + if (dartsSoFar.isEmpty()) { return allPossibilities } @@ -143,21 +146,20 @@ class DartzeeCalculator: IDartzeeCalculator val segmentsSoFar = dartsSoFar.map { DartboardSegment(it.segmentType, it.score) } var allPossibilities: List> = segments.map { segmentsSoFar + it } - while (allPossibilities.first().size < 3) - { + while (allPossibilities.first().size < 3) { allPossibilities = addAnotherLayer(allPossibilities, segments) } return allPossibilities } - private fun addAnotherLayer(allPossibilities: List>, segments: List): List> - { + + private fun addAnotherLayer( + allPossibilities: List>, + segments: List + ): List> { val ret = mutableListOf>() - for (possibility in allPossibilities) - { - segments.forEach { - ret.add(possibility + it) - } + for (possibility in allPossibilities) { + segments.forEach { ret.add(possibility + it) } } return ret diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeRandomiser.kt b/src/main/kotlin/dartzee/dartzee/DartzeeRandomiser.kt index be0c8c701..dcf885695 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeRandomiser.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeRandomiser.kt @@ -4,12 +4,15 @@ import dartzee.dartzee.dart.AbstractDartzeeDartRule import dartzee.dartzee.dart.DartzeeDartRuleCustom import kotlin.random.Random -object DartzeeRandomiser -{ - data class DartRule(val dart1Rule: AbstractDartzeeDartRule, val dart2Rule: AbstractDartzeeDartRule?, val dart3Rule: AbstractDartzeeDartRule?, val inOrder: Boolean) - - fun generateRandomRule(): DartzeeRuleDto - { +object DartzeeRandomiser { + data class DartRule( + val dart1Rule: AbstractDartzeeDartRule, + val dart2Rule: AbstractDartzeeDartRule?, + val dart3Rule: AbstractDartzeeDartRule?, + val inOrder: Boolean + ) + + fun generateRandomRule(): DartzeeRuleDto { val dartRuleBit = Random.nextInt(2) val totalRuleBit = Random.nextInt(2) @@ -17,31 +20,35 @@ object DartzeeRandomiser val hasTotalRule = totalRuleBit == 1 val dartRule = if (hasDartRule) makeDartRule() else null - val totalRule = if (hasTotalRule) getAllAggregateRules().random().also { it.randomise() } else null + val totalRule = + if (hasTotalRule) getAllAggregateRules().random().also { it.randomise() } else null val allowMisses = Random.nextInt(5) == 1 - return DartzeeRuleDto(dartRule?.dart1Rule, dartRule?.dart2Rule, dartRule?.dart3Rule, totalRule, dartRule?.inOrder ?: false, allowMisses, null) + return DartzeeRuleDto( + dartRule?.dart1Rule, + dartRule?.dart2Rule, + dartRule?.dart3Rule, + totalRule, + dartRule?.inOrder ?: false, + allowMisses, + null + ) } - private fun makeDartRule(): DartRule - { + private fun makeDartRule(): DartRule { val typeBit = Random.nextInt(3) - return if (typeBit == 2) - { + return if (typeBit == 2) { DartRule(randomDartRule(), null, null, false) - } - else - { + } else { // Generate all of them val inOrder = Random.nextInt(2) == 1 DartRule(randomDartRule(), randomDartRule(), randomDartRule(), inOrder) } } - private fun randomDartRule(): AbstractDartzeeDartRule - { - val rules = getAllDartRules().filter{ it !is DartzeeDartRuleCustom } + private fun randomDartRule(): AbstractDartzeeDartRule { + val rules = getAllDartRules().filter { it !is DartzeeDartRuleCustom } return rules.random().also { it.randomise() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeRoundResult.kt b/src/main/kotlin/dartzee/dartzee/DartzeeRoundResult.kt index 8009b952c..105fabf4e 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeRoundResult.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeRoundResult.kt @@ -1,5 +1,3 @@ package dartzee.dartzee -data class DartzeeRoundResult(val ruleNumber: Int, - val success: Boolean, - val score: Int = -1) \ No newline at end of file +data class DartzeeRoundResult(val ruleNumber: Int, val success: Boolean, val score: Int = -1) diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeRuleCalculationResult.kt b/src/main/kotlin/dartzee/dartzee/DartzeeRuleCalculationResult.kt index 767e63001..81b947985 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeRuleCalculationResult.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeRuleCalculationResult.kt @@ -9,8 +9,7 @@ import dartzee.screen.game.SegmentStatuses import dartzee.utils.DartsColour import kotlin.math.sqrt -enum class DartzeeRuleDifficulty(val desc: String) -{ +enum class DartzeeRuleDifficulty(val desc: String) { IMPOSSIBLE("Impossible"), INSANE("Insane"), VERY_HARD("Very Hard"), @@ -22,15 +21,25 @@ enum class DartzeeRuleDifficulty(val desc: String) val INVALID_CALCULATION_RESULT = DartzeeRuleCalculationResult(listOf(), listOf(), 0, 0, 0.0, 1.0) -@JsonIgnoreProperties("percentage", "combinationsDesc", "difficultyDesc", "segmentStatus", "foreground", "background", "difficulty") -data class DartzeeRuleCalculationResult(val scoringSegments: List, - val validSegments: List, - val validCombinations: Int, - val allCombinations: Int, - val validCombinationProbability: Double, - val allCombinationsProbability: Double) -{ - val percentage = MathsUtil.getPercentage(validCombinationProbability, allCombinationsProbability) +@JsonIgnoreProperties( + "percentage", + "combinationsDesc", + "difficultyDesc", + "segmentStatus", + "foreground", + "background", + "difficulty" +) +data class DartzeeRuleCalculationResult( + val scoringSegments: List, + val validSegments: List, + val validCombinations: Int, + val allCombinations: Int, + val validCombinationProbability: Double, + val allCombinationsProbability: Double +) { + val percentage = + MathsUtil.getPercentage(validCombinationProbability, allCombinationsProbability) fun getCombinationsDesc() = "$validCombinations combinations (success%: $percentage%)" @@ -39,23 +48,24 @@ data class DartzeeRuleCalculationResult(val scoringSegments: List DartzeeRuleDifficulty.IMPOSSIBLE - percentage > 40 -> DartzeeRuleDifficulty.VERY_EASY - percentage > 25 -> DartzeeRuleDifficulty.EASY - percentage > 10 -> DartzeeRuleDifficulty.MODERATE - percentage > 5 -> DartzeeRuleDifficulty.HARD - percentage > 1 -> DartzeeRuleDifficulty.VERY_HARD - else -> DartzeeRuleDifficulty.INSANE - } + private fun getDifficulty() = + when { + validCombinations == 0 -> DartzeeRuleDifficulty.IMPOSSIBLE + percentage > 40 -> DartzeeRuleDifficulty.VERY_EASY + percentage > 25 -> DartzeeRuleDifficulty.EASY + percentage > 10 -> DartzeeRuleDifficulty.MODERATE + percentage > 5 -> DartzeeRuleDifficulty.HARD + percentage > 1 -> DartzeeRuleDifficulty.VERY_HARD + else -> DartzeeRuleDifficulty.INSANE + } fun toDbString(): String = jsonMapper().writeValueAsString(this) - companion object - { - fun fromDbString(dbString: String): DartzeeRuleCalculationResult = jsonMapper().readValue(dbString) + companion object { + fun fromDbString(dbString: String): DartzeeRuleCalculationResult = + jsonMapper().readValue(dbString) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeRuleDto.kt b/src/main/kotlin/dartzee/dartzee/DartzeeRuleDto.kt index f815b0f60..df6cd51c5 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeRuleDto.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeRuleDto.kt @@ -11,21 +11,25 @@ import dartzee.utils.InjectedThings.dartzeeCalculator import dartzee.utils.InjectedThings.mainDatabase import dartzee.utils.sumScore -data class DartzeeRuleDto(val dart1Rule: AbstractDartzeeDartRule?, val dart2Rule: AbstractDartzeeDartRule?, val dart3Rule: AbstractDartzeeDartRule?, - val aggregateRule: AbstractDartzeeAggregateRule?, val inOrder: Boolean, val allowMisses: Boolean, val ruleName: String?) -{ +data class DartzeeRuleDto( + val dart1Rule: AbstractDartzeeDartRule?, + val dart2Rule: AbstractDartzeeDartRule?, + val dart3Rule: AbstractDartzeeDartRule?, + val aggregateRule: AbstractDartzeeAggregateRule?, + val inOrder: Boolean, + val allowMisses: Boolean, + val ruleName: String? +) { var calculationResult: DartzeeRuleCalculationResult? = null - fun getDartRuleList(): List? - { + fun getDartRuleList(): List? { dart1Rule ?: return null dart2Rule ?: return listOf(dart1Rule) return listOf(dart1Rule, dart2Rule, dart3Rule!!) } - fun runStrengthCalculation(): DartzeeRuleCalculationResult - { + fun runStrengthCalculation(): DartzeeRuleCalculationResult { val calculationResult = dartzeeCalculator.getValidSegments(this, listOf()) this.calculationResult = calculationResult @@ -33,8 +37,7 @@ data class DartzeeRuleDto(val dart1Rule: AbstractDartzeeDartRule?, val dart2Rule return calculationResult } - fun getSuccessTotal(darts: List): Int - { + fun getSuccessTotal(darts: List): Int { val dartsAfterAggregate = aggregateRule?.getScoringDarts(darts) ?: darts dart1Rule ?: return sumScore(dartsAfterAggregate) @@ -47,26 +50,30 @@ data class DartzeeRuleDto(val dart1Rule: AbstractDartzeeDartRule?, val dart2Rule } } - /** - * If this is a "Score X" rule, return the relevant segments - */ - fun getScoringSegments(dartsSoFar: List, validSegments: List): List - { + /** If this is a "Score X" rule, return the relevant segments */ + fun getScoringSegments( + dartsSoFar: List, + validSegments: List + ): List { val scoringSegments = getScoringSegmentsForAggregateRule(dartsSoFar, validSegments) - if (dart1Rule == null || dart2Rule != null) - { + if (dart1Rule == null || dart2Rule != null) { return scoringSegments } return scoringSegments.filter { dart1Rule.isValidSegment(it) } } - private fun getScoringSegmentsForAggregateRule(dartsSoFar: List, validSegments: List): List - { - if (dartsSoFar.size == 2 && aggregateRule != null) - { + + private fun getScoringSegmentsForAggregateRule( + dartsSoFar: List, + validSegments: List + ): List { + if (dartsSoFar.size == 2 && aggregateRule != null) { return validSegments.filter { segment -> val scoringDartsAfterTwo = aggregateRule.getScoringDarts(dartsSoFar).size - val scoringDartsAfterThree = aggregateRule.getScoringDarts(dartsSoFar + Dart(segment.score, segment.getMultiplier())).size + val scoringDartsAfterThree = + aggregateRule + .getScoringDarts(dartsSoFar + Dart(segment.score, segment.getMultiplier())) + .size scoringDartsAfterThree > scoringDartsAfterTwo } } @@ -74,14 +81,13 @@ data class DartzeeRuleDto(val dart1Rule: AbstractDartzeeDartRule?, val dart2Rule return validSegments } - fun getDifficulty() = calculationResult?.percentage ?: 0.0 + fun getDifficultyDesc() = calculationResult?.getDifficultyDesc().orEmpty() fun getDisplayName() = ruleName ?: generateRuleDescription() - fun generateRuleDescription(): String - { + fun generateRuleDescription(): String { val dartsDesc = getDartsDescription() val totalDesc = getTotalDescription() @@ -92,40 +98,44 @@ data class DartzeeRuleDto(val dart1Rule: AbstractDartzeeDartRule?, val dart2Rule val result = ruleParts.joinToString() return if (result.isEmpty()) "Anything" else result } + private fun getTotalDescription() = aggregateRule?.getDescription().orEmpty() - private fun getDartsDescription(): String - { + + private fun getDartsDescription(): String { dart1Rule ?: return "" dart2Rule ?: return "Score ${dart1Rule.getDescription()}s" - //It's a 3 dart rule + // It's a 3 dart rule val dart1Desc = dart1Rule.getDescription() val dart2Desc = dart2Rule.getDescription() val dart3Desc = dart3Rule!!.getDescription() val rules = listOf(dart1Desc, dart2Desc, dart3Desc) - if (rules.all { it == "Any"} ) - { + if (rules.all { it == "Any" }) { return "" } - return if (inOrder) - { + return if (inOrder) { "$dart1Desc → $dart2Desc → $dart3Desc" - } - else - { - //Try to condense the descriptions + } else { + // Try to condense the descriptions val interestingRules = rules.filter { it != "Any" } val mapEntries = interestingRules.groupBy { it }.map { it } - val sortedGroupedRules = mapEntries.sortedByDescending { it.value.size }.map { "${it.value.size}x ${it.key}" } + val sortedGroupedRules = + mapEntries + .sortedByDescending { it.value.size } + .map { "${it.value.size}x ${it.key}" } "{ ${sortedGroupedRules.joinToString()} }" } } - fun toEntity(ordinal: Int, entityName: EntityName, entityId: String, database: Database = mainDatabase): DartzeeRuleEntity - { + fun toEntity( + ordinal: Int, + entityName: EntityName, + entityId: String, + database: Database = mainDatabase + ): DartzeeRuleEntity { val entity = DartzeeRuleEntity(database) entity.assignRowId() diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeRuleFactory.kt b/src/main/kotlin/dartzee/dartzee/DartzeeRuleFactory.kt index ebd72597c..494dd2b49 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeRuleFactory.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeRuleFactory.kt @@ -2,26 +2,23 @@ package dartzee.dartzee import dartzee.screen.dartzee.DartzeeRuleCreationDialog -interface IDartzeeRuleFactory -{ +interface IDartzeeRuleFactory { fun newRule(): DartzeeRuleDto? + fun amendRule(rule: DartzeeRuleDto): DartzeeRuleDto } -class DartzeeRuleFactory: IDartzeeRuleFactory -{ - override fun newRule(): DartzeeRuleDto? - { +class DartzeeRuleFactory : IDartzeeRuleFactory { + override fun newRule(): DartzeeRuleDto? { val dlg = DartzeeRuleCreationDialog() dlg.isVisible = true return dlg.dartzeeRule } - override fun amendRule(rule: DartzeeRuleDto): DartzeeRuleDto - { + override fun amendRule(rule: DartzeeRuleDto): DartzeeRuleDto { val dlg = DartzeeRuleCreationDialog() dlg.amendRule(rule) dlg.isVisible = true return dlg.dartzeeRule!! } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/DartzeeSegmentFactory.kt b/src/main/kotlin/dartzee/dartzee/DartzeeSegmentFactory.kt index 5f64a9e1c..c7cebf353 100644 --- a/src/main/kotlin/dartzee/dartzee/DartzeeSegmentFactory.kt +++ b/src/main/kotlin/dartzee/dartzee/DartzeeSegmentFactory.kt @@ -3,17 +3,14 @@ package dartzee.dartzee import dartzee.`object`.DartboardSegment import dartzee.screen.dartzee.DartboardSegmentSelectDialog -interface IDartzeeSegmentFactory -{ +interface IDartzeeSegmentFactory { fun selectSegments(segments: Set): Set } -class DartzeeSegmentFactory: IDartzeeSegmentFactory -{ - override fun selectSegments(segments: Set): Set - { +class DartzeeSegmentFactory : IDartzeeSegmentFactory { + override fun selectSegments(segments: Set): Set { val dlg = DartboardSegmentSelectDialog(segments) dlg.isVisible = true return dlg.getSelection() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/IDartzeeRuleConfigurable.kt b/src/main/kotlin/dartzee/dartzee/IDartzeeRuleConfigurable.kt index 2018fc4e1..cbc778e53 100644 --- a/src/main/kotlin/dartzee/dartzee/IDartzeeRuleConfigurable.kt +++ b/src/main/kotlin/dartzee/dartzee/IDartzeeRuleConfigurable.kt @@ -2,7 +2,6 @@ package dartzee.dartzee import javax.swing.JPanel -interface IDartzeeRuleConfigurable -{ +interface IDartzeeRuleConfigurable { val configPanel: JPanel -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeAggregateRule.kt b/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeAggregateRule.kt index 9b8ed858f..fe3db5410 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeAggregateRule.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeAggregateRule.kt @@ -4,9 +4,8 @@ import dartzee.dartzee.AbstractDartzeeRule import dartzee.`object`.Dart import dartzee.`object`.DartboardSegment -abstract class AbstractDartzeeAggregateRule: AbstractDartzeeRule() -{ +abstract class AbstractDartzeeAggregateRule : AbstractDartzeeRule() { abstract fun isValidRound(segments: List): Boolean open fun getScoringDarts(darts: List) = darts -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeRuleTotalSize.kt b/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeRuleTotalSize.kt index 7b848eaae..4435e15e8 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeRuleTotalSize.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeRuleTotalSize.kt @@ -2,8 +2,6 @@ package dartzee.dartzee.aggregate import dartzee.core.util.getAttributeInt import dartzee.dartzee.IDartzeeRuleConfigurable -import org.w3c.dom.Document -import org.w3c.dom.Element import java.awt.FlowLayout import javax.swing.JPanel import javax.swing.JSpinner @@ -11,16 +9,17 @@ import javax.swing.SpinnerNumberModel import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener import kotlin.random.Random +import org.w3c.dom.Document +import org.w3c.dom.Element -abstract class AbstractDartzeeRuleTotalSize: AbstractDartzeeTotalRule(), ChangeListener, IDartzeeRuleConfigurable -{ +abstract class AbstractDartzeeRuleTotalSize : + AbstractDartzeeTotalRule(), ChangeListener, IDartzeeRuleConfigurable { var target = 20 override val configPanel = JPanel() val spinner = JSpinner() - init - { + init { configPanel.layout = FlowLayout() configPanel.add(spinner) @@ -30,25 +29,21 @@ abstract class AbstractDartzeeRuleTotalSize: AbstractDartzeeTotalRule(), ChangeL spinner.value = target } - override fun writeXmlAttributes(doc: Document, rootElement: Element) - { + override fun writeXmlAttributes(doc: Document, rootElement: Element) { rootElement.setAttribute("Target", "$target") } - override fun populate(rootElement: Element) - { + override fun populate(rootElement: Element) { target = rootElement.getAttributeInt("Target") spinner.value = target } - override fun stateChanged(e: ChangeEvent?) - { + override fun stateChanged(e: ChangeEvent?) { target = spinner.value as Int } - override fun randomise() - { + override fun randomise() { target = Random.nextInt(178) + 3 spinner.value = target } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeTotalRule.kt b/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeTotalRule.kt index e5ee2f44b..3f9af8353 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeTotalRule.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/AbstractDartzeeTotalRule.kt @@ -2,8 +2,9 @@ package dartzee.dartzee.aggregate import dartzee.`object`.DartboardSegment -abstract class AbstractDartzeeTotalRule: AbstractDartzeeAggregateRule() -{ - override fun isValidRound(segments: List) = isValidTotal(segments.sumOf { it.getTotal() }) +abstract class AbstractDartzeeTotalRule : AbstractDartzeeAggregateRule() { + override fun isValidRound(segments: List) = + isValidTotal(segments.sumOf { it.getTotal() }) + abstract fun isValidTotal(total: Int): Boolean -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleCluster.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleCluster.kt index 26b4ba7f1..9c8392c40 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleCluster.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleCluster.kt @@ -1,24 +1,22 @@ package dartzee.dartzee.aggregate -import dartzee.`object`.DartboardSegment import dartzee.core.util.getAttributeInt import dartzee.dartzee.IDartzeeRuleConfigurable +import dartzee.`object`.DartboardSegment import dartzee.utils.getNumbersWithinN -import org.w3c.dom.Document -import org.w3c.dom.Element import java.awt.FlowLayout import javax.swing.JPanel import javax.swing.JSpinner import javax.swing.SpinnerNumberModel import kotlin.random.Random +import org.w3c.dom.Document +import org.w3c.dom.Element -class DartzeeAggregateRuleCluster: AbstractDartzeeAggregateRule(), IDartzeeRuleConfigurable -{ +class DartzeeAggregateRuleCluster : AbstractDartzeeAggregateRule(), IDartzeeRuleConfigurable { override val configPanel = JPanel() val spinner = JSpinner() - init - { + init { configPanel.layout = FlowLayout() configPanel.add(spinner) @@ -26,8 +24,7 @@ class DartzeeAggregateRuleCluster: AbstractDartzeeAggregateRule(), IDartzeeRuleC spinner.value = 1 } - override fun isValidRound(segments: List): Boolean - { + override fun isValidRound(segments: List): Boolean { if (segments.any { it.isMiss() }) { return false } @@ -40,21 +37,20 @@ class DartzeeAggregateRuleCluster: AbstractDartzeeAggregateRule(), IDartzeeRuleC } override fun getRuleIdentifier() = "DartsCluster" + override fun toString() = "Darts spaced by at most " + override fun getDescription() = "Darts spaced by at most ${spinner.value}" - override fun writeXmlAttributes(doc: Document, rootElement: Element) - { + override fun writeXmlAttributes(doc: Document, rootElement: Element) { rootElement.setAttribute("Cluster", "${spinner.value}") } - override fun populate(rootElement: Element) - { + override fun populate(rootElement: Element) { spinner.value = rootElement.getAttributeInt("Cluster") } - override fun randomise() - { + override fun randomise() { spinner.value = Random.nextInt(4) + 1 } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDecreasing.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDecreasing.kt index d64dbf6c3..7773276fe 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDecreasing.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDecreasing.kt @@ -2,14 +2,13 @@ package dartzee.dartzee.aggregate import dartzee.`object`.DartboardSegment -class DartzeeAggregateRuleDecreasing: AbstractDartzeeAggregateRule() -{ - override fun isValidRound(segments: List): Boolean - { +class DartzeeAggregateRuleDecreasing : AbstractDartzeeAggregateRule() { + override fun isValidRound(segments: List): Boolean { val scores = segments.map { it.getTotal() } return scores.distinct().size == 3 && scores.sortedDescending() == scores } override fun getRuleIdentifier() = "DartsDecreasing" + override fun toString() = "Darts are decreasing" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDistinctScores.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDistinctScores.kt index 8cc43e814..1e216d289 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDistinctScores.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleDistinctScores.kt @@ -2,12 +2,9 @@ package dartzee.dartzee.aggregate import dartzee.`object`.DartboardSegment -class DartzeeAggregateRuleDistinctScores: AbstractDartzeeAggregateRule() -{ - override fun isValidRound(segments: List): Boolean - { - if (segments.any { it.isMiss() }) - { +class DartzeeAggregateRuleDistinctScores : AbstractDartzeeAggregateRule() { + override fun isValidRound(segments: List): Boolean { + if (segments.any { it.isMiss() }) { return false } @@ -15,5 +12,6 @@ class DartzeeAggregateRuleDistinctScores: AbstractDartzeeAggregateRule() } override fun getRuleIdentifier() = "DistinctScores" + override fun toString() = "Darts are distinct" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleIncreasing.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleIncreasing.kt index 775e7924d..83a820808 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleIncreasing.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleIncreasing.kt @@ -2,14 +2,13 @@ package dartzee.dartzee.aggregate import dartzee.`object`.DartboardSegment -class DartzeeAggregateRuleIncreasing: AbstractDartzeeAggregateRule() -{ - override fun isValidRound(segments: List): Boolean - { +class DartzeeAggregateRuleIncreasing : AbstractDartzeeAggregateRule() { + override fun isValidRound(segments: List): Boolean { val scores = segments.map { it.getTotal() } return scores.distinct().size == 3 && scores.sorted() == scores } override fun getRuleIdentifier() = "DartsIncreasing" + override fun toString() = "Darts are increasing" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleRepeats.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleRepeats.kt index c41816024..b8feed0ec 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleRepeats.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleRepeats.kt @@ -3,20 +3,18 @@ package dartzee.dartzee.aggregate import dartzee.`object`.Dart import dartzee.`object`.DartboardSegment -class DartzeeAggregateRuleRepeats: AbstractDartzeeAggregateRule() -{ - override fun isValidRound(segments: List): Boolean - { +class DartzeeAggregateRuleRepeats : AbstractDartzeeAggregateRule() { + override fun isValidRound(segments: List): Boolean { val nonMissGroups = segments.filterNot { it.isMiss() }.groupBy { it.score }.values return nonMissGroups.any { it.size > 1 } } override fun getRuleIdentifier() = "DartRepeats" + override fun toString() = "Score repeats" - override fun getScoringDarts(darts: List): List - { + override fun getScoringDarts(darts: List): List { val nonMissGroups = darts.filterNot { it.multiplier == 0 }.groupBy { it.score }.values return nonMissGroups.firstOrNull { it.size > 1 }.orEmpty() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleSpread.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleSpread.kt index 403f9ad7d..e820ad97e 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleSpread.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeAggregateRuleSpread.kt @@ -1,24 +1,22 @@ package dartzee.dartzee.aggregate -import dartzee.`object`.DartboardSegment import dartzee.core.util.getAttributeInt import dartzee.dartzee.IDartzeeRuleConfigurable +import dartzee.`object`.DartboardSegment import dartzee.utils.getNumbersWithinN -import org.w3c.dom.Document -import org.w3c.dom.Element import java.awt.FlowLayout import javax.swing.JPanel import javax.swing.JSpinner import javax.swing.SpinnerNumberModel import kotlin.random.Random +import org.w3c.dom.Document +import org.w3c.dom.Element -class DartzeeAggregateRuleSpread: AbstractDartzeeAggregateRule(), IDartzeeRuleConfigurable -{ +class DartzeeAggregateRuleSpread : AbstractDartzeeAggregateRule(), IDartzeeRuleConfigurable { override val configPanel = JPanel() val spinner = JSpinner() - init - { + init { configPanel.layout = FlowLayout() configPanel.add(spinner) @@ -26,8 +24,7 @@ class DartzeeAggregateRuleSpread: AbstractDartzeeAggregateRule(), IDartzeeRuleCo spinner.value = 1 } - override fun isValidRound(segments: List): Boolean - { + override fun isValidRound(segments: List): Boolean { if (segments.any { it.isMiss() || it.score == 25 }) { return false } @@ -45,21 +42,20 @@ class DartzeeAggregateRuleSpread: AbstractDartzeeAggregateRule(), IDartzeeRuleCo } override fun getRuleIdentifier() = "DartsSpread" + override fun toString() = "Darts spaced by at least " + override fun getDescription() = "Darts spaced by at least ${spinner.value}" - override fun writeXmlAttributes(doc: Document, rootElement: Element) - { + override fun writeXmlAttributes(doc: Document, rootElement: Element) { rootElement.setAttribute("Spread", "${spinner.value}") } - override fun populate(rootElement: Element) - { + override fun populate(rootElement: Element) { spinner.value = rootElement.getAttributeInt("Spread") } - override fun randomise() - { + override fun randomise() { spinner.value = Random.nextInt(4) + 1 } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEqualTo.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEqualTo.kt index ab74c250c..c5fe444b7 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEqualTo.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEqualTo.kt @@ -1,7 +1,6 @@ package dartzee.dartzee.aggregate -class DartzeeTotalRuleEqualTo: AbstractDartzeeRuleTotalSize() -{ +class DartzeeTotalRuleEqualTo : AbstractDartzeeRuleTotalSize() { override fun getRuleIdentifier() = "EqualTo" override fun isValidTotal(total: Int) = total == target @@ -9,4 +8,4 @@ class DartzeeTotalRuleEqualTo: AbstractDartzeeRuleTotalSize() override fun toString() = "Total equal to" override fun getDescription() = "Total = $target" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEven.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEven.kt index 112421734..e0e0c2a81 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEven.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleEven.kt @@ -1,9 +1,9 @@ package dartzee.dartzee.aggregate -class DartzeeTotalRuleEven: AbstractDartzeeTotalRule() -{ +class DartzeeTotalRuleEven : AbstractDartzeeTotalRule() { override fun getRuleIdentifier() = "Even" override fun isValidTotal(total: Int) = (total % 2) == 0 + override fun toString() = "Total is even" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleGreaterThan.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleGreaterThan.kt index 5a488f703..048d0fddd 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleGreaterThan.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleGreaterThan.kt @@ -1,7 +1,6 @@ package dartzee.dartzee.aggregate -class DartzeeTotalRuleGreaterThan: AbstractDartzeeRuleTotalSize() -{ +class DartzeeTotalRuleGreaterThan : AbstractDartzeeRuleTotalSize() { override fun getRuleIdentifier() = "GreaterThan" override fun isValidTotal(total: Int) = total > target @@ -9,4 +8,4 @@ class DartzeeTotalRuleGreaterThan: AbstractDartzeeRuleTotalSize() override fun toString() = "Total greater than" override fun getDescription() = "Total > $target" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleLessThan.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleLessThan.kt index 6bf658bd3..311ce92a5 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleLessThan.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleLessThan.kt @@ -1,7 +1,6 @@ package dartzee.dartzee.aggregate -class DartzeeTotalRuleLessThan: AbstractDartzeeRuleTotalSize() -{ +class DartzeeTotalRuleLessThan : AbstractDartzeeRuleTotalSize() { override fun getRuleIdentifier() = "LessThan" override fun isValidTotal(total: Int) = total < target @@ -9,4 +8,4 @@ class DartzeeTotalRuleLessThan: AbstractDartzeeRuleTotalSize() override fun toString() = "Total less than" override fun getDescription() = "Total < $target" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleMultipleOf.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleMultipleOf.kt index 4228e38a3..ed451bd32 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleMultipleOf.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleMultipleOf.kt @@ -1,7 +1,6 @@ package dartzee.dartzee.aggregate -class DartzeeTotalRuleMultipleOf: AbstractDartzeeRuleTotalSize() -{ +class DartzeeTotalRuleMultipleOf : AbstractDartzeeRuleTotalSize() { override fun getRuleIdentifier() = "MultipleOf" override fun isValidTotal(total: Int) = total % target == 0 @@ -9,4 +8,4 @@ class DartzeeTotalRuleMultipleOf: AbstractDartzeeRuleTotalSize() override fun toString() = "Total multiple of" override fun getDescription() = "Total multiple of $target" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleOdd.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleOdd.kt index d6dc1b1f2..bfb7cf50e 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleOdd.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRuleOdd.kt @@ -1,9 +1,9 @@ package dartzee.dartzee.aggregate -class DartzeeTotalRuleOdd: AbstractDartzeeTotalRule() -{ +class DartzeeTotalRuleOdd : AbstractDartzeeTotalRule() { override fun getRuleIdentifier() = "Odd" override fun isValidTotal(total: Int) = (total % 2) != 0 + override fun toString() = "Total is odd" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRulePrime.kt b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRulePrime.kt index 7d241ec32..29e541618 100644 --- a/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRulePrime.kt +++ b/src/main/kotlin/dartzee/dartzee/aggregate/DartzeeTotalRulePrime.kt @@ -2,10 +2,10 @@ package dartzee.dartzee.aggregate import org.apache.commons.math3.primes.Primes -class DartzeeTotalRulePrime: AbstractDartzeeTotalRule() -{ +class DartzeeTotalRulePrime : AbstractDartzeeTotalRule() { override fun getRuleIdentifier() = "Prime" override fun isValidTotal(total: Int) = Primes.isPrime(total) + override fun toString() = "Total is prime" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRule.kt b/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRule.kt index cd00c6c8c..6a7c01c79 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRule.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRule.kt @@ -4,9 +4,8 @@ import dartzee.dartzee.AbstractDartzeeRule import dartzee.`object`.Dart import dartzee.`object`.DartboardSegment -abstract class AbstractDartzeeDartRule: AbstractDartzeeRule() -{ +abstract class AbstractDartzeeDartRule : AbstractDartzeeRule() { abstract fun isValidSegment(segment: DartboardSegment): Boolean fun isValidDart(dart: Dart) = isValidSegment(DartboardSegment(dart.segmentType, dart.score)) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRuleConfigurable.kt b/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRuleConfigurable.kt index f8df35215..dc30158a1 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRuleConfigurable.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/AbstractDartzeeDartRuleConfigurable.kt @@ -3,7 +3,7 @@ package dartzee.dartzee.dart import dartzee.dartzee.IDartzeeRuleConfigurable import javax.swing.JPanel -abstract class AbstractDartzeeDartRuleConfigurable: AbstractDartzeeDartRule(), IDartzeeRuleConfigurable -{ +abstract class AbstractDartzeeDartRuleConfigurable : + AbstractDartzeeDartRule(), IDartzeeRuleConfigurable { override var configPanel = JPanel() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleAny.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleAny.kt index f8c77f633..4aa73665d 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleAny.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleAny.kt @@ -2,8 +2,8 @@ package dartzee.dartzee.dart import dartzee.`object`.DartboardSegment -class DartzeeDartRuleAny: AbstractDartzeeDartRule() -{ +class DartzeeDartRuleAny : AbstractDartzeeDartRule() { override fun getRuleIdentifier() = "Any" + override fun isValidSegment(segment: DartboardSegment) = true -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleColour.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleColour.kt index 14b622c27..27d763057 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleColour.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleColour.kt @@ -3,17 +3,16 @@ package dartzee.dartzee.dart import dartzee.`object`.DEFAULT_COLOUR_WRAPPER import dartzee.`object`.DartboardSegment import dartzee.utils.DartsColour -import org.w3c.dom.Document -import org.w3c.dom.Element import java.awt.Color import java.awt.FlowLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JCheckBox import kotlin.random.Random +import org.w3c.dom.Document +import org.w3c.dom.Element -class DartzeeDartRuleColour: AbstractDartzeeDartRuleConfigurable(), ActionListener -{ +class DartzeeDartRuleColour : AbstractDartzeeDartRuleConfigurable(), ActionListener { var black = false var white = false var green = false @@ -24,8 +23,7 @@ class DartzeeDartRuleColour: AbstractDartzeeDartRuleConfigurable(), ActionListen val cbGreen = JCheckBox("Green") val cbRed = JCheckBox("Red") - init - { + init { configPanel.layout = FlowLayout() cbBlack.name = "Black" @@ -44,58 +42,51 @@ class DartzeeDartRuleColour: AbstractDartzeeDartRuleConfigurable(), ActionListen cbRed.addActionListener(this) } - override fun isValidSegment(segment: DartboardSegment): Boolean - { - if (segment.isMiss()) - { + override fun isValidSegment(segment: DartboardSegment): Boolean { + if (segment.isMiss()) { return false } val color = DEFAULT_COLOUR_WRAPPER.getColour(segment) - return (color == DartsColour.DARTBOARD_BLACK && black) - || (color == Color.WHITE && white) - || (color == Color.GREEN && green) - || (color == Color.RED && red) + return (color == DartsColour.DARTBOARD_BLACK && black) || + (color == Color.WHITE && white) || + (color == Color.GREEN && green) || + (color == Color.RED && red) } override fun getRuleIdentifier() = "Colour" - override fun validate(): String - { - if (!red && !green && !black && !white) - { + + override fun validate(): String { + if (!red && !green && !black && !white) { return "You must select at least one colour." } return "" } - override fun getDescription(): String - { + override fun getDescription(): String { val colourList = mutableListOf() if (red) colourList.add("R") if (green) colourList.add("G") if (black) colourList.add("B") if (white) colourList.add("W") - if (colourList.size == 4) - { + if (colourList.size == 4) { return "Any" } return colourList.joinToString("/") } - override fun writeXmlAttributes(doc: Document, rootElement: Element) - { + override fun writeXmlAttributes(doc: Document, rootElement: Element) { rootElement.setAttribute("Black", black.toString()) rootElement.setAttribute("White", white.toString()) rootElement.setAttribute("Red", red.toString()) rootElement.setAttribute("Green", green.toString()) } - override fun populate(rootElement: Element) - { + override fun populate(rootElement: Element) { cbBlack.isSelected = rootElement.getAttribute("Black")?.toBoolean() ?: false cbWhite.isSelected = rootElement.getAttribute("White")?.toBoolean() ?: false cbRed.isSelected = rootElement.getAttribute("Red")?.toBoolean() ?: false @@ -104,21 +95,18 @@ class DartzeeDartRuleColour: AbstractDartzeeDartRuleConfigurable(), ActionListen updateFromUi() } - override fun actionPerformed(e: ActionEvent?) - { + override fun actionPerformed(e: ActionEvent?) { updateFromUi() } - private fun updateFromUi() - { + private fun updateFromUi() { black = cbBlack.isSelected white = cbWhite.isSelected green = cbGreen.isSelected red = cbRed.isSelected } - override fun randomise() - { + override fun randomise() { val result = Random.nextInt(14) + 1 cbBlack.isSelected = (result and 1) > 0 @@ -128,5 +116,4 @@ class DartzeeDartRuleColour: AbstractDartzeeDartRuleConfigurable(), ActionListen updateFromUi() } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleCustom.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleCustom.kt index 522c5607e..c94d16311 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleCustom.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleCustom.kt @@ -3,24 +3,22 @@ package dartzee.dartzee.dart import dartzee.core.bean.addUpdateListener import dartzee.`object`.DartboardSegment import dartzee.utils.InjectedThings -import org.w3c.dom.Document -import org.w3c.dom.Element import java.awt.FlowLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JButton import javax.swing.JTextField +import org.w3c.dom.Document +import org.w3c.dom.Element -class DartzeeDartRuleCustom: AbstractDartzeeDartRuleConfigurable(), ActionListener -{ +class DartzeeDartRuleCustom : AbstractDartzeeDartRuleConfigurable(), ActionListener { val segments = mutableSetOf() var name = "" val btnConfigure = JButton("Configure") val tfName = JTextField() - init - { + init { configPanel.layout = FlowLayout() configPanel.add(btnConfigure) configPanel.add(tfName) @@ -38,42 +36,37 @@ class DartzeeDartRuleCustom: AbstractDartzeeDartRuleConfigurable(), ActionListen override fun getDescription() = name.ifEmpty { "Custom" } - override fun writeXmlAttributes(doc: Document, rootElement: Element) - { + override fun writeXmlAttributes(doc: Document, rootElement: Element) { segments.forEach { it.writeXml(rootElement, "Segment") } rootElement.setAttribute("Name", name) } - override fun populate(rootElement: Element) - { + override fun populate(rootElement: Element) { segments.addAll(DartboardSegment.readList(rootElement, "Segment")) name = rootElement.getAttribute("Name") tfName.text = name } - override fun validate(): String - { - if (segments.isEmpty()) - { + override fun validate(): String { + if (segments.isEmpty()) { return "You must select at least one segment." } return "" } - override fun actionPerformed(e: ActionEvent?) - { - if (e?.source == btnConfigure) - { - val updatedSelection = InjectedThings.dartzeeSegmentFactory.selectSegments(segments.toSet()) + override fun actionPerformed(e: ActionEvent?) { + if (e?.source == btnConfigure) { + val updatedSelection = + InjectedThings.dartzeeSegmentFactory.selectSegments(segments.toSet()) segments.clear() segments.addAll(updatedSelection) } name = tfName.text - //Propagate an action event to any other listeners + // Propagate an action event to any other listeners btnConfigure.actionListeners.find { it != this }?.actionPerformed(e) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleEven.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleEven.kt index 6ece2f414..5c320f570 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleEven.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleEven.kt @@ -2,9 +2,9 @@ package dartzee.dartzee.dart import dartzee.`object`.DartboardSegment -class DartzeeDartRuleEven : AbstractDartzeeDartRule() -{ - override fun isValidSegment(segment: DartboardSegment) = segment.score % 2 == 0 && !segment.isMiss() +class DartzeeDartRuleEven : AbstractDartzeeDartRule() { + override fun isValidSegment(segment: DartboardSegment) = + segment.score % 2 == 0 && !segment.isMiss() override fun getRuleIdentifier() = "Even" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleInner.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleInner.kt index 4d74aa0f8..a72e8f9f5 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleInner.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleInner.kt @@ -3,14 +3,12 @@ package dartzee.dartzee.dart import dartzee.`object`.DartboardSegment import dartzee.`object`.SegmentType -class DartzeeDartRuleInner : AbstractDartzeeDartRule() -{ - override fun isValidSegment(segment: DartboardSegment): Boolean - { - return segment.type == SegmentType.INNER_SINGLE - || segment.type == SegmentType.TREBLE - || segment.score == 25 +class DartzeeDartRuleInner : AbstractDartzeeDartRule() { + override fun isValidSegment(segment: DartboardSegment): Boolean { + return segment.type == SegmentType.INNER_SINGLE || + segment.type == SegmentType.TREBLE || + segment.score == 25 } override fun getRuleIdentifier() = "Inner" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleMiss.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleMiss.kt index 2651a38fb..04097d065 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleMiss.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleMiss.kt @@ -2,9 +2,8 @@ package dartzee.dartzee.dart import dartzee.`object`.DartboardSegment -class DartzeeDartRuleMiss: AbstractDartzeeDartRule() -{ +class DartzeeDartRuleMiss : AbstractDartzeeDartRule() { override fun isValidSegment(segment: DartboardSegment) = segment.isMiss() override fun getRuleIdentifier() = "Miss" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOdd.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOdd.kt index 677eac19a..8f3d36428 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOdd.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOdd.kt @@ -2,9 +2,9 @@ package dartzee.dartzee.dart import dartzee.`object`.DartboardSegment -class DartzeeDartRuleOdd : AbstractDartzeeDartRule() -{ - override fun isValidSegment(segment: DartboardSegment) = segment.score % 2 != 0 && !segment.isMiss() +class DartzeeDartRuleOdd : AbstractDartzeeDartRule() { + override fun isValidSegment(segment: DartboardSegment) = + segment.score % 2 != 0 && !segment.isMiss() override fun getRuleIdentifier() = "Odd" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOuter.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOuter.kt index 6933ca11d..84bf6923a 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOuter.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleOuter.kt @@ -3,12 +3,9 @@ package dartzee.dartzee.dart import dartzee.`object`.DartboardSegment import dartzee.`object`.SegmentType -class DartzeeDartRuleOuter : AbstractDartzeeDartRule() -{ - override fun isValidSegment(segment: DartboardSegment): Boolean - { - if (segment.score == 25) - { +class DartzeeDartRuleOuter : AbstractDartzeeDartRule() { + override fun isValidSegment(segment: DartboardSegment): Boolean { + if (segment.score == 25) { return false } @@ -16,4 +13,4 @@ class DartzeeDartRuleOuter : AbstractDartzeeDartRule() } override fun getRuleIdentifier() = "Outer" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleScore.kt b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleScore.kt index 86f10358d..004c912b7 100644 --- a/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleScore.kt +++ b/src/main/kotlin/dartzee/dartzee/dart/DartzeeDartRuleScore.kt @@ -3,20 +3,18 @@ package dartzee.dartzee.dart import dartzee.bean.SpinnerSingleSelector import dartzee.core.util.getAttributeInt import dartzee.`object`.DartboardSegment -import org.w3c.dom.Document -import org.w3c.dom.Element import java.awt.FlowLayout import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener +import org.w3c.dom.Document +import org.w3c.dom.Element -class DartzeeDartRuleScore: AbstractDartzeeDartRuleConfigurable(), ChangeListener -{ +class DartzeeDartRuleScore : AbstractDartzeeDartRuleConfigurable(), ChangeListener { var score = 20 val spinner = SpinnerSingleSelector() - init - { + init { configPanel.layout = FlowLayout() configPanel.add(spinner) @@ -24,33 +22,33 @@ class DartzeeDartRuleScore: AbstractDartzeeDartRuleConfigurable(), ChangeListene spinner.value = score } - override fun isValidSegment(segment: DartboardSegment) = segment.score == score && !segment.isMiss() + override fun isValidSegment(segment: DartboardSegment) = + segment.score == score && !segment.isMiss() override fun getRuleIdentifier() = "Score" + override fun getDescription() = "$score" - override fun writeXmlAttributes(doc: Document, rootElement: Element) - { + override fun writeXmlAttributes(doc: Document, rootElement: Element) { rootElement.setAttribute("Target", "$score") } - override fun populate(rootElement: Element) - { + override fun populate(rootElement: Element) { score = rootElement.getAttributeInt("Target") spinner.value = score } - override fun stateChanged(e: ChangeEvent?) - { + override fun stateChanged(e: ChangeEvent?) { score = spinner.value as Int } - override fun randomise() - { + override fun randomise() { val list = mutableListOf(25) - for (i in 1..20) { list.add(i) } + for (i in 1..20) { + list.add(i) + } score = list.random() spinner.value = score } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/AbstractEntity.kt b/src/main/kotlin/dartzee/db/AbstractEntity.kt index bb525e8f2..4bc75dcdd 100644 --- a/src/main/kotlin/dartzee/db/AbstractEntity.kt +++ b/src/main/kotlin/dartzee/db/AbstractEntity.kt @@ -26,47 +26,45 @@ import java.sql.Timestamp import java.util.* import java.util.regex.Pattern -abstract class AbstractEntity>(protected val database: Database = InjectedThings.mainDatabase) -{ - //DB Fields +abstract class AbstractEntity>( + protected val database: Database = InjectedThings.mainDatabase +) { + // DB Fields var rowId: String = "" var dtCreation = getSqlDateNow() var dtLastUpdate = DateStatics.END_OF_TIME - //other variables + // other variables var retrievedFromDb = false - /** - * Abstract fns - */ + /** Abstract fns */ abstract fun getTableName(): EntityName + abstract fun getCreateTableSqlSpecific(): String - /** - * Default implementations - */ + /** Default implementations */ open fun getColumnsAllowedToBeUnset() = listOf() + open fun addListsOfColumnsForIndexes(indexes: MutableList>) {} + open fun cacheValuesWhileResultSetActive() {} + open fun includeInSync() = true - /** - * Helpers - */ + /** Helpers */ private fun getColumnCount() = getColumns().size - private fun getCreateTableColumnSql() = "RowId VARCHAR(36) PRIMARY KEY, DtCreation Timestamp NOT NULL, DtLastUpdate Timestamp NOT NULL, ${getCreateTableSqlSpecific()}" + private fun getCreateTableColumnSql() = + "RowId VARCHAR(36) PRIMARY KEY, DtCreation Timestamp NOT NULL, DtLastUpdate Timestamp NOT NULL, ${getCreateTableSqlSpecific()}" - fun getColumns(): MutableList - { + fun getColumns(): MutableList { val columnCreateSql = getCreateTableColumnSql() val cols = columnCreateSql.split(",") - return cols.map{ getColumnNameFromCreateSql(it) }.toMutableList() + return cols.map { getColumnNameFromCreateSql(it) }.toMutableList() } - private fun getColumnsExcluding(vararg columnsToExclude: String): MutableList - { + private fun getColumnsExcluding(vararg columnsToExclude: String): MutableList { val columns = getColumns() columnsToExclude.forEach { columns.remove(it) } return columns @@ -74,8 +72,7 @@ abstract class AbstractEntity>(protected val database: Dat fun getTableNameUpperCase() = getTableName().name.uppercase() - fun factoryFromResultSet(rs: ResultSet): E - { + fun factoryFromResultSet(rs: ResultSet): E { val ret = factory()!! ret.rowId = rs.getString("RowId") @@ -95,62 +92,56 @@ abstract class AbstractEntity>(protected val database: Dat @Suppress("UNCHECKED_CAST") private fun factory(db: Database = database): E? = - try - { + try { javaClass.getDeclaredConstructor(Database::class.java).newInstance(db) as E - } - catch (t: Throwable) - { - logger.error(CODE_INSTANTIATION_ERROR, "Failed to instantiate ${javaClass.simpleName}", t) + } catch (t: Throwable) { + logger.error( + CODE_INSTANTIATION_ERROR, + "Failed to instantiate ${javaClass.simpleName}", + t + ) null } - fun columnCanBeUnset(columnName: String) = getColumnsAllowedToBeUnset().contains(columnName) - open fun assignRowId(): String - { + open fun assignRowId(): String { rowId = UUID.randomUUID().toString() return rowId } - fun retrieveEntity(whereSql: String): E? - { + fun retrieveEntity(whereSql: String): E? { val entities = retrieveEntities(whereSql) - if (entities.size > 1) - { - logger.error(CODE_SQL_EXCEPTION, - "Retrieved ${entities.size} rows from ${getTableName()}. Expected 1. WhereSQL [$whereSql]", - KEY_SQL to whereSql) + if (entities.size > 1) { + logger.error( + CODE_SQL_EXCEPTION, + "Retrieved ${entities.size} rows from ${getTableName()}. Expected 1. WhereSQL [$whereSql]", + KEY_SQL to whereSql + ) } return entities.firstOrNull() } - fun retrieveEntities(whereSql: String = "", alias: String = ""): MutableList - { + fun retrieveEntities(whereSql: String = "", alias: String = ""): MutableList { var queryWithFrom = "FROM ${getTableName()}" - if (alias.isNotEmpty()) - { + if (alias.isNotEmpty()) { queryWithFrom += " $alias" } - if (whereSql.isNotEmpty()) - { + if (whereSql.isNotEmpty()) { queryWithFrom += " WHERE $whereSql" } return retrieveEntitiesWithFrom(queryWithFrom, alias) } - private fun retrieveEntitiesWithFrom(whereSqlWithFrom: String, alias: String): MutableList - { + private fun retrieveEntitiesWithFrom(whereSqlWithFrom: String, alias: String): MutableList { val query = "SELECT " + getColumnsForSelectStatement(alias) + " " + whereSqlWithFrom val ret = mutableListOf() database.executeQuery(query).use { rs -> - while (rs.next()) - { + while (rs.next()) { val entity = factoryFromResultSet(rs) ret.add(entity) } @@ -159,22 +150,20 @@ abstract class AbstractEntity>(protected val database: Dat return ret } - fun retrieveForId(rowId: String, stackTraceIfNotFound: Boolean = true): E? - { + fun retrieveForId(rowId: String, stackTraceIfNotFound: Boolean = true): E? { val entity = retrieveEntity("RowId = '$rowId'") - if (entity == null && stackTraceIfNotFound) - { - logger.error(CODE_SQL_EXCEPTION, - "Failed to find ${getTableName()} for ID [$rowId]", - KEY_SQL to "RowId = '$rowId'") + if (entity == null && stackTraceIfNotFound) { + logger.error( + CODE_SQL_EXCEPTION, + "Failed to find ${getTableName()} for ID [$rowId]", + KEY_SQL to "RowId = '$rowId'" + ) } - return entity } - fun deleteFromDatabase(): Boolean - { + fun deleteFromDatabase(): Boolean { val sql = "DELETE FROM ${getTableName()} WHERE RowId = '$rowId'" val success = database.executeUpdate(sql) if (success && includeInSync()) { @@ -184,18 +173,18 @@ abstract class AbstractEntity>(protected val database: Dat return success } - fun deleteAll() - { - if (includeInSync()) - { - logger.error(CODE_DELETE_ERROR, "Wiping of ${getTableName()} will not be audited. This will break the sync!") + fun deleteAll() { + if (includeInSync()) { + logger.error( + CODE_DELETE_ERROR, + "Wiping of ${getTableName()} will not be audited. This will break the sync!" + ) } database.executeUpdate("DELETE FROM ${getTableName()}") } - fun deleteWhere(whereSql: String): Boolean - { + fun deleteWhere(whereSql: String): Boolean { val audits = retrieveEntities(whereSql).map { DeletionAuditEntity.factory(it) } val sql = "DELETE FROM ${getTableName()} WHERE $whereSql" val success = database.executeUpdate(sql) @@ -206,68 +195,62 @@ abstract class AbstractEntity>(protected val database: Dat return success } - fun saveToDatabase(dtLastUpdate: Timestamp = getSqlDateNow()) - { + fun saveToDatabase(dtLastUpdate: Timestamp = getSqlDateNow()) { this.dtLastUpdate = dtLastUpdate - if (retrievedFromDb) - { + if (retrievedFromDb) { updateDatabaseRow() - } - else - { + } else { insertIntoDatabase() } } fun count() = countWhere("") - fun countWhere(whereSql: String): Int - { + + fun countWhere(whereSql: String): Int { val fullWhere = if (whereSql.isNotEmpty()) "WHERE $whereSql" else "" return database.executeQueryAggregate("SELECT COUNT(1) FROM ${getTableName()} $fullWhere") } - /** - * Merge helpers - */ - fun countModifiedSince(dt: Timestamp?): Int - { + /** Merge helpers */ + fun countModifiedSince(dt: Timestamp?): Int { val whereSql = if (dt != null) "DtLastUpdate > ${dt.getSqlString()}" else "" return countWhere(whereSql) } - fun retrieveModifiedSince(dt: Timestamp?): List - { + + fun retrieveModifiedSince(dt: Timestamp?): List { val whereSql = if (dt != null) "DtLastUpdate > ${dt.getSqlString()}" else "" return retrieveEntities(whereSql).sortedBy { it.dtCreation } } - fun mergeIntoDatabase(otherDatabase: Database) - { - val otherDao = factory(otherDatabase) ?: throw ApplicationFault(CODE_MERGE_ERROR, "Failed to factory ${getTableName()} dao") + fun mergeIntoDatabase(otherDatabase: Database) { + val otherDao = + factory(otherDatabase) + ?: throw ApplicationFault( + CODE_MERGE_ERROR, + "Failed to factory ${getTableName()} dao" + ) val existingRow = otherDao.retrieveForId(rowId, false) - if (existingRow == null) - { + if (existingRow == null) { reassignLocalId(otherDatabase) insertIntoDatabase(otherDatabase) - } - else if (dtLastUpdate.after(existingRow.dtLastUpdate)) - { + } else if (dtLastUpdate.after(existingRow.dtLastUpdate)) { updateDatabaseRow(otherDatabase) } mergeImpl(otherDatabase) } + open fun reassignLocalId(otherDatabase: Database) {} + open fun mergeImpl(otherDatabase: Database) {} - private fun updateDatabaseRow(db: Database = database) - { + private fun updateDatabaseRow(db: Database = database) { val genericUpdate = buildUpdateQuery() var updateQuery = genericUpdate val conn = db.borrowConnection() - try - { + try { conn.prepareStatement(updateQuery).use { psUpdate -> updateQuery = writeValuesToStatement(psUpdate, 1, updateQuery) updateQuery = writeString(psUpdate, getColumnCount(), rowId, updateQuery) @@ -277,29 +260,31 @@ abstract class AbstractEntity>(protected val database: Dat val updateCount = psUpdate.updateCount - logger.logSql(updateQuery, genericUpdate, timer.getDuration(), updateCount, db.dbName) - - if (updateCount == 0) - { - logger.error(CODE_SQL_EXCEPTION, - "0 rows updated for statement $updateQuery", - KEY_SQL to updateQuery) + logger.logSql( + updateQuery, + genericUpdate, + timer.getDuration(), + updateCount, + db.dbName + ) + + if (updateCount == 0) { + logger.error( + CODE_SQL_EXCEPTION, + "0 rows updated for statement $updateQuery", + KEY_SQL to updateQuery + ) } } - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { throw WrappedSqlException(updateQuery, genericUpdate, sqle) - } - finally - { + } finally { db.returnConnection(conn) } } - private fun buildUpdateQuery(): String - { - //Some fun String manipulation + private fun buildUpdateQuery(): String { + // Some fun String manipulation var columns = getColumnsForSelectStatement() columns = columns.replaceFirst("RowId, ", "") columns = columns.replace(",", "=?,") @@ -308,37 +293,41 @@ abstract class AbstractEntity>(protected val database: Dat return "UPDATE ${getTableName()} SET $columns WHERE RowId=?" } - private fun insertIntoDatabase(db: Database = database) - { + private fun insertIntoDatabase(db: Database = database) { val genericInsert = "INSERT INTO ${getTableName()} VALUES ${getInsertBlockForStatement()}" var insertQuery = genericInsert val conn = db.borrowConnection() - try - { + try { conn.prepareStatement(insertQuery).use { psInsert -> insertQuery = writeValuesToInsertStatement(insertQuery, psInsert) val timer = DurationTimer() psInsert.executeUpdate() - logger.logSql(insertQuery, genericInsert, timer.getDuration(), psInsert.updateCount, db.dbName) - - //Set this so we can call save() again on the same object and get the right behaviour + logger.logSql( + insertQuery, + genericInsert, + timer.getDuration(), + psInsert.updateCount, + db.dbName + ) + + // Set this so we can call save() again on the same object and get the right + // behaviour retrievedFromDb = true } - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { throw WrappedSqlException(insertQuery, genericInsert, sqle) - } - finally - { + } finally { db.returnConnection(conn) } } - fun writeValuesToInsertStatement(emptyStatement: String, psInsert: PreparedStatement, entityNumber: Int = 0): String - { + fun writeValuesToInsertStatement( + emptyStatement: String, + psInsert: PreparedStatement, + entityNumber: Int = 0 + ): String { val adjustment = entityNumber * getColumnCount() var insertQuery = emptyStatement @@ -348,8 +337,11 @@ abstract class AbstractEntity>(protected val database: Dat return insertQuery } - private fun writeValuesToStatement(ps: PreparedStatement, startIx: Int, emptyStatement: String): String - { + private fun writeValuesToStatement( + ps: PreparedStatement, + startIx: Int, + emptyStatement: String + ): String { var ix = startIx var statementStr = emptyStatement getColumnsExcluding("RowId").forEach { @@ -361,30 +353,25 @@ abstract class AbstractEntity>(protected val database: Dat fun getInsertBlockForStatement() = "(${getColumns().joinToString{"?"}})" - open fun createTable(): Boolean - { - val createdTable = database.createTableIfNotExists(getTableName().name, getCreateTableColumnSql()) - if (createdTable) - { + open fun createTable(): Boolean { + val createdTable = + database.createTableIfNotExists(getTableName().name, getCreateTableColumnSql()) + if (createdTable) { createIndexes() } return createdTable } - private fun createIndexes() - { - //Also create the indexes + private fun createIndexes() { + // Also create the indexes val indexes = mutableListOf>() addListsOfColumnsForIndexes(indexes) - indexes.forEach{ - createIndex(it) - } + indexes.forEach { createIndex(it) } } - private fun createIndex(columns: List) - { + private fun createIndex(columns: List) { val columnList = columns.joinToString() val indexName = columnList.replace(", ", "_") @@ -392,19 +379,16 @@ abstract class AbstractEntity>(protected val database: Dat database.executeUpdate(statement) } - fun getColumnsForSelectStatement(alias: String = ""): String - { + fun getColumnsForSelectStatement(alias: String = ""): String { var cols = getColumns().toList() - if (alias.isNotEmpty()) - { - cols = cols.map{ "$alias.$it" } + if (alias.isNotEmpty()) { + cols = cols.map { "$alias.$it" } } return cols.joinToString() } - private fun getColumnNameFromCreateSql(col: String): String - { + private fun getColumnNameFromCreateSql(col: String): String { var colSanitised = col colSanitised = colSanitised.trim() colSanitised = colSanitised.replace("(", "") @@ -413,78 +397,104 @@ abstract class AbstractEntity>(protected val database: Dat return colSanitised.split(" ")[0] } - fun getField(fieldName: String): Any? - { + fun getField(fieldName: String): Any? { val getter = javaClass.getMethod("get$fieldName") return getter.invoke(this) } - fun setField(fieldName: String, value: Any?) - { + + fun setField(fieldName: String, value: Any?) { val getMethod = javaClass.getMethod("get$fieldName") val setMethod = javaClass.getDeclaredMethod("set$fieldName", getMethod.returnType) setMethod.invoke(this, value) } - fun getFieldType(fieldName: String): Class<*> - { + + fun getFieldType(fieldName: String): Class<*> { val getter = javaClass.getMethod("get$fieldName") return getter.returnType } - /** - * Write to statement methods - */ - private fun writeLong(ps: PreparedStatement, ix: Int, value: Long, statementStr: String): String - { + /** Write to statement methods */ + private fun writeLong( + ps: PreparedStatement, + ix: Int, + value: Long, + statementStr: String + ): String { ps.setLong(ix, value) return swapInValue(statementStr, value) } - private fun writeInt(ps: PreparedStatement, ix: Int, value: Int, statementStr: String): String - { + private fun writeInt(ps: PreparedStatement, ix: Int, value: Int, statementStr: String): String { ps.setInt(ix, value) return swapInValue(statementStr, value) } - private fun writeDouble(ps: PreparedStatement, ix: Int, value: Double, statementStr: String): String - { + private fun writeDouble( + ps: PreparedStatement, + ix: Int, + value: Double, + statementStr: String + ): String { ps.setDouble(ix, value) return swapInValue(statementStr, value) } - private fun writeString(ps: PreparedStatement, ix: Int, value: String, statementStr: String): String - { + private fun writeString( + ps: PreparedStatement, + ix: Int, + value: String, + statementStr: String + ): String { ps.setString(ix, value) return swapInValue(statementStr, "'$value'") } - private fun writeTimestamp(ps: PreparedStatement, ix: Int, value: Timestamp, statementStr: String): String - { + private fun writeTimestamp( + ps: PreparedStatement, + ix: Int, + value: Timestamp, + statementStr: String + ): String { ps.setTimestamp(ix, value) return swapInValue(statementStr, "'$value'") } - private fun writeBlob(ps: PreparedStatement, ix: Int, value: Blob, statementStr: String): String - { + private fun writeBlob( + ps: PreparedStatement, + ix: Int, + value: Blob, + statementStr: String + ): String { ps.setBlob(ix, value) val blobStr = "Blob (dataLength: " + value.length() + ")" return swapInValue(statementStr, blobStr) } - private fun writeBoolean(ps: PreparedStatement, ix: Int, value: Boolean, statementStr: String): String - { + private fun writeBoolean( + ps: PreparedStatement, + ix: Int, + value: Boolean, + statementStr: String + ): String { ps.setBoolean(ix, value) return swapInValue(statementStr, value) } - private fun swapInValue(statementStr: String, value: Any) = statementStr.replaceFirst(Pattern.quote("?").toRegex(), "" + value) + private fun swapInValue(statementStr: String, value: Any) = + statementStr.replaceFirst(Pattern.quote("?").toRegex(), "" + value) - private fun writeValue(ps: PreparedStatement, ix: Int, columnName: String, statementStr: String): String - { - val value = getField(columnName) ?: throw Exception("Attempted to write NULL value to ${getTableName()}.$columnName") + private fun writeValue( + ps: PreparedStatement, + ix: Int, + columnName: String, + statementStr: String + ): String { + val value = + getField(columnName) + ?: throw Exception("Attempted to write NULL value to ${getTableName()}.$columnName") - return when (getFieldType(columnName)) - { + return when (getFieldType(columnName)) { String::class.java -> writeString(ps, ix, value as String, statementStr) Long::class.java -> writeLong(ps, ix, value as Long, statementStr) Int::class.java -> writeInt(ps, ix, value as Int, statementStr) @@ -497,8 +507,7 @@ abstract class AbstractEntity>(protected val database: Dat } private fun getFieldFromResultSet(rs: ResultSet, columnName: String): Any? = - when(getFieldType(columnName)) - { + when (getFieldType(columnName)) { String::class.java -> rs.getString(columnName) Long::class.java -> rs.getLong(columnName) Int::class.java -> rs.getInt(columnName) diff --git a/src/main/kotlin/dartzee/db/AchievementEntity.kt b/src/main/kotlin/dartzee/db/AchievementEntity.kt index 2041a4ace..dca73a06e 100644 --- a/src/main/kotlin/dartzee/db/AchievementEntity.kt +++ b/src/main/kotlin/dartzee/db/AchievementEntity.kt @@ -14,9 +14,9 @@ import java.sql.Timestamp * * Points at a GameId if applicable, and uses DtCreation as the "date unlocked". */ -class AchievementEntity(database: Database = mainDatabase) : AbstractEntity(database) -{ - //DB Fields +class AchievementEntity(database: Database = mainDatabase) : + AbstractEntity(database) { + // DB Fields var playerId: String = "" var achievementType: AchievementType = AchievementType.X01_BEST_FINISH var gameIdEarned = "" @@ -24,32 +24,28 @@ class AchievementEntity(database: Database = mainDatabase) : AbstractEntity>) - { + override fun addListsOfColumnsForIndexes(indexes: MutableList>) { indexes.add(listOf("PlayerId", "AchievementType")) } - companion object - { - fun retrieveAchievements(playerId: String): MutableList - { + companion object { + fun retrieveAchievements(playerId: String): MutableList { val achievements = mutableListOf() val dao = AchievementEntity() @@ -61,8 +57,7 @@ class AchievementEntity(database: Database = mainDatabase) : AbstractEntity - while (rs.next()) - { + while (rs.next()) { val entity = dao.factoryFromResultSet(rs) entity.localGameIdEarned = rs.getLong("LocalGameId") @@ -73,108 +68,148 @@ class AchievementEntity(database: Database = mainDatabase) : AbstractEntity existingCounter && !decreasing - || counter < existingCounter && decreasing) - { + // Update the achievement if appropriate + if ( + counter > existingCounter && !decreasing || + counter < existingCounter && decreasing + ) { existingAchievement.achievementCounter = counter existingAchievement.gameIdEarned = gameId existingAchievement.dtAchieved = getSqlDateNow() existingAchievement.saveToDatabase() - triggerAchievementUnlock(existingCounter, counter, achievementType, playerId, gameId) + triggerAchievementUnlock( + existingCounter, + counter, + achievementType, + playerId, + gameId + ) } } } - fun insertAchievement(achievementType: AchievementType, playerId: String, gameId: String, detail: String = "", counter: Int = -1) - { - val sql = "SELECT COUNT(1) FROM Achievement WHERE PlayerId = '$playerId' AND AchievementType = '$achievementType'" + fun insertAchievement( + achievementType: AchievementType, + playerId: String, + gameId: String, + detail: String = "", + counter: Int = -1 + ) { + val sql = + "SELECT COUNT(1) FROM Achievement WHERE PlayerId = '$playerId' AND AchievementType = '$achievementType'" val count = mainDatabase.executeQueryAggregate(sql) factoryAndSave(achievementType, playerId, gameId, counter, detail) triggerAchievementUnlock(count, count + 1, achievementType, playerId, gameId) } - fun insertAchievementWithCounter(achievementType: AchievementType, playerId: String, gameId: String, detail: String, counter: Int) - { - val sql = "SELECT SUM(AchievementCounter) FROM Achievement WHERE PlayerId = '$playerId' AND AchievementType = '$achievementType'" + fun insertAchievementWithCounter( + achievementType: AchievementType, + playerId: String, + gameId: String, + detail: String, + counter: Int + ) { + val sql = + "SELECT SUM(AchievementCounter) FROM Achievement WHERE PlayerId = '$playerId' AND AchievementType = '$achievementType'" val count = mainDatabase.executeQueryAggregate(sql) factoryAndSave(achievementType, playerId, gameId, counter, detail) triggerAchievementUnlock(count, count + counter, achievementType, playerId, gameId) } - fun insertForUniqueCounter(achievementType: AchievementType, playerId: String, gameId: String, counter: Int, detail: String) - { + fun insertForUniqueCounter( + achievementType: AchievementType, + playerId: String, + gameId: String, + counter: Int, + detail: String + ) { val whereSql = "PlayerId = '$playerId' AND AchievementType = '$achievementType'" val achievementRows = AchievementEntity().retrieveEntities(whereSql) val hits = achievementRows.map { it.achievementCounter } - if (!hits.contains(counter)) - { + if (!hits.contains(counter)) { val newRow = factoryAndSave(achievementType, playerId, gameId, counter, detail) val allRows = achievementRows + newRow - triggerAchievementUnlock(achievementRows.size, achievementRows.size + 1, achievementType, playerId, gameId, allRows) + triggerAchievementUnlock( + achievementRows.size, + achievementRows.size + 1, + achievementType, + playerId, + gameId, + allRows + ) } } - private fun triggerAchievementUnlock(oldValue: Int, newValue: Int, achievementType: AchievementType, playerId: String, gameId: String, achievementRows: List? = null) - { + private fun triggerAchievementUnlock( + oldValue: Int, + newValue: Int, + achievementType: AchievementType, + playerId: String, + gameId: String, + achievementRows: List? = null + ) { val achievementTemplate = getAchievementForType(achievementType) ?: return - achievementRows?.let { achievementTemplate.initialiseFromDb(achievementRows,null) } + achievementRows?.let { achievementTemplate.initialiseFromDb(achievementRows, null) } triggerAchievementUnlock(oldValue, newValue, achievementTemplate, playerId, gameId) } - fun triggerAchievementUnlock(oldValue: Int, newValue: Int, achievementTemplate: AbstractAchievement, playerId: String, gameId: String) - { - //Work out if the threshold has changed + fun triggerAchievementUnlock( + oldValue: Int, + newValue: Int, + achievementTemplate: AbstractAchievement, + playerId: String, + gameId: String + ) { + // Work out if the threshold has changed achievementTemplate.attainedValue = oldValue val oldColor = achievementTemplate.getColor(false) achievementTemplate.attainedValue = newValue val newColor = achievementTemplate.getColor(false) - if (oldColor !== newColor) - { - //Hooray we've done a thing! + if (oldColor !== newColor) { + // Hooray we've done a thing! val scrn = ScreenCache.getDartsGameScreen(gameId) scrn?.achievementUnlocked(gameId, playerId, achievementTemplate) } } - fun factory(achievementType: AchievementType, - playerId: String, - gameId: String, - counter: Int, - achievementDetail: String, - dtAchieved: Timestamp, - database: Database = mainDatabase): AchievementEntity - { + fun factory( + achievementType: AchievementType, + playerId: String, + gameId: String, + counter: Int, + achievementDetail: String, + dtAchieved: Timestamp, + database: Database = mainDatabase + ): AchievementEntity { val ae = AchievementEntity(database) ae.assignRowId() ae.achievementType = achievementType @@ -186,15 +221,25 @@ class AchievementEntity(database: Database = mainDatabase) : AbstractEntity, database: Database = mainDatabase) - { + /** Entity insert */ + fun insert(vararg entities: AbstractEntity<*>, database: Database = mainDatabase) { insert(entities.toList(), database = database) } - fun insert(entities: List>, rowsPerThread: Int = 5000, rowsPerStatement: Int = 100, database: Database = mainDatabase) - { - if (entities.isEmpty()) - { + + fun insert( + entities: List>, + rowsPerThread: Int = 5000, + rowsPerStatement: Int = 100, + database: Database = mainDatabase + ) { + if (entities.isEmpty()) { return } val tableName = entities.first().getTableName() - if (entities.any { it.retrievedFromDb }) - { - logger.error(CODE_SQL_EXCEPTION, "Attempting to bulk insert $tableName entities, but some are already in the database") + if (entities.any { it.retrievedFromDb }) { + logger.error( + CODE_SQL_EXCEPTION, + "Attempting to bulk insert $tableName entities, but some are already in the database" + ) return } val entitiesBatched = entities.chunked(rowsPerThread) - val threads = entitiesBatched.map { getInsertThreadForBatch(it, tableName, rowsPerStatement, database) } + val threads = + entitiesBatched.map { + getInsertThreadForBatch(it, tableName, rowsPerStatement, database) + } doBulkInsert(threads, tableName, entities.size, rowsPerStatement) - entities.forEach {it.retrievedFromDb = true} + entities.forEach { it.retrievedFromDb = true } } - private fun getInsertThreadForBatch(batch: List>, entityName: EntityName, rowsPerInsert: Int, database: Database): Thread - { + + private fun getInsertThreadForBatch( + batch: List>, + entityName: EntityName, + rowsPerInsert: Int, + database: Database + ): Thread { return Thread { batch.chunked(rowsPerInsert).forEach { entities -> - val genericInsert = "INSERT INTO $entityName VALUES ${entities.joinToString{it.getInsertBlockForStatement()}}" + val genericInsert = + "INSERT INTO $entityName VALUES ${entities.joinToString{it.getInsertBlockForStatement()}}" var insertQuery = genericInsert val conn = database.borrowConnection() - try - { + try { conn.prepareStatement(insertQuery).use { ps -> entities.forEachIndexed { index, entity -> entity.dtLastUpdate = getSqlDateNow() - insertQuery = entity.writeValuesToInsertStatement(insertQuery, ps, index) + insertQuery = + entity.writeValuesToInsertStatement(insertQuery, ps, index) } val timer = DurationTimer() ps.executeUpdate() - if (logInserts) - { - logger.logSql(insertQuery, genericInsert, timer.getDuration(), ps.updateCount, database.dbName) + if (logInserts) { + logger.logSql( + insertQuery, + genericInsert, + timer.getDuration(), + ps.updateCount, + database.dbName + ) } } - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { logger.logSqlException(insertQuery, genericInsert, sqle) - } - finally - { + } finally { database.returnConnection(conn) } } } } - private fun doBulkInsert(threads: List, entityName: EntityName, rowCount: Int, rowsPerStatement: Int) - { - if (rowCount > 100) - { + private fun doBulkInsert( + threads: List, + entityName: EntityName, + rowCount: Int, + rowsPerStatement: Int + ) { + if (rowCount > 100) { logInserts = false - logger.info(CODE_BULK_SQL, "Inserting $rowCount rows into $entityName (${threads.size} threads @ $rowsPerStatement rows per insert)") + logger.info( + CODE_BULK_SQL, + "Inserting $rowCount rows into $entityName (${threads.size} threads @ $rowsPerStatement rows per insert)" + ) } threads.forEach { it.start() } @@ -90,4 +108,4 @@ object BulkInserter logInserts = true } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/DartEntity.kt b/src/main/kotlin/dartzee/db/DartEntity.kt index 56a436491..ade128133 100644 --- a/src/main/kotlin/dartzee/db/DartEntity.kt +++ b/src/main/kotlin/dartzee/db/DartEntity.kt @@ -5,11 +5,8 @@ import dartzee.`object`.SegmentType import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase -class DartEntity(database: Database = mainDatabase) : AbstractEntity(database) -{ - /** - * DB fields - */ +class DartEntity(database: Database = mainDatabase) : AbstractEntity(database) { + /** DB fields */ var playerId = "" var participantId = "" var roundNumber = -1 @@ -21,27 +18,29 @@ class DartEntity(database: Database = mainDatabase) : AbstractEntity override fun getTableName() = EntityName.Dart - override fun getCreateTableSqlSpecific(): String - { - return ("PlayerId VARCHAR(36) NOT NULL, " - + "ParticipantId VARCHAR(36) NOT NULL, " - + "RoundNumber INT NOT NULL, " - + "Ordinal INT NOT NULL, " - + "Score INT NOT NULL, " - + "Multiplier INT NOT NULL, " - + "StartingScore INT NOT NULL, " - + "SegmentType VARCHAR(255) NOT NULL") + override fun getCreateTableSqlSpecific(): String { + return ("PlayerId VARCHAR(36) NOT NULL, " + + "ParticipantId VARCHAR(36) NOT NULL, " + + "RoundNumber INT NOT NULL, " + + "Ordinal INT NOT NULL, " + + "Score INT NOT NULL, " + + "Multiplier INT NOT NULL, " + + "StartingScore INT NOT NULL, " + + "SegmentType VARCHAR(255) NOT NULL") } - override fun addListsOfColumnsForIndexes(indexes: MutableList>) - { + override fun addListsOfColumnsForIndexes(indexes: MutableList>) { indexes.add(listOf("PlayerId", "ParticipantId", "RoundNumber", "Ordinal")) } - companion object - { - fun factory(dart: Dart, playerId: String, participantId: String, roundNumber: Int, ordinal: Int): DartEntity - { + companion object { + fun factory( + dart: Dart, + playerId: String, + participantId: String, + roundNumber: Int, + ordinal: Int + ): DartEntity { val de = DartEntity() de.assignRowId() de.playerId = playerId diff --git a/src/main/kotlin/dartzee/db/DartsMatchEntity.kt b/src/main/kotlin/dartzee/db/DartsMatchEntity.kt index 82a7a98a9..88df98fce 100644 --- a/src/main/kotlin/dartzee/db/DartsMatchEntity.kt +++ b/src/main/kotlin/dartzee/db/DartsMatchEntity.kt @@ -9,23 +9,19 @@ import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase /** - * Simple entity to join multiple 'games' together into a 'match'. - * Table has to be called 'DartsMatch' because 'Match' is a derby keyword! + * Simple entity to join multiple 'games' together into a 'match'. Table has to be called + * 'DartsMatch' because 'Match' is a derby keyword! */ -class DartsMatchEntity(database: Database = mainDatabase) : AbstractEntity(database) -{ - /** - * DB Fields - */ +class DartsMatchEntity(database: Database = mainDatabase) : + AbstractEntity(database) { + /** DB Fields */ var localId = -1L var games = -1 var mode: MatchMode = MatchMode.FIRST_TO var dtFinish = DateStatics.END_OF_TIME var matchParams = "" - /** - * Non-db gets / sets - */ + /** Non-db gets / sets */ var gameParams = "" var gameType: GameType = GameType.X01 @@ -36,62 +32,67 @@ class DartsMatchEntity(database: Database = mainDatabase) : AbstractEntity "First to $games" MatchMode.POINTS -> "Points based ($games games)" } fun getScoreForFinishingPosition(position: Int) = - when(mode) - { + when (mode) { MatchMode.FIRST_TO -> if (position == 1) 1 else 0 - MatchMode.POINTS -> if (position == -1) 0 else getHmPositionToPoints().getValue(position) + MatchMode.POINTS -> + if (position == -1) 0 else getHmPositionToPoints().getValue(position) } - private fun getHmPositionToPoints(): Map - { + private fun getHmPositionToPoints(): Map { val result = hmPositionToPoints ?: jsonMapper().readValue(matchParams) hmPositionToPoints = result return result } - fun cacheMetadataFromGame(lastGame: GameEntity) - { + fun cacheMetadataFromGame(lastGame: GameEntity) { this.gameType = lastGame.gameType this.gameParams = lastGame.gameParams } - companion object - { - fun constructPointsJson(first: Int, second: Int, third: Int, fourth: Int, fifth: Int, sixth: Int): String - { - val map = mapOf(1 to first, 2 to second, 3 to third, 4 to fourth, 5 to fifth, 6 to sixth) + companion object { + fun constructPointsJson( + first: Int, + second: Int, + third: Int, + fourth: Int, + fifth: Int, + sixth: Int + ): String { + val map = + mapOf(1 to first, 2 to second, 3 to third, 4 to fourth, 5 to fifth, 6 to sixth) return jsonMapper().writeValueAsString(map) } - /** - * Factory methods - */ + /** Factory methods */ fun factoryFirstTo(games: Int) = factoryAndSave(games, MatchMode.FIRST_TO, "") - fun factoryPoints(games: Int, pointsJson: String) = factoryAndSave(games, MatchMode.POINTS, pointsJson) - private fun factoryAndSave(games: Int, mode: MatchMode, matchParams: String): DartsMatchEntity - { + fun factoryPoints(games: Int, pointsJson: String) = + factoryAndSave(games, MatchMode.POINTS, pointsJson) + + private fun factoryAndSave( + games: Int, + mode: MatchMode, + matchParams: String + ): DartsMatchEntity { val matchEntity = DartsMatchEntity() matchEntity.assignRowId() matchEntity.mode = mode diff --git a/src/main/kotlin/dartzee/db/DartzeeRoundResultEntity.kt b/src/main/kotlin/dartzee/db/DartzeeRoundResultEntity.kt index 47243ace2..7767d5d60 100644 --- a/src/main/kotlin/dartzee/db/DartzeeRoundResultEntity.kt +++ b/src/main/kotlin/dartzee/db/DartzeeRoundResultEntity.kt @@ -4,8 +4,8 @@ import dartzee.dartzee.DartzeeRoundResult import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase -class DartzeeRoundResultEntity(database: Database = mainDatabase): AbstractEntity(database) -{ +class DartzeeRoundResultEntity(database: Database = mainDatabase) : + AbstractEntity(database) { var playerId: String = "" var participantId: String = "" var roundNumber: Int = -1 @@ -15,27 +15,28 @@ class DartzeeRoundResultEntity(database: Database = mainDatabase): AbstractEntit override fun getTableName() = EntityName.DartzeeRoundResult - override fun getCreateTableSqlSpecific(): String - { - return ("PlayerId VARCHAR(36) NOT NULL, " - + "ParticipantId VARCHAR(36) NOT NULL, " - + "RoundNumber INT NOT NULL, " - + "RuleNumber INT NOT NULL, " - + "Success BOOLEAN NOT NULL, " - + "Score INT NOT NULL") + override fun getCreateTableSqlSpecific(): String { + return ("PlayerId VARCHAR(36) NOT NULL, " + + "ParticipantId VARCHAR(36) NOT NULL, " + + "RoundNumber INT NOT NULL, " + + "RuleNumber INT NOT NULL, " + + "Success BOOLEAN NOT NULL, " + + "Score INT NOT NULL") } - override fun addListsOfColumnsForIndexes(indexes: MutableList>) - { + override fun addListsOfColumnsForIndexes(indexes: MutableList>) { indexes.add(listOf("PlayerId", "ParticipantId", "RoundNumber")) } fun toDto(): DartzeeRoundResult = DartzeeRoundResult(ruleNumber, success, score) - companion object - { - fun factoryAndSave(dto: DartzeeRoundResult, pt: ParticipantEntity, roundNumber: Int, database: Database = mainDatabase): DartzeeRoundResultEntity - { + companion object { + fun factoryAndSave( + dto: DartzeeRoundResult, + pt: ParticipantEntity, + roundNumber: Int, + database: Database = mainDatabase + ): DartzeeRoundResultEntity { val entity = DartzeeRoundResultEntity(database) entity.assignRowId() entity.ruleNumber = dto.ruleNumber @@ -49,4 +50,4 @@ class DartzeeRoundResultEntity(database: Database = mainDatabase): AbstractEntit return entity } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/DartzeeRuleEntity.kt b/src/main/kotlin/dartzee/db/DartzeeRuleEntity.kt index 78d84ae43..e310f9885 100644 --- a/src/main/kotlin/dartzee/db/DartzeeRuleEntity.kt +++ b/src/main/kotlin/dartzee/db/DartzeeRuleEntity.kt @@ -9,8 +9,8 @@ import dartzee.utils.InjectedThings.mainDatabase const val MAX_RULE_NAME = 1000 -class DartzeeRuleEntity(database: Database = mainDatabase): AbstractEntity(database) -{ +class DartzeeRuleEntity(database: Database = mainDatabase) : + AbstractEntity(database) { var entityName = EntityName.DartzeeRule var entityId = "" var dart1Rule = "" @@ -25,23 +25,21 @@ class DartzeeRuleEntity(database: Database = mainDatabase): AbstractEntity(database) -{ +class DartzeeTemplateEntity(database: Database = mainDatabase) : + AbstractEntity(database) { var name = "" override fun getTableName() = EntityName.DartzeeTemplate override fun getCreateTableSqlSpecific() = "Name VARCHAR(1000) NOT NULL" - companion object - { - fun factoryAndSave(name: String): DartzeeTemplateEntity - { + companion object { + fun factoryAndSave(name: String): DartzeeTemplateEntity { val entity = DartzeeTemplateEntity() entity.assignRowId() entity.name = name diff --git a/src/main/kotlin/dartzee/db/DatabaseMerger.kt b/src/main/kotlin/dartzee/db/DatabaseMerger.kt index 4860d05d2..335f1a225 100644 --- a/src/main/kotlin/dartzee/db/DatabaseMerger.kt +++ b/src/main/kotlin/dartzee/db/DatabaseMerger.kt @@ -13,17 +13,19 @@ import dartzee.utils.Database import dartzee.utils.InjectedThings.logger import java.sql.Timestamp -class DatabaseMerger(private val localDatabase: Database, - private val remoteDatabase: Database, - private val remoteName: String) -{ - fun performMerge(): Database - { +class DatabaseMerger( + private val localDatabase: Database, + private val remoteDatabase: Database, + private val remoteName: String +) { + fun performMerge(): Database { SyncProgressDialog.progressToStage(SyncStage.MERGE_LOCAL_CHANGES) val lastLocalSync = SyncAuditEntity.getLastSyncData(localDatabase)?.lastSynced logger.info(CODE_MERGE_STARTED, "Starting merge - last local sync $lastLocalSync") - DartsDatabaseUtil.getSyncEntities(localDatabase).forEach { dao -> syncRowsFromTable(dao, lastLocalSync) } + DartsDatabaseUtil.getSyncEntities(localDatabase).forEach { dao -> + syncRowsFromTable(dao, lastLocalSync) + } // Explicitly sync deletion audits last syncRowsFromTable(DeletionAuditEntity(localDatabase), lastLocalSync) @@ -31,8 +33,7 @@ class DatabaseMerger(private val localDatabase: Database, SyncProgressDialog.progressToStage(SyncStage.UPDATE_ACHIEVEMENTS) val achievementsChanged = AchievementEntity().retrieveModifiedSince(lastLocalSync) - if (achievementsChanged.isNotEmpty()) - { + if (achievementsChanged.isNotEmpty()) { val players = achievementsChanged.map { it.playerId }.distinct() val achievementTypes = achievementsChanged.map { it.achievementType }.distinct() val achievements = achievementTypes.mapNotNull(::getAchievementForType) @@ -44,12 +45,15 @@ class DatabaseMerger(private val localDatabase: Database, return remoteDatabase } - private fun syncRowsFromTable(localDao: AbstractEntity<*>, lastSync: Timestamp?) - { + private fun syncRowsFromTable(localDao: AbstractEntity<*>, lastSync: Timestamp?) { val rows = localDao.retrieveModifiedSince(lastSync) - logger.info(CODE_MERGING_ENTITY, "Merging ${rows.size} rows from ${localDao.getTableName()}", - KEY_TABLE_NAME to localDao.getTableName(), KEY_ROW_COUNT to rows.size) + logger.info( + CODE_MERGING_ENTITY, + "Merging ${rows.size} rows from ${localDao.getTableName()}", + KEY_TABLE_NAME to localDao.getTableName(), + KEY_ROW_COUNT to rows.size + ) rows.forEach { it.mergeIntoDatabase(remoteDatabase) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/DatabaseMigrator.kt b/src/main/kotlin/dartzee/db/DatabaseMigrator.kt index 613351302..1db8f3d03 100644 --- a/src/main/kotlin/dartzee/db/DatabaseMigrator.kt +++ b/src/main/kotlin/dartzee/db/DatabaseMigrator.kt @@ -16,47 +16,47 @@ enum class MigrationResult { TOO_OLD } -class DatabaseMigrator(private val migrations: Map Any)>>) -{ - fun migrateToLatest(database: Database, databaseDesc: String): MigrationResult - { +class DatabaseMigrator(private val migrations: Map Any)>>) { + fun migrateToLatest(database: Database, databaseDesc: String): MigrationResult { val version = database.getDatabaseVersion() - if (version == null) - { + if (version == null) { initDatabaseFirstTime(database) return MigrationResult.SUCCESS } - if (version == DartsDatabaseUtil.DATABASE_VERSION) - { - //nothing to do + if (version == DartsDatabaseUtil.DATABASE_VERSION) { + // nothing to do logger.info(CODE_DATABASE_UP_TO_DATE, "$databaseDesc database is up to date") return MigrationResult.SUCCESS } val minSupported = getMinimumSupportedVersion() - if (version < minSupported) - { - val dbDetails = "$databaseDesc version: $version, min supported: ${minSupported}, current: ${DartsDatabaseUtil.DATABASE_VERSION}" - logger.warn(CODE_DATABASE_TOO_OLD, "$databaseDesc database too old, exiting. $dbDetails") - DialogUtil.showErrorOLD("$databaseDesc database is too out-of-date to be upgraded by this version of Dartzee. " + - "Please downgrade to an earlier version so that the data can be converted.\n\n$dbDetails") + if (version < minSupported) { + val dbDetails = + "$databaseDesc version: $version, min supported: ${minSupported}, current: ${DartsDatabaseUtil.DATABASE_VERSION}" + logger.warn( + CODE_DATABASE_TOO_OLD, + "$databaseDesc database too old, exiting. $dbDetails" + ) + DialogUtil.showErrorOLD( + "$databaseDesc database is too out-of-date to be upgraded by this version of Dartzee. " + + "Please downgrade to an earlier version so that the data can be converted.\n\n$dbDetails" + ) return MigrationResult.TOO_OLD } - for (currentVersion in version until DartsDatabaseUtil.DATABASE_VERSION) - { + for (currentVersion in version until DartsDatabaseUtil.DATABASE_VERSION) { runMigrationsForVersion(database, databaseDesc, currentVersion) } return MigrationResult.SUCCESS } - private fun getMinimumSupportedVersion() = migrations.keys.minOrNull() ?: DartsDatabaseUtil.DATABASE_VERSION + private fun getMinimumSupportedVersion() = + migrations.keys.minOrNull() ?: DartsDatabaseUtil.DATABASE_VERSION - private fun runMigrationsForVersion(database: Database, databaseDesc: String, version: Int) - { + private fun runMigrationsForVersion(database: Database, databaseDesc: String, version: Int) { val newVersion = version + 1 val migrationBatch = migrations.getValue(version) val migrationCount = migrationBatch.size @@ -82,8 +82,7 @@ class DatabaseMigrator(private val migrations: Map(database) -{ - /** - * DB fields - */ +/** Represents a row that's been deleted. Used by the sync to ensure deleted rows stay deleted */ +class DeletionAuditEntity(database: Database = mainDatabase) : + AbstractEntity(database) { + /** DB fields */ var entityName: EntityName = EntityName.DeletionAudit var entityId = "" @@ -19,21 +14,18 @@ class DeletionAuditEntity(database: Database = mainDatabase): AbstractEntity, database: Database = mainDatabase): DeletionAuditEntity - { + companion object { + fun factory( + entity: AbstractEntity<*>, + database: Database = mainDatabase + ): DeletionAuditEntity { val result = DeletionAuditEntity(database) result.assignRowId() result.entityName = entity.getTableName() @@ -44,4 +36,4 @@ class DeletionAuditEntity(database: Database = mainDatabase): AbstractEntity, database: Database = mainDatabase) = factory(entity, database).also { it.saveToDatabase() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/EntityName.kt b/src/main/kotlin/dartzee/db/EntityName.kt index 9371f4735..31d6217da 100644 --- a/src/main/kotlin/dartzee/db/EntityName.kt +++ b/src/main/kotlin/dartzee/db/EntityName.kt @@ -17,4 +17,4 @@ enum class EntityName { Version, X01Finish, Team -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/ForeignDatabaseValidator.kt b/src/main/kotlin/dartzee/db/ForeignDatabaseValidator.kt index fc9d0e479..dfd0063b9 100644 --- a/src/main/kotlin/dartzee/db/ForeignDatabaseValidator.kt +++ b/src/main/kotlin/dartzee/db/ForeignDatabaseValidator.kt @@ -6,27 +6,26 @@ import dartzee.utils.DartsDatabaseUtil import dartzee.utils.Database import dartzee.utils.InjectedThings.logger -class ForeignDatabaseValidator(private val migrator: DatabaseMigrator) -{ - fun validateAndMigrateForeignDatabase(database: Database, desc: String): Boolean - { - if (!database.testConnection()) - { +class ForeignDatabaseValidator(private val migrator: DatabaseMigrator) { + fun validateAndMigrateForeignDatabase(database: Database, desc: String): Boolean { + if (!database.testConnection()) { DialogUtil.showErrorOLD("An error occurred connecting to the $desc database.") return false } val remoteVersion = database.getDatabaseVersion() - if (remoteVersion == null) - { - logger.error(CODE_MERGE_ERROR, "Unable to ascertain $desc database version (but could connect) - this is unexpected.") + if (remoteVersion == null) { + logger.error( + CODE_MERGE_ERROR, + "Unable to ascertain $desc database version (but could connect) - this is unexpected." + ) DialogUtil.showErrorOLD("An error occurred connecting to the $desc database.") return false } - if (remoteVersion > DartsDatabaseUtil.DATABASE_VERSION) - { - val error = "The $desc database contains data written by a higher Dartzee version. \n\nYou will need to update to the latest version of Dartzee before continuing." + if (remoteVersion > DartsDatabaseUtil.DATABASE_VERSION) { + val error = + "The $desc database contains data written by a higher Dartzee version. \n\nYou will need to update to the latest version of Dartzee before continuing." DialogUtil.showErrorOLD(error) return false } @@ -34,4 +33,4 @@ class ForeignDatabaseValidator(private val migrator: DatabaseMigrator) val result = migrator.migrateToLatest(database, desc.replaceFirstChar { it.uppercase() }) return result == MigrationResult.SUCCESS } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/GameEntity.kt b/src/main/kotlin/dartzee/db/GameEntity.kt index 22a8ba4bc..4f95f9702 100644 --- a/src/main/kotlin/dartzee/db/GameEntity.kt +++ b/src/main/kotlin/dartzee/db/GameEntity.kt @@ -9,14 +9,9 @@ import dartzee.utils.InjectedThings.mainDatabase const val MAX_PLAYERS = 6 -/** - * Represents a single game of Darts, e.g. X01 or Dartzee. - */ -class GameEntity(database: Database = mainDatabase): AbstractEntity(database) -{ - /** - * DB fields - */ +/** Represents a single game of Darts, e.g. X01 or Dartzee. */ +class GameEntity(database: Database = mainDatabase) : AbstractEntity(database) { + /** DB fields */ var localId = -1L var gameType: GameType = GameType.X01 var gameParams = "" @@ -26,51 +21,46 @@ class GameEntity(database: Database = mainDatabase): AbstractEntity( override fun getTableName() = EntityName.Game - override fun getCreateTableSqlSpecific(): String - { - return ("LocalId INT UNIQUE NOT NULL, " - + "GameType varchar(255) NOT NULL, " - + "GameParams varchar(255) NOT NULL, " - + "DtFinish timestamp NOT NULL, " - + "DartsMatchId VARCHAR(36) NOT NULL, " - + "MatchOrdinal INT NOT NULL") + override fun getCreateTableSqlSpecific(): String { + return ("LocalId INT UNIQUE NOT NULL, " + + "GameType varchar(255) NOT NULL, " + + "GameParams varchar(255) NOT NULL, " + + "DtFinish timestamp NOT NULL, " + + "DartsMatchId VARCHAR(36) NOT NULL, " + + "MatchOrdinal INT NOT NULL") } - override fun addListsOfColumnsForIndexes(indexes: MutableList>) - { + override fun addListsOfColumnsForIndexes(indexes: MutableList>) { indexes.add(listOf("GameType")) } override fun getColumnsAllowedToBeUnset() = listOf("DartsMatchId") - override fun assignRowId(): String - { + override fun assignRowId(): String { localId = database.generateLocalId(getTableName()) return super.assignRowId() } - override fun reassignLocalId(otherDatabase: Database) - { + override fun reassignLocalId(otherDatabase: Database) { localId = otherDatabase.generateLocalId(getTableName()) } - /** - * Helpers - */ + /** Helpers */ fun isFinished() = !isEndOfTime(dtFinish) + fun getTypeDesc() = gameType.getDescription(gameParams) - fun retrievePlayersVector(): List - { + fun retrievePlayersVector(): List { val whereSql = "GameId = '$rowId' ORDER BY Ordinal ASC" val participants = ParticipantEntity().retrieveEntities(whereSql) return participants.map { it.getPlayer() } } - companion object - { - fun factoryAndSave(launchParams: GameLaunchParams, match: DartsMatchEntity? = null): GameEntity - { + companion object { + fun factoryAndSave( + launchParams: GameLaunchParams, + match: DartsMatchEntity? = null + ): GameEntity { val game = factory(launchParams.gameType, launchParams.gameParams) match?.let { game.dartsMatchId = match.rowId @@ -81,8 +71,7 @@ class GameEntity(database: Database = mainDatabase): AbstractEntity( return game } - fun factory(gameType: GameType, gameParams: String): GameEntity - { + fun factory(gameType: GameType, gameParams: String): GameEntity { val gameEntity = GameEntity() gameEntity.assignRowId() gameEntity.gameType = gameType @@ -91,18 +80,17 @@ class GameEntity(database: Database = mainDatabase): AbstractEntity( } /** - * Ordered by DtCreation as well because of an historic bug with loading where the ordinals could get screwed up. + * Ordered by DtCreation as well because of an historic bug with loading where the ordinals + * could get screwed up. */ - fun retrieveGamesForMatch(matchId: String): MutableList - { + fun retrieveGamesForMatch(matchId: String): MutableList { val sql = "DartsMatchId = '$matchId' ORDER BY MatchOrdinal, DtCreation" return GameEntity().retrieveEntities(sql) } - fun getGameId(localId: Long): String? - { + fun getGameId(localId: Long): String? { val game = GameEntity().retrieveEntity("LocalId = $localId") ?: return null return game.rowId } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/IParticipant.kt b/src/main/kotlin/dartzee/db/IParticipant.kt index 53833e4ec..6fbfe9212 100644 --- a/src/main/kotlin/dartzee/db/IParticipant.kt +++ b/src/main/kotlin/dartzee/db/IParticipant.kt @@ -4,8 +4,7 @@ import dartzee.core.util.StringUtil import dartzee.core.util.isEndOfTime import java.sql.Timestamp -interface IParticipant -{ +interface IParticipant { var gameId: String var ordinal: Int var finishingPosition: Int @@ -15,11 +14,11 @@ interface IParticipant fun saveToDatabase() fun isActive() = isEndOfTime(dtFinished) + fun getFinishingPositionDesc(): String = StringUtil.convertOrdinalToText(finishingPosition) - fun saveFinishingPosition(game: GameEntity, position: Int) - { + fun saveFinishingPosition(game: GameEntity, position: Int) { this.finishingPosition = position this.saveToDatabase() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/LocalIdGenerator.kt b/src/main/kotlin/dartzee/db/LocalIdGenerator.kt index 32c8ca615..6b81296e9 100644 --- a/src/main/kotlin/dartzee/db/LocalIdGenerator.kt +++ b/src/main/kotlin/dartzee/db/LocalIdGenerator.kt @@ -2,21 +2,18 @@ package dartzee.db import dartzee.utils.Database -class LocalIdGenerator(private val database: Database) -{ +class LocalIdGenerator(private val database: Database) { private val uniqueIdSyncObject = Any() private val hmLastAssignedIdByEntityName = mutableMapOf() - fun clearCache() - { + fun clearCache() { hmLastAssignedIdByEntityName.clear() } - fun generateLocalId(entityName: EntityName): Long - { - synchronized(uniqueIdSyncObject) - { - val lastAssignedId = hmLastAssignedIdByEntityName[entityName] ?: retrieveLastAssignedId(entityName) + fun generateLocalId(entityName: EntityName): Long { + synchronized(uniqueIdSyncObject) { + val lastAssignedId = + hmLastAssignedIdByEntityName[entityName] ?: retrieveLastAssignedId(entityName) val nextId = lastAssignedId + 1 hmLastAssignedIdByEntityName[entityName] = nextId @@ -24,6 +21,7 @@ class LocalIdGenerator(private val database: Database) return nextId } } + private fun retrieveLastAssignedId(entityName: EntityName) = database.executeQueryAggregate("SELECT MAX(LocalId) FROM $entityName").toLong() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/ParticipantEntity.kt b/src/main/kotlin/dartzee/db/ParticipantEntity.kt index a24fb4e8d..0060446ff 100644 --- a/src/main/kotlin/dartzee/db/ParticipantEntity.kt +++ b/src/main/kotlin/dartzee/db/ParticipantEntity.kt @@ -7,12 +7,12 @@ import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase /** - * Represents the participant of a game. This is a link between a player and a game, with additional information - * such as play position and finishing position. + * Represents the participant of a game. This is a link between a player and a game, with additional + * information such as play position and finishing position. */ -class ParticipantEntity(database: Database = mainDatabase): AbstractEntity(database), IParticipant -{ - //DB Fields +class ParticipantEntity(database: Database = mainDatabase) : + AbstractEntity(database), IParticipant { + // DB Fields override var gameId = "" var playerId = "" override var ordinal = -1 @@ -21,24 +21,22 @@ class ParticipantEntity(database: Database = mainDatabase): AbstractEntity>) - { + override fun addListsOfColumnsForIndexes(indexes: MutableList>) { indexes.add(listOf("PlayerId", "GameId")) } @@ -46,46 +44,42 @@ class ParticipantEntity(database: Database = mainDatabase): AbstractEntity(database) -{ - //DB Fields +class PendingLogsEntity(database: Database = mainDatabase) : + AbstractEntity(database) { + // DB Fields var logJson = "" override fun getTableName() = EntityName.PendingLogs @@ -14,14 +14,12 @@ class PendingLogsEntity(database: Database = mainDatabase): AbstractEntity(database) -{ - //DB Fields +open class PlayerEntity(database: Database = mainDatabase) : + AbstractEntity(database) { + // DB Fields var name = "" var strategy = "" var dtDeleted = DateStatics.END_OF_TIME @@ -17,16 +17,14 @@ open class PlayerEntity(database: Database = mainDatabase): AbstractEntity>) - { + override fun addListsOfColumnsForIndexes(indexes: MutableList>) { val nameIndex = listOf("Name") val strategyDtDeletedIndex = listOf("Strategy", "DtDeleted") @@ -36,46 +34,41 @@ open class PlayerEntity(database: Database = mainDatabase): AbstractEntity - { + /** Retrieval methods */ + fun retrievePlayers(startingSql: String): List { var whereSql = startingSql - if (!startingSql.isEmpty()) - { + if (!startingSql.isEmpty()) { whereSql += " AND " } whereSql += "DtDeleted = " + getEndOfTimeSqlString() return PlayerEntity().retrieveEntities(whereSql) } - fun retrieveForName(name:String): PlayerEntity? - { + + fun retrieveForName(name: String): PlayerEntity? { val whereSql = "Name = '$name' AND DtDeleted = ${getEndOfTimeSqlString()}" val players = PlayerEntity().retrieveEntities(whereSql) return if (players.isEmpty()) null else players[0] } - fun factoryCreate(): PlayerEntity - { + fun factoryCreate(): PlayerEntity { val entity = PlayerEntity() entity.assignRowId() diff --git a/src/main/kotlin/dartzee/db/PlayerImageEntity.kt b/src/main/kotlin/dartzee/db/PlayerImageEntity.kt index 76312f65a..983138599 100644 --- a/src/main/kotlin/dartzee/db/PlayerImageEntity.kt +++ b/src/main/kotlin/dartzee/db/PlayerImageEntity.kt @@ -9,14 +9,14 @@ import java.sql.SQLException import javax.sql.rowset.serial.SerialBlob import javax.swing.ImageIcon -class PlayerImageEntity(database: Database = mainDatabase): AbstractEntity(database) -{ - //DB fields +class PlayerImageEntity(database: Database = mainDatabase) : + AbstractEntity(database) { + // DB fields var blobData: Blob? = null var filepath = "" var preset = false - //Will be set when we retrieve from the DB + // Will be set when we retrieve from the DB var bytes: ByteArray? = null override fun getTableName() = EntityName.PlayerImage @@ -24,27 +24,23 @@ class PlayerImageEntity(database: Database = mainDatabase): AbstractEntity val resourceLocation = "/avatars/$preset.png" val bytes = FileUtil.getByteArrayForResource(resourceLocation) @@ -54,20 +50,36 @@ class PlayerImageEntity(database: Database = mainDatabase): AbstractEntity() fun factoryAndSave(originalPath: String, bytes: ByteArray, preset: Boolean) = factoryAndSave(originalPath, bytes, preset, mainDatabase) - private fun factoryAndSave(filepath: String, fileBytes: ByteArray?, preset: Boolean, database: Database): PlayerImageEntity? - { - return try - { + private fun factoryAndSave( + filepath: String, + fileBytes: ByteArray?, + preset: Boolean, + database: Database + ): PlayerImageEntity? { + return try { val pi = PlayerImageEntity(database) pi.assignRowId() @@ -79,24 +91,23 @@ class PlayerImageEntity(database: Database = mainDatabase): AbstractEntity INSERT statement.contains("UPDATE") -> UPDATE statement.contains("DELETE") -> DELETE @@ -19,4 +16,4 @@ enum class SqlStatementType } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/SyncAuditEntity.kt b/src/main/kotlin/dartzee/db/SyncAuditEntity.kt index db2c21414..c043f334d 100644 --- a/src/main/kotlin/dartzee/db/SyncAuditEntity.kt +++ b/src/main/kotlin/dartzee/db/SyncAuditEntity.kt @@ -1,15 +1,15 @@ package dartzee.db -import dartzee.`object`.DartsClient import dartzee.main.getDeviceId import dartzee.main.getUsername +import dartzee.`object`.DartsClient import dartzee.sync.LastSyncData import dartzee.utils.DARTS_VERSION_NUMBER import dartzee.utils.Database import dartzee.utils.InjectedThings -class SyncAuditEntity(database: Database = InjectedThings.mainDatabase) : AbstractEntity(database) -{ +class SyncAuditEntity(database: Database = InjectedThings.mainDatabase) : + AbstractEntity(database) { var remoteName = "" var username = "" var appVersion = "" @@ -20,14 +20,12 @@ class SyncAuditEntity(database: Database = InjectedThings.mainDatabase) : Abstra override fun getCreateTableSqlSpecific() = "RemoteName VARCHAR(255) NOT NULL, Username VARCHAR(1000) NOT NULL, AppVersion VARCHAR(255) NOT NULL, " + - "DeviceId VARCHAR(36) NOT NULL, OperatingSystem VARCHAR(1000) NOT NULL" + "DeviceId VARCHAR(36) NOT NULL, OperatingSystem VARCHAR(1000) NOT NULL" override fun includeInSync() = false - companion object - { - fun insertSyncAudit(database: Database, remoteName: String): SyncAuditEntity - { + companion object { + fun insertSyncAudit(database: Database, remoteName: String): SyncAuditEntity { val entity = SyncAuditEntity(database) entity.assignRowId() entity.appVersion = DARTS_VERSION_NUMBER @@ -40,13 +38,11 @@ class SyncAuditEntity(database: Database = InjectedThings.mainDatabase) : Abstra return entity } - fun getLastSyncData(database: Database): LastSyncData? - { + fun getLastSyncData(database: Database): LastSyncData? { val dao = SyncAuditEntity(database) val entities = dao.retrieveEntities() val latest = entities.maxByOrNull { it.dtLastUpdate } ?: return null return LastSyncData(latest.remoteName, latest.dtLastUpdate) } } - } diff --git a/src/main/kotlin/dartzee/db/TeamEntity.kt b/src/main/kotlin/dartzee/db/TeamEntity.kt index deb0c572e..a8837a55b 100644 --- a/src/main/kotlin/dartzee/db/TeamEntity.kt +++ b/src/main/kotlin/dartzee/db/TeamEntity.kt @@ -5,12 +5,10 @@ import dartzee.core.util.getSqlDateNow import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase -/** - * Represents a team in a game. Individual participants will point at this entity in team games. - */ -class TeamEntity(database: Database = mainDatabase): AbstractEntity(database), IParticipant -{ - //DB Fields +/** Represents a team in a game. Individual participants will point at this entity in team games. */ +class TeamEntity(database: Database = mainDatabase) : + AbstractEntity(database), IParticipant { + // DB Fields override var gameId = "" override var ordinal = -1 override var finishingPosition = -1 @@ -19,26 +17,22 @@ class TeamEntity(database: Database = mainDatabase): AbstractEntity( override fun getTableName() = EntityName.Team - override fun getCreateTableSqlSpecific(): String - { - return ("GameId VARCHAR(36) NOT NULL, " - + "Ordinal INT NOT NULL, " - + "FinishingPosition INT NOT NULL, " - + "FinalScore INT NOT NULL, " - + "DtFinished TIMESTAMP NOT NULL") + override fun getCreateTableSqlSpecific(): String { + return ("GameId VARCHAR(36) NOT NULL, " + + "Ordinal INT NOT NULL, " + + "FinishingPosition INT NOT NULL, " + + "FinalScore INT NOT NULL, " + + "DtFinished TIMESTAMP NOT NULL") } - override fun addListsOfColumnsForIndexes(indexes: MutableList>) - { + override fun addListsOfColumnsForIndexes(indexes: MutableList>) { indexes.add(listOf("GameId")) } override fun saveToDatabase() = saveToDatabase(getSqlDateNow()) - companion object - { - fun factoryAndSave(gameId: String, ordinal: Int): TeamEntity - { + companion object { + fun factoryAndSave(gameId: String, ordinal: Int): TeamEntity { val team = TeamEntity() team.assignRowId() team.gameId = gameId diff --git a/src/main/kotlin/dartzee/db/VersionEntity.kt b/src/main/kotlin/dartzee/db/VersionEntity.kt index fed0e539a..33840f0fc 100644 --- a/src/main/kotlin/dartzee/db/VersionEntity.kt +++ b/src/main/kotlin/dartzee/db/VersionEntity.kt @@ -4,8 +4,7 @@ import dartzee.utils.DartsDatabaseUtil import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase -class VersionEntity(database: Database = mainDatabase) : AbstractEntity(database) -{ +class VersionEntity(database: Database = mainDatabase) : AbstractEntity(database) { var version = DartsDatabaseUtil.DATABASE_VERSION override fun getTableName() = EntityName.Version diff --git a/src/main/kotlin/dartzee/db/X01FinishEntity.kt b/src/main/kotlin/dartzee/db/X01FinishEntity.kt index 42e88a498..94277d0f5 100644 --- a/src/main/kotlin/dartzee/db/X01FinishEntity.kt +++ b/src/main/kotlin/dartzee/db/X01FinishEntity.kt @@ -3,28 +3,23 @@ package dartzee.db import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase -class X01FinishEntity(database: Database = mainDatabase) : AbstractEntity(database) -{ - /** - * DB fields - */ +class X01FinishEntity(database: Database = mainDatabase) : + AbstractEntity(database) { + /** DB fields */ var playerId = "" var gameId = "" var finish = -1 override fun getTableName() = EntityName.X01Finish - override fun getCreateTableSqlSpecific(): String - { - return ("PlayerId VARCHAR(36) NOT NULL, " - + "GameId VARCHAR(36) NOT NULL, " - + "Finish INT NOT NULL") + override fun getCreateTableSqlSpecific(): String { + return ("PlayerId VARCHAR(36) NOT NULL, " + + "GameId VARCHAR(36) NOT NULL, " + + "Finish INT NOT NULL") } - companion object - { - fun factoryAndSave(playerId: String, gameId: String, finish: Int) - { + companion object { + fun factoryAndSave(playerId: String, gameId: String, finish: Int) { val entity = X01FinishEntity() entity.assignRowId() entity.playerId = playerId @@ -33,4 +28,4 @@ class X01FinishEntity(database: Database = mainDatabase) : AbstractEntity - { - val tempTable = mainDatabase.createTempTable("ParticipantToFinalScore_$gameType", "ParticipantId VARCHAR(36), FinalScoreCalculated INT") + override fun runCheck(): List { + val tempTable = + mainDatabase.createTempTable( + "ParticipantToFinalScore_$gameType", + "ParticipantId VARCHAR(36), FinalScoreCalculated INT" + ) tempTable ?: return listOf() populateParticipantToFinalScoreTable(tempTable) @@ -26,23 +28,21 @@ abstract class AbstractSanityCheckFinalScore: ISanityCheck val hmParticipantToActualCount = mutableMapOf() mainDatabase.executeQuery(sb).use { rs -> - while (rs.next()) - { - val pt = ParticipantEntity().factoryFromResultSet(rs) - val dartCount = rs.getInt("FinalScoreCalculated") + while (rs.next()) { + val pt = ParticipantEntity().factoryFromResultSet(rs) + val dartCount = rs.getInt("FinalScoreCalculated") - hmParticipantToActualCount[pt] = dartCount - } + hmParticipantToActualCount[pt] = dartCount } + } mainDatabase.dropTable(tempTable) - //Add the sanity error - if (hmParticipantToActualCount.isNotEmpty()) - { + // Add the sanity error + if (hmParticipantToActualCount.isNotEmpty()) { return listOf(SanityCheckResultFinalScoreMismatch(gameType, hmParticipantToActualCount)) } return listOf() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResult.kt b/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResult.kt index 8e10dd0fd..5cced0a54 100644 --- a/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResult.kt +++ b/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResult.kt @@ -6,21 +6,20 @@ import dartzee.core.util.DialogUtil import java.awt.event.KeyEvent import javax.swing.table.DefaultTableModel -abstract class AbstractSanityCheckResult -{ +abstract class AbstractSanityCheckResult { abstract fun getResultsModel(): DefaultTableModel + abstract fun getDescription(): String + abstract fun getCount(): Int - fun getResultsDialog(): TableModelDialog - { + fun getResultsDialog(): TableModelDialog { val t = getScrollTable() t.model = getResultsModel() val deleteAction = getDeleteAction(t) - if (deleteAction != null) - { + if (deleteAction != null) { t.addKeyAction(KeyEvent.VK_DELETE, deleteAction) } @@ -31,8 +30,7 @@ abstract class AbstractSanityCheckResult open fun getScrollTable() = ScrollTable() - open fun autoFix() - { + open fun autoFix() { DialogUtil.showErrorOLD("No auto-fix available.") } diff --git a/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResultEntities.kt b/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResultEntities.kt index 010ab452d..68b95b472 100644 --- a/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResultEntities.kt +++ b/src/main/kotlin/dartzee/db/sanity/AbstractSanityCheckResultEntities.kt @@ -7,32 +7,34 @@ import dartzee.db.AbstractEntity import dartzee.utils.InjectedThings.mainDatabase import javax.swing.JOptionPane -abstract class AbstractSanityCheckResultEntities(val entities: List>): AbstractSanityCheckResult() -{ +abstract class AbstractSanityCheckResultEntities(val entities: List>) : + AbstractSanityCheckResult() { val entityName = entities.first().getTableName() override fun getResultsModel() = TableModelEntity(entities) + override fun getDeleteAction(t: ScrollTable): (() -> Unit)? = fun() { val rows = t.selectedModelRows - val ans = DialogUtil.showQuestionOLD("Are you sure you want to delete ${rows.size} row(s) from $entityName?", false) - if (ans == JOptionPane.YES_OPTION) - { + val ans = + DialogUtil.showQuestionOLD( + "Are you sure you want to delete ${rows.size} row(s) from $entityName?", + false + ) + if (ans == JOptionPane.YES_OPTION) { val success = deleteSelectedRows(t, rows) - if (!success) - { - DialogUtil.showErrorOLD("An error occurred deleting the rows. You should re-run the sanity check and check logs.") + if (!success) { + DialogUtil.showErrorOLD( + "An error occurred deleting the rows. You should re-run the sanity check and check logs." + ) } } } - - private fun deleteSelectedRows(t: ScrollTable, selectedRows: IntArray): Boolean - { + private fun deleteSelectedRows(t: ScrollTable, selectedRows: IntArray): Boolean { val rowIds = mutableListOf() - for (i in selectedRows.indices) - { + for (i in selectedRows.indices) { val rowId = t.getNonNullValueAt(selectedRows[i], 0) as String rowIds.add(rowId) } diff --git a/src/main/kotlin/dartzee/db/sanity/DatabaseSanityCheck.kt b/src/main/kotlin/dartzee/db/sanity/DatabaseSanityCheck.kt index 7ceb62610..5ffda596d 100644 --- a/src/main/kotlin/dartzee/db/sanity/DatabaseSanityCheck.kt +++ b/src/main/kotlin/dartzee/db/sanity/DatabaseSanityCheck.kt @@ -20,60 +20,58 @@ import javax.swing.AbstractAction import javax.swing.table.DefaultTableModel private fun getAllSanityChecks(): List { - val specificChecks = listOf( - SanityCheckFinishedParticipantsNoScore(), - SanityCheckDuplicateDarts(), - SanityCheckColumnsThatAllowDefaults(), - SanityCheckUnfinishedGamesNoActiveParticipants(), - SanityCheckDuplicateMatchOrdinals(), - SanityCheckFinalScoreX01(), - SanityCheckFinalScoreGolf(), - SanityCheckFinalScoreRtc(), - SanityCheckPlayerIdMismatch(), - SanityCheckX01Finishes() - ) - - val genericChecks: List = DartsDatabaseUtil.getAllEntities().flatMap { - listOf(SanityCheckDanglingIdFields(it), SanityCheckUnsetIdFields(it)) - } + val specificChecks = + listOf( + SanityCheckFinishedParticipantsNoScore(), + SanityCheckDuplicateDarts(), + SanityCheckColumnsThatAllowDefaults(), + SanityCheckUnfinishedGamesNoActiveParticipants(), + SanityCheckDuplicateMatchOrdinals(), + SanityCheckFinalScoreX01(), + SanityCheckFinalScoreGolf(), + SanityCheckFinalScoreRtc(), + SanityCheckPlayerIdMismatch(), + SanityCheckX01Finishes() + ) + + val genericChecks: List = + DartsDatabaseUtil.getAllEntities().flatMap { + listOf(SanityCheckDanglingIdFields(it), SanityCheckUnsetIdFields(it)) + } return specificChecks + genericChecks } -object DatabaseSanityCheck -{ - fun runSanityCheck(checks: List = getAllSanityChecks()) - { - logger.info(CODE_SANITY_CHECK_STARTED, "Running ${getAllSanityChecks().size} sanity checks...") +object DatabaseSanityCheck { + fun runSanityCheck(checks: List = getAllSanityChecks()) { + logger.info( + CODE_SANITY_CHECK_STARTED, + "Running ${getAllSanityChecks().size} sanity checks..." + ) runAllChecks(checks) } - private fun runAllChecks(checks: List) - { + private fun runAllChecks(checks: List) { val r = Runnable { runChecksInOtherThread(checks) } val t = Thread(r, "Sanity checks") t.start() } - private fun runChecksInOtherThread(checks: List) - { + private fun runChecksInOtherThread(checks: List) { val dlg = ProgressDialog.factory("Running Sanity Check", "checks remaining", checks.size) dlg.setVisibleLater() val sanityErrors = mutableListOf() - try - { + try { checks.forEach { check -> val results = check.runCheck() sanityErrors.addAll(results) dlg.incrementProgressLater() } - } - finally - { + } finally { mainDatabase.dropUnexpectedTables() dlg.disposeLater() } @@ -81,41 +79,42 @@ object DatabaseSanityCheck runOnEventThread { sanityCheckComplete(sanityErrors) } } - private fun sanityCheckComplete(sanityErrors: List) - { - logger.info(CODE_SANITY_CHECK_COMPLETED, "Completed sanity check and found ${sanityErrors.size} issues") + private fun sanityCheckComplete(sanityErrors: List) { + logger.info( + CODE_SANITY_CHECK_COMPLETED, + "Completed sanity check and found ${sanityErrors.size} issues" + ) sanityErrors.forEach { - logger.info(CODE_SANITY_CHECK_RESULT, - "${it.getCount()} ${it.getDescription()}", - KEY_SANITY_DESCRIPTION to it.getDescription(), - KEY_SANITY_COUNT to it.getCount()) + logger.info( + CODE_SANITY_CHECK_RESULT, + "${it.getCount()} ${it.getDescription()}", + KEY_SANITY_DESCRIPTION to it.getDescription(), + KEY_SANITY_COUNT to it.getCount() + ) } val tm = buildResultsModel(sanityErrors) - if (tm.rowCount > 0) - { - val showResults = object : AbstractAction() - { - override fun actionPerformed(e: ActionEvent) - { - val modelRow = Integer.valueOf(e.actionCommand) - - val result = sanityErrors[modelRow] - showResultsBreakdown(result) + if (tm.rowCount > 0) { + val showResults = + object : AbstractAction() { + override fun actionPerformed(e: ActionEvent) { + val modelRow = Integer.valueOf(e.actionCommand) + + val result = sanityErrors[modelRow] + showResultsBreakdown(result) + } } - } - val autoFix = object : AbstractAction() - { - override fun actionPerformed(e: ActionEvent) - { - val modelRow = Integer.valueOf(e.actionCommand) + val autoFix = + object : AbstractAction() { + override fun actionPerformed(e: ActionEvent) { + val modelRow = Integer.valueOf(e.actionCommand) - val result = sanityErrors[modelRow] - result.autoFix() + val result = sanityErrors[modelRow] + result.autoFix() + } } - } val table = ScrollTableButton(tm) table.setButtonColumn(2, showResults) @@ -125,32 +124,30 @@ object DatabaseSanityCheck dlg.setColumnWidths("-1;50;150;150") dlg.setLocationRelativeTo(ScreenCache.mainScreen) dlg.isVisible = true - } - else - { + } else { DialogUtil.showInfoOLD("Sanity check completed and found no issues") } } - private fun buildResultsModel(sanityErrors: List): DefaultTableModel - { + private fun buildResultsModel( + sanityErrors: List + ): DefaultTableModel { val model = DefaultModel() model.addColumn("Description") model.addColumn("Count") model.addColumn("") model.addColumn("") - for (result in sanityErrors) - { - val row = arrayOf(result.getDescription(), result.getCount(), "View Results >", "Auto-fix") + for (result in sanityErrors) { + val row = + arrayOf(result.getDescription(), result.getCount(), "View Results >", "Auto-fix") model.addRow(row) } return model } - private fun showResultsBreakdown(result: AbstractSanityCheckResult) - { + private fun showResultsBreakdown(result: AbstractSanityCheckResult) { val dlg = result.getResultsDialog() dlg.setSize(800, 600) dlg.setLocationRelativeTo(ScreenCache.mainScreen) diff --git a/src/main/kotlin/dartzee/db/sanity/ISanityCheck.kt b/src/main/kotlin/dartzee/db/sanity/ISanityCheck.kt index f1891f320..b273dfc08 100644 --- a/src/main/kotlin/dartzee/db/sanity/ISanityCheck.kt +++ b/src/main/kotlin/dartzee/db/sanity/ISanityCheck.kt @@ -1,6 +1,5 @@ package dartzee.db.sanity -interface ISanityCheck -{ +interface ISanityCheck { fun runCheck(): List -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckColumnsThatAllowDefaults.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckColumnsThatAllowDefaults.kt index a291d08d9..33ebd4889 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckColumnsThatAllowDefaults.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckColumnsThatAllowDefaults.kt @@ -2,10 +2,8 @@ package dartzee.db.sanity import dartzee.core.util.TableUtil -class SanityCheckColumnsThatAllowDefaults: ISanityCheck -{ - override fun runCheck(): List - { +class SanityCheckColumnsThatAllowDefaults : ISanityCheck { + override fun runCheck(): List { val model = TableUtil.DefaultModel() model.addColumn("TableName") model.addColumn("ColumnName") @@ -13,8 +11,7 @@ class SanityCheckColumnsThatAllowDefaults: ISanityCheck val results = getColumnsAllowingDefaults().map { arrayOf(it.table, it.column) } results.forEach { model.addRow(it) } - if (model.rowCount > 0) - { + if (model.rowCount > 0) { return listOf(SanityCheckResultSimpleTableModel(model, "Columns that allow defaults")) } diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckDanglingIdFields.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckDanglingIdFields.kt index 142f18abf..3ed387314 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckDanglingIdFields.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckDanglingIdFields.kt @@ -4,25 +4,19 @@ import dartzee.db.AbstractEntity import dartzee.db.EntityName import dartzee.utils.DartsDatabaseUtil -class SanityCheckDanglingIdFields(val entity: AbstractEntity<*>): ISanityCheck -{ +class SanityCheckDanglingIdFields(val entity: AbstractEntity<*>) : ISanityCheck { private val sanityErrors = mutableListOf() - override fun runCheck(): List - { - if (entity.getTableName() == EntityName.DeletionAudit) - { + override fun runCheck(): List { + if (entity.getTableName() == EntityName.DeletionAudit) { return emptyList() } val idColumns = getIdColumns(entity) - idColumns.forEach{ - checkForHangingValues(entity, it) - } + idColumns.forEach { checkForHangingValues(entity, it) } - if (entity.getColumns().contains("EntityId")) - { + if (entity.getColumns().contains("EntityId")) { DartsDatabaseUtil.getAllEntities().forEach { checkForHangingEntityId(entity, it.getTableName()) } @@ -31,8 +25,7 @@ class SanityCheckDanglingIdFields(val entity: AbstractEntity<*>): ISanityCheck return sanityErrors } - private fun checkForHangingValues(entity: AbstractEntity<*>, idColumn: String) - { + private fun checkForHangingValues(entity: AbstractEntity<*>, idColumn: String) { val tableStr = idColumn.substring(0, idColumn.length - 2) val referencedTable = EntityName.valueOf(tableStr) @@ -46,14 +39,12 @@ class SanityCheckDanglingIdFields(val entity: AbstractEntity<*>): ISanityCheck val entities = entity.retrieveEntities(whereSql, "e") val count = entities.size - if (count > 0) - { + if (count > 0) { sanityErrors.add(SanityCheckResultDanglingIdFields(idColumn, referencedTable, entities)) } } - private fun checkForHangingEntityId(entity: AbstractEntity<*>, referencedTable: EntityName) - { + private fun checkForHangingEntityId(entity: AbstractEntity<*>, referencedTable: EntityName) { val sb = StringBuilder() sb.append("EntityId <> ''") sb.append(" AND e.EntityName = '$referencedTable'") @@ -65,9 +56,10 @@ class SanityCheckDanglingIdFields(val entity: AbstractEntity<*>): ISanityCheck val entities = entity.retrieveEntities(whereSql, "e") val count = entities.size - if (count > 0) - { - sanityErrors.add(SanityCheckResultDanglingIdFields("EntityId", referencedTable, entities)) + if (count > 0) { + sanityErrors.add( + SanityCheckResultDanglingIdFields("EntityId", referencedTable, entities) + ) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateDarts.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateDarts.kt index 288569f7f..ccfadfc48 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateDarts.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateDarts.kt @@ -2,10 +2,8 @@ package dartzee.db.sanity import dartzee.db.DartEntity -class SanityCheckDuplicateDarts: ISanityCheck -{ - override fun runCheck(): List - { +class SanityCheckDuplicateDarts : ISanityCheck { + override fun runCheck(): List { val sb = StringBuilder() sb.append(" EXISTS (") sb.append(" SELECT 1") @@ -19,11 +17,10 @@ class SanityCheckDuplicateDarts: ISanityCheck val whereSql = sb.toString() val darts = DartEntity().retrieveEntities(whereSql, "drt") - if (!darts.isEmpty()) - { + if (!darts.isEmpty()) { return listOf(SanityCheckResultEntitiesSimple(darts, "Duplicate darts")) } return listOf() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateMatchOrdinals.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateMatchOrdinals.kt index 5660a0ce7..fe2db88d9 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateMatchOrdinals.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckDuplicateMatchOrdinals.kt @@ -2,10 +2,8 @@ package dartzee.db.sanity import dartzee.db.GameEntity -class SanityCheckDuplicateMatchOrdinals: ISanityCheck -{ - override fun runCheck(): List - { +class SanityCheckDuplicateMatchOrdinals : ISanityCheck { + override fun runCheck(): List { val sb = StringBuilder() sb.append(" g.MatchOrdinal > -1") sb.append(" AND EXISTS (") @@ -19,11 +17,10 @@ class SanityCheckDuplicateMatchOrdinals: ISanityCheck val whereSql = sb.toString() val games = GameEntity().retrieveEntities(whereSql, "g") val count = games.size - if (count > 0) - { + if (count > 0) { return listOf(SanityCheckResultDuplicateMatchOrdinals(games)) } return listOf() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreGolf.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreGolf.kt index 919c40867..a00b79f1e 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreGolf.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreGolf.kt @@ -4,12 +4,10 @@ import dartzee.achievements.getGolfSegmentCases import dartzee.game.GameType import dartzee.utils.InjectedThings.mainDatabase -class SanityCheckFinalScoreGolf: AbstractSanityCheckFinalScore() -{ +class SanityCheckFinalScoreGolf : AbstractSanityCheckFinalScore() { override val gameType = GameType.GOLF - override fun populateParticipantToFinalScoreTable(tempTable: String) - { + override fun populateParticipantToFinalScoreTable(tempTable: String) { val sb = StringBuilder() sb.append(" INSERT INTO $tempTable") sb.append(" SELECT pt.RowId, SUM(") @@ -38,4 +36,4 @@ class SanityCheckFinalScoreGolf: AbstractSanityCheckFinalScore() val sql = sb.toString() mainDatabase.executeUpdate(sql) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreRtc.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreRtc.kt index 12f71bd45..d1b7e25c8 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreRtc.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreRtc.kt @@ -3,12 +3,10 @@ package dartzee.db.sanity import dartzee.game.GameType import dartzee.utils.InjectedThings.mainDatabase -class SanityCheckFinalScoreRtc: AbstractSanityCheckFinalScore() -{ +class SanityCheckFinalScoreRtc : AbstractSanityCheckFinalScore() { override val gameType = GameType.ROUND_THE_CLOCK - override fun populateParticipantToFinalScoreTable(tempTable: String) - { + override fun populateParticipantToFinalScoreTable(tempTable: String) { val sb = StringBuilder() sb.append("INSERT INTO $tempTable") sb.append(" SELECT pt.RowId, COUNT(1)") diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreX01.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreX01.kt index 8c2cb40bc..4cb0da4f6 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreX01.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinalScoreX01.kt @@ -3,20 +3,22 @@ package dartzee.db.sanity import dartzee.game.GameType import dartzee.utils.InjectedThings.mainDatabase -/** - * Should be (totalRounds - 1) * 3 + (# darts in final round) - */ -class SanityCheckFinalScoreX01: AbstractSanityCheckFinalScore() -{ +/** Should be (totalRounds - 1) * 3 + (# darts in final round) */ +class SanityCheckFinalScoreX01 : AbstractSanityCheckFinalScore() { override val gameType = GameType.X01 - override fun populateParticipantToFinalScoreTable(tempTable: String) - { - val tempTable1 = mainDatabase.createTempTable("ParticipantToRoundCount", "ParticipantId VARCHAR(36), PlayerId VARCHAR(36), RoundCount INT, FinalRoundNumber INT") ?: return + override fun populateParticipantToFinalScoreTable(tempTable: String) { + val tempTable1 = + mainDatabase.createTempTable( + "ParticipantToRoundCount", + "ParticipantId VARCHAR(36), PlayerId VARCHAR(36), RoundCount INT, FinalRoundNumber INT" + ) ?: return var sb = StringBuilder() sb.append("INSERT INTO $tempTable1") - sb.append(" SELECT pt.RowId, pt.PlayerId, COUNT(DISTINCT drt.RoundNumber), MAX(drt.RoundNumber)") + sb.append( + " SELECT pt.RowId, pt.PlayerId, COUNT(DISTINCT drt.RoundNumber), MAX(drt.RoundNumber)" + ) sb.append(" FROM Dart drt, Participant pt, Game g") sb.append(" WHERE drt.ParticipantId = pt.RowId") sb.append(" AND drt.PlayerId = pt.PlayerId") @@ -39,4 +41,4 @@ class SanityCheckFinalScoreX01: AbstractSanityCheckFinalScore() mainDatabase.executeUpdate("" + sb) mainDatabase.dropTable(tempTable1) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinishedParticipantsNoScore.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinishedParticipantsNoScore.kt index dc3c78fde..a1ad70283 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckFinishedParticipantsNoScore.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckFinishedParticipantsNoScore.kt @@ -3,10 +3,8 @@ package dartzee.db.sanity import dartzee.core.util.getEndOfTimeSqlString import dartzee.db.ParticipantEntity -class SanityCheckFinishedParticipantsNoScore: ISanityCheck -{ - override fun runCheck(): List - { +class SanityCheckFinishedParticipantsNoScore : ISanityCheck { + override fun runCheck(): List { val sb = StringBuilder() sb.append(" DtFinished < ") sb.append(getEndOfTimeSqlString()) @@ -14,11 +12,15 @@ class SanityCheckFinishedParticipantsNoScore: ISanityCheck val whereSql = sb.toString() val participants = ParticipantEntity().retrieveEntities(whereSql) - if (!participants.isEmpty()) - { - return listOf(SanityCheckResultEntitiesSimple(participants, "Participants marked as finished but with no final score")) + if (!participants.isEmpty()) { + return listOf( + SanityCheckResultEntitiesSimple( + participants, + "Participants marked as finished but with no final score" + ) + ) } return listOf() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckPlayerIdMismatch.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckPlayerIdMismatch.kt index d09efcc99..93193b9e8 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckPlayerIdMismatch.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckPlayerIdMismatch.kt @@ -3,13 +3,13 @@ package dartzee.db.sanity import dartzee.core.util.TableUtil import dartzee.utils.InjectedThings.mainDatabase -class SanityCheckPlayerIdMismatch: ISanityCheck -{ - override fun runCheck(): List - { +class SanityCheckPlayerIdMismatch : ISanityCheck { + override fun runCheck(): List { val sb = StringBuilder() - sb.append("SELECT drt.RowId AS DartId, pt.RowId AS ParticipantId, drt.PlayerId AS DartPlayerId, pt.PlayerId as ParticipantPlayerId") + sb.append( + "SELECT drt.RowId AS DartId, pt.RowId AS ParticipantId, drt.PlayerId AS DartPlayerId, pt.PlayerId as ParticipantPlayerId" + ) sb.append(" FROM Dart drt, Participant pt") sb.append(" WHERE drt.ParticipantId = pt.RowId") sb.append(" AND drt.PlayerId <> pt.PlayerId") @@ -20,8 +20,7 @@ class SanityCheckPlayerIdMismatch: ISanityCheck tm.addColumn("DartPlayerId") tm.addColumn("ParticipantPlayerId") mainDatabase.executeQuery(sb).use { rs -> - while (rs.next()) - { + while (rs.next()) { val dartId = rs.getString("DartId") val participantId = rs.getString("ParticipantId") val dartPlayerId = rs.getString("DartPlayerId") @@ -31,11 +30,15 @@ class SanityCheckPlayerIdMismatch: ISanityCheck } } - if (tm.rowCount > 0) - { - return listOf(SanityCheckResultSimpleTableModel(tm, "Darts where PlayerId doesn't match the Participant row")) + if (tm.rowCount > 0) { + return listOf( + SanityCheckResultSimpleTableModel( + tm, + "Darts where PlayerId doesn't match the Participant row" + ) + ) } return listOf() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDanglingIdFields.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDanglingIdFields.kt index abc8ae3f1..e19a65dc5 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDanglingIdFields.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDanglingIdFields.kt @@ -6,29 +6,29 @@ import dartzee.db.EntityName import dartzee.utils.InjectedThings.mainDatabase import javax.swing.JOptionPane -class SanityCheckResultDanglingIdFields(private val idColumn: String, - private val referencedEntity: EntityName, - entities: List>) : AbstractSanityCheckResultEntities(entities) -{ - override fun getDescription() = "$entityName rows where the $idColumn points at a non-existent $referencedEntity" +class SanityCheckResultDanglingIdFields( + private val idColumn: String, + private val referencedEntity: EntityName, + entities: List> +) : AbstractSanityCheckResultEntities(entities) { + override fun getDescription() = + "$entityName rows where the $idColumn points at a non-existent $referencedEntity" - override fun autoFix() - { + override fun autoFix() { val rowIds = entities.map { it.rowId } - val ans = DialogUtil.showQuestionOLD("Are you sure you want to delete ${entities.size} rows from $entityName?") - if (ans != JOptionPane.YES_OPTION) - { + val ans = + DialogUtil.showQuestionOLD( + "Are you sure you want to delete ${entities.size} rows from $entityName?" + ) + if (ans != JOptionPane.YES_OPTION) { return } val success = mainDatabase.deleteRowsFromTable(entityName, rowIds) - if (success) - { + if (success) { DialogUtil.showInfoOLD("Rows deleted successfully. You should re-run the sanity check.") - } - else - { + } else { DialogUtil.showErrorOLD("An error occurred deleting the rows.") } } diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDuplicateMatchOrdinals.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDuplicateMatchOrdinals.kt index 553d1c660..2847ceb21 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDuplicateMatchOrdinals.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultDuplicateMatchOrdinals.kt @@ -7,44 +7,46 @@ import dartzee.db.GameEntity import javax.swing.JOptionPane /** - * Check for Games as part of the same match but with the same ordinal. - * Originally happened due to a bug where the ordinal reset upon re-loading an incomplete match + * Check for Games as part of the same match but with the same ordinal. Originally happened due to a + * bug where the ordinal reset upon re-loading an incomplete match */ -class SanityCheckResultDuplicateMatchOrdinals(entities: List>) : AbstractSanityCheckResultEntities(entities) -{ - override fun autoFix() - { +class SanityCheckResultDuplicateMatchOrdinals(entities: List>) : + AbstractSanityCheckResultEntities(entities) { + override fun autoFix() { val tm = getResultsModel() val rowCount = tm.rowCount - //Get the distinct matches affected + // Get the distinct matches affected val matchIds = mutableListOf() - for (i in 0 until rowCount) - { + for (i in 0 until rowCount) { val matchId = tm.getValueAt(i, 7).toString() matchIds.addUnique(matchId) } - //Just double-check... - val ans = DialogUtil.showQuestionOLD("This will reset the ordinal for all games in ${matchIds.size} matches. Proceed?", false) - if (ans == JOptionPane.NO_OPTION) - { + // Just double-check... + val ans = + DialogUtil.showQuestionOLD( + "This will reset the ordinal for all games in ${matchIds.size} matches. Proceed?", + false + ) + if (ans == JOptionPane.NO_OPTION) { return } - //Fix the matches one at a time - for (matchId in matchIds) - { + // Fix the matches one at a time + for (matchId in matchIds) { val gameSql = "DartsMatchId = '$matchId' ORDER BY DtCreation" val games = GameEntity().retrieveEntities(gameSql) games.forEachIndexed { index, gameEntity -> - gameEntity.matchOrdinal = index+1 + gameEntity.matchOrdinal = index + 1 gameEntity.saveToDatabase() } } - DialogUtil.showInfoOLD("Auto-fix complete. You should re-run the sanity check and check there are no errors.") + DialogUtil.showInfoOLD( + "Auto-fix complete. You should re-run the sanity check and check there are no errors." + ) } override fun getDescription() = "Games with duplicate MatchOrdinals" diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultEntitiesSimple.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultEntitiesSimple.kt index 0f5f3e064..3814ac35d 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultEntitiesSimple.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultEntitiesSimple.kt @@ -2,7 +2,7 @@ package dartzee.db.sanity import dartzee.db.AbstractEntity -class SanityCheckResultEntitiesSimple(entities: List>, val desc: String) : AbstractSanityCheckResultEntities(entities) -{ +class SanityCheckResultEntitiesSimple(entities: List>, val desc: String) : + AbstractSanityCheckResultEntities(entities) { override fun getDescription() = desc } diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultFinalScoreMismatch.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultFinalScoreMismatch.kt index 6c76bd9db..edfbcc9d5 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultFinalScoreMismatch.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultFinalScoreMismatch.kt @@ -6,16 +6,18 @@ import dartzee.db.ParticipantEntity import dartzee.game.GameType import javax.swing.table.DefaultTableModel -class SanityCheckResultFinalScoreMismatch(private val gameType: GameType, private val hmParticipantToFinalScore: MutableMap) : AbstractSanityCheckResult() -{ - override fun getDescription() = "FinalScores that don't match the raw data (${gameType.getDescription()})" +class SanityCheckResultFinalScoreMismatch( + private val gameType: GameType, + private val hmParticipantToFinalScore: MutableMap +) : AbstractSanityCheckResult() { + override fun getDescription() = + "FinalScores that don't match the raw data (${gameType.getDescription()})" override fun getScrollTable() = ScrollTableDartsGame("GameId") override fun getCount() = hmParticipantToFinalScore.size - override fun getResultsModel(): DefaultTableModel - { + override fun getResultsModel(): DefaultTableModel { val model = DefaultModel() model.addColumn("ParticipantId") model.addColumn("PlayerId") @@ -25,8 +27,7 @@ class SanityCheckResultFinalScoreMismatch(private val gameType: GameType, privat model.addColumn("FinalScoreRAW") val pts = hmParticipantToFinalScore.keys - for (pt in pts) - { + for (pt in pts) { val participantId = pt.rowId val playerId = pt.playerId val gameId = pt.gameId @@ -34,11 +35,11 @@ class SanityCheckResultFinalScoreMismatch(private val gameType: GameType, privat val finalScore = pt.finalScore val finalScoreRaw = hmParticipantToFinalScore[pt]!! - val row = arrayOf(participantId, playerId, gameId, dtLastUpdate, finalScore, finalScoreRaw) + val row = + arrayOf(participantId, playerId, gameId, dtLastUpdate, finalScore, finalScoreRaw) model.addRow(row) } return model } - } diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultSimpleTableModel.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultSimpleTableModel.kt index c3c60b604..b9909732d 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultSimpleTableModel.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultSimpleTableModel.kt @@ -2,9 +2,13 @@ package dartzee.db.sanity import dartzee.core.util.TableUtil.DefaultModel -open class SanityCheckResultSimpleTableModel(private val model: DefaultModel, private val desc: String) : AbstractSanityCheckResult() -{ +open class SanityCheckResultSimpleTableModel( + private val model: DefaultModel, + private val desc: String +) : AbstractSanityCheckResult() { override fun getDescription() = desc + override fun getCount() = model.rowCount + override fun getResultsModel() = model } diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultUnsetColumns.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultUnsetColumns.kt index 164af8f0f..045202adf 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckResultUnsetColumns.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckResultUnsetColumns.kt @@ -2,7 +2,9 @@ package dartzee.db.sanity import dartzee.db.AbstractEntity -class SanityCheckResultUnsetColumns(private val columnName: String, entities: List>) : AbstractSanityCheckResultEntities(entities) -{ +class SanityCheckResultUnsetColumns( + private val columnName: String, + entities: List> +) : AbstractSanityCheckResultEntities(entities) { override fun getDescription() = "$entityName rows where $columnName is unset" } diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckUnfinishedGamesNoActiveParticipants.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckUnfinishedGamesNoActiveParticipants.kt index ade2648fb..0eff60c2d 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckUnfinishedGamesNoActiveParticipants.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckUnfinishedGamesNoActiveParticipants.kt @@ -3,10 +3,8 @@ package dartzee.db.sanity import dartzee.core.util.getEndOfTimeSqlString import dartzee.db.GameEntity -class SanityCheckUnfinishedGamesNoActiveParticipants: ISanityCheck -{ - override fun runCheck(): List - { +class SanityCheckUnfinishedGamesNoActiveParticipants : ISanityCheck { + override fun runCheck(): List { val sb = StringBuilder() sb.append("DtFinish = ${getEndOfTimeSqlString()}") sb.append(" AND NOT EXISTS ") @@ -19,11 +17,12 @@ class SanityCheckUnfinishedGamesNoActiveParticipants: ISanityCheck val whereSql = sb.toString() val games = GameEntity().retrieveEntities(whereSql, "g") - if (games.size > 0) - { - return listOf(SanityCheckResultEntitiesSimple(games, "Unfinished games without active players")) + if (games.size > 0) { + return listOf( + SanityCheckResultEntitiesSimple(games, "Unfinished games without active players") + ) } return listOf() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckUnsetIdFields.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckUnsetIdFields.kt index bc054e499..b471019ca 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckUnsetIdFields.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckUnsetIdFields.kt @@ -2,17 +2,14 @@ package dartzee.db.sanity import dartzee.db.AbstractEntity -class SanityCheckUnsetIdFields(val entity: AbstractEntity<*>): ISanityCheck -{ +class SanityCheckUnsetIdFields(val entity: AbstractEntity<*>) : ISanityCheck { private val sanityErrors = mutableListOf() - override fun runCheck(): List - { + override fun runCheck(): List { val idColumns = getIdColumns(entity) idColumns.forEach { column -> - if (!entity.columnCanBeUnset(column)) - { + if (!entity.columnCanBeUnset(column)) { checkForUnsetValues(entity, column) } } @@ -20,15 +17,13 @@ class SanityCheckUnsetIdFields(val entity: AbstractEntity<*>): ISanityCheck return sanityErrors } - private fun checkForUnsetValues(entity: AbstractEntity<*>, idColumn: String) - { + private fun checkForUnsetValues(entity: AbstractEntity<*>, idColumn: String) { val whereSql = "$idColumn = ''" val entities = entity.retrieveEntities(whereSql) val count = entities.size - if (count > 0) - { + if (count > 0) { sanityErrors.add(SanityCheckResultUnsetColumns(idColumn, entities)) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityCheckX01Finishes.kt b/src/main/kotlin/dartzee/db/sanity/SanityCheckX01Finishes.kt index a29d41b83..b05590e6b 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityCheckX01Finishes.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityCheckX01Finishes.kt @@ -6,12 +6,10 @@ import dartzee.core.util.TableUtil import dartzee.utils.InjectedThings.mainDatabase import java.sql.ResultSet -class SanityCheckX01Finishes: ISanityCheck -{ +class SanityCheckX01Finishes : ISanityCheck { data class X01Finish(val playerId: String, val gameId: String, val finish: Int) - override fun runCheck(): List - { + override fun runCheck(): List { ensureX01RoundsTableExists(emptyList(), mainDatabase) var sb = StringBuilder() @@ -40,19 +38,16 @@ class SanityCheckX01Finishes: ISanityCheck missing.forEach { model.addRow(arrayOf("MISSING", it.playerId, it.gameId, it.finish)) } extra.forEach { model.addRow(arrayOf("EXTRA", it.playerId, it.gameId, it.finish)) } - if (model.rowCount > 0) - { + if (model.rowCount > 0) { return listOf(SanityCheckResultSimpleTableModel(model, "X01 Finish mismatches")) } return emptyList() } - private fun extractX01Finishes(rs: ResultSet): List - { + private fun extractX01Finishes(rs: ResultSet): List { val finishes = mutableListOf() - while (rs.next()) - { + while (rs.next()) { val playerId = rs.getString("PlayerId") val gameId = rs.getString("GameId") val finish = rs.getInt("Finish") @@ -62,5 +57,4 @@ class SanityCheckX01Finishes: ISanityCheck return finishes.toList() } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/db/sanity/SanityUtils.kt b/src/main/kotlin/dartzee/db/sanity/SanityUtils.kt index 23ff3ff68..ea8c3f03c 100644 --- a/src/main/kotlin/dartzee/db/sanity/SanityUtils.kt +++ b/src/main/kotlin/dartzee/db/sanity/SanityUtils.kt @@ -4,15 +4,14 @@ import dartzee.db.AbstractEntity import dartzee.utils.DartsDatabaseUtil import dartzee.utils.InjectedThings -fun getIdColumns(entity: AbstractEntity<*>): List -{ +fun getIdColumns(entity: AbstractEntity<*>): List { val potentialIdColumns = DartsDatabaseUtil.getAllEntities().map { "${it.getTableName()}Id" } - return entity.getColumns().filter{ potentialIdColumns.contains(it) } + return entity.getColumns().filter { potentialIdColumns.contains(it) } } data class TableAndColumn(val table: String, val column: String) -fun getColumnsAllowingDefaults(): List -{ + +fun getColumnsAllowingDefaults(): List { val sb = StringBuilder() sb.append("SELECT t.TableName, c.ColumnName ") sb.append("FROM sys.systables t, sys.syscolumns c ") @@ -22,8 +21,7 @@ fun getColumnsAllowingDefaults(): List val result = mutableListOf() InjectedThings.mainDatabase.executeQuery(sb).use { rs -> - while (rs.next()) - { + while (rs.next()) { val tableName = rs.getString("TableName") val columnName = rs.getString("ColumnName") @@ -32,4 +30,4 @@ fun getColumnsAllowingDefaults(): List } return result.toList() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/GameLaunchParams.kt b/src/main/kotlin/dartzee/game/GameLaunchParams.kt index 38c5f55c6..91179e1e6 100644 --- a/src/main/kotlin/dartzee/game/GameLaunchParams.kt +++ b/src/main/kotlin/dartzee/game/GameLaunchParams.kt @@ -11,4 +11,4 @@ data class GameLaunchParams( val dartzeeDtos: List? = null ) { fun teamCount(): Int = if (pairMode) players.chunked(2).size else players.size -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/GameLauncher.kt b/src/main/kotlin/dartzee/game/GameLauncher.kt index 6354138c7..8c6574666 100644 --- a/src/main/kotlin/dartzee/game/GameLauncher.kt +++ b/src/main/kotlin/dartzee/game/GameLauncher.kt @@ -21,10 +21,8 @@ import dartzee.screen.game.x01.X01MatchScreen import dartzee.utils.InjectedThings.logger import dartzee.utils.insertDartzeeRules -class GameLauncher -{ - fun launchNewMatch(match: DartsMatchEntity, params: GameLaunchParams) - { +class GameLauncher { + fun launchNewMatch(match: DartsMatchEntity, params: GameLaunchParams) { val game = GameEntity.factoryAndSave(params, match) match.cacheMetadataFromGame(game) @@ -35,73 +33,73 @@ class GameLauncher val panel = scrn.addGameToMatch(game, participants.size) panel.startNewGame(participants) - logger.info(CODE_MATCH_LAUNCHED, "Launched ${scrn.windowName}", - KEY_MATCH_ID to match.rowId, KEY_MATCH_LOCAL_ID to match.localId) + logger.info( + CODE_MATCH_LAUNCHED, + "Launched ${scrn.windowName}", + KEY_MATCH_ID to match.rowId, + KEY_MATCH_LOCAL_ID to match.localId + ) } - fun launchNewGame(params: GameLaunchParams) - { - //Create and save a game + fun launchNewGame(params: GameLaunchParams) { + // Create and save a game val game = GameEntity.factoryAndSave(params) val participants = insertNewGameEntities(game.rowId, params) - //Construct the screen and factory a tab + // Construct the screen and factory a tab val scrn = DartsGameScreen(game, params.teamCount()) scrn.isVisible = true scrn.gamePanel.startNewGame(participants) - logger.info(CODE_GAME_LAUNCHED, "Launched ${scrn.windowName}", - KEY_GAME_ID to game.rowId, KEY_GAME_LOCAL_ID to game.localId, KEY_FROM_MATCH to false) + logger.info( + CODE_GAME_LAUNCHED, + "Launched ${scrn.windowName}", + KEY_GAME_ID to game.rowId, + KEY_GAME_LOCAL_ID to game.localId, + KEY_FROM_MATCH to false + ) } - private fun insertNewGameEntities(gameId: String, params: GameLaunchParams): List - { + private fun insertNewGameEntities( + gameId: String, + params: GameLaunchParams + ): List { insertDartzeeRules(gameId, params.dartzeeDtos) return prepareParticipants(gameId, params.players, params.pairMode) } - fun loadAndDisplayGame(gameId: String) - { + fun loadAndDisplayGame(gameId: String) { val existingScreen = ScreenCache.getDartsGameScreen(gameId) - if (existingScreen != null) - { + if (existingScreen != null) { existingScreen.displayGame(gameId) return } - //Screen isn't currently visible, so look for the game on the DB + // Screen isn't currently visible, so look for the game on the DB val gameEntity = GameEntity().retrieveForId(gameId, false) - if (gameEntity == null) - { + if (gameEntity == null) { DialogUtil.showErrorOLD("Game $gameId does not exist.") return } val matchId = gameEntity.dartsMatchId - if (matchId.isEmpty()) - { + if (matchId.isEmpty()) { loadAndDisplaySingleGame(gameEntity) - } - else - { + } else { loadAndDisplayMatch(matchId, gameId) } } - private fun loadAndDisplaySingleGame(gameEntity: GameEntity) - { - //We've found a game, so construct a screen and initialise it + private fun loadAndDisplaySingleGame(gameEntity: GameEntity) { + // We've found a game, so construct a screen and initialise it val participants = loadParticipants(gameEntity.rowId) val scrn = DartsGameScreen(gameEntity, participants.size) scrn.isVisible = true - //Now try to load the game - try - { + // Now try to load the game + try { scrn.gamePanel.loadGame(participants) - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_LOAD_ERROR, "Failed to load Game ${gameEntity.rowId}", t) DialogUtil.showErrorOLD("Failed to load Game #${gameEntity.localId}") scrn.dispose() @@ -109,8 +107,7 @@ class GameLauncher } } - private fun loadAndDisplayMatch(matchId: String, originalGameId: String) - { + private fun loadAndDisplayMatch(matchId: String, originalGameId: String) { val allGames = GameEntity.retrieveGamesForMatch(matchId) val lastGame = allGames[allGames.size - 1] @@ -119,8 +116,7 @@ class GameLauncher val scrn = factoryMatchScreen(match) - try - { + try { allGames.forEach { game -> val participants = loadParticipants(game.rowId) val panel = scrn.addGameToMatch(game, participants.size) @@ -128,9 +124,7 @@ class GameLauncher } scrn.displayGame(originalGameId) - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_LOAD_ERROR, "Failed to load Match $matchId", t) DialogUtil.showErrorOLD("Failed to load Match #${match.localId}") scrn.dispose() @@ -139,11 +133,10 @@ class GameLauncher } private fun factoryMatchScreen(match: DartsMatchEntity) = - when (match.gameType) - { + when (match.gameType) { GameType.X01 -> X01MatchScreen(match) GameType.ROUND_THE_CLOCK -> RoundTheClockMatchScreen(match) GameType.GOLF -> GolfMatchScreen(match) GameType.DARTZEE -> DartzeeMatchScreen(match) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/GameSqlUtils.kt b/src/main/kotlin/dartzee/game/GameSqlUtils.kt index 530f5d339..dd716704a 100644 --- a/src/main/kotlin/dartzee/game/GameSqlUtils.kt +++ b/src/main/kotlin/dartzee/game/GameSqlUtils.kt @@ -11,64 +11,71 @@ import dartzee.game.state.SingleParticipant import dartzee.game.state.TeamParticipant import dartzee.utils.insertDartzeeRules -/** - * New Game - */ -fun prepareParticipants(gameId: String, players: List, pairMode: Boolean): List -{ - return if (pairMode) - { +/** New Game */ +fun prepareParticipants( + gameId: String, + players: List, + pairMode: Boolean +): List { + return if (pairMode) { val groups = players.chunked(2) groups.mapIndexed { ordinal, group -> - if (group.size == 1) addSinglePlayer(gameId, group.first(), ordinal) else addTeam(gameId, group, ordinal) + if (group.size == 1) addSinglePlayer(gameId, group.first(), ordinal) + else addTeam(gameId, group, ordinal) } - } - else - { + } else { players.mapIndexed { ordinal, player -> addSinglePlayer(gameId, player, ordinal) } } } -private fun addTeam(gameId: String, players: List, ordinal: Int): IWrappedParticipant -{ + +private fun addTeam( + gameId: String, + players: List, + ordinal: Int +): IWrappedParticipant { val team = TeamEntity.factoryAndSave(gameId, ordinal) - val pts = players.mapIndexed { playerIx, player -> - ParticipantEntity.factoryAndSave(gameId, player, playerIx, team.rowId) - } + val pts = + players.mapIndexed { playerIx, player -> + ParticipantEntity.factoryAndSave(gameId, player, playerIx, team.rowId) + } return TeamParticipant(team, pts) } -private fun addSinglePlayer(gameId: String, player: PlayerEntity, ordinal: Int): IWrappedParticipant -{ + +private fun addSinglePlayer( + gameId: String, + player: PlayerEntity, + ordinal: Int +): IWrappedParticipant { val participant = ParticipantEntity.factoryAndSave(gameId, player, ordinal) return SingleParticipant(participant) } -/** - * Load Game - */ -fun loadParticipants(gameId: String): List -{ +/** Load Game */ +fun loadParticipants(gameId: String): List { val teams = TeamEntity().retrieveEntities("GameId = '$gameId'") val teamParticipants = teams.map(::loadTeam) - val soloParticipants = ParticipantEntity().retrieveEntities("GameId = '$gameId' AND TeamId = ''").map(::SingleParticipant) + val soloParticipants = + ParticipantEntity() + .retrieveEntities("GameId = '$gameId' AND TeamId = ''") + .map(::SingleParticipant) return (teamParticipants + soloParticipants).sortedBy { it.ordinal() } } -private fun loadTeam(team: TeamEntity): TeamParticipant -{ - val participants = ParticipantEntity().retrieveEntities("TeamId = '${team.rowId}'").sortedBy { it.ordinal } + +private fun loadTeam(team: TeamEntity): TeamParticipant { + val participants = + ParticipantEntity().retrieveEntities("TeamId = '${team.rowId}'").sortedBy { it.ordinal } return TeamParticipant(team, participants) } -/** - * Follow-on game (in a match) - */ +/** Follow-on game (in a match) */ fun prepareNextEntities( firstGame: GameEntity, firstGameParticipants: List, - matchOrdinal: Int): Pair> -{ + matchOrdinal: Int +): Pair> { val nextGame = GameEntity.factory(firstGame.gameType, firstGame.gameParams) nextGame.dartsMatchId = firstGame.dartsMatchId nextGame.matchOrdinal = matchOrdinal @@ -80,29 +87,34 @@ fun prepareNextEntities( val participants = prepareNextParticipants(firstGameParticipants, nextGame) return nextGame to participants } -private fun prepareNextParticipants(firstGameParticipants: List, newGame: GameEntity): List -{ + +private fun prepareNextParticipants( + firstGameParticipants: List, + newGame: GameEntity +): List { val templateParticipants = shuffleForNewGame(firstGameParticipants, newGame.matchOrdinal) - return templateParticipants.mapIndexed { ordinal, pt -> - copyForNewGame(ordinal, pt, newGame) - } + return templateParticipants.mapIndexed { ordinal, pt -> copyForNewGame(ordinal, pt, newGame) } } -private fun copyForNewGame(participantOrdinal: Int, template: IWrappedParticipant, newGame: GameEntity) = - when (template) - { - is SingleParticipant -> addSinglePlayer(newGame.rowId, template.participant.getPlayer(), participantOrdinal) + +private fun copyForNewGame( + participantOrdinal: Int, + template: IWrappedParticipant, + newGame: GameEntity +) = + when (template) { + is SingleParticipant -> + addSinglePlayer(newGame.rowId, template.participant.getPlayer(), participantOrdinal) is TeamParticipant -> { val players = template.individuals.map { it.getPlayer() } val newPlayerOrder = shuffleForNewGame(players, newGame.matchOrdinal) addTeam(newGame.rowId, newPlayerOrder, participantOrdinal) } } -private fun shuffleForNewGame(things: List, gameOrdinal: Int): List -{ - if (things.size > 2) - { + +private fun shuffleForNewGame(things: List, gameOrdinal: Int): List { + if (things.size > 2) { return collectionShuffler.shuffleCollection(things) } return if (gameOrdinal % 2 == 1) things.toList() else things.reversed() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/GameType.kt b/src/main/kotlin/dartzee/game/GameType.kt index 9f4b9b80e..ab7123e47 100644 --- a/src/main/kotlin/dartzee/game/GameType.kt +++ b/src/main/kotlin/dartzee/game/GameType.kt @@ -2,27 +2,23 @@ package dartzee.game import dartzee.db.DartzeeTemplateEntity -enum class GameType -{ +enum class GameType { X01, GOLF, ROUND_THE_CLOCK, DARTZEE; fun getDescription(): String = - when (this) - { + when (this) { X01 -> "X01" GOLF -> "Golf" ROUND_THE_CLOCK -> "Round the Clock" DARTZEE -> "Dartzee" } - fun getDescription(gameParams: String): String - { + fun getDescription(gameParams: String): String { val paramDesc = getParamsDescription(gameParams) - return when (this) - { + return when (this) { X01 -> paramDesc GOLF -> "Golf - $paramDesc" ROUND_THE_CLOCK -> "Round the Clock - $paramDesc" @@ -31,11 +27,10 @@ enum class GameType } fun getParamsDescription(gameParams: String) = - when (this) - { + when (this) { X01 -> gameParams GOLF -> "$gameParams holes" ROUND_THE_CLOCK -> RoundTheClockConfig.fromJson(gameParams).getDescription() DARTZEE -> DartzeeTemplateEntity().retrieveForId(gameParams, false)?.name.orEmpty() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/MatchMode.kt b/src/main/kotlin/dartzee/game/MatchMode.kt index d1cf62358..4be3f83f9 100644 --- a/src/main/kotlin/dartzee/game/MatchMode.kt +++ b/src/main/kotlin/dartzee/game/MatchMode.kt @@ -1,7 +1,6 @@ package dartzee.game -enum class MatchMode -{ +enum class MatchMode { FIRST_TO, POINTS -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/MatchUtils.kt b/src/main/kotlin/dartzee/game/MatchUtils.kt index abd34711b..e038100ce 100644 --- a/src/main/kotlin/dartzee/game/MatchUtils.kt +++ b/src/main/kotlin/dartzee/game/MatchUtils.kt @@ -3,8 +3,7 @@ package dartzee.game import dartzee.db.DartsMatchEntity import dartzee.game.state.IWrappedParticipant -fun matchIsComplete(match: DartsMatchEntity, participants: List): Boolean -{ +fun matchIsComplete(match: DartsMatchEntity, participants: List): Boolean { val grouped = participants.groupBy { it.getUniqueParticipantName() } val winCounts = grouped.values.map(::countWins) return when (match.mode) { @@ -12,4 +11,6 @@ fun matchIsComplete(match: DartsMatchEntity, participants: List winCounts.sum() == match.games } } -private fun countWins(participants: List) = participants.count { it.participant.finishingPosition == 1 } \ No newline at end of file + +private fun countWins(participants: List) = + participants.count { it.participant.finishingPosition == 1 } diff --git a/src/main/kotlin/dartzee/game/RoundTheClockConfig.kt b/src/main/kotlin/dartzee/game/RoundTheClockConfig.kt index d615aeb45..cbd9fb928 100644 --- a/src/main/kotlin/dartzee/game/RoundTheClockConfig.kt +++ b/src/main/kotlin/dartzee/game/RoundTheClockConfig.kt @@ -4,22 +4,21 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.module.kotlin.readValue import dartzee.core.util.jsonMapper -enum class ClockType -{ +enum class ClockType { Standard, Doubles, Trebles } @JsonIgnoreProperties("description", "orderStr") -data class RoundTheClockConfig(val clockType: ClockType, val inOrder: Boolean) -{ +data class RoundTheClockConfig(val clockType: ClockType, val inOrder: Boolean) { fun toJson(): String = jsonMapper().writeValueAsString(this) + fun getDescription() = "$clockType - ${getOrderStr()}" + fun getOrderStr() = if (inOrder) "in order" else "any order" - companion object - { + companion object { fun fromJson(json: String) = jsonMapper().readValue(json) } } diff --git a/src/main/kotlin/dartzee/game/UniqueParticipantName.kt b/src/main/kotlin/dartzee/game/UniqueParticipantName.kt index 6d9a8aee1..5da488abf 100644 --- a/src/main/kotlin/dartzee/game/UniqueParticipantName.kt +++ b/src/main/kotlin/dartzee/game/UniqueParticipantName.kt @@ -2,7 +2,5 @@ package dartzee.game import dartzee.types.StringMicrotype -/** - * The team name in a deterministic order - does not vary based on throw order - */ -class UniqueParticipantName(value: String) : StringMicrotype(value) \ No newline at end of file +/** The team name in a deterministic order - does not vary based on throw order */ +class UniqueParticipantName(value: String) : StringMicrotype(value) diff --git a/src/main/kotlin/dartzee/game/state/AbstractPlayerState.kt b/src/main/kotlin/dartzee/game/state/AbstractPlayerState.kt index 429ab1abd..7360a2502 100644 --- a/src/main/kotlin/dartzee/game/state/AbstractPlayerState.kt +++ b/src/main/kotlin/dartzee/game/state/AbstractPlayerState.kt @@ -6,8 +6,7 @@ import dartzee.db.DartEntity import dartzee.db.ParticipantEntity import dartzee.`object`.Dart -abstract class AbstractPlayerState> -{ +abstract class AbstractPlayerState> { private val listeners = mutableListOf>() abstract val wrappedParticipant: IWrappedParticipant @@ -18,33 +17,33 @@ abstract class AbstractPlayerState> abstract fun getScoreSoFar(): Int @Suppress("UNCHECKED_CAST") - fun addListener(listener: PlayerStateListener) - { + fun addListener(listener: PlayerStateListener) { listeners.add(listener) listener.stateChanged(this as S) } - /** - * Helpers - */ + /** Helpers */ fun currentRoundNumber() = completedRounds.size + 1 + fun currentIndividual() = wrappedParticipant.getIndividual(currentRoundNumber()) + fun lastIndividual() = wrappedParticipant.getIndividual(completedRounds.size) fun getRoundsForIndividual(individual: ParticipantEntity) = - (completedRounds + listOf(currentRound)).filter { it.all { drt -> drt.participantId == individual.rowId } } + (completedRounds + listOf(currentRound)).filter { + it.all { drt -> drt.participantId == individual.rowId } + } protected fun getAllDartsFlattened() = completedRounds.flatten() + currentRound fun isHuman() = !currentIndividual().isAi() + fun hasMultiplePlayers() = wrappedParticipant.individuals.size > 1 + fun getPlayerIds() = wrappedParticipant.individuals.map { it.playerId } - /** - * Modifiers - */ - open fun dartThrown(dart: Dart) - { + /** Modifiers */ + open fun dartThrown(dart: Dart) { dart.roundNumber = currentRoundNumber() dart.participantId = currentIndividual().rowId currentRound.add(dart) @@ -52,18 +51,17 @@ abstract class AbstractPlayerState> fireStateChanged() } - fun resetRound() - { + fun resetRound() { currentRound.clear() fireStateChanged() } - fun commitRound() - { + fun commitRound() { val pt = currentIndividual() - val entities = currentRound.mapIndexed { ix, drt -> - DartEntity.factory(drt, pt.playerId, pt.rowId, currentRoundNumber(), ix + 1) - } + val entities = + currentRound.mapIndexed { ix, drt -> + DartEntity.factory(drt, pt.playerId, pt.rowId, currentRoundNumber(), ix + 1) + } BulkInserter.insert(entities) @@ -73,13 +71,11 @@ abstract class AbstractPlayerState> fireStateChanged() } - open fun addLoadedRound(darts: List) - { + open fun addLoadedRound(darts: List) { addCompletedRound(darts) } - fun addCompletedRound(darts: List) - { + fun addCompletedRound(darts: List) { val pt = currentIndividual() darts.forEach { it.participantId = pt.rowId } this.completedRounds.add(darts.toList()) @@ -87,8 +83,7 @@ abstract class AbstractPlayerState> fireStateChanged() } - fun setParticipantFinishPosition(finishingPosition: Int) - { + fun setParticipantFinishPosition(finishingPosition: Int) { val ptEntity = wrappedParticipant.participant ptEntity.finishingPosition = finishingPosition ptEntity.saveToDatabase() @@ -96,8 +91,7 @@ abstract class AbstractPlayerState> fireStateChanged() } - fun participantFinished(finishingPosition: Int, finalScore: Int) - { + fun participantFinished(finishingPosition: Int, finalScore: Int) { val ptEntity = wrappedParticipant.participant ptEntity.finishingPosition = finishingPosition ptEntity.finalScore = finalScore @@ -107,22 +101,16 @@ abstract class AbstractPlayerState> fireStateChanged() } - fun updateActive(active: Boolean) - { + fun updateActive(active: Boolean) { val changing = active != isActive isActive = active - if (changing) - { + if (changing) { fireStateChanged() } } @Suppress("UNCHECKED_CAST") - protected fun fireStateChanged() - { + protected fun fireStateChanged() { listeners.forEach { it.stateChanged(this as S) } } } - - - diff --git a/src/main/kotlin/dartzee/game/state/ClockPlayerState.kt b/src/main/kotlin/dartzee/game/state/ClockPlayerState.kt index 60bb8f28e..8e492cc8a 100644 --- a/src/main/kotlin/dartzee/game/state/ClockPlayerState.kt +++ b/src/main/kotlin/dartzee/game/state/ClockPlayerState.kt @@ -6,15 +6,17 @@ import dartzee.screen.game.SegmentStatuses import dartzee.utils.getAllNonMissSegments import dartzee.utils.getLongestStreak -data class ClockPlayerState(private val config: RoundTheClockConfig, - override val wrappedParticipant: IWrappedParticipant, - override val completedRounds: MutableList> = mutableListOf(), - override val currentRound: MutableList = mutableListOf(), - override var isActive: Boolean = false): AbstractPlayerState() -{ +data class ClockPlayerState( + private val config: RoundTheClockConfig, + override val wrappedParticipant: IWrappedParticipant, + override val completedRounds: MutableList> = mutableListOf(), + override val currentRound: MutableList = mutableListOf(), + override var isActive: Boolean = false +) : AbstractPlayerState() { fun findCurrentTarget() = getRemainingTargets().firstOrNull() - fun getCurrentTarget() = findCurrentTarget() ?: throw Exception("Dart thrown when no remaining targets") + fun getCurrentTarget() = + findCurrentTarget() ?: throw Exception("Dart thrown when no remaining targets") override fun getScoreSoFar() = getAllDartsFlattened().size @@ -22,46 +24,43 @@ data class ClockPlayerState(private val config: RoundTheClockConfig, fun onTrackForBrucey() = currentRound.all { it.hitClockTarget(config.clockType) } - fun hasHitTarget(target: Int) = getAllDartsFlattened().any { it.hitAnyClockTarget(config.clockType) && it.score == target } + fun hasHitTarget(target: Int) = + getAllDartsFlattened().any { it.hitAnyClockTarget(config.clockType) && it.score == target } - fun getSegmentStatus(): SegmentStatuses - { + fun getSegmentStatus(): SegmentStatuses { val scoringSegments = getAllNonMissSegments().filter { it.score == findCurrentTarget() } - val validSegments = if (!config.inOrder) - { - getAllNonMissSegments().filterNot { hasHitTarget(it.score) || it.score == 25 } - } - else - { - getAllNonMissSegments() - scoringSegments - } + val validSegments = + if (!config.inOrder) { + getAllNonMissSegments().filterNot { hasHitTarget(it.score) || it.score == 25 } + } else { + getAllNonMissSegments() - scoringSegments + } return SegmentStatuses(scoringSegments, validSegments) } - override fun dartThrown(dart: Dart) - { + override fun dartThrown(dart: Dart) { dart.startingScore = getCurrentTarget() - if (!config.inOrder) - { + if (!config.inOrder) { dart.clockTargets = getRemainingTargets() } super.dartThrown(dart) } - override fun addLoadedRound(darts: List) - { + override fun addLoadedRound(darts: List) { darts.forEach(::dartThrown) resetRound() addCompletedRound(darts) } - private fun getRemainingTargets(): List - { - val targetsHit = getAllDartsFlattened().filter { it.hitAnyClockTarget(config.clockType) }.map { it.score } + private fun getRemainingTargets(): List { + val targetsHit = + getAllDartsFlattened() + .filter { it.hitAnyClockTarget(config.clockType) } + .map { it.score } return (1..20).filterNot { targetsHit.contains(it) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/state/DartzeePlayerState.kt b/src/main/kotlin/dartzee/game/state/DartzeePlayerState.kt index 628b45e78..26e4fc712 100644 --- a/src/main/kotlin/dartzee/game/state/DartzeePlayerState.kt +++ b/src/main/kotlin/dartzee/game/state/DartzeePlayerState.kt @@ -7,37 +7,41 @@ import dartzee.db.DartzeeRoundResultEntity import dartzee.`object`.Dart import dartzee.utils.sumScore -data class DartzeePlayerState(override val wrappedParticipant: IWrappedParticipant, - override val completedRounds: MutableList> = mutableListOf(), - override val currentRound: MutableList = mutableListOf(), - override var isActive: Boolean = false, - val roundResults: MutableList = mutableListOf()): AbstractPlayerState() -{ - fun saveRoundResult(result: DartzeeRoundResult) - { +data class DartzeePlayerState( + override val wrappedParticipant: IWrappedParticipant, + override val completedRounds: MutableList> = mutableListOf(), + override val currentRound: MutableList = mutableListOf(), + override var isActive: Boolean = false, + val roundResults: MutableList = mutableListOf() +) : AbstractPlayerState() { + fun saveRoundResult(result: DartzeeRoundResult) { val pt = currentIndividual() val entity = DartzeeRoundResultEntity.factoryAndSave(result, pt, currentRoundNumber()) - if (!result.success) - { - AchievementEntity.updateAchievement(AchievementType.DARTZEE_HALVED, pt.playerId, pt.gameId, -result.score) + if (!result.success) { + AchievementEntity.updateAchievement( + AchievementType.DARTZEE_HALVED, + pt.playerId, + pt.gameId, + -result.score + ) } addRoundResult(entity) } - fun addRoundResult(result: DartzeeRoundResultEntity) - { + fun addRoundResult(result: DartzeeRoundResultEntity) { roundResults.add(result) fireStateChanged() } fun getPeakScore() = (1 until currentRoundNumber()).map(::getCumulativeScore).maxOrNull() - fun getCumulativeScore(roundNumber: Int): Int - { - val roundResultTotal = roundResults.filter { it.roundNumber <= roundNumber }.sumOf { it.score } + + fun getCumulativeScore(roundNumber: Int): Int { + val roundResultTotal = + roundResults.filter { it.roundNumber <= roundNumber }.sumOf { it.score } return roundResultTotal + sumScore(completedRounds.firstOrNull().orEmpty()) } override fun getScoreSoFar() = getCumulativeScore(currentRoundNumber()) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/state/GolfPlayerState.kt b/src/main/kotlin/dartzee/game/state/GolfPlayerState.kt index 9a9735afd..db48ab7c0 100644 --- a/src/main/kotlin/dartzee/game/state/GolfPlayerState.kt +++ b/src/main/kotlin/dartzee/game/state/GolfPlayerState.kt @@ -2,20 +2,21 @@ package dartzee.game.state import dartzee.`object`.Dart -data class GolfPlayerState(override val wrappedParticipant: IWrappedParticipant, - override val completedRounds: MutableList> = mutableListOf(), - override val currentRound: MutableList = mutableListOf(), - override var isActive: Boolean = false): AbstractPlayerState() -{ +data class GolfPlayerState( + override val wrappedParticipant: IWrappedParticipant, + override val completedRounds: MutableList> = mutableListOf(), + override val currentRound: MutableList = mutableListOf(), + override var isActive: Boolean = false +) : AbstractPlayerState() { override fun getScoreSoFar() = getCumulativeScoreForRound(completedRounds.size) - fun getCumulativeScoreForRound(roundNumber: Int) = (1..roundNumber).map(::getScoreForRound).sum() + fun getCumulativeScoreForRound(roundNumber: Int) = + (1..roundNumber).map(::getScoreForRound).sum() fun getScoreForRound(roundNumber: Int) = completedRounds[roundNumber - 1].last().getGolfScore() - fun countHoleInOnes(): Int - { + fun countHoleInOnes(): Int { val rounds = getRoundsForIndividual(currentIndividual()) return rounds.count { it.lastOrNull()?.getGolfScore() == 1 } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/state/IWrappedParticipant.kt b/src/main/kotlin/dartzee/game/state/IWrappedParticipant.kt index 9f3358fcf..2a541198d 100644 --- a/src/main/kotlin/dartzee/game/state/IWrappedParticipant.kt +++ b/src/main/kotlin/dartzee/game/state/IWrappedParticipant.kt @@ -10,33 +10,35 @@ import javax.swing.ImageIcon /** * Wraps up either a Team or an individual Participant, granting access to either: - * - * - The individual player of a round, e.g. to save their darts, unlock achievements and so on - * - The top-level "participant" (a player or team), for checking/setting finishing position, score etc + * - The individual player of a round, e.g. to save their darts, unlock achievements and so on + * - The top-level "participant" (a player or team), for checking/setting finishing position, score + * etc */ -sealed interface IWrappedParticipant -{ +sealed interface IWrappedParticipant { val individuals: List val participant: IParticipant fun ordinal() = participant.ordinal + fun getIndividual(roundNumber: Int): ParticipantEntity - fun getUniqueParticipantName() = UniqueParticipantName(individuals.map { it.getPlayerName() }.sorted().joinToString(" & ")) - fun getParticipantNameHtml(active: Boolean, currentParticipant: ParticipantEntity? = null): String - { - val contents = individuals.joinToString(" & ") { pt -> - if (active && pt == currentParticipant) - { - "${pt.getPlayerName()}" - } - else - { - pt.getPlayerName() + + fun getUniqueParticipantName() = + UniqueParticipantName(individuals.map { it.getPlayerName() }.sorted().joinToString(" & ")) + + fun getParticipantNameHtml( + active: Boolean, + currentParticipant: ParticipantEntity? = null + ): String { + val contents = + individuals.joinToString(" & ") { pt -> + if (active && pt == currentParticipant) { + "${pt.getPlayerName()}" + } else { + pt.getPlayerName() + } } - } - if (active && currentParticipant == null) - { + if (active && currentParticipant == null) { return "$contents" } @@ -46,17 +48,14 @@ sealed interface IWrappedParticipant fun getAvatar(roundNumber: Int, selected: Boolean, gameFinished: Boolean): ImageIcon } -class SingleParticipant(override val participant: ParticipantEntity): IWrappedParticipant -{ +class SingleParticipant(override val participant: ParticipantEntity) : IWrappedParticipant { override val individuals = listOf(participant) override fun getIndividual(roundNumber: Int) = participant - override fun getAvatar(roundNumber: Int, selected: Boolean, gameFinished: Boolean): ImageIcon - { + override fun getAvatar(roundNumber: Int, selected: Boolean, gameFinished: Boolean): ImageIcon { val avatar = participant.getPlayer().getAvatar() - if (gameFinished || selected) - { + if (gameFinished || selected) { return avatar } @@ -64,15 +63,21 @@ class SingleParticipant(override val participant: ParticipantEntity): IWrappedPa } } -class TeamParticipant(override val participant: TeamEntity, override val individuals: List): IWrappedParticipant -{ +class TeamParticipant( + override val participant: TeamEntity, + override val individuals: List +) : IWrappedParticipant { private val teamSize = individuals.size override fun getIndividual(roundNumber: Int) = individuals[(roundNumber - 1) % teamSize] - override fun getAvatar(roundNumber: Int, selected: Boolean, gameFinished: Boolean): ImageIcon - { + override fun getAvatar(roundNumber: Int, selected: Boolean, gameFinished: Boolean): ImageIcon { val selectedPlayer = if (selected) getIndividual(roundNumber).getPlayer() else null - return splitAvatar(individuals[0].getPlayer(), individuals[1].getPlayer(), selectedPlayer, gameFinished) + return splitAvatar( + individuals[0].getPlayer(), + individuals[1].getPlayer(), + selectedPlayer, + gameFinished + ) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/state/PlayerStateListener.kt b/src/main/kotlin/dartzee/game/state/PlayerStateListener.kt index ec3264e05..41851f7f4 100644 --- a/src/main/kotlin/dartzee/game/state/PlayerStateListener.kt +++ b/src/main/kotlin/dartzee/game/state/PlayerStateListener.kt @@ -1,6 +1,5 @@ package dartzee.game.state -interface PlayerStateListener> -{ +interface PlayerStateListener> { fun stateChanged(state: S) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/game/state/X01PlayerState.kt b/src/main/kotlin/dartzee/game/state/X01PlayerState.kt index 86ad5751b..8560fe8e3 100644 --- a/src/main/kotlin/dartzee/game/state/X01PlayerState.kt +++ b/src/main/kotlin/dartzee/game/state/X01PlayerState.kt @@ -6,39 +6,38 @@ import dartzee.utils.isFinishRound import dartzee.utils.isNearMissDouble import dartzee.utils.sumScore -data class X01PlayerState(private val startingScore: Int, - override val wrappedParticipant: IWrappedParticipant, - override val completedRounds: MutableList> = mutableListOf(), - override val currentRound: MutableList = mutableListOf(), - override var isActive: Boolean = false): AbstractPlayerState() -{ - override fun getScoreSoFar(): Int - { +data class X01PlayerState( + private val startingScore: Int, + override val wrappedParticipant: IWrappedParticipant, + override val completedRounds: MutableList> = mutableListOf(), + override val currentRound: MutableList = mutableListOf(), + override var isActive: Boolean = false +) : AbstractPlayerState() { + override fun getScoreSoFar(): Int { val hasFinished = completedRounds.isNotEmpty() && isFinishRound(completedRounds.last()) - if (!hasFinished) - { + if (!hasFinished) { return (completedRounds.size * 3) + currentRound.size - } - else - { + } else { val lastRound = completedRounds.last() val earlierRounds = completedRounds.subList(0, completedRounds.size - 1) return (earlierRounds.size * 3) + lastRound.size } } - fun getRemainingScoreForRound(roundNumber: Int): Int - { - val lastCompleted = if (roundNumber == currentRoundNumber()) roundNumber - 1 else roundNumber + fun getRemainingScoreForRound(roundNumber: Int): Int { + val lastCompleted = + if (roundNumber == currentRoundNumber()) roundNumber - 1 else roundNumber val roundSubSet = completedRounds.subList(0, lastCompleted) - val nonBustRounds = roundSubSet.filterNot { round -> - val lastDart = round.lastOrNull() - lastDart?.let(::isBust) ?: false - }.toMutableList() + val nonBustRounds = + roundSubSet + .filterNot { round -> + val lastDart = round.lastOrNull() + lastDart?.let(::isBust) ?: false + } + .toMutableList() - if (roundNumber == currentRoundNumber()) - { + if (roundNumber == currentRoundNumber()) { nonBustRounds.add(currentRound.toList()) } @@ -47,8 +46,7 @@ data class X01PlayerState(private val startingScore: Int, fun getRemainingScore() = getRemainingScoreForRound(currentRoundNumber()) - fun getBadLuckCount(): Int - { + fun getBadLuckCount(): Int { val rounds = getRoundsForIndividual(currentIndividual()) return rounds.flatten().count { isNearMissDouble(it) } } @@ -57,9 +55,8 @@ data class X01PlayerState(private val startingScore: Int, fun isCurrentRoundComplete() = currentRound.size == 3 || getRemainingScore() <= 1 - override fun dartThrown(dart: Dart) - { + override fun dartThrown(dart: Dart) { dart.startingScore = getRemainingScore() super.dartThrown(dart) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/listener/DartboardListener.kt b/src/main/kotlin/dartzee/listener/DartboardListener.kt index 906902a07..96ea91859 100644 --- a/src/main/kotlin/dartzee/listener/DartboardListener.kt +++ b/src/main/kotlin/dartzee/listener/DartboardListener.kt @@ -2,7 +2,6 @@ package dartzee.listener import dartzee.`object`.Dart -interface DartboardListener -{ +interface DartboardListener { fun dartThrown(dart: Dart) } diff --git a/src/main/kotlin/dartzee/logging/ElasticsearchPoster.kt b/src/main/kotlin/dartzee/logging/ElasticsearchPoster.kt index a48975423..e7c5f0d25 100644 --- a/src/main/kotlin/dartzee/logging/ElasticsearchPoster.kt +++ b/src/main/kotlin/dartzee/logging/ElasticsearchPoster.kt @@ -6,6 +6,8 @@ import com.amazonaws.auth.AWSStaticCredentialsProvider import com.amazonaws.http.AWSRequestSigningApacheInterceptor import com.amazonaws.services.elasticsearch.AWSElasticsearch import dartzee.utils.InjectedThings.logger +import java.io.IOException +import java.util.* import org.apache.http.HttpHost import org.apache.http.HttpStatus import org.apache.http.entity.ContentType @@ -13,88 +15,82 @@ import org.apache.http.nio.entity.NStringEntity import org.elasticsearch.client.Request import org.elasticsearch.client.ResponseException import org.elasticsearch.client.RestClient -import java.io.IOException -import java.util.* - -class ElasticsearchPoster(private val credentials: AWSCredentials?, - private val url: String, - private val indexPath: String, - client: RestClient? = null) -{ +class ElasticsearchPoster( + private val credentials: AWSCredentials?, + private val url: String, + private val indexPath: String, + client: RestClient? = null +) { private val client: RestClient? by lazy { client ?: createClient() } - private fun createClient(): RestClient? - { - try - { - val signer = AWS4Signer().apply { - serviceName = AWSElasticsearch.ENDPOINT_PREFIX - regionName = "eu-west-2" - } + private fun createClient(): RestClient? { + try { + val signer = + AWS4Signer().apply { + serviceName = AWSElasticsearch.ENDPOINT_PREFIX + regionName = "eu-west-2" + } - val interceptor = AWSRequestSigningApacheInterceptor(signer.serviceName, signer, AWSStaticCredentialsProvider(credentials)) + val interceptor = + AWSRequestSigningApacheInterceptor( + signer.serviceName, + signer, + AWSStaticCredentialsProvider(credentials) + ) return RestClient.builder(HttpHost.create(url)) - .setHttpClientConfigCallback { it.addInterceptorLast(interceptor) } - .build() - } - catch (t: Throwable) - { - logger.error(CODE_ELASTICSEARCH_ERROR, "Failed to set up RestClient - won't post logs to ES", t) + .setHttpClientConfigCallback { it.addInterceptorLast(interceptor) } + .build() + } catch (t: Throwable) { + logger.error( + CODE_ELASTICSEARCH_ERROR, + "Failed to set up RestClient - won't post logs to ES", + t + ) return null } } @Suppress("SwallowedException") - fun isOnline(): Boolean - { + fun isOnline(): Boolean { val initialisedClient = client ?: return false - try - { + try { val request = Request("GET", "/_cluster/health") val response = initialisedClient.performRequest(request) val status = response.statusLine.statusCode return status == HttpStatus.SC_OK - } - catch (t: IOException) - { + } catch (t: IOException) { return false - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_ELASTICSEARCH_ERROR, "Unexpected error checking if we are online", t) return false } } - fun postLog(logJson: String): Boolean - { + fun postLog(logJson: String): Boolean { val initialisedClient = client ?: return false - try - { + try { val request = Request("PUT", "/$indexPath/_doc/${UUID.randomUUID()}") request.entity = NStringEntity(logJson, ContentType.APPLICATION_JSON) val response = initialisedClient.performRequest(request) val status = response.statusLine.statusCode - if (status == HttpStatus.SC_CREATED) - { + if (status == HttpStatus.SC_CREATED) { return true - } - else - { + } else { handleResponseException(ResponseException(response)) return false } - } - catch (t: Throwable) - { - when (t) - { + } catch (t: Throwable) { + when (t) { is ResponseException -> handleResponseException(t) - is IOException -> logger.warn(CODE_ELASTICSEARCH_ERROR, "Caught $t trying to post to elasticsearch") + is IOException -> + logger.warn( + CODE_ELASTICSEARCH_ERROR, + "Caught $t trying to post to elasticsearch" + ) else -> logger.error(CODE_ELASTICSEARCH_ERROR, "Failed to post log to ES", t) } @@ -102,12 +98,23 @@ class ElasticsearchPoster(private val credentials: AWSCredentials?, } } - private fun handleResponseException(t: ResponseException) - { - when (val statusCode = t.response.statusLine.statusCode) - { - 502, 503, 504 -> logger.warn(CODE_ELASTICSEARCH_ERROR, "Elasticsearch currently unavailable - got $statusCode response", KEY_RESPONSE_BODY to t.response) - else -> logger.error(CODE_ELASTICSEARCH_ERROR, "Received status code $statusCode trying to post to ES", t, KEY_RESPONSE_BODY to t.response) + private fun handleResponseException(t: ResponseException) { + when (val statusCode = t.response.statusLine.statusCode) { + 502, + 503, + 504 -> + logger.warn( + CODE_ELASTICSEARCH_ERROR, + "Elasticsearch currently unavailable - got $statusCode response", + KEY_RESPONSE_BODY to t.response + ) + else -> + logger.error( + CODE_ELASTICSEARCH_ERROR, + "Received status code $statusCode trying to post to ES", + t, + KEY_RESPONSE_BODY to t.response + ) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/ILogDestination.kt b/src/main/kotlin/dartzee/logging/ILogDestination.kt index 0f73e2742..76ae2203c 100644 --- a/src/main/kotlin/dartzee/logging/ILogDestination.kt +++ b/src/main/kotlin/dartzee/logging/ILogDestination.kt @@ -1,7 +1,7 @@ package dartzee.logging -interface ILogDestination -{ +interface ILogDestination { fun log(record: LogRecord) + fun contextUpdated(context: Map) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/LogDestinationElasticsearch.kt b/src/main/kotlin/dartzee/logging/LogDestinationElasticsearch.kt index 8b7a26954..13dac065e 100644 --- a/src/main/kotlin/dartzee/logging/LogDestinationElasticsearch.kt +++ b/src/main/kotlin/dartzee/logging/LogDestinationElasticsearch.kt @@ -1,63 +1,56 @@ package dartzee.logging -import dartzee.`object`.DartsClient import dartzee.db.BulkInserter import dartzee.db.PendingLogsEntity +import dartzee.`object`.DartsClient import dartzee.utils.InjectedThings.logger import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit -class LogDestinationElasticsearch(private val poster: ElasticsearchPoster?, private val scheduler: ScheduledExecutorService): ILogDestination -{ +class LogDestinationElasticsearch( + private val poster: ElasticsearchPoster?, + private val scheduler: ScheduledExecutorService +) : ILogDestination { private val pendingLogs = ConcurrentHashMap.newKeySet() - override fun log(record: LogRecord) - { - if (!DartsClient.devMode) - { + override fun log(record: LogRecord) { + if (!DartsClient.devMode) { pendingLogs.add(record.toJsonString()) } } - override fun contextUpdated(context: Map){} + override fun contextUpdated(context: Map) {} - fun startPosting() - { + fun startPosting() { val runnable = Runnable { postPendingLogs() } scheduler.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS) } - fun postPendingLogs() - { + fun postPendingLogs() { poster ?: return - if (!poster.isOnline()) - { + if (!poster.isOnline()) { return } val logsForThisRun = pendingLogs.toList() logsForThisRun.forEach(::postLogToElasticsearch) } - private fun postLogToElasticsearch(logJson: String) - { - if (poster?.postLog(logJson) == true) - { + + private fun postLogToElasticsearch(logJson: String) { + if (poster?.postLog(logJson) == true) { pendingLogs.remove(logJson) } } - - fun readOldLogs() - { + fun readOldLogs() { val persistedLogs = PendingLogsEntity().retrieveEntities().map { it.logJson } pendingLogs.addAll(persistedLogs) PendingLogsEntity().deleteAll() } - fun shutDown() - { + fun shutDown() { scheduler.shutdown() logger.waitUntilLoggingFinished() @@ -65,4 +58,4 @@ class LogDestinationElasticsearch(private val poster: ElasticsearchPoster?, priv val entities = remainingLogs.map { PendingLogsEntity.factory(it) } BulkInserter.insert(entities) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/LogDestinationSystemOut.kt b/src/main/kotlin/dartzee/logging/LogDestinationSystemOut.kt index e178ce6cf..ea8fad1b3 100644 --- a/src/main/kotlin/dartzee/logging/LogDestinationSystemOut.kt +++ b/src/main/kotlin/dartzee/logging/LogDestinationSystemOut.kt @@ -1,13 +1,11 @@ package dartzee.logging -class LogDestinationSystemOut: ILogDestination -{ - override fun log(record: LogRecord) - { +class LogDestinationSystemOut : ILogDestination { + override fun log(record: LogRecord) { println(record) record.getThrowableStr()?.let { println(it) } record.keyValuePairs[KEY_STACK]?.let { println(it) } } override fun contextUpdated(context: Map) {} -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/LogRecord.kt b/src/main/kotlin/dartzee/logging/LogRecord.kt index 1b295bebc..89a3bc2b1 100644 --- a/src/main/kotlin/dartzee/logging/LogRecord.kt +++ b/src/main/kotlin/dartzee/logging/LogRecord.kt @@ -1,10 +1,10 @@ package dartzee.logging -import kong.unirest.json.JSONObject import java.time.Instant import java.time.ZoneId import java.time.format.DateTimeFormatter import java.util.* +import kong.unirest.json.JSONObject enum class Severity { INFO, @@ -12,20 +12,21 @@ enum class Severity { ERROR } -data class LogRecord(val timestamp: Instant, - val severity: Severity, - val loggingCode: LoggingCode, - val message: String, - val errorObject: Throwable?, - val keyValuePairs: Map) -{ - private val dateStr = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") +data class LogRecord( + val timestamp: Instant, + val severity: Severity, + val loggingCode: LoggingCode, + val message: String, + val errorObject: Throwable?, + val keyValuePairs: Map +) { + private val dateStr = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withLocale(Locale.UK) .withZone(ZoneId.systemDefault()) .format(timestamp) - override fun toString(): String - { + override fun toString(): String { val durationStr = keyValuePairs[KEY_DURATION]?.let { " (${it}ms) " }.orEmpty() val rowCountStr = keyValuePairs[KEY_ROW_COUNT]?.let { " (${it} rows) " }.orEmpty() return "$dateStr [$loggingCode] $durationStr$rowCountStr$message" @@ -33,22 +34,17 @@ data class LogRecord(val timestamp: Instant, fun getThrowableStr() = errorObject?.let { "$dateStr ${extractStackTrace(errorObject)}" } - fun toJsonString(): String - { + fun toJsonString(): String { val obj = JSONObject() obj.put("timestamp", DateTimeFormatter.ISO_INSTANT.format(timestamp)) obj.put("severity", severity.name) obj.put("loggingCode", loggingCode.toString()) obj.put("message", message) - errorObject?.let { - obj.put("stackTrace", extractStackTrace(errorObject)) - } + errorObject?.let { obj.put("stackTrace", extractStackTrace(errorObject)) } - keyValuePairs.forEach { - obj.put(it.key, "${it.value}") - } + keyValuePairs.forEach { obj.put(it.key, "${it.value}") } return obj.toString() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/Logger.kt b/src/main/kotlin/dartzee/logging/Logger.kt index 80c58f2eb..198b3b9e8 100644 --- a/src/main/kotlin/dartzee/logging/Logger.kt +++ b/src/main/kotlin/dartzee/logging/Logger.kt @@ -12,99 +12,131 @@ import kotlin.math.floor private const val LOGGER_THREAD = "Logger" -class Logger(private val destinations: List) -{ +class Logger(private val destinations: List) { val loggingContext = ConcurrentHashMap() private val loggerFactory = ThreadFactory { r -> Thread(r, LOGGER_THREAD) } private var logService = Executors.newFixedThreadPool(1, loggerFactory) - fun addToContext(loggingKey: String, value: Any?) - { + fun addToContext(loggingKey: String, value: Any?) { loggingContext[loggingKey] = value ?: "" destinations.forEach { it.contextUpdated(loggingContext.toMap()) } } - fun logSql(sqlStatement: String, genericStatement: String, duration: Long, rowCount: Int, dbName: String) - { - info(CODE_SQL, sqlStatement, + fun logSql( + sqlStatement: String, + genericStatement: String, + duration: Long, + rowCount: Int, + dbName: String + ) { + info( + CODE_SQL, + sqlStatement, KEY_DURATION to duration, KEY_GENERIC_SQL to genericStatement, KEY_SQL to sqlStatement, KEY_ROW_COUNT to rowCount, KEY_DATABASE_NAME to dbName, - KEY_STATEMENT_TYPE to SqlStatementType.fromStatement(sqlStatement).name) + KEY_STATEMENT_TYPE to SqlStatementType.fromStatement(sqlStatement).name + ) } - fun logProgress(code: LoggingCode, workDone: Long, workToDo: Long, percentageToLogAt: Int = 10) - { - //Convert 1 to 0.01, 50 to 0.5, etc. + fun logProgress( + code: LoggingCode, + workDone: Long, + workToDo: Long, + percentageToLogAt: Int = 10 + ) { + // Convert 1 to 0.01, 50 to 0.5, etc. val percentageAsDecimal = percentageToLogAt.toDouble() / 100 val percentageOfTotal = floor(workToDo * percentageAsDecimal) val remainder = workDone % percentageOfTotal - if (remainder == 0.0) - { + if (remainder == 0.0) { val percentStr = MathsUtil.getPercentage(workDone, workToDo) val logStr = "Done $workDone/$workToDo ($percentStr%)" info(code, logStr) } } - fun info(code: LoggingCode, message: String, vararg keyValuePairs: Pair) - { + fun info(code: LoggingCode, message: String, vararg keyValuePairs: Pair) { log(Severity.INFO, code, message, null, mapOf(*keyValuePairs)) } - fun warn(code: LoggingCode, message: String, vararg keyValuePairs: Pair) - { + fun warn(code: LoggingCode, message: String, vararg keyValuePairs: Pair) { log(Severity.WARN, code, message, null, mapOf(*keyValuePairs)) } - fun error(code: LoggingCode, message: String, vararg keyValuePairs: Pair) - { - error(code, message, Throwable(message), keyValuePairs=keyValuePairs) + fun error(code: LoggingCode, message: String, vararg keyValuePairs: Pair) { + error(code, message, Throwable(message), keyValuePairs = keyValuePairs) } - fun error(code: LoggingCode, message: String, errorObject: Throwable = Throwable(message), vararg keyValuePairs: Pair) - { - log(Severity.ERROR, code, message, errorObject, mapOf(*keyValuePairs, KEY_EXCEPTION_MESSAGE to errorObject.message)) + fun error( + code: LoggingCode, + message: String, + errorObject: Throwable = Throwable(message), + vararg keyValuePairs: Pair + ) { + log( + Severity.ERROR, + code, + message, + errorObject, + mapOf(*keyValuePairs, KEY_EXCEPTION_MESSAGE to errorObject.message) + ) } - fun logSqlException(sqlStatement: String, genericStatement: String, sqlException: SQLException) - { - error(CODE_SQL_EXCEPTION, "Caught SQLException for statement: $sqlStatement", sqlException, - KEY_SQL to sqlStatement, - KEY_GENERIC_SQL to genericStatement, - KEY_ERROR_CODE to sqlException.errorCode, - KEY_SQL_STATE to sqlException.sqlState) + fun logSqlException( + sqlStatement: String, + genericStatement: String, + sqlException: SQLException + ) { + error( + CODE_SQL_EXCEPTION, + "Caught SQLException for statement: $sqlStatement", + sqlException, + KEY_SQL to sqlStatement, + KEY_GENERIC_SQL to genericStatement, + KEY_ERROR_CODE to sqlException.errorCode, + KEY_SQL_STATE to sqlException.sqlState + ) } - private fun log(severity: Severity, code: LoggingCode, message: String, errorObject: Throwable?, keyValuePairs: Map) - { + private fun log( + severity: Severity, + code: LoggingCode, + message: String, + errorObject: Throwable?, + keyValuePairs: Map + ) { val timestamp = InjectedThings.clock.instant() - val logRecord = LogRecord(timestamp, severity, code, message, errorObject, loggingContext + keyValuePairs) + val logRecord = + LogRecord( + timestamp, + severity, + code, + message, + errorObject, + loggingContext + keyValuePairs + ) val runnable = Runnable { destinations.forEach { it.log(logRecord) } } - if (Thread.currentThread().name != LOGGER_THREAD && !logService.isShutdown && !logService.isTerminated) - { + if ( + Thread.currentThread().name != LOGGER_THREAD && + !logService.isShutdown && + !logService.isTerminated + ) { logService.execute(runnable) - } - else - { + } else { runnable.run() } } - fun waitUntilLoggingFinished() - { - try - { + fun waitUntilLoggingFinished() { + try { logService.shutdown() logService.awaitTermination(30, TimeUnit.SECONDS) - } - catch (_: InterruptedException) { } - finally - { + } catch (_: InterruptedException) {} finally { logService = Executors.newFixedThreadPool(1, loggerFactory) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/LoggerFactory.kt b/src/main/kotlin/dartzee/logging/LoggerFactory.kt index b0c7339f8..aa22d78e1 100644 --- a/src/main/kotlin/dartzee/logging/LoggerFactory.kt +++ b/src/main/kotlin/dartzee/logging/LoggerFactory.kt @@ -3,14 +3,16 @@ package dartzee.logging import dartzee.utils.AwsUtils import java.util.concurrent.Executors -const val ELASTICSEARCH_URL = "https://search-dartzee-nfqeufkxsx6cu7sybhm53dts7e.eu-west-2.es.amazonaws.com" +const val ELASTICSEARCH_URL = + "https://search-dartzee-nfqeufkxsx6cu7sybhm53dts7e.eu-west-2.es.amazonaws.com" private const val INDEX_PATH = "dartzee" -object LoggerFactory -{ - fun constructElasticsearchDestination(): LogDestinationElasticsearch - { - val poster = AwsUtils.readCredentials("AWS_LOGS")?.let { ElasticsearchPoster(it, ELASTICSEARCH_URL, INDEX_PATH) } +object LoggerFactory { + fun constructElasticsearchDestination(): LogDestinationElasticsearch { + val poster = + AwsUtils.readCredentials("AWS_LOGS")?.let { + ElasticsearchPoster(it, ELASTICSEARCH_URL, INDEX_PATH) + } return LogDestinationElasticsearch(poster, Executors.newScheduledThreadPool(1)) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/LoggerUncaughtExceptionHandler.kt b/src/main/kotlin/dartzee/logging/LoggerUncaughtExceptionHandler.kt index 0f41b5cfa..0f09bda03 100644 --- a/src/main/kotlin/dartzee/logging/LoggerUncaughtExceptionHandler.kt +++ b/src/main/kotlin/dartzee/logging/LoggerUncaughtExceptionHandler.kt @@ -5,38 +5,43 @@ import dartzee.logging.exceptions.WrappedSqlException import dartzee.utils.InjectedThings.logger import java.lang.Thread.UncaughtExceptionHandler -class LoggerUncaughtExceptionHandler : UncaughtExceptionHandler -{ - override fun uncaughtException(arg0: Thread, arg1: Throwable) - { - if (isSuppressed(arg1)) - { - //Still stack trace, but don't show an error message or email a log - logger.warn(CODE_UNCAUGHT_EXCEPTION, "Suppressing uncaught exception: $arg1", KEY_THREAD to arg0.toString(), KEY_EXCEPTION_MESSAGE to arg1.message) - } - else if (arg1 is WrappedSqlException) - { +class LoggerUncaughtExceptionHandler : UncaughtExceptionHandler { + override fun uncaughtException(arg0: Thread, arg1: Throwable) { + if (isSuppressed(arg1)) { + // Still stack trace, but don't show an error message or email a log + logger.warn( + CODE_UNCAUGHT_EXCEPTION, + "Suppressing uncaught exception: $arg1", + KEY_THREAD to arg0.toString(), + KEY_EXCEPTION_MESSAGE to arg1.message + ) + } else if (arg1 is WrappedSqlException) { logger.logSqlException(arg1.sqlStatement, arg1.genericStatement, arg1.sqlException) - } - else if (arg1 is ApplicationFault) - { - logger.error(arg1.loggingCode, "Uncaught exception: ${arg1.message}", arg1, KEY_THREAD to arg0.toString()) - } - else - { - logger.error(CODE_UNCAUGHT_EXCEPTION, "Uncaught exception: $arg1 in thread $arg0", arg1, KEY_THREAD to arg0.toString()) + } else if (arg1 is ApplicationFault) { + logger.error( + arg1.loggingCode, + "Uncaught exception: ${arg1.message}", + arg1, + KEY_THREAD to arg0.toString() + ) + } else { + logger.error( + CODE_UNCAUGHT_EXCEPTION, + "Uncaught exception: $arg1 in thread $arg0", + arg1, + KEY_THREAD to arg0.toString() + ) } } /** - * Some exceptions just can't be prevented, for example some Nimbus L&F exceptions that aren't caused by threading - * issues (I can see it's in the AWT thread) + * Some exceptions just can't be prevented, for example some Nimbus L&F exceptions that aren't + * caused by threading issues (I can see it's in the AWT thread) */ - private fun isSuppressed(t: Throwable): Boolean - { + private fun isSuppressed(t: Throwable): Boolean { val message = t.message ?: return false - return message.contains("cannot be cast to class javax.swing.Painter") - || message.contains("UIResource cannot be cast to class java.awt.Color") + return message.contains("cannot be cast to class javax.swing.Painter") || + message.contains("UIResource cannot be cast to class java.awt.Color") } } diff --git a/src/main/kotlin/dartzee/logging/LoggingCode.kt b/src/main/kotlin/dartzee/logging/LoggingCode.kt index fe11f875e..a1885b186 100644 --- a/src/main/kotlin/dartzee/logging/LoggingCode.kt +++ b/src/main/kotlin/dartzee/logging/LoggingCode.kt @@ -2,4 +2,4 @@ package dartzee.logging import dartzee.types.StringMicrotype -class LoggingCode(value: String): StringMicrotype(value) \ No newline at end of file +class LoggingCode(value: String) : StringMicrotype(value) diff --git a/src/main/kotlin/dartzee/logging/LoggingCodes.kt b/src/main/kotlin/dartzee/logging/LoggingCodes.kt index 32b4fab2b..f7439f70e 100644 --- a/src/main/kotlin/dartzee/logging/LoggingCodes.kt +++ b/src/main/kotlin/dartzee/logging/LoggingCodes.kt @@ -1,6 +1,6 @@ package dartzee.logging -//Info +// Info val CODE_SQL = LoggingCode("sql") val CODE_BULK_SQL = LoggingCode("bulkSql") val CODE_JUST_UPDATED = LoggingCode("justUpdated") @@ -51,14 +51,14 @@ val CODE_GAME_LAUNCHED = LoggingCode("gameLaunched") val CODE_MATCH_LAUNCHED = LoggingCode("matchLaunched") val CODE_MATCH_FINISHED = LoggingCode("matchFinished") -//Warn +// Warn val CODE_UNEXPECTED_ARGUMENT = LoggingCode("unexpectedArgument") val CODE_DATABASE_TOO_OLD = LoggingCode("databaseTooOld") val CODE_RESOURCE_CACHE_NOT_INITIALISED = LoggingCode("resourceCacheNotInitialised") val CODE_DATABASE_IN_USE = LoggingCode("databaseInUse") val CODE_NO_STREAMS = LoggingCode("noStreams") -//Error +// Error val CODE_LOOK_AND_FEEL_ERROR = LoggingCode("lafError") val CODE_SQL_EXCEPTION = LoggingCode("sqlException") val CODE_UNCAUGHT_EXCEPTION = LoggingCode("uncaughtException") @@ -86,4 +86,4 @@ val CODE_BACKUP_ERROR = LoggingCode("backupError") val CODE_RESTORE_ERROR = LoggingCode("restoreError") val CODE_DELETE_ERROR = LoggingCode("deleteError") val CODE_HYPERLINK_ERROR = LoggingCode("hyperlinkError") -val CODE_EDT_FROZEN = LoggingCode("edtFrozen") \ No newline at end of file +val CODE_EDT_FROZEN = LoggingCode("edtFrozen") diff --git a/src/main/kotlin/dartzee/logging/LoggingConsole.kt b/src/main/kotlin/dartzee/logging/LoggingConsole.kt index 8377fcd2e..e66bc2857 100644 --- a/src/main/kotlin/dartzee/logging/LoggingConsole.kt +++ b/src/main/kotlin/dartzee/logging/LoggingConsole.kt @@ -20,8 +20,7 @@ import javax.swing.text.DefaultStyledDocument import javax.swing.text.StyleConstants import javax.swing.text.StyleContext -class LoggingConsole: FocusableWindow(), ILogDestination -{ +class LoggingConsole : FocusableWindow(), ILogDestination { override val windowName = "Console" val doc = DefaultStyledDocument() @@ -29,8 +28,7 @@ class LoggingConsole: FocusableWindow(), ILogDestination private val textArea = JTextPane(doc) private val contextPanel = JPanel() - init - { + init { title = "Console" setSize(1000, 600) setLocationRelativeTo(null) @@ -47,35 +45,30 @@ class LoggingConsole: FocusableWindow(), ILogDestination contextPanel.layout = WrapLayout() } - override fun log(record: LogRecord) - { + override fun log(record: LogRecord) { val cx = StyleContext() val text = record.toString() val style = cx.addStyle(text, null) - if (record.loggingCode == CODE_SQL) - { + if (record.loggingCode == CODE_SQL) { val type = SqlStatementType.fromStatement(text) - when (type) - { - SqlStatementType.INSERT, SqlStatementType.UPDATE -> StyleConstants.setForeground(style, Color.ORANGE) + when (type) { + SqlStatementType.INSERT, + SqlStatementType.UPDATE -> StyleConstants.setForeground(style, Color.ORANGE) SqlStatementType.DELETE -> StyleConstants.setForeground(style, Color.PINK) SqlStatementType.SELECT -> StyleConstants.setForeground(style, Color.CYAN) } val dbName = record.keyValuePairs[KEY_DATABASE_NAME] - if (dbName != DartsDatabaseUtil.DATABASE_NAME) - { + if (dbName != DartsDatabaseUtil.DATABASE_NAME) { StyleConstants.setBackground(style, Color.DARK_GRAY) } } - if (record.severity == Severity.ERROR) - { + if (record.severity == Severity.ERROR) { StyleConstants.setForeground(style, Color.RED) } - try - { + try { doc.insertString(doc.length, "\n$text", style) record.getThrowableStr()?.let { doc.insertString(doc.length, "\n$it", style) } @@ -83,16 +76,13 @@ class LoggingConsole: FocusableWindow(), ILogDestination threadStack?.let { doc.insertString(doc.length, "\n$it", style) } textArea.select(doc.length, doc.length) - } - catch (ble: BadLocationException) - { + } catch (ble: BadLocationException) { System.err.println("BLE trying to append: $text") System.err.println(extractStackTrace(ble)) } } - override fun contextUpdated(context: Map) - { + override fun contextUpdated(context: Map) { contextPanel.removeAll() val labels = context.map(::factoryLabelForContext) @@ -104,8 +94,7 @@ class LoggingConsole: FocusableWindow(), ILogDestination } } - private fun factoryLabelForContext(field: Map.Entry): Component - { + private fun factoryLabelForContext(field: Map.Entry): Component { val label = JLabel("${field.key}: ${field.value}") label.foreground = Color.GREEN label.setMargins(5) @@ -118,8 +107,7 @@ class LoggingConsole: FocusableWindow(), ILogDestination return panel } - fun clear() - { + fun clear() { textArea.text = "" } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/LoggingKeys.kt b/src/main/kotlin/dartzee/logging/LoggingKeys.kt index 94ab56b30..a12c44f29 100644 --- a/src/main/kotlin/dartzee/logging/LoggingKeys.kt +++ b/src/main/kotlin/dartzee/logging/LoggingKeys.kt @@ -1,6 +1,6 @@ package dartzee.logging -//Logging Context +// Logging Context const val KEY_USERNAME = "username" const val KEY_APP_VERSION = "appVersion" const val KEY_DB_VERSION = "dbVersion" @@ -10,7 +10,7 @@ const val KEY_DEV_MODE = "devMode" const val KEY_CURRENT_SCREEN = "currentScreen" const val KEY_ACTIVE_WINDOW = "activeWindow" -//Other +// Other const val KEY_DURATION = "duration" const val KEY_SQL = "sql" const val KEY_GENERIC_SQL = "genericSql" diff --git a/src/main/kotlin/dartzee/logging/LoggingUtils.kt b/src/main/kotlin/dartzee/logging/LoggingUtils.kt index 553e967c7..1bb946369 100644 --- a/src/main/kotlin/dartzee/logging/LoggingUtils.kt +++ b/src/main/kotlin/dartzee/logging/LoggingUtils.kt @@ -4,46 +4,38 @@ import java.io.PrintWriter import java.io.StringWriter import java.sql.SQLException -fun extractStackTrace(t: Throwable): String -{ - if (t is SQLException) - { +fun extractStackTrace(t: Throwable): String { + if (t is SQLException) { return extractSqlException(t) } return getStackString(t) } -private fun getStackString(t: Throwable): String -{ +private fun getStackString(t: Throwable): String { val sw = StringWriter() val pw = PrintWriter(sw) t.printStackTrace(pw) return sw.toString() } -fun extractThreadStack(stack: Array): String -{ +fun extractThreadStack(stack: Array): String { val sw = StringWriter() val pw = PrintWriter(sw) - stack.forEach { - pw.println("\tat $it") - } + stack.forEach { pw.println("\tat $it") } return sw.toString() } -private fun extractSqlException(sqle: SQLException): String -{ +private fun extractSqlException(sqle: SQLException): String { val sb = StringBuilder() sb.append(getStackString(sqle)) var childSqle: SQLException? = sqle.nextException - while (childSqle != null) - { + while (childSqle != null) { sb.append("Child: ${getStackString(childSqle)}") childSqle = childSqle.nextException } return sb.toString() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/logging/exceptions/ApplicationFault.kt b/src/main/kotlin/dartzee/logging/exceptions/ApplicationFault.kt index 9d9965b6d..886949e04 100644 --- a/src/main/kotlin/dartzee/logging/exceptions/ApplicationFault.kt +++ b/src/main/kotlin/dartzee/logging/exceptions/ApplicationFault.kt @@ -2,5 +2,5 @@ package dartzee.logging.exceptions import dartzee.logging.LoggingCode -data class ApplicationFault(val loggingCode: LoggingCode, - override val message: String): Exception() \ No newline at end of file +data class ApplicationFault(val loggingCode: LoggingCode, override val message: String) : + Exception() diff --git a/src/main/kotlin/dartzee/logging/exceptions/WrappedSqlException.kt b/src/main/kotlin/dartzee/logging/exceptions/WrappedSqlException.kt index 41277985b..545fdd36f 100644 --- a/src/main/kotlin/dartzee/logging/exceptions/WrappedSqlException.kt +++ b/src/main/kotlin/dartzee/logging/exceptions/WrappedSqlException.kt @@ -2,4 +2,8 @@ package dartzee.logging.exceptions import java.sql.SQLException -data class WrappedSqlException(val sqlStatement: String, val genericStatement: String, val sqlException: SQLException): Exception() \ No newline at end of file +data class WrappedSqlException( + val sqlStatement: String, + val genericStatement: String, + val sqlException: SQLException +) : Exception() diff --git a/src/main/kotlin/dartzee/main/ApplicationExit.kt b/src/main/kotlin/dartzee/main/ApplicationExit.kt index d7a950924..b73244f8d 100644 --- a/src/main/kotlin/dartzee/main/ApplicationExit.kt +++ b/src/main/kotlin/dartzee/main/ApplicationExit.kt @@ -6,15 +6,16 @@ import dartzee.utils.InjectedThings import javax.swing.JOptionPane import kotlin.system.exitProcess -fun exitApplication() -{ +fun exitApplication() { val openGames = ScreenCache.getDartsGameScreens() val size = openGames.size - if (size > 0) - { - val ans = DialogUtil.showQuestionOLD("Are you sure you want to exit? There are $size game window(s) still open.", false) - if (ans == JOptionPane.NO_OPTION) - { + if (size > 0) { + val ans = + DialogUtil.showQuestionOLD( + "Are you sure you want to exit? There are $size game window(s) still open.", + false + ) + if (ans == JOptionPane.NO_OPTION) { return } } diff --git a/src/main/kotlin/dartzee/main/DartsMain.kt b/src/main/kotlin/dartzee/main/DartsMain.kt index ca5856351..6ee63e522 100644 --- a/src/main/kotlin/dartzee/main/DartsMain.kt +++ b/src/main/kotlin/dartzee/main/DartsMain.kt @@ -1,21 +1,20 @@ package dartzee.main -import dartzee.`object`.DartsClient import dartzee.core.util.DialogUtil import dartzee.core.util.EdtMonitor import dartzee.core.util.MessageDialogFactory import dartzee.logging.LoggerUncaughtExceptionHandler +import dartzee.`object`.DartsClient import dartzee.screen.ScreenCache import dartzee.utils.InjectedThings import kotlin.system.exitProcess -fun main(args: Array) -{ +fun main(args: Array) { DartsClient.parseProgramArguments(args) - if (!DartsClient.trueLaunch && DartsClient.isWindowsOs()) - { - Runtime.getRuntime().exec("cmd /c start javaw -Xms256m -Xmx512m -jar Dartzee.jar trueLaunch") + if (!DartsClient.trueLaunch && DartsClient.isWindowsOs()) { + Runtime.getRuntime() + .exec("cmd /c start javaw -Xms256m -Xmx512m -jar Dartzee.jar trueLaunch") exitProcess(0) } @@ -36,4 +35,4 @@ fun main(args: Array) val mainScreen = ScreenCache.mainScreen mainScreen.isVisible = true mainScreen.init() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/main/MainUtil.kt b/src/main/kotlin/dartzee/main/MainUtil.kt index 81390a49a..75dbc7ba3 100644 --- a/src/main/kotlin/dartzee/main/MainUtil.kt +++ b/src/main/kotlin/dartzee/main/MainUtil.kt @@ -16,22 +16,16 @@ import dartzee.utils.InjectedThings.logger import java.util.* import javax.swing.UIManager -fun setLookAndFeel() -{ - if (!DartsClient.isAppleOs()) - { +fun setLookAndFeel() { + if (!DartsClient.isAppleOs()) { setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel") } } -fun setLookAndFeel(laf: String) -{ - try - { +fun setLookAndFeel(laf: String) { + try { UIManager.setLookAndFeel(laf) - } - catch (e: Throwable) - { + } catch (e: Throwable) { logger.error(CODE_LOOK_AND_FEEL_ERROR, "Failed to load laf $laf", e) DialogUtil.showErrorOLD("Failed to load Look & Feel 'Nimbus'.") } @@ -39,8 +33,7 @@ fun setLookAndFeel(laf: String) logger.info(CODE_LOOK_AND_FEEL_SET, "Set look and feel to $laf") } -fun setLoggingContextFields() -{ +fun setLoggingContextFields() { logger.addToContext(KEY_USERNAME, getUsername()) logger.addToContext(KEY_APP_VERSION, DARTS_VERSION_NUMBER) logger.addToContext(KEY_OPERATING_SYSTEM, DartsClient.operatingSystem) @@ -49,11 +42,11 @@ fun setLoggingContextFields() } fun getDeviceId() = instance.get(INSTANCE_STRING_DEVICE_ID, null) ?: setDeviceId() -private fun setDeviceId(): String -{ + +private fun setDeviceId(): String { val deviceId = UUID.randomUUID().toString() instance.put(INSTANCE_STRING_DEVICE_ID, deviceId) return deviceId } -fun getUsername(): String = System.getProperty("user.name") \ No newline at end of file +fun getUsername(): String = System.getProperty("user.name") diff --git a/src/main/kotlin/dartzee/object/CheckoutSuggester.kt b/src/main/kotlin/dartzee/object/CheckoutSuggester.kt index 516807aa1..934c1207c 100644 --- a/src/main/kotlin/dartzee/object/CheckoutSuggester.kt +++ b/src/main/kotlin/dartzee/object/CheckoutSuggester.kt @@ -3,18 +3,14 @@ package dartzee.`object` import dartzee.logging.CODE_FILE_ERROR import dartzee.utils.InjectedThings.logger -object CheckoutSuggester -{ +object CheckoutSuggester { private val hmScoreToCheckout = readInCheckouts() - fun suggestCheckout(score: Int, dartsRemaining: Int): List? - { - for (dart in 1..dartsRemaining) - { + fun suggestCheckout(score: Int, dartsRemaining: Int): List? { + for (dart in 1..dartsRemaining) { val hmKey = "$score-$dart" val checkout = hmScoreToCheckout[hmKey] - if (checkout != null) - { + if (checkout != null) { return checkout } } @@ -22,26 +18,21 @@ object CheckoutSuggester return null } - private fun readInCheckouts(): MutableMap> - { - return try - { + private fun readInCheckouts(): MutableMap> { + return try { val inputStream = javaClass.getResourceAsStream("/Checkouts") val checkouts = mutableListOf() inputStream.bufferedReader().useLines { lines -> lines.forEach { checkouts.add(it) } } parseCheckouts(checkouts) - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_FILE_ERROR, "Failed to read in checkouts - won't make suggestions", t) mutableMapOf() } } - fun parseCheckouts(checkouts: List): MutableMap> - { + fun parseCheckouts(checkouts: List): MutableMap> { val map = mutableMapOf>() checkouts.forEach { checkout -> @@ -57,12 +48,14 @@ object CheckoutSuggester return map } - private fun addCheckoutsToMap(score: Int, darts: List, map: MutableMap>) - { + private fun addCheckoutsToMap( + score: Int, + darts: List, + map: MutableMap> + ) { val currentCheckout = darts.toMutableList() var currentScore = score - while (currentCheckout.isNotEmpty()) - { + while (currentCheckout.isNotEmpty()) { val key = "$currentScore-${currentCheckout.size}" map[key] = currentCheckout.toList() @@ -70,4 +63,4 @@ object CheckoutSuggester currentScore -= dart.getTotal() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/object/ColourWrapper.kt b/src/main/kotlin/dartzee/object/ColourWrapper.kt index eb99665ae..8047be382 100644 --- a/src/main/kotlin/dartzee/object/ColourWrapper.kt +++ b/src/main/kotlin/dartzee/object/ColourWrapper.kt @@ -4,33 +4,60 @@ import dartzee.utils.DartsColour import dartzee.utils.hmScoreToOrdinal import java.awt.Color -val DEFAULT_COLOUR_WRAPPER = ColourWrapper(DartsColour.DARTBOARD_BLACK, Color.RED, Color.RED, Color.WHITE, Color.GREEN, Color.GREEN, Color.RED, Color.GREEN) +val DEFAULT_COLOUR_WRAPPER = + ColourWrapper( + DartsColour.DARTBOARD_BLACK, + Color.RED, + Color.RED, + Color.WHITE, + Color.GREEN, + Color.GREEN, + Color.RED, + Color.GREEN + ) -val WIREFRAME_COLOUR_WRAPPER = ColourWrapper(DartsColour.TRANSPARENT).also { it.edgeColour = Color.BLACK } +val WIREFRAME_COLOUR_WRAPPER = + ColourWrapper(DartsColour.TRANSPARENT).also { it.edgeColour = Color.BLACK } -val GREY_COLOUR_WRAPPER = makeMonochromeWrapper(Color.GRAY.brighter(), Color.LIGHT_GRAY).also { it.outerDartboardColour = Color.GRAY } +val GREY_COLOUR_WRAPPER = + makeMonochromeWrapper(Color.GRAY.brighter(), Color.LIGHT_GRAY).also { + it.outerDartboardColour = Color.GRAY + } -fun makeMonochromeWrapper(dark: Color, light: Color) = ColourWrapper(dark, light, light, light, dark, dark, dark, light) +fun makeMonochromeWrapper(dark: Color, light: Color) = + ColourWrapper(dark, light, light, light, dark, dark, dark, light) -data class ColourWrapper(private val evenSingleColour : Color, private val evenDoubleColour : Color, - private val evenTrebleColour : Color, private val oddSingleColour : Color, - private val oddDoubleColour : Color, private val oddTrebleColour : Color, - private val innerBullColour : Color, private val outerBullColour : Color, - var outerDartboardColour : Color = Color.black) -{ +data class ColourWrapper( + private val evenSingleColour: Color, + private val evenDoubleColour: Color, + private val evenTrebleColour: Color, + private val oddSingleColour: Color, + private val oddDoubleColour: Color, + private val oddTrebleColour: Color, + private val innerBullColour: Color, + private val outerBullColour: Color, + var outerDartboardColour: Color = Color.black +) { var missedBoardColour: Color = DartsColour.TRANSPARENT var edgeColour: Color? = null - constructor(singleColour: Color) : this(singleColour, singleColour, singleColour, singleColour, singleColour, - singleColour, singleColour, singleColour, singleColour) + constructor( + singleColour: Color + ) : this( + singleColour, + singleColour, + singleColour, + singleColour, + singleColour, + singleColour, + singleColour, + singleColour, + singleColour + ) - /** - * Helpers - */ - private fun getBullColour(multiplier: Int): Color - { - return when (multiplier) - { + /** Helpers */ + private fun getBullColour(multiplier: Int): Color { + return when (multiplier) { 1 -> outerBullColour else -> innerBullColour } @@ -38,16 +65,13 @@ data class ColourWrapper(private val evenSingleColour : Color, private val evenD fun getColour(segment: DartboardSegment) = getColour(segment.getMultiplier(), segment.score) - private fun getColour(multiplier: Int, score: Int): Color - { - if (score == 25) - { + private fun getColour(multiplier: Int, score: Int): Color { + if (score == 25) { return getBullColour(multiplier) } val even = hmScoreToOrdinal[Integer.valueOf(score)] ?: false - return when (multiplier) - { + return when (multiplier) { 1 -> getSingleColour(even) 2 -> getDoubleColour(even) 3 -> getTrebleColour(even) @@ -56,6 +80,8 @@ data class ColourWrapper(private val evenSingleColour : Color, private val evenD } private fun getSingleColour(even: Boolean) = if (even) evenSingleColour else oddSingleColour + private fun getDoubleColour(even: Boolean) = if (even) evenDoubleColour else oddDoubleColour + private fun getTrebleColour(even: Boolean) = if (even) evenTrebleColour else oddTrebleColour } diff --git a/src/main/kotlin/dartzee/object/ComputationalDartboard.kt b/src/main/kotlin/dartzee/object/ComputationalDartboard.kt index e79a09c76..750c6d82f 100644 --- a/src/main/kotlin/dartzee/object/ComputationalDartboard.kt +++ b/src/main/kotlin/dartzee/object/ComputationalDartboard.kt @@ -7,15 +7,20 @@ import dartzee.utils.getPotentialAimPoints import dartzee.utils.translatePoint import java.awt.Point -class ComputationalDartboard(private val width: Int, private val height: Int): IDartboard -{ +class ComputationalDartboard(private val width: Int, private val height: Int) : IDartboard { private val hmSegmentToCenterPoint = constructCenterPointMap() override fun computeRadius() = computeRadius(width, height) + override fun computeCenter() = Point(width / 2, height / 2) fun getDeliberateMissPoint(): ComputedPoint { - val rawPoint = translatePoint(computeCenter(), computeRadius() * UPPER_BOUND_OUTSIDE_BOARD_RATIO, 180.0) + val rawPoint = + translatePoint( + computeCenter(), + computeRadius() * UPPER_BOUND_OUTSIDE_BOARD_RATIO, + 180.0 + ) return toComputedPoint(rawPoint) } @@ -28,4 +33,4 @@ class ComputationalDartboard(private val width: Int, private val height: Int): I val pt = getAverage(getPointsForSegment(segment)) toComputedPoint(pt) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/object/ComputedPoint.kt b/src/main/kotlin/dartzee/object/ComputedPoint.kt index c1320e095..1c750f8bd 100644 --- a/src/main/kotlin/dartzee/object/ComputedPoint.kt +++ b/src/main/kotlin/dartzee/object/ComputedPoint.kt @@ -2,4 +2,9 @@ package dartzee.`object` import java.awt.Point -data class ComputedPoint(val pt: Point, val segment: DartboardSegment, val radius: Double, val angle: Double) \ No newline at end of file +data class ComputedPoint( + val pt: Point, + val segment: DartboardSegment, + val radius: Double, + val angle: Double +) diff --git a/src/main/kotlin/dartzee/object/Dart.kt b/src/main/kotlin/dartzee/object/Dart.kt index 54646078c..a0339cb39 100644 --- a/src/main/kotlin/dartzee/object/Dart.kt +++ b/src/main/kotlin/dartzee/object/Dart.kt @@ -7,64 +7,54 @@ import dartzee.game.ClockType import java.sql.Timestamp open class Dart( - override val score: Int, - override val multiplier: Int, - val segmentType: SegmentType = SegmentType.MISS): IDart -{ + override val score: Int, + override val multiplier: Int, + val segmentType: SegmentType = SegmentType.MISS +) : IDart { var ordinal = -1 - //What the player's "score" was before throwing this dart. - //Means what you'd think for X01 - //For Round the Clock, this'll be what they were to aim for + // What the player's "score" was before throwing this dart. + // Means what you'd think for X01 + // For Round the Clock, this'll be what they were to aim for var startingScore = -1 - //For RTC again + // For RTC again var clockTargets: List = emptyList() - //Never set on the DB. Used for in-game stats, and is just set to the round number. + // Never set on the DB. Used for in-game stats, and is just set to the round number. var roundNumber = -1 var participantId: String = "" var gameId: String = "" var dtThrown: Timestamp = DateStatics.END_OF_TIME - /** - * Helpers - */ - + /** Helpers */ fun getGolfScore() = getGolfScore(roundNumber) - fun getHitScore(): Int - { - return when(multiplier) - { + fun getHitScore(): Int { + return when (multiplier) { 0 -> 0 else -> score } } - fun getSegmentTypeToAimAt(): SegmentType - { - return when (multiplier) - { + fun getSegmentTypeToAimAt(): SegmentType { + return when (multiplier) { 1 -> SegmentType.OUTER_SINGLE 2 -> SegmentType.DOUBLE else -> SegmentType.TREBLE } } - fun getGolfScore(target: Int): Int - { - return if (score != target) - { + fun getGolfScore(target: Int): Int { + return if (score != target) { 5 } else segmentType.getGolfScore() } fun toAimDart(): AimDart = AimDart(score, multiplier, segmentType) - override fun hashCode(): Int - { + override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + multiplier @@ -73,34 +63,30 @@ open class Dart( return result } - override fun equals(other: Any?): Boolean - { - if (this === other) - return true - if (other == null) - return false - if (other !is Dart) - return false - if (multiplier != other.multiplier) - return false - if (ordinal != other.ordinal) - return false + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null) return false + if (other !is Dart) return false + if (multiplier != other.multiplier) return false + if (ordinal != other.ordinal) return false return (score == other.score) } override fun toString() = format() - fun hitClockTarget(clockType: ClockType) = score == startingScore && isRightClockMultiplier(clockType) + fun hitClockTarget(clockType: ClockType) = + score == startingScore && isRightClockMultiplier(clockType) + fun hitAnyClockTarget(clockType: ClockType) = - hitClockTarget(clockType) || (clockTargets.contains(score) && isRightClockMultiplier(clockType)) + hitClockTarget(clockType) || + (clockTargets.contains(score) && isRightClockMultiplier(clockType)) private fun isRightClockMultiplier(clockType: ClockType): Boolean = - when (clockType) - { + when (clockType) { ClockType.Doubles -> isDouble() ClockType.Trebles -> isTreble() ClockType.Standard -> multiplier > 0 } } -class DartNotThrown : Dart(-1, -1) \ No newline at end of file +class DartNotThrown : Dart(-1, -1) diff --git a/src/main/kotlin/dartzee/object/DartHint.kt b/src/main/kotlin/dartzee/object/DartHint.kt index b1dbea575..f319e29dd 100644 --- a/src/main/kotlin/dartzee/object/DartHint.kt +++ b/src/main/kotlin/dartzee/object/DartHint.kt @@ -1,22 +1,16 @@ package dartzee.`object` -class DartHint(score: Int, multiplier: Int): Dart(score, multiplier) +class DartHint(score: Int, multiplier: Int) : Dart(score, multiplier) -fun factoryDartHintFromString(dartStr: String): DartHint? -{ - return if (dartStr.startsWith("D")) - { +fun factoryDartHintFromString(dartStr: String): DartHint? { + return if (dartStr.startsWith("D")) { val score = dartStr.replace("D", "").toInt() DartHint(score, 2) - } - else if (dartStr.startsWith("T")) - { + } else if (dartStr.startsWith("T")) { val score = dartStr.replace("T", "").toInt() DartHint(score, 3) - } - else - { + } else { val score = dartStr.toInt() DartHint(score, 1) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/object/DartboardSegment.kt b/src/main/kotlin/dartzee/object/DartboardSegment.kt index 0801af3b6..e990c43b5 100644 --- a/src/main/kotlin/dartzee/object/DartboardSegment.kt +++ b/src/main/kotlin/dartzee/object/DartboardSegment.kt @@ -8,25 +8,25 @@ import org.w3c.dom.Element const val MISS_FUDGE_FACTOR = 1805 /** - * Data class so that equivalent segments are treated as equal (e.g. DartzeeRuleCalculationResult externalisation) + * Data class so that equivalent segments are treated as equal (e.g. DartzeeRuleCalculationResult + * externalisation) */ @JsonIgnoreProperties("miss", "doubleExcludingBull", "multiplier", "total", "roughProbability") -data class DartboardSegment(val type: SegmentType, val score: Int) -{ - /** - * Helpers - */ +data class DartboardSegment(val type: SegmentType, val score: Int) { + /** Helpers */ fun isMiss() = type == SegmentType.MISS + fun isDoubleExcludingBull() = type == SegmentType.DOUBLE && score != 25 + fun getMultiplier() = type.getMultiplier() + fun getTotal(): Int = score * getMultiplier() override fun toString() = "$score ($type)" fun getRoughProbability() = type.getRoughSize(score).toDouble() / getRoughScoringArea() - fun writeXml(root: Element, name: String) - { + fun writeXml(root: Element, name: String) { val element = root.ownerDocument.createElement(name) element.setAttributeAny("Score", score) element.setAttributeAny("Type", type) @@ -34,10 +34,8 @@ data class DartboardSegment(val type: SegmentType, val score: Int) root.appendChild(element) } - companion object - { - fun readList(root: Element, itemName: String): List - { + companion object { + fun readList(root: Element, itemName: String): List { val list = root.getElementsByTagName(itemName) return (0 until list.length).map { i -> @@ -49,4 +47,3 @@ data class DartboardSegment(val type: SegmentType, val score: Int) } } } - diff --git a/src/main/kotlin/dartzee/object/DartsClient.kt b/src/main/kotlin/dartzee/object/DartsClient.kt index 2bee01347..286212509 100644 --- a/src/main/kotlin/dartzee/object/DartsClient.kt +++ b/src/main/kotlin/dartzee/object/DartsClient.kt @@ -11,36 +11,30 @@ import dartzee.utils.PreferenceUtil import dartzee.utils.UpdateManager import java.util.* -object DartsClient -{ +object DartsClient { var devMode = false var trueLaunch = false var operatingSystem = System.getProperty("os.name").lowercase(Locale.ENGLISH) var justUpdated = false var updateManager = UpdateManager - fun parseProgramArguments(args: Array) - { + fun parseProgramArguments(args: Array) { args.forEach { parseProgramArgument(it) } } - fun logArgumentState() - { - if (justUpdated) - { + fun logArgumentState() { + if (justUpdated) { logger.info(CODE_JUST_UPDATED, "Just updated to a new version") } val rt = Runtime.getRuntime() - val maxMb = rt.maxMemory() / (1024*1024) - val totalMb = rt.totalMemory() / (1024*1024) + val maxMb = rt.maxMemory() / (1024 * 1024) + val totalMb = rt.totalMemory() / (1024 * 1024) logger.info(CODE_MEMORY_SETTINGS, "Heap settings - Max [$maxMb MB], Total [$totalMb MB]") } - private fun parseProgramArgument(arg: String) - { - when (arg) - { + private fun parseProgramArgument(arg: String) { + when (arg) { "justUpdated" -> justUpdated = true "devMode" -> devMode = true "trueLaunch" -> trueLaunch = true @@ -48,29 +42,28 @@ object DartsClient } } - fun isAppleOs() = operatingSystem.contains("mac", ignoreCase = true) || operatingSystem.contains("darwin", ignoreCase = true) + fun isAppleOs() = + operatingSystem.contains("mac", ignoreCase = true) || + operatingSystem.contains("darwin", ignoreCase = true) + fun isWindowsOs() = operatingSystem.contains("windows", ignoreCase = true) - fun checkForUpdatesIfRequired() - { - if (devMode) - { + fun checkForUpdatesIfRequired() { + if (devMode) { logger.info(CODE_UPDATE_CHECK, "Not checking for updates: I'm in dev mode") return } - if (justUpdated) - { + if (justUpdated) { logger.info(CODE_UPDATE_CHECK, "Not checking for updates: just updated") return } - if (!PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES)) - { + if (!PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES)) { logger.info(CODE_UPDATE_CHECK, "Not checking for updates: preference disabled") return } updateManager.checkForUpdates(DARTS_VERSION_NUMBER) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/object/IDartboard.kt b/src/main/kotlin/dartzee/object/IDartboard.kt index a4b64f1aa..fde4c4946 100644 --- a/src/main/kotlin/dartzee/object/IDartboard.kt +++ b/src/main/kotlin/dartzee/object/IDartboard.kt @@ -6,18 +6,22 @@ import dartzee.utils.factorySegmentForPoint import dartzee.utils.getAngleForPoint import java.awt.Point -interface IDartboard -{ +interface IDartboard { fun computeRadius(): Double + fun computeCenter(): Point fun computeRadius(width: Int, height: Int) = 0.7 * minOf(width, height) / 2.0 - fun getPointsForSegment(segment: DartboardSegment) = computePointsForSegment(segment, computeCenter(), computeRadius()) + + fun getPointsForSegment(segment: DartboardSegment) = + computePointsForSegment(segment, computeCenter(), computeRadius()) fun isDouble(pt: Point) = getSegmentForPoint(pt).isDoubleExcludingBull() + fun getSegmentForPoint(pt: Point) = factorySegmentForPoint(pt, computeCenter(), computeRadius()) - fun translateAimPoint(aimPoint: AimPoint) = AimPoint(computeCenter(), computeRadius(), aimPoint.angle, aimPoint.ratio).point + fun translateAimPoint(aimPoint: AimPoint) = + AimPoint(computeCenter(), computeRadius(), aimPoint.angle, aimPoint.ratio).point fun toComputedPoint(pt: Point): ComputedPoint { val segment = getSegmentForPoint(pt) @@ -26,4 +30,4 @@ interface IDartboard return ComputedPoint(pt, segment, distance, angle) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/object/Quadrant.kt b/src/main/kotlin/dartzee/object/Quadrant.kt index 82d6ec562..b04d57e47 100644 --- a/src/main/kotlin/dartzee/object/Quadrant.kt +++ b/src/main/kotlin/dartzee/object/Quadrant.kt @@ -1,11 +1,15 @@ package dartzee.`object` /** - * Represents a quadrant on a planar graph. - * NOTE: The sign of y is different because in Java, (0,0) is in the top left. This means that moving "up" - * actually DECREASES y. "yIsPositive" means y is positive IN JAVA. + * Represents a quadrant on a planar graph. NOTE: The sign of y is different because in Java, (0,0) + * is in the top left. This means that moving "up" actually DECREASES y. "yIsPositive" means y is + * positive IN JAVA. */ -data class Quadrant(val minimumAngle : Int, val maximumAngle: Int, val xIsPositive: Boolean, val yIsPositive: Boolean) -{ +data class Quadrant( + val minimumAngle: Int, + val maximumAngle: Int, + val xIsPositive: Boolean, + val yIsPositive: Boolean +) { val sinForX = xIsPositive xor yIsPositive -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/object/SegmentType.kt b/src/main/kotlin/dartzee/object/SegmentType.kt index 86bca8eaf..ad4a05a3f 100644 --- a/src/main/kotlin/dartzee/object/SegmentType.kt +++ b/src/main/kotlin/dartzee/object/SegmentType.kt @@ -2,8 +2,7 @@ package dartzee.`object` import dartzee.game.ClockType -enum class SegmentType -{ +enum class SegmentType { DOUBLE, TREBLE, OUTER_SINGLE, @@ -11,8 +10,7 @@ enum class SegmentType MISS; fun getGolfScore() = - when (this) - { + when (this) { DOUBLE -> 1 TREBLE -> 2 INNER_SINGLE -> 3 @@ -21,39 +19,33 @@ enum class SegmentType } fun getMultiplier() = - when (this) - { + when (this) { DOUBLE -> 2 TREBLE -> 3 MISS -> 0 - OUTER_SINGLE, INNER_SINGLE -> 1 + OUTER_SINGLE, + INNER_SINGLE -> 1 } - fun getRoughSize(score: Int): Int - { + fun getRoughSize(score: Int): Int { if (score == 25) return if (this == DOUBLE) 137 else 716 - return when (this) - { - DOUBLE -> 441 //8820 - TREBLE -> 275 //5500 - OUTER_SINGLE -> 2464 //49280 - INNER_SINGLE -> 1586 //31720 + return when (this) { + DOUBLE -> 441 // 8820 + TREBLE -> 275 // 5500 + OUTER_SINGLE -> 2464 // 49280 + INNER_SINGLE -> 1586 // 31720 MISS -> MISS_FUDGE_FACTOR } } } -fun getSegmentTypeForClockType(clockType: ClockType): SegmentType -{ - return when (clockType) - { +fun getSegmentTypeForClockType(clockType: ClockType): SegmentType { + return when (clockType) { ClockType.Standard -> SegmentType.OUTER_SINGLE ClockType.Doubles -> SegmentType.DOUBLE ClockType.Trebles -> SegmentType.TREBLE } } -/** - * Hard-coded values based on counting the points in a 500x500 rendered dartboard. - */ -fun getRoughScoringArea(): Double = 96173.0 + MISS_FUDGE_FACTOR \ No newline at end of file +/** Hard-coded values based on counting the points in a 500x500 rendered dartboard. */ +fun getRoughScoringArea(): Double = 96173.0 + MISS_FUDGE_FACTOR diff --git a/src/main/kotlin/dartzee/reporting/IncludedPlayerParameters.kt b/src/main/kotlin/dartzee/reporting/IncludedPlayerParameters.kt index 61b0b3fd2..d3a2399d4 100644 --- a/src/main/kotlin/dartzee/reporting/IncludedPlayerParameters.kt +++ b/src/main/kotlin/dartzee/reporting/IncludedPlayerParameters.kt @@ -2,25 +2,21 @@ package dartzee.reporting const val COMPARATOR_SCORE_UNSET = "is unset" -data class IncludedPlayerParameters(var finishingPositions: List = listOf(), - var finalScoreComparator: String = "", - var finalScore: Int = -1) -{ - fun generateExtraWhereSql(alias: String): String - { +data class IncludedPlayerParameters( + var finishingPositions: List = listOf(), + var finalScoreComparator: String = "", + var finalScore: Int = -1 +) { + fun generateExtraWhereSql(alias: String): String { val sb = StringBuilder() - if (finishingPositions.isNotEmpty()) - { + if (finishingPositions.isNotEmpty()) { val finishingPositionsStr = finishingPositions.joinToString() sb.append(" AND $alias.FinishingPosition IN ($finishingPositionsStr)") } - if (finalScoreComparator.equals(COMPARATOR_SCORE_UNSET, ignoreCase = true)) - { + if (finalScoreComparator.equals(COMPARATOR_SCORE_UNSET, ignoreCase = true)) { sb.append(" AND $alias.FinalScore = -1") - } - else if (finalScore > -1) - { + } else if (finalScore > -1) { sb.append(" AND $alias.FinalScore $finalScoreComparator $finalScore") sb.append(" AND $alias.FinalScore > -1") } diff --git a/src/main/kotlin/dartzee/reporting/ParticipantWrapper.kt b/src/main/kotlin/dartzee/reporting/ParticipantWrapper.kt index 2164d356f..36cdca160 100644 --- a/src/main/kotlin/dartzee/reporting/ParticipantWrapper.kt +++ b/src/main/kotlin/dartzee/reporting/ParticipantWrapper.kt @@ -1,12 +1,8 @@ package dartzee.reporting -/** - * Lightweight wrapper object to represent a participant - * Used in reporting - */ -class ParticipantWrapper(private val playerName: String, val finishingPosition: Int) -{ +/** Lightweight wrapper object to represent a participant Used in reporting */ +class ParticipantWrapper(private val playerName: String, val finishingPosition: Int) { override fun toString() = "$playerName (${getPositionDesc()})" private fun getPositionDesc() = if (finishingPosition == -1) "-" else "$finishingPosition" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/reporting/ReportParameters.kt b/src/main/kotlin/dartzee/reporting/ReportParameters.kt index 3ef7a9533..7e6dbcea0 100644 --- a/src/main/kotlin/dartzee/reporting/ReportParameters.kt +++ b/src/main/kotlin/dartzee/reporting/ReportParameters.kt @@ -9,8 +9,7 @@ import dartzee.game.GameType import dartzee.utils.InjectedThings.mainDatabase import java.sql.Timestamp -class ReportParameters -{ +class ReportParameters { var gameType: GameType? = null var gameParams = "" var unfinishedOnly = false @@ -24,78 +23,65 @@ class ReportParameters var partOfMatch = MatchFilter.BOTH var pendingChanges: Boolean? = null - fun getExtraWhereSql(): String - { + fun getExtraWhereSql(): String { val sb = StringBuilder() - if (gameType != null) - { + if (gameType != null) { sb.append(" AND g.GameType = '$gameType'") } - if (!gameParams.isEmpty()) - { + if (!gameParams.isEmpty()) { sb.append(" AND g.GameParams = '$gameParams'") } - if (dtStartFrom != null) - { + if (dtStartFrom != null) { sb.append(" AND g.DtCreation >= '") sb.append(dtStartFrom) sb.append("'") } - if (dtStartTo != null) - { + if (dtStartTo != null) { sb.append(" AND g.DtCreation <= '") sb.append(dtStartTo) sb.append("'") } - if (dtFinishFrom != null) - { + if (dtFinishFrom != null) { sb.append(" AND g.DtFinish >= '") sb.append(dtFinishFrom) sb.append("'") } - if (dtFinishTo != null) - { + if (dtFinishTo != null) { sb.append(" AND g.DtFinish <= '") sb.append(dtFinishTo) sb.append("'") } - if (unfinishedOnly) - { + if (unfinishedOnly) { sb.append(" AND g.DtFinish = ") sb.append(getEndOfTimeSqlString()) } - if (partOfMatch == MatchFilter.GAMES_ONLY) - { + if (partOfMatch == MatchFilter.GAMES_ONLY) { sb.append(" AND g.DartsMatchId = ''") - } - else if (partOfMatch == MatchFilter.MATCHES_ONLY) - { + } else if (partOfMatch == MatchFilter.MATCHES_ONLY) { sb.append(" AND g.DartsMatchId <> ''") } pendingChanges?.let { pendingChanges -> - val dtLastSynced = SyncAuditEntity.getLastSyncData(mainDatabase)?.lastSynced ?: DateStatics.START_OF_TIME - if (pendingChanges) - { + val dtLastSynced = + SyncAuditEntity.getLastSyncData(mainDatabase)?.lastSynced + ?: DateStatics.START_OF_TIME + if (pendingChanges) { sb.append(" AND g.DtLastUpdate > ${dtLastSynced.getSqlString()}") - } - else - { + } else { sb.append(" AND g.DtLastUpdate <= ${dtLastSynced.getSqlString()}") } } val it = hmIncludedPlayerToParms.entries.iterator() - while (it.hasNext()) - { + while (it.hasNext()) { val entry = it.next() val player = entry.key val parms = entry.value @@ -111,16 +97,14 @@ class ReportParameters sb.append(")") } - for (player in excludedPlayers) - { + for (player in excludedPlayers) { sb.append(" AND NOT EXISTS (") sb.append(" SELECT 1 FROM Participant z") sb.append(" WHERE z.PlayerId = '${player.rowId}'") sb.append(" AND z.GameId = g.RowId)") } - if (excludeOnlyAi) - { + if (excludeOnlyAi) { sb.append(" AND EXISTS (") sb.append(" SELECT 1 FROM Participant z, Player p") sb.append(" WHERE z.PlayerId = p.RowId") @@ -131,17 +115,16 @@ class ReportParameters return sb.toString() } - override fun toString() = "[$gameType, $gameParams, $dtStartFrom, $dtStartTo, $dtFinishFrom, $dtFinishTo]" + override fun toString() = + "[$gameType, $gameParams, $dtStartFrom, $dtStartTo, $dtFinishFrom, $dtFinishTo]" - fun setEnforceMatch(matches: Boolean) - { + fun setEnforceMatch(matches: Boolean) { partOfMatch = if (matches) MatchFilter.MATCHES_ONLY else MatchFilter.GAMES_ONLY } } -enum class MatchFilter -{ +enum class MatchFilter { MATCHES_ONLY, GAMES_ONLY, BOTH -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/reporting/ReportingSqlUtil.kt b/src/main/kotlin/dartzee/reporting/ReportingSqlUtil.kt index 695ade577..671653d0b 100644 --- a/src/main/kotlin/dartzee/reporting/ReportingSqlUtil.kt +++ b/src/main/kotlin/dartzee/reporting/ReportingSqlUtil.kt @@ -5,11 +5,8 @@ import dartzee.utils.InjectedThings.mainDatabase import java.sql.ResultSet import java.sql.Timestamp -/** - * Refactored from ReportingResultsScreen - */ -fun runReport(rp: ReportParameters?): List -{ +/** Refactored from ReportingResultsScreen */ +fun runReport(rp: ReportParameters?): List { rp ?: return listOf() var sql = buildBasicSqlStatement() @@ -17,10 +14,10 @@ fun runReport(rp: ReportParameters?): List val hm = mutableMapOf() mainDatabase.executeQuery(sql).use { rs -> - while (rs.next()) - { + while (rs.next()) { val localId = rs.getLong("LocalId") - val wrapper = hm.getOrPut(localId) { ReportResultWrapper.factoryFromResultSet(localId, rs) } + val wrapper = + hm.getOrPut(localId) { ReportResultWrapper.factoryFromResultSet(localId, rs) } wrapper.addParticipant(rs) } } @@ -28,62 +25,61 @@ fun runReport(rp: ReportParameters?): List return hm.values.toList() } -fun buildBasicSqlStatement(): String -{ +fun buildBasicSqlStatement(): String { val sb = StringBuilder() - sb.append("SELECT g.RowId, g.LocalId, g.GameType, g.GameParams, g.DtCreation, g.DtFinish, p.Name, pt.FinishingPosition, g.DartsMatchId, g.MatchOrdinal, dt.Name AS TemplateName,") + sb.append( + "SELECT g.RowId, g.LocalId, g.GameType, g.GameParams, g.DtCreation, g.DtFinish, p.Name, pt.FinishingPosition, g.DartsMatchId, g.MatchOrdinal, dt.Name AS TemplateName," + ) sb.append(" CASE WHEN m.LocalId IS NULL THEN -1 ELSE m.LocalId END AS LocalMatchId") sb.append(" FROM Participant pt, Player p, Game g") sb.append(" LEFT OUTER JOIN DartsMatch m ON (g.DartsMatchId = m.RowId)") - sb.append(" LEFT OUTER JOIN DartzeeTemplate dt ON (g.GameType = '${GameType.DARTZEE}' AND g.GameParams = dt.RowId)") + sb.append( + " LEFT OUTER JOIN DartzeeTemplate dt ON (g.GameType = '${GameType.DARTZEE}' AND g.GameParams = dt.RowId)" + ) sb.append(" WHERE pt.GameId = g.RowId") sb.append(" AND pt.PlayerId = p.RowId") return sb.toString() } -data class ReportResultWrapper(val localId: Long, - val gameType: GameType, - val gameParams: String, - val dtStart: Timestamp, - val dtFinish: Timestamp, - val localMatchId: Long, - val matchOrdinal: Int, - val templateName: String?) -{ +data class ReportResultWrapper( + val localId: Long, + val gameType: GameType, + val gameParams: String, + val dtStart: Timestamp, + val dtFinish: Timestamp, + val localMatchId: Long, + val matchOrdinal: Int, + val templateName: String? +) { private val participants = mutableListOf() - fun getTableRow(): Array - { - val gameTypeDesc = templateName?.let { "Dartzee - $templateName" } ?: gameType.getDescription(gameParams) + fun getTableRow(): Array { + val gameTypeDesc = + templateName?.let { "Dartzee - $templateName" } ?: gameType.getDescription(gameParams) val playerDesc = getPlayerDesc() var matchDesc = "" - if (localMatchId > -1) - { + if (localMatchId > -1) { matchDesc = "#$localMatchId (Game $matchOrdinal)" } return arrayOf(localId, gameTypeDesc, playerDesc, dtStart, dtFinish, matchDesc) } - private fun getPlayerDesc(): String - { + private fun getPlayerDesc(): String { participants.sortBy { it.finishingPosition } return participants.joinToString() } - fun addParticipant(rs: ResultSet) - { + fun addParticipant(rs: ResultSet) { val playerName = rs.getString("Name") val finishPos = rs.getInt("FinishingPosition") participants.add(ParticipantWrapper(playerName, finishPos)) } - companion object - { - fun factoryFromResultSet(localId: Long, rs: ResultSet): ReportResultWrapper - { + companion object { + fun factoryFromResultSet(localId: Long, rs: ResultSet): ReportResultWrapper { val gameType = GameType.valueOf(rs.getString("GameType")) val gameParams = rs.getString("GameParams") val dtStart = rs.getTimestamp("DtCreation") @@ -92,9 +88,19 @@ data class ReportResultWrapper(val localId: Long, val matchOrdinal = rs.getInt("MatchOrdinal") val templateName = rs.getString("TemplateName") - return ReportResultWrapper(localId, gameType, gameParams, dtStart, dtFinish, localMatchId, matchOrdinal, templateName) + return ReportResultWrapper( + localId, + gameType, + gameParams, + dtStart, + dtFinish, + localMatchId, + matchOrdinal, + templateName + ) } - fun getTableRowsFromWrappers(wrappers: List) = wrappers.map { it.getTableRow() } + fun getTableRowsFromWrappers(wrappers: List) = + wrappers.map { it.getTableRow() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/AbstractPlayerConfigurationDialog.kt b/src/main/kotlin/dartzee/screen/AbstractPlayerConfigurationDialog.kt index fcee4cc8c..ad8cfd0e3 100644 --- a/src/main/kotlin/dartzee/screen/AbstractPlayerConfigurationDialog.kt +++ b/src/main/kotlin/dartzee/screen/AbstractPlayerConfigurationDialog.kt @@ -6,38 +6,33 @@ import dartzee.core.util.DialogUtil import dartzee.db.PlayerEntity import javax.swing.JTextField -abstract class AbstractPlayerConfigurationDialog(protected val saveCallback: (player: PlayerEntity) -> Unit, protected val player: PlayerEntity): SimpleDialog() -{ - //Components +abstract class AbstractPlayerConfigurationDialog( + protected val saveCallback: (player: PlayerEntity) -> Unit, + protected val player: PlayerEntity +) : SimpleDialog() { + // Components protected val avatar = PlayerAvatar() protected val textFieldName = JTextField().also { it.name = "nameField" } - //Abstract methods + // Abstract methods abstract fun savePlayer() - override fun okPressed() - { - if (valid()) - { + override fun okPressed() { + if (valid()) { savePlayer() saveCallback(player) } } - /** - * Basic validation on the player name and avatar selections - */ - protected fun valid(): Boolean - { + /** Basic validation on the player name and avatar selections */ + protected fun valid(): Boolean { val name = textFieldName.text - if (!isValidName(name)) - { + if (!isValidName(name)) { return false } val avatarId = avatar.avatarId - if (avatarId.isEmpty()) - { + if (avatarId.isEmpty()) { DialogUtil.showErrorOLD("You must select an avatar.") return false } @@ -45,31 +40,25 @@ abstract class AbstractPlayerConfigurationDialog(protected val saveCallback: (pl return true } - private fun isValidName(name: String?): Boolean - { - if (name.isNullOrEmpty()) - { + private fun isValidName(name: String?): Boolean { + if (name.isNullOrEmpty()) { DialogUtil.showErrorOLD("You must enter a name for this player.") return false } val length = name.length - if (length < 3) - { + if (length < 3) { DialogUtil.showErrorOLD("The player name must be at least 3 characters long.") return false } - if (length > 25) - { + if (length > 25) { DialogUtil.showErrorOLD("The player name cannot be more than 25 characters long.") return false } - val existingPlayer = PlayerEntity.retrieveForName(name) - if (existingPlayer != null && existingPlayer.rowId != player.rowId) - { + if (existingPlayer != null && existingPlayer.rowId != player.rowId) { DialogUtil.showErrorOLD("A player with the name $name already exists.") return false } diff --git a/src/main/kotlin/dartzee/screen/AchievementConversionDialog.kt b/src/main/kotlin/dartzee/screen/AchievementConversionDialog.kt index 4d2e3ad51..4c9c753aa 100644 --- a/src/main/kotlin/dartzee/screen/AchievementConversionDialog.kt +++ b/src/main/kotlin/dartzee/screen/AchievementConversionDialog.kt @@ -8,7 +8,6 @@ import dartzee.core.bean.RadioButtonPanel import dartzee.core.screen.SimpleDialog import dartzee.core.util.DialogUtil import dartzee.utils.InjectedThings -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.event.ActionEvent import java.util.* @@ -16,17 +15,16 @@ import javax.swing.DefaultComboBoxModel import javax.swing.JComboBox import javax.swing.JOptionPane import javax.swing.JRadioButton +import net.miginfocom.swing.MigLayout -class AchievementConversionDialog : SimpleDialog() -{ +class AchievementConversionDialog : SimpleDialog() { private val panelTop = RadioButtonPanel() private val rdbtnAll = JRadioButton("All") private val rdbtnSpecific = JRadioButton("Specific conversion") private val cbConversionType = JComboBox() private val playerSelector = PlayerSelector() - init - { + init { title = "Achievement Conversion" setSize(600, 400) isResizable = false @@ -47,27 +45,21 @@ class AchievementConversionDialog : SimpleDialog() initComboBox() } - private fun initComboBox() - { + private fun initComboBox() { val achievements = Vector(getAllAchievements()) cbConversionType.model = DefaultComboBoxModel(achievements) } - override fun okPressed() - { - if (!valid()) - { + override fun okPressed() { + if (!valid()) { return } val selectedPlayerIds = playerSelector.getSelectedPlayers().map { it.rowId } - if (rdbtnAll.isSelected) - { + if (rdbtnAll.isSelected) { val achievements = getAllAchievements() runConversionsWithProgressBar(achievements, selectedPlayerIds) - } - else - { + } else { val ix = cbConversionType.selectedIndex val achievement = cbConversionType.getItemAt(ix) @@ -77,25 +69,23 @@ class AchievementConversionDialog : SimpleDialog() dispose() } - private fun valid() : Boolean - { - if (playerSelector.getSelectedPlayers().isEmpty()) - { - val ans = DialogUtil.showQuestionOLD("This will run the conversion(s) for ALL players. Proceed?", false) + private fun valid(): Boolean { + if (playerSelector.getSelectedPlayers().isEmpty()) { + val ans = + DialogUtil.showQuestionOLD( + "This will run the conversion(s) for ALL players. Proceed?", + false + ) return ans == JOptionPane.YES_OPTION } return true } - override fun actionPerformed(arg0: ActionEvent) - { - if (panelTop.isEventSource(arg0)) - { + override fun actionPerformed(arg0: ActionEvent) { + if (panelTop.isEventSource(arg0)) { cbConversionType.isEnabled = rdbtnSpecific.isSelected - } - else - { + } else { super.actionPerformed(arg0) } } diff --git a/src/main/kotlin/dartzee/screen/ChangeLog.kt b/src/main/kotlin/dartzee/screen/ChangeLog.kt index 994a734ed..0d37c3626 100644 --- a/src/main/kotlin/dartzee/screen/ChangeLog.kt +++ b/src/main/kotlin/dartzee/screen/ChangeLog.kt @@ -11,8 +11,7 @@ class ChangeLog : JFrame() { private val scrollPane = JScrollPane() private val textArea = JTextArea() - init - { + init { title = "Change Log" setSize(500, 570) setLocationRelativeTo(null) @@ -25,8 +24,7 @@ class ChangeLog : JFrame() { scrollPane.setViewportView(textArea) } - private fun appendChangeLog() - { + private fun appendChangeLog() { textArea.text = "" val text = javaClass.getResource("/ChangeLog").readText() @@ -35,4 +33,4 @@ class ChangeLog : JFrame() { textArea.caretPosition = 0 textArea.lineWrap = true } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/DartsApp.kt b/src/main/kotlin/dartzee/screen/DartsApp.kt index 7a97b0437..b304004af 100644 --- a/src/main/kotlin/dartzee/screen/DartsApp.kt +++ b/src/main/kotlin/dartzee/screen/DartsApp.kt @@ -43,13 +43,11 @@ private const val CMD_TEST = "test" val APP_SIZE = Dimension(1000, 700) -class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowListener -{ +class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowListener { override val windowName = "Main Window" var currentScreen: EmbeddedScreen = ScreenCache.get() - init - { + init { title = "Darts" size = APP_SIZE minimumSize = APP_SIZE @@ -62,8 +60,7 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList addWindowListener(this) } - fun init() - { + fun init() { setIcon() ResourceCache.initialiseResources() @@ -75,9 +72,8 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList addConsoleShortcut() switchScreen(ScreenCache.get()) - //Pop up the change log if we've just updated - if (DartsClient.justUpdated) - { + // Pop up the change log if we've just updated + if (DartsClient.justUpdated) { convertEmptyAchievements() val dialog = ChangeLog() @@ -85,15 +81,13 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList } } - private fun setIcon() - { + private fun setIcon() { val imageStr = "dartzee" - //Load the four images corresponding to 16px, 32px, 64px and 128px + // Load the four images corresponding to 16px, 32px, 64px and 128px val images = ArrayList() var i = 16 - while (i < 256) - { + while (i < 256) { val ico = ImageIcon(javaClass.getResource("/icons/$imageStr$i.png")).image images.add(ico) i *= 2 @@ -102,8 +96,7 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList iconImages = images } - private fun addConsoleShortcut() - { + private fun addConsoleShortcut() { val triggerStroke = KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_DOWN_MASK) val content = contentPane as JPanel @@ -111,28 +104,24 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList inputMap.put(triggerStroke, "showConsole") val actionMap = content.actionMap - actionMap.put("showConsole", object : AbstractAction() - { - override fun actionPerformed(e: ActionEvent) - { - val loggingDialog = InjectedThings.loggingConsole - loggingDialog.isVisible = true - loggingDialog.toFront() + actionMap.put( + "showConsole", + object : AbstractAction() { + override fun actionPerformed(e: ActionEvent) { + val loggingDialog = InjectedThings.loggingConsole + loggingDialog.isVisible = true + loggingDialog.toFront() + } } - }) + ) } - fun switchScreen(scrn: EmbeddedScreen, reInit: Boolean = true) - { - try - { - if (reInit) - { + fun switchScreen(scrn: EmbeddedScreen, reInit: Boolean = true) { + try { + if (reInit) { scrn.initialise() } - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_SCREEN_LOAD_ERROR, "Failed to load screen ${scrn.getScreenName()}", t) DialogUtil.showErrorOLD("Error loading screen - " + scrn.getScreenName()) return @@ -150,56 +139,38 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList logger.addToContext(KEY_CURRENT_SCREEN, scrn.getScreenName()) - //Need repaint() in case we don't resize. + // Need repaint() in case we don't resize. pack() repaint() scrn.postInit() } - /** - * CheatListener - */ + /** CheatListener */ override fun commandsEnabled() = DartsClient.devMode - override fun processCommand(cmd: String): String - { + override fun processCommand(cmd: String): String { var textToShow = "" - if (cmd.startsWith(CMD_PURGE_GAME)) - { + if (cmd.startsWith(CMD_PURGE_GAME)) { val gameIdentifier = cmd.substring(CMD_PURGE_GAME.length) val gameId = Integer.parseInt(gameIdentifier) DevUtilities.purgeGame(gameId.toLong()) - } - else if (cmd.startsWith(CMD_LOAD_GAME)) - { + } else if (cmd.startsWith(CMD_LOAD_GAME)) { val gameIdentifier = cmd.substring(CMD_LOAD_GAME.length) val localId = gameIdentifier.toLong() val gameId = GameEntity.getGameId(localId) gameId?.let { gameLauncher.loadAndDisplayGame(gameId) } - } - else if (cmd == CMD_CLEAR_CONSOLE) - { + } else if (cmd == CMD_CLEAR_CONSOLE) { InjectedThings.loggingConsole.clear() - } - else if (cmd == "dim") - { + } else if (cmd == "dim") { println("Current screen size: $size") - } - else if (cmd == CMD_EMPTY_SCREEN_CACHE) - { + } else if (cmd == CMD_EMPTY_SCREEN_CACHE) { ScreenCache.emptyCache() - } - else if (cmd == CMD_GUID) - { + } else if (cmd == CMD_GUID) { textToShow = UUID.randomUUID().toString() - } - else if (cmd == "stacktrace") - { + } else if (cmd == "stacktrace") { logger.error(LoggingCode("test"), "Testing stack trace") - } - else if (cmd == CMD_TEST) - { + } else if (cmd == CMD_TEST) { val window = TestWindow() window.isVisible = true } @@ -208,14 +179,18 @@ class DartsApp(commandBar: CheatBar) : AbstractDevScreen(commandBar), WindowList } override fun windowActivated(arg0: WindowEvent) {} + override fun windowClosed(arg0: WindowEvent) {} + override fun windowDeactivated(arg0: WindowEvent) {} + override fun windowDeiconified(arg0: WindowEvent) {} + override fun windowIconified(arg0: WindowEvent) {} + override fun windowOpened(arg0: WindowEvent) {} - override fun windowClosing(arg0: WindowEvent) - { + override fun windowClosing(arg0: WindowEvent) { exitApplication() } } diff --git a/src/main/kotlin/dartzee/screen/EmbeddedScreen.kt b/src/main/kotlin/dartzee/screen/EmbeddedScreen.kt index 04379bac9..c0a38c10d 100644 --- a/src/main/kotlin/dartzee/screen/EmbeddedScreen.kt +++ b/src/main/kotlin/dartzee/screen/EmbeddedScreen.kt @@ -10,9 +10,7 @@ import java.awt.event.ActionListener import javax.swing.JButton import javax.swing.JPanel - -abstract class EmbeddedScreen : JPanel(), ActionListener -{ +abstract class EmbeddedScreen : JPanel(), ActionListener { val btnBack = JButton(" < Back") val btnNext = JButton("Next > ") @@ -20,8 +18,7 @@ abstract class EmbeddedScreen : JPanel(), ActionListener protected val panelNext = JPanel() protected val panelBack = JPanel() - init - { + init { preferredSize = Dimension(800, 610) layout = BorderLayout(0, 0) @@ -42,13 +39,11 @@ abstract class EmbeddedScreen : JPanel(), ActionListener } abstract fun initialise() - abstract fun getScreenName() : String - /** - * Called after the new screen has been switched in etc - */ - open fun postInit() - { + abstract fun getScreenName(): String + + /** Called after the new screen has been switched in etc */ + open fun postInit() { btnBack.isVisible = showBackButton() btnNext.isVisible = showNextButton() @@ -57,11 +52,9 @@ abstract class EmbeddedScreen : JPanel(), ActionListener open fun getBackTarget(): EmbeddedScreen = ScreenCache.get() - override fun actionPerformed(arg0: ActionEvent) - { + override fun actionPerformed(arg0: ActionEvent) { val src = arg0.source - when (arg0.source) - { + when (arg0.source) { btnBack -> backPressed() btnNext -> nextPressed() else -> logger.error(CODE_SWING_ERROR, "Unexpected actionPerformed: $src") @@ -70,30 +63,24 @@ abstract class EmbeddedScreen : JPanel(), ActionListener open fun getNextText() = "Next" - open fun hideBackButton() - { + open fun hideBackButton() { btnBack.isVisible = false } - - open fun backPressed() - { + open fun backPressed() { ScreenCache.switch(getBackTarget(), false) } - fun toggleNextVisibility(visible: Boolean) - { + fun toggleNextVisibility(visible: Boolean) { btnNext.isVisible = visible } - open fun nextPressed() - { - //default method + open fun nextPressed() { + // default method } - /** - * Default methods - */ + /** Default methods */ open fun showBackButton() = true + open fun showNextButton() = false } diff --git a/src/main/kotlin/dartzee/screen/FocusableWindow.kt b/src/main/kotlin/dartzee/screen/FocusableWindow.kt index 860471fc8..9e5366a75 100644 --- a/src/main/kotlin/dartzee/screen/FocusableWindow.kt +++ b/src/main/kotlin/dartzee/screen/FocusableWindow.kt @@ -6,19 +6,16 @@ import java.awt.event.WindowEvent import java.awt.event.WindowFocusListener import javax.swing.JFrame -abstract class FocusableWindow: JFrame(), WindowFocusListener -{ +abstract class FocusableWindow : JFrame(), WindowFocusListener { abstract val windowName: String - init - { + init { addWindowFocusListener(this) } - override fun windowGainedFocus(e: WindowEvent?) - { + override fun windowGainedFocus(e: WindowEvent?) { InjectedThings.logger.addToContext(KEY_ACTIVE_WINDOW, windowName) } override fun windowLostFocus(e: WindowEvent?) {} -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/GameSetupScreen.kt b/src/main/kotlin/dartzee/screen/GameSetupScreen.kt index 5b2cbb1f3..1d329b258 100644 --- a/src/main/kotlin/dartzee/screen/GameSetupScreen.kt +++ b/src/main/kotlin/dartzee/screen/GameSetupScreen.kt @@ -17,7 +17,6 @@ import dartzee.game.GameType import dartzee.screen.dartzee.DartzeeRuleSetupScreen import dartzee.utils.InjectedThings.gameLauncher import dartzee.utils.getFilterPanel -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.GridLayout import java.awt.event.ActionEvent @@ -28,9 +27,9 @@ import javax.swing.JRadioButton import javax.swing.JSpinner import javax.swing.SpinnerNumberModel import javax.swing.border.TitledBorder +import net.miginfocom.swing.MigLayout -class GameSetupScreen : EmbeddedScreen() -{ +class GameSetupScreen : EmbeddedScreen() { private val panelSetup = JPanel() private val panelGameType = JPanel() private val panelPlayers = JPanel() @@ -51,27 +50,32 @@ class GameSetupScreen : EmbeddedScreen() val lblGames = JLabel(" games ") val panelPointBreakdown = JPanel() - val spinners = List(MAX_PLAYERS) { ix -> JSpinner().also { it.model = SpinnerNumberModel(maxOf(0, 4 - ix), 0, 20, 1) } } + val spinners = + List(MAX_PLAYERS) { ix -> + JSpinner().also { it.model = SpinnerNumberModel(maxOf(0, 4 - ix), 0, 20, 1) } + } private val labels = List(MAX_PLAYERS) { ix -> JLabel(StringUtil.convertOrdinalToText(ix + 1)) } - init - { + init { panelSetup.layout = BorderLayout(0, 0) - panelGameType.border = TitledBorder(null, "Game Type", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelGameType.border = + TitledBorder(null, "Game Type", TitledBorder.LEADING, TitledBorder.TOP, null, null) panelSetup.add(panelGameType, BorderLayout.NORTH) panelGameType.layout = GridLayout(0, 1, 0, 0) add(panelSetup, BorderLayout.NORTH) panelGameType.add(panelGameTypeCb) panelGameTypeCb.add(gameTypeComboBox) panelGameType.add(gameParamFilterPanel) - panelPlayers.border = TitledBorder(null, "Players", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelPlayers.border = + TitledBorder(null, "Players", TitledBorder.LEADING, TitledBorder.TOP, null, null) add(panelPlayers, BorderLayout.CENTER) panelPlayers.layout = BorderLayout(0, 0) panelPlayers.add(launchPanel, BorderLayout.SOUTH) launchPanel.add(btnLaunch) panelPlayers.add(playerSelector, BorderLayout.CENTER) panelSetup.add(matchConfigPanel, BorderLayout.CENTER) - matchConfigPanel.border = TitledBorder(null, "Match Setup", TitledBorder.LEADING, TitledBorder.TOP, null, null) + matchConfigPanel.border = + TitledBorder(null, "Match Setup", TitledBorder.LEADING, TitledBorder.TOP, null, null) matchConfigPanel.layout = MigLayout("", "[80px][101px][grow][45px][][][]", "[][]") matchConfigPanel.add(rdbtnSingleGame, "flowy,cell 0 0,alignx left,aligny top") matchConfigPanel.add(rdbtnFirstTo, "flowy,cell 0 1,alignx left,aligny top") @@ -83,16 +87,19 @@ class GameSetupScreen : EmbeddedScreen() matchConfigPanel.add(lblWins, "cell 1 1") matchConfigPanel.add(lblGames, "cell 1 2,alignx left,aligny top") panelPointBreakdown.layout = MigLayout("", "[]", "[]") - labels.forEachIndexed { ix, lbl -> panelPointBreakdown.add(lbl, "flowy,cell $ix 0,alignx center") } - spinners.forEachIndexed { ix, spinner -> panelPointBreakdown.add(spinner, "cell $ix 0,alignx center") } + labels.forEachIndexed { ix, lbl -> + panelPointBreakdown.add(lbl, "flowy,cell $ix 0,alignx center") + } + spinners.forEachIndexed { ix, spinner -> + panelPointBreakdown.add(spinner, "cell $ix 0,alignx center") + } matchConfigPanel.addActionListener(this) gameTypeComboBox.addActionListener(this) btnLaunch.addActionListener(this) } - override fun initialise() - { + override fun initialise() { playerSelector.init() refreshGameParamFilterPanel() @@ -100,29 +107,20 @@ class GameSetupScreen : EmbeddedScreen() toggleComponents() } - override fun actionPerformed(arg0: ActionEvent) - { - if (arg0.source === btnLaunch) - { + override fun actionPerformed(arg0: ActionEvent) { + if (arg0.source === btnLaunch) { launchGame() - } - else if (arg0.source === gameTypeComboBox) - { + } else if (arg0.source === gameTypeComboBox) { refreshGameParamFilterPanel() - } - else if (arg0.source != btnNext && arg0.source != btnBack) - { + } else if (arg0.source != btnNext && arg0.source != btnBack) { toggleComponents() - } - else - { + } else { super.actionPerformed(arg0) } } - private fun refreshGameParamFilterPanel() - { - //Remove what's already there + private fun refreshGameParamFilterPanel() { + // Remove what's already there gameParamFilterPanel.removeActionListener(this) panelGameType.remove(gameParamFilterPanel) @@ -135,14 +133,10 @@ class GameSetupScreen : EmbeddedScreen() toggleComponents() } - private fun toggleComponents() - { - if (rdbtnSingleGame.isSelected) - { + private fun toggleComponents() { + if (rdbtnSingleGame.isSelected) { btnLaunch.text = "Launch Game" - } - else - { + } else { btnLaunch.text = "Launch Match" } @@ -152,16 +146,15 @@ class GameSetupScreen : EmbeddedScreen() spinnerGames.isVisible = rdbtnPoints.isSelected lblGames.isVisible = rdbtnPoints.isSelected - if (rdbtnPoints.isSelected) - { + if (rdbtnPoints.isSelected) { matchConfigPanel.add(panelPointBreakdown, "cell 0 3,span") - } - else - { + } else { matchConfigPanel.remove(panelPointBreakdown) } - val customDartzee = gameTypeComboBox.getGameType() == GameType.DARTZEE && gameParamFilterPanel.getGameParams() == "" + val customDartzee = + gameTypeComboBox.getGameType() == GameType.DARTZEE && + gameParamFilterPanel.getGameParams() == "" btnLaunch.isVisible = !customDartzee toggleNextVisibility(customDartzee) @@ -172,68 +165,67 @@ class GameSetupScreen : EmbeddedScreen() private fun getGameParams() = gameParamFilterPanel.getGameParams() - private fun launchGame() - { + private fun launchGame() { val selectedPlayers = playerSelector.getSelectedPlayers() val match = factoryMatch() - if (!playerSelector.valid(match != null)) - { + if (!playerSelector.valid(match != null)) { return } val rules = retrieveDartzeeRules() - val launchParams = GameLaunchParams(selectedPlayers, gameTypeComboBox.getGameType(), getGameParams(), playerSelector.pairMode(), rules) - - if (match == null) - { + val launchParams = + GameLaunchParams( + selectedPlayers, + gameTypeComboBox.getGameType(), + getGameParams(), + playerSelector.pairMode(), + rules + ) + + if (match == null) { gameLauncher.launchNewGame(launchParams) - } - else - { + } else { gameLauncher.launchNewMatch(match, launchParams) } } - private fun retrieveDartzeeRules(): List? - { - if (gameTypeComboBox.getGameType() != GameType.DARTZEE) - { + private fun retrieveDartzeeRules(): List? { + if (gameTypeComboBox.getGameType() != GameType.DARTZEE) { return null } - val dartzeeTemplate = (gameParamFilterPanel as GameParamFilterPanelDartzee).getSelectedTemplate()!! + val dartzeeTemplate = + (gameParamFilterPanel as GameParamFilterPanelDartzee).getSelectedTemplate()!! val rules = DartzeeRuleEntity().retrieveForTemplate(dartzeeTemplate.rowId) return rules.map { it.toDto() } } - private fun factoryMatch(): DartsMatchEntity? - { - return when - { + private fun factoryMatch(): DartsMatchEntity? { + return when { rdbtnFirstTo.isSelected -> DartsMatchEntity.factoryFirstTo(spinnerWins.value as Int) - rdbtnPoints.isSelected -> DartsMatchEntity.factoryPoints(spinnerGames.value as Int, getPointsJson()) + rdbtnPoints.isSelected -> + DartsMatchEntity.factoryPoints(spinnerGames.value as Int, getPointsJson()) else -> null } } - private fun getPointsJson(): String - { - return constructPointsJson(spinners[0].value as Int, - spinners[1].value as Int, - spinners[2].value as Int, - spinners[3].value as Int, - spinners[4].value as Int, - spinners[5].value as Int) + private fun getPointsJson(): String { + return constructPointsJson( + spinners[0].value as Int, + spinners[1].value as Int, + spinners[2].value as Int, + spinners[3].value as Int, + spinners[4].value as Int, + spinners[5].value as Int + ) } override fun getScreenName() = "Game Setup" - override fun nextPressed() - { + override fun nextPressed() { val selectedPlayers = playerSelector.getSelectedPlayers() val match = factoryMatch() - if (!playerSelector.valid(match != null)) - { + if (!playerSelector.valid(match != null)) { return } diff --git a/src/main/kotlin/dartzee/screen/GameplayDartboard.kt b/src/main/kotlin/dartzee/screen/GameplayDartboard.kt index 6649ccca7..bcd65525a 100644 --- a/src/main/kotlin/dartzee/screen/GameplayDartboard.kt +++ b/src/main/kotlin/dartzee/screen/GameplayDartboard.kt @@ -24,8 +24,8 @@ import javax.swing.SwingUtilities const val LAYER_DARTS = 2 const val LAYER_DODGY = 3 -class GameplayDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs()) : JLayeredPane(), IMouseListener -{ +class GameplayDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs()) : + JLayeredPane(), IMouseListener { var latestClip: Clip? = null private val dartboard = InteractiveDartboard(colourWrapper) @@ -33,22 +33,22 @@ class GameplayDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs private val listeners: MutableList = mutableListOf() private var allowInteraction = true - init - { + init { preferredSize = Dimension(500, 500) add(dartboard, Integer.valueOf(-1)) dartboard.addMouseListener(this) - addComponentListener(object : ComponentAdapter() { - override fun componentResized(evt: ComponentEvent) = resized() - }) + addComponentListener( + object : ComponentAdapter() { + override fun componentResized(evt: ComponentEvent) = resized() + } + ) SwingUtilities.invokeLater { resized() } } - private fun resized() - { + private fun resized() { dartboard.setBounds(0, 0, width, height) clearDartLabels() @@ -56,8 +56,7 @@ class GameplayDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs dartsThrown.forEach(::addDartLabel) } - fun clearDarts() - { + fun clearDarts() { dartsThrown.clear() clearDartLabels() repaint() @@ -65,13 +64,11 @@ class GameplayDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs private fun clearDartLabels() = getAllChildComponentsForType().forEach { remove(it) } - fun addDartboardListener(listener: DartboardListener) - { + fun addDartboardListener(listener: DartboardListener) { listeners.add(listener) } - fun dartThrown(pt: ComputedPoint) - { + fun dartThrown(pt: ComputedPoint) { runOnEventThreadBlocking { dartsThrown.add(pt) addDartLabel(pt) @@ -80,8 +77,7 @@ class GameplayDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs listeners.forEach { it.dartThrown(getDartForSegment(pt.segment)) } } - private fun addDartLabel(computedPt: ComputedPoint) - { + private fun addDartLabel(computedPt: ComputedPoint) { if (dartboard.isVisible && dartboard.width > 80 && dartboard.height > 80) { val lbl = DartLabel() lbl.location = dartboard.interpretPoint(computedPt) @@ -90,40 +86,34 @@ class GameplayDartboard(colourWrapper: ColourWrapper = getColourWrapperFromPrefs } } - fun refreshValidSegments(segmentStatuses: SegmentStatuses?) - { + fun refreshValidSegments(segmentStatuses: SegmentStatuses?) { dartboard.updateSegmentStatus(segmentStatuses) } - fun stopListening() - { + fun stopListening() { allowInteraction = false dartboard.stopInteraction() } - fun ensureListening() - { + fun ensureListening() { allowInteraction = true dartboard.allowInteraction() } - override fun mouseReleased(e: MouseEvent) - { - if (!suppressClickForGameWindow() && allowInteraction) - { + override fun mouseReleased(e: MouseEvent) { + if (!suppressClickForGameWindow() && allowInteraction) { dartboard.clearHover() dartThrown(dartboard.toComputedPoint(e.point)) } } - private fun suppressClickForGameWindow(): Boolean - { + + private fun suppressClickForGameWindow(): Boolean { val scrn = getParentWindow() as? AbstractDartsGameScreen ?: return false - if (scrn.haveLostFocus) - { + if (scrn.haveLostFocus) { scrn.haveLostFocus = false return true } return false } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/HumanConfigurationDialog.kt b/src/main/kotlin/dartzee/screen/HumanConfigurationDialog.kt index c54ddad64..92807212e 100644 --- a/src/main/kotlin/dartzee/screen/HumanConfigurationDialog.kt +++ b/src/main/kotlin/dartzee/screen/HumanConfigurationDialog.kt @@ -6,13 +6,13 @@ import java.awt.BorderLayout import java.awt.FlowLayout import javax.swing.JPanel -class HumanConfigurationDialog(saveCallback: (player: PlayerEntity) -> Unit, player: PlayerEntity = PlayerEntity.factoryCreate()) : - AbstractPlayerConfigurationDialog(saveCallback, player) -{ +class HumanConfigurationDialog( + saveCallback: (player: PlayerEntity) -> Unit, + player: PlayerEntity = PlayerEntity.factoryCreate() +) : AbstractPlayerConfigurationDialog(saveCallback, player) { private val panel = JPanel() - init - { + init { setSize(350, 225) isResizable = false isModal = InjectedThings.allowModalDialogs @@ -28,16 +28,14 @@ class HumanConfigurationDialog(saveCallback: (player: PlayerEntity) -> Unit, pla initFields() } - private fun initFields() - { + private fun initFields() { textFieldName.text = player.name avatar.init(player, false) avatar.readOnly = player.retrievedFromDb title = if (player.retrievedFromDb) "Amend Player" else "New Player" } - override fun savePlayer() - { + override fun savePlayer() { val name = textFieldName.text val avatarId = avatar.avatarId @@ -45,14 +43,12 @@ class HumanConfigurationDialog(saveCallback: (player: PlayerEntity) -> Unit, pla player.playerImageId = avatarId player.saveToDatabase() - //Now dispose the window + // Now dispose the window dispose() } - companion object - { - fun amendPlayer(saveCallback: (PlayerEntity) -> Unit, player: PlayerEntity) - { + companion object { + fun amendPlayer(saveCallback: (PlayerEntity) -> Unit, player: PlayerEntity) { val dlg = HumanConfigurationDialog(saveCallback, player) dlg.setLocationRelativeTo(ScreenCache.mainScreen) dlg.isVisible = true diff --git a/src/main/kotlin/dartzee/screen/MenuScreen.kt b/src/main/kotlin/dartzee/screen/MenuScreen.kt index 145a57886..1b21a023b 100644 --- a/src/main/kotlin/dartzee/screen/MenuScreen.kt +++ b/src/main/kotlin/dartzee/screen/MenuScreen.kt @@ -22,8 +22,7 @@ import javax.swing.JButton private const val BUTTON_WIDTH = 220 private const val BUTTON_HEIGHT = 80 -class MenuScreen : EmbeddedScreen() -{ +class MenuScreen : EmbeddedScreen() { private val changeLog = ChangeLog() private val dartboard = PresentationDartboard() private val btnNewGame = JButton("New Game") @@ -38,8 +37,7 @@ class MenuScreen : EmbeddedScreen() private val buttonFont = ResourceCache.BASE_FONT.deriveFont(Font.PLAIN, 18f) - init - { + init { layout = null setLocations(1000, 663) @@ -73,26 +71,25 @@ class MenuScreen : EmbeddedScreen() button.addActionListener(this) } - addComponentListener(object : ComponentAdapter() { - override fun componentResized(evt: ComponentEvent) = setLocations() - }) + addComponentListener( + object : ComponentAdapter() { + override fun componentResized(evt: ComponentEvent) = setLocations() + } + ) } override fun getScreenName() = "Menu" - override fun initialise() - { + override fun initialise() { // do nothing } - override fun postInit() - { + override fun postInit() { super.postInit() setLocations() } - private fun setLocations(width: Int = getWidth(), height: Int = getHeight()) - { + private fun setLocations(width: Int = getWidth(), height: Int = getHeight()) { val widthToSubtract = maxOf(0, (minOf(width, height) + (2 * BUTTON_WIDTH) + 50) - width) val dartboardSize = minOf(width, height) - widthToSubtract @@ -106,21 +103,44 @@ class MenuScreen : EmbeddedScreen() val btnYGap = maxOf(yGapSpace / 4, 40) val dartboardCenter = dartboardY + (dartboardSize / 2) - btnNewGame.setLocation(dartboardX - 140, dartboardCenter - (1.5 * btnYGap).toInt() - (2 * BUTTON_HEIGHT)) - btnManagePlayers.setLocation(dartboardX - BUTTON_WIDTH, dartboardCenter - (0.5 * btnYGap).toInt() - BUTTON_HEIGHT) - btnLeaderboards.setLocation(dartboardX - BUTTON_WIDTH, dartboardCenter + (0.5 * btnYGap).toInt()) - btnGameReport.setLocation(dartboardX - 140, dartboardCenter + (1.5 * btnYGap).toInt() + BUTTON_HEIGHT) - - btnPreferences.setLocation(dartboardX + dartboardSize + 140 - BUTTON_WIDTH, dartboardCenter - (1.5 * btnYGap).toInt() - (2 * BUTTON_HEIGHT)) - btnDartzeeTemplates.setLocation(dartboardX + dartboardSize, dartboardCenter - (0.5 * btnYGap).toInt() - BUTTON_HEIGHT) - btnUtilities.setLocation(dartboardX + dartboardSize, dartboardCenter + (0.5 * btnYGap).toInt()) - btnSyncSummary.setLocation(dartboardX + dartboardSize + 140 - BUTTON_WIDTH, dartboardCenter + (1.5 * btnYGap).toInt() + BUTTON_HEIGHT) + btnNewGame.setLocation( + dartboardX - 140, + dartboardCenter - (1.5 * btnYGap).toInt() - (2 * BUTTON_HEIGHT) + ) + btnManagePlayers.setLocation( + dartboardX - BUTTON_WIDTH, + dartboardCenter - (0.5 * btnYGap).toInt() - BUTTON_HEIGHT + ) + btnLeaderboards.setLocation( + dartboardX - BUTTON_WIDTH, + dartboardCenter + (0.5 * btnYGap).toInt() + ) + btnGameReport.setLocation( + dartboardX - 140, + dartboardCenter + (1.5 * btnYGap).toInt() + BUTTON_HEIGHT + ) + + btnPreferences.setLocation( + dartboardX + dartboardSize + 140 - BUTTON_WIDTH, + dartboardCenter - (1.5 * btnYGap).toInt() - (2 * BUTTON_HEIGHT) + ) + btnDartzeeTemplates.setLocation( + dartboardX + dartboardSize, + dartboardCenter - (0.5 * btnYGap).toInt() - BUTTON_HEIGHT + ) + btnUtilities.setLocation( + dartboardX + dartboardSize, + dartboardCenter + (0.5 * btnYGap).toInt() + ) + btnSyncSummary.setLocation( + dartboardX + dartboardSize + 140 - BUTTON_WIDTH, + dartboardCenter + (1.5 * btnYGap).toInt() + BUTTON_HEIGHT + ) lblVersion.setLocation(width - lblVersion.width - 5, height - lblVersion.height - 5) } - private fun linkClicked() - { + private fun linkClicked() { changeLog.run { setLocationRelativeTo(this) isVisible = true @@ -129,10 +149,8 @@ class MenuScreen : EmbeddedScreen() override fun showBackButton() = false - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnPreferences -> ScreenCache.switch() btnSyncSummary -> ScreenCache.switch() btnNewGame -> ScreenCache.switch() diff --git a/src/main/kotlin/dartzee/screen/PlayerImageDialog.kt b/src/main/kotlin/dartzee/screen/PlayerImageDialog.kt index da7b1321a..90ae4f26e 100644 --- a/src/main/kotlin/dartzee/screen/PlayerImageDialog.kt +++ b/src/main/kotlin/dartzee/screen/PlayerImageDialog.kt @@ -29,8 +29,7 @@ import javax.swing.border.TitledBorder import javax.swing.filechooser.FileNameExtensionFilter class PlayerImageDialog(private val imageSelectedCallback: (String) -> Unit) : - SimpleDialog(), IFileUploadListener -{ + SimpleDialog(), IFileUploadListener { private val tabbedPane = JTabbedPane(SwingConstants.TOP) private val panelPreset = JPanel() private val panelUpload = JPanel() @@ -41,8 +40,7 @@ class PlayerImageDialog(private val imageSelectedCallback: (String) -> Unit) : private val bgUploaded = ButtonGroup() private val scrollPaneUploaded = JScrollPane() - init - { + init { setSize(650, 400) setLocationRelativeTo(null) isModal = InjectedThings.allowModalDialogs @@ -63,7 +61,15 @@ class PlayerImageDialog(private val imageSelectedCallback: (String) -> Unit) : val panelUploadOptions = JPanel() panelUpload.add(panelUploadOptions, BorderLayout.NORTH) scrollPaneUploaded.verticalScrollBar.unitIncrement = 16 - scrollPaneUploaded.border = TitledBorder(UIManager.getBorder("TitledBorder.border"), "Previously Uploaded", TitledBorder.LEADING, TitledBorder.TOP, null, Color(0, 0, 0)) + scrollPaneUploaded.border = + TitledBorder( + UIManager.getBorder("TitledBorder.border"), + "Previously Uploaded", + TitledBorder.LEADING, + TitledBorder.TOP, + null, + Color(0, 0, 0) + ) panelUpload.add(scrollPaneUploaded, BorderLayout.CENTER) scrollPaneUploaded.setViewportView(panelPreviouslyUploaded) panelPreviouslyUploaded.layout = WrapLayout() @@ -74,15 +80,13 @@ class PlayerImageDialog(private val imageSelectedCallback: (String) -> Unit) : init() } - private fun init() - { + private fun init() { val entities = PlayerImageEntity().retrieveEntities() populatePanel(panelPresets, entities.filter { it.preset }, ButtonGroup()) - populatePanel(panelPreviouslyUploaded, entities.filter{ !it.preset }, bgUploaded) + populatePanel(panelPreviouslyUploaded, entities.filter { !it.preset }, bgUploaded) } - private fun populatePanel(panel: JPanel, entities: List, bg: ButtonGroup) - { + private fun populatePanel(panel: JPanel, entities: List, bg: ButtonGroup) { entities.forEach { img -> val radio = PlayerImageRadio(img) panel.add(radio) @@ -90,19 +94,16 @@ class PlayerImageDialog(private val imageSelectedCallback: (String) -> Unit) : } } - private fun getPlayerImageIdFromSelection(): String? - { + private fun getPlayerImageIdFromSelection(): String? { val panel = tabbedPane.selectedComponent as JPanel val radios = panel.getAllChildComponentsForType() - return radios.find { it.isSelected() } ?.playerImageId + return radios.find { it.isSelected() }?.playerImageId } - override fun okPressed() - { + override fun okPressed() { val playerImageId = getPlayerImageIdFromSelection() - if (playerImageId == null) - { + if (playerImageId == null) { DialogUtil.showErrorOLD("You must select an image.") return } @@ -111,29 +112,26 @@ class PlayerImageDialog(private val imageSelectedCallback: (String) -> Unit) : dispose() } - private fun validateFile(file: File): Boolean - { + private fun validateFile(file: File): Boolean { val imageReaders = ImageIO.getImageReadersBySuffix(file.extension) - if (!imageReaders.hasNext()) - { + if (!imageReaders.hasNext()) { DialogUtil.showErrorOLD("You must select a valid image file.") return false } val imgDim = FileUtil.getImageDim(file) ?: Dimension(Int.MAX_VALUE, Int.MAX_VALUE) - if (imgDim.getWidth() < PLAYER_IMAGE_WIDTH || imgDim.getHeight() < PLAYER_IMAGE_HEIGHT) - { - DialogUtil.showErrorOLD("The image is too small - it must be at least $PLAYER_IMAGE_WIDTH x $PLAYER_IMAGE_HEIGHT px.") + if (imgDim.getWidth() < PLAYER_IMAGE_WIDTH || imgDim.getHeight() < PLAYER_IMAGE_HEIGHT) { + DialogUtil.showErrorOLD( + "The image is too small - it must be at least $PLAYER_IMAGE_WIDTH x $PLAYER_IMAGE_HEIGHT px." + ) return false } return true } - override fun fileUploaded(file: File): Boolean - { - if (!validateFile(file)) - { + override fun fileUploaded(file: File): Boolean { + if (!validateFile(file)) { return false } diff --git a/src/main/kotlin/dartzee/screen/PlayerSelectDialog.kt b/src/main/kotlin/dartzee/screen/PlayerSelectDialog.kt index 2450d80a9..a7cc1b1e2 100644 --- a/src/main/kotlin/dartzee/screen/PlayerSelectDialog.kt +++ b/src/main/kotlin/dartzee/screen/PlayerSelectDialog.kt @@ -13,16 +13,14 @@ import java.awt.Component import java.awt.event.ActionEvent import javax.swing.ListSelectionModel -class PlayerSelectDialog(selectionMode: Int) : SimpleDialog(), IDoubleClickListener -{ +class PlayerSelectDialog(selectionMode: Int) : SimpleDialog(), IDoubleClickListener { var selectedPlayers = listOf() var playersToExclude = listOf() val panelNorth = PlayerTypeFilterPanel() val tablePlayers = ScrollTable() - init - { + init { title = "Select Player(s)" setSize(300, 300) isModal = true @@ -35,37 +33,29 @@ class PlayerSelectDialog(selectionMode: Int) : SimpleDialog(), IDoubleClickListe panelNorth.addActionListener(this) } - override fun actionPerformed(arg0: ActionEvent) - { - if (panelNorth.isEventSource(arg0)) - { + override fun actionPerformed(arg0: ActionEvent) { + if (panelNorth.isEventSource(arg0)) { buildTable() - } - else - { + } else { super.actionPerformed(arg0) } } - override fun doubleClicked(source: Component) - { + override fun doubleClicked(source: Component) { okPressed() } - fun buildTable() - { + fun buildTable() { val whereSql = panelNorth.getWhereSql() val allPlayers = PlayerEntity.retrievePlayers(whereSql) - val players = allPlayers.filter{ p -> playersToExclude.none{ it.rowId == p.rowId} } + val players = allPlayers.filter { p -> playersToExclude.none { it.rowId == p.rowId } } tablePlayers.initPlayerTableModel(players) } - override fun okPressed() - { + override fun okPressed() { selectedPlayers = tablePlayers.getSelectedPlayers() - if (selectedPlayers.isEmpty()) - { + if (selectedPlayers.isEmpty()) { DialogUtil.showErrorOLD("You must select at least one player.") return } @@ -73,10 +63,8 @@ class PlayerSelectDialog(selectionMode: Int) : SimpleDialog(), IDoubleClickListe dispose() } - companion object - { - fun selectPlayer(): PlayerEntity? - { + companion object { + fun selectPlayer(): PlayerEntity? { val players = selectPlayers(listOf(), ListSelectionModel.SINGLE_SELECTION) return if (players.isEmpty()) null else players.first() } @@ -84,8 +72,10 @@ class PlayerSelectDialog(selectionMode: Int) : SimpleDialog(), IDoubleClickListe fun selectPlayers(playersToExclude: List) = selectPlayers(playersToExclude, ListSelectionModel.MULTIPLE_INTERVAL_SELECTION) - private fun selectPlayers(playersToExclude: List, selectionMode: Int): List - { + private fun selectPlayers( + playersToExclude: List, + selectionMode: Int + ): List { val dialog = PlayerSelectDialog(selectionMode) dialog.playersToExclude = playersToExclude dialog.buildTable() diff --git a/src/main/kotlin/dartzee/screen/ScreenCache.kt b/src/main/kotlin/dartzee/screen/ScreenCache.kt index ca5c11729..934d16761 100644 --- a/src/main/kotlin/dartzee/screen/ScreenCache.kt +++ b/src/main/kotlin/dartzee/screen/ScreenCache.kt @@ -6,53 +6,47 @@ import dartzee.screen.game.AbstractDartsGameScreen import dartzee.screen.stats.player.PlayerAchievementsScreen import java.util.concurrent.ConcurrentHashMap -object ScreenCache -{ +object ScreenCache { private val hmGameIdToGameScreen = ConcurrentHashMap() - //Embedded screens + // Embedded screens val hmClassToScreen = mutableMapOf, EmbeddedScreen>() val mainScreen = DartsApp(CheatBar()) fun getDartsGameScreens() = hmGameIdToGameScreen.values.distinct() inline fun get() = - hmClassToScreen.getOrPut(K::class.java) { K::class.java.getConstructor().newInstance() } as K + hmClassToScreen.getOrPut(K::class.java) { K::class.java.getConstructor().newInstance() } + as K fun currentScreen() = mainScreen.currentScreen - inline fun switch() - { + inline fun switch() { val screen = get() switch(screen) } - fun switch(scrn: EmbeddedScreen, reInit: Boolean = true) - { + fun switch(scrn: EmbeddedScreen, reInit: Boolean = true) { mainScreen.switchScreen(scrn, reInit) } fun getDartsGameScreen(gameId: String) = hmGameIdToGameScreen[gameId] - fun addDartsGameScreen(gameId: String, scrn: AbstractDartsGameScreen) - { + fun addDartsGameScreen(gameId: String, scrn: AbstractDartsGameScreen) { hmGameIdToGameScreen[gameId] = scrn } - fun removeDartsGameScreen(scrn: AbstractDartsGameScreen) - { + fun removeDartsGameScreen(scrn: AbstractDartsGameScreen) { val keys = hmGameIdToGameScreen.filter { it.value == scrn }.map { it.key } keys.forEach { hmGameIdToGameScreen.remove(it) } } - fun emptyCache() - { + fun emptyCache() { hmClassToScreen.clear() hmGameIdToGameScreen.clear() } - fun switchToAchievementsScreen(player: PlayerEntity): PlayerAchievementsScreen - { + fun switchToAchievementsScreen(player: PlayerEntity): PlayerAchievementsScreen { val scrn = PlayerAchievementsScreen(player) hmClassToScreen[PlayerAchievementsScreen::class.java] = scrn scrn.previousScrn = currentScreen() diff --git a/src/main/kotlin/dartzee/screen/TestWindow.kt b/src/main/kotlin/dartzee/screen/TestWindow.kt index e7cbf2ae4..456962753 100644 --- a/src/main/kotlin/dartzee/screen/TestWindow.kt +++ b/src/main/kotlin/dartzee/screen/TestWindow.kt @@ -18,8 +18,7 @@ import javax.swing.JButton import javax.swing.JFrame import javax.swing.JPanel -class TestWindow : JFrame(), ActionListener, DartboardListener, IDartzeeCarouselListener -{ +class TestWindow : JFrame(), ActionListener, DartboardListener, IDartzeeCarouselListener { private val dartsThrown = mutableListOf() private val template = DartzeeTemplateEntity().retrieveEntities().first() private val rules = DartzeeRuleEntity().retrieveForTemplate(template.rowId).map { it.toDto() } @@ -31,8 +30,7 @@ class TestWindow : JFrame(), ActionListener, DartboardListener, IDartzeeCarousel private val btnChucklevision = JButton("Chucklevision") private val btnBadLuck = JButton("Bad luck") - init - { + init { contentPane.layout = BorderLayout(0, 0) size = Dimension(1000, 800) preferredSize = Dimension(1000, 800) @@ -68,16 +66,14 @@ class TestWindow : JFrame(), ActionListener, DartboardListener, IDartzeeCarousel } } - private fun clearDarts() - { + private fun clearDarts() { dartboard.clearDarts() dartsThrown.clear() carousel.update(emptyList(), dartsThrown, 100) dartboard.refreshValidSegments(carousel.getSegmentStatus()) } - override fun dartThrown(dart: Dart) - { + override fun dartThrown(dart: Dart) { dartsThrown.add(dart) if (dartsThrown.size <= 3) { @@ -86,12 +82,11 @@ class TestWindow : JFrame(), ActionListener, DartboardListener, IDartzeeCarousel } } - override fun hoverChanged(segmentStatuses: SegmentStatuses) - { - dartboard.refreshValidSegments(segmentStatuses) + override fun hoverChanged(segmentStatuses: SegmentStatuses) { + dartboard.refreshValidSegments(segmentStatuses) } override fun tilePressed(dartzeeRoundResult: DartzeeRoundResult) { // do nothing } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/UtilitiesScreen.kt b/src/main/kotlin/dartzee/screen/UtilitiesScreen.kt index 28bd7a3fc..356d695eb 100644 --- a/src/main/kotlin/dartzee/screen/UtilitiesScreen.kt +++ b/src/main/kotlin/dartzee/screen/UtilitiesScreen.kt @@ -1,24 +1,23 @@ package dartzee.screen -import dartzee.`object`.DartsClient import dartzee.core.util.dumpThreadStacks import dartzee.core.util.getAllChildComponentsForType import dartzee.core.util.runInOtherThread import dartzee.db.sanity.DatabaseSanityCheck +import dartzee.`object`.DartsClient import dartzee.utils.DARTS_VERSION_NUMBER import dartzee.utils.DartsDatabaseUtil import dartzee.utils.DevUtilities import dartzee.utils.InjectedThings -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Font import java.awt.event.ActionEvent import javax.swing.AbstractButton import javax.swing.JButton import javax.swing.JPanel +import net.miginfocom.swing.MigLayout -class UtilitiesScreen : EmbeddedScreen() -{ +class UtilitiesScreen : EmbeddedScreen() { private val btnDeleteGame = JButton("Delete Game") private val btnCreateBackup = JButton("Create backup") private val btnRestoreFromBackup = JButton("Restore from backup") @@ -28,8 +27,7 @@ class UtilitiesScreen : EmbeddedScreen() private val btnThreadStacks = JButton("Thread Stacks") private val btnAchievementConversion = JButton("Run Achievement Conversion") - init - { + init { val panel = JPanel() add(panel, BorderLayout.CENTER) panel.layout = MigLayout("", "[grow]", "[][][][][][][][][][][]") @@ -43,38 +41,36 @@ class UtilitiesScreen : EmbeddedScreen() panel.add(btnAchievementConversion, "cell 0 11,alignx center") val buttons = panel.getAllChildComponentsForType() - for (button in buttons) - { + for (button in buttons) { button.font = Font("Tahoma", Font.PLAIN, 18) button.addActionListener(this) } } - override fun initialise() - { - //Nothing to do, it's just a placeholder for some buttons + override fun initialise() { + // Nothing to do, it's just a placeholder for some buttons } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnDeleteGame -> DevUtilities.purgeGame() btnCreateBackup -> DartsDatabaseUtil.backupCurrentDatabase() btnRestoreFromBackup -> DartsDatabaseUtil.restoreDatabase() btnPerformDatabaseCheck -> DatabaseSanityCheck.runSanityCheck() - btnCheckForUpdates -> runInOtherThread { DartsClient.updateManager.checkForUpdates(DARTS_VERSION_NUMBER) } - btnViewLogs -> {val loggingDialog = InjectedThings.loggingConsole - loggingDialog.isVisible = true - loggingDialog.toFront()} + btnCheckForUpdates -> + runInOtherThread { DartsClient.updateManager.checkForUpdates(DARTS_VERSION_NUMBER) } + btnViewLogs -> { + val loggingDialog = InjectedThings.loggingConsole + loggingDialog.isVisible = true + loggingDialog.toFront() + } btnThreadStacks -> dumpThreadStacks() btnAchievementConversion -> runAchievementConversion() else -> super.actionPerformed(arg0) } } - private fun runAchievementConversion() - { + private fun runAchievementConversion() { val dlg = AchievementConversionDialog() dlg.setLocationRelativeTo(ScreenCache.mainScreen) dlg.isVisible = true diff --git a/src/main/kotlin/dartzee/screen/ai/AIConfigurationDialog.kt b/src/main/kotlin/dartzee/screen/ai/AIConfigurationDialog.kt index 4a598b443..c12f56f60 100644 --- a/src/main/kotlin/dartzee/screen/ai/AIConfigurationDialog.kt +++ b/src/main/kotlin/dartzee/screen/ai/AIConfigurationDialog.kt @@ -23,9 +23,10 @@ import javax.swing.border.EmptyBorder import javax.swing.border.SoftBevelBorder import javax.swing.border.TitledBorder -class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: PlayerEntity = PlayerEntity.factoryCreate()) : - AbstractPlayerConfigurationDialog(saveCallback, player) -{ +class AIConfigurationDialog( + saveCallback: (PlayerEntity) -> Unit, + player: PlayerEntity = PlayerEntity.factoryCreate() +) : AbstractPlayerConfigurationDialog(saveCallback, player) { private val panelScreen = JPanel() private val panelNorth = JPanel() private val panelName = JPanel() @@ -49,8 +50,7 @@ class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: Player private val lblTreble = JLabel("Treble %") val textFieldTreblePercent = JTextField() - init - { + init { title = "Configure AI" setSize(1100, 720) isResizable = false @@ -58,7 +58,8 @@ class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: Player contentPane.add(panelSouth, BorderLayout.EAST) panelSouth.border = null panelSouth.layout = BorderLayout(0, 0) - panelCalculateStats.border = TitledBorder(null, "Statistics", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelCalculateStats.border = + TitledBorder(null, "Statistics", TitledBorder.LEADING, TitledBorder.TOP, null, null) panelSouth.add(panelCalculateStats, BorderLayout.NORTH) panelCalculateStats.layout = BorderLayout(0, 0) @@ -113,14 +114,15 @@ class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: Player panelNorth.add(panelAvatar, BorderLayout.WEST) panelAvatar.layout = BorderLayout(0, 0) panelAvatar.add(avatar, BorderLayout.NORTH) - tabbedPaneGameSpecifics.border = TitledBorder(null, "Strategy", TitledBorder.LEADING, TitledBorder.TOP, null, null) + tabbedPaneGameSpecifics.border = + TitledBorder(null, "Strategy", TitledBorder.LEADING, TitledBorder.TOP, null, null) panelScreen.add(tabbedPaneGameSpecifics, BorderLayout.CENTER) tabbedPaneGameSpecifics.addTab("X01", panelX01Config) tabbedPaneGameSpecifics.addTab("Golf", panelGolfConfig) tabbedPaneGameSpecifics.addTab("Dartzee", panelDartzeeConfig) - //Listeners + // Listeners btnCalculate.addActionListener(this) btnRunSimulation.addActionListener(this) @@ -129,21 +131,17 @@ class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: Player tabbedPane.isEnabled = false } - private fun initFields() - { + private fun initFields() { avatar.init(player, false) - if (!player.retrievedFromDb) - { + if (!player.retrievedFromDb) { avatar.readOnly = false panelX01Config.reset() panelGolfConfig.reset() panelDartzeeConfig.reset() panelAIConfig.reset() - } - else - { + } else { avatar.readOnly = true val name = player.name @@ -158,8 +156,7 @@ class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: Player } } - private fun factoryModelFromPanels(): DartsAiModel - { + private fun factoryModelFromPanels(): DartsAiModel { var model = panelAIConfig.initialiseModel() model = panelX01Config.populateModel(model) model = panelGolfConfig.populateModel(model) @@ -168,41 +165,37 @@ class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: Player return model } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnCalculate -> calculateStats() btnRunSimulation -> runSimulation() else -> super.actionPerformed(arg0) } } - private fun runSimulation() - { + private fun runSimulation() { val model = factoryModelFromPanels() - //If the player hasn't actually been created yet, then we need to instantiate a PlayerEntity just to hold stuff like the name + // If the player hasn't actually been created yet, then we need to instantiate a + // PlayerEntity just to hold stuff like the name player.name = textFieldName.text val dlg = AISimulationSetupDialog(player, model, true) dlg.isVisible = true } - override fun savePlayer() - { + override fun savePlayer() { val name = textFieldName.text player.name = name player.strategy = factoryModelFromPanels().toJson() player.playerImageId = avatar.avatarId player.saveToDatabase() - //Now dispose the window + // Now dispose the window dispose() } - private fun calculateStats() - { + private fun calculateStats() { val model = factoryModelFromPanels() val dartboard = scatterTab.dartboard @@ -227,10 +220,8 @@ class AIConfigurationDialog(saveCallback: (PlayerEntity) -> Unit, player: Player densityTab.populate(simulationWrapper.hmPointToCount, model) } - companion object - { - fun amendPlayer(saveCallback: (PlayerEntity) -> Unit, player: PlayerEntity) - { + companion object { + fun amendPlayer(saveCallback: (PlayerEntity) -> Unit, player: PlayerEntity) { val dialog = AIConfigurationDialog(saveCallback, player) dialog.setLocationRelativeTo(ScreenCache.mainScreen) dialog.isVisible = true diff --git a/src/main/kotlin/dartzee/screen/ai/AIConfigurationGolfDartPanel.kt b/src/main/kotlin/dartzee/screen/ai/AIConfigurationGolfDartPanel.kt index b17658036..bcc46348f 100644 --- a/src/main/kotlin/dartzee/screen/ai/AIConfigurationGolfDartPanel.kt +++ b/src/main/kotlin/dartzee/screen/ai/AIConfigurationGolfDartPanel.kt @@ -15,16 +15,15 @@ import javax.swing.border.TitledBorder import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener -class AIConfigurationGolfDartPanel(private val dartNo: Int) : JPanel(), ChangeListener -{ +class AIConfigurationGolfDartPanel(private val dartNo: Int) : JPanel(), ChangeListener { private val comboBox = JComboBox>() private val panelStoppingPoint = JPanel() private val spinner = JSpinner() private val lblOrBelow = JLabel("or better") - init - { - border = TitledBorder(null, "Dart #$dartNo", TitledBorder.LEADING, TitledBorder.TOP, null, null) + init { + border = + TitledBorder(null, "Dart #$dartNo", TitledBorder.LEADING, TitledBorder.TOP, null, null) val lblAimAt = JLabel("Aim at") add(lblAimAt) @@ -45,9 +44,7 @@ class AIConfigurationGolfDartPanel(private val dartNo: Int) : JPanel(), ChangeLi setComponentVisibility() } - - private fun setModels() - { + private fun setModels() { comboBox.addItem(ComboBoxItem(SegmentType.DOUBLE, "Double (1)")) comboBox.addItem(ComboBoxItem(SegmentType.TREBLE, "Treble (2)")) comboBox.addItem(ComboBoxItem(SegmentType.INNER_SINGLE, "Inner Single (3)")) @@ -56,44 +53,41 @@ class AIConfigurationGolfDartPanel(private val dartNo: Int) : JPanel(), ChangeLi spinner.model = SpinnerNumberModel(2, 1, 4, 1) } - private fun setComponentVisibility() - { + private fun setComponentVisibility() { panelStoppingPoint.isVisible = dartNo < 3 val value = spinner.value as Int lblOrBelow.isEnabled = value > 1 } - fun initialiseFromModel(model: DartsAiModel) - { - //Combo box selection + fun initialiseFromModel(model: DartsAiModel) { + // Combo box selection val segmentType = model.getSegmentTypeForDartNo(dartNo) val item = comboBox.items().find { it.hiddenData == segmentType } item?.let { comboBox.selectedItem = it } - if (panelStoppingPoint.isVisible) - { + if (panelStoppingPoint.isVisible) { val stopThreshold = model.getStopThresholdForDartNo(dartNo) spinner.value = stopThreshold } } - fun populateMaps(hmDartNoToSegmentType: MutableMap, hmDartNoToStopThreshold: MutableMap) - { + fun populateMaps( + hmDartNoToSegmentType: MutableMap, + hmDartNoToStopThreshold: MutableMap + ) { val item = comboBox.selectedItemTyped() val segmentType = item.hiddenData hmDartNoToSegmentType[dartNo] = segmentType - if (panelStoppingPoint.isVisible) - { + if (panelStoppingPoint.isVisible) { val stopThreshold = spinner.value as Int hmDartNoToStopThreshold[dartNo] = stopThreshold } } - override fun stateChanged(arg0: ChangeEvent) - { + override fun stateChanged(arg0: ChangeEvent) { setComponentVisibility() } } diff --git a/src/main/kotlin/dartzee/screen/ai/AIConfigurationPanelNormalDistribution.kt b/src/main/kotlin/dartzee/screen/ai/AIConfigurationPanelNormalDistribution.kt index 6bb7dd497..25dd632ca 100644 --- a/src/main/kotlin/dartzee/screen/ai/AIConfigurationPanelNormalDistribution.kt +++ b/src/main/kotlin/dartzee/screen/ai/AIConfigurationPanelNormalDistribution.kt @@ -2,7 +2,6 @@ package dartzee.screen.ai import dartzee.ai.DartsAiModel import dartzee.core.bean.NumberField -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ActionEvent @@ -13,9 +12,9 @@ import javax.swing.JPanel import javax.swing.JSlider import javax.swing.border.EmptyBorder import javax.swing.border.TitledBorder +import net.miginfocom.swing.MigLayout -class AIConfigurationPanelNormalDistribution : AbstractAIConfigurationSubPanel(), ActionListener -{ +class AIConfigurationPanelNormalDistribution : AbstractAIConfigurationSubPanel(), ActionListener { private val panelNorth = JPanel() private val lblStandardDeviation = JLabel("Standard Deviation") val nfStandardDeviation = NumberField(1) @@ -26,10 +25,10 @@ class AIConfigurationPanelNormalDistribution : AbstractAIConfigurationSubPanel() private val lblConsistent = JLabel("Max radius") private val slider = JSlider() - init - { + init { layout = BorderLayout(0, 0) - panelNorth.border = TitledBorder(null, "Variables", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelNorth.border = + TitledBorder(null, "Variables", TitledBorder.LEADING, TitledBorder.TOP, null, null) add(panelNorth, BorderLayout.CENTER) panelNorth.layout = MigLayout("", "[125px,grow][100px,grow]", "[25px][][][][grow]") lblStandardDeviation.border = EmptyBorder(0, 5, 0, 0) @@ -54,50 +53,46 @@ class AIConfigurationPanelNormalDistribution : AbstractAIConfigurationSubPanel() cbCenterBias.addActionListener(this) } - fun initialiseModel(): DartsAiModel - { + fun initialiseModel(): DartsAiModel { val model = DartsAiModel.new() val sd = nfStandardDeviation.getDouble() - val sdDoubles = if (cbStandardDeviationDoubles.isSelected) nfStandardDeviationDoubles.getDouble() else null + val sdDoubles = + if (cbStandardDeviationDoubles.isSelected) nfStandardDeviationDoubles.getDouble() + else null val sdCentral = if (cbCenterBias.isSelected) nfCentralBias.getDouble() else null - return model.copy(standardDeviation = sd, + return model.copy( + standardDeviation = sd, standardDeviationDoubles = sdDoubles, standardDeviationCentral = sdCentral, - maxRadius = slider.value) + maxRadius = slider.value + ) } override fun populateModel(model: DartsAiModel) = model - override fun initialiseFromModel(model: DartsAiModel) - { + override fun initialiseFromModel(model: DartsAiModel) { val standardDeviation = model.standardDeviation nfStandardDeviation.value = standardDeviation val standardDeviationDoubles = model.standardDeviationDoubles - if (standardDeviationDoubles != null) - { + if (standardDeviationDoubles != null) { cbStandardDeviationDoubles.isSelected = true nfStandardDeviationDoubles.isEnabled = true nfStandardDeviationDoubles.value = standardDeviationDoubles - } - else - { + } else { cbStandardDeviationDoubles.isSelected = false nfStandardDeviationDoubles.isEnabled = false nfStandardDeviationDoubles.value = 50 } val sdCentral = model.standardDeviationCentral - if (sdCentral != null) - { + if (sdCentral != null) { cbCenterBias.isSelected = true nfCentralBias.isEnabled = true nfCentralBias.value = sdCentral - } - else - { + } else { cbCenterBias.isSelected = false nfCentralBias.isEnabled = false nfCentralBias.value = 50 @@ -106,13 +101,11 @@ class AIConfigurationPanelNormalDistribution : AbstractAIConfigurationSubPanel() slider.value = model.maxRadius } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { - cbStandardDeviationDoubles -> nfStandardDeviationDoubles.isEnabled = cbStandardDeviationDoubles.isSelected + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { + cbStandardDeviationDoubles -> + nfStandardDeviationDoubles.isEnabled = cbStandardDeviationDoubles.isSelected cbCenterBias -> nfCentralBias.isEnabled = cbCenterBias.isSelected } } - -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelDartzee.kt b/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelDartzee.kt index 89f59054c..742059742 100644 --- a/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelDartzee.kt +++ b/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelDartzee.kt @@ -5,28 +5,25 @@ import dartzee.ai.DartzeePlayStyle import dartzee.core.bean.RadioButtonPanel import javax.swing.JRadioButton -class AIConfigurationSubPanelDartzee : AbstractAIConfigurationSubPanel() -{ +class AIConfigurationSubPanelDartzee : AbstractAIConfigurationSubPanel() { private val radioButtonPanel = RadioButtonPanel() private val rdbtnCautious = JRadioButton("Cautious") private val rdbtnAggressive = JRadioButton("Aggressive") - init - { + init { add(radioButtonPanel) radioButtonPanel.add(rdbtnCautious) radioButtonPanel.add(rdbtnAggressive) } - override fun populateModel(model: DartsAiModel): DartsAiModel - { - val dartzeePlayStyle = if (rdbtnCautious.isSelected) DartzeePlayStyle.CAUTIOUS else DartzeePlayStyle.AGGRESSIVE + override fun populateModel(model: DartsAiModel): DartsAiModel { + val dartzeePlayStyle = + if (rdbtnCautious.isSelected) DartzeePlayStyle.CAUTIOUS else DartzeePlayStyle.AGGRESSIVE return model.copy(dartzeePlayStyle = dartzeePlayStyle) } - override fun initialiseFromModel(model: DartsAiModel) - { + override fun initialiseFromModel(model: DartsAiModel) { rdbtnCautious.isSelected = model.dartzeePlayStyle == DartzeePlayStyle.CAUTIOUS rdbtnAggressive.isSelected = model.dartzeePlayStyle == DartzeePlayStyle.AGGRESSIVE } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelGolf.kt b/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelGolf.kt index 78182d2d3..705bbd99f 100644 --- a/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelGolf.kt +++ b/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelGolf.kt @@ -1,17 +1,15 @@ package dartzee.screen.ai -import dartzee.`object`.SegmentType import dartzee.ai.DartsAiModel +import dartzee.`object`.SegmentType import net.miginfocom.swing.MigLayout -class AIConfigurationSubPanelGolf : AbstractAIConfigurationSubPanel() -{ +class AIConfigurationSubPanelGolf : AbstractAIConfigurationSubPanel() { private val panelDartOne = AIConfigurationGolfDartPanel(1) private val panelDartTwo = AIConfigurationGolfDartPanel(2) private val panelDartThree = AIConfigurationGolfDartPanel(3) - init - { + init { layout = MigLayout("", "[grow]", "[grow][grow][grow]") add(panelDartOne, "cell 0 0,grow") @@ -19,20 +17,21 @@ class AIConfigurationSubPanelGolf : AbstractAIConfigurationSubPanel() add(panelDartThree, "cell 0 2,grow") } - override fun populateModel(model: DartsAiModel): DartsAiModel - { - val hmDartNoToSegmentType = mutableMapOf() + override fun populateModel(model: DartsAiModel): DartsAiModel { + val hmDartNoToSegmentType = mutableMapOf() val hmDartNoToStopThreshold = mutableMapOf() panelDartOne.populateMaps(hmDartNoToSegmentType, hmDartNoToStopThreshold) panelDartTwo.populateMaps(hmDartNoToSegmentType, hmDartNoToStopThreshold) panelDartThree.populateMaps(hmDartNoToSegmentType, hmDartNoToStopThreshold) - return model.copy(hmDartNoToSegmentType = hmDartNoToSegmentType.toMap(), hmDartNoToStopThreshold = hmDartNoToStopThreshold.toMap()) + return model.copy( + hmDartNoToSegmentType = hmDartNoToSegmentType.toMap(), + hmDartNoToStopThreshold = hmDartNoToStopThreshold.toMap() + ) } - override fun initialiseFromModel(model: DartsAiModel) - { + override fun initialiseFromModel(model: DartsAiModel) { panelDartOne.initialiseFromModel(model) panelDartTwo.initialiseFromModel(model) panelDartThree.initialiseFromModel(model) diff --git a/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelX01.kt b/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelX01.kt index 8be69cf8b..70b309799 100644 --- a/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelX01.kt +++ b/src/main/kotlin/dartzee/screen/ai/AIConfigurationSubPanelX01.kt @@ -11,8 +11,7 @@ import javax.swing.JLabel import javax.swing.JSpinner import javax.swing.SpinnerNumberModel -class AIConfigurationSubPanelX01 : AbstractAIConfigurationSubPanel(), ActionListener -{ +class AIConfigurationSubPanelX01 : AbstractAIConfigurationSubPanel(), ActionListener { val hmScoreToDart = mutableMapOf() val spinnerScoringDart = SpinnerSingleSelector() @@ -21,8 +20,7 @@ class AIConfigurationSubPanelX01 : AbstractAIConfigurationSubPanel(), ActionList val lblWhenScoreLess = JLabel("when score less than") val spinnerMercyThreshold = JSpinner() - init - { + init { border = null layout = null val lblScoringDart = JLabel("Scoring Dart") @@ -40,20 +38,21 @@ class AIConfigurationSubPanelX01 : AbstractAIConfigurationSubPanel(), ActionList lblWhenScoreLess.setBounds(140, 55, 118, 24) add(lblWhenScoreLess) - //Listeners + // Listeners btnConfigureSetupDarts.addActionListener(this) chckbxMercyRule.addActionListener(this) } - override fun populateModel(model: DartsAiModel): DartsAiModel - { - return model.copy(hmScoreToDart = hmScoreToDart, - scoringDart = spinnerScoringDart.value as Int, - mercyThreshold = if (chckbxMercyRule.isSelected) spinnerMercyThreshold.value as Int else null) + override fun populateModel(model: DartsAiModel): DartsAiModel { + return model.copy( + hmScoreToDart = hmScoreToDart, + scoringDart = spinnerScoringDart.value as Int, + mercyThreshold = + if (chckbxMercyRule.isSelected) spinnerMercyThreshold.value as Int else null + ) } - override fun initialiseFromModel(model: DartsAiModel) - { + override fun initialiseFromModel(model: DartsAiModel) { spinnerScoringDart.value = model.scoringDart val mercyThreshold = model.mercyThreshold @@ -68,10 +67,8 @@ class AIConfigurationSubPanelX01 : AbstractAIConfigurationSubPanel(), ActionList hmScoreToDart.putAll(model.hmScoreToDart) } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnConfigureSetupDarts -> AISetupConfigurationDialog.configureSetups(hmScoreToDart) chckbxMercyRule -> { val mercyRule = chckbxMercyRule.isSelected diff --git a/src/main/kotlin/dartzee/screen/ai/AISetupConfigurationDialog.kt b/src/main/kotlin/dartzee/screen/ai/AISetupConfigurationDialog.kt index 4de538d59..05be1f2d2 100644 --- a/src/main/kotlin/dartzee/screen/ai/AISetupConfigurationDialog.kt +++ b/src/main/kotlin/dartzee/screen/ai/AISetupConfigurationDialog.kt @@ -19,19 +19,20 @@ import javax.swing.text.DefaultStyledDocument /** * Dialog to specify setup darts that override defaults. Some examples: - * - On 48, the default is to aim for 8 (D20). But you might want to override this to aim for 16 (D16). - * - On 10, the default is to aim for D5. But if an AI is bad, you might want to override this to aim for 2. + * - On 48, the default is to aim for 8 (D20). But you might want to override this to aim for 16 + * (D16). + * - On 10, the default is to aim for D5. But if an AI is bad, you might want to override this to + * aim for 2. * - On 35, the default is to aim for 3 (D16). But you might want to aim for 19 (D8). */ -class AISetupConfigurationDialog(private val hmScoreToSingle: MutableMap): SimpleDialog() -{ +class AISetupConfigurationDialog(private val hmScoreToSingle: MutableMap) : + SimpleDialog() { private val info = JTextPane() private val tableScores = ScrollTable() private val btnAddRule = JButton("Add Rule...") private val btnRemove = JButton("Remove") - init - { + init { title = "Setup Configuration" setSize(500, 500) isResizable = false @@ -61,8 +62,7 @@ class AISetupConfigurationDialog(private val hmScoreToSingle: MutableMap) - { + private fun buildTable(hmRules: Map) { val allValues = hmRules.entries val tm = TableUtil.DefaultModel() @@ -119,10 +118,8 @@ class AISetupConfigurationDialog(private val hmScoreToSingle: MutableMap { val hmCurrentRules = mutableMapOf() fillHashMapFromTable(hmCurrentRules) @@ -135,11 +132,9 @@ class AISetupConfigurationDialog(private val hmScoreToSingle: MutableMap) - { + private fun fillHashMapFromTable(hm: MutableMap) { val tm = tableScores.model val rows = tm.rowCount - for (i in 0 until rows) - { + for (i in 0 until rows) { val score = tm.getValueAt(i, 0) as Int val drt = tm.getValueAt(i, 1) as AimDart @@ -173,10 +165,8 @@ class AISetupConfigurationDialog(private val hmScoreToSingle: MutableMap) - { + companion object { + fun configureSetups(hmScoreToSingle: MutableMap) { val dlg = AISetupConfigurationDialog(hmScoreToSingle) dlg.setLocationRelativeTo(ScreenCache.mainScreen) dlg.isVisible = true diff --git a/src/main/kotlin/dartzee/screen/ai/AISetupRuleFactory.kt b/src/main/kotlin/dartzee/screen/ai/AISetupRuleFactory.kt index 506ec14a3..d90979078 100644 --- a/src/main/kotlin/dartzee/screen/ai/AISetupRuleFactory.kt +++ b/src/main/kotlin/dartzee/screen/ai/AISetupRuleFactory.kt @@ -2,15 +2,12 @@ package dartzee.screen.ai import dartzee.ai.AimDart -interface IAISetupRuleFactory -{ +interface IAISetupRuleFactory { fun newSetupRule(currentRules: MutableMap) } -class AISetupRuleFactory: IAISetupRuleFactory -{ - override fun newSetupRule(currentRules: MutableMap) - { +class AISetupRuleFactory : IAISetupRuleFactory { + override fun newSetupRule(currentRules: MutableMap) { NewSetupRuleDialog.addNewSetupRule(currentRules) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/ai/AISimulationSetupDialog.kt b/src/main/kotlin/dartzee/screen/ai/AISimulationSetupDialog.kt index 01acb867c..9f06c5e44 100644 --- a/src/main/kotlin/dartzee/screen/ai/AISimulationSetupDialog.kt +++ b/src/main/kotlin/dartzee/screen/ai/AISimulationSetupDialog.kt @@ -11,17 +11,18 @@ import dartzee.db.PlayerEntity import dartzee.screen.ScreenCache import dartzee.utils.InjectedThings import dartzee.utils.InjectedThings.simulationRunner -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.FlowLayout import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JRadioButton +import net.miginfocom.swing.MigLayout -class AISimulationSetupDialog(private val player: PlayerEntity, - private val model: DartsAiModel, - private val modal: Boolean = false) : SimpleDialog() -{ +class AISimulationSetupDialog( + private val player: PlayerEntity, + private val model: DartsAiModel, + private val modal: Boolean = false +) : SimpleDialog() { private val panelCenter = JPanel() private val lblGameMode = JLabel("Game Mode") private val panelSimulationType = RadioButtonPanel() @@ -30,8 +31,7 @@ class AISimulationSetupDialog(private val player: PlayerEntity, private val lblNumberOfGames = JLabel("Number of games") private val nfNumberOfGames = NumberField(100, 100000) - init - { + init { title = "Simulation Options" setSize(400, 160) setLocationRelativeTo(ScreenCache.mainScreen) @@ -51,17 +51,14 @@ class AISimulationSetupDialog(private val player: PlayerEntity, nfNumberOfGames.value = 1000 } - override fun okPressed() - { + override fun okPressed() { val sim = factorySimulationForSelection() simulationRunner.runSimulation(sim, nfNumberOfGames.getNumber(), modal) dispose() } - private fun factorySimulationForSelection(): AbstractDartsSimulation - { - return when (panelSimulationType.selection) - { + private fun factorySimulationForSelection(): AbstractDartsSimulation { + return when (panelSimulationType.selection) { rdbtn501 -> DartsSimulationX01(player, model) else -> DartsSimulationGolf(player, model) } diff --git a/src/main/kotlin/dartzee/screen/ai/AbstractAIConfigurationSubPanel.kt b/src/main/kotlin/dartzee/screen/ai/AbstractAIConfigurationSubPanel.kt index 5c160f23d..cbc4a36d4 100644 --- a/src/main/kotlin/dartzee/screen/ai/AbstractAIConfigurationSubPanel.kt +++ b/src/main/kotlin/dartzee/screen/ai/AbstractAIConfigurationSubPanel.kt @@ -3,13 +3,12 @@ package dartzee.screen.ai import dartzee.ai.DartsAiModel import javax.swing.JPanel -abstract class AbstractAIConfigurationSubPanel : JPanel() -{ +abstract class AbstractAIConfigurationSubPanel : JPanel() { abstract fun populateModel(model: DartsAiModel): DartsAiModel + abstract fun initialiseFromModel(model: DartsAiModel) - fun reset() - { + fun reset() { initialiseFromModel(DartsAiModel.new()) } } diff --git a/src/main/kotlin/dartzee/screen/ai/AbstractVisualisationPanel.kt b/src/main/kotlin/dartzee/screen/ai/AbstractVisualisationPanel.kt index a3c899062..d57c530cb 100644 --- a/src/main/kotlin/dartzee/screen/ai/AbstractVisualisationPanel.kt +++ b/src/main/kotlin/dartzee/screen/ai/AbstractVisualisationPanel.kt @@ -10,9 +10,8 @@ import javax.swing.ImageIcon import javax.swing.JLabel import javax.swing.JPanel -abstract class AbstractVisualisationPanel : JPanel() -{ - //Cached stuff +abstract class AbstractVisualisationPanel : JPanel() { + // Cached stuff private var paintedKey = false val dartboard = PresentationDartboard(factoryColourWrapper()) @@ -21,8 +20,7 @@ abstract class AbstractVisualisationPanel : JPanel() protected val overlay = JLabel() protected val panel = JPanel() - init - { + init { layout = null overlay.setBounds(0, 0, 500, 500) dartboard.setBounds(0, 0, 500, 500) @@ -34,30 +32,27 @@ abstract class AbstractVisualisationPanel : JPanel() reset() } - /** - * Abstract fns - */ + /** Abstract fns */ abstract fun showVisualisation(hmPointToCount: Map, model: DartsAiModel) + abstract fun paintKey() + protected abstract fun factoryColourWrapper(): ColourWrapper - fun reset() - { + fun reset() { overlayImg = BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB) overlay.icon = ImageIcon(overlayImg) overlay.background = DartsColour.TRANSPARENT } - fun populate(hmPointToCount: Map, model: DartsAiModel) - { + fun populate(hmPointToCount: Map, model: DartsAiModel) { showVisualisation(hmPointToCount, model) - if (!paintedKey) - { + if (!paintedKey) { paintKey() paintedKey = true } isEnabled = true } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/ai/NewSetupRuleDialog.kt b/src/main/kotlin/dartzee/screen/ai/NewSetupRuleDialog.kt index fc54c5a9d..ad5c06b01 100644 --- a/src/main/kotlin/dartzee/screen/ai/NewSetupRuleDialog.kt +++ b/src/main/kotlin/dartzee/screen/ai/NewSetupRuleDialog.kt @@ -10,15 +10,14 @@ import dartzee.core.util.DialogUtil import dartzee.`object`.Dart import dartzee.screen.ScreenCache import dartzee.utils.isBust -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ActionEvent import javax.swing.JLabel import javax.swing.JRadioButton +import net.miginfocom.swing.MigLayout -class NewSetupRuleDialog(private val hmScoreToDart: MutableMap) : SimpleDialog() -{ +class NewSetupRuleDialog(private val hmScoreToDart: MutableMap) : SimpleDialog() { val panel = RadioButtonPanel() private val lblScore = JLabel("Score") val nfScore = NumberField(4, 501) @@ -28,8 +27,7 @@ class NewSetupRuleDialog(private val hmScoreToDart: MutableMap) : val rdbtnTreble = JRadioButton("Treble") val spinner = SpinnerSingleSelector() - init - { + init { title = "Add Rule" setSize(200, 200) isResizable = false @@ -55,43 +53,35 @@ class NewSetupRuleDialog(private val hmScoreToDart: MutableMap) : pack() } - private fun getDartFromSelections(): AimDart - { + private fun getDartFromSelections(): AimDart { val multiplier = getMultiplier() val value = spinner.value as Int return AimDart(value, multiplier) } - private fun getMultiplier(): Int - { - return when (panel.selection) - { + + private fun getMultiplier(): Int { + return when (panel.selection) { rdbtnSingle -> 1 rdbtnDouble -> 2 else -> 3 } } - override fun actionPerformed(arg0: ActionEvent) - { - if (panel.isEventSource(arg0)) - { + override fun actionPerformed(arg0: ActionEvent) { + if (panel.isEventSource(arg0)) { panel.remove(spinner) val multiplier = getMultiplier() panel.add(spinner, "cell 2 $multiplier") pack() - } - else - { + } else { super.actionPerformed(arg0) } } - override fun okPressed() - { - if (valid()) - { + override fun okPressed() { + if (valid()) { val score = nfScore.getNumber() val drt = getDartFromSelections() @@ -101,36 +91,32 @@ class NewSetupRuleDialog(private val hmScoreToDart: MutableMap) : } } - fun valid(): Boolean - { + fun valid(): Boolean { val score = nfScore.getNumber() - if (score == -1) - { + if (score == -1) { DialogUtil.showErrorOLD("You must enter a score for this rule to apply to.") return false } val drt = getDartFromSelections() - if (drt.score == 25 && drt.multiplier == 3) - { + if (drt.score == 25 && drt.multiplier == 3) { DialogUtil.showErrorOLD("Treble 25 is not a valid dart!") return false } - if (isBust(score, Dart(drt.score, drt.multiplier))) - { + if (isBust(score, Dart(drt.score, drt.multiplier))) { DialogUtil.showErrorOLD("This target would bust the player") return false } - //If we're specifying a rule for under 60, validate whether what we're setting up is - //already the default - if (score <= 60) - { + // If we're specifying a rule for under 60, validate whether what we're setting up is + // already the default + if (score <= 60) { val defaultDart = getDefaultDartToAimAt(score) - if (defaultDart == drt) - { - DialogUtil.showErrorOLD("The selected dart is already the default for this starting score.") + if (defaultDart == drt) { + DialogUtil.showErrorOLD( + "The selected dart is already the default for this starting score." + ) return false } } @@ -138,10 +124,8 @@ class NewSetupRuleDialog(private val hmScoreToDart: MutableMap) : return true } - companion object - { - fun addNewSetupRule(hmScoreToDart: MutableMap) - { + companion object { + fun addNewSetupRule(hmScoreToDart: MutableMap) { val dlg = NewSetupRuleDialog(hmScoreToDart) dlg.setLocationRelativeTo(ScreenCache.mainScreen) dlg.isVisible = true diff --git a/src/main/kotlin/dartzee/screen/ai/VisualisationPanelDensity.kt b/src/main/kotlin/dartzee/screen/ai/VisualisationPanelDensity.kt index 2d4c9e11d..6881a72b3 100644 --- a/src/main/kotlin/dartzee/screen/ai/VisualisationPanelDensity.kt +++ b/src/main/kotlin/dartzee/screen/ai/VisualisationPanelDensity.kt @@ -14,13 +14,11 @@ import javax.swing.ImageIcon import javax.swing.JLabel import javax.swing.SwingConstants -class VisualisationPanelDensity: AbstractVisualisationPanel() -{ +class VisualisationPanelDensity : AbstractVisualisationPanel() { private val keyImg = BufferedImage(100, 500, BufferedImage.TYPE_INT_ARGB) val panelKey = JLabel() - init - { + init { add(dartboard) add(overlay) @@ -31,8 +29,7 @@ class VisualisationPanelDensity: AbstractVisualisationPanel() override fun factoryColourWrapper() = WIREFRAME_COLOUR_WRAPPER - override fun showVisualisation(hmPointToCount: Map, model: DartsAiModel) - { + override fun showVisualisation(hmPointToCount: Map, model: DartsAiModel) { val modelPt = model.calculateScoringPoint() val centerPt = dartboard.interpretPoint(modelPt) @@ -47,16 +44,15 @@ class VisualisationPanelDensity: AbstractVisualisationPanel() repaint() } - override fun paintKey() - { + override fun paintKey() { keyImg.paint { val probability: Double = it.y.toDouble() / height.toDouble() getColorForProbability(probability) } - //Add labels at 10% increments + // Add labels at 10% increments val lblXPosition = panel.width / 2 - LABEL_WIDTH / 2 - val yPositions = (1 until 500).filter { it % (500/10) == 0 } + val yPositions = (1 until 500).filter { it % (500 / 10) == 0 } yPositions.forEach { y -> val probInt = 10 * y / 50 val label = JLabel("- $probInt% -") @@ -73,17 +69,15 @@ class VisualisationPanelDensity: AbstractVisualisationPanel() repaint() } - private fun getColorForProbability(probability: Double?): Color - { + private fun getColorForProbability(probability: Double?): Color { probability ?: return Color.BLACK val hue = (probability / 1.2).toFloat() return Color.getHSBColor(hue, 1f, 1f) } - companion object - { + companion object { private const val LABEL_WIDTH = 60 private const val LABEL_HEIGHT = 40 } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/ai/VisualisationPanelScatter.kt b/src/main/kotlin/dartzee/screen/ai/VisualisationPanelScatter.kt index 770b53f93..0dc21debf 100644 --- a/src/main/kotlin/dartzee/screen/ai/VisualisationPanelScatter.kt +++ b/src/main/kotlin/dartzee/screen/ai/VisualisationPanelScatter.kt @@ -12,10 +12,8 @@ import javax.swing.JLabel import javax.swing.SwingConstants import javax.swing.border.LineBorder -class VisualisationPanelScatter : AbstractVisualisationPanel() -{ - init - { +class VisualisationPanelScatter : AbstractVisualisationPanel() { + init { add(overlay) add(dartboard) @@ -45,38 +43,41 @@ class VisualisationPanelScatter : AbstractVisualisationPanel() panel.add(lblRed) } - override fun factoryColourWrapper(): ColourWrapper - { + override fun factoryColourWrapper(): ColourWrapper { val evenSingle = DartsColour.DARTBOARD_LIGHT_GREY val evenDouble = DartsColour.DARTBOARD_LIGHTER_GREY val evenTreble = DartsColour.DARTBOARD_LIGHTER_GREY val oddSingle = DartsColour.DARTBOARD_WHITE val oddDouble = DartsColour.DARTBOARD_LIGHTEST_GREY val oddTreble = DartsColour.DARTBOARD_LIGHTEST_GREY - val wrapper = ColourWrapper( - evenSingle, evenDouble, evenTreble, - oddSingle, oddDouble, oddTreble, evenDouble, oddDouble - ) + val wrapper = + ColourWrapper( + evenSingle, + evenDouble, + evenTreble, + oddSingle, + oddDouble, + oddTreble, + evenDouble, + oddDouble + ) wrapper.missedBoardColour = Color.WHITE wrapper.outerDartboardColour = Color.WHITE return wrapper } - override fun showVisualisation(hmPointToCount: Map, model: DartsAiModel) - { + override fun showVisualisation(hmPointToCount: Map, model: DartsAiModel) { overlayImg.paint { getColorForPoint(it, hmPointToCount) } repaint() } - private fun getColorForPoint(pt: Point, hmPointToCount: Map): Color - { + + private fun getColorForPoint(pt: Point, hmPointToCount: Map): Color { val count = hmPointToCount[pt] ?: return DartsColour.TRANSPARENT return getColourForNoOfHits(count) } - private fun getColourForNoOfHits(count: Int): Color - { - return when - { + private fun getColourForNoOfHits(count: Int): Color { + return when { count >= 20 -> Color.yellow count >= 5 -> Color.orange else -> Color.red @@ -84,4 +85,4 @@ class VisualisationPanelScatter : AbstractVisualisationPanel() } override fun paintKey() {} -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartboardSegmentSelectDialog.kt b/src/main/kotlin/dartzee/screen/dartzee/DartboardSegmentSelectDialog.kt index 5465ebed1..0e3e4a1d3 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartboardSegmentSelectDialog.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartboardSegmentSelectDialog.kt @@ -16,9 +16,8 @@ import java.awt.event.MouseEvent import javax.swing.JButton import javax.swing.JPanel -class DartboardSegmentSelectDialog(private val initialSegments: Set): - SimpleDialog(), IMouseListener -{ +class DartboardSegmentSelectDialog(private val initialSegments: Set) : + SimpleDialog(), IMouseListener { private val selectedSegments = mutableSetOf() private var lastDraggedSegment: DartboardSegment? = null @@ -26,8 +25,7 @@ class DartboardSegmentSelectDialog(private val initialSegments: Set selectAll() btnSelectNone -> selectNone() else -> super.actionPerformed(arg0) @@ -72,57 +68,49 @@ class DartboardSegmentSelectDialog(private val initialSegments: Set) = segments.toList().forEach(::toggleSegment) + private fun toggleAll(segments: Collection) = + segments.toList().forEach(::toggleSegment) - private fun toggleSegment(segment: DartboardSegment) - { + private fun toggleSegment(segment: DartboardSegment) { lastDraggedSegment = segment - if (segment.isMiss()) - { + if (segment.isMiss()) { return } - if (selectedSegments.contains(segment)) - { + if (selectedSegments.contains(segment)) { selectedSegments.remove(segment) dartboard.revertOverriddenSegmentColour(segment) - } - else - { + } else { selectedSegments.add(segment) val col = DEFAULT_COLOUR_WRAPPER.getColour(segment) dartboard.overrideSegmentColour(segment, col) } } - override fun okPressed() - { + override fun okPressed() { dispose() } - override fun cancelPressed() - { + override fun cancelPressed() { selectedSegments.clear() selectedSegments.addAll(initialSegments) dispose() } - override fun mouseDragged(e: MouseEvent) - { + override fun mouseDragged(e: MouseEvent) { val segment = dartboard.getSegmentForPoint(e.point) - if (segment == lastDraggedSegment) - { + if (segment == lastDraggedSegment) { return } toggleSegment(segment) } - override fun mouseReleased(e: MouseEvent) - { + override fun mouseReleased(e: MouseEvent) { val segment = dartboard.getSegmentForPoint(e.point) toggleSegment(segment) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleCreationDialog.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleCreationDialog.kt index 0a1c13b7a..f0cb9701a 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleCreationDialog.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleCreationDialog.kt @@ -10,7 +10,6 @@ import dartzee.dartzee.DartzeeRandomiser import dartzee.dartzee.DartzeeRuleDto import dartzee.db.MAX_RULE_NAME import dartzee.screen.ScreenCache -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Dimension import java.awt.event.ActionEvent @@ -25,9 +24,11 @@ import javax.swing.SwingUtilities import javax.swing.border.TitledBorder import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener +import net.miginfocom.swing.MigLayout -class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerificationPanel = DartzeeRuleVerificationPanel()): SimpleDialog(), ChangeListener -{ +class DartzeeRuleCreationDialog( + private val verificationPanel: DartzeeRuleVerificationPanel = DartzeeRuleVerificationPanel() +) : SimpleDialog(), ChangeListener { var dartzeeRule: DartzeeRuleDto? = null val lblDifficulty = JLabel() @@ -54,8 +55,7 @@ class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerifi private val cbRuleName = JCheckBox("Custom rule name") val tfRuleName = JTextField() - init - { + init { title = "Add Dartzee Rule" setSize(900, 640) setLocationRelativeTo(ScreenCache.mainScreen) @@ -95,7 +95,7 @@ class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerifi panelAllowMisses.layout = MigLayout("", "[]", "[]") panelAllowMisses.add(cbAllowMisses, "cell 0 0") - panelRuleDescription.layout = BorderLayout(0,0) + panelRuleDescription.layout = BorderLayout(0, 0) panelRuleDescription.border = TitledBorder("") panelRuleDescription.add(tfDescription, BorderLayout.CENTER) panelRuleDescription.add(btnRandom, BorderLayout.EAST) @@ -124,31 +124,24 @@ class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerifi updateComponents() } - fun amendRule(rule: DartzeeRuleDto) - { + fun amendRule(rule: DartzeeRuleDto) { title = "Amend Dartzee Rule" this.dartzeeRule = rule populate(rule) } - fun populate(rule: DartzeeRuleDto) - { + fun populate(rule: DartzeeRuleDto) { cbRuleName.isSelected = rule.ruleName != null tfRuleName.text = rule.ruleName.orEmpty() - if (rule.dart1Rule == null) - { + if (rule.dart1Rule == null) { rdbtnNoDarts.isSelected = true - } - else if (rule.dart2Rule == null) - { + } else if (rule.dart2Rule == null) { rdbtnAtLeastOne.isSelected = true targetSelector.populate(rule.dart1Rule) - } - else - { + } else { rdbtnAllDarts.isSelected = true cbInOrder.isSelected = rule.inOrder @@ -165,31 +158,22 @@ class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerifi repaint() } - override fun stateChanged(e: ChangeEvent?) - { + override fun stateChanged(e: ChangeEvent?) { updateComponents() } - override fun actionPerformed(arg0: ActionEvent) - { - if (arg0.source == btnRandom) - { + override fun actionPerformed(arg0: ActionEvent) { + if (arg0.source == btnRandom) { populate(DartzeeRandomiser.generateRandomRule()) - } - else if (arg0.source !in listOf(btnOk, btnCancel)) - { + } else if (arg0.source !in listOf(btnOk, btnCancel)) { updateComponents() - } - else - { + } else { super.actionPerformed(arg0) } } - override fun okPressed() - { - if (!valid()) - { + override fun okPressed() { + if (!valid()) { return } @@ -197,8 +181,7 @@ class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerifi val calculationResult = rule.runStrengthCalculation() val combinations = calculationResult.validCombinations - if (combinations == 0) - { + if (combinations == 0) { DialogUtil.showErrorOLD("This rule is impossible!") return } @@ -208,77 +191,74 @@ class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerifi dispose() } - fun constructRuleFromComponents(): DartzeeRuleDto - { + fun constructRuleFromComponents(): DartzeeRuleDto { val totalRule = if (aggregateSelector.isEnabled) aggregateSelector.getSelection() else null val ruleName = if (cbRuleName.isSelected) tfRuleName.text else null - return if (rdbtnAllDarts.isSelected) - { - DartzeeRuleDto(dartOneSelector.getSelection(), - dartTwoSelector.getSelection(), dartThreeSelector.getSelection(), totalRule, cbInOrder.isSelected, cbAllowMisses.isSelected, ruleName) - } - else - { + return if (rdbtnAllDarts.isSelected) { + DartzeeRuleDto( + dartOneSelector.getSelection(), + dartTwoSelector.getSelection(), + dartThreeSelector.getSelection(), + totalRule, + cbInOrder.isSelected, + cbAllowMisses.isSelected, + ruleName + ) + } else { val dart1Rule = if (rdbtnAtLeastOne.isSelected) targetSelector.getSelection() else null - DartzeeRuleDto(dart1Rule, null, null, totalRule, false, cbAllowMisses.isSelected, ruleName) + DartzeeRuleDto( + dart1Rule, + null, + null, + totalRule, + false, + cbAllowMisses.isSelected, + ruleName + ) } } - private fun valid(): Boolean - { - if (cbRuleName.isSelected) - { + private fun valid(): Boolean { + if (cbRuleName.isSelected) { val ruleName = tfRuleName.text - if (ruleName.isBlank()) - { + if (ruleName.isBlank()) { DialogUtil.showErrorOLD("You cannot have an empty rule name.") return false } - if (ruleName.length > MAX_RULE_NAME) - { + if (ruleName.length > MAX_RULE_NAME) { DialogUtil.showErrorOLD("Rule name cannot exceed $MAX_RULE_NAME characters.") return false } } - return if (rdbtnAtLeastOne.isSelected) - { + return if (rdbtnAtLeastOne.isSelected) { targetSelector.valid() - } - else - { + } else { dartOneSelector.valid() && dartTwoSelector.valid() && dartThreeSelector.valid() } } - private fun updateComponents() - { + private fun updateComponents() { tfRuleName.isEnabled = cbRuleName.isSelected - if (rdbtnAllDarts.isSelected) - { + if (rdbtnAllDarts.isSelected) { panelDarts.remove(targetSelector) panelDarts.add(dartOneSelector, "cell 0 1") panelDarts.add(dartTwoSelector, "cell 0 2") panelDarts.add(dartThreeSelector, "cell 0 3") panelDarts.add(cbInOrder, "cell 0 4") - } - else - { + } else { panelDarts.remove(dartOneSelector) panelDarts.remove(dartTwoSelector) panelDarts.remove(dartThreeSelector) panelDarts.remove(cbInOrder) - if (rdbtnAtLeastOne.isSelected) - { + if (rdbtnAtLeastOne.isSelected) { panelDarts.add(targetSelector, "cell 0 1") - } - else - { + } else { panelDarts.remove(targetSelector) } } @@ -300,4 +280,4 @@ class DartzeeRuleCreationDialog(private val verificationPanel: DartzeeRuleVerifi verificationPanel.updateRule(rule) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleRenderer.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleRenderer.kt index f1442c84b..a0a2a6a93 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleRenderer.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleRenderer.kt @@ -4,22 +4,18 @@ import dartzee.core.bean.AbstractTableRenderer import dartzee.dartzee.DartzeeRuleDto import java.awt.Font -class DartzeeRuleRenderer(private val colNo: Int) : AbstractTableRenderer() -{ - override fun getReplacementValue(value: DartzeeRuleDto): Any - { +class DartzeeRuleRenderer(private val colNo: Int) : AbstractTableRenderer() { + override fun getReplacementValue(value: DartzeeRuleDto): Any { val ruleDesc = value.ruleName ?: value.generateRuleDescription() return if (colNo == 0) ruleDesc else value.getDifficultyDesc() } - override fun setCellColours(typedValue: DartzeeRuleDto?, isSelected: Boolean) - { + override fun setCellColours(typedValue: DartzeeRuleDto?, isSelected: Boolean) { foreground = typedValue?.calculationResult?.getForeground() background = typedValue?.calculationResult?.getBackground() } - override fun setFontsAndAlignment() - { + override fun setFontsAndAlignment() { font = Font(font.name, Font.PLAIN, 20) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupPanel.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupPanel.kt index 968a0b592..b7f2df5cf 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupPanel.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupPanel.kt @@ -16,16 +16,14 @@ import javax.swing.JButton import javax.swing.JPanel import javax.swing.border.EmptyBorder -class DartzeeRuleSetupPanel: JPanel(), ActionListener, RowSelectionListener -{ +class DartzeeRuleSetupPanel : JPanel(), ActionListener, RowSelectionListener { val tableRules = ScrollTableOrdered(3) val btnAddRule = JButton() val btnAmendRule = JButton() val btnRemoveRule = JButton() val btnCalculateOrder = JButton() - init - { + init { layout = BorderLayout(0, 0) add(tableRules, BorderLayout.CENTER) @@ -67,8 +65,7 @@ class DartzeeRuleSetupPanel: JPanel(), ActionListener, RowSelectionListener btnCalculateOrder.addActionListener(this) } - private fun setTableModel() - { + private fun setTableModel() { val tm = TableUtil.DefaultModel() tm.addColumn("Rule") tm.addColumn("Difficulty") @@ -81,10 +78,8 @@ class DartzeeRuleSetupPanel: JPanel(), ActionListener, RowSelectionListener selectionChanged(tableRules) } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnAddRule -> addRule() btnAmendRule -> amendRule() btnRemoveRule -> removeRule() @@ -92,16 +87,14 @@ class DartzeeRuleSetupPanel: JPanel(), ActionListener, RowSelectionListener } } - private fun addRule() - { + private fun addRule() { val rule = InjectedThings.dartzeeRuleFactory.newRule() - if (rule != null) - { + if (rule != null) { addRuleToTable(rule) } } - private fun amendRule() - { + + private fun amendRule() { val rowIndex = tableRules.selectedModelRow val tm = tableRules.model @@ -116,32 +109,30 @@ class DartzeeRuleSetupPanel: JPanel(), ActionListener, RowSelectionListener tableRules.repaint() } - private fun removeRule() - { + + private fun removeRule() { val tm = tableRules.model tm.removeRow(tableRules.selectedModelRow) tableRules.repaint() } - private fun sortRulesByDifficulty() - { + + private fun sortRulesByDifficulty() { tableRules.reorderRows { -(it[0]!! as DartzeeRuleDto).getDifficulty() } } - fun addRulesToTable(rules: List) - { + fun addRulesToTable(rules: List) { rules.forEach { addRuleToTable(it) } } - private fun addRuleToTable(rule: DartzeeRuleDto) - { + + private fun addRuleToTable(rule: DartzeeRuleDto) { tableRules.addRow(arrayOf(rule, rule)) } - override fun selectionChanged(src: ScrollTable) - { + override fun selectionChanged(src: ScrollTable) { btnAmendRule.isEnabled = src.selectedModelRow != -1 btnRemoveRule.isEnabled = src.selectedModelRow != -1 } fun getRules() = tableRules.getAllRows().map { it[0]!! as DartzeeRuleDto } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupScreen.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupScreen.kt index 30a9da969..adae88b86 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupScreen.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleSetupScreen.kt @@ -13,34 +13,32 @@ import java.awt.BorderLayout class DartzeeRuleSetupScreen( private val match: DartsMatchEntity?, private val players: List, - private val pairMode: Boolean) : EmbeddedScreen() -{ + private val pairMode: Boolean +) : EmbeddedScreen() { private val dartzeeRulePanel = DartzeeRuleSetupPanel() - init - { + init { add(dartzeeRulePanel, BorderLayout.CENTER) } override fun initialise() {} - override fun nextPressed() - { + override fun nextPressed() { val dtos = dartzeeRulePanel.getRules() val launchParams = GameLaunchParams(players, GameType.DARTZEE, "", pairMode, dtos) - if (match != null) - { + if (match != null) { gameLauncher.launchNewMatch(match, launchParams) - } - else - { + } else { gameLauncher.launchNewGame(launchParams) } } override fun getScreenName() = "Dartzee - Custom Setup" + override fun getBackTarget() = ScreenCache.get() + override fun showNextButton() = true + override fun getNextText() = if (match != null) "Launch Match" else "Launch Game" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleVerificationPanel.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleVerificationPanel.kt index 548c95c42..8c3e2e1b8 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleVerificationPanel.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeRuleVerificationPanel.kt @@ -22,9 +22,7 @@ import javax.swing.JPanel import javax.swing.JTextField import javax.swing.border.EmptyBorder - -class DartzeeRuleVerificationPanel: JPanel(), DartboardListener, ActionListener -{ +class DartzeeRuleVerificationPanel : JPanel(), DartboardListener, ActionListener { val dartboard: GameplayDartboard = GameplayDartboard(DEFAULT_COLOUR_WRAPPER) val dartsThrown = mutableListOf() private var dartzeeRule = DartzeeRuleDto(null, null, null, null, false, false, null) @@ -34,8 +32,7 @@ class DartzeeRuleVerificationPanel: JPanel(), DartboardListener, ActionListener val lblCombinations = JLabel() val tfResult = JTextField() - init - { + init { layout = BorderLayout(0, 0) preferredSize = Dimension(400, 400) @@ -66,42 +63,34 @@ class DartzeeRuleVerificationPanel: JPanel(), DartboardListener, ActionListener btnReset.addActionListener(this) } - fun updateRule(rule: DartzeeRuleDto) - { + fun updateRule(rule: DartzeeRuleDto) { this.dartzeeRule = rule repaintDartboard() } - override fun dartThrown(dart: Dart) - { + override fun dartThrown(dart: Dart) { dartsThrown.add(dart) - if (dartsThrown.size == 3) - { + if (dartsThrown.size == 3) { dartboard.stopListening() } repaintDartboard() } - private fun repaintDartboard() - { + private fun repaintDartboard() { val calculationResult = runCalculationIfNecessary() val failed = calculationResult.validCombinations == 0 - if (dartsThrown.size < 3) - { + if (dartsThrown.size < 3) { lblCombinations.text = calculationResult.getCombinationsDesc() dartboard.refreshValidSegments(calculationResult.getSegmentStatus()) - } - else - { + } else { lblCombinations.text = "" } - when - { + when { failed -> setAllColours(Color.RED) dartsThrown.size == 3 -> setAllColours(Color.GREEN) else -> setAllColours(Color.WHITE, DartsColour.COLOUR_PASTEL_BLUE) @@ -109,33 +98,29 @@ class DartzeeRuleVerificationPanel: JPanel(), DartboardListener, ActionListener updateDartDesc(failed) } - private fun updateDartDesc(failed: Boolean) - { + + private fun updateDartDesc(failed: Boolean) { val dartStrs = dartsThrown.map { it.toString() }.toMutableList() while (dartStrs.size < 3) { dartStrs.add("?") } val dartsStr = dartStrs.joinToString(" → ") - val total = if (failed) "Total: N/A" else "Total: ${dartzeeRule.getSuccessTotal(dartsThrown)}" + val total = + if (failed) "Total: N/A" else "Total: ${dartzeeRule.getSuccessTotal(dartsThrown)}" tfResult.text = "$dartsStr, $total" } - private fun runCalculationIfNecessary(): DartzeeRuleCalculationResult - { - return if (dartsThrown.isEmpty()) - { + private fun runCalculationIfNecessary(): DartzeeRuleCalculationResult { + return if (dartsThrown.isEmpty()) { dartzeeRule.calculationResult!! - } - else - { + } else { dartzeeCalculator.getValidSegments(dartzeeRule, dartsThrown) } } - private fun setAllColours(fg: Color, bg: Color = DartsColour.getDarkenedColour(fg)) - { + private fun setAllColours(fg: Color, bg: Color = DartsColour.getDarkenedColour(fg)) { tfResult.foreground = fg lblCombinations.foreground = fg @@ -147,10 +132,8 @@ class DartzeeRuleVerificationPanel: JPanel(), DartboardListener, ActionListener lblCombinations.background = bg } - override fun actionPerformed(e: ActionEvent?) - { - if (dartsThrown.isNotEmpty()) - { + override fun actionPerformed(e: ActionEvent?) { + if (dartsThrown.isNotEmpty()) { dartsThrown.clear() dartboard.clearDarts() dartboard.ensureListening() @@ -158,4 +141,4 @@ class DartzeeRuleVerificationPanel: JPanel(), DartboardListener, ActionListener repaintDartboard() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateDialog.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateDialog.kt index 0cfabcbcf..10b0cf3c4 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateDialog.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateDialog.kt @@ -15,14 +15,12 @@ import javax.swing.JPanel import javax.swing.JTextField import javax.swing.border.EmptyBorder -class DartzeeTemplateDialog(private val confirmedCallback: () -> Unit) : SimpleDialog() -{ +class DartzeeTemplateDialog(private val confirmedCallback: () -> Unit) : SimpleDialog() { private val namePanel = JPanel() private val tfName = JTextField() val rulePanel = DartzeeRuleSetupPanel() - init - { + init { title = "New Dartzee Template" size = Dimension(800, 600) isModal = InjectedThings.allowModalDialogs @@ -38,10 +36,8 @@ class DartzeeTemplateDialog(private val confirmedCallback: () -> Unit) : SimpleD namePanel.add(tfName) } - override fun okPressed() - { - if (!valid()) - { + override fun okPressed() { + if (!valid()) { return } @@ -50,17 +46,14 @@ class DartzeeTemplateDialog(private val confirmedCallback: () -> Unit) : SimpleD dispose() } - private fun valid(): Boolean - { - if (tfName.text.isEmpty()) - { + private fun valid(): Boolean { + if (tfName.text.isEmpty()) { DialogUtil.showErrorOLD("You must enter a name.") tfName.requestFocus() return false } - if (rulePanel.getRules().size < 2) - { + if (rulePanel.getRules().size < 2) { DialogUtil.showErrorOLD("You must create at least 2 rules.") return false } @@ -68,9 +61,7 @@ class DartzeeTemplateDialog(private val confirmedCallback: () -> Unit) : SimpleD return true } - - fun copy(templateToCopy: DartzeeTemplateEntity) - { + fun copy(templateToCopy: DartzeeTemplateEntity) { tfName.text = "${templateToCopy.name} - Copy" val rules = DartzeeRuleEntity().retrieveForTemplate(templateToCopy.rowId) @@ -79,14 +70,12 @@ class DartzeeTemplateDialog(private val confirmedCallback: () -> Unit) : SimpleD rulePanel.addRulesToTable(dtos) } - companion object - { - fun createTemplate(callback: () -> Unit, templateToCopy: DartzeeTemplateEntity? = null) - { + companion object { + fun createTemplate(callback: () -> Unit, templateToCopy: DartzeeTemplateEntity? = null) { val dlg = DartzeeTemplateDialog(callback) templateToCopy?.let { dlg.copy(it) } dlg.setLocationRelativeTo(ScreenCache.mainScreen) dlg.isVisible = true } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateRuleRenderer.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateRuleRenderer.kt index f832ce251..f23b635ba 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateRuleRenderer.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateRuleRenderer.kt @@ -8,10 +8,8 @@ import java.awt.image.BufferedImage import javax.swing.ImageIcon import javax.swing.SwingConstants -class DartzeeTemplateRuleRenderer : AbstractTableRenderer>() -{ - override fun getReplacementValue(value: List): Any - { +class DartzeeTemplateRuleRenderer : AbstractTableRenderer>() { + override fun getReplacementValue(value: List): Any { val width = (20 * value.size) + (5 * (value.size)) val bi = BufferedImage(width + 2, 22, BufferedImage.TYPE_INT_ARGB) @@ -20,11 +18,11 @@ class DartzeeTemplateRuleRenderer : AbstractTableRenderer>( value.forEachIndexed { ix, dto -> val x = (ix * 25) + 5 - //Fill + // Fill g.color = dto.calculationResult!!.getForeground() g.fill(Rectangle(x, 0, 20, 20)) - //Border + // Border g.color = Color.BLACK g.drawRect(x, 0, 20, 20) } @@ -39,4 +37,4 @@ class DartzeeTemplateRuleRenderer : AbstractTableRenderer>( } override fun toString() = "" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateSetupScreen.kt b/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateSetupScreen.kt index 14ccceffc..7599c9c2d 100644 --- a/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateSetupScreen.kt +++ b/src/main/kotlin/dartzee/screen/dartzee/DartzeeTemplateSetupScreen.kt @@ -11,7 +11,6 @@ import dartzee.game.GameType import dartzee.screen.EmbeddedScreen import dartzee.utils.InjectedThings.mainDatabase import dartzee.utils.deleteDartzeeTemplate -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Dimension import java.awt.Font @@ -20,9 +19,9 @@ import java.awt.event.KeyEvent import javax.swing.ImageIcon import javax.swing.JButton import javax.swing.JPanel +import net.miginfocom.swing.MigLayout -class DartzeeTemplateSetupScreen: EmbeddedScreen(), RowSelectionListener -{ +class DartzeeTemplateSetupScreen : EmbeddedScreen(), RowSelectionListener { private val scrollTable = ScrollTable() private val panelEast = JPanel() private val btnAdd = JButton() @@ -30,8 +29,7 @@ class DartzeeTemplateSetupScreen: EmbeddedScreen(), RowSelectionListener private val btnCopy = JButton() private val btnDelete = JButton() - init - { + init { add(scrollTable) add(panelEast, BorderLayout.EAST) @@ -73,8 +71,7 @@ class DartzeeTemplateSetupScreen: EmbeddedScreen(), RowSelectionListener btnDelete.addActionListener(this) } - override fun initialise() - { + override fun initialise() { val tm = TableUtil.DefaultModel() tm.addColumn("Template") @@ -93,17 +90,19 @@ class DartzeeTemplateSetupScreen: EmbeddedScreen(), RowSelectionListener selectionChanged(scrollTable) } - private fun populateTable() - { + private fun populateTable() { val cols = DartzeeTemplateEntity().getColumnsForSelectStatement("t") - val allRules = DartzeeRuleEntity().retrieveEntities("EntityName = '${EntityName.DartzeeTemplate}'") + val allRules = + DartzeeRuleEntity().retrieveEntities("EntityName = '${EntityName.DartzeeTemplate}'") val hmTemplateIdToRules = allRules.groupBy { it.entityId } val sb = StringBuilder() sb.append(" SELECT $cols, COUNT(g.RowId) AS GameCount") sb.append(" FROM DartzeeTemplate t") - sb.append(" LEFT OUTER JOIN Game g ON (g.GameType = '${GameType.DARTZEE}' AND g.GameParams = t.RowId)") + sb.append( + " LEFT OUTER JOIN Game g ON (g.GameType = '${GameType.DARTZEE}' AND g.GameParams = t.RowId)" + ) sb.append(" GROUP BY $cols") mainDatabase.executeQuery(sb).use { rs -> @@ -117,60 +116,55 @@ class DartzeeTemplateSetupScreen: EmbeddedScreen(), RowSelectionListener } } } - private fun addTemplateToTable(template: DartzeeTemplateEntity, rules: List, gameCount: Int) - { + + private fun addTemplateToTable( + template: DartzeeTemplateEntity, + rules: List, + gameCount: Int + ) { val dtos = rules.sortedBy { it.ordinal }.map { it.toDto() } - + scrollTable.addRow(arrayOf(template, dtos, gameCount)) } - private fun addTemplate() - { + private fun addTemplate() { DartzeeTemplateDialog.createTemplate(::initialise) } - private fun renameTemplate() - { + private fun renameTemplate() { val selection = getSelectedTemplate() val result = DialogUtil.showInput("Rename Template", "Name", null, selection.name) ?: return - if (result.isNotEmpty()) - { + if (result.isNotEmpty()) { selection.name = result selection.saveToDatabase() scrollTable.repaint() } } - private fun copySelectedTemplate() - { + private fun copySelectedTemplate() { val selection = getSelectedTemplate() DartzeeTemplateDialog.createTemplate(::initialise, selection) } - private fun deleteTemplate() - { + private fun deleteTemplate() { val selection = getSelectedTemplate() val gameCount = scrollTable.model.getValueAt(scrollTable.selectedModelRow, 2) as Int val deleted = deleteDartzeeTemplate(selection, gameCount) - if (deleted) - { + if (deleted) { initialise() } } - private fun getSelectedTemplate(): DartzeeTemplateEntity - { + private fun getSelectedTemplate(): DartzeeTemplateEntity { val rowIndex = scrollTable.selectedModelRow return scrollTable.model.getValueAt(rowIndex, 0) as DartzeeTemplateEntity } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnAdd -> addTemplate() btnRename -> renameTemplate() btnCopy -> copySelectedTemplate() @@ -179,12 +173,11 @@ class DartzeeTemplateSetupScreen: EmbeddedScreen(), RowSelectionListener } } - override fun selectionChanged(src: ScrollTable) - { + override fun selectionChanged(src: ScrollTable) { btnRename.isEnabled = src.selectedModelRow != -1 btnCopy.isEnabled = src.selectedModelRow != -1 btnDelete.isEnabled = src.selectedModelRow != -1 } override fun getScreenName() = "Dartzee Templates" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/AbstractDartsGameScreen.kt b/src/main/kotlin/dartzee/screen/game/AbstractDartsGameScreen.kt index fb3835a77..3142a9dbb 100644 --- a/src/main/kotlin/dartzee/screen/game/AbstractDartsGameScreen.kt +++ b/src/main/kotlin/dartzee/screen/game/AbstractDartsGameScreen.kt @@ -8,58 +8,56 @@ import java.awt.event.WindowEvent import java.awt.event.WindowListener import javax.swing.WindowConstants -abstract class AbstractDartsGameScreen : FocusableWindow(), WindowListener -{ +abstract class AbstractDartsGameScreen : FocusableWindow(), WindowListener { var haveLostFocus = false protected var shouldPack = true - init - { + init { defaultCloseOperation = WindowConstants.DISPOSE_ON_CLOSE addWindowListener(this) } - /** - * Abstract fns - */ - abstract fun achievementUnlocked(gameId: String, playerId: String, achievement: AbstractAchievement) + /** Abstract fns */ + abstract fun achievementUnlocked( + gameId: String, + playerId: String, + achievement: AbstractAchievement + ) + abstract fun fireAppearancePreferencesChanged() - /** - * Hook for when a GameId has been clicked and the screen is already visible. - */ - open fun displayGame(gameId: String) - { + /** Hook for when a GameId has been clicked and the screen is already visible. */ + open fun displayGame(gameId: String) { toFront() state = Frame.NORMAL } - open fun startNextGameIfNecessary() - { - //Do nothing by default + + open fun startNextGameIfNecessary() { + // Do nothing by default } - fun packIfNecessary() - { - if (shouldPack) - { + + fun packIfNecessary() { + if (shouldPack) { pack() } } - /** - * WindowListener - */ - override fun windowClosed(arg0: WindowEvent) - { + /** WindowListener */ + override fun windowClosed(arg0: WindowEvent) { ScreenCache.removeDartsGameScreen(this) } - override fun windowDeactivated(arg0: WindowEvent) - { + + override fun windowDeactivated(arg0: WindowEvent) { haveLostFocus = true } - override fun windowActivated(arg0: WindowEvent){} - override fun windowClosing(arg0: WindowEvent){} - override fun windowDeiconified(arg0: WindowEvent){} - override fun windowIconified(arg0: WindowEvent){} - override fun windowOpened(arg0: WindowEvent){} -} \ No newline at end of file + override fun windowActivated(arg0: WindowEvent) {} + + override fun windowClosing(arg0: WindowEvent) {} + + override fun windowDeiconified(arg0: WindowEvent) {} + + override fun windowIconified(arg0: WindowEvent) {} + + override fun windowOpened(arg0: WindowEvent) {} +} diff --git a/src/main/kotlin/dartzee/screen/game/AbstractGameStatisticsPanel.kt b/src/main/kotlin/dartzee/screen/game/AbstractGameStatisticsPanel.kt index 0f517d740..76820b4f1 100644 --- a/src/main/kotlin/dartzee/screen/game/AbstractGameStatisticsPanel.kt +++ b/src/main/kotlin/dartzee/screen/game/AbstractGameStatisticsPanel.kt @@ -14,11 +14,9 @@ import javax.swing.JPanel import javax.swing.UIManager import javax.swing.border.EmptyBorder -/** - * Shows statistics for each player in a particular game, based on the PlayerStates - */ -abstract class AbstractGameStatisticsPanel>: JPanel() -{ +/** Shows statistics for each player in a particular game, based on the PlayerStates */ +abstract class AbstractGameStatisticsPanel> : + JPanel() { protected val uniqueParticipantNamesOrdered = mutableListOf() protected var participants: List = emptyList() protected val hmPlayerToDarts = mutableMapOf>>() @@ -29,13 +27,16 @@ abstract class AbstractGameStatisticsPanel + abstract fun getRankedRowsLowestWins(): List + abstract fun getHistogramRows(): List + protected abstract fun getStartOfSectionRows(): List + protected abstract fun addRowsToTable() - init - { + init { layout = BorderLayout(0, 0) add(table, BorderLayout.CENTER) @@ -51,8 +52,7 @@ abstract class AbstractGameStatisticsPanel) - { + fun showStats(playerStates: List) { this.participants = playerStates.map { it.wrappedParticipant } hmPlayerToDarts.clear() @@ -61,85 +61,87 @@ abstract class AbstractGameStatisticsPanel state.completedRounds }}) + hmPlayerToDarts.putAll(hm.mapValues { it.value.flatMap { state -> state.completedRounds } }) - if (isSufficientData()) - { + if (isSufficientData()) { buildTableModel() } } - private fun isSufficientData(): Boolean - { + private fun isSufficientData(): Boolean { val names = hmPlayerToDarts.keys return names.all { p -> getFlattenedDarts(p).isNotEmpty() } } - protected fun buildTableModel() - { + protected fun buildTableModel() { tm.clear() - for (pt in participants) - { + for (pt in participants) { val participantName = pt.getUniqueParticipantName() uniqueParticipantNamesOrdered.addUnique(participantName) } val requiredColumns = listOf("") + uniqueParticipantNamesOrdered.map { it.value } - (tm.columnCount until requiredColumns.size).forEach { - table.addColumn(requiredColumns[it]) - } + (tm.columnCount until requiredColumns.size).forEach { table.addColumn(requiredColumns[it]) } addRowsToTable() - //Rendering - for (i in 0 until tm.columnCount) - { + // Rendering + for (i in 0 until tm.columnCount) { table.getColumn(i).cellRenderer = factoryStatsCellRenderer() table.getColumn(i).headerRenderer = GameStatisticsHeaderRenderer() } } private fun factoryStatsCellRenderer() = - GameStatisticsCellRenderer(getStartOfSectionRows(), getRankedRowsHighestWins(), getRankedRowsLowestWins(), getHistogramRows()) - - protected fun addRow(row: Array) - { + GameStatisticsCellRenderer( + getStartOfSectionRows(), + getRankedRowsHighestWins(), + getRankedRowsLowestWins(), + getHistogramRows() + ) + + protected fun addRow(row: Array) { tm.addRow(row) } - protected fun getFlattenedDarts(uniqueParticipantName: UniqueParticipantName): List - { + protected fun getFlattenedDarts(uniqueParticipantName: UniqueParticipantName): List { val rounds = hmPlayerToDarts[uniqueParticipantName] return rounds?.flatten().orEmpty() } - protected fun factoryRow(rowName: String): Array - { + protected fun factoryRow(rowName: String): Array { val row = arrayOfNulls(tm.columnCount) row[0] = rowName return row } - protected fun getBestGameRow(fn: (s: List) -> Int) = prepareRow("Best Game") { participantName -> - val playerPts = getFinishedParticipants(participantName) - val scores = playerPts.map { it.participant.finalScore } - if (scores.isEmpty()) null else fn(scores) - } - protected fun getAverageGameRow() = prepareRow("Avg Game") { participantName -> - val playerPts = getFinishedParticipants(participantName) - val scores = playerPts.map { it.participant.finalScore } - if (scores.isEmpty()) null else MathsUtil.round(scores.average(), 2) - } + protected fun getBestGameRow(fn: (s: List) -> Int) = + prepareRow("Best Game") { participantName -> + val playerPts = getFinishedParticipants(participantName) + val scores = playerPts.map { it.participant.finalScore } + if (scores.isEmpty()) null else fn(scores) + } - private fun getFinishedParticipants(uniqueParticipantName: UniqueParticipantName) = participants.filter { it.getUniqueParticipantName() == uniqueParticipantName && it.participant.finalScore > -1 } + protected fun getAverageGameRow() = + prepareRow("Avg Game") { participantName -> + val playerPts = getFinishedParticipants(participantName) + val scores = playerPts.map { it.participant.finalScore } + if (scores.isEmpty()) null else MathsUtil.round(scores.average(), 2) + } + + private fun getFinishedParticipants(uniqueParticipantName: UniqueParticipantName) = + participants.filter { + it.getUniqueParticipantName() == uniqueParticipantName && it.participant.finalScore > -1 + } - protected fun prepareRow(name: String, fn: (uniqueParticipantName: UniqueParticipantName) -> Any?): Array - { + protected fun prepareRow( + name: String, + fn: (uniqueParticipantName: UniqueParticipantName) -> Any? + ): Array { val row = factoryRow(name) - for (i in uniqueParticipantNamesOrdered.indices) - { + for (i in uniqueParticipantNamesOrdered.indices) { val playerName = uniqueParticipantNamesOrdered[i] val result = fn(playerName) diff --git a/src/main/kotlin/dartzee/screen/game/DartsGamePanel.kt b/src/main/kotlin/dartzee/screen/game/DartsGamePanel.kt index abe7c22c1..12b9d4c99 100644 --- a/src/main/kotlin/dartzee/screen/game/DartsGamePanel.kt +++ b/src/main/kotlin/dartzee/screen/game/DartsGamePanel.kt @@ -47,27 +47,27 @@ import javax.swing.JButton import javax.swing.JPanel import javax.swing.JToggleButton - -abstract class DartsGamePanel, PlayerState: AbstractPlayerState>( - protected val parentWindow: AbstractDartsGameScreen, - val gameEntity: GameEntity, - protected val totalPlayers: Int) : PanelWithScorers(), DartboardListener, ActionListener -{ +abstract class DartsGamePanel< + S : AbstractDartsScorer, + PlayerState : AbstractPlayerState +>( + protected val parentWindow: AbstractDartsGameScreen, + val gameEntity: GameEntity, + protected val totalPlayers: Int +) : PanelWithScorers(), DartboardListener, ActionListener { private val hmPlayerNumberToState = mutableMapOf() private val hmPlayerNumberToScorer = mutableMapOf() val gameTitle = makeGameTitle() - //Transitive things + // Transitive things var currentPlayerNumber = 0 protected var currentRoundNumber = -1 - //For AI turns + // For AI turns protected var cpuThread: Thread? = null - /** - * Screen stuff - */ + /** Screen stuff */ val dartboard = GameplayDartboard(colourWrapper()) private val statsPanel = factoryStatsPanel(gameEntity.gameParams) @@ -80,40 +80,46 @@ abstract class DartsGamePanel, PlayerState: private val btnStats = JToggleButton("") private val btnSlider = JToggleButton("") - private fun getPlayersDesc() = if (totalPlayers == 1) "practice game" else "$totalPlayers players" + private fun getPlayersDesc() = + if (totalPlayers == 1) "practice game" else "$totalPlayers players" + protected fun getActiveCount() = getParticipants().count { it.participant.isActive() } fun getGameId() = gameEntity.rowId open fun colourWrapper() = getColourWrapperFromPrefs() - open fun getFinishingPositionFromPlayersRemaining(): Int - { - if (totalPlayers == 1) - { + open fun getFinishingPositionFromPlayersRemaining(): Int { + if (totalPlayers == 1) { return -1 } return totalPlayers - getActiveCount() + 1 } - protected fun getCurrentPlayerStrategy(): DartsAiModel - { + protected fun getCurrentPlayerStrategy(): DartsAiModel { val participant = getCurrentIndividual() return participant.getModel() } - /** - * Stuff that will ultimately get refactored off into a GameState thingy - */ + /** Stuff that will ultimately get refactored off into a GameState thingy */ fun getPlayerStates() = hmPlayerNumberToState.getSortedValues() - protected fun getParticipants() = hmPlayerNumberToState.entries.sortedBy { it.key }.map { it.value.wrappedParticipant } + + protected fun getParticipants() = + hmPlayerNumberToState.entries.sortedBy { it.key }.map { it.value.wrappedParticipant } + protected fun getCurrentPlayerId() = getCurrentIndividual().playerId + protected fun getCurrentPlayerState() = getPlayerState(currentPlayerNumber) + private fun getPlayerState(playerNumber: Int) = hmPlayerNumberToState[playerNumber]!! + private fun getParticipant(playerNumber: Int) = getPlayerState(playerNumber).wrappedParticipant + private fun getCurrentIndividual() = getCurrentPlayerState().currentIndividual() + fun getDartsThrown() = getCurrentPlayerState().currentRound + fun dartsThrownCount() = getDartsThrown().size private fun addState(playerNumber: Int, state: PlayerState, scorer: S) { @@ -122,10 +128,10 @@ abstract class DartsGamePanel, PlayerState: } protected fun getCurrentScorer() = hmPlayerNumberToScorer.getValue(currentPlayerNumber) + protected fun getPlayerNumberForScorer(scorer: S): Int = scorersOrdered.indexOf(scorer) - init - { + init { panelCenter.add(dartboard, BorderLayout.CENTER) dartboard.addDartboardListener(this) panelCenter.add(panelSouth, BorderLayout.SOUTH) @@ -162,24 +168,23 @@ abstract class DartsGamePanel, PlayerState: btnSlider.addActionListener(this) } - /** - * Abstract methods - */ + /** Abstract methods */ abstract fun factoryState(pt: IWrappedParticipant): PlayerState + abstract fun computeAiDart(model: DartsAiModel): ComputedPoint? abstract fun shouldStopAfterDartThrown(): Boolean + abstract fun shouldAIStop(): Boolean + abstract fun saveDartsAndProceed() + abstract fun factoryStatsPanel(gameParams: String): AbstractGameStatisticsPanel open fun updateVariablesForDartThrown(dart: Dart) {} - /** - * Regular methods - */ - fun startNewGame(participants: List) - { + /** Regular methods */ + fun startNewGame(participants: List) { participants.forEachIndexed(::addParticipant) finaliseParticipants() @@ -187,11 +192,10 @@ abstract class DartsGamePanel, PlayerState: nextTurn() } - protected fun nextTurn() - { + protected fun nextTurn() { updateActivePlayer() - //Create a new round for this player + // Create a new round for this player currentRoundNumber = getCurrentPlayerState().currentRoundNumber() btnReset.isEnabled = false @@ -202,30 +206,24 @@ abstract class DartsGamePanel, PlayerState: readyForThrow() } - protected fun updateActivePlayer() - { - hmPlayerNumberToState.values.forEach { - it.updateActive(it == getCurrentPlayerState()) - } + protected fun updateActivePlayer() { + hmPlayerNumberToState.values.forEach { it.updateActive(it == getCurrentPlayerState()) } } - private fun initForAi(hasAi: Boolean) - { + private fun initForAi(hasAi: Boolean) { btnSlider.isVisible = hasAi val defaultSpd = PreferenceUtil.getIntValue(PREFERENCES_INT_AI_SPEED) slider.value = defaultSpd } - protected fun makeGameTitle(): String - { + protected fun makeGameTitle(): String { val gameNo = gameEntity.localId val gameDesc = gameEntity.getTypeDesc() return "Game #$gameNo ($gameDesc - ${getPlayersDesc()})" } - fun loadGame(participants: List) - { + fun loadGame(participants: List) { val gameId = gameEntity.rowId participants.forEachIndexed(::addParticipant) @@ -233,40 +231,30 @@ abstract class DartsGamePanel, PlayerState: loadScoresAndCurrentPlayer(gameId) - //If the game is over, do some extra stuff to sort the screen out + // If the game is over, do some extra stuff to sort the screen out val dtFinish = gameEntity.dtFinish - if (!isEndOfTime(dtFinish)) - { + if (!isEndOfTime(dtFinish)) { setGameReadOnly() - } - else - { + } else { nextTurn() } } - protected open fun setGameReadOnly() - { + protected open fun setGameReadOnly() { dartboard.stopListening() - scorersOrdered.forEach { - it.gameFinished() - } + scorersOrdered.forEach { it.gameFinished() } - if (getActiveCount() == 0) - { + if (getActiveCount() == 0) { btnSlider.isVisible = false btnConfirm.isVisible = false btnReset.isVisible = false - } - else - { + } else { btnConfirm.isEnabled = false btnReset.isEnabled = false } - //Default to showing the stats panel for completed games, if applicable - if (btnStats.isVisible) - { + // Default to showing the stats panel for completed games, if applicable + if (btnStats.isVisible) { btnStats.isSelected = true viewStats() } @@ -274,23 +262,18 @@ abstract class DartsGamePanel, PlayerState: /** * Populate the scorers and populate the current player by: - * * - Finding the Max(RoundNumber) for this game * - Finding how many players have already completed this round, X. * - CurrentPlayerNumber = X % totalPlayers */ - private fun loadScoresAndCurrentPlayer(gameId: String) - { - for (i in 0 until totalPlayers) - { + private fun loadScoresAndCurrentPlayer(gameId: String) { + for (i in 0 until totalPlayers) { val pt = getParticipant(i) val hmRoundToDarts = loadRoundsMap(pt) val state = getPlayerState(i) - hmRoundToDarts.getSortedValues().forEach { - state.addLoadedRound(it) - } + hmRoundToDarts.getSortedValues().forEach { state.addLoadedRound(it) } loadAdditionalEntities(state) } @@ -298,10 +281,11 @@ abstract class DartsGamePanel, PlayerState: val maxRounds = getPlayerStates().maxOf { it.currentRoundNumber() - 1 } setCurrentPlayer(maxRounds, gameId) } - private fun loadRoundsMap(pt: IWrappedParticipant): HashMapList - { + + private fun loadRoundsMap(pt: IWrappedParticipant): HashMapList { val individuals = pt.individuals - val sql = """ + val sql = + """ SELECT drt.RoundNumber, drt.Score, drt.Multiplier, drt.SegmentType, drt.StartingScore FROM Dart drt WHERE drt.ParticipantId IN ${individuals.getQuotedIdStr { it.rowId } } @@ -312,15 +296,14 @@ abstract class DartsGamePanel, PlayerState: val hmRoundToDarts = HashMapList() mainDatabase.executeQuery(sql).use { rs -> - while (rs.next()) - { + while (rs.next()) { val roundNumber = rs.getInt("RoundNumber") val score = rs.getInt("Score") val multiplier = rs.getInt("Multiplier") val segmentType = SegmentType.valueOf(rs.getString("SegmentType")) val startingScore = rs.getInt("StartingScore") - val drt = Dart(score, multiplier, segmentType=segmentType) + val drt = Dart(score, multiplier, segmentType = segmentType) drt.startingScore = startingScore drt.roundNumber = roundNumber @@ -334,14 +317,13 @@ abstract class DartsGamePanel, PlayerState: protected open fun loadAdditionalEntities(state: PlayerState) {} /** - * 1) Get the MAX(Ordinal) of the person who's played the maxRounds, i.e. the last player to have a turn. + * 1) Get the MAX(Ordinal) of the person who's played the maxRounds, i.e. the last player to + * have a turn. * 2) Call into getNextPlayer(), which takes into account inactive players. */ - private fun setCurrentPlayer(maxRounds: Int, gameId: String) - { - if (maxRounds == 0) - { - //The game literally hasn't started yet. No one has completed a round. + private fun setCurrentPlayer(maxRounds: Int, gameId: String) { + if (maxRounds == 0) { + // The game literally hasn't started yet. No one has completed a round. currentPlayerNumber = 0 return } @@ -362,10 +344,8 @@ abstract class DartsGamePanel, PlayerState: currentPlayerNumber = getNextPlayerNumber(lastPlayerNumber) } - protected fun allPlayersFinished() - { - if (!gameEntity.isFinished()) - { + protected fun allPlayersFinished() { + if (!gameEntity.isFinished()) { gameEntity.dtFinish = getSqlDateNow() gameEntity.saveToDatabase() } @@ -373,32 +353,27 @@ abstract class DartsGamePanel, PlayerState: setGameReadOnly() } - /** * Should I stop throwing? * - * Default behaviour for if window has been closed, with extensible hook (e.g. in X01 where an AI can be paused). + * Default behaviour for if window has been closed, with extensible hook (e.g. in X01 where an + * AI can be paused). */ - private fun shouldAiStopThrowing(): Boolean - { - if (!parentWindow.isVisible) - { + private fun shouldAiStopThrowing(): Boolean { + if (!parentWindow.isVisible) { return true } return shouldAIStop() } - protected fun getNextPlayerNumber(currentPlayerNumber: Int): Int - { - if (getActiveCount() == 0) - { + protected fun getNextPlayerNumber(currentPlayerNumber: Int): Int { + if (getActiveCount() == 0) { return currentPlayerNumber } var candidate = (currentPlayerNumber + 1) % totalPlayers - while (!isActive(candidate)) - { + while (!isActive(candidate)) { candidate = (candidate + 1) % totalPlayers } @@ -409,16 +384,13 @@ abstract class DartsGamePanel, PlayerState: private fun isActive(playerNumber: Int) = getParticipant(playerNumber).participant.isActive() - fun fireAppearancePreferencesChanged() - { - for (scorer in scorersOrdered) - { + fun fireAppearancePreferencesChanged() { + for (scorer in scorersOrdered) { scorer.repaint() } } - protected fun handlePlayerFinish(): Int - { + protected fun handlePlayerFinish(): Int { val state = getCurrentPlayerState() val finishingPosition = getFinishingPositionFromPlayersRemaining() val numberOfDarts = state.getScoreSoFar() @@ -429,105 +401,91 @@ abstract class DartsGamePanel, PlayerState: return finishingPosition } - open fun updateAchievementsForFinish(playerState: PlayerState, finishingPosition: Int, score: Int) - { - if (playerState.hasMultiplePlayers()) - { - if (finishingPosition == 1) - { + open fun updateAchievementsForFinish( + playerState: PlayerState, + finishingPosition: Int, + score: Int + ) { + if (playerState.hasMultiplePlayers()) { + if (finishingPosition == 1) { val type = getTeamWinAchievementType(gameEntity.gameType) playerState.getPlayerIds().forEach { playerId -> AchievementEntity.insertAchievement(type, playerId, gameEntity.rowId, "$score") } } - } - else - { + } else { val playerId = playerState.lastIndividual().playerId - if (finishingPosition == 1) - { + if (finishingPosition == 1) { val type = getWinAchievementType(gameEntity.gameType) AchievementEntity.insertAchievement(type, playerId, gameEntity.rowId, "$score") } - //Update the 'best game' achievement + // Update the 'best game' achievement val aa = getBestGameAchievement(gameEntity.gameType) ?: return val gameParams = aa.gameParams - if (gameParams == gameEntity.gameParams) - { - AchievementEntity.updateAchievement(aa.achievementType, playerId, gameEntity.rowId, score) + if (gameParams == gameEntity.gameParams) { + AchievementEntity.updateAchievement( + aa.achievementType, + playerId, + gameEntity.rowId, + score + ) } } } - override fun dartThrown(dart: Dart) - { + override fun dartThrown(dart: Dart) { getCurrentPlayerState().dartThrown(dart) - //If there are any specific variables we need to update (e.g. current score for X01), do it now + // If there are any specific variables we need to update (e.g. current score for X01), do it + // now updateVariablesForDartThrown(dart) doAnimations(dart) - //Enable both of these + // Enable both of these btnReset.isEnabled = getCurrentPlayerState().isHuman() - if (!mustContinueThrowing()) - { + if (!mustContinueThrowing()) { btnConfirm.isEnabled = getCurrentPlayerState().isHuman() } - //If we've thrown three or should stop for other reasons (bust in X01), then stop throwing - if (shouldStopAfterDartThrown()) - { + // If we've thrown three or should stop for other reasons (bust in X01), then stop throwing + if (shouldStopAfterDartThrown()) { stopThrowing() - } - else - { - //Fine, just carry on + } else { + // Fine, just carry on readyForThrow() } } - private fun doAnimations(dart: Dart) - { - if (dart.multiplier == 0 && shouldAnimateMiss(dart)) - { + private fun doAnimations(dart: Dart) { + if (dart.multiplier == 0 && shouldAnimateMiss(dart)) { doMissAnimation() - } - else if (dart.getTotal() == 50) - { + } else if (dart.getTotal() == 50) { dartboard.doBull() } } protected open fun shouldAnimateMiss(dart: Dart) = true - - protected open fun doMissAnimation() - { + protected open fun doMissAnimation() { dartboard.doBadMiss() } - protected fun stopThrowing() - { - if (getCurrentPlayerState().isHuman()) - { + protected fun stopThrowing() { + if (getCurrentPlayerState().isHuman()) { dartboard.stopListening() - } - else - { + } else { Thread.sleep(slider.value.toLong()) // If we've been told to pause then we're going to do a reset and not save anything - if (!shouldAiStopThrowing()) - { + if (!shouldAiStopThrowing()) { runOnEventThread { confirmRound() } } } } - private fun confirmRound() - { + private fun confirmRound() { btnConfirm.isEnabled = false btnReset.isEnabled = false @@ -536,40 +494,31 @@ abstract class DartsGamePanel, PlayerState: saveDartsAndProceed() } - protected fun resetRound() - { + protected fun resetRound() { dartboard.clearDarts() getCurrentPlayerState().resetRound() - //If we're resetting, disable the buttons + // If we're resetting, disable the buttons btnConfirm.isEnabled = false btnReset.isEnabled = false - //Might need to re-enable the dartboard for listening if we're a human player - if (getCurrentPlayerState().isHuman()) - { + // Might need to re-enable the dartboard for listening if we're a human player + if (getCurrentPlayerState().isHuman()) { dartboard.ensureListening() } } - /** - * Commit round to current player state and the database - */ - protected fun commitRound() - { + /** Commit round to current player state and the database */ + protected fun commitRound() { getCurrentPlayerState().commitRound() } - open fun readyForThrow() - { - if (getCurrentPlayerState().isHuman()) - { - //Human player + open fun readyForThrow() { + if (getCurrentPlayerState().isHuman()) { + // Human player dartboard.ensureListening() - } - else - { - //AI + } else { + // AI dartboard.stopListening() cpuThread = Thread(DelayedOpponentTurn(), "Cpu-Thread-" + gameEntity.localId) @@ -579,10 +528,8 @@ abstract class DartsGamePanel, PlayerState: protected open fun mustContinueThrowing() = false - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnReset -> { resetRound() readyForThrow() @@ -593,22 +540,17 @@ abstract class DartsGamePanel, PlayerState: } } - private fun toggleSlider() - { + private fun toggleSlider() { slider.isVisible = btnSlider.isSelected } - private fun viewStats() - { - if (btnStats.isSelected) - { + private fun viewStats() { + if (btnStats.isSelected) { panelCenter.remove(dartboard) panelCenter.add(statsPanel, BorderLayout.CENTER) statsPanel.showStats(getPlayerStates()) - } - else - { + } else { panelCenter.remove(statsPanel) panelCenter.add(dartboard, BorderLayout.CENTER) } @@ -617,8 +559,7 @@ abstract class DartsGamePanel, PlayerState: panelCenter.repaint() } - private fun addParticipant(ordinal: Int, wrappedPt: IWrappedParticipant) - { + private fun addParticipant(ordinal: Int, wrappedPt: IWrappedParticipant) { val scorer = assignScorer(wrappedPt) val state = factoryState(wrappedPt) state.addListener(scorer) @@ -627,8 +568,7 @@ abstract class DartsGamePanel, PlayerState: runForMatch { it.addParticipant(gameEntity.localId, state) } } - private fun finaliseParticipants() - { + private fun finaliseParticipants() { finaliseScorers(parentWindow) initForAi(hasAi()) @@ -637,59 +577,52 @@ abstract class DartsGamePanel, PlayerState: } } - private fun runForMatch(fn: (matchScreen: DartsMatchScreen) -> Unit) - { - if (parentWindow is DartsMatchScreen<*>) - { - @Suppress("UNCHECKED_CAST") - fn(parentWindow as DartsMatchScreen) + private fun runForMatch(fn: (matchScreen: DartsMatchScreen) -> Unit) { + if (parentWindow is DartsMatchScreen<*>) { + @Suppress("UNCHECKED_CAST") fn(parentWindow as DartsMatchScreen) } } - fun achievementUnlocked(playerId: String, achievement: AbstractAchievement) - { - scorersOrdered.find { it.playerIds.contains(playerId) }?.achievementUnlocked(achievement, playerId) + fun achievementUnlocked(playerId: String, achievement: AbstractAchievement) { + scorersOrdered + .find { it.playerIds.contains(playerId) } + ?.achievementUnlocked(achievement, playerId) } - fun disableInputButtons() - { + fun disableInputButtons() { btnConfirm.isEnabled = false btnReset.isEnabled = false } - internal inner class DelayedOpponentTurn : Runnable - { - override fun run() - { + internal inner class DelayedOpponentTurn : Runnable { + override fun run() { Thread.sleep(slider.value.toLong()) - if (shouldAiStopThrowing()) - { + if (shouldAiStopThrowing()) { return } val model = getCurrentPlayerStrategy() val pt = computeAiDart(model) - pt?.let { - dartboard.dartThrown(pt) - } + pt?.let { dartboard.dartThrown(pt) } } } - companion object - { + companion object { fun factory(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) = - when (game.gameType) - { + when (game.gameType) { GameType.X01 -> GamePanelX01(parent, game, totalPlayers) GameType.GOLF -> GamePanelGolf(parent, game, totalPlayers) GameType.ROUND_THE_CLOCK -> GamePanelRoundTheClock(parent, game, totalPlayers) GameType.DARTZEE -> constructGamePanelDartzee(parent, game, totalPlayers) } - fun constructGamePanelDartzee(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int): GamePanelDartzee - { + fun constructGamePanelDartzee( + parent: AbstractDartsGameScreen, + game: GameEntity, + totalPlayers: Int + ): GamePanelDartzee { val dtos = DartzeeRuleEntity().retrieveForGame(game.rowId).map { it.toDto() } val summaryPanel = DartzeeRuleSummaryPanel(DartzeeRuleCarousel(dtos)) diff --git a/src/main/kotlin/dartzee/screen/game/DartsGameScreen.kt b/src/main/kotlin/dartzee/screen/game/DartsGameScreen.kt index 19cd96b22..5aff1a0d2 100644 --- a/src/main/kotlin/dartzee/screen/game/DartsGameScreen.kt +++ b/src/main/kotlin/dartzee/screen/game/DartsGameScreen.kt @@ -4,34 +4,31 @@ import dartzee.achievements.AbstractAchievement import dartzee.db.GameEntity import dartzee.screen.ScreenCache -/** - * DartsGameScreen - * Simple screen which wraps up a single game panel - */ -class DartsGameScreen(game: GameEntity, totalPlayers: Int) : AbstractDartsGameScreen() -{ +/** DartsGameScreen Simple screen which wraps up a single game panel */ +class DartsGameScreen(game: GameEntity, totalPlayers: Int) : AbstractDartsGameScreen() { var gamePanel: DartsGamePanel<*, *> = DartsGamePanel.factory(this, game, totalPlayers) override val windowName = gamePanel.gameTitle - init - { - //Cache this screen in ScreenCache + init { + // Cache this screen in ScreenCache val gameId = game.rowId ScreenCache.addDartsGameScreen(gameId, this) title = gamePanel.gameTitle - //Add the single game tab and set visible + // Add the single game tab and set visible contentPane.add(gamePanel) } - override fun fireAppearancePreferencesChanged() - { + override fun fireAppearancePreferencesChanged() { gamePanel.fireAppearancePreferencesChanged() } - override fun achievementUnlocked(gameId: String, playerId: String, achievement: AbstractAchievement) - { + override fun achievementUnlocked( + gameId: String, + playerId: String, + achievement: AbstractAchievement + ) { gamePanel.achievementUnlocked(playerId, achievement) } } diff --git a/src/main/kotlin/dartzee/screen/game/DartsMatchScreen.kt b/src/main/kotlin/dartzee/screen/game/DartsMatchScreen.kt index 049a802eb..5b67ba6ed 100644 --- a/src/main/kotlin/dartzee/screen/game/DartsMatchScreen.kt +++ b/src/main/kotlin/dartzee/screen/game/DartsMatchScreen.kt @@ -22,17 +22,16 @@ import javax.swing.SwingConstants import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener -abstract class DartsMatchScreen>( +abstract class DartsMatchScreen>( private val matchPanel: MatchSummaryPanel, - val match: DartsMatchEntity): AbstractDartsGameScreen(), ChangeListener -{ + val match: DartsMatchEntity +) : AbstractDartsGameScreen(), ChangeListener { override val windowName = match.getMatchDesc() private val tabbedPane = JTabbedPane(SwingConstants.TOP) private val hmGameIdToTab = mutableMapOf>() - init - { + init { contentPane.add(tabbedPane, BorderLayout.CENTER) tabbedPane.addTab("Match", matchPanel) @@ -47,18 +46,17 @@ abstract class DartsMatchScreen>( totalPlayers: Int ): DartsGamePanel<*, PlayerState> - fun addGameToMatch(game: GameEntity, totalPlayers: Int): DartsGamePanel<*, *> - { - //Cache this screen in ScreenCache + fun addGameToMatch(game: GameEntity, totalPlayers: Int): DartsGamePanel<*, *> { + // Cache this screen in ScreenCache val gameId = game.rowId ScreenCache.addDartsGameScreen(gameId, this) - //Initialise some basic properties of the tab, such as visibility of components etc + // Initialise some basic properties of the tab, such as visibility of components etc val tab = factoryGamePanel(this, game, totalPlayers) matchPanel.addGameTab(tab) - //Add the single game tab and set the parent window to be visible + // Add the single game tab and set the parent window to be visible tabbedPane.addTab("#" + game.localId, tab) hmGameIdToTab[gameId] = tab isVisible = true @@ -66,22 +64,22 @@ abstract class DartsMatchScreen>( return tab } - fun addParticipant(localId: Long, state: PlayerState) - { + fun addParticipant(localId: Long, state: PlayerState) { matchPanel.addParticipant(localId, state) } - fun finaliseParticipants() - { + fun finaliseParticipants() { matchPanel.finaliseScorers(this) } - override fun startNextGameIfNecessary() - { - if (isMatchComplete()) - { - logger.info(CODE_MATCH_FINISHED, "Match #${match.localId} finished.", - KEY_MATCH_ID to match.rowId, KEY_MATCH_LOCAL_ID to match.localId) + override fun startNextGameIfNecessary() { + if (isMatchComplete()) { + logger.info( + CODE_MATCH_FINISHED, + "Match #${match.localId} finished.", + KEY_MATCH_ID to match.rowId, + KEY_MATCH_LOCAL_ID to match.localId + ) match.dtFinish = getSqlDateNow() match.saveToDatabase() return @@ -92,7 +90,12 @@ abstract class DartsMatchScreen>( val firstGamePanel = hmGameIdToTab.values.first() val firstGameParticipants = firstGamePanel.getPlayerStates().map { it.wrappedParticipant } - val (nextGame, nextParticipants) = prepareNextEntities(firstGamePanel.gameEntity, firstGameParticipants, hmGameIdToTab.size + 1) + val (nextGame, nextParticipants) = + prepareNextEntities( + firstGamePanel.gameEntity, + firstGameParticipants, + hmGameIdToTab.size + 1 + ) logger.info( CODE_GAME_LAUNCHED, @@ -108,48 +111,40 @@ abstract class DartsMatchScreen>( panel.startNewGame(nextParticipants) } - private fun isMatchComplete(): Boolean - { + private fun isMatchComplete(): Boolean { val participants = matchPanel.getAllParticipants() return matchIsComplete(match, participants) } - override fun achievementUnlocked(gameId: String, playerId: String, achievement: AbstractAchievement) - { + override fun achievementUnlocked( + gameId: String, + playerId: String, + achievement: AbstractAchievement + ) { val tab = hmGameIdToTab[gameId]!! tab.achievementUnlocked(playerId, achievement) } - override fun displayGame(gameId: String) - { + override fun displayGame(gameId: String) { super.displayGame(gameId) val tab = hmGameIdToTab[gameId] tabbedPane.selectedComponent = tab } - override fun fireAppearancePreferencesChanged() - { - hmGameIdToTab.values.forEach { - it.fireAppearancePreferencesChanged() - } + override fun fireAppearancePreferencesChanged() { + hmGameIdToTab.values.forEach { it.fireAppearancePreferencesChanged() } } - /** - * ChangeListener - */ - override fun stateChanged(e: ChangeEvent) - { + /** ChangeListener */ + override fun stateChanged(e: ChangeEvent) { val sourceTabbedPane = e.source as JTabbedPane val selectedTab = sourceTabbedPane.selectedComponent - if (selectedTab is DartsGamePanel<*, *>) - { + if (selectedTab is DartsGamePanel<*, *>) { val title = selectedTab.gameTitle setTitle(title) - } - else - { + } else { title = match.getMatchDesc() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/GamePanelFixedLength.kt b/src/main/kotlin/dartzee/screen/game/GamePanelFixedLength.kt index bfa86dd60..7a0ef5e52 100644 --- a/src/main/kotlin/dartzee/screen/game/GamePanelFixedLength.kt +++ b/src/main/kotlin/dartzee/screen/game/GamePanelFixedLength.kt @@ -6,35 +6,29 @@ import dartzee.screen.game.scorer.AbstractDartsScorer import dartzee.utils.doesHighestWin import dartzee.utils.setFinishingPositions -abstract class GamePanelFixedLength, PlayerState: AbstractPlayerState>( - parent: AbstractDartsGameScreen, - game: GameEntity, - totalPlayers: Int): DartsGamePanel(parent, game, totalPlayers) -{ +abstract class GamePanelFixedLength< + S : AbstractDartsScorer, + PlayerState : AbstractPlayerState +>(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) : + DartsGamePanel(parent, game, totalPlayers) { abstract val totalRounds: Int val highestWins = doesHighestWin(game.gameType) - fun finishRound() - { - if (currentRoundNumber == totalRounds) - { + fun finishRound() { + if (currentRoundNumber == totalRounds) { handlePlayerFinish() } currentPlayerNumber = getNextPlayerNumber(currentPlayerNumber) - if (getActiveCount() > 0) - { + if (getActiveCount() > 0) { nextTurn() - } - else - { + } else { finishGame() } } - private fun finishGame() - { - //Get the participants sorted by score so we can assign finishing positions + private fun finishGame() { + // Get the participants sorted by score so we can assign finishing positions setFinishingPositions(getParticipants().map { it.participant }, gameEntity) allPlayersFinished() @@ -43,4 +37,4 @@ abstract class GamePanelFixedLength, Player } override fun getFinishingPositionFromPlayersRemaining() = -1 -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/GamePanelPausable.kt b/src/main/kotlin/dartzee/screen/game/GamePanelPausable.kt index 6e472afd2..1d576abcd 100644 --- a/src/main/kotlin/dartzee/screen/game/GamePanelPausable.kt +++ b/src/main/kotlin/dartzee/screen/game/GamePanelPausable.kt @@ -8,54 +8,44 @@ import dartzee.utils.PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE import dartzee.utils.PreferenceUtil import javax.swing.SwingUtilities -abstract class GamePanelPausable, PlayerState: AbstractPlayerState>(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int): - DartsGamePanel(parent, game, totalPlayers) -{ +abstract class GamePanelPausable< + S : AbstractDartsScorerPausable, + PlayerState : AbstractPlayerState +>(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) : + DartsGamePanel(parent, game, totalPlayers) { private var aiShouldPause = false - /** - * Abstract methods - */ + /** Abstract methods */ abstract fun currentPlayerHasFinished(): Boolean - override fun saveDartsAndProceed() - { + override fun saveDartsAndProceed() { commitRound() - //This player has finished. The game isn't necessarily over though... - if (currentPlayerHasFinished()) - { + // This player has finished. The game isn't necessarily over though... + if (currentPlayerHasFinished()) { handlePlayerFinish() } currentPlayerNumber = getNextPlayerNumber(currentPlayerNumber) val activePlayers = getActiveCount() - if (activePlayers > 1 || (activePlayers == 1 && totalPlayers == 1)) - { - //We always keep going if there's more than 1 active person in play + if (activePlayers > 1 || (activePlayers == 1 && totalPlayers == 1)) { + // We always keep going if there's more than 1 active person in play nextTurn() - } - else if (activePlayers == 1) - { - //Finish the game and set the last player's finishing position if we haven't already + } else if (activePlayers == 1) { + // Finish the game and set the last player's finishing position if we haven't already finishGameIfNecessary() - if (!getCurrentScorer().getPaused()) - { + if (!getCurrentScorer().getPaused()) { nextTurn() } - } - else - { + } else { allPlayersFinished() } } - override fun shouldAIStop(): Boolean - { - if (aiShouldPause) - { + override fun shouldAIStop(): Boolean { + if (aiShouldPause) { aiShouldPause = false return true } @@ -63,10 +53,8 @@ abstract class GamePanelPausable, P return false } - private fun finishGameIfNecessary() - { - if (gameEntity.isFinished()) - { + private fun finishGameIfNecessary() { + if (gameEntity.isFinished()) { return } @@ -77,19 +65,19 @@ abstract class GamePanelPausable, P parentWindow.startNextGameIfNecessary() - //Display this player's result. If they're an AI and we have the preference, then - //automatically play on. + // Display this player's result. If they're an AI and we have the preference, then + // automatically play on. updateActivePlayer() - if (!getCurrentPlayerState().isHuman() && PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE)) - { + if ( + !getCurrentPlayerState().isHuman() && + PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) + ) { getCurrentScorer().toggleResume() } } - fun pauseLastPlayer() - { - if (!getCurrentPlayerState().isHuman() && cpuThread != null) - { + fun pauseLastPlayer() { + if (!getCurrentPlayerState().isHuman() && cpuThread != null) { aiShouldPause = true cpuThread!!.join() } @@ -99,15 +87,14 @@ abstract class GamePanelPausable, P SwingUtilities.invokeLater { resetRound() - //Set the current round number back to the previous round + // Set the current round number back to the previous round currentRoundNumber-- dartboard.stopListening() } } - fun unpauseLastPlayer() - { + fun unpauseLastPlayer() { aiShouldPause = false nextTurn() } diff --git a/src/main/kotlin/dartzee/screen/game/GameStatisticsCellRenderer.kt b/src/main/kotlin/dartzee/screen/game/GameStatisticsCellRenderer.kt index e519eebc3..af7429faa 100644 --- a/src/main/kotlin/dartzee/screen/game/GameStatisticsCellRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/GameStatisticsCellRenderer.kt @@ -10,13 +10,20 @@ import javax.swing.border.MatteBorder import javax.swing.table.DefaultTableCellRenderer import javax.swing.table.TableModel -class GameStatisticsCellRenderer(private val sectionStarts: List, - private val highestWins: List, - private val lowestWins: List, - private val histogramRows: List): DefaultTableCellRenderer() -{ - override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { +class GameStatisticsCellRenderer( + private val sectionStarts: List, + private val highestWins: List, + private val lowestWins: List, + private val histogramRows: List +) : DefaultTableCellRenderer() { + override fun getTableCellRendererComponent( + table: JTable?, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) table ?: return this @@ -31,8 +38,7 @@ class GameStatisticsCellRenderer(private val sectionStarts: List, return this } - private fun getBorder(table: JTable, row: Int, column: Int): MatteBorder - { + private fun getBorder(table: JTable, row: Int, column: Int): MatteBorder { val left = if (column == 0) 2 else 1 val right = if (column == table.model.columnCount - 1) 2 else 1 val bottom = if (row == table.rowCount - 1) 2 else 0 @@ -43,11 +49,9 @@ class GameStatisticsCellRenderer(private val sectionStarts: List, return MatteBorder(top, left, bottom, right, Color.BLACK) } - private fun setColours(table: JTable, row: Int, column: Int) - { - if (column == 0) - { - //Do nothing + private fun setColours(table: JTable, row: Int, column: Int) { + if (column == 0) { + // Do nothing foreground = null background = Color.WHITE return @@ -56,18 +60,13 @@ class GameStatisticsCellRenderer(private val sectionStarts: List, val tm = table.model val rowName = table.getValueAt(row, 0) - if (highestWins.contains(rowName)) - { + if (highestWins.contains(rowName)) { val pos = getPositionForColour(tm, row, column, true) DartsColour.setFgAndBgColoursForPosition(this, pos, Color.WHITE) - } - else if (lowestWins.contains(rowName)) - { + } else if (lowestWins.contains(rowName)) { val pos = getPositionForColour(tm, row, column, false) DartsColour.setFgAndBgColoursForPosition(this, pos, Color.WHITE) - } - else if (histogramRows.contains(rowName)) - { + } else if (histogramRows.contains(rowName)) { val sum = getHistogramSum(tm, column) val thisValue = getDoubleAt(tm, row, column) @@ -77,49 +76,45 @@ class GameStatisticsCellRenderer(private val sectionStarts: List, foreground = null background = bg - } - else - { + } else { foreground = null background = Color.WHITE } } - private fun getDoubleAt(tm: TableModel, row: Int, col: Int): Double - { + private fun getDoubleAt(tm: TableModel, row: Int, col: Int): Double { val thisValue = tm.getValueAt(row, col) - if (thisValue == null) - { + if (thisValue == null) { return -1.0 } return (thisValue as Number).toDouble() } - private fun getPositionForColour(tm: TableModel, row: Int, col: Int, highestWins: Boolean): Int - { - if (tm.getValueAt(row, col) is String || tm.columnCount == 2) - { + private fun getPositionForColour( + tm: TableModel, + row: Int, + col: Int, + highestWins: Boolean + ): Int { + if (tm.getValueAt(row, col) is String || tm.columnCount == 2) { return -1 } val myScore = getDoubleAt(tm, row, col) var myPosition = 1 - for (i in 1 until tm.columnCount) - { - if (i == col || tm.getValueAt(row, i) is String) - { + for (i in 1 until tm.columnCount) { + if (i == col || tm.getValueAt(row, i) is String) { continue } val theirScore = getDoubleAt(tm, row, i) - //Compare positivity to the boolean + // Compare positivity to the boolean val result = theirScore.compareTo(myScore) - if (result > 0 == highestWins && result != 0) - { + if (result > 0 == highestWins && result != 0) { myPosition++ } } @@ -132,4 +127,4 @@ class GameStatisticsCellRenderer(private val sectionStarts: List, private fun getHistogramRowNumbers(tm: TableModel) = (0 until tm.rowCount).filter { histogramRows.contains(tm.getValueAt(it, 0)) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/GameStatisticsHeaderRenderer.kt b/src/main/kotlin/dartzee/screen/game/GameStatisticsHeaderRenderer.kt index f137d33ee..7d9aee1a0 100644 --- a/src/main/kotlin/dartzee/screen/game/GameStatisticsHeaderRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/GameStatisticsHeaderRenderer.kt @@ -10,28 +10,29 @@ import javax.swing.table.TableCellRenderer import javax.swing.text.SimpleAttributeSet import javax.swing.text.StyleConstants -class GameStatisticsHeaderRenderer: JTextPane(), TableCellRenderer -{ - init - { +class GameStatisticsHeaderRenderer : JTextPane(), TableCellRenderer { + init { val doc = this.styledDocument val center = SimpleAttributeSet() StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER) doc.setParagraphAttributes(0, doc.length, center, false) } - override fun getTableCellRendererComponent(table: JTable, - value: Any, isSelected: Boolean, hasFocus: Boolean, row: Int, - column: Int): Component - { + override fun getTableCellRendererComponent( + table: JTable, + value: Any, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { text = value as String font = Font("Trebuchet MS", Font.BOLD, 15) border = getBorder(table, column) setSize(table.columnModel.getColumn(column).width, preferredSize.height) - if (column == 0) - { + if (column == 0) { background = Color(0, 0, 0, 0) isOpaque = false } @@ -39,12 +40,11 @@ class GameStatisticsHeaderRenderer: JTextPane(), TableCellRenderer return this } - private fun getBorder(table: JTable, column: Int): MatteBorder - { + private fun getBorder(table: JTable, column: Int): MatteBorder { val top = if (column == 0) 0 else 2 val left = if (column == 0) 0 else 1 val right = if (column == table.columnCount - 1) 2 else 1 return MatteBorder(top, left, 2, right, Color.BLACK) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/MatchSummaryPanel.kt b/src/main/kotlin/dartzee/screen/game/MatchSummaryPanel.kt index b576d08da..a413a69b5 100644 --- a/src/main/kotlin/dartzee/screen/game/MatchSummaryPanel.kt +++ b/src/main/kotlin/dartzee/screen/game/MatchSummaryPanel.kt @@ -10,22 +10,20 @@ import java.awt.BorderLayout import java.util.concurrent.CopyOnWriteArrayList /** - * The first tab displayed for any match. Provides a summary of the players' overall scores with (hopefully) nice graphs and stuff + * The first tab displayed for any match. Provides a summary of the players' overall scores with + * (hopefully) nice graphs and stuff */ -class MatchSummaryPanel>( +class MatchSummaryPanel>( val match: DartsMatchEntity, - private val statsPanel: AbstractGameStatisticsPanel) : PanelWithScorers(), - PlayerStateListener -{ + private val statsPanel: AbstractGameStatisticsPanel +) : PanelWithScorers(), PlayerStateListener { private val gameTabs = CopyOnWriteArrayList>() - init - { + init { panelCenter.add(statsPanel, BorderLayout.CENTER) } - fun addParticipant(localId: Long, state: PlayerState) - { + fun addParticipant(localId: Long, state: PlayerState) { val participant = state.wrappedParticipant val scorer = findOrAssignScorer(participant) @@ -35,17 +33,17 @@ class MatchSummaryPanel>( state.addListener(this) } - fun getAllParticipants(): List - { + fun getAllParticipants(): List { val states = gameTabs.map { it.getPlayerStates() }.flatten() return states.map { it.wrappedParticipant } } private fun findOrAssignScorer(participant: IWrappedParticipant) = - scorersOrdered.find { it.participant.getUniqueParticipantName() == participant.getUniqueParticipantName() } ?: assignScorer(participant) + scorersOrdered.find { + it.participant.getUniqueParticipantName() == participant.getUniqueParticipantName() + } ?: assignScorer(participant) - private fun updateStats() - { + private fun updateStats() { scorersOrdered.forEach { it.updateResult() } val states = gameTabs.map { it.getPlayerStates() }.flatten() @@ -54,13 +52,11 @@ class MatchSummaryPanel>( override fun factoryScorer(participant: IWrappedParticipant) = MatchScorer(participant, match) - fun addGameTab(tab: DartsGamePanel<*, PlayerState>) - { + fun addGameTab(tab: DartsGamePanel<*, PlayerState>) { gameTabs.add(tab) } - override fun stateChanged(state: PlayerState) - { + override fun stateChanged(state: PlayerState) { runOnEventThread { updateStats() } } } diff --git a/src/main/kotlin/dartzee/screen/game/PanelWithScorers.kt b/src/main/kotlin/dartzee/screen/game/PanelWithScorers.kt index 1eb8b3439..da98c409b 100644 --- a/src/main/kotlin/dartzee/screen/game/PanelWithScorers.kt +++ b/src/main/kotlin/dartzee/screen/game/PanelWithScorers.kt @@ -3,23 +3,22 @@ package dartzee.screen.game import dartzee.core.util.ceilDiv import dartzee.game.state.IWrappedParticipant import dartzee.screen.game.scorer.AbstractScorer -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import javax.swing.JPanel +import net.miginfocom.swing.MigLayout /** - * Represents a panel that has scorers on it, centralising the logic for laying them out and assigning players to them etc. + * Represents a panel that has scorers on it, centralising the logic for laying them out and + * assigning players to them etc. */ -abstract class PanelWithScorers : JPanel() -{ +abstract class PanelWithScorers : JPanel() { val panelEast = JPanel() val panelWest = JPanel() protected val panelCenter = JPanel() val scorersOrdered = mutableListOf() - init - { + init { layout = BorderLayout(0, 0) panelCenter.layout = BorderLayout(0, 0) @@ -28,13 +27,10 @@ abstract class PanelWithScorers : JPanel() add(panelWest, BorderLayout.WEST) } - /** - * Abstract methods - */ + /** Abstract methods */ protected abstract fun factoryScorer(participant: IWrappedParticipant): S - fun finaliseScorers(parentWindow: AbstractDartsGameScreen) - { + fun finaliseScorers(parentWindow: AbstractDartsGameScreen) { panelEast.removeAll() panelWest.removeAll() @@ -54,8 +50,7 @@ abstract class PanelWithScorers : JPanel() parentWindow.packIfNecessary() } - fun assignScorer(participant: IWrappedParticipant): S - { + fun assignScorer(participant: IWrappedParticipant): S { val scorer = factoryScorer(participant) scorer.init() scorersOrdered.add(scorer) diff --git a/src/main/kotlin/dartzee/screen/game/SegmentStatuses.kt b/src/main/kotlin/dartzee/screen/game/SegmentStatuses.kt index e53d47b89..75057f286 100644 --- a/src/main/kotlin/dartzee/screen/game/SegmentStatuses.kt +++ b/src/main/kotlin/dartzee/screen/game/SegmentStatuses.kt @@ -3,27 +3,31 @@ package dartzee.screen.game import dartzee.`object`.DartboardSegment enum class SegmentStatus { - SCORING, VALID, INVALID + SCORING, + VALID, + INVALID } -data class SegmentStatuses(val scoringSegments: Set, val validSegments: Set) -{ - constructor(scoringSegments: List, validSegments: List): this(scoringSegments.toSet(), validSegments.toSet()) +data class SegmentStatuses( + val scoringSegments: Set, + val validSegments: Set +) { + constructor( + scoringSegments: List, + validSegments: List + ) : this(scoringSegments.toSet(), validSegments.toSet()) fun allowsMissing() = validSegments.any { it.isMiss() } } -fun SegmentStatuses?.getSegmentStatus(segment: DartboardSegment): SegmentStatus -{ - if (this == null) - { +fun SegmentStatuses?.getSegmentStatus(segment: DartboardSegment): SegmentStatus { + if (this == null) { return SegmentStatus.SCORING } - return when - { + return when { scoringSegments.contains(segment) -> SegmentStatus.SCORING validSegments.contains(segment) -> SegmentStatus.VALID else -> SegmentStatus.INVALID } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeMatchScreen.kt b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeMatchScreen.kt index eddef2ce0..3346225b6 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeMatchScreen.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeMatchScreen.kt @@ -8,9 +8,14 @@ import dartzee.screen.game.DartsGamePanel.Companion.constructGamePanelDartzee import dartzee.screen.game.DartsMatchScreen import dartzee.screen.game.MatchSummaryPanel -class DartzeeMatchScreen(match: DartsMatchEntity): - DartsMatchScreen(MatchSummaryPanel(match, MatchStatisticsPanelDartzee()), match) -{ - override fun factoryGamePanel(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) = - constructGamePanelDartzee(parent, game, totalPlayers) -} \ No newline at end of file +class DartzeeMatchScreen(match: DartsMatchEntity) : + DartsMatchScreen( + MatchSummaryPanel(match, MatchStatisticsPanelDartzee()), + match + ) { + override fun factoryGamePanel( + parent: AbstractDartsGameScreen, + game: GameEntity, + totalPlayers: Int + ) = constructGamePanelDartzee(parent, game, totalPlayers) +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleCarousel.kt b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleCarousel.kt index 9a24cd5db..637617325 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleCarousel.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleCarousel.kt @@ -22,8 +22,8 @@ import javax.swing.JScrollPane import javax.swing.JToggleButton import javax.swing.ScrollPaneConstants -class DartzeeRuleCarousel(private val dtos: List): JPanel(), ActionListener, IMouseListener -{ +class DartzeeRuleCarousel(private val dtos: List) : + JPanel(), ActionListener, IMouseListener { val tilePanel = JPanel() private val tileScroller = JScrollPane() val toggleButtonPanel = JPanel() @@ -40,8 +40,7 @@ class DartzeeRuleCarousel(private val dtos: List): JPanel(), Act private var hoveredTile: DartzeeRuleTilePending? = null - init - { + init { layout = BorderLayout(0, 0) add(tileScroller, BorderLayout.CENTER) add(toggleButtonPanel, BorderLayout.EAST) @@ -72,8 +71,7 @@ class DartzeeRuleCarousel(private val dtos: List): JPanel(), Act toggleButtonPanel.add(toggleButtonComplete, BorderLayout.SOUTH) } - fun update(results: List, darts: List, currentScore: Int) - { + fun update(results: List, darts: List, currentScore: Int) { initialised = false hoveredTile = null @@ -82,16 +80,15 @@ class DartzeeRuleCarousel(private val dtos: List): JPanel(), Act initialiseTiles(results, currentScore) - when - { + when { toggleButtonComplete.isSelected -> displayTiles(completeTiles) else -> displayTiles(pendingTiles) } initialised = true } - private fun initialiseTiles(results: List, currentScore: Int) - { + + private fun initialiseTiles(results: List, currentScore: Int) { completeTiles.clear() pendingTiles.clear() @@ -101,30 +98,24 @@ class DartzeeRuleCarousel(private val dtos: List): JPanel(), Act updateIncompleteTilesBasedOnDarts(currentScore) } - private fun populateCompleteTiles(results: List) - { - results.sortedBy { it.roundNumber }.forEach { result -> - val dto = dtos[result.ruleNumber - 1] - val completeRule = DartzeeRuleTileComplete( - dto, - getRuleNumber(dto), - result.success, - result.score - ) - completeTiles.add(completeRule) - } + private fun populateCompleteTiles(results: List) { + results + .sortedBy { it.roundNumber } + .forEach { result -> + val dto = dtos[result.ruleNumber - 1] + val completeRule = + DartzeeRuleTileComplete(dto, getRuleNumber(dto), result.success, result.score) + completeTiles.add(completeRule) + } toggleButtonComplete.isEnabled = completeTiles.isNotEmpty() } - private fun populateIncompleteTiles(results: List) - { - val incompleteRules = dtos.filterIndexed { ix, _ -> results.none { it.ruleNumber == ix + 1 }} - pendingTiles.addAll(incompleteRules.map { rule -> - DartzeeRuleTilePending( - rule, - getRuleNumber(rule) - ) - }) + private fun populateIncompleteTiles(results: List) { + val incompleteRules = + dtos.filterIndexed { ix, _ -> results.none { it.ruleNumber == ix + 1 } } + pendingTiles.addAll( + incompleteRules.map { rule -> DartzeeRuleTilePending(rule, getRuleNumber(rule)) } + ) pendingTiles.forEach { tile -> tile.addActionListener(this) tile.addMouseListener(this) @@ -132,19 +123,17 @@ class DartzeeRuleCarousel(private val dtos: List): JPanel(), Act } } - private fun updateIncompleteTilesBasedOnDarts(currentScore: Int) - { - if (dartsThrown.size == 3) - { + private fun updateIncompleteTilesBasedOnDarts(currentScore: Int) { + if (dartsThrown.size == 3) { val successfulRules = pendingTiles.filter { it.isVisible } - successfulRules.forEach { it.setPendingResult(true, it.dto.getSuccessTotal(dartsThrown)) } + successfulRules.forEach { + it.setPendingResult(true, it.dto.getSuccessTotal(dartsThrown)) + } } - if (pendingTiles.none { it.isVisible }) - { + if (pendingTiles.none { it.isVisible }) { val ruleToFail = getFirstIncompleteRule() - if (ruleToFail != null) - { + if (ruleToFail != null) { val score = currentScore.ceilDiv(2) - currentScore ruleToFail.isVisible = true ruleToFail.setPendingResult(false, score) @@ -156,34 +145,33 @@ class DartzeeRuleCarousel(private val dtos: List): JPanel(), Act private fun getFirstIncompleteRule(): DartzeeRuleTilePending? = pendingTiles.firstOrNull() - fun getSegmentStatus(): SegmentStatuses - { + fun getSegmentStatus(): SegmentStatuses { val statuses = pendingTiles.map { it.getSegmentStatus(dartsThrown) } - return SegmentStatuses(statuses.flatMap { it.scoringSegments }, statuses.flatMap { it.validSegments }) + return SegmentStatuses( + statuses.flatMap { it.scoringSegments }, + statuses.flatMap { it.validSegments } + ) } fun getAvailableRuleTiles() = pendingTiles.filter { it.isVisible } - fun selectRule(model: DartsAiModel) - { + fun selectRule(model: DartsAiModel) { val aggressive = model.dartzeePlayStyle == DartzeePlayStyle.AGGRESSIVE val availableTiles = getAvailableRuleTiles() - val selectedTile = if (aggressive) - { - val sortedTiles = availableTiles.sortedWith(compareBy( { it.pendingScore }, { it.ruleNumber })) - sortedTiles.last() - } - else - { - availableTiles.maxByOrNull { it.ruleNumber } - } + val selectedTile = + if (aggressive) { + val sortedTiles = + availableTiles.sortedWith(compareBy({ it.pendingScore }, { it.ruleNumber })) + sortedTiles.last() + } else { + availableTiles.maxByOrNull { it.ruleNumber } + } selectedTile!!.doClick() } - private fun displayTiles(tiles: List) - { + private fun displayTiles(tiles: List) { tilePanel.removeAll() tiles.forEach { tilePanel.add(it) } tilePanel.validate() @@ -192,45 +180,39 @@ class DartzeeRuleCarousel(private val dtos: List): JPanel(), Act tileScroller.repaint() } - fun gameFinished() - { + fun gameFinished() { toggleButtonComplete.isSelected = true displayTiles(completeTiles) toggleButtonPanel.isVisible = false } - override fun actionPerformed(e: ActionEvent?) - { - when (val src = e?.source) - { + override fun actionPerformed(e: ActionEvent?) { + when (val src = e?.source) { toggleButtonPending -> displayTiles(pendingTiles) toggleButtonComplete -> displayTiles(completeTiles) is DartzeeRuleTilePending -> tilePressed(src) } } - private fun tilePressed(tile: DartzeeRuleTilePending) - { + private fun tilePressed(tile: DartzeeRuleTilePending) { if (tile.pendingResult != null) { - val result = DartzeeRoundResult(tile.ruleNumber, tile.pendingResult!!, tile.pendingScore!!) + val result = + DartzeeRoundResult(tile.ruleNumber, tile.pendingResult!!, tile.pendingScore!!) listener?.tilePressed(result) } } - override fun mouseEntered(e: MouseEvent) - { + override fun mouseEntered(e: MouseEvent) { val src = e.source - if (src is DartzeeRuleTilePending) - { + if (src is DartzeeRuleTilePending) { hoveredTile = src listener?.hoverChanged(src.getSegmentStatus(dartsThrown)) } } - override fun mouseExited(e: MouseEvent) - { + override fun mouseExited(e: MouseEvent) { hoveredTile = null listener?.hoverChanged(getSegmentStatus()) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleSummaryPanel.kt b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleSummaryPanel.kt index 906783d60..13c3c72b1 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleSummaryPanel.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleSummaryPanel.kt @@ -14,13 +14,11 @@ import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants -class DartzeeRuleSummaryPanel(private val carousel: DartzeeRuleCarousel): JPanel() -{ +class DartzeeRuleSummaryPanel(private val carousel: DartzeeRuleCarousel) : JPanel() { private val lblHighScore = JLabel() val panelHighScore = JPanel() - init - { + init { layout = BorderLayout(0, 0) preferredSize = Dimension(150, 120) @@ -33,23 +31,22 @@ class DartzeeRuleSummaryPanel(private val carousel: DartzeeRuleCarousel): JPanel add(panelHighScore) } - fun update(results: List, darts: List, currentScore: Int, roundNumber: Int) - { - if (roundNumber == 1) - { + fun update( + results: List, + darts: List, + currentScore: Int, + roundNumber: Int + ) { + if (roundNumber == 1) { swapInComponentIfNecessary(panelHighScore) - } - else - { + } else { swapInComponentIfNecessary(carousel) carousel.update(results, darts, currentScore) } } - private fun swapInComponentIfNecessary(c: Component) - { - if (components.contains(c)) - { + private fun swapInComponentIfNecessary(c: Component) { + if (components.contains(c)) { return } @@ -61,27 +58,23 @@ class DartzeeRuleSummaryPanel(private val carousel: DartzeeRuleCarousel): JPanel } fun getSegmentStatus(): SegmentStatuses = - when - { - components.contains(panelHighScore) -> SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) + when { + components.contains(panelHighScore) -> + SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) else -> carousel.getSegmentStatus() } - fun ensureReady() - { - while (!carousel.initialised) - { + fun ensureReady() { + while (!carousel.initialised) { Thread.sleep(200) } } - fun selectRule(model: DartsAiModel) - { + fun selectRule(model: DartsAiModel) { carousel.selectRule(model) } - fun gameFinished() - { + fun gameFinished() { swapInComponentIfNecessary(carousel) carousel.gameFinished() } diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTile.kt b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTile.kt index 57e89d7bc..47ee13e8e 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTile.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTile.kt @@ -3,16 +3,15 @@ package dartzee.screen.game.dartzee import dartzee.bean.IMouseListener import dartzee.core.util.setFontSize import dartzee.dartzee.DartzeeRuleDto -import org.jfree.chart.imagemap.ImageMapUtils import java.awt.Dimension import java.awt.event.MouseEvent import javax.swing.JButton import kotlin.math.abs +import org.jfree.chart.imagemap.ImageMapUtils -abstract class DartzeeRuleTile(val dto: DartzeeRuleDto, val ruleNumber: Int): JButton(), IMouseListener -{ - init - { +abstract class DartzeeRuleTile(val dto: DartzeeRuleDto, val ruleNumber: Int) : + JButton(), IMouseListener { + init { preferredSize = Dimension(150, 80) text = getButtonText(false) @@ -21,26 +20,23 @@ abstract class DartzeeRuleTile(val dto: DartzeeRuleDto, val ruleNumber: Int): JB abstract fun getScoreForHover(): Int? - private fun getButtonText(hovered: Boolean = false): String - { + private fun getButtonText(hovered: Boolean = false): String { val ruleDesc = ImageMapUtils.htmlEscape(dto.generateRuleDescription()) val ruleNameOrDesc = dto.ruleName?.let { ImageMapUtils.htmlEscape(it) } ?: ruleDesc - val nonHoverHtml = "
#$ruleNumber

$ruleNameOrDesc
" + val nonHoverHtml = + "
#$ruleNumber

$ruleNameOrDesc
" val hoverHtml = "
#$ruleNumber

$ruleDesc
" val scoreHtml = "
${getScoreText()}
" - return when - { + return when { hovered && getScoreForHover() != null -> scoreHtml hovered -> hoverHtml else -> nonHoverHtml } } - - private fun getScoreText(): String - { + private fun getScoreText(): String { val score = getScoreForHover() ?: return "" val prefix = if (score > 0) "+" else "-" @@ -48,8 +44,7 @@ abstract class DartzeeRuleTile(val dto: DartzeeRuleDto, val ruleNumber: Int): JB return "$prefix ${abs(score)}" } - override fun mouseEntered(e: MouseEvent) - { + override fun mouseEntered(e: MouseEvent) { text = getButtonText(true) if (getScoreForHover() != null) { @@ -57,9 +52,8 @@ abstract class DartzeeRuleTile(val dto: DartzeeRuleDto, val ruleNumber: Int): JB } } - override fun mouseExited(e: MouseEvent) - { + override fun mouseExited(e: MouseEvent) { text = getButtonText() setFontSize(12) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTileComplete.kt b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTileComplete.kt index fa1643296..ad55ddb9a 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTileComplete.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTileComplete.kt @@ -4,10 +4,13 @@ import dartzee.dartzee.DartzeeRuleDto import dartzee.utils.setColoursForDartzeeResult import javax.swing.DefaultButtonModel -class DartzeeRuleTileComplete(dto: DartzeeRuleDto, ruleNumber: Int, success: Boolean, val score: Int): DartzeeRuleTile(dto, ruleNumber) -{ - init - { +class DartzeeRuleTileComplete( + dto: DartzeeRuleDto, + ruleNumber: Int, + success: Boolean, + val score: Int +) : DartzeeRuleTile(dto, ruleNumber) { + init { model = SoftDisableButtonModel() isFocusable = false @@ -17,8 +20,8 @@ class DartzeeRuleTileComplete(dto: DartzeeRuleDto, ruleNumber: Int, success: Boo override fun getScoreForHover() = score } -class SoftDisableButtonModel : DefaultButtonModel() -{ +class SoftDisableButtonModel : DefaultButtonModel() { override fun isPressed() = false + override fun isRollover() = false -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTilePending.kt b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTilePending.kt index f2cc5ca59..4b9bc3fc3 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTilePending.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/DartzeeRuleTilePending.kt @@ -6,13 +6,12 @@ import dartzee.screen.game.SegmentStatuses import dartzee.utils.InjectedThings import dartzee.utils.setColoursForDartzeeResult -class DartzeeRuleTilePending(dto: DartzeeRuleDto, ruleNumber: Int): DartzeeRuleTile(dto, ruleNumber) -{ +class DartzeeRuleTilePending(dto: DartzeeRuleDto, ruleNumber: Int) : + DartzeeRuleTile(dto, ruleNumber) { var pendingResult: Boolean? = null var pendingScore: Int? = null - fun setPendingResult(success: Boolean, score: Int) - { + fun setPendingResult(success: Boolean, score: Int) { pendingResult = success pendingScore = score @@ -21,16 +20,16 @@ class DartzeeRuleTilePending(dto: DartzeeRuleDto, ruleNumber: Int): DartzeeRuleT setColoursForDartzeeResult(success) } - fun updateState(darts: List) - { + fun updateState(darts: List) { isVisible = getSegmentStatus(darts).validSegments.isNotEmpty() } - fun getSegmentStatus(darts: List): SegmentStatuses - { - val result = if (darts.isEmpty()) dto.calculationResult!! else InjectedThings.dartzeeCalculator.getValidSegments(dto, darts) + fun getSegmentStatus(darts: List): SegmentStatuses { + val result = + if (darts.isEmpty()) dto.calculationResult!! + else InjectedThings.dartzeeCalculator.getValidSegments(dto, darts) return result.getSegmentStatus() } override fun getScoreForHover() = pendingScore -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/GamePanelDartzee.kt b/src/main/kotlin/dartzee/screen/game/dartzee/GamePanelDartzee.kt index 52bfec24b..74e2d81b2 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/GamePanelDartzee.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/GamePanelDartzee.kt @@ -27,20 +27,21 @@ import java.awt.event.ActionEvent import javax.swing.ImageIcon import javax.swing.JButton -class GamePanelDartzee(parent: AbstractDartsGameScreen, - game: GameEntity, - totalPlayers: Int, - private val dtos: List, - private val summaryPanel: DartzeeRuleSummaryPanel -) : GamePanelFixedLength(parent, game, totalPlayers), - IDartzeeCarouselListener -{ +class GamePanelDartzee( + parent: AbstractDartsGameScreen, + game: GameEntity, + totalPlayers: Int, + private val dtos: List, + private val summaryPanel: DartzeeRuleSummaryPanel +) : + GamePanelFixedLength(parent, game, totalPlayers), + IDartzeeCarouselListener { override val totalRounds = dtos.size + 1 private val btnConvertToTemplate = JButton("") - init - { - btnConvertToTemplate.icon = ImageIcon(javaClass.getResource("/buttons/dartzeeTemplates.png")) + init { + btnConvertToTemplate.icon = + ImageIcon(javaClass.getResource("/buttons/dartzeeTemplates.png")) btnConvertToTemplate.name = "convertToTemplate" btnConvertToTemplate.preferredSize = Dimension(80, 80) btnConvertToTemplate.toolTipText = "Generate template from game" @@ -55,12 +56,9 @@ class GamePanelDartzee(parent: AbstractDartsGameScreen, override fun factoryState(pt: IWrappedParticipant) = DartzeePlayerState(pt) override fun computeAiDart(model: DartsAiModel) = - if (isScoringRound()) - { + if (isScoringRound()) { model.throwScoringDart() - } - else - { + } else { summaryPanel.ensureReady() val segmentStatus = summaryPanel.getSegmentStatus() @@ -69,31 +67,30 @@ class GamePanelDartzee(parent: AbstractDartsGameScreen, override fun colourWrapper() = DEFAULT_COLOUR_WRAPPER - override fun setGameReadOnly() - { + override fun setGameReadOnly() { super.setGameReadOnly() summaryPanel.gameFinished() scorerSelected(scorersOrdered.first()) } - override fun loadAdditionalEntities(state: DartzeePlayerState) - { + override fun loadAdditionalEntities(state: DartzeePlayerState) { val individuals = state.wrappedParticipant.individuals val playerIds = individuals.getQuotedIdStr { it.playerId } val ptIds = individuals.getQuotedIdStr { it.rowId } - val roundResults = DartzeeRoundResultEntity().retrieveEntities("PlayerId IN $playerIds AND ParticipantId IN $ptIds").sortedBy { it.roundNumber } + val roundResults = + DartzeeRoundResultEntity() + .retrieveEntities("PlayerId IN $playerIds AND ParticipantId IN $ptIds") + .sortedBy { it.roundNumber } roundResults.forEach { state.addRoundResult(it) } } - override fun updateVariablesForDartThrown(dart: Dart) - { + override fun updateVariablesForDartThrown(dart: Dart) { updateCarouselAndDartboard() } - override fun shouldStopAfterDartThrown(): Boolean - { + override fun shouldStopAfterDartThrown(): Boolean { val segmentStatus = summaryPanel.getSegmentStatus() val failedAllRules = segmentStatus.validSegments.isEmpty() return dartsThrownCount() == 3 || failedAllRules @@ -101,27 +98,24 @@ class GamePanelDartzee(parent: AbstractDartsGameScreen, override fun shouldAIStop() = false - override fun readyForThrow() - { + override fun readyForThrow() { super.readyForThrow() updateCarouselAndDartboard() - if (!isScoringRound()) - { + if (!isScoringRound()) { btnConfirm.isVisible = false } } - private fun updateCarouselAndDartboard() - { + private fun updateCarouselAndDartboard() { runOnEventThreadBlocking { updateCarousel() dartboard.refreshValidSegments(summaryPanel.getSegmentStatus()) } } - private fun updateCarousel() - { + + private fun updateCarousel() { val ruleResults = getCurrentPlayerState().roundResults val lastRoundScore = getCurrentPlayerState().getCumulativeScore(currentRoundNumber - 1) summaryPanel.update(ruleResults, getDartsThrown(), lastRoundScore, currentRoundNumber) @@ -130,25 +124,19 @@ class GamePanelDartzee(parent: AbstractDartsGameScreen, /** * Hook called from the confirm button, which is only available for the initial high score round */ - override fun saveDartsAndProceed() - { - if (isScoringRound()) - { + override fun saveDartsAndProceed() { + if (isScoringRound()) { completeRound(factoryHighScoreResult(getDartsThrown())) - } - else - { - //AI has finished a Dartzee round + } else { + // AI has finished a Dartzee round summaryPanel.selectRule(getCurrentPlayerStrategy()) } } private fun isScoringRound() = currentRoundNumber == 1 - private fun completeRound(result: DartzeeRoundResult) - { - if (!isScoringRound()) - { + private fun completeRound(result: DartzeeRoundResult) { + if (!isScoringRound()) { getCurrentPlayerState().saveRoundResult(result) } @@ -159,92 +147,105 @@ class GamePanelDartzee(parent: AbstractDartsGameScreen, finishRound() - if (gameEntity.isFinished()) - { + if (gameEntity.isFinished()) { gameFinished() } } - private fun gameFinished() - { + private fun gameFinished() { summaryPanel.gameFinished() dartboard.refreshValidSegments(null) updateCarousel() } - override fun updateAchievementsForFinish(playerState: DartzeePlayerState, finishingPosition: Int, score: Int) - { + override fun updateAchievementsForFinish( + playerState: DartzeePlayerState, + finishingPosition: Int, + score: Int + ) { super.updateAchievementsForFinish(playerState, finishingPosition, score) - if (totalRounds < DARTZEE_ACHIEVEMENT_MIN_ROUNDS) - { + if (totalRounds < DARTZEE_ACHIEVEMENT_MIN_ROUNDS) { return } val playerId = playerState.lastIndividual().playerId - if (!playerState.hasMultiplePlayers()) - { + if (!playerState.hasMultiplePlayers()) { val scorePerRound = score / totalRounds - AchievementEntity.updateAchievement(AchievementType.DARTZEE_BEST_GAME, playerId, gameEntity.rowId, scorePerRound) - - if (playerState.roundResults.all { it.success }) - { + AchievementEntity.updateAchievement( + AchievementType.DARTZEE_BEST_GAME, + playerId, + gameEntity.rowId, + scorePerRound + ) + + if (playerState.roundResults.all { it.success }) { val templateName = GameType.DARTZEE.getParamsDescription(gameEntity.gameParams) - AchievementEntity.insertAchievement(AchievementType.DARTZEE_FLAWLESS, playerId, gameEntity.rowId, templateName, score) + AchievementEntity.insertAchievement( + AchievementType.DARTZEE_FLAWLESS, + playerId, + gameEntity.rowId, + templateName, + score + ) } - AchievementEntity.insertForUniqueCounter(AchievementType.DARTZEE_BINGO, playerId, gameEntity.rowId, score % 100, "$score") + AchievementEntity.insertForUniqueCounter( + AchievementType.DARTZEE_BINGO, + playerId, + gameEntity.rowId, + score % 100, + "$score" + ) } val lastRoundResult = playerState.roundResults.last() - if (lastRoundResult.success && lastRoundResult.ruleNumber == dtos.size) - { + if (lastRoundResult.success && lastRoundResult.ruleNumber == dtos.size) { val ruleDescription = dtos.last().getDisplayName() - AchievementEntity.insertAchievement(AchievementType.DARTZEE_UNDER_PRESSURE, playerId, gameEntity.rowId, ruleDescription, lastRoundResult.score) + AchievementEntity.insertAchievement( + AchievementType.DARTZEE_UNDER_PRESSURE, + playerId, + gameEntity.rowId, + ruleDescription, + lastRoundResult.score + ) } } override fun factoryStatsPanel(gameParams: String) = GameStatisticsPanelDartzee() - override fun factoryScorer(participant: IWrappedParticipant) = DartsScorerDartzee(this, participant) - override fun hoverChanged(segmentStatuses: SegmentStatuses) - { - if (dartsThrownCount() < 3) - { + override fun factoryScorer(participant: IWrappedParticipant) = + DartsScorerDartzee(this, participant) + + override fun hoverChanged(segmentStatuses: SegmentStatuses) { + if (dartsThrownCount() < 3) { dartboard.refreshValidSegments(segmentStatuses) } } - override fun tilePressed(dartzeeRoundResult: DartzeeRoundResult) - { + override fun tilePressed(dartzeeRoundResult: DartzeeRoundResult) { completeRound(dartzeeRoundResult) } - fun scorerSelected(selectedScorer: DartsScorerDartzee) - { + fun scorerSelected(selectedScorer: DartsScorerDartzee) { currentPlayerNumber = getPlayerNumberForScorer(selectedScorer) - scorersOrdered.forEach { scorer -> - scorer.togglePostGame(scorer == selectedScorer) - } + scorersOrdered.forEach { scorer -> scorer.togglePostGame(scorer == selectedScorer) } updateCarousel() } - private fun generateTemplate() - { + private fun generateTemplate() { generateDartzeeTemplateFromGame(gameEntity, dtos) ?: return btnConvertToTemplate.isVisible = false parentWindow.title = makeGameTitle() } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnConvertToTemplate -> generateTemplate() else -> super.actionPerformed(arg0) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/GameStatisticsPanelDartzee.kt b/src/main/kotlin/dartzee/screen/game/dartzee/GameStatisticsPanelDartzee.kt index 2df498e88..f763b6d89 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/GameStatisticsPanelDartzee.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/GameStatisticsPanelDartzee.kt @@ -9,10 +9,8 @@ import dartzee.game.UniqueParticipantName import dartzee.game.state.DartzeePlayerState import dartzee.screen.game.AbstractGameStatisticsPanel -open class GameStatisticsPanelDartzee: AbstractGameStatisticsPanel() -{ - override fun addRowsToTable() - { +open class GameStatisticsPanelDartzee : AbstractGameStatisticsPanel() { + override fun addRowsToTable() { addRow(getPeakScoreRow()) addRow(getScoreRow("Highest Round") { it.maxOrZero() }) addRow(getScoreRow("Avg Round") { MathsUtil.round(it.average(), 1) }) @@ -22,39 +20,54 @@ open class GameStatisticsPanelDartzee: AbstractGameStatisticsPanel() + override fun getHistogramRows() = emptyList() + override fun getStartOfSectionRows() = listOf("Longest Streak") private fun getPeakScoreRow() = prepareRow("Peak Score", ::getPeakScore) - private fun getPeakScore(playerName: UniqueParticipantName): Any? - { + + private fun getPeakScore(playerName: UniqueParticipantName): Any? { val states = hmPlayerToStates[playerName] ?: return null return states.mapNotNull { it.getPeakScore() }.maxOrNull() } - private fun getScoreRow(desc: String, f: (i: List) -> Number) = prepareRow(desc) { playerName -> - val results = getRoundResults(playerName).flatten() - val scores = results.map { it.score } + private fun getScoreRow(desc: String, f: (i: List) -> Number) = + prepareRow(desc) { playerName -> + val results = getRoundResults(playerName).flatten() + val scores = results.map { it.score } - if (scores.isEmpty()) null else f(scores) - } + if (scores.isEmpty()) null else f(scores) + } - private fun getLongestStreakRow() = prepareRow("Longest Streak") { playerName -> - val allResults = getRoundResults(playerName) + private fun getLongestStreakRow() = + prepareRow("Longest Streak") { playerName -> + val allResults = getRoundResults(playerName) - allResults.maxOfOrNull { results -> results.getLongestStreak { it.success }.size } - } + allResults.maxOfOrNull { results -> results.getLongestStreak { it.success }.size } + } - private fun getHardestRuleRow() = prepareRow("Hardest Rule") { playerName -> - val allResults = getRoundResults(playerName).flatten() - allResults.filter { it.success }.maxOfOrNull { it.ruleNumber } - } + private fun getHardestRuleRow() = + prepareRow("Hardest Rule") { playerName -> + val allResults = getRoundResults(playerName).flatten() + allResults.filter { it.success }.maxOfOrNull { it.ruleNumber } + } - private fun getRoundResults(playerName: UniqueParticipantName): List> - { + private fun getRoundResults( + playerName: UniqueParticipantName + ): List> { val states = hmPlayerToStates[playerName] return states?.map { it.roundResults }.orEmpty() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/IDartzeeCarouselListener.kt b/src/main/kotlin/dartzee/screen/game/dartzee/IDartzeeCarouselListener.kt index 6da22e335..bb2558831 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/IDartzeeCarouselListener.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/IDartzeeCarouselListener.kt @@ -3,8 +3,8 @@ package dartzee.screen.game.dartzee import dartzee.dartzee.DartzeeRoundResult import dartzee.screen.game.SegmentStatuses -interface IDartzeeCarouselListener -{ +interface IDartzeeCarouselListener { fun hoverChanged(segmentStatuses: SegmentStatuses) + fun tilePressed(dartzeeRoundResult: DartzeeRoundResult) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/dartzee/MatchStatisticsPanelDartzee.kt b/src/main/kotlin/dartzee/screen/game/dartzee/MatchStatisticsPanelDartzee.kt index e54c4c21c..1d30dd260 100644 --- a/src/main/kotlin/dartzee/screen/game/dartzee/MatchStatisticsPanelDartzee.kt +++ b/src/main/kotlin/dartzee/screen/game/dartzee/MatchStatisticsPanelDartzee.kt @@ -2,10 +2,8 @@ package dartzee.screen.game.dartzee import dartzee.core.util.maxOrZero -class MatchStatisticsPanelDartzee: GameStatisticsPanelDartzee() -{ - override fun addRowsToTable() - { +class MatchStatisticsPanelDartzee : GameStatisticsPanelDartzee() { + override fun addRowsToTable() { super.addRowsToTable() addRow(getBestGameRow { it.maxOrZero() }) @@ -13,5 +11,7 @@ class MatchStatisticsPanelDartzee: GameStatisticsPanelDartzee() } override fun getStartOfSectionRows() = super.getStartOfSectionRows() + "Best Game" - override fun getRankedRowsHighestWins() = super.getRankedRowsHighestWins() + "Best Game" + "Avg Game" -} \ No newline at end of file + + override fun getRankedRowsHighestWins() = + super.getRankedRowsHighestWins() + "Best Game" + "Avg Game" +} diff --git a/src/main/kotlin/dartzee/screen/game/golf/GamePanelGolf.kt b/src/main/kotlin/dartzee/screen/game/golf/GamePanelGolf.kt index eb549204f..fb5665dd5 100644 --- a/src/main/kotlin/dartzee/screen/game/golf/GamePanelGolf.kt +++ b/src/main/kotlin/dartzee/screen/game/golf/GamePanelGolf.kt @@ -14,43 +14,35 @@ import dartzee.screen.game.GamePanelFixedLength import dartzee.screen.game.scorer.DartsScorerGolf class GamePanelGolf(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) : - GamePanelFixedLength(parent, game, totalPlayers) -{ - //Number of rounds - 9 holes or 18? + GamePanelFixedLength(parent, game, totalPlayers) { + // Number of rounds - 9 holes or 18? override val totalRounds = Integer.parseInt(game.gameParams) override fun factoryState(pt: IWrappedParticipant) = GolfPlayerState(pt) - private fun getScoreForMostRecentDart() : Int - { + private fun getScoreForMostRecentDart(): Int { val lastDart = getDartsThrown().last() val targetHole = currentRoundNumber return lastDart.getGolfScore(targetHole) } - override fun computeAiDart(model: DartsAiModel): ComputedPoint - { + override fun computeAiDart(model: DartsAiModel): ComputedPoint { val targetHole = currentRoundNumber val dartNo = dartsThrownCount() + 1 return model.throwGolfDart(targetHole, dartNo) } - override fun shouldStopAfterDartThrown(): Boolean - { + override fun shouldStopAfterDartThrown(): Boolean { val dartsThrownCount = dartsThrownCount() - if (dartsThrownCount == 3) - { + if (dartsThrownCount == 3) { return true } val score = getScoreForMostRecentDart() - if (getCurrentPlayerState().isHuman()) - { + if (getCurrentPlayerState().isHuman()) { return score == 1 - } - else - { + } else { val model = getCurrentPlayerStrategy() val stopThreshold = model.getStopThresholdForDartNo(dartsThrownCount) @@ -58,47 +50,71 @@ class GamePanelGolf(parent: AbstractDartsGameScreen, game: GameEntity, totalPlay } } - override fun saveDartsAndProceed() - { + override fun saveDartsAndProceed() { unlockAchievements() commitRound() finishRound() } - override fun updateAchievementsForFinish(playerState: GolfPlayerState, finishingPosition: Int, score: Int) - { + override fun updateAchievementsForFinish( + playerState: GolfPlayerState, + finishingPosition: Int, + score: Int + ) { super.updateAchievementsForFinish(playerState, finishingPosition, score) - if (!playerState.hasMultiplePlayers()) - { + if (!playerState.hasMultiplePlayers()) { val scores = playerState.completedRounds.map { it.last().getGolfScore() } - if (scores.size == 18 && scores.none { it == 5 }) - { - AchievementEntity.insertAchievement(AchievementType.GOLF_IN_BOUNDS, getCurrentPlayerId(), getGameId(), "$score") + if (scores.size == 18 && scores.none { it == 5 }) { + AchievementEntity.insertAchievement( + AchievementType.GOLF_IN_BOUNDS, + getCurrentPlayerId(), + getGameId(), + "$score" + ) } } } - private fun unlockAchievements() - { + private fun unlockAchievements() { val size = getDartsThrown().size val dartsRisked = getDartsThrown().subList(0, size - 1) val pointsRisked = dartsRisked.sumOf { 5 - it.getGolfScore(currentRoundNumber) } - if (pointsRisked > 0) - { - AchievementEntity.insertAchievementWithCounter(AchievementType.GOLF_POINTS_RISKED, getCurrentPlayerId(), gameEntity.rowId, "$currentRoundNumber", pointsRisked) + if (pointsRisked > 0) { + AchievementEntity.insertAchievementWithCounter( + AchievementType.GOLF_POINTS_RISKED, + getCurrentPlayerId(), + gameEntity.rowId, + "$currentRoundNumber", + pointsRisked + ) } - if (getDartsThrown().last().getGolfScore(currentRoundNumber) == 1) - { - if (retrieveAchievementForDetail(AchievementType.GOLF_COURSE_MASTER, getCurrentPlayerId(), "$currentRoundNumber") == null) { - AchievementEntity.insertAchievement(AchievementType.GOLF_COURSE_MASTER, getCurrentPlayerId(), getGameId(), "$currentRoundNumber") + if (getDartsThrown().last().getGolfScore(currentRoundNumber) == 1) { + if ( + retrieveAchievementForDetail( + AchievementType.GOLF_COURSE_MASTER, + getCurrentPlayerId(), + "$currentRoundNumber" + ) == null + ) { + AchievementEntity.insertAchievement( + AchievementType.GOLF_COURSE_MASTER, + getCurrentPlayerId(), + getGameId(), + "$currentRoundNumber" + ) } val holeInOneCount = getCurrentPlayerState().countHoleInOnes() - AchievementEntity.updateAchievement(AchievementType.GOLF_ONE_HIT_WONDER, getCurrentPlayerId(), getGameId(), holeInOneCount) + AchievementEntity.updateAchievement( + AchievementType.GOLF_ONE_HIT_WONDER, + getCurrentPlayerId(), + getGameId(), + holeInOneCount + ) } } @@ -106,8 +122,7 @@ class GamePanelGolf(parent: AbstractDartsGameScreen, game: GameEntity, totalPlay override fun shouldAIStop() = false - override fun doMissAnimation() - { + override fun doMissAnimation() { dartboard.doGolfMiss() } diff --git a/src/main/kotlin/dartzee/screen/game/golf/GameStatisticsPanelGolf.kt b/src/main/kotlin/dartzee/screen/game/golf/GameStatisticsPanelGolf.kt index fc7a0556d..f0eb5b8e8 100644 --- a/src/main/kotlin/dartzee/screen/game/golf/GameStatisticsPanelGolf.kt +++ b/src/main/kotlin/dartzee/screen/game/golf/GameStatisticsPanelGolf.kt @@ -6,16 +6,18 @@ import dartzee.game.state.GolfPlayerState import dartzee.`object`.Dart import dartzee.screen.game.AbstractGameStatisticsPanel -open class GameStatisticsPanelGolf: AbstractGameStatisticsPanel() -{ +open class GameStatisticsPanelGolf : AbstractGameStatisticsPanel() { override fun getRankedRowsHighestWins() = listOf("Points Improved") - override fun getRankedRowsLowestWins() = listOf("Best Hole", "Avg. Hole", "Worst Hole", "Miss %", "Points Squandered") + + override fun getRankedRowsLowestWins() = + listOf("Best Hole", "Avg. Hole", "Worst Hole", "Miss %", "Points Squandered") + override fun getHistogramRows() = listOf("1", "2", "3", "4", "5") + override fun getStartOfSectionRows() = listOf("Points Squandered", "1", "Best Game") - override fun addRowsToTable() - { - addRow(getScoreRow("Best Hole") { it.minOrNull() } ) + override fun addRowsToTable() { + addRow(getScoreRow("Best Hole") { it.minOrNull() }) addRow(getScoreRow("Avg. Hole") { MathsUtil.round(it.average(), 2) }) addRow(getScoreRow("Worst Hole") { it.maxOrNull() }) addRow(getMissesRow()) @@ -31,66 +33,60 @@ open class GameStatisticsPanelGolf: AbstractGameStatisticsPanel table.setColumnWidths("150") } - private fun getMissesRow() = prepareRow("Miss %") { playerName -> - val darts = getFlattenedDarts(playerName) - val missDarts = darts.filter { d -> d.getGolfScore() == 5 } - MathsUtil.getPercentage(missDarts.size, darts.size) - } + private fun getMissesRow() = + prepareRow("Miss %") { playerName -> + val darts = getFlattenedDarts(playerName) + val missDarts = darts.filter { d -> d.getGolfScore() == 5 } + MathsUtil.getPercentage(missDarts.size, darts.size) + } - /** - * Any round where you could have "banked" and ended on something higher. - */ - private fun getGambleRow(f: (rnd: List) -> Int, desc: String) = prepareRow(desc) { playerName -> - val rounds = hmPlayerToDarts[playerName].orEmpty() - rounds.sumOf { f(it) } - } + /** Any round where you could have "banked" and ended on something higher. */ + private fun getGambleRow(f: (rnd: List) -> Int, desc: String) = + prepareRow(desc) { playerName -> + val rounds = hmPlayerToDarts[playerName].orEmpty() + rounds.sumOf { f(it) } + } - private fun getPointsSquandered(round: List): Int - { + private fun getPointsSquandered(round: List): Int { val finalScore = round.last().getGolfScore() val bestScore = round.minOfOrNull { it.getGolfScore() } ?: finalScore return finalScore - bestScore } - private fun getPointsImproved(round: List): Int - { + private fun getPointsImproved(round: List): Int { val finalScore = round.last().getGolfScore() val bestScore = round.minOfOrNull { d -> d.getGolfScore() } ?: finalScore - //This round is stuffed - points have been squandered, not gained! Or it's just 1 dart! - if (finalScore > bestScore || round.size == 1) - { + // This round is stuffed - points have been squandered, not gained! Or it's just 1 dart! + if (finalScore > bestScore || round.size == 1) { return 0 } - //Filter out the 5s - they're not interesting. + // Filter out the 5s - they're not interesting. val roundWithoutMisses = round.filter { d -> d.getGolfScore() < 5 } - if (roundWithoutMisses.isEmpty()) - { - //Round is all misses, so nothing to do + if (roundWithoutMisses.isEmpty()) { + // Round is all misses, so nothing to do return 0 } - //Now get the first non-5. Result is the difference between this and where you ended up. + // Now get the first non-5. Result is the difference between this and where you ended up. val gambledScore = roundWithoutMisses.first().getGolfScore() return gambledScore - bestScore } + private fun getScoreCountRow(score: Int) = + getScoreRow("$score") { scores -> scores.count { it == score } } - private fun getScoreCountRow(score: Int) = getScoreRow("$score") { scores -> scores.count { it == score } } - - private fun getScoreRow(desc: String, f: (golfScores: List) -> Any?) = prepareRow(desc) { playerName -> - val countedDarts = getCountedDarts(playerName) - val scores = countedDarts.map { d -> d.getGolfScore() } - f(scores) - } + private fun getScoreRow(desc: String, f: (golfScores: List) -> Any?) = + prepareRow(desc) { playerName -> + val countedDarts = getCountedDarts(playerName) + val scores = countedDarts.map { d -> d.getGolfScore() } + f(scores) + } - /** - * Get the darts that were actually counted, i.e. the last of each round. - */ - private fun getCountedDarts(playerName: UniqueParticipantName): List - { + /** Get the darts that were actually counted, i.e. the last of each round. */ + private fun getCountedDarts(playerName: UniqueParticipantName): List { val rounds = hmPlayerToDarts[playerName]!! return rounds.map { r -> r.last() } diff --git a/src/main/kotlin/dartzee/screen/game/golf/GolfMatchScreen.kt b/src/main/kotlin/dartzee/screen/game/golf/GolfMatchScreen.kt index 87704ba36..9e5a5fe12 100644 --- a/src/main/kotlin/dartzee/screen/game/golf/GolfMatchScreen.kt +++ b/src/main/kotlin/dartzee/screen/game/golf/GolfMatchScreen.kt @@ -8,8 +8,10 @@ import dartzee.screen.game.DartsMatchScreen import dartzee.screen.game.MatchSummaryPanel class GolfMatchScreen(match: DartsMatchEntity) : - DartsMatchScreen(MatchSummaryPanel(match, MatchStatisticsPanelGolf()), match) -{ - override fun factoryGamePanel(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) = - GamePanelGolf(parent, game, totalPlayers) -} \ No newline at end of file + DartsMatchScreen(MatchSummaryPanel(match, MatchStatisticsPanelGolf()), match) { + override fun factoryGamePanel( + parent: AbstractDartsGameScreen, + game: GameEntity, + totalPlayers: Int + ) = GamePanelGolf(parent, game, totalPlayers) +} diff --git a/src/main/kotlin/dartzee/screen/game/golf/MatchStatisticsPanelGolf.kt b/src/main/kotlin/dartzee/screen/game/golf/MatchStatisticsPanelGolf.kt index 33b09de9e..38d07d137 100644 --- a/src/main/kotlin/dartzee/screen/game/golf/MatchStatisticsPanelGolf.kt +++ b/src/main/kotlin/dartzee/screen/game/golf/MatchStatisticsPanelGolf.kt @@ -2,15 +2,14 @@ package dartzee.screen.game.golf import dartzee.core.util.minOrZero -class MatchStatisticsPanelGolf: GameStatisticsPanelGolf() -{ - override fun addRowsToTable() - { +class MatchStatisticsPanelGolf : GameStatisticsPanelGolf() { + override fun addRowsToTable() { super.addRowsToTable() addRow(getBestGameRow { it.minOrZero() }) addRow(getAverageGameRow()) } - override fun getRankedRowsLowestWins() = super.getRankedRowsLowestWins() + "Best Game" + "Avg Game" + override fun getRankedRowsLowestWins() = + super.getRankedRowsLowestWins() + "Best Game" + "Avg Game" } diff --git a/src/main/kotlin/dartzee/screen/game/rtc/GamePanelRoundTheClock.kt b/src/main/kotlin/dartzee/screen/game/rtc/GamePanelRoundTheClock.kt index e943d4c54..085ead4d3 100644 --- a/src/main/kotlin/dartzee/screen/game/rtc/GamePanelRoundTheClock.kt +++ b/src/main/kotlin/dartzee/screen/game/rtc/GamePanelRoundTheClock.kt @@ -15,66 +15,58 @@ import dartzee.screen.game.AbstractDartsGameScreen import dartzee.screen.game.GamePanelPausable import dartzee.screen.game.scorer.DartsScorerRoundTheClock -class GamePanelRoundTheClock(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int): - GamePanelPausable(parent, game, totalPlayers) -{ +class GamePanelRoundTheClock(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) : + GamePanelPausable(parent, game, totalPlayers) { private val config = RoundTheClockConfig.fromJson(game.gameParams) override fun factoryState(pt: IWrappedParticipant) = ClockPlayerState(config, pt) - override fun computeAiDart(model: DartsAiModel): ComputedPoint - { + override fun computeAiDart(model: DartsAiModel): ComputedPoint { val currentTarget = getCurrentPlayerState().getCurrentTarget() return model.throwClockDart(currentTarget, config.clockType) } - override fun updateVariablesForDartThrown(dart: Dart) - { - if (dart.hitClockTarget(config.clockType) && dartsThrownCount() == 4) - { + override fun updateVariablesForDartThrown(dart: Dart) { + if (dart.hitClockTarget(config.clockType) && dartsThrownCount() == 4) { dartboard.doForsyth() - } - else if (dartsThrownCount() == 4) - { + } else if (dartsThrownCount() == 4) { dartboard.doBadLuck() } updateDartboard() } - override fun readyForThrow() - { + override fun readyForThrow() { super.readyForThrow() updateDartboard() } override fun shouldAnimateMiss(dart: Dart) = dartsThrownCount() < 4 - override fun shouldStopAfterDartThrown(): Boolean - { - if (dartsThrownCount() == 4) - { + override fun shouldStopAfterDartThrown(): Boolean { + if (dartsThrownCount() == 4) { return true } - if (getCurrentPlayerState().findCurrentTarget() == null) - { - //Finished. + if (getCurrentPlayerState().findCurrentTarget() == null) { + // Finished. return true } val allHits = getDartsThrown().all { it.hitClockTarget(config.clockType) } return dartsThrownCount() == 3 && !allHits - } override fun mustContinueThrowing() = !shouldStopAfterDartThrown() - override fun saveDartsAndProceed() - { - if (dartsThrownCount() == 4 && getDartsThrown().last().hitClockTarget(config.clockType)) - { - AchievementEntity.insertAchievement(AchievementType.CLOCK_BRUCEY_BONUSES, getCurrentPlayerId(), getGameId(), "$currentRoundNumber") + override fun saveDartsAndProceed() { + if (dartsThrownCount() == 4 && getDartsThrown().last().hitClockTarget(config.clockType)) { + AchievementEntity.insertAchievement( + AchievementType.CLOCK_BRUCEY_BONUSES, + getCurrentPlayerId(), + getGameId(), + "$currentRoundNumber" + ) } updateBestStreakAchievement() @@ -82,22 +74,23 @@ class GamePanelRoundTheClock(parent: AbstractDartsGameScreen, game: GameEntity, super.saveDartsAndProceed() } - private fun updateBestStreakAchievement() - { - if (getCurrentPlayerState().hasMultiplePlayers()) - { + private fun updateBestStreakAchievement() { + if (getCurrentPlayerState().hasMultiplePlayers()) { return } val longestStreakThisGame = getCurrentPlayerState().getLongestStreak() - if (longestStreakThisGame > 1) - { - AchievementEntity.updateAchievement(AchievementType.CLOCK_BEST_STREAK, getCurrentPlayerId(), getGameId(), longestStreakThisGame) + if (longestStreakThisGame > 1) { + AchievementEntity.updateAchievement( + AchievementType.CLOCK_BEST_STREAK, + getCurrentPlayerId(), + getGameId(), + longestStreakThisGame + ) } } - private fun updateDartboard() - { + private fun updateDartboard() { val state = getCurrentPlayerState() val segmentStatus = state.getSegmentStatus() dartboard.refreshValidSegments(segmentStatus) @@ -106,8 +99,12 @@ class GamePanelRoundTheClock(parent: AbstractDartsGameScreen, game: GameEntity, override fun currentPlayerHasFinished() = getCurrentPlayerState().findCurrentTarget() == null override fun factoryScorer(participant: IWrappedParticipant) = - DartsScorerRoundTheClock(this, RoundTheClockConfig.fromJson(gameEntity.gameParams), participant) - - override fun factoryStatsPanel(gameParams: String) = GameStatisticsPanelRoundTheClock(gameParams) - + DartsScorerRoundTheClock( + this, + RoundTheClockConfig.fromJson(gameEntity.gameParams), + participant + ) + + override fun factoryStatsPanel(gameParams: String) = + GameStatisticsPanelRoundTheClock(gameParams) } diff --git a/src/main/kotlin/dartzee/screen/game/rtc/GameStatisticsPanelRoundTheClock.kt b/src/main/kotlin/dartzee/screen/game/rtc/GameStatisticsPanelRoundTheClock.kt index f48389bae..ed783ba75 100644 --- a/src/main/kotlin/dartzee/screen/game/rtc/GameStatisticsPanelRoundTheClock.kt +++ b/src/main/kotlin/dartzee/screen/game/rtc/GameStatisticsPanelRoundTheClock.kt @@ -9,17 +9,21 @@ import dartzee.`object`.Dart import dartzee.screen.game.AbstractGameStatisticsPanel import dartzee.utils.getLongestStreak -open class GameStatisticsPanelRoundTheClock(gameParams: String): AbstractGameStatisticsPanel() -{ +open class GameStatisticsPanelRoundTheClock(gameParams: String) : + AbstractGameStatisticsPanel() { private val config = RoundTheClockConfig.fromJson(gameParams) - override fun getRankedRowsHighestWins() = listOf("Best Streak", "Brucey chances", "Bruceys executed") + override fun getRankedRowsHighestWins() = + listOf("Best Streak", "Brucey chances", "Bruceys executed") + override fun getRankedRowsLowestWins() = listOf("Most darts", "Avg darts", "Fewest darts") - override fun getHistogramRows() = listOf("1", "2 - 3", "4 - 6", "7 - 10", "11 - 15", "16 - 20", "21+") + + override fun getHistogramRows() = + listOf("1", "2 - 3", "4 - 6", "7 - 10", "11 - 15", "16 - 20", "21+") + override fun getStartOfSectionRows() = listOf("Best Streak", "1", "Best Game") - override fun addRowsToTable() - { + override fun addRowsToTable() { addRow(getDartsPerNumber("Most darts", true) { it.maxOrZero() }) addRow(getDartsPerNumber("Avg darts", false) { getAverageDartsForAnyRound(it) }) addRow(getDartsPerNumber("Fewest darts", false) { it.minOrNull() }) @@ -39,36 +43,48 @@ open class GameStatisticsPanelRoundTheClock(gameParams: String): AbstractGameSta table.setColumnWidths("140") } - private fun getLongestStreak() = prepareRow("Best Streak") { playerName -> - val darts = getFlattenedDarts(playerName) - getLongestStreak(darts, config.clockType).size - } + private fun getLongestStreak() = + prepareRow("Best Streak") { playerName -> + val darts = getFlattenedDarts(playerName) + getLongestStreak(darts, config.clockType).size + } private fun getAverageDartsForAnyRound(darts: List) = - if (darts.isEmpty()) null else MathsUtil.round(darts.average(), 2) + if (darts.isEmpty()) null else MathsUtil.round(darts.average(), 2) - private fun getBruceys(desc: String, enforceSuccess: Boolean) = prepareRow(desc) { playerName -> - val rounds = hmPlayerToDarts[playerName].orEmpty() - rounds.count { it.size == 4 && (it.last().hitClockTarget(config.clockType) || !enforceSuccess) } - } + private fun getBruceys(desc: String, enforceSuccess: Boolean) = + prepareRow(desc) { playerName -> + val rounds = hmPlayerToDarts[playerName].orEmpty() + rounds.count { + it.size == 4 && (it.last().hitClockTarget(config.clockType) || !enforceSuccess) + } + } - private fun getDartsPerNumber(min: Int, max: Int, desc: String = "$min - $max") = prepareRow(desc) { playerName -> - val dartsGrouped = getDartsGroupedByParticipantAndNumber(playerName) - dartsGrouped.count { it.size in min..max && it.last().hitClockTarget(config.clockType) } - } + private fun getDartsPerNumber(min: Int, max: Int, desc: String = "$min - $max") = + prepareRow(desc) { playerName -> + val dartsGrouped = getDartsGroupedByParticipantAndNumber(playerName) + dartsGrouped.count { it.size in min..max && it.last().hitClockTarget(config.clockType) } + } - private fun getDartsPerNumber(desc: String, - includeUnfinished: Boolean, - fn: (stream: List) -> Any?) = prepareRow(desc) { playerName -> - val dartsGrouped = getDartsGroupedByParticipantAndNumber(playerName) - val sizes = dartsGrouped.filter { it.last().hitClockTarget(config.clockType) || includeUnfinished }.map { it.size } - fn(sizes) - } + private fun getDartsPerNumber( + desc: String, + includeUnfinished: Boolean, + fn: (stream: List) -> Any? + ) = + prepareRow(desc) { playerName -> + val dartsGrouped = getDartsGroupedByParticipantAndNumber(playerName) + val sizes = + dartsGrouped + .filter { it.last().hitClockTarget(config.clockType) || includeUnfinished } + .map { it.size } + fn(sizes) + } - private fun getDartsGroupedByParticipantAndNumber(playerName: UniqueParticipantName): List> - { + private fun getDartsGroupedByParticipantAndNumber( + playerName: UniqueParticipantName + ): List> { val darts = getFlattenedDarts(playerName) - val hm = darts.groupBy{d -> "${d.participantId}_${d.startingScore}"} + val hm = darts.groupBy { d -> "${d.participantId}_${d.startingScore}" } return hm.values.toList() } } diff --git a/src/main/kotlin/dartzee/screen/game/rtc/MatchStatisticsPanelRoundTheClock.kt b/src/main/kotlin/dartzee/screen/game/rtc/MatchStatisticsPanelRoundTheClock.kt index 330db38cf..dc3abf135 100644 --- a/src/main/kotlin/dartzee/screen/game/rtc/MatchStatisticsPanelRoundTheClock.kt +++ b/src/main/kotlin/dartzee/screen/game/rtc/MatchStatisticsPanelRoundTheClock.kt @@ -2,15 +2,15 @@ package dartzee.screen.game.rtc import dartzee.core.util.minOrZero -class MatchStatisticsPanelRoundTheClock(gameParams: String): GameStatisticsPanelRoundTheClock(gameParams) -{ - override fun addRowsToTable() - { +class MatchStatisticsPanelRoundTheClock(gameParams: String) : + GameStatisticsPanelRoundTheClock(gameParams) { + override fun addRowsToTable() { super.addRowsToTable() addRow(getBestGameRow { it.minOrZero() }) addRow(getAverageGameRow()) } - override fun getRankedRowsLowestWins() = super.getRankedRowsLowestWins() + "Best Game" + "Avg Game" + override fun getRankedRowsLowestWins() = + super.getRankedRowsLowestWins() + "Best Game" + "Avg Game" } diff --git a/src/main/kotlin/dartzee/screen/game/rtc/RoundTheClockMatchScreen.kt b/src/main/kotlin/dartzee/screen/game/rtc/RoundTheClockMatchScreen.kt index dafe77d85..ebcbbb2db 100644 --- a/src/main/kotlin/dartzee/screen/game/rtc/RoundTheClockMatchScreen.kt +++ b/src/main/kotlin/dartzee/screen/game/rtc/RoundTheClockMatchScreen.kt @@ -7,9 +7,14 @@ import dartzee.screen.game.AbstractDartsGameScreen import dartzee.screen.game.DartsMatchScreen import dartzee.screen.game.MatchSummaryPanel -class RoundTheClockMatchScreen(match: DartsMatchEntity): - DartsMatchScreen(MatchSummaryPanel(match, MatchStatisticsPanelRoundTheClock(match.gameParams)), match) -{ - override fun factoryGamePanel(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) = - GamePanelRoundTheClock(parent, game, totalPlayers) -} \ No newline at end of file +class RoundTheClockMatchScreen(match: DartsMatchEntity) : + DartsMatchScreen( + MatchSummaryPanel(match, MatchStatisticsPanelRoundTheClock(match.gameParams)), + match + ) { + override fun factoryGamePanel( + parent: AbstractDartsGameScreen, + game: GameEntity, + totalPlayers: Int + ) = GamePanelRoundTheClock(parent, game, totalPlayers) +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorer.kt b/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorer.kt index 7cbfc6c08..59dcac114 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorer.kt @@ -11,19 +11,17 @@ import javax.swing.border.EmptyBorder const val SCORER_WIDTH = 210 -abstract class AbstractDartsScorer>(participant: IWrappedParticipant) : - AbstractScorer(participant), PlayerStateListener, IDartsScorerTable -{ +abstract class AbstractDartsScorer>( + participant: IWrappedParticipant +) : AbstractScorer(participant), PlayerStateListener, IDartsScorerTable { private val overlays = mutableListOf() - init - { + init { preferredSize = Dimension(SCORER_WIDTH, 700) panelAvatar.border = EmptyBorder(5, 30, 5, 30) } - override fun stateChanged(state: PlayerState) - { + override fun stateChanged(state: PlayerState) { runOnEventThreadBlocking { model.clear() updateSelectionState(state) @@ -37,46 +35,43 @@ abstract class AbstractDartsScorer } } - protected fun setScoreAndFinishingPosition(state: PlayerState) - { + protected fun setScoreAndFinishingPosition(state: PlayerState) { val scoreSoFar = state.getScoreSoFar() lblResult.text = if (scoreSoFar > 0) "$scoreSoFar" else "" updateResultColourForPosition(state.wrappedParticipant.participant.finishingPosition) } - private fun updateSelectionState(state: PlayerState) - { + private fun updateSelectionState(state: PlayerState) { val currentIndividual = state.currentIndividual() - lblName.text = state.wrappedParticipant.getParticipantNameHtml(state.isActive, currentIndividual) + lblName.text = + state.wrappedParticipant.getParticipantNameHtml(state.isActive, currentIndividual) lblAvatar.setSelected(state.isActive, state.currentRoundNumber()) } - fun gameFinished() - { + fun gameFinished() { lblName.text = participant.getParticipantNameHtml(false) lblAvatar.setSelected(false, -1, true) } protected open fun stateChangedImpl(state: PlayerState) {} - fun achievementUnlocked(achievement: AbstractAchievement, playerId: String) - { + fun achievementUnlocked(achievement: AbstractAchievement, playerId: String) { val playerName = getPlayerNameIfNecessary(playerId) val overlay = AchievementOverlay(this, achievement, playerName) overlays.add(overlay) - //Let's just only ever have one thing at a time on display. Actually layering them sometimes worked but - //sometimes caused weird bollocks when things happened close together + // Let's just only ever have one thing at a time on display. Actually layering them + // sometimes worked but + // sometimes caused weird bollocks when things happened close together panelCenter.removeAll() panelCenter.add(overlay, BorderLayout.CENTER) panelCenter.revalidate() panelCenter.repaint() } - private fun getPlayerNameIfNecessary(playerId: String): String? - { - if (participant.individuals.size == 1) - { + + private fun getPlayerNameIfNecessary(playerId: String): String? { + if (participant.individuals.size == 1) { return null } @@ -84,18 +79,14 @@ abstract class AbstractDartsScorer return pt.getPlayerName() } - fun achievementClosed(overlay: AchievementOverlay) - { + fun achievementClosed(overlay: AchievementOverlay) { panelCenter.removeAll() overlays.remove(overlay) - //If there are more overlays stacked 'beneath', show the next one of them now - if (overlays.isNotEmpty()) - { + // If there are more overlays stacked 'beneath', show the next one of them now + if (overlays.isNotEmpty()) { panelCenter.add(overlays.last(), BorderLayout.CENTER) - } - else - { + } else { allAchievementsClosed() } @@ -103,8 +94,7 @@ abstract class AbstractDartsScorer panelCenter.repaint() } - open fun allAchievementsClosed() - { + open fun allAchievementsClosed() { panelCenter.add(tableScores) } } diff --git a/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorerPausable.kt b/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorerPausable.kt index 75ba1ee45..8151868d7 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorerPausable.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/AbstractDartsScorerPausable.kt @@ -15,16 +15,14 @@ import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JButton -abstract class AbstractDartsScorerPausable>( +abstract class AbstractDartsScorerPausable>( private val parent: GamePanelPausable<*, *>, participant: IWrappedParticipant - ) : AbstractDartsScorer(participant), ActionListener -{ +) : AbstractDartsScorer(participant), ActionListener { private val btnResume = JButton("") private var latestState: PlayerState? = null - init - { + init { btnResume.preferredSize = Dimension(30, 30) panelSouth.add(btnResume, BorderLayout.EAST) btnResume.isVisible = false @@ -35,22 +33,23 @@ abstract class AbstractDartsScorerPausable, achievement: AbstractAchievement, playerName: String?) : - JPanel(), ActionListener, IMouseListener -{ +class AchievementOverlay( + private val parent: AbstractDartsScorer<*>, + achievement: AbstractAchievement, + playerName: String? +) : JPanel(), ActionListener, IMouseListener { private val btnClose = JButton("X") private val fillColor = achievement.getColor(false).brighter() private val borderColor = fillColor.darker() - init - { + init { layout = BorderLayout(0, 0) border = LineBorder(borderColor, 6) @@ -64,8 +65,7 @@ class AchievementOverlay(private val parent: AbstractDartsScorer<*>, achievement lblUnlocked.verticalAlignment = JLabel.TOP panelCenter.add(lblUnlocked, "cell 0 1") - if (playerName != null) - { + if (playerName != null) { val lblPlayerName = factoryTextLabel(playerName, 20, "playerName") panelCenter.add(lblPlayerName, "cell 0 3") } @@ -77,8 +77,7 @@ class AchievementOverlay(private val parent: AbstractDartsScorer<*>, achievement btnClose.addActionListener(this) } - private fun factoryTextLabel(text: String, fontSize: Int = 24, testId: String = "") : JLabel - { + private fun factoryTextLabel(text: String, fontSize: Int = 24, testId: String = ""): JLabel { val lbl = JLabel(text) lbl.name = testId lbl.background = fillColor @@ -89,26 +88,24 @@ class AchievementOverlay(private val parent: AbstractDartsScorer<*>, achievement return lbl } - override fun actionPerformed(e: ActionEvent) - { + override fun actionPerformed(e: ActionEvent) { parent.achievementClosed(this) revalidate() repaint() } - override fun mousePressed(e: MouseEvent) - { + override fun mousePressed(e: MouseEvent) { btnClose.foreground = borderColor.darker().darker() btnClose.background = fillColor.darker() - btnClose.border = BevelBorder(BevelBorder.LOWERED, borderColor.darker(), borderColor.darker().darker()) + btnClose.border = + BevelBorder(BevelBorder.LOWERED, borderColor.darker(), borderColor.darker().darker()) btnClose.repaint() } - override fun mouseReleased(e: MouseEvent) - { + override fun mouseReleased(e: MouseEvent) { btnClose.background = fillColor btnClose.foreground = borderColor.darker() btnClose.border = BevelBorder(BevelBorder.RAISED, borderColor, borderColor.darker()) btnClose.repaint() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/DartRenderer.kt b/src/main/kotlin/dartzee/screen/game/scorer/DartRenderer.kt index f86f146fe..905be7f79 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/DartRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/DartRenderer.kt @@ -6,27 +6,21 @@ import dartzee.`object`.DartHint import java.awt.Color import java.awt.Font -class DartRenderer : AbstractTableRenderer() -{ - override fun getReplacementValue(value: Dart): Any - { - return when(value) - { +class DartRenderer : AbstractTableRenderer() { + override fun getReplacementValue(value: Dart): Any { + return when (value) { is DartHint -> "($value)" else -> "$value" } } - override fun setCellColours(typedValue: Dart?, isSelected: Boolean) - { - foreground = if (isSelected) - { - if (typedValue is DartHint) Color.CYAN else Color.WHITE - } - else - { - if (typedValue is DartHint) Color.RED else Color.BLACK - } + override fun setCellColours(typedValue: Dart?, isSelected: Boolean) { + foreground = + if (isSelected) { + if (typedValue is DartHint) Color.CYAN else Color.WHITE + } else { + if (typedValue is DartHint) Color.RED else Color.BLACK + } val style = if (typedValue is DartHint) Font.ITALIC else Font.PLAIN @@ -34,4 +28,4 @@ class DartRenderer : AbstractTableRenderer() } override fun allowNulls() = true -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerDartzee.kt b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerDartzee.kt index ece785fc5..911a11925 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerDartzee.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerDartzee.kt @@ -11,15 +11,12 @@ private const val RULE_COLUMN = 3 private const val SCORE_COLUMN = 4 class DartsScorerDartzee(private val parent: GamePanelDartzee, participant: IWrappedParticipant) : - AbstractDartsScorer(participant), IMouseListener -{ - init - { + AbstractDartsScorer(participant), IMouseListener { + init { lblAvatar.addMouseListener(this) } - override fun stateChangedImpl(state: DartzeePlayerState) - { + override fun stateChangedImpl(state: DartzeePlayerState) { setScoreAndFinishingPosition(state) state.completedRounds.forEachIndexed { ix, round -> @@ -33,37 +30,32 @@ class DartsScorerDartzee(private val parent: GamePanelDartzee, participant: IWra model.setValueAt(cumulativeScore, ix, SCORE_COLUMN) } - if (state.currentRound.isNotEmpty()) - { + if (state.currentRound.isNotEmpty()) { addDartRound(state.currentRound) } - tableScores.getColumn(SCORE_COLUMN).cellRenderer = DartzeeScoreRenderer(state.getPeakScore() ?: 0) + tableScores.getColumn(SCORE_COLUMN).cellRenderer = + DartzeeScoreRenderer(state.getPeakScore() ?: 0) } override fun getNumberOfColumns() = 5 - override fun initImpl() - { - for (i in 0 until RULE_COLUMN) - { + override fun initImpl() { + for (i in 0 until RULE_COLUMN) { tableScores.getColumn(i).cellRenderer = DartRenderer() } tableScores.getColumn(RULE_COLUMN).cellRenderer = DartzeeRoundResultRenderer() } - fun togglePostGame(selected: Boolean) - { + fun togglePostGame(selected: Boolean) { lblName.text = participant.getParticipantNameHtml(selected) lblAvatar.setSelected(selected, -1, selected) } - override fun mouseReleased(e: MouseEvent) - { - if (parent.gameEntity.isFinished()) - { + override fun mouseReleased(e: MouseEvent) { + if (parent.gameEntity.isFinished()) { parent.scorerSelected(this) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerGolf.kt b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerGolf.kt index 3f6669cbb..2d5c0964c 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerGolf.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerGolf.kt @@ -4,28 +4,23 @@ import dartzee.game.state.GolfPlayerState import dartzee.game.state.IWrappedParticipant class DartsScorerGolf(participant: IWrappedParticipant) : - AbstractDartsScorer(participant), IGolfScorerTable -{ + AbstractDartsScorer(participant), IGolfScorerTable { override val fudgeFactor = 0 override fun getNumberOfColumns() = 5 - override fun initImpl() - { - for (i in 0..GOLF_SCORE_COLUMN) - { + override fun initImpl() { + for (i in 0..GOLF_SCORE_COLUMN) { tableScores.setRenderer(i, GolfDartRenderer(false)) } } - override fun stateChangedImpl(state: GolfPlayerState) - { + override fun stateChangedImpl(state: GolfPlayerState) { setScoreAndFinishingPosition(state) populateTable(state.completedRounds) - if (state.currentRound.isNotEmpty()) - { + if (state.currentRound.isNotEmpty()) { addDartRound(state.currentRound) } } diff --git a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerRoundTheClock.kt b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerRoundTheClock.kt index 8227d5511..3730de7c9 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerRoundTheClock.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerRoundTheClock.kt @@ -1,4 +1,4 @@ - package dartzee.screen.game.scorer +package dartzee.screen.game.scorer import dartzee.game.RoundTheClockConfig import dartzee.game.state.ClockPlayerState @@ -7,60 +7,51 @@ import dartzee.`object`.DartNotThrown import dartzee.screen.game.GamePanelPausable import java.awt.BorderLayout - class DartsScorerRoundTheClock( +class DartsScorerRoundTheClock( parent: GamePanelPausable<*, *>, private val clockConfig: RoundTheClockConfig, - participant: IWrappedParticipant) : AbstractDartsScorerPausable(parent, participant) -{ + participant: IWrappedParticipant +) : AbstractDartsScorerPausable(parent, participant) { private val tableRemaining = RoundTheClockScorecard() override fun getNumberOfColumns() = 4 override fun getNumberOfColumnsForAddingNewDart() = getNumberOfColumns() - override fun initImpl() - { - for (i in 0..BONUS_COLUMN) - { + override fun initImpl() { + for (i in 0..BONUS_COLUMN) { tableScores.getColumn(i).cellRenderer = RoundTheClockDartRenderer(clockConfig.clockType) } - if (!clockConfig.inOrder) - { + if (!clockConfig.inOrder) { panelCenter.add(tableRemaining, BorderLayout.NORTH) } } - override fun allAchievementsClosed() - { + override fun allAchievementsClosed() { super.allAchievementsClosed() - if (!clockConfig.inOrder) - { + if (!clockConfig.inOrder) { panelCenter.add(tableRemaining, BorderLayout.NORTH) } } - override fun stateChangedImpl(state: ClockPlayerState) - { + override fun stateChangedImpl(state: ClockPlayerState) { tableRemaining.stateChanged(state, getPaused()) state.completedRounds.forEach { round -> addDartRound(round) - if (round.size < 4) - { + if (round.size < 4) { disableBrucey() } } val currentRound = state.currentRound - if (currentRound.isNotEmpty()) - { + if (currentRound.isNotEmpty()) { addDartRound(currentRound) - if (!state.onTrackForBrucey() && currentRound.size < 4) - { + if (!state.onTrackForBrucey() && currentRound.size < 4) { disableBrucey() } } @@ -68,14 +59,12 @@ import java.awt.BorderLayout finalisePlayerResult(state) } - private fun disableBrucey() - { + private fun disableBrucey() { val row = model.rowCount - 1 model.setValueAt(DartNotThrown(), row, BONUS_COLUMN) } - companion object - { + companion object { private const val BONUS_COLUMN = 3 } } diff --git a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerX01.kt b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerX01.kt index 671476694..2835b6537 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerX01.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/DartsScorerX01.kt @@ -9,29 +9,27 @@ import java.awt.Font import javax.swing.JLabel import javax.swing.SwingConstants -class DartsScorerX01(parent: GamePanelPausable<*, *>, gameParams: String, participant: IWrappedParticipant) : - AbstractDartsScorerPausable(parent, participant) -{ +class DartsScorerX01( + parent: GamePanelPausable<*, *>, + gameParams: String, + participant: IWrappedParticipant +) : AbstractDartsScorerPausable(parent, participant) { private val lblStartingScore = JLabel(gameParams) - init - { + init { lblStartingScore.horizontalAlignment = SwingConstants.CENTER lblStartingScore.font = Font("Trebuchet MS", Font.PLAIN, 16) panelNorth.add(lblStartingScore, BorderLayout.SOUTH) } - override fun initImpl() - { + override fun initImpl() { tableScores.getColumn(SCORE_COLUMN).cellRenderer = X01ScoreRenderer() - for (i in 0 until SCORE_COLUMN) - { + for (i in 0 until SCORE_COLUMN) { tableScores.getColumn(i).cellRenderer = DartRenderer() } } - override fun stateChangedImpl(state: X01PlayerState) - { + override fun stateChangedImpl(state: X01PlayerState) { state.completedRounds.forEachIndexed { ix, round -> addDartRound(round) @@ -41,8 +39,7 @@ class DartsScorerX01(parent: GamePanelPausable<*, *>, gameParams: String, partic model.setValueAt(scoreRemaining, ix, SCORE_COLUMN) } - if (state.currentRound.isNotEmpty()) - { + if (state.currentRound.isNotEmpty()) { addDartRound(state.currentRound) } @@ -51,10 +48,8 @@ class DartsScorerX01(parent: GamePanelPausable<*, *>, gameParams: String, partic addCheckoutSuggestion(state) } - private fun addCheckoutSuggestion(state: X01PlayerState) - { - if (getPaused() || !state.isActive) - { + private fun addCheckoutSuggestion(state: X01PlayerState) { + if (getPaused() || !state.isActive) { return } @@ -62,8 +57,7 @@ class DartsScorerX01(parent: GamePanelPausable<*, *>, gameParams: String, partic val currentScore = state.getRemainingScore() val checkout = CheckoutSuggester.suggestCheckout(currentScore, dartsRemaining) ?: return - if (state.currentRound.isEmpty()) - { + if (state.currentRound.isEmpty()) { addRow(makeEmptyRow()) } @@ -72,8 +66,7 @@ class DartsScorerX01(parent: GamePanelPausable<*, *>, gameParams: String, partic override fun getNumberOfColumns() = SCORE_COLUMN + 1 - companion object - { + companion object { const val SCORE_COLUMN = 3 } } diff --git a/src/main/kotlin/dartzee/screen/game/scorer/DartzeeRoundResultRenderer.kt b/src/main/kotlin/dartzee/screen/game/scorer/DartzeeRoundResultRenderer.kt index ecd125a45..99df49b22 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/DartzeeRoundResultRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/DartzeeRoundResultRenderer.kt @@ -6,21 +6,16 @@ import dartzee.utils.setColoursForDartzeeResult import java.awt.Font import javax.swing.SwingConstants -class DartzeeRoundResultRenderer : AbstractTableRenderer() -{ - override fun getReplacementValue(value: DartzeeRoundResult): Any - { - return when - { +class DartzeeRoundResultRenderer : AbstractTableRenderer() { + override fun getReplacementValue(value: DartzeeRoundResult): Any { + return when { value.ruleNumber == -1 -> "-" else -> "#${value.ruleNumber}" } } - override fun setCellColours(typedValue: DartzeeRoundResult?, isSelected: Boolean) - { - if (typedValue == null) - { + override fun setCellColours(typedValue: DartzeeRoundResult?, isSelected: Boolean) { + if (typedValue == null) { background = null foreground = null return @@ -29,11 +24,10 @@ class DartzeeRoundResultRenderer : AbstractTableRenderer() setColoursForDartzeeResult(typedValue.success) } - override fun setFontsAndAlignment() - { + override fun setFontsAndAlignment() { horizontalAlignment = SwingConstants.CENTER font = Font(font.name, Font.BOLD, 12) } override fun allowNulls() = true -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/DartzeeScoreRenderer.kt b/src/main/kotlin/dartzee/screen/game/scorer/DartzeeScoreRenderer.kt index 56d3de641..73efce21c 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/DartzeeScoreRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/DartzeeScoreRenderer.kt @@ -5,14 +5,11 @@ import java.awt.Color import java.awt.Font import javax.swing.SwingConstants -class DartzeeScoreRenderer(val maxScore: Int): AbstractTableRenderer() -{ +class DartzeeScoreRenderer(val maxScore: Int) : AbstractTableRenderer() { override fun getReplacementValue(value: Int) = value - override fun setCellColours(typedValue: Int?, isSelected: Boolean) - { - if (typedValue == null) - { + override fun setCellColours(typedValue: Int?, isSelected: Boolean) { + if (typedValue == null) { background = null foreground = null return @@ -22,11 +19,10 @@ class DartzeeScoreRenderer(val maxScore: Int): AbstractTableRenderer() background = Color.getHSBColor(0.5.toFloat(), percent, 1f) } - override fun setFontsAndAlignment() - { + override fun setFontsAndAlignment() { horizontalAlignment = SwingConstants.CENTER font = Font(font.name, Font.BOLD, 12) } override fun allowNulls() = true -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/GolfDartRenderer.kt b/src/main/kotlin/dartzee/screen/game/scorer/GolfDartRenderer.kt index 0236a153f..3e00ff6f2 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/GolfDartRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/GolfDartRenderer.kt @@ -14,12 +14,19 @@ import javax.swing.border.Border import javax.swing.border.MatteBorder import javax.swing.table.DefaultTableCellRenderer -class GolfDartRenderer(private val showGameId: Boolean) : DefaultTableCellRenderer() -{ - override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { +class GolfDartRenderer(private val showGameId: Boolean) : DefaultTableCellRenderer() { + override fun getTableCellRendererComponent( + table: JTable?, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { val newValue = getReplacementValue(table, value, row) - val cell = super.getTableCellRendererComponent(table, newValue, isSelected, hasFocus, row, column) as JComponent + val cell = + super.getTableCellRendererComponent(table, newValue, isSelected, hasFocus, row, column) + as JComponent horizontalAlignment = SwingConstants.CENTER font = Font("Trebuchet MS", Font.BOLD, 15) @@ -27,13 +34,10 @@ class GolfDartRenderer(private val showGameId: Boolean) : DefaultTableCellRender val border = getBorderForCell(row, column) cell.border = border - if (column == 0 || newValue == null || isScoreRow(row)) - { + if (column == 0 || newValue == null || isScoreRow(row)) { foreground = null background = null - } - else - { + } else { val score = newValue as Int val bgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS) @@ -46,15 +50,12 @@ class GolfDartRenderer(private val showGameId: Boolean) : DefaultTableCellRender return this } - private fun getReplacementValue(table: JTable?, obj: Any?, row: Int): Any? - { - if (obj == null) - { + private fun getReplacementValue(table: JTable?, obj: Any?, row: Int): Any? { + if (obj == null) { return null } - if (obj !is Dart) - { + if (obj !is Dart) { return obj } @@ -62,34 +63,29 @@ class GolfDartRenderer(private val showGameId: Boolean) : DefaultTableCellRender return obj.getGolfScore(target) } - private fun getBorderForCell(row: Int, col: Int): Border - { + private fun getBorderForCell(row: Int, col: Int): Border { var top = 0 var bottom = 0 var left = 0 var right = 0 - if (isScoreRow(row)) - { + if (isScoreRow(row)) { top = 2 bottom = 2 } - if (col == 1) - { + if (col == 1) { left = 2 } - if (col == 3) - { + if (col == 3) { right = 2 } - if (showGameId && col == 4) - { + if (showGameId && col == 4) { right = 2 } return MatteBorder(top, left, bottom, right, Color.BLACK) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/IDartsScorerTable.kt b/src/main/kotlin/dartzee/screen/game/scorer/IDartsScorerTable.kt index d005551ee..ca9e27e69 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/IDartsScorerTable.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/IDartsScorerTable.kt @@ -2,29 +2,23 @@ package dartzee.screen.game.scorer import dartzee.`object`.Dart -interface IDartsScorerTable : IScorerTable -{ +interface IDartsScorerTable : IScorerTable { fun getNumberOfColumnsForAddingNewDart() = getNumberOfColumns() - 1 - fun addDartRound(darts: List) - { + fun addDartRound(darts: List) { addRow(makeEmptyRow()) darts.forEach(::addDart) } - fun addDart(drt: Dart) - { + fun addDart(drt: Dart) { addDartToRow(model.rowCount - 1, drt) } - private fun addDartToRow(rowNumber: Int, drt: Dart) - { - for (i in 0 until getNumberOfColumnsForAddingNewDart()) - { + private fun addDartToRow(rowNumber: Int, drt: Dart) { + for (i in 0 until getNumberOfColumnsForAddingNewDart()) { val currentVal = model.getValueAt(rowNumber, i) - if (currentVal == null) - { + if (currentVal == null) { model.setValueAt(drt, rowNumber, i) return } @@ -32,4 +26,4 @@ interface IDartsScorerTable : IScorerTable throw Exception("Trying to add dart to row $rowNumber but it's already full.") } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/IGolfScorerTable.kt b/src/main/kotlin/dartzee/screen/game/scorer/IGolfScorerTable.kt index 31b4b5019..26e174f12 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/IGolfScorerTable.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/IGolfScorerTable.kt @@ -10,26 +10,23 @@ const val GOLF_GAME_ID_COLUMN = 5 fun isScoreRow(row: Int) = row == ROUNDS_HALFWAY || row == ROUNDS_FULL + 1 -fun getGolfScorerColour(score: Int, brightness: Double): Color -{ - val hue = when(score) - { - 4 -> 0.1f - 3 -> 0.2f - 2 -> 0.3f - 1 -> 0.5f - else -> 0f - } +fun getGolfScorerColour(score: Int, brightness: Double): Color { + val hue = + when (score) { + 4 -> 0.1f + 3 -> 0.2f + 2 -> 0.3f + 1 -> 0.5f + else -> 0f + } return Color.getHSBColor(hue, 1f, brightness.toFloat()) } -interface IGolfScorerTable : IDartsScorerTable -{ +interface IGolfScorerTable : IDartsScorerTable { val fudgeFactor: Int - fun populateTable(rounds: List>) - { + fun populateTable(rounds: List>) { var totalScore = 0 rounds.forEachIndexed { ix, round -> val roundNumber = ix + 1 @@ -40,39 +37,34 @@ interface IGolfScorerTable : IDartsScorerTable totalScore += score model.setValueAt(score, model.rowCount - 1, GOLF_SCORE_COLUMN) - if (roundNumber == 9 || roundNumber == 18) - { + if (roundNumber == 9 || roundNumber == 18) { val totalRow = arrayOf(null, null, null, null, totalScore) model.addRow(totalRow) } } } - override fun makeEmptyRow(): Array - { + override fun makeEmptyRow(): Array { val emptyRow = super.makeEmptyRow() - //Set the first column to be the round number + // Set the first column to be the round number val rowCount = model.rowCount emptyRow[0] = getTargetForRowNumber(rowCount) return emptyRow } - private fun getTargetForRowNumber(row: Int): Int - { - if (row < ROUNDS_HALFWAY) - { - //Row 0 is 1, etc. + private fun getTargetForRowNumber(row: Int): Int { + if (row < ROUNDS_HALFWAY) { + // Row 0 is 1, etc. return row + fudgeFactor + 1 } - if (row > ROUNDS_HALFWAY) - { - //We have an extra subtotal row to consider + if (row > ROUNDS_HALFWAY) { + // We have an extra subtotal row to consider return row + fudgeFactor } throw Exception("Trying to get round target for the subtotal row") } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/IScorerTable.kt b/src/main/kotlin/dartzee/screen/game/scorer/IScorerTable.kt index 9d14bbf11..51e29d311 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/IScorerTable.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/IScorerTable.kt @@ -2,16 +2,14 @@ package dartzee.screen.game.scorer import dartzee.core.util.TableUtil -interface IScorerTable -{ +interface IScorerTable { val model: TableUtil.DefaultModel fun getNumberOfColumns(): Int - fun addRow(row: Array<*>) - { + fun addRow(row: Array<*>) { model.addRow(row) } fun makeEmptyRow() = arrayOfNulls(getNumberOfColumns()) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/MatchScorer.kt b/src/main/kotlin/dartzee/screen/game/scorer/MatchScorer.kt index 93b682425..e4dfc7f98 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/MatchScorer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/MatchScorer.kt @@ -5,35 +5,27 @@ import dartzee.db.DartsMatchEntity import dartzee.game.state.IWrappedParticipant import dartzee.utils.DartsColour -/** - * For the 'Match Summary' tab. - */ -class MatchScorer(pt: IWrappedParticipant, private val match: DartsMatchEntity) : AbstractScorer(pt) -{ - /** - * Game #, Score, Position, Points - */ +/** For the 'Match Summary' tab. */ +class MatchScorer(pt: IWrappedParticipant, private val match: DartsMatchEntity) : + AbstractScorer(pt) { + /** Game #, Score, Position, Points */ override fun getNumberOfColumns() = 4 - override fun initImpl() - { + override fun initImpl() { tableScores.setLinkColumnIndex(0) - for (i in COLUMN_NO_GAME_ID + 1 until model.columnCount) - { + for (i in COLUMN_NO_GAME_ID + 1 until model.columnCount) { tableScores.getColumn(i).cellRenderer = ParticipantRenderer(i) } tableScores.setColumnWidths("100") } - fun updateResult() - { + fun updateResult() { var totalScore = 0 val rowCount = tableScores.rowCount - for (i in 0 until rowCount) - { + for (i in 0 until rowCount) { val pt = tableScores.getNonNullValueAt(i, COLUMN_NO_MATCH_POINTS) as IWrappedParticipant totalScore += match.getScoreForFinishingPosition(pt.participant.finishingPosition) } @@ -41,20 +33,16 @@ class MatchScorer(pt: IWrappedParticipant, private val match: DartsMatchEntity) lblResult.isVisible = true lblResult.text = "" + totalScore - //Also update the screen + // Also update the screen tableScores.repaint() } - /** - * Inner classes - */ - private inner class ParticipantRenderer(private val colNo: Int) : AbstractTableRenderer() - { - override fun getReplacementValue(value: IWrappedParticipant): Any - { + /** Inner classes */ + private inner class ParticipantRenderer(private val colNo: Int) : + AbstractTableRenderer() { + override fun getReplacementValue(value: IWrappedParticipant): Any { val pt = value.participant - return when (colNo) - { + return when (colNo) { COLUMN_NO_FINAL_SCORE -> if (pt.finalScore == -1) "N/A" else pt.finalScore COLUMN_NO_FINISHING_POSITION -> pt.getFinishingPositionDesc() COLUMN_NO_MATCH_POINTS -> match.getScoreForFinishingPosition(pt.finishingPosition) @@ -62,18 +50,15 @@ class MatchScorer(pt: IWrappedParticipant, private val match: DartsMatchEntity) } } - override fun setCellColours(typedValue: IWrappedParticipant?, isSelected: Boolean) - { - if (colNo == COLUMN_NO_FINISHING_POSITION) - { + override fun setCellColours(typedValue: IWrappedParticipant?, isSelected: Boolean) { + if (colNo == COLUMN_NO_FINISHING_POSITION) { val finishingPos = typedValue!!.participant.finishingPosition DartsColour.setFgAndBgColoursForPosition(this, finishingPos) } } } - companion object - { + companion object { private const val COLUMN_NO_GAME_ID = 0 private const val COLUMN_NO_FINAL_SCORE = 1 private const val COLUMN_NO_FINISHING_POSITION = 2 diff --git a/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockDartRenderer.kt b/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockDartRenderer.kt index c6c3fb43d..76bb2e38c 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockDartRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockDartRenderer.kt @@ -1,9 +1,9 @@ package dartzee.screen.game.scorer -import dartzee.`object`.Dart -import dartzee.`object`.DartNotThrown import dartzee.core.bean.AbstractTableRenderer import dartzee.game.ClockType +import dartzee.`object`.Dart +import dartzee.`object`.DartNotThrown import dartzee.utils.PREFERENCES_DOUBLE_BG_BRIGHTNESS import dartzee.utils.PREFERENCES_DOUBLE_FG_BRIGHTNESS import dartzee.utils.PreferenceUtil @@ -11,39 +11,28 @@ import java.awt.Color import java.awt.Font import javax.swing.SwingConstants -class RoundTheClockDartRenderer(private val clockType: ClockType): AbstractTableRenderer() -{ - override fun setFontsAndAlignment() - { +class RoundTheClockDartRenderer(private val clockType: ClockType) : AbstractTableRenderer() { + override fun setFontsAndAlignment() { horizontalAlignment = SwingConstants.CENTER font = Font("Trebuchet MS", Font.BOLD, 15) } - override fun setCellColours(typedValue: Dart?, isSelected: Boolean) - { - if (typedValue == null) - { + override fun setCellColours(typedValue: Dart?, isSelected: Boolean) { + if (typedValue == null) { foreground = null background = null - } - else if (typedValue is DartNotThrown) - { + } else if (typedValue is DartNotThrown) { foreground = Color.BLACK background = Color.BLACK - } - else - { + } else { val bgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS) val fgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS) - var hue = 0f //Red - if (typedValue.hitClockTarget(clockType)) - { - hue = 0.3f //Green - } - else if (typedValue.hitAnyClockTarget(clockType)) - { - hue = 0.15f //orangey + var hue = 0f // Red + if (typedValue.hitClockTarget(clockType)) { + hue = 0.3f // Green + } else if (typedValue.hitAnyClockTarget(clockType)) { + hue = 0.15f // orangey } foreground = Color.getHSBColor(hue, 1f, fgBrightness.toFloat()) @@ -51,7 +40,8 @@ class RoundTheClockDartRenderer(private val clockType: ClockType): AbstractTable } } - override fun getReplacementValue(value: Dart) = if (!value.hitAnyClockTarget(clockType)) "X" else "$value" + override fun getReplacementValue(value: Dart) = + if (!value.hitAnyClockTarget(clockType)) "X" else "$value" + override fun allowNulls() = true } - diff --git a/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecard.kt b/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecard.kt index 14b5c33a8..40ad183ee 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecard.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecard.kt @@ -5,12 +5,10 @@ import dartzee.core.util.TableUtil import dartzee.game.state.ClockPlayerState import java.awt.Dimension -class RoundTheClockScorecard: ScrollTable() -{ +class RoundTheClockScorecard : ScrollTable() { private val tm = TableUtil.DefaultModel() - init - { + init { model = tm (0..3).forEach { _ -> model.addColumn("") } (0..3).forEach { ix -> getColumn(ix).cellRenderer = RoundTheClockScorecardRenderer() } @@ -20,20 +18,22 @@ class RoundTheClockScorecard: ScrollTable() setShowRowCount(false) } - fun stateChanged(state: ClockPlayerState, paused: Boolean) - { + fun stateChanged(state: ClockPlayerState, paused: Boolean) { tm.clear() val results = (1..20).map { makeClockResult(it, state, paused) } results.chunked(4).forEach(::addRow) } - private fun makeClockResult(target: Int, state: ClockPlayerState, paused: Boolean): ClockResult - { + private fun makeClockResult( + target: Int, + state: ClockPlayerState, + paused: Boolean + ): ClockResult { val hit = state.hasHitTarget(target) val isCurrentTarget = state.findCurrentTarget() == target && state.isActive && !paused return ClockResult(target, hit, isCurrentTarget) } } -data class ClockResult(val value: Int, val hit: Boolean, val isCurrentTarget: Boolean) \ No newline at end of file +data class ClockResult(val value: Int, val hit: Boolean, val isCurrentTarget: Boolean) diff --git a/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecardRenderer.kt b/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecardRenderer.kt index 21906479b..1f7b74112 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecardRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/RoundTheClockScorecardRenderer.kt @@ -9,25 +9,19 @@ import java.awt.Font import javax.swing.SwingConstants import javax.swing.border.LineBorder -class RoundTheClockScorecardRenderer: AbstractTableRenderer() -{ - override fun setFontsAndAlignment() - { +class RoundTheClockScorecardRenderer : AbstractTableRenderer() { + override fun setFontsAndAlignment() { horizontalAlignment = SwingConstants.CENTER font = Font("Trebuchet MS", Font.BOLD, 15) } - override fun setCellColours(typedValue: ClockResult?, isSelected: Boolean) - { + override fun setCellColours(typedValue: ClockResult?, isSelected: Boolean) { typedValue ?: return - if (!typedValue.hit) - { + if (!typedValue.hit) { foreground = Color.BLACK background = null - } - else - { + } else { val bgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS) val fgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS) @@ -35,15 +29,12 @@ class RoundTheClockScorecardRenderer: AbstractTableRenderer() background = Color.getHSBColor(0.3f, 1f, bgBrightness.toFloat()) } - if (typedValue.isCurrentTarget) - { + if (typedValue.isCurrentTarget) { border = LineBorder(Color.RED, 2) - } - else - { + } else { border = null } } override fun getReplacementValue(value: ClockResult) = "${value.value}" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/scorer/X01ScoreRenderer.kt b/src/main/kotlin/dartzee/screen/game/scorer/X01ScoreRenderer.kt index d2a4253a1..2a91969af 100644 --- a/src/main/kotlin/dartzee/screen/game/scorer/X01ScoreRenderer.kt +++ b/src/main/kotlin/dartzee/screen/game/scorer/X01ScoreRenderer.kt @@ -11,10 +11,15 @@ import javax.swing.SwingConstants import javax.swing.table.DefaultTableCellRenderer import javax.swing.table.TableModel -class X01ScoreRenderer : DefaultTableCellRenderer() -{ - override fun getTableCellRendererComponent(table: JTable, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { +class X01ScoreRenderer : DefaultTableCellRenderer() { + override fun getTableCellRendererComponent( + table: JTable, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) horizontalAlignment = SwingConstants.CENTER font = Font("Trebuchet MS", Font.BOLD, 15) @@ -24,12 +29,10 @@ class X01ScoreRenderer : DefaultTableCellRenderer() return this } - private fun setColours(table: JTable, modelRow: Int) - { + private fun setColours(table: JTable, modelRow: Int) { val tm = table.model val darts = getDartsForRow(tm, modelRow) - if (darts.isEmpty()) - { + if (darts.isEmpty()) { foreground = null background = null return @@ -44,18 +47,15 @@ class X01ScoreRenderer : DefaultTableCellRenderer() background = bg } - private fun getDartsForRow(tm: TableModel, row: Int): List - { + private fun getDartsForRow(tm: TableModel, row: Int): List { val ret = mutableListOf() - for (i in 0 until DartsScorerX01.SCORE_COLUMN) - { + for (i in 0 until DartsScorerX01.SCORE_COLUMN) { val drt = tm.getValueAt(row, i) as Dart? - if (drt != null && drt !is DartHint) - { + if (drt != null && drt !is DartHint) { ret.add(drt) } } return ret } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/game/x01/GamePanelX01.kt b/src/main/kotlin/dartzee/screen/game/x01/GamePanelX01.kt index 2cb9aba5e..0ed45f07c 100644 --- a/src/main/kotlin/dartzee/screen/game/x01/GamePanelX01.kt +++ b/src/main/kotlin/dartzee/screen/game/x01/GamePanelX01.kt @@ -25,137 +25,168 @@ import dartzee.utils.isShanghai import dartzee.utils.shouldStopForMercyRule import dartzee.utils.sumScore -class GamePanelX01(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int): - GamePanelPausable(parent, game, totalPlayers) -{ +class GamePanelX01(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) : + GamePanelPausable(parent, game, totalPlayers) { private val startingScore = Integer.parseInt(game.gameParams) override fun factoryState(pt: IWrappedParticipant) = X01PlayerState(startingScore, pt) - override fun saveDartsAndProceed() - { - //Finalise the scorer + override fun saveDartsAndProceed() { + // Finalise the scorer val lastDart = getDartsThrown().last() val bust = isBust(lastDart) val count = getCurrentPlayerState().getBadLuckCount() - if (count > 0) - { - AchievementEntity.updateAchievement(AchievementType.X01_SUCH_BAD_LUCK, getCurrentPlayerId(), getGameId(), count) + if (count > 0) { + AchievementEntity.updateAchievement( + AchievementType.X01_SUCH_BAD_LUCK, + getCurrentPlayerId(), + getGameId(), + count + ) } - if (!bust) - { + if (!bust) { val totalScore = sumScore(getDartsThrown()) - if (totalScore == 69) - { + if (totalScore == 69) { dartboard.doChucklevision() updateForUniqueScore(AchievementType.X01_CHUCKLEVISION) } - if (totalScore == 26) - { + if (totalScore == 26) { dartboard.doFawlty() updateForUniqueScore(AchievementType.X01_HOTEL_INSPECTOR) } - if (isShanghai(getDartsThrown())) - { - AchievementEntity.insertAchievement(AchievementType.X01_SHANGHAI, getCurrentPlayerId(), getGameId()) + if (isShanghai(getDartsThrown())) { + AchievementEntity.insertAchievement( + AchievementType.X01_SHANGHAI, + getCurrentPlayerId(), + getGameId() + ) } dartboard.playDodgySound("" + totalScore) val total = sumScore(getDartsThrown()) - AchievementEntity.updateAchievement(AchievementType.X01_BEST_THREE_DART_SCORE, getCurrentPlayerId(), getGameId(), total) - } - else - { - val startingScoreForRound = getCurrentPlayerState().getRemainingScoreForRound(currentRoundNumber - 1) - AchievementEntity.updateAchievement(AchievementType.X01_HIGHEST_BUST, getCurrentPlayerId(), getGameId(), startingScoreForRound) + AchievementEntity.updateAchievement( + AchievementType.X01_BEST_THREE_DART_SCORE, + getCurrentPlayerId(), + getGameId(), + total + ) + } else { + val startingScoreForRound = + getCurrentPlayerState().getRemainingScoreForRound(currentRoundNumber - 1) + AchievementEntity.updateAchievement( + AchievementType.X01_HIGHEST_BUST, + getCurrentPlayerId(), + getGameId(), + startingScoreForRound + ) } super.saveDartsAndProceed() } - private fun updateForUniqueScore(achievementType: AchievementType) - { - //Need to have thrown 3 darts, all of which didn't miss. - if (getDartsThrown().any { d -> d.multiplier == 0 } - || dartsThrownCount() < 3) - { + private fun updateForUniqueScore(achievementType: AchievementType) { + // Need to have thrown 3 darts, all of which didn't miss. + if (getDartsThrown().any { d -> d.multiplier == 0 } || dartsThrownCount() < 3) { return } val methodStr = getSortedDartStr(getDartsThrown()) - val existingRow = retrieveAchievementForDetail(achievementType, getCurrentPlayerId(), methodStr) - if (existingRow == null) - { - AchievementEntity.insertAchievement(achievementType, getCurrentPlayerId(), getGameId(), methodStr) + val existingRow = + retrieveAchievementForDetail(achievementType, getCurrentPlayerId(), methodStr) + if (existingRow == null) { + AchievementEntity.insertAchievement( + achievementType, + getCurrentPlayerId(), + getGameId(), + methodStr + ) } } override fun currentPlayerHasFinished() = getCurrentPlayerState().getRemainingScore() == 0 - override fun updateAchievementsForFinish(playerState: X01PlayerState, finishingPosition: Int, score: Int) - { + override fun updateAchievementsForFinish( + playerState: X01PlayerState, + finishingPosition: Int, + score: Int + ) { super.updateAchievementsForFinish(playerState, finishingPosition, score) val playerId = playerState.lastIndividual().playerId val finalRound = getCurrentPlayerState().getLastRound() val sum = sumScore(finalRound) - AchievementEntity.updateAchievement(AchievementType.X01_BEST_FINISH, playerId, getGameId(), sum) - - if (finalRound.count { it.multiplier > 1 } > 1) - { + AchievementEntity.updateAchievement( + AchievementType.X01_BEST_FINISH, + playerId, + getGameId(), + sum + ) + + if (finalRound.count { it.multiplier > 1 } > 1) { val method = finalRound.joinToString() - AchievementEntity.insertAchievement(AchievementType.X01_STYLISH_FINISH, playerId, getGameId(), method, sum) + AchievementEntity.insertAchievement( + AchievementType.X01_STYLISH_FINISH, + playerId, + getGameId(), + method, + sum + ) } - //Insert into the X01Finishes table for the leaderboard + // Insert into the X01Finishes table for the leaderboard X01FinishEntity.factoryAndSave(playerId, getGameId(), sum) val checkout = finalRound.last().score - AchievementEntity.insertForUniqueCounter(AchievementType.X01_CHECKOUT_COMPLETENESS, playerId, getGameId(), checkout, "") - - if (sum in listOf(3, 5, 7, 9)) - { - AchievementEntity.insertAchievement(AchievementType.X01_NO_MERCY, playerId, getGameId(), "$sum") + AchievementEntity.insertForUniqueCounter( + AchievementType.X01_CHECKOUT_COMPLETENESS, + playerId, + getGameId(), + checkout, + "" + ) + + if (sum in listOf(3, 5, 7, 9)) { + AchievementEntity.insertAchievement( + AchievementType.X01_NO_MERCY, + playerId, + getGameId(), + "$sum" + ) } - if (checkout == 1) - { + if (checkout == 1) { AchievementEntity.insertAchievement(AchievementType.X01_BTBF, playerId, getGameId()) } } - override fun updateVariablesForDartThrown(dart: Dart) - { - if (isNearMissDouble(dart)) - { + override fun updateVariablesForDartThrown(dart: Dart) { + if (isNearMissDouble(dart)) { dartboard.doBadLuck() } } override fun shouldStopAfterDartThrown() = getCurrentPlayerState().isCurrentRoundComplete() - override fun computeAiDart(model: DartsAiModel): ComputedPoint? - { - val startOfRoundScore = getCurrentPlayerState().getRemainingScoreForRound(currentRoundNumber - 1) + override fun computeAiDart(model: DartsAiModel): ComputedPoint? { + val startOfRoundScore = + getCurrentPlayerState().getRemainingScoreForRound(currentRoundNumber - 1) val currentScore = getCurrentPlayerState().getRemainingScore() - return if (shouldStopForMercyRule(model, startOfRoundScore, currentScore)) - { + return if (shouldStopForMercyRule(model, startOfRoundScore, currentScore)) { stopThrowing() null - } - else - { + } else { model.throwX01Dart(currentScore) } } - override fun factoryScorer(participant: IWrappedParticipant) = DartsScorerX01(this, gameEntity.gameParams, participant) + override fun factoryScorer(participant: IWrappedParticipant) = + DartsScorerX01(this, gameEntity.gameParams, participant) override fun factoryStatsPanel(gameParams: String) = GameStatisticsPanelX01(gameParams) diff --git a/src/main/kotlin/dartzee/screen/game/x01/GameStatisticsPanelX01.kt b/src/main/kotlin/dartzee/screen/game/x01/GameStatisticsPanelX01.kt index f6cf8dd0a..a0efda90a 100644 --- a/src/main/kotlin/dartzee/screen/game/x01/GameStatisticsPanelX01.kt +++ b/src/main/kotlin/dartzee/screen/game/x01/GameStatisticsPanelX01.kt @@ -18,17 +18,14 @@ import java.beans.PropertyChangeListener import javax.swing.JLabel import javax.swing.JPanel -/** - * Shows running stats for X01 games - three-dart average, checkout % etc. - */ -open class GameStatisticsPanelX01(gameParams: String): AbstractGameStatisticsPanel(), PropertyChangeListener -{ +/** Shows running stats for X01 games - three-dart average, checkout % etc. */ +open class GameStatisticsPanelX01(gameParams: String) : + AbstractGameStatisticsPanel(), PropertyChangeListener { private val panel = JPanel() private val lblSetupThreshold = JLabel("Setup Threshold") val nfSetupThreshold = NumberField() - init - { + init { add(panel, BorderLayout.NORTH) panel.add(lblSetupThreshold) @@ -41,13 +38,26 @@ open class GameStatisticsPanelX01(gameParams: String): AbstractGameStatisticsPan nfSetupThreshold.setMaximum(Integer.parseInt(gameParams) - 1) } - override fun getRankedRowsHighestWins() = listOf("Highest Score", "3-dart avg", "Lowest Score", "Treble %", "Checkout %") + override fun getRankedRowsHighestWins() = + listOf("Highest Score", "3-dart avg", "Lowest Score", "Treble %", "Checkout %") + override fun getRankedRowsLowestWins() = listOf("Miss %") - override fun getHistogramRows() = listOf("180", "140 - 179", "100 - 139", "80 - 99", "60 - 79", "40 - 59", "20 - 39", "0 - 19") + + override fun getHistogramRows() = + listOf( + "180", + "140 - 179", + "100 - 139", + "80 - 99", + "60 - 79", + "40 - 59", + "20 - 39", + "0 - 19" + ) + override fun getStartOfSectionRows() = listOf("180", "Top Darts", "Checkout %", "Best Game") - override fun addRowsToTable() - { + override fun addRowsToTable() { addRow(getScoreRow("Highest Score") { it.maxOrZero() }) addRow(getThreeDartAvgsRow()) addRow(getScoreRow("Lowest Score") { it.minOrZero() }) @@ -70,8 +80,7 @@ open class GameStatisticsPanelX01(gameParams: String): AbstractGameStatisticsPan table.setColumnWidths("120") } - private fun addTopDartsRows() - { + private fun addTopDartsRows() { val topDarts = factoryRow("Top Darts") val secondDarts = factoryRow("") val thirdDarts = factoryRow("") @@ -79,16 +88,18 @@ open class GameStatisticsPanelX01(gameParams: String): AbstractGameStatisticsPan val fifthDarts = factoryRow("") val remainingDarts = factoryRow("Remainder") - for (i in uniqueParticipantNamesOrdered.indices) - { + for (i in uniqueParticipantNamesOrdered.indices) { val playerName = uniqueParticipantNamesOrdered[i] val darts = getScoringDarts(playerName) - val hmHitScoreToDarts = darts.groupBy{it.getHitScore()} - val sortedEntries = hmHitScoreToDarts.entries - .sortedWith(compareByDescending>> {it.value.size} - .thenByDescending{it.key}) - .toMutableList() + val hmHitScoreToDarts = darts.groupBy { it.getHitScore() } + val sortedEntries = + hmHitScoreToDarts.entries + .sortedWith( + compareByDescending>> { it.value.size } + .thenByDescending { it.key } + ) + .toMutableList() parseTopDartEntry(sortedEntries, topDarts, i, darts.size) parseTopDartEntry(sortedEntries, secondDarts, i, darts.size) @@ -96,10 +107,10 @@ open class GameStatisticsPanelX01(gameParams: String): AbstractGameStatisticsPan parseTopDartEntry(sortedEntries, fourthDarts, i, darts.size) parseTopDartEntry(sortedEntries, fifthDarts, i, darts.size) - //Deal with the remainder + // Deal with the remainder val remainder = sortedEntries.map { it.value.size }.sum().toDouble() val percent = MathsUtil.getPercentage(remainder, darts.size, 0).toInt() - remainingDarts[i+1] = "$percent%" + remainingDarts[i + 1] = "$percent%" } addRow(topDarts) @@ -109,83 +120,82 @@ open class GameStatisticsPanelX01(gameParams: String): AbstractGameStatisticsPan addRow(fifthDarts) addRow(remainingDarts) } - private fun parseTopDartEntry(sortedEntries: MutableList>>, row: Array, - i: Int, totalDarts: Int) - { - if (sortedEntries.isEmpty()) - { - row[i+1] = "N/A [0%]" - } - else - { + + private fun parseTopDartEntry( + sortedEntries: MutableList>>, + row: Array, + i: Int, + totalDarts: Int + ) { + if (sortedEntries.isEmpty()) { + row[i + 1] = "N/A [0%]" + } else { val entry = sortedEntries.removeAt(0) val percent = MathsUtil.getPercentage(entry.value.size, totalDarts, 0).toInt() - row[i+1] = "${entry.key} [$percent%]" + row[i + 1] = "${entry.key} [$percent%]" } } + private fun getThreeDartAvgsRow() = + prepareRow("3-dart avg") { playerName -> + val darts = getFlattenedDarts(playerName) - private fun getThreeDartAvgsRow() = prepareRow("3-dart avg") { playerName -> - val darts = getFlattenedDarts(playerName) - - val avg = calculateThreeDartAverage(darts, nfSetupThreshold.getNumber()) - if (avg < 0) null else MathsUtil.round(avg, 2) - } + val avg = calculateThreeDartAverage(darts, nfSetupThreshold.getNumber()) + if (avg < 0) null else MathsUtil.round(avg, 2) + } - private fun getCheckoutPercentRow() = prepareRow("Checkout %") { playerName -> - val darts = getFlattenedDarts(playerName) + private fun getCheckoutPercentRow() = + prepareRow("Checkout %") { playerName -> + val darts = getFlattenedDarts(playerName) - val potentialFinishers = darts.filter { d -> isCheckoutDart(d) } - val actualFinishes = potentialFinishers.filter { d -> d.isDouble() && d.getTotal() == d.startingScore } + val potentialFinishers = darts.filter { d -> isCheckoutDart(d) } + val actualFinishes = + potentialFinishers.filter { d -> d.isDouble() && d.getTotal() == d.startingScore } - if (actualFinishes.isEmpty()) - { - null - } - else - { - MathsUtil.getPercentage(actualFinishes.size, potentialFinishers.size) + if (actualFinishes.isEmpty()) { + null + } else { + MathsUtil.getPercentage(actualFinishes.size, potentialFinishers.size) + } } - } - private fun getScoresBetween(min: Int, max: Int, desc: String) = prepareRow(desc) { playerName -> - val rounds = getScoringRounds(playerName) - val roundsInRange = rounds.filter { r -> sumScore(r) in min until max } - roundsInRange.size - } + private fun getScoresBetween(min: Int, max: Int, desc: String) = + prepareRow(desc) { playerName -> + val rounds = getScoringRounds(playerName) + val roundsInRange = rounds.filter { r -> sumScore(r) in min until max } + roundsInRange.size + } - private fun getScoreRow(desc: String, f: (i: List) -> Int) = prepareRow(desc) { playerName -> - val rounds = getScoringRounds(playerName) - val roundsAsTotal = rounds.map { rnd -> sumScore(rnd) } - if (roundsAsTotal.isEmpty()) null else f(roundsAsTotal) - } + private fun getScoreRow(desc: String, f: (i: List) -> Int) = + prepareRow(desc) { playerName -> + val rounds = getScoringRounds(playerName) + val roundsAsTotal = rounds.map { rnd -> sumScore(rnd) } + if (roundsAsTotal.isEmpty()) null else f(roundsAsTotal) + } - private fun getMultiplePercent(desc: String, multiplier: Int) = prepareRow(desc) { playerName -> - val scoringDarts = getScoringDarts(playerName) - val hits = scoringDarts.filter { d -> d.multiplier == multiplier } - MathsUtil.getPercentage(hits.size, scoringDarts.size) - } + private fun getMultiplePercent(desc: String, multiplier: Int) = + prepareRow(desc) { playerName -> + val scoringDarts = getScoringDarts(playerName) + val hits = scoringDarts.filter { d -> d.multiplier == multiplier } + MathsUtil.getPercentage(hits.size, scoringDarts.size) + } - private fun getScoringRounds(playerName: UniqueParticipantName): List> - { + private fun getScoringRounds(playerName: UniqueParticipantName): List> { val rounds = hmPlayerToDarts[playerName] rounds ?: return mutableListOf() return rounds.filter { it.last().startingScore > nfSetupThreshold.getNumber() }.toList() } - private fun getScoringDarts(playerName: UniqueParticipantName): List - { + private fun getScoringDarts(playerName: UniqueParticipantName): List { val darts = getFlattenedDarts(playerName) return getScoringDarts(darts, nfSetupThreshold.getNumber()) } - override fun propertyChange(arg0: PropertyChangeEvent) - { + override fun propertyChange(arg0: PropertyChangeEvent) { val propertyName = arg0.propertyName - if (propertyName == "value") - { + if (propertyName == "value") { buildTableModel() repaint() } diff --git a/src/main/kotlin/dartzee/screen/game/x01/MatchStatisticsPanelX01.kt b/src/main/kotlin/dartzee/screen/game/x01/MatchStatisticsPanelX01.kt index 43c0b7d28..2da609869 100644 --- a/src/main/kotlin/dartzee/screen/game/x01/MatchStatisticsPanelX01.kt +++ b/src/main/kotlin/dartzee/screen/game/x01/MatchStatisticsPanelX01.kt @@ -4,10 +4,8 @@ import dartzee.core.util.minOrZero import dartzee.utils.isFinishRound import dartzee.utils.sumScore -class MatchStatisticsPanelX01(gameParams: String): GameStatisticsPanelX01(gameParams) -{ - override fun addRowsToTable() - { +class MatchStatisticsPanelX01(gameParams: String) : GameStatisticsPanelX01(gameParams) { + override fun addRowsToTable() { super.addRowsToTable() addRow(getHighestFinishRow()) @@ -16,12 +14,15 @@ class MatchStatisticsPanelX01(gameParams: String): GameStatisticsPanelX01(gamePa addRow(getAverageGameRow()) } - private fun getHighestFinishRow() = prepareRow("Best Finish") { playerName -> - val rounds = hmPlayerToDarts[playerName].orEmpty() - val finishRounds = rounds.filter { r -> isFinishRound(r) } - finishRounds.maxOfOrNull { r -> sumScore(r) } - } + private fun getHighestFinishRow() = + prepareRow("Best Finish") { playerName -> + val rounds = hmPlayerToDarts[playerName].orEmpty() + val finishRounds = rounds.filter { r -> isFinishRound(r) } + finishRounds.maxOfOrNull { r -> sumScore(r) } + } override fun getRankedRowsHighestWins() = super.getRankedRowsHighestWins() + "Best Finish" - override fun getRankedRowsLowestWins() = super.getRankedRowsLowestWins() + "Best Game" + "Avg Game" + + override fun getRankedRowsLowestWins() = + super.getRankedRowsLowestWins() + "Best Game" + "Avg Game" } diff --git a/src/main/kotlin/dartzee/screen/game/x01/X01MatchScreen.kt b/src/main/kotlin/dartzee/screen/game/x01/X01MatchScreen.kt index f470af333..d17e53eb7 100644 --- a/src/main/kotlin/dartzee/screen/game/x01/X01MatchScreen.kt +++ b/src/main/kotlin/dartzee/screen/game/x01/X01MatchScreen.kt @@ -7,9 +7,14 @@ import dartzee.screen.game.AbstractDartsGameScreen import dartzee.screen.game.DartsMatchScreen import dartzee.screen.game.MatchSummaryPanel -class X01MatchScreen(match: DartsMatchEntity): - DartsMatchScreen(MatchSummaryPanel(match, MatchStatisticsPanelX01(match.gameParams)), match) -{ - override fun factoryGamePanel(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int) = - GamePanelX01(parent, game, totalPlayers) -} \ No newline at end of file +class X01MatchScreen(match: DartsMatchEntity) : + DartsMatchScreen( + MatchSummaryPanel(match, MatchStatisticsPanelX01(match.gameParams)), + match + ) { + override fun factoryGamePanel( + parent: AbstractDartsGameScreen, + game: GameEntity, + totalPlayers: Int + ) = GamePanelX01(parent, game, totalPlayers) +} diff --git a/src/main/kotlin/dartzee/screen/player/PlayerAchievementsButton.kt b/src/main/kotlin/dartzee/screen/player/PlayerAchievementsButton.kt index 4fcbbdb2e..c4356fc9b 100644 --- a/src/main/kotlin/dartzee/screen/player/PlayerAchievementsButton.kt +++ b/src/main/kotlin/dartzee/screen/player/PlayerAchievementsButton.kt @@ -7,14 +7,14 @@ import dartzee.db.PlayerEntity import dartzee.screen.ScreenCache import javax.swing.ImageIcon -class PlayerAchievementsButton(private val player: PlayerEntity, - private val achievementRows: List): PlayerSummaryButton() -{ +class PlayerAchievementsButton( + private val player: PlayerEntity, + private val achievementRows: List +) : PlayerSummaryButton() { override val defaultText = makeDefaultText() override val hoverText = "

Achievements >

" - init - { + init { icon = ImageIcon(javaClass.getResource("/achievements/trophy.png")) text = defaultText @@ -25,16 +25,14 @@ class PlayerAchievementsButton(private val player: PlayerEntity, addMouseListener(this) } - private fun makeDefaultText(): String - { + private fun makeDefaultText(): String { val score = getPlayerAchievementScore(achievementRows, player) val lineOne = "

Achievements

" val lineTwo = "$score / ${getAchievementMaximum()}" return "
$lineOne $lineTwo
" } - override fun buttonPressed() - { + override fun buttonPressed() { ScreenCache.switchToAchievementsScreen(player) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/player/PlayerManagementPanel.kt b/src/main/kotlin/dartzee/screen/player/PlayerManagementPanel.kt index 5776d405b..b10d0413b 100644 --- a/src/main/kotlin/dartzee/screen/player/PlayerManagementPanel.kt +++ b/src/main/kotlin/dartzee/screen/player/PlayerManagementPanel.kt @@ -29,8 +29,7 @@ import javax.swing.JPanel import javax.swing.SwingConstants import javax.swing.border.EmptyBorder -class PlayerManagementPanel : JPanel(), ActionListener -{ +class PlayerManagementPanel : JPanel(), ActionListener { private var player: PlayerEntity? = null private val btnEdit = JButton("Edit") @@ -41,8 +40,7 @@ class PlayerManagementPanel : JPanel(), ActionListener private val panelCenter = JPanel() private val btnRunSimulation = JButton("Run Simulation") - init - { + init { layout = BorderLayout(0, 0) val panelOptions = JPanel() @@ -84,13 +82,12 @@ class PlayerManagementPanel : JPanel(), ActionListener panelCenter.layout = WrapLayout() } - fun refresh(player: PlayerEntity?) - { + fun refresh(player: PlayerEntity?) { this.player = player lblPlayerName.text = player?.name.orEmpty() - //Only show this for AIs + // Only show this for AIs btnRunSimulation.isVisible = player?.isAi() == true btnEdit.isVisible = player != null @@ -108,8 +105,7 @@ class PlayerManagementPanel : JPanel(), ActionListener revalidate() } - private fun addSummaryPanels(player: PlayerEntity) - { + private fun addSummaryPanels(player: PlayerEntity) { val counts = getGameCounts(player) val achievements = AchievementEntity.retrieveAchievements(player.rowId) @@ -119,48 +115,52 @@ class PlayerManagementPanel : JPanel(), ActionListener panelCenter.add(PlayerAchievementsButton(player, achievements)) } - private fun makeStatsButton(player: PlayerEntity, gameCounts: HashMapCount, achievements: List, gameType: GameType): PlayerStatsButton - { + private fun makeStatsButton( + player: PlayerEntity, + gameCounts: HashMapCount, + achievements: List, + gameType: GameType + ): PlayerStatsButton { val gamesPlayed = gameCounts.getCount(gameType) - val achievement = achievements.find { it.achievementType == getBestGameAchievement(gameType)?.achievementType } + val achievement = + achievements.find { + it.achievementType == getBestGameAchievement(gameType)?.achievementType + } val bestScore: Int = achievement?.achievementCounter ?: 0 return PlayerStatsButton(player, gameType, gamesPlayed, bestScore) } - override fun actionPerformed(arg0: ActionEvent) - { + override fun actionPerformed(arg0: ActionEvent) { val selectedPlayer = player ?: return - when (arg0.source) - { + when (arg0.source) { btnEdit -> amendPlayer(selectedPlayer) btnDelete -> confirmAndDeletePlayer(selectedPlayer) - btnRunSimulation -> AISimulationSetupDialog(selectedPlayer, selectedPlayer.getModel()).isVisible = true + btnRunSimulation -> + AISimulationSetupDialog(selectedPlayer, selectedPlayer.getModel()).isVisible = true } } - private fun amendPlayer(playerEntity: PlayerEntity) - { - if (playerEntity.isAi()) - { + private fun amendPlayer(playerEntity: PlayerEntity) { + if (playerEntity.isAi()) { AIConfigurationDialog.amendPlayer(::refresh, playerEntity) - } - else - { + } else { HumanConfigurationDialog.amendPlayer(::refresh, playerEntity) } } - private fun confirmAndDeletePlayer(selectedPlayer: PlayerEntity) - { - val option = DialogUtil.showQuestionOLD("Are you sure you want to delete ${selectedPlayer.name}?", false) - if (option == JOptionPane.YES_OPTION) - { + private fun confirmAndDeletePlayer(selectedPlayer: PlayerEntity) { + val option = + DialogUtil.showQuestionOLD( + "Are you sure you want to delete ${selectedPlayer.name}?", + false + ) + if (option == JOptionPane.YES_OPTION) { selectedPlayer.dtDeleted = getSqlDateNow() selectedPlayer.saveToDatabase() - //Re-initialise the screen so it updates + // Re-initialise the screen so it updates ScreenCache.get().initialise() } } diff --git a/src/main/kotlin/dartzee/screen/player/PlayerManagementScreen.kt b/src/main/kotlin/dartzee/screen/player/PlayerManagementScreen.kt index 616234c59..34949f9ca 100644 --- a/src/main/kotlin/dartzee/screen/player/PlayerManagementScreen.kt +++ b/src/main/kotlin/dartzee/screen/player/PlayerManagementScreen.kt @@ -22,22 +22,21 @@ import javax.swing.border.TitledBorder import javax.swing.event.ListSelectionEvent import javax.swing.event.ListSelectionListener -class PlayerManagementScreen : EmbeddedScreen(), ListSelectionListener -{ +class PlayerManagementScreen : EmbeddedScreen(), ListSelectionListener { private val tablePlayers = ScrollTable() private val panel = PlayerManagementPanel() private val btnNewPlayer = JButton("") private val panelNorth = JPanel() private val btnNewAi = JButton("") - init - { + init { val sideBar = JPanel() sideBar.layout = BorderLayout(0, 0) val panelPlayers = JPanel() panelPlayers.preferredSize = Dimension(200, 300) - panelPlayers.border = TitledBorder(null, "Players", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelPlayers.border = + TitledBorder(null, "Players", TitledBorder.LEADING, TitledBorder.TOP, null, null) sideBar.add(panelPlayers, BorderLayout.CENTER) add(sideBar, BorderLayout.WEST) @@ -48,13 +47,15 @@ class PlayerManagementScreen : EmbeddedScreen(), ListSelectionListener sideBar.add(panelNorth, BorderLayout.NORTH) panelNorth.layout = FlowLayout(FlowLayout.LEFT, 5, 5) - btnNewPlayer.icon = ImageIcon(PlayerManagementScreen::class.java.getResource("/buttons/addHuman.png")) + btnNewPlayer.icon = + ImageIcon(PlayerManagementScreen::class.java.getResource("/buttons/addHuman.png")) btnNewPlayer.preferredSize = Dimension(30, 30) btnNewPlayer.toolTipText = "Add player" btnNewPlayer.name = "AddPlayer" panelNorth.add(btnNewPlayer) btnNewPlayer.border = EmptyBorder(5, 0, 5, 0) - btnNewAi.icon = ImageIcon(PlayerManagementScreen::class.java.getResource("/buttons/addAi.png")) + btnNewAi.icon = + ImageIcon(PlayerManagementScreen::class.java.getResource("/buttons/addAi.png")) btnNewAi.toolTipText = "Add computer" btnNewAi.name = "AddAi" btnNewAi.preferredSize = Dimension(30, 30) @@ -66,13 +67,12 @@ class PlayerManagementScreen : EmbeddedScreen(), ListSelectionListener model.selectionMode = ListSelectionModel.SINGLE_SELECTION model.addListSelectionListener(this) - //Listeners + // Listeners btnNewPlayer.addActionListener(this) btnNewAi.addActionListener(this) } - override fun initialise() - { + override fun initialise() { val players = PlayerEntity.retrievePlayers("") tablePlayers.initPlayerTableModel(players) refreshSummaryPanel() @@ -80,32 +80,29 @@ class PlayerManagementScreen : EmbeddedScreen(), ListSelectionListener override fun getScreenName() = "Player Management" - override fun valueChanged(arg0: ListSelectionEvent) - { + override fun valueChanged(arg0: ListSelectionEvent) { refreshSummaryPanel() } - private fun refreshSummaryPanel() - { + private fun refreshSummaryPanel() { val player = tablePlayers.getSelectedPlayer() panel.refresh(player) } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnNewPlayer -> createPlayer(true) btnNewAi -> createPlayer(false) else -> super.actionPerformed(arg0) } } - private fun createPlayer(human: Boolean) - { + private fun createPlayer(human: Boolean) { val playerUpdated = { _: PlayerEntity -> initialise() } - val dlg = if (human) HumanConfigurationDialog(playerUpdated) else AIConfigurationDialog(playerUpdated) + val dlg = + if (human) HumanConfigurationDialog(playerUpdated) + else AIConfigurationDialog(playerUpdated) dlg.setLocationRelativeTo(ScreenCache.mainScreen) dlg.isVisible = true } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/player/PlayerStatsButton.kt b/src/main/kotlin/dartzee/screen/player/PlayerStatsButton.kt index a6667a03e..53e9cd202 100644 --- a/src/main/kotlin/dartzee/screen/player/PlayerStatsButton.kt +++ b/src/main/kotlin/dartzee/screen/player/PlayerStatsButton.kt @@ -7,17 +7,17 @@ import dartzee.screen.ScreenCache import dartzee.screen.stats.player.PlayerStatisticsScreen import javax.swing.ImageIcon -class PlayerStatsButton(private val player: PlayerEntity, - private val gameType: GameType, - played: Int, - highScore: Int) : PlayerSummaryButton() -{ +class PlayerStatsButton( + private val player: PlayerEntity, + private val gameType: GameType, + played: Int, + highScore: Int +) : PlayerSummaryButton() { private val iconUrl = getGamesWonIcon(gameType) override val defaultText = makeStatsText(played, highScore) override val hoverText = "

${gameType.getDescription()} stats >

" - init - { + init { icon = ImageIcon(iconUrl) text = defaultText @@ -30,8 +30,7 @@ class PlayerStatsButton(private val player: PlayerEntity, addMouseListener(this) } - private fun makeStatsText(played: Int, highScore: Int): String - { + private fun makeStatsText(played: Int, highScore: Int): String { val scoreDesc = if (highScore > 0) "$highScore" else "-" val lineOne = "

${gameType.getDescription()}

" @@ -40,8 +39,7 @@ class PlayerStatsButton(private val player: PlayerEntity, return "
$lineOne $lineTwo
$lineThree
" } - override fun buttonPressed() - { + override fun buttonPressed() { val statsScrn = ScreenCache.get() statsScrn.setVariables(gameType, player) diff --git a/src/main/kotlin/dartzee/screen/player/PlayerSummaryButton.kt b/src/main/kotlin/dartzee/screen/player/PlayerSummaryButton.kt index 12a915dd9..d2b166e46 100644 --- a/src/main/kotlin/dartzee/screen/player/PlayerSummaryButton.kt +++ b/src/main/kotlin/dartzee/screen/player/PlayerSummaryButton.kt @@ -7,36 +7,30 @@ import java.awt.event.ActionListener import java.awt.event.MouseEvent import javax.swing.JButton -abstract class PlayerSummaryButton: JButton(), ActionListener, IMouseListener -{ +abstract class PlayerSummaryButton : JButton(), ActionListener, IMouseListener { abstract val defaultText: String abstract val hoverText: String - init - { + init { preferredSize = Dimension(275, 100) iconTextGap = 10 } abstract fun buttonPressed() - override fun actionPerformed(e: ActionEvent?) - { + override fun actionPerformed(e: ActionEvent?) { buttonPressed() text = defaultText } - override fun mouseEntered(e: MouseEvent) - { - if (isEnabled) - { + override fun mouseEntered(e: MouseEvent) { + if (isEnabled) { text = hoverText } } - override fun mouseExited(e: MouseEvent) - { + override fun mouseExited(e: MouseEvent) { text = defaultText } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/preference/AbstractPreferencesPanel.kt b/src/main/kotlin/dartzee/screen/preference/AbstractPreferencesPanel.kt index 4d73e8b55..bf48192b5 100644 --- a/src/main/kotlin/dartzee/screen/preference/AbstractPreferencesPanel.kt +++ b/src/main/kotlin/dartzee/screen/preference/AbstractPreferencesPanel.kt @@ -9,16 +9,14 @@ import java.awt.event.ActionListener import javax.swing.JButton import javax.swing.JPanel -abstract class AbstractPreferencesPanel : JPanel() -{ +abstract class AbstractPreferencesPanel : JPanel() { abstract val title: String private val panelOptions = JPanel() private val btnApply = JButton("Apply") private val btnRestoreDefaults = JButton("Restore Defaults") - init - { + init { layout = BorderLayout(0, 0) add(panelOptions, BorderLayout.SOUTH) panelOptions.add(btnApply) @@ -32,48 +30,43 @@ abstract class AbstractPreferencesPanel : JPanel() btnRestoreDefaults.addActionListener(listener) } - fun refresh(useDefaults: Boolean) - { + fun refresh(useDefaults: Boolean) { refreshImpl(useDefaults) stateChanged() } - fun stateChanged() - { + fun stateChanged() { btnApply.isEnabled = hasOutstandingChanges() } - inner class PreferencesPanelListener: ActionListener - { - override fun actionPerformed(e: ActionEvent?) - { - when (e?.source) - { + inner class PreferencesPanelListener : ActionListener { + override fun actionPerformed(e: ActionEvent?) { + when (e?.source) { btnApply -> save() btnRestoreDefaults -> refresh(true) } } - private fun save() - { + private fun save() { saveImpl() stateChanged() - //Refresh all active screens in case we've changed appearance preferences + // Refresh all active screens in case we've changed appearance preferences resetCachedDartboardValues() - ScreenCache.getDartsGameScreens().forEach{ - it.fireAppearancePreferencesChanged() - } + ScreenCache.getDartsGameScreens().forEach { it.fireAppearancePreferencesChanged() } } } /** * Refresh this panel * - * @param useDefaults: If true, the panel will refresh using the default values of its preferences. + * @param useDefaults: If true, the panel will refresh using the default values of its + * preferences. */ abstract fun refreshImpl(useDefaults: Boolean) + abstract fun saveImpl() + abstract fun hasOutstandingChanges(): Boolean } diff --git a/src/main/kotlin/dartzee/screen/preference/PreferencesPanelDartboard.kt b/src/main/kotlin/dartzee/screen/preference/PreferencesPanelDartboard.kt index e00accf5b..0252a3899 100644 --- a/src/main/kotlin/dartzee/screen/preference/PreferencesPanelDartboard.kt +++ b/src/main/kotlin/dartzee/screen/preference/PreferencesPanelDartboard.kt @@ -13,15 +13,14 @@ import dartzee.utils.PREFERENCES_STRING_ODD_DOUBLE_COLOUR import dartzee.utils.PREFERENCES_STRING_ODD_SINGLE_COLOUR import dartzee.utils.PREFERENCES_STRING_ODD_TREBLE_COLOUR import dartzee.utils.PreferenceUtil -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Color import java.awt.Dimension import javax.swing.JLabel import javax.swing.JPanel +import net.miginfocom.swing.MigLayout -class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionListener -{ +class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionListener { override val title = "Dartboard" private val panelCenter = JPanel() @@ -34,8 +33,7 @@ class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionLis val cpEvenTreble = ColourPicker() private var dartboard = InteractiveDartboard() - init - { + init { panelCenter.layout = BorderLayout() add(panelCenter, BorderLayout.CENTER) panelCenter.add(dartboard, BorderLayout.CENTER) @@ -69,14 +67,19 @@ class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionLis cpEvenTreble.addColourSelectionListener(this) } - override fun refreshImpl(useDefaults: Boolean) - { - val evenSingleStr = PreferenceUtil.getStringValue(PREFERENCES_STRING_EVEN_SINGLE_COLOUR, useDefaults) - val evenDoubleStr = PreferenceUtil.getStringValue(PREFERENCES_STRING_EVEN_DOUBLE_COLOUR, useDefaults) - val evenTrebleStr = PreferenceUtil.getStringValue(PREFERENCES_STRING_EVEN_TREBLE_COLOUR, useDefaults) - val oddSingleStr = PreferenceUtil.getStringValue(PREFERENCES_STRING_ODD_SINGLE_COLOUR, useDefaults) - val oddDoubleStr = PreferenceUtil.getStringValue(PREFERENCES_STRING_ODD_DOUBLE_COLOUR, useDefaults) - val oddTrebleStr = PreferenceUtil.getStringValue(PREFERENCES_STRING_ODD_TREBLE_COLOUR, useDefaults) + override fun refreshImpl(useDefaults: Boolean) { + val evenSingleStr = + PreferenceUtil.getStringValue(PREFERENCES_STRING_EVEN_SINGLE_COLOUR, useDefaults) + val evenDoubleStr = + PreferenceUtil.getStringValue(PREFERENCES_STRING_EVEN_DOUBLE_COLOUR, useDefaults) + val evenTrebleStr = + PreferenceUtil.getStringValue(PREFERENCES_STRING_EVEN_TREBLE_COLOUR, useDefaults) + val oddSingleStr = + PreferenceUtil.getStringValue(PREFERENCES_STRING_ODD_SINGLE_COLOUR, useDefaults) + val oddDoubleStr = + PreferenceUtil.getStringValue(PREFERENCES_STRING_ODD_DOUBLE_COLOUR, useDefaults) + val oddTrebleStr = + PreferenceUtil.getStringValue(PREFERENCES_STRING_ODD_TREBLE_COLOUR, useDefaults) val evenSingle = DartsColour.getColorFromPrefStr(evenSingleStr) val evenDouble = DartsColour.getColorFromPrefStr(evenDoubleStr) @@ -96,8 +99,7 @@ class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionLis refreshDartboard() } - private fun refreshDartboard() - { + private fun refreshDartboard() { val oddSingle = cpOddSingle.selectedColour val oddDouble = cpOddDouble.selectedColour val oddTreble = cpOddTreble.selectedColour @@ -105,8 +107,17 @@ class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionLis val evenDouble = cpEvenDouble.selectedColour val evenTreble = cpEvenTreble.selectedColour - val wrapper = ColourWrapper(evenSingle, evenDouble, evenTreble, - oddSingle, oddDouble, oddTreble, evenDouble, oddDouble) + val wrapper = + ColourWrapper( + evenSingle, + evenDouble, + evenTreble, + oddSingle, + oddDouble, + oddTreble, + evenDouble, + oddDouble + ) panelCenter.remove(dartboard) dartboard = InteractiveDartboard(wrapper) @@ -115,8 +126,7 @@ class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionLis panelCenter.repaint() } - override fun saveImpl() - { + override fun saveImpl() { val oddSingleStr = cpOddSingle.getPrefString() val oddDoubleStr = cpOddDouble.getPrefString() val oddTrebleStr = cpOddTreble.getPrefString() @@ -133,18 +143,17 @@ class PreferencesPanelDartboard : AbstractPreferencesPanel(), ColourSelectionLis } override fun hasOutstandingChanges() = - !cpOddSingle.matchesPreference(PREFERENCES_STRING_ODD_SINGLE_COLOUR) - || !cpOddDouble.matchesPreference(PREFERENCES_STRING_ODD_DOUBLE_COLOUR) - || !cpOddTreble.matchesPreference(PREFERENCES_STRING_ODD_TREBLE_COLOUR) - || !cpEvenSingle.matchesPreference(PREFERENCES_STRING_EVEN_SINGLE_COLOUR) - || !cpEvenDouble.matchesPreference(PREFERENCES_STRING_EVEN_DOUBLE_COLOUR) - || !cpEvenTreble.matchesPreference(PREFERENCES_STRING_EVEN_TREBLE_COLOUR) + !cpOddSingle.matchesPreference(PREFERENCES_STRING_ODD_SINGLE_COLOUR) || + !cpOddDouble.matchesPreference(PREFERENCES_STRING_ODD_DOUBLE_COLOUR) || + !cpOddTreble.matchesPreference(PREFERENCES_STRING_ODD_TREBLE_COLOUR) || + !cpEvenSingle.matchesPreference(PREFERENCES_STRING_EVEN_SINGLE_COLOUR) || + !cpEvenDouble.matchesPreference(PREFERENCES_STRING_EVEN_DOUBLE_COLOUR) || + !cpEvenTreble.matchesPreference(PREFERENCES_STRING_EVEN_TREBLE_COLOUR) private fun ColourPicker.matchesPreference(preferenceKey: String) = getPrefString() == PreferenceUtil.getStringValue(preferenceKey) - override fun colourSelected(colour: Color) - { + override fun colourSelected(colour: Color) { refreshDartboard() stateChanged() } diff --git a/src/main/kotlin/dartzee/screen/preference/PreferencesPanelMisc.kt b/src/main/kotlin/dartzee/screen/preference/PreferencesPanelMisc.kt index 24271fce0..35e5f62a9 100644 --- a/src/main/kotlin/dartzee/screen/preference/PreferencesPanelMisc.kt +++ b/src/main/kotlin/dartzee/screen/preference/PreferencesPanelMisc.kt @@ -9,7 +9,6 @@ import dartzee.utils.PREFERENCES_BOOLEAN_SHOW_ANIMATIONS import dartzee.utils.PREFERENCES_INT_AI_SPEED import dartzee.utils.PREFERENCES_INT_LEADERBOARD_SIZE import dartzee.utils.PreferenceUtil -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener @@ -20,9 +19,10 @@ import javax.swing.JLabel import javax.swing.JPanel import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener +import net.miginfocom.swing.MigLayout -class PreferencesPanelMisc : AbstractPreferencesPanel(), ActionListener, PropertyChangeListener, ChangeListener -{ +class PreferencesPanelMisc : + AbstractPreferencesPanel(), ActionListener, PropertyChangeListener, ChangeListener { override val title = "Misc" private val panelCenter = JPanel() @@ -34,8 +34,7 @@ class PreferencesPanelMisc : AbstractPreferencesPanel(), ActionListener, Propert val nfLeaderboardSize = NumberField(10, 200) val chckbxShowAnimations = JCheckBox("Play sounds/animations") - init - { + init { add(panelCenter, BorderLayout.CENTER) nfLeaderboardSize.columns = 10 panelCenter.layout = MigLayout("", "[][grow][]", "[][][][][][]") @@ -62,17 +61,19 @@ class PreferencesPanelMisc : AbstractPreferencesPanel(), ActionListener, Propert chckbxShowAnimations.addActionListener(this) } - override fun refreshImpl(useDefaults: Boolean) - { + override fun refreshImpl(useDefaults: Boolean) { slider.value = PreferenceUtil.getIntValue(PREFERENCES_INT_AI_SPEED, useDefaults) - nfLeaderboardSize.value = PreferenceUtil.getIntValue(PREFERENCES_INT_LEADERBOARD_SIZE, useDefaults) - chckbxAiAutomaticallyFinish.isSelected = PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE, useDefaults) - chckbxCheckForUpdates.isSelected = PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES, useDefaults) - chckbxShowAnimations.isSelected = PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS, useDefaults) + nfLeaderboardSize.value = + PreferenceUtil.getIntValue(PREFERENCES_INT_LEADERBOARD_SIZE, useDefaults) + chckbxAiAutomaticallyFinish.isSelected = + PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE, useDefaults) + chckbxCheckForUpdates.isSelected = + PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES, useDefaults) + chckbxShowAnimations.isSelected = + PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS, useDefaults) } - override fun saveImpl() - { + override fun saveImpl() { val aiSpd = slider.value PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, aiSpd) @@ -90,14 +91,19 @@ class PreferencesPanelMisc : AbstractPreferencesPanel(), ActionListener, Propert } override fun hasOutstandingChanges() = - slider.value != PreferenceUtil.getIntValue(PREFERENCES_INT_AI_SPEED) - || nfLeaderboardSize.value != PreferenceUtil.getIntValue(PREFERENCES_INT_LEADERBOARD_SIZE) - || chckbxAiAutomaticallyFinish.isSelected != PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) - || chckbxCheckForUpdates.isSelected != PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES) - || chckbxShowAnimations.isSelected != PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS) - + slider.value != PreferenceUtil.getIntValue(PREFERENCES_INT_AI_SPEED) || + nfLeaderboardSize.value != + PreferenceUtil.getIntValue(PREFERENCES_INT_LEADERBOARD_SIZE) || + chckbxAiAutomaticallyFinish.isSelected != + PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) || + chckbxCheckForUpdates.isSelected != + PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES) || + chckbxShowAnimations.isSelected != + PreferenceUtil.getBooleanValue(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS) override fun stateChanged(e: ChangeEvent?) = stateChanged() + override fun propertyChange(evt: PropertyChangeEvent?) = stateChanged() + override fun actionPerformed(e: ActionEvent?) = stateChanged() } diff --git a/src/main/kotlin/dartzee/screen/preference/PreferencesPanelScorer.kt b/src/main/kotlin/dartzee/screen/preference/PreferencesPanelScorer.kt index 6041371ad..80c7b69f8 100644 --- a/src/main/kotlin/dartzee/screen/preference/PreferencesPanelScorer.kt +++ b/src/main/kotlin/dartzee/screen/preference/PreferencesPanelScorer.kt @@ -6,7 +6,6 @@ import dartzee.utils.PREFERENCES_DOUBLE_BG_BRIGHTNESS import dartzee.utils.PREFERENCES_DOUBLE_FG_BRIGHTNESS import dartzee.utils.PREFERENCES_DOUBLE_HUE_FACTOR import dartzee.utils.PreferenceUtil -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Dimension import java.awt.FlowLayout @@ -19,9 +18,9 @@ import javax.swing.SwingConstants import javax.swing.border.TitledBorder import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener +import net.miginfocom.swing.MigLayout -class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener -{ +class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener { override val title = "Scorer" private val panelCenter = JPanel() @@ -34,12 +33,19 @@ class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener val spinnerFgBrightness = JSpinner() val spinnerBgBrightness = JSpinner() - init - { + init { add(panelCenter, BorderLayout.CENTER) panelCenter.layout = MigLayout("al center center, gapy 20") panelCenter.add(panelX01Colours) - panelX01Colours.border = TitledBorder(null, "X01 Colour Scheme", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelX01Colours.border = + TitledBorder( + null, + "X01 Colour Scheme", + TitledBorder.LEADING, + TitledBorder.TOP, + null, + null + ) panelX01Colours.preferredSize = Dimension(600, 160) panelX01Colours.layout = MigLayout("al center center, wrap, gapy 20") @@ -81,8 +87,7 @@ class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener spinnerFgBrightness.addChangeListener(this) } - private fun makeScoreLabel(score: Int): JLabel - { + private fun makeScoreLabel(score: Int): JLabel { val label = JLabel("$score") label.font = Font("Trebuchet MS", Font.BOLD, 15) label.horizontalAlignment = SwingConstants.CENTER @@ -90,11 +95,12 @@ class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener return label } - override fun refreshImpl(useDefaults: Boolean) - { + override fun refreshImpl(useDefaults: Boolean) { val hueFactor = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_HUE_FACTOR, useDefaults) - val bgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS, useDefaults) - val fgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS, useDefaults) + val bgBrightness = + PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS, useDefaults) + val fgBrightness = + PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS, useDefaults) spinnerHueFactor.value = hueFactor spinnerBgBrightness.value = bgBrightness @@ -103,15 +109,13 @@ class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener repaintScorerPreview() } - private fun repaintScorerPreview() - { + private fun repaintScorerPreview() { val hueFactor = spinnerHueFactor.value as Double val fgBrightness = spinnerFgBrightness.value as Double val bgBrightness = spinnerBgBrightness.value as Double val scoreLabels = panelScorerPreview.getAllChildComponentsForType() - for (i in scoreLabels.indices) - { + for (i in scoreLabels.indices) { val scoreLabel = scoreLabels[i] val score = Integer.parseInt(scoreLabel.text) @@ -125,8 +129,7 @@ class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener } } - override fun saveImpl() - { + override fun saveImpl() { val hueFactor = spinnerHueFactor.value as Double val fgBrightness = spinnerFgBrightness.value as Double val bgBrightness = spinnerBgBrightness.value as Double @@ -137,12 +140,13 @@ class PreferencesPanelScorer : AbstractPreferencesPanel(), ChangeListener } override fun hasOutstandingChanges() = - spinnerHueFactor.value != PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_HUE_FACTOR) - || spinnerBgBrightness.value != PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS) - || spinnerFgBrightness.value != PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS) + spinnerHueFactor.value != PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_HUE_FACTOR) || + spinnerBgBrightness.value != + PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS) || + spinnerFgBrightness.value != + PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS) - override fun stateChanged(arg0: ChangeEvent) - { + override fun stateChanged(arg0: ChangeEvent) { repaintScorerPreview() stateChanged() } diff --git a/src/main/kotlin/dartzee/screen/preference/PreferencesScreen.kt b/src/main/kotlin/dartzee/screen/preference/PreferencesScreen.kt index e767205a2..8a1f8ea0c 100644 --- a/src/main/kotlin/dartzee/screen/preference/PreferencesScreen.kt +++ b/src/main/kotlin/dartzee/screen/preference/PreferencesScreen.kt @@ -7,41 +7,36 @@ import javax.swing.JOptionPane import javax.swing.JTabbedPane import javax.swing.SwingConstants -private fun getPreferenceTabs() = listOf(PreferencesPanelDartboard(), PreferencesPanelScorer(), PreferencesPanelMisc()) +private fun getPreferenceTabs() = + listOf(PreferencesPanelDartboard(), PreferencesPanelScorer(), PreferencesPanelMisc()) -class PreferencesScreen(private val tabs: List = getPreferenceTabs()) : EmbeddedScreen() -{ +class PreferencesScreen(private val tabs: List = getPreferenceTabs()) : + EmbeddedScreen() { private val tabbedPane = JTabbedPane(SwingConstants.TOP) - init - { + init { add(tabbedPane, BorderLayout.CENTER) - tabs.forEach { - tabbedPane.addTab(it.title, it) - } + tabs.forEach { tabbedPane.addTab(it.title, it) } } - override fun initialise() - { - tabs.forEach { - it.refresh(false) - } + override fun initialise() { + tabs.forEach { it.refresh(false) } } override fun getScreenName() = "Preferences" - override fun backPressed() - { + override fun backPressed() { val outstandingChanges = tabs.any { it.hasOutstandingChanges() } - if (outstandingChanges) - { - val ans = DialogUtil.showQuestionOLD("Are you sure you want to go back?\n\nYou have unsaved changes that will be discarded.") - if (ans != JOptionPane.YES_OPTION) - { + if (outstandingChanges) { + val ans = + DialogUtil.showQuestionOLD( + "Are you sure you want to go back?\n\nYou have unsaved changes that will be discarded." + ) + if (ans != JOptionPane.YES_OPTION) { return } } super.backPressed() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/reporting/ConfigureReportColumnsDialog.kt b/src/main/kotlin/dartzee/screen/reporting/ConfigureReportColumnsDialog.kt index e0b702312..ffcae140a 100644 --- a/src/main/kotlin/dartzee/screen/reporting/ConfigureReportColumnsDialog.kt +++ b/src/main/kotlin/dartzee/screen/reporting/ConfigureReportColumnsDialog.kt @@ -1,21 +1,19 @@ package dartzee.screen.reporting import dartzee.core.screen.SimpleDialog -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import javax.swing.JCheckBox import javax.swing.JPanel +import net.miginfocom.swing.MigLayout private val CONFIGURABLE_COLUMNS = listOf("Type", "Players", "Start Date", "Finish Date", "Match") -class ConfigureReportColumnsDialog: SimpleDialog() -{ +class ConfigureReportColumnsDialog : SimpleDialog() { private val hmColumnNameToCheckBox = mutableMapOf() private val panel = JPanel() - init - { + init { setSize(301, 251) title = "Configure Columns" isModal = true @@ -26,8 +24,7 @@ class ConfigureReportColumnsDialog: SimpleDialog() init() } - private fun init() - { + private fun init() { CONFIGURABLE_COLUMNS.forEachIndexed { ix, columnName -> val cb = JCheckBox(columnName) cb.isSelected = true @@ -39,8 +36,7 @@ class ConfigureReportColumnsDialog: SimpleDialog() fun excludedColumns() = hmColumnNameToCheckBox.filterValues { !it.isSelected }.map { it.key } - override fun okPressed() - { + override fun okPressed() { dispose() } diff --git a/src/main/kotlin/dartzee/screen/reporting/PlayerParametersPanel.kt b/src/main/kotlin/dartzee/screen/reporting/PlayerParametersPanel.kt index 00567536e..8926005e4 100644 --- a/src/main/kotlin/dartzee/screen/reporting/PlayerParametersPanel.kt +++ b/src/main/kotlin/dartzee/screen/reporting/PlayerParametersPanel.kt @@ -7,25 +7,24 @@ import dartzee.db.MAX_PLAYERS import dartzee.db.PlayerEntity import dartzee.reporting.COMPARATOR_SCORE_UNSET import dartzee.reporting.IncludedPlayerParameters -import net.miginfocom.swing.MigLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JCheckBox import javax.swing.JPanel import javax.swing.JSpinner import javax.swing.SpinnerNumberModel +import net.miginfocom.swing.MigLayout -class PlayerParametersPanel : JPanel(), ActionListener -{ +class PlayerParametersPanel : JPanel(), ActionListener { val chckbxFinalScore = JCheckBox("Game Score") val comboBox = ComboBoxNumberComparison() val spinner = JSpinner(SpinnerNumberModel(3, 3, 200, 1)) val chckbxPosition = JCheckBox("Position") - val positionCheckboxes = List(MAX_PLAYERS) { ix -> JCheckBox(StringUtil.convertOrdinalToText(ix + 1)) } + val positionCheckboxes = + List(MAX_PLAYERS) { ix -> JCheckBox(StringUtil.convertOrdinalToText(ix + 1)) } val cbUndecided = JCheckBox("Undecided") - init - { + init { layout = MigLayout("", "[][][]", "[][]") comboBox.addOption(COMPARATOR_SCORE_UNSET) @@ -44,23 +43,21 @@ class PlayerParametersPanel : JPanel(), ActionListener comboBox.addActionListener(this) } - fun valid(player: PlayerEntity): Boolean - { - if (chckbxPosition.isSelected && getFinishingPositions().isEmpty()) - { - DialogUtil.showErrorOLD("You must select at least one finishing position for player " + player.name) + fun valid(player: PlayerEntity): Boolean { + if (chckbxPosition.isSelected && getFinishingPositions().isEmpty()) { + DialogUtil.showErrorOLD( + "You must select at least one finishing position for player " + player.name + ) return false } return true } - fun generateParameters(): IncludedPlayerParameters - { + fun generateParameters(): IncludedPlayerParameters { val parms = IncludedPlayerParameters() - if (chckbxFinalScore.isSelected) - { + if (chckbxFinalScore.isSelected) { val finalScore = spinner.value as Int val comparator = comboBox.selectedItem as String @@ -68,8 +65,7 @@ class PlayerParametersPanel : JPanel(), ActionListener parms.finalScoreComparator = comparator } - if (chckbxPosition.isSelected) - { + if (chckbxPosition.isSelected) { val finishingPositions = getFinishingPositions() parms.finishingPositions = finishingPositions } @@ -77,33 +73,26 @@ class PlayerParametersPanel : JPanel(), ActionListener return parms } - private fun getFinishingPositions(): List - { + private fun getFinishingPositions(): List { val ret = mutableListOf() - positionCheckboxes.forEachIndexed { ix, cb -> - addValueIfSelected(ret, cb, ix + 1) - } + positionCheckboxes.forEachIndexed { ix, cb -> addValueIfSelected(ret, cb, ix + 1) } addValueIfSelected(ret, cbUndecided, -1) return ret } - private fun addValueIfSelected(v: MutableList, cb: JCheckBox, value: Int) - { - if (cb.isSelected) - { + private fun addValueIfSelected(v: MutableList, cb: JCheckBox, value: Int) { + if (cb.isSelected) { v.add(value) } } - override fun actionPerformed(arg0: ActionEvent) - { + override fun actionPerformed(arg0: ActionEvent) { updatePlayerOptionsEnabled() } - fun disableAll() - { + fun disableAll() { chckbxFinalScore.isSelected = false chckbxFinalScore.isEnabled = false chckbxPosition.isSelected = false @@ -112,8 +101,7 @@ class PlayerParametersPanel : JPanel(), ActionListener updatePlayerOptionsEnabled() } - private fun updatePlayerOptionsEnabled() - { + private fun updatePlayerOptionsEnabled() { positionCheckboxes.forEach { it.isEnabled = chckbxPosition.isSelected } cbUndecided.isEnabled = chckbxPosition.isSelected diff --git a/src/main/kotlin/dartzee/screen/reporting/ReportingGameTab.kt b/src/main/kotlin/dartzee/screen/reporting/ReportingGameTab.kt index aadd7b499..79358db08 100644 --- a/src/main/kotlin/dartzee/screen/reporting/ReportingGameTab.kt +++ b/src/main/kotlin/dartzee/screen/reporting/ReportingGameTab.kt @@ -10,7 +10,6 @@ import dartzee.core.util.createButtonGroup import dartzee.core.util.enableChildren import dartzee.reporting.ReportParameters import dartzee.utils.getFilterPanel -import net.miginfocom.swing.MigLayout import java.awt.FlowLayout import java.awt.event.ActionEvent import java.awt.event.ActionListener @@ -18,9 +17,9 @@ import javax.swing.Box import javax.swing.JCheckBox import javax.swing.JPanel import javax.swing.JRadioButton +import net.miginfocom.swing.MigLayout -class ReportingGameTab: JPanel(), ActionListener -{ +class ReportingGameTab : JPanel(), ActionListener { private val checkBoxGameType = JCheckBox("Game") private val verticalStrut = Box.createVerticalStrut(20) private val horizontalStrut = Box.createHorizontalStrut(20) @@ -42,8 +41,7 @@ class ReportingGameTab: JPanel(), ActionListener private val rdbtnSynced = JRadioButton("Synced") private val rdbtnPendingChanges = JRadioButton("Pending changes") - init - { + init { layout = MigLayout("hidemode 3", "[][][grow][]", "[][][][][][][][][][][][]") add(checkBoxGameType, "flowx,cell 0 0") @@ -73,21 +71,18 @@ class ReportingGameTab: JPanel(), ActionListener addListeners() } - private fun createButtonGroupsAndSelectDefaults() - { + private fun createButtonGroupsAndSelectDefaults() { createButtonGroup(rdbtnDtFinish, rdbtnUnfinished) createButtonGroup(rdbtnYes, rdbtnNo) createButtonGroup(rdbtnPendingChanges, rdbtnSynced) } - private fun addListeners() - { + private fun addListeners() { addActionListenerToAllChildren(this) toggleComponents() } - private fun toggleComponents() - { + private fun toggleComponents() { comboBox.isEnabled = checkBoxGameType.isSelected panelGameParams.isEnabled = cbType.isSelected dateFilterPanelStart.enableChildren(cbStartDate.isSelected) @@ -102,12 +97,9 @@ class ReportingGameTab: JPanel(), ActionListener rdbtnSynced.isEnabled = cbSyncStatus.isSelected } - override fun actionPerformed(e: ActionEvent?) - { - when (e?.source) - { - comboBox -> - { + override fun actionPerformed(e: ActionEvent?) { + when (e?.source) { + comboBox -> { remove(panelGameParams) panelGameParams = getFilterPanel(comboBox.getGameType()) panelGameParams.isEnabled = cbType.isSelected @@ -120,45 +112,35 @@ class ReportingGameTab: JPanel(), ActionListener fun valid() = dateFilterPanelStart.valid() && dateFilterPanelFinish.valid() - fun populateReportParameters(rp: ReportParameters) - { - if (checkBoxGameType.isSelected) - { + fun populateReportParameters(rp: ReportParameters) { + if (checkBoxGameType.isSelected) { rp.gameType = comboBox.getGameType() } - if (cbType.isSelected) - { + if (cbType.isSelected) { rp.gameParams = panelGameParams.getGameParams() } - if (cbPartOfMatch.isSelected) - { + if (cbPartOfMatch.isSelected) { rp.setEnforceMatch(rdbtnYes.isSelected) } - if (cbSyncStatus.isSelected) - { + if (cbSyncStatus.isSelected) { rp.pendingChanges = rdbtnPendingChanges.isSelected } - if (cbStartDate.isSelected) - { + if (cbStartDate.isSelected) { rp.dtStartFrom = dateFilterPanelStart.getSqlDtFrom() rp.dtStartTo = dateFilterPanelStart.getSqlDtTo() } - if (cbFinishDate.isSelected) - { - if (rdbtnUnfinished.isSelected) - { + if (cbFinishDate.isSelected) { + if (rdbtnUnfinished.isSelected) { rp.unfinishedOnly = true - } - else - { + } else { rp.dtFinishFrom = dateFilterPanelFinish.getSqlDtFrom() rp.dtFinishTo = dateFilterPanelFinish.getSqlDtTo() } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/reporting/ReportingPlayersTab.kt b/src/main/kotlin/dartzee/screen/reporting/ReportingPlayersTab.kt index db1ca2c07..60ba10c31 100644 --- a/src/main/kotlin/dartzee/screen/reporting/ReportingPlayersTab.kt +++ b/src/main/kotlin/dartzee/screen/reporting/ReportingPlayersTab.kt @@ -11,7 +11,6 @@ import dartzee.db.PlayerEntity import dartzee.reporting.ReportParameters import dartzee.screen.PlayerSelectDialog import dartzee.screen.ScreenCache -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Dimension import java.awt.FlowLayout @@ -23,9 +22,9 @@ import javax.swing.JCheckBox import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JRadioButton +import net.miginfocom.swing.MigLayout -class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener -{ +class ReportingPlayersTab : JPanel(), ActionListener, RowSelectionListener { private val hmPlayerToParametersPanel = mutableMapOf() private val panelNorth = JPanel() @@ -42,8 +41,7 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener var includedPlayerPanel = PlayerParametersPanel().also { it.disableAll() } - init - { + init { layout = BorderLayout(0, 0) add(panelNorth, BorderLayout.NORTH) @@ -59,9 +57,11 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener val flowLayout = panelTableButtons.layout as FlowLayout flowLayout.alignment = FlowLayout.LEFT btnAddPlayer.preferredSize = Dimension(30, 30) - btnAddPlayer.icon = ImageIcon(ReportingSetupScreen::class.java.getResource("/buttons/addPlayer.png")) + btnAddPlayer.icon = + ImageIcon(ReportingSetupScreen::class.java.getResource("/buttons/addPlayer.png")) panelTableButtons.add(btnAddPlayer) - btnRemovePlayer.icon = ImageIcon(ReportingSetupScreen::class.java.getResource("/buttons/removePlayer.png")) + btnRemovePlayer.icon = + ImageIcon(ReportingSetupScreen::class.java.getResource("/buttons/removePlayer.png")) btnRemovePlayer.preferredSize = Dimension(30, 30) panelTableButtons.add(btnRemovePlayer) add(panelTable, BorderLayout.CENTER) @@ -76,24 +76,19 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener scrollTable.initPlayerTableModel(emptyList()) } - override fun actionPerformed(e: ActionEvent?) - { - when (e?.source) - { + override fun actionPerformed(e: ActionEvent?) { + when (e?.source) { btnAddPlayer -> addPlayers() btnRemovePlayer -> removePlayers() - rdbtnInclude, rdbtnExclude -> togglePlayerParameters() + rdbtnInclude, + rdbtnExclude -> togglePlayerParameters() } } - private fun togglePlayerParameters() - { - if (rdbtnInclude.isSelected) - { + private fun togglePlayerParameters() { + if (rdbtnInclude.isSelected) { add(includedPlayerPanel, BorderLayout.SOUTH) - } - else - { + } else { remove(includedPlayerPanel) } @@ -101,17 +96,14 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener repaint() } - private fun addPlayers() - { + private fun addPlayers() { val allSelected = hmPlayerToParametersPanel.keys.toList() val players = PlayerSelectDialog.selectPlayers(allSelected) addPlayers(players) } - fun addPlayers(players: List) - { - for (player in players) - { + fun addPlayers(players: List) { + for (player in players) { hmPlayerToParametersPanel[player] = PlayerParametersPanel() } @@ -119,11 +111,9 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener scrollTable.selectFirstRow() } - private fun removePlayers() - { + private fun removePlayers() { val playersToRemove = scrollTable.getSelectedPlayers() - if (playersToRemove.isEmpty()) - { + if (playersToRemove.isEmpty()) { DialogUtil.showErrorOLD("You must select player(s) to remove.") return } @@ -132,22 +122,17 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener scrollTable.initPlayerTableModel(hmPlayerToParametersPanel.keys.toList()) } - override fun selectionChanged(src: ScrollTable) - { + override fun selectionChanged(src: ScrollTable) { remove(includedPlayerPanel) val player = scrollTable.getSelectedPlayer() - if (player == null) - { + if (player == null) { includedPlayerPanel = PlayerParametersPanel().also { it.disableAll() } - } - else - { + } else { includedPlayerPanel = hmPlayerToParametersPanel[player]!! } - if (rdbtnInclude.isSelected) - { + if (rdbtnInclude.isSelected) { add(includedPlayerPanel, BorderLayout.SOUTH) } @@ -155,10 +140,8 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener repaint() } - fun valid(): Boolean - { - if (rdbtnInclude.isSelected) - { + fun valid(): Boolean { + if (rdbtnInclude.isSelected) { val entries = hmPlayerToParametersPanel.entries return entries.all { it.value.valid(it.key) } } @@ -166,17 +149,14 @@ class ReportingPlayersTab: JPanel(), ActionListener, RowSelectionListener return true } - fun populateReportParameters(rp: ReportParameters) - { + fun populateReportParameters(rp: ReportParameters) { rp.excludeOnlyAi = checkBoxExcludeOnlyAi.isSelected - if (rdbtnInclude.isSelected) - { - rp.hmIncludedPlayerToParms = hmPlayerToParametersPanel.mapValues { entry -> entry.value.generateParameters() } - } - else - { + if (rdbtnInclude.isSelected) { + rp.hmIncludedPlayerToParms = + hmPlayerToParametersPanel.mapValues { entry -> entry.value.generateParameters() } + } else { rp.excludedPlayers = hmPlayerToParametersPanel.keys.toList() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/reporting/ReportingResultsScreen.kt b/src/main/kotlin/dartzee/screen/reporting/ReportingResultsScreen.kt index 9cf132517..70de0dddc 100644 --- a/src/main/kotlin/dartzee/screen/reporting/ReportingResultsScreen.kt +++ b/src/main/kotlin/dartzee/screen/reporting/ReportingResultsScreen.kt @@ -13,16 +13,17 @@ import java.sql.Timestamp import javax.swing.JButton import javax.swing.JPanel -class ReportingResultsScreen(private val configureColumnsDialog: ConfigureReportColumnsDialog = ConfigureReportColumnsDialog()) : EmbeddedScreen() -{ +class ReportingResultsScreen( + private val configureColumnsDialog: ConfigureReportColumnsDialog = + ConfigureReportColumnsDialog() +) : EmbeddedScreen() { var rp: ReportParameters? = null private var cachedRows = emptyList>() private val btnConfigureColumns = JButton("Configure Columns...") private val tableResults = ScrollTableDartsGame() - init - { + init { add(tableResults, BorderLayout.CENTER) val panel = JPanel() @@ -34,13 +35,11 @@ class ReportingResultsScreen(private val configureColumnsDialog: ConfigureReport override fun getScreenName() = "Game Report" - override fun initialise() - { + override fun initialise() { buildTable(true) } - private fun buildTable(runSql: Boolean) - { + private fun buildTable(runSql: Boolean) { val model = TableUtil.DefaultModel() model.addColumn("Game") model.addColumn("Type") @@ -49,8 +48,7 @@ class ReportingResultsScreen(private val configureColumnsDialog: ConfigureReport model.addColumn("Finish Date") model.addColumn("Match") - if (runSql) - { + if (runSql) { val wrappers = runReport(rp) cachedRows = ReportResultWrapper.getTableRowsFromWrappers(wrappers) } @@ -66,8 +64,7 @@ class ReportingResultsScreen(private val configureColumnsDialog: ConfigureReport stripOutRemovedColumns() } - private fun setRenderersAndComparators() - { + private fun setRenderersAndComparators() { tableResults.setRenderer(3, TableUtil.TimestampRenderer()) tableResults.setRenderer(4, TableUtil.TimestampRenderer()) @@ -75,14 +72,11 @@ class ReportingResultsScreen(private val configureColumnsDialog: ConfigureReport tableResults.setComparator(4, compareBy { it }) } - private fun stripOutRemovedColumns() - { + private fun stripOutRemovedColumns() { val columns = tableResults.columnCount - for (i in columns - 1 downTo 0) - { + for (i in columns - 1 downTo 0) { val columnName = tableResults.getColumnName(i) - if (configureColumnsDialog.excludedColumns().contains(columnName)) - { + if (configureColumnsDialog.excludedColumns().contains(columnName)) { tableResults.removeColumn(i) } } @@ -90,10 +84,8 @@ class ReportingResultsScreen(private val configureColumnsDialog: ConfigureReport override fun getBackTarget() = ScreenCache.get() - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnConfigureColumns -> { configureColumnsDialog.setLocationRelativeTo(this) configureColumnsDialog.isVisible = true diff --git a/src/main/kotlin/dartzee/screen/reporting/ReportingSetupScreen.kt b/src/main/kotlin/dartzee/screen/reporting/ReportingSetupScreen.kt index 4e07ec046..d066bf1a1 100644 --- a/src/main/kotlin/dartzee/screen/reporting/ReportingSetupScreen.kt +++ b/src/main/kotlin/dartzee/screen/reporting/ReportingSetupScreen.kt @@ -7,14 +7,12 @@ import java.awt.BorderLayout import javax.swing.JTabbedPane import javax.swing.SwingConstants -class ReportingSetupScreen: EmbeddedScreen() -{ +class ReportingSetupScreen : EmbeddedScreen() { private val tabbedPane = JTabbedPane(SwingConstants.TOP) private val gameTab = ReportingGameTab() private val playerTab = ReportingPlayersTab() - init - { + init { add(tabbedPane, BorderLayout.CENTER) tabbedPane.addTab("Game", null, gameTab, null) @@ -22,15 +20,15 @@ class ReportingSetupScreen: EmbeddedScreen() } override fun getScreenName() = "Report Setup" + override fun initialise() {} private fun valid() = gameTab.valid() && playerTab.valid() override fun showNextButton() = true - override fun nextPressed() - { - if (!valid()) - { + + override fun nextPressed() { + if (!valid()) { return } @@ -40,8 +38,7 @@ class ReportingSetupScreen: EmbeddedScreen() ScreenCache.switch(scrn) } - private fun generateReportParams(): ReportParameters - { + private fun generateReportParams(): ReportParameters { val rp = ReportParameters() gameTab.populateReportParameters(rp) playerTab.populateReportParameters(rp) diff --git a/src/main/kotlin/dartzee/screen/stats/StatsUtils.kt b/src/main/kotlin/dartzee/screen/stats/StatsUtils.kt index 39e725e12..baace1926 100644 --- a/src/main/kotlin/dartzee/screen/stats/StatsUtils.kt +++ b/src/main/kotlin/dartzee/screen/stats/StatsUtils.kt @@ -1,30 +1,25 @@ package dartzee.screen.stats - -fun List.median(): Double -{ - if (isEmpty()) - { +fun List.median(): Double { + if (isEmpty()) { return 0.0 } val allKeys = sorted() val n = allKeys.size - return if (n % 2 == 0) - { - //Even, so we want either side of the middle value and then to take the average of them. + return if (n % 2 == 0) { + // Even, so we want either side of the middle value and then to take the average of them. val bigIx = n / 2 val smallIx = n / 2 - 1 val sum = (allKeys[bigIx] + allKeys[smallIx]).toDouble() sum / 2 - } - else - { - //Odd, so we just want the middle value. It's (n-1)/2 because of stupid index starting at 0 not 1. + } else { + // Odd, so we just want the middle value. It's (n-1)/2 because of stupid index starting at 0 + // not 1. val ix = (n - 1) / 2 allKeys[ix].toDouble() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/overall/AbstractLeaderboard.kt b/src/main/kotlin/dartzee/screen/stats/overall/AbstractLeaderboard.kt index 0d3f90232..9b40bbe94 100644 --- a/src/main/kotlin/dartzee/screen/stats/overall/AbstractLeaderboard.kt +++ b/src/main/kotlin/dartzee/screen/stats/overall/AbstractLeaderboard.kt @@ -9,31 +9,33 @@ import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JPanel -abstract class AbstractLeaderboard: JPanel(), ActionListener -{ +abstract class AbstractLeaderboard : JPanel(), ActionListener { val panelPlayerFilters = PlayerTypeFilterPanel() private var builtTable = false abstract fun buildTable() + abstract fun getTabName(): String override fun actionPerformed(e: ActionEvent?) = buildTable() - fun buildTableFirstTime() - { - if (!builtTable) - { + fun buildTableFirstTime() { + if (!builtTable) { buildTable() builtTable = true } } /** - * Build a standard leaderboard table, which contains the flag, name, Game ID and a custom 'score' column. + * Build a standard leaderboard table, which contains the flag, name, Game ID and a custom + * 'score' column. */ - protected fun buildStandardLeaderboard(table: ScrollTableDartsGame, sql: String, scoreColumnName: String) - { + protected fun buildStandardLeaderboard( + table: ScrollTableDartsGame, + sql: String, + scoreColumnName: String + ) { val model = TableUtil.DefaultModel() model.addColumn("#") model.addColumn("") @@ -49,13 +51,11 @@ abstract class AbstractLeaderboard: JPanel(), ActionListener table.sortBy(0, false) } - private fun retrieveDatabaseRowsForLeaderboard(sqlStr: String): List> - { + private fun retrieveDatabaseRowsForLeaderboard(sqlStr: String): List> { val rows = mutableListOf() mainDatabase.executeQuery(sqlStr).use { rs -> - while (rs.next()) - { + while (rs.next()) { val strategy = rs.getString("Strategy") val playerName = rs.getString("Name") val localId = rs.getLong("LocalId") @@ -69,4 +69,4 @@ abstract class AbstractLeaderboard: JPanel(), ActionListener return getRankedRowsForTable(rows) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/overall/AbstractProgressBarRenderer.kt b/src/main/kotlin/dartzee/screen/stats/overall/AbstractProgressBarRenderer.kt index 48459699d..4213f94f2 100644 --- a/src/main/kotlin/dartzee/screen/stats/overall/AbstractProgressBarRenderer.kt +++ b/src/main/kotlin/dartzee/screen/stats/overall/AbstractProgressBarRenderer.kt @@ -11,10 +11,8 @@ import javax.swing.border.MatteBorder import javax.swing.plaf.basic.BasicProgressBarUI import javax.swing.table.TableCellRenderer -abstract class AbstractProgressBarRenderer: JProgressBar(), TableCellRenderer -{ - init - { +abstract class AbstractProgressBarRenderer : JProgressBar(), TableCellRenderer { + init { font = Font("Tahoma", Font.BOLD, 12) minimum = 0 isStringPainted = true @@ -27,18 +25,24 @@ abstract class AbstractProgressBarRenderer: JProgressBar(), TableCellRenderer } abstract fun getColorForValue(value: Any?): Color + abstract fun getScoreForValue(value: Any?): Int - override fun getTableCellRendererComponent(table: JTable?, value: Any?, isSelected: Boolean, hasFocus: Boolean, row: Int, column: Int): Component - { + override fun getTableCellRendererComponent( + table: JTable?, + value: Any?, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { val score = getScoreForValue(value) string = getScoreDescForValue(value) setValue(score) var col = getColorForValue(value) - if (isSelected) - { + if (isSelected) { col = col.darker() } @@ -50,10 +54,9 @@ abstract class AbstractProgressBarRenderer: JProgressBar(), TableCellRenderer open fun getScoreDescForValue(value: Any?) = "${getScoreForValue(value)}/$maximum" - private class AchievementProgressUI : BasicProgressBarUI() - { + private class AchievementProgressUI : BasicProgressBarUI() { override fun getSelectionBackground(): Color = progressBar.foreground override fun getSelectionForeground(): Color = progressBar.foreground.darker() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardAchievements.kt b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardAchievements.kt index 3948c933f..211927f8e 100644 --- a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardAchievements.kt +++ b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardAchievements.kt @@ -18,16 +18,14 @@ import javax.swing.JPanel const val ACHIEVEMENT_COLUMN_IX = 3 -class LeaderboardAchievements: AbstractLeaderboard() -{ +class LeaderboardAchievements : AbstractLeaderboard() { val table = ScrollTableAchievements() private val panelFilters = JPanel() val cbSpecificAchievement = JCheckBox("Achievement") val comboBox = JComboBox() - init - { + init { layout = BorderLayout(0, 0) table.setRowHeight(23) add(table) @@ -45,16 +43,14 @@ class LeaderboardAchievements: AbstractLeaderboard() cbSpecificAchievement.addActionListener(this) } - private fun initComboBox() - { + private fun initComboBox() { val achievements = Vector(getAllAchievements()) comboBox.model = DefaultComboBoxModel(achievements) } override fun getTabName() = "Achievements" - override fun buildTable() - { + override fun buildTable() { val achievement = getSelectedAchievement() val achievementRows = achievement.retrieveAllRows() @@ -65,20 +61,22 @@ class LeaderboardAchievements: AbstractLeaderboard() model.addColumn("Score") val players = PlayerEntity.retrievePlayers(panelPlayerFilters.getWhereSql()) - val entries = players.map { p -> - val myRows = achievementRows.filter { it.playerId == p.rowId } + val entries = + players + .map { p -> + val myRows = achievementRows.filter { it.playerId == p.rowId } - val myAchievement = achievement.javaClass.getDeclaredConstructor().newInstance() - myAchievement.initialiseFromDb(myRows, p) + val myAchievement = achievement.javaClass.getDeclaredConstructor().newInstance() + myAchievement.initialiseFromDb(myRows, p) - if (myAchievement.isDecreasing() && myAchievement.attainedValue == -1) - { - myAchievement.attainedValue = Integer.MAX_VALUE - } + if (myAchievement.isDecreasing() && myAchievement.attainedValue == -1) { + myAchievement.attainedValue = Integer.MAX_VALUE + } - val row = listOf(p.getFlag(), p, myAchievement) - LeaderboardEntry(myAchievement.attainedValue, row) - }.sortedBy(!achievement.isDecreasing()) { it.score } + val row = listOf(p.getFlag(), p, myAchievement) + LeaderboardEntry(myAchievement.attainedValue, row) + } + .sortedBy(!achievement.isDecreasing()) { it.score } val modelRows = getRankedRowsForTable(entries) model.addRows(modelRows) @@ -87,51 +85,55 @@ class LeaderboardAchievements: AbstractLeaderboard() table.setColumnWidths("35;25;200") table.sortBy(0, false) - table.setComparator(ACHIEVEMENT_COLUMN_IX, compareBy{ it.attainedValue }) + table.setComparator( + ACHIEVEMENT_COLUMN_IX, + compareBy { it.attainedValue } + ) val renderer = AchievementProgressBarRenderer() renderer.minimum = 0 - if (achievement.isDecreasing()) - { + if (achievement.isDecreasing()) { renderer.maximum = achievement.redThreshold - achievement.maxValue - } - else - { + } else { renderer.maximum = achievement.maxValue } table.getColumn(ACHIEVEMENT_COLUMN_IX).cellRenderer = renderer } - private fun getSelectedAchievement(): AbstractAchievement = if (cbSpecificAchievement.isSelected) comboBox.getItemAt(comboBox.selectedIndex) else DummyAchievementTotal() + private fun getSelectedAchievement(): AbstractAchievement = + if (cbSpecificAchievement.isSelected) comboBox.getItemAt(comboBox.selectedIndex) + else DummyAchievementTotal() - override fun actionPerformed(e: ActionEvent?) - { + override fun actionPerformed(e: ActionEvent?) { super.actionPerformed(e) comboBox.isEnabled = cbSpecificAchievement.isSelected } - class AchievementProgressBarRenderer: AbstractProgressBarRenderer() - { - override fun getColorForValue(value: Any?) = (value!! as AbstractAchievement).getColor(false) + class AchievementProgressBarRenderer : AbstractProgressBarRenderer() { + override fun getColorForValue(value: Any?) = + (value!! as AbstractAchievement).getColor(false) - override fun getScoreForValue(value: Any?): Int - { + override fun getScoreForValue(value: Any?): Int { val achievement = (value!! as AbstractAchievement) - if (achievement.isDecreasing()) - { + if (achievement.isDecreasing()) { return (achievement.redThreshold - achievement.attainedValue).coerceAtLeast(0) } return achievement.attainedValue } - override fun getScoreDescForValue(value: Any?): String - { + override fun getScoreDescForValue(value: Any?): String { val achievement = value!! as AbstractAchievement - val attainedValueDesc = if (achievement.attainedValue == -1 || achievement.attainedValue == Integer.MAX_VALUE) "-" else "${achievement.attainedValue}" + val attainedValueDesc = + if ( + achievement.attainedValue == -1 || + achievement.attainedValue == Integer.MAX_VALUE + ) + "-" + else "${achievement.attainedValue}" return "$attainedValueDesc/${achievement.maxValue}" } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTopX01Finishes.kt b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTopX01Finishes.kt index f88dd753f..841695feb 100644 --- a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTopX01Finishes.kt +++ b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTopX01Finishes.kt @@ -6,13 +6,11 @@ import dartzee.utils.PreferenceUtil import java.awt.BorderLayout import javax.swing.JPanel -class LeaderboardTopX01Finishes: AbstractLeaderboard() -{ +class LeaderboardTopX01Finishes : AbstractLeaderboard() { val tableTopFinishes = ScrollTableDartsGame() private val panelTopFinishesFilters = JPanel() - init - { + init { layout = BorderLayout(0, 0) add(tableTopFinishes) @@ -25,8 +23,7 @@ class LeaderboardTopX01Finishes: AbstractLeaderboard() override fun getTabName() = "X01 Finishes" - override fun buildTable() - { + override fun buildTable() { val extraWhereSql = panelPlayerFilters.getWhereSql() val leaderboardSize = PreferenceUtil.getIntValue(PREFERENCES_INT_LEADERBOARD_SIZE) @@ -36,8 +33,7 @@ class LeaderboardTopX01Finishes: AbstractLeaderboard() sb.append(" FROM X01Finish xf, Player p, Game g") sb.append(" WHERE xf.PlayerId = p.RowId") sb.append(" AND xf.GameId = g.RowId") - if (!extraWhereSql.isEmpty()) - { + if (!extraWhereSql.isEmpty()) { sb.append(" AND p.$extraWhereSql") } sb.append(" ORDER BY Finish DESC, xf.DtCreation ASC") @@ -46,4 +42,4 @@ class LeaderboardTopX01Finishes: AbstractLeaderboard() val sql = sb.toString() buildStandardLeaderboard(tableTopFinishes, sql, "Finish") } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTotalScore.kt b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTotalScore.kt index f654a8e09..56e584466 100644 --- a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTotalScore.kt +++ b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardTotalScore.kt @@ -13,8 +13,8 @@ import javax.swing.Box import javax.swing.JPanel import javax.swing.JRadioButton -class LeaderboardTotalScore(private val gameType: GameType) : AbstractLeaderboard(), ActionListener -{ +class LeaderboardTotalScore(private val gameType: GameType) : + AbstractLeaderboard(), ActionListener { private val panelGameParams = getFilterPanel(gameType) private val panelFilters = JPanel() @@ -23,8 +23,7 @@ class LeaderboardTotalScore(private val gameType: GameType) : AbstractLeaderboar private val rdbtnBest = JRadioButton("Best") private val rdbtnWorst = JRadioButton("Worst") - init - { + init { layout = BorderLayout(0, 0) panelGameParams.addActionListener(this) @@ -48,14 +47,12 @@ class LeaderboardTotalScore(private val gameType: GameType) : AbstractLeaderboar override fun getTabName() = gameType.getDescription() - override fun buildTable() - { + override fun buildTable() { val sql = getTotalScoreSql() buildStandardLeaderboard(scrollPane, sql, "Score") } - private fun getTotalScoreSql() : String - { + private fun getTotalScoreSql(): String { val leaderboardSize = PreferenceUtil.getIntValue(PREFERENCES_INT_LEADERBOARD_SIZE) val gameParams = panelGameParams.getGameParams() val playerWhereSql = panelPlayerFilters.getWhereSql() @@ -69,12 +66,10 @@ class LeaderboardTotalScore(private val gameType: GameType) : AbstractLeaderboar sb.append(" AND g.GameParams = '$gameParams'") sb.append(" AND pt.FinalScore > -1") - if (!playerWhereSql.isEmpty()) - { + if (!playerWhereSql.isEmpty()) { sb.append(" AND p.$playerWhereSql") } - val orderStr = if (doesHighestWin(gameType) == rdbtnWorst.isSelected) "ASC" else "DESC" sb.append(" ORDER BY pt.FinalScore $orderStr") sb.append(" FETCH FIRST $leaderboardSize ROWS ONLY") diff --git a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardUtils.kt b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardUtils.kt index 5de972b48..50afabf8b 100644 --- a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardUtils.kt +++ b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardUtils.kt @@ -2,14 +2,13 @@ package dartzee.screen.stats.overall data class LeaderboardEntry(val score: Int, val rowValues: List) -fun getRankedRowsForTable(entries: List): List> -{ +fun getRankedRowsForTable(entries: List): List> { var previousPosition = 1 var previousScore = -1 return entries.mapIndexed { ix, entry -> - val position = if (entry.score != previousScore) ix+1 else previousPosition + val position = if (entry.score != previousScore) ix + 1 else previousPosition previousPosition = position previousScore = entry.score (listOf(position) + entry.rowValues).toTypedArray() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardsScreen.kt b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardsScreen.kt index a5bdc0eae..9e988243d 100644 --- a/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardsScreen.kt +++ b/src/main/kotlin/dartzee/screen/stats/overall/LeaderboardsScreen.kt @@ -8,36 +8,28 @@ import javax.swing.SwingConstants import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener -class LeaderboardsScreen : EmbeddedScreen(), ChangeListener -{ +class LeaderboardsScreen : EmbeddedScreen(), ChangeListener { private val tabbedPane = JTabbedPane(SwingConstants.TOP) private val tabs = getTabs() - init - { + init { add(tabbedPane, BorderLayout.CENTER) - tabs.forEach{ - tabbedPane.addTab(it.getTabName(), null, it, null) - } + tabs.forEach { tabbedPane.addTab(it.getTabName(), null, it, null) } tabbedPane.addChangeListener(this) } override fun getScreenName() = "Leaderboards" - override fun initialise() - { + override fun initialise() { tabs.first().buildTableFirstTime() } - private fun getTabs(): List - { + private fun getTabs(): List { val tabs = mutableListOf() - GameType.values().forEach{ - tabs.add(LeaderboardTotalScore(it)) - } + GameType.values().forEach { tabs.add(LeaderboardTotalScore(it)) } tabs.add(LeaderboardTopX01Finishes()) tabs.add(LeaderboardAchievements()) @@ -45,8 +37,7 @@ class LeaderboardsScreen : EmbeddedScreen(), ChangeListener return tabs } - override fun stateChanged(e: ChangeEvent) - { + override fun stateChanged(e: ChangeEvent) { val index = tabbedPane.selectedIndex val selectedTab = tabs[index] diff --git a/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTab.kt b/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTab.kt index ebb1a769b..7272e3476 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTab.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTab.kt @@ -11,36 +11,28 @@ import java.beans.PropertyChangeEvent import java.beans.PropertyChangeListener import javax.swing.JPanel -abstract class AbstractStatisticsTab : JPanel(), PropertyChangeListener -{ +abstract class AbstractStatisticsTab : JPanel(), PropertyChangeListener { protected var filteredGames = listOf() protected var filteredGamesOther = listOf() - init - { + init { preferredSize = Dimension(500, 150) } abstract fun populateStats() + fun includeOtherComparison() = filteredGamesOther.isNotEmpty() - /** - * For the tabs that are a simple grid layout showing two tables. - */ - protected fun setOtherComponentVisibility(container: Container, otherComponent: Component) - { - if (container.layout !is GridLayout) - { + /** For the tabs that are a simple grid layout showing two tables. */ + protected fun setOtherComponentVisibility(container: Container, otherComponent: Component) { + if (container.layout !is GridLayout) { throw Exception("Calling method with inappropriate layout: $layout") } - if (!includeOtherComparison()) - { + if (!includeOtherComparison()) { container.layout = GridLayout(0, 1, 0, 0) container.remove(otherComponent) - } - else if (!container.containsComponent(otherComponent)) - { + } else if (!container.containsComponent(otherComponent)) { container.layout = GridLayout(0, 2, 0, 0) container.add(otherComponent) } @@ -48,29 +40,21 @@ abstract class AbstractStatisticsTab : JPanel(), PropertyChangeListener repaint() } - /** - * Helpers - */ - fun getDistinctGameParams() = filteredGames.map{ it.gameParams }.distinct() + /** Helpers */ + fun getDistinctGameParams() = filteredGames.map { it.gameParams }.distinct() + fun getGameType() = ScreenCache.get().gameType - /** - * Gets / sets - */ - fun setFilteredGames(filteredGames: List, filteredGamesOther: List) - { + /** Gets / sets */ + fun setFilteredGames(filteredGames: List, filteredGamesOther: List) { this.filteredGames = filteredGames this.filteredGamesOther = filteredGamesOther } - /** - * PropertyChangeListener - */ - override fun propertyChange(arg0: PropertyChangeEvent) - { + /** PropertyChangeListener */ + override fun propertyChange(arg0: PropertyChangeEvent) { val propertyName = arg0.propertyName - if (propertyName == "value") - { + if (propertyName == "value") { populateStats() } } diff --git a/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTabPieBreakdown.kt b/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTabPieBreakdown.kt index 7f52f4c84..86a4c1926 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTabPieBreakdown.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/AbstractStatisticsTabPieBreakdown.kt @@ -6,18 +6,17 @@ import dartzee.core.util.TableUtil import dartzee.core.util.containsComponent import dartzee.core.util.getDescription import dartzee.stats.GameWrapper -import org.jfree.chart.ChartFactory -import org.jfree.chart.ChartPanel -import org.jfree.chart.plot.PiePlot -import org.jfree.data.general.DefaultPieDataset import java.awt.Color import java.awt.GridLayout import javax.swing.JPanel import javax.swing.ListSelectionModel import javax.swing.border.EmptyBorder +import org.jfree.chart.ChartFactory +import org.jfree.chart.ChartPanel +import org.jfree.chart.plot.PiePlot +import org.jfree.data.general.DefaultPieDataset -abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowSelectionListener -{ +abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowSelectionListener { abstract val ranges: List private val tableHoleBreakdown = ScrollTable(testId = "BreakdownMine") @@ -27,8 +26,7 @@ abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowS private val myPieChartPanel = ChartPanel(null) val otherPieChartPanel = ChartPanel(null) - init - { + init { layout = GridLayout(1, 3, 0, 0) tableHoleBreakdownOther.tableForeground = Color.RED @@ -51,29 +49,31 @@ abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowS } abstract fun getColorForRange(range: IntRange): Color + abstract fun getTableRows(filteredGames: List): Pair>, List?> - open fun applyAdditionalFilters(filteredGames: List): List = filteredGames + open fun applyAdditionalFilters(filteredGames: List): List = + filteredGames - override fun populateStats() - { + override fun populateStats() { setTableVisibility() populateHoleBreakdown(tableHoleBreakdown, myPieChartPanel, filteredGames) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { populateHoleBreakdown(tableHoleBreakdownOther, otherPieChartPanel, filteredGamesOther) } } - private fun populateHoleBreakdown(table: ScrollTable, chartPanel: ChartPanel, games: List) - { + + private fun populateHoleBreakdown( + table: ScrollTable, + chartPanel: ChartPanel, + games: List + ) { val filteredGames = applyAdditionalFilters(games) val model = TableUtil.DefaultModel() model.addColumn("Target") - ranges.forEach{ - model.addColumn(it.getDescription()) - } + ranges.forEach { model.addColumn(it.getDescription()) } model.addColumn("Avg") table.model = model @@ -87,26 +87,22 @@ abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowS updatePieChart(table, chartPanel) } - private fun populateModel(table: ScrollTable, filteredGames: List) - { + private fun populateModel(table: ScrollTable, filteredGames: List) { val allRows = getTableRows(filteredGames) - val breakdownRows = allRows.first.map{ it.toTypedArray() } + val breakdownRows = allRows.first.map { it.toTypedArray() } - breakdownRows.forEach{ table.addRow(it) } + breakdownRows.forEach { table.addRow(it) } val totalRow = allRows.second - if (totalRow != null) - { + if (totalRow != null) { table.addFooterRow(totalRow.toTypedArray()) } } - private fun updatePieChart(table: ScrollTable, panel: ChartPanel) - { + private fun updatePieChart(table: ScrollTable, panel: ChartPanel) { val selectedRow = table.selectedModelRow - if (selectedRow == -1) - { - //Do nothing + if (selectedRow == -1) { + // Do nothing return } @@ -117,7 +113,10 @@ abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowS val plot = pieChart.plot as PiePlot<*> ranges.forEachIndexed { ix, range -> - dataset.setValue(range.getDescription(), (table.getNonNullValueAt(selectedRow, ix + 1) as Int)) + dataset.setValue( + range.getDescription(), + (table.getNonNullValueAt(selectedRow, ix + 1) as Int) + ) val col = getColorForRange(range) plot.setSectionPaint(range.getDescription(), col) @@ -127,17 +126,13 @@ abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowS panel.chart = pieChart } - private fun setTableVisibility() - { - if (!includeOtherComparison()) - { + private fun setTableVisibility() { + if (!includeOtherComparison()) { pieChartPanel.layout = GridLayout(1, 1, 0, 0) pieChartPanel.remove(otherPieChartPanel) tablePanel.layout = GridLayout(1, 1, 0, 0) tablePanel.remove(tableHoleBreakdownOther) - } - else if (!tablePanel.containsComponent(tableHoleBreakdownOther)) - { + } else if (!tablePanel.containsComponent(tableHoleBreakdownOther)) { pieChartPanel.layout = GridLayout(2, 1, 0, 0) pieChartPanel.add(otherPieChartPanel) tablePanel.layout = GridLayout(2, 1, 0, 0) @@ -147,10 +142,8 @@ abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowS tablePanel.repaint() } - override fun selectionChanged(src: ScrollTable) - { - when (src) - { + override fun selectionChanged(src: ScrollTable) { + when (src) { tableHoleBreakdown -> { updateSelection(tableHoleBreakdown, tableHoleBreakdownOther) updatePieChart(tableHoleBreakdown, myPieChartPanel) @@ -161,12 +154,11 @@ abstract class AbstractStatisticsTabPieBreakdown : AbstractStatisticsTab(), RowS } } } - private fun updateSelection(src: ScrollTable, dest: ScrollTable) - { + + private fun updateSelection(src: ScrollTable, dest: ScrollTable) { val row = src.selectedModelRow - if (row < dest.rowCount) - { + if (row < dest.rowCount) { dest.selectRow(row) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/HoleBreakdownWrapper.kt b/src/main/kotlin/dartzee/screen/stats/player/HoleBreakdownWrapper.kt index 30d8719ca..98d47cd1b 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/HoleBreakdownWrapper.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/HoleBreakdownWrapper.kt @@ -2,18 +2,15 @@ package dartzee.screen.stats.player import dartzee.core.obj.HashMapCount -class HoleBreakdownWrapper -{ +class HoleBreakdownWrapper { private val hmScoreToCount = HashMapCount() - fun getAverage(): Double - { + fun getAverage(): Double { val totalGamesCounted = hmScoreToCount.getTotalCount().toDouble() var weightedTotal = 0.0 val scores = hmScoreToCount.keys - for (score in scores) - { + for (score in scores) { val count = hmScoreToCount.getCount(score) weightedTotal += (score * count).toDouble() } @@ -22,6 +19,17 @@ class HoleBreakdownWrapper } fun increment(score: Int) = hmScoreToCount.incrementCount(score) + fun getCount(score: Int) = hmScoreToCount.getCount(score) - fun getAsTableRow(holeIdentifier: Any) = listOf(holeIdentifier, getCount(1), getCount(2), getCount(3), getCount(4), getCount(5), getAverage()) -} \ No newline at end of file + + fun getAsTableRow(holeIdentifier: Any) = + listOf( + holeIdentifier, + getCount(1), + getCount(2), + getCount(3), + getCount(4), + getCount(5), + getAverage() + ) +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/MovingAverageChartPanel.kt b/src/main/kotlin/dartzee/screen/stats/player/MovingAverageChartPanel.kt index 72303984f..c20b1a946 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/MovingAverageChartPanel.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/MovingAverageChartPanel.kt @@ -2,6 +2,12 @@ package dartzee.screen.stats.player import dartzee.core.util.getAllChildComponentsForType import dartzee.utils.DartsColour.getBrightenedColour +import java.awt.BorderLayout +import java.awt.Color +import java.awt.event.ActionEvent +import java.awt.event.ActionListener +import javax.swing.JCheckBox +import javax.swing.JPanel import org.jfree.chart.ChartFactory import org.jfree.chart.ChartPanel import org.jfree.chart.JFreeChart @@ -9,53 +15,43 @@ import org.jfree.chart.plot.XYPlot import org.jfree.data.time.MovingAverage import org.jfree.data.xy.XYSeries import org.jfree.data.xy.XYSeriesCollection -import java.awt.BorderLayout -import java.awt.Color -import java.awt.event.ActionEvent -import java.awt.event.ActionListener -import javax.swing.JCheckBox -import javax.swing.JPanel -class MovingAverageChartPanel(private val parentTab: AbstractStatisticsTab) : JPanel(), ActionListener -{ +class MovingAverageChartPanel(private val parentTab: AbstractStatisticsTab) : + JPanel(), ActionListener { private var graphCollection = XYSeriesCollection() private val panelGraph = ChartPanel(null) private val panelCheckBoxes = JPanel() - init - { + init { layout = BorderLayout(0, 0) panelGraph.layout = BorderLayout(0, 0) add(panelGraph, BorderLayout.CENTER) add(panelCheckBoxes, BorderLayout.SOUTH) } - fun reset(title: String, yLabel: String) - { + fun reset(title: String, yLabel: String) { graphCollection = XYSeriesCollection() panelGraph.chart = ChartFactory.createXYLineChart(title, "Game", yLabel, graphCollection) } - fun finalise() - { + fun finalise() { adjustTickboxes() setPlotColours(panelGraph.chart) } - private fun adjustTickboxes() - { - //Remove checkboxes that are no longer relevant (e.g. just removed a comparison) + private fun adjustTickboxes() { + // Remove checkboxes that are no longer relevant (e.g. just removed a comparison) panelCheckBoxes.getAllChildComponentsForType().forEach { if (getGraphSeriesIndexForCheckBox(it) == -1) panelCheckBoxes.remove(it) } - //Go through what's left and add any others that are required by the graph (e.g. just added a comparison) + // Go through what's left and add any others that are required by the graph (e.g. just added + // a comparison) val checkBoxes = panelCheckBoxes.getAllChildComponentsForType() val allSeries: List = graphCollection.getXYSeries() allSeries.forEach { series -> val key = "${series.key}" - if (checkBoxes.none { cb -> cb.text == key} ) - { + if (checkBoxes.none { cb -> cb.text == key }) { val checkBox = JCheckBox(key) checkBox.isSelected = true checkBox.addActionListener(this) @@ -63,23 +59,23 @@ class MovingAverageChartPanel(private val parentTab: AbstractStatisticsTab) : JP } } - //For any checkboxes that are unticked, remove the graph series - checkBoxes.filter { !it.isSelected }.forEach { graphCollection.removeSeries(getGraphSeriesIndexForCheckBox(it)) } + // For any checkboxes that are unticked, remove the graph series + checkBoxes + .filter { !it.isSelected } + .forEach { graphCollection.removeSeries(getGraphSeriesIndexForCheckBox(it)) } panelCheckBoxes.validate() panelCheckBoxes.repaint() } - private fun getGraphSeriesIndexForCheckBox(checkBox: JCheckBox): Int - { + private fun getGraphSeriesIndexForCheckBox(checkBox: JCheckBox): Int { val allSeries: List = graphCollection.getXYSeries() return allSeries.indexOfFirst { it.key == checkBox.text } } private fun XYSeriesCollection.getXYSeries() = series.filterIsInstance() - private fun setPlotColours(chart: JFreeChart?) - { + private fun setPlotColours(chart: JFreeChart?) { val plot = chart?.plot as? XYPlot ?: throw Exception("No XYPlot found: ${chart?.plot}") val allSeries: List = graphCollection.getXYSeries() @@ -97,22 +93,25 @@ class MovingAverageChartPanel(private val parentTab: AbstractStatisticsTab) : JP } } - fun addSeries(series: XYSeries, avgThreshold: Int) - { + fun addSeries(series: XYSeries, avgThreshold: Int) { val movingAvgSeries = createMovingAverage(series, avgThreshold.toLong()) graphCollection.addSeries(series) graphCollection.addSeries(movingAvgSeries) } - private fun createMovingAverage(original: XYSeries, avgThreshold: Long): XYSeries - { + private fun createMovingAverage(original: XYSeries, avgThreshold: Long): XYSeries { val collection = XYSeriesCollection(original) - val movingAvgCollection = MovingAverage.createMovingAverage(collection," (moving)", avgThreshold,avgThreshold - 1) + val movingAvgCollection = + MovingAverage.createMovingAverage( + collection, + " (moving)", + avgThreshold, + avgThreshold - 1 + ) return (movingAvgCollection as XYSeriesCollection).getSeries(0) } - override fun actionPerformed(arg0: ActionEvent) - { + override fun actionPerformed(arg0: ActionEvent) { parentTab.populateStats() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementBreakdown.kt b/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementBreakdown.kt index 0cf83a14f..72a939736 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementBreakdown.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementBreakdown.kt @@ -6,21 +6,18 @@ import dartzee.screen.EmbeddedScreen import dartzee.screen.ScreenCache import java.awt.BorderLayout -class PlayerAchievementBreakdown : EmbeddedScreen() -{ +class PlayerAchievementBreakdown : EmbeddedScreen() { var achievement: AbstractAchievement? = null private val tableBreakdown = ScrollTableDartsGame() - override fun initialise() - { + override fun initialise() { add(tableBreakdown, BorderLayout.CENTER) } override fun getScreenName() = "${achievement?.name} Breakdown - ${achievement?.player?.name}" - fun setState(achievement: AbstractAchievement) - { + fun setState(achievement: AbstractAchievement) { this.achievement = achievement tableBreakdown.model = achievement.tmBreakdown!! @@ -28,4 +25,3 @@ class PlayerAchievementBreakdown : EmbeddedScreen() override fun getBackTarget() = ScreenCache.get() } - diff --git a/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementsScreen.kt b/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementsScreen.kt index c6db94e1a..c48745f17 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementsScreen.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/PlayerAchievementsScreen.kt @@ -28,8 +28,7 @@ import javax.swing.JScrollPane import javax.swing.ScrollPaneConstants import javax.swing.border.TitledBorder -class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() -{ +class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() { var previousScrn: EmbeddedScreen = ScreenCache.get() private var progressDesc = "" @@ -46,8 +45,7 @@ class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() private val lblIndividualIndicator = JLabel() private val lblTeamIndicator = JLabel() - init - { + init { add(centerPanel, BorderLayout.CENTER) centerPanel.layout = BorderLayout(0, 0) centerPanel.add(scrollPane, BorderLayout.CENTER) @@ -88,8 +86,7 @@ class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() override fun getScreenName() = "Achievements - ${player.name} - $progressDesc" - override fun initialise() - { + override fun initialise() { val achievementRows = AchievementEntity.retrieveAchievements(player.rowId) GameType.values().forEachIndexed { ix, gameType -> addAchievementTab(gameType, ix, achievementRows) @@ -99,8 +96,11 @@ class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() progressDesc = "$score/${getAchievementMaximum()}" } - private fun addAchievementTab(gameType: GameType, index: Int, achievementRows: List) - { + private fun addAchievementTab( + gameType: GameType, + index: Int, + achievementRows: List + ) { val achievementTypes = getAchievementsForGameType(gameType).map { it.achievementType } val max = achievementTypes.size * MAX_ACHIEVEMENT_SCORE val filteredRows = achievementRows.filter { achievementTypes.contains(it.achievementType) } @@ -129,13 +129,14 @@ class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() gridBag.setConstraints(panel, constraints) achievementsPanel.add(panel) - getAchievementsForGameType(gameType).forEach { - addAchievement(it, filteredRows, panel) - } + getAchievementsForGameType(gameType).forEach { addAchievement(it, filteredRows, panel) } } - private fun addAchievement(aa: AbstractAchievement, achievementRows: List, panel: JPanel) - { + private fun addAchievement( + aa: AbstractAchievement, + achievementRows: List, + panel: JPanel + ) { val type = aa.achievementType val achievementRowsFiltered = achievementRows.filter { a -> a.achievementType == type } @@ -145,10 +146,8 @@ class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() panel.add(medal) } - fun toggleAchievementDesc(hovered: Boolean, achievement: AbstractAchievement) - { - if (hovered) - { + fun toggleAchievementDesc(hovered: Boolean, achievement: AbstractAchievement) { + if (hovered) { val color = achievement.getColor(false) setPanelColors(color, color.darker().darker()) @@ -156,22 +155,23 @@ class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() lblAchievementExtraDetails.setMargins(0, -btnBack.width, 0, 0) panelNavigation.add(lblAchievementExtraDetails) - val singlePlayerIcon = if (achievement.allowedForIndividuals) "singlePlayerEnabled" else "singlePlayerDisabled" + val singlePlayerIcon = + if (achievement.allowedForIndividuals) "singlePlayerEnabled" + else "singlePlayerDisabled" lblIndividualIndicator.isVisible = true - lblIndividualIndicator.icon = ImageIcon(javaClass.getResource("/achievements/$singlePlayerIcon.png")) + lblIndividualIndicator.icon = + ImageIcon(javaClass.getResource("/achievements/$singlePlayerIcon.png")) - val teamIcon = if (achievement.allowedForTeams) "multiPlayerEnabled" else "multiPlayerDisabled" + val teamIcon = + if (achievement.allowedForTeams) "multiPlayerEnabled" else "multiPlayerDisabled" lblTeamIndicator.isVisible = true lblTeamIndicator.icon = ImageIcon(javaClass.getResource("/achievements/$teamIcon.png")) - if (!achievement.isLocked()) - { + if (!achievement.isLocked()) { lblAchievementDesc.text = achievement.desc lblAchievementExtraDetails.text = achievement.getExtraDetails() } - } - else - { + } else { setPanelColors(null, null) lblIndividualIndicator.isVisible = false lblTeamIndicator.isVisible = false @@ -182,8 +182,7 @@ class PlayerAchievementsScreen(val player: PlayerEntity) : EmbeddedScreen() } } - private fun setPanelColors(bgColor: Color?, fgColor: Color?) - { + private fun setPanelColors(bgColor: Color?, fgColor: Color?) { panelNavigation.background = bgColor panelAchievementDesc.background = bgColor panelNext.background = bgColor diff --git a/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterDialog.kt b/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterDialog.kt index 6d3c70763..71e26c00c 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterDialog.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterDialog.kt @@ -16,9 +16,7 @@ import javax.swing.JPanel import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener - -class PlayerStatisticsFilterDialog(gameType: GameType): SimpleDialog(), ChangeListener -{ +class PlayerStatisticsFilterDialog(gameType: GameType) : SimpleDialog(), ChangeListener { private var gameParams = "" private var filterByDate = false @@ -30,8 +28,7 @@ class PlayerStatisticsFilterDialog(gameType: GameType): SimpleDialog(), ChangeLi private val chckbxDatePlayed = JCheckBox("Date") private val dateFilter = DateFilterPanel() - init - { + init { title = "Filters" setSize(473, 200) isModal = true @@ -54,15 +51,11 @@ class PlayerStatisticsFilterDialog(gameType: GameType): SimpleDialog(), ChangeLi chckbxDatePlayed.addChangeListener(this) } - fun getFiltersDesc(): String - { + fun getFiltersDesc(): String { var desc = "Showing " - if (gameParams.isEmpty()) - { + if (gameParams.isEmpty()) { desc += "all games" - } - else - { + } else { desc += filterPanel.getFilterDesc() } @@ -71,33 +64,26 @@ class PlayerStatisticsFilterDialog(gameType: GameType): SimpleDialog(), ChangeLi fun getDateDesc() = if (filterByDate) dateFilter.getFilterDesc() else "" - fun resetFilters() - { + fun resetFilters() { gameParams = "" filterByDate = false } - private fun saveState() - { - if (cbType.isSelected) - { + private fun saveState() { + if (cbType.isSelected) { gameParams = filterPanel.getGameParams() - } - else - { + } else { gameParams = "" } filterByDate = chckbxDatePlayed.isSelected } - fun refresh() - { + fun refresh() { cbType.isSelected = !gameParams.isEmpty() filterPanel.isEnabled = cbType.isSelected - if (!gameParams.isEmpty()) - { + if (!gameParams.isEmpty()) { filterPanel.setGameParams(gameParams) } @@ -107,20 +93,16 @@ class PlayerStatisticsFilterDialog(gameType: GameType): SimpleDialog(), ChangeLi private fun valid() = dateFilter.valid() - fun includeGameBasedOnFilters(game:GameWrapper):Boolean - { + fun includeGameBasedOnFilters(game: GameWrapper): Boolean { val gameParamsToCheck = game.gameParams - if (gameParams.isNotEmpty() && gameParamsToCheck != gameParams) - { + if (gameParams.isNotEmpty() && gameParamsToCheck != gameParams) { return false } - //Date filter - if (filterByDate) - { + // Date filter + if (filterByDate) { val dtStart = game.dtStart - if (!dateFilter.filterSqlDate(dtStart)) - { + if (!dateFilter.filterSqlDate(dtStart)) { return false } } @@ -128,10 +110,8 @@ class PlayerStatisticsFilterDialog(gameType: GameType): SimpleDialog(), ChangeLi return true } - override fun okPressed() - { - if (valid()) - { + override fun okPressed() { + if (valid()) { saveState() dispose() @@ -140,15 +120,11 @@ class PlayerStatisticsFilterDialog(gameType: GameType): SimpleDialog(), ChangeLi } } - override fun stateChanged(arg0:ChangeEvent) - { + override fun stateChanged(arg0: ChangeEvent) { val src = arg0.source as Component - if (src === cbType) - { + if (src === cbType) { filterPanel.isEnabled = cbType.isSelected - } - else if (src === chckbxDatePlayed) - { + } else if (src === chckbxDatePlayed) { dateFilter.enableChildren(chckbxDatePlayed.isSelected) } } diff --git a/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterPanel.kt b/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterPanel.kt index 8c3e13729..562238f76 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterPanel.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsFilterPanel.kt @@ -5,7 +5,6 @@ import dartzee.db.PlayerEntity import dartzee.game.GameType import dartzee.screen.ScreenCache import dartzee.stats.GameWrapper -import net.miginfocom.swing.MigLayout import java.awt.Color import java.awt.Dimension import java.awt.FlowLayout @@ -18,12 +17,12 @@ import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants import javax.swing.border.EtchedBorder +import net.miginfocom.swing.MigLayout /** * Info panel to appear above the statistics detailing the player and the filters that are in use. */ -class PlayerStatisticsFilterPanel : JPanel(), ActionListener -{ +class PlayerStatisticsFilterPanel : JPanel(), ActionListener { private val lblAvatar = PlayerAvatar() private val lblFilterDesc = JLabel("No filters") private val btnFilters = JButton("Filters...") @@ -37,8 +36,7 @@ class PlayerStatisticsFilterPanel : JPanel(), ActionListener private var dlg: PlayerStatisticsFilterDialog = PlayerStatisticsFilterDialog(GameType.X01) - init - { + init { val flowLayout = layout as FlowLayout flowLayout.hgap = 0 add(lblAvatar) @@ -67,27 +65,24 @@ class PlayerStatisticsFilterPanel : JPanel(), ActionListener btnX.addActionListener(this) } - fun init(player: PlayerEntity, gameType: GameType, comparison: Boolean) - { + fun init(player: PlayerEntity, gameType: GameType, comparison: Boolean) { dlg = PlayerStatisticsFilterDialog(gameType) lblAvatar.init(player, false) label.text = player.name panelX.isVisible = comparison - if (comparison) - { + if (comparison) { label.foreground = Color.RED lblFilterDesc.foreground = Color.RED lblDateFilter.foreground = Color.RED } - //Reset the filters + // Reset the filters dlg.resetFilters() } - fun update(filteredGames: List) - { + fun update(filteredGames: List) { lblFilterDesc.text = dlg.getFiltersDesc() lblDateFilter.text = dlg.getDateDesc() lblXGames.text = "${filteredGames.size} Games" @@ -95,10 +90,8 @@ class PlayerStatisticsFilterPanel : JPanel(), ActionListener fun includeGame(game: GameWrapper) = dlg.includeGameBasedOnFilters(game) - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnFilters -> { dlg.refresh() dlg.setLocationRelativeTo(this) diff --git a/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsScreen.kt b/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsScreen.kt index af18c9366..3dd10ab31 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsScreen.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/PlayerStatisticsScreen.kt @@ -25,8 +25,7 @@ import javax.swing.JPanel import javax.swing.JTabbedPane import javax.swing.SwingConstants -class PlayerStatisticsScreen : EmbeddedScreen() -{ +class PlayerStatisticsScreen : EmbeddedScreen() { private var hmLocalIdToWrapper = mapOf() private var hmLocalIdToWrapperOther = mapOf() private var filteredGames = listOf() @@ -35,14 +34,14 @@ class PlayerStatisticsScreen : EmbeddedScreen() var gameType: GameType = GameType.X01 var player: PlayerEntity? = null - //Components + // Components private val filterPanels = JPanel() private val filterPanel = PlayerStatisticsFilterPanel() private val filterPanelOther = PlayerStatisticsFilterPanel() private val tabbedPane = JTabbedPane(SwingConstants.TOP) private val btnAdd = JButton("Add Comparison") - //X01 tabs + // X01 tabs private val tabFinishing = StatisticsTabFinishBreakdown() private val tabCheckoutPercent = StatisticsTabX01CheckoutPercent() private val tabTopFinishes = StatisticsTabX01TopFinishes() @@ -50,18 +49,17 @@ class PlayerStatisticsScreen : EmbeddedScreen() private val tabTotalDarts = StatisticsTabTotalScore("Total Darts", 200) private val tabThreeDartScores = StatisticsTabX01ThreeDartScores() - //Golf tabs + // Golf tabs private val tabHoleBreakdown = StatisticsTabGolfHoleBreakdown() private val tabAllScores = StatisticsTabTotalScore("Total Shots", 90) private val tabBestRounds = StatisticsTabGolfScorecards() private val tabOptimalScorecard = StatisticsTabGolfOptimalScorecard() - //Round the Clock tabs + // Round the Clock tabs private val tabTotalClockDarts = StatisticsTabTotalScore("Total Darts", 500) private val tabTargetBreakdown = StatisticsTabRoundTheClockHitRate() - init - { + init { add(filterPanels, BorderLayout.NORTH) add(tabbedPane, BorderLayout.CENTER) @@ -74,8 +72,7 @@ class PlayerStatisticsScreen : EmbeddedScreen() override fun getScreenName() = "${gameType.getDescription()} Statistics for $player" - override fun initialise() - { + override fun initialise() { filterPanel.init(player!!, gameType, false) filterPanelOther.isVisible = false btnAdd.isVisible = true @@ -88,10 +85,10 @@ class PlayerStatisticsScreen : EmbeddedScreen() } /** - * Called when popping this up in a dialog after simulating games from the player amendment dialog (for AIs) + * Called when popping this up in a dialog after simulating games from the player amendment + * dialog (for AIs) */ - fun initFake(hmGameIdToWrapper: Map) - { + fun initFake(hmGameIdToWrapper: Map) { filterPanel.init(player!!, gameType, false) filterPanelOther.isVisible = false btnAdd.isVisible = false @@ -103,36 +100,29 @@ class PlayerStatisticsScreen : EmbeddedScreen() buildTabs() } - private fun resetTabs() - { + private fun resetTabs() { tabbedPane.removeAll() - if (gameType == GameType.X01) - { + if (gameType == GameType.X01) { tabbedPane.addTab("Finish Breakdown", null, tabFinishing, null) tabbedPane.addTab("Checkout %", null, tabCheckoutPercent, null) tabbedPane.addTab("Top Finishes", null, tabTopFinishes, null) tabbedPane.addTab("Dart Average", null, tabThreeDartAverage, null) tabbedPane.addTab("Total Darts", null, tabTotalDarts, null) tabbedPane.addTab("Three Dart Scores", null, tabThreeDartScores, null) - } - else if (gameType == GameType.GOLF) - { + } else if (gameType == GameType.GOLF) { tabbedPane.addTab("Hole Breakdown", null, tabHoleBreakdown, null) tabbedPane.addTab("Scorecards", null, tabBestRounds, null) tabbedPane.addTab("Optimal Scorecard", null, tabOptimalScorecard, null) tabbedPane.addTab("All Scores", null, tabAllScores, null) - } - else if (gameType == GameType.ROUND_THE_CLOCK) - { + } else if (gameType == GameType.ROUND_THE_CLOCK) { tabbedPane.addTab("Total Darts", null, tabTotalClockDarts, null) tabbedPane.addTab("Target Breakdown", null, tabTargetBreakdown, null) } } - private fun addComparison() - { - val player = PlayerSelectDialog.selectPlayer() ?: return //Cancelled + private fun addComparison() { + val player = PlayerSelectDialog.selectPlayer() ?: return // Cancelled filterPanelOther.init(player, gameType, true) filterPanelOther.isVisible = true @@ -142,8 +132,7 @@ class PlayerStatisticsScreen : EmbeddedScreen() buildTabs() } - fun removeComparison() - { + fun removeComparison() { filterPanelOther.isVisible = false btnAdd.isVisible = true hmLocalIdToWrapperOther = mapOf() @@ -151,26 +140,24 @@ class PlayerStatisticsScreen : EmbeddedScreen() buildTabs() } - fun buildTabs() - { + fun buildTabs() { filteredGames = populateFilteredGames(hmLocalIdToWrapper, filterPanel) filteredGamesOther = populateFilteredGames(hmLocalIdToWrapperOther, filterPanelOther) - //Update the tabs + // Update the tabs val tabs = getAllChildComponentsForType() - for (tab in tabs) - { + for (tab in tabs) { tab.setFilteredGames(filteredGames, filteredGamesOther) tab.populateStats() } } - private fun populateFilteredGames(hmGameIdToWrapper: Map, - filterPanel: PlayerStatisticsFilterPanel): List - { + private fun populateFilteredGames( + hmGameIdToWrapper: Map, + filterPanel: PlayerStatisticsFilterPanel + ): List { val allGames = hmGameIdToWrapper.values - if (!filterPanel.isVisible) - { + if (!filterPanel.isVisible) { return allGames.toList() } @@ -179,18 +166,15 @@ class PlayerStatisticsScreen : EmbeddedScreen() return filteredGames } - fun setVariables(gameType: GameType, player: PlayerEntity) - { + fun setVariables(gameType: GameType, player: PlayerEntity) { this.gameType = gameType this.player = player } override fun getBackTarget() = ScreenCache.get() - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnAdd -> addComparison() else -> super.actionPerformed(arg0) } diff --git a/src/main/kotlin/dartzee/screen/stats/player/StatisticsTabTotalScore.kt b/src/main/kotlin/dartzee/screen/stats/player/StatisticsTabTotalScore.kt index 90880a912..5a45d244b 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/StatisticsTabTotalScore.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/StatisticsTabTotalScore.kt @@ -8,14 +8,6 @@ import dartzee.core.obj.HashMapCount import dartzee.core.util.TableUtil.DefaultModel import dartzee.screen.stats.median import dartzee.stats.GameWrapper -import net.miginfocom.swing.MigLayout -import org.jfree.chart.ChartFactory -import org.jfree.chart.ChartPanel -import org.jfree.chart.plot.PlotOrientation -import org.jfree.chart.renderer.category.BoxAndWhiskerRenderer -import org.jfree.data.category.DefaultCategoryDataset -import org.jfree.data.statistics.DefaultBoxAndWhiskerCategoryDataset -import org.jfree.data.xy.XYSeries import java.awt.BorderLayout import java.awt.Color import java.awt.Component @@ -34,14 +26,22 @@ import javax.swing.JTable import javax.swing.SwingConstants import javax.swing.border.TitledBorder import javax.swing.table.DefaultTableCellRenderer +import net.miginfocom.swing.MigLayout +import org.jfree.chart.ChartFactory +import org.jfree.chart.ChartPanel +import org.jfree.chart.plot.PlotOrientation +import org.jfree.chart.renderer.category.BoxAndWhiskerRenderer +import org.jfree.data.category.DefaultCategoryDataset +import org.jfree.data.statistics.DefaultBoxAndWhiskerCategoryDataset +import org.jfree.data.xy.XYSeries /** - * A tab to show bar a line representations for the 'FinalScore' column on Participant. - * Configurable title so it can show "Total Darts" for X01, etc. Also displays mean and median values for FinalScore. - * + * A tab to show bar a line representations for the 'FinalScore' column on Participant. Configurable + * title so it can show "Total Darts" for X01, etc. Also displays mean and median values for + * FinalScore. */ -class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : AbstractStatisticsTab(), ActionListener -{ +class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : + AbstractStatisticsTab(), ActionListener { private var graphMin = Integer.MAX_VALUE private var graphMax = -1 @@ -74,13 +74,17 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : private val boxAndWhiskerChartPanel = ChartPanel(null) private val chckbxIncludeUnfinishedGames = JCheckBox("Include unfinished") - init - { + init { nfMedianOther.preferredSize = Dimension(50, 20) nfMeanOther.preferredSize = Dimension(50, 20) layout = BorderLayout(0, 0) add(tabbedPane, BorderLayout.CENTER) - tabbedPane.addTab("", ImageIcon(javaClass.getResource("/icons/bar chart.png")), panelBar, null) + tabbedPane.addTab( + "", + ImageIcon(javaClass.getResource("/icons/bar chart.png")), + panelBar, + null + ) panelBar.layout = BorderLayout(0, 0) panelBar.add(panel, BorderLayout.CENTER) panelBar.add(panelBarConfiguration, BorderLayout.EAST) @@ -95,7 +99,12 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : panelBarConfiguration.add(nfGroups, "cell 1 1") nfGroups.value = 3 nfGroups.preferredSize = Dimension(50, 20) - tabbedPane.addTab("", ImageIcon(javaClass.getResource("/icons/line chart.png")), panelLine, null) + tabbedPane.addTab( + "", + ImageIcon(javaClass.getResource("/icons/line chart.png")), + panelLine, + null + ) panelLine.layout = BorderLayout(0, 0) panelLine.add(lineChartPanel, BorderLayout.CENTER) panelLine.add(panelLineConfiguration, BorderLayout.EAST) @@ -104,7 +113,12 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : nfAverageThreshold.value = 5 nfAverageThreshold.preferredSize = Dimension(40, 20) panelLineConfiguration.add(nfAverageThreshold, "cell 1 0") - tabbedPane.addTab("", ImageIcon(javaClass.getResource("/icons/boxAndWhisker.png")), panelBoxAndWhisker, null) + tabbedPane.addTab( + "", + ImageIcon(javaClass.getResource("/icons/boxAndWhisker.png")), + panelBoxAndWhisker, + null + ) panelBoxAndWhisker.layout = BorderLayout(0, 0) panelBoxAndWhisker.add(boxAndWhiskerChartPanel, BorderLayout.CENTER) nfGroups.addPropertyChangeListener(this) @@ -125,7 +139,8 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : nfMedian.preferredSize = Dimension(50, 20) panelRawData.add(nfMedian, "flowx,cell 1 3") nfMedian.isEditable = false - panelRawDataTable.border = TitledBorder(null, "Raw Data", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelRawDataTable.border = + TitledBorder(null, "Raw Data", TitledBorder.LEADING, TitledBorder.TOP, null, null) panelRawData.add(panelRawDataTable, "cell 0 5 2 3,grow") panelRawDataTable.layout = BorderLayout(0, 0) panelRawDataTable.add(table) @@ -140,36 +155,36 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : comboBox.addActionListener(this) } - override fun populateStats() - { + override fun populateStats() { val gameParams = initialiseFields() populateStatsWithoutChangingFields(gameParams) } - private fun populateStatsWithoutChangingFields(selectedParams: ComboBoxItem) - { + private fun populateStatsWithoutChangingFields(selectedParams: ComboBoxItem) { val paramDesc = "$selectedParams" lineChartPanel.reset("$graphTitle ($paramDesc)", graphTitle) - //Filter out unfinished games and games with the wrong params - val filter = { g: GameWrapper -> g.gameParams == selectedParams.hiddenData && (g.isFinished() || chckbxIncludeUnfinishedGames.isSelected) } - val gamesToGraph = filteredGames.filter(filter).sortedBy{ it.dtStart } - val otherGamesToGraph = filteredGamesOther.filter(filter).sortedBy{ it.dtStart } + // Filter out unfinished games and games with the wrong params + val filter = { g: GameWrapper -> + g.gameParams == selectedParams.hiddenData && + (g.isFinished() || chckbxIncludeUnfinishedGames.isSelected) + } + val gamesToGraph = filteredGames.filter(filter).sortedBy { it.dtStart } + val otherGamesToGraph = filteredGamesOther.filter(filter).sortedBy { it.dtStart } val includeOther = !otherGamesToGraph.isEmpty() - //Sort out what the min and max displayed on the graph will be + // Sort out what the min and max displayed on the graph will be adjustGraphMinAndMax(gamesToGraph, otherGamesToGraph) - //Sort the games and populate the raw data table + // Sort the games and populate the raw data table populateTable(gamesToGraph) dataset = DefaultCategoryDataset() boxDataset = DefaultBoxAndWhiskerCategoryDataset() addValuesToDataset(gamesToGraph, "Me", nfMedian, nfMean) - if (includeOther) - { + if (includeOther) { addValuesToDataset(otherGamesToGraph, "Other", nfMedianOther, nfMeanOther) } @@ -182,8 +197,7 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : lineChartPanel.finalise() } - private fun initialiseFields(): ComboBoxItem - { + private fun initialiseFields(): ComboBoxItem { val gameParams = initialiseGameTypeComboBox() initialiseOutlierCutOffAndGrouping(gameParams.hiddenData) @@ -191,16 +205,14 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : return gameParams } - private fun initialiseOutlierCutOffAndGrouping(gameParams: String) - { + private fun initialiseOutlierCutOffAndGrouping(gameParams: String) { val filter = { g: GameWrapper -> g.gameParams == gameParams && g.isFinished() } val gamesToGraph = filteredGames.filter(filter) - if (gamesToGraph.isEmpty()) - { + if (gamesToGraph.isEmpty()) { return } - val scores = gamesToGraph.map{ it.finalScore }.sorted() + val scores = gamesToGraph.map { it.finalScore }.sorted() val lqIndex = scores.size / 4 val uqIndex = 3 * lqIndex @@ -213,42 +225,48 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : val min = scores.first() val max = scores.last() - //Go for 10 bars, whatever that works out to be + // Go for 10 bars, whatever that works out to be var grouping = (max - min) / 10 grouping = Math.max(1, grouping) nfGroups.value = grouping } - private fun finaliseBarChart(gameParams: String) - { - val barChart = ChartFactory.createBarChart( + private fun finaliseBarChart(gameParams: String) { + val barChart = + ChartFactory.createBarChart( "$graphTitle ($gameParams)", graphTitle, "Count", dataset, PlotOrientation.VERTICAL, - true, true, false) + true, + true, + false + ) val plot = barChart.categoryPlot plot.renderer.setSeriesPaint(0, Color.BLUE) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { plot.renderer.setSeriesPaint(1, Color.RED) } panel.chart = barChart } - private fun finaliseBoxPlot(gameParams: String) - { - val boxChart = ChartFactory.createBoxAndWhiskerChart("$graphTitle ($gameParams)", - "", "", boxDataset, true) + private fun finaliseBoxPlot(gameParams: String) { + val boxChart = + ChartFactory.createBoxAndWhiskerChart( + "$graphTitle ($gameParams)", + "", + "", + boxDataset, + true + ) val renderer = BoxAndWhiskerRenderer() renderer.isMeanVisible = false renderer.setSeriesPaint(0, Color.BLUE) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { renderer.setSeriesPaint(1, Color.RED) } @@ -260,21 +278,18 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : boxAndWhiskerChartPanel.chart = boxChart } - private fun populateTable(gamesToGraph: List) - { + private fun populateTable(gamesToGraph: List) { val model = DefaultModel() model.addColumn("Ordinal") model.addColumn("Score") model.addColumn("Game") model.addColumn("!Unfinished") - for (i in gamesToGraph.indices) - { + for (i in gamesToGraph.indices) { val g = gamesToGraph[i] var finalScore = g.finalScore - if (finalScore == -1) - { + if (finalScore == -1) { finalScore = g.getAllDarts().size } @@ -288,30 +303,30 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : } /** - * No more mentalness with radio buttons (though it was fun...) - * Now just have a combo box that we populate. Still try to preserve the previous selection if we can. + * No more mentalness with radio buttons (though it was fun...) Now just have a combo box that + * we populate. Still try to preserve the previous selection if we can. */ - private fun initialiseGameTypeComboBox(): ComboBoxItem - { - //Remember what was selected previously. + private fun initialiseGameTypeComboBox(): ComboBoxItem { + // Remember what was selected previously. val selectedItem = comboBox.selectedItem - //Now get what scores should now show + // Now get what scores should now show val startingScores = getDistinctGameParams().sorted().toMutableList() - //Handle 0 games - if (startingScores.isEmpty()) - { + // Handle 0 games + if (startingScores.isEmpty()) { startingScores.add("N/A") } - val comboOptions = startingScores.map { ComboBoxItem(it, getGameType().getParamsDescription(it)) }.toTypedArray() + val comboOptions = + startingScores + .map { ComboBoxItem(it, getGameType().getParamsDescription(it)) } + .toTypedArray() comboBox.model = DefaultComboBoxModel(comboOptions) comboBox.selectedItem = selectedItem var ix = comboBox.selectedIndex - if (ix == -1) - { + if (ix == -1) { ix = 0 comboBox.selectedIndex = 0 } @@ -319,33 +334,32 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : return comboBox.getItemAt(ix) } - - /** - * Get the minimum and maximum number of darts for the graph - */ - private fun adjustGraphMinAndMax(gamesToGraph: List, gamesToGraphOther: List) - { + /** Get the minimum and maximum number of darts for the graph */ + private fun adjustGraphMinAndMax( + gamesToGraph: List, + gamesToGraphOther: List + ) { val combined = (gamesToGraph + gamesToGraphOther).filter { it.isFinished() } - graphMax = combined.map{ it.finalScore }.maxOrNull() ?: Integer.MAX_VALUE - graphMin = combined.map{ it.finalScore }.minOrNull() ?: 0 + graphMax = combined.map { it.finalScore }.maxOrNull() ?: Integer.MAX_VALUE + graphMin = combined.map { it.finalScore }.minOrNull() ?: 0 } - /** - * Deal with populating the dataset used by the bar chart - */ - private fun addValuesToDataset(gamesToGraph: List, legendKey: String, nfMedian: NumberField, nfMean: NumberField) - { - //Build up counts for each game finish value + /** Deal with populating the dataset used by the bar chart */ + private fun addValuesToDataset( + gamesToGraph: List, + legendKey: String, + nfMedian: NumberField, + nfMean: NumberField + ) { + // Build up counts for each game finish value val suffix = " ($legendKey)" val series = XYSeries(graphTitle + suffix) val hmNoDartsToCount = HashMapCount() - for (i in gamesToGraph.indices) - { + for (i in gamesToGraph.indices) { val game = gamesToGraph[i] val score = game.finalScore - if (score > -1) - { + if (score > -1) { series.add((i + 1).toDouble(), score.toDouble()) hmNoDartsToCount.incrementCount(score) } @@ -362,30 +376,27 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : nfMean.value = avg } - private fun appendToDataset(legendKey: String, hmNoDartsToCount: HashMapCount) - { + private fun appendToDataset(legendKey: String, hmNoDartsToCount: HashMapCount) { val outlierLimit = nfOutlier.getNumber() val groups = nfGroups.getNumber() var groupCount = 0 var rangeStart = graphMin - for (i in graphMin..Math.min(outlierLimit, graphMax)) - { + for (i in graphMin..Math.min(outlierLimit, graphMax)) { groupCount += hmNoDartsToCount.getCount(i) - //If we're a multiple of the group #... - if (i % groups == 0 || i == Math.min(outlierLimit, graphMax)) - { + // If we're a multiple of the group #... + if (i % groups == 0 || i == Math.min(outlierLimit, graphMax)) { val rangeDesc = getRangeDesc(rangeStart, i) dataset!!.addValue(groupCount.toDouble(), legendKey, rangeDesc) - //Set up for the next block + // Set up for the next block groupCount = 0 rangeStart = i + 1 } } - val hmOutliers = hmNoDartsToCount.filterKeys{it > outlierLimit} + val hmOutliers = hmNoDartsToCount.filterKeys { it > outlierLimit } val outlierCount = hmOutliers.map { it.value }.sum() dataset!!.addValue(outlierCount.toDouble(), legendKey, (outlierLimit + 1).toString() + "+") @@ -395,49 +406,44 @@ class StatisticsTabTotalScore(private val graphTitle: String, outlierMax: Int) : boxDataset!!.add(allValues, legendKey, "") } - private fun getRangeDesc(start: Int, finish: Int) = if (start == finish) "$start" else "$start - $finish" + private fun getRangeDesc(start: Int, finish: Int) = + if (start == finish) "$start" else "$start - $finish" - /** - * GameParams combo box - */ - override fun actionPerformed(arg0: ActionEvent) - { + /** GameParams combo box */ + override fun actionPerformed(arg0: ActionEvent) { populateStats() } - /** - * The number fields - */ - override fun propertyChange(arg0: PropertyChangeEvent) - { + /** The number fields */ + override fun propertyChange(arg0: PropertyChangeEvent) { val propertyName = arg0.propertyName - if (propertyName == "value") - { + if (propertyName == "value") { val selectedGameParams = comboBox.selectedItemTyped() populateStatsWithoutChangingFields(selectedGameParams) } } - private class TotalScoreRenderer : DefaultTableCellRenderer() - { - override fun getTableCellRendererComponent(table: JTable?, - value: Any, isSelected: Boolean, hasFocus: Boolean, row: Int, - column: Int): Component - { + private class TotalScoreRenderer : DefaultTableCellRenderer() { + override fun getTableCellRendererComponent( + table: JTable?, + value: Any, + isSelected: Boolean, + hasFocus: Boolean, + row: Int, + column: Int + ): Component { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) val modelRow = table!!.rowSorter.convertRowIndexToModel(row) val model = table.model as DefaultModel val unfinished = model.getValueAt(modelRow, 3) as Boolean - foreground = if (unfinished) - { - if (isSelected) Color.CYAN else Color.RED - } - else - { - if (isSelected) Color.WHITE else Color.BLACK - } + foreground = + if (unfinished) { + if (isSelected) Color.CYAN else Color.RED + } else { + if (isSelected) Color.WHITE else Color.BLACK + } return this } diff --git a/src/main/kotlin/dartzee/screen/stats/player/golf/GolfStatsScorecard.kt b/src/main/kotlin/dartzee/screen/stats/player/golf/GolfStatsScorecard.kt index 643f43d0f..7f01cda7b 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/golf/GolfStatsScorecard.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/golf/GolfStatsScorecard.kt @@ -12,15 +12,18 @@ import java.awt.Color import java.awt.Dimension import javax.swing.JPanel -class GolfStatsScorecard(override val fudgeFactor: Int, private val showGameId: Boolean, val testId: String = "") : JPanel(), IGolfScorerTable -{ +class GolfStatsScorecard( + override val fudgeFactor: Int, + private val showGameId: Boolean, + val testId: String = "" +) : JPanel(), IGolfScorerTable { override val model = TableUtil.DefaultModel() + override fun getNumberOfColumns() = if (showGameId) 6 else 5 val tableScores = ScrollTableDartsGame() - init - { + init { layout = BorderLayout(0, 0) add(tableScores, BorderLayout.CENTER) tableScores.setFillsViewportHeight(false) @@ -31,39 +34,32 @@ class GolfStatsScorecard(override val fudgeFactor: Int, private val showGameId: initialiseTable() } - private fun initialiseTable() - { + private fun initialiseTable() { tableScores.setRowHeight(25) - for (i in 0 until getNumberOfColumns()) - { + for (i in 0 until getNumberOfColumns()) { model.addColumn("") } tableScores.model = model - for (i in 0..GOLF_SCORE_COLUMN) - { + for (i in 0..GOLF_SCORE_COLUMN) { tableScores.setRenderer(i, GolfDartRenderer(showGameId)) } - if (showGameId) - { + if (showGameId) { tableScores.setLinkColumnIndex(tableScores.columnCount - 1) } } - fun addGameIds(localGameIds: List) - { + fun addGameIds(localGameIds: List) { localGameIds.forEachIndexed { ix, gameId -> val row = if (ix >= 9) ix + 1 else ix - if (gameId > -1) - { + if (gameId > -1) { model.setValueAt(gameId, row, GOLF_GAME_ID_COLUMN) } } } - fun setTableForeground(color: Color) - { + fun setTableForeground(color: Color) { tableScores.tableForeground = color } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfHoleBreakdown.kt b/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfHoleBreakdown.kt index a77a50b37..bcbb9b66a 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfHoleBreakdown.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfHoleBreakdown.kt @@ -6,19 +6,19 @@ import dartzee.screen.stats.player.HoleBreakdownWrapper import dartzee.stats.GameWrapper import java.awt.Color -class StatisticsTabGolfHoleBreakdown: AbstractStatisticsTabPieBreakdown() -{ +class StatisticsTabGolfHoleBreakdown : AbstractStatisticsTabPieBreakdown() { override val ranges = listOf(1..1, 2..2, 3..3, 4..4, 5..5) override fun getColorForRange(range: IntRange): Color = getGolfScorerColour(range.first, 1.0) - override fun getTableRows(filteredGames: List): Pair>, List?> - { + override fun getTableRows( + filteredGames: List + ): Pair>, List?> { val breakdownRows = mutableListOf>() val hm = mutableMapOf() - filteredGames.forEach{ it.updateHoleBreakdowns(hm) } + filteredGames.forEach { it.updateHoleBreakdowns(hm) } val overall = hm.remove(-1) @@ -29,4 +29,4 @@ class StatisticsTabGolfHoleBreakdown: AbstractStatisticsTabPieBreakdown() return Pair(breakdownRows, overall?.getAsTableRow("Overall")) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfOptimalScorecard.kt b/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfOptimalScorecard.kt index 781244439..c9cc40c35 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfOptimalScorecard.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfOptimalScorecard.kt @@ -13,15 +13,13 @@ import javax.swing.JPanel * Cherry-picks your best performance ever for each hole and assembles it into an 'ideal' scorecard. * Just for fun! */ -class StatisticsTabGolfOptimalScorecard : AbstractStatisticsTab() -{ +class StatisticsTabGolfOptimalScorecard : AbstractStatisticsTab() { private val panelMine = JPanel() private val panelMyScorecard = JPanel() private val panelOther = JPanel() private val panelOtherScorecard = JPanel() - init - { + init { layout = GridLayout(0, 2, 0, 0) add(panelMine) panelMine.layout = BorderLayout(0, 0) @@ -34,31 +32,26 @@ class StatisticsTabGolfOptimalScorecard : AbstractStatisticsTab() panelOtherScorecard.layout = BorderLayout(0, 0) } - override fun populateStats() - { + override fun populateStats() { setOtherComponentVisibility(this, panelOther) populateStats(filteredGames, panelMyScorecard, false) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { populateStats(filteredGamesOther, panelOtherScorecard, true) } } - private fun populateStats(filteredGames: List, panel: JPanel, other: Boolean) - { + private fun populateStats(filteredGames: List, panel: JPanel, other: Boolean) { val hmHoleToOptimalScorecard = makeOptimalScorecardStartingMap() val sortedGames = filteredGames.sortedBy { it.dtStart } - for (game in sortedGames) - { + for (game in sortedGames) { game.populateOptimalScorecardMaps(hmHoleToOptimalScorecard) } val testId = if (other) "scorecardOther" else "scorecardMine" val scoreSheet = GolfStatsScorecard(0, true, testId) - if (other) - { + if (other) { scoreSheet.setTableForeground(Color.RED) } @@ -75,15 +68,13 @@ class StatisticsTabGolfOptimalScorecard : AbstractStatisticsTab() data class OptimalHoleStat(val darts: List, val localGameId: Long) -fun makeOptimalScorecardStartingMap(): MutableMap -{ +fun makeOptimalScorecardStartingMap(): MutableMap { val hm = mutableMapOf() // Add fudge data so we always display something, even if there are no games - for (i in 1..18) - { + for (i in 1..18) { hm[i] = OptimalHoleStat(listOf(Dart(20, 0), Dart(20, 0), Dart(20, 0)), -1) } return hm -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfScorecards.kt b/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfScorecards.kt index 227051793..8f20a8b87 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfScorecards.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/golf/StatisticsTabGolfScorecards.kt @@ -20,8 +20,7 @@ import javax.swing.JLabel import javax.swing.JPanel import javax.swing.ListSelectionModel -class StatisticsTabGolfScorecards : AbstractStatisticsTab(), ActionListener, RowSelectionListener -{ +class StatisticsTabGolfScorecards : AbstractStatisticsTab(), ActionListener, RowSelectionListener { private var mode: GolfMode = GolfMode.FULL_18 private val comboBoxMode = JComboBox>() private val panelCenter = JPanel() @@ -33,8 +32,7 @@ class StatisticsTabGolfScorecards : AbstractStatisticsTab(), ActionListener, Row private val scrollTableOther = ScrollTableDartsGame(testId = "ScorecardsOther") private val panelOtherScorecard = JPanel() - init - { + init { layout = BorderLayout(0, 0) val panelMode = JPanel() @@ -65,49 +63,46 @@ class StatisticsTabGolfScorecards : AbstractStatisticsTab(), ActionListener, Row override fun populateStats() = populateStats(true) - private fun populateStats(rebuildComboBox: Boolean) - { - if (rebuildComboBox) - { + private fun populateStats(rebuildComboBox: Boolean) { + if (rebuildComboBox) { initialiseComboBoxModel() } - //Hide or show the 'other' panel depending on whether there's a comparison + // Hide or show the 'other' panel depending on whether there's a comparison setOtherComponentVisibility(panelCenter, panelOther) - //Update the mode based on what's selected in the combo box + // Update the mode based on what's selected in the combo box val ix = comboBoxMode.selectedIndex val item = comboBoxMode.getItemAt(ix) mode = item.hiddenData - //And now populate the table(s) + // And now populate the table(s) populateTable(filteredGames, scrollTableMine) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { populateTable(filteredGamesOther, scrollTableOther) } } - private fun initialiseComboBoxModel() - { + private fun initialiseComboBoxModel() { val model = DefaultComboBoxModel>() addMode("Front 9", GolfMode.FRONT_9, model) addMode("Back 9", GolfMode.BACK_9, model) addMode("Full 18", GolfMode.FULL_18, model) - if (model.size == 0) - { + if (model.size == 0) { model.addElement(ComboBoxItem(GolfMode.FULL_18, "N/A")) } comboBoxMode.model = model } - private fun addMode(modeDesc: String, mode: GolfMode, model: DefaultComboBoxModel>) - { + private fun addMode( + modeDesc: String, + mode: GolfMode, + model: DefaultComboBoxModel> + ) { val validGames = filteredGames.filter { !it.teamGame && it.getRoundScore(mode) > -1 } - if (validGames.isEmpty()) - { + if (validGames.isEmpty()) { return } @@ -115,39 +110,36 @@ class StatisticsTabGolfScorecards : AbstractStatisticsTab(), ActionListener, Row model.addElement(item) } - private fun populateTable(games: List, scrollTable: ScrollTableDartsGame) - { - //Filter out the -1's - these are games that haven't gone on long enough to have all the data + private fun populateTable(games: List, scrollTable: ScrollTableDartsGame) { + // Filter out the -1's - these are games that haven't gone on long enough to have all the + // data val filteredGames = games.filter { !it.teamGame } val validGames = filteredGames.filter { it.getRoundScore(mode) > -1 } - //Populate the table from the wrappers + // Populate the table from the wrappers val model = TableUtil.DefaultModel() model.addColumn("Game") model.addColumn("Score") model.addColumn("!GameObject") - val rows = validGames.map{ arrayOf(it.localId, it.getRoundScore(mode), it) } + val rows = validGames.map { arrayOf(it.localId, it.getRoundScore(mode), it) } model.addRows(rows) scrollTable.model = model scrollTable.removeColumn(2) scrollTable.sortBy(1, false) - //Select a row so the scorecard automatically populates - if (validGames.isNotEmpty()) - { + // Select a row so the scorecard automatically populates + if (validGames.isNotEmpty()) { scrollTable.selectFirstRow() } } - private fun displayScorecard(game: GameWrapper, scorecardPanel: JPanel, other: Boolean) - { + private fun displayScorecard(game: GameWrapper, scorecardPanel: JPanel, other: Boolean) { val fudgeFactor = if (mode == GolfMode.BACK_9) 9 else 0 val testId = if (other) "scorecardOther" else "scorecardMine" val scorer = GolfStatsScorecard(fudgeFactor, showGameId = false, testId = testId) - if (other) - { + if (other) { scorer.setTableForeground(Color.RED) } @@ -162,17 +154,14 @@ class StatisticsTabGolfScorecards : AbstractStatisticsTab(), ActionListener, Row override fun actionPerformed(e: ActionEvent) = populateStats(false) - override fun selectionChanged(src: ScrollTable) - { + override fun selectionChanged(src: ScrollTable) { val row = src.selectedModelRow - if (row == -1) - { + if (row == -1) { return } val game = src.getNonNullValueAt(row, 2) as GameWrapper - when (src) - { + when (src) { scrollTableMine -> displayScorecard(game, panelMyScorecard, false) scrollTableOther -> displayScorecard(game, panelOtherScorecard, true) } diff --git a/src/main/kotlin/dartzee/screen/stats/player/rtc/StatisticsTabRoundTheClockHitRate.kt b/src/main/kotlin/dartzee/screen/stats/player/rtc/StatisticsTabRoundTheClockHitRate.kt index e81f7c696..e1b71d7b1 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/rtc/StatisticsTabRoundTheClockHitRate.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/rtc/StatisticsTabRoundTheClockHitRate.kt @@ -6,13 +6,11 @@ import dartzee.screen.stats.player.AbstractStatisticsTabPieBreakdown import dartzee.stats.GameWrapper import java.awt.Color -class StatisticsTabRoundTheClockHitRate : AbstractStatisticsTabPieBreakdown() -{ +class StatisticsTabRoundTheClockHitRate : AbstractStatisticsTabPieBreakdown() { override val ranges = listOf(1..1, 2..2, 3..3, 4..6, 7..10, 11..15, 16..Int.MAX_VALUE) override fun getColorForRange(range: IntRange): Color = - when (range) - { + when (range) { ranges[0] -> Color.GREEN ranges[1] -> Color.getHSBColor(0.25f, 1f, 1f) ranges[2] -> Color.getHSBColor(0.2f, 1f, 1f) @@ -25,8 +23,7 @@ class StatisticsTabRoundTheClockHitRate : AbstractStatisticsTabPieBreakdown() override fun applyAdditionalFilters(filteredGames: List) = filteredGames.filter { RoundTheClockConfig.fromJson(it.gameParams).inOrder } - override fun getTableRows(filteredGames: List): Pair>, List> - { + override fun getTableRows(filteredGames: List): Pair>, List> { val breakdownRows = mutableListOf>() val hmTargetToAverageDarts = getAverageThrowsPerTarget(filteredGames) @@ -42,19 +39,24 @@ class StatisticsTabRoundTheClockHitRate : AbstractStatisticsTabPieBreakdown() ranges.forEach { hmRangeToOverallCount.incrementCount(it, rangeToCount.getCount(it)) } } - //Overall + // Overall val overallAverage = hmTargetToAverageDarts.values.sum() / 20 - val totalRow = listOf("Overall") + ranges.map{ hmRangeToOverallCount.getCount(it) } + listOf(overallAverage) + val totalRow = + listOf("Overall") + + ranges.map { hmRangeToOverallCount.getCount(it) } + + listOf(overallAverage) return Pair(breakdownRows, totalRow) } private fun getAverageThrowsPerTarget(games: List) = - games.flatMap { it.getAllDarts() } + games + .flatMap { it.getAllDarts() } .groupBy { it.startingScore } .mapValues { it.value.size.toDouble() / games.size } - private fun getRangeBreakdownPerTarget(games: List): Map> - { + private fun getRangeBreakdownPerTarget( + games: List + ): Map> { val hmRangeBreakdown = mutableMapOf>() val hmCountConstructor = { HashMapCount() } @@ -68,4 +70,4 @@ class StatisticsTabRoundTheClockHitRate : AbstractStatisticsTabPieBreakdown() return hmRangeBreakdown } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabFinishBreakdown.kt b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabFinishBreakdown.kt index a228fa135..fc8b9bbf6 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabFinishBreakdown.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabFinishBreakdown.kt @@ -8,19 +8,17 @@ import dartzee.core.util.containsComponent import dartzee.screen.stats.player.AbstractStatisticsTab import dartzee.stats.GameWrapper import dartzee.utils.getCheckoutSingles -import org.jfree.chart.ChartFactory -import org.jfree.chart.ChartPanel -import org.jfree.chart.plot.PiePlot -import org.jfree.data.general.DefaultPieDataset import java.awt.Color import java.awt.GridLayout import javax.swing.JPanel import javax.swing.ListSelectionModel import javax.swing.border.TitledBorder +import org.jfree.chart.ChartFactory +import org.jfree.chart.ChartPanel +import org.jfree.chart.plot.PiePlot +import org.jfree.data.general.DefaultPieDataset - -class StatisticsTabFinishBreakdown: AbstractStatisticsTab(), RowSelectionListener -{ +class StatisticsTabFinishBreakdown : AbstractStatisticsTab(), RowSelectionListener { private var selectedScore: Int? = null private val tableFavouriteDoubles = ScrollTable(testId = "DoublesMine") @@ -28,31 +26,28 @@ class StatisticsTabFinishBreakdown: AbstractStatisticsTab(), RowSelectionListene private val tablePanel = JPanel() private val pieChartPanel = ChartPanel(null) - init - { - layout = GridLayout(1, 3, 0, 0) + init { + layout = GridLayout(1, 3, 0, 0) - tableFavouriteDoublesOther.tableForeground = Color.RED - tableFavouriteDoubles.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) - tableFavouriteDoublesOther.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) - tablePanel.border = TitledBorder(null, "Double Finishes") + tableFavouriteDoublesOther.tableForeground = Color.RED + tableFavouriteDoubles.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) + tableFavouriteDoublesOther.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) + tablePanel.border = TitledBorder(null, "Double Finishes") - add(tablePanel) - tablePanel.layout = GridLayout(2, 1, 0, 0) - tablePanel.add(tableFavouriteDoubles) - tablePanel.add(tableFavouriteDoublesOther) - add(pieChartPanel) + add(tablePanel) + tablePanel.layout = GridLayout(2, 1, 0, 0) + tablePanel.add(tableFavouriteDoubles) + tablePanel.add(tableFavouriteDoublesOther) + add(pieChartPanel) tableFavouriteDoubles.addRowSelectionListener(this) - } + } - override fun populateStats() - { + override fun populateStats() { setTableVisibility() val dataset = buildFavouriteDoublesData(tableFavouriteDoubles, filteredGames) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { buildFavouriteDoublesData(tableFavouriteDoublesOther, filteredGamesOther) } @@ -62,8 +57,10 @@ class StatisticsTabFinishBreakdown: AbstractStatisticsTab(), RowSelectionListene pieChartPanel.chart = pieChart } - private fun buildFavouriteDoublesData(table: ScrollTable, filteredGames: List): DefaultPieDataset - { + private fun buildFavouriteDoublesData( + table: ScrollTable, + filteredGames: List + ): DefaultPieDataset { val model = DefaultModel() model.addColumn("Double") model.addColumn("Finishes") @@ -74,19 +71,23 @@ class StatisticsTabFinishBreakdown: AbstractStatisticsTab(), RowSelectionListene return dataset } - private fun populateFavouriteDoubles(model: DefaultModel, filteredGames: List): DefaultPieDataset - { - val scores = filteredGames.filter { it.isFinished() }.map { it.getDartsForFinalRound().last().score } + private fun populateFavouriteDoubles( + model: DefaultModel, + filteredGames: List + ): DefaultPieDataset { + val scores = + filteredGames.filter { it.isFinished() }.map { it.getDartsForFinalRound().last().score } - val rows: List> = scores.distinct().map { double -> - val count = scores.count { score -> score == double } - val percent = MathsUtil.getPercentage(count, scores.size.toDouble()) - arrayOf(double, count, percent) - } + val rows: List> = + scores.distinct().map { double -> + val count = scores.count { score -> score == double } + val percent = MathsUtil.getPercentage(count, scores.size.toDouble()) + arrayOf(double, count, percent) + } model.addRows(rows) - //Build up the pie set. Unlike the table, we need ALL values + // Build up the pie set. Unlike the table, we need ALL values val dataset = DefaultPieDataset() getCheckoutSingles().sorted().forEach { double -> val count = scores.count { score -> score == double } @@ -96,15 +97,11 @@ class StatisticsTabFinishBreakdown: AbstractStatisticsTab(), RowSelectionListene return dataset } - private fun setTableVisibility() - { - if (!includeOtherComparison()) - { + private fun setTableVisibility() { + if (!includeOtherComparison()) { tablePanel.layout = GridLayout(1, 1, 0, 0) tablePanel.remove(tableFavouriteDoublesOther) - } - else if (!tablePanel.containsComponent(tableFavouriteDoublesOther)) - { + } else if (!tablePanel.containsComponent(tableFavouriteDoublesOther)) { tablePanel.layout = GridLayout(2, 1, 0, 0) tablePanel.add(tableFavouriteDoublesOther) } @@ -112,22 +109,19 @@ class StatisticsTabFinishBreakdown: AbstractStatisticsTab(), RowSelectionListene tablePanel.repaint() } - override fun selectionChanged(src: ScrollTable) - { + override fun selectionChanged(src: ScrollTable) { val pieChart = pieChartPanel.chart - @Suppress("UNCHECKED_CAST") - val plot = pieChart.plot!! as PiePlot + @Suppress("UNCHECKED_CAST") val plot = pieChart.plot!! as PiePlot - //Unset the old value + // Unset the old value selectedScore?.let { plot.setExplodePercent(it.toString(), 0.0) } val selectedRow = src.selectedModelRow - if (selectedRow > -1) - { + if (selectedRow > -1) { val newSelection = src.getNonNullValueAt(selectedRow, 0) as Int plot.setExplodePercent(newSelection.toString(), 0.2) selectedScore = newSelection } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01CheckoutPercent.kt b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01CheckoutPercent.kt index b3d11d9f0..1c55e0ba4 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01CheckoutPercent.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01CheckoutPercent.kt @@ -14,18 +14,14 @@ import java.awt.Color import java.awt.GridLayout import javax.swing.JPanel -/** - * Checkout percentages for X01 - */ -class StatisticsTabX01CheckoutPercent : AbstractStatisticsTab() -{ +/** Checkout percentages for X01 */ +class StatisticsTabX01CheckoutPercent : AbstractStatisticsTab() { private val panelMine = JPanel() private val tableMine = ScrollTable() private val panelOther = JPanel() private val tableOther = ScrollTable() - init - { + init { layout = GridLayout(0, 2, 0, 0) add(panelMine) @@ -37,23 +33,18 @@ class StatisticsTabX01CheckoutPercent : AbstractStatisticsTab() tableOther.tableForeground = Color.RED } - override fun populateStats() - { + override fun populateStats() { setOtherComponentVisibility(this, panelOther) populateTable(tableMine, filteredGames) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { populateTable(tableOther, filteredGamesOther) } - } - private fun populateTable(table: ScrollTable, games: List) - { + private fun populateTable(table: ScrollTable, games: List) { val hmDoubleToDartsThrown = HashMapList() - for (g in games) - { + for (g in games) { addDartsToHashMap(g, hmDoubleToDartsThrown) } @@ -72,7 +63,13 @@ class StatisticsTabX01CheckoutPercent : AbstractStatisticsTab() val opportunities = darts.size val hits = darts.filter { drt -> drt.isDouble() && drt.getTotal() == checkout }.size - val row = arrayOf(checkout / 2, opportunities, hits, MathsUtil.getPercentage(hits, opportunities.toDouble())) + val row = + arrayOf( + checkout / 2, + opportunities, + hits, + MathsUtil.getPercentage(hits, opportunities.toDouble()) + ) model.addRow(row) totalOpportunities += opportunities @@ -81,22 +78,25 @@ class StatisticsTabX01CheckoutPercent : AbstractStatisticsTab() table.model = model - val totalsRow = arrayOf("", totalOpportunities, totalHits, MathsUtil.getPercentage(totalHits, totalOpportunities.toDouble())) + val totalsRow = + arrayOf( + "", + totalOpportunities, + totalHits, + MathsUtil.getPercentage(totalHits, totalOpportunities.toDouble()) + ) table.addFooterRow(totalsRow) table.sortBy(0, false) } - private fun addDartsToHashMap(g: GameWrapper, hmDoubleToDartsThrown: HashMapList) - { + private fun addDartsToHashMap(g: GameWrapper, hmDoubleToDartsThrown: HashMapList) { val darts = g.getAllDarts() - for (drt in darts) - { - if (isCheckoutDart(drt)) - { + for (drt in darts) { + if (isCheckoutDart(drt)) { val startingScore = drt.startingScore hmDoubleToDartsThrown.putInList(startingScore, drt) } } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartAverage.kt b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartAverage.kt index 3a085d923..6bd24a17c 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartAverage.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartAverage.kt @@ -7,8 +7,6 @@ import dartzee.core.util.TableUtil.DefaultModel import dartzee.screen.stats.player.AbstractStatisticsTab import dartzee.screen.stats.player.MovingAverageChartPanel import dartzee.stats.GameWrapper -import net.miginfocom.swing.MigLayout -import org.jfree.data.xy.XYSeries import java.awt.BorderLayout import java.awt.Color import java.awt.Dimension @@ -16,9 +14,10 @@ import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JTextField import javax.swing.border.TitledBorder +import net.miginfocom.swing.MigLayout +import org.jfree.data.xy.XYSeries -class StatisticsTabX01ThreeDartAverage : AbstractStatisticsTab() -{ +class StatisticsTabX01ThreeDartAverage : AbstractStatisticsTab() { private val nfScoringThreshold = NumberField(62, 501, testId = "setupThreshold") private val lblMovingAverageInterval = JLabel("Moving Average Interval") private val nfAverageThreshold = NumberField(1, 200) @@ -33,8 +32,7 @@ class StatisticsTabX01ThreeDartAverage : AbstractStatisticsTab() private val nfMissPercent = NumberField(testId = "missPercent") private val nfOtherMissPercent = NumberField(testId = "missPercentOther") - init - { + init { nfAverageThreshold.preferredSize = Dimension(40, 20) layout = BorderLayout(0, 0) val panel = JPanel() @@ -56,7 +54,8 @@ class StatisticsTabX01ThreeDartAverage : AbstractStatisticsTab() nfMissPercent.preferredSize = Dimension(40, 20) nfMissPercent.isEditable = false panel.add(nfMissPercent, "flowx,cell 1 4") - panelTable.border = TitledBorder(null, "Raw Data", TitledBorder.LEADING, TitledBorder.TOP, null, null) + panelTable.border = + TitledBorder(null, "Raw Data", TitledBorder.LEADING, TitledBorder.TOP, null, null) panel.add(panelTable, "cell 0 6 2 1") panelTable.layout = BorderLayout(0, 0) panelTable.add(tableBestAverages) @@ -77,14 +76,13 @@ class StatisticsTabX01ThreeDartAverage : AbstractStatisticsTab() nfAverageThreshold.addPropertyChangeListener(this) } - override fun populateStats() - { + override fun populateStats() { chartPanel.reset("3 Dart Average", "Average") nfOtherThreeDartAvg.isVisible = includeOtherComparison() nfOtherMissPercent.isVisible = includeOtherComparison() - //Construct the table model + // Construct the table model val model = DefaultModel() model.addColumn("Ordinal") model.addColumn("Average") @@ -92,30 +90,40 @@ class StatisticsTabX01ThreeDartAverage : AbstractStatisticsTab() model.addColumn("Game") populateStats(filteredGames, model, nfThreeDartAverage, nfMissPercent, "") - if (includeOtherComparison()) - { - populateStats(filteredGamesOther, null, nfOtherThreeDartAvg, nfOtherMissPercent, " (Other)") + if (includeOtherComparison()) { + populateStats( + filteredGamesOther, + null, + nfOtherThreeDartAvg, + nfOtherMissPercent, + " (Other)" + ) } chartPanel.finalise() - //Finish off the table model + // Finish off the table model tableBestAverages.model = model tableBestAverages.sortBy(0, false) } - private fun populateStats(filteredGames: List, model: DefaultModel?, nfThreeDartAverage: JTextField, - nfMissPercent: JTextField, graphSuffix: String) - { - //Filter out unfinished games, then sort by start date - val sortedGames = filteredGames.sortedBy{ it.dtStart } + private fun populateStats( + filteredGames: List, + model: DefaultModel?, + nfThreeDartAverage: JTextField, + nfMissPercent: JTextField, + graphSuffix: String + ) { + // Filter out unfinished games, then sort by start date + val sortedGames = filteredGames.sortedBy { it.dtStart } val scoreThreshold = nfScoringThreshold.getNumber() val allScoringDarts = sortedGames.flatMap { it.getScoringDarts(scoreThreshold) } val totalScoringDarts = allScoringDarts.size.toDouble() val misses = allScoringDarts.count { it.multiplier == 0 }.toDouble() - val overallThreeDartAvg = 3 * allScoringDarts.sumOf { it.getTotal() } / allScoringDarts.size.toDouble() + val overallThreeDartAvg = + 3 * allScoringDarts.sumOf { it.getTotal() } / allScoringDarts.size.toDouble() val rawAverages = XYSeries("Avg$graphSuffix") sortedGames.forEachIndexed { i, game -> @@ -124,23 +132,22 @@ class StatisticsTabX01ThreeDartAverage : AbstractStatisticsTab() val startValue = game.getGameStartValueX01() val gameId = game.localId - //Table row - only show the raw data for the actual player, not the comparison - if (model != null) - { + // Table row - only show the raw data for the actual player, not the comparison + if (model != null) { val row = arrayOf(ordinal, avg, startValue, gameId) model.addRow(row) } - //Graph point + // Graph point rawAverages.add(ordinal, avg) } chartPanel.addSeries(rawAverages, nfAverageThreshold.getNumber()) - //Overall avg, to 1 d.p + // Overall avg, to 1 d.p nfThreeDartAverage.text = "" + MathsUtil.round(overallThreeDartAvg, 1) - //Miss percent, to 1 d.p + // Miss percent, to 1 d.p nfMissPercent.text = "" + MathsUtil.round(100 * misses / totalScoringDarts, 1) } } diff --git a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartScores.kt b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartScores.kt index a9817a54b..6474d1112 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartScores.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01ThreeDartScores.kt @@ -18,19 +18,19 @@ import javax.swing.JPanel import javax.swing.ListSelectionModel import javax.swing.SwingConstants -class StatisticsTabX01ThreeDartScores : AbstractStatisticsTab(), RowSelectionListener -{ +class StatisticsTabX01ThreeDartScores : AbstractStatisticsTab(), RowSelectionListener { private val panelTables = JPanel() - private val tableBreakdownMine = ScrollTableDartsGame("Example Game", testId = "PlayerBreakdown") - private val tableBreakdownOther = ScrollTableDartsGame("Example Game", testId = "OtherBreakdown") + private val tableBreakdownMine = + ScrollTableDartsGame("Example Game", testId = "PlayerBreakdown") + private val tableBreakdownOther = + ScrollTableDartsGame("Example Game", testId = "OtherBreakdown") private val panelConfig = JPanel() private val lblScoreThreshold = JLabel("Score Threshold") private val nfScoreThreshold = NumberField(62, 300) private val tableScoresMine = ScrollTable(testId = "PlayerScores") private val tableScoresOther = ScrollTable(testId = "OtherScores") - init - { + init { nfScoreThreshold.columns = 10 layout = BorderLayout(0, 0) @@ -55,47 +55,43 @@ class StatisticsTabX01ThreeDartScores : AbstractStatisticsTab(), RowSelectionLis tableScoresOther.addRowSelectionListener(this) } - override fun populateStats() - { + override fun populateStats() { setComponentVisibility() populateTable(tableScoresMine, filteredGames) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { populateTable(tableScoresOther, filteredGamesOther) } } - private fun setComponentVisibility() - { + private fun setComponentVisibility() { panelTables.removeAll() - if (includeOtherComparison()) - { + if (includeOtherComparison()) { panelTables.layout = GridLayout(2, 2, 0, 0) panelTables.add(tableScoresMine) panelTables.add(tableScoresOther) panelTables.add(tableBreakdownMine) panelTables.add(tableBreakdownOther) - } - else - { + } else { panelTables.layout = GridLayout(2, 1, 0, 0) panelTables.add(tableScoresMine) panelTables.add(tableBreakdownMine) } } - private fun populateTable(table: ScrollTable, filteredGames: List) - { - //Sort by start date + private fun populateTable(table: ScrollTable, filteredGames: List) { + // Sort by start date val sortedGames = filteredGames.sortedBy { it.dtStart } - //Build up two maps, one of score to count (e.g. 20, 5, 1 -> 10) and the other of score to example game + // Build up two maps, one of score to count (e.g. 20, 5, 1 -> 10) and the other of score to + // example game val hmScoreToThreeDartBreakdown = mutableMapOf() - for (game in sortedGames) - { - game.populateThreeDartScoreMap(hmScoreToThreeDartBreakdown, nfScoreThreshold.getNumber()) + for (game in sortedGames) { + game.populateThreeDartScoreMap( + hmScoreToThreeDartBreakdown, + nfScoreThreshold.getNumber() + ) } val model = DefaultModel() @@ -103,9 +99,10 @@ class StatisticsTabX01ThreeDartScores : AbstractStatisticsTab(), RowSelectionLis model.addColumn("Count") model.addColumn("!Wrapper") - val rows = hmScoreToThreeDartBreakdown.entries.map { (score, wrapper) - -> arrayOf(score, wrapper.getTotalCount(), wrapper) - } + val rows = + hmScoreToThreeDartBreakdown.entries.map { (score, wrapper) -> + arrayOf(score, wrapper.getTotalCount(), wrapper) + } model.addRows(rows) @@ -120,9 +117,10 @@ class StatisticsTabX01ThreeDartScores : AbstractStatisticsTab(), RowSelectionLis table.sortBy(0, false) } - - private fun populateBreakdownTable(table: ScrollTableDartsGame, wrapper: ThreeDartScoreWrapper) - { + private fun populateBreakdownTable( + table: ScrollTableDartsGame, + wrapper: ThreeDartScoreWrapper + ) { val model = DefaultModel() model.addColumn("Method") model.addColumn("Count") @@ -140,20 +138,17 @@ class StatisticsTabX01ThreeDartScores : AbstractStatisticsTab(), RowSelectionLis table.sortBy(1, true) } - override fun selectionChanged(src: ScrollTable) - { + override fun selectionChanged(src: ScrollTable) { val selectedRow = src.selectedModelRow - if (selectedRow == -1) - { + if (selectedRow == -1) { return } val wrapper = src.getNonNullValueAt(selectedRow, 2) as ThreeDartScoreWrapper - when (src) - { + when (src) { tableScoresMine -> populateBreakdownTable(tableBreakdownMine, wrapper) tableScoresOther -> populateBreakdownTable(tableBreakdownOther, wrapper) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01TopFinishes.kt b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01TopFinishes.kt index ca6f8c5a3..755c0d96b 100644 --- a/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01TopFinishes.kt +++ b/src/main/kotlin/dartzee/screen/stats/player/x01/StatisticsTabX01TopFinishes.kt @@ -9,13 +9,11 @@ import java.awt.Color import java.awt.GridLayout import javax.swing.SwingConstants -class StatisticsTabX01TopFinishes : AbstractStatisticsTab() -{ +class StatisticsTabX01TopFinishes : AbstractStatisticsTab() { private val tableTopFinishesMine = ScrollTableDartsGame(testId = "TopFinishesMine") private val tableTopFinishesOther = ScrollTableDartsGame() - init - { + init { layout = GridLayout(0, 2, 0, 0) add(tableTopFinishesMine) @@ -24,33 +22,28 @@ class StatisticsTabX01TopFinishes : AbstractStatisticsTab() tableTopFinishesOther.tableForeground = Color.RED } - override fun populateStats() - { + override fun populateStats() { setOtherComponentVisibility(this, tableTopFinishesOther) buildTopFinishesTable(filteredGames, tableTopFinishesMine) - if (includeOtherComparison()) - { + if (includeOtherComparison()) { buildTopFinishesTable(filteredGamesOther, tableTopFinishesOther) } } - private fun buildTopFinishesTable(games: List, table: ScrollTableDartsGame) - { + private fun buildTopFinishesTable(games: List, table: ScrollTableDartsGame) { val model = TableUtil.DefaultModel() model.addColumn("Finish") model.addColumn("Darts") model.addColumn("Game") - //Sort by checkout total. + // Sort by checkout total. val sortedGames = games.sortedByDescending { it.getCheckoutTotal() } val listSize = Math.min(MAX_FINISHES_TO_SHOW, games.size) - for (i in 0 until listSize) - { + for (i in 0 until listSize) { val game = sortedGames[i] - if (!game.isFinished()) - { + if (!game.isFinished()) { continue } @@ -68,8 +61,7 @@ class StatisticsTabX01TopFinishes : AbstractStatisticsTab() table.sortBy(0, true) } - companion object - { + companion object { private const val MAX_FINISHES_TO_SHOW = 25 } } diff --git a/src/main/kotlin/dartzee/screen/sync/SyncManagementPanel.kt b/src/main/kotlin/dartzee/screen/sync/SyncManagementPanel.kt index 64abc2686..0a17f9242 100644 --- a/src/main/kotlin/dartzee/screen/sync/SyncManagementPanel.kt +++ b/src/main/kotlin/dartzee/screen/sync/SyncManagementPanel.kt @@ -10,7 +10,6 @@ import dartzee.sync.resetRemote import dartzee.sync.validateSyncAction import dartzee.utils.InjectedThings import dartzee.utils.ResourceCache -import net.miginfocom.swing.MigLayout import java.awt.BorderLayout import java.awt.Color import java.awt.Dimension @@ -27,9 +26,9 @@ import javax.swing.JOptionPane import javax.swing.JPanel import javax.swing.border.LineBorder import javax.swing.border.TitledBorder +import net.miginfocom.swing.MigLayout -class SyncManagementPanel: JPanel(), ActionListener -{ +class SyncManagementPanel : JPanel(), ActionListener { private var remoteName = "" private val btnPerformSync = JButton("Perform Sync") @@ -43,8 +42,7 @@ class SyncManagementPanel: JPanel(), ActionListener private val btnPull = JButton("Pull") private val btnReset = JButton("Reset") - init - { + init { layout = BorderLayout(0, 0) add(panelMainOptions, BorderLayout.CENTER) btnPerformSync.icon = ImageIcon(javaClass.getResource("/buttons/sync.png")) @@ -76,11 +74,17 @@ class SyncManagementPanel: JPanel(), ActionListener panelPushPull.add(btnPull) panelOtherOptions.add(panelPushPull, "cell 0 0,alignx center,aligny center") panelOtherOptions.add(btnReset, "cell 0 1,alignx center,aligny center") - panelOtherOptions.border = TitledBorder(null, "Other options", TitledBorder.LEADING, TitledBorder.DEFAULT_POSITION, ResourceCache.BASE_FONT.deriveFont(Font.PLAIN, 20f)) + panelOtherOptions.border = + TitledBorder( + null, + "Other options", + TitledBorder.LEADING, + TitledBorder.DEFAULT_POSITION, + ResourceCache.BASE_FONT.deriveFont(Font.PLAIN, 20f) + ) val buttons = getAllChildComponentsForType() - for (button in buttons) - { + for (button in buttons) { button.font = Font("Tahoma", Font.PLAIN, 18) button.preferredSize = Dimension(200, 100) button.addActionListener(this) @@ -89,40 +93,38 @@ class SyncManagementPanel: JPanel(), ActionListener btnReset.foreground = Color.RED.darker() } - fun updateStatus(syncData: LastSyncData) - { + fun updateStatus(syncData: LastSyncData) { val pendingGameCount = getModifiedGameCount() remoteName = syncData.remoteName lblSharedDatabaseName.text = "Shared Database: $remoteName" - lblLastSynced.text = "Last Synced: ${syncData.lastSynced.formatTimestamp()}" - lblPendingGames.text = "Pending Games: $pendingGameCount" + lblLastSynced.text = + "Last Synced: ${syncData.lastSynced.formatTimestamp()}" + lblPendingGames.text = + "Pending Games: $pendingGameCount" } - private fun getColourForGameCount(pendingGameCount: Int) = when { - pendingGameCount >= 10 -> "red" - pendingGameCount >= 1 -> "orange" - else -> "green" - } + private fun getColourForGameCount(pendingGameCount: Int) = + when { + pendingGameCount >= 10 -> "red" + pendingGameCount >= 1 -> "orange" + else -> "green" + } - private fun getColour(lastSynced: Timestamp): String - { + private fun getColour(lastSynced: Timestamp): String { val currentTime = InjectedThings.clock.instant() val diff = Duration.between(lastSynced.toInstant(), currentTime) - return when - { + return when { diff.toDays() > 7 -> "red" diff.toHours() > 24 -> "orange" else -> "green" } } - override fun actionPerformed(arg0: ActionEvent) - { - when (arg0.source) - { + override fun actionPerformed(arg0: ActionEvent) { + when (arg0.source) { btnReset -> resetPressed() btnPerformSync -> syncPressed() btnPush -> pushPressed() @@ -130,19 +132,16 @@ class SyncManagementPanel: JPanel(), ActionListener } } - private fun pushPressed() - { - if (!validateSyncAction()) - { + private fun pushPressed() { + if (!validateSyncAction()) { return } - if (InjectedThings.syncManager.databaseExists(remoteName)) - { - val q = "Are you sure you want to push to $remoteName? \n\nThis will overwrite any data that hasn't been synced to this device." + if (InjectedThings.syncManager.databaseExists(remoteName)) { + val q = + "Are you sure you want to push to $remoteName? \n\nThis will overwrite any data that hasn't been synced to this device." val ans = DialogUtil.showQuestionOLD(q) - if (ans != JOptionPane.YES_OPTION) - { + if (ans != JOptionPane.YES_OPTION) { return } } @@ -150,40 +149,35 @@ class SyncManagementPanel: JPanel(), ActionListener InjectedThings.syncManager.doPush(remoteName) } - private fun pullPressed() - { - if (!validateSyncAction()) - { + private fun pullPressed() { + if (!validateSyncAction()) { return } - val q = "Are you sure you want to pull from $remoteName? \n\nThis will overwrite any local data that hasn't been synced to $remoteName from this device." + val q = + "Are you sure you want to pull from $remoteName? \n\nThis will overwrite any local data that hasn't been synced to $remoteName from this device." val ans = DialogUtil.showQuestionOLD(q) - if (ans != JOptionPane.YES_OPTION) - { + if (ans != JOptionPane.YES_OPTION) { return } InjectedThings.syncManager.doPull(remoteName) } - private fun syncPressed() - { - if (!validateSyncAction()) - { + private fun syncPressed() { + if (!validateSyncAction()) { return } InjectedThings.syncManager.doSyncIfNecessary(remoteName) } - private fun resetPressed() - { - val q = "Are you sure you want to reset?\n\nThis will not delete any local data, but will sever the link with $remoteName, requiring you to set it up again." + private fun resetPressed() { + val q = + "Are you sure you want to reset?\n\nThis will not delete any local data, but will sever the link with $remoteName, requiring you to set it up again." val answer = DialogUtil.showQuestionOLD(q) - if (answer == JOptionPane.YES_OPTION) - { + if (answer == JOptionPane.YES_OPTION) { resetRemote() } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/sync/SyncManagementScreen.kt b/src/main/kotlin/dartzee/screen/sync/SyncManagementScreen.kt index 08afe2a9f..fbf12e37e 100644 --- a/src/main/kotlin/dartzee/screen/sync/SyncManagementScreen.kt +++ b/src/main/kotlin/dartzee/screen/sync/SyncManagementScreen.kt @@ -6,23 +6,18 @@ import dartzee.screen.ScreenCache import dartzee.utils.InjectedThings.mainDatabase import java.awt.BorderLayout -class SyncManagementScreen: EmbeddedScreen() -{ +class SyncManagementScreen : EmbeddedScreen() { private val setupPanel = SyncSetupPanel() private val managementPanel = SyncManagementPanel() - override fun initialise() - { + override fun initialise() { remove(setupPanel) remove(managementPanel) val lastSyncData = SyncAuditEntity.getLastSyncData(mainDatabase) - if (lastSyncData == null) - { + if (lastSyncData == null) { add(setupPanel, BorderLayout.CENTER) - } - else - { + } else { managementPanel.updateStatus(lastSyncData) add(managementPanel, BorderLayout.CENTER) } @@ -32,4 +27,4 @@ class SyncManagementScreen: EmbeddedScreen() } override fun getScreenName() = "Sync Management" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/screen/sync/SyncProgressDialog.kt b/src/main/kotlin/dartzee/screen/sync/SyncProgressDialog.kt index b13e4a026..9042a395b 100644 --- a/src/main/kotlin/dartzee/screen/sync/SyncProgressDialog.kt +++ b/src/main/kotlin/dartzee/screen/sync/SyncProgressDialog.kt @@ -12,12 +12,10 @@ import javax.swing.SwingUtilities import javax.swing.WindowConstants import javax.swing.border.EmptyBorder -class SyncProgressDialog : JDialog() -{ +class SyncProgressDialog : JDialog() { private val progressBar = JProgressBar() - init - { + init { setSize(300, 90) isResizable = false setLocationRelativeTo(ScreenCache.mainScreen) @@ -39,13 +37,11 @@ class SyncProgressDialog : JDialog() defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE } - fun setVisibleLater() - { + fun setVisibleLater() { SwingUtilities.invokeLater { isVisible = true } } - fun progressToStage(stage: SyncStage) - { + fun progressToStage(stage: SyncStage) { val stageIndex = SyncStage.values().toList().indexOf(stage) SwingUtilities.invokeLater { progressBar.value = stageIndex @@ -54,28 +50,23 @@ class SyncProgressDialog : JDialog() } } - fun disposeLater() - { + fun disposeLater() { SwingUtilities.invokeLater { dispose() } } - companion object - { + companion object { private val instance = SyncProgressDialog() - fun syncStarted() - { + fun syncStarted() { instance.progressToStage(SyncStage.PULL_REMOTE) instance.setVisibleLater() } - fun progressToStage(stage: SyncStage) - { + fun progressToStage(stage: SyncStage) { instance.progressToStage(stage) } - fun dispose() - { + fun dispose() { instance.disposeLater() } diff --git a/src/main/kotlin/dartzee/screen/sync/SyncSetupPanel.kt b/src/main/kotlin/dartzee/screen/sync/SyncSetupPanel.kt index 8871c127c..4d2d82708 100644 --- a/src/main/kotlin/dartzee/screen/sync/SyncSetupPanel.kt +++ b/src/main/kotlin/dartzee/screen/sync/SyncSetupPanel.kt @@ -17,8 +17,7 @@ import javax.swing.JLabel import javax.swing.JPanel import javax.swing.SwingConstants -class SyncSetupPanel: JPanel(), ActionListener -{ +class SyncSetupPanel : JPanel(), ActionListener { private val instructionsPanel = JPanel() private val syncPanelOne = JLabel() private val syncPanelTwo = JLabel() @@ -31,8 +30,7 @@ class SyncSetupPanel: JPanel(), ActionListener private val setupPanel = JPanel() private val btnSetUp = JButton("Get Started > ") - init - { + init { layout = BorderLayout(0, 0) infoPanel.layout = BorderLayout(0, 0) @@ -79,24 +77,20 @@ class SyncSetupPanel: JPanel(), ActionListener btnSetUp.addActionListener(this) } - override fun actionPerformed(e: ActionEvent?) - { + override fun actionPerformed(e: ActionEvent?) { setUpPressed() } - private fun setUpPressed() - { - if (!validateSyncAction()) - { + private fun setUpPressed() { + if (!validateSyncAction()) { return } val result = syncConfigurer.doFirstTimeSetup() ?: return - when (result.mode) - { + when (result.mode) { SyncMode.CREATE_REMOTE -> syncManager.doPush(result.remoteName) SyncMode.OVERWRITE_LOCAL -> syncManager.doPull(result.remoteName) SyncMode.NORMAL_SYNC -> syncManager.doSync(result.remoteName) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/stats/GameWrapper.kt b/src/main/kotlin/dartzee/stats/GameWrapper.kt index f8dac1df3..7fd9a7e62 100644 --- a/src/main/kotlin/dartzee/stats/GameWrapper.kt +++ b/src/main/kotlin/dartzee/stats/GameWrapper.kt @@ -23,9 +23,7 @@ enum class GolfMode { FULL_18 } -/** - * Wraps up an entire game of darts from a single player's perspective - */ +/** Wraps up an entire game of darts from a single player's perspective */ class GameWrapper( val localId: Long, val gameParams: String, @@ -36,35 +34,32 @@ class GameWrapper( private var totalRounds: Int = 0, private val hmRoundNumberToDarts: HashMapList = HashMapList(), ) { - /** - * Helpers - */ + /** Helpers */ fun getAllDarts() = hmRoundNumberToDarts.getFlattenedValuesSortedByKey() fun isFinished() = finalScore > -1 private fun getScoreForFinalRound() = getScoreForRound(totalRounds) + fun getDartsForFinalRound() = getDartsForRound(totalRounds) - /** - * X01 Helpers - */ - //For unfinished games, return -1 so they're sorted to the back + /** X01 Helpers */ + // For unfinished games, return -1 so they're sorted to the back fun getCheckoutTotal() = if (finalScore == -1) -1 else getScoreForFinalRound() + fun getGameStartValueX01() = gameParams.toInt() private fun getAllDartsFlattened() = hmRoundNumberToDarts.getAllValues() - fun addDart(dart: Dart) - { + fun addDart(dart: Dart) { totalRounds = max(dart.roundNumber, totalRounds) hmRoundNumberToDarts.putInList(dart.roundNumber, dart) } - private fun getDartsForRound(roundNumber: Int) = hmRoundNumberToDarts[roundNumber] ?: emptyList() + private fun getDartsForRound(roundNumber: Int) = + hmRoundNumberToDarts[roundNumber] ?: emptyList() - private fun getScoreForRound(roundNumber: Int): Int - { + private fun getScoreForRound(roundNumber: Int): Int { val darts = getDartsForRound(roundNumber) return sumScore(darts) @@ -72,67 +67,58 @@ class GameWrapper( /** * Calculate the 3-dart average, only counting the darts that were thrown up to a certain point. - * N.B: This method does NOT handle 'busts' when considering whether you've gone below the score threshold. - * Therefore, the smallest threshold that should ever be passed in is 62. + * N.B: This method does NOT handle 'busts' when considering whether you've gone below the score + * threshold. Therefore, the smallest threshold that should ever be passed in is 62. */ - fun getThreeDartAverage(scoreCutOff: Int): Double - { + fun getThreeDartAverage(scoreCutOff: Int): Double { val darts = getAllDartsFlattened() - if (darts.isEmpty()) - { + if (darts.isEmpty()) { return -1.0 } return calculateThreeDartAverage(darts, scoreCutOff) } - fun getScoringDarts(scoreCutOff: Int): List - { + fun getScoringDarts(scoreCutOff: Int): List { val allDarts = getAllDartsFlattened() return getScoringDarts(allDarts, scoreCutOff) } - /** - * Three dart scores - */ - fun populateThreeDartScoreMap(hmScoreToBreakdownWrapper: MutableMap, scoreThreshold: Int) - { + /** Three dart scores */ + fun populateThreeDartScoreMap( + hmScoreToBreakdownWrapper: MutableMap, + scoreThreshold: Int + ) { val dartRounds = hmRoundNumberToDarts.values.toList() val scoringRounds = getScoringRounds(dartRounds, scoreThreshold) scoringRounds.forEach { dartsForRound -> val score = sumScore(dartsForRound) - val wrapper: ThreeDartScoreWrapper = hmScoreToBreakdownWrapper.getOrPut(score, ::ThreeDartScoreWrapper) + val wrapper: ThreeDartScoreWrapper = + hmScoreToBreakdownWrapper.getOrPut(score, ::ThreeDartScoreWrapper) val dartStr = getSortedDartStr(dartsForRound) wrapper.addDartStr(dartStr, localId) } } - /** - * Golf Helpers - */ - private fun getScoreForHole(hole: Int): Int - { + /** Golf Helpers */ + private fun getScoreForHole(hole: Int): Int { val darts = getDartsForRound(hole) val scoringDart = darts.last() return scoringDart.getGolfScore(hole) } - fun updateHoleBreakdowns(hm: MutableMap) - { + fun updateHoleBreakdowns(hm: MutableMap) { var overallBreakdown: HoleBreakdownWrapper? = hm[-1] - if (overallBreakdown == null) - { + if (overallBreakdown == null) { overallBreakdown = HoleBreakdownWrapper() hm[-1] = overallBreakdown } - for (i in 1..totalRounds) - { + for (i in 1..totalRounds) { var wrapper: HoleBreakdownWrapper? = hm[i] - if (wrapper == null) - { + if (wrapper == null) { wrapper = HoleBreakdownWrapper() hm[i] = wrapper } @@ -140,73 +126,64 @@ class GameWrapper( val score = getScoreForHole(i) wrapper.increment(score) - //Increment an overall one + // Increment an overall one overallBreakdown.increment(score) } } - /** - * Get the overall score for front 9, back 9 or the whole lot - */ - fun getRoundScore(mode: GolfMode): Int - { + /** Get the overall score for front 9, back 9 or the whole lot */ + fun getRoundScore(mode: GolfMode): Int { val startHole = getStartHoleForMode(mode) val endHole = getEndHoleForMode(mode) return getScore(startHole, endHole) } - private fun getScore(startHole: Int, finishHole: Int): Int - { - if (totalRounds < finishHole) - { - //We haven't completed all the necessary rounds + private fun getScore(startHole: Int, finishHole: Int): Int { + if (totalRounds < finishHole) { + // We haven't completed all the necessary rounds return -1 } var total = 0 - for (i in startHole..finishHole) - { + for (i in startHole..finishHole) { total += getScoreForHole(i) } return total } - fun getGolfRounds(mode: GolfMode): List> - { + fun getGolfRounds(mode: GolfMode): List> { val startHole = getStartHoleForMode(mode) val endHole = getEndHoleForMode(mode) return (startHole..endHole).map(::getDartsForRound) } - private fun getStartHoleForMode(mode: GolfMode) = - if (mode == GolfMode.BACK_9) 10 else 1 + private fun getStartHoleForMode(mode: GolfMode) = if (mode == GolfMode.BACK_9) 10 else 1 - private fun getEndHoleForMode(mode: GolfMode) = - if (mode == GolfMode.FRONT_9) 9 else 18 + private fun getEndHoleForMode(mode: GolfMode) = if (mode == GolfMode.FRONT_9) 9 else 18 - fun populateOptimalScorecardMaps(hmHoleToOptimalHoleStat: MutableMap) - { - for (i in 1..totalRounds) - { + fun populateOptimalScorecardMaps(hmHoleToOptimalHoleStat: MutableMap) { + for (i in 1..totalRounds) { val darts = getDartsForRound(i) if (darts.isEmpty()) continue val currentValue = hmHoleToOptimalHoleStat.getValue(i) - if (isBetterGolfRound(i, darts, currentValue.localGameId, currentValue.darts)) - { + if (isBetterGolfRound(i, darts, currentValue.localGameId, currentValue.darts)) { hmHoleToOptimalHoleStat[i] = OptimalHoleStat(darts, localId) } } } - private fun isBetterGolfRound(hole: Int, dartsNew: List, currentGameId: Long, dartsCurrent: List): Boolean - { - if (currentGameId == -1L) - { + private fun isBetterGolfRound( + hole: Int, + dartsNew: List, + currentGameId: Long, + dartsCurrent: List + ): Boolean { + if (currentGameId == -1L) { return true } @@ -216,14 +193,12 @@ class GameWrapper( lastDart = dartsCurrent.last() val scoreCurrent = lastDart.getGolfScore(hole) - //If the new score is strictly less, then it's better - if (scoreNew < scoreCurrent) - { + // If the new score is strictly less, then it's better + if (scoreNew < scoreCurrent) { return true } - if (scoreNew > scoreCurrent) - { + if (scoreNew > scoreCurrent) { return false } @@ -233,29 +208,25 @@ class GameWrapper( return newSize < currentSize } - /** - * RTC Helpers - */ - fun getRangeByTarget(ranges: List): Map - { - return getAllDarts().groupBy{ it.startingScore } - .mapValues{ it.value.size } - .mapValues{ e -> ranges.find{ it.contains(e.value) }!! } + /** RTC Helpers */ + fun getRangeByTarget(ranges: List): Map { + return getAllDarts() + .groupBy { it.startingScore } + .mapValues { it.value.size } + .mapValues { e -> ranges.find { it.contains(e.value) }!! } } var gameEntity: GameEntity? = null var participantEntity: ParticipantEntity? = null val simulationDartEntities = mutableListOf() - fun clearEntities() - { + fun clearEntities() { gameEntity = null participantEntity = null simulationDartEntities.clear() } - fun generateRealEntities(gameType: GameType, player: PlayerEntity) - { + fun generateRealEntities(gameType: GameType, player: PlayerEntity) { val game = GameEntity() game.assignRowId() game.gameType = gameType @@ -275,12 +246,11 @@ class GameWrapper( participantEntity = pt - for (i in 1..totalRounds) - { + for (i in 1..totalRounds) { val darts = hmRoundNumberToDarts[i]!! darts.forEachIndexed { ix, drt -> - val de = DartEntity.factory(drt, player.rowId, pt.rowId, i, ix+1) + val de = DartEntity.factory(drt, player.rowId, pt.rowId, i, ix + 1) simulationDartEntities.add(de) } } diff --git a/src/main/kotlin/dartzee/stats/StatsSqlUtil.kt b/src/main/kotlin/dartzee/stats/StatsSqlUtil.kt index 92751cc04..1a0d7c26a 100644 --- a/src/main/kotlin/dartzee/stats/StatsSqlUtil.kt +++ b/src/main/kotlin/dartzee/stats/StatsSqlUtil.kt @@ -9,13 +9,12 @@ import dartzee.utils.InjectedThings import dartzee.utils.InjectedThings.mainDatabase import java.sql.SQLException -fun getGameCounts(player: PlayerEntity): HashMapCount -{ +fun getGameCounts(player: PlayerEntity): HashMapCount { val hmTypeToCount = HashMapCount() - val query = "SELECT g.GameType FROM Participant pt, Game g WHERE pt.GameId = g.RowId AND pt.PlayerId = '${player.rowId}'" + val query = + "SELECT g.GameType FROM Participant pt, Game g WHERE pt.GameId = g.RowId AND pt.PlayerId = '${player.rowId}'" mainDatabase.executeQuery(query).use { rs -> - while (rs.next()) - { + while (rs.next()) { val gameType = GameType.valueOf(rs.getString("GameType")) hmTypeToCount.incrementCount(gameType) } @@ -24,24 +23,23 @@ fun getGameCounts(player: PlayerEntity): HashMapCount return hmTypeToCount } -fun retrieveGameData(playerId: String, gameType: GameType): Map -{ +fun retrieveGameData(playerId: String, gameType: GameType): Map { val hm = mutableMapOf() val zzParticipants = buildParticipantTable(playerId, gameType) ?: return hm val sb = StringBuilder() - sb.append(" SELECT zz.LocalId, zz.GameParams, zz.DtCreation, zz.DtFinish, zz.FinalScore, zz.TeamId, ") + sb.append( + " SELECT zz.LocalId, zz.GameParams, zz.DtCreation, zz.DtFinish, zz.FinalScore, zz.TeamId, " + ) sb.append(" drt.RoundNumber,") sb.append(" drt.Ordinal, drt.Score, drt.Multiplier, drt.StartingScore, drt.SegmentType") sb.append(" FROM Dart drt, $zzParticipants zz") sb.append(" WHERE drt.ParticipantId = zz.ParticipantId") sb.append(" AND drt.PlayerId = zz.PlayerId") - try - { + try { mainDatabase.executeQuery(sb).use { rs -> - while (rs.next()) - { + while (rs.next()) { val gameId = rs.getLong("LocalId") val gameParams = rs.getString("GameParams") val dtStart = rs.getTimestamp("DtCreation") @@ -55,7 +53,17 @@ fun retrieveGameData(playerId: String, gameType: GameType): Map() private val hmDartStrToExampleGameId = HashMap() - fun addDartStr(dartStr: String, gameId: Long) - { + fun addDartStr(dartStr: String, gameId: Long) { val count = hmDartStrToCount.incrementCount(dartStr) - if (count == 1) - { + if (count == 1) { hmDartStrToExampleGameId[dartStr] = gameId } } - fun createRows(): List> - { - return hmDartStrToCount.entries.map {(dartStr, count) -> + fun createRows(): List> { + return hmDartStrToCount.entries.map { (dartStr, count) -> arrayOf(dartStr, count, hmDartStrToExampleGameId[dartStr]!!) } } fun getTotalCount() = hmDartStrToCount.getTotalCount() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStore.kt b/src/main/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStore.kt index dbfa43e1a..56f030a29 100644 --- a/src/main/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStore.kt +++ b/src/main/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStore.kt @@ -15,40 +15,51 @@ import dartzee.utils.AwsUtils import dartzee.utils.DartsDatabaseUtil import dartzee.utils.Database import dartzee.utils.InjectedThings.logger -import net.lingala.zip4j.ZipFile -import net.lingala.zip4j.model.ZipParameters import java.io.File import java.util.* +import net.lingala.zip4j.ZipFile +import net.lingala.zip4j.model.ZipParameters -class AmazonS3RemoteDatabaseStore(private val bucketName: String): IRemoteDatabaseStore -{ +class AmazonS3RemoteDatabaseStore(private val bucketName: String) : IRemoteDatabaseStore { private val s3Client = AwsUtils.makeS3Client() - override fun databaseExists(remoteName: String) = s3Client.doesObjectExist(bucketName, getCurrentDatabaseKey(remoteName)) + override fun databaseExists(remoteName: String) = + s3Client.doesObjectExist(bucketName, getCurrentDatabaseKey(remoteName)) - override fun fetchDatabase(remoteName: String): FetchDatabaseResult - { - logger.info(CODE_FETCHING_DATABASE, "Fetching database $remoteName", KEY_REMOTE_NAME to remoteName) + override fun fetchDatabase(remoteName: String): FetchDatabaseResult { + logger.info( + CODE_FETCHING_DATABASE, + "Fetching database $remoteName", + KEY_REMOTE_NAME to remoteName + ) val downloadPath = File("$SYNC_DIR/original.zip") val request = GetObjectRequest(bucketName, getCurrentDatabaseKey(remoteName)) val s3Obj = s3Client.getObject(request, downloadPath) - logger.info(CODE_FETCHED_DATABASE, + logger.info( + CODE_FETCHED_DATABASE, "Fetched database $remoteName - saved to $downloadPath. Last modified remotely: ${s3Obj.lastModified}", - KEY_REMOTE_NAME to remoteName) + KEY_REMOTE_NAME to remoteName + ) val resultingDb = Database(DartsDatabaseUtil.OTHER_DATABASE_NAME) ZipFile(downloadPath).extractAll(resultingDb.getDirectoryStr()) - logger.info(CODE_UNZIPPED_DATABASE, "Unzipped database $remoteName to ${resultingDb.getDirectory()}") + logger.info( + CODE_UNZIPPED_DATABASE, + "Unzipped database $remoteName to ${resultingDb.getDirectory()}" + ) return FetchDatabaseResult(resultingDb, s3Obj.lastModified) } - override fun pushDatabase(remoteName: String, database: Database, lastModified: Date?) - { + override fun pushDatabase(remoteName: String, database: Database, lastModified: Date?) { SyncProgressDialog.progressToStage(SyncStage.PUSH_TO_REMOTE) - logger.info(CODE_PUSHING_DATABASE, "Pushing database to $remoteName", KEY_REMOTE_NAME to remoteName) + logger.info( + CODE_PUSHING_DATABASE, + "Pushing database to $remoteName", + KEY_REMOTE_NAME to remoteName + ) lastModified?.let { verifyLastModifiedNotChanged(remoteName, lastModified) } @@ -58,27 +69,43 @@ class AmazonS3RemoteDatabaseStore(private val bucketName: String): IRemoteDataba val params = ZipParameters().also { it.isIncludeRootFolder = false } val zip = ZipFile(zipFilePath).also { it.addFolder(dbDirectory, params) } - logger.info(CODE_ZIPPED_DATABASE, "Zipped up database to push to $remoteName - $zipFilePath") + logger.info( + CODE_ZIPPED_DATABASE, + "Zipped up database to push to $remoteName - $zipFilePath" + ) s3Client.putObject(bucketName, getCurrentDatabaseKey(remoteName), zip.file) - logger.info(CODE_PUSHED_DATABASE, "Pushed database to ${getCurrentDatabaseKey(remoteName)}", KEY_REMOTE_NAME to remoteName) + logger.info( + CODE_PUSHED_DATABASE, + "Pushed database to ${getCurrentDatabaseKey(remoteName)}", + KEY_REMOTE_NAME to remoteName + ) SyncProgressDialog.progressToStage(SyncStage.PUSH_BACKUP_TO_REMOTE) val dbVersion = database.getDatabaseVersion() val backupName = "${getFileTimeString()}_V$dbVersion.zip" - s3Client.copyObject(bucketName, getCurrentDatabaseKey(remoteName), bucketName, "$remoteName/backups/$backupName") - logger.info(CODE_PUSHED_DATABASE_BACKUP, "Copied backup to $remoteName/backups/$backupName", KEY_REMOTE_NAME to remoteName) + s3Client.copyObject( + bucketName, + getCurrentDatabaseKey(remoteName), + bucketName, + "$remoteName/backups/$backupName" + ) + logger.info( + CODE_PUSHED_DATABASE_BACKUP, + "Copied backup to $remoteName/backups/$backupName", + KEY_REMOTE_NAME to remoteName + ) } - private fun verifyLastModifiedNotChanged(remoteName: String, lastModified: Date) - { + private fun verifyLastModifiedNotChanged(remoteName: String, lastModified: Date) { val metadata = s3Client.getObjectMetadata(bucketName, getCurrentDatabaseKey(remoteName)) - if (metadata.lastModified > lastModified) - { - throw ConcurrentModificationException("Remote database $remoteName was last modified ${metadata.lastModified}, which is after $lastModified - aborting") + if (metadata.lastModified > lastModified) { + throw ConcurrentModificationException( + "Remote database $remoteName was last modified ${metadata.lastModified}, which is after $lastModified - aborting" + ) } } private fun getCurrentDatabaseKey(remoteName: String) = "$remoteName/current.zip" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/sync/IRemoteDatabaseStore.kt b/src/main/kotlin/dartzee/sync/IRemoteDatabaseStore.kt index ee485b874..ecd8adeab 100644 --- a/src/main/kotlin/dartzee/sync/IRemoteDatabaseStore.kt +++ b/src/main/kotlin/dartzee/sync/IRemoteDatabaseStore.kt @@ -5,10 +5,10 @@ import java.util.* data class FetchDatabaseResult(val database: Database, val lastModified: Date) -interface IRemoteDatabaseStore -{ +interface IRemoteDatabaseStore { fun databaseExists(remoteName: String): Boolean + fun fetchDatabase(remoteName: String): FetchDatabaseResult fun pushDatabase(remoteName: String, database: Database, lastModified: Date? = null) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/sync/SyncConfigurer.kt b/src/main/kotlin/dartzee/sync/SyncConfigurer.kt index d4b10eae9..c1b1b8afc 100644 --- a/src/main/kotlin/dartzee/sync/SyncConfigurer.kt +++ b/src/main/kotlin/dartzee/sync/SyncConfigurer.kt @@ -2,42 +2,48 @@ package dartzee.sync import dartzee.core.util.DialogUtil -class SyncConfigurer(private val dbStore: IRemoteDatabaseStore) -{ - fun doFirstTimeSetup(): SyncConfig? - { - val remoteName = DialogUtil.showInput("Sync Setup", "Enter a unique name for the shared database (case-sensitive)") - if (remoteName.isNullOrBlank()) - { +class SyncConfigurer(private val dbStore: IRemoteDatabaseStore) { + fun doFirstTimeSetup(): SyncConfig? { + val remoteName = + DialogUtil.showInput( + "Sync Setup", + "Enter a unique name for the shared database (case-sensitive)" + ) + if (remoteName.isNullOrBlank()) { return null } - if (dbStore.databaseExists(remoteName)) - { + if (dbStore.databaseExists(remoteName)) { val options = listOf("Overwrite local data", "Sync with local data", "Cancel") - val response = DialogUtil.showOption("Database found", - "Shared database '$remoteName' already exists. How would you like to proceed?", options) + val response = + DialogUtil.showOption( + "Database found", + "Shared database '$remoteName' already exists. How would you like to proceed?", + options + ) - if (response == null || response == "Cancel") - { + if (response == null || response == "Cancel") { return null } - val choice = if (response == "Overwrite local data") SyncMode.OVERWRITE_LOCAL else SyncMode.NORMAL_SYNC + val choice = + if (response == "Overwrite local data") SyncMode.OVERWRITE_LOCAL + else SyncMode.NORMAL_SYNC return SyncConfig(choice, remoteName) - } - else - { + } else { val options = listOf("Create '$remoteName'", "Cancel") - val response = DialogUtil.showOption("Database not found", - "No shared database found called '$remoteName'. Would you like to create it?", options) + val response = + DialogUtil.showOption( + "Database not found", + "No shared database found called '$remoteName'. Would you like to create it?", + options + ) - if (response == null || response == "Cancel") - { + if (response == null || response == "Cancel") { return null } return SyncConfig(SyncMode.CREATE_REMOTE, remoteName) } } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/sync/SyncDataLossError.kt b/src/main/kotlin/dartzee/sync/SyncDataLossError.kt index a9754a6d7..099ae5245 100644 --- a/src/main/kotlin/dartzee/sync/SyncDataLossError.kt +++ b/src/main/kotlin/dartzee/sync/SyncDataLossError.kt @@ -1,3 +1,4 @@ package dartzee.sync -class SyncDataLossError(val missingGameIds: Set): Exception("${missingGameIds.size} game(s) missing from resulting database after merge") \ No newline at end of file +class SyncDataLossError(val missingGameIds: Set) : + Exception("${missingGameIds.size} game(s) missing from resulting database after merge") diff --git a/src/main/kotlin/dartzee/sync/SyncManager.kt b/src/main/kotlin/dartzee/sync/SyncManager.kt index 353d18813..e3a40e3c7 100644 --- a/src/main/kotlin/dartzee/sync/SyncManager.kt +++ b/src/main/kotlin/dartzee/sync/SyncManager.kt @@ -31,30 +31,24 @@ import javax.swing.SwingUtilities val SYNC_DIR = "${System.getProperty("user.dir")}/Sync" -class SyncManager(private val dbStore: IRemoteDatabaseStore) -{ +class SyncManager(private val dbStore: IRemoteDatabaseStore) { fun databaseExists(remoteName: String) = dbStore.databaseExists(remoteName) fun doPush(remoteName: String) = runInOtherThread { doPushOnOtherThread(remoteName) } - private fun doPushOnOtherThread(remoteName: String) - { + + private fun doPushOnOtherThread(remoteName: String) { var auditEntry: SyncAuditEntity? = null - try - { + try { SwingUtilities.invokeLater { DialogUtil.showLoadingDialogOLD("Pushing $remoteName...") } setUpSyncDir() auditEntry = SyncAuditEntity.insertSyncAudit(mainDatabase, remoteName) dbStore.pushDatabase(remoteName, mainDatabase) - } - catch (e: Exception) - { + } catch (e: Exception) { auditEntry?.deleteFromDatabase() handleSyncError(e, CODE_PUSH_ERROR) - } - finally - { + } finally { tidyUpAllSyncDirs() SwingUtilities.invokeLater { DialogUtil.dismissLoadingDialogOLD() } ScreenCache.get().initialise() @@ -62,72 +56,56 @@ class SyncManager(private val dbStore: IRemoteDatabaseStore) } fun doPull(remoteName: String) = runInOtherThread { doPullOnOtherThread(remoteName) } - private fun doPullOnOtherThread(remoteName: String) - { - try - { + + private fun doPullOnOtherThread(remoteName: String) { + try { SwingUtilities.invokeLater { DialogUtil.showLoadingDialogOLD("Pulling $remoteName...") } setUpSyncDir() val remote = dbStore.fetchDatabase(remoteName).database - if (!validateForeignDatabase(remote)) - { + if (!validateForeignDatabase(remote)) { return } DartsDatabaseUtil.swapInDatabase(remote) - } - catch (e: Exception) - { + } catch (e: Exception) { handleSyncError(e, CODE_PULL_ERROR) - } - finally - { + } finally { tidyUpAllSyncDirs() SwingUtilities.invokeLater { DialogUtil.dismissLoadingDialogOLD() } ScreenCache.get().initialise() } } - fun doSyncIfNecessary(remoteName: String): Thread - { - if (needsSync()) - { + fun doSyncIfNecessary(remoteName: String): Thread { + if (needsSync()) { return doSync(remoteName) - } - else - { + } else { logger.info(CODE_REVERT_TO_PULL, "Reverting to a pull as there are no local changes.") return doPull(remoteName) } } fun doSync(remoteName: String) = runInOtherThread { doSyncOnOtherThread(remoteName) } - private fun doSyncOnOtherThread(remoteName: String) - { - try - { + + private fun doSyncOnOtherThread(remoteName: String) { + try { val result = performSyncSteps(remoteName) - if (result != null) - { - val summary = "\n\nGames pushed: ${result.gamesPushed}\nGames pulled: ${result.gamesPulled}" + if (result != null) { + val summary = + "\n\nGames pushed: ${result.gamesPushed}\nGames pulled: ${result.gamesPulled}" DialogUtil.showInfoOLD("Sync completed successfully!$summary") } - } - catch (e: Exception) - { + } catch (e: Exception) { handleSyncError(e, CODE_SYNC_ERROR) - } - finally - { + } finally { tidyUpAllSyncDirs() SyncProgressDialog.dispose() ScreenCache.get().initialise() } } - private fun performSyncSteps(remoteName: String): SyncResult? - { + private fun performSyncSteps(remoteName: String): SyncResult? { setUpSyncDir() SyncProgressDialog.syncStarted() @@ -136,8 +114,7 @@ class SyncManager(private val dbStore: IRemoteDatabaseStore) SyncProgressDialog.progressToStage(SyncStage.VALIDATE_REMOTE) - if (!validateForeignDatabase(fetchResult.database)) - { + if (!validateForeignDatabase(fetchResult.database)) { return null } @@ -159,8 +136,7 @@ class SyncManager(private val dbStore: IRemoteDatabaseStore) val success = DartsDatabaseUtil.swapInDatabase(resultingDatabase) SyncProgressDialog.dispose() - if (!success) - { + if (!success) { return null } @@ -168,41 +144,52 @@ class SyncManager(private val dbStore: IRemoteDatabaseStore) return SyncResult(localGamesToPush, gamesPulled) } - private fun validateForeignDatabase(db: Database): Boolean - { - val validator = ForeignDatabaseValidator(DatabaseMigrator(DatabaseMigrations.getConversionsMap())) + private fun validateForeignDatabase(db: Database): Boolean { + val validator = + ForeignDatabaseValidator(DatabaseMigrator(DatabaseMigrations.getConversionsMap())) return validator.validateAndMigrateForeignDatabase(db, "remote") } - private fun getGameIds(database: Database) = GameEntity(database).retrieveModifiedSince(null).map { it.rowId }.toSet() + private fun getGameIds(database: Database) = + GameEntity(database).retrieveModifiedSince(null).map { it.rowId }.toSet() private fun getDeletedGameIds(database: Database) = - DeletionAuditEntity(database).retrieveEntities("EntityName = 'Game'").map { it.entityId }.toSet() - - private fun checkAllGamesStillExist(startingGameIds: Set, resultingGameIds: Set, deletedGameIds: Set) - { + DeletionAuditEntity(database) + .retrieveEntities("EntityName = 'Game'") + .map { it.entityId } + .toSet() + + private fun checkAllGamesStillExist( + startingGameIds: Set, + resultingGameIds: Set, + deletedGameIds: Set + ) { val missingGames = startingGameIds - resultingGameIds - deletedGameIds - if (missingGames.isNotEmpty()) - { + if (missingGames.isNotEmpty()) { throw SyncDataLossError(missingGames) } } - private fun handleSyncError(e: Exception, code: LoggingCode) - { - when (e) - { - is SocketException, is InterruptedIOException -> { + private fun handleSyncError(e: Exception, code: LoggingCode) { + when (e) { + is SocketException, + is InterruptedIOException -> { logger.warn(code, "Caught network error during sync: $e") - DialogUtil.showErrorOLD("A connection error occurred. Check your internet connection and try again.") + DialogUtil.showErrorOLD( + "A connection error occurred. Check your internet connection and try again." + ) } is ConcurrentModificationException -> { logger.warn(code, "$e") - DialogUtil.showErrorOLD("Another sync has been performed since this one started. \n\nResults have been discarded.") + DialogUtil.showErrorOLD( + "Another sync has been performed since this one started. \n\nResults have been discarded." + ) } is SyncDataLossError -> { logger.error(code, "$e", e, KEY_GAME_IDS to e.missingGameIds) - DialogUtil.showErrorOLD("Sync resulted in missing data. \n\nResults have been discarded.") + DialogUtil.showErrorOLD( + "Sync resulted in missing data. \n\nResults have been discarded." + ) } is WrappedSqlException -> { logger.logSqlException(e.sqlStatement, e.genericStatement, e.sqlException) @@ -215,15 +202,13 @@ class SyncManager(private val dbStore: IRemoteDatabaseStore) } } - private fun setUpSyncDir() - { + private fun setUpSyncDir() { tidyUpAllSyncDirs() File(SYNC_DIR).mkdirs() } - private fun tidyUpAllSyncDirs() - { + private fun tidyUpAllSyncDirs() { File(SYNC_DIR).deleteRecursively() File("$databaseDirectory/${DartsDatabaseUtil.OTHER_DATABASE_NAME}").deleteRecursively() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/sync/SyncStage.kt b/src/main/kotlin/dartzee/sync/SyncStage.kt index 04f054e90..5da0dd1f4 100644 --- a/src/main/kotlin/dartzee/sync/SyncStage.kt +++ b/src/main/kotlin/dartzee/sync/SyncStage.kt @@ -1,7 +1,6 @@ package dartzee.sync -enum class SyncStage -{ +enum class SyncStage { PULL_REMOTE, VALIDATE_REMOTE, MERGE_LOCAL_CHANGES, @@ -12,8 +11,7 @@ enum class SyncStage } fun SyncStage.desc() = - when (this) - { + when (this) { SyncStage.PULL_REMOTE -> "Download data" SyncStage.VALIDATE_REMOTE -> "Validate database" SyncStage.MERGE_LOCAL_CHANGES -> "Merge changes" @@ -21,4 +19,4 @@ fun SyncStage.desc() = SyncStage.PUSH_TO_REMOTE -> "Upload new version" SyncStage.PUSH_BACKUP_TO_REMOTE -> "Upload backup" SyncStage.OVERWRITE_LOCAL -> "Finalise" - } \ No newline at end of file + } diff --git a/src/main/kotlin/dartzee/sync/SyncUtils.kt b/src/main/kotlin/dartzee/sync/SyncUtils.kt index bbe95725e..ff063d2a3 100644 --- a/src/main/kotlin/dartzee/sync/SyncUtils.kt +++ b/src/main/kotlin/dartzee/sync/SyncUtils.kt @@ -13,8 +13,7 @@ import java.sql.Timestamp const val SYNC_BUCKET_NAME = "dartzee-databases" -enum class SyncMode -{ +enum class SyncMode { CREATE_REMOTE, OVERWRITE_LOCAL, NORMAL_SYNC @@ -26,23 +25,19 @@ data class LastSyncData(val remoteName: String, val lastSynced: Timestamp) data class SyncResult(val gamesPushed: Int, val gamesPulled: Int) -fun getModifiedGameCount(): Int -{ +fun getModifiedGameCount(): Int { val lastSynced = SyncAuditEntity.getLastSyncData(mainDatabase)?.lastSynced return GameEntity().countModifiedSince(lastSynced) } -fun resetRemote() -{ +fun resetRemote() { SyncAuditEntity().deleteAll() ScreenCache.get().initialise() } -fun validateSyncAction(): Boolean -{ +fun validateSyncAction(): Boolean { val openScreens = ScreenCache.getDartsGameScreens() - if (openScreens.isNotEmpty()) - { + if (openScreens.isNotEmpty()) { DialogUtil.showErrorOLD("You must close all open games before performing this action.") return false } @@ -50,9 +45,11 @@ fun validateSyncAction(): Boolean return true } -fun needsSync(): Boolean -{ - val entitiesToCheck = DartsDatabaseUtil.getSyncEntities(mainDatabase) + AchievementEntity(mainDatabase) + DeletionAuditEntity(mainDatabase) +fun needsSync(): Boolean { + val entitiesToCheck = + DartsDatabaseUtil.getSyncEntities(mainDatabase) + + AchievementEntity(mainDatabase) + + DeletionAuditEntity(mainDatabase) val lastLocalSync = SyncAuditEntity.getLastSyncData(mainDatabase)?.lastSynced return entitiesToCheck.flatMap { it.retrieveModifiedSince(lastLocalSync) }.isNotEmpty() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/types/StringMicrotype.kt b/src/main/kotlin/dartzee/types/StringMicrotype.kt index 57f2e15fe..4d6d90332 100644 --- a/src/main/kotlin/dartzee/types/StringMicrotype.kt +++ b/src/main/kotlin/dartzee/types/StringMicrotype.kt @@ -2,10 +2,9 @@ package dartzee.types open class StringMicrotype(val value: String) { override fun equals(other: Any?) = - other is StringMicrotype - && this.javaClass == other.javaClass - && this.value == other.value + other is StringMicrotype && this.javaClass == other.javaClass && this.value == other.value override fun hashCode(): Int = value.hashCode() + override fun toString(): String = value -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/ApplicationConstants.kt b/src/main/kotlin/dartzee/utils/ApplicationConstants.kt index 461f01986..91b163880 100644 --- a/src/main/kotlin/dartzee/utils/ApplicationConstants.kt +++ b/src/main/kotlin/dartzee/utils/ApplicationConstants.kt @@ -2,4 +2,4 @@ package dartzee.utils const val DARTS_VERSION_NUMBER = "v7.0.1" const val DARTZEE_REPOSITORY_URL = "https://api.github.com/repos/alyssaruth/Dartzee" -const val DARTZEE_MANUAL_DOWNLOAD_URL = "https://github.com/alyssaruth/Dartzee/releases" \ No newline at end of file +const val DARTZEE_MANUAL_DOWNLOAD_URL = "https://github.com/alyssaruth/Dartzee/releases" diff --git a/src/main/kotlin/dartzee/utils/AwsUtils.kt b/src/main/kotlin/dartzee/utils/AwsUtils.kt index 16192a794..d775f7c41 100644 --- a/src/main/kotlin/dartzee/utils/AwsUtils.kt +++ b/src/main/kotlin/dartzee/utils/AwsUtils.kt @@ -8,36 +8,32 @@ import com.amazonaws.services.s3.AmazonS3ClientBuilder import java.nio.charset.Charset import java.util.* -object AwsUtils -{ +object AwsUtils { fun readCredentials(resourceName: String) = - try - { + try { val awsCredentials = getAwsCredentialsStr(resourceName) - val decoded = Base64.getDecoder().decode(awsCredentials).toString(Charset.forName("UTF-8")) + val decoded = + Base64.getDecoder().decode(awsCredentials).toString(Charset.forName("UTF-8")) val lines = decoded.lines() BasicAWSCredentials(lines[0], lines[1]) - } - catch (t: Throwable) - { + } catch (t: Throwable) { println("Failed to read in AWS credentials: $t") null } - private fun getAwsCredentialsStr(resourceName: String): String - { + private fun getAwsCredentialsStr(resourceName: String): String { val rsrc = javaClass.getResource("/$resourceName") return rsrc?.readText() ?: System.getenv(resourceName) } - fun makeS3Client(): AmazonS3 - { + fun makeS3Client(): AmazonS3 { val credentials = readCredentials("AWS_SYNC") - val credProvider = if (credentials != null) AWSStaticCredentialsProvider(credentials) else EnvironmentVariableCredentialsProvider() - return AmazonS3ClientBuilder - .standard() - .withRegion("eu-west-2") - .withCredentials(credProvider) - .build() + val credProvider = + if (credentials != null) AWSStaticCredentialsProvider(credentials) + else EnvironmentVariableCredentialsProvider() + return AmazonS3ClientBuilder.standard() + .withRegion("eu-west-2") + .withCredentials(credProvider) + .build() } } diff --git a/src/main/kotlin/dartzee/utils/DartboardUtil.kt b/src/main/kotlin/dartzee/utils/DartboardUtil.kt index af3caa403..6053a2403 100644 --- a/src/main/kotlin/dartzee/utils/DartboardUtil.kt +++ b/src/main/kotlin/dartzee/utils/DartboardUtil.kt @@ -11,10 +11,9 @@ import java.awt.Font import java.awt.FontMetrics import java.awt.Point -/** - * Utilities for the Dartboard object. - */ -private val numberOrder = listOf(20, 1, 18, 4, 13, 6, 10, 15, 2, 17, 3, 19, 7, 16, 8, 11, 14, 9, 12, 5, 20) +/** Utilities for the Dartboard object. */ +private val numberOrder = + listOf(20, 1, 18, 4, 13, 6, 10, 15, 2, 17, 3, 19, 7, 16, 8, 11, 14, 9, 12, 5, 20) val hmScoreToOrdinal = initialiseOrdinalHashMap() private var colourWrapperFromPrefs: ColourWrapper? = null @@ -28,25 +27,22 @@ private const val LOWER_BOUND_DOUBLE_RATIO = 0.953 const val UPPER_BOUND_DOUBLE_RATIO = 1.0 const val UPPER_BOUND_OUTSIDE_BOARD_RATIO = 1.3 -fun getDartForSegment(segment: DartboardSegment): Dart -{ +fun getDartForSegment(segment: DartboardSegment): Dart { val score = segment.score val multiplier = segment.getMultiplier() return Dart(score, multiplier, segment.type) } -fun getNumbersWithinN(number: Int, n: Int): List -{ +fun getNumbersWithinN(number: Int, n: Int): List { val ix = numberOrder.indexOf(number) - val range = ((ix-n)..(ix+n)) + val range = ((ix - n)..(ix + n)) - return range.map { numberOrder[(it+20) % 20] } + return range.map { numberOrder[(it + 20) % 20] } } fun getAdjacentNumbers(number: Int) = getNumbersWithinN(number, 1).filterNot { it == number } -fun computePointsForSegment(segment: DartboardSegment, centre: Point, radius: Double): Set -{ +fun computePointsForSegment(segment: DartboardSegment, centre: Point, radius: Double): Set { if (segment.isMiss()) { return emptySet() } @@ -59,7 +55,14 @@ fun computePointsForSegment(segment: DartboardSegment, centre: Point, radius: Do val (startAngle, endAngle) = getAnglesForScore(score) val radii = getRadiiForSegmentType(segment.type, radius) val angleStep = getAngleStepForSegmentType(segment.type) - generateSegment(segment, centre, radius, startAngle.toDouble() - 0.1 to endAngle.toDouble() + 0.1, angleStep, radii) + generateSegment( + segment, + centre, + radius, + startAngle.toDouble() - 0.1 to endAngle.toDouble() + 0.1, + angleStep, + radii + ) } } @@ -70,19 +73,26 @@ private fun getAngleStepForSegmentType(segmentType: SegmentType) = else -> 0.1 } -private fun generateSegment(segment: DartboardSegment, centre: Point, radius: Double, angleRange: Pair, angleStep: Double, radiusRange: Pair): Set { - val allPts = angleRange.mapStepped(angleStep) { angle -> - radiusRange.mapStepped(0.8) { r -> - translatePoint(centre, r, angle) - } - }.flatten().toSet() +private fun generateSegment( + segment: DartboardSegment, + centre: Point, + radius: Double, + angleRange: Pair, + angleStep: Double, + radiusRange: Pair +): Set { + val allPts = + angleRange + .mapStepped(angleStep) { angle -> + radiusRange.mapStepped(0.8) { r -> translatePoint(centre, r, angle) } + } + .flatten() + .toSet() return allPts.filter { factorySegmentForPoint(it, centre, radius) == segment }.toSet() } - -fun computeEdgePoints(segmentPoints: Collection): Set -{ +fun computeEdgePoints(segmentPoints: Collection): Set { val ptsByX = segmentPoints.groupBy { it.x } val ptsByY = segmentPoints.groupBy { it.y } @@ -113,6 +123,7 @@ fun getRadiiForSegmentType(segmentType: SegmentType, radius: Double): Pair { return when (segmentType) { SegmentType.INNER_SINGLE -> Pair(RATIO_OUTER_BULL, LOWER_BOUND_TRIPLE_RATIO) @@ -123,21 +134,17 @@ private fun getRatioBounds(segmentType: SegmentType): Pair { } } -fun factorySegmentForPoint(dartPt: Point, centerPt: Point, radius: Double): DartboardSegment -{ +fun factorySegmentForPoint(dartPt: Point, centerPt: Point, radius: Double): DartboardSegment { val distance = dartPt.distance(centerPt) val ratio = distance / radius - if (ratio < RATIO_INNER_BULL) - { + if (ratio < RATIO_INNER_BULL) { return DartboardSegment(SegmentType.DOUBLE, 25) - } - else if (ratio < RATIO_OUTER_BULL) - { + } else if (ratio < RATIO_OUTER_BULL) { return DartboardSegment(SegmentType.OUTER_SINGLE, 25) } - //We've not hit the bullseye, so do other calculations to work out score/multiplier + // We've not hit the bullseye, so do other calculations to work out score/multiplier val angle = getAngleForPoint(dartPt, centerPt) val score = getScoreForAngle(angle) val type = calculateTypeForRatioNonBullseye(ratio) @@ -150,8 +157,7 @@ fun factorySegmentForPoint(dartPt: Point, centerPt: Point, radius: Double): Dart * 2) Using the radius, work out whether this makes us a miss, single, double or treble */ private fun calculateTypeForRatioNonBullseye(ratioToRadius: Double) = - when - { + when { ratioToRadius < LOWER_BOUND_TRIPLE_RATIO -> SegmentType.INNER_SINGLE ratioToRadius < UPPER_BOUND_TRIPLE_RATIO -> SegmentType.TREBLE ratioToRadius < LOWER_BOUND_DOUBLE_RATIO -> SegmentType.OUTER_SINGLE @@ -159,12 +165,10 @@ private fun calculateTypeForRatioNonBullseye(ratioToRadius: Double) = else -> SegmentType.MISS } -private fun getScoreForAngle(angle: Double): Int -{ +private fun getScoreForAngle(angle: Double): Int { var checkValue = 9 var index = 0 - while (angle > checkValue) - { + while (angle > checkValue) { index++ checkValue += 18 } @@ -172,29 +176,48 @@ private fun getScoreForAngle(angle: Double): Int return numberOrder[index] } -data class AimPoint(val centerPoint: Point, val radius: Double, val angle: Int, val ratio: Double) -{ +data class AimPoint(val centerPoint: Point, val radius: Double, val angle: Int, val ratio: Double) { val point = translatePoint(centerPoint, radius * ratio, angle.toDouble()) } -fun getPotentialAimPoints(centerPt: Point, radius: Double): Set -{ + +fun getPotentialAimPoints(centerPt: Point, radius: Double): Set { val points = mutableSetOf() - for (angle in 0 until 360 step 9) - { - points.add(AimPoint(centerPt, radius, angle, (RATIO_OUTER_BULL + LOWER_BOUND_TRIPLE_RATIO)/2)) - points.add(AimPoint(centerPt, radius, angle, (LOWER_BOUND_TRIPLE_RATIO + UPPER_BOUND_TRIPLE_RATIO)/2)) - points.add(AimPoint(centerPt, radius, angle, (UPPER_BOUND_TRIPLE_RATIO + LOWER_BOUND_DOUBLE_RATIO)/2)) - points.add(AimPoint(centerPt, radius, angle, (LOWER_BOUND_DOUBLE_RATIO + UPPER_BOUND_DOUBLE_RATIO)/2)) + for (angle in 0 until 360 step 9) { + points.add( + AimPoint(centerPt, radius, angle, (RATIO_OUTER_BULL + LOWER_BOUND_TRIPLE_RATIO) / 2) + ) + points.add( + AimPoint( + centerPt, + radius, + angle, + (LOWER_BOUND_TRIPLE_RATIO + UPPER_BOUND_TRIPLE_RATIO) / 2 + ) + ) + points.add( + AimPoint( + centerPt, + radius, + angle, + (UPPER_BOUND_TRIPLE_RATIO + LOWER_BOUND_DOUBLE_RATIO) / 2 + ) + ) + points.add( + AimPoint( + centerPt, + radius, + angle, + (LOWER_BOUND_DOUBLE_RATIO + UPPER_BOUND_DOUBLE_RATIO) / 2 + ) + ) } points.add(AimPoint(centerPt, radius, 0, 0.0)) return points.toSet() } -fun getColourWrapperFromPrefs(): ColourWrapper -{ - if (colourWrapperFromPrefs != null) - { +fun getColourWrapperFromPrefs(): ColourWrapper { + if (colourWrapperFromPrefs != null) { return colourWrapperFromPrefs!! } @@ -213,18 +236,25 @@ fun getColourWrapperFromPrefs(): ColourWrapper val oddDouble = DartsColour.getColorFromPrefStr(oddDoubleStr) val oddTreble = DartsColour.getColorFromPrefStr(oddTrebleStr) - colourWrapperFromPrefs = ColourWrapper(evenSingle, evenDouble, evenTreble, - oddSingle, oddDouble, oddTreble, evenDouble, oddDouble) + colourWrapperFromPrefs = + ColourWrapper( + evenSingle, + evenDouble, + evenTreble, + oddSingle, + oddDouble, + oddTreble, + evenDouble, + oddDouble + ) return colourWrapperFromPrefs!! } -private fun initialiseOrdinalHashMap() : MutableMap -{ +private fun initialiseOrdinalHashMap(): MutableMap { val ret = mutableMapOf() - for (i in 0 until numberOrder.size - 1) - { + for (i in 0 until numberOrder.size - 1) { val even = i and 1 == 0 ret[numberOrder[i]] = even } @@ -232,16 +262,13 @@ private fun initialiseOrdinalHashMap() : MutableMap return ret } -fun resetCachedDartboardValues() -{ +fun resetCachedDartboardValues() { colourWrapperFromPrefs = null } -fun getAllPossibleSegments(): List -{ +fun getAllPossibleSegments(): List { val segments = mutableListOf() - for (i in 1..20) - { + for (i in 1..20) { segments.add(DartboardSegment(SegmentType.DOUBLE, i)) segments.add(DartboardSegment(SegmentType.TREBLE, i)) segments.add(DartboardSegment(SegmentType.OUTER_SINGLE, i)) @@ -257,27 +284,25 @@ fun getAllPossibleSegments(): List fun getAllNonMissSegments() = getAllPossibleSegments().filterNot { it.isMiss() } -fun getFontForDartboardLabels(lblHeight: Int): Font -{ - //Start with a fontSize of 1 +fun getFontForDartboardLabels(lblHeight: Int): Font { + // Start with a fontSize of 1 var fontSize = 1f var font = ResourceCache.BASE_FONT.deriveFont(Font.PLAIN, fontSize) - //We're going to increment our test font 1 at a time, and keep checking its height + // We're going to increment our test font 1 at a time, and keep checking its height var testFont = font var metrics = factoryFontMetrics(testFont) var fontHeight = metrics.height - while (fontHeight < lblHeight - 2) - { - //The last iteration succeeded, so set our return value to be the font we tested. + while (fontHeight < lblHeight - 2) { + // The last iteration succeeded, so set our return value to be the font we tested. font = testFont - //Create a new testFont, with incremented font size + // Create a new testFont, with incremented font size fontSize++ testFont = ResourceCache.BASE_FONT.deriveFont(Font.PLAIN, fontSize) - //Get the updated font height + // Get the updated font height metrics = factoryFontMetrics(testFont) fontHeight = metrics.height } @@ -288,11 +313,8 @@ fun getFontForDartboardLabels(lblHeight: Int): Font fun factoryFontMetrics(font: Font): FontMetrics = Canvas().getFontMetrics(font) fun getHighlightedColour(colour: Color): Color = - if (colour == DartsColour.DARTBOARD_BLACK) - { + if (colour == DartsColour.DARTBOARD_BLACK) { Color.DARK_GRAY - } - else - { + } else { DartsColour.getDarkenedColour(colour) - } \ No newline at end of file + } diff --git a/src/main/kotlin/dartzee/utils/DartsColour.kt b/src/main/kotlin/dartzee/utils/DartsColour.kt index 02211acf8..7bacc0ee3 100644 --- a/src/main/kotlin/dartzee/utils/DartsColour.kt +++ b/src/main/kotlin/dartzee/utils/DartsColour.kt @@ -6,9 +6,7 @@ import java.awt.Color import java.awt.Component import java.lang.Float.max - -object DartsColour -{ +object DartsColour { val TRANSPARENT = Color(0, 0, 0, 0) val DARTBOARD_RED: Color = Color.red @@ -33,8 +31,9 @@ object DartsColour val COLOUR_ACHIEVEMENT_ORANGE: Color = Color.getHSBColor(0.1f, 1f, 1f) - val COLOUR_PASTEL_BLUE: Color = Color.getHSBColor(242.toFloat() / 360, 0.48.toFloat(), 0.8.toFloat()) - val PURPLE = Color(138,43,226) + val COLOUR_PASTEL_BLUE: Color = + Color.getHSBColor(242.toFloat() / 360, 0.48.toFloat(), 0.8.toFloat()) + val PURPLE = Color(138, 43, 226) val ORANGE = Color(255, 140, 0) val FIRST_COLOURS = Pair(Color.YELLOW, COLOUR_GOLD_TEXT) @@ -44,8 +43,7 @@ object DartsColour fun getDarkenedColour(colour: Color): Color = colour.darker().darker() - fun getBrightenedColour(colour: Color): Color - { + fun getBrightenedColour(colour: Color): Color { var hsbValues = FloatArray(3) hsbValues = Color.RGBtoHSB(colour.red, colour.green, colour.blue, hsbValues) @@ -63,22 +61,16 @@ object DartsColour } fun getColorFromPrefStr(prefStr: String): Color = - try - { - val colours = prefStr.split(";").map{ it.toInt() } + try { + val colours = prefStr.split(";").map { it.toInt() } Color(colours[0], colours[1], colours[2], colours[3]) - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_PARSE_ERROR, "Failed to reconstruct colour from string: $prefStr", t) Color.BLACK } - - fun setFgAndBgColoursForPosition(c: Component, finishPos: Int, defaultBg: Color? = null) - { - when (finishPos) - { + fun setFgAndBgColoursForPosition(c: Component, finishPos: Int, defaultBg: Color? = null) { + when (finishPos) { -1 -> setColors(c, defaultBg, null) 1 -> setColors(c, Color.YELLOW, COLOUR_GOLD_TEXT) 2 -> setColors(c, Color.GRAY, COLOUR_SILVER_TEXT) @@ -88,22 +80,19 @@ object DartsColour c.repaint() } - private fun setColors(c: Component, background: Color?, foreground: Color?) - { + + private fun setColors(c: Component, background: Color?, foreground: Color?) { c.background = background c.foreground = foreground } - - fun getScorerForegroundColour(totalScore: Double): Color - { + fun getScorerForegroundColour(totalScore: Double): Color { val hueFactor = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_HUE_FACTOR) val fgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS) return getScorerColour(totalScore, hueFactor, fgBrightness) } - fun getScorerBackgroundColour(totalScore: Double): Color - { + fun getScorerBackgroundColour(totalScore: Double): Color { val hueFactor = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_HUE_FACTOR) val bgBrightness = PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS) return getScorerColour(totalScore, hueFactor, bgBrightness) @@ -112,13 +101,18 @@ object DartsColour fun getScorerColour(totalScore: Double, multiplier: Double, brightness: Double) = getProportionalColour(totalScore, 180, multiplier, brightness) - private fun getProportionalColour(value: Double, total: Int, multiplier: Double, brightness: Double): Color - { + private fun getProportionalColour( + value: Double, + total: Int, + multiplier: Double, + brightness: Double + ): Color { val hue = (value * multiplier).toFloat() / total return Color.getHSBColor(hue, 1f, brightness.toFloat()) } - fun getProportionalColourRedToGreen(value: Double, total: Int, brightness: Double) = getProportionalColour(value, total, 0.4, brightness) + fun getProportionalColourRedToGreen(value: Double, total: Int, brightness: Double) = + getProportionalColour(value, total, 0.4, brightness) } fun Color.translucent() = Color(this.red, this.green, this.blue, 120) diff --git a/src/main/kotlin/dartzee/utils/DartsDatabaseUtil.kt b/src/main/kotlin/dartzee/utils/DartsDatabaseUtil.kt index 41ebc8cab..3b6fc9bc4 100644 --- a/src/main/kotlin/dartzee/utils/DartsDatabaseUtil.kt +++ b/src/main/kotlin/dartzee/utils/DartsDatabaseUtil.kt @@ -32,20 +32,18 @@ import dartzee.screen.ScreenCache import dartzee.utils.InjectedThings.connectionPoolSize import dartzee.utils.InjectedThings.logger import dartzee.utils.InjectedThings.mainDatabase -import org.apache.derby.jdbc.EmbeddedDriver import java.io.File import java.sql.DriverManager import javax.swing.JOptionPane import kotlin.system.exitProcess +import org.apache.derby.jdbc.EmbeddedDriver -/** - * Database helpers specific to Dartzee, e.g. first time initialisation - */ -object DartsDatabaseUtil -{ +/** Database helpers specific to Dartzee, e.g. first time initialisation */ +object DartsDatabaseUtil { const val DATABASE_VERSION = 22 const val DATABASE_NAME = "Darts" - const val OTHER_DATABASE_NAME = "DartsOther" //Tmp name used for restore from backup and/or sync + const val OTHER_DATABASE_NAME = + "DartsOther" // Tmp name used for restore from backup and/or sync fun getSyncEntities(database: Database = mainDatabase): List> = getAllEntities(database).filter { it.includeInSync() } @@ -73,15 +71,14 @@ object DartsDatabaseUtil fun getAllEntitiesIncludingVersion(database: Database = mainDatabase) = getAllEntities(database) + VersionEntity(database) - fun initialiseDatabase(database: Database) - { + fun initialiseDatabase(database: Database) { initialiseDerby() DialogUtil.showLoadingDialogOLD("Checking database status...") database.doDuplicateInstanceCheck() - //Pool the db connections now. Initialise with 5 to begin with? + // Pool the db connections now. Initialise with 5 to begin with? database.initialiseConnectionPool(connectionPoolSize) val version = database.getDatabaseVersion() @@ -94,8 +91,7 @@ object DartsDatabaseUtil migrateDatabase(migrator, database) } - private fun initialiseDerby() - { + private fun initialiseDerby() { DriverManager.registerDriver(EmbeddedDriver()) val p = System.getProperties() @@ -104,130 +100,109 @@ object DartsDatabaseUtil p.setProperty("derby.language.logQueryPlan", "${DartsClient.devMode}") } - fun migrateDatabase(migrator: DatabaseMigrator, database: Database) - { + fun migrateDatabase(migrator: DatabaseMigrator, database: Database) { val result = migrator.migrateToLatest(database, "Your") - if (result == MigrationResult.TOO_OLD) - { + if (result == MigrationResult.TOO_OLD) { exitProcess(1) } logger.addToContext(KEY_DB_VERSION, DATABASE_VERSION) } - /** - * Backup / Restore - */ - fun backupCurrentDatabase() - { + /** Backup / Restore */ + fun backupCurrentDatabase() { logger.info(CODE_STARTING_BACKUP, "About to start DB backup") val file = DialogUtil.chooseDirectory(ScreenCache.mainScreen) ?: return val fullDestination = File("${file.absolutePath}/$DATABASE_NAME") val success = backupDatabaseToDestination(fullDestination) - if (!success) - { + if (!success) { DialogUtil.showErrorOLD("There was a problem creating the backup.") - } - else - { + } else { DialogUtil.showInfoOLD("Database successfully backed up to $fullDestination") } } + private fun backupDatabaseToDestination(fullDestination: File): Boolean = - try - { + try { val dbFolder = mainDatabase.getDirectory() dbFolder.copyRecursively(fullDestination) - } - catch (e: Exception) - { + } catch (e: Exception) { logger.error(CODE_BACKUP_ERROR, "Caught $e trying to backup database", e) false } - fun restoreDatabase() - { + fun restoreDatabase() { logger.info(CODE_STARTING_RESTORE, "About to start DB restore") - if (!checkAllGamesAreClosed()) - { + if (!checkAllGamesAreClosed()) { return } val directoryFrom = selectNewDatabase() ?: return val dbOther = Database(OTHER_DATABASE_NAME) - try - { + try { directoryFrom.copyRecursively(dbOther.getDirectory(), true) validateAndRestoreDatabase(dbOther) - } - catch (e: Exception) - { + } catch (e: Exception) { logger.error(CODE_RESTORE_ERROR, "Caught $e trying to restore database", e) DialogUtil.showErrorOLD("There was a problem restoring the database.") - } - finally - { + } finally { dbOther.shutDown() dbOther.getDirectory().deleteRecursively() } } - private fun selectNewDatabase(): File? - { + + private fun selectNewDatabase(): File? { DialogUtil.showInfoOLD("Select the '$DATABASE_NAME' folder you want to restore from.") val directoryFrom = DialogUtil.chooseDirectory(ScreenCache.mainScreen) ?: return null - //Check it's named right + // Check it's named right val name = directoryFrom.name - if (name != DATABASE_NAME) - { - DialogUtil.showErrorOLD("Selected path is not valid - you must select a folder named '$DATABASE_NAME'") + if (name != DATABASE_NAME) { + DialogUtil.showErrorOLD( + "Selected path is not valid - you must select a folder named '$DATABASE_NAME'" + ) return null } return directoryFrom } - fun validateAndRestoreDatabase(dbOther: Database) - { - val validator = ForeignDatabaseValidator(DatabaseMigrator(DatabaseMigrations.getConversionsMap())) - if (!validator.validateAndMigrateForeignDatabase(dbOther, "selected")) - { + + fun validateAndRestoreDatabase(dbOther: Database) { + val validator = + ForeignDatabaseValidator(DatabaseMigrator(DatabaseMigrations.getConversionsMap())) + if (!validator.validateAndMigrateForeignDatabase(dbOther, "selected")) { return } - //Confirm at this point - val confirmationQ = "Successfully connected to target database.\n\nAre you sure you want to restore this database? All current data will be lost." + // Confirm at this point + val confirmationQ = + "Successfully connected to target database.\n\nAre you sure you want to restore this database? All current data will be lost." val option = DialogUtil.showQuestionOLD(confirmationQ, false) - if (option == JOptionPane.NO_OPTION) - { + if (option == JOptionPane.NO_OPTION) { return } - if (swapInDatabase(dbOther)) - { + if (swapInDatabase(dbOther)) { DialogUtil.showInfoOLD("Database restored successfully.") } } - fun swapInDatabase(otherDatabase: Database): Boolean - { - //Now switch it in - try - { + fun swapInDatabase(otherDatabase: Database): Boolean { + // Now switch it in + try { mainDatabase.shutDown() otherDatabase.shutDown() - val error = FileUtil.swapInFile(mainDatabase.getDirectoryStr(), otherDatabase.getDirectoryStr()) - if (error != null) - { + val error = + FileUtil.swapInFile(mainDatabase.getDirectoryStr(), otherDatabase.getDirectoryStr()) + if (error != null) { DialogUtil.showErrorOLD("Failed to restore database. Error: $error") return false } - } - finally - { + } finally { mainDatabase.initialiseConnectionPool(connectionPoolSize) mainDatabase.localIdGenerator.clearCache() } @@ -235,11 +210,9 @@ object DartsDatabaseUtil return true } - private fun checkAllGamesAreClosed(): Boolean - { + private fun checkAllGamesAreClosed(): Boolean { val openScreens = ScreenCache.getDartsGameScreens() - if (openScreens.isNotEmpty()) - { + if (openScreens.isNotEmpty()) { DialogUtil.showErrorOLD("You must close all open games before continuing.") return false } diff --git a/src/main/kotlin/dartzee/utils/DartzeeRuleConversion.kt b/src/main/kotlin/dartzee/utils/DartzeeRuleConversion.kt index 400271678..89379723d 100644 --- a/src/main/kotlin/dartzee/utils/DartzeeRuleConversion.kt +++ b/src/main/kotlin/dartzee/utils/DartzeeRuleConversion.kt @@ -3,20 +3,16 @@ package dartzee.utils import dartzee.core.screen.ProgressDialog import dartzee.db.DartzeeRuleEntity -object DartzeeRuleConversion -{ - fun convertDartzeeRules() - { +object DartzeeRuleConversion { + fun convertDartzeeRules() { val allRules = DartzeeRuleEntity().retrieveEntities() val r = Runnable { - val dlg = ProgressDialog.factory("Converting Dartzee Rules", - "rules", allRules.size) + val dlg = ProgressDialog.factory("Converting Dartzee Rules", "rules", allRules.size) dlg.setVisibleLater() - try - { + try { allRules.forEach { rule -> val dto = rule.toDto(false) val newResult = dto.runStrengthCalculation() @@ -25,9 +21,7 @@ object DartzeeRuleConversion dlg.incrementProgressLater() } - } - finally - { + } finally { dlg.disposeLater() } } @@ -36,4 +30,4 @@ object DartzeeRuleConversion t.start() t.join() } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/DartzeeUtils.kt b/src/main/kotlin/dartzee/utils/DartzeeUtils.kt index 7761313b8..47008ad8a 100644 --- a/src/main/kotlin/dartzee/utils/DartzeeUtils.kt +++ b/src/main/kotlin/dartzee/utils/DartzeeUtils.kt @@ -16,24 +16,24 @@ import java.awt.Color import java.awt.Component import javax.swing.JOptionPane -fun Component.setColoursForDartzeeResult(success: Boolean) -{ - if (success) - { +fun Component.setColoursForDartzeeResult(success: Boolean) { + if (success) { background = Color.GREEN foreground = DartsColour.getProportionalColourRedToGreen(1.0, 1, 0.5) - } - else - { + } else { background = Color.RED foreground = DartsColour.getProportionalColourRedToGreen(0.0, 1, 0.5) } } -fun factoryHighScoreResult(darts: List) = DartzeeRoundResult(-1, success = true, score = sumScore(darts)) +fun factoryHighScoreResult(darts: List) = + DartzeeRoundResult(-1, success = true, score = sumScore(darts)) -fun insertDartzeeRules(gameId: String, dartzeeDtos: List? = null, database: Database = mainDatabase) -{ +fun insertDartzeeRules( + gameId: String, + dartzeeDtos: List? = null, + database: Database = mainDatabase +) { dartzeeDtos ?: return dartzeeDtos.forEachIndexed { ix, dto -> @@ -42,14 +42,12 @@ fun insertDartzeeRules(gameId: String, dartzeeDtos: List? = null } } -fun getAllSegmentsForDartzee(): List -{ +fun getAllSegmentsForDartzee(): List { val segments = getAllNonMissSegments() return segments + DartboardSegment(SegmentType.MISS, 20) } -fun saveDartzeeTemplate(name: String, dtos: List): DartzeeTemplateEntity -{ +fun saveDartzeeTemplate(name: String, dtos: List): DartzeeTemplateEntity { val template = DartzeeTemplateEntity.factoryAndSave(name) dtos.forEachIndexed { ix, rule -> val entity = rule.toEntity(ix + 1, EntityName.DartzeeTemplate, template.rowId) @@ -59,10 +57,13 @@ fun saveDartzeeTemplate(name: String, dtos: List): DartzeeTempla return template } -fun generateDartzeeTemplateFromGame(game: GameEntity, dtos: List): DartzeeTemplateEntity? -{ - val templateName = DialogUtil.showInput("Template Name", "Please enter a name for the template") - ?: return null +fun generateDartzeeTemplateFromGame( + game: GameEntity, + dtos: List +): DartzeeTemplateEntity? { + val templateName = + DialogUtil.showInput("Template Name", "Please enter a name for the template") + ?: return null val template = saveDartzeeTemplate(templateName, dtos) game.gameParams = template.rowId @@ -73,25 +74,25 @@ fun generateDartzeeTemplateFromGame(game: GameEntity, dtos: List return template } -fun deleteDartzeeTemplate(template: DartzeeTemplateEntity, gameCount: Int): Boolean -{ - val message = when (gameCount) - { - 0 -> "Are you sure you want to delete the ${template.name} Template?" - else -> "You have played $gameCount games using the ${template.name} Template." + - "\n\nThese will become custom games if you delete it. Are you sure you want to continue?" - } +fun deleteDartzeeTemplate(template: DartzeeTemplateEntity, gameCount: Int): Boolean { + val message = + when (gameCount) { + 0 -> "Are you sure you want to delete the ${template.name} Template?" + else -> + "You have played $gameCount games using the ${template.name} Template." + + "\n\nThese will become custom games if you delete it. Are you sure you want to continue?" + } val ans = DialogUtil.showQuestionOLD(message) - if (ans != JOptionPane.YES_OPTION) - { + if (ans != JOptionPane.YES_OPTION) { return false } template.deleteFromDatabase() DartzeeRuleEntity().deleteForTemplate(template.rowId) - val gameSql = "UPDATE Game SET GameParams = '' WHERE GameType = '${GameType.DARTZEE}' AND GameParams = '${template.rowId}'" + val gameSql = + "UPDATE Game SET GameParams = '' WHERE GameType = '${GameType.DARTZEE}' AND GameParams = '${template.rowId}'" mainDatabase.executeUpdate(gameSql) return true -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/Database.kt b/src/main/kotlin/dartzee/utils/Database.kt index ac6ad708e..bedf24535 100644 --- a/src/main/kotlin/dartzee/utils/Database.kt +++ b/src/main/kotlin/dartzee/utils/Database.kt @@ -25,36 +25,30 @@ import kotlin.system.exitProcess const val TABLE_ALREADY_EXISTS = "X0Y32" val DATABASE_FILE_PATH: String = "${System.getProperty("user.dir")}/Databases" -/** - * Generic derby helper methods - */ -class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val inMemory: Boolean = false) -{ +/** Generic derby helper methods */ +class Database( + val dbName: String = DartsDatabaseUtil.DATABASE_NAME, + private val inMemory: Boolean = false +) { val localIdGenerator = LocalIdGenerator(this) private val hsConnections = mutableListOf() private val connectionPoolLock = Any() private var connectionCreateCount = 0 - fun initialiseConnectionPool(initialCount: Int) - { - synchronized(connectionPoolLock) - { + fun initialiseConnectionPool(initialCount: Int) { + synchronized(connectionPoolLock) { hsConnections.clear() - repeat(initialCount) - { + repeat(initialCount) { val conn = createDatabaseConnection() hsConnections.add(conn) } } } - fun borrowConnection() : Connection - { - synchronized(connectionPoolLock) - { - if (hsConnections.isEmpty()) - { + fun borrowConnection(): Connection { + synchronized(connectionPoolLock) { + if (hsConnections.isEmpty()) { return createDatabaseConnection() } @@ -62,36 +56,31 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val } } - fun returnConnection(connection: Connection) - { - synchronized(connectionPoolLock) - { - hsConnections.add(connection) - } + fun returnConnection(connection: Connection) { + synchronized(connectionPoolLock) { hsConnections.add(connection) } } - private fun createDatabaseConnection(): Connection - { + private fun createDatabaseConnection(): Connection { connectionCreateCount++ val connection = DriverManager.getConnection(getDbStringForNewConnection(), getProps()) - logger.info(CODE_NEW_CONNECTION, "Created new connection. Total created: $connectionCreateCount, pool size: ${hsConnections.size}") + logger.info( + CODE_NEW_CONNECTION, + "Created new connection. Total created: $connectionCreateCount, pool size: ${hsConnections.size}" + ) return connection } private fun getDbStringForNewConnection() = "${getQualifiedDbName()};create=true" + fun getQualifiedDbName() = - if (inMemory) - { + if (inMemory) { "jdbc:derby:memory:$databaseDirectory/$dbName" - } - else - { + } else { "jdbc:derby:$databaseDirectory/$dbName" } - private fun getProps(): Properties - { + private fun getProps(): Properties { val props = Properties() props["user"] = "administrator" props["password"] = "wallace" @@ -99,13 +88,12 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val } fun getDirectoryStr() = "$databaseDirectory/$dbName" + fun getDirectory() = File(getDirectoryStr()) - fun executeUpdates(statements: List): Boolean - { + fun executeUpdates(statements: List): Boolean { statements.forEach { statement -> - if (!executeUpdate(statement)) - { + if (!executeUpdate(statement)) { return false } } @@ -114,14 +102,11 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val } fun executeUpdate(sb: StringBuilder) = executeUpdate(sb.toString()) - fun executeUpdate(statement: String, log: Boolean = true): Boolean - { - try - { + + fun executeUpdate(statement: String, log: Boolean = true): Boolean { + try { executeUpdateUncaught(statement, log) - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { logger.logSqlException(statement, "", sqle) return false } @@ -129,109 +114,88 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val return true } - private fun executeUpdateUncaught(statement: String, log: Boolean = true) - { + private fun executeUpdateUncaught(statement: String, log: Boolean = true) { val timer = DurationTimer() val conn = borrowConnection() - val updateCount = try - { - conn.createStatement().use { - s -> s.execute(statement) - s.updateCount + val updateCount = + try { + conn.createStatement().use { s -> + s.execute(statement) + s.updateCount + } + } finally { + returnConnection(conn) } - } - finally - { - returnConnection(conn) - } - if (log) - { + if (log) { logger.logSql(statement, "", timer.getDuration(), updateCount, dbName) } } fun executeQuery(sb: StringBuilder) = executeQuery(sb.toString()) - fun executeQuery(query: String): ResultSet - { + fun executeQuery(query: String): ResultSet { val timer = DurationTimer() val conn = borrowConnection() - try - { + try { conn.createStatement().use { s -> - val resultSet: CachedRowSet = s.executeQuery(query).use { rs -> - val crs = RowSetProvider.newFactory().createCachedRowSet() - crs.populate(rs) - crs - } + val resultSet: CachedRowSet = + s.executeQuery(query).use { rs -> + val crs = RowSetProvider.newFactory().createCachedRowSet() + crs.populate(rs) + crs + } logger.logSql(query, "", timer.getDuration(), resultSet.size(), dbName) return resultSet } - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { throw WrappedSqlException(query, "", sqle) - } - finally - { + } finally { returnConnection(conn) } } fun executeQueryAggregate(sb: StringBuilder) = executeQueryAggregate(sb.toString()) - fun executeQueryAggregate(sql: String): Int - { + fun executeQueryAggregate(sql: String): Int { executeQuery(sql).use { rs -> return if (rs.next()) rs.getInt(1) else -1 } } - fun doDuplicateInstanceCheck() - { - try - { + fun doDuplicateInstanceCheck() { + try { createDatabaseConnection() - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { val next = sqle.nextException - if (next != null - && next.message!!.contains("Another instance of Derby may have already booted the database")) - { + if ( + next != null && + next.message!!.contains( + "Another instance of Derby may have already booted the database" + ) + ) { logger.warn(CODE_DATABASE_IN_USE, "Failed multiple instance check, exiting.") DialogUtil.showErrorOLD("Database already in use - Dartzee will now exit.") exitProcess(1) - } - else - { + } else { logger.logSqlException("", "", sqle) } } - } - fun createTableIfNotExists(tableName: String, columnSql: String): Boolean - { + fun createTableIfNotExists(tableName: String, columnSql: String): Boolean { val statement = "CREATE TABLE $tableName($columnSql)" - try - { + try { executeUpdateUncaught(statement) logger.info(CODE_TABLE_CREATED, "Created $tableName") - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { val state = sqle.sqlState - if (state == TABLE_ALREADY_EXISTS) - { + if (state == TABLE_ALREADY_EXISTS) { logger.info(CODE_TABLE_EXISTS, "$tableName already exists") - } - else - { + } else { logger.logSqlException(statement, "", sqle) } @@ -243,8 +207,7 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val fun getDatabaseVersion(): Int? = getVersionRow()?.version - fun updateDatabaseVersion(version: Int) - { + fun updateDatabaseVersion(version: Int) { val entity = getVersionRow() ?: VersionEntity(this).also { it.assignRowId() } entity.version = version entity.saveToDatabase() @@ -252,67 +215,57 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val fun generateLocalId(entityName: EntityName) = localIdGenerator.generateLocalId(entityName) - private fun getVersionRow(): VersionEntity? - { + private fun getVersionRow(): VersionEntity? { val versionEntity = VersionEntity(this) versionEntity.createTable() return versionEntity.retrieveEntity("1 = 1") } - fun createTempTable(tableName: String, colStr: String): String? - { + fun createTempTable(tableName: String, colStr: String): String? { val millis = System.currentTimeMillis() val fullTableName = "zzTmp_$tableName$millis" val success = createTableIfNotExists(fullTableName, colStr) - return if (success) - { + return if (success) { fullTableName - } - else null + } else null } fun dropTable(tableName: EntityName) = dropTable(tableName.name) - fun dropTable(tableName: String): Boolean - { + + fun dropTable(tableName: String): Boolean { val sql = "DROP TABLE $tableName" return executeUpdate(sql) } - fun testConnection(): Boolean - { - try - { + fun testConnection(): Boolean { + try { createDatabaseConnection() - } - catch (t: Throwable) - { - logger.error(CODE_TEST_CONNECTION_ERROR, "Failed to establish test connection for path ${getDirectory()}", t) + } catch (t: Throwable) { + logger.error( + CODE_TEST_CONNECTION_ERROR, + "Failed to establish test connection for path ${getDirectory()}", + t + ) return false } return true } - fun shutDown(): Boolean - { + fun shutDown(): Boolean { closeConnections() val command = "${getQualifiedDbName()};shutdown=true" - try - { + try { DriverManager.getConnection(command, getProps()) - } - catch (sqle: SQLException) - { + } catch (sqle: SQLException) { val msg = sqle.message ?: "" - if (msg.contains("shutdown")) - { + if (msg.contains("shutdown")) { return true } - if (!msg.contains("not found")) - { + if (!msg.contains("not found")) { logger.logSqlException(command, command, sqle) } } @@ -320,14 +273,12 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val return false } - private fun closeConnections() - { + private fun closeConnections() { hsConnections.forEach { it.close() } hsConnections.clear() } - fun deleteRowsFromTable(entityName: EntityName, rowIds: List): Boolean - { + fun deleteRowsFromTable(entityName: EntityName, rowIds: List): Boolean { var success = true rowIds.chunked(50).forEach { rowIdBatch -> val idStr = rowIdBatch.getQuotedIdStr() @@ -338,10 +289,9 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val return success } - fun dropUnexpectedTables(): List - { + fun dropUnexpectedTables(): List { val entities = DartsDatabaseUtil.getAllEntitiesIncludingVersion() - val tableNameSql = entities.getQuotedIdStr{ it.getTableNameUpperCase() } + val tableNameSql = entities.getQuotedIdStr { it.getTableNameUpperCase() } val sb = StringBuilder() sb.append(" SELECT TableName") @@ -350,14 +300,13 @@ class Database(val dbName: String = DartsDatabaseUtil.DATABASE_NAME, private val sb.append(" AND TableName NOT IN $tableNameSql") val list = mutableListOf() - executeQuery(sb).use{ rs -> - while (rs.next()) - { + executeQuery(sb).use { rs -> + while (rs.next()) { list.add(rs.getString("TableName")) } } - list.forEach{ dropTable(it) } + list.forEach { dropTable(it) } return list } } diff --git a/src/main/kotlin/dartzee/utils/DatabaseMigrations.kt b/src/main/kotlin/dartzee/utils/DatabaseMigrations.kt index eed659743..859114621 100644 --- a/src/main/kotlin/dartzee/utils/DatabaseMigrations.kt +++ b/src/main/kotlin/dartzee/utils/DatabaseMigrations.kt @@ -2,22 +2,20 @@ package dartzee.utils import dartzee.db.TeamEntity -object DatabaseMigrations -{ - fun getConversionsMap(): Map Any>> - { +object DatabaseMigrations { + fun getConversionsMap(): Map Any>> { return mapOf( - 19 to listOf ( - { db -> TeamEntity(db).createTable() }, - { db -> runScript(db, 20, "Participant.sql") } - ), + 19 to + listOf( + { db -> TeamEntity(db).createTable() }, + { db -> runScript(db, 20, "Participant.sql") } + ), 20 to listOf { db -> runScript(db, 21, "Dart.sql") }, 21 to listOf { db -> runScript(db, 22, "Dart.sql") } ) } - private fun runScript(database: Database, version: Int, scriptName: String): Boolean - { + private fun runScript(database: Database, version: Int, scriptName: String): Boolean { val resourcePath = "/sql/v$version/" val rsrc = javaClass.getResource("$resourcePath$scriptName").readText() diff --git a/src/main/kotlin/dartzee/utils/DevUtilities.kt b/src/main/kotlin/dartzee/utils/DevUtilities.kt index bee0dcfad..814e056ed 100644 --- a/src/main/kotlin/dartzee/utils/DevUtilities.kt +++ b/src/main/kotlin/dartzee/utils/DevUtilities.kt @@ -14,33 +14,29 @@ import dartzee.screen.ScreenCache import dartzee.utils.InjectedThings.mainDatabase import javax.swing.JOptionPane -object DevUtilities -{ - fun purgeGame() - { +object DevUtilities { + fun purgeGame() { val gameIds = getAllGameIds() - if (gameIds == null) - { + if (gameIds == null) { DialogUtil.showErrorOLD("No games to delete.") return } - val choice = DialogUtil.showInput("Delete Game", "Select Game ID", gameIds, gameIds[0]) ?: return + val choice = + DialogUtil.showInput("Delete Game", "Select Game ID", gameIds, gameIds[0]) ?: return purgeGame(choice) } - private fun getAllGameIds(): Array? - { + + private fun getAllGameIds(): Array? { val gameCount = mainDatabase.executeQueryAggregate("SELECT COUNT(1) FROM Game") - if (gameCount == 0) - { + if (gameCount == 0) { return null } val gameIds = mutableListOf() mainDatabase.executeQuery("SELECT LocalId FROM Game").use { rs -> - while (rs.next()) - { + while (rs.next()) { val rowId = rs.getLong("LocalId") gameIds.add(rowId) } @@ -49,32 +45,35 @@ object DevUtilities return gameIds.toTypedArray() } - fun purgeGame(localId: Long) - { + fun purgeGame(localId: Long) { val gameId = GameEntity.getGameId(localId) - if (gameId == null) - { + if (gameId == null) { DialogUtil.showError("No game exists for ID $localId") return } val scrn = ScreenCache.getDartsGameScreen(gameId) - if (scrn != null) - { + if (scrn != null) { DialogUtil.showError("Cannot delete a game that's open.") return } val participants = loadParticipants(gameId) - val participantEntities: List = participants.flatMap { it.individuals + it.participant }.distinct() - val participantIds = participantEntities.filterIsInstance().map { it.rowId } + val participantEntities: List = + participants.flatMap { it.individuals + it.participant }.distinct() + val participantIds = + participantEntities.filterIsInstance().map { it.rowId } val teamIds = participantEntities.filterIsInstance().map { it.rowId } val ptSql = participantIds.getQuotedIdStr() - val dartCount = if (participantIds.isEmpty()) 0 else DartEntity().countWhere("ParticipantId IN $ptSql") - val dartzeeRoundResultCount = if (participantIds.isEmpty()) 0 else DartzeeRoundResultEntity().countWhere("ParticipantId IN $ptSql") + val dartCount = + if (participantIds.isEmpty()) 0 else DartEntity().countWhere("ParticipantId IN $ptSql") + val dartzeeRoundResultCount = + if (participantIds.isEmpty()) 0 + else DartzeeRoundResultEntity().countWhere("ParticipantId IN $ptSql") val dartzeeRules = DartzeeRuleEntity().retrieveForGame(gameId) - val question = """ + val question = + """ Purge all data for Game #$localId? The following rows will be deleted: Participant: ${participantIds.size} rows @@ -82,13 +81,12 @@ object DevUtilities Dart: $dartCount rows DartzeeRoundResult: $dartzeeRoundResultCount rows DartzeeRule: ${dartzeeRules.size} rows - """.trimIndent() + """ + .trimIndent() val answer = DialogUtil.showQuestion(question, false) - if (answer == JOptionPane.YES_OPTION) - { - if (participantIds.isNotEmpty()) - { + if (answer == JOptionPane.YES_OPTION) { + if (participantIds.isNotEmpty()) { DartEntity().deleteWhere("ParticipantId IN $ptSql") DartzeeRoundResultEntity().deleteWhere("ParticipantId IN $ptSql") } diff --git a/src/main/kotlin/dartzee/utils/DurationTimer.kt b/src/main/kotlin/dartzee/utils/DurationTimer.kt index 7698ab52b..aeec28f8f 100644 --- a/src/main/kotlin/dartzee/utils/DurationTimer.kt +++ b/src/main/kotlin/dartzee/utils/DurationTimer.kt @@ -1,8 +1,7 @@ package dartzee.utils -class DurationTimer -{ +class DurationTimer { val start = System.currentTimeMillis() fun getDuration() = System.currentTimeMillis() - start -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/GameUtil.kt b/src/main/kotlin/dartzee/utils/GameUtil.kt index feb4f532c..096f3d53f 100644 --- a/src/main/kotlin/dartzee/utils/GameUtil.kt +++ b/src/main/kotlin/dartzee/utils/GameUtil.kt @@ -10,8 +10,7 @@ import dartzee.db.IParticipant import dartzee.game.GameType fun getFilterPanel(gameType: GameType) = - when (gameType) - { + when (gameType) { GameType.X01 -> GameParamFilterPanelX01() GameType.GOLF -> GameParamFilterPanelGolf() GameType.ROUND_THE_CLOCK -> GameParamFilterPanelRoundTheClock() @@ -19,27 +18,29 @@ fun getFilterPanel(gameType: GameType) = } fun doesHighestWin(gameType: GameType?) = - when (gameType) - { + when (gameType) { GameType.DARTZEE -> true - GameType.X01, GameType.GOLF, GameType.ROUND_THE_CLOCK, null -> false + GameType.X01, + GameType.GOLF, + GameType.ROUND_THE_CLOCK, + null -> false } -fun setFinishingPositions(participants: List, game: GameEntity) -{ - //If there's only one player, it's already set to -1 which is correct - if (participants.size == 1) - { +fun setFinishingPositions(participants: List, game: GameEntity) { + // If there's only one player, it's already set to -1 which is correct + if (participants.size == 1) { return } - val entries = participants.groupBy { it.finalScore } - .entries - .sortedBy(doesHighestWin(game.gameType)) { it.key } + val entries = + participants + .groupBy { it.finalScore } + .entries + .sortedBy(doesHighestWin(game.gameType)) { it.key } var finishPos = 1 entries.forEach { (_, participants) -> participants.forEach { it.saveFinishingPosition(game, finishPos) } finishPos += participants.size } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/GeometryUtil.kt b/src/main/kotlin/dartzee/utils/GeometryUtil.kt index 18a15e10b..728c7ce57 100644 --- a/src/main/kotlin/dartzee/utils/GeometryUtil.kt +++ b/src/main/kotlin/dartzee/utils/GeometryUtil.kt @@ -11,12 +11,13 @@ private val TOP_LEFT = Quadrant(270, 360, false, yIsPositive = false) private val QUADRANTS = arrayOf(TOP_RIGHT, BOTTOM_RIGHT, BOTTOM_LEFT, TOP_LEFT) -fun translatePoint(pt: Point, radius: Double, degrees: Double): Point -{ +fun translatePoint(pt: Point, radius: Double, degrees: Double): Point { val positiveAngle = degrees.mod(360.0) - val quadrant = getQuadrantForAngle(positiveAngle) ?: return translatePointAlongAxis(pt, radius, positiveAngle) + val quadrant = + getQuadrantForAngle(positiveAngle) + ?: return translatePointAlongAxis(pt, radius, positiveAngle) - //Need radians for trig functions + // Need radians for trig functions val theta = Math.toRadians(positiveAngle) val dSin = Math.abs(radius * Math.sin(theta)) val dCos = Math.abs(radius * Math.cos(theta)) @@ -24,13 +25,11 @@ fun translatePoint(pt: Point, radius: Double, degrees: Double): Point var x = dSin var y = dCos - if (!quadrant.xIsPositive) - { + if (!quadrant.xIsPositive) { x *= -1.0 } - if (!quadrant.yIsPositive) - { + if (!quadrant.yIsPositive) { y *= -1.0 } @@ -42,14 +41,12 @@ fun translatePoint(pt: Point, radius: Double, degrees: Double): Point return ret } -private fun translatePointAlongAxis(pt: Point, radius: Double, degrees: Double): Point -{ +private fun translatePointAlongAxis(pt: Point, radius: Double, degrees: Double): Point { val x = pt.getX() val y = pt.getY() val ret = Point() - when (degrees) - { + when (degrees) { 0.0 -> ret.setLocation(x, y - radius) 90.0 -> ret.setLocation(x + radius, y) 180.0 -> ret.setLocation(x, y + radius) @@ -60,28 +57,25 @@ private fun translatePointAlongAxis(pt: Point, radius: Double, degrees: Double): } fun getNeighbours(pt: Point) = - setOf(Point(pt.x, pt.y + 1), Point(pt.x, pt.y - 1), Point(pt.x + 1, pt.y), Point(pt.x - 1, pt.y)) - -/** - * Compute the clockwise angle for the point, relative to the center - */ -fun getAngleForPoint(dartPt: Point, centerPt: Point): Double -{ + setOf( + Point(pt.x, pt.y + 1), + Point(pt.x, pt.y - 1), + Point(pt.x + 1, pt.y), + Point(pt.x - 1, pt.y) + ) + +/** Compute the clockwise angle for the point, relative to the center */ +fun getAngleForPoint(dartPt: Point, centerPt: Point): Double { val xLength = dartPt.getX() - centerPt.getX() val yLength = dartPt.getY() - centerPt.getY() val hypotenuse = Math.sqrt(xLength * xLength + yLength * yLength) - return if (xLength == 0.0) - { + return if (xLength == 0.0) { (if (yLength > 0) 180 else 0).toDouble() - } - else if (yLength == 0.0) - { + } else if (yLength == 0.0) { (if (xLength > 0) 90 else 270).toDouble() - } - else - { - //We're not on an axis + } else { + // We're not on an axis val xIsPositive = xLength > 0 val yIsPositive = yLength > 0 @@ -98,7 +92,8 @@ fun getAngleForPoint(dartPt: Point, centerPt: Point): Double } /** - * For the given angle, return the Quadrant. Returns null if there is none (because we're on an axis). + * For the given angle, return the Quadrant. Returns null if there is none (because we're on an + * axis). */ private fun getQuadrantForAngle(angle: Double) = QUADRANTS.find { it.minimumAngle < angle && angle < it.maximumAngle } @@ -106,25 +101,21 @@ private fun getQuadrantForAngle(angle: Double) = private fun getQuadrant(xIsPositive: Boolean, yIsPositive: Boolean) = QUADRANTS.find { it.xIsPositive == xIsPositive && it.yIsPositive == yIsPositive } -/** - * For a group of points, calculate the average point - */ -fun getAverage(points: Set): Point -{ +/** For a group of points, calculate the average point */ +fun getAverage(points: Set): Point { if (points.isEmpty()) { throw Error("Can't get average of empty set") } - val xAvg = points.map{ it.x }.average() - val yAvg = points.map{ it.y }.average() + val xAvg = points.map { it.x }.average() + val yAvg = points.map { it.y }.average() val ret = Point() ret.setLocation(xAvg, yAvg) return ret } -fun generateRandomAngle(): Double -{ +fun generateRandomAngle(): Double { val rand = Random() return rand.nextDouble() * 360 } diff --git a/src/main/kotlin/dartzee/utils/InjectedThings.kt b/src/main/kotlin/dartzee/utils/InjectedThings.kt index afb55cf25..71aca05ff 100644 --- a/src/main/kotlin/dartzee/utils/InjectedThings.kt +++ b/src/main/kotlin/dartzee/utils/InjectedThings.kt @@ -22,8 +22,7 @@ import dartzee.sync.SyncConfigurer import dartzee.sync.SyncManager import java.time.Clock -object InjectedThings -{ +object InjectedThings { var allowModalDialogs = true var connectionPoolSize = 5 var databaseDirectory = DATABASE_FILE_PATH @@ -39,7 +38,8 @@ object InjectedThings var dartzeeAimCalculator: DartzeeAimCalculator = DartzeeAimCalculator() var aiSetupRuleFactory: IAISetupRuleFactory = AISetupRuleFactory() var simulationRunner: SimulationRunner = SimulationRunner() - private val remoteDatabaseStore: IRemoteDatabaseStore = AmazonS3RemoteDatabaseStore(SYNC_BUCKET_NAME) + private val remoteDatabaseStore: IRemoteDatabaseStore = + AmazonS3RemoteDatabaseStore(SYNC_BUCKET_NAME) var syncConfigurer: SyncConfigurer = SyncConfigurer(remoteDatabaseStore) var syncManager: SyncManager = SyncManager(remoteDatabaseStore) -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/PlayerImageUtils.kt b/src/main/kotlin/dartzee/utils/PlayerImageUtils.kt index 8c3abd627..7509df60b 100644 --- a/src/main/kotlin/dartzee/utils/PlayerImageUtils.kt +++ b/src/main/kotlin/dartzee/utils/PlayerImageUtils.kt @@ -11,7 +11,6 @@ import javax.swing.ImageIcon import kotlin.math.abs import kotlin.math.pow - const val PLAYER_IMAGE_WIDTH = 150 const val PLAYER_IMAGE_HEIGHT = 150 @@ -19,21 +18,25 @@ fun splitAvatar( playerOne: PlayerEntity, playerTwo: PlayerEntity, selectedPlayer: PlayerEntity?, - gameFinished: Boolean): ImageIcon -{ + gameFinished: Boolean +): ImageIcon { val firstImg = playerOne.getAvatarImage() val secondImg = playerTwo.getAvatarImage() - val diagonalOffset = if (gameFinished) 1.0 else when (selectedPlayer) { - playerOne -> 1.4 - playerTwo -> 0.6 - else -> 1.0 - } + val diagonalOffset = + if (gameFinished) 1.0 + else + when (selectedPlayer) { + playerOne -> 1.4 + playerTwo -> 0.6 + else -> 1.0 + } val diagonalCenter = (PLAYER_IMAGE_WIDTH * diagonalOffset).toInt() val diagonalThickness = if (selectedPlayer != null) 1 else 0 - val newImage = BufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB) + val newImage = + BufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB) newImage.paint { pt -> val manhattan = pt.x + pt.y if (abs(manhattan - diagonalCenter) <= diagonalThickness) { @@ -42,7 +45,8 @@ fun splitAvatar( val playerForSection = if (manhattan < diagonalCenter) playerOne else playerTwo val originalImg = if (playerForSection == playerOne) firstImg else secondImg val rgb = originalImg.getRGB(pt.x, pt.y) - val rgbToUse = if (selectedPlayer == playerForSection || gameFinished) rgb else greyscale(rgb) + val rgbToUse = + if (selectedPlayer == playerForSection || gameFinished) rgb else greyscale(rgb) Color(rgbToUse) } } @@ -53,11 +57,11 @@ fun splitAvatar( private fun PlayerEntity.getAvatarImage() = getAvatar().image.toBufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT) -fun ImageIcon.greyscale(): ImageIcon -{ +fun ImageIcon.greyscale(): ImageIcon { val original = image.toBufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT) - val newImage = BufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB) + val newImage = + BufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB) newImage.paint { pt -> val rgb = original.getRGB(pt.x, pt.y) Color(greyscale(rgb)) @@ -66,9 +70,7 @@ fun ImageIcon.greyscale(): ImageIcon return ImageIcon(newImage) } - -private fun greyscale(rgb: Int): Int -{ +private fun greyscale(rgb: Int): Int { val r = rgb shr 16 and 0xFF val g = rgb shr 8 and 0xFF val b = rgb and 0xFF @@ -86,8 +88,7 @@ private fun greyscale(rgb: Int): Int return (grayLevel shl 16) + (grayLevel shl 8) + grayLevel } -fun convertImageToAvatarDimensions(imageBytes: ByteArray): ByteArray -{ +fun convertImageToAvatarDimensions(imageBytes: ByteArray): ByteArray { val icon = ImageIcon(imageBytes) val image = icon.image.toBufferedImage(icon.iconWidth, icon.iconHeight) val minDimension = minOf(icon.iconWidth, icon.iconHeight) @@ -96,11 +97,12 @@ fun convertImageToAvatarDimensions(imageBytes: ByteArray): ByteArray val yc = (image.height - minDimension) / 2 val croppedImage = image.getSubimage(xc, yc, minDimension, minDimension) - val resizedImage = croppedImage - .getScaledInstance(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT, BufferedImage.SCALE_SMOOTH) - .toBufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT) + val resizedImage = + croppedImage + .getScaledInstance(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT, BufferedImage.SCALE_SMOOTH) + .toBufferedImage(PLAYER_IMAGE_WIDTH, PLAYER_IMAGE_HEIGHT) val baos = ByteArrayOutputStream() ImageIO.write(resizedImage, "jpg", baos) return baos.toByteArray() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/PreferenceUtil.kt b/src/main/kotlin/dartzee/utils/PreferenceUtil.kt index 5e67cf6bc..4bbe53928 100644 --- a/src/main/kotlin/dartzee/utils/PreferenceUtil.kt +++ b/src/main/kotlin/dartzee/utils/PreferenceUtil.kt @@ -2,69 +2,58 @@ package dartzee.utils import java.util.prefs.Preferences -object PreferenceUtil -{ +object PreferenceUtil { private const val PREFERENCE_DELIM_CHAR = ";" private val preferences = Preferences.userRoot().node(NODE_PREFERENCES) - /** - * Helpers - */ - private fun getPrefAndDefault(prefStr: String): Pair - { + /** Helpers */ + private fun getPrefAndDefault(prefStr: String): Pair { val prefAndDefault = prefStr.split(PREFERENCE_DELIM_CHAR, limit = 2) return Pair(prefAndDefault[0], prefAndDefault[1]) } private fun getRawPref(prefStr: String) = getPrefAndDefault(prefStr).first - fun deleteSetting(prefStr: String) - { + fun deleteSetting(prefStr: String) { val pref = getRawPref(prefStr) preferences.remove(pref) } - /** - * Strings - */ - fun getStringValue(prefStr: String, returnDefault: Boolean = false): String - { + /** Strings */ + fun getStringValue(prefStr: String, returnDefault: Boolean = false): String { val (pref, default) = getPrefAndDefault(prefStr) return if (returnDefault) default else preferences[pref, default] } - fun saveString(prefStr: String, value: String?) - { + fun saveString(prefStr: String, value: String?) { val pref = getRawPref(prefStr) preferences.put(pref, value) } - /** - * Ints - */ - fun getIntValue(prefStr: String, returnDefault: Boolean = false) = getStringValue(prefStr, returnDefault).toInt() - fun saveInt(prefStr: String, value: Int) - { + /** Ints */ + fun getIntValue(prefStr: String, returnDefault: Boolean = false) = + getStringValue(prefStr, returnDefault).toInt() + + fun saveInt(prefStr: String, value: Int) { val pref = getRawPref(prefStr) preferences.putInt(pref, value) } - /** - * Doubles! - */ - fun getDoubleValue(prefStr: String, returnDefault: Boolean = false) = getStringValue(prefStr, returnDefault).toDouble() - fun saveDouble(prefStr: String, value: Double) - { + /** Doubles! */ + fun getDoubleValue(prefStr: String, returnDefault: Boolean = false) = + getStringValue(prefStr, returnDefault).toDouble() + + fun saveDouble(prefStr: String, value: Double) { val pref = getRawPref(prefStr) preferences.putDouble(pref, value) } - /** - * Bools - */ - fun getBooleanValue(prefStr: String, returnDefault: Boolean = false) = getStringValue(prefStr, returnDefault).toBoolean() + /** Bools */ + fun getBooleanValue(prefStr: String, returnDefault: Boolean = false) = + getStringValue(prefStr, returnDefault).toBoolean() + fun saveBoolean(prefStr: String, value: Boolean) { val pref = getRawPref(prefStr) preferences.putBoolean(pref, value) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/RegistryConstants.kt b/src/main/kotlin/dartzee/utils/RegistryConstants.kt index 924738751..4af1f6c82 100644 --- a/src/main/kotlin/dartzee/utils/RegistryConstants.kt +++ b/src/main/kotlin/dartzee/utils/RegistryConstants.kt @@ -5,10 +5,10 @@ import dartzee.utils.DartsColour.DARTBOARD_GREEN_STR import dartzee.utils.DartsColour.DARTBOARD_RED_STR import dartzee.utils.DartsColour.DARTBOARD_WHITE_STR -//Node names +// Node names const val NODE_PREFERENCES = "DartsPrefs" -//Variable names +// Variable names val PREFERENCES_STRING_ODD_SINGLE_COLOUR = "oddsing;$DARTBOARD_WHITE_STR" val PREFERENCES_STRING_ODD_DOUBLE_COLOUR = "odddoub;$DARTBOARD_GREEN_STR" val PREFERENCES_STRING_ODD_TREBLE_COLOUR = "oddtreb;$DARTBOARD_GREEN_STR" @@ -25,4 +25,4 @@ const val PREFERENCES_INT_LEADERBOARD_SIZE = "ldbrdsz;50" const val PREFERENCES_DOUBLE_HUE_FACTOR = "huefactor;0.8" const val PREFERENCES_DOUBLE_FG_BRIGHTNESS = "fgbri;0.5" -const val PREFERENCES_DOUBLE_BG_BRIGHTNESS = "bgbri;1" \ No newline at end of file +const val PREFERENCES_DOUBLE_BG_BRIGHTNESS = "bgbri;1" diff --git a/src/main/kotlin/dartzee/utils/ResourceCache.kt b/src/main/kotlin/dartzee/utils/ResourceCache.kt index c55145e82..6d3fd51cf 100644 --- a/src/main/kotlin/dartzee/utils/ResourceCache.kt +++ b/src/main/kotlin/dartzee/utils/ResourceCache.kt @@ -15,11 +15,10 @@ import javax.sound.sampled.AudioSystem import javax.swing.ImageIcon /** - * Simple class housing statics for various image/sound resources - * So that these can be pre-loaded on start-up, rather than causing lag the first time they're required. + * Simple class housing statics for various image/sound resources So that these can be pre-loaded on + * start-up, rather than causing lag the first time they're required. */ -object ResourceCache -{ +object ResourceCache { val DART_IMG = ImageIcon(javaClass.getResource("/dartImage.png")) val IMG_BRUCE = ImageIcon(javaClass.getResource("/horrific/forsyth.png")) @@ -37,64 +36,100 @@ object ResourceCache val URL_ACHIEVEMENT_LOCKED: URL? = javaClass.getResource("/achievements/locked.png") val URL_ACHIEVEMENT_BEST_FINISH: URL? = javaClass.getResource("/achievements/bestFinish.png") val URL_ACHIEVEMENT_BEST_SCORE: URL? = javaClass.getResource("/achievements/bestScore.png") - val URL_ACHIEVEMENT_CHECKOUT_COMPLETENESS: URL? = javaClass.getResource("/achievements/checkoutCompleteness.png") + val URL_ACHIEVEMENT_CHECKOUT_COMPLETENESS: URL? = + javaClass.getResource("/achievements/checkoutCompleteness.png") val URL_ACHIEVEMENT_HIGHEST_BUST: URL? = javaClass.getResource("/achievements/bust.png") - val URL_ACHIEVEMENT_POINTS_RISKED: URL? = javaClass.getResource("/achievements/pointsRisked.png") + val URL_ACHIEVEMENT_POINTS_RISKED: URL? = + javaClass.getResource("/achievements/pointsRisked.png") val URL_ACHIEVEMENT_X01_GAMES_WON: URL? = javaClass.getResource("/achievements/trophyX01.png") val URL_ACHIEVEMENT_GOLF_GAMES_WON: URL? = javaClass.getResource("/achievements/trophyGolf.png") - val URL_ACHIEVEMENT_CLOCK_GAMES_WON: URL? = javaClass.getResource("/achievements/trophyClock.png") + val URL_ACHIEVEMENT_CLOCK_GAMES_WON: URL? = + javaClass.getResource("/achievements/trophyClock.png") val URL_ACHIEVEMENT_X01_BEST_GAME: URL? = javaClass.getResource("/achievements/podiumX01.png") val URL_ACHIEVEMENT_GOLF_BEST_GAME: URL? = javaClass.getResource("/achievements/podiumGolf.png") - val URL_ACHIEVEMENT_CLOCK_BEST_GAME: URL? = javaClass.getResource("/achievements/podiumClock.png") - val URL_ACHIEVEMENT_CLOCK_BRUCEY_BONUSES: URL? = javaClass.getResource("/achievements/Bruce.png") + val URL_ACHIEVEMENT_CLOCK_BEST_GAME: URL? = + javaClass.getResource("/achievements/podiumClock.png") + val URL_ACHIEVEMENT_CLOCK_BRUCEY_BONUSES: URL? = + javaClass.getResource("/achievements/Bruce.png") val URL_ACHIEVEMENT_X01_SHANGHAI: URL? = javaClass.getResource("/achievements/shanghai.png") - val URL_ACHIEVEMENT_X01_HOTEL_INSPECTOR: URL? = javaClass.getResource("/achievements/hotelInspector.png") - val URL_ACHIEVEMENT_X01_SUCH_BAD_LUCK: URL? = javaClass.getResource("/achievements/suchBadLuck.png") + val URL_ACHIEVEMENT_X01_HOTEL_INSPECTOR: URL? = + javaClass.getResource("/achievements/hotelInspector.png") + val URL_ACHIEVEMENT_X01_SUCH_BAD_LUCK: URL? = + javaClass.getResource("/achievements/suchBadLuck.png") val URL_ACHIEVEMENT_X01_BTBF: URL? = javaClass.getResource("/achievements/BTBF.png") - val URL_ACHIEVEMENT_CLOCK_BEST_STREAK: URL? = javaClass.getResource("/achievements/likeClockwork.png") + val URL_ACHIEVEMENT_CLOCK_BEST_STREAK: URL? = + javaClass.getResource("/achievements/likeClockwork.png") val URL_ACHIEVEMENT_X01_NO_MERCY: URL? = javaClass.getResource("/achievements/noMercy.png") - val URL_ACHIEVEMENT_GOLF_COURSE_MASTER: URL? = javaClass.getResource("/achievements/courseMaster.png") - val URL_ACHIEVEMENT_DARTZEE_GAMES_WON: URL? = javaClass.getResource("/achievements/trophyDartzee.png") - val URL_ACHIEVEMENT_DARTZEE_BEST_GAME: URL? = javaClass.getResource("/achievements/podiumDartzee.png") + val URL_ACHIEVEMENT_GOLF_COURSE_MASTER: URL? = + javaClass.getResource("/achievements/courseMaster.png") + val URL_ACHIEVEMENT_DARTZEE_GAMES_WON: URL? = + javaClass.getResource("/achievements/trophyDartzee.png") + val URL_ACHIEVEMENT_DARTZEE_BEST_GAME: URL? = + javaClass.getResource("/achievements/podiumDartzee.png") val URL_ACHIEVEMENT_DARTZEE_FLAWLESS: URL? = javaClass.getResource("/achievements/flawless.png") - val URL_ACHIEVEMENT_DARTZEE_UNDER_PRESSURE: URL? = javaClass.getResource("/achievements/underPressure.png") + val URL_ACHIEVEMENT_DARTZEE_UNDER_PRESSURE: URL? = + javaClass.getResource("/achievements/underPressure.png") val URL_ACHIEVEMENT_DARTZEE_BINGO: URL? = javaClass.getResource("/achievements/bingo.png") val URL_ACHIEVEMENT_DARTZEE_HALVED: URL? = javaClass.getResource("/achievements/bust.png") - val URL_ACHIEVEMENT_X01_CHUCKLEVISION: URL? = javaClass.getResource("/achievements/chucklevision.png") - val URL_ACHIEVEMENT_GOLF_ONE_HIT_WONDER: URL? = javaClass.getResource("/achievements/oneHitWonder.png") + val URL_ACHIEVEMENT_X01_CHUCKLEVISION: URL? = + javaClass.getResource("/achievements/chucklevision.png") + val URL_ACHIEVEMENT_GOLF_ONE_HIT_WONDER: URL? = + javaClass.getResource("/achievements/oneHitWonder.png") val URL_ACHIEVEMENT_GOLF_IN_BOUNDS: URL? = javaClass.getResource("/achievements/inBounds.png") val URL_ACHIEVEMENT_X01_WINNERS: URL? = javaClass.getResource("/achievements/x01Winners.png") val URL_ACHIEVEMENT_GOLF_WINNERS: URL? = javaClass.getResource("/achievements/golfWinners.png") - val URL_ACHIEVEMENT_DARTZEE_WINNERS: URL? = javaClass.getResource("/achievements/dartzeeWinners.png") - val URL_ACHIEVEMENT_CLOCK_WINNERS: URL? = javaClass.getResource("/achievements/clockWinners.png") - val URL_ACHIEVEMENT_X01_STYLISH_FINISH: URL? = javaClass.getResource("/achievements/stylishFinish.png") + val URL_ACHIEVEMENT_DARTZEE_WINNERS: URL? = + javaClass.getResource("/achievements/dartzeeWinners.png") + val URL_ACHIEVEMENT_CLOCK_WINNERS: URL? = + javaClass.getResource("/achievements/clockWinners.png") + val URL_ACHIEVEMENT_X01_STYLISH_FINISH: URL? = + javaClass.getResource("/achievements/stylishFinish.png") - val BASE_FONT: Font = Font.createFont(Font.TRUETYPE_FONT, javaClass.getResourceAsStream("/trebuc.ttf")) + val BASE_FONT: Font = + Font.createFont(Font.TRUETYPE_FONT, javaClass.getResourceAsStream("/trebuc.ttf")) private val wavPoolLock = Any() private val hmWavToInputStreams = HashMapList() var isInitialised = false - private fun getWavFiles(): List - { - return listOf("60.wav", "100.wav", "140.wav", "180.wav", "badmiss1.wav", "badmiss2.wav", "badmiss3.wav", "badmiss4.wav", - "basil1.wav", "basil2.wav", "basil3.wav", "basil4.wav", "bull.wav", "damage.wav", "forsyth1.wav", "forsyth2.wav", - "forsyth3.wav", "forsyth4.wav", "fourTrimmed.wav", "badLuck1.wav", "badLuck2.wav", "chucklevision1.wav", "chucklevision2.wav", "chucklevision3.wav") - } + private fun getWavFiles(): List { + return listOf( + "60.wav", + "100.wav", + "140.wav", + "180.wav", + "badmiss1.wav", + "badmiss2.wav", + "badmiss3.wav", + "badmiss4.wav", + "basil1.wav", + "basil2.wav", + "basil3.wav", + "basil4.wav", + "bull.wav", + "damage.wav", + "forsyth1.wav", + "forsyth2.wav", + "forsyth3.wav", + "forsyth4.wav", + "fourTrimmed.wav", + "badLuck1.wav", + "badLuck2.wav", + "chucklevision1.wav", + "chucklevision2.wav", + "chucklevision3.wav" + ) + } - fun initialiseResources() - { - try - { + fun initialiseResources() { + try { DialogUtil.showLoadingDialogOLD("Loading resources...") val wavFiles = getWavFiles() - for (wavFile in wavFiles) - { - repeat(3) - { + for (wavFile in wavFiles) { + repeat(3) { val ais = getAudioInputStream(wavFile) ais.mark(Integer.MAX_VALUE) @@ -104,29 +139,25 @@ object ResourceCache logger.info(CODE_LOADED_RESOURCES, "Finished loading ${wavFiles.size} resources") isInitialised = true - } - catch (e: Exception) - { + } catch (e: Exception) { logger.error(CODE_RESOURCE_LOAD_ERROR, "Failed to load resources", e) - } - finally - { + } finally { DialogUtil.dismissLoadingDialogOLD() } } - fun borrowInputStream(wavName: String): AudioInputStream? - { - synchronized(wavPoolLock) - { + fun borrowInputStream(wavName: String): AudioInputStream? { + synchronized(wavPoolLock) { val wavFile = "$wavName.wav" - //Return if the wav file doesn't exist + // Return if the wav file doesn't exist val streams = hmWavToInputStreams[wavFile] ?: return null - if (streams.isEmpty()) - { - logger.warn(CODE_NO_STREAMS, "No streams left for WAV [$wavName], will spawn another") + if (streams.isEmpty()) { + logger.warn( + CODE_NO_STREAMS, + "No streams left for WAV [$wavName], will spawn another" + ) val ais = getAudioInputStream(wavFile) ais.mark(Integer.MAX_VALUE) @@ -140,24 +171,18 @@ object ResourceCache } } - private fun getAudioInputStream(wavFile: String): AudioInputStream - { + private fun getAudioInputStream(wavFile: String): AudioInputStream { val inputStream = javaClass.getResourceAsStream("/wav/$wavFile") val bis = BufferedInputStream(inputStream) return AudioSystem.getAudioInputStream(bis) } - fun returnInputStream(wavName: String, stream: AudioInputStream) - { - synchronized (wavPoolLock) - { - hmWavToInputStreams.putInList("$wavName.wav", stream) - } + fun returnInputStream(wavName: String, stream: AudioInputStream) { + synchronized(wavPoolLock) { hmWavToInputStreams.putInList("$wavName.wav", stream) } } - fun resetCache() - { + fun resetCache() { isInitialised = false hmWavToInputStreams.clear() } diff --git a/src/main/kotlin/dartzee/utils/RoundTheClockUtil.kt b/src/main/kotlin/dartzee/utils/RoundTheClockUtil.kt index a80167aa1..32eb01340 100644 --- a/src/main/kotlin/dartzee/utils/RoundTheClockUtil.kt +++ b/src/main/kotlin/dartzee/utils/RoundTheClockUtil.kt @@ -4,10 +4,10 @@ import dartzee.core.util.getLongestStreak import dartzee.game.ClockType import dartzee.`object`.Dart -fun getLongestStreak(allDarts: List, clockType: ClockType = ClockType.Standard): List -{ +fun getLongestStreak(allDarts: List, clockType: ClockType = ClockType.Standard): List { val groupedByPt = allDarts.groupBy { it.participantId }.values - val streaks = groupedByPt.map { darts -> darts.getLongestStreak { it.hitClockTarget(clockType) } } + val streaks = + groupedByPt.map { darts -> darts.getLongestStreak { it.hitClockTarget(clockType) } } return streaks.maxByOrNull { it.size }.orEmpty() -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/SqlUtil.kt b/src/main/kotlin/dartzee/utils/SqlUtil.kt index 30781a1c8..69a847b8b 100644 --- a/src/main/kotlin/dartzee/utils/SqlUtil.kt +++ b/src/main/kotlin/dartzee/utils/SqlUtil.kt @@ -1,4 +1,6 @@ package dartzee.utils fun List.getQuotedIdStr() = getQuotedIdStr { it } -fun List.getQuotedIdStr(fieldSelector: (obj: T) -> String) = "(${joinToString { "'${fieldSelector(it)}'" } })" \ No newline at end of file + +fun List.getQuotedIdStr(fieldSelector: (obj: T) -> String) = + "(${joinToString { "'${fieldSelector(it)}'" } })" diff --git a/src/main/kotlin/dartzee/utils/UpdateManager.kt b/src/main/kotlin/dartzee/utils/UpdateManager.kt index ee0f502ba..84b3a2594 100644 --- a/src/main/kotlin/dartzee/utils/UpdateManager.kt +++ b/src/main/kotlin/dartzee/utils/UpdateManager.kt @@ -10,98 +10,90 @@ import dartzee.logging.CODE_UPDATE_ERROR import dartzee.logging.KEY_RESPONSE_BODY import dartzee.`object`.DartsClient import dartzee.utils.InjectedThings.logger -import kong.unirest.Unirest -import kong.unirest.json.JSONObject import java.awt.BorderLayout import java.io.File import javax.swing.JLabel import javax.swing.JOptionPane import javax.swing.JPanel +import kong.unirest.Unirest +import kong.unirest.json.JSONObject import kotlin.system.exitProcess - /** * Automatically check for and download updates using the Github API * * https://developer.github.com/v3/repos/releases/#get-the-latest-release */ -object UpdateManager -{ - fun checkForUpdates(currentVersion: String) - { - //Show this here, checking the CRC can take time +object UpdateManager { + fun checkForUpdates(currentVersion: String) { + // Show this here, checking the CRC can take time logger.info(CODE_UPDATE_CHECK, "Checking for updates - my version is $currentVersion") val jsonResponse = queryLatestReleaseJson(DARTZEE_REPOSITORY_URL) jsonResponse ?: return val metadata = parseUpdateMetadata(jsonResponse) - if (metadata == null || !shouldUpdate(currentVersion, metadata)) - { + if (metadata == null || !shouldUpdate(currentVersion, metadata)) { return } startUpdate(metadata.getArgs(), Runtime.getRuntime()) } - fun queryLatestReleaseJson(repositoryUrl: String): JSONObject? - { - try - { + fun queryLatestReleaseJson(repositoryUrl: String): JSONObject? { + try { DialogUtil.showLoadingDialog("Checking for updates...") val response = Unirest.get("$repositoryUrl/releases/latest").asJson() - if (response.status != 200) - { - logger.error(CODE_UPDATE_ERROR, - "Received non-success HTTP status: ${response.status} - ${response.statusText}", - KEY_RESPONSE_BODY to response.body) + if (response.status != 200) { + logger.error( + CODE_UPDATE_ERROR, + "Received non-success HTTP status: ${response.status} - ${response.statusText}", + KEY_RESPONSE_BODY to response.body + ) DialogUtil.showError("Failed to check for updates (unable to connect).") return null } return response.body.`object` - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_UPDATE_ERROR, "Caught $t checking for updates", t) DialogUtil.showError("Failed to check for updates (unable to connect).") return null - } - finally - { + } finally { DialogUtil.dismissLoadingDialog() } } - fun shouldUpdate(currentVersion: String, metadata: UpdateMetadata): Boolean - { + fun shouldUpdate(currentVersion: String, metadata: UpdateMetadata): Boolean { val newVersion = metadata.version - if (newVersion == currentVersion) - { + if (newVersion == currentVersion) { logger.info(CODE_UPDATE_CHECK_RESULT, "Up to date") return false } - //An update is available + // An update is available logger.info(CODE_UPDATE_CHECK_RESULT, "Newer release available - $newVersion") - if (!DartsClient.isWindowsOs()) - { + if (!DartsClient.isWindowsOs()) { showManualDownloadMessage(newVersion) return false } - val answer = DialogUtil.showQuestion("An update is available (${metadata.version}). Would you like to download it now?", false) + val answer = + DialogUtil.showQuestion( + "An update is available (${metadata.version}). Would you like to download it now?", + false + ) return answer == JOptionPane.YES_OPTION } - private fun showManualDownloadMessage(newVersion: String) - { + private fun showManualDownloadMessage(newVersion: String) { val fullUrl = "$DARTZEE_MANUAL_DOWNLOAD_URL/tag/$newVersion" val panel = JPanel() panel.layout = BorderLayout(0, 0) - val lblOne = JLabel("An update is available ($newVersion). You can download it manually from:") + val lblOne = + JLabel("An update is available ($newVersion). You can download it manually from:") val linkLabel = LinkLabel(fullUrl) { launchUrl(fullUrl) } panel.add(lblOne, BorderLayout.NORTH) @@ -110,10 +102,8 @@ object UpdateManager DialogUtil.showCustomMessage(panel) } - fun parseUpdateMetadata(responseJson: JSONObject): UpdateMetadata? - { - return try - { + fun parseUpdateMetadata(responseJson: JSONObject): UpdateMetadata? { + return try { val remoteVersion = responseJson.getString("tag_name") val assets = responseJson.getJSONArray("assets") val asset = assets.getJSONObject(0) @@ -121,29 +111,29 @@ object UpdateManager val assetId = asset.getLong("id") val fileName = asset.getString("name") val size = asset.getLong("size") - UpdateMetadata(remoteVersion, assetId, fileName, size) - } - catch (t: Throwable) - { - logger.error(CODE_PARSE_ERROR, "Error parsing update response", t, KEY_RESPONSE_BODY to responseJson) + UpdateMetadata(remoteVersion, assetId, fileName, size) + } catch (t: Throwable) { + logger.error( + CODE_PARSE_ERROR, + "Error parsing update response", + t, + KEY_RESPONSE_BODY to responseJson + ) null } } - fun startUpdate(args: String, runtime: Runtime) - { + fun startUpdate(args: String, runtime: Runtime) { prepareBatchFile() - try - { + try { runtime.exec("cmd /c start update.bat $args") - } - catch (t: Throwable) - { + } catch (t: Throwable) { logger.error(CODE_BATCH_ERROR, "Error running update.bat", t) val manualCommand = "update.bat $args" - val msg = "Failed to launch update.bat - call the following manually to perform the update: \n\n$manualCommand" + val msg = + "Failed to launch update.bat - call the following manually to perform the update: \n\n$manualCommand" DialogUtil.showError(msg) return } @@ -151,8 +141,7 @@ object UpdateManager exitProcess(0) } - fun prepareBatchFile() - { + fun prepareBatchFile() { val updateFile = File("update.bat") updateFile.delete() @@ -161,7 +150,11 @@ object UpdateManager } } -data class UpdateMetadata(val version: String, val assetId: Long, val fileName: String, val size: Long) -{ +data class UpdateMetadata( + val version: String, + val assetId: Long, + val fileName: String, + val size: Long +) { fun getArgs() = "$size $version $fileName $assetId" -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/UrlUtil.kt b/src/main/kotlin/dartzee/utils/UrlUtil.kt index 266f9f6d8..a57bec736 100644 --- a/src/main/kotlin/dartzee/utils/UrlUtil.kt +++ b/src/main/kotlin/dartzee/utils/UrlUtil.kt @@ -2,17 +2,11 @@ package dartzee.utils import dartzee.logging.CODE_HYPERLINK_ERROR -/** - * N.B. will likely only work on linux - */ -fun launchUrl(url: String, runtime: Runtime = Runtime.getRuntime()) -{ - try - { +/** N.B. will likely only work on linux */ +fun launchUrl(url: String, runtime: Runtime = Runtime.getRuntime()) { + try { runtime.exec("xdg-open $url") - } - catch (e: Exception) - { + } catch (e: Exception) { InjectedThings.logger.error(CODE_HYPERLINK_ERROR, "Failed to launch $url", e) } -} \ No newline at end of file +} diff --git a/src/main/kotlin/dartzee/utils/X01Util.kt b/src/main/kotlin/dartzee/utils/X01Util.kt index 9d56433f4..38591a3c1 100644 --- a/src/main/kotlin/dartzee/utils/X01Util.kt +++ b/src/main/kotlin/dartzee/utils/X01Util.kt @@ -4,12 +4,12 @@ import dartzee.ai.DartsAiModel import dartzee.`object`.Dart fun isBust(dart: Dart) = isBust(dart.startingScore, dart) -fun isBust(score: Int, lastDart: Dart): Boolean -{ + +fun isBust(score: Int, lastDart: Dart): Boolean { val scoreRemaining = score - lastDart.getTotal() - return (scoreRemaining < 0 - || scoreRemaining == 1 - || scoreRemaining == 0 && !lastDart.isDouble()) + return (scoreRemaining < 0 || + scoreRemaining == 1 || + scoreRemaining == 0 && !lastDart.isDouble()) } /** @@ -18,66 +18,52 @@ fun isBust(score: Int, lastDart: Dart): Boolean * - The starting score was odd and < the threshold (configurable per AI) * - The current score is even, meaning we have bailed ourselves out in some way */ -fun shouldStopForMercyRule(model: DartsAiModel, startingScore: Int, currentScore: Int): Boolean -{ +fun shouldStopForMercyRule(model: DartsAiModel, startingScore: Int, currentScore: Int): Boolean { val mercyThreshold = model.mercyThreshold ?: return false - return startingScore < mercyThreshold - && startingScore % 2 != 0 - && currentScore % 2 == 0 + return startingScore < mercyThreshold && startingScore % 2 != 0 && currentScore % 2 == 0 } -/** - * 50, 40, 38, 36, 34, ... , 8, 4, 2 - */ -fun isCheckoutDart(drt: Dart): Boolean -{ +/** 50, 40, 38, 36, 34, ... , 8, 4, 2 */ +fun isCheckoutDart(drt: Dart): Boolean { val startingScore = drt.startingScore return isCheckoutScore(startingScore) } + fun isCheckoutScore(score: Int) = getCheckoutScores().contains(score) -fun isNearMissDouble(dart: Dart): Boolean -{ - if (!isCheckoutDart(dart)) - { +fun isNearMissDouble(dart: Dart): Boolean { + if (!isCheckoutDart(dart)) { return false } - //Outer bull case - if (dart.startingScore == 50) - { + // Outer bull case + if (dart.startingScore == 50) { return dart.score == 25 && dart.multiplier == 1 } - val adjacents = getAdjacentNumbers(dart.startingScore/2) + val adjacents = getAdjacentNumbers(dart.startingScore / 2) - return dart.multiplier == 2 - && adjacents.contains(dart.score) + return dart.multiplier == 2 && adjacents.contains(dart.score) } -fun getCheckoutScores(): MutableList -{ +fun getCheckoutScores(): MutableList { val list = mutableListOf(50) - for (i in 2..40 step 2) - { + for (i in 2..40 step 2) { list.add(i) } return list } + fun getCheckoutSingles(): List = getCheckoutScores().map { it / 2 } -fun isFinishRound(round: List): Boolean -{ +fun isFinishRound(round: List): Boolean { val drt = round.last() return drt.isDouble() && drt.getTotal() == drt.startingScore } -/** - * Refactored out of GameWrapper for use in game stats panel - */ -fun getScoringDarts(allDarts: List?, scoreCutOff: Int): List -{ +/** Refactored out of GameWrapper for use in game stats panel */ +fun getScoringDarts(allDarts: List?, scoreCutOff: Int): List { allDarts ?: return emptyList() return allDarts.filter { it.startingScore > scoreCutOff }.toList() @@ -86,11 +72,9 @@ fun getScoringDarts(allDarts: List?, scoreCutOff: Int): List fun getScoringRounds(dartRounds: List>, scoreCutOff: Int) = dartRounds.filter { round -> round.all { it.startingScore > scoreCutOff } } -fun calculateThreeDartAverage(darts: List, scoreCutOff: Int): Double -{ +fun calculateThreeDartAverage(darts: List, scoreCutOff: Int): Double { val scoringDarts = getScoringDarts(darts, scoreCutOff) - if (scoringDarts.isEmpty()) - { + if (scoringDarts.isEmpty()) { return -1.0 } @@ -106,12 +90,11 @@ fun sumScore(darts: List) = darts.sumOf { it.getTotal() } * * Check there are 3 darts, all are 20s, the sum is 120 and there is at least one single */ -fun isShanghai(darts: MutableList): Boolean -{ - return darts.size == 3 - && sumScore(darts) == 120 - && darts.all { it.score == 20 } - && darts.any { it.multiplier == 1 } +fun isShanghai(darts: MutableList): Boolean { + return darts.size == 3 && + sumScore(darts) == 120 && + darts.all { it.score == 20 } && + darts.any { it.multiplier == 1 } } /** @@ -119,8 +102,10 @@ fun isShanghai(darts: MutableList): Boolean * * (5, T20, 1) -> "T20, 5, 1". */ -fun getSortedDartStr(darts: List): String -{ - val sortedDarts = darts.sortedWith(compareByDescending{ it.getTotal() }.thenByDescending{ it.multiplier }) +fun getSortedDartStr(darts: List): String { + val sortedDarts = + darts.sortedWith( + compareByDescending { it.getTotal() }.thenByDescending { it.multiplier } + ) return sortedDarts.joinToString { it.format() } } diff --git a/src/test/kotlin/dartzee/TestDarts.kt b/src/test/kotlin/dartzee/TestDarts.kt index 0a89dbe6d..a30e010f9 100644 --- a/src/test/kotlin/dartzee/TestDarts.kt +++ b/src/test/kotlin/dartzee/TestDarts.kt @@ -1,131 +1,212 @@ package dartzee -import dartzee.`object`.SegmentType import dartzee.helper.makeDart +import dartzee.`object`.SegmentType fun drtDoubleOne() = makeDart(1, 2, SegmentType.DOUBLE) + fun drtOuterOne() = makeDart(1, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleOne() = makeDart(1, 3, SegmentType.TREBLE) + fun drtInnerOne() = makeDart(1, 1, SegmentType.INNER_SINGLE) + fun drtMissOne() = makeDart(1, 0, SegmentType.MISS) fun drtDoubleTwo() = makeDart(2, 2, SegmentType.DOUBLE) + fun drtOuterTwo() = makeDart(2, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleTwo() = makeDart(2, 3, SegmentType.TREBLE) + fun drtInnerTwo() = makeDart(2, 1, SegmentType.INNER_SINGLE) + fun drtMissTwo() = makeDart(2, 0, SegmentType.MISS) fun drtDoubleThree() = makeDart(3, 2, SegmentType.DOUBLE) + fun drtOuterThree() = makeDart(3, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleThree() = makeDart(3, 3, SegmentType.TREBLE) + fun drtInnerThree() = makeDart(3, 1, SegmentType.INNER_SINGLE) + fun drtMissThree() = makeDart(3, 0, SegmentType.MISS) fun drtDoubleFour() = makeDart(4, 2, SegmentType.DOUBLE) + fun drtOuterFour() = makeDart(4, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleFour() = makeDart(4, 3, SegmentType.TREBLE) + fun drtInnerFour() = makeDart(4, 1, SegmentType.INNER_SINGLE) + fun drtMissFour() = makeDart(4, 0, SegmentType.MISS) fun drtDoubleFive() = makeDart(5, 2, SegmentType.DOUBLE) + fun drtOuterFive() = makeDart(5, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleFive() = makeDart(5, 3, SegmentType.TREBLE) + fun drtInnerFive() = makeDart(5, 1, SegmentType.INNER_SINGLE) + fun drtMissFive() = makeDart(5, 0, SegmentType.MISS) fun drtDoubleSix() = makeDart(6, 2, SegmentType.DOUBLE) + fun drtOuterSix() = makeDart(6, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleSix() = makeDart(6, 3, SegmentType.TREBLE) + fun drtInnerSix() = makeDart(6, 1, SegmentType.INNER_SINGLE) + fun drtMissSix() = makeDart(6, 0, SegmentType.MISS) fun drtDoubleSeven() = makeDart(7, 2, SegmentType.DOUBLE) + fun drtOuterSeven() = makeDart(7, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleSeven() = makeDart(7, 3, SegmentType.TREBLE) + fun drtInnerSeven() = makeDart(7, 1, SegmentType.INNER_SINGLE) + fun drtMissSeven() = makeDart(7, 0, SegmentType.MISS) fun drtDoubleEight() = makeDart(8, 2, SegmentType.DOUBLE) + fun drtOuterEight() = makeDart(8, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleEight() = makeDart(8, 3, SegmentType.TREBLE) + fun drtInnerEight() = makeDart(8, 1, SegmentType.INNER_SINGLE) + fun drtMissEight() = makeDart(8, 0, SegmentType.MISS) fun drtDoubleNine() = makeDart(9, 2, SegmentType.DOUBLE) + fun drtOuterNine() = makeDart(9, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleNine() = makeDart(9, 3, SegmentType.TREBLE) + fun drtInnerNine() = makeDart(9, 1, SegmentType.INNER_SINGLE) + fun drtMissNine() = makeDart(9, 0, SegmentType.MISS) fun drtDoubleTen() = makeDart(10, 2, SegmentType.DOUBLE) + fun drtOuterTen() = makeDart(10, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleTen() = makeDart(10, 3, SegmentType.TREBLE) + fun drtInnerTen() = makeDart(10, 1, SegmentType.INNER_SINGLE) + fun drtMissTen() = makeDart(10, 0, SegmentType.MISS) fun drtDoubleEleven() = makeDart(11, 2, SegmentType.DOUBLE) + fun drtOuterEleven() = makeDart(11, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleEleven() = makeDart(11, 3, SegmentType.TREBLE) + fun drtInnerEleven() = makeDart(11, 1, SegmentType.INNER_SINGLE) + fun drtMissEleven() = makeDart(11, 0, SegmentType.MISS) fun drtDoubleTwelve() = makeDart(12, 2, SegmentType.DOUBLE) + fun drtOuterTwelve() = makeDart(12, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleTwelve() = makeDart(12, 3, SegmentType.TREBLE) + fun drtInnerTwelve() = makeDart(12, 1, SegmentType.INNER_SINGLE) + fun drtMissTwelve() = makeDart(12, 0, SegmentType.MISS) fun drtDoubleThirteen() = makeDart(13, 2, SegmentType.DOUBLE) + fun drtOuterThirteen() = makeDart(13, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleThirteen() = makeDart(13, 3, SegmentType.TREBLE) + fun drtInnerThirteen() = makeDart(13, 1, SegmentType.INNER_SINGLE) + fun drtMissThirteen() = makeDart(13, 0, SegmentType.MISS) fun drtDoubleFourteen() = makeDart(14, 2, SegmentType.DOUBLE) + fun drtOuterFourteen() = makeDart(14, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleFourteen() = makeDart(14, 3, SegmentType.TREBLE) + fun drtInnerFourteen() = makeDart(14, 1, SegmentType.INNER_SINGLE) + fun drtMissFourteen() = makeDart(14, 0, SegmentType.MISS) fun drtDoubleFifteen() = makeDart(15, 2, SegmentType.DOUBLE) + fun drtOuterFifteen() = makeDart(15, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleFifteen() = makeDart(15, 3, SegmentType.TREBLE) + fun drtInnerFifteen() = makeDart(15, 1, SegmentType.INNER_SINGLE) + fun drtMissFifteen() = makeDart(15, 0, SegmentType.MISS) fun drtDoubleSixteen() = makeDart(16, 2, SegmentType.DOUBLE) + fun drtOuterSixteen() = makeDart(16, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleSixteen() = makeDart(16, 3, SegmentType.TREBLE) + fun drtInnerSixteen() = makeDart(16, 1, SegmentType.INNER_SINGLE) + fun drtMissSixteen() = makeDart(16, 0, SegmentType.MISS) fun drtDoubleSeventeen() = makeDart(17, 2, SegmentType.DOUBLE) + fun drtOuterSeventeen() = makeDart(17, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleSeventeen() = makeDart(17, 3, SegmentType.TREBLE) + fun drtInnerSeventeen() = makeDart(17, 1, SegmentType.INNER_SINGLE) + fun drtMissSeventeen() = makeDart(17, 0, SegmentType.MISS) fun drtDoubleEighteen() = makeDart(18, 2, SegmentType.DOUBLE) + fun drtOuterEighteen() = makeDart(18, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleEighteen() = makeDart(18, 3, SegmentType.TREBLE) + fun drtInnerEighteen() = makeDart(18, 1, SegmentType.INNER_SINGLE) + fun drtMissEighteen() = makeDart(18, 0, SegmentType.MISS) fun drtDoubleNineteen() = makeDart(19, 2, SegmentType.DOUBLE) + fun drtOuterNineteen() = makeDart(19, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleNineteen() = makeDart(19, 3, SegmentType.TREBLE) + fun drtInnerNineteen() = makeDart(19, 1, SegmentType.INNER_SINGLE) + fun drtMissNineteen() = makeDart(19, 0, SegmentType.MISS) fun drtDoubleTwenty() = makeDart(20, 2, SegmentType.DOUBLE) + fun drtOuterTwenty() = makeDart(20, 1, SegmentType.OUTER_SINGLE) + fun drtTrebleTwenty() = makeDart(20, 3, SegmentType.TREBLE) + fun drtInnerTwenty() = makeDart(20, 1, SegmentType.INNER_SINGLE) + fun drtMissTwenty() = makeDart(20, 0, SegmentType.MISS) -//fun main() -//{ -// fun numbers() = listOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", +// fun main() +// { +// fun numbers() = listOf("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", +// "Ten", "Eleven", "Twelve", "Thirteen", // "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty") // // (1..20).forEach { @@ -137,4 +218,4 @@ fun drtMissTwenty() = makeDart(20, 0, SegmentType.MISS) // println("fun drtMiss$numDesc() = makeDart($it, 0, SegmentType.MISS)") // println("") // } -//} \ No newline at end of file +// } diff --git a/src/test/kotlin/dartzee/TestUtils.kt b/src/test/kotlin/dartzee/TestUtils.kt index 97f9c24f5..53fd1f31a 100644 --- a/src/test/kotlin/dartzee/TestUtils.kt +++ b/src/test/kotlin/dartzee/TestUtils.kt @@ -74,31 +74,31 @@ val singleFive = DartboardSegment(SegmentType.INNER_SINGLE, 5) val PAST_TIME: Instant = Instant.parse("2020-04-12T11:04:00.00Z") val CURRENT_TIME: Instant = Instant.parse("2020-04-13T11:04:00.00Z") -val CURRENT_TIME_STRING: String = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") +val CURRENT_TIME_STRING: String = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") .withLocale(Locale.UK) .withZone(ZoneId.systemDefault()) .format(CURRENT_TIME) -fun makeLogRecord(timestamp: Instant = CURRENT_TIME, - severity: Severity = Severity.INFO, - loggingCode: LoggingCode = LoggingCode("log"), - message: String = "A thing happened", - errorObject: Throwable? = null, - keyValuePairs: Map = mapOf()) = - LogRecord(timestamp, severity, loggingCode, message, errorObject, keyValuePairs) +fun makeLogRecord( + timestamp: Instant = CURRENT_TIME, + severity: Severity = Severity.INFO, + loggingCode: LoggingCode = LoggingCode("log"), + message: String = "A thing happened", + errorObject: Throwable? = null, + keyValuePairs: Map = mapOf() +) = LogRecord(timestamp, severity, loggingCode, message, errorObject, keyValuePairs) fun Float.shouldBeBetween(a: Double, b: Double) { toDouble().shouldBeBetween(a, b, 0.0) } -fun Component.shouldHaveColours(colours: Pair) -{ +fun Component.shouldHaveColours(colours: Pair) { background shouldBe colours.first foreground shouldBe colours.second } -fun JComponent.shouldHaveBorderThickness(left: Int, right: Int, top: Int, bottom: Int) -{ +fun JComponent.shouldHaveBorderThickness(left: Int, right: Int, top: Int, bottom: Int) { val insets = border.getBorderInsets(this) insets.left shouldBe left insets.right shouldBe right @@ -106,26 +106,25 @@ fun JComponent.shouldHaveBorderThickness(left: Int, right: Int, top: Int, bottom insets.bottom shouldBe bottom } -fun MockKMatcherScope.launchParamsEqual(expected: GameLaunchParams) = match { actual -> - val expectedNoDartzee = expected.copy(dartzeeDtos = emptyList()) - val actualNoDartzee = actual.copy(dartzeeDtos = emptyList()) +fun MockKMatcherScope.launchParamsEqual(expected: GameLaunchParams) = + match { actual -> + val expectedNoDartzee = expected.copy(dartzeeDtos = emptyList()) + val actualNoDartzee = actual.copy(dartzeeDtos = emptyList()) - expectedNoDartzee == actualNoDartzee && - expected.dartzeeDtos?.map { it.generateRuleDescription() } == actual.dartzeeDtos?.map { it.generateRuleDescription() } -} + expectedNoDartzee == actualNoDartzee && + expected.dartzeeDtos?.map { it.generateRuleDescription() } == + actual.dartzeeDtos?.map { it.generateRuleDescription() } + } -fun LogRecord.shouldContainKeyValues(vararg values: Pair) -{ +fun LogRecord.shouldContainKeyValues(vararg values: Pair) { keyValuePairs.shouldContainExactly(mapOf(*values)) } -fun ComboBoxGameType.updateSelection(type: GameType) -{ +fun ComboBoxGameType.updateSelection(type: GameType) { selectedItem = items().find { it.hiddenData == type } } -fun DateFilterPanel.makeInvalid() -{ +fun DateFilterPanel.makeInvalid() { cbDateFrom.date = LocalDate.ofYearDay(2020, 30) cbDateTo.date = LocalDate.ofYearDay(2020, 20) } @@ -134,12 +133,11 @@ fun ScrollTable.getColumnNames() = (0 until columnCount).map { getColumnName(it) fun ScrollTable.getDisplayValueAt(row: Int, col: Int): Any = table.getValueAt(row, col) -fun ScrollTable.getRows(): List> = - model.getRows(columnCount) +fun ScrollTable.getRows(): List> = model.getRows(columnCount) fun ScrollTable.getRenderedRows(): List> = - (0 until rowCount).map { row -> (0 until columnCount) - .map { col -> + (0 until rowCount).map { row -> + (0 until columnCount).map { col -> val value = getValueAt(row, col) val r = table.getCellRenderer(row, col) val component = r?.getTableCellRendererComponent(table, value, false, false, row, col) @@ -158,12 +156,11 @@ fun ScrollTable.clickTableButton(row: Int, col: Int) { } fun ScrollTable.getFooterRow(): List = - (0 until columnCount).map { getValueAt(ScrollTable.TABLE_ROW_FOOTER, it)} + (0 until columnCount).map { getValueAt(ScrollTable.TABLE_ROW_FOOTER, it) } fun ScrollTable.getFirstRow() = getRows().first() -fun DefaultTableModel.getRows(columns: Int = columnCount): List> -{ +fun DefaultTableModel.getRows(columns: Int = columnCount): List> { val result = mutableListOf>() for (rowIx in 0 until rowCount) { val row = (0 until columns).map { getValueAt(rowIx, it) } @@ -182,15 +179,17 @@ fun List>.zipDartRounds(other: List>): List> { return result + extraRows } -fun PresentationDartboard.getPointForSegment(segment: DartboardSegment) = getAverage(getPointsForSegment(segment)) +fun PresentationDartboard.getPointForSegment(segment: DartboardSegment) = + getAverage(getPointsForSegment(segment)) fun PresentationDartboard.doClick(pt: Point) { doClick(pt.x, pt.y) flushEdt() } -fun GameplayDartboard.throwDartByClick(segment: DartboardSegment = DartboardSegment(SegmentType.OUTER_SINGLE, 20)) -{ +fun GameplayDartboard.throwDartByClick( + segment: DartboardSegment = DartboardSegment(SegmentType.OUTER_SINGLE, 20) +) { val interactiveDartboard = getChild() val pt = interactiveDartboard.getPointForSegment(segment) interactiveDartboard.doClick(pt.x, pt.y) @@ -205,8 +204,7 @@ fun List.only(): T { return first() } -fun PlayerImageDialog.selectImage(playerImageId: String) -{ +fun PlayerImageDialog.selectImage(playerImageId: String) { getChild().selectTab("uploadTab") val radio = getChild { it.playerImageId == playerImageId } @@ -215,8 +213,7 @@ fun PlayerImageDialog.selectImage(playerImageId: String) flushEdt() } -fun FileUploader.uploadFileFromResource(resourceName: String) -{ +fun FileUploader.uploadFileFromResource(resourceName: String) { clickChild(text = "...", async = true) val chooserDialog = getFileChooser() @@ -231,7 +228,9 @@ fun FileUploader.uploadFileFromResource(resourceName: String) } fun getInfoDialog() = findWindow { it.title == "Information" }!! + fun getQuestionDialog() = findWindow { it.title == "Question" }!! + fun getErrorDialog() = findWindow { it.title == "Error" }!! fun JDialog.getDialogMessage(): String { @@ -241,9 +240,7 @@ fun JDialog.getDialogMessage(): String { fun runAsync(block: () -> T?): T? { var result: T? = null - SwingUtilities.invokeLater { - result = block() - } + SwingUtilities.invokeLater { result = block() } flushEdt() return result @@ -269,12 +266,10 @@ fun confirmGameDeletion(localId: Long): String { return questionText } -/** - * TODO - Add to swing-test - */ -inline fun JTabbedPane.selectTab(name: String, noinline filterFn: ((T) -> Boolean)? = null) -{ - runOnEventThreadBlocking { - selectedComponent = getChild(name, filterFn = filterFn) - } +/** TODO - Add to swing-test */ +inline fun JTabbedPane.selectTab( + name: String, + noinline filterFn: ((T) -> Boolean)? = null +) { + runOnEventThreadBlocking { selectedComponent = getChild(name, filterFn = filterFn) } } diff --git a/src/test/kotlin/dartzee/achievements/AbstractAchievementTest.kt b/src/test/kotlin/dartzee/achievements/AbstractAchievementTest.kt index b12d0cacd..74f9ac753 100644 --- a/src/test/kotlin/dartzee/achievements/AbstractAchievementTest.kt +++ b/src/test/kotlin/dartzee/achievements/AbstractAchievementTest.kt @@ -21,54 +21,71 @@ import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual import io.kotest.matchers.ints.shouldBeLessThanOrEqual import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.sql.Timestamp import javax.imageio.ImageIO +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -abstract class AbstractAchievementTest: AbstractTest() -{ +abstract class AbstractAchievementTest : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { mainDatabase.dropUnexpectedTables() } abstract fun factoryAchievement(): E - abstract fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database = mainDatabase) - protected fun runConversion(playerIds: List = emptyList(), database: Database = mainDatabase) - { + abstract fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database = mainDatabase + ) + + protected fun runConversion( + playerIds: List = emptyList(), + database: Database = mainDatabase + ) { factoryAchievement().populateForConversion(playerIds, database) } - protected fun setUpAchievementRowForPlayer(p: PlayerEntity, database: Database = mainDatabase) - { + protected fun setUpAchievementRowForPlayer(p: PlayerEntity, database: Database = mainDatabase) { val g = insertRelevantGame(database = database) setUpAchievementRowForPlayerAndGame(p, g, database) } - protected fun getAchievementCount(database: Database = mainDatabase): Int - { + protected fun getAchievementCount(database: Database = mainDatabase): Int { val type = factoryAchievement().achievementType return AchievementEntity(database).countWhere("AchievementType = '$type'") } - open fun insertRelevantGame(dtLastUpdate: Timestamp = getSqlDateNow(), database: Database = mainDatabase) = - insertGame(gameType = factoryAchievement().gameType!!, dtLastUpdate = dtLastUpdate, database = database) - - fun insertRelevantParticipant(player: PlayerEntity = insertPlayer(), finalScore: Int = -1, team: Boolean = false): ParticipantEntity - { + open fun insertRelevantGame( + dtLastUpdate: Timestamp = getSqlDateNow(), + database: Database = mainDatabase + ) = + insertGame( + gameType = factoryAchievement().gameType!!, + dtLastUpdate = dtLastUpdate, + database = database + ) + + fun insertRelevantParticipant( + player: PlayerEntity = insertPlayer(), + finalScore: Int = -1, + team: Boolean = false + ): ParticipantEntity { val g = insertRelevantGame() val teamEntity = if (team) insertTeam(gameId = g.rowId, finalScore = finalScore) else null val ptFinalScore = if (team) -1 else finalScore - return insertParticipant(playerId = player.rowId, gameId = g.rowId, finalScore = ptFinalScore, teamId = teamEntity?.rowId.orEmpty()) + return insertParticipant( + playerId = player.rowId, + gameId = g.rowId, + finalScore = ptFinalScore, + teamId = teamEntity?.rowId.orEmpty() + ) } @Test - fun `Should ignore games of the wrong type`() - { + fun `Should ignore games of the wrong type`() { if (!factoryAchievement().usesTransactionalTablesForConversion) return val otherType = GameType.values().find { it != factoryAchievement().gameType }!! @@ -82,8 +99,7 @@ abstract class AbstractAchievementTest: AbstractTest() } @Test - fun `Should only generate data for specified players`() - { + fun `Should only generate data for specified players`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") @@ -99,8 +115,7 @@ abstract class AbstractAchievementTest: AbstractTest() } @Test - fun `Should generate data for all players by default`() - { + fun `Should generate data for all players by default`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") @@ -111,13 +126,12 @@ abstract class AbstractAchievementTest: AbstractTest() getAchievementCount() shouldBe 2 - val players = AchievementEntity().retrieveEntities("").map{ it.playerId } + val players = AchievementEntity().retrieveEntities("").map { it.playerId } players.shouldContainExactlyInAnyOrder(alice.rowId, bob.rowId) } @Test - fun `Icon URL should be valid`() - { + fun `Icon URL should be valid`() { val url = factoryAchievement().getIconURL() val bufferedImage = ImageIO.read(url) @@ -125,21 +139,17 @@ abstract class AbstractAchievementTest: AbstractTest() } @Test - fun `Unbounded achievements should have MaxValue = PinkThreshold`() - { + fun `Unbounded achievements should have MaxValue = PinkThreshold`() { val achievement = factoryAchievement() - if (achievement.isUnbounded()) - { + if (achievement.isUnbounded()) { achievement.maxValue shouldBe achievement.pinkThreshold } } @Test - fun `should run conversion on the right database`() - { - try - { + fun `should run conversion on the right database`() { + try { usingInMemoryDatabase(withSchema = true) { otherDatabase -> val alice = insertPlayer(name = "Alice", database = otherDatabase) setUpAchievementRowForPlayer(alice, otherDatabase) @@ -149,32 +159,26 @@ abstract class AbstractAchievementTest: AbstractTest() factoryAchievement().populateForConversion(emptyList(), otherDatabase) getAchievementCount(otherDatabase) shouldBe 1 - //If it's been connected to during the test, then another shut down would succeed + // If it's been connected to during the test, then another shut down would succeed mainDatabase.shutDown() shouldBe false } - } - finally - { + } finally { mainDatabase.initialiseConnectionPool(1) } } @Test - fun `Thresholds should be strictly increasing or decreasing`() - { + fun `Thresholds should be strictly increasing or decreasing`() { val achievement = factoryAchievement() - if (!achievement.isDecreasing()) - { + if (!achievement.isDecreasing()) { achievement.redThreshold shouldBeLessThan achievement.orangeThreshold achievement.orangeThreshold shouldBeLessThan achievement.yellowThreshold achievement.yellowThreshold shouldBeLessThan achievement.greenThreshold achievement.greenThreshold shouldBeLessThan achievement.blueThreshold achievement.blueThreshold shouldBeLessThan achievement.pinkThreshold achievement.pinkThreshold shouldBeLessThanOrEqual achievement.maxValue - } - else - { + } else { achievement.redThreshold shouldBeGreaterThan achievement.orangeThreshold achievement.orangeThreshold shouldBeGreaterThan achievement.yellowThreshold achievement.yellowThreshold shouldBeGreaterThan achievement.greenThreshold @@ -183,4 +187,4 @@ abstract class AbstractAchievementTest: AbstractTest() achievement.pinkThreshold shouldBeGreaterThanOrEqual achievement.maxValue } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/AbstractMultiRowAchievementTest.kt b/src/test/kotlin/dartzee/achievements/AbstractMultiRowAchievementTest.kt index 11d82cbb6..73caa734a 100644 --- a/src/test/kotlin/dartzee/achievements/AbstractMultiRowAchievementTest.kt +++ b/src/test/kotlin/dartzee/achievements/AbstractMultiRowAchievementTest.kt @@ -5,29 +5,35 @@ import dartzee.helper.insertAchievement import dartzee.helper.insertPlayer import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test + +abstract class AbstractMultiRowAchievementTest : + AbstractAchievementTest() { + private fun getDtAchievedColumnIndex() = + factoryAchievement().getBreakdownColumns().indexOf("Date Achieved") -abstract class AbstractMultiRowAchievementTest: AbstractAchievementTest() -{ - private fun getDtAchievedColumnIndex() = factoryAchievement().getBreakdownColumns().indexOf("Date Achieved") fun getGameIdEarnedColumnIndex() = factoryAchievement().getBreakdownColumns().indexOf("Game") - private fun insertAchievementRow(dtAchieved: Timestamp = getSqlDateNow(), - achievementCounter: Int = -1) - = insertAchievement(dtAchieved = dtAchieved, achievementCounter = achievementCounter, achievementDetail = "10") + private fun insertAchievementRow( + dtAchieved: Timestamp = getSqlDateNow(), + achievementCounter: Int = -1 + ) = + insertAchievement( + dtAchieved = dtAchieved, + achievementCounter = achievementCounter, + achievementDetail = "10" + ) @Test - fun `Breakdown column count should match row length`() - { + fun `Breakdown column count should match row length`() { val a = factoryAchievement() a.getBreakdownColumns().size shouldBe a.getBreakdownRow(insertAchievementRow()).size } @Test - fun `Should handle 0 achievement rows`() - { + fun `Should handle 0 achievement rows`() { val a = factoryAchievement() a.initialiseFromDb(listOf(), null) @@ -38,23 +44,26 @@ abstract class AbstractMultiRowAchievementTest: } @Test - fun `Should set the attainedValue correctly, taking into account all rows`() - { + fun `Should set the attainedValue correctly, taking into account all rows`() { val a = factoryAchievement() - if (a.useCounter()) - { - a.initialiseFromDb(listOf( - insertAchievementRow(achievementCounter = 1), - insertAchievementRow(achievementCounter = 2), - insertAchievementRow(achievementCounter = 4)), null) + if (a.useCounter()) { + a.initialiseFromDb( + listOf( + insertAchievementRow(achievementCounter = 1), + insertAchievementRow(achievementCounter = 2), + insertAchievementRow(achievementCounter = 4) + ), + null + ) a.attainedValue shouldBe 7 a.initialiseFromDb(listOf(insertAchievementRow(achievementCounter = 8)), null) a.attainedValue shouldBe 8 - } - else - { - a.initialiseFromDb(listOf(insertAchievementRow(), insertAchievementRow(), insertAchievementRow()), null) + } else { + a.initialiseFromDb( + listOf(insertAchievementRow(), insertAchievementRow(), insertAchievementRow()), + null + ) a.attainedValue shouldBe 3 a.initialiseFromDb(listOf(insertAchievementRow()), null) @@ -63,15 +72,17 @@ abstract class AbstractMultiRowAchievementTest: } @Test - fun `Should sort the rows by dtLastUpdate`() - { + fun `Should sort the rows by dtLastUpdate`() { val achievementOne = insertAchievementRow(dtAchieved = Timestamp(500)) val achievementTwo = insertAchievementRow(dtAchieved = Timestamp(1000)) val achievementThree = insertAchievementRow(dtAchieved = Timestamp(1500)) val achievementFour = insertAchievementRow(dtAchieved = Timestamp(2000)) val a = factoryAchievement() - a.initialiseFromDb(listOf(achievementTwo, achievementFour, achievementThree, achievementOne), null) + a.initialiseFromDb( + listOf(achievementTwo, achievementFour, achievementThree, achievementOne), + null + ) a.dtLatestUpdate shouldBe Timestamp(2000) a.tmBreakdown shouldNotBe null @@ -83,8 +94,7 @@ abstract class AbstractMultiRowAchievementTest: } @Test - fun `Should set the player`() - { + fun `Should set the player`() { val player = insertPlayer() val a = factoryAchievement() @@ -93,8 +103,7 @@ abstract class AbstractMultiRowAchievementTest: } @Test - fun `Should display the local game ID in the breakdown`() - { + fun `Should display the local game ID in the breakdown`() { val a = factoryAchievement() val dbRow = insertAchievementRow() @@ -104,4 +113,4 @@ abstract class AbstractMultiRowAchievementTest: a.tmBreakdown!!.getValueAt(0, getGameIdEarnedColumnIndex()) shouldBe 20 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/TestAbstractAchievementBestGame.kt b/src/test/kotlin/dartzee/achievements/TestAbstractAchievementBestGame.kt index 13955476b..b853bc229 100644 --- a/src/test/kotlin/dartzee/achievements/TestAbstractAchievementBestGame.kt +++ b/src/test/kotlin/dartzee/achievements/TestAbstractAchievementBestGame.kt @@ -12,27 +12,35 @@ import dartzee.helper.insertTeam import dartzee.helper.retrieveAchievement import dartzee.utils.Database import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -abstract class TestAbstractAchievementBestGame: AbstractAchievementTest() -{ - override fun insertRelevantGame(dtLastUpdate: Timestamp, database: Database): GameEntity - { - return insertGame(gameType = factoryAchievement().gameType!!, +abstract class TestAbstractAchievementBestGame : + AbstractAchievementTest() { + override fun insertRelevantGame(dtLastUpdate: Timestamp, database: Database): GameEntity { + return insertGame( + gameType = factoryAchievement().gameType!!, gameParams = factoryAchievement().gameParams, dtLastUpdate = dtLastUpdate, - database = database) + database = database + ) } - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - insertParticipant(gameId = g.rowId, playerId = p.rowId, finalScore = 30, database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + insertParticipant( + gameId = g.rowId, + playerId = p.rowId, + finalScore = 30, + database = database + ) } @Test - fun `Should ignore games that are the wrong type`() - { + fun `Should ignore games that are the wrong type`() { val otherType = GameType.values().find { it != factoryAchievement().gameType }!! val alice = insertPlayer(name = "Alice") val game = insertGame(gameType = otherType, gameParams = factoryAchievement().gameParams) @@ -45,13 +53,17 @@ abstract class TestAbstractAchievementBestGame: } @Test - fun `Should ignore games that were completed as a team`() - { + fun `Should ignore games that were completed as a team`() { val alice = insertPlayer(name = "Alice") val game = insertRelevantGame() val team = insertTeam(gameId = game.rowId) - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finalScore = 20, teamId = team.rowId) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finalScore = 20, + teamId = team.rowId + ) runConversion() @@ -59,8 +71,7 @@ abstract class TestAbstractAchievementBestGame: } @Test - fun `Should ignore games that are the wrong params`() - { + fun `Should ignore games that are the wrong params`() { val alice = insertPlayer(name = "Alice") val game = insertGame(gameType = factoryAchievement().gameType!!, gameParams = "blah") @@ -72,8 +83,7 @@ abstract class TestAbstractAchievementBestGame: } @Test - fun `Should ignore games of the wrong params with better scores`() - { + fun `Should ignore games of the wrong params with better scores`() { val alice = insertPlayer(name = "Alice") val badGame = insertGame(gameType = factoryAchievement().gameType!!, gameParams = "blah") val goodGame = insertRelevantGame() @@ -87,8 +97,7 @@ abstract class TestAbstractAchievementBestGame: } @Test - fun `Should ignore games where the finalScore is unset`() - { + fun `Should ignore games where the finalScore is unset`() { val alice = insertPlayer(name = "Alice") val game = insertRelevantGame() @@ -107,14 +116,23 @@ abstract class TestAbstractAchievementBestGame: } @Test - fun `Should return the lowest scoring game`() - { + fun `Should return the lowest scoring game`() { val alice = insertPlayer(name = "Alice") val game = insertRelevantGame() - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finalScore = 15, dtFinished = Timestamp(1000)) - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finalScore = 12, dtFinished = Timestamp(1500)) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finalScore = 15, + dtFinished = Timestamp(1000) + ) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finalScore = 12, + dtFinished = Timestamp(1500) + ) runConversion() @@ -124,15 +142,29 @@ abstract class TestAbstractAchievementBestGame: } @Test - fun `Should return the earliest game if there is a tie for best score`() - { + fun `Should return the earliest game if there is a tie for best score`() { val alice = insertPlayer(name = "Alice") val game = insertRelevantGame() - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finalScore = 12, dtFinished = Timestamp(1000)) - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finalScore = 12, dtFinished = Timestamp(800)) - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finalScore = 12, dtFinished = Timestamp(1500)) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finalScore = 12, + dtFinished = Timestamp(1000) + ) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finalScore = 12, + dtFinished = Timestamp(800) + ) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finalScore = 12, + dtFinished = Timestamp(1500) + ) runConversion() @@ -143,13 +175,17 @@ abstract class TestAbstractAchievementBestGame: } @Test - fun `Should set the correct values on the generated achievement row`() - { + fun `Should set the correct values on the generated achievement row`() { val alice = insertPlayer(name = "Alice") val game = insertRelevantGame() - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finalScore = 12, dtFinished = Timestamp(1000)) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finalScore = 12, + dtFinished = Timestamp(1000) + ) runConversion() @@ -161,4 +197,4 @@ abstract class TestAbstractAchievementBestGame: achievementRow.gameIdEarned shouldBe game.rowId achievementRow.achievementType shouldBe factoryAchievement().achievementType } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/TestAbstractAchievementGamesWon.kt b/src/test/kotlin/dartzee/achievements/TestAbstractAchievementGamesWon.kt index 0d39ead1f..364a2010c 100644 --- a/src/test/kotlin/dartzee/achievements/TestAbstractAchievementGamesWon.kt +++ b/src/test/kotlin/dartzee/achievements/TestAbstractAchievementGamesWon.kt @@ -10,19 +10,26 @@ import dartzee.helper.insertTeam import dartzee.utils.Database import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -abstract class TestAbstractAchievementGamesWon: AbstractMultiRowAchievementTest() -{ - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - insertParticipant(gameId = g.rowId, playerId = p.rowId, finishingPosition = 1, database = database) +abstract class TestAbstractAchievementGamesWon : + AbstractMultiRowAchievementTest() { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + insertParticipant( + gameId = g.rowId, + playerId = p.rowId, + finishingPosition = 1, + database = database + ) } @Test - fun `Should ignore participants who did not come 1st`() - { + fun `Should ignore participants who did not come 1st`() { val alice = insertPlayer(name = "Alice") val game = insertRelevantGame() insertParticipant(gameId = game.rowId, playerId = alice.rowId, finishingPosition = 2) @@ -33,12 +40,16 @@ abstract class TestAbstractAchievementGamesWon: } @Test - fun `Should ignore participants who were part of a team`() - { + fun `Should ignore participants who were part of a team`() { val alice = insertPlayer(name = "Alice") val game = insertRelevantGame() val team = insertTeam(gameId = game.rowId) - insertParticipant(gameId = game.rowId, playerId = alice.rowId, finishingPosition = 1, teamId = team.rowId) + insertParticipant( + gameId = game.rowId, + playerId = alice.rowId, + finishingPosition = 1, + teamId = team.rowId + ) runConversion() @@ -46,17 +57,47 @@ abstract class TestAbstractAchievementGamesWon: } @Test - fun `Should insert a row per player and game, and take their latest finish date as DtLastUpdate`() - { + fun `Should insert a row per player and game, and take their latest finish date as DtLastUpdate`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") - val pt1 = insertParticipant(gameId = insertRelevantGame().rowId, playerId = alice.rowId, finishingPosition = 1, dtFinished = Timestamp(500), finalScore = 20) - val pt2 = insertParticipant(gameId = insertRelevantGame().rowId, playerId = alice.rowId, finishingPosition = 1, dtFinished = Timestamp(1500), finalScore = 45) - val pt3 = insertParticipant(gameId = insertRelevantGame().rowId, playerId = alice.rowId, finishingPosition = 1, dtFinished = Timestamp(1000), finalScore = 26) + val pt1 = + insertParticipant( + gameId = insertRelevantGame().rowId, + playerId = alice.rowId, + finishingPosition = 1, + dtFinished = Timestamp(500), + finalScore = 20 + ) + val pt2 = + insertParticipant( + gameId = insertRelevantGame().rowId, + playerId = alice.rowId, + finishingPosition = 1, + dtFinished = Timestamp(1500), + finalScore = 45 + ) + val pt3 = + insertParticipant( + gameId = insertRelevantGame().rowId, + playerId = alice.rowId, + finishingPosition = 1, + dtFinished = Timestamp(1000), + finalScore = 26 + ) - insertParticipant(gameId = insertRelevantGame().rowId, playerId = bob.rowId, finishingPosition = 1, dtFinished = Timestamp(2000)) - insertParticipant(gameId = insertRelevantGame().rowId, playerId = bob.rowId, finishingPosition = 1, dtFinished = Timestamp(1000)) + insertParticipant( + gameId = insertRelevantGame().rowId, + playerId = bob.rowId, + finishingPosition = 1, + dtFinished = Timestamp(2000) + ) + insertParticipant( + gameId = insertRelevantGame().rowId, + playerId = bob.rowId, + finishingPosition = 1, + dtFinished = Timestamp(1000) + ) runConversion() @@ -74,4 +115,4 @@ abstract class TestAbstractAchievementGamesWon: val bobRow = achievementRows.filter { it.playerId == bob.rowId } bobRow.size shouldBe 2 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/TestAbstractAchievementTeamGamesWon.kt b/src/test/kotlin/dartzee/achievements/TestAbstractAchievementTeamGamesWon.kt index c68497e4a..9b024b70b 100644 --- a/src/test/kotlin/dartzee/achievements/TestAbstractAchievementTeamGamesWon.kt +++ b/src/test/kotlin/dartzee/achievements/TestAbstractAchievementTeamGamesWon.kt @@ -13,13 +13,16 @@ import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -abstract class TestAbstractAchievementTeamGamesWon: AbstractMultiRowAchievementTest() -{ - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { +abstract class TestAbstractAchievementTeamGamesWon : + AbstractMultiRowAchievementTest() { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { insertWinningTeamAndParticipant(p, g, database = database) } @@ -28,16 +31,27 @@ abstract class TestAbstractAchievementTeamGamesWon() -{ +class TestAchievementDartzeeBestGame : AbstractAchievementTest() { override fun factoryAchievement() = AchievementDartzeeBestGame() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - insertParticipant(gameId = g.rowId, playerId = p.rowId, finalScore = 127, database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + insertParticipant( + gameId = g.rowId, + playerId = p.rowId, + finalScore = 127, + database = database + ) insertDartzeeRules(g.rowId, testRules, database) } @Test - fun `should ignore participants who were part of a team`() - { + fun `should ignore participants who were part of a team`() { val pt = insertRelevantParticipant(finalScore = 120, team = true) insertDartzeeRules(pt.gameId, testRules) @@ -35,8 +41,7 @@ class TestAchievementDartzeeBestGame: AbstractAchievementTest() -{ +class TestAchievementDartzeeBingo : AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementDartzeeBingo() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - insertParticipant(gameId = g.rowId, playerId = p.rowId, finalScore = 275, database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + insertParticipant( + gameId = g.rowId, + playerId = p.rowId, + finalScore = 275, + database = database + ) insertDartzeeRules(g.rowId, testRules, database) } @Test - fun `Should ignore participants who were part of a team`() - { + fun `Should ignore participants who were part of a team`() { val pt = insertRelevantParticipant(finalScore = 120, team = true) insertDartzeeRules(pt.gameId, testRules) @@ -35,8 +41,7 @@ class TestAchievementDartzeeBingo: AbstractMultiRowAchievementTest() -{ +class TestAchievementDartzeeFlawless : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementDartzeeFlawless() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - val pt = insertParticipant(gameId = g.rowId, playerId = p.rowId, finalScore = 275, database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + val pt = + insertParticipant( + gameId = g.rowId, + playerId = p.rowId, + finalScore = 275, + database = database + ) insertSuccessRoundResults(pt, testRules, database) } @Test - fun `Should ignore participants who were part of a team`() - { + fun `Should ignore participants who were part of a team`() { val pt = insertRelevantParticipant(finalScore = 120, team = true) insertSuccessRoundResults(pt, testRules) @@ -43,8 +51,7 @@ class TestAchievementDartzeeFlawless: AbstractMultiRowAchievementTest, database: Database = mainDatabase) - { + private fun insertSuccessRoundResults( + participant: ParticipantEntity, + rules: List, + database: Database = mainDatabase + ) { insertDartzeeRules(participant.gameId, rules, database) val roundResults = List(rules.size) { ix -> DartzeeRoundResult(ix, true, 50) } - roundResults.forEach { DartzeeRoundResultEntity.factoryAndSave(it, participant, it.ruleNumber + 1, database) } + roundResults.forEach { + DartzeeRoundResultEntity.factoryAndSave(it, participant, it.ruleNumber + 1, database) + } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeGamesWon.kt b/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeGamesWon.kt index b047ef1ad..e5317e374 100644 --- a/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeGamesWon.kt +++ b/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeGamesWon.kt @@ -5,13 +5,12 @@ import dartzee.game.GameType import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementDartzeeGamesWon: TestAbstractAchievementGamesWon() -{ +class TestAchievementDartzeeGamesWon : + TestAbstractAchievementGamesWon() { override fun factoryAchievement() = AchievementDartzeeGamesWon() @Test - fun `Game type should be correct`() - { + fun `Game type should be correct`() { factoryAchievement().gameType shouldBe GameType.DARTZEE } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeHalved.kt b/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeHalved.kt index 592a41e70..60d3360ff 100644 --- a/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeHalved.kt +++ b/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeHalved.kt @@ -9,22 +9,23 @@ import dartzee.helper.insertParticipant import dartzee.helper.retrieveAchievement import dartzee.utils.Database import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestAchievementDartzeeHalved: AbstractAchievementTest() -{ +class TestAchievementDartzeeHalved : AbstractAchievementTest() { override fun factoryAchievement() = AchievementDartzeeHalved() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(gameId = g.rowId, playerId = p.rowId, database = database) insertDartzeeRoundResult(pt, success = false, score = -100, database = database) } @Test - fun `Should include participants who were part of a team`() - { + fun `Should include participants who were part of a team`() { val pt = insertRelevantParticipant(team = true) insertDartzeeRoundResult(pt, success = false, score = -100) @@ -33,8 +34,7 @@ class TestAchievementDartzeeHalved: AbstractAchievementTest() -{ +class TestAchievementDartzeeTeamGamesWon : + TestAbstractAchievementTeamGamesWon() { override fun factoryAchievement() = AchievementDartzeeTeamGamesWon() } diff --git a/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeUnderPressure.kt b/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeUnderPressure.kt index 4eb89c85e..4aae95966 100644 --- a/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeUnderPressure.kt +++ b/src/test/kotlin/dartzee/achievements/dartzee/TestAchievementDartzeeUnderPressure.kt @@ -18,19 +18,27 @@ import dartzee.utils.insertDartzeeRules import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementDartzeeUnderPressure: AbstractMultiRowAchievementTest() -{ +class TestAchievementDartzeeUnderPressure : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementDartzeeUnderPressure() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - val pt = insertParticipant(gameId = g.rowId, playerId = p.rowId, finalScore = 275, database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + val pt = + insertParticipant( + gameId = g.rowId, + playerId = p.rowId, + finalScore = 275, + database = database + ) insertValidRoundResult(pt, testRules, database) } @Test - fun `Should include participants who were part of a team`() - { + fun `Should include participants who were part of a team`() { val pt = insertRelevantParticipant(finalScore = 120, team = true) insertValidRoundResult(pt, testRules) @@ -39,8 +47,7 @@ class TestAchievementDartzeeUnderPressure: AbstractMultiRowAchievementTest, database: Database = mainDatabase): DartzeeRoundResultEntity - { + private fun insertValidRoundResult( + participant: ParticipantEntity, + rules: List, + database: Database = mainDatabase + ): DartzeeRoundResultEntity { insertDartzeeRules(participant.gameId, rules, database) val roundResult = getHardestRulePass(rules) - return DartzeeRoundResultEntity.factoryAndSave(roundResult, participant, rules.size + 1, database) + return DartzeeRoundResultEntity.factoryAndSave( + roundResult, + participant, + rules.size + 1, + database + ) } - private fun getHardestRulePass(rules: List) = DartzeeRoundResult(rules.size, true, 50) -} \ No newline at end of file + private fun getHardestRulePass(rules: List) = + DartzeeRoundResult(rules.size, true, 50) +} diff --git a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfBestGame.kt b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfBestGame.kt index a5425f990..6bc1e6460 100644 --- a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfBestGame.kt +++ b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfBestGame.kt @@ -5,16 +5,14 @@ import dartzee.game.GameType import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementGolfBestGame: TestAbstractAchievementBestGame() -{ +class TestAchievementGolfBestGame : TestAbstractAchievementBestGame() { override fun factoryAchievement() = AchievementGolfBestGame() @Test - fun `Should only count 18-hole games`() - { + fun `Should only count 18-hole games`() { val achievement = factoryAchievement() achievement.gameType shouldBe GameType.GOLF achievement.gameParams shouldBe "18" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfCourseMaster.kt b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfCourseMaster.kt index 7f2e3918f..b2d63e54b 100644 --- a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfCourseMaster.kt +++ b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfCourseMaster.kt @@ -1,31 +1,40 @@ package dartzee.achievements.golf -import dartzee.`object`.SegmentType -import dartzee.achievements.AchievementType import dartzee.achievements.AbstractMultiRowAchievementTest +import dartzee.achievements.AchievementType import dartzee.db.GameEntity import dartzee.db.PlayerEntity import dartzee.helper.insertDart import dartzee.helper.insertParticipant import dartzee.helper.retrieveAchievement +import dartzee.`object`.SegmentType import dartzee.utils.Database import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestAchievementGolfCourseMaster: AbstractMultiRowAchievementTest() -{ +class TestAchievementGolfCourseMaster : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementGolfCourseMaster() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) - insertDart(pt, score = 1, roundNumber = 1, segmentType = SegmentType.DOUBLE, database = database) + insertDart( + pt, + score = 1, + roundNumber = 1, + segmentType = SegmentType.DOUBLE, + database = database + ) } @Test - fun `Should include games that were finished as part of a team`() - { + fun `Should include games that were finished as part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, score = 1, roundNumber = 1, segmentType = SegmentType.DOUBLE) @@ -34,12 +43,23 @@ class TestAchievementGolfCourseMaster: AbstractMultiRowAchievementTest() -{ +class TestAchievementGolfGamesWon : TestAbstractAchievementGamesWon() { override fun factoryAchievement() = AchievementGolfGamesWon() @Test - fun `Game type should be correct`() - { + fun `Game type should be correct`() { factoryAchievement().gameType shouldBe GameType.GOLF } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfInBounds.kt b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfInBounds.kt index 35681f033..1cee5899a 100644 --- a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfInBounds.kt +++ b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfInBounds.kt @@ -41,19 +41,32 @@ import dartzee.only import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestAchievementGolfInBounds : AbstractAchievementTest() -{ +class TestAchievementGolfInBounds : AbstractAchievementTest() { override fun factoryAchievement() = AchievementGolfInBounds() override fun insertRelevantGame(dtLastUpdate: Timestamp, database: Database) = - insertGame(gameType = factoryAchievement().gameType, gameParams = "18", dtLastUpdate = dtLastUpdate, database = database) + insertGame( + gameType = factoryAchievement().gameType, + gameParams = "18", + dtLastUpdate = dtLastUpdate, + database = database + ) - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, finalScore = 54, database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + val pt = + insertParticipant( + playerId = p.rowId, + gameId = g.rowId, + finalScore = 54, + database = database + ) setUpDartsForParticipant(pt, database) } @@ -80,17 +93,13 @@ class TestAchievementGolfInBounds : AbstractAchievementTest() -{ +class TestAchievementGolfOneHitWonder : AbstractAchievementTest() { override fun factoryAchievement() = AchievementGolfOneHitWonder() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) - val dartRounds = listOf( - makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())), - makeGolfRound(2, listOf(drtOuterTwo(), drtInnerTwo())), - makeGolfRound(3, listOf(drtOuterThree(), drtDoubleNineteen(), drtDoubleSeventeen())), - makeGolfRound(4, listOf(drtDoubleFour())) - ) - - dartRounds.flatten().forEach { - insertDart(pt, it, database = database) - } + val dartRounds = + listOf( + makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())), + makeGolfRound(2, listOf(drtOuterTwo(), drtInnerTwo())), + makeGolfRound( + 3, + listOf(drtOuterThree(), drtDoubleNineteen(), drtDoubleSeventeen()) + ), + makeGolfRound(4, listOf(drtDoubleFour())) + ) + + dartRounds.flatten().forEach { insertDart(pt, it, database = database) } } @Test - fun `Should ignore rounds where the double hit is not the correct one`() - { + fun `Should ignore rounds where the double hit is not the correct one`() { val pt = insertRelevantParticipant() val dartRound = makeGolfRound(1, listOf(drtDoubleTwenty())) - dartRound.forEach { - insertDart(pt, it) - } + dartRound.forEach { insertDart(pt, it) } runConversion() getAchievementCount() shouldBe 0 } @Test - fun `Should ignore rounds where a double was not thrown`() - { + fun `Should ignore rounds where a double was not thrown`() { val pt = insertRelevantParticipant() val dartRound = makeGolfRound(1, listOf(drtInnerOne(), drtOuterOne(), drtTrebleOne())) - dartRound.forEach { - insertDart(pt, it) - } + dartRound.forEach { insertDart(pt, it) } runConversion() getAchievementCount() shouldBe 0 } @Test - fun `Should pick the game with the highest count`() - { + fun `Should pick the game with the highest count`() { val player = insertPlayer() val pt1 = insertRelevantParticipant(player) val pt2 = insertRelevantParticipant(player) - val dartRounds1 = listOf( - makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())) - ) - dartRounds1.flatten().forEach { - insertDart(pt1, it, dtCreation = Timestamp(500)) - } - - val dartRounds2 = listOf( - makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())), - makeGolfRound(2, listOf(drtDoubleTwo())), - ) - dartRounds2.flatten().forEach { - insertDart(pt2, it, dtCreation = Timestamp(1000)) - } + val dartRounds1 = listOf(makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne()))) + dartRounds1.flatten().forEach { insertDart(pt1, it, dtCreation = Timestamp(500)) } + + val dartRounds2 = + listOf( + makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())), + makeGolfRound(2, listOf(drtDoubleTwo())), + ) + dartRounds2.flatten().forEach { insertDart(pt2, it, dtCreation = Timestamp(1000)) } runConversion() - val a = AchievementEntity.retrieveAchievement(AchievementType.GOLF_ONE_HIT_WONDER, player.rowId)!! + val a = + AchievementEntity.retrieveAchievement( + AchievementType.GOLF_ONE_HIT_WONDER, + player.rowId + )!! a.gameIdEarned shouldBe pt2.gameId a.dtAchieved shouldBe Timestamp(1000) a.achievementCounter shouldBe 2 } - @Test - fun `Should take the earliest game where the record was achieved`() - { + fun `Should take the earliest game where the record was achieved`() { val player = insertPlayer() val pt1 = insertRelevantParticipant(player) val pt2 = insertRelevantParticipant(player) val dartRound1 = makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())) - dartRound1.forEach { - insertDart(pt1, it, dtCreation = Timestamp(500)) - } + dartRound1.forEach { insertDart(pt1, it, dtCreation = Timestamp(500)) } val dartRound2 = makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())) - dartRound2.forEach { - insertDart(pt2, it, dtCreation = Timestamp(1000)) - } + dartRound2.forEach { insertDart(pt2, it, dtCreation = Timestamp(1000)) } runConversion() - val a = AchievementEntity.retrieveAchievement(AchievementType.GOLF_ONE_HIT_WONDER, player.rowId)!! + val a = + AchievementEntity.retrieveAchievement( + AchievementType.GOLF_ONE_HIT_WONDER, + player.rowId + )!! a.gameIdEarned shouldBe pt1.gameId a.dtAchieved shouldBe Timestamp(500) a.achievementCounter shouldBe 1 } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfPointsRisked.kt b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfPointsRisked.kt index bc33b6391..7739050be 100644 --- a/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfPointsRisked.kt +++ b/src/test/kotlin/dartzee/achievements/golf/TestAchievementGolfPointsRisked.kt @@ -18,18 +18,21 @@ import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestAchievementGolfPointsRisked: AbstractMultiRowAchievementTest() -{ +class TestAchievementGolfPointsRisked : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementGolfPointsRisked() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) = - insertRiskedDart(p.rowId, g.rowId, database = database) + + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) = insertRiskedDart(p.rowId, g.rowId, database = database) @Test - fun `Should include games that were finished as part of a team`() - { + fun `Should include games that were finished as part of a team`() { val pt = insertRelevantParticipant(team = true) insertRiskedDart(pt, SegmentType.INNER_SINGLE, 1) @@ -38,22 +41,28 @@ class TestAchievementGolfPointsRisked: AbstractMultiRowAchievementTest() -{ +class TestAchievementGolfTeamGamesWon : + TestAbstractAchievementTeamGamesWon() { override fun factoryAchievement() = AchievementGolfTeamGamesWon() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestGame.kt b/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestGame.kt index 43267c3ad..4002e00c3 100644 --- a/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestGame.kt +++ b/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestGame.kt @@ -7,16 +7,14 @@ import dartzee.game.RoundTheClockConfig import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementClockBestGame: TestAbstractAchievementBestGame() -{ +class TestAchievementClockBestGame : TestAbstractAchievementBestGame() { override fun factoryAchievement() = AchievementClockBestGame() @Test - fun `Should only count standard games of RTC`() - { + fun `Should only count standard games of RTC`() { val achievement = factoryAchievement() achievement.gameType shouldBe GameType.ROUND_THE_CLOCK achievement.gameParams shouldBe RoundTheClockConfig(ClockType.Standard, true).toJson() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestStreak.kt b/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestStreak.kt index ca30be2db..477f3188d 100644 --- a/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestStreak.kt +++ b/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockBestStreak.kt @@ -14,16 +14,14 @@ import dartzee.helper.insertPlayer import dartzee.utils.Database import dartzee.utils.InjectedThings.mainDatabase import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestAchievementClockBestStreak: AbstractAchievementTest() -{ +class TestAchievementClockBestStreak : AbstractAchievementTest() { override fun factoryAchievement() = AchievementClockBestStreak() @Test - fun `Should ignore streaks executed as part of a team`() - { + fun `Should ignore streaks executed as part of a team`() { val pt = insertRelevantParticipant(team = true) insertOpeningStreak(pt) @@ -33,8 +31,7 @@ class TestAchievementClockBestStreak: AbstractAchievementTest() -{ +class TestAchievementClockBruceyBonuses : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementClockBruceyBonuses() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) - insertDart(pt, ordinal = 4, startingScore = 4, score = 4, multiplier = 1, database = database) + insertDart( + pt, + ordinal = 4, + startingScore = 4, + score = 4, + multiplier = 1, + database = database + ) } - override fun insertRelevantGame(dtLastUpdate: Timestamp, database: Database): GameEntity - { - return insertGame(gameType = factoryAchievement().gameType, + override fun insertRelevantGame(dtLastUpdate: Timestamp, database: Database): GameEntity { + return insertGame( + gameType = factoryAchievement().gameType, gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson(), dtLastUpdate = dtLastUpdate, - database = database) + database = database + ) } @Test - fun `Should include participants who were part of a team`() - { + fun `Should include participants who were part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, ordinal = 4, startingScore = 4, score = 4, multiplier = 1) @@ -52,8 +62,7 @@ class TestAchievementClockBruceyBonuses: AbstractMultiRowAchievementTest() -{ +class TestAchievementClockGamesWon : TestAbstractAchievementGamesWon() { override fun factoryAchievement() = AchievementClockGamesWon() @Test - fun `Game type should be correct`() - { + fun `Game type should be correct`() { factoryAchievement().gameType shouldBe GameType.ROUND_THE_CLOCK } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockTeamGamesWon.kt b/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockTeamGamesWon.kt index a1a02f798..a606714bc 100644 --- a/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockTeamGamesWon.kt +++ b/src/test/kotlin/dartzee/achievements/rtc/TestAchievementClockTeamGamesWon.kt @@ -2,7 +2,7 @@ package dartzee.achievements.rtc import dartzee.achievements.TestAbstractAchievementTeamGamesWon -class TestAchievementClockTeamGamesWon : TestAbstractAchievementTeamGamesWon() -{ +class TestAchievementClockTeamGamesWon : + TestAbstractAchievementTeamGamesWon() { override fun factoryAchievement() = AchievementClockTeamGamesWon() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestFinish.kt b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestFinish.kt index 754f1db7f..a6e5a3ab6 100644 --- a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestFinish.kt +++ b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestFinish.kt @@ -12,25 +12,32 @@ import dartzee.helper.insertPlayer import dartzee.helper.retrieveAchievement import dartzee.utils.Database import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestAchievementX01BestFinish: AbstractAchievementTest() -{ +class TestAchievementX01BestFinish : AbstractAchievementTest() { override fun factoryAchievement() = AchievementX01BestFinish() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - insertParticipant(playerId = p.rowId, gameId = g.rowId, dtFinished = getSqlDateNow(), database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + insertParticipant( + playerId = p.rowId, + gameId = g.rowId, + dtFinished = getSqlDateNow(), + database = database + ) insertFinishForPlayer(p, 60, game = g, database = database) } @Test - fun `Should ignore darts that are not doubles`() - { + fun `Should ignore darts that are not doubles`() { val p = insertPlayer() val g = insertRelevantGame() - val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, dtFinished = getSqlDateNow()) + val pt = + insertParticipant(playerId = p.rowId, gameId = g.rowId, dtFinished = getSqlDateNow()) insertDart(pt, ordinal = 1, startingScore = 40, score = 20, multiplier = 1) insertDart(pt, ordinal = 2, startingScore = 20, score = 20, multiplier = 1) @@ -41,11 +48,11 @@ class TestAchievementX01BestFinish: AbstractAchievementTest() -{ +class TestAchievementX01BestGame : TestAbstractAchievementBestGame() { override fun factoryAchievement() = AchievementX01BestGame() @Test - fun `Should only count games of 501`() - { + fun `Should only count games of 501`() { val achievement = factoryAchievement() achievement.gameType shouldBe GameType.X01 achievement.gameParams shouldBe "501" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestThreeDarts.kt b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestThreeDarts.kt index b5b786060..f3d7e2dfe 100644 --- a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestThreeDarts.kt +++ b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01BestThreeDarts.kt @@ -10,25 +10,47 @@ import dartzee.helper.insertPlayer import dartzee.helper.retrieveAchievement import dartzee.utils.Database import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestAchievementX01BestThreeDarts: AbstractAchievementTest() -{ +class TestAchievementX01BestThreeDarts : AbstractAchievementTest() { override fun factoryAchievement() = AchievementX01BestThreeDarts() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) - insertDart(pt, ordinal = 1, startingScore = 501, score = 20, multiplier = 3, database = database) - insertDart(pt, ordinal = 2, startingScore = 441, score = 20, multiplier = 3, database = database) - insertDart(pt, ordinal = 3, startingScore = 381, score = 20, multiplier = 3, database = database) + insertDart( + pt, + ordinal = 1, + startingScore = 501, + score = 20, + multiplier = 3, + database = database + ) + insertDart( + pt, + ordinal = 2, + startingScore = 441, + score = 20, + multiplier = 3, + database = database + ) + insertDart( + pt, + ordinal = 3, + startingScore = 381, + score = 20, + multiplier = 3, + database = database + ) } @Test - fun `Should include rounds that were thrown as part of a team`() - { + fun `Should include rounds that were thrown as part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, ordinal = 1, startingScore = 501, score = 20, multiplier = 3) @@ -39,10 +61,8 @@ class TestAchievementX01BestThreeDarts: AbstractAchievementTest() -{ +class TestAchievementX01Btbf : AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementX01Btbf() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { insertSuccessfulParticipant(g, p, database) } @Test - fun `Should include games that were won as part of a team`() - { + fun `Should include games that were won as part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, roundNumber = 1, startingScore = 2, score = 1, multiplier = 2) @@ -32,8 +33,7 @@ class TestAchievementX01Btbf: AbstractMultiRowAchievementTest() -{ +class TestAchievementX01CheckoutCompleteness : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementX01CheckoutCompleteness() @Test - fun `Should include participants who were part of a team`() - { + fun `Should include participants who were part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, startingScore = 2, score = 1, multiplier = 2) @@ -32,8 +31,7 @@ class TestAchievementX01CheckoutCompleteness: AbstractMultiRowAchievementTest() -{ +class TestAchievementX01Chucklevision : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementX01Chucklevision() private fun makeChucklevisionDarts() = listOf(Dart(20, 3), Dart(5, 1), Dart(4, 1)) @Test - fun `Should include rounds that were completed as part of a team`() - { + fun `Should include rounds that were completed as part of a team`() { val p = insertPlayer() val g = insertRelevantGame() val team = insertTeam(gameId = g.rowId) @@ -40,8 +39,7 @@ class TestAchievementX01Chucklevision: AbstractMultiRowAchievementTest, - startingScore: Int = 501, - database: Database = mainDatabase, - participant: ParticipantEntity? = null, - roundNumber: Int = 1) - { - val pt = participant ?: insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) + private fun insertDartsForPlayer( + g: GameEntity, + p: PlayerEntity, + darts: List, + startingScore: Int = 501, + database: Database = mainDatabase, + participant: ParticipantEntity? = null, + roundNumber: Int = 1 + ) { + val pt = + participant + ?: insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) var currentScore = startingScore darts.forEachIndexed { ix, drt -> - insertDart(pt, score = drt.score, multiplier = drt.multiplier, ordinal = ix+1, startingScore = currentScore, roundNumber = roundNumber, database = database) + insertDart( + pt, + score = drt.score, + multiplier = drt.multiplier, + ordinal = ix + 1, + startingScore = currentScore, + roundNumber = roundNumber, + database = database + ) currentScore -= drt.getTotal() } - } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01GamesWon.kt b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01GamesWon.kt index e931ed645..ebdac76aa 100644 --- a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01GamesWon.kt +++ b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01GamesWon.kt @@ -5,13 +5,11 @@ import dartzee.game.GameType import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementX01GamesWon: TestAbstractAchievementGamesWon() -{ +class TestAchievementX01GamesWon : TestAbstractAchievementGamesWon() { override fun factoryAchievement() = AchievementX01GamesWon() @Test - fun `Game type should be correct`() - { + fun `Game type should be correct`() { AchievementX01GamesWon().gameType shouldBe GameType.X01 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01HighestBust.kt b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01HighestBust.kt index 8fbbee807..84d9f00e3 100644 --- a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01HighestBust.kt +++ b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01HighestBust.kt @@ -12,22 +12,44 @@ import dartzee.utils.Database import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementX01HighestBust: AbstractAchievementTest() -{ +class TestAchievementX01HighestBust : AbstractAchievementTest() { override fun factoryAchievement() = AchievementX01HighestBust() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) - insertDart(pt, ordinal = 1, startingScore = 181, score = 20, multiplier = 3, database = database) - insertDart(pt, ordinal = 2, startingScore = 121, score = 20, multiplier = 3, database = database) - insertDart(pt, ordinal = 3, startingScore = 61, score = 20, multiplier = 3, database = database) + insertDart( + pt, + ordinal = 1, + startingScore = 181, + score = 20, + multiplier = 3, + database = database + ) + insertDart( + pt, + ordinal = 2, + startingScore = 121, + score = 20, + multiplier = 3, + database = database + ) + insertDart( + pt, + ordinal = 3, + startingScore = 61, + score = 20, + multiplier = 3, + database = database + ) } @Test - fun `Should include participants who were part of a team`() - { + fun `Should include participants who were part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, ordinal = 1, roundNumber = 1, startingScore = 40, score = 20, multiplier = 1) @@ -39,8 +61,7 @@ class TestAchievementX01HighestBust: AbstractAchievementTest() -{ +class TestAchievementX01HotelInspector : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementX01HotelInspector() @Test - fun `Should include rounds that were completed as part of a team`() - { + fun `Should include rounds that were completed as part of a team`() { val p = insertPlayer() val g = insertRelevantGame() val team = insertTeam(gameId = g.rowId) @@ -40,8 +39,7 @@ class TestAchievementX01HotelInspector: AbstractMultiRowAchievementTest, - startingScore: Int = 501, - database: Database = mainDatabase, - participant: ParticipantEntity? = null, - roundNumber: Int = 1) - { - val pt = participant ?: insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) + private fun insertDartsForPlayer( + g: GameEntity, + p: PlayerEntity, + darts: List, + startingScore: Int = 501, + database: Database = mainDatabase, + participant: ParticipantEntity? = null, + roundNumber: Int = 1 + ) { + val pt = + participant + ?: insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) var currentScore = startingScore darts.forEachIndexed { ix, drt -> - insertDart(pt, score = drt.score, multiplier = drt.multiplier, ordinal = ix+1, startingScore = currentScore, roundNumber = roundNumber, database = database) + insertDart( + pt, + score = drt.score, + multiplier = drt.multiplier, + ordinal = ix + 1, + startingScore = currentScore, + roundNumber = roundNumber, + database = database + ) currentScore -= drt.getTotal() } - } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01NoMercy.kt b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01NoMercy.kt index 5af6b002f..ba6863df9 100644 --- a/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01NoMercy.kt +++ b/src/test/kotlin/dartzee/achievements/x01/TestAchievementX01NoMercy.kt @@ -11,20 +11,27 @@ import dartzee.utils.Database import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementX01NoMercy: AbstractMultiRowAchievementTest() -{ +class TestAchievementX01NoMercy : AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementX01NoMercy() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { - val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, finalScore = 21, database = database) + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { + val pt = + insertParticipant( + playerId = p.rowId, + gameId = g.rowId, + finalScore = 21, + database = database + ) insertDart(pt, roundNumber = 7, startingScore = 7, ordinal = 1, database = database) } @Test - fun `Should include participants who were part of a team`() - { + fun `Should include participants who were part of a team`() { val pt = insertRelevantParticipant(team = true, finalScore = 21) val drt = insertDart(pt, roundNumber = 7, startingScore = 7, ordinal = 1) @@ -34,8 +41,7 @@ class TestAchievementX01NoMercy: AbstractMultiRowAchievementTest() -{ +class TestAchievementX01Shanghai : AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementX01Shanghai() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) - insertDart(pt, score = 20, multiplier = 2, ordinal = 1, startingScore = 400, database = database) - insertDart(pt, score = 20, multiplier = 3, ordinal = 2, startingScore = 360, database = database) - insertDart(pt, score = 20, multiplier = 1, ordinal = 3, startingScore = 300, database = database) + insertDart( + pt, + score = 20, + multiplier = 2, + ordinal = 1, + startingScore = 400, + database = database + ) + insertDart( + pt, + score = 20, + multiplier = 3, + ordinal = 2, + startingScore = 360, + database = database + ) + insertDart( + pt, + score = 20, + multiplier = 1, + ordinal = 3, + startingScore = 300, + database = database + ) } @Test - fun `Should count shanghais thrown when part of a team`() - { + fun `Should count shanghais thrown when part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, score = 20, multiplier = 3, ordinal = 1, startingScore = 400) @@ -38,8 +60,7 @@ class TestAchievementX01Shanghai: AbstractMultiRowAchievementTest() -{ +class TestAchievementX01StylishFinish : + AbstractMultiRowAchievementTest() { override fun factoryAchievement() = AchievementX01StylishFinish() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) val round = makeX01Round(101, 1, Dart(19, 3), Dart(4, 1), Dart(20, 2)) - round.forEach { - insertDart(pt, it, database = database) - } + round.forEach { insertDart(pt, it, database = database) } } @Test - fun `Should populate achievement row with correct details`() - { + fun `Should populate achievement row with correct details`() { val pt = insertParticipantAndDarts(101, Dart(20, 3), Dart(11, 1), Dart(15, 2)) runConversion() - val a = AchievementEntity.retrieveAchievement(AchievementType.X01_STYLISH_FINISH, pt.playerId)!! + val a = + AchievementEntity.retrieveAchievement(AchievementType.X01_STYLISH_FINISH, pt.playerId)!! a.achievementCounter shouldBe 101 a.achievementDetail shouldBe "T20, 11, D15" a.gameIdEarned shouldBe pt.gameId } @Test - fun `Should cope with two dart finishes`() - { + fun `Should cope with two dart finishes`() { val pt = insertParticipantAndDarts(55, Dart(5, 3), Dart(20, 2)) runConversion() - val a = AchievementEntity.retrieveAchievement(AchievementType.X01_STYLISH_FINISH, pt.playerId)!! + val a = + AchievementEntity.retrieveAchievement(AchievementType.X01_STYLISH_FINISH, pt.playerId)!! a.achievementCounter shouldBe 55 a.achievementDetail shouldBe "T5, D20" a.gameIdEarned shouldBe pt.gameId } @Test - fun `Should ignore single dart finishes`() - { + fun `Should ignore single dart finishes`() { insertParticipantAndDarts(40, Dart(20, 2)) runConversion() @@ -61,8 +61,7 @@ class TestAchievementX01StylishFinish : AbstractMultiRowAchievementTest() -{ +class TestAchievementX01SuchBadLuck : AbstractAchievementTest() { override fun factoryAchievement() = AchievementX01SuchBadLuck() - override fun setUpAchievementRowForPlayerAndGame(p: PlayerEntity, g: GameEntity, database: Database) - { + override fun setUpAchievementRowForPlayerAndGame( + p: PlayerEntity, + g: GameEntity, + database: Database + ) { val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId, database = database) - insertDart(pt, ordinal = 1, startingScore = 2, score = 20, multiplier = 2, database = database) + insertDart( + pt, + ordinal = 1, + startingScore = 2, + score = 20, + multiplier = 2, + database = database + ) } @Test - fun `Should include participants who were part of a team`() - { + fun `Should include participants who were part of a team`() { val pt = insertRelevantParticipant(team = true) insertDart(pt, ordinal = 1, startingScore = 2, score = 20, multiplier = 2) @@ -36,8 +44,7 @@ class TestAchievementX01SuchBadLuck: AbstractAchievementTest() -{ +class TestAchievementX01TeamGamesWon : + TestAbstractAchievementTeamGamesWon() { override fun factoryAchievement() = AchievementX01TeamGamesWon() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/DartsAiModelBenchmarkTest.kt b/src/test/kotlin/dartzee/ai/DartsAiModelBenchmarkTest.kt index 91a03a799..d38bb0eaa 100644 --- a/src/test/kotlin/dartzee/ai/DartsAiModelBenchmarkTest.kt +++ b/src/test/kotlin/dartzee/ai/DartsAiModelBenchmarkTest.kt @@ -6,22 +6,48 @@ import dartzee.helper.insertPlayer import dartzee.`object`.SegmentType import dartzee.screen.stats.median import io.kotest.matchers.doubles.shouldBeBetween +import java.awt.Dimension import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import java.awt.Dimension private const val SIMPLE_SIMULATION_TOLERANCE = 1.0 -class DartsAiModelBenchmarkTest : AbstractTest() -{ - private val alanPartridge = DartsAiModel(170.0, 160.0, 80.0, 129, 20, emptyMap(), 18, mapOf(1 to SegmentType.DOUBLE, 2 to SegmentType.DOUBLE, 3 to SegmentType.DOUBLE), mapOf(1 to 3, 2 to 4), DartzeePlayStyle.CAUTIOUS) +class DartsAiModelBenchmarkTest : AbstractTest() { + private val alanPartridge = + DartsAiModel( + 170.0, + 160.0, + 80.0, + 129, + 20, + emptyMap(), + 18, + mapOf(1 to SegmentType.DOUBLE, 2 to SegmentType.DOUBLE, 3 to SegmentType.DOUBLE), + mapOf(1 to 3, 2 to 4), + DartzeePlayStyle.CAUTIOUS + ) - private val bruceForsyth = DartsAiModel(90.0, 180.0, 90.0, 101, 20, emptyMap(), null, mapOf(1 to SegmentType.INNER_SINGLE, 2 to SegmentType.INNER_SINGLE, 3 to SegmentType.OUTER_SINGLE), mapOf(1 to 3, 2 to 4), DartzeePlayStyle.CAUTIOUS) + private val bruceForsyth = + DartsAiModel( + 90.0, + 180.0, + 90.0, + 101, + 20, + emptyMap(), + null, + mapOf( + 1 to SegmentType.INNER_SINGLE, + 2 to SegmentType.INNER_SINGLE, + 3 to SegmentType.OUTER_SINGLE + ), + mapOf(1 to 3, 2 to 4), + DartzeePlayStyle.CAUTIOUS + ) @Test @Tag("integration") - fun `Alan Partridge - Simple simulation`() - { + fun `Alan Partridge - Simple simulation`() { val dartboard = PresentationDartboard().also { it.size = Dimension(400, 400) } repeat(5) { @@ -35,8 +61,7 @@ class DartsAiModelBenchmarkTest : AbstractTest() @Test @Tag("integration") - fun `Alan Partridge - Full games`() - { + fun `Alan Partridge - Full games`() { val simulation = DartsSimulationX01(insertPlayer(), alanPartridge) val results = (1..5000).map { simulation.simulateGame(-it.toLong()).finalScore } @@ -46,8 +71,7 @@ class DartsAiModelBenchmarkTest : AbstractTest() @Test @Tag("integration") - fun `Bruce Forsyth - Simple simulation`() - { + fun `Bruce Forsyth - Simple simulation`() { val dartboard = PresentationDartboard().also { it.size = Dimension(400, 400) } repeat(5) { @@ -61,12 +85,11 @@ class DartsAiModelBenchmarkTest : AbstractTest() @Test @Tag("integration") - fun `Bruce Forsyth - Full games`() - { + fun `Bruce Forsyth - Full games`() { val simulation = DartsSimulationX01(insertPlayer(), bruceForsyth) val results = (1..5000).map { simulation.simulateGame(-it.toLong()).finalScore } results.average().shouldBeBetween(44.5, 45.0, SIMPLE_SIMULATION_TOLERANCE) results.median().shouldBeBetween(40.0, 40.0, SIMPLE_SIMULATION_TOLERANCE) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/TestAimDart.kt b/src/test/kotlin/dartzee/ai/TestAimDart.kt index 18323a1c9..e4f476b3c 100644 --- a/src/test/kotlin/dartzee/ai/TestAimDart.kt +++ b/src/test/kotlin/dartzee/ai/TestAimDart.kt @@ -1,18 +1,16 @@ package dartzee.ai -import dartzee.`object`.SegmentType import dartzee.helper.AbstractTest +import dartzee.`object`.SegmentType import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAimDart: AbstractTest() -{ +class TestAimDart : AbstractTest() { @Test - fun `Should report the right segment type to aim for`() - { + fun `Should report the right segment type to aim for`() { AimDart(1, 0).getSegmentType() shouldBe SegmentType.MISS AimDart(1, 1).getSegmentType() shouldBe SegmentType.OUTER_SINGLE AimDart(1, 2).getSegmentType() shouldBe SegmentType.DOUBLE AimDart(1, 3).getSegmentType() shouldBe SegmentType.TREBLE } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/TestDartsAiModel.kt b/src/test/kotlin/dartzee/ai/TestDartsAiModel.kt index d7a9b7389..ed2662866 100644 --- a/src/test/kotlin/dartzee/ai/TestDartsAiModel.kt +++ b/src/test/kotlin/dartzee/ai/TestDartsAiModel.kt @@ -17,22 +17,19 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.mockk.every import io.mockk.mockk -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.awt.Point import kotlin.math.floor +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestDartsAiModel: AbstractTest() -{ +class TestDartsAiModel : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { InjectedThings.dartzeeAimCalculator = DartzeeAimCalculator() } @Test - fun `Should serialize and deserialize with default values`() - { + fun `Should serialize and deserialize with default values`() { val model = DartsAiModel.new() val result = model.toJson() @@ -41,8 +38,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should serialize and deserialize with populated values`() - { + fun `Should serialize and deserialize with populated values`() { val model = makePopulatedAiModel() val result = model.toJson() @@ -51,18 +47,17 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should deserialize from static JSON`() - { + fun `Should deserialize from static JSON`() { val jsonString = javaClass.getResource("/aiModel.json")!!.readText() val model = DartsAiModel.fromJson(jsonString) model shouldBe makePopulatedAiModel() } - private fun makePopulatedAiModel(): DartsAiModel - { + private fun makePopulatedAiModel(): DartsAiModel { val setupDarts = mapOf(57 to AimDart(17, 1), 97 to AimDart(19, 3)) - val hmDartNoToSegmentType = mapOf(1 to SegmentType.TREBLE, 2 to SegmentType.TREBLE, 3 to SegmentType.OUTER_SINGLE) + val hmDartNoToSegmentType = + mapOf(1 to SegmentType.TREBLE, 2 to SegmentType.TREBLE, 3 to SegmentType.OUTER_SINGLE) val hmDartNoToThreshold = mapOf(1 to 2, 2 to 3) return DartsAiModel( 50.0, @@ -74,45 +69,39 @@ class TestDartsAiModel: AbstractTest() 17, hmDartNoToSegmentType, hmDartNoToThreshold, - DartzeePlayStyle.CAUTIOUS) + DartzeePlayStyle.CAUTIOUS + ) } - /** - * Verified against standard Normal Dist z-tables - */ + /** Verified against standard Normal Dist z-tables */ @Test - fun `Should return the correct density based on the standard deviation`() - { + fun `Should return the correct density based on the standard deviation`() { val model = makeDartsModel(standardDeviation = 20.0) - //P(within 0.5 SD) + // P(within 0.5 SD) model.getProbabilityWithinRadius(10.0)!!.shouldBeBetween(0.3829, 0.3831, 0.0) - //P(within 1 SD) + // P(within 1 SD) model.getProbabilityWithinRadius(20.0)!!.shouldBeBetween(0.6826, 0.6827, 0.0) - //P(within 2 SD) + // P(within 2 SD) model.getProbabilityWithinRadius(40.0)!!.shouldBeBetween(0.9543, 0.9545, 0.0) - //P(within 3 SD) + // P(within 3 SD) model.getProbabilityWithinRadius(60.0)!!.shouldBeBetween(0.9973, 0.9975, 0.0) } @Test - fun `Should return null density if maxOutlierRatio prevents darts going there`() - { + fun `Should return null density if maxOutlierRatio prevents darts going there`() { val model = makeDartsModel(standardDeviation = 3.0, maxRadius = 50) model.getProbabilityWithinRadius(51.0) shouldBe null model.getProbabilityWithinRadius(50.0) shouldNotBe null } - /** - * Actual sampling behaviour - */ + /** Actual sampling behaviour */ @Test - fun `Should use the double distribution if throwing at a double, and the regular distribution otherwise`() - { + fun `Should use the double distribution if throwing at a double, and the regular distribution otherwise`() { val model = beastDartsModel(standardDeviationDoubles = 100000.0, maxRadius = 1000) val pt = model.throwX01Dart(40) @@ -120,8 +109,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should revert to the regular distribution for doubles`() - { + fun `Should revert to the regular distribution for doubles`() { val model = beastDartsModel(standardDeviationDoubles = null) val pt = model.throwX01Dart(40) @@ -129,14 +117,12 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should generate a random angle between 0 - 360 by default`() - { + fun `Should generate a random angle between 0 - 360 by default`() { val model = makeDartsModel(standardDeviation = 3.0) val pt = Point(0, 0) val hsAngles = HashSet() - for (i in 0..100000) - { + for (i in 0..100000) { val (_, theta) = model.calculateRadiusAndAngle(pt) theta.shouldBeBetween(0.0, 360.0, 0.0) @@ -147,8 +133,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should not allow the radius to exceed the max outlier ratio`() - { + fun `Should not allow the radius to exceed the max outlier ratio`() { val pt = Point(0, 0) val model = makeDartsModel(standardDeviation = 50.0, maxRadius = 50) @@ -161,12 +146,12 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should just miss the board if told to deliberately miss`() - { + fun `Should just miss the board if told to deliberately miss`() { val erraticModel = makeDartsModel(standardDeviation = 100.0, maxRadius = 75) val mockDartzeeAimCalculator = mockk() - every { mockDartzeeAimCalculator.getPointToAimFor(any(), any(), any()) } returns DELIBERATE_MISS + every { mockDartzeeAimCalculator.getPointToAimFor(any(), any(), any()) } returns + DELIBERATE_MISS InjectedThings.dartzeeAimCalculator = mockDartzeeAimCalculator repeat(20) { @@ -175,12 +160,9 @@ class TestDartsAiModel: AbstractTest() } } - /** - * X01 test - */ + /** X01 test */ @Test - fun `Should aim for the overridden value if one is set for the current setup score`() - { + fun `Should aim for the overridden value if one is set for the current setup score`() { val model = beastDartsModel(hmScoreToDart = mapOf(77 to AimDart(17, 2))) val pt = model.throwX01Dart(77) @@ -188,8 +170,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should aim for the scoring dart when the score is over 60`() - { + fun `Should aim for the scoring dart when the score is over 60`() { val model = beastDartsModel(scoringDart = 18) val pt = model.throwX01Dart(61) @@ -197,8 +178,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should throw at inner bull if the scoring dart is 25`() - { + fun `Should throw at inner bull if the scoring dart is 25`() { val model = beastDartsModel(scoringDart = 25) val pt = model.throwX01Dart(501) @@ -206,20 +186,17 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should aim to reduce down to D20 when in the 41 - 60 range`() - { + fun `Should aim to reduce down to D20 when in the 41 - 60 range`() { val model = beastDartsModel(scoringDart = 25) - for (i in 41..60) - { + for (i in 41..60) { val pt = model.throwX01Dart(i) pt.segment shouldBe DartboardSegment(SegmentType.OUTER_SINGLE, i - 40) } } @Test - fun `Should aim to reduce to 32 when the score is less than 40`() - { + fun `Should aim to reduce to 32 when the score is less than 40`() { val model = beastDartsModel() val pt = model.throwX01Dart(37) @@ -227,8 +204,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should aim to reduce to 16 when the score is less than 32`() - { + fun `Should aim to reduce to 16 when the score is less than 32`() { val model = beastDartsModel() val pt = model.throwX01Dart(31) @@ -236,8 +212,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should aim to reduce to 8 when the score is less than 16`() - { + fun `Should aim to reduce to 8 when the score is less than 16`() { val model = beastDartsModel() val pt = model.throwX01Dart(15) @@ -245,8 +220,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should aim to reduce to 4 when the score is less than 8`() - { + fun `Should aim to reduce to 4 when the score is less than 8`() { val model = beastDartsModel() val pt = model.throwX01Dart(7) @@ -254,23 +228,19 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should aim for the double when on an even number`() - { + fun `Should aim for the double when on an even number`() { val model = beastDartsModel() - val scores = getCheckoutScores().filter{ it <= 40 } + val scores = getCheckoutScores().filter { it <= 40 } scores.forEach { val pt = model.throwX01Dart(it) - pt.segment shouldBe DartboardSegment(SegmentType.DOUBLE, it/2) + pt.segment shouldBe DartboardSegment(SegmentType.DOUBLE, it / 2) } } - /** - * Golf behaviour - */ + /** Golf behaviour */ @Test - fun `Should aim for double, treble, treble by default`() - { + fun `Should aim for double, treble, treble by default`() { val model = beastDartsModel() model.getSegmentTypeForDartNo(1) shouldBe SegmentType.DOUBLE model.getSegmentTypeForDartNo(2) shouldBe SegmentType.TREBLE @@ -287,9 +257,9 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should respect overridden targets per dart`() - { - val hmDartNoToSegmentType = mapOf(1 to SegmentType.TREBLE, 2 to SegmentType.OUTER_SINGLE, 3 to SegmentType.DOUBLE) + fun `Should respect overridden targets per dart`() { + val hmDartNoToSegmentType = + mapOf(1 to SegmentType.TREBLE, 2 to SegmentType.OUTER_SINGLE, 3 to SegmentType.DOUBLE) val model = beastDartsModel(hmDartNoToSegmentType = hmDartNoToSegmentType) val pt1 = model.throwGolfDart(1, 1) @@ -303,8 +273,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Stop thresholds should be 2 then 3 by default`() - { + fun `Stop thresholds should be 2 then 3 by default`() { val model = beastDartsModel() model.getStopThresholdForDartNo(1) shouldBe 2 @@ -312,8 +281,7 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Overridden stop thresholds should be adhered to`() - { + fun `Overridden stop thresholds should be adhered to`() { val hmDartNoToStopThreshold = mapOf(1 to 3, 2 to 4) val model = beastDartsModel(hmDartNoToStopThreshold = hmDartNoToStopThreshold) @@ -321,12 +289,9 @@ class TestDartsAiModel: AbstractTest() model.getStopThresholdForDartNo(2) shouldBe 4 } - /** - * Clock - */ + /** Clock */ @Test - fun `Should aim for the right segmentType and target number`() - { + fun `Should aim for the right segmentType and target number`() { val model = beastDartsModel() val pt1 = model.throwClockDart(1, ClockType.Standard) @@ -339,15 +304,16 @@ class TestDartsAiModel: AbstractTest() pt3.segment shouldBe DartboardSegment(SegmentType.TREBLE, 11) } - /** - * Dartzee - */ + /** Dartzee */ @Test - fun `Should aim aggressively if less than 2 darts thrown, and cautiously for the final one`() - { + fun `Should aim aggressively if less than 2 darts thrown, and cautiously for the final one`() { val model = beastDartsModel(dartzeePlayStyle = DartzeePlayStyle.CAUTIOUS) - val segmentStatuses = SegmentStatuses(listOf(DartboardSegment(SegmentType.TREBLE, 20)), getAllNonMissSegments()) + val segmentStatuses = + SegmentStatuses( + listOf(DartboardSegment(SegmentType.TREBLE, 20)), + getAllNonMissSegments() + ) val pt1 = model.throwDartzeeDart(0, segmentStatuses) pt1.segment shouldBe DartboardSegment(SegmentType.TREBLE, 20) @@ -359,11 +325,14 @@ class TestDartsAiModel: AbstractTest() } @Test - fun `Should throw aggressively for the final dart if player is aggressive`() - { + fun `Should throw aggressively for the final dart if player is aggressive`() { val model = beastDartsModel(dartzeePlayStyle = DartzeePlayStyle.AGGRESSIVE) - val segmentStatuses = SegmentStatuses(listOf(DartboardSegment(SegmentType.TREBLE, 20)), getAllNonMissSegments()) + val segmentStatuses = + SegmentStatuses( + listOf(DartboardSegment(SegmentType.TREBLE, 20)), + getAllNonMissSegments() + ) val pt1 = model.throwDartzeeDart(0, segmentStatuses) pt1.segment shouldBe DartboardSegment(SegmentType.TREBLE, 20) @@ -373,4 +342,4 @@ class TestDartsAiModel: AbstractTest() val pt3 = model.throwDartzeeDart(2, segmentStatuses) pt3.segment shouldBe DartboardSegment(SegmentType.TREBLE, 20) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/TestDartsAiSimulator.kt b/src/test/kotlin/dartzee/ai/TestDartsAiSimulator.kt index 53891e4a2..f9909516c 100644 --- a/src/test/kotlin/dartzee/ai/TestDartsAiSimulator.kt +++ b/src/test/kotlin/dartzee/ai/TestDartsAiSimulator.kt @@ -19,28 +19,28 @@ import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.slot -import org.junit.jupiter.api.Test import java.awt.Dimension +import org.junit.jupiter.api.Test -class TestDartsAiSimulator : AbstractTest() -{ +class TestDartsAiSimulator : AbstractTest() { @Test - fun `Should return expected values for deterministic AI`() - { + fun `Should return expected values for deterministic AI`() { val dartboard = PresentationDartboard().also { it.size = Dimension(100, 100) } - val scoringDarts = (1..200).map { drtMissTwenty() } + // 1% - (1..200).map { drtDoubleTwenty() } + // 1% - (1..12000).map { drtOuterTwenty() } + // 60% - (1..2000).map { drtTrebleTwenty() } + // 10% - (1..1000).map { drtOuterOne() } + // 5% - (1..1000).map { drtOuterFive() } + // 5% - (1..1000).map { drtTrebleOne() } + // 5% - (1..1000).map { drtTrebleFive() } + // 5% - (1..800).map { drtOuterTwelve() } + // 4% - (1..800).map { drtOuterEighteen() } // 4% + val scoringDarts = + (1..200).map { drtMissTwenty() } + // 1% + (1..200).map { drtDoubleTwenty() } + // 1% + (1..12000).map { drtOuterTwenty() } + // 60% + (1..2000).map { drtTrebleTwenty() } + // 10% + (1..1000).map { drtOuterOne() } + // 5% + (1..1000).map { drtOuterFive() } + // 5% + (1..1000).map { drtTrebleOne() } + // 5% + (1..1000).map { drtTrebleFive() } + // 5% + (1..800).map { drtOuterTwelve() } + // 4% + (1..800).map { drtOuterEighteen() } // 4% - val doubleSegmentTypes = (1..2000).map { SegmentType.DOUBLE } + // 10% + val doubleSegmentTypes = + (1..2000).map { SegmentType.DOUBLE } + // 10% (1..9000).map { SegmentType.MISS } + // 45% (1..9000).map { SegmentType.OUTER_SINGLE } // 45% @@ -53,11 +53,11 @@ class TestDartsAiSimulator : AbstractTest() result.averageDart shouldBe scoringDarts.map { it.getTotal() }.average() } - private fun mockDartsModel(scoringDarts: List, doubles: List): DartsAiModel - { + private fun mockDartsModel(scoringDarts: List, doubles: List): DartsAiModel { val model = mockk() every { model.scoringDart } returns 20 - every { model.calculateScoringPoint() } returns getComputedPointForScore(20, SegmentType.TREBLE) + every { model.calculateScoringPoint() } returns + getComputedPointForScore(20, SegmentType.TREBLE) val aimDarts = scoringDarts.map { it.toAimDart() }.shuffled() val throwDartFn = makeThrowDartFn(aimDarts) @@ -65,12 +65,14 @@ class TestDartsAiSimulator : AbstractTest() val shuffledSegmentTypes = doubles.shuffled().toMutableList() val doubleSlot = slot() - every { model.throwAtDouble(capture(doubleSlot)) } answers { - val score = doubleSlot.captured - val segmentType = shuffledSegmentTypes.removeFirst() - if (segmentType == SegmentType.MISS) AI_DARTBOARD.getDeliberateMissPoint() else getComputedPointForScore(score, segmentType) - } + every { model.throwAtDouble(capture(doubleSlot)) } answers + { + val score = doubleSlot.captured + val segmentType = shuffledSegmentTypes.removeFirst() + if (segmentType == SegmentType.MISS) AI_DARTBOARD.getDeliberateMissPoint() + else getComputedPointForScore(score, segmentType) + } return model } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/TestDartsSimulationGolf.kt b/src/test/kotlin/dartzee/ai/TestDartsSimulationGolf.kt index 996437a2a..f8db3883c 100644 --- a/src/test/kotlin/dartzee/ai/TestDartsSimulationGolf.kt +++ b/src/test/kotlin/dartzee/ai/TestDartsSimulationGolf.kt @@ -11,11 +11,9 @@ import io.kotest.matchers.collections.shouldContainInOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartsSimulationGolf: AbstractTest() -{ +class TestDartsSimulationGolf : AbstractTest() { @Test - fun `Should simulate a game correctly for a perfect player`() - { + fun `Should simulate a game correctly for a perfect player`() { val model = beastDartsModel() val player = insertPlayer(model = model) @@ -31,31 +29,34 @@ class TestDartsSimulationGolf: AbstractTest() } @Test - fun `Should pay attention to stop thresholds`() - { + fun `Should pay attention to stop thresholds`() { val player = insertPlayer() val hmDartNoToStopThreshold = mutableMapOf(1 to 2, 2 to 3) - val model = predictableGolfModel(hmDartNoToStopThreshold) { hole, _ -> - when - { - hole == 1 -> ScoreAndSegmentType(1, SegmentType.TREBLE) - hole == 2 -> ScoreAndSegmentType(2, SegmentType.INNER_SINGLE) - hole == 3 -> ScoreAndSegmentType(3, SegmentType.DOUBLE) - else -> ScoreAndSegmentType(hole, SegmentType.OUTER_SINGLE) + val model = + predictableGolfModel(hmDartNoToStopThreshold) { hole, _ -> + when { + hole == 1 -> ScoreAndSegmentType(1, SegmentType.TREBLE) + hole == 2 -> ScoreAndSegmentType(2, SegmentType.INNER_SINGLE) + hole == 3 -> ScoreAndSegmentType(3, SegmentType.DOUBLE) + else -> ScoreAndSegmentType(hole, SegmentType.OUTER_SINGLE) + } } - } val simulation = DartsSimulationGolf(player, model) val result = simulation.simulateGame(-1) - //2 + 3 + 1 + (15*4) + // 2 + 3 + 1 + (15*4) result.finalScore shouldBe 66 val darts = result.getAllDarts() darts.shouldContainInOrder( Dart(1, 3), - Dart(2, 1), Dart(2, 1), + Dart(2, 1), + Dart(2, 1), Dart(3, 2), - Dart(4, 1), Dart(4, 1), Dart(4, 1)) + Dart(4, 1), + Dart(4, 1), + Dart(4, 1) + ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/TestDartsSimulationX01.kt b/src/test/kotlin/dartzee/ai/TestDartsSimulationX01.kt index bbabc15d6..1f0dfe3ad 100644 --- a/src/test/kotlin/dartzee/ai/TestDartsSimulationX01.kt +++ b/src/test/kotlin/dartzee/ai/TestDartsSimulationX01.kt @@ -9,11 +9,9 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartsSimulationX01: AbstractTest() -{ +class TestDartsSimulationX01 : AbstractTest() { @Test - fun `Should simulate a game correctly for a perfect player`() - { + fun `Should simulate a game correctly for a perfect player`() { val model = beastDartsModel(hmScoreToDart = mapOf(81 to AimDart(19, 3))) val player = insertPlayer(model = model) @@ -23,25 +21,38 @@ class TestDartsSimulationX01: AbstractTest() result.finalScore shouldBe 9 val darts = result.getAllDarts() darts.shouldContainExactly( - Dart(20, 3), Dart(20, 3), Dart(20, 3), - Dart(20, 3), Dart(20, 3), Dart(20, 3), - Dart(20, 3), Dart(19, 3), Dart(12, 2)) + Dart(20, 3), + Dart(20, 3), + Dart(20, 3), + Dart(20, 3), + Dart(20, 3), + Dart(20, 3), + Dart(20, 3), + Dart(19, 3), + Dart(12, 2) + ) result.getCheckoutTotal() shouldBe 141 } @Test - fun `Should take into account mercy rule`() - { + fun `Should take into account mercy rule`() { val player = insertPlayer() - val aimDarts = listOf( - AimDart(20, 3), AimDart(20, 3), AimDart(20, 3), //321 - AimDart(20, 3), AimDart(20, 3), AimDart(20, 3), //141 - AimDart(20, 3), AimDart(20, 3), AimDart(18, 1), // 3 - AimDart(1, 1), // 2 (mercy) - AimDart(1, 2) // 0 - ) + val aimDarts = + listOf( + AimDart(20, 3), + AimDart(20, 3), + AimDart(20, 3), // 321 + AimDart(20, 3), + AimDart(20, 3), + AimDart(20, 3), // 141 + AimDart(20, 3), + AimDart(20, 3), + AimDart(18, 1), // 3 + AimDart(1, 1), // 2 (mercy) + AimDart(1, 2) // 0 + ) val model = predictableDartsModel(aimDarts, mercyThreshold = 7) @@ -51,21 +62,27 @@ class TestDartsSimulationX01: AbstractTest() } @Test - fun `Should take into account busts`() - { + fun `Should take into account busts`() { val player = insertPlayer() - val aimDarts = listOf( - AimDart(20, 3), AimDart(20, 3), AimDart(20, 3), //321 - AimDart(20, 3), AimDart(20, 3), AimDart(20, 3), //141 - AimDart(20, 3), AimDart(20, 3), AimDart(1, 1), // 20 - AimDart(15, 2), // 20 (bust) - AimDart(10, 2) // 0 - ) + val aimDarts = + listOf( + AimDart(20, 3), + AimDart(20, 3), + AimDart(20, 3), // 321 + AimDart(20, 3), + AimDart(20, 3), + AimDart(20, 3), // 141 + AimDart(20, 3), + AimDart(20, 3), + AimDart(1, 1), // 20 + AimDart(15, 2), // 20 (bust) + AimDart(10, 2) // 0 + ) val model = predictableDartsModel(aimDarts, mercyThreshold = 7) val simulation = DartsSimulationX01(player, model) val result = simulation.simulateGame(-1) result.finalScore shouldBe 13 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/TestSimulationRunner.kt b/src/test/kotlin/dartzee/ai/TestSimulationRunner.kt index 831eae6e2..56899c7f7 100644 --- a/src/test/kotlin/dartzee/ai/TestSimulationRunner.kt +++ b/src/test/kotlin/dartzee/ai/TestSimulationRunner.kt @@ -31,18 +31,16 @@ import io.kotest.matchers.shouldNotBe import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.util.concurrent.locks.ReentrantLock import javax.swing.JDialog import javax.swing.JFrame import javax.swing.JOptionPane import javax.swing.JProgressBar +import org.junit.jupiter.api.Test -class TestSimulationRunner : AbstractTest() -{ +class TestSimulationRunner : AbstractTest() { @Test - fun `Should handle an error being thrown from the simulation`() - { + fun `Should handle an error being thrown from the simulation`() { val simulation = mockk(relaxed = true) every { simulation.simulateGame(any()) } throws Exception("Something went wrong") @@ -51,24 +49,26 @@ class TestSimulationRunner : AbstractTest() waitForSimulation() verifyLog(CODE_SIMULATION_ERROR, Severity.ERROR) - dialogFactory.errorsShown.shouldContainExactly("A serious problem has occurred with the simulation.") + dialogFactory.errorsShown.shouldContainExactly( + "A serious problem has occurred with the simulation." + ) findResultsWindow() shouldBe null findWindow()!!.shouldNotBeVisible() } @Test - fun `Should show a progress dialog and allow cancelling`() - { + fun `Should show a progress dialog and allow cancelling`() { val lock = ReentrantLock(true) val blockingSimulation = mockk(relaxed = true) - every { blockingSimulation.simulateGame(any()) } answers { - try { - lock.lock() - makeGameWrapper() - } finally { - lock.unlock() + every { blockingSimulation.simulateGame(any()) } answers + { + try { + lock.lock() + makeGameWrapper() + } finally { + lock.unlock() + } } - } lock.lock() @@ -91,8 +91,7 @@ class TestSimulationRunner : AbstractTest() } @Test - fun `Should complete simulation and show results in a frame`() - { + fun `Should complete simulation and show results in a frame`() { val model = makeDartsModel() val player = insertPlayer(model = model, name = "Alyssa") val simulation = DartsSimulationX01(player, model) @@ -118,8 +117,7 @@ class TestSimulationRunner : AbstractTest() } @Test - fun `Should show results in a JDialog if told to be modal`() - { + fun `Should show results in a JDialog if told to be modal`() { val model = makeDartsModel() val player = insertPlayer(model = model, name = "Alyssa") val simulation = DartsSimulationX01(player, model) @@ -135,8 +133,7 @@ class TestSimulationRunner : AbstractTest() } @Test - fun `Should not prompt to save real entities in non-dev mode`() - { + fun `Should not prompt to save real entities in non-dev mode`() { val model = makeDartsModel() val player = insertPlayer(model = model, name = "Alyssa") val simulation = DartsSimulationX01(player, model) @@ -149,8 +146,7 @@ class TestSimulationRunner : AbstractTest() } @Test - fun `Should not save real entities if response is No`() - { + fun `Should not save real entities if response is No`() { DartsClient.devMode = true dialogFactory.questionOption = JOptionPane.NO_OPTION @@ -167,8 +163,7 @@ class TestSimulationRunner : AbstractTest() } @Test - fun `Should save real entities if response is Yes`() - { + fun `Should save real entities if response is Yes`() { DartsClient.devMode = true dialogFactory.questionOption = JOptionPane.YES_OPTION @@ -186,10 +181,12 @@ class TestSimulationRunner : AbstractTest() } private fun findResultsWindow() = findWindow { it.title.contains("Simulation Results") } - private fun findResultsDialog() = findWindow { it.title.contains("Simulation Results") } + + private fun findResultsDialog() = + findWindow { it.title.contains("Simulation Results") } private fun waitForSimulation(loggingCode: LoggingCode = CODE_SIMULATION_FINISHED) { waitForAssertion { findLog(loggingCode) shouldNotBe null } flushEdt() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/ai/TestStrategyUtils.kt b/src/test/kotlin/dartzee/ai/TestStrategyUtils.kt index 4da4e923f..c2a1d8f6a 100644 --- a/src/test/kotlin/dartzee/ai/TestStrategyUtils.kt +++ b/src/test/kotlin/dartzee/ai/TestStrategyUtils.kt @@ -9,12 +9,10 @@ import dartzee.`object`.SegmentType import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestStrategyUtils: AbstractTest() -{ +class TestStrategyUtils : AbstractTest() { @Test @Tag("screenshot") - fun `Should aim at the average point for the relevant segment`() - { + fun `Should aim at the average point for the relevant segment`() { val t20 = getPointForScore(AimDart(20, 3)) val outerEleven = getPointForScore(11, SegmentType.OUTER_SINGLE) @@ -23,4 +21,4 @@ class TestStrategyUtils: AbstractTest() val lbl = presentationDartboard.markPoints(listOf(t20, outerEleven)) lbl.shouldMatchImage("centerPoints") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestAbstractDartzeeRuleSelector.kt b/src/test/kotlin/dartzee/bean/TestAbstractDartzeeRuleSelector.kt index 419997535..24f05ad28 100644 --- a/src/test/kotlin/dartzee/bean/TestAbstractDartzeeRuleSelector.kt +++ b/src/test/kotlin/dartzee/bean/TestAbstractDartzeeRuleSelector.kt @@ -16,19 +16,16 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.Test -class TestAbstractDartzeeRuleSelector: AbstractTest() -{ +class TestAbstractDartzeeRuleSelector : AbstractTest() { @Test - fun `Should render the description passed to it`() - { + fun `Should render the description passed to it`() { val selector = FakeDartzeeRuleSelector("foo") selector.lblDesc.text shouldBe "foo" selector.cbDesc.text shouldBe "foo" } @Test - fun `Should initialise with the options specified`() - { + fun `Should initialise with the options specified`() { val selector = FakeDartzeeRuleSelector("foo") val items = selector.comboBoxRuleType.items() @@ -39,8 +36,7 @@ class TestAbstractDartzeeRuleSelector: AbstractTest() } @Test - fun `Should show an error if the rule is invalid`() - { + fun `Should show an error if the rule is invalid`() { val selector = FakeDartzeeRuleSelector("foo") selector.populate(DartzeeDartRuleColour()) @@ -49,8 +45,7 @@ class TestAbstractDartzeeRuleSelector: AbstractTest() } @Test - fun `Should pass validation if the rule is valid`() - { + fun `Should pass validation if the rule is valid`() { val selector = FakeDartzeeRuleSelector("foo") selector.populate(DartzeeDartRuleEven()) @@ -59,16 +54,14 @@ class TestAbstractDartzeeRuleSelector: AbstractTest() } @Test - fun `Should populate from an existing rule successfully`() - { + fun `Should populate from an existing rule successfully`() { val selector = DartzeeDartRuleSelector("foo") selector.populate(DartzeeDartRuleInner()) selector.getSelection().shouldBeInstanceOf() } @Test - fun `Should populate a rule's configPanel successfully`() - { + fun `Should populate a rule's configPanel successfully`() { val selector = DartzeeDartRuleSelector("foo") val rule = DartzeeDartRuleColour() rule.black = true @@ -84,8 +77,7 @@ class TestAbstractDartzeeRuleSelector: AbstractTest() } @Test - fun `Should swap in and out the configPanel based on the selected rule`() - { + fun `Should swap in and out the configPanel based on the selected rule`() { val selector = FakeDartzeeRuleSelector("foo") val comboBox = selector.comboBoxRuleType @@ -100,9 +92,8 @@ class TestAbstractDartzeeRuleSelector: AbstractTest() configPanel.parent shouldBe null } - private class FakeDartzeeRuleSelector(desc: String): AbstractDartzeeRuleSelector(desc) - { + private class FakeDartzeeRuleSelector(desc: String) : + AbstractDartzeeRuleSelector(desc) { override fun getRules() = getAllDartRules() - } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestAchievementMedal.kt b/src/test/kotlin/dartzee/bean/TestAchievementMedal.kt index 820bb97c6..e3c17dbdf 100644 --- a/src/test/kotlin/dartzee/bean/TestAchievementMedal.kt +++ b/src/test/kotlin/dartzee/bean/TestAchievementMedal.kt @@ -17,19 +17,17 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Tag -import org.junit.jupiter.api.Test import java.awt.Cursor import javax.swing.JButton import javax.swing.JLabel import javax.swing.table.DefaultTableModel +import org.junit.jupiter.api.Tag +import org.junit.jupiter.api.Test -class TestAchievementMedal: AbstractTest() -{ +class TestAchievementMedal : AbstractTest() { @Test @Tag("screenshot") - fun `Should match snapshot - locked`() - { + fun `Should match snapshot - locked`() { val achievement = makeAchievement(-1) val medal = AchievementMedal(achievement) medal.shouldMatchImage("locked") @@ -37,8 +35,7 @@ class TestAchievementMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - red`() - { + fun `Should match snapshot - red`() { val achievement = makeAchievement(AchievementX01BestThreeDarts().redThreshold) val medal = AchievementMedal(achievement) medal.shouldMatchImage("red") @@ -46,8 +43,7 @@ class TestAchievementMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - orange`() - { + fun `Should match snapshot - orange`() { val achievement = makeAchievement(AchievementX01BestThreeDarts().orangeThreshold) val medal = AchievementMedal(achievement) medal.shouldMatchImage("orange") @@ -55,8 +51,7 @@ class TestAchievementMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - yellow`() - { + fun `Should match snapshot - yellow`() { val achievement = makeAchievement(AchievementX01BestThreeDarts().yellowThreshold) val medal = AchievementMedal(achievement) medal.shouldMatchImage("yellow") @@ -64,8 +59,7 @@ class TestAchievementMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - green`() - { + fun `Should match snapshot - green`() { val achievement = makeAchievement(AchievementX01BestThreeDarts().greenThreshold) val medal = AchievementMedal(achievement) medal.shouldMatchImage("green") @@ -73,8 +67,7 @@ class TestAchievementMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - blue`() - { + fun `Should match snapshot - blue`() { val achievement = makeAchievement(AchievementX01BestThreeDarts().blueThreshold) val medal = AchievementMedal(achievement) medal.shouldMatchImage("blue") @@ -82,16 +75,14 @@ class TestAchievementMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - pink`() - { + fun `Should match snapshot - pink`() { val achievement = makeAchievement(AchievementX01BestThreeDarts().pinkThreshold) val medal = AchievementMedal(achievement) medal.shouldMatchImage("pink") } @Test - fun `Should update cursor and description for hover if enabled and clickable`() - { + fun `Should update cursor and description for hover if enabled and clickable`() { val scrn = ScreenCache.switchToAchievementsScreen(insertPlayer()) val achievement = makeAchievement(30) @@ -105,8 +96,7 @@ class TestAchievementMedal: AbstractTest() } @Test - fun `Should not update cursor for hover if not clickable`() - { + fun `Should not update cursor for hover if not clickable`() { val scrn = ScreenCache.switchToAchievementsScreen(insertPlayer()) val achievement = makeAchievement(30) @@ -118,8 +108,7 @@ class TestAchievementMedal: AbstractTest() } @Test - fun `Should not update for hover if outside the circle`() - { + fun `Should not update for hover if outside the circle`() { val achievement = makeAchievement(30) achievement.gameIdEarned = "foo" val medal = AchievementMedal(achievement) @@ -129,8 +118,7 @@ class TestAchievementMedal: AbstractTest() } @Test - fun `Should show the achievement breakdown on click if it has one`() - { + fun `Should show the achievement breakdown on click if it has one`() { val scrn = ScreenCache.switchToAchievementsScreen(insertPlayer()) val achievement = makeAchievement(30) @@ -148,8 +136,7 @@ class TestAchievementMedal: AbstractTest() } @Test - fun `Should launch the relevant game if it has one`() - { + fun `Should launch the relevant game if it has one`() { val launcher = mockk(relaxed = true) InjectedThings.gameLauncher = launcher @@ -162,5 +149,6 @@ class TestAchievementMedal: AbstractTest() verify { launcher.loadAndDisplayGame("some-game") } } - private fun makeAchievement(attainedValue: Int = -1) = AchievementX01BestThreeDarts().also { it.attainedValue = attainedValue } -} \ No newline at end of file + private fun makeAchievement(attainedValue: Int = -1) = + AchievementX01BestThreeDarts().also { it.attainedValue = attainedValue } +} diff --git a/src/test/kotlin/dartzee/bean/TestAchievmentUnlockedMedal.kt b/src/test/kotlin/dartzee/bean/TestAchievmentUnlockedMedal.kt index 7f1d358e7..27a2ecb2b 100644 --- a/src/test/kotlin/dartzee/bean/TestAchievmentUnlockedMedal.kt +++ b/src/test/kotlin/dartzee/bean/TestAchievmentUnlockedMedal.kt @@ -6,12 +6,10 @@ import dartzee.helper.AbstractTest import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestAchievmentUnlockedMedal: AbstractTest() -{ +class TestAchievmentUnlockedMedal : AbstractTest() { @Test @Tag("screenshot") - fun `Should match snapshot - red`() - { + fun `Should match snapshot - red`() { val achievement = makeAchievement(AchievementX01HotelInspector().redThreshold) val medal = AchievementUnlockedMedal(achievement) medal.shouldMatchImage("red") @@ -19,8 +17,7 @@ class TestAchievmentUnlockedMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - orange`() - { + fun `Should match snapshot - orange`() { val achievement = makeAchievement(AchievementX01HotelInspector().orangeThreshold) val medal = AchievementUnlockedMedal(achievement) medal.shouldMatchImage("orange") @@ -28,8 +25,7 @@ class TestAchievmentUnlockedMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - yellow`() - { + fun `Should match snapshot - yellow`() { val achievement = makeAchievement(AchievementX01HotelInspector().yellowThreshold) val medal = AchievementUnlockedMedal(achievement) medal.shouldMatchImage("yellow") @@ -37,8 +33,7 @@ class TestAchievmentUnlockedMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - green`() - { + fun `Should match snapshot - green`() { val achievement = makeAchievement(AchievementX01HotelInspector().greenThreshold) val medal = AchievementUnlockedMedal(achievement) medal.shouldMatchImage("green") @@ -46,8 +41,7 @@ class TestAchievmentUnlockedMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - blue`() - { + fun `Should match snapshot - blue`() { val achievement = makeAchievement(AchievementX01HotelInspector().blueThreshold) val medal = AchievementUnlockedMedal(achievement) medal.shouldMatchImage("blue") @@ -55,12 +49,12 @@ class TestAchievmentUnlockedMedal: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - pink`() - { + fun `Should match snapshot - pink`() { val achievement = makeAchievement(AchievementX01HotelInspector().pinkThreshold) val medal = AchievementUnlockedMedal(achievement) medal.shouldMatchImage("pink") } - private fun makeAchievement(attainedValue: Int = -1) = AchievementX01HotelInspector().also { it.attainedValue = attainedValue } -} \ No newline at end of file + private fun makeAchievement(attainedValue: Int = -1) = + AchievementX01HotelInspector().also { it.attainedValue = attainedValue } +} diff --git a/src/test/kotlin/dartzee/bean/TestDartzeeAggregateRuleSelector.kt b/src/test/kotlin/dartzee/bean/TestDartzeeAggregateRuleSelector.kt index c1e93288a..e8e564d1d 100644 --- a/src/test/kotlin/dartzee/bean/TestDartzeeAggregateRuleSelector.kt +++ b/src/test/kotlin/dartzee/bean/TestDartzeeAggregateRuleSelector.kt @@ -1,25 +1,22 @@ package dartzee.bean -import dartzee.dartzee.getAllAggregateRules import dartzee.dartzee.aggregate.DartzeeTotalRuleEqualTo +import dartzee.dartzee.getAllAggregateRules import dartzee.helper.AbstractTest import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.collections.shouldNotContain import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeAggregateRuleSelector : AbstractTest() -{ +class TestDartzeeAggregateRuleSelector : AbstractTest() { @Test - fun `Should initialise with all the total rules`() - { + fun `Should initialise with all the total rules`() { val selector = DartzeeAggregateRuleSelector("") selector.getRules().size shouldBe getAllAggregateRules().size } @Test - fun `Should be optional`() - { + fun `Should be optional`() { val selector = DartzeeAggregateRuleSelector("") selector.isOptional() shouldBe true val children = selector.components.toList() @@ -34,8 +31,7 @@ class TestDartzeeAggregateRuleSelector : AbstractTest() } @Test - fun `Should enable or disable all children`() - { + fun `Should enable or disable all children`() { val selector = DartzeeAggregateRuleSelector("") selector.populate(DartzeeTotalRuleEqualTo()) @@ -53,4 +49,4 @@ class TestDartzeeAggregateRuleSelector : AbstractTest() populatedRule.configPanel.isEnabled shouldBe true populatedRule.spinner.isEnabled shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestDartzeeDartRuleSelector.kt b/src/test/kotlin/dartzee/bean/TestDartzeeDartRuleSelector.kt index 3bb338afd..8021c2091 100644 --- a/src/test/kotlin/dartzee/bean/TestDartzeeDartRuleSelector.kt +++ b/src/test/kotlin/dartzee/bean/TestDartzeeDartRuleSelector.kt @@ -7,18 +7,15 @@ import io.kotest.matchers.collections.shouldNotContain import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleSelector : AbstractTest() -{ +class TestDartzeeDartRuleSelector : AbstractTest() { @Test - fun `Should initialise with all the dart rules`() - { + fun `Should initialise with all the dart rules`() { val selector = DartzeeDartRuleSelector("") selector.getRules().size shouldBe getAllDartRules().size } @Test - fun `Should not be optional`() - { + fun `Should not be optional`() { val selector = DartzeeDartRuleSelector("") selector.isOptional() shouldBe false selector.shouldBeEnabled() shouldBe true @@ -27,4 +24,4 @@ class TestDartzeeDartRuleSelector : AbstractTest() children.shouldContain(selector.lblDesc) children.shouldNotContain(selector.cbDesc) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestFileUploader.kt b/src/test/kotlin/dartzee/bean/TestFileUploader.kt index 2ceda636c..2054ad0c7 100644 --- a/src/test/kotlin/dartzee/bean/TestFileUploader.kt +++ b/src/test/kotlin/dartzee/bean/TestFileUploader.kt @@ -14,18 +14,16 @@ import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.io.File import javax.swing.JButton import javax.swing.JComboBox import javax.swing.JTextField import javax.swing.filechooser.FileNameExtensionFilter +import org.junit.jupiter.api.Test -class TestFileUploader : AbstractTest() -{ +class TestFileUploader : AbstractTest() { @Test - fun `Should error if upload is pressed with no file`() - { + fun `Should error if upload is pressed with no file`() { val uploader = FileUploader(FileNameExtensionFilter("all", "*")) val listener = makeFileListener(true) uploader.addFileUploadListener(listener) @@ -36,8 +34,7 @@ class TestFileUploader : AbstractTest() } @Test - fun `Should not pick a file if cancelled`() - { + fun `Should not pick a file if cancelled`() { val uploader = FileUploader(FileNameExtensionFilter("all", "*")) val listener = makeFileListener(true) uploader.addFileUploadListener(listener) @@ -52,8 +49,7 @@ class TestFileUploader : AbstractTest() } @Test - fun `Should be able to upload a file`() - { + fun `Should be able to upload a file`() { val rsrc = javaClass.getResource("/outer-wilds.jpeg")!! val path = rsrc.path @@ -67,8 +63,7 @@ class TestFileUploader : AbstractTest() } @Test - fun `Should not clear text if file listener reports failure`() - { + fun `Should not clear text if file listener reports failure`() { val rsrc = javaClass.getResource("/outer-wilds.jpeg")!! val path = rsrc.path @@ -82,8 +77,7 @@ class TestFileUploader : AbstractTest() } @Test - fun `Should respect the file filter passed in`() - { + fun `Should respect the file filter passed in`() { val filter = FileNameExtensionFilter("all", "*") val uploader = FileUploader(filter) val listener = makeFileListener(false) @@ -92,7 +86,10 @@ class TestFileUploader : AbstractTest() uploader.clickChild(text = "...", async = true) val chooserDialog = getFileChooser() - val combo = chooserDialog.getChild> { it.selectedItem is FileNameExtensionFilter } + val combo = + chooserDialog.getChild> { + it.selectedItem is FileNameExtensionFilter + } combo.selectedItem.shouldBe(filter) combo.itemCount shouldBe 1 } @@ -102,4 +99,4 @@ class TestFileUploader : AbstractTest() every { listener.fileUploaded(any()) } returns success return listener } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelDartzee.kt b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelDartzee.kt index 41ef7e00b..1b3b079dd 100644 --- a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelDartzee.kt +++ b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelDartzee.kt @@ -11,25 +11,25 @@ import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.event.ActionListener +import org.junit.jupiter.api.Test -class TestGameParamFilterPanelDartzee: AbstractTest() -{ +class TestGameParamFilterPanelDartzee : AbstractTest() { @Test - fun `Should populate empty if there are no templates set up`() - { + fun `Should populate empty if there are no templates set up`() { val panel = GameParamFilterPanelDartzee() - panel.getOptions().shouldContainExactly( - ComboBoxItem(null, "Custom"), - ComboBoxItem(null, "-----", false), - ComboBoxItem(null, "No templates configured", false)) + panel + .getOptions() + .shouldContainExactly( + ComboBoxItem(null, "Custom"), + ComboBoxItem(null, "-----", false), + ComboBoxItem(null, "No templates configured", false) + ) } @Test - fun `Should always return empty gameParams if there are no templates set up`() - { + fun `Should always return empty gameParams if there are no templates set up`() { val panel = GameParamFilterPanelDartzee() panel.comboBox.selectedIndex = 0 @@ -46,23 +46,20 @@ class TestGameParamFilterPanelDartzee: AbstractTest() } @Test - fun `Should add templates below the divider if they exist`() - { + fun `Should add templates below the divider if they exist`() { insertDartzeeTemplate(name = "Template A") insertDartzeeTemplate(name = "Template B") val panel = GameParamFilterPanelDartzee() - panel.getOptions().map { it.visibleData }.shouldContainExactly( - "Custom", - "-----", - "Template A", - "Template B") + panel + .getOptions() + .map { it.visibleData } + .shouldContainExactly("Custom", "-----", "Template A", "Template B") } @Test - fun `Selecting a template should populate its ID as the game params`() - { + fun `Selecting a template should populate its ID as the game params`() { val templateId = insertDartzeeTemplate(name = "Template A").rowId val panel = GameParamFilterPanelDartzee() @@ -73,8 +70,7 @@ class TestGameParamFilterPanelDartzee: AbstractTest() } @Test - fun `Should support setting the selection by gameParams`() - { + fun `Should support setting the selection by gameParams`() { val templateId = insertDartzeeTemplate(name = "Some Template").rowId val panel = GameParamFilterPanelDartzee() @@ -86,8 +82,7 @@ class TestGameParamFilterPanelDartzee: AbstractTest() } @Test - fun `Should enable and disable its comboBox correctly`() - { + fun `Should enable and disable its comboBox correctly`() { val panel = GameParamFilterPanelDartzee() panel.enableChildren(false) @@ -98,8 +93,7 @@ class TestGameParamFilterPanelDartzee: AbstractTest() } @Test - fun `Should add and remove action listeners on the combo box`() - { + fun `Should add and remove action listeners on the combo box`() { val panel = GameParamFilterPanelDartzee() val listener = mockk(relaxed = true) @@ -117,6 +111,5 @@ class TestGameParamFilterPanelDartzee: AbstractTest() verifyNotCalled { listener.actionPerformed(any()) } } - private fun GameParamFilterPanelDartzee.getOptions() = comboBox.items() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelGolf.kt b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelGolf.kt index 6750cf0a2..b59b51274 100644 --- a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelGolf.kt +++ b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelGolf.kt @@ -6,22 +6,19 @@ import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.event.ActionListener +import org.junit.jupiter.api.Test -class TestGameParamFilterPanelGolf: AbstractTest() -{ +class TestGameParamFilterPanelGolf : AbstractTest() { @Test - fun `Should select 18 holes by default`() - { + fun `Should select 18 holes by default`() { val panel = GameParamFilterPanelGolf() panel.rdbtn18.isSelected shouldBe true } @Test - fun `Should return game params based on the radio selection`() - { + fun `Should return game params based on the radio selection`() { val panel = GameParamFilterPanelGolf() panel.rdbtn9.doClick() @@ -34,8 +31,7 @@ class TestGameParamFilterPanelGolf: AbstractTest() } @Test - fun `Should support setting the selection by gameParams`() - { + fun `Should support setting the selection by gameParams`() { val panel = GameParamFilterPanelGolf() panel.setGameParams("9") @@ -46,8 +42,7 @@ class TestGameParamFilterPanelGolf: AbstractTest() } @Test - fun `Should enable and disable its radio buttons correctly`() - { + fun `Should enable and disable its radio buttons correctly`() { val panel = GameParamFilterPanelGolf() panel.enableChildren(false) @@ -60,8 +55,7 @@ class TestGameParamFilterPanelGolf: AbstractTest() } @Test - fun `Should add and remove action listeners on the radio button panel`() - { + fun `Should add and remove action listeners on the radio button panel`() { val panel = GameParamFilterPanelGolf() val listener = mockk(relaxed = true) @@ -78,4 +72,4 @@ class TestGameParamFilterPanelGolf: AbstractTest() verifyNotCalled { listener.actionPerformed(any()) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelRoundTheClock.kt b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelRoundTheClock.kt index 10b1c5dc3..d925213b5 100644 --- a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelRoundTheClock.kt +++ b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelRoundTheClock.kt @@ -12,16 +12,14 @@ import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.event.ActionListener import javax.swing.JCheckBox import javax.swing.JRadioButton +import org.junit.jupiter.api.Test -class TestGameParamFilterPanelRoundTheClock: AbstractTest() -{ +class TestGameParamFilterPanelRoundTheClock : AbstractTest() { @Test - fun `Should select the correct defaults`() - { + fun `Should select the correct defaults`() { val panel = GameParamFilterPanelRoundTheClock() panel.getChild(text = "Standard").isSelected shouldBe true @@ -29,8 +27,7 @@ class TestGameParamFilterPanelRoundTheClock: AbstractTest() } @Test - fun `Should return game params based on the radio & checkbox selection`() - { + fun `Should return game params based on the radio & checkbox selection`() { val panel = GameParamFilterPanelRoundTheClock() panel.clickChild(text = "Standard") @@ -48,8 +45,7 @@ class TestGameParamFilterPanelRoundTheClock: AbstractTest() } @Test - fun `Should support setting the selection by gameParams`() - { + fun `Should support setting the selection by gameParams`() { val panel = GameParamFilterPanelRoundTheClock() val doublesInOrder = RoundTheClockConfig(ClockType.Doubles, true) @@ -69,8 +65,7 @@ class TestGameParamFilterPanelRoundTheClock: AbstractTest() } @Test - fun `Should enable and disable its children correctly`() - { + fun `Should enable and disable its children correctly`() { val panel = GameParamFilterPanelRoundTheClock() panel.enableChildren(false) @@ -87,8 +82,7 @@ class TestGameParamFilterPanelRoundTheClock: AbstractTest() } @Test - fun `Should add and remove action listeners on the radio button panel`() - { + fun `Should add and remove action listeners on the radio button panel`() { val panel = GameParamFilterPanelRoundTheClock() val listener = mockk(relaxed = true) @@ -107,8 +101,7 @@ class TestGameParamFilterPanelRoundTheClock: AbstractTest() } @Test - fun `Should add and remove action listeners on the checkbox`() - { + fun `Should add and remove action listeners on the checkbox`() { val panel = GameParamFilterPanelRoundTheClock() val listener = mockk(relaxed = true) @@ -126,5 +119,6 @@ class TestGameParamFilterPanelRoundTheClock: AbstractTest() verifyNotCalled { listener.actionPerformed(any()) } } - private fun GameParamFilterPanelRoundTheClock.getConfig() = RoundTheClockConfig.fromJson(getGameParams()) -} \ No newline at end of file + private fun GameParamFilterPanelRoundTheClock.getConfig() = + RoundTheClockConfig.fromJson(getGameParams()) +} diff --git a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelX01.kt b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelX01.kt index e778f5529..4d16c2044 100644 --- a/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelX01.kt +++ b/src/test/kotlin/dartzee/bean/TestGameParamFilterPanelX01.kt @@ -6,14 +6,12 @@ import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.event.ActionListener +import org.junit.jupiter.api.Test -class TestGameParamFilterPanelX01: AbstractTest() -{ +class TestGameParamFilterPanelX01 : AbstractTest() { @Test - fun `Should return game params based on the spinner selection`() - { + fun `Should return game params based on the spinner selection`() { val panel = GameParamFilterPanelX01() panel.spinner.value = 701 @@ -26,8 +24,7 @@ class TestGameParamFilterPanelX01: AbstractTest() } @Test - fun `Should support setting the selection by gameParams`() - { + fun `Should support setting the selection by gameParams`() { val panel = GameParamFilterPanelX01() panel.setGameParams("701") @@ -35,8 +32,7 @@ class TestGameParamFilterPanelX01: AbstractTest() } @Test - fun `Should enable and disable its spinner correctly`() - { + fun `Should enable and disable its spinner correctly`() { val panel = GameParamFilterPanelX01() panel.enableChildren(false) @@ -47,8 +43,7 @@ class TestGameParamFilterPanelX01: AbstractTest() } @Test - fun `Should add and remove action listeners on the combo box`() - { + fun `Should add and remove action listeners on the combo box`() { val panel = GameParamFilterPanelX01() val listener = mockk(relaxed = true) @@ -65,4 +60,4 @@ class TestGameParamFilterPanelX01: AbstractTest() verifyNotCalled { listener.actionPerformed(any()) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestGameSetupPlayerSelector.kt b/src/test/kotlin/dartzee/bean/TestGameSetupPlayerSelector.kt index 20fbebf11..ca107475f 100644 --- a/src/test/kotlin/dartzee/bean/TestGameSetupPlayerSelector.kt +++ b/src/test/kotlin/dartzee/bean/TestGameSetupPlayerSelector.kt @@ -8,14 +8,12 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JToggleButton +import org.junit.jupiter.api.Test -class TestGameSetupPlayerSelector: AbstractTest() -{ +class TestGameSetupPlayerSelector : AbstractTest() { @Test - fun `Should always be invalid if 0 players selected`() - { + fun `Should always be invalid if 0 players selected`() { val selector = GameSetupPlayerSelector() selector.init() @@ -26,8 +24,7 @@ class TestGameSetupPlayerSelector: AbstractTest() } @Test - fun `Should be valid for 1 player if not a match`() - { + fun `Should be valid for 1 player if not a match`() { val alex = insertPlayer() val selector = GameSetupPlayerSelector() @@ -38,20 +35,20 @@ class TestGameSetupPlayerSelector: AbstractTest() } @Test - fun `Should be invalid for a match of 1 player`() - { + fun `Should be invalid for a match of 1 player`() { val alex = insertPlayer() val selector = GameSetupPlayerSelector() selector.init(listOf(alex)) selector.valid(true) shouldBe false - dialogFactory.errorsShown.shouldContainExactly("You must select at least 2 players for a match.") + dialogFactory.errorsShown.shouldContainExactly( + "You must select at least 2 players for a match." + ) } @Test - fun `Should be invalid for a match of 1 team`() - { + fun `Should be invalid for a match of 1 team`() { val alyssa = insertPlayer() val alex = insertPlayer() val selector = GameSetupPlayerSelector() @@ -59,18 +56,18 @@ class TestGameSetupPlayerSelector: AbstractTest() selector.clickChild() selector.valid(true) shouldBe false - dialogFactory.errorsShown.shouldContainExactly("You must select at least 2 teams for a match.") + dialogFactory.errorsShown.shouldContainExactly( + "You must select at least 2 teams for a match." + ) } @Test - fun `Should always be valid for up to 6 players`() - { + fun `Should always be valid for up to 6 players`() { val p1 = insertPlayer() val p2 = insertPlayer() val players = mutableListOf(p1, p2) - while (players.size <= 6) - { + while (players.size <= 6) { val selector = GameSetupPlayerSelector() selector.init(players) @@ -84,11 +81,9 @@ class TestGameSetupPlayerSelector: AbstractTest() } @Test - fun `Should always be valid for up to 12 players in team play`() - { + fun `Should always be valid for up to 12 players in team play`() { val players = mutableListOf(insertPlayer(), insertPlayer(), insertPlayer(), insertPlayer()) - while (players.size <= 12) - { + while (players.size <= 12) { val selector = GameSetupPlayerSelector() selector.init(players) selector.clickChild() @@ -103,10 +98,11 @@ class TestGameSetupPlayerSelector: AbstractTest() } @Test - fun `Should not allow more than 6 players`() - { + fun `Should not allow more than 6 players`() { val players = mutableListOf() - while (players.size <= 7) { players.add(insertPlayer()) } + while (players.size <= 7) { + players.add(insertPlayer()) + } val selector = GameSetupPlayerSelector() selector.init(players) @@ -120,8 +116,7 @@ class TestGameSetupPlayerSelector: AbstractTest() } @Test - fun `Should not allow more than 12 players in team play`() - { + fun `Should not allow more than 12 players in team play`() { val players = mutableListOf() repeat(13) { players.add(insertPlayer()) } @@ -138,8 +133,7 @@ class TestGameSetupPlayerSelector: AbstractTest() } @Test - fun `Should correctly report whether pair mode is active`() - { + fun `Should correctly report whether pair mode is active`() { val selector = GameSetupPlayerSelector() selector.pairMode() shouldBe false @@ -149,4 +143,4 @@ class TestGameSetupPlayerSelector: AbstractTest() selector.clickChild() selector.pairMode() shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestInteractiveDartboard.kt b/src/test/kotlin/dartzee/bean/TestInteractiveDartboard.kt index 6b2e92818..438f4da90 100644 --- a/src/test/kotlin/dartzee/bean/TestInteractiveDartboard.kt +++ b/src/test/kotlin/dartzee/bean/TestInteractiveDartboard.kt @@ -8,16 +8,14 @@ import dartzee.`object`.SegmentType import dartzee.screen.game.SegmentStatuses import dartzee.utils.getAllNonMissSegments import dartzee.utils.getAllSegmentsForDartzee +import java.awt.Point import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import java.awt.Point -class TestInteractiveDartboard : AbstractTest() -{ +class TestInteractiveDartboard : AbstractTest() { @Test @Tag("screenshot") - fun `Should match snapshot - hovered`() - { + fun `Should match snapshot - hovered`() { val dartboard = InteractiveDartboard(DEFAULT_COLOUR_WRAPPER) dartboard.setBounds(0, 0, 400, 400) @@ -30,12 +28,12 @@ class TestInteractiveDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should support disabling and reenabling interaction`() - { + fun `Should support disabling and reenabling interaction`() { val dartboard = InteractiveDartboard(DEFAULT_COLOUR_WRAPPER) dartboard.setBounds(0, 0, 400, 400) - val pt = dartboard.getPointsForSegment(DartboardSegment(SegmentType.OUTER_SINGLE, 1)).first() + val pt = + dartboard.getPointsForSegment(DartboardSegment(SegmentType.OUTER_SINGLE, 1)).first() dartboard.highlightDartboard(pt) dartboard.stopInteraction() dartboard.highlightDartboard(pt) @@ -48,8 +46,7 @@ class TestInteractiveDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Hovering should interact correctly with segment statuses`() - { + fun `Hovering should interact correctly with segment statuses`() { val scoringSegments = getAllNonMissSegments().filter { it.getTotal() >= 20 } val validSegments = getAllNonMissSegments().filter { it.getTotal() >= 10 } val segmentStatuses = SegmentStatuses(scoringSegments, validSegments) @@ -77,8 +74,7 @@ class TestInteractiveDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Hovering should toggle the outer dartboard if it is a valid segment`() - { + fun `Hovering should toggle the outer dartboard if it is a valid segment`() { val scoringSegments = getAllNonMissSegments().filter { it.score % 2 == 1 } val validSegments = getAllSegmentsForDartzee() val segmentStatuses = SegmentStatuses(scoringSegments, validSegments) @@ -94,9 +90,8 @@ class TestInteractiveDartboard : AbstractTest() dartboard.shouldMatchImage("hover-nothing") } - private fun InteractiveDartboard.hoverSegment(segment: DartboardSegment) - { + private fun InteractiveDartboard.hoverSegment(segment: DartboardSegment) { val pt = getPointsForSegment(segment).first() highlightDartboard(pt) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestParticipantAvatar.kt b/src/test/kotlin/dartzee/bean/TestParticipantAvatar.kt index a6b265ae2..9c909c502 100644 --- a/src/test/kotlin/dartzee/bean/TestParticipantAvatar.kt +++ b/src/test/kotlin/dartzee/bean/TestParticipantAvatar.kt @@ -10,12 +10,10 @@ import dartzee.screen.game.makeTeam import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestParticipantAvatar : AbstractTest() -{ +class TestParticipantAvatar : AbstractTest() { @Test @Tag("screenshot") - fun `Should default to the split avatar, and update accordingly based on round number`() - { + fun `Should default to the split avatar, and update accordingly based on round number`() { val playerOneImage = insertPlayerImage(resource = "yoshi") val playerOne = insertPlayer(playerImageId = playerOneImage.rowId) @@ -41,8 +39,7 @@ class TestParticipantAvatar : AbstractTest() @Test @Tag("screenshot") - fun `Should correct avatar for a single participant`() - { + fun `Should correct avatar for a single participant`() { val singlePt = SingleParticipant(insertParticipant()) val avatar = ParticipantAvatar(singlePt) @@ -55,4 +52,4 @@ class TestParticipantAvatar : AbstractTest() avatar.setSelected(selected = false, 1, gameFinished = false) avatar.shouldMatchImage("single-unselected") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestPlayerAvatar.kt b/src/test/kotlin/dartzee/bean/TestPlayerAvatar.kt index dcb1f75e9..be7cf10fb 100644 --- a/src/test/kotlin/dartzee/bean/TestPlayerAvatar.kt +++ b/src/test/kotlin/dartzee/bean/TestPlayerAvatar.kt @@ -14,16 +14,14 @@ import dartzee.helper.insertPlayerImage import dartzee.screen.PlayerImageDialog import dartzee.selectImage import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Cursor import javax.swing.Icon import javax.swing.ImageIcon +import org.junit.jupiter.api.Test -class TestPlayerAvatar: AbstractTest() -{ +class TestPlayerAvatar : AbstractTest() { @Test - fun `Should update on click if not read-only`() - { + fun `Should update on click if not read-only`() { val image = insertPlayerImage("wage") val avatar = PlayerAvatar() @@ -38,8 +36,7 @@ class TestPlayerAvatar: AbstractTest() } @Test - fun `Should not clear current selection if image selection is cancelled`() - { + fun `Should not clear current selection if image selection is cancelled`() { val image = insertPlayerImage("wage") val otherImage = insertPlayerImage("dibble") val p = insertPlayer(playerImageId = image.rowId) @@ -57,8 +54,7 @@ class TestPlayerAvatar: AbstractTest() } @Test - fun `Should auto-update the player entity if saveChanges is set`() - { + fun `Should auto-update the player entity if saveChanges is set`() { val oldImage = insertPlayerImage("wage") val newImage = insertPlayerImage("dibble") @@ -80,8 +76,7 @@ class TestPlayerAvatar: AbstractTest() } @Test - fun `Should not update the player if saveChanges is false`() - { + fun `Should not update the player if saveChanges is false`() { val oldImage = insertPlayerImage("wage") val newImage = insertPlayerImage("dibble") @@ -96,7 +91,7 @@ class TestPlayerAvatar: AbstractTest() window.clickOk() avatar.icon.shouldMatchAvatar("dibble") - avatar.avatarId shouldBe newImage.rowId //Should still update the UI + avatar.avatarId shouldBe newImage.rowId // Should still update the UI player.playerImageId shouldBe oldImage.rowId val reretrievedPlayer = PlayerEntity().retrieveForId(player.rowId)!! @@ -104,8 +99,7 @@ class TestPlayerAvatar: AbstractTest() } @Test - fun `Should do nothing on click in read-only mode`() - { + fun `Should do nothing on click in read-only mode`() { val avatar = PlayerAvatar() avatar.readOnly = true avatar.doClick() @@ -114,16 +108,14 @@ class TestPlayerAvatar: AbstractTest() } @Test - fun `Should default to an unset avatar when initialised with a new player`() - { + fun `Should default to an unset avatar when initialised with a new player`() { val avatar = PlayerAvatar() avatar.init(PlayerEntity(), false) avatar.icon.shouldMatchAvatar("Unset") } @Test - fun `Should update cursor on hover`() - { + fun `Should update cursor on hover`() { val avatar = PlayerAvatar() avatar.cursor shouldBe Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) @@ -135,8 +127,7 @@ class TestPlayerAvatar: AbstractTest() } @Test - fun `Should not respond to hover if read only`() - { + fun `Should not respond to hover if read only`() { val avatar = PlayerAvatar() avatar.readOnly = true avatar.cursor shouldBe Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) @@ -148,9 +139,9 @@ class TestPlayerAvatar: AbstractTest() avatar.cursor shouldBe Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR) } - private fun Icon.shouldMatchAvatar(avatarName: String) - { - val expected = ImageIcon(TestPlayerAvatar::class.java.getResource("/avatars/$avatarName.png")) + private fun Icon.shouldMatchAvatar(avatarName: String) { + val expected = + ImageIcon(TestPlayerAvatar::class.java.getResource("/avatars/$avatarName.png")) shouldMatch(expected) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestPlayerImageRadio.kt b/src/test/kotlin/dartzee/bean/TestPlayerImageRadio.kt index 7b58361e0..0008fb24a 100644 --- a/src/test/kotlin/dartzee/bean/TestPlayerImageRadio.kt +++ b/src/test/kotlin/dartzee/bean/TestPlayerImageRadio.kt @@ -7,16 +7,14 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.Test import javax.swing.ButtonGroup import javax.swing.border.EmptyBorder import javax.swing.border.LineBorder +import org.junit.jupiter.api.Test -class TestPlayerImageRadio: AbstractTest() -{ +class TestPlayerImageRadio : AbstractTest() { @Test - fun `Should pull through the image and ID from the PlayerImageEntity`() - { + fun `Should pull through the image and ID from the PlayerImageEntity`() { val entity = PlayerImageEntity() entity.assignRowId() entity.blobData = getBlobValue("Dennis") @@ -29,8 +27,7 @@ class TestPlayerImageRadio: AbstractTest() } @Test - fun `Should update selection status when image is clicked`() - { + fun `Should update selection status when image is clicked`() { val radio = makePlayerImageRadio() radio.isSelected() shouldBe false @@ -39,8 +36,7 @@ class TestPlayerImageRadio: AbstractTest() } @Test - fun `Should update selection when radio button is clicked`() - { + fun `Should update selection when radio button is clicked`() { val radio = makePlayerImageRadio() radio.isSelected() shouldBe false @@ -49,8 +45,7 @@ class TestPlayerImageRadio: AbstractTest() } @Test - fun `Should function as part of a button group`() - { + fun `Should function as part of a button group`() { val r1 = makePlayerImageRadio() val r2 = makePlayerImageRadio() @@ -70,8 +65,7 @@ class TestPlayerImageRadio: AbstractTest() } @Test - fun `Should have the right border based on state`() - { + fun `Should have the right border based on state`() { val r = makePlayerImageRadio() r.border.shouldBeInstanceOf() @@ -80,8 +74,7 @@ class TestPlayerImageRadio: AbstractTest() r.border.shouldBeInstanceOf() } - private fun makePlayerImageRadio(): PlayerImageRadio - { + private fun makePlayerImageRadio(): PlayerImageRadio { val entity = PlayerImageEntity() entity.assignRowId() entity.blobData = getBlobValue("Dennis") @@ -89,4 +82,4 @@ class TestPlayerImageRadio: AbstractTest() return PlayerImageRadio(entity) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestPlayerSelector.kt b/src/test/kotlin/dartzee/bean/TestPlayerSelector.kt index acaeb34d1..e0b3df29f 100644 --- a/src/test/kotlin/dartzee/bean/TestPlayerSelector.kt +++ b/src/test/kotlin/dartzee/bean/TestPlayerSelector.kt @@ -8,15 +8,13 @@ import dartzee.helper.insertPlayer import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.event.KeyEvent import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestPlayerSelector: AbstractTest() -{ +class TestPlayerSelector : AbstractTest() { @Test - fun `Should start with no players selected`() - { + fun `Should start with no players selected`() { insertPlayer(name = "Alex") val selector = PlayerSelector() @@ -28,8 +26,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should return all selected players to unselected on init`() - { + fun `Should return all selected players to unselected on init`() { val alex = insertPlayer(name = "Alex") val selector = PlayerSelector() @@ -41,8 +38,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should do nothing if the select button is clicked with no selection`() - { + fun `Should do nothing if the select button is clicked with no selection`() { insertPlayer() val selector = PlayerSelector() @@ -53,8 +49,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should move the selected player across when the select button is clicked`() - { + fun `Should move the selected player across when the select button is clicked`() { insertPlayer(name = "Alex") insertPlayer(name = "Bob") insertPlayer(name = "Clive") @@ -70,8 +65,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should maintain selection in tables as players are moved`() - { + fun `Should maintain selection in tables as players are moved`() { insertPlayer(name = "Alex") insertPlayer(name = "Bob") insertPlayer(name = "Clive") @@ -96,8 +90,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should initialise with the selected players passed in`() - { + fun `Should initialise with the selected players passed in`() { val alex = insertPlayer(name = "Alex") insertPlayer(name = "Bob") val clive = insertPlayer(name = "Clive") @@ -110,8 +103,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should do nothing if the deselect button is clicked with no selection`() - { + fun `Should do nothing if the deselect button is clicked with no selection`() { val alex = insertPlayer(name = "Alex") insertPlayer(name = "Bob") insertPlayer(name = "Clive") @@ -125,8 +117,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should move the selected player back when deselect button is clicked`() - { + fun `Should move the selected player back when deselect button is clicked`() { val alex = insertPlayer(name = "Alex") val bob = insertPlayer(name = "Bob") val clive = insertPlayer(name = "Clive") @@ -141,8 +132,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should select players when Enter is pressed`() - { + fun `Should select players when Enter is pressed`() { insertPlayer("Alex") val selector = PlayerSelector() @@ -157,8 +147,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should deselect players when Enter is pressed`() - { + fun `Should deselect players when Enter is pressed`() { val alex = insertPlayer("Alex") val selector = PlayerSelector() @@ -173,8 +162,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should select players on double-click`() - { + fun `Should select players on double-click`() { insertPlayer("Alex") val selector = PlayerSelector() @@ -186,8 +174,7 @@ class TestPlayerSelector: AbstractTest() } @Test - fun `Should deselect players on double-click`() - { + fun `Should deselect players on double-click`() { val alex = insertPlayer("Alex") val selector = PlayerSelector() @@ -199,8 +186,9 @@ class TestPlayerSelector: AbstractTest() } private fun PlayerSelector.clickSelect() = clickChild("Select") + private fun PlayerSelector.clickUnselect() = clickChild("Unselect") private fun getPlayerNamesToSelectFrom(selector: PlayerSelector) = selector.tablePlayersToSelectFrom.getAllPlayers().map { it.name } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestPlayerTypeFilterPanel.kt b/src/test/kotlin/dartzee/bean/TestPlayerTypeFilterPanel.kt index 5f6b02367..6382a64b2 100644 --- a/src/test/kotlin/dartzee/bean/TestPlayerTypeFilterPanel.kt +++ b/src/test/kotlin/dartzee/bean/TestPlayerTypeFilterPanel.kt @@ -3,23 +3,20 @@ package dartzee.bean import dartzee.db.PlayerEntity import dartzee.helper.AbstractTest import dartzee.helper.insertPlayer -import io.kotest.matchers.string.shouldBeEmpty import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldBeEmpty import org.junit.jupiter.api.Test -class TestPlayerTypeFilterPanel: AbstractTest() -{ +class TestPlayerTypeFilterPanel : AbstractTest() { @Test - fun `Should have All selected by default`() - { + fun `Should have All selected by default`() { val panel = PlayerTypeFilterPanel() panel.rdbtnAll.isSelected shouldBe true panel.getWhereSql().shouldBeEmpty() } @Test - fun `Should return correct filter SQL for humans and AIs`() - { + fun `Should return correct filter SQL for humans and AIs`() { val ai = insertPlayer(strategy = "foo") val human = insertPlayer(strategy = "") @@ -38,4 +35,4 @@ class TestPlayerTypeFilterPanel: AbstractTest() humanPlayers.size shouldBe 1 humanPlayers.first().rowId shouldBe human.rowId } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestPresentationDartboard.kt b/src/test/kotlin/dartzee/bean/TestPresentationDartboard.kt index 954ba85bc..58e9ff3ee 100644 --- a/src/test/kotlin/dartzee/bean/TestPresentationDartboard.kt +++ b/src/test/kotlin/dartzee/bean/TestPresentationDartboard.kt @@ -13,17 +13,15 @@ import dartzee.`object`.WIREFRAME_COLOUR_WRAPPER import dartzee.screen.game.SegmentStatuses import dartzee.utils.getAllNonMissSegments import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Tag -import org.junit.jupiter.api.Test import java.awt.Color import java.awt.Dimension import java.awt.Point +import org.junit.jupiter.api.Tag +import org.junit.jupiter.api.Test -class TestPresentationDartboard : AbstractTest() -{ +class TestPresentationDartboard : AbstractTest() { @Test - fun `Should preserve the segment type when mapping between dartboards`() - { + fun `Should preserve the segment type when mapping between dartboards`() { val computationalDartboard = ComputationalDartboard(200, 200) val smallDartboard = PresentationDartboard().also { it.size = Dimension(100, 100) } val bigDartboard = PresentationDartboard().also { it.size = Dimension(400, 400) } @@ -40,8 +38,7 @@ class TestPresentationDartboard : AbstractTest() } @Test - fun `Should rationalise points to within the bounds of the dartboard`() - { + fun `Should rationalise points to within the bounds of the dartboard`() { val computationalDartboard = ComputationalDartboard(400, 400) val wildPoint = computationalDartboard.toComputedPoint(Point(1000, 1000)) @@ -52,8 +49,7 @@ class TestPresentationDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - default`() - { + fun `Should match snapshot - default`() { val dartboard = PresentationDartboard(DEFAULT_COLOUR_WRAPPER) dartboard.setBounds(0, 0, 400, 400) dartboard.shouldMatchImage("default") @@ -61,8 +57,7 @@ class TestPresentationDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - with numbers`() - { + fun `Should match snapshot - with numbers`() { val dartboard = PresentationDartboard(DEFAULT_COLOUR_WRAPPER, renderScoreLabels = true) dartboard.setBounds(0, 0, 500, 500) dartboard.shouldMatchImage("scores") @@ -70,8 +65,7 @@ class TestPresentationDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - wireframe`() - { + fun `Should match snapshot - wireframe`() { val dartboard = PresentationDartboard(WIREFRAME_COLOUR_WRAPPER) dartboard.setBounds(0, 0, 250, 250) dartboard.shouldMatchImage("wireframe") @@ -79,13 +73,18 @@ class TestPresentationDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - custom colours`() - { - val colourWrapper = ColourWrapper( - Color.PINK.darker(), Color.PINK, Color.PINK, - Color.YELLOW.brighter(), Color.YELLOW.darker(), Color.YELLOW.darker(), - Color.PINK, Color.YELLOW.darker() - ) + fun `Should match snapshot - custom colours`() { + val colourWrapper = + ColourWrapper( + Color.PINK.darker(), + Color.PINK, + Color.PINK, + Color.YELLOW.brighter(), + Color.YELLOW.darker(), + Color.YELLOW.darker(), + Color.PINK, + Color.YELLOW.darker() + ) val dartboard = PresentationDartboard(colourWrapper) dartboard.setBounds(0, 0, 400, 400) @@ -94,8 +93,7 @@ class TestPresentationDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should respect overridden segments and retain them on resize`() - { + fun `Should respect overridden segments and retain them on resize`() { val segment = DartboardSegment(SegmentType.OUTER_SINGLE, 11) val dartboard = PresentationDartboard(DEFAULT_COLOUR_WRAPPER) @@ -112,8 +110,7 @@ class TestPresentationDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should draw edges with segment statuses set`() - { + fun `Should draw edges with segment statuses set`() { val dartboard = PresentationDartboard(DEFAULT_COLOUR_WRAPPER) dartboard.setBounds(0, 0, 400, 400) dartboard.updateSegmentStatus(makeSegmentStatuses()) @@ -123,8 +120,7 @@ class TestPresentationDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should respect segment statuses`() - { + fun `Should respect segment statuses`() { val dartboard = PresentationDartboard(DEFAULT_COLOUR_WRAPPER) dartboard.setBounds(0, 0, 600, 600) @@ -134,4 +130,4 @@ class TestPresentationDartboard : AbstractTest() dartboard.updateSegmentStatus(SegmentStatuses(scoringSegments, validSegments)) dartboard.shouldMatchImage("segment-statuses") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestScrollTableAchievements.kt b/src/test/kotlin/dartzee/bean/TestScrollTableAchievements.kt index 43b6ef545..c755c9f41 100644 --- a/src/test/kotlin/dartzee/bean/TestScrollTableAchievements.kt +++ b/src/test/kotlin/dartzee/bean/TestScrollTableAchievements.kt @@ -9,11 +9,9 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.Test -class TestScrollTableAchievements: AbstractTest() -{ +class TestScrollTableAchievements : AbstractTest() { @Test - fun `Should switch to the player achievements screen on click`() - { + fun `Should switch to the player achievements screen on click`() { val startingScreen = LeaderboardsScreen() ScreenCache.switch(startingScreen) @@ -27,4 +25,4 @@ class TestScrollTableAchievements: AbstractTest() scrn.shouldBeInstanceOf() scrn.player shouldBe player } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestScrollTableOrdered.kt b/src/test/kotlin/dartzee/bean/TestScrollTableOrdered.kt index 611d18504..f237a9f4e 100644 --- a/src/test/kotlin/dartzee/bean/TestScrollTableOrdered.kt +++ b/src/test/kotlin/dartzee/bean/TestScrollTableOrdered.kt @@ -10,22 +10,19 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.spyk import io.mockk.verify +import javax.swing.JButton import net.miginfocom.swing.MigLayout import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import javax.swing.JButton -class TestScrollTableOrdered: AbstractTest() -{ +class TestScrollTableOrdered : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { InjectedCore.collectionShuffler = CollectionShuffler() } @Test - fun `should move rows up`() - { + fun `should move rows up`() { val scrollTable = setupTable() scrollTable.selectRow(2) @@ -38,8 +35,7 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `Should do nothing if trying to move the first row up`() - { + fun `Should do nothing if trying to move the first row up`() { val scrollTable = setupTable() scrollTable.selectRow(0) @@ -49,8 +45,7 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `should move rows down`() - { + fun `should move rows down`() { val scrollTable = setupTable() scrollTable.selectRow(0) @@ -63,8 +58,7 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `Should do nothing if trying to move last row down`() - { + fun `Should do nothing if trying to move last row down`() { val scrollTable = setupTable() scrollTable.selectRow(2) @@ -74,8 +68,7 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `Should do nothing if trying to move a row with no selection`() - { + fun `Should do nothing if trying to move a row with no selection`() { val scrollTable = setupTable() scrollTable.btnMoveUp.doClick() @@ -86,8 +79,7 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `Should support programatically sorting the rows by something`() - { + fun `Should support programatically sorting the rows by something`() { val table = ScrollTableOrdered() val tm = TableUtil.DefaultModel() tm.addColumn("Value") @@ -100,7 +92,6 @@ class TestScrollTableOrdered: AbstractTest() val c3 = TestRow("C", 3) val d1 = TestRow("D", 1) - table.addRow(arrayOf(a4)) table.addRow(arrayOf(c3)) table.addRow(arrayOf(d1)) @@ -114,15 +105,13 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `Should grab all the rows`() - { + fun `Should grab all the rows`() { val table = setupTable() table.getRowValues().shouldContainExactly("A", "B", "C") } @Test - fun `Should scramble the row order`() - { + fun `Should scramble the row order`() { val mockShuffler = spyk() InjectedCore.collectionShuffler = mockShuffler @@ -135,8 +124,7 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `Should not offset the standard buttons by default`() - { + fun `Should not offset the standard buttons by default`() { val table = ScrollTableOrdered() table.getButtonConstraints(table.btnMoveUp) shouldBe "cell 0 0" table.getButtonConstraints(table.btnMoveDown) shouldBe "cell 0 1" @@ -144,8 +132,7 @@ class TestScrollTableOrdered: AbstractTest() } @Test - fun `Should offset standard buttons and support adding custom ones`() - { + fun `Should offset standard buttons and support adding custom ones`() { val table = ScrollTableOrdered(1) table.getButtonConstraints(table.btnMoveUp) shouldBe "cell 0 1" table.getButtonConstraints(table.btnMoveDown) shouldBe "cell 0 2" @@ -156,16 +143,14 @@ class TestScrollTableOrdered: AbstractTest() table.getButtonConstraints(newBtn) shouldBe "cell 0 0" } - private fun ScrollTableOrdered.getButtonConstraints(btn: JButton): Any - { + private fun ScrollTableOrdered.getButtonConstraints(btn: JButton): Any { val layoutManager = panelOrdering.layout as MigLayout return layoutManager.getComponentConstraints(btn) } private fun ScrollTableOrdered.getRowValues(): List = getAllRows().map { it[0] } - private fun setupTable(): ScrollTableOrdered - { + private fun setupTable(): ScrollTableOrdered { val table = ScrollTableOrdered() val tm = TableUtil.DefaultModel() tm.addColumn("Value") @@ -177,4 +162,4 @@ class TestScrollTableOrdered: AbstractTest() return table } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestScrollTablePlayers.kt b/src/test/kotlin/dartzee/bean/TestScrollTablePlayers.kt index 89e159e7b..6e1426ef1 100644 --- a/src/test/kotlin/dartzee/bean/TestScrollTablePlayers.kt +++ b/src/test/kotlin/dartzee/bean/TestScrollTablePlayers.kt @@ -6,14 +6,12 @@ import dartzee.helper.AbstractTest import dartzee.helper.insertPlayer import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.ListSelectionModel +import org.junit.jupiter.api.Test -class TestScrollTablePlayers: AbstractTest() -{ +class TestScrollTablePlayers : AbstractTest() { @Test - fun `Should initialise correctly`() - { + fun `Should initialise correctly`() { val table = ScrollTable() val bob = insertPlayer(name = "Bob", strategy = "") @@ -21,7 +19,6 @@ class TestScrollTablePlayers: AbstractTest() val players = listOf(bob, robot) table.initPlayerTableModel(players) - table.getColumnName(0) shouldBe "" table.getColumnName(1) shouldBe "Player" table.rowCount shouldBe 2 @@ -34,22 +31,28 @@ class TestScrollTablePlayers: AbstractTest() } @Test - fun `Should return all players correctly`() - { + fun `Should return all players correctly`() { val table = ScrollTable() - val players = listOf(insertPlayer(name = "Bob", strategy = ""), insertPlayer(name = "Robot", strategy = "foo")) + val players = + listOf( + insertPlayer(name = "Bob", strategy = ""), + insertPlayer(name = "Robot", strategy = "foo") + ) table.initPlayerTableModel(players) table.getAllPlayers() shouldBe players } @Test - fun `Should return null and empty list if no selection`() - { + fun `Should return null and empty list if no selection`() { val table = ScrollTable() - val players = listOf(insertPlayer(name = "Bob", strategy = ""), insertPlayer(name = "Robot", strategy = "foo")) + val players = + listOf( + insertPlayer(name = "Bob", strategy = ""), + insertPlayer(name = "Robot", strategy = "foo") + ) table.initPlayerTableModel(players) table.getSelectedPlayer() shouldBe null @@ -57,8 +60,7 @@ class TestScrollTablePlayers: AbstractTest() } @Test - fun `Should return the selected player`() - { + fun `Should return the selected player`() { val table = ScrollTable() val playerTwo = insertPlayer(name = "Robot", strategy = "foo") @@ -73,8 +75,7 @@ class TestScrollTablePlayers: AbstractTest() } @Test - fun `Should return all the selected players`() - { + fun `Should return all the selected players`() { val table = ScrollTable() val playerOne = insertPlayer(name = "Alice") @@ -89,8 +90,7 @@ class TestScrollTablePlayers: AbstractTest() } @Test - fun `Should sort by name by default`() - { + fun `Should sort by name by default`() { val table = ScrollTable() val playerOne = insertPlayer(name = "Alice") @@ -103,8 +103,7 @@ class TestScrollTablePlayers: AbstractTest() } @Test - fun `Should be able to add players dynamically`() - { + fun `Should be able to add players dynamically`() { val table = ScrollTable() val playerOne = insertPlayer(name = "Alice") @@ -117,9 +116,7 @@ class TestScrollTablePlayers: AbstractTest() table.getAllPlayers() shouldBe listOf(playerOne, playerTwo, playerThree) } - private fun ScrollTable.selectRows(first: Int, last: Int) - { + private fun ScrollTable.selectRows(first: Int, last: Int) { table.setRowSelectionInterval(first, last) } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestSliderAiSpeed.kt b/src/test/kotlin/dartzee/bean/TestSliderAiSpeed.kt index fc881e408..35823802d 100644 --- a/src/test/kotlin/dartzee/bean/TestSliderAiSpeed.kt +++ b/src/test/kotlin/dartzee/bean/TestSliderAiSpeed.kt @@ -3,18 +3,16 @@ package dartzee.bean import com.github.alyssaburlton.swingtest.getChild import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JSlider +import org.junit.jupiter.api.Test -class TestSliderAiSpeed: AbstractTest() -{ +class TestSliderAiSpeed : AbstractTest() { @Test - fun `Should initialise with the correct slider bounds`() - { + fun `Should initialise with the correct slider bounds`() { val aiSlider = SliderAiSpeed() val actualSlider = aiSlider.getChild() actualSlider.maximum shouldBe AI_SPEED_MAXIMUM actualSlider.minimum shouldBe AI_SPEED_MINIMUM actualSlider.inverted shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestSpinnerSingleSelector.kt b/src/test/kotlin/dartzee/bean/TestSpinnerSingleSelector.kt index 90dc83eb6..fd57cf430 100644 --- a/src/test/kotlin/dartzee/bean/TestSpinnerSingleSelector.kt +++ b/src/test/kotlin/dartzee/bean/TestSpinnerSingleSelector.kt @@ -4,11 +4,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSpinnerSingleSelector: AbstractTest() -{ +class TestSpinnerSingleSelector : AbstractTest() { @Test - fun `Should not be able to select 21-24`() - { + fun `Should not be able to select 21-24`() { val spinner = SpinnerSingleSelector() spinner.value = 21 @@ -23,4 +21,4 @@ class TestSpinnerSingleSelector: AbstractTest() spinner.value = 24 spinner.value shouldBe 20 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestSpinnerX01.kt b/src/test/kotlin/dartzee/bean/TestSpinnerX01.kt index 4fd6af042..42f78e487 100644 --- a/src/test/kotlin/dartzee/bean/TestSpinnerX01.kt +++ b/src/test/kotlin/dartzee/bean/TestSpinnerX01.kt @@ -4,25 +4,21 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSpinnerX01: AbstractTest() -{ +class TestSpinnerX01 : AbstractTest() { @Test - fun `It should default to 501`() - { + fun `It should default to 501`() { val spinner = SpinnerX01() spinner.value shouldBe 501 } @Test - fun `It should increment in multiples of 100`() - { + fun `It should increment in multiples of 100`() { val spinner = SpinnerX01() spinner.model.nextValue shouldBe 601 } @Test - fun `It should range from 101 to 701`() - { + fun `It should range from 101 to 701`() { val spinner = SpinnerX01() spinner.value = 701 @@ -33,8 +29,7 @@ class TestSpinnerX01: AbstractTest() } @Test - fun `It should reset to 501 if an invalid value is entered`() - { + fun `It should reset to 501 if an invalid value is entered`() { val spinner = SpinnerX01() spinner.value = 301 @@ -43,4 +38,4 @@ class TestSpinnerX01: AbstractTest() spinner.value = 200 spinner.value shouldBe 501 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestTableModelEntity.kt b/src/test/kotlin/dartzee/bean/TestTableModelEntity.kt index 0c59161ae..a6424ffd5 100644 --- a/src/test/kotlin/dartzee/bean/TestTableModelEntity.kt +++ b/src/test/kotlin/dartzee/bean/TestTableModelEntity.kt @@ -6,38 +6,34 @@ import io.kotest.matchers.collections.shouldBeOneOf import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestTableModelEntity: AbstractTest() -{ +class TestTableModelEntity : AbstractTest() { @Test - fun `Should have precisely the same column names and types as on the table`() - { - DartsDatabaseUtil.getAllEntitiesIncludingVersion().forEach{ + fun `Should have precisely the same column names and types as on the table`() { + DartsDatabaseUtil.getAllEntitiesIncludingVersion().forEach { val tm = TableModelEntity(listOf(it)) val entityCols = it.getColumns() - for (i in 0 until tm.columnCount) - { + for (i in 0 until tm.columnCount) { tm.getColumnName(i) shouldBe entityCols[i] - tm.getColumnClass(i) shouldBeOneOf(listOf(it.getFieldType(entityCols[i]), Any::class.java)) + tm.getColumnClass(i) shouldBeOneOf + (listOf(it.getFieldType(entityCols[i]), Any::class.java)) } } } @Test - fun `Should initialise with the correct values from the entity`() - { - DartsDatabaseUtil.getAllEntitiesIncludingVersion().forEach{ + fun `Should initialise with the correct values from the entity`() { + DartsDatabaseUtil.getAllEntitiesIncludingVersion().forEach { val list = listOf(it) val tm = TableModelEntity(list) val cols = it.getColumns() - for (col in cols) - { + for (col in cols) { val ix = tm.findColumn(col) tm.getValueAt(0, ix) shouldBe it.getField(col) } } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/bean/TestTeamRenderer.kt b/src/test/kotlin/dartzee/bean/TestTeamRenderer.kt index 15d44f13d..254f5be36 100644 --- a/src/test/kotlin/dartzee/bean/TestTeamRenderer.kt +++ b/src/test/kotlin/dartzee/bean/TestTeamRenderer.kt @@ -4,22 +4,20 @@ import dartzee.helper.AbstractTest import dartzee.utils.DartsColour import dartzee.utils.translucent import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.JComponent import javax.swing.JTable import javax.swing.table.DefaultTableCellRenderer import javax.swing.table.TableCellRenderer +import org.junit.jupiter.api.Test -class TestTeamRenderer: AbstractTest() -{ +class TestTeamRenderer : AbstractTest() { private val defaultRenderer = DefaultTableCellRenderer() private val table = JTable() private val value = "foo" @Test - fun `Should do nothing if teams disabled`() - { + fun `Should do nothing if teams disabled`() { val renderer = TeamRenderer(defaultRenderer) { false } val c = renderer.getRendererComponent() @@ -31,8 +29,7 @@ class TestTeamRenderer: AbstractTest() } @Test - fun `Should do nothing if row out of bounds`() - { + fun `Should do nothing if row out of bounds`() { val renderer = TeamRenderer(defaultRenderer) { true } val c = renderer.getRendererComponent(row = 12) @@ -44,8 +41,7 @@ class TestTeamRenderer: AbstractTest() } @Test - fun `Should render the correct colours based on row index`() - { + fun `Should render the correct colours based on row index`() { val renderer = TeamRenderer(defaultRenderer) { true } checkColoursForRowIndex(renderer, 0, Color.RED) @@ -62,12 +58,17 @@ class TestTeamRenderer: AbstractTest() checkColoursForRowIndex(renderer, 11, DartsColour.ORANGE) } - private fun checkColoursForRowIndex(renderer: TeamRenderer, rowIndex: Int, rawColour: Color) - { - renderer.getRendererComponent(row = rowIndex, isSelected = true).background shouldBe rawColour - renderer.getRendererComponent(row = rowIndex, isSelected = false).background shouldBe rawColour.translucent() + private fun checkColoursForRowIndex(renderer: TeamRenderer, rowIndex: Int, rawColour: Color) { + renderer.getRendererComponent(row = rowIndex, isSelected = true).background shouldBe + rawColour + renderer.getRendererComponent(row = rowIndex, isSelected = false).background shouldBe + rawColour.translucent() } - private fun TableCellRenderer.getRendererComponent(isSelected: Boolean = false, hasFocus: Boolean = false, row: Int = 0, column: Int = 0) = - getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) as JComponent -} \ No newline at end of file + private fun TableCellRenderer.getRendererComponent( + isSelected: Boolean = false, + hasFocus: Boolean = false, + row: Int = 0, + column: Int = 0 + ) = getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column) as JComponent +} diff --git a/src/test/kotlin/dartzee/core/bean/TestColourPicker.kt b/src/test/kotlin/dartzee/core/bean/TestColourPicker.kt index b1567df0b..e64f89160 100644 --- a/src/test/kotlin/dartzee/core/bean/TestColourPicker.kt +++ b/src/test/kotlin/dartzee/core/bean/TestColourPicker.kt @@ -11,15 +11,13 @@ import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.Color import java.awt.Cursor +import org.junit.jupiter.api.Test -class TestColourPicker: AbstractTest() -{ +class TestColourPicker : AbstractTest() { @Test - fun `Should change the cursor to a hand on hover`() - { + fun `Should change the cursor to a hand on hover`() { val cp = ColourPicker() cp.doHover() cp.cursor.type shouldBe Cursor.HAND_CURSOR @@ -29,8 +27,7 @@ class TestColourPicker: AbstractTest() } @Test - fun `Should support updating the current colour`() - { + fun `Should support updating the current colour`() { val cp = ColourPicker() cp.updateSelectedColor(Color.RED) @@ -40,8 +37,7 @@ class TestColourPicker: AbstractTest() } @Test - fun `Should update the colour on mouse click to whatever was selected in the dialog`() - { + fun `Should update the colour on mouse click to whatever was selected in the dialog`() { val mockSelector = mockk(relaxed = true) every { mockSelector.selectColour(any()) } returns Color.BLUE @@ -59,8 +55,7 @@ class TestColourPicker: AbstractTest() } @Test - fun `Should notify its listener if a new colour is selected`() - { + fun `Should notify its listener if a new colour is selected`() { val mockSelector = mockk(relaxed = true) every { mockSelector.selectColour(any()) } returns Color.BLUE InjectedDesktopCore.colourSelector = mockSelector @@ -75,8 +70,7 @@ class TestColourPicker: AbstractTest() } @Test - fun `Should not notify its listener if told not to`() - { + fun `Should not notify its listener if told not to`() { val listener = mockk(relaxed = true) val cp = ColourPicker() @@ -85,4 +79,4 @@ class TestColourPicker: AbstractTest() verifyNotCalled { listener.colourSelected(Color.BLUE) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestComboBoxNumberComparison.kt b/src/test/kotlin/dartzee/core/bean/TestComboBoxNumberComparison.kt index 34c2e8039..afb1dfc13 100644 --- a/src/test/kotlin/dartzee/core/bean/TestComboBoxNumberComparison.kt +++ b/src/test/kotlin/dartzee/core/bean/TestComboBoxNumberComparison.kt @@ -4,11 +4,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestComboBoxNumberComparison: AbstractTest() -{ +class TestComboBoxNumberComparison : AbstractTest() { @Test - fun `Should contain the default options, and support adding new ones`() - { + fun `Should contain the default options, and support adding new ones`() { val cb = ComboBoxNumberComparison() cb.itemCount shouldBe 3 @@ -16,4 +14,4 @@ class TestComboBoxNumberComparison: AbstractTest() cb.itemCount shouldBe 4 cb.getItemAt(3) shouldBe "foo" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestDateFilterPanel.kt b/src/test/kotlin/dartzee/core/bean/TestDateFilterPanel.kt index 94003f343..466cc0671 100644 --- a/src/test/kotlin/dartzee/core/bean/TestDateFilterPanel.kt +++ b/src/test/kotlin/dartzee/core/bean/TestDateFilterPanel.kt @@ -4,18 +4,16 @@ import dartzee.core.util.enableChildren import dartzee.helper.AbstractTest import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp import java.text.SimpleDateFormat import java.time.LocalDate +import org.junit.jupiter.api.Test -class TestDateFilterPanel: AbstractTest() -{ +class TestDateFilterPanel : AbstractTest() { private val fmt = SimpleDateFormat("dd/MM/yyyy") @Test - fun `Should always be valid if disabled`() - { + fun `Should always be valid if disabled`() { val filterPanel = DateFilterPanel() filterPanel.cbDateFrom.date = LocalDate.parse("2020-01-04") filterPanel.cbDateTo.date = LocalDate.parse("2020-01-01") @@ -25,19 +23,19 @@ class TestDateFilterPanel: AbstractTest() } @Test - fun `Should not be valid if start date is after end date`() - { + fun `Should not be valid if start date is after end date`() { val filterPanel = DateFilterPanel() filterPanel.cbDateFrom.date = LocalDate.parse("2020-01-04") filterPanel.cbDateTo.date = LocalDate.parse("2020-01-01") filterPanel.valid() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("The 'date from' cannot be after the 'date to'") + dialogFactory.errorsShown.shouldContainExactly( + "The 'date from' cannot be after the 'date to'" + ) } @Test - fun `Should be valid if the end date is on or after the start date`() - { + fun `Should be valid if the end date is on or after the start date`() { val filterPanel = DateFilterPanel() filterPanel.cbDateFrom.date = LocalDate.parse("2020-01-01") filterPanel.cbDateTo.date = LocalDate.parse("2020-01-01") @@ -48,8 +46,7 @@ class TestDateFilterPanel: AbstractTest() } @Test - fun `Should provide a sensible filter description`() - { + fun `Should provide a sensible filter description`() { val filterPanel = DateFilterPanel() filterPanel.cbDateFrom.date = LocalDate.parse("2020-01-01") @@ -59,8 +56,7 @@ class TestDateFilterPanel: AbstractTest() } @Test - fun `Should provide converted SQL timestamps`() - { + fun `Should provide converted SQL timestamps`() { val filterPanel = DateFilterPanel() filterPanel.cbDateFrom.date = LocalDate.parse("2020-01-01") @@ -74,8 +70,7 @@ class TestDateFilterPanel: AbstractTest() } @Test - fun `Should correctly filter SQL dates`() - { + fun `Should correctly filter SQL dates`() { val filterPanel = DateFilterPanel() filterPanel.cbDateFrom.date = LocalDate.parse("2020-01-02") filterPanel.cbDateTo.date = LocalDate.parse("2020-01-04") @@ -88,4 +83,4 @@ class TestDateFilterPanel: AbstractTest() filterPanel.filterSqlDate(Timestamp.valueOf("2020-01-04 23:59:59")) shouldBe false filterPanel.filterSqlDate(Timestamp.valueOf("2020-01-05 00:00:00")) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestDevScreenCommands.kt b/src/test/kotlin/dartzee/core/bean/TestDevScreenCommands.kt index 2d3eca61e..0c89a012d 100644 --- a/src/test/kotlin/dartzee/core/bean/TestDevScreenCommands.kt +++ b/src/test/kotlin/dartzee/core/bean/TestDevScreenCommands.kt @@ -8,19 +8,17 @@ import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldBeEmpty import io.mockk.mockk -import org.junit.jupiter.api.Test import java.awt.event.KeyEvent import javax.swing.JPanel import javax.swing.SwingUtilities +import org.junit.jupiter.api.Test -class TestDevScreenCommands: AbstractTest() -{ +class TestDevScreenCommands : AbstractTest() { var commandsEnabled = true var toggle = false @Test - fun testCommandsDisabled() - { + fun testCommandsDisabled() { commandsEnabled = false val cheatBar = CheatBar() @@ -32,8 +30,7 @@ class TestDevScreenCommands: AbstractTest() } @Test - fun testCommandsEnabled() - { + fun testCommandsEnabled() { commandsEnabled = true val cheatBar = CheatBar() @@ -44,8 +41,7 @@ class TestDevScreenCommands: AbstractTest() cheatBar.isVisible shouldBe true } - private fun simulateKeyStroke(devScreen: AbstractDevScreen) - { + private fun simulateKeyStroke(devScreen: AbstractDevScreen) { val cheatBarKeyStroke = devScreen.getKeyStrokeForCommandBar() val innerPanel = devScreen.contentPane as JPanel @@ -56,8 +52,7 @@ class TestDevScreenCommands: AbstractTest() } @Test - fun testTextualCommand() - { + fun testTextualCommand() { commandsEnabled = true val cheatBar = CheatBar() @@ -73,8 +68,7 @@ class TestDevScreenCommands: AbstractTest() } @Test - fun testStateChangingCommand() - { + fun testStateChangingCommand() { commandsEnabled = true toggle = false @@ -92,8 +86,7 @@ class TestDevScreenCommands: AbstractTest() } @Test - fun testExceptionCommand() - { + fun testExceptionCommand() { commandsEnabled = true val cheatBar = CheatBar() @@ -111,28 +104,20 @@ class TestDevScreenCommands: AbstractTest() log.errorObject?.message shouldBe "Test" } - - inner class TestDevScreen(cheatBar: CheatBar): AbstractDevScreen(cheatBar) - { + inner class TestDevScreen(cheatBar: CheatBar) : AbstractDevScreen(cheatBar) { override val windowName = "Test" override fun commandsEnabled() = commandsEnabled - override fun processCommand(cmd: String): String - { - if (cmd == "1+1") - { + override fun processCommand(cmd: String): String { + if (cmd == "1+1") { return "2" - } - else if (cmd == "exception") - { + } else if (cmd == "exception") { throw Exception("Test") - } - else - { + } else { toggle = !toggle return "" } } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestGhostText.kt b/src/test/kotlin/dartzee/core/bean/TestGhostText.kt index 2e13151c8..ca7fc84d0 100644 --- a/src/test/kotlin/dartzee/core/bean/TestGhostText.kt +++ b/src/test/kotlin/dartzee/core/bean/TestGhostText.kt @@ -2,16 +2,14 @@ package dartzee.core.bean import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Font import javax.swing.JTextField import javax.swing.SwingConstants.LEADING +import org.junit.jupiter.api.Test -class TestGhostText: AbstractTest() -{ +class TestGhostText : AbstractTest() { @Test - fun `Should construct with the right values`() - { + fun `Should construct with the right values`() { val label = JTextField() val font = Font("Tahoma", Font.BOLD, 25) label.font = font @@ -24,8 +22,7 @@ class TestGhostText: AbstractTest() } @Test - fun `Should be visible when text field has no text`() - { + fun `Should be visible when text field has no text`() { val tf = JTextField() val ghostText = GhostText("Foo", tf) @@ -33,8 +30,7 @@ class TestGhostText: AbstractTest() } @Test - fun `Should not be visible when text is entered, and should return when field is cleared`() - { + fun `Should not be visible when text is entered, and should return when field is cleared`() { val tf = JTextField() val ghostText = GhostText("Foo", tf) @@ -45,4 +41,4 @@ class TestGhostText: AbstractTest() tf.document.remove(0, tf.document.length) ghostText.isVisible shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestHyperlinkAdaptor.kt b/src/test/kotlin/dartzee/core/bean/TestHyperlinkAdaptor.kt index d2add0496..3a3c4ba22 100644 --- a/src/test/kotlin/dartzee/core/bean/TestHyperlinkAdaptor.kt +++ b/src/test/kotlin/dartzee/core/bean/TestHyperlinkAdaptor.kt @@ -6,40 +6,37 @@ import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verifySequence -import org.junit.jupiter.api.Test import java.awt.Cursor import java.awt.event.MouseEvent import javax.swing.JButton import javax.swing.JPanel +import org.junit.jupiter.api.Test private val mouseEventOverLink = makeMouseEvent(JButton()) private val mouseEventNotOverLink = makeMouseEvent(JButton()) -class TestHyperlinkAdaptor: AbstractTest() -{ +class TestHyperlinkAdaptor : AbstractTest() { @Test - fun `Should not accept a non-component listener`() - { - shouldThrow { - HyperlinkAdaptor(NonComponentHyperlinkListener()) - } + fun `Should not accept a non-component listener`() { + shouldThrow { HyperlinkAdaptor(NonComponentHyperlinkListener()) } } @Test - fun `Should respond to mouse clicks`() - { + fun `Should respond to mouse clicks`() { val listener = mockk(relaxed = true) val adaptor = HyperlinkAdaptor(listener) adaptor.mouseClicked(mouseEventOverLink) adaptor.mouseClicked(mouseEventNotOverLink) - verifySequence { listener.linkClicked(mouseEventOverLink); listener.linkClicked(mouseEventNotOverLink) } + verifySequence { + listener.linkClicked(mouseEventOverLink) + listener.linkClicked(mouseEventNotOverLink) + } } @Test - fun `Should change the cursor on mouse movement`() - { + fun `Should change the cursor on mouse movement`() { val listener = TestHyperlinkListener() val adaptor = HyperlinkAdaptor(listener) @@ -60,8 +57,7 @@ class TestHyperlinkAdaptor: AbstractTest() } @Test - fun `Should revert the cursor on mouseExit`() - { + fun `Should revert the cursor on mouseExit`() { val listener = TestHyperlinkListener() val adaptor = HyperlinkAdaptor(listener) @@ -73,8 +69,7 @@ class TestHyperlinkAdaptor: AbstractTest() } @Test - fun `Should revert the cursor on mouseDragged`() - { + fun `Should revert the cursor on mouseDragged`() { val listener = TestHyperlinkListener() val adaptor = HyperlinkAdaptor(listener) @@ -86,15 +81,14 @@ class TestHyperlinkAdaptor: AbstractTest() } } -private class TestHyperlinkListener: JPanel(), IHyperlinkListener -{ +private class TestHyperlinkListener : JPanel(), IHyperlinkListener { override fun isOverHyperlink(arg0: MouseEvent) = arg0 === mouseEventOverLink - override fun linkClicked(arg0: MouseEvent){} + override fun linkClicked(arg0: MouseEvent) {} } -private class NonComponentHyperlinkListener : IHyperlinkListener -{ +private class NonComponentHyperlinkListener : IHyperlinkListener { override fun isOverHyperlink(arg0: MouseEvent) = false - override fun linkClicked(arg0: MouseEvent){} -} \ No newline at end of file + + override fun linkClicked(arg0: MouseEvent) {} +} diff --git a/src/test/kotlin/dartzee/core/bean/TestLinkLabel.kt b/src/test/kotlin/dartzee/core/bean/TestLinkLabel.kt index dcdade3d4..f29870ef6 100644 --- a/src/test/kotlin/dartzee/core/bean/TestLinkLabel.kt +++ b/src/test/kotlin/dartzee/core/bean/TestLinkLabel.kt @@ -7,15 +7,13 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.Color import java.awt.Cursor +import org.junit.jupiter.api.Test -class TestLinkLabel: AbstractTest() -{ +class TestLinkLabel : AbstractTest() { @Test - fun `Should style text as URL`() - { + fun `Should style text as URL`() { val label = LinkLabel("https://foo.bar") {} label.text shouldBe "https://foo.bar" @@ -23,8 +21,7 @@ class TestLinkLabel: AbstractTest() } @Test - fun `Should update cursor on hover, and execute callback on click`() - { + fun `Should update cursor on hover, and execute callback on click`() { val callback = mockk<() -> Unit>(relaxed = true) val label = LinkLabel("test", callback) @@ -37,4 +34,4 @@ class TestLinkLabel: AbstractTest() label.doClick() verify { callback() } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestNumberField.kt b/src/test/kotlin/dartzee/core/bean/TestNumberField.kt index b3a3b3f06..7b627411e 100644 --- a/src/test/kotlin/dartzee/core/bean/TestNumberField.kt +++ b/src/test/kotlin/dartzee/core/bean/TestNumberField.kt @@ -1,24 +1,21 @@ package dartzee.core.bean import dartzee.helper.AbstractTest -import io.kotest.matchers.shouldBe import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.Test +import io.kotest.matchers.shouldBe import java.text.ParseException +import org.junit.jupiter.api.Test -class TestNumberField: AbstractTest() -{ +class TestNumberField : AbstractTest() { @Test - fun `Should return -1 when value unset`() - { + fun `Should return -1 when value unset`() { val nf = NumberField() nf.getNumber() shouldBe -1 } @Test - fun `Should be unbounded by default`() - { + fun `Should be unbounded by default`() { val nf = NumberField() nf.formatter.stringToValue("${Integer.MAX_VALUE}") @@ -26,38 +23,29 @@ class TestNumberField: AbstractTest() } @Test - fun `Should allow negative values`() - { + fun `Should allow negative values`() { val nf = NumberField() nf.formatter.stringToValue("-20") } @Test - fun `Shouldn't allow non-numerics`() - { + fun `Shouldn't allow non-numerics`() { val nf = NumberField() - shouldThrow{ - nf.formatter.stringToValue("x") - } + shouldThrow { nf.formatter.stringToValue("x") } } @Test - fun `Should respect min and max values from constructor`() - { + fun `Should respect min and max values from constructor`() { val nf = NumberField(10, 20) - shouldThrow{ - nf.formatter.stringToValue("21") - } + shouldThrow { nf.formatter.stringToValue("21") } - shouldThrow{ - nf.formatter.stringToValue("9") - } + shouldThrow { nf.formatter.stringToValue("9") } - //Shouldn't throw errors + // Shouldn't throw errors nf.formatter.stringToValue("10") nf.formatter.stringToValue("20") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestRadioButtonPanel.kt b/src/test/kotlin/dartzee/core/bean/TestRadioButtonPanel.kt index e5e443a8e..6ab17b12e 100644 --- a/src/test/kotlin/dartzee/core/bean/TestRadioButtonPanel.kt +++ b/src/test/kotlin/dartzee/core/bean/TestRadioButtonPanel.kt @@ -4,16 +4,14 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JRadioButton +import org.junit.jupiter.api.Test -class TestRadioButtonPanel: AbstractTest() -{ +class TestRadioButtonPanel : AbstractTest() { @Test - fun `Should select the first radio button passed in by default`() - { + fun `Should select the first radio button passed in by default`() { val rdbtnPanel = RadioButtonPanel() val rdbtn1 = JRadioButton() @@ -27,8 +25,7 @@ class TestRadioButtonPanel: AbstractTest() } @Test - fun `Should only allow one radio selection at a time`() - { + fun `Should only allow one radio selection at a time`() { val rdbtnPanel = RadioButtonPanel() val rdbtn1 = JRadioButton() @@ -44,8 +41,7 @@ class TestRadioButtonPanel: AbstractTest() } @Test - fun `Should return the selected radio button string`() - { + fun `Should return the selected radio button string`() { val rdbtnPanel = RadioButtonPanel() rdbtnPanel.getSelectionStr() shouldBe "" @@ -62,8 +58,7 @@ class TestRadioButtonPanel: AbstractTest() } @Test - fun `Should support setting the selection by string`() - { + fun `Should support setting the selection by string`() { val rdbtnPanel = RadioButtonPanel() val rdbtn1 = JRadioButton("foo") @@ -84,8 +79,7 @@ class TestRadioButtonPanel: AbstractTest() } @Test - fun `Should report whether it was the event source`() - { + fun `Should report whether it was the event source`() { val rdbtnPanel = RadioButtonPanel() val rdbtn1 = JRadioButton("foo") @@ -108,8 +102,7 @@ class TestRadioButtonPanel: AbstractTest() } @Test - fun `Should add action listeners to all radio buttons`() - { + fun `Should add action listeners to all radio buttons`() { val panel = RadioButtonPanel() val rdbtn1 = JRadioButton() @@ -127,8 +120,7 @@ class TestRadioButtonPanel: AbstractTest() } @Test - fun `Should remove action listeners from all radio buttons`() - { + fun `Should remove action listeners from all radio buttons`() { val panel = RadioButtonPanel() val rdbtn1 = JRadioButton() @@ -146,13 +138,11 @@ class TestRadioButtonPanel: AbstractTest() listener.sources.shouldBeEmpty() } - class SourceActionListener: ActionListener - { + class SourceActionListener : ActionListener { val sources = mutableListOf() - override fun actionPerformed(e: ActionEvent) - { + override fun actionPerformed(e: ActionEvent) { sources.add(e.source) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/bean/TestSwingExtensions.kt b/src/test/kotlin/dartzee/core/bean/TestSwingExtensions.kt index 60094bc4d..bee986ffa 100644 --- a/src/test/kotlin/dartzee/core/bean/TestSwingExtensions.kt +++ b/src/test/kotlin/dartzee/core/bean/TestSwingExtensions.kt @@ -8,7 +8,6 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.Test import java.awt.BorderLayout import java.awt.Point import java.awt.event.ActionEvent @@ -16,12 +15,11 @@ import java.awt.event.ActionListener import java.awt.event.KeyEvent import javax.swing.JComboBox import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestSwingExtensions: AbstractTest() -{ +class TestSwingExtensions : AbstractTest() { @Test - fun `Should return the typed items of a combo box`() - { + fun `Should return the typed items of a combo box`() { val comboBox = JComboBox() comboBox.items().shouldBeEmpty() comboBox.items().shouldBeInstanceOf>() @@ -35,8 +33,7 @@ class TestSwingExtensions: AbstractTest() } @Test - fun `Should return a typed selected item`() - { + fun `Should return a typed selected item`() { val comboBox = JComboBox() comboBox.addItem("Foo") comboBox.addItem("Bar") @@ -51,8 +48,7 @@ class TestSwingExtensions: AbstractTest() } @Test - fun `Should find items by class`() - { + fun `Should find items by class`() { val comboBox = JComboBox() comboBox.addItem(20) comboBox.addItem(30.0) @@ -68,8 +64,7 @@ class TestSwingExtensions: AbstractTest() } @Test - fun `Should select by class`() - { + fun `Should select by class`() { val comboBox = JComboBox() comboBox.addItem(20) comboBox.addItem(30.0) @@ -82,8 +77,7 @@ class TestSwingExtensions: AbstractTest() } @Test - fun `Should add a listener for when focus is lost`() - { + fun `Should add a listener for when focus is lost`() { val actionListener = CapturingActionListener() val tf = JTextField() @@ -94,8 +88,7 @@ class TestSwingExtensions: AbstractTest() } @Test - fun `Should add an action for the specified key, and only process if a row is selected`() - { + fun `Should add an action for the specified key, and only process if a row is selected`() { val scrollTable = ScrollTable() var keyPressed = false @@ -107,7 +100,7 @@ class TestSwingExtensions: AbstractTest() scrollTable.processKeyPress(KeyEvent.VK_DELETE) keyPressed shouldBe false - //Now select a row + // Now select a row scrollTable.addColumn("Test") scrollTable.addRow(arrayOf("Foo")) scrollTable.selectFirstRow() @@ -117,8 +110,7 @@ class TestSwingExtensions: AbstractTest() } @Test - fun `Should add ghost text to a text component`() - { + fun `Should add ghost text to a text component`() { val tf = JTextField() tf.addGhostText("Hello") @@ -128,20 +120,24 @@ class TestSwingExtensions: AbstractTest() ghostText.text shouldBe "Hello" } - private class CapturingActionListener: ActionListener - { + private class CapturingActionListener : ActionListener { var eventSource: Any? = null - override fun actionPerformed(e: ActionEvent?) - { + override fun actionPerformed(e: ActionEvent?) { eventSource = e?.source } } @Test - fun `Should return all of the points for a given width and height in the correct order`() - { + fun `Should return all of the points for a given width and height in the correct order`() { val points = getPointList(2, 3) - points.shouldContainExactly(Point(0, 0), Point(1, 0), Point(0, 1), Point(1, 1), Point(0, 2), Point(1, 2)) + points.shouldContainExactly( + Point(0, 0), + Point(1, 0), + Point(0, 1), + Point(1, 1), + Point(0, 2), + Point(1, 2) + ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/helper/ComponentHelpers.kt b/src/test/kotlin/dartzee/core/helper/ComponentHelpers.kt index 809d94c10..9d3b04842 100644 --- a/src/test/kotlin/dartzee/core/helper/ComponentHelpers.kt +++ b/src/test/kotlin/dartzee/core/helper/ComponentHelpers.kt @@ -7,17 +7,13 @@ import java.awt.image.BufferedImage import javax.swing.ImageIcon import javax.swing.JLabel -/** - * Test methods - */ -fun ScrollTable.processKeyPress(key: Int) -{ +/** Test methods */ +fun ScrollTable.processKeyPress(key: Int) { this.table.processKeyPress(key) } -fun ScrollTable.doubleClick() -{ +fun ScrollTable.doubleClick() { this.table.doubleClick() } -fun JLabel.getIconImage(): BufferedImage = (icon as ImageIcon).image as BufferedImage \ No newline at end of file +fun JLabel.getIconImage(): BufferedImage = (icon as ImageIcon).image as BufferedImage diff --git a/src/test/kotlin/dartzee/core/helper/DeterministicCollectionShuffler.kt b/src/test/kotlin/dartzee/core/helper/DeterministicCollectionShuffler.kt index 6c5064513..855955aa4 100644 --- a/src/test/kotlin/dartzee/core/helper/DeterministicCollectionShuffler.kt +++ b/src/test/kotlin/dartzee/core/helper/DeterministicCollectionShuffler.kt @@ -2,10 +2,8 @@ package dartzee.core.helper import dartzee.core.util.IShuffler -/** - * Puts the first element to the end, i.e. [1, 2, 3, 4] -> [2, 3, 4, 1] - */ -class DeterministicCollectionShuffler: IShuffler -{ - override fun shuffleCollection(collection: List) = collection.subList(1, collection.size) + collection[0] -} \ No newline at end of file +/** Puts the first element to the end, i.e. [1, 2, 3, 4] -> [2, 3, 4, 1] */ +class DeterministicCollectionShuffler : IShuffler { + override fun shuffleCollection(collection: List) = + collection.subList(1, collection.size) + collection[0] +} diff --git a/src/test/kotlin/dartzee/core/helper/TestHelpers.kt b/src/test/kotlin/dartzee/core/helper/TestHelpers.kt index 22bb823f4..932707398 100644 --- a/src/test/kotlin/dartzee/core/helper/TestHelpers.kt +++ b/src/test/kotlin/dartzee/core/helper/TestHelpers.kt @@ -3,19 +3,16 @@ package dartzee.core.helper import io.mockk.verify import java.sql.Timestamp -fun verifyNotCalled(verifyBlock: io.mockk.MockKVerificationScope.() -> Unit) -{ +fun verifyNotCalled(verifyBlock: io.mockk.MockKVerificationScope.() -> Unit) { verify(exactly = 0) { verifyBlock() } } -fun getPastTime(now: Timestamp): Timestamp -{ +fun getPastTime(now: Timestamp): Timestamp { val instant = now.toInstant() return Timestamp.from(instant.minusSeconds(2000)) } -fun getFutureTime(now: Timestamp): Timestamp -{ +fun getFutureTime(now: Timestamp): Timestamp { val instant = now.toInstant() return Timestamp.from(instant.plusSeconds(2000)) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/helper/TestMessageDialogFactory.kt b/src/test/kotlin/dartzee/core/helper/TestMessageDialogFactory.kt index 318122c40..62c3c246b 100644 --- a/src/test/kotlin/dartzee/core/helper/TestMessageDialogFactory.kt +++ b/src/test/kotlin/dartzee/core/helper/TestMessageDialogFactory.kt @@ -5,17 +5,16 @@ import java.awt.Component import java.io.File import javax.swing.JOptionPane -class TestMessageDialogFactory: IMessageDialogFactory -{ - //Directory +class TestMessageDialogFactory : IMessageDialogFactory { + // Directory var directoryToSelect: File? = null - //Inputs + // Inputs var inputSelection: Any? = null var inputOptionsPresented: Array<*>? = null val inputsShown = mutableListOf() - //Questions + // Questions var questionOption = JOptionPane.NO_OPTION val questionsShown = mutableListOf() @@ -29,54 +28,52 @@ class TestMessageDialogFactory: IMessageDialogFactory val loadingsShown = mutableListOf() - override fun showInput(title: String, message: String, options: Array?, defaultOption: K?): K? - { + override fun showInput( + title: String, + message: String, + options: Array?, + defaultOption: K? + ): K? { inputsShown.add(title) inputOptionsPresented = options val selection = inputSelection selection ?: return null - if (options == null || options.contains(inputSelection)) - { - @Suppress("UNCHECKED_CAST") - return inputSelection as K + if (options == null || options.contains(inputSelection)) { + @Suppress("UNCHECKED_CAST") return inputSelection as K } - throw Exception("Running a test where $inputSelection was to be returned, but wasn't a valid selection in the dialog shown.") + throw Exception( + "Running a test where $inputSelection was to be returned, but wasn't a valid selection in the dialog shown." + ) } - override fun showInfo(text: String) - { + override fun showInfo(text: String) { infosShown.add(text) } - override fun showError(text: String) - { + override fun showError(text: String) { errorsShown.add(text) } - override fun showQuestion(text: String, allowCancel: Boolean): Int - { + override fun showQuestion(text: String, allowCancel: Boolean): Int { questionsShown.add(text) return questionOption } - override fun showOption(title: String, message: String, options: List): String? - { + override fun showOption(title: String, message: String, options: List): String? { optionsShown.add(message) val selection = optionSequence.removeAt(0) return selection } - override fun showLoading(text: String) - { + override fun showLoading(text: String) { loadingsShown.add(text) loadingVisible = true } - override fun dismissLoading(): Boolean - { + override fun dismissLoading(): Boolean { val wasVisible = loadingVisible loadingVisible = false return wasVisible @@ -84,8 +81,7 @@ class TestMessageDialogFactory: IMessageDialogFactory override fun chooseDirectory(parent: Component?) = directoryToSelect - fun reset() - { + fun reset() { inputsShown.clear() inputOptionsPresented = arrayOf() infosShown.clear() @@ -97,4 +93,4 @@ class TestMessageDialogFactory: IMessageDialogFactory optionsShown.clear() directoryToSelect = null } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/obj/TestHashMapCount.kt b/src/test/kotlin/dartzee/core/obj/TestHashMapCount.kt index aa825574a..ecda1ebc5 100644 --- a/src/test/kotlin/dartzee/core/obj/TestHashMapCount.kt +++ b/src/test/kotlin/dartzee/core/obj/TestHashMapCount.kt @@ -5,18 +5,15 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestHashMapCount: AbstractTest() -{ +class TestHashMapCount : AbstractTest() { @Test - fun `Should return a total count of 0 by default`() - { + fun `Should return a total count of 0 by default`() { val hm = HashMapCount() hm.getTotalCount() shouldBe 0 } @Test - fun `Should sum the total count across all keys`() - { + fun `Should sum the total count across all keys`() { val hm = HashMapCount() hm.incrementCount(5, 100) @@ -27,8 +24,7 @@ class TestHashMapCount: AbstractTest() } @Test - fun `Should return the right individual count for a key`() - { + fun `Should return the right individual count for a key`() { val hm = HashMapCount() hm.getCount(5) shouldBe 0 @@ -39,18 +35,17 @@ class TestHashMapCount: AbstractTest() } @Test - fun `Should return a flattened ordered list`() - { + fun `Should return a flattened ordered list`() { val hm = HashMapCount() hm.incrementCount(7, 2) hm.incrementCount(3, 2) hm.incrementCount(5, 1) - val list = hm.getFlattenedOrderedList(Comparator.comparingInt{it}) + val list = hm.getFlattenedOrderedList(Comparator.comparingInt { it }) list.shouldContainExactly(3, 3, 5, 7, 7) - val reverseList = hm.getFlattenedOrderedList(Comparator.comparingInt{ -it }) + val reverseList = hm.getFlattenedOrderedList(Comparator.comparingInt { -it }) reverseList.shouldContainExactly(7, 7, 5, 3, 3) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/obj/TestHashMapList.kt b/src/test/kotlin/dartzee/core/obj/TestHashMapList.kt index 1387166f2..2e34cb171 100644 --- a/src/test/kotlin/dartzee/core/obj/TestHashMapList.kt +++ b/src/test/kotlin/dartzee/core/obj/TestHashMapList.kt @@ -6,11 +6,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestHashMapList: AbstractTest() -{ +class TestHashMapList : AbstractTest() { @Test - fun `Should create a new list for a new key`() - { + fun `Should create a new list for a new key`() { val hm = HashMapList() hm.putInList(1, "foo") @@ -19,8 +17,7 @@ class TestHashMapList: AbstractTest() } @Test - fun `Should add to existing list for an existing key`() - { + fun `Should add to existing list for an existing key`() { val hm = HashMapList() hm.putInList(1, "foo") @@ -30,8 +27,7 @@ class TestHashMapList: AbstractTest() } @Test - fun `Should return all values across different keys`() - { + fun `Should return all values across different keys`() { val hm = HashMapList() hm.putInList(1, "foo") @@ -45,4 +41,4 @@ class TestHashMapList: AbstractTest() hm.getAllValues().shouldContainExactlyInAnyOrder("foo", "bar", "baz", "muppet") hm.getFlattenedValuesSortedByKey().shouldContainExactly("muppet", "foo", "bar", "baz") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/obj/TestLimitedDocument.kt b/src/test/kotlin/dartzee/core/obj/TestLimitedDocument.kt index 97c4668f2..68df35321 100644 --- a/src/test/kotlin/dartzee/core/obj/TestLimitedDocument.kt +++ b/src/test/kotlin/dartzee/core/obj/TestLimitedDocument.kt @@ -4,21 +4,23 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestLimitedDocument: AbstractTest() -{ +class TestLimitedDocument : AbstractTest() { @Test - fun `should restrict the length of text that can be inserted`() - { + fun `should restrict the length of text that can be inserted`() { val limitedDocument = LimitedDocument(50) - limitedDocument.insertString(0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", null) //40 chars - limitedDocument.insertString(0, null, null) //Should do nothing - limitedDocument.insertString(0, "bbbbbbbbbbb", null) //11 chars - too many - limitedDocument.insertString(0, "cccccccccc", null) //10 chars - should work - limitedDocument.insertString(0, "d", null) //Now full - shouldn't accept anything + limitedDocument.insertString( + 0, + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + null + ) // 40 chars + limitedDocument.insertString(0, null, null) // Should do nothing + limitedDocument.insertString(0, "bbbbbbbbbbb", null) // 11 chars - too many + limitedDocument.insertString(0, "cccccccccc", null) // 10 chars - should work + limitedDocument.insertString(0, "d", null) // Now full - shouldn't accept anything val text = limitedDocument.getText(0, 50) text.shouldBe("ccccccccccaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/screen/TestColourChooserDialog.kt b/src/test/kotlin/dartzee/core/screen/TestColourChooserDialog.kt index b6d7d5e74..1784757c2 100644 --- a/src/test/kotlin/dartzee/core/screen/TestColourChooserDialog.kt +++ b/src/test/kotlin/dartzee/core/screen/TestColourChooserDialog.kt @@ -1,19 +1,17 @@ package dartzee.core.screen -import com.github.alyssaburlton.swingtest.clickOk import com.github.alyssaburlton.swingtest.clickCancel +import com.github.alyssaburlton.swingtest.clickOk import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import io.mockk.spyk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.Color +import org.junit.jupiter.api.Test -class TestColourChooserDialog: AbstractTest() -{ +class TestColourChooserDialog : AbstractTest() { @Test - fun `Should update selectedColour and dispose on Ok`() - { + fun `Should update selectedColour and dispose on Ok`() { val dlg = spyk() dlg.initialColour = Color.RED dlg.selectedColour = Color.BLACK @@ -26,8 +24,7 @@ class TestColourChooserDialog: AbstractTest() } @Test - fun `Should set selectedColour back to initialColour and dispose on Cancel`() - { + fun `Should set selectedColour back to initialColour and dispose on Cancel`() { val dlg = spyk() dlg.initialColour = Color.RED dlg.selectedColour = Color.BLACK @@ -38,4 +35,4 @@ class TestColourChooserDialog: AbstractTest() dlg.selectedColour shouldBe Color.RED verify { dlg.dispose() } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/screen/TestSimpleDialog.kt b/src/test/kotlin/dartzee/core/screen/TestSimpleDialog.kt index 9a71badc6..bf0a14aa1 100644 --- a/src/test/kotlin/dartzee/core/screen/TestSimpleDialog.kt +++ b/src/test/kotlin/dartzee/core/screen/TestSimpleDialog.kt @@ -1,22 +1,20 @@ package dartzee.core.screen -import com.github.alyssaburlton.swingtest.getChild import com.github.alyssaburlton.swingtest.clickCancel import com.github.alyssaburlton.swingtest.clickOk +import com.github.alyssaburlton.swingtest.getChild import dartzee.helper.AbstractTest import dartzee.helper.logger import dartzee.logging.LoggingCode import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestSimpleDialog: AbstractTest() -{ +class TestSimpleDialog : AbstractTest() { var allowCancel = true @Test - fun `Should show or hide the cancel button as appropriate`() - { + fun `Should show or hide the cancel button as appropriate`() { allowCancel = true val dlg = SimpleDialogTestExtension() dlg.getChild(text = "Cancel").isVisible shouldBe true @@ -27,8 +25,7 @@ class TestSimpleDialog: AbstractTest() } @Test - fun `Pressing cancel should dispose the dialog by default`() - { + fun `Pressing cancel should dispose the dialog by default`() { allowCancel = true val dlg = SimpleDialogTestExtension() @@ -40,8 +37,7 @@ class TestSimpleDialog: AbstractTest() } @Test - fun `Pressing ok should do whatever has been implemented`() - { + fun `Pressing ok should do whatever has been implemented`() { val dlg = SimpleDialogTestExtension() dlg.clickOk() @@ -49,15 +45,11 @@ class TestSimpleDialog: AbstractTest() verifyLog(LoggingCode("OkPressed")) } - inner class SimpleDialogTestExtension: SimpleDialog() - { - override fun okPressed() - { + inner class SimpleDialogTestExtension : SimpleDialog() { + override fun okPressed() { logger.info(LoggingCode("OkPressed"), "pressed ok") } override fun allowCancel() = allowCancel - } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/screen/TestTableModelDialog.kt b/src/test/kotlin/dartzee/core/screen/TestTableModelDialog.kt index 851174a2a..c3e628526 100644 --- a/src/test/kotlin/dartzee/core/screen/TestTableModelDialog.kt +++ b/src/test/kotlin/dartzee/core/screen/TestTableModelDialog.kt @@ -10,11 +10,9 @@ import io.mockk.spyk import io.mockk.verify import org.junit.jupiter.api.Test -class TestTableModelDialog: AbstractTest() -{ +class TestTableModelDialog : AbstractTest() { @Test - fun `Should display with the correct title and dialog properties`() - { + fun `Should display with the correct title and dialog properties`() { val table = ScrollTable() val tmd = TableModelDialog("Bah", table) @@ -25,25 +23,23 @@ class TestTableModelDialog: AbstractTest() } @Test - fun `Should pass through column widths to the ScrollTable`() - { + fun `Should pass through column widths to the ScrollTable`() { val st = mockk(relaxed = true) val tmd = TableModelDialog("Test", st) tmd.setColumnWidths("foo") - verify{ st.setColumnWidths("foo") } + verify { st.setColumnWidths("foo") } } @Test - fun `Should dispose when Ok is pressed`() - { + fun `Should dispose when Ok is pressed`() { val tmd = TableModelDialog("Test", ScrollTable()) val spy = spyk(tmd) spy.okPressed() - verify{ spy.dispose() } + verify { spy.dispose() } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestComponentUtil.kt b/src/test/kotlin/dartzee/core/util/TestComponentUtil.kt index 32d4ae373..318ef7b3f 100644 --- a/src/test/kotlin/dartzee/core/util/TestComponentUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestComponentUtil.kt @@ -9,7 +9,6 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import io.mockk.mockk -import org.junit.jupiter.api.Test import java.awt.event.ActionListener import javax.swing.AbstractButton import javax.swing.JButton @@ -21,12 +20,11 @@ import javax.swing.JRadioButton import javax.swing.JSpinner import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener +import org.junit.jupiter.api.Test -class TestComponentUtil: AbstractTest() -{ +class TestComponentUtil : AbstractTest() { @Test - fun `Should return children of the appropriate type`() - { + fun `Should return children of the appropriate type`() { val panel = JPanel() val btn = JButton() val rdbtn = JRadioButton() @@ -41,8 +39,7 @@ class TestComponentUtil: AbstractTest() } @Test - fun `should return nested components`() - { + fun `should return nested components`() { val panel = JPanel() val panel2 = JPanel() val panel3 = JPanel() @@ -61,8 +58,7 @@ class TestComponentUtil: AbstractTest() } @Test - fun `Should identify whether a component is contained`() - { + fun `Should identify whether a component is contained`() { val panel = JPanel() val panel2 = JPanel() val btnOne = JButton() @@ -77,16 +73,12 @@ class TestComponentUtil: AbstractTest() } @Test - fun `Should not create an empty ButtonGroup`() - { - shouldThrow { - createButtonGroup() - } + fun `Should not create an empty ButtonGroup`() { + shouldThrow { createButtonGroup() } } @Test - fun `Should create a working button group and select the first radiobutton passed in`() - { + fun `Should create a working button group and select the first radiobutton passed in`() { val rdbtnOne = JRadioButton() val rdbtnTwo = JRadioButton() @@ -101,15 +93,13 @@ class TestComponentUtil: AbstractTest() } @Test - fun `Should return null if no parent window`() - { + fun `Should return null if no parent window`() { val panel = JPanel() panel.getParentWindow() shouldBe null } @Test - fun `Should recurse up the tree to find the parent window`() - { + fun `Should recurse up the tree to find the parent window`() { val window = JFrame() val panel = JPanel() val btn = JButton() @@ -121,8 +111,7 @@ class TestComponentUtil: AbstractTest() } @Test - fun `Should enable and disable all nested components`() - { + fun `Should enable and disable all nested components`() { val window = JFrame() val panel = JPanel() val btn = JButton() @@ -144,8 +133,7 @@ class TestComponentUtil: AbstractTest() } @Test - fun `Should add actionListeners to all applicable children`() - { + fun `Should add actionListeners to all applicable children`() { val window = JFrame() val panel = JPanel() val btn = JButton() @@ -168,8 +156,7 @@ class TestComponentUtil: AbstractTest() } @Test - fun `Should not add the same actionListener twice`() - { + fun `Should not add the same actionListener twice`() { val panel = JPanel() val btn = JButton() @@ -189,8 +176,7 @@ class TestComponentUtil: AbstractTest() } @Test - fun `Should add changeListeners to all applicable children`() - { + fun `Should add changeListeners to all applicable children`() { val window = JFrame() val panel = JPanel() val spinner = JSpinner() @@ -205,13 +191,16 @@ class TestComponentUtil: AbstractTest() val changeListener = ListenerOne() window.addChangeListenerToAllChildren(changeListener) - spinner.changeListeners.toList().shouldContainExactlyInAnyOrder(changeListener, spinner.editor) - subSpinner.changeListeners.toList().shouldContainExactlyInAnyOrder(changeListener, subSpinner.editor) + spinner.changeListeners + .toList() + .shouldContainExactlyInAnyOrder(changeListener, spinner.editor) + subSpinner.changeListeners + .toList() + .shouldContainExactlyInAnyOrder(changeListener, subSpinner.editor) } @Test - fun `Should not add the same changeListener twice`() - { + fun `Should not add the same changeListener twice`() { val panel = JPanel() val spinner = JSpinner() @@ -227,16 +216,16 @@ class TestComponentUtil: AbstractTest() spinner.changeListeners.toList().shouldContainExactlyInAnyOrder(listenerOne, spinner.editor) panel.addChangeListenerToAllChildren(listenerTwo) - spinner.changeListeners.toList().shouldContainExactlyInAnyOrder(listenerOne, listenerTwo, spinner.editor) + spinner.changeListeners + .toList() + .shouldContainExactlyInAnyOrder(listenerOne, listenerTwo, spinner.editor) } - private class ListenerOne: ChangeListener - { + private class ListenerOne : ChangeListener { override fun stateChanged(e: ChangeEvent?) {} } - private class ListenerTwo: ChangeListener - { + private class ListenerTwo : ChangeListener { override fun stateChanged(e: ChangeEvent?) {} } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestDartboardDodgyUtil.kt b/src/test/kotlin/dartzee/core/util/TestDartboardDodgyUtil.kt index b4ee577ff..3e7b54a1d 100644 --- a/src/test/kotlin/dartzee/core/util/TestDartboardDodgyUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestDartboardDodgyUtil.kt @@ -17,10 +17,6 @@ import io.kotest.matchers.nulls.shouldNotBeNull import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic -import org.junit.jupiter.api.AfterAll -import org.junit.jupiter.api.BeforeAll -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import javax.sound.sampled.AudioFormat import javax.sound.sampled.AudioInputStream import javax.sound.sampled.AudioSystem @@ -30,20 +26,21 @@ import javax.sound.sampled.Line import javax.sound.sampled.LineEvent import javax.sound.sampled.LineListener import javax.swing.JLabel +import org.junit.jupiter.api.AfterAll +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestDartboardDodgyUtil : AbstractRegistryTest() -{ +class TestDartboardDodgyUtil : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveBoolean(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS, true) } @Test - fun `should not play a sound if preference is disabled`() - { + fun `should not play a sound if preference is disabled`() { mockkStatic(AudioSystem::class) PreferenceUtil.saveBoolean(PREFERENCES_BOOLEAN_SHOW_ANIMATIONS, false) @@ -54,8 +51,7 @@ class TestDartboardDodgyUtil : AbstractRegistryTest() } @Test - fun `should do nothing if invalid sound is requested`() - { + fun `should do nothing if invalid sound is requested`() { mockkStatic(AudioSystem::class) val dartboard = GameplayDartboard() @@ -65,8 +61,7 @@ class TestDartboardDodgyUtil : AbstractRegistryTest() } @Test - fun `should log an error and hide the image if there is an error playing the audio`() - { + fun `should log an error and hide the image if there is an error playing the audio`() { val dartboard = GameplayDartboard() captureClip(true) @@ -78,8 +73,7 @@ class TestDartboardDodgyUtil : AbstractRegistryTest() } @Test - fun `should show image until sound clip has finished playing`() - { + fun `should show image until sound clip has finished playing`() { val dartboard = GameplayDartboard() val clip = captureClip() @@ -93,8 +87,7 @@ class TestDartboardDodgyUtil : AbstractRegistryTest() } @Test - fun `should continue to show image until the final sound clip has finished playing`() - { + fun `should continue to show image until the final sound clip has finished playing`() { val dartboard = GameplayDartboard() val clip1 = captureClip() @@ -114,8 +107,7 @@ class TestDartboardDodgyUtil : AbstractRegistryTest() dartboard.dodgyLabelShouldNotExist() } - private fun captureClip(throwError: Boolean = false): HackedClip - { + private fun captureClip(throwError: Boolean = false): HackedClip { val clip = HackedClip(throwError) mockkStatic(AudioSystem::class) every { AudioSystem.getLine(any()) } returns clip @@ -133,22 +125,19 @@ class TestDartboardDodgyUtil : AbstractRegistryTest() companion object { @JvmStatic @BeforeAll - fun beforeAll() - { + fun beforeAll() { ResourceCache.initialiseResources() } @JvmStatic @AfterAll - fun afterAll() - { + fun afterAll() { ResourceCache.resetCache() } } } -class HackedClip(private val throwError: Boolean) : Clip -{ +class HackedClip(private val throwError: Boolean) : Clip { private var lineListener: LineListener? = null private var running: Boolean = true @@ -165,35 +154,62 @@ class HackedClip(private val throwError: Boolean) : Clip } override fun close() {} + override fun getLineInfo() = mockk() + override fun open(p0: AudioFormat?, p1: ByteArray?, p2: Int, p3: Int) {} + override fun open(p0: AudioInputStream?) { if (throwError) { throw Exception("Oh dear oh dear") } } + override fun open() {} + override fun isOpen() = false + override fun getControls(): Array = arrayOf() + override fun isControlSupported(p0: Control.Type?) = false + override fun getControl(p0: Control.Type?) = mockk() + override fun removeLineListener(p0: LineListener?) {} + override fun drain() {} + override fun flush() {} + override fun start() {} + override fun stop() {} + override fun isActive() = false + override fun getFormat() = mockk() + override fun getBufferSize() = 0 + override fun available() = 0 + override fun getFramePosition() = 0 + override fun getLongFramePosition() = 0L + override fun getMicrosecondPosition() = 0L + override fun getLevel() = 0f + override fun getFrameLength() = 0 + override fun getMicrosecondLength() = 0L + override fun setFramePosition(p0: Int) {} + override fun setMicrosecondPosition(p0: Long) {} + override fun setLoopPoints(p0: Int, p1: Int) {} + override fun loop(p0: Int) {} -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestDartzeeRuleConversion.kt b/src/test/kotlin/dartzee/core/util/TestDartzeeRuleConversion.kt index a84033173..2b9ce80cf 100644 --- a/src/test/kotlin/dartzee/core/util/TestDartzeeRuleConversion.kt +++ b/src/test/kotlin/dartzee/core/util/TestDartzeeRuleConversion.kt @@ -17,12 +17,16 @@ import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Test -class TestDartzeeRuleConversion: AbstractTest() -{ +class TestDartzeeRuleConversion : AbstractTest() { @Test - fun `Should take all dartzee rules on the database and rerun their calculations`() - { - val dartzeeRule = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(19), makeScoreRule(18), inOrder = true) + fun `Should take all dartzee rules on the database and rerun their calculations`() { + val dartzeeRule = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(19), + makeScoreRule(18), + inOrder = true + ) dartzeeRule.calculationResult!!.validSegments.shouldBeEmpty() val entity = dartzeeRule.toEntity(1, EntityName.Game, randomGuid()) @@ -37,14 +41,19 @@ class TestDartzeeRuleConversion: AbstractTest() } @Test - fun `Should dismiss the loading dialog even if an exception is thrown`() - { + fun `Should dismiss the loading dialog even if an exception is thrown`() { val mockCalculator = mockk() every { mockCalculator.getValidSegments(any(), any()) } throws Exception("Boom") InjectedThings.dartzeeCalculator = mockCalculator - val dartzeeRule = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(19), makeScoreRule(18), inOrder = true) + val dartzeeRule = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(19), + makeScoreRule(18), + inOrder = true + ) dartzeeRule.calculationResult!!.validSegments.shouldBeEmpty() val entity = dartzeeRule.toEntity(1, EntityName.Game, randomGuid()) @@ -56,4 +65,4 @@ class TestDartzeeRuleConversion: AbstractTest() errorLogged() shouldBe true dialogFactory.loadingVisible shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestDateUtil.kt b/src/test/kotlin/dartzee/core/util/TestDateUtil.kt index eecf15b73..849b2999c 100644 --- a/src/test/kotlin/dartzee/core/util/TestDateUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestDateUtil.kt @@ -7,46 +7,41 @@ import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldBeEmpty -import org.junit.jupiter.api.Test import java.sql.Timestamp import java.time.ZonedDateTime +import org.junit.jupiter.api.Test -class TestDateUtil: AbstractTest() -{ +class TestDateUtil : AbstractTest() { @Test - fun testGetSqlDateNow() - { + fun testGetSqlDateNow() { val now = ZonedDateTime.now() val dtNow = getSqlDateNow() val convertedDtNow = dtNow.toLocalDateTime() - now.year shouldBe convertedDtNow.year + now.year shouldBe convertedDtNow.year now.month shouldBe convertedDtNow.month now.dayOfMonth shouldBe convertedDtNow.dayOfMonth now.hour shouldBe convertedDtNow.hour } @Test - fun testEndOfTimeStr() - { + fun testEndOfTimeStr() { val str = getEndOfTimeSqlString() str.shouldBe("'9999-12-31 00:00:00.000'") } @Test - fun testIsEndOfTime() - { + fun testIsEndOfTime() { isEndOfTime(null).shouldBeFalse() isEndOfTime(getSqlDateNow()).shouldBeFalse() isEndOfTime(DateStatics.END_OF_TIME).shouldBeTrue() } @Test - fun `Should format a regular date as expected`() - { - val millis = 1545733545000 //25/12/2018 10:25:45 + fun `Should format a regular date as expected`() { + val millis = 1545733545000 // 25/12/2018 10:25:45 val timestamp = Timestamp(millis) @@ -55,16 +50,14 @@ class TestDateUtil: AbstractTest() } @Test - fun `Should format end of time correctly`() - { + fun `Should format end of time correctly`() { DateStatics.END_OF_TIME.formatAsDate().shouldBeEmpty() DateStatics.END_OF_TIME.formatTimestamp().shouldBeEmpty() } @Test - fun `Should return a valid string for running SQL`() - { - val millis = 1545733545000 //25/12/2018 10:25:45 + fun `Should return a valid string for running SQL`() { + val millis = 1545733545000 // 25/12/2018 10:25:45 val timestamp = Timestamp(millis) insertGame(dtFinish = timestamp) @@ -73,4 +66,4 @@ class TestDateUtil: AbstractTest() val result = mainDatabase.executeQueryAggregate(sql) result shouldBe 1 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestDialogUtil.kt b/src/test/kotlin/dartzee/core/util/TestDialogUtil.kt index 0361b0b30..c1ecf9266 100644 --- a/src/test/kotlin/dartzee/core/util/TestDialogUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestDialogUtil.kt @@ -22,24 +22,26 @@ import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.mockk import io.mockk.verifySequence -import org.junit.jupiter.api.Test import java.io.File import javax.swing.SwingUtilities +import org.junit.jupiter.api.Test -class TestDialogUtil: AbstractTest() -{ +class TestDialogUtil : AbstractTest() { var factoryMock = mockk(relaxed = true) @Test - fun `Should pass method calls on to implementation`() - { + fun `Should pass method calls on to implementation`() { DialogUtil.init(factoryMock) DialogUtil.showInfoOLD("Info") DialogUtil.showLoadingDialogOLD("Loading...") DialogUtil.showQuestionOLD("Q") DialogUtil.dismissLoadingDialogOLD() - DialogUtil.showOption("Free Pizza", "Would you like some?", listOf("Yes please", "No thanks")) + DialogUtil.showOption( + "Free Pizza", + "Would you like some?", + listOf("Yes please", "No thanks") + ) DialogUtil.chooseDirectory(null) verifySequence { @@ -47,7 +49,11 @@ class TestDialogUtil: AbstractTest() factoryMock.showLoading("Loading...") factoryMock.showQuestion("Q", false) factoryMock.dismissLoading() - factoryMock.showOption("Free Pizza", "Would you like some?", listOf("Yes please", "No thanks")) + factoryMock.showOption( + "Free Pizza", + "Would you like some?", + listOf("Yes please", "No thanks") + ) factoryMock.chooseDirectory(null) } @@ -64,11 +70,11 @@ class TestDialogUtil: AbstractTest() } @Test - fun `Should log for INFO dialogs`() - { + fun `Should log for INFO dialogs`() { runAsync { DialogUtil.showInfo("Something useful") } - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Info dialog shown: Something useful" + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Info dialog shown: Something useful" getInfoDialog().clickOk() flushEdt() @@ -76,19 +82,18 @@ class TestDialogUtil: AbstractTest() } @Test - fun `Should log for ERROR dialogs`() - { + fun `Should log for ERROR dialogs`() { runAsync { DialogUtil.showError("Something bad") } - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Error dialog shown: Something bad" + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Error dialog shown: Something bad" getErrorDialog().clickOk() flushEdt() verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "Error dialog closed" } @Test - fun `Should show an ERROR dialog later`() - { + fun `Should show an ERROR dialog later`() { SwingUtilities.invokeLater { Thread.sleep(500) } DialogUtil.showErrorLater("Some error") dialogFactory.errorsShown.shouldBeEmpty() @@ -98,74 +103,79 @@ class TestDialogUtil: AbstractTest() } @Test - fun `Should log for QUESTION dialogs, with the correct selection`() - { + fun `Should log for QUESTION dialogs, with the correct selection`() { runAsync { DialogUtil.showQuestion("Do you like cheese?") } - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Question dialog shown: Do you like cheese?" + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Question dialog shown: Do you like cheese?" getQuestionDialog().clickYes() flushEdt() - verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "Question dialog closed - selected Yes" + verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe + "Question dialog closed - selected Yes" clearLogs() purgeWindows() runAsync { DialogUtil.showQuestion("Do you like mushrooms?") } - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Question dialog shown: Do you like mushrooms?" + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Question dialog shown: Do you like mushrooms?" getQuestionDialog().clickNo() flushEdt() - verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "Question dialog closed - selected No" + verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe + "Question dialog closed - selected No" clearLogs() purgeWindows() runAsync { DialogUtil.showQuestion("Do you want to delete all data?", true) } - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Question dialog shown: Do you want to delete all data?" + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Question dialog shown: Do you want to delete all data?" getQuestionDialog().clickCancel() flushEdt() - verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "Question dialog closed - selected Cancel" + verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe + "Question dialog closed - selected Cancel" } @Test - fun `Should log when showing and dismissing loading dialog`() - { + fun `Should log when showing and dismissing loading dialog`() { DialogUtil.showLoadingDialog("One moment...") flushEdt() - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Loading dialog shown: One moment..." + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Loading dialog shown: One moment..." DialogUtil.dismissLoadingDialog() verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "Loading dialog closed" } @Test - fun `Should not log if loading dialog wasn't visible`() - { + fun `Should not log if loading dialog wasn't visible`() { DialogUtil.dismissLoadingDialog() verifyNoLogs(CODE_DIALOG_CLOSED) } @Test - fun `Should log for OPTION dialogs, with the selection`() - { + fun `Should log for OPTION dialogs, with the selection`() { dialogFactory.optionSequence.add("Yes please") DialogUtil.showOption("Free Pizza", "Free pizza?", listOf("Yes please", "No thanks")) - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Option dialog shown: Free pizza?" - verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "Option dialog closed - selected Yes please" + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Option dialog shown: Free pizza?" + verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe + "Option dialog closed - selected Yes please" } @Test - fun `Should log for INPUT dialogs, with the selection`() - { + fun `Should log for INPUT dialogs, with the selection`() { dialogFactory.inputSelection = "Camembert" DialogUtil.showInput("Cheezoid", "Enter your favourite cheese") - verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "Input dialog shown: Enter your favourite cheese" - verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "Input dialog closed - selected Camembert" + verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe + "Input dialog shown: Enter your favourite cheese" + verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe + "Input dialog closed - selected Camembert" } @Test - fun `Should handle a null file when logging file selection`() - { + fun `Should handle a null file when logging file selection`() { dialogFactory.directoryToSelect = null DialogUtil.chooseDirectory(null) @@ -175,15 +185,14 @@ class TestDialogUtil: AbstractTest() } @Test - fun `Should log the file path when selecting a directory`() - { + fun `Should log the file path when selecting a directory`() { val f = File(TEST_ROOT) dialogFactory.directoryToSelect = f DialogUtil.chooseDirectory(null) verifyLog(CODE_DIALOG_SHOWN, Severity.INFO).message shouldBe "File selector dialog shown: " - verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe "File selector dialog closed - selected ${f.absolutePath}" + verifyLog(CODE_DIALOG_CLOSED, Severity.INFO).message shouldBe + "File selector dialog closed - selected ${f.absolutePath}" } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestEdtMonitor.kt b/src/test/kotlin/dartzee/core/util/TestEdtMonitor.kt index 22ee5b9e1..316618ec9 100644 --- a/src/test/kotlin/dartzee/core/util/TestEdtMonitor.kt +++ b/src/test/kotlin/dartzee/core/util/TestEdtMonitor.kt @@ -5,20 +5,18 @@ import dartzee.logging.CODE_EDT_FROZEN import dartzee.logging.Severity import io.kotest.matchers.concurrent.shouldBeAlive import io.kotest.matchers.concurrent.shouldNotBeAlive -import org.junit.jupiter.api.Test import javax.swing.SwingUtilities +import org.junit.jupiter.api.Test -class TestEdtMonitor : AbstractTest() -{ +class TestEdtMonitor : AbstractTest() { @Test - fun `Should keep running while the EDT is responsive, then stop and log an error when it freezes`() - { + fun `Should keep running while the EDT is responsive, then stop and log an error when it freezes`() { val t = EdtMonitor.start(500) t.shouldBeAlive() - SwingUtilities.invokeAndWait { } - SwingUtilities.invokeAndWait { } - SwingUtilities.invokeAndWait { } + SwingUtilities.invokeAndWait {} + SwingUtilities.invokeAndWait {} + SwingUtilities.invokeAndWait {} Thread.sleep(1000) @@ -30,4 +28,4 @@ class TestEdtMonitor : AbstractTest() t.shouldNotBeAlive() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestExtensionFunctions.kt b/src/test/kotlin/dartzee/core/util/TestExtensionFunctions.kt index fa4b2885a..40b9678fe 100644 --- a/src/test/kotlin/dartzee/core/util/TestExtensionFunctions.kt +++ b/src/test/kotlin/dartzee/core/util/TestExtensionFunctions.kt @@ -11,19 +11,16 @@ import io.mockk.spyk import io.mockk.verify import org.junit.jupiter.api.Test -class TestExtensionFunctions: AbstractTest() -{ +class TestExtensionFunctions : AbstractTest() { @Test - fun `IntRange descriptions`() - { + fun `IntRange descriptions`() { (1..1).getDescription() shouldBe "1" (1..3).getDescription() shouldBe "1 - 3" (1..Int.MAX_VALUE).getDescription() shouldBe "1+" } @Test - fun `Should only add unique elements`() - { + fun `Should only add unique elements`() { val list = mutableListOf() list.addUnique("foo") @@ -37,36 +34,43 @@ class TestExtensionFunctions: AbstractTest() } @Test - fun `Should return empty when permuting an empty list`() - { + fun `Should return empty when permuting an empty list`() { val list = listOf() list.getAllPermutations().size shouldBe 1 list.getAllPermutations()[0] shouldBe listOf() } @Test - fun `Should generate all permutations of a list`() - { + fun `Should generate all permutations of a list`() { val list = listOf(1, 2, 3) - list.getAllPermutations().shouldContainExactlyInAnyOrder(listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1)) + list + .getAllPermutations() + .shouldContainExactlyInAnyOrder( + listOf(1, 2, 3), + listOf(1, 3, 2), + listOf(2, 1, 3), + listOf(2, 3, 1), + listOf(3, 1, 2), + listOf(3, 2, 1) + ) } @Test - fun `Should not return duplicate permutations`() - { + fun `Should not return duplicate permutations`() { val list = listOf(1, 1, 2) - list.getAllPermutations().shouldContainExactlyInAnyOrder(listOf(1, 1, 2), listOf(1, 2, 1), listOf(2, 1, 1)) + list + .getAllPermutations() + .shouldContainExactlyInAnyOrder(listOf(1, 1, 2), listOf(1, 2, 1), listOf(2, 1, 1)) } - interface Validator - { + interface Validator { fun isValid(text: String, index: Int): Boolean } + @Test - fun `Should pass the element & index to the predicate correctly`() - { + fun `Should pass the element & index to the predicate correctly`() { val mockValidator = mockk() every { mockValidator.isValid(any(), any()) } returns true @@ -79,14 +83,12 @@ class TestExtensionFunctions: AbstractTest() verify { mockValidator.isValid("three", 2) } } - class ElementValidator - { + class ElementValidator { fun isValid(text: String, index: Int) = text == index.toString() } @Test - fun `Should stop as soon as an element is found to be invalid`() - { + fun `Should stop as soon as an element is found to be invalid`() { val validator = spyk() val list = listOf("foo", "bar", "baz") @@ -100,8 +102,7 @@ class TestExtensionFunctions: AbstractTest() } @Test - fun `Should return the correct result based on whether the contents were all valid`() - { + fun `Should return the correct result based on whether the contents were all valid`() { val validator = ElementValidator() val invalidList = listOf("0", "1", "2", "4") @@ -112,8 +113,7 @@ class TestExtensionFunctions: AbstractTest() } @Test - fun `Should sort in the correct order`() - { + fun `Should sort in the correct order`() { val list = listOf(1, 3, 2, 5, 4) val ascending = list.sortedBy(false) { it } @@ -124,8 +124,7 @@ class TestExtensionFunctions: AbstractTest() } @Test - fun `Should return hash map values sorted by key`() - { + fun `Should return hash map values sorted by key`() { val map = mutableMapOf() map[1] = "First" map[3] = "Third" @@ -136,8 +135,7 @@ class TestExtensionFunctions: AbstractTest() } @Test - fun `Should return 0 for an empty list, or minmax otherwise`() - { + fun `Should return 0 for an empty list, or minmax otherwise`() { val list = mutableListOf() list.minOrZero() shouldBe 0 @@ -152,8 +150,7 @@ class TestExtensionFunctions: AbstractTest() } @Test - fun `Should correctly report the longest streak`() - { + fun `Should correctly report the longest streak`() { val list: List = listOf(1, 2, "a", "b", "c", 4, "d", 6, 7, 8, 9, "e", "f", 1) list.getLongestStreak { it is String } shouldBe listOf("a", "b", "c") @@ -161,4 +158,4 @@ class TestExtensionFunctions: AbstractTest() list.getLongestStreak { true } shouldBe list list.getLongestStreak { false } shouldBe emptyList() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestFileUtil.kt b/src/test/kotlin/dartzee/core/util/TestFileUtil.kt index a4908ae46..78c20a3fa 100644 --- a/src/test/kotlin/dartzee/core/util/TestFileUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestFileUtil.kt @@ -6,34 +6,30 @@ import dartzee.logging.Severity import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.awt.Dimension import java.io.File import java.nio.file.DirectoryNotEmptyException import javax.swing.ImageIcon +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestFileUtil: AbstractTest() -{ +class TestFileUtil : AbstractTest() { private val testDirectory = File("Test/") @BeforeEach - fun beforeEach() - { + fun beforeEach() { testDirectory.deleteRecursively() testDirectory.mkdirs() } @AfterEach - fun afterEach() - { + fun afterEach() { testDirectory.deleteRecursively() } @Test - fun `Should successfully delete a file`() - { + fun `Should successfully delete a file`() { val f = File("Test/Test.txt") f.createNewFile() f.exists() shouldBe true @@ -44,15 +40,13 @@ class TestFileUtil: AbstractTest() } @Test - fun `Should handle a non-existent file`() - { + fun `Should handle a non-existent file`() { val result = FileUtil.deleteFileIfExists("DoesNotExist.txt") result shouldBe false } @Test - fun `Should stack trace and return false if the deletion fails`() - { + fun `Should stack trace and return false if the deletion fails`() { val f = File("Test/File.txt") f.createNewFile() @@ -64,8 +58,7 @@ class TestFileUtil: AbstractTest() } @Test - fun `Should swap in a file successfully`() - { + fun `Should swap in a file successfully`() { val current = File("Test/Current.txt") current.createNewFile() current.writeText("Current") @@ -82,8 +75,7 @@ class TestFileUtil: AbstractTest() } @Test - fun `Should swap in a directory successfully`() - { + fun `Should swap in a directory successfully`() { File("Test/Current").mkdir() File("Test/New").mkdir() @@ -103,8 +95,7 @@ class TestFileUtil: AbstractTest() } @Test - fun `Should read image dimensions correctly`() - { + fun `Should read image dimensions correctly`() { val bean = javaClass.getResource("/Bean.png")!!.toURI() val statsIcon = javaClass.getResource("/stats_large.png")!!.toURI() @@ -113,12 +104,11 @@ class TestFileUtil: AbstractTest() } @Test - fun `Should extract correct bytes`() - { + fun `Should extract correct bytes`() { val bytes = FileUtil.getByteArrayForResource("/Bean.png") val ii = ImageIcon(bytes) ii.iconWidth shouldBe 150 ii.iconHeight shouldBe 150 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestMathsUtil.kt b/src/test/kotlin/dartzee/core/util/TestMathsUtil.kt index ce3055b3f..549474691 100644 --- a/src/test/kotlin/dartzee/core/util/TestMathsUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestMathsUtil.kt @@ -5,11 +5,9 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestMathsUtil: AbstractTest() -{ +class TestMathsUtil : AbstractTest() { @Test - fun `Should round to the specified dp`() - { + fun `Should round to the specified dp`() { val number = 20.547 MathsUtil.round(number, 0) shouldBe 21.0 @@ -19,8 +17,7 @@ class TestMathsUtil: AbstractTest() } @Test - fun `Should get percentages to 1 dp`() - { + fun `Should get percentages to 1 dp`() { val total = 10000.0 MathsUtil.getPercentage(1, total) shouldBe 0.0 @@ -34,8 +31,7 @@ class TestMathsUtil: AbstractTest() } @Test - fun `Percentages should still work for large numbers`() - { + fun `Percentages should still work for large numbers`() { val total = 123456788.0 MathsUtil.getPercentage(123456788, total) shouldBe 100.0 @@ -43,8 +39,7 @@ class TestMathsUtil: AbstractTest() } @Test - fun `Percentage for thirds`() - { + fun `Percentage for thirds`() { val total = 3.0 MathsUtil.getPercentage(0, total) shouldBe 0.0 @@ -53,8 +48,7 @@ class TestMathsUtil: AbstractTest() } @Test - fun `Test ceiling divide`() - { + fun `Test ceiling divide`() { 4.ceilDiv(2) shouldBe 2 7.ceilDiv(3) shouldBe 3 5.ceilDiv(2) shouldBe 3 @@ -65,17 +59,106 @@ class TestMathsUtil: AbstractTest() fun `mapStepped should not run into any stupid double precision nonsense`() { val list = Pair(-5.0, 5.0).mapStepped(0.1) { it } list.shouldContainExactly( - -5.0, -4.9, -4.8, -4.7, -4.6, -4.5, -4.4, -4.3, -4.2, -4.1, - -4.0, -3.9, -3.8, -3.7, -3.6, -3.5, -3.4, -3.3, -3.2, -3.1, - -3.0, -2.9, -2.8, -2.7, -2.6, -2.5, -2.4, -2.3, -2.2, -2.1, - -2.0, -1.9, -1.8, -1.7, -1.6, -1.5, -1.4, -1.3, -1.2, -1.1, - -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, + -5.0, + -4.9, + -4.8, + -4.7, + -4.6, + -4.5, + -4.4, + -4.3, + -4.2, + -4.1, + -4.0, + -3.9, + -3.8, + -3.7, + -3.6, + -3.5, + -3.4, + -3.3, + -3.2, + -3.1, + -3.0, + -2.9, + -2.8, + -2.7, + -2.6, + -2.5, + -2.4, + -2.3, + -2.2, + -2.1, + -2.0, + -1.9, + -1.8, + -1.7, + -1.6, + -1.5, + -1.4, + -1.3, + -1.2, + -1.1, + -1.0, + -0.9, + -0.8, + -0.7, + -0.6, + -0.5, + -0.4, + -0.3, + -0.2, + -0.1, 0.0, - 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, - 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, - 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0, - 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4.0, - 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9 + 0.1, + 0.2, + 0.3, + 0.4, + 0.5, + 0.6, + 0.7, + 0.8, + 0.9, + 1.0, + 1.1, + 1.2, + 1.3, + 1.4, + 1.5, + 1.6, + 1.7, + 1.8, + 1.9, + 2.0, + 2.1, + 2.2, + 2.3, + 2.4, + 2.5, + 2.6, + 2.7, + 2.8, + 2.9, + 3.0, + 3.1, + 3.2, + 3.3, + 3.4, + 3.5, + 3.6, + 3.7, + 3.8, + 3.9, + 4.0, + 4.1, + 4.2, + 4.3, + 4.4, + 4.5, + 4.6, + 4.7, + 4.8, + 4.9 ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestStringUtil.kt b/src/test/kotlin/dartzee/core/util/TestStringUtil.kt index f1b084e49..b50b17885 100644 --- a/src/test/kotlin/dartzee/core/util/TestStringUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestStringUtil.kt @@ -4,11 +4,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestStringUtil: AbstractTest() -{ +class TestStringUtil : AbstractTest() { @Test - fun `Should return the right position descriptions for 1 - 13`() - { + fun `Should return the right position descriptions for 1 - 13`() { StringUtil.convertOrdinalToText(1) shouldBe "1st" StringUtil.convertOrdinalToText(2) shouldBe "2nd" StringUtil.convertOrdinalToText(3) shouldBe "3rd" @@ -25,10 +23,9 @@ class TestStringUtil: AbstractTest() } @Test - fun `Should return the right position descriptions for random other numbers`() - { + fun `Should return the right position descriptions for random other numbers`() { StringUtil.convertOrdinalToText(20) shouldBe "20th" StringUtil.convertOrdinalToText(51) shouldBe "51st" StringUtil.convertOrdinalToText(102) shouldBe "102nd" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestTableUtil.kt b/src/test/kotlin/dartzee/core/util/TestTableUtil.kt index 69d0a259b..e9f99106a 100644 --- a/src/test/kotlin/dartzee/core/util/TestTableUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestTableUtil.kt @@ -6,11 +6,9 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestTableUtil: AbstractTest() -{ +class TestTableUtil : AbstractTest() { @Test - fun `Default model should return all column values`() - { + fun `Default model should return all column values`() { val model = TableUtil.DefaultModel() model.addColumn("Foo") model.getColumnValues(0).shouldBeEmpty() @@ -23,8 +21,7 @@ class TestTableUtil: AbstractTest() } @Test - fun `Should set a list of column names`() - { + fun `Should set a list of column names`() { val model = TableUtil.DefaultModel() model.setColumnNames(listOf("A", "B", "C")) @@ -35,8 +32,7 @@ class TestTableUtil: AbstractTest() } @Test - fun `Should support adding multiple rows at once`() - { + fun `Should support adding multiple rows at once`() { val model = TableUtil.DefaultModel() model.addColumn("Foo") @@ -50,8 +46,7 @@ class TestTableUtil: AbstractTest() } @Test - fun `Should be able to clear all rows`() - { + fun `Should be able to clear all rows`() { val model = TableUtil.DefaultModel() model.addColumn("Foo") @@ -62,11 +57,10 @@ class TestTableUtil: AbstractTest() } @Test - fun `Should be able to clear an empty table model`() - { + fun `Should be able to clear an empty table model`() { val model = TableUtil.DefaultModel() model.addColumn("Foo") model.clear() model.rowCount shouldBe 0 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/core/util/TestXmlUtil.kt b/src/test/kotlin/dartzee/core/util/TestXmlUtil.kt index 92a9698a0..59e9f9ef1 100644 --- a/src/test/kotlin/dartzee/core/util/TestXmlUtil.kt +++ b/src/test/kotlin/dartzee/core/util/TestXmlUtil.kt @@ -4,11 +4,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestXmlUtil: AbstractTest() -{ +class TestXmlUtil : AbstractTest() { @Test - fun `Should convert an XML doc to a string`() - { + fun `Should convert an XML doc to a string`() { val doc = XmlUtil.factoryNewDocument() val rootElement = doc.createRootElement("Root") @@ -22,22 +20,19 @@ class TestXmlUtil: AbstractTest() } @Test - fun `Should handle an empty document`() - { + fun `Should handle an empty document`() { val doc = XmlUtil.factoryNewDocument() doc.toXmlString() shouldBe "" } @Test - fun `Should return null for an invalid string`() - { + fun `Should return null for an invalid string`() { val str = "bugg'rit" str.toXmlDoc() shouldBe null } @Test - fun `Should convert a valid xml string back to a document`() - { + fun `Should convert a valid xml string back to a document`() { val str = """""" val doc = str.toXmlDoc()!! @@ -47,8 +42,7 @@ class TestXmlUtil: AbstractTest() } @Test - fun `Should create a root element and append it to the doc`() - { + fun `Should create a root element and append it to the doc`() { val doc = XmlUtil.factoryNewDocument() doc.createRootElement("Baz") @@ -57,8 +51,7 @@ class TestXmlUtil: AbstractTest() } @Test - fun `Should handle setting non-string attributes`() - { + fun `Should handle setting non-string attributes`() { val doc = XmlUtil.factoryNewDocument() val root = doc.createRootElement("Root") @@ -67,8 +60,7 @@ class TestXmlUtil: AbstractTest() } @Test - fun `Should return integer value if valid`() - { + fun `Should return integer value if valid`() { val doc = XmlUtil.factoryNewDocument() val root = doc.createRootElement("Root") @@ -77,8 +69,7 @@ class TestXmlUtil: AbstractTest() } @Test - fun `Should return defaultValue if not present`() - { + fun `Should return defaultValue if not present`() { val doc = XmlUtil.factoryNewDocument() val root = doc.createRootElement("Root") @@ -86,11 +77,10 @@ class TestXmlUtil: AbstractTest() } @Test - fun `Should return 0 if not present and no default value specified`() - { + fun `Should return 0 if not present and no default value specified`() { val doc = XmlUtil.factoryNewDocument() val root = doc.createRootElement("Root") root.getAttributeInt("Foo") shouldBe 0 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/AbstractDartzeeRuleTest.kt b/src/test/kotlin/dartzee/dartzee/AbstractDartzeeRuleTest.kt index ebb05ecf2..edc5e8e6b 100644 --- a/src/test/kotlin/dartzee/dartzee/AbstractDartzeeRuleTest.kt +++ b/src/test/kotlin/dartzee/dartzee/AbstractDartzeeRuleTest.kt @@ -6,15 +6,13 @@ import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -abstract class AbstractDartzeeRuleTest: AbstractTest() -{ +abstract class AbstractDartzeeRuleTest : AbstractTest() { abstract fun factory(): E open val emptyIsValid = true @Test - fun `Should be parsable from an atomic tag`() - { + fun `Should be parsable from an atomic tag`() { val rule = factory() val tag = "<${rule.getRuleIdentifier()}/>" @@ -23,28 +21,22 @@ abstract class AbstractDartzeeRuleTest: AbstractTest() } @Test - open fun `Validate empty rule`() - { + open fun `Validate empty rule`() { val rule = factory() rule.validate().isEmpty() shouldBe emptyIsValid } @Test - fun `Should be in the correct rule list`() - { + fun `Should be in the correct rule list`() { val rule = factory() getRuleList().filter { rule.javaClass.isInstance(it) } shouldHaveSize 1 } - private fun getRuleList(): List - { - return if (factory() is AbstractDartzeeDartRule) - { + private fun getRuleList(): List { + return if (factory() is AbstractDartzeeDartRule) { getAllDartRules() - } - else - { + } else { getAllAggregateRules() } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/TestDartzeeAimCalculator.kt b/src/test/kotlin/dartzee/dartzee/TestDartzeeAimCalculator.kt index 48f2336a5..da70bfc4d 100644 --- a/src/test/kotlin/dartzee/dartzee/TestDartzeeAimCalculator.kt +++ b/src/test/kotlin/dartzee/dartzee/TestDartzeeAimCalculator.kt @@ -21,20 +21,17 @@ import org.junit.jupiter.api.Test private val allNonMisses = getAllNonMissSegments() private val calculator = DartzeeAimCalculator() -class TestDartzeeAimCalculator: AbstractTest() -{ +class TestDartzeeAimCalculator : AbstractTest() { @Test @Tag("screenshot") - fun `Should aim at the bullseye for a fully valid dartboard`() - { + fun `Should aim at the bullseye for a fully valid dartboard`() { val segmentStatuses = SegmentStatuses(allNonMisses, allNonMisses) verifyAim(segmentStatuses, "All valid") } @Test @Tag("screenshot") - fun `Should aim at the right place for all odd`() - { + fun `Should aim at the right place for all odd`() { val odd = allNonMisses.filter { DartzeeDartRuleOdd().isValidSegment(it) } val segmentStatuses = SegmentStatuses(odd, odd) verifyAim(segmentStatuses, "Odd") @@ -42,8 +39,7 @@ class TestDartzeeAimCalculator: AbstractTest() @Test @Tag("screenshot") - fun `Should aim based on valid segments for if cautious`() - { + fun `Should aim based on valid segments for if cautious`() { val twenties = allNonMisses.filter { it.score == 20 } val segmentStatuses = SegmentStatuses(twenties, allNonMisses) verifyAim(segmentStatuses, "Score 20s - cautious", false) @@ -51,8 +47,7 @@ class TestDartzeeAimCalculator: AbstractTest() @Test @Tag("screenshot") - fun `Should aim based on scoring segments if aggressive`() - { + fun `Should aim based on scoring segments if aggressive`() { val twenties = allNonMisses.filter { it.score == 20 } val segmentStatuses = SegmentStatuses(twenties, allNonMisses) verifyAim(segmentStatuses, "Score 20s - aggressive", true) @@ -60,8 +55,7 @@ class TestDartzeeAimCalculator: AbstractTest() @Test @Tag("screenshot") - fun `Should go on score for tie breakers`() - { + fun `Should go on score for tie breakers`() { val trebles = allNonMisses.filter { it.getMultiplier() == 3 } val segmentStatuses = SegmentStatuses(trebles, trebles) verifyAim(segmentStatuses, "Trebles") @@ -72,8 +66,7 @@ class TestDartzeeAimCalculator: AbstractTest() @Test @Tag("screenshot") - fun `Should aim correctly if bullseye is missing`() - { + fun `Should aim correctly if bullseye is missing`() { val nonBull = allNonMisses.filter { it.getTotal() != 50 } val segmentStatuses = SegmentStatuses(nonBull, nonBull) verifyAim(segmentStatuses, "No bullseye") @@ -81,25 +74,23 @@ class TestDartzeeAimCalculator: AbstractTest() @Test @Tag("screenshot") - fun `Should aim correctly for some missing trebles`() - { - val segments = allNonMisses.filterNot { it.getMultiplier() == 3 && (it.score == 20 || it.score == 3) } + fun `Should aim correctly for some missing trebles`() { + val segments = + allNonMisses.filterNot { it.getMultiplier() == 3 && (it.score == 20 || it.score == 3) } val segmentStatuses = SegmentStatuses(segments, segments) verifyAim(segmentStatuses, "Missing trebles") } @Test @Tag("screenshot") - fun `Should revert to aiming at valid segments if there are no scoring segments`() - { + fun `Should revert to aiming at valid segments if there are no scoring segments`() { val validSegments = allNonMisses.filter { it.score == 1 } val segmentStatuses = SegmentStatuses(emptyList(), validSegments) verifyAim(segmentStatuses, "No scoring segments", true) } @Test - fun `Should deliberately miss if no valid segments`() - { + fun `Should deliberately miss if no valid segments`() { val segmentStatuses = SegmentStatuses(emptyList(), emptyList()) val pt = calculator.getPointToAimFor(AI_DARTBOARD, segmentStatuses, true) @@ -107,8 +98,7 @@ class TestDartzeeAimCalculator: AbstractTest() } @Test - fun `Should deliberately miss if only valid segments are misses`() - { + fun `Should deliberately miss if only valid segments are misses`() { val segmentStatuses = SegmentStatuses(listOf(missTwenty), listOf(missTwenty)) val pt = calculator.getPointToAimFor(AI_DARTBOARD, segmentStatuses, true) @@ -117,24 +107,24 @@ class TestDartzeeAimCalculator: AbstractTest() @Test @Tag("integration") - fun `Should be performant`() - { + fun `Should be performant`() { val awkward = allNonMisses.filter { it.score != 25 } val segmentStatuses = SegmentStatuses(awkward, awkward) val dartboard = ComputationalDartboard(400, 400) val timer = DurationTimer() - repeat(10) { - calculator.getPointToAimFor(dartboard, segmentStatuses, true) - } + repeat(10) { calculator.getPointToAimFor(dartboard, segmentStatuses, true) } val timeElapsed = timer.getDuration() timeElapsed shouldBeLessThan 5000 } - private fun verifyAim(segmentStatuses: SegmentStatuses, screenshotName: String, aggressive: Boolean = false) - { + private fun verifyAim( + segmentStatuses: SegmentStatuses, + screenshotName: String, + aggressive: Boolean = false + ) { val dartboard = ComputationalDartboard(400, 400) val pt = calculator.getPointToAimFor(dartboard, segmentStatuses, aggressive) @@ -145,4 +135,4 @@ class TestDartzeeAimCalculator: AbstractTest() val lbl = oldDartboard.markPoints(listOf(pt)) lbl.shouldMatchImage(screenshotName) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/TestDartzeeCalculator.kt b/src/test/kotlin/dartzee/dartzee/TestDartzeeCalculator.kt index 9616ecee2..0d0ae4a45 100644 --- a/src/test/kotlin/dartzee/dartzee/TestDartzeeCalculator.kt +++ b/src/test/kotlin/dartzee/dartzee/TestDartzeeCalculator.kt @@ -34,19 +34,16 @@ import io.kotest.matchers.doubles.shouldBeExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAllPossibilities: AbstractTest() -{ +class TestAllPossibilities : AbstractTest() { @Test - fun `Should generate the right number of possibilities if given no darts`() - { + fun `Should generate the right number of possibilities if given no darts`() { val possibilities = DartzeeCalculator().generateAllPossibilities(listOf()) possibilities.size shouldBe 83 * 83 * 83 possibilities.all { it.size == 3 } shouldBe true } @Test - fun `Should generate the right number of possibilities if given 1 starting dart`() - { + fun `Should generate the right number of possibilities if given 1 starting dart`() { val dart = Dart(20, 3, segmentType = SegmentType.TREBLE) val possibilities = DartzeeCalculator().generateAllPossibilities(listOf(dart)) @@ -57,8 +54,7 @@ class TestAllPossibilities: AbstractTest() } @Test - fun `Should generate the right number of possibilities if given 2 starting darts`() - { + fun `Should generate the right number of possibilities if given 2 starting darts`() { val dartOne = Dart(20, 3, segmentType = SegmentType.TREBLE) val dartTwo = Dart(19, 2, segmentType = SegmentType.DOUBLE) @@ -70,19 +66,19 @@ class TestAllPossibilities: AbstractTest() } } -class TestValidSegments: AbstractTest() -{ +class TestValidSegments : AbstractTest() { @Test - fun `getValidSegments should return the right results for the first dart`() - { - val rule = makeDartzeeRuleDto( - DartzeeDartRuleEven(), - DartzeeDartRuleOdd(), - DartzeeDartRuleOuter(), - inOrder = true - ) + fun `getValidSegments should return the right results for the first dart`() { + val rule = + makeDartzeeRuleDto( + DartzeeDartRuleEven(), + DartzeeDartRuleOdd(), + DartzeeDartRuleOuter(), + inOrder = true + ) - val expectedSegments = getAllNonMissSegments().filter { DartzeeDartRuleEven().isValidSegment(it) } + val expectedSegments = + getAllNonMissSegments().filter { DartzeeDartRuleEven().isValidSegment(it) } val firstSegments = DartzeeCalculator().getValidSegments(rule, listOf()) firstSegments.validSegments.shouldContainExactlyInAnyOrder(expectedSegments) @@ -90,69 +86,88 @@ class TestValidSegments: AbstractTest() } @Test - fun `should return the right results for the second dart`() - { - val rule = makeDartzeeRuleDto( + fun `should return the right results for the second dart`() { + val rule = + makeDartzeeRuleDto( DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleOuter(), inOrder = true - ) + ) - val expectedSegments = getAllNonMissSegments().filter { DartzeeDartRuleOdd().isValidSegment(it) } - val secondSegments = DartzeeCalculator().getValidSegments(rule, listOf(makeDart(2, 1, SegmentType.OUTER_SINGLE))) + val expectedSegments = + getAllNonMissSegments().filter { DartzeeDartRuleOdd().isValidSegment(it) } + val secondSegments = + DartzeeCalculator() + .getValidSegments(rule, listOf(makeDart(2, 1, SegmentType.OUTER_SINGLE))) secondSegments.validSegments.shouldContainExactlyInAnyOrder(expectedSegments) secondSegments.scoringSegments.shouldContainExactlyInAnyOrder(expectedSegments) } @Test - fun `should return the right results for the third dart`() - { - val rule = makeDartzeeRuleDto( + fun `should return the right results for the third dart`() { + val rule = + makeDartzeeRuleDto( DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleOuter(), inOrder = true - ) - - val dartsThrown = listOf(makeDart(2, 1, SegmentType.OUTER_SINGLE), makeDart(3, 1, SegmentType.INNER_SINGLE)) - val expectedSegments = getAllNonMissSegments().filter { DartzeeDartRuleOuter().isValidSegment(it) } + ) + + val dartsThrown = + listOf( + makeDart(2, 1, SegmentType.OUTER_SINGLE), + makeDart(3, 1, SegmentType.INNER_SINGLE) + ) + val expectedSegments = + getAllNonMissSegments().filter { DartzeeDartRuleOuter().isValidSegment(it) } val thirdSegments = DartzeeCalculator().getValidSegments(rule, dartsThrown) thirdSegments.validSegments.shouldContainExactlyInAnyOrder(expectedSegments) thirdSegments.scoringSegments.shouldContainExactlyInAnyOrder(expectedSegments) } @Test - fun `should return no results for darts 2 or 3 if the rule is already failed`() - { - val rule = makeDartzeeRuleDto( + fun `should return no results for darts 2 or 3 if the rule is already failed`() { + val rule = + makeDartzeeRuleDto( DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleOuter(), inOrder = true - ) + ) - val secondSegments = DartzeeCalculator().getValidSegments(rule, listOf(makeDart(3, 1, SegmentType.OUTER_SINGLE))) + val secondSegments = + DartzeeCalculator() + .getValidSegments(rule, listOf(makeDart(3, 1, SegmentType.OUTER_SINGLE))) secondSegments.validSegments.shouldBeEmpty() secondSegments.scoringSegments.shouldBeEmpty() - val invalidSecondDart = listOf(makeDart(2, 1, SegmentType.OUTER_SINGLE), makeDart(2, 1, SegmentType.OUTER_SINGLE)) + val invalidSecondDart = + listOf( + makeDart(2, 1, SegmentType.OUTER_SINGLE), + makeDart(2, 1, SegmentType.OUTER_SINGLE) + ) val thirdSegments = DartzeeCalculator().getValidSegments(rule, invalidSecondDart) thirdSegments.validSegments.shouldBeEmpty() thirdSegments.scoringSegments.shouldBeEmpty() } @Test - fun `Should return empty list if three darts thrown and rule has failed`() - { - val rule = makeDartzeeRuleDto( + fun `Should return empty list if three darts thrown and rule has failed`() { + val rule = + makeDartzeeRuleDto( DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleOuter(), inOrder = true - ) - - val dartsThrown = listOf(makeDart(2, 1, SegmentType.DOUBLE), makeDart(19, 3, SegmentType.TREBLE), makeDart(20, 0, SegmentType.MISS)) + ) + + val dartsThrown = + listOf( + makeDart(2, 1, SegmentType.DOUBLE), + makeDart(19, 3, SegmentType.TREBLE), + makeDart(20, 0, SegmentType.MISS) + ) val result = DartzeeCalculator().getValidSegments(rule, dartsThrown) result.scoringSegments.shouldBeEmpty() @@ -162,16 +177,21 @@ class TestValidSegments: AbstractTest() } @Test - fun `Should return the segments for dart 3 if the rule has been passed`() - { - val rule = makeDartzeeRuleDto( + fun `Should return the segments for dart 3 if the rule has been passed`() { + val rule = + makeDartzeeRuleDto( DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleOuter(), inOrder = true - ) - - val dartsThrown = listOf(makeDart(2, 1, SegmentType.DOUBLE), makeDart(19, 3, SegmentType.TREBLE), makeDart(20, 2, SegmentType.DOUBLE)) + ) + + val dartsThrown = + listOf( + makeDart(2, 1, SegmentType.DOUBLE), + makeDart(19, 3, SegmentType.TREBLE), + makeDart(20, 2, SegmentType.DOUBLE) + ) val result = DartzeeCalculator().getValidSegments(rule, dartsThrown) result.scoringSegments.shouldContainExactlyInAnyOrder(getOuterSegments()) @@ -179,36 +199,62 @@ class TestValidSegments: AbstractTest() } @Test - fun `Should handle dart rules that can be in any order`() - { - val rule = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(19), makeScoreRule(18), inOrder = false) - - val expectedSegments = getAllNonMissSegments().filter { listOf(20, 19, 18).contains(it.score) } + fun `Should handle dart rules that can be in any order`() { + val rule = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(19), + makeScoreRule(18), + inOrder = false + ) + + val expectedSegments = + getAllNonMissSegments().filter { listOf(20, 19, 18).contains(it.score) } val result = DartzeeCalculator().getValidSegments(rule, listOf()) result.scoringSegments.shouldContainExactlyInAnyOrder(expectedSegments) result.validSegments.shouldContainExactlyInAnyOrder(expectedSegments) - val resultTwo = DartzeeCalculator().getValidSegments(rule, listOf(makeDart(20, 1, SegmentType.OUTER_SINGLE))) - resultTwo.validSegments.shouldContainExactlyInAnyOrder(expectedSegments.filter { it.score != 20 }) - resultTwo.scoringSegments.shouldContainExactlyInAnyOrder(expectedSegments.filter { it.score != 20 }) + val resultTwo = + DartzeeCalculator() + .getValidSegments(rule, listOf(makeDart(20, 1, SegmentType.OUTER_SINGLE))) + resultTwo.validSegments.shouldContainExactlyInAnyOrder( + expectedSegments.filter { it.score != 20 } + ) + resultTwo.scoringSegments.shouldContainExactlyInAnyOrder( + expectedSegments.filter { it.score != 20 } + ) } @Test - fun `Should yield sensible probabilities`() - { - val rule = makeDartzeeRuleDto(DartzeeDartRuleOdd(), DartzeeDartRuleAny(), DartzeeDartRuleAny(), inOrder = true, allowMisses = true) + fun `Should yield sensible probabilities`() { + val rule = + makeDartzeeRuleDto( + DartzeeDartRuleOdd(), + DartzeeDartRuleAny(), + DartzeeDartRuleAny(), + inOrder = true, + allowMisses = true + ) val result = DartzeeCalculator().getValidSegments(rule, listOf()) result.percentage.shouldBeBetween(49.0, 51.0, 0.0) - val resultTwo = DartzeeCalculator().getValidSegments(rule, listOf(makeDart(13, 1, SegmentType.OUTER_SINGLE))) + val resultTwo = + DartzeeCalculator() + .getValidSegments(rule, listOf(makeDart(13, 1, SegmentType.OUTER_SINGLE))) resultTwo.percentage.shouldBeExactly(100.0) } @Test - fun `should combine total and darts rules correctly`() - { - val rule = makeDartzeeRuleDto(DartzeeDartRuleEven(), DartzeeDartRuleEven(), DartzeeDartRuleEven(), makeTotalScoreRule(20), true) + fun `should combine total and darts rules correctly`() { + val rule = + makeDartzeeRuleDto( + DartzeeDartRuleEven(), + DartzeeDartRuleEven(), + DartzeeDartRuleEven(), + makeTotalScoreRule(20), + true + ) val segments = DartzeeCalculator().getValidSegments(rule, listOf()) @@ -217,10 +263,21 @@ class TestValidSegments: AbstractTest() } @Test - fun `should not cache results between calculations`() - { - val ruleOne = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(19), makeScoreRule(18), inOrder = false) - val ruleTwo = makeDartzeeRuleDto(makeScoreRule(1), makeScoreRule(2), makeScoreRule(3), inOrder = false) + fun `should not cache results between calculations`() { + val ruleOne = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(19), + makeScoreRule(18), + inOrder = false + ) + val ruleTwo = + makeDartzeeRuleDto( + makeScoreRule(1), + makeScoreRule(2), + makeScoreRule(3), + inOrder = false + ) val calculator = DartzeeCalculator() @@ -234,8 +291,7 @@ class TestValidSegments: AbstractTest() } @Test - fun `Should distinguish scoring segments from valid ones for Score X rules`() - { + fun `Should distinguish scoring segments from valid ones for Score X rules`() { val dartRule = makeScoreRule(20) val rule = makeDartzeeRuleDto(dartRule) val calculator = DartzeeCalculator() @@ -243,30 +299,31 @@ class TestValidSegments: AbstractTest() val expectedScoringSegments = getAllNonMissSegments().filter { dartRule.isValidSegment(it) } val expectedValidSegments = getAllNonMissSegments() - //0 darts + // 0 darts val firstSegments = calculator.getValidSegments(rule, emptyList()) firstSegments.scoringSegments.shouldContainExactlyInAnyOrder(expectedScoringSegments) firstSegments.validSegments.shouldContainExactlyInAnyOrder(expectedValidSegments) - //1 dart - non-20s should still be valid + // 1 dart - non-20s should still be valid val secondSegments = calculator.getValidSegments(rule, listOf(makeDart(19, 1))) secondSegments.scoringSegments.shouldContainExactlyInAnyOrder(expectedScoringSegments) secondSegments.validSegments.shouldContainExactlyInAnyOrder(expectedValidSegments) - //2 darts - non-20s should no longer be valid - val thirdSegments = calculator.getValidSegments(rule, listOf(makeDart(19, 1), makeDart(19, 1))) + // 2 darts - non-20s should no longer be valid + val thirdSegments = + calculator.getValidSegments(rule, listOf(makeDart(19, 1), makeDart(19, 1))) thirdSegments.scoringSegments.shouldContainExactlyInAnyOrder(expectedScoringSegments) thirdSegments.validSegments.shouldContainExactlyInAnyOrder(expectedScoringSegments) - //2 darts, but with a hit - non-20s should be valid - val thirdSegmentsWithHit = calculator.getValidSegments(rule, listOf(makeDart(19, 1), makeDart(20, 1))) + // 2 darts, but with a hit - non-20s should be valid + val thirdSegmentsWithHit = + calculator.getValidSegments(rule, listOf(makeDart(19, 1), makeDart(20, 1))) thirdSegmentsWithHit.scoringSegments.shouldContainExactlyInAnyOrder(expectedScoringSegments) thirdSegmentsWithHit.validSegments.shouldContainExactlyInAnyOrder(expectedValidSegments) } @Test - fun `Should return a miss segment as valid if missing is an option`() - { + fun `Should return a miss segment as valid if missing is an option`() { val totalRule = makeTotalScoreRule(20) val rule = makeDartzeeRuleDto(aggregateRule = totalRule, allowMisses = true) @@ -278,26 +335,33 @@ class TestValidSegments: AbstractTest() } } -class TestValidCombinations: AbstractTest() -{ +class TestValidCombinations : AbstractTest() { @Test - fun `should correctly identify all permutations as valid if no ordering required`() - { - val rule = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(19), makeScoreRule(18), inOrder = false) + fun `should correctly identify all permutations as valid if no ordering required`() { + val rule = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(19), + makeScoreRule(18), + inOrder = false + ) val segments = listOf(doubleNineteen, singleTwenty, singleEighteen) val permutations = segments.getAllPermutations() - permutations.forEach { - DartzeeCalculator().isValidCombination(it, rule) shouldBe true - } + permutations.forEach { DartzeeCalculator().isValidCombination(it, rule) shouldBe true } } @Test - fun `should enforce ordering correctly`() - { - val rule = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(19), makeScoreRule(18), inOrder = true) + fun `should enforce ordering correctly`() { + val rule = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(19), + makeScoreRule(18), + inOrder = true + ) val orderedSegments = listOf(singleTwenty, singleNineteen, singleEighteen) @@ -309,39 +373,65 @@ class TestValidCombinations: AbstractTest() } @Test - fun `should test for both total and dart rules`() - { - val rule = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(19), makeScoreRule(18), DartzeeTotalRuleEven(), true) - - DartzeeCalculator().isValidCombination(listOf(singleTwenty, singleNineteen, singleEighteen), rule) shouldBe false - DartzeeCalculator().isValidCombination(listOf(singleEighteen, singleEighteen, singleEighteen), rule) shouldBe false - DartzeeCalculator().isValidCombination(listOf(singleTwenty, doubleNineteen, singleEighteen), rule) shouldBe true + fun `should test for both total and dart rules`() { + val rule = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(19), + makeScoreRule(18), + DartzeeTotalRuleEven(), + true + ) + + DartzeeCalculator() + .isValidCombination(listOf(singleTwenty, singleNineteen, singleEighteen), rule) shouldBe + false + DartzeeCalculator() + .isValidCombination( + listOf(singleEighteen, singleEighteen, singleEighteen), + rule + ) shouldBe false + DartzeeCalculator() + .isValidCombination(listOf(singleTwenty, doubleNineteen, singleEighteen), rule) shouldBe + true } @Test - fun `Should test for just a single dart rule`() - { + fun `Should test for just a single dart rule`() { val rule = makeDartzeeRuleDto(makeScoreRule(20)) - DartzeeCalculator().isValidCombination(listOf(singleTwenty, singleTwenty, singleTwenty), rule) shouldBe true - DartzeeCalculator().isValidCombination(listOf(singleTwenty, singleTwenty, singleNineteen), rule) shouldBe true - DartzeeCalculator().isValidCombination(listOf(singleTwenty, singleNineteen, singleNineteen), rule) shouldBe true - DartzeeCalculator().isValidCombination(listOf(singleNineteen, singleNineteen, singleNineteen), rule) shouldBe false + DartzeeCalculator() + .isValidCombination(listOf(singleTwenty, singleTwenty, singleTwenty), rule) shouldBe + true + DartzeeCalculator() + .isValidCombination(listOf(singleTwenty, singleTwenty, singleNineteen), rule) shouldBe + true + DartzeeCalculator() + .isValidCombination(listOf(singleTwenty, singleNineteen, singleNineteen), rule) shouldBe + true + DartzeeCalculator() + .isValidCombination( + listOf(singleNineteen, singleNineteen, singleNineteen), + rule + ) shouldBe false } @Test - fun `should test for just total rules`() - { - val rule = makeDartzeeRuleDto(aggregateRule = makeTotalScoreRule(50)) - - DartzeeCalculator().isValidCombination(listOf(singleTwenty, singleTwenty, singleTen), rule) shouldBe true - DartzeeCalculator().isValidCombination(listOf(outerBull, singleTwenty, singleFive), rule) shouldBe true - DartzeeCalculator().isValidCombination(listOf(singleTwenty, singleTwenty, singleTwenty), rule) shouldBe false + fun `should test for just total rules`() { + val rule = + makeDartzeeRuleDto(aggregateRule = makeTotalScoreRule(50)) + + DartzeeCalculator() + .isValidCombination(listOf(singleTwenty, singleTwenty, singleTen), rule) shouldBe true + DartzeeCalculator() + .isValidCombination(listOf(outerBull, singleTwenty, singleFive), rule) shouldBe true + DartzeeCalculator() + .isValidCombination(listOf(singleTwenty, singleTwenty, singleTwenty), rule) shouldBe + false } @Test - fun `should validate misses correctly`() - { + fun `should validate misses correctly`() { val rule = makeDartzeeRuleDto(allowMisses = false) val ruleWithMisses = makeDartzeeRuleDto(allowMisses = true) @@ -349,4 +439,4 @@ class TestValidCombinations: AbstractTest() DartzeeCalculator().isValidCombination(combination, rule) shouldBe false DartzeeCalculator().isValidCombination(combination, ruleWithMisses) shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleCalculationResult.kt b/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleCalculationResult.kt index 6ed102d23..2e7d13f88 100644 --- a/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleCalculationResult.kt +++ b/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleCalculationResult.kt @@ -10,28 +10,49 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeRuleCalculationResult: AbstractTest() -{ +class TestDartzeeRuleCalculationResult : AbstractTest() { @Test - fun `Should calculate the correct percentage based on the passed in probabilities`() - { - makeDartzeeRuleCalculationResult(validCombinationProbability = 20.0, allCombinationsProbability = 50.0).percentage shouldBe 40.0 - makeDartzeeRuleCalculationResult(validCombinationProbability = 0.0, allCombinationsProbability = 1.0).percentage shouldBe 0.0 - makeDartzeeRuleCalculationResult(validCombinationProbability = 0.9, allCombinationsProbability = 1.0).percentage shouldBe 90.0 - makeDartzeeRuleCalculationResult(validCombinationProbability = 0.985, allCombinationsProbability = 1.0).percentage shouldBe 98.5 - makeDartzeeRuleCalculationResult(validCombinationProbability = 27.0, allCombinationsProbability = 27.0).percentage shouldBe 100.0 + fun `Should calculate the correct percentage based on the passed in probabilities`() { + makeDartzeeRuleCalculationResult( + validCombinationProbability = 20.0, + allCombinationsProbability = 50.0 + ) + .percentage shouldBe 40.0 + makeDartzeeRuleCalculationResult( + validCombinationProbability = 0.0, + allCombinationsProbability = 1.0 + ) + .percentage shouldBe 0.0 + makeDartzeeRuleCalculationResult( + validCombinationProbability = 0.9, + allCombinationsProbability = 1.0 + ) + .percentage shouldBe 90.0 + makeDartzeeRuleCalculationResult( + validCombinationProbability = 0.985, + allCombinationsProbability = 1.0 + ) + .percentage shouldBe 98.5 + makeDartzeeRuleCalculationResult( + validCombinationProbability = 27.0, + allCombinationsProbability = 27.0 + ) + .percentage shouldBe 100.0 } @Test - fun `Should show number of combinations, along with percentage`() - { - val result = makeDartzeeRuleCalculationResult(validCombinations = 256, validCombinationProbability = 20.0, allCombinationsProbability = 50.0) + fun `Should show number of combinations, along with percentage`() { + val result = + makeDartzeeRuleCalculationResult( + validCombinations = 256, + validCombinationProbability = 20.0, + allCombinationsProbability = 50.0 + ) result.getCombinationsDesc() shouldBe "256 combinations (success%: 40.0%)" } @Test - fun `Should report the correct difficulty`() - { + fun `Should report the correct difficulty`() { makeCalculationResult(0.0, 0).getDifficultyDesc() shouldBe "Impossible" makeCalculationResult(0.0, 1).getDifficultyDesc() shouldBe "Insane" makeCalculationResult(1.0).getDifficultyDesc() shouldBe "Insane" @@ -48,15 +69,16 @@ class TestDartzeeRuleCalculationResult: AbstractTest() } @Test - fun `Should externalise correctly`() - { - val result = DartzeeRuleCalculationResult(listOf(doubleNineteen), - listOf(doubleNineteen, singleTwenty, outerBull), - 10, - 100, - 5.7, - 100.0) - + fun `Should externalise correctly`() { + val result = + DartzeeRuleCalculationResult( + listOf(doubleNineteen), + listOf(doubleNineteen, singleTwenty, outerBull), + 10, + 100, + 5.7, + 100.0 + ) val dbStr = result.toDbString() @@ -66,9 +88,17 @@ class TestDartzeeRuleCalculationResult: AbstractTest() newResult.validCombinationProbability shouldBe 5.7 newResult.allCombinationsProbability shouldBe 100.0 newResult.scoringSegments.shouldContainExactly(doubleNineteen) - newResult.validSegments.shouldContainExactlyInAnyOrder(doubleNineteen, singleTwenty, outerBull) + newResult.validSegments.shouldContainExactlyInAnyOrder( + doubleNineteen, + singleTwenty, + outerBull + ) } private fun makeCalculationResult(percentage: Double, validCombinations: Int = 100) = - makeDartzeeRuleCalculationResult(validCombinations = validCombinations, validCombinationProbability = percentage, allCombinationsProbability = 100.0) -} \ No newline at end of file + makeDartzeeRuleCalculationResult( + validCombinations = validCombinations, + validCombinationProbability = percentage, + allCombinationsProbability = 100.0 + ) +} diff --git a/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleDto.kt b/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleDto.kt index 2d4a501f5..cf92c8dd8 100644 --- a/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleDto.kt +++ b/src/test/kotlin/dartzee/dartzee/TestDartzeeRuleDto.kt @@ -26,11 +26,9 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldNotBeEmpty import org.junit.jupiter.api.Test -class TestDartzeeRuleDto: AbstractTest() -{ +class TestDartzeeRuleDto : AbstractTest() { @Test - fun `Dart rule list should return all 3 rules when set`() - { + fun `Dart rule list should return all 3 rules when set`() { val dartRule1 = DartzeeDartRuleInner() val dartRule2 = DartzeeDartRuleEven() val dartRule3 = DartzeeDartRuleOdd() @@ -40,8 +38,7 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Dart rule list should just contain the first rule if the others arent set`() - { + fun `Dart rule list should just contain the first rule if the others arent set`() { val dartRule1 = DartzeeDartRuleOuter() val rule = makeDartzeeRuleDto(dartRule1) @@ -49,16 +46,14 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Dart rule list should be null if no dart rules have been set`() - { + fun `Dart rule list should be null if no dart rules have been set`() { val rule = makeDartzeeRuleDto(aggregateRule = DartzeeTotalRulePrime()) rule.getDartRuleList() shouldBe null } @Test - fun `Should run a calculation and cache the result`() - { + fun `Should run a calculation and cache the result`() { val dto = makeDartzeeRuleDto() dto.runStrengthCalculation() @@ -68,8 +63,7 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Should return the difficulty + difficulty desc of its calculation result`() - { + fun `Should return the difficulty + difficulty desc of its calculation result`() { val dto = makeDartzeeRuleDto() dto.calculationResult = makeDartzeeRuleCalculationResult(50) @@ -78,8 +72,7 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Should describe total rules correctly`() - { + fun `Should describe total rules correctly`() { val rule = makeDartzeeRuleDto(aggregateRule = DartzeeTotalRulePrime()) rule.generateRuleDescription() shouldBe "Total is prime" @@ -88,71 +81,70 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Should describe in-order dart rules`() - { - val rule = makeDartzeeRuleDto( - DartzeeDartRuleEven(), - DartzeeDartRuleOdd(), - DartzeeDartRuleEven(), - inOrder = true - ) + fun `Should describe in-order dart rules`() { + val rule = + makeDartzeeRuleDto( + DartzeeDartRuleEven(), + DartzeeDartRuleOdd(), + DartzeeDartRuleEven(), + inOrder = true + ) rule.generateRuleDescription() shouldBe "Even → Odd → Even" } @Test - fun `Should condense the same rules if order isn't required`() - { - val rule = makeDartzeeRuleDto( - DartzeeDartRuleInner(), - DartzeeDartRuleOuter(), - DartzeeDartRuleOuter(), - inOrder = false - ) + fun `Should condense the same rules if order isn't required`() { + val rule = + makeDartzeeRuleDto( + DartzeeDartRuleInner(), + DartzeeDartRuleOuter(), + DartzeeDartRuleOuter(), + inOrder = false + ) rule.generateRuleDescription() shouldBe "{ 2x Outer, 1x Inner }" } @Test - fun `Should ignore Any rules if order isn't required`() - { - val rule = makeDartzeeRuleDto( - DartzeeDartRuleInner(), - DartzeeDartRuleOuter(), - DartzeeDartRuleAny(), - inOrder = false - ) + fun `Should ignore Any rules if order isn't required`() { + val rule = + makeDartzeeRuleDto( + DartzeeDartRuleInner(), + DartzeeDartRuleOuter(), + DartzeeDartRuleAny(), + inOrder = false + ) rule.generateRuleDescription() shouldBe "{ 1x Inner, 1x Outer }" } @Test - fun `Should return Anything for a totally empty rule`() - { + fun `Should return Anything for a totally empty rule`() { val rule = makeDartzeeRuleDto() rule.generateRuleDescription() shouldBe "Anything" } @Test - fun `Should return Anything for a rule with Any dart rules`() - { - val unorderedRule = makeDartzeeRuleDto( - DartzeeDartRuleAny(), - DartzeeDartRuleAny(), - DartzeeDartRuleAny(), - inOrder = false - ) - val orderedRule = makeDartzeeRuleDto( - DartzeeDartRuleAny(), - DartzeeDartRuleAny(), - DartzeeDartRuleAny(), - inOrder = false - ) + fun `Should return Anything for a rule with Any dart rules`() { + val unorderedRule = + makeDartzeeRuleDto( + DartzeeDartRuleAny(), + DartzeeDartRuleAny(), + DartzeeDartRuleAny(), + inOrder = false + ) + val orderedRule = + makeDartzeeRuleDto( + DartzeeDartRuleAny(), + DartzeeDartRuleAny(), + DartzeeDartRuleAny(), + inOrder = false + ) unorderedRule.generateRuleDescription() shouldBe "Anything" orderedRule.generateRuleDescription() shouldBe "Anything" } @Test - fun `Should describe 'score' dart rules`() - { + fun `Should describe 'score' dart rules`() { val scoreRule = DartzeeDartRuleScore() scoreRule.score = 15 @@ -161,45 +153,45 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Dart and total rules should be concatenated if both are present`() - { - val rule = makeDartzeeRuleDto( - DartzeeDartRuleEven(), - aggregateRule = DartzeeTotalRuleGreaterThan() - ) + fun `Dart and total rules should be concatenated if both are present`() { + val rule = + makeDartzeeRuleDto(DartzeeDartRuleEven(), aggregateRule = DartzeeTotalRuleGreaterThan()) rule.generateRuleDescription() shouldBe "Score Evens, Total > 20" } @Test - fun `Should return all validSegments as scoring segments if there are no dart rules`() - { + fun `Should return all validSegments as scoring segments if there are no dart rules`() { val validSegments = listOf(doubleNineteen, doubleTwenty) val rule = makeDartzeeRuleDto(aggregateRule = DartzeeTotalRulePrime()) - rule.getScoringSegments(emptyList(), validSegments).shouldContainExactly(doubleNineteen, doubleTwenty) + rule + .getScoringSegments(emptyList(), validSegments) + .shouldContainExactly(doubleNineteen, doubleTwenty) } @Test - fun `Should return all validSegments as scoring segments if there are three dart rules`() - { + fun `Should return all validSegments as scoring segments if there are three dart rules`() { val validSegments = listOf(doubleNineteen, doubleTwenty) - val rule = makeDartzeeRuleDto(makeScoreRule(19), DartzeeDartRuleOdd(), DartzeeDartRuleEven()) - rule.getScoringSegments(emptyList(), validSegments).shouldContainExactly(doubleNineteen, doubleTwenty) + val rule = + makeDartzeeRuleDto(makeScoreRule(19), DartzeeDartRuleOdd(), DartzeeDartRuleEven()) + rule + .getScoringSegments(emptyList(), validSegments) + .shouldContainExactly(doubleNineteen, doubleTwenty) } @Test - fun `Should return all validSegments as scoring segments if fewer than 2 darts thrown for aggregate rule`() - { + fun `Should return all validSegments as scoring segments if fewer than 2 darts thrown for aggregate rule`() { val validSegments = listOf(doubleNineteen, doubleTwenty) val rule = makeDartzeeRuleDto(aggregateRule = DartzeeAggregateRuleRepeats()) val dartsSoFar = listOf(Dart(20, 1)) - rule.getScoringSegments(dartsSoFar, validSegments).shouldContainExactly(doubleNineteen, doubleTwenty) + rule + .getScoringSegments(dartsSoFar, validSegments) + .shouldContainExactly(doubleNineteen, doubleTwenty) } @Test - fun `Should only return the segments that score if there is a single dart rule`() - { + fun `Should only return the segments that score if there is a single dart rule`() { val validSegments = listOf(doubleNineteen, doubleTwenty) val rule = makeDartzeeRuleDto(makeScoreRule(19)) @@ -207,8 +199,7 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Should only return the segments that score if we are 2 darts into an aggregate rule`() - { + fun `Should only return the segments that score if we are 2 darts into an aggregate rule`() { val validSegments = listOf(doubleNineteen, doubleTwenty) val rule = makeDartzeeRuleDto(aggregateRule = DartzeeAggregateRuleRepeats()) val dartsSoFar = listOf(Dart(20, 1), Dart(20, 1)) @@ -216,9 +207,17 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Should convert to an entity correctly`() - { - val rule = DartzeeRuleDto(DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleInner(), DartzeeTotalRulePrime(), true, false, "foobar") + fun `Should convert to an entity correctly`() { + val rule = + DartzeeRuleDto( + DartzeeDartRuleEven(), + DartzeeDartRuleOdd(), + DartzeeDartRuleInner(), + DartzeeTotalRulePrime(), + true, + false, + "foobar" + ) rule.runStrengthCalculation() val dao = rule.toEntity(5, EntityName.Game, "foo") @@ -238,8 +237,7 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Should convert null ruleName and rules to empty strings`() - { + fun `Should convert null ruleName and rules to empty strings`() { val rule = DartzeeRuleDto(DartzeeDartRuleEven(), null, null, null, true, false, null) rule.runStrengthCalculation() @@ -253,22 +251,20 @@ class TestDartzeeRuleDto: AbstractTest() private val dartsForTotal = listOf(makeDart(20, 1), makeDart(20, 1), makeDart(5, 2)) @Test - fun `Should just sum the darts if there are no dart rules`() - { + fun `Should just sum the darts if there are no dart rules`() { val dto = makeDartzeeRuleDto() dto.getSuccessTotal(dartsForTotal) shouldBe 50 } @Test - fun `Should just sum the darts if there are three dart rules`() - { - val dto = makeDartzeeRuleDto(DartzeeDartRuleEven(), DartzeeDartRuleEven(), DartzeeDartRuleOdd()) + fun `Should just sum the darts if there are three dart rules`() { + val dto = + makeDartzeeRuleDto(DartzeeDartRuleEven(), DartzeeDartRuleEven(), DartzeeDartRuleOdd()) dto.getSuccessTotal(dartsForTotal) shouldBe 50 } @Test - fun `Should only sum the valid darts when there is only one dart rule`() - { + fun `Should only sum the valid darts when there is only one dart rule`() { val dto = makeDartzeeRuleDto(DartzeeDartRuleScore()) dto.getSuccessTotal(dartsForTotal) shouldBe 40 @@ -280,17 +276,19 @@ class TestDartzeeRuleDto: AbstractTest() } @Test - fun `Should only sum the valid darts when tehre is an aggregate rule`() - { + fun `Should only sum the valid darts when tehre is an aggregate rule`() { val dto = makeDartzeeRuleDto(aggregateRule = DartzeeAggregateRuleRepeats()) dto.getSuccessTotal(dartsForTotal) shouldBe 40 } @Test - fun `Should sum the intersection of valid darts when there is a score and aggregate rule`() - { - val dto = makeDartzeeRuleDto(makeColourRule(red = true), aggregateRule = DartzeeAggregateRuleRepeats()) + fun `Should sum the intersection of valid darts when there is a score and aggregate rule`() { + val dto = + makeDartzeeRuleDto( + makeColourRule(red = true), + aggregateRule = DartzeeAggregateRuleRepeats() + ) val darts = listOf(makeDart(20, 1), makeDart(20, 3), makeDart(18, 3)) dto.getSuccessTotal(darts) shouldBe 60 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/TestDartzeeRules.kt b/src/test/kotlin/dartzee/dartzee/TestDartzeeRules.kt index 577c31832..7bff7922f 100644 --- a/src/test/kotlin/dartzee/dartzee/TestDartzeeRules.kt +++ b/src/test/kotlin/dartzee/dartzee/TestDartzeeRules.kt @@ -3,55 +3,48 @@ package dartzee.dartzee import dartzee.dartzee.dart.DartzeeDartRuleEven import dartzee.dartzee.dart.DartzeeDartRuleOuter import dartzee.helper.AbstractTest -import io.kotest.matchers.types.shouldBeInstanceOf import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.Test -class TestDartzeeRules: AbstractTest() -{ +class TestDartzeeRules : AbstractTest() { @Test - fun `no dart rules should have overlapping identifiers`() - { + fun `no dart rules should have overlapping identifiers`() { val rules = getAllDartRules() - val nameCount = rules.map{ it.getRuleIdentifier() }.distinct().count() + val nameCount = rules.map { it.getRuleIdentifier() }.distinct().count() nameCount shouldBe rules.size } @Test - fun `no total rules should have overlapping identifiers`() - { + fun `no total rules should have overlapping identifiers`() { val rules = getAllAggregateRules() - val nameCount = rules.map{ it.getRuleIdentifier() }.distinct().count() + val nameCount = rules.map { it.getRuleIdentifier() }.distinct().count() nameCount shouldBe rules.size } @Test - fun `sensible toString implementation`() - { + fun `sensible toString implementation`() { val rule = DartzeeDartRuleOuter() rule.getRuleIdentifier() shouldBe "$rule" } @Test - fun `invalid XML should return null rule`() - { + fun `invalid XML should return null rule`() { val rule = parseDartRule("BAD") rule shouldBe null } @Test - fun `invalid identifier in XML should return null rule`() - { + fun `invalid identifier in XML should return null rule`() { val rule = parseDartRule("") rule shouldBe null } @Test - fun `write simple XML`() - { + fun `write simple XML`() { val rule = DartzeeDartRuleEven() val xml = rule.toDbString() val parsedRule = parseDartRule(xml)!! diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestAbstractDartzeeRuleTotalSize.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestAbstractDartzeeRuleTotalSize.kt index d74508c54..8f975ab8e 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestAbstractDartzeeRuleTotalSize.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestAbstractDartzeeRuleTotalSize.kt @@ -1,32 +1,28 @@ package dartzee.dartzee.aggregate import dartzee.helper.AbstractTest -import io.kotest.matchers.shouldBe import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.Test +import io.kotest.matchers.shouldBe import java.text.ParseException +import org.junit.jupiter.api.Test -class TestAbstractDartzeeRuleTotalSize: AbstractTest() -{ +class TestAbstractDartzeeRuleTotalSize : AbstractTest() { @Test - fun `Should initialise with a target of 20`() - { + fun `Should initialise with a target of 20`() { val rule = FakeDartzeeTotalRule() rule.spinner.value shouldBe 20 rule.target shouldBe 20 } @Test - fun `Should update the target when spinner value is changed`() - { + fun `Should update the target when spinner value is changed`() { val rule = FakeDartzeeTotalRule() rule.spinner.value = 18 rule.target shouldBe 18 } @Test - fun `Should be possible to set values between 3 and 180`() - { + fun `Should be possible to set values between 3 and 180`() { val rule = FakeDartzeeTotalRule() rule.spinner.value = 3 rule.spinner.commitEdit() @@ -38,8 +34,7 @@ class TestAbstractDartzeeRuleTotalSize: AbstractTest() } @Test - fun `Should not be possible to set values lower than 3 or higher than 180`() - { + fun `Should not be possible to set values lower than 3 or higher than 180`() { val rule = FakeDartzeeTotalRule() shouldThrow { @@ -54,8 +49,7 @@ class TestAbstractDartzeeRuleTotalSize: AbstractTest() } @Test - fun `Should initialise spinner and target when reading from XML`() - { + fun `Should initialise spinner and target when reading from XML`() { val rule = FakeDartzeeTotalRule() rule.target = 77 @@ -68,9 +62,9 @@ class TestAbstractDartzeeRuleTotalSize: AbstractTest() newRule.spinner.value shouldBe 77 } - private class FakeDartzeeTotalRule: AbstractDartzeeRuleTotalSize() - { + private class FakeDartzeeTotalRule : AbstractDartzeeRuleTotalSize() { override fun isValidTotal(total: Int) = true + override fun getRuleIdentifier() = "Fake" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleCluster.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleCluster.kt index 3114ba1c8..64386ffb0 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleCluster.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleCluster.kt @@ -10,23 +10,20 @@ import dartzee.helper.treble import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.Test import java.text.ParseException +import org.junit.jupiter.api.Test -class TestDartzeeAggregateRuleCluster: AbstractDartzeeRuleTest() -{ +class TestDartzeeAggregateRuleCluster : AbstractDartzeeRuleTest() { override fun factory() = DartzeeAggregateRuleCluster() @Test - fun `Should initialise with a spread of 1`() - { + fun `Should initialise with a spread of 1`() { val rule = factory() rule.spinner.value shouldBe 1 } @Test - fun `Should be possible to set values between 1 and 5`() - { + fun `Should be possible to set values between 1 and 5`() { val rule = factory() rule.spinner.value = 1 rule.spinner.commitEdit() @@ -38,8 +35,7 @@ class TestDartzeeAggregateRuleCluster: AbstractDartzeeRuleTest { @@ -54,8 +50,7 @@ class TestDartzeeAggregateRuleCluster: AbstractDartzeeRuleTest() -{ +class TestDartzeeAggregateRuleDecreasing : + AbstractDartzeeRuleTest() { override fun factory() = DartzeeAggregateRuleDecreasing() @Test - fun `Should be valid if scores are decreasing`() - { + fun `Should be valid if scores are decreasing`() { val rule = factory() rule.isValidRound(listOf(outerSingle(15), outerSingle(10), outerSingle(5))) shouldBe true rule.isValidRound(listOf(treble(5), double(6), outerSingle(10))) shouldBe true } @Test - fun `Should not be valid if two the same`() - { + fun `Should not be valid if two the same`() { val rule = factory() rule.isValidRound(listOf(outerSingle(10), outerSingle(10), outerSingle(5))) shouldBe false rule.isValidRound(listOf(outerSingle(12), double(6), outerSingle(6))) shouldBe false } @Test - fun `Should not be valid if not decreasing`() - { + fun `Should not be valid if not decreasing`() { val rule = factory() rule.isValidRound(listOf(outerSingle(5), outerSingle(15), outerSingle(10))) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleDistinctScores.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleDistinctScores.kt index d08d29ecb..966e2f3e2 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleDistinctScores.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleDistinctScores.kt @@ -8,27 +8,24 @@ import dartzee.helper.treble import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeAggregateRuleDistinctScores: AbstractDartzeeRuleTest() -{ +class TestDartzeeAggregateRuleDistinctScores : + AbstractDartzeeRuleTest() { override fun factory() = DartzeeAggregateRuleDistinctScores() @Test - fun `Should not allow misses`() - { + fun `Should not allow misses`() { factory().isValidRound(listOf(miss(20), outerSingle(11), double(3))) shouldBe false } @Test - fun `Should be valid if all scores are distinct`() - { + fun `Should be valid if all scores are distinct`() { factory().isValidRound(listOf(outerSingle(20), treble(11), double(3))) shouldBe true } @Test - fun `Should not be valid if one or more scores are repeated`() - { + fun `Should not be valid if one or more scores are repeated`() { factory().isValidRound(listOf(outerSingle(20), treble(20), double(3))) shouldBe false factory().isValidRound(listOf(outerSingle(20), double(20), treble(20))) shouldBe false factory().isValidRound(listOf(outerSingle(5), outerSingle(10), double(5))) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleIncreasing.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleIncreasing.kt index a6a3a3545..483658971 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleIncreasing.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleIncreasing.kt @@ -7,30 +7,27 @@ import dartzee.helper.treble import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeAggregateRuleIncreasing: AbstractDartzeeRuleTest() -{ +class TestDartzeeAggregateRuleIncreasing : + AbstractDartzeeRuleTest() { override fun factory() = DartzeeAggregateRuleIncreasing() @Test - fun `Should be valid if scores are increasing`() - { + fun `Should be valid if scores are increasing`() { val rule = factory() rule.isValidRound(listOf(outerSingle(5), outerSingle(10), outerSingle(15))) shouldBe true rule.isValidRound(listOf(outerSingle(10), double(6), treble(5))) shouldBe true } @Test - fun `Should not be valid if two the same`() - { + fun `Should not be valid if two the same`() { val rule = factory() rule.isValidRound(listOf(outerSingle(5), outerSingle(10), outerSingle(10))) shouldBe false rule.isValidRound(listOf(outerSingle(12), double(6), treble(6))) shouldBe false } @Test - fun `Should not be valid if not increasing`() - { + fun `Should not be valid if not increasing`() { val rule = factory() rule.isValidRound(listOf(outerSingle(5), outerSingle(15), outerSingle(10))) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleRepeats.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleRepeats.kt index e152f1a87..b82ea81c7 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleRepeats.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeAggregateRuleRepeats.kt @@ -10,34 +10,29 @@ import dartzee.utils.sumScore import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeAggregateRuleRepeats: AbstractDartzeeRuleTest() -{ +class TestDartzeeAggregateRuleRepeats : AbstractDartzeeRuleTest() { override fun factory() = DartzeeAggregateRuleRepeats() @Test - fun `Should not count a missed dart as a repeat`() - { + fun `Should not count a missed dart as a repeat`() { factory().isValidRound(listOf(miss(20), outerSingle(20), double(3))) shouldBe false } @Test - fun `Should be valid if at least one score is repeated`() - { + fun `Should be valid if at least one score is repeated`() { factory().isValidRound(listOf(outerSingle(20), treble(20), miss(3))) shouldBe true factory().isValidRound(listOf(outerSingle(5), double(20), treble(5))) shouldBe true factory().isValidRound(listOf(outerSingle(20), double(20), treble(20))) shouldBe true } @Test - fun `Should not be valid if all scores are distinct`() - { + fun `Should not be valid if all scores are distinct`() { factory().isValidRound(listOf(outerSingle(20), treble(5), double(3))) shouldBe false factory().isValidRound(listOf(outerSingle(20), double(25), treble(14))) shouldBe false } @Test - fun `Should only score the darts that were repeats`() - { + fun `Should only score the darts that were repeats`() { factory().getScore(Dart(20, 1), Dart(20, 2), Dart(5, 1)) shouldBe 60 factory().getScore(Dart(5, 1), Dart(5, 2), Dart(5, 3)) shouldBe 30 factory().getScore(Dart(20, 1), Dart(20, 0), Dart(20, 1)) shouldBe 40 @@ -46,4 +41,4 @@ class TestDartzeeAggregateRuleRepeats: AbstractDartzeeRuleTest() -{ +class TestDartzeeAggregateRuleSpread : AbstractDartzeeRuleTest() { override fun factory() = DartzeeAggregateRuleSpread() @Test - fun `Should initialise with a spread of 1`() - { + fun `Should initialise with a spread of 1`() { val rule = DartzeeAggregateRuleSpread() rule.spinner.value shouldBe 1 } @Test - fun `Should be possible to set values between 1 and 5`() - { + fun `Should be possible to set values between 1 and 5`() { val rule = DartzeeAggregateRuleSpread() rule.spinner.value = 1 rule.spinner.commitEdit() @@ -38,8 +35,7 @@ class TestDartzeeAggregateRuleSpread: AbstractDartzeeRuleTest { @@ -54,8 +50,7 @@ class TestDartzeeAggregateRuleSpread: AbstractDartzeeRuleTest() -{ +class TestDartzeeTotalRuleEqualTo : AbstractDartzeeRuleTest() { override fun factory() = DartzeeTotalRuleEqualTo() @Test - fun `Total validation`() - { + fun `Total validation`() { val rule = DartzeeTotalRuleEqualTo() rule.target = 55 @@ -20,11 +18,10 @@ class TestDartzeeTotalRuleEqualTo: AbstractDartzeeRuleTest() -{ +class TestDartzeeTotalRuleEven : AbstractDartzeeRuleTest() { override fun factory() = DartzeeTotalRuleEven() @Test - fun `Total validation`() - { + fun `Total validation`() { val rule = DartzeeTotalRuleEven() rule.isValidTotal(20) shouldBe true @@ -18,9 +16,8 @@ class TestDartzeeTotalRuleEven: AbstractDartzeeRuleTest() } @Test - fun `Rule description`() - { + fun `Rule description`() { val rule = DartzeeTotalRuleEven() rule.getDescription() shouldBe "Total is even" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleGreaterThan.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleGreaterThan.kt index cf81573d4..53f668ebc 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleGreaterThan.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleGreaterThan.kt @@ -4,13 +4,11 @@ import dartzee.dartzee.AbstractDartzeeRuleTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeTotalRuleGreaterThan: AbstractDartzeeRuleTest() -{ +class TestDartzeeTotalRuleGreaterThan : AbstractDartzeeRuleTest() { override fun factory() = DartzeeTotalRuleGreaterThan() @Test - fun `Total validation`() - { + fun `Total validation`() { val rule = DartzeeTotalRuleGreaterThan() rule.target = 55 @@ -20,11 +18,10 @@ class TestDartzeeTotalRuleGreaterThan: AbstractDartzeeRuleTest 25" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleLessThan.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleLessThan.kt index 91f3c1bf9..652662dc5 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleLessThan.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRuleLessThan.kt @@ -4,13 +4,11 @@ import dartzee.dartzee.AbstractDartzeeRuleTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeTotalRuleLessThan: AbstractDartzeeRuleTest() -{ +class TestDartzeeTotalRuleLessThan : AbstractDartzeeRuleTest() { override fun factory() = DartzeeTotalRuleLessThan() @Test - fun `Total validation`() - { + fun `Total validation`() { val rule = DartzeeTotalRuleLessThan() rule.target = 55 @@ -20,11 +18,10 @@ class TestDartzeeTotalRuleLessThan: AbstractDartzeeRuleTest() -{ +class TestDartzeeTotalRuleMultipleOf : AbstractDartzeeRuleTest() { override fun factory() = DartzeeTotalRuleMultipleOf() @Test - fun `Total validation`() - { + fun `Total validation`() { val rule = factory() rule.target = 7 @@ -20,11 +18,10 @@ class TestDartzeeTotalRuleMultipleOf: AbstractDartzeeRuleTest() -{ +class TestDartzeeTotalRuleOdd : AbstractDartzeeRuleTest() { override fun factory() = DartzeeTotalRuleOdd() @Test - fun `Total validation`() - { + fun `Total validation`() { val rule = DartzeeTotalRuleOdd() rule.isValidTotal(20) shouldBe false @@ -18,9 +16,8 @@ class TestDartzeeTotalRuleOdd: AbstractDartzeeRuleTest() } @Test - fun `Rule description`() - { + fun `Rule description`() { val rule = DartzeeTotalRuleOdd() rule.getDescription() shouldBe "Total is odd" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRulePrime.kt b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRulePrime.kt index e93ca8ad2..d8b703c85 100644 --- a/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRulePrime.kt +++ b/src/test/kotlin/dartzee/dartzee/aggregate/TestDartzeeTotalRulePrime.kt @@ -4,13 +4,11 @@ import dartzee.dartzee.AbstractDartzeeRuleTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeTotalRulePrime: AbstractDartzeeRuleTest() -{ +class TestDartzeeTotalRulePrime : AbstractDartzeeRuleTest() { override fun factory() = DartzeeTotalRulePrime() @Test - fun `Total validation`() - { + fun `Total validation`() { val rule = DartzeeTotalRulePrime() rule.isValidTotal(2) shouldBe true @@ -21,5 +19,4 @@ class TestDartzeeTotalRulePrime: AbstractDartzeeRuleTest( rule.isValidTotal(6) shouldBe false rule.isValidTotal(21) shouldBe false } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleAny.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleAny.kt index fcec70d59..2d258ec84 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleAny.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleAny.kt @@ -5,17 +5,13 @@ import dartzee.utils.getAllSegmentsForDartzee import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleAny: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleAny : AbstractDartzeeRuleTest() { override fun factory() = DartzeeDartRuleAny() @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = DartzeeDartRuleAny() - getAllSegmentsForDartzee().forEach { - rule.isValidSegment(it) shouldBe true - } + getAllSegmentsForDartzee().forEach { rule.isValidSegment(it) shouldBe true } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleColour.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleColour.kt index ec4d6f7b8..7f36e94a7 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleColour.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleColour.kt @@ -15,18 +15,16 @@ import dartzee.trebleTwenty import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldBeEmpty -import org.junit.jupiter.api.Test import javax.swing.JCheckBox +import org.junit.jupiter.api.Test -class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleColour : AbstractDartzeeRuleTest() { override val emptyIsValid = false override fun factory() = DartzeeDartRuleColour() @Test - fun `segment validation - black`() - { + fun `segment validation - black`() { val rule = DartzeeDartRuleColour() rule.black = true @@ -42,8 +40,7 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `segment validation - white`() - { + fun `segment validation - white`() { val rule = DartzeeDartRuleColour() rule.white = true @@ -59,8 +56,7 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `segment validation - green`() - { + fun `segment validation - green`() { val rule = DartzeeDartRuleColour() rule.green = true @@ -76,8 +72,7 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `segment validation - red`() - { + fun `segment validation - red`() { val rule = DartzeeDartRuleColour() rule.red = true @@ -93,8 +88,7 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `segment validation - combination`() - { + fun `segment validation - combination`() { val rule = DartzeeDartRuleColour() rule.red = true rule.black = true @@ -111,25 +105,23 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `colour config panel updates rule correctly`() - { + fun `colour config panel updates rule correctly`() { val rule = DartzeeDartRuleColour() val panel = rule.configPanel val checkBoxes: List = panel.components.filterIsInstance(JCheckBox::class.java) - val cbBlack = checkBoxes.find{it.text == "Black"} - val cbWhite = checkBoxes.find{it.text == "White"} - val cbGreen = checkBoxes.find{it.text == "Green"} - val cbRed = checkBoxes.find{it.text == "Red"} + val cbBlack = checkBoxes.find { it.text == "Black" } + val cbWhite = checkBoxes.find { it.text == "White" } + val cbGreen = checkBoxes.find { it.text == "Green" } + val cbRed = checkBoxes.find { it.text == "Red" } cbBlack.shouldNotBeNull() cbWhite.shouldNotBeNull() cbGreen.shouldNotBeNull() cbRed.shouldNotBeNull() - for (i in 0..15) - { + for (i in 0..15) { cbBlack.isSelected = (i and 1) > 0 cbWhite.isSelected = (i and 2) > 0 cbRed.isSelected = (i and 4) > 0 @@ -145,10 +137,9 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `read and write XML`() - { + fun `read and write XML`() { val rules = getAllValidColorPermutations() - rules.forEach{ + rules.forEach { val red = it.red val green = it.green val black = it.black @@ -170,20 +161,16 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `all non-empty colour rules are valid`() - { + fun `all non-empty colour rules are valid`() { val rules = getAllValidColorPermutations() - rules.forEach{ - it.validate().shouldBeEmpty() - } + rules.forEach { it.validate().shouldBeEmpty() } } - private fun getAllValidColorPermutations(): MutableList - { + + private fun getAllValidColorPermutations(): MutableList { val list = mutableListOf() - for (i in 1..15) - { + for (i in 1..15) { val rule = DartzeeDartRuleColour() rule.black = (i and 1) > 0 rule.white = (i and 2) > 0 @@ -197,8 +184,7 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `rule description`() - { + fun `rule description`() { val rule = makeColourRule(red = true, black = true) rule.getDescription() shouldBe "R/B" @@ -211,8 +197,7 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( } @Test - fun `should update from UI interaction`() - { + fun `should update from UI interaction`() { val rule = makeColourRule() rule.cbBlack.doClick() rule.black shouldBe true @@ -226,4 +211,4 @@ class TestDartzeeDartRuleColour: AbstractDartzeeRuleTest( rule.cbGreen.doClick() rule.green shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleCustom.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleCustom.kt index 0a230de76..d7b9a8b86 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleCustom.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleCustom.kt @@ -18,18 +18,16 @@ import io.kotest.matchers.string.shouldBeEmpty import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.event.ActionListener +import org.junit.jupiter.api.Test -class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleCustom : AbstractDartzeeRuleTest() { override val emptyIsValid = false override fun factory() = DartzeeDartRuleCustom() @Test - fun `a custom rule with at least one segment is valid`() - { + fun `a custom rule with at least one segment is valid`() { val rule = DartzeeDartRuleCustom() rule.segments.add(doubleTwenty) @@ -37,8 +35,7 @@ class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest( } @Test - fun `description should return Custom or the specified name`() - { + fun `description should return Custom or the specified name`() { val rule = factory() rule.getDescription() shouldBe "Custom" @@ -47,8 +44,7 @@ class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest( } @Test - fun `Should update the name variable when a new one is typed in`() - { + fun `Should update the name variable when a new one is typed in`() { val rule = factory() rule.tfName.text = "Foo" @@ -57,8 +53,7 @@ class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest( } @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = DartzeeDartRuleCustom() rule.segments.addAll(setOf(doubleTwenty, trebleNineteen)) @@ -68,8 +63,7 @@ class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest( } @Test - fun `Read and write XML`() - { + fun `Read and write XML`() { val rule = DartzeeDartRuleCustom() rule.segments.addAll(setOf(doubleTwenty, outerBull, trebleNineteen)) @@ -79,7 +73,7 @@ class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest( val parsedRule = parseDartRule(xml) parsedRule.shouldBeInstanceOf() - parsedRule.segments shouldHaveSize(3) + parsedRule.segments shouldHaveSize (3) parsedRule.isValidSegment(doubleTwenty) shouldBe true parsedRule.isValidSegment(singleTwenty) shouldBe false @@ -88,8 +82,7 @@ class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest( } @Test - fun `Should propagate action events to other listeners`() - { + fun `Should propagate action events to other listeners`() { val rule = DartzeeDartRuleCustom() val listener = mockk(relaxed = true) @@ -101,8 +94,7 @@ class TestDartzeeDartRuleCustom: AbstractDartzeeRuleTest( } @Test - fun `Should pop up segment selector and update accordingly`() - { + fun `Should pop up segment selector and update accordingly`() { val fakeFactory = FakeDartzeeSegmentFactory(hashSetOf(trebleTwenty, trebleNineteen)) InjectedThings.dartzeeSegmentFactory = fakeFactory diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleEven.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleEven.kt index 06c68cd94..f622c7a68 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleEven.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleEven.kt @@ -9,13 +9,11 @@ import dartzee.trebleTwenty import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleEven: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleEven : AbstractDartzeeRuleTest() { override fun factory() = DartzeeDartRuleEven() @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = DartzeeDartRuleEven() rule.isValidSegment(doubleNineteen) shouldBe false @@ -24,4 +22,4 @@ class TestDartzeeDartRuleEven: AbstractDartzeeRuleTest() rule.isValidSegment(singleNineteen) shouldBe false rule.isValidSegment(missTwenty) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleInner.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleInner.kt index 8a249c724..2df48a4bd 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleInner.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleInner.kt @@ -11,13 +11,11 @@ import dartzee.trebleNineteen import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleInner: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleInner : AbstractDartzeeRuleTest() { override fun factory() = DartzeeDartRuleInner() @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = DartzeeDartRuleInner() rule.isValidSegment(bullseye) shouldBe true @@ -28,4 +26,4 @@ class TestDartzeeDartRuleInner: AbstractDartzeeRuleTest() rule.isValidSegment(doubleTwenty) shouldBe false rule.isValidSegment(missTwenty) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleMiss.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleMiss.kt index 88e927340..22bd886bf 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleMiss.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleMiss.kt @@ -11,13 +11,11 @@ import dartzee.trebleNineteen import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleMiss: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleMiss : AbstractDartzeeRuleTest() { override fun factory() = DartzeeDartRuleMiss() @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = factory() rule.isValidSegment(bullseye) shouldBe false @@ -28,4 +26,4 @@ class TestDartzeeDartRuleMiss: AbstractDartzeeRuleTest() rule.isValidSegment(doubleTwenty) shouldBe false rule.isValidSegment(missTwenty) shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOdd.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOdd.kt index aa111f568..43a0a0bf9 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOdd.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOdd.kt @@ -9,13 +9,11 @@ import dartzee.trebleTwenty import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleOdd: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleOdd : AbstractDartzeeRuleTest() { override fun factory() = DartzeeDartRuleOdd() @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = DartzeeDartRuleOdd() rule.isValidSegment(doubleNineteen) shouldBe true @@ -24,4 +22,4 @@ class TestDartzeeDartRuleOdd: AbstractDartzeeRuleTest() rule.isValidSegment(missTwenty) shouldBe false rule.isValidSegment(outerBull) shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOuter.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOuter.kt index f12055ae6..f45322013 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOuter.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleOuter.kt @@ -11,13 +11,11 @@ import dartzee.trebleNineteen import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleOuter: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleOuter : AbstractDartzeeRuleTest() { override fun factory() = DartzeeDartRuleOuter() @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = DartzeeDartRuleOuter() rule.isValidSegment(bullseye) shouldBe false @@ -28,4 +26,4 @@ class TestDartzeeDartRuleOuter: AbstractDartzeeRuleTest() rule.isValidSegment(doubleTwenty) shouldBe true rule.isValidSegment(missTwenty) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleScore.kt b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleScore.kt index f9cf5b42b..b646f3098 100644 --- a/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleScore.kt +++ b/src/test/kotlin/dartzee/dartzee/dart/TestDartzeeDartRuleScore.kt @@ -12,13 +12,11 @@ import io.kotest.matchers.ints.shouldNotBeInRange import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeDartRuleScore: AbstractDartzeeRuleTest() -{ +class TestDartzeeDartRuleScore : AbstractDartzeeRuleTest() { override fun factory() = DartzeeDartRuleScore() @Test - fun `segment validation`() - { + fun `segment validation`() { val rule = DartzeeDartRuleScore() rule.score = 20 @@ -30,14 +28,12 @@ class TestDartzeeDartRuleScore: AbstractDartzeeRuleTest() } @Test - fun `Score config panel updates rule correctly`() - { + fun `Score config panel updates rule correctly`() { val rule = DartzeeDartRuleScore() rule.spinner.value shouldBe rule.score rule.score shouldBeGreaterThan -1 - for (i in 1..25) - { + for (i in 1..25) { rule.spinner.value = i rule.spinner.value shouldBe rule.score @@ -46,8 +42,7 @@ class TestDartzeeDartRuleScore: AbstractDartzeeRuleTest() } @Test - fun `Read and write XML`() - { + fun `Read and write XML`() { val rule = DartzeeDartRuleScore() rule.score = 18 @@ -59,12 +54,11 @@ class TestDartzeeDartRuleScore: AbstractDartzeeRuleTest() } @Test - fun `rule description`() - { + fun `rule description`() { val rule = DartzeeDartRuleScore() rule.getDescription() shouldBe "20" rule.score = 15 rule.getDescription() shouldBe "15" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/AbstractEntityTest.kt b/src/test/kotlin/dartzee/db/AbstractEntityTest.kt index 3cf3dc5c6..8ba6b79b7 100644 --- a/src/test/kotlin/dartzee/db/AbstractEntityTest.kt +++ b/src/test/kotlin/dartzee/db/AbstractEntityTest.kt @@ -22,28 +22,29 @@ import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.kotest.matchers.string.shouldContain -import org.junit.jupiter.api.Test import java.sql.Blob import java.sql.Timestamp import javax.sql.rowset.serial.SerialBlob +import org.junit.jupiter.api.Test -abstract class AbstractEntityTest>: AbstractTest() -{ +abstract class AbstractEntityTest> : AbstractTest() { private val dao by lazy { factoryDao() } abstract fun factoryDao(): AbstractEntity + open fun setExtraValuesForBulkInsert(e: E) {} private fun factory(): AbstractEntity = dao.javaClass.getDeclaredConstructor().newInstance() - private fun factoryAndSave() = factory().also { - it.assignRowId() - setValuesAndSaveToDatabase(it, true) - } + + private fun factoryAndSave() = + factory().also { + it.assignRowId() + setValuesAndSaveToDatabase(it, true) + } @Suppress("UNCHECKED_CAST") @Test - fun `Should be bulk insertable`() - { + fun `Should be bulk insertable`() { val tableName = dao.getTableName() val e1 = factory() val e2 = factory() @@ -62,44 +63,38 @@ abstract class AbstractEntityTest>: AbstractTest() getCountFromTable(tableName) shouldBe 2 - mainDatabase.executeQueryAggregate("SELECT COUNT(1) FROM $tableName WHERE DtLastUpdate = ${getEndOfTimeSqlString()}") shouldBe 0 + mainDatabase.executeQueryAggregate( + "SELECT COUNT(1) FROM $tableName WHERE DtLastUpdate = ${getEndOfTimeSqlString()}" + ) shouldBe 0 e1.retrievedFromDb shouldBe true e2.retrievedFromDb shouldBe true } @Test - fun `Column names should match declared fields`() - { - getExpectedClassFields().forEach{ - dao.javaClass.getMethod("get$it") shouldNotBe null - } + fun `Column names should match declared fields`() { + getExpectedClassFields().forEach { dao.javaClass.getMethod("get$it") shouldNotBe null } } @Test - fun `Delete individual row`() - { + fun `Delete individual row`() { val entity = factoryAndSave() getCountFromTable(dao.getTableName()) shouldBe 1 entity.deleteFromDatabase() shouldBe true getCountFromTable(dao.getTableName()) shouldBe 0 - if (entity.includeInSync()) - { + if (entity.includeInSync()) { val audit = retrieveDeletionAudit() audit.entityName shouldBe entity.getTableName() audit.entityId shouldBe entity.rowId - } - else - { + } else { getCountFromTable(EntityName.DeletionAudit) shouldBe 0 } } @Test - fun `Delete where`() - { + fun `Delete where`() { val entityOne = factoryAndSave() val entityTwo = factoryAndSave() val entityThree = factoryAndSave() @@ -109,34 +104,35 @@ abstract class AbstractEntityTest>: AbstractTest() factory().retrieveEntities().map { it.rowId }.shouldContainExactly(entityTwo.rowId) - if (factory().includeInSync()) - { + if (factory().includeInSync()) { val audits = DeletionAuditEntity().retrieveEntities() - audits.map { it.entityId }.shouldContainExactlyInAnyOrder(entityOne.rowId, entityThree.rowId) - } - else if (dao.getTableName() != EntityName.DeletionAudit) - { + audits + .map { it.entityId } + .shouldContainExactlyInAnyOrder(entityOne.rowId, entityThree.rowId) + } else if (dao.getTableName() != EntityName.DeletionAudit) { getCountFromTable(EntityName.DeletionAudit) shouldBe 0 } } @Test - fun `Insert and retrieve`() - { + fun `Insert and retrieve`() { val entity = factory() entity.assignRowId() val rowId = entity.rowId setValuesAndSaveToDatabase(entity, true) - val insertLog = flushAndGetLogRecords().find { it.loggingCode == CODE_SQL - && it.message.contains("INSERT INTO ${dao.getTableName()} VALUES ('$rowId'") } + val insertLog = + flushAndGetLogRecords().find { + it.loggingCode == CODE_SQL && + it.message.contains("INSERT INTO ${dao.getTableName()} VALUES ('$rowId'") + } insertLog.shouldNotBeNull() - //Retrieve and check all values are as expected + // Retrieve and check all values are as expected val retrievedEntity = dao.retrieveForId(rowId)!! - getExpectedClassFields().forEach{ + getExpectedClassFields().forEach { val fieldType = retrievedEntity.getFieldType(it) val retrievedValue = retrievedEntity.getField(it) @@ -148,28 +144,30 @@ abstract class AbstractEntityTest>: AbstractTest() } @Test - fun `Update and retrieve`() - { + fun `Update and retrieve`() { val entity = factory() entity.assignRowId() val rowId = entity.rowId - //Insert + // Insert setValuesAndSaveToDatabase(entity, true) val dtFirstUpdate = entity.dtLastUpdate getCountFromTable(dao.getTableName()) shouldBe 1 - //Update + // Update setValuesAndSaveToDatabase(entity, false) - val updateLog = flushAndGetLogRecords().find { it.loggingCode == CODE_SQL && it.message.contains("UPDATE ${dao.getTableName()}") } + val updateLog = + flushAndGetLogRecords().find { + it.loggingCode == CODE_SQL && it.message.contains("UPDATE ${dao.getTableName()}") + } updateLog.shouldNotBeNull() getCountFromTable(dao.getTableName()) shouldBe 1 - //Retrieve to make sure updated values are set correctly + // Retrieve to make sure updated values are set correctly val finalEntity = dao.retrieveEntity("RowId = '$rowId'")!! - getExpectedClassFields().forEach{ + getExpectedClassFields().forEach { val fieldType = finalEntity.getFieldType(it) val retrievedValue = finalEntity.getField(it) @@ -181,49 +179,49 @@ abstract class AbstractEntityTest>: AbstractTest() } @Test - fun `Columns should not allow NULLs`() - { + fun `Columns should not allow NULLs`() { val entity = factory() val rowId = entity.assignRowId() - //Insert into the DB + // Insert into the DB setValuesAndSaveToDatabase(entity, true) - //Now go through and try to update each field to NULL - getExpectedClassFields().forEach{ + // Now go through and try to update each field to NULL + getExpectedClassFields().forEach { val sql = "UPDATE ${dao.getTableName()} SET $it = NULL WHERE RowId = '$rowId'" mainDatabase.executeUpdate(sql) shouldBe false val log = verifyLog(CODE_SQL_EXCEPTION, Severity.ERROR) log.message shouldBe "Caught SQLException for statement: $sql" - log.errorObject?.message shouldContain "Column '${it.uppercase()}' cannot accept a NULL value." + log.errorObject?.message shouldContain + "Column '${it.uppercase()}' cannot accept a NULL value." } } @Test - fun `Should be able to insert and update in specified database instance`() - { + fun `Should be able to insert and update in specified database instance`() { usingInMemoryDatabase { db -> - val entity: AbstractEntity = dao.javaClass.getDeclaredConstructor(Database::class.java).newInstance(db) + val entity: AbstractEntity = + dao.javaClass.getDeclaredConstructor(Database::class.java).newInstance(db) entity.createTable() db.executeUpdate("DELETE FROM ${entity.getTableName()}") entity.assignRowId() val rowId = entity.rowId - //Insert + // Insert setValuesAndSaveToDatabase(entity, true) getCountFromTable(dao.getTableName(), db) shouldBe 1 val retrievedEntity = entity.retrieveEntity("1 = 1")!! - //Update + // Update setValuesAndSaveToDatabase(retrievedEntity, false) getCountFromTable(dao.getTableName(), db) shouldBe 1 - //Retrieve to make sure updated values are set correctly + // Retrieve to make sure updated values are set correctly val finalEntity = retrievedEntity.retrieveEntity("RowId = '$rowId'")!! - getExpectedClassFields().forEach{ + getExpectedClassFields().forEach { val fieldType = finalEntity.getFieldType(it) val retrievedValue = finalEntity.getField(it) @@ -235,12 +233,11 @@ abstract class AbstractEntityTest>: AbstractTest() } } - private fun setValuesAndSaveToDatabase(entity: AbstractEntity, initial: Boolean) - { - //Sleep to ensure DtLastUpdate has some time to move + private fun setValuesAndSaveToDatabase(entity: AbstractEntity, initial: Boolean) { + // Sleep to ensure DtLastUpdate has some time to move Thread.sleep(50) - getExpectedClassFields().forEach{ + getExpectedClassFields().forEach { val fieldType = entity.getFieldType(it) entity.setField(it, getValueForField(fieldType, initial)) } @@ -248,8 +245,7 @@ abstract class AbstractEntityTest>: AbstractTest() entity.saveToDatabase() } - private fun getExpectedClassFields(): List - { + private fun getExpectedClassFields(): List { val cols = dao.getColumns() cols.remove("RowId") cols.remove("LocalId") @@ -259,21 +255,21 @@ abstract class AbstractEntityTest>: AbstractTest() return cols } - private fun getValueForField(fieldType: Class, initial: Boolean): Any - { - return when (fieldType) - { + private fun getValueForField(fieldType: Class, initial: Boolean): Any { + return when (fieldType) { String::class.java -> if (initial) "foo" else "bar" Int::class.java -> if (initial) 20 else 100 Long::class.java -> if (initial) 2000 else Integer.MAX_VALUE - 1 - Timestamp::class.java -> if (initial) Timestamp.valueOf("2019-04-01 21:29:32") else DateStatics.END_OF_TIME + Timestamp::class.java -> + if (initial) Timestamp.valueOf("2019-04-01 21:29:32") else DateStatics.END_OF_TIME Blob::class.java -> if (initial) getBlobValue("BaboOne") else getBlobValue("Goomba") Boolean::class.java -> initial Double::class.java -> if (initial) 5.0 else 10.0 GameType::class.java -> if (initial) GameType.X01 else GameType.GOLF MatchMode::class.java -> if (initial) MatchMode.FIRST_TO else MatchMode.POINTS SegmentType::class.java -> if (initial) SegmentType.OUTER_SINGLE else SegmentType.DOUBLE - AchievementType::class.java -> if (initial) AchievementType.X01_BEST_FINISH else AchievementType.CLOCK_BEST_GAME + AchievementType::class.java -> + if (initial) AchievementType.X01_BEST_FINISH else AchievementType.CLOCK_BEST_GAME EntityName::class.java -> if (initial) EntityName.Game else EntityName.Player else -> { println(fieldType) @@ -281,12 +277,10 @@ abstract class AbstractEntityTest>: AbstractTest() } } } - } -fun getBlobValue(resource: String): Blob -{ +fun getBlobValue(resource: String): Blob { val resourceLocation = "/avatars/$resource.png" val bytes = FileUtil.getByteArrayForResource(resourceLocation) return SerialBlob(bytes) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestAbstractEntity.kt b/src/test/kotlin/dartzee/db/TestAbstractEntity.kt index 121cad126..36dc2539a 100644 --- a/src/test/kotlin/dartzee/db/TestAbstractEntity.kt +++ b/src/test/kotlin/dartzee/db/TestAbstractEntity.kt @@ -13,34 +13,28 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import io.mockk.every import io.mockk.mockk +import java.sql.Timestamp +import java.util.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import java.sql.Timestamp -import java.util.* -class TestAbstractEntity: AbstractTest() -{ +class TestAbstractEntity : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { FakeEntity().createTable() } @AfterEach - fun afterEach() - { + fun afterEach() { mainDatabase.dropUnexpectedTables() } @Test - fun `Should throw wrapped SQL exception if an error occurs while preparing insert statement`() - { + fun `Should throw wrapped SQL exception if an error occurs while preparing insert statement`() { mainDatabase.dropTable("TestTable") - val ex = shouldThrow { - insertFakeEntity() - } + val ex = shouldThrow { insertFakeEntity() } ex.sqlException.message shouldContain "Table/View 'TESTTABLE' does not exist" ex.sqlStatement shouldBe "INSERT INTO TestTable VALUES (?, ?, ?, ?)" @@ -48,53 +42,54 @@ class TestAbstractEntity: AbstractTest() } @Test - fun `Should throw wrapped SQL exception with values if an error occurs whilst performing the insert`() - { + fun `Should throw wrapped SQL exception with values if an error occurs whilst performing the insert`() { val rowId = UUID.randomUUID().toString() val dtCreation = Timestamp(100) val dtLastUpdate = Timestamp(10000) - val ex = shouldThrow { - insertFakeEntity(rowId = rowId, testString = "thisistoolong", dtCreation = dtCreation, dtLastUpdate = dtLastUpdate) - } + val ex = + shouldThrow { + insertFakeEntity( + rowId = rowId, + testString = "thisistoolong", + dtCreation = dtCreation, + dtLastUpdate = dtLastUpdate + ) + } ex.sqlException.message shouldContain "truncation error" - ex.sqlStatement shouldBe "INSERT INTO TestTable VALUES ('$rowId', '$dtCreation', '$dtLastUpdate', 'thisistoolong')" + ex.sqlStatement shouldBe + "INSERT INTO TestTable VALUES ('$rowId', '$dtCreation', '$dtLastUpdate', 'thisistoolong')" ex.genericStatement shouldBe "INSERT INTO TestTable VALUES (?, ?, ?, ?)" } @Test - fun `Should throw a wrapped SQL exception with values if an error occurs whilst performing an update`() - { + fun `Should throw a wrapped SQL exception with values if an error occurs whilst performing an update`() { val entity = insertFakeEntity() entity.testString = "thisistoolong" - val ex = shouldThrow { - entity.saveToDatabase() - } + val ex = shouldThrow { entity.saveToDatabase() } ex.sqlException.message shouldContain "truncation error" ex.sqlStatement shouldBe - "UPDATE TestTable SET DtCreation='${entity.dtCreation}', DtLastUpdate='${entity.dtLastUpdate}', TestString='thisistoolong' WHERE RowId='${entity.rowId}'" - ex.genericStatement shouldBe "UPDATE TestTable SET DtCreation=?, DtLastUpdate=?, TestString=? WHERE RowId=?" + "UPDATE TestTable SET DtCreation='${entity.dtCreation}', DtLastUpdate='${entity.dtLastUpdate}', TestString='thisistoolong' WHERE RowId='${entity.rowId}'" + ex.genericStatement shouldBe + "UPDATE TestTable SET DtCreation=?, DtLastUpdate=?, TestString=? WHERE RowId=?" } @Test - fun `Should throw a wrapped SQL exception on retrieve`() - { + fun `Should throw a wrapped SQL exception on retrieve`() { val dao = FakeEntity() - val ex = shouldThrow { - dao.retrieveEntities("butterfingers") - } + val ex = shouldThrow { dao.retrieveEntities("butterfingers") } ex.sqlException.message shouldContain "BUTTERFINGERS" - ex.sqlStatement shouldBe "SELECT RowId, DtCreation, DtLastUpdate, TestString FROM TestTable WHERE butterfingers" + ex.sqlStatement shouldBe + "SELECT RowId, DtCreation, DtLastUpdate, TestString FROM TestTable WHERE butterfingers" } @Test - fun `Should retrieve all entities if passed a null date`() - { + fun `Should retrieve all entities if passed a null date`() { val e1 = insertFakeEntity() val e2 = insertFakeEntity() @@ -103,8 +98,7 @@ class TestAbstractEntity: AbstractTest() } @Test - fun `Should retrieve all entities modified since a particular date`() - { + fun `Should retrieve all entities modified since a particular date`() { insertFakeEntity(dtLastUpdate = Timestamp(500)) insertFakeEntity(dtLastUpdate = Timestamp(1000)) val e3 = insertFakeEntity(dtLastUpdate = Timestamp(1001)) @@ -115,8 +109,7 @@ class TestAbstractEntity: AbstractTest() } @Test - fun `Should sort by dtCreation`() - { + fun `Should sort by dtCreation`() { val e1 = insertFakeEntity(dtCreation = Timestamp(500)) val e3 = insertFakeEntity(dtCreation = Timestamp(1000)) val e2 = insertFakeEntity(dtCreation = Timestamp(750)) @@ -126,8 +119,7 @@ class TestAbstractEntity: AbstractTest() } @Test - fun `Should insert into other database if row does not already exist`() - { + fun `Should insert into other database if row does not already exist`() { usingInMemoryDatabase { otherDatabase -> FakeEntity(otherDatabase).createTable() @@ -142,17 +134,25 @@ class TestAbstractEntity: AbstractTest() otherEntity.testString shouldBe "carrot" otherEntity.dtLastUpdate shouldBe Timestamp(500) } - } @Test - fun `Should update other database if dtLastUpdate is more recent`() - { + fun `Should update other database if dtLastUpdate is more recent`() { usingInMemoryDatabase { otherDatabase -> FakeEntity(otherDatabase).createTable() - val localEntity = insertFakeEntity(testString = "carrot", dtLastUpdate = Timestamp(500), database = mainDatabase) - insertFakeEntity(rowId = localEntity.rowId, testString = "banana", dtLastUpdate = Timestamp(499), database = otherDatabase) + val localEntity = + insertFakeEntity( + testString = "carrot", + dtLastUpdate = Timestamp(500), + database = mainDatabase + ) + insertFakeEntity( + rowId = localEntity.rowId, + testString = "banana", + dtLastUpdate = Timestamp(499), + database = otherDatabase + ) localEntity.mergeIntoDatabase(otherDatabase) getCountFromTable("TestTable", otherDatabase) shouldBe 1 @@ -164,12 +164,21 @@ class TestAbstractEntity: AbstractTest() } @Test - fun `Should not update other database if dtLastUpdate is older`() - { + fun `Should not update other database if dtLastUpdate is older`() { usingInMemoryDatabase { otherDatabase -> FakeEntity(otherDatabase).createTable() - val localEntity = insertFakeEntity(testString = "carrot", dtLastUpdate = Timestamp(500), database = mainDatabase) - insertFakeEntity(rowId = localEntity.rowId, testString = "banana", dtLastUpdate = Timestamp(501), database = otherDatabase) + val localEntity = + insertFakeEntity( + testString = "carrot", + dtLastUpdate = Timestamp(500), + database = mainDatabase + ) + insertFakeEntity( + rowId = localEntity.rowId, + testString = "banana", + dtLastUpdate = Timestamp(501), + database = otherDatabase + ) localEntity.mergeIntoDatabase(otherDatabase) getCountFromTable("TestTable", otherDatabase) shouldBe 1 @@ -180,12 +189,13 @@ class TestAbstractEntity: AbstractTest() } } - private fun insertFakeEntity(rowId: String = UUID.randomUUID().toString(), - testString: String = "", - dtCreation: Timestamp = getSqlDateNow(), - dtLastUpdate: Timestamp = getSqlDateNow(), - database: Database = mainDatabase): FakeEntity - { + private fun insertFakeEntity( + rowId: String = UUID.randomUUID().toString(), + testString: String = "", + dtCreation: Timestamp = getSqlDateNow(), + dtLastUpdate: Timestamp = getSqlDateNow(), + database: Database = mainDatabase + ): FakeEntity { val entity = FakeEntity(database) entity.rowId = rowId entity.dtCreation = dtCreation @@ -195,8 +205,7 @@ class TestAbstractEntity: AbstractTest() } } -class FakeEntity(database: Database = mainDatabase): AbstractEntity(database) -{ +class FakeEntity(database: Database = mainDatabase) : AbstractEntity(database) { var testString = "" override fun getTableName(): EntityName { @@ -205,5 +214,6 @@ class FakeEntity(database: Database = mainDatabase): AbstractEntity( every { result.toString() } returns "TestTable" return result } + override fun getCreateTableSqlSpecific() = "TestString VARCHAR(10) NOT NULL" -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestAchievementEntity.kt b/src/test/kotlin/dartzee/db/TestAchievementEntity.kt index e7a5d58b7..0c41d43af 100644 --- a/src/test/kotlin/dartzee/db/TestAchievementEntity.kt +++ b/src/test/kotlin/dartzee/db/TestAchievementEntity.kt @@ -16,7 +16,7 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAchievementEntity: AbstractEntityTest() { +class TestAchievementEntity : AbstractEntityTest() { override fun factoryDao() = AchievementEntity() @Test @@ -47,7 +47,6 @@ class TestAchievementEntity: AbstractEntityTest() { achievements.size shouldBe 1 achievements.first().playerId shouldBe p1.rowId achievements.first().rowId shouldBe a1.rowId - } @Test @@ -127,7 +126,12 @@ class TestAchievementEntity: AbstractEntityTest() { val gameScreen = FakeDartsScreen() ScreenCache.addDartsGameScreen(newGameId, gameScreen) - insertAchievement(type = ref, playerId = playerId, gameIdEarned = oldGameId, achievementCounter = 100) + insertAchievement( + type = ref, + playerId = playerId, + gameIdEarned = oldGameId, + achievementCounter = 100 + ) AchievementEntity.updateAchievement(ref, playerId, newGameId, 99) AchievementEntity.updateAchievement(ref, playerId, newGameId, 100) @@ -151,7 +155,12 @@ class TestAchievementEntity: AbstractEntityTest() { val gameScreen = FakeDartsScreen() ScreenCache.addDartsGameScreen(newGameId, gameScreen) - insertAchievement(type = ref, playerId = playerId, gameIdEarned = oldGameId, achievementCounter = oldValue) + insertAchievement( + type = ref, + playerId = playerId, + gameIdEarned = oldGameId, + achievementCounter = oldValue + ) AchievementEntity.updateAchievement(ref, playerId, newGameId, newValue) @@ -161,7 +170,6 @@ class TestAchievementEntity: AbstractEntityTest() { gameScreen.attainedValue shouldBe newValue } - @Test fun `updateAchievement - should preserve a decreasing achievement for values that are not strictly less`() { val ref = AchievementType.X01_BEST_GAME @@ -172,7 +180,12 @@ class TestAchievementEntity: AbstractEntityTest() { val gameScreen = FakeDartsScreen() ScreenCache.addDartsGameScreen(newGameId, gameScreen) - insertAchievement(type = ref, playerId = playerId, gameIdEarned = oldGameId, achievementCounter = 100) + insertAchievement( + type = ref, + playerId = playerId, + gameIdEarned = oldGameId, + achievementCounter = 100 + ) AchievementEntity.updateAchievement(ref, playerId, newGameId, 101) AchievementEntity.updateAchievement(ref, playerId, newGameId, 100) @@ -196,7 +209,12 @@ class TestAchievementEntity: AbstractEntityTest() { val gameScreen = FakeDartsScreen() ScreenCache.addDartsGameScreen(newGameId, gameScreen) - insertAchievement(type = ref, playerId = playerId, gameIdEarned = oldGameId, achievementCounter = oldValue) + insertAchievement( + type = ref, + playerId = playerId, + gameIdEarned = oldGameId, + achievementCounter = oldValue + ) AchievementEntity.updateAchievement(ref, playerId, newGameId, newValue) @@ -245,7 +263,7 @@ class TestAchievementEntity: AbstractEntityTest() { val playerId = randomGuid() val gameId = randomGuid() - //Start with 1 row + // Start with 1 row insertAchievement(type = ref, playerId = playerId) val scrn = FakeDartsScreen() @@ -281,8 +299,13 @@ class TestAchievementEntity: AbstractEntityTest() { val playerId = randomGuid() val gameId = randomGuid() - //Start with 1 row for 6 points - insertAchievement(type = ref, playerId = playerId, achievementCounter = 6, achievementDetail = "2") + // Start with 1 row for 6 points + insertAchievement( + type = ref, + playerId = playerId, + achievementCounter = 6, + achievementDetail = "2" + ) val scrn = FakeDartsScreen() ScreenCache.addDartsGameScreen(gameId, scrn) @@ -296,8 +319,7 @@ class TestAchievementEntity: AbstractEntityTest() { } @Test - fun `insertForUniqueCounter - should insert unique values`() - { + fun `insertForUniqueCounter - should insert unique values`() { val ref = AchievementType.DARTZEE_BINGO val playerId = randomGuid() val gameId = randomGuid() @@ -313,14 +335,15 @@ class TestAchievementEntity: AbstractEntityTest() { } @Test - fun `insertForUniqueCounter - should call into triggerAchievementUnlock`() - { + fun `insertForUniqueCounter - should call into triggerAchievementUnlock`() { val ref = AchievementType.DARTZEE_BINGO val playerId = randomGuid() val gameId = randomGuid() - //Start with 9 / 10 rows - (1..9).forEach { insertAchievement(type = ref, playerId = playerId, achievementCounter = it) } + // Start with 9 / 10 rows + (1..9).forEach { + insertAchievement(type = ref, playerId = playerId, achievementCounter = it) + } val scrn = FakeDartsScreen() ScreenCache.addDartsGameScreen(gameId, scrn) @@ -334,8 +357,7 @@ class TestAchievementEntity: AbstractEntityTest() { } @Test - fun `triggerAchievementUnlock - should do nothing if achievement has not moved over a grade boundary`() - { + fun `triggerAchievementUnlock - should do nothing if achievement has not moved over a grade boundary`() { val achievement = AchievementX01BestFinish() val oldValue = achievement.orangeThreshold @@ -345,14 +367,19 @@ class TestAchievementEntity: AbstractEntityTest() { val scrn = FakeDartsScreen() ScreenCache.addDartsGameScreen(gameId, scrn) - AchievementEntity.triggerAchievementUnlock(oldValue, newValue, achievement, randomGuid(), gameId) + AchievementEntity.triggerAchievementUnlock( + oldValue, + newValue, + achievement, + randomGuid(), + gameId + ) scrn.achievementType shouldBe null } @Test - fun `triggerAchievementUnlock - should trigger if achievement has moved over a grade boundary`() - { + fun `triggerAchievementUnlock - should trigger if achievement has moved over a grade boundary`() { val achievement = AchievementX01BestFinish() val oldValue = achievement.orangeThreshold @@ -362,10 +389,16 @@ class TestAchievementEntity: AbstractEntityTest() { val scrn = FakeDartsScreen() ScreenCache.addDartsGameScreen(gameId, scrn) - AchievementEntity.triggerAchievementUnlock(oldValue, newValue, achievement, randomGuid(), gameId) + AchievementEntity.triggerAchievementUnlock( + oldValue, + newValue, + achievement, + randomGuid(), + gameId + ) scrn.achievementType shouldBe achievement.achievementType scrn.attainedValue shouldBe achievement.yellowThreshold scrn.gameId shouldBe gameId } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestBulkInserter.kt b/src/test/kotlin/dartzee/db/TestBulkInserter.kt index 59d970ad5..1dc038a5a 100644 --- a/src/test/kotlin/dartzee/db/TestBulkInserter.kt +++ b/src/test/kotlin/dartzee/db/TestBulkInserter.kt @@ -15,32 +15,29 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import org.junit.jupiter.api.Test -class TestBulkInserter: AbstractTest() -{ +class TestBulkInserter : AbstractTest() { @Test - fun `Should do nothing if passed no entities to insert`() - { + fun `Should do nothing if passed no entities to insert`() { clearLogs() BulkInserter.insert() flushAndGetLogRecords().shouldBeEmpty() } @Test - fun `Should stack trace and do nothing if any entities are retrievedFromDb`() - { + fun `Should stack trace and do nothing if any entities are retrievedFromDb`() { val playerOne = PlayerEntity() val playerTwo = insertPlayer() BulkInserter.insert(playerOne, playerTwo) val log = verifyLog(CODE_SQL_EXCEPTION, Severity.ERROR) - log.message shouldBe "Attempting to bulk insert Player entities, but some are already in the database" + log.message shouldBe + "Attempting to bulk insert Player entities, but some are already in the database" getCountFromTable("Player") shouldBe 1 } @Test - fun `Should log SQLExceptions if something goes wrong inserting entities`() - { + fun `Should log SQLExceptions if something goes wrong inserting entities`() { val playerOne = factoryPlayer("Pete") val playerTwo = factoryPlayer("Leah") @@ -55,26 +52,28 @@ class TestBulkInserter: AbstractTest() } @Test - fun `Should insert the right number of rows per INSERT statement`() - { + fun `Should insert the right number of rows per INSERT statement`() { checkInsertBatching(prepareRows(80), 1, 80) checkInsertBatching(prepareRows(80), 20, 4) checkInsertBatching(prepareRows(80), 21, 4) } - private fun checkInsertBatching(rows: List, rowsPerInsert: Int, expectedNumberOfBatches: Int) - { + + private fun checkInsertBatching( + rows: List, + rowsPerInsert: Int, + expectedNumberOfBatches: Int + ) { wipeTable(EntityName.Game) clearLogs() BulkInserter.insert(rows, 1000, rowsPerInsert) - flushAndGetLogRecords() shouldHaveSize(expectedNumberOfBatches) + flushAndGetLogRecords() shouldHaveSize (expectedNumberOfBatches) getCountFromTable(EntityName.Game) shouldBe rows.size } @Test - fun `Should only run single-threaded successfully for a small number of rows`() - { + fun `Should only run single-threaded successfully for a small number of rows`() { val rows = prepareRows(50) BulkInserter.insert(rows, 50, 5) @@ -82,8 +81,7 @@ class TestBulkInserter: AbstractTest() } @Test - fun `Should run multi-threaded successfully`() - { + fun `Should run multi-threaded successfully`() { val rows = prepareRows(50) BulkInserter.insert(rows, 5, 5) @@ -91,8 +89,7 @@ class TestBulkInserter: AbstractTest() } @Test - fun `Should temporarily suppress logging for a large number of rows`() - { + fun `Should temporarily suppress logging for a large number of rows`() { val rows = prepareRows(501) clearLogs() @@ -112,7 +109,6 @@ class TestBulkInserter: AbstractTest() newLog.message shouldContain "INSERT INTO Game VALUES" } - private fun prepareRows(numberToGenerate: Int) = (1..numberToGenerate).map { - GameEntity().also { g -> g.assignRowId() } - } -} \ No newline at end of file + private fun prepareRows(numberToGenerate: Int) = + (1..numberToGenerate).map { GameEntity().also { g -> g.assignRowId() } } +} diff --git a/src/test/kotlin/dartzee/db/TestDartEntity.kt b/src/test/kotlin/dartzee/db/TestDartEntity.kt index 5ca6f1271..8013cfbe9 100644 --- a/src/test/kotlin/dartzee/db/TestDartEntity.kt +++ b/src/test/kotlin/dartzee/db/TestDartEntity.kt @@ -7,13 +7,11 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.junit.jupiter.api.Test -class TestDartEntity: AbstractEntityTest() -{ +class TestDartEntity : AbstractEntityTest() { override fun factoryDao() = DartEntity() @Test - fun `Should factory with the correct values`() - { + fun `Should factory with the correct values`() { val dart = Dart(20, 3, SegmentType.TREBLE) dart.startingScore = 301 val playerId = randomGuid() @@ -31,4 +29,4 @@ class TestDartEntity: AbstractEntityTest() de.multiplier shouldBe 3 de.segmentType shouldBe SegmentType.TREBLE } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDartsMatchEntity.kt b/src/test/kotlin/dartzee/db/TestDartsMatchEntity.kt index bbb668256..4fce31def 100644 --- a/src/test/kotlin/dartzee/db/TestDartsMatchEntity.kt +++ b/src/test/kotlin/dartzee/db/TestDartsMatchEntity.kt @@ -10,26 +10,22 @@ import dartzee.helper.usingInMemoryDatabase import dartzee.logging.CODE_SQL_EXCEPTION import dartzee.logging.exceptions.WrappedSqlException import dartzee.utils.InjectedThings -import io.kotest.matchers.string.shouldContain -import io.kotest.matchers.string.shouldNotBeEmpty +import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.string.shouldNotBeEmpty import org.junit.jupiter.api.Test -class TestDartsMatchEntity: AbstractEntityTest() -{ +class TestDartsMatchEntity : AbstractEntityTest() { override fun factoryDao() = DartsMatchEntity() @Test - fun `LocalId field should be unique`() - { + fun `LocalId field should be unique`() { insertDartsMatch(localId = 5) verifyNoLogs(CODE_SQL_EXCEPTION) - val ex = shouldThrow { - insertDartsMatch(localId = 5) - } + val ex = shouldThrow { insertDartsMatch(localId = 5) } val sqle = ex.sqlException sqle.message shouldContain "duplicate key" @@ -38,8 +34,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `LocalIds should be assigned along with RowId`() - { + fun `LocalIds should be assigned along with RowId`() { val entity = DartsMatchEntity() entity.assignRowId() @@ -48,8 +43,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `Should reassign localId when merging into another database`() - { + fun `Should reassign localId when merging into another database`() { usingInMemoryDatabase(withSchema = true) { otherDatabase -> insertDartsMatch(database = otherDatabase) insertDartsMatch(database = otherDatabase) @@ -66,8 +60,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `FIRST_TO descriptions`() - { + fun `FIRST_TO descriptions`() { val dm = DartsMatchEntity() dm.localId = 1 dm.games = 3 @@ -79,8 +72,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `POINTS descriptions`() - { + fun `POINTS descriptions`() { val dm = DartsMatchEntity() dm.localId = 1 dm.games = 3 @@ -92,8 +84,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `Should only return 1 point for 1st place in FIRST_TO`() - { + fun `Should only return 1 point for 1st place in FIRST_TO`() { val dm = DartsMatchEntity.factoryFirstTo(3) dm.getScoreForFinishingPosition(1) shouldBe 1 @@ -104,8 +95,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `Should return the correct points per position in POINTS mode`() - { + fun `Should return the correct points per position in POINTS mode`() { val matchParams = constructPointsJson(15, 9, 6, 3, 2, 1) val dm = DartsMatchEntity.factoryPoints(3, matchParams) @@ -119,8 +109,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `Should cache metadata from a game correctly`() - { + fun `Should cache metadata from a game correctly`() { val game501 = insertGame(gameType = GameType.X01, gameParams = "301") val gameGolf = insertGame(gameType = GameType.GOLF, gameParams = "18") @@ -136,8 +125,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `Should save a first-to match correctly`() - { + fun `Should save a first-to match correctly`() { val dm = DartsMatchEntity.factoryFirstTo(3) val retrievedDm = dm.retrieveForId(dm.rowId)!! @@ -148,8 +136,7 @@ class TestDartsMatchEntity: AbstractEntityTest() } @Test - fun `Should save a points match correctly`() - { + fun `Should save a points match correctly`() { val dm = DartsMatchEntity.factoryPoints(3, "foo") val retrievedDm = dm.retrieveForId(dm.rowId)!! @@ -158,4 +145,4 @@ class TestDartsMatchEntity: AbstractEntityTest() retrievedDm.mode shouldBe MatchMode.POINTS retrievedDm.localId shouldNotBe -1 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDartzeeRoundResultEntity.kt b/src/test/kotlin/dartzee/db/TestDartzeeRoundResultEntity.kt index 631428112..b3fc3d937 100644 --- a/src/test/kotlin/dartzee/db/TestDartzeeRoundResultEntity.kt +++ b/src/test/kotlin/dartzee/db/TestDartzeeRoundResultEntity.kt @@ -8,13 +8,11 @@ import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeRoundResultEntity: AbstractEntityTest() -{ +class TestDartzeeRoundResultEntity : AbstractEntityTest() { override fun factoryDao() = DartzeeRoundResultEntity() @Test - fun `Should be indexed on PlayerId_ParticipantId_RoundNumber`() - { + fun `Should be indexed on PlayerId_ParticipantId_RoundNumber`() { val indexes = mutableListOf>() factoryDao().addListsOfColumnsForIndexes(indexes) @@ -22,8 +20,7 @@ class TestDartzeeRoundResultEntity: AbstractEntityTest } @Test - fun `Should convert to a DTO correctly`() - { + fun `Should convert to a DTO correctly`() { val entity = DartzeeRoundResultEntity() entity.roundNumber = 5 entity.ruleNumber = 2 @@ -38,8 +35,7 @@ class TestDartzeeRoundResultEntity: AbstractEntityTest } @Test - fun `Should save from a DTO correctly`() - { + fun `Should save from a DTO correctly`() { val dto = DartzeeRoundResult(5, false, -100) val player = insertPlayer() @@ -57,4 +53,4 @@ class TestDartzeeRoundResultEntity: AbstractEntityTest entity.success shouldBe false entity.score shouldBe -100 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDartzeeRuleEntity.kt b/src/test/kotlin/dartzee/db/TestDartzeeRuleEntity.kt index 96f5b0801..4be2eed2a 100644 --- a/src/test/kotlin/dartzee/db/TestDartzeeRuleEntity.kt +++ b/src/test/kotlin/dartzee/db/TestDartzeeRuleEntity.kt @@ -19,13 +19,11 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.Test -class TestDartzeeRuleEntity: AbstractEntityTest() -{ +class TestDartzeeRuleEntity : AbstractEntityTest() { override fun factoryDao() = DartzeeRuleEntity() @Test - fun `Should support unset dartzee rules`() - { + fun `Should support unset dartzee rules`() { val entity = DartzeeRuleEntity() val rowId = entity.assignRowId() entity.dart1Rule = DartzeeDartRuleEven().toDbString() @@ -39,8 +37,7 @@ class TestDartzeeRuleEntity: AbstractEntityTest() } @Test - fun `Should support large custom rules in all the dart rule fields`() - { + fun `Should support large custom rules in all the dart rule fields`() { val entity = DartzeeRuleEntity() val rowId = entity.assignRowId() @@ -51,11 +48,9 @@ class TestDartzeeRuleEntity: AbstractEntityTest() entity.dart2Rule = customRule.toDbString() entity.dart3Rule = customRule.toDbString() - shouldNotThrowAny { - entity.saveToDatabase() - } + shouldNotThrowAny { entity.saveToDatabase() } - //Re-retrieve to make sure no silent truncation has happened + // Re-retrieve to make sure no silent truncation has happened val reretrievedEntity = DartzeeRuleEntity().retrieveForId(rowId)!! reretrievedEntity.dart1Rule shouldBe customRule.toDbString() reretrievedEntity.dart2Rule shouldBe customRule.toDbString() @@ -63,8 +58,7 @@ class TestDartzeeRuleEntity: AbstractEntityTest() } @Test - fun `Should repopulate the DTO correctly`() - { + fun `Should repopulate the DTO correctly`() { val entity = DartzeeRuleEntity() entity.dart1Rule = "" entity.dart2Rule = "" @@ -92,8 +86,7 @@ class TestDartzeeRuleEntity: AbstractEntityTest() } @Test - fun `Should optionally skip populating the calculationResult when converting to a DTO`() - { + fun `Should optionally skip populating the calculationResult when converting to a DTO`() { val entity = DartzeeRuleEntity() entity.dart1Rule = "" entity.dart2Rule = "" @@ -118,8 +111,7 @@ class TestDartzeeRuleEntity: AbstractEntityTest() } @Test - fun `Should convert empty values to nulls when converting to a DTO`() - { + fun `Should convert empty values to nulls when converting to a DTO`() { val entity = DartzeeRuleEntity() entity.dart1Rule = "" entity.dart2Rule = "" @@ -139,35 +131,70 @@ class TestDartzeeRuleEntity: AbstractEntityTest() } @Test - fun `Should retrieve rows for a template, sorted by ordinal`() - { + fun `Should retrieve rows for a template, sorted by ordinal`() { val templateA = insertDartzeeTemplate(name = "Template A") val templateB = insertDartzeeTemplate(name = "Template B") - val ruleA3 = insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateA.rowId, ordinal = 3) - val ruleA1 = insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateA.rowId, ordinal = 1) - val ruleA2 = insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateA.rowId, ordinal = 2) - - insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateB.rowId, ordinal = 1) + val ruleA3 = + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateA.rowId, + ordinal = 3 + ) + val ruleA1 = + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateA.rowId, + ordinal = 1 + ) + val ruleA2 = + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateA.rowId, + ordinal = 2 + ) + + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateB.rowId, + ordinal = 1 + ) insertDartzeeRule(entityName = EntityName.Game, entityId = templateA.rowId, ordinal = 4) val rules = DartzeeRuleEntity().retrieveForTemplate(templateA.rowId) - rules.map{ it.rowId }.shouldContainExactly(ruleA1.rowId, ruleA2.rowId, ruleA3.rowId) + rules.map { it.rowId }.shouldContainExactly(ruleA1.rowId, ruleA2.rowId, ruleA3.rowId) } @Test - fun `Should delete rows for a template`() - { + fun `Should delete rows for a template`() { val templateA = insertDartzeeTemplate(name = "Template A") val templateB = insertDartzeeTemplate(name = "Template B") - insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateA.rowId, ordinal = 3) - insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateA.rowId, ordinal = 1) - insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateA.rowId, ordinal = 2) - - val ruleB1 = insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = templateB.rowId, ordinal = 1) - val gameRule = insertDartzeeRule(entityName = EntityName.Game, entityId = templateA.rowId, ordinal = 4) + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateA.rowId, + ordinal = 3 + ) + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateA.rowId, + ordinal = 1 + ) + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateA.rowId, + ordinal = 2 + ) + + val ruleB1 = + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = templateB.rowId, + ordinal = 1 + ) + val gameRule = + insertDartzeeRule(entityName = EntityName.Game, entityId = templateA.rowId, ordinal = 4) DartzeeRuleEntity().deleteForTemplate(templateA.rowId) @@ -177,8 +204,7 @@ class TestDartzeeRuleEntity: AbstractEntityTest() } @Test - fun `Should delete rows for a game`() - { + fun `Should delete rows for a game`() { val gameA = insertGame() val gameB = insertGame() @@ -186,32 +212,45 @@ class TestDartzeeRuleEntity: AbstractEntityTest() insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 1) insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 2) - val ruleB1 = insertDartzeeRule(entityName = EntityName.Game, entityId = gameB.rowId, ordinal = 1) - val templateRule = insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = insertDartzeeTemplate().rowId, ordinal = 1) + val ruleB1 = + insertDartzeeRule(entityName = EntityName.Game, entityId = gameB.rowId, ordinal = 1) + val templateRule = + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = insertDartzeeTemplate().rowId, + ordinal = 1 + ) DartzeeRuleEntity().deleteForGame(gameA.rowId) val remainingRules = DartzeeRuleEntity().retrieveEntities() - remainingRules.map { it.rowId }.shouldContainExactlyInAnyOrder(ruleB1.rowId, templateRule.rowId) + remainingRules + .map { it.rowId } + .shouldContainExactlyInAnyOrder(ruleB1.rowId, templateRule.rowId) } @Test - fun `Should retrieve rules for a game, sorted by ordinal`() - { + fun `Should retrieve rules for a game, sorted by ordinal`() { val gameA = insertGame() val gameB = insertGame() - val ruleA3 = insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 3) - val ruleA1 = insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 1) - val ruleA2 = insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 2) + val ruleA3 = + insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 3) + val ruleA1 = + insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 1) + val ruleA2 = + insertDartzeeRule(entityName = EntityName.Game, entityId = gameA.rowId, ordinal = 2) insertDartzeeRule(entityName = EntityName.Game, entityId = gameB.rowId, ordinal = 1) - insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = gameA.rowId, ordinal = 4) + insertDartzeeRule( + entityName = EntityName.DartzeeTemplate, + entityId = gameA.rowId, + ordinal = 4 + ) val rules = DartzeeRuleEntity().retrieveForGame(gameA.rowId) - rules.map{ it.rowId }.shouldContainExactly(ruleA1.rowId, ruleA2.rowId, ruleA3.rowId) + rules.map { it.rowId }.shouldContainExactly(ruleA1.rowId, ruleA2.rowId, ruleA3.rowId) } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDartzeeTemplateEntity.kt b/src/test/kotlin/dartzee/db/TestDartzeeTemplateEntity.kt index ead6c2a4b..55f630c24 100644 --- a/src/test/kotlin/dartzee/db/TestDartzeeTemplateEntity.kt +++ b/src/test/kotlin/dartzee/db/TestDartzeeTemplateEntity.kt @@ -4,13 +4,11 @@ import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeTemplateEntity: AbstractEntityTest() -{ +class TestDartzeeTemplateEntity : AbstractEntityTest() { override fun factoryDao() = DartzeeTemplateEntity() @Test - fun `Should use the template name for toString`() - { + fun `Should use the template name for toString`() { val template = DartzeeTemplateEntity() template.name = "Foo" @@ -18,8 +16,7 @@ class TestDartzeeTemplateEntity: AbstractEntityTest() } @Test - fun `Should factory and save`() - { + fun `Should factory and save`() { DartzeeTemplateEntity.factoryAndSave("Hello") val entityOnDb = DartzeeTemplateEntity().retrieveEntities().first() @@ -27,4 +24,4 @@ class TestDartzeeTemplateEntity: AbstractEntityTest() entityOnDb.name shouldBe "Hello" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDatabaseMIgrationV21toV22.kt b/src/test/kotlin/dartzee/db/TestDatabaseMIgrationV21toV22.kt index 8b06c7a1d..fc082281e 100644 --- a/src/test/kotlin/dartzee/db/TestDatabaseMIgrationV21toV22.kt +++ b/src/test/kotlin/dartzee/db/TestDatabaseMIgrationV21toV22.kt @@ -11,11 +11,9 @@ import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Test -class TestDatabaseMIgrationV21toV22 : AbstractTest() -{ +class TestDatabaseMIgrationV21toV22 : AbstractTest() { @Test - fun `Should update MISSED_BOARD darts to just MISS`() - { + fun `Should update MISSED_BOARD darts to just MISS`() { val segmentType = mockk() every { segmentType.toString() } returns "MISSED_BOARD" val dart = insertDart(insertParticipant(), segmentType = segmentType) @@ -27,8 +25,7 @@ class TestDatabaseMIgrationV21toV22 : AbstractTest() } @Test - fun `Should leave other segment types alone`() - { + fun `Should leave other segment types alone`() { SegmentType.values().forEach { segmentType -> wipeDatabase() val dart = insertDart(insertParticipant(), segmentType = segmentType) @@ -38,4 +35,4 @@ class TestDatabaseMIgrationV21toV22 : AbstractTest() retrieved.segmentType shouldBe segmentType } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDatabaseMerger.kt b/src/test/kotlin/dartzee/db/TestDatabaseMerger.kt index 1f37d79af..7f960da75 100644 --- a/src/test/kotlin/dartzee/db/TestDatabaseMerger.kt +++ b/src/test/kotlin/dartzee/db/TestDatabaseMerger.kt @@ -20,14 +20,12 @@ import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestDatabaseMerger: AbstractTest() -{ +class TestDatabaseMerger : AbstractTest() { @Test - fun `Should insert into SyncAudit when performing the merge`() - { + fun `Should insert into SyncAudit when performing the merge`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val merger = makeDatabaseMerger(remoteDatabase = remoteDatabase, remoteName = "Goomba") val result = merger.performMerge() @@ -38,8 +36,7 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should not sync the PendingLogs table`() - { + fun `Should not sync the PendingLogs table`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> PendingLogsEntity.factory("foo").saveToDatabase() @@ -52,8 +49,7 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should not sync the Achievement table`() - { + fun `Should not sync the Achievement table`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> insertAchievement(database = mainDatabase) @@ -66,13 +62,14 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should only sync rows that were modified since the last sync`() - { + fun `Should only sync rows that were modified since the last sync`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val dtLastSync = setUpLastSync(mainDatabase) - val oldGame = insertGame(dtLastUpdate = getPastTime(dtLastSync), database = mainDatabase) - val newGame = insertGame(dtLastUpdate = getFutureTime(dtLastSync), database = mainDatabase) + val oldGame = + insertGame(dtLastUpdate = getPastTime(dtLastSync), database = mainDatabase) + val newGame = + insertGame(dtLastUpdate = getFutureTime(dtLastSync), database = mainDatabase) val merger = makeDatabaseMerger(mainDatabase, remoteDatabase) val resultingDatabase = merger.performMerge() @@ -84,8 +81,7 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should sync all rows if no last sync date`() - { + fun `Should sync all rows if no last sync date`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val oldGame = insertGame(dtLastUpdate = Timestamp(500), database = mainDatabase) val newGame = insertGame(dtLastUpdate = getSqlDateNow(), database = mainDatabase) @@ -100,8 +96,7 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should sync deletion audits and remove corresponding rows from the remote`() - { + fun `Should sync deletion audits and remove corresponding rows from the remote`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val game = insertGame(database = remoteDatabase) @@ -116,8 +111,7 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should handle syncing a newly deleted entity that never made it to the remote`() - { + fun `Should handle syncing a newly deleted entity that never made it to the remote`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val game = insertGame(database = mainDatabase) @@ -132,13 +126,14 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should reassign localIds in order for new games`() - { + fun `Should reassign localIds in order for new games`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> insertGame(localId = 7, database = remoteDatabase) - val gameOne = insertGame(localId = 1, dtCreation = Timestamp(500), database = mainDatabase) - val gameTwo = insertGame(localId = 2, dtCreation = Timestamp(1000), database = mainDatabase) + val gameOne = + insertGame(localId = 1, dtCreation = Timestamp(500), database = mainDatabase) + val gameTwo = + insertGame(localId = 2, dtCreation = Timestamp(1000), database = mainDatabase) val merger = makeDatabaseMerger(mainDatabase, remoteDatabase) val resultingDatabase = merger.performMerge() @@ -150,17 +145,17 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should not reassign localId for a modified game`() - { + fun `Should not reassign localId for a modified game`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val dtLastSync = setUpLastSync(mainDatabase) - val oldGame = insertGame( - localId = 4, - dtFinish = DateStatics.END_OF_TIME, - dtLastUpdate = getPastTime(dtLastSync), - database = remoteDatabase - ) + val oldGame = + insertGame( + localId = 4, + dtFinish = DateStatics.END_OF_TIME, + dtLastUpdate = getPastTime(dtLastSync), + database = remoteDatabase + ) insertGame(localId = 7, database = remoteDatabase) insertGame( @@ -182,11 +177,14 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should regenerate achievement rows for players whose achievements have changed`() - { + fun `Should regenerate achievement rows for players whose achievements have changed`() { val (playerId, gameId) = setUpThreeDarterData() - insertAchievement(playerId = playerId, type = AchievementType.X01_BEST_THREE_DART_SCORE, achievementCounter = 60) + insertAchievement( + playerId = playerId, + type = AchievementType.X01_BEST_THREE_DART_SCORE, + achievementCounter = 60 + ) usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val merger = makeDatabaseMerger(mainDatabase, remoteDatabase) @@ -194,7 +192,8 @@ class TestDatabaseMerger: AbstractTest() getCountFromTable("Achievement", resultingDb) shouldBe 1 - val remoteRow = AchievementEntity(resultingDb).retrieveEntity("PlayerId = '$playerId'")!! + val remoteRow = + AchievementEntity(resultingDb).retrieveEntity("PlayerId = '$playerId'")!! remoteRow.achievementCounter shouldBe 140 remoteRow.achievementType shouldBe AchievementType.X01_BEST_THREE_DART_SCORE remoteRow.gameIdEarned shouldBe gameId @@ -202,18 +201,23 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should not replace achievement rows for players whose achievements have not changed`() - { + fun `Should not replace achievement rows for players whose achievements have not changed`() { val (playerId, _) = setUpThreeDarterData() - insertAchievement(playerId = playerId, type = AchievementType.X01_BEST_THREE_DART_SCORE, achievementCounter = 60) + insertAchievement( + playerId = playerId, + type = AchievementType.X01_BEST_THREE_DART_SCORE, + achievementCounter = 60 + ) usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val remotePlayer = insertPlayer(database = remoteDatabase) - insertAchievement(playerId = remotePlayer.rowId, + insertAchievement( + playerId = remotePlayer.rowId, type = AchievementType.X01_BEST_THREE_DART_SCORE, database = remoteDatabase, - achievementCounter = 25) + achievementCounter = 25 + ) val merger = makeDatabaseMerger(mainDatabase, remoteDatabase) val resultingDb = merger.performMerge() @@ -221,18 +225,23 @@ class TestDatabaseMerger: AbstractTest() getCountFromTable("Achievement", mainDatabase) shouldBe 1 getCountFromTable("Achievement", resultingDb) shouldBe 2 - val remoteRow = AchievementEntity(resultingDb).retrieveEntity("PlayerId = '${remotePlayer.rowId}'")!! + val remoteRow = + AchievementEntity(resultingDb) + .retrieveEntity("PlayerId = '${remotePlayer.rowId}'")!! remoteRow.achievementCounter shouldBe 25 remoteRow.achievementType shouldBe AchievementType.X01_BEST_THREE_DART_SCORE } } @Test - fun `Should only run achievement conversion for changed refs`() - { + fun `Should only run achievement conversion for changed refs`() { val (playerId, _) = setUpThreeDarterData() - insertAchievement(playerId = playerId, type = AchievementType.X01_BEST_FINISH, achievementCounter = 60) + insertAchievement( + playerId = playerId, + type = AchievementType.X01_BEST_FINISH, + achievementCounter = 60 + ) usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val merger = makeDatabaseMerger(mainDatabase, remoteDatabase) @@ -243,16 +252,17 @@ class TestDatabaseMerger: AbstractTest() } @Test - fun `Should not run achievement conversion at all if no achievements changed`() - { + fun `Should not run achievement conversion at all if no achievements changed`() { val (playerId, _) = setUpThreeDarterData() usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val remotePlayer = insertPlayer(uuid = playerId, database = remoteDatabase) - insertAchievement(playerId = remotePlayer.rowId, + insertAchievement( + playerId = remotePlayer.rowId, type = AchievementType.GOLF_BEST_GAME, database = remoteDatabase, - achievementCounter = 18) + achievementCounter = 18 + ) val merger = makeDatabaseMerger(mainDatabase, remoteDatabase) val resultingDb = merger.performMerge() @@ -260,33 +270,55 @@ class TestDatabaseMerger: AbstractTest() getCountFromTable("Achievement", mainDatabase) shouldBe 0 getCountFromTable("Achievement", resultingDb) shouldBe 1 - val remoteRow = AchievementEntity(resultingDb).retrieveEntity("PlayerId = '${remotePlayer.rowId}'")!! + val remoteRow = + AchievementEntity(resultingDb) + .retrieveEntity("PlayerId = '${remotePlayer.rowId}'")!! remoteRow.achievementCounter shouldBe 18 remoteRow.achievementType shouldBe AchievementType.GOLF_BEST_GAME } } - private fun setUpThreeDarterData(): Pair - { + private fun setUpThreeDarterData(): Pair { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) val pt = insertParticipant(playerId = p.rowId, gameId = g.rowId) - insertDart(pt, startingScore = 501, roundNumber = 1, ordinal = 1, score = 20, multiplier = 3) - insertDart(pt, startingScore = 441, roundNumber = 1, ordinal = 2, score = 20, multiplier = 3) - insertDart(pt, startingScore = 381, roundNumber = 1, ordinal = 3, score = 20, multiplier = 1) + insertDart( + pt, + startingScore = 501, + roundNumber = 1, + ordinal = 1, + score = 20, + multiplier = 3 + ) + insertDart( + pt, + startingScore = 441, + roundNumber = 1, + ordinal = 2, + score = 20, + multiplier = 3 + ) + insertDart( + pt, + startingScore = 381, + roundNumber = 1, + ordinal = 3, + score = 20, + multiplier = 1 + ) return Pair(p.rowId, g.rowId) } - private fun setUpLastSync(database: Database): Timestamp - { + private fun setUpLastSync(database: Database): Timestamp { SyncAuditEntity.insertSyncAudit(database, "Goomba") return SyncAuditEntity.getLastSyncData(database)!!.lastSynced } - private fun makeDatabaseMerger(localDatabase: Database = mainDatabase, - remoteDatabase: Database, - remoteName: String = "Goomba") = - DatabaseMerger(localDatabase, remoteDatabase, remoteName) -} \ No newline at end of file + private fun makeDatabaseMerger( + localDatabase: Database = mainDatabase, + remoteDatabase: Database, + remoteName: String = "Goomba" + ) = DatabaseMerger(localDatabase, remoteDatabase, remoteName) +} diff --git a/src/test/kotlin/dartzee/db/TestDatabaseMigrationV19toV20.kt b/src/test/kotlin/dartzee/db/TestDatabaseMigrationV19toV20.kt index c885c521b..9522af969 100644 --- a/src/test/kotlin/dartzee/db/TestDatabaseMigrationV19toV20.kt +++ b/src/test/kotlin/dartzee/db/TestDatabaseMigrationV19toV20.kt @@ -10,11 +10,9 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDatabaseMigrationV19toV20: AbstractTest() -{ +class TestDatabaseMigrationV19toV20 : AbstractTest() { @Test - fun `Should correctly add Team table, and TeamId column for Participant`() - { + fun `Should correctly add Team table, and TeamId column for Participant`() { // Setup val pt = insertParticipant() mainDatabase.dropTable(EntityName.Team) @@ -29,4 +27,4 @@ class TestDatabaseMigrationV19toV20: AbstractTest() val updatedPt = ParticipantEntity().retrieveForId(pt.rowId)!! updatedPt.teamId shouldBe "" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDatabaseMigrationV20toV21.kt b/src/test/kotlin/dartzee/db/TestDatabaseMigrationV20toV21.kt index 766983f78..4e60fb24c 100644 --- a/src/test/kotlin/dartzee/db/TestDatabaseMigrationV20toV21.kt +++ b/src/test/kotlin/dartzee/db/TestDatabaseMigrationV20toV21.kt @@ -8,11 +8,9 @@ import dartzee.utils.InjectedThings.mainDatabase import io.kotest.matchers.nulls.shouldNotBeNull import org.junit.jupiter.api.Test -class TestDatabaseMigrationV20toV21: AbstractTest() -{ +class TestDatabaseMigrationV20toV21 : AbstractTest() { @Test - fun `Should correctly drop old columns`() - { + fun `Should correctly drop old columns`() { val dart = insertDart(insertParticipant()) mainDatabase.executeUpdate("ALTER TABLE Dart ADD COLUMN PosX INT DEFAULT 0") @@ -23,4 +21,4 @@ class TestDatabaseMigrationV20toV21: AbstractTest() val retrieved = DartEntity().retrieveForId(dart.rowId) retrieved.shouldNotBeNull() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDatabaseMigrations.kt b/src/test/kotlin/dartzee/db/TestDatabaseMigrations.kt index 180873973..9400cee31 100644 --- a/src/test/kotlin/dartzee/db/TestDatabaseMigrations.kt +++ b/src/test/kotlin/dartzee/db/TestDatabaseMigrations.kt @@ -9,11 +9,9 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDatabaseMigrations: AbstractTest() -{ +class TestDatabaseMigrations : AbstractTest() { @Test - fun `Conversions map should not have gaps`() - { + fun `Conversions map should not have gaps`() { val supportedVersions = DatabaseMigrations.getConversionsMap().keys val min = supportedVersions.minOrNull()!! val max = supportedVersions.maxOrNull()!! @@ -22,8 +20,7 @@ class TestDatabaseMigrations: AbstractTest() } @Test - fun `Conversions map should get us up to the current version`() - { + fun `Conversions map should get us up to the current version`() { val supportedVersions = DatabaseMigrations.getConversionsMap().keys val max = supportedVersions.maxOrNull()!! @@ -31,28 +28,25 @@ class TestDatabaseMigrations: AbstractTest() } @Test - fun `Conversions should all run on the specified database`() - { - try - { + fun `Conversions should all run on the specified database`() { + try { usingInMemoryDatabase(withSchema = true) { dbToRunOn -> mainDatabase.shutDown() shouldBe true val conversionFns = DatabaseMigrations.getConversionsMap().values.flatten() - for (conversion in conversionFns) - { - try { conversion(dbToRunOn) } catch (_: Exception) {} + for (conversion in conversionFns) { + try { + conversion(dbToRunOn) + } catch (_: Exception) {} } - //Will probably have one logged, which is fine + // Will probably have one logged, which is fine errorLogged() - //If it's been connected to during the test, then another shut down would succeed + // If it's been connected to during the test, then another shut down would succeed mainDatabase.shutDown() shouldBe false } - } - finally - { + } finally { mainDatabase.initialiseConnectionPool(1) } } diff --git a/src/test/kotlin/dartzee/db/TestDatabaseMigrator.kt b/src/test/kotlin/dartzee/db/TestDatabaseMigrator.kt index f3c818120..ff86cb28a 100644 --- a/src/test/kotlin/dartzee/db/TestDatabaseMigrator.kt +++ b/src/test/kotlin/dartzee/db/TestDatabaseMigrator.kt @@ -18,11 +18,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDatabaseMigrator: AbstractTest() -{ +class TestDatabaseMigrator : AbstractTest() { @Test - fun `Should initialise a fresh database if no version is found`() - { + fun `Should initialise a fresh database if no version is found`() { clearLogs() usingInMemoryDatabase { db -> @@ -35,15 +33,17 @@ class TestDatabaseMigrator: AbstractTest() db.getDatabaseVersion() shouldBe DATABASE_VERSION - val expectedTableNames = DartsDatabaseUtil.getAllEntitiesIncludingVersion().map { it.getTableNameUpperCase() } + val expectedTableNames = + DartsDatabaseUtil.getAllEntitiesIncludingVersion().map { + it.getTableNameUpperCase() + } val tableNames = db.getTableNames() tableNames.shouldContainExactlyInAnyOrder(expectedTableNames) } } @Test - fun `Should not carry out a migration if database is already on the latest version`() - { + fun `Should not carry out a migration if database is already on the latest version`() { clearLogs() usingInMemoryDatabase { db -> @@ -60,11 +60,11 @@ class TestDatabaseMigrator: AbstractTest() } @Test - fun `Should not carry out a migration if database version is too old based on migrations passed in`() - { + fun `Should not carry out a migration if database version is too old based on migrations passed in`() { clearLogs() - val migrations = mapOf(13 to listOf { _: Database -> true }, 14 to listOf { _: Database -> true }) + val migrations = + mapOf(13 to listOf { _: Database -> true }, 14 to listOf { _: Database -> true }) usingInMemoryDatabase { database -> val oldVersion = 12 @@ -77,10 +77,13 @@ class TestDatabaseMigrator: AbstractTest() verifyLog(CODE_DATABASE_TOO_OLD, Severity.WARN) database.getTableNames().shouldContainExactly("VERSION") - val dbDetails = "Test version: $oldVersion, min supported: 13, current: $DATABASE_VERSION" + val dbDetails = + "Test version: $oldVersion, min supported: 13, current: $DATABASE_VERSION" - dialogFactory.errorsShown.shouldContainExactly("Test database is too out-of-date to be upgraded by this version of Dartzee. " + - "Please downgrade to an earlier version so that the data can be converted.\n\n$dbDetails") + dialogFactory.errorsShown.shouldContainExactly( + "Test database is too out-of-date to be upgraded by this version of Dartzee. " + + "Please downgrade to an earlier version so that the data can be converted.\n\n$dbDetails" + ) } } @@ -89,31 +92,39 @@ class TestDatabaseMigrator: AbstractTest() usingInMemoryDatabase { database -> database.updateDatabaseVersion(DATABASE_VERSION - 2) - val migration1a = { db: Database -> db.executeUpdate("CREATE TABLE Test(RowId VARCHAR(36) PRIMARY KEY)") } - val migration1b = { db: Database -> db.executeUpdate("ALTER TABLE Test ADD TestCol2 INT") } - val migration2 = { db: Database -> db.executeUpdate("RENAME COLUMN Test.TestCol2 TO IntCol2") } + val migration1a = { db: Database -> + db.executeUpdate("CREATE TABLE Test(RowId VARCHAR(36) PRIMARY KEY)") + } + val migration1b = { db: Database -> + db.executeUpdate("ALTER TABLE Test ADD TestCol2 INT") + } + val migration2 = { db: Database -> + db.executeUpdate("RENAME COLUMN Test.TestCol2 TO IntCol2") + } - val map = mapOf( - DATABASE_VERSION - 2 to listOf(migration1a, migration1b), - DATABASE_VERSION - 1 to listOf(migration2) - ) + val map = + mapOf( + DATABASE_VERSION - 2 to listOf(migration1a, migration1b), + DATABASE_VERSION - 1 to listOf(migration2) + ) val migrator = DatabaseMigrator(map) val result = migrator.migrateToLatest(database, "Test") result shouldBe MigrationResult.SUCCESS // Logging - val logs = flushAndGetLogRecords().filter { it.loggingCode == CODE_DATABASE_NEEDS_UPDATE } - logs.map { it.message }.shouldContainExactly( - "Upgrading Test database to V${DATABASE_VERSION - 1} (2 migrations)", - "Upgrading Test database to V${DATABASE_VERSION} (1 migrations)" - ) + val logs = + flushAndGetLogRecords().filter { it.loggingCode == CODE_DATABASE_NEEDS_UPDATE } + logs + .map { it.message } + .shouldContainExactly( + "Upgrading Test database to V${DATABASE_VERSION - 1} (2 migrations)", + "Upgrading Test database to V${DATABASE_VERSION} (1 migrations)" + ) // Should be on latest version and have expected metadata database.getDatabaseVersion() shouldBe DATABASE_VERSION - shouldNotThrowAny { - database.executeQuery("SELECT RowId, IntCol2 FROM Test") - } + shouldNotThrowAny { database.executeQuery("SELECT RowId, IntCol2 FROM Test") } } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestDeletionAuditEntity.kt b/src/test/kotlin/dartzee/db/TestDeletionAuditEntity.kt index 1f55f2388..3ddd0a185 100644 --- a/src/test/kotlin/dartzee/db/TestDeletionAuditEntity.kt +++ b/src/test/kotlin/dartzee/db/TestDeletionAuditEntity.kt @@ -1,6 +1,5 @@ package dartzee.db -class TestDeletionAuditEntity: AbstractEntityTest() -{ +class TestDeletionAuditEntity : AbstractEntityTest() { override fun factoryDao() = DeletionAuditEntity() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestForeignDatabaseValidator.kt b/src/test/kotlin/dartzee/db/TestForeignDatabaseValidator.kt index f1d1f0464..3453d9f88 100644 --- a/src/test/kotlin/dartzee/db/TestForeignDatabaseValidator.kt +++ b/src/test/kotlin/dartzee/db/TestForeignDatabaseValidator.kt @@ -12,22 +12,21 @@ import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Test -class TestForeignDatabaseValidator: AbstractTest() -{ +class TestForeignDatabaseValidator : AbstractTest() { @Test - fun `Should return false if connecting to remote database fails`() - { + fun `Should return false if connecting to remote database fails`() { val remote = mockk() every { remote.testConnection() } returns false val validator = makeValidator() validator.validateAndMigrateForeignDatabase(remote, "remote") shouldBe false - dialogFactory.errorsShown.shouldContainExactly("An error occurred connecting to the remote database.") + dialogFactory.errorsShown.shouldContainExactly( + "An error occurred connecting to the remote database." + ) } @Test - fun `Should return false and log an error if remote database version cannot be verified`() - { + fun `Should return false and log an error if remote database version cannot be verified`() { val remoteDatabase = mockk(relaxed = true) every { remoteDatabase.testConnection() } returns true every { remoteDatabase.getDatabaseVersion() } returns null @@ -36,25 +35,28 @@ class TestForeignDatabaseValidator: AbstractTest() validator.validateAndMigrateForeignDatabase(remoteDatabase, "selected") shouldBe false val log = verifyLog(CODE_MERGE_ERROR, Severity.ERROR) - log.message shouldBe "Unable to ascertain selected database version (but could connect) - this is unexpected." - dialogFactory.errorsShown.shouldContainExactly("An error occurred connecting to the selected database.") + log.message shouldBe + "Unable to ascertain selected database version (but could connect) - this is unexpected." + dialogFactory.errorsShown.shouldContainExactly( + "An error occurred connecting to the selected database." + ) } @Test - fun `Should return false if remote database has higher version`() - { + fun `Should return false if remote database has higher version`() { usingInMemoryDatabase { remoteDatabase -> remoteDatabase.updateDatabaseVersion(DartsDatabaseUtil.DATABASE_VERSION + 1) val validator = makeValidator() validator.validateAndMigrateForeignDatabase(remoteDatabase, "other") shouldBe false - dialogFactory.errorsShown.shouldContainExactly("The other database contains data written by a higher Dartzee version. \n\nYou will need to update to the latest version of Dartzee before continuing.") + dialogFactory.errorsShown.shouldContainExactly( + "The other database contains data written by a higher Dartzee version. \n\nYou will need to update to the latest version of Dartzee before continuing." + ) } } @Test - fun `Should return false if unable to migrate remote database`() - { + fun `Should return false if unable to migrate remote database`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val dbVersion = DartsDatabaseUtil.DATABASE_VERSION - 1 remoteDatabase.updateDatabaseVersion(dbVersion) @@ -65,24 +67,27 @@ class TestForeignDatabaseValidator: AbstractTest() result shouldBe false val dbDetails = - "Other version: $dbVersion, min supported: ${DartsDatabaseUtil.DATABASE_VERSION}, current: ${DartsDatabaseUtil.DATABASE_VERSION}" + "Other version: $dbVersion, min supported: ${DartsDatabaseUtil.DATABASE_VERSION}, current: ${DartsDatabaseUtil.DATABASE_VERSION}" dialogFactory.errorsShown.shouldContainExactly( - "Other database is too out-of-date to be upgraded by this version of Dartzee. " + - "Please downgrade to an earlier version so that the data can be converted.\n\n$dbDetails" + "Other database is too out-of-date to be upgraded by this version of Dartzee. " + + "Please downgrade to an earlier version so that the data can be converted.\n\n$dbDetails" ) } } @Test - fun `Should migrate remote database to latest version and return true on success`() - { + fun `Should migrate remote database to latest version and return true on success`() { usingInMemoryDatabase(withSchema = true) { remoteDatabase -> val dbVersion = DartsDatabaseUtil.DATABASE_VERSION - 1 remoteDatabase.updateDatabaseVersion(dbVersion) - val migrations = mapOf( - dbVersion to listOf { database: Database -> database.executeUpdate("CREATE TABLE Test(RowId VARCHAR(36))") } - ) + val migrations = + mapOf( + dbVersion to + listOf { database: Database -> + database.executeUpdate("CREATE TABLE Test(RowId VARCHAR(36))") + } + ) val migrator = DatabaseMigrator(migrations) val validator = makeValidator(migrator) @@ -94,5 +99,6 @@ class TestForeignDatabaseValidator: AbstractTest() } } - private fun makeValidator(databaseMigrator: DatabaseMigrator = DatabaseMigrator(emptyMap())) = ForeignDatabaseValidator(databaseMigrator) -} \ No newline at end of file + private fun makeValidator(databaseMigrator: DatabaseMigrator = DatabaseMigrator(emptyMap())) = + ForeignDatabaseValidator(databaseMigrator) +} diff --git a/src/test/kotlin/dartzee/db/TestGameEntity.kt b/src/test/kotlin/dartzee/db/TestGameEntity.kt index 84c6cdadc..0f9474f49 100644 --- a/src/test/kotlin/dartzee/db/TestGameEntity.kt +++ b/src/test/kotlin/dartzee/db/TestGameEntity.kt @@ -12,30 +12,26 @@ import dartzee.helper.usingInMemoryDatabase import dartzee.logging.CODE_SQL_EXCEPTION import dartzee.logging.exceptions.WrappedSqlException import dartzee.utils.InjectedThings.mainDatabase +import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldHaveSize -import io.kotest.matchers.string.shouldContain -import io.kotest.matchers.string.shouldNotBeEmpty import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import io.kotest.assertions.throwables.shouldThrow -import org.junit.jupiter.api.Test +import io.kotest.matchers.string.shouldContain +import io.kotest.matchers.string.shouldNotBeEmpty import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestGameEntity: AbstractEntityTest() -{ +class TestGameEntity : AbstractEntityTest() { override fun factoryDao() = GameEntity() @Test - fun `LocalId field should be unique`() - { + fun `LocalId field should be unique`() { insertGame(localId = 5) verifyNoLogs(CODE_SQL_EXCEPTION) - val ex = shouldThrow { - insertGame(localId = 5) - } + val ex = shouldThrow { insertGame(localId = 5) } val sqle = ex.sqlException sqle.message shouldContain "duplicate key" @@ -44,8 +40,7 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `LocalIds should be assigned along with RowId`() - { + fun `LocalIds should be assigned along with RowId`() { val entity = GameEntity() entity.assignRowId() @@ -54,8 +49,7 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `isFinished should work correctly`() - { + fun `isFinished should work correctly`() { val entity = GameEntity() entity.isFinished() shouldBe false @@ -64,8 +58,7 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `Should handle no participants when getting players vector`() - { + fun `Should handle no participants when getting players vector`() { val game = GameEntity() game.saveToDatabase() @@ -73,9 +66,8 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `Should return the player vector correctly`() - { - //Insert a random player + fun `Should return the player vector correctly`() { + // Insert a random player val game = GameEntity() val gameId = game.assignRowId() game.saveToDatabase() @@ -89,10 +81,8 @@ class TestGameEntity: AbstractEntityTest() players.first().name shouldBe "Clive" } - @Test - fun `Should get the description along with the params`() - { + fun `Should get the description along with the params`() { val game = GameEntity() game.gameParams = "foo" game.gameType = GameType.GOLF @@ -100,8 +90,7 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `Factory individual game`() - { + fun `Factory individual game`() { val game = GameEntity.factory(GameType.X01, "301") game.localId shouldNotBe -1 game.gameType shouldBe GameType.X01 @@ -115,8 +104,7 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `Factory and save individual game`() - { + fun `Factory and save individual game`() { val launchParams = GameLaunchParams(emptyList(), GameType.GOLF, "18", false) val game = GameEntity.factoryAndSave(launchParams) game.matchOrdinal shouldBe -1 @@ -130,8 +118,7 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `Factory and save for a match`() - { + fun `Factory and save for a match`() { val match = DartsMatchEntity.factoryFirstTo(4) val launchParams = GameLaunchParams(emptyList(), GameType.GOLF, "18", false) @@ -144,23 +131,31 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `Should retrieve games in the right order for a match`() - { + fun `Should retrieve games in the right order for a match`() { val matchId = randomGuid() val millis = System.currentTimeMillis() - val gameTwoId = insertGame(dartsMatchId = matchId, matchOrdinal = 1, dtCreation = Timestamp(millis)).rowId - val gameOneId = insertGame(dartsMatchId = matchId, matchOrdinal = 1, dtCreation = Timestamp(millis - 5)).rowId + val gameTwoId = + insertGame(dartsMatchId = matchId, matchOrdinal = 1, dtCreation = Timestamp(millis)) + .rowId + val gameOneId = + insertGame(dartsMatchId = matchId, matchOrdinal = 1, dtCreation = Timestamp(millis - 5)) + .rowId insertGame(dartsMatchId = randomGuid()) - val gameThreeId = insertGame(dartsMatchId = matchId, matchOrdinal = 2, dtCreation = Timestamp(millis - 10)).rowId - - val gameIds = GameEntity.retrieveGamesForMatch(matchId).map{it.rowId}.toList() + val gameThreeId = + insertGame( + dartsMatchId = matchId, + matchOrdinal = 2, + dtCreation = Timestamp(millis - 10) + ) + .rowId + + val gameIds = GameEntity.retrieveGamesForMatch(matchId).map { it.rowId }.toList() gameIds.shouldContainExactly(gameOneId, gameTwoId, gameThreeId) } @Test - fun `Should map localId to gameId`() - { + fun `Should map localId to gameId`() { val gameOne = insertGame(localId = 1) val gameTwo = insertGame(localId = 2) @@ -170,8 +165,7 @@ class TestGameEntity: AbstractEntityTest() } @Test - fun `Should reassign localId when merging into another database`() - { + fun `Should reassign localId when merging into another database`() { usingInMemoryDatabase(withSchema = true) { otherDatabase -> insertGame(database = otherDatabase) insertGame(database = otherDatabase) @@ -186,4 +180,4 @@ class TestGameEntity: AbstractEntityTest() retrieved.localId shouldBe 3 } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestLocalIdGenerator.kt b/src/test/kotlin/dartzee/db/TestLocalIdGenerator.kt index 0d822f1a1..e903d346d 100644 --- a/src/test/kotlin/dartzee/db/TestLocalIdGenerator.kt +++ b/src/test/kotlin/dartzee/db/TestLocalIdGenerator.kt @@ -9,25 +9,21 @@ import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestLocalIdGenerator: AbstractTest() -{ +class TestLocalIdGenerator : AbstractTest() { @Test - fun `It should generate an ID of 1 for an empty table`() - { + fun `It should generate an ID of 1 for an empty table`() { LocalIdGenerator(mainDatabase).generateLocalId(EntityName.Game) shouldBe 1 } @Test - fun `It should generate the next ID for a non-empty table`() - { + fun `It should generate the next ID for a non-empty table`() { insertGame(localId = 5) LocalIdGenerator(mainDatabase).generateLocalId(EntityName.Game) shouldBe 6 } @Test - fun `It should generate sequential IDs`() - { + fun `It should generate sequential IDs`() { val generator = LocalIdGenerator(mainDatabase) insertGame(localId = 25) @@ -41,8 +37,7 @@ class TestLocalIdGenerator: AbstractTest() } @Test - fun `It should keep track of different entities`() - { + fun `It should keep track of different entities`() { val generator = LocalIdGenerator(mainDatabase) insertGame(localId = 5) insertDartsMatch(localId = 25) @@ -54,41 +49,32 @@ class TestLocalIdGenerator: AbstractTest() } @Test - fun `It should be thread-safe`() - { + fun `It should be thread-safe`() { val generator = LocalIdGenerator(mainDatabase) generator.generateLocalId(EntityName.Game) val threads = mutableListOf() val runnables = mutableListOf() - repeat(10) - { + repeat(10) { val runnable = IdGeneratorRunnable(generator, mutableListOf()) runnables.add(runnable) threads.add(Thread(runnable)) } - threads.forEach{ - it.start() - } + threads.forEach { it.start() } - threads.forEach{ - it.join() - } + threads.forEach { it.join() } val allIds = mutableListOf() - runnables.forEach{ - allIds.addAll(it.list) - } + runnables.forEach { allIds.addAll(it.list) } allIds.shouldHaveSize(200) allIds.shouldBeUnique() } @Test - fun `Should clear the cache, generating correct local IDs afterwards`() - { + fun `Should clear the cache, generating correct local IDs afterwards`() { val generator = LocalIdGenerator(mainDatabase) generator.generateLocalId(EntityName.Game) shouldBe 1L @@ -99,15 +85,15 @@ class TestLocalIdGenerator: AbstractTest() generator.generateLocalId(EntityName.Game) shouldBe 4L } - private class IdGeneratorRunnable(val generator: LocalIdGenerator, val list: MutableList): Runnable - { - override fun run() - { - repeat(20) - { + private class IdGeneratorRunnable( + val generator: LocalIdGenerator, + val list: MutableList + ) : Runnable { + override fun run() { + repeat(20) { val id = generator.generateLocalId(EntityName.Game) list.add(id) } } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestParticipantEntity.kt b/src/test/kotlin/dartzee/db/TestParticipantEntity.kt index 37d111be1..a6d93500d 100644 --- a/src/test/kotlin/dartzee/db/TestParticipantEntity.kt +++ b/src/test/kotlin/dartzee/db/TestParticipantEntity.kt @@ -5,19 +5,17 @@ import dartzee.core.util.DateStatics import dartzee.helper.insertPlayer import dartzee.helper.randomGuid import dartzee.logging.CODE_SQL -import io.kotest.matchers.string.shouldContain +import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.string.shouldContain import org.junit.jupiter.api.Test -class TestParticipantEntity: AbstractEntityTest() -{ +class TestParticipantEntity : AbstractEntityTest() { override fun factoryDao() = ParticipantEntity() @Test - fun `Should cache the player on first query then use it from then on`() - { + fun `Should cache the player on first query then use it from then on`() { val playerId = insertPlayer(name = "Bob", strategy = "").rowId val pt = ParticipantEntity() @@ -36,10 +34,8 @@ class TestParticipantEntity: AbstractEntityTest() } @Test - fun `Should return correct values for an AI player`() - { - val aiId = insertPlayer(name = "Robot", - strategy = DartsAiModel.new().toJson()).rowId + fun `Should return correct values for an AI player`() { + val aiId = insertPlayer(name = "Robot", strategy = DartsAiModel.new().toJson()).rowId val pt = ParticipantEntity() pt.playerId = aiId @@ -50,8 +46,7 @@ class TestParticipantEntity: AbstractEntityTest() } @Test - fun `Should return correct values for a human player`() - { + fun `Should return correct values for a human player`() { val player = PlayerEntity() player.name = "Bob" player.strategy = "" @@ -61,14 +56,11 @@ class TestParticipantEntity: AbstractEntityTest() pt.isAi() shouldBe false pt.getPlayerName() shouldBe "Bob" - shouldThrow{ - pt.getModel() - } + shouldThrow { pt.getModel() } } @Test - fun `Factory and save`() - { + fun `Factory and save`() { val player = PlayerEntity() val playerId = player.assignRowId() player.name = "Stuart" @@ -89,4 +81,4 @@ class TestParticipantEntity: AbstractEntityTest() pt.retrieveForId(rowId) shouldNotBe null } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestPendingLogsEntity.kt b/src/test/kotlin/dartzee/db/TestPendingLogsEntity.kt index fdfc5b6a7..32d3de925 100644 --- a/src/test/kotlin/dartzee/db/TestPendingLogsEntity.kt +++ b/src/test/kotlin/dartzee/db/TestPendingLogsEntity.kt @@ -1,16 +1,14 @@ package dartzee.db -import io.kotest.matchers.string.shouldNotBeEmpty import io.kotest.matchers.shouldBe +import io.kotest.matchers.string.shouldNotBeEmpty import org.junit.jupiter.api.Test -class TestPendingLogsEntity: AbstractEntityTest() -{ +class TestPendingLogsEntity : AbstractEntityTest() { override fun factoryDao() = PendingLogsEntity() @Test - fun `Should factory with an assigned rowId and the specified JSON`() - { + fun `Should factory with an assigned rowId and the specified JSON`() { val logJson = "foo" val e = PendingLogsEntity.factory(logJson) diff --git a/src/test/kotlin/dartzee/db/TestPlayerEntity.kt b/src/test/kotlin/dartzee/db/TestPlayerEntity.kt index 2eefccafa..f262f464e 100644 --- a/src/test/kotlin/dartzee/db/TestPlayerEntity.kt +++ b/src/test/kotlin/dartzee/db/TestPlayerEntity.kt @@ -10,24 +10,21 @@ import dartzee.helper.makeDartsModel import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.Test import javax.swing.ImageIcon +import org.junit.jupiter.api.Test -class TestPlayerEntity: AbstractEntityTest() -{ +class TestPlayerEntity : AbstractEntityTest() { override fun factoryDao() = PlayerEntity() @Test - fun `Should have sensible string representation`() - { + fun `Should have sensible string representation`() { val player = PlayerEntity() player.name = "BTBF" "$player" shouldBe "BTBF" } @Test - fun `Should correctly identify human vs AI`() - { + fun `Should correctly identify human vs AI`() { val human = PlayerEntity() human.strategy = "" @@ -44,8 +41,7 @@ class TestPlayerEntity: AbstractEntityTest() } @Test - fun `Should correctly construct the AI model`() - { + fun `Should correctly construct the AI model`() { val model = makeDartsModel(scoringDart = 15) val player = PlayerEntity() @@ -57,8 +53,7 @@ class TestPlayerEntity: AbstractEntityTest() } @Test - fun `Should retrieve a player avatar`() - { + fun `Should retrieve a player avatar`() { val image = insertPlayerImage() val player = insertPlayer(playerImageId = image.rowId) @@ -69,8 +64,7 @@ class TestPlayerEntity: AbstractEntityTest() } @Test - fun `Should automatically exclude deleted players for custom queries`() - { + fun `Should automatically exclude deleted players for custom queries`() { insertPlayer(name = "Bob", dtDeleted = getSqlDateNow()) val p2 = insertPlayer(name = "Bob", dtDeleted = DateStatics.END_OF_TIME) val p3 = insertPlayer(name = "Clive", dtDeleted = DateStatics.END_OF_TIME) @@ -80,8 +74,7 @@ class TestPlayerEntity: AbstractEntityTest() } @Test - fun `Should automatically exclude deleted players when retrieving by name`() - { + fun `Should automatically exclude deleted players when retrieving by name`() { insertPlayer(name = "Bob", dtDeleted = getSqlDateNow()) val p2 = insertPlayer(name = "Bob", dtDeleted = DateStatics.END_OF_TIME) insertPlayer(name = "Clive", dtDeleted = getSqlDateNow()) @@ -90,4 +83,4 @@ class TestPlayerEntity: AbstractEntityTest() PlayerEntity.retrieveForName("Clive") shouldBe null PlayerEntity.retrieveForName("ZZZZ") shouldBe null } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestPlayerImageEntity.kt b/src/test/kotlin/dartzee/db/TestPlayerImageEntity.kt index 864f84c37..ac78c2900 100644 --- a/src/test/kotlin/dartzee/db/TestPlayerImageEntity.kt +++ b/src/test/kotlin/dartzee/db/TestPlayerImageEntity.kt @@ -1,11 +1,9 @@ package dartzee.db -class TestPlayerImageEntity: AbstractEntityTest() -{ +class TestPlayerImageEntity : AbstractEntityTest() { override fun factoryDao() = PlayerImageEntity() - override fun setExtraValuesForBulkInsert(e: PlayerImageEntity) - { + override fun setExtraValuesForBulkInsert(e: PlayerImageEntity) { e.blobData = getBlobValue("Dennis") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestSqlStatementType.kt b/src/test/kotlin/dartzee/db/TestSqlStatementType.kt index b581f98e6..35e91c719 100644 --- a/src/test/kotlin/dartzee/db/TestSqlStatementType.kt +++ b/src/test/kotlin/dartzee/db/TestSqlStatementType.kt @@ -4,14 +4,12 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSqlStatementType : AbstractTest() -{ +class TestSqlStatementType : AbstractTest() { @Test - fun `Should parse correct type from statement`() - { + fun `Should parse correct type from statement`() { SqlStatementType.fromStatement("SELECT * FROM Foo") shouldBe SqlStatementType.SELECT SqlStatementType.fromStatement("INSERT INTO Foo") shouldBe SqlStatementType.INSERT SqlStatementType.fromStatement("UPDATE Foo") shouldBe SqlStatementType.UPDATE SqlStatementType.fromStatement("DELETE FROM Foo") shouldBe SqlStatementType.DELETE } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestSyncAuditEntity.kt b/src/test/kotlin/dartzee/db/TestSyncAuditEntity.kt index e2e525ce2..b1136b18c 100644 --- a/src/test/kotlin/dartzee/db/TestSyncAuditEntity.kt +++ b/src/test/kotlin/dartzee/db/TestSyncAuditEntity.kt @@ -1,40 +1,37 @@ package dartzee.db -import dartzee.`object`.DartsClient import dartzee.core.util.CoreRegistry import dartzee.helper.REMOTE_NAME import dartzee.helper.makeSyncAudit +import dartzee.`object`.DartsClient import dartzee.sync.LastSyncData import dartzee.utils.DARTS_VERSION_NUMBER import dartzee.utils.InjectedThings.mainDatabase -import io.kotest.matchers.string.shouldNotBeEmpty import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Test +import io.kotest.matchers.string.shouldNotBeEmpty import java.sql.Timestamp import java.util.* +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test -class TestSyncAuditEntity: AbstractEntityTest() -{ - private val originalDeviceId = CoreRegistry.instance.get(CoreRegistry.INSTANCE_STRING_DEVICE_ID, "") +class TestSyncAuditEntity : AbstractEntityTest() { + private val originalDeviceId = + CoreRegistry.instance.get(CoreRegistry.INSTANCE_STRING_DEVICE_ID, "") @AfterEach - fun afterEach() - { + fun afterEach() { CoreRegistry.instance.put(CoreRegistry.INSTANCE_STRING_DEVICE_ID, originalDeviceId) } override fun factoryDao() = SyncAuditEntity() @Test - fun `Should report a null lastSyncDate if not recorded before`() - { + fun `Should report a null lastSyncDate if not recorded before`() { SyncAuditEntity.getLastSyncData(mainDatabase) shouldBe null } @Test - fun `Should insert a sync audit with the correct values`() - { + fun `Should insert a sync audit with the correct values`() { val deviceId = UUID.randomUUID().toString() DartsClient.operatingSystem = "Funky OS 2.1" CoreRegistry.instance.put(CoreRegistry.INSTANCE_STRING_DEVICE_ID, deviceId) @@ -52,11 +49,11 @@ class TestSyncAuditEntity: AbstractEntityTest() } @Test - fun `Should report the correct last sync date and remote name`() - { + fun `Should report the correct last sync date and remote name`() { makeSyncAudit(mainDatabase).saveToDatabase(Timestamp(50)) makeSyncAudit(mainDatabase).saveToDatabase(Timestamp(150)) - SyncAuditEntity.getLastSyncData(mainDatabase) shouldBe LastSyncData(REMOTE_NAME, Timestamp(150)) + SyncAuditEntity.getLastSyncData(mainDatabase) shouldBe + LastSyncData(REMOTE_NAME, Timestamp(150)) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestTeamEntity.kt b/src/test/kotlin/dartzee/db/TestTeamEntity.kt index 11f6389ba..b8a3625e8 100644 --- a/src/test/kotlin/dartzee/db/TestTeamEntity.kt +++ b/src/test/kotlin/dartzee/db/TestTeamEntity.kt @@ -6,13 +6,11 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.junit.jupiter.api.Test -class TestTeamEntity: AbstractEntityTest() -{ +class TestTeamEntity : AbstractEntityTest() { override fun factoryDao() = TeamEntity() @Test - fun `Factory and save`() - { + fun `Factory and save`() { val gameId = randomGuid() val tean = TeamEntity.factoryAndSave(gameId, 2) @@ -26,4 +24,4 @@ class TestTeamEntity: AbstractEntityTest() tean.retrieveForId(rowId) shouldNotBe null } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestVersionEntity.kt b/src/test/kotlin/dartzee/db/TestVersionEntity.kt index 9ea45d1be..9d96c3ccd 100644 --- a/src/test/kotlin/dartzee/db/TestVersionEntity.kt +++ b/src/test/kotlin/dartzee/db/TestVersionEntity.kt @@ -1,6 +1,5 @@ package dartzee.db -class TestVersionEntity: AbstractEntityTest() -{ +class TestVersionEntity : AbstractEntityTest() { override fun factoryDao() = VersionEntity() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/TestX01FinishEntity.kt b/src/test/kotlin/dartzee/db/TestX01FinishEntity.kt index bb21bf806..e8a9e311c 100644 --- a/src/test/kotlin/dartzee/db/TestX01FinishEntity.kt +++ b/src/test/kotlin/dartzee/db/TestX01FinishEntity.kt @@ -1,6 +1,5 @@ package dartzee.db -class TestX01FinishEntity: AbstractEntityTest() -{ +class TestX01FinishEntity : AbstractEntityTest() { override fun factoryDao() = X01FinishEntity() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/sanity/TestDatabaseSanityCheck.kt b/src/test/kotlin/dartzee/db/sanity/TestDatabaseSanityCheck.kt index 639ee34a3..1a1b0d807 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestDatabaseSanityCheck.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestDatabaseSanityCheck.kt @@ -25,11 +25,9 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestDatabaseSanityCheck : AbstractTest() -{ +class TestDatabaseSanityCheck : AbstractTest() { @Test - fun `Should produce no results on an empty database, and tidy up all temp tables`() - { + fun `Should produce no results on an empty database, and tidy up all temp tables`() { DatabaseSanityCheck.runSanityCheck() awaitSanityCheck() @@ -40,13 +38,16 @@ class TestDatabaseSanityCheck : AbstractTest() } @Test - fun `Should display failed checks with correct descriptions and counts`() - { + fun `Should display failed checks with correct descriptions and counts`() { val game = insertGame() val p1 = insertPlayer() val p2 = insertPlayer() - val checks = listOf(DummySanityCheckBadGames(listOf(game)), DummySanityCheckMultipleThings(listOf(p1, p2))) + val checks = + listOf( + DummySanityCheckBadGames(listOf(game)), + DummySanityCheckMultipleThings(listOf(p1, p2)) + ) DatabaseSanityCheck.runSanityCheck(checks) awaitSanityCheck() @@ -61,8 +62,7 @@ class TestDatabaseSanityCheck : AbstractTest() } @Test - fun `Should support auto-fixing`() - { + fun `Should support auto-fixing`() { val mockResult = mockk(relaxed = true) every { mockResult.getDescription() } returns "Foo" @@ -78,8 +78,7 @@ class TestDatabaseSanityCheck : AbstractTest() } @Test - fun `Should support viewing results breakdown`() - { + fun `Should support viewing results breakdown`() { val breakdownDialog = TableModelDialog("Mock breakdown", ScrollTable()) breakdownDialog.shouldNotBeVisible() @@ -98,31 +97,26 @@ class TestDatabaseSanityCheck : AbstractTest() breakdownDialog.shouldBeVisible() } - private fun findResultsWindow() = - findWindow { it.title == "Sanity Results" } + private fun findResultsWindow() = findWindow { it.title == "Sanity Results" } - private fun awaitSanityCheck() - { - waitForAssertion { - findLog(CODE_SANITY_CHECK_COMPLETED) shouldNotBe null - } + private fun awaitSanityCheck() { + waitForAssertion { findLog(CODE_SANITY_CHECK_COMPLETED) shouldNotBe null } flushEdt() } } -private class DummySanityCheckBadGames(private val games: List) : ISanityCheck -{ +private class DummySanityCheckBadGames(private val games: List) : ISanityCheck { override fun runCheck(): List = listOf(SanityCheckResultEntitiesSimple(games, "Games where something's wrong")) } -private class DummySanityCheckMultipleThings(private val players: List): ISanityCheck -{ +private class DummySanityCheckMultipleThings(private val players: List) : + ISanityCheck { override fun runCheck(): List { return listOf( SanityCheckResultEntitiesSimple(players, "Players with thing one wrong"), SanityCheckResultEntitiesSimple(players, "Players with thing two wrong") ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckDanglingIdFields.kt b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckDanglingIdFields.kt index ec1f526e5..64ce48b6f 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckDanglingIdFields.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckDanglingIdFields.kt @@ -2,8 +2,8 @@ package dartzee.db.sanity import dartzee.db.DartzeeRuleEntity import dartzee.db.DeletionAuditEntity -import dartzee.db.GameEntity import dartzee.db.EntityName +import dartzee.db.GameEntity import dartzee.game.GameType import dartzee.helper.AbstractTest import dartzee.helper.insertDartsMatch @@ -14,11 +14,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSanityCheckDanglingIdFields: AbstractTest() -{ +class TestSanityCheckDanglingIdFields : AbstractTest() { @Test - fun `Should flag up ID fields that point at non-existent rows`() - { + fun `Should flag up ID fields that point at non-existent rows`() { val gameId = insertGame(dartsMatchId = "foo").rowId val results = SanityCheckDanglingIdFields(GameEntity()).runCheck() @@ -26,12 +24,12 @@ class TestSanityCheckDanglingIdFields: AbstractTest() val result = results.first() as SanityCheckResultDanglingIdFields result.entities.first().rowId shouldBe gameId - result.getDescription() shouldBe "Game rows where the DartsMatchId points at a non-existent DartsMatch" + result.getDescription() shouldBe + "Game rows where the DartsMatchId points at a non-existent DartsMatch" } @Test - fun `Should not flag up an ID field that points at a row that exists`() - { + fun `Should not flag up an ID field that points at a row that exists`() { val matchId = insertDartsMatch().rowId insertGame(dartsMatchId = matchId) @@ -40,8 +38,7 @@ class TestSanityCheckDanglingIdFields: AbstractTest() } @Test - fun `Should not flag up an ID field which is empty`() - { + fun `Should not flag up an ID field which is empty`() { insertGame(dartsMatchId = "") val results = SanityCheckDanglingIdFields(GameEntity()).runCheck() @@ -49,8 +46,7 @@ class TestSanityCheckDanglingIdFields: AbstractTest() } @Test - fun `Should flag up generic EntityId+EntityName pairs`() - { + fun `Should flag up generic EntityId+EntityName pairs`() { insertDartzeeRule(entityName = EntityName.Game, entityId = "Foo") insertDartzeeRule(entityName = EntityName.Game, entityId = "Bar") insertDartzeeRule(entityName = EntityName.Player, entityId = "Baz") @@ -58,17 +54,20 @@ class TestSanityCheckDanglingIdFields: AbstractTest() val results = SanityCheckDanglingIdFields(DartzeeRuleEntity()).runCheck() results.size shouldBe 2 - results.map { it.getDescription() }.shouldContainExactlyInAnyOrder("DartzeeRule rows where the EntityId points at a non-existent Game", - "DartzeeRule rows where the EntityId points at a non-existent Player") + results + .map { it.getDescription() } + .shouldContainExactlyInAnyOrder( + "DartzeeRule rows where the EntityId points at a non-existent Game", + "DartzeeRule rows where the EntityId points at a non-existent Player" + ) } @Test - fun `Should ignore DeletionAudit table`() - { + fun `Should ignore DeletionAudit table`() { val entity = GameEntity.factory(GameType.X01, "501") DeletionAuditEntity.factoryAndSave(entity) val results = SanityCheckDanglingIdFields(DeletionAuditEntity()).runCheck() results.shouldBeEmpty() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckFinalScoreGolf.kt b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckFinalScoreGolf.kt index 0e43a4681..138fe0ab5 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckFinalScoreGolf.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckFinalScoreGolf.kt @@ -13,25 +13,40 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.Test -class TestSanityCheckFinalScoreGolf: AbstractTest() -{ +class TestSanityCheckFinalScoreGolf : AbstractTest() { @Test - fun `Should take the score from the latest dart thrown`() - { + fun `Should take the score from the latest dart thrown`() { val pt = setUpParticipant(4) - //Round one - 4 - insertDart(pt, roundNumber = 1, ordinal = 1, score = 1, segmentType = SegmentType.OUTER_SINGLE) - insertDart(pt, roundNumber = 1, ordinal = 2, score = 1, segmentType = SegmentType.INNER_SINGLE) - insertDart(pt, roundNumber = 1, ordinal = 3, score = 1, segmentType = SegmentType.OUTER_SINGLE) + // Round one - 4 + insertDart( + pt, + roundNumber = 1, + ordinal = 1, + score = 1, + segmentType = SegmentType.OUTER_SINGLE + ) + insertDart( + pt, + roundNumber = 1, + ordinal = 2, + score = 1, + segmentType = SegmentType.INNER_SINGLE + ) + insertDart( + pt, + roundNumber = 1, + ordinal = 3, + score = 1, + segmentType = SegmentType.OUTER_SINGLE + ) val results = SanityCheckFinalScoreGolf().runCheck() results.shouldBeEmpty() } @Test - fun `Should score 5 if score does not match round number`() - { + fun `Should score 5 if score does not match round number`() { val pt = setUpParticipant(5) insertDart(pt, roundNumber = 1, ordinal = 1, score = 2, segmentType = SegmentType.DOUBLE) @@ -40,21 +55,31 @@ class TestSanityCheckFinalScoreGolf: AbstractTest() } @Test - fun `Should sum the score across rounds for the same participant`() - { + fun `Should sum the score across rounds for the same participant`() { val pt = setUpParticipant(7) - //Round one - insertDart(pt, roundNumber = 1, ordinal = 1, score = 1, segmentType = SegmentType.OUTER_SINGLE) - insertDart(pt, roundNumber = 2, ordinal = 1, score = 2, segmentType = SegmentType.INNER_SINGLE) + // Round one + insertDart( + pt, + roundNumber = 1, + ordinal = 1, + score = 1, + segmentType = SegmentType.OUTER_SINGLE + ) + insertDart( + pt, + roundNumber = 2, + ordinal = 1, + score = 2, + segmentType = SegmentType.INNER_SINGLE + ) val results = SanityCheckFinalScoreGolf().runCheck() results.shouldBeEmpty() } @Test - fun `Should get the right score based on segment type`() - { + fun `Should get the right score based on segment type`() { checkScoreCorrectForSegmentType(SegmentType.MISS, 5) checkScoreCorrectForSegmentType(SegmentType.OUTER_SINGLE, 4) checkScoreCorrectForSegmentType(SegmentType.INNER_SINGLE, 3) @@ -63,11 +88,16 @@ class TestSanityCheckFinalScoreGolf: AbstractTest() } @Test - fun `Should flag up if the score is incorrect`() - { + fun `Should flag up if the score is incorrect`() { val pt = setUpParticipant(5) - insertDart(pt, roundNumber = 1, ordinal = 1, score = 1, segmentType = SegmentType.OUTER_SINGLE) + insertDart( + pt, + roundNumber = 1, + ordinal = 1, + score = 1, + segmentType = SegmentType.OUTER_SINGLE + ) val results = SanityCheckFinalScoreGolf().runCheck() results.size shouldBe 1 @@ -78,8 +108,7 @@ class TestSanityCheckFinalScoreGolf: AbstractTest() result.getCount() shouldBe 1 } - private fun checkScoreCorrectForSegmentType(segmentType: SegmentType, expectedScore: Int) - { + private fun checkScoreCorrectForSegmentType(segmentType: SegmentType, expectedScore: Int) { val pt = setUpParticipant(expectedScore) insertDart(pt, roundNumber = 1, ordinal = 1, score = 1, segmentType = segmentType) @@ -88,10 +117,13 @@ class TestSanityCheckFinalScoreGolf: AbstractTest() results.shouldBeEmpty() } - private fun setUpParticipant(finalScore: Int): ParticipantEntity - { + private fun setUpParticipant(finalScore: Int): ParticipantEntity { val game = insertGame(gameType = GameType.GOLF) val player = insertPlayer() - return insertParticipant(gameId = game.rowId, playerId = player.rowId, finalScore = finalScore) + return insertParticipant( + gameId = game.rowId, + playerId = player.rowId, + finalScore = finalScore + ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckPlayerIdMismatch.kt b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckPlayerIdMismatch.kt index 413d7fa02..81c17793b 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckPlayerIdMismatch.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckPlayerIdMismatch.kt @@ -8,11 +8,9 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSanityCheckPlayerIdMismatch: AbstractTest() -{ +class TestSanityCheckPlayerIdMismatch : AbstractTest() { @Test - fun `Should not flag up matching rows`() - { + fun `Should not flag up matching rows`() { val pt = insertParticipant() insertDart(pt) @@ -21,8 +19,7 @@ class TestSanityCheckPlayerIdMismatch: AbstractTest() } @Test - fun `Should flag up mismatching rows`() - { + fun `Should flag up mismatching rows`() { val pt = insertParticipant() val ptPlayerId = pt.playerId @@ -39,4 +36,4 @@ class TestSanityCheckPlayerIdMismatch: AbstractTest() tm.getValueAt(0, 2) shouldBe newPlayerId tm.getValueAt(0, 3) shouldBe ptPlayerId } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckSanityCheckColumnsThatAllowDefaults.kt b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckSanityCheckColumnsThatAllowDefaults.kt index 891247725..4585f64bc 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckSanityCheckColumnsThatAllowDefaults.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckSanityCheckColumnsThatAllowDefaults.kt @@ -6,11 +6,9 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSanityCheckSanityCheckColumnsThatAllowDefaults: AbstractTest() -{ +class TestSanityCheckSanityCheckColumnsThatAllowDefaults : AbstractTest() { @Test - fun `Should return no results by default`() - { + fun `Should return no results by default`() { val check = SanityCheckColumnsThatAllowDefaults() val results = check.runCheck() @@ -18,8 +16,7 @@ class TestSanityCheckSanityCheckColumnsThatAllowDefaults: AbstractTest() } @Test - fun `Should pick up on tables that allow defaults`() - { + fun `Should pick up on tables that allow defaults`() { val sql = "CREATE TABLE BadTable(Id INT PRIMARY KEY, OtherField VARCHAR(50) DEFAULT 'foo')" mainDatabase.executeUpdate(sql) diff --git a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckUnsetIdFields.kt b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckUnsetIdFields.kt index cae940ce3..ecf508453 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckUnsetIdFields.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckUnsetIdFields.kt @@ -9,11 +9,9 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import org.junit.jupiter.api.Test -class TestSanityCheckUnsetIdFields: AbstractTest() -{ +class TestSanityCheckUnsetIdFields : AbstractTest() { @Test - fun `Should not flag up ID fields which are allowed to be unset`() - { + fun `Should not flag up ID fields which are allowed to be unset`() { insertGame(dartsMatchId = "") val results = SanityCheckUnsetIdFields(GameEntity()).runCheck() @@ -21,12 +19,15 @@ class TestSanityCheckUnsetIdFields: AbstractTest() } @Test - fun `Should flag up unset ID fields`() - { + fun `Should flag up unset ID fields`() { insertParticipant(gameId = "", playerId = "") val results = SanityCheckUnsetIdFields(ParticipantEntity()).runCheck() - results.map { it.getDescription() }.shouldContainExactlyInAnyOrder("Participant rows where GameId is unset", - "Participant rows where PlayerId is unset") + results + .map { it.getDescription() } + .shouldContainExactlyInAnyOrder( + "Participant rows where GameId is unset", + "Participant rows where PlayerId is unset" + ) } } diff --git a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckX01Finishes.kt b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckX01Finishes.kt index b418666c4..b8a46e0f6 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestSanityCheckX01Finishes.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestSanityCheckX01Finishes.kt @@ -14,21 +14,18 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe +import java.util.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import java.util.* -class TestSanityCheckX01Finishes: AbstractTest() -{ +class TestSanityCheckX01Finishes : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { mainDatabase.dropUnexpectedTables() } @Test - fun `Should return an empty list if the finishes line up`() - { + fun `Should return an empty list if the finishes line up`() { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) val pt = insertParticipant(gameId = g.rowId, playerId = p.rowId) @@ -43,8 +40,7 @@ class TestSanityCheckX01Finishes: AbstractTest() } @Test - fun `Should return results if mismatching playerIds`() - { + fun `Should return results if mismatching playerIds`() { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) val pt = insertParticipant(gameId = g.rowId, playerId = UUID.randomUUID().toString()) @@ -59,11 +55,14 @@ class TestSanityCheckX01Finishes: AbstractTest() } @Test - fun `Should return results if mismatching gameIds`() - { + fun `Should return results if mismatching gameIds`() { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) - val pt = insertParticipant(gameId = insertGame(gameType = GameType.X01).rowId, playerId = p.rowId) + val pt = + insertParticipant( + gameId = insertGame(gameType = GameType.X01).rowId, + playerId = p.rowId + ) insertFinishForPlayer(p, 60, game = g) @@ -75,8 +74,7 @@ class TestSanityCheckX01Finishes: AbstractTest() } @Test - fun `Should return results if mismatching finish value`() - { + fun `Should return results if mismatching finish value`() { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) val pt = insertParticipant(gameId = g.rowId, playerId = p.rowId) @@ -91,8 +89,7 @@ class TestSanityCheckX01Finishes: AbstractTest() } @Test - fun `Should report extra rows in X01Finish`() - { + fun `Should report extra rows in X01Finish`() { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) @@ -105,8 +102,7 @@ class TestSanityCheckX01Finishes: AbstractTest() } @Test - fun `Should report missing rows in X01Finish`() - { + fun `Should report missing rows in X01Finish`() { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) val pt = insertParticipant(gameId = g.rowId, playerId = p.rowId) @@ -121,8 +117,7 @@ class TestSanityCheckX01Finishes: AbstractTest() } @Test - fun `Should report discrepancy as missing and extra`() - { + fun `Should report discrepancy as missing and extra`() { val p = insertPlayer() val g = insertGame(gameType = GameType.X01) val pt = insertParticipant(gameId = g.rowId, playerId = p.rowId) @@ -136,9 +131,10 @@ class TestSanityCheckX01Finishes: AbstractTest() val rows = result.getResultsModel().getRows() rows.shouldContainExactlyInAnyOrder( listOf("MISSING", p.rowId, g.rowId, 55), - listOf("EXTRA", p.rowId, g.rowId, 60)) + listOf("EXTRA", p.rowId, g.rowId, 60) + ) } - private fun assertPositiveResult(): SanityCheckResultSimpleTableModel - = SanityCheckX01Finishes().runCheck().first() as SanityCheckResultSimpleTableModel -} \ No newline at end of file + private fun assertPositiveResult(): SanityCheckResultSimpleTableModel = + SanityCheckX01Finishes().runCheck().first() as SanityCheckResultSimpleTableModel +} diff --git a/src/test/kotlin/dartzee/db/sanity/TestSanityUtils.kt b/src/test/kotlin/dartzee/db/sanity/TestSanityUtils.kt index be0cc631a..f363d86aa 100644 --- a/src/test/kotlin/dartzee/db/sanity/TestSanityUtils.kt +++ b/src/test/kotlin/dartzee/db/sanity/TestSanityUtils.kt @@ -5,11 +5,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.collections.shouldContainExactly import org.junit.jupiter.api.Test -class TestSanityUtils: AbstractTest() -{ +class TestSanityUtils : AbstractTest() { @Test - fun `Should only return the correct columns`() - { + fun `Should only return the correct columns`() { getIdColumns(GameEntity()).shouldContainExactly("DartsMatchId") } } diff --git a/src/test/kotlin/dartzee/e2e/DeterministicPlayer.kt b/src/test/kotlin/dartzee/e2e/DeterministicPlayer.kt index e8d3c3877..2334b5e7f 100644 --- a/src/test/kotlin/dartzee/e2e/DeterministicPlayer.kt +++ b/src/test/kotlin/dartzee/e2e/DeterministicPlayer.kt @@ -3,13 +3,11 @@ package dartzee.e2e import dartzee.ai.DartsAiModel import dartzee.db.PlayerEntity -class DeterministicPlayer(private val model: DartsAiModel) : PlayerEntity() -{ +class DeterministicPlayer(private val model: DartsAiModel) : PlayerEntity() { override fun getModel() = model } -fun PlayerEntity.toDeterministicPlayer(model: DartsAiModel): DeterministicPlayer -{ +fun PlayerEntity.toDeterministicPlayer(model: DartsAiModel): DeterministicPlayer { val p = DeterministicPlayer(model) p.rowId = rowId p.playerImageId = playerImageId @@ -17,4 +15,4 @@ fun PlayerEntity.toDeterministicPlayer(model: DartsAiModel): DeterministicPlayer p.strategy = "stubbed" p.dtDeleted = dtDeleted return p -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/GameHelpers.kt b/src/test/kotlin/dartzee/e2e/GameHelpers.kt index 4e938e61f..1b1c68eec 100644 --- a/src/test/kotlin/dartzee/e2e/GameHelpers.kt +++ b/src/test/kotlin/dartzee/e2e/GameHelpers.kt @@ -40,18 +40,15 @@ import io.mockk.verifySequence import javax.swing.JButton import javax.swing.JToggleButton -fun AbstractDartsScorerPausable<*>.shouldBePaused() -{ +fun AbstractDartsScorerPausable<*>.shouldBePaused() { getChild { it.icon == ICON_RESUME } } -fun AbstractDartsScorerPausable<*>.resume() -{ +fun AbstractDartsScorerPausable<*>.resume() { clickChild { it.icon == ICON_RESUME } } -fun AbstractDartsGameScreen.toggleStats() -{ +fun AbstractDartsGameScreen.toggleStats() { clickChild { it.icon == dartzee.utils.ResourceCache.ICON_STATS_LARGE } } @@ -59,8 +56,8 @@ fun AbstractDartsGameScreen.getScorer(playerName: String) = getChild { it.playerName.contains(playerName) } data class TwoPlayers(val winner: PlayerEntity, val loser: PlayerEntity) -fun createPlayers(): TwoPlayers -{ + +fun createPlayers(): TwoPlayers { val aiModel = beastDartsModel(hmScoreToDart = mapOf(81 to AimDart(19, 3))) val winner = insertPlayer(model = aiModel, name = "Winner") @@ -70,20 +67,16 @@ fun createPlayers(): TwoPlayers return TwoPlayers(winner, loser) } -fun closeOpenGames() -{ +fun closeOpenGames() { ScreenCache.getDartsGameScreens().forEach { it.dispose() } } data class GamePanelTestSetup(val gamePanel: DartsGamePanel<*, *>, val listener: DartboardListener) fun setUpGamePanelAndStartGame(game: GameEntity, players: List) = - setUpGamePanel(game).also { - it.gamePanel.startGame(players) - } + setUpGamePanel(game).also { it.gamePanel.startGame(players) } -fun setUpGamePanel(game: GameEntity): GamePanelTestSetup -{ +fun setUpGamePanel(game: GameEntity): GamePanelTestSetup { val parentWindow = DartsGameScreen(game, 1) parentWindow.isVisible = true val gamePanel = parentWindow.gamePanel @@ -94,37 +87,38 @@ fun setUpGamePanel(game: GameEntity): GamePanelTestSetup return GamePanelTestSetup(gamePanel, listener) } -fun DartsGamePanel<*, *>.startGame(players: List) -{ +fun DartsGamePanel<*, *>.startGame(players: List) { val participants = prepareParticipants(gameEntity.rowId, players, false) startNewGame(participants) } -fun awaitGameFinish(game: GameEntity) -{ +fun awaitGameFinish(game: GameEntity) { waitForAssertion(timeout = 30000) { game.isFinished() shouldBe true } // Flush the EDT to ensure UI actions fired off from the AI threads are all completed flushEdt() } -fun makePlayerWithModel(model: DartsAiModel, name: String = "Clive", image: String = "BaboOne"): PlayerEntity -{ +fun makePlayerWithModel( + model: DartsAiModel, + name: String = "Clive", + image: String = "BaboOne" +): PlayerEntity { val playerImage = insertPlayerImage(resource = image) val player = insertPlayer(playerImageId = playerImage.rowId, name = name) return player.toDeterministicPlayer(model) } -fun verifyState(panel: DartsGamePanel<*, *>, - listener: DartboardListener, - dartRounds: List>, - finalScore: Int, - scoreSuffix: String = "", - expectedScorerRows: Int = dartRounds.size, - pt: IParticipant = retrieveParticipant() -) -{ +fun verifyState( + panel: DartsGamePanel<*, *>, + listener: DartboardListener, + dartRounds: List>, + finalScore: Int, + scoreSuffix: String = "", + expectedScorerRows: Int = dartRounds.size, + pt: IParticipant = retrieveParticipant() +) { // ParticipantEntity on the database pt.finalScore shouldBe finalScore pt.dtFinished shouldNotBe DateStatics.END_OF_TIME @@ -138,25 +132,26 @@ fun verifyState(panel: DartsGamePanel<*, *>, // Use our dartboardListener to verify that the right throws were registered val darts = dartRounds.flatten() - verifySequence { - darts.forEach { - listener.dartThrown(it) - } - } + verifySequence { darts.forEach { listener.dartThrown(it) } } // Check that the dart entities on the database line up - val dartEntities = DartEntity().retrieveEntities().sortedWith(compareBy( { it.roundNumber }, { it.ordinal })) - val chunkedDartEntities: List> = dartEntities.groupBy { it.roundNumber }.getSortedValues().map { it.sortedBy { drt -> drt.ordinal } } - val retrievedDartRounds = chunkedDartEntities.map { rnd -> rnd.map { drt -> Dart(drt.score, drt.multiplier) } } + val dartEntities = + DartEntity().retrieveEntities().sortedWith(compareBy({ it.roundNumber }, { it.ordinal })) + val chunkedDartEntities: List> = + dartEntities + .groupBy { it.roundNumber } + .getSortedValues() + .map { it.sortedBy { drt -> drt.ordinal } } + val retrievedDartRounds = + chunkedDartEntities.map { rnd -> rnd.map { drt -> Dart(drt.score, drt.multiplier) } } retrievedDartRounds shouldBe dartRounds } -fun checkAchievementConversions(playerId: String) -{ +fun checkAchievementConversions(playerId: String) { checkAchievementConversions(listOf(playerId)) } -fun checkAchievementConversions(playerIds: List) -{ + +fun checkAchievementConversions(playerIds: List) { val transactionalStates = playerIds.associateWith(::retrieveAchievementsForPlayer) wipeTable(EntityName.Achievement) @@ -167,4 +162,4 @@ fun checkAchievementConversions(playerIds: List) val retrieved = retrieveAchievementsForPlayer(playerId) retrieved.shouldContainExactlyInAnyOrder(transactionalState) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/SimulationE2E.kt b/src/test/kotlin/dartzee/e2e/SimulationE2E.kt index ee19c6e7f..b79979e47 100644 --- a/src/test/kotlin/dartzee/e2e/SimulationE2E.kt +++ b/src/test/kotlin/dartzee/e2e/SimulationE2E.kt @@ -26,18 +26,15 @@ import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class SimulationE2E: AbstractTest() -{ +class SimulationE2E : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { InjectedThings.simulationRunner = SimulationRunner() } @Test @Tag("e2e") - fun `Should be able to run a simulation of 500 games`() - { + fun `Should be able to run a simulation of 500 games`() { val model = beastDartsModel(hmScoreToDart = mapOf(81 to AimDart(19, 3))) val player = insertPlayer(model = model) @@ -68,7 +65,8 @@ class SimulationE2E: AbstractTest() tableDoubles.getRows().shouldContainExactly(listOf(listOf(12, 500, 100.0))) val topFinishesPanel = statsScrn.getChild() - val tableTopFinishes = topFinishesPanel.getChild { it.testId == "TopFinishesMine" } + val tableTopFinishes = + topFinishesPanel.getChild { it.testId == "TopFinishesMine" } val rows = tableTopFinishes.getRows() rows.first().shouldContainExactly(141, "T20, T19, D12", -1L) @@ -76,8 +74,9 @@ class SimulationE2E: AbstractTest() val tableScores = threeDartScoresPanel.getChild { it.testId == "PlayerScores" } tableScores.rowCount shouldBe 1 tableScores.getRows().first().shouldContainExactly(180, 1000) - val tableBreakdown = threeDartScoresPanel.getChild { it.testId == "PlayerBreakdown" } + val tableBreakdown = + threeDartScoresPanel.getChild { it.testId == "PlayerBreakdown" } tableBreakdown.rowCount shouldBe 1 tableBreakdown.getRows().first().shouldContainExactly("T20, T20, T20", 1000, -1L) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/SimulationHelpers.kt b/src/test/kotlin/dartzee/e2e/SimulationHelpers.kt index fff02283a..2fc175933 100644 --- a/src/test/kotlin/dartzee/e2e/SimulationHelpers.kt +++ b/src/test/kotlin/dartzee/e2e/SimulationHelpers.kt @@ -12,8 +12,7 @@ import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.shouldNotBe import java.awt.Window -fun AbstractTest.awaitStatisticsScreen(): PlayerStatisticsScreen -{ +fun AbstractTest.awaitStatisticsScreen(): PlayerStatisticsScreen { waitForAssertion { getLogRecordsSoFar().map { it.loggingCode }.shouldContain(CODE_SIMULATION_FINISHED) findWindow { it.findChild() != null } shouldNotBe null @@ -21,4 +20,4 @@ fun AbstractTest.awaitStatisticsScreen(): PlayerStatisticsScreen flushEdt() return findWindow { it.findChild() != null }!!.getChild() -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/SyncE2E.kt b/src/test/kotlin/dartzee/e2e/SyncE2E.kt index 4ad51bc09..430e8ac89 100644 --- a/src/test/kotlin/dartzee/e2e/SyncE2E.kt +++ b/src/test/kotlin/dartzee/e2e/SyncE2E.kt @@ -38,22 +38,21 @@ import dartzee.utils.PREFERENCES_INT_AI_SPEED import dartzee.utils.PreferenceUtil import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Tag -import org.junit.jupiter.api.Test import java.io.File import java.util.* import javax.swing.JButton import javax.swing.JOptionPane +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Tag +import org.junit.jupiter.api.Test -class SyncE2E: AbstractRegistryTest() -{ - override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED, PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) +class SyncE2E : AbstractRegistryTest() { + override fun getPreferencesAffected() = + listOf(PREFERENCES_INT_AI_SPEED, PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) @BeforeEach - fun before() - { + fun before() { InjectedThings.databaseDirectory = TEST_DB_DIRECTORY InjectedThings.mainDatabase = Database(dbName = UUID.randomUUID().toString()) DartsDatabaseUtil.initialiseDatabase(InjectedThings.mainDatabase) @@ -69,16 +68,14 @@ class SyncE2E: AbstractRegistryTest() } @AfterEach - fun after() - { + fun after() { InjectedThings.mainDatabase = Database(inMemory = true) File(TEST_ROOT).deleteRecursively() } @Tag("e2e") @Test - fun `Syncing two games with same local ID`() - { + fun `Syncing two games with same local ID`() { val (winner, loser) = createPlayers() val gameId = runGame(winner, loser) @@ -99,16 +96,20 @@ class SyncE2E: AbstractRegistryTest() GameEntity().retrieveForId(secondGameId)!!.localId shouldBe 2 retrieveParticipant(gameId, loser.rowId).finalScore shouldBe losingPtScore - dialogFactory.infosShown.last() shouldBe "Sync completed successfully!\n\nGames pushed: 1\nGames pulled: 1" + dialogFactory.infosShown.last() shouldBe + "Sync completed successfully!\n\nGames pushed: 1\nGames pulled: 1" - val x01Wins = AchievementEntity().retrieveEntities("PlayerId = '${winner.rowId}' AND AchievementType = '${AchievementType.X01_GAMES_WON}'") + val x01Wins = + AchievementEntity() + .retrieveEntities( + "PlayerId = '${winner.rowId}' AND AchievementType = '${AchievementType.X01_GAMES_WON}'" + ) x01Wins.size shouldBe 2 } @Tag("e2e") @Test - fun `Syncing deleted data`() - { + fun `Syncing deleted data`() { val (winner, loser) = createPlayers() runGame(winner, loser) @@ -126,15 +127,17 @@ class SyncE2E: AbstractRegistryTest() waitForAssertion { SyncProgressDialog.isVisible() shouldBe true } waitForAssertion { SyncProgressDialog.isVisible() shouldBe false } - waitForAssertion { dialogFactory.infosShown.lastOrNull() shouldBe "Sync completed successfully!\n\nGames pushed: 0\nGames pulled: 0" } + waitForAssertion { + dialogFactory.infosShown.lastOrNull() shouldBe + "Sync completed successfully!\n\nGames pushed: 0\nGames pulled: 0" + } getCountFromTable(EntityName.Game) shouldBe 0 getCountFromTable(EntityName.Dart) shouldBe 0 getCountFromTable(EntityName.Participant) shouldBe 0 getCountFromTable(EntityName.X01Finish) shouldBe 0 } - private fun deleteGame(mainScreen: DartsApp) - { + private fun deleteGame(mainScreen: DartsApp) { ScreenCache.switch() dialogFactory.inputSelection = 1L dialogFactory.questionOption = JOptionPane.YES_OPTION @@ -142,19 +145,19 @@ class SyncE2E: AbstractRegistryTest() confirmGameDeletion(1) } - private fun runGame(winner: PlayerEntity, loser: PlayerEntity): String - { + private fun runGame(winner: PlayerEntity, loser: PlayerEntity): String { val params = GameLaunchParams(listOf(winner, loser), GameType.X01, "501", false) GameLauncher().launchNewGame(params) val gameId = retrieveGame().rowId - waitForAssertion(15000) { retrieveParticipant(gameId, loser.rowId).isActive() shouldBe false } + waitForAssertion(15000) { + retrieveParticipant(gameId, loser.rowId).isActive() shouldBe false + } closeOpenGames() return gameId } - private fun performPush(mainScreen: DartsApp): String - { + private fun performPush(mainScreen: DartsApp): String { val remoteName = UUID.randomUUID().toString() dialogFactory.inputSelection = remoteName dialogFactory.optionSequence.add("Create '$remoteName'") @@ -165,15 +168,13 @@ class SyncE2E: AbstractRegistryTest() return remoteName } - private fun performSync(mainScreen: DartsApp) - { + private fun performSync(mainScreen: DartsApp) { dialogFactory.optionSequence.add("Sync with local data") mainScreen.clickChild(text = "Get Started > ") waitForAssertion { mainScreen.findChild() shouldNotBe null } } - private fun wipeGamesAndResetRemote(mainScreen: DartsApp) - { + private fun wipeGamesAndResetRemote(mainScreen: DartsApp) { purgeGameAndConfirm(1) wipeTable(EntityName.DeletionAudit) wipeTable(EntityName.Achievement) @@ -182,4 +183,4 @@ class SyncE2E: AbstractRegistryTest() mainScreen.clickChild(text = "Reset") waitForAssertion { mainScreen.findChild() shouldNotBe null } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/TestDartzeeE2E.kt b/src/test/kotlin/dartzee/e2e/TestDartzeeE2E.kt index 0c97d1d9d..f0b28e9fb 100644 --- a/src/test/kotlin/dartzee/e2e/TestDartzeeE2E.kt +++ b/src/test/kotlin/dartzee/e2e/TestDartzeeE2E.kt @@ -34,20 +34,17 @@ import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestDartzeeE2E: AbstractRegistryTest() -{ +class TestDartzeeE2E : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, 100) } @Test @Tag("e2e") - fun `E2E - Dartzee`() - { + fun `E2E - Dartzee`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val game = insertGame(gameType = GameType.DARTZEE) @@ -61,11 +58,12 @@ class TestDartzeeE2E: AbstractRegistryTest() val (panel, listener) = setUpGamePanelAndStartGame(game, listOf(player)) awaitGameFinish(game) - val expectedRounds = listOf( - listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), //Scoring round - listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)), //All Twenties - listOf(Dart(18, 1), Dart(18, 1), Dart(25, 2)) //Score Eighteens - ) + val expectedRounds = + listOf( + listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), // Scoring round + listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)), // All Twenties + listOf(Dart(18, 1), Dart(18, 1), Dart(25, 2)) // Score Eighteens + ) verifyState(panel, listener, expectedRounds, finalScore = 276) @@ -89,8 +87,7 @@ class TestDartzeeE2E: AbstractRegistryTest() @Test @Tag("e2e") - fun `E2E - Dartzee - 2 player team`() - { + fun `E2E - Dartzee - 2 player team`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val game = insertGame(gameType = GameType.DARTZEE) @@ -98,26 +95,38 @@ class TestDartzeeE2E: AbstractRegistryTest() val (gamePanel, listener) = setUpGamePanel(game) - val p1Rounds = listOf( - listOf(makeDart(20, 1), makeDart(5, 1), makeDart(1, 1)), // Scoring round - 26 - listOf(makeDart(18, 1), makeDart(19, 1), makeDart(18, 1)), // Score 18s & 2B1W, picks 2B1W - 107 - listOf(makeDart(20, 1), makeDart(18, 1), makeDart(12, 1)), // Total is 50 - 175 - ) - - val p2Rounds = listOf( + val p1Rounds = + listOf( + listOf(makeDart(20, 1), makeDart(5, 1), makeDart(1, 1)), // Scoring round - 26 + listOf( + makeDart(18, 1), + makeDart(19, 1), + makeDart(18, 1) + ), // Score 18s & 2B1W, picks 2B1W - 107 + listOf(makeDart(20, 1), makeDart(18, 1), makeDart(12, 1)), // Total is 50 - 175 + ) + + val p2Rounds = listOf( - makeDart(20, 1, SegmentType.INNER_SINGLE), - makeDart(5, 1, SegmentType.OUTER_SINGLE), - makeDart(1, 1, SegmentType.INNER_SINGLE)), // IOI - 52 - listOf(makeDart(18, 1), makeDart(20, 1), makeDart(5, 1)), // Score 18s - 125 - ) + listOf( + makeDart(20, 1, SegmentType.INNER_SINGLE), + makeDart(5, 1, SegmentType.OUTER_SINGLE), + makeDart(1, 1, SegmentType.INNER_SINGLE) + ), // IOI - 52 + listOf(makeDart(18, 1), makeDart(20, 1), makeDart(5, 1)), // Score 18s - 125 + ) val expectedRounds = p1Rounds.zipDartRounds(p2Rounds) val p1AimDarts = p1Rounds.flatten().map { it.toAimDart() } val p2AimDarts = p2Rounds.flatten().map { it.toAimDart() } - val p1Model = predictableDartsModel(p1AimDarts, mercyThreshold = 7, dartzeePlayStyle = DartzeePlayStyle.AGGRESSIVE) + val p1Model = + predictableDartsModel( + p1AimDarts, + mercyThreshold = 7, + dartzeePlayStyle = DartzeePlayStyle.AGGRESSIVE + ) val p2Model = predictableDartsModel(p2AimDarts, mercyThreshold = 20) val p1 = makePlayerWithModel(p1Model, name = "Alan") @@ -129,12 +138,18 @@ class TestDartzeeE2E: AbstractRegistryTest() awaitGameFinish(game) verifyState(gamePanel, listener, expectedRounds, finalScore = 175, pt = retrieveTeam()) - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactly( - AchievementSummary(AchievementType.DARTZEE_UNDER_PRESSURE, 50, game.rowId, totalIsFifty.getDisplayName()) - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactly( + AchievementSummary( + AchievementType.DARTZEE_UNDER_PRESSURE, + 50, + game.rowId, + totalIsFifty.getDisplayName() + ) + ) retrieveAchievementsForPlayer(p2.rowId).shouldBeEmpty() checkAchievementConversions(listOf(p1.rowId, p2.rowId)) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/TestGameLoadE2E.kt b/src/test/kotlin/dartzee/e2e/TestGameLoadE2E.kt index 90eb88e92..11ca2e9ec 100644 --- a/src/test/kotlin/dartzee/e2e/TestGameLoadE2E.kt +++ b/src/test/kotlin/dartzee/e2e/TestGameLoadE2E.kt @@ -19,26 +19,24 @@ import dartzee.utils.PreferenceUtil import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe +import javax.swing.SwingUtilities import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import javax.swing.SwingUtilities -class TestGameLoadE2E: AbstractRegistryTest() -{ - override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED, PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) +class TestGameLoadE2E : AbstractRegistryTest() { + override fun getPreferencesAffected() = + listOf(PREFERENCES_INT_AI_SPEED, PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, 0) PreferenceUtil.saveBoolean(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE, false) } @Test @Tag("e2e") - fun `E2E - Game load and AI resume`() - { + fun `E2E - Game load and AI resume`() { val (winner, loser) = createPlayers() val params = GameLaunchParams(listOf(winner, loser), GameType.X01, "501", false) @@ -69,8 +67,7 @@ class TestGameLoadE2E: AbstractRegistryTest() waitForAssertion { retrieveParticipant().dtFinished shouldNotBe DateStatics.END_OF_TIME } } - private fun verifyGameLoadedCorrectly(gameScreen: AbstractDartsGameScreen) - { + private fun verifyGameLoadedCorrectly(gameScreen: AbstractDartsGameScreen) { val winnerScorer = gameScreen.getScorer("Winner") winnerScorer.lblResult.text shouldBe "9 Darts" val rows = winnerScorer.tableScores.getRows() @@ -78,4 +75,4 @@ class TestGameLoadE2E: AbstractRegistryTest() rows[1].shouldContainExactly(Dart(20, 3), Dart(20, 3), Dart(20, 3), 141) rows[2].shouldContainExactly(Dart(20, 3), Dart(19, 3), Dart(12, 2), 0) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/TestGolfE2E.kt b/src/test/kotlin/dartzee/e2e/TestGolfE2E.kt index b55a8577f..f442695d4 100644 --- a/src/test/kotlin/dartzee/e2e/TestGolfE2E.kt +++ b/src/test/kotlin/dartzee/e2e/TestGolfE2E.kt @@ -51,20 +51,17 @@ import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestGolfE2E: AbstractRegistryTest() -{ +class TestGolfE2E : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, 100) } @Test @Tag("e2e") - fun `E2E - Golf`() - { + fun `E2E - Golf`() { val game = insertGame(gameType = GameType.GOLF, gameParams = "18") val model = beastDartsModel() @@ -76,33 +73,41 @@ class TestGolfE2E: AbstractRegistryTest() val expectedDarts = (1..18).map { listOf(Dart(it, 2)) } verifyState(panel, listener, expectedDarts, finalScore = 18, expectedScorerRows = 20) - val expectedAchievementRows = (1..18).map { AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "$it") } + + val expectedAchievementRows = + (1..18).map { + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "$it") + } + AchievementSummary(AchievementType.GOLF_BEST_GAME, 18, game.rowId) + AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 18, game.rowId) + AchievementSummary(AchievementType.GOLF_IN_BOUNDS, -1, game.rowId, "18") - retrieveAchievementsForPlayer(player.rowId).shouldContainExactlyInAnyOrder(expectedAchievementRows) + retrieveAchievementsForPlayer(player.rowId) + .shouldContainExactlyInAnyOrder(expectedAchievementRows) checkAchievementConversions(player.rowId) } @Test @Tag("e2e") - fun `E2E - Golf - Gambler, stop threshold`() - { + fun `E2E - Golf - Gambler, stop threshold`() { val game = insertGame(gameType = GameType.GOLF, gameParams = "9") val (gamePanel, listener) = setUpGamePanel(game) - val expectedRounds = listOf( - listOf(drtOuterOne(), drtInnerOne()), // 3, 1 gambled - listOf(drtOuterFifteen(), drtTrebleSeventeen(), drtOuterSeventeen()), // 8, 1 gambled - listOf(drtInnerThree(), drtOuterThree(), drtDoubleThree()), // 9, 4 gambled, OHW: 1 - listOf(drtTrebleFour()), // 11, 4 gambled (tests first stopThreshold) - listOf(drtDoubleFive()), // 12, 4 gambled, OHW: 2 - listOf(drtOuterSix(), drtOuterSix(), drtOuterSix()), // 16, 6 gambled - listOf(drtOuterSeven(), drtOuterSixteen(), drtInnerSixteen()), // 21, 7 gambled - listOf(drtMissEight(), drtInnerEight()), // 24, 7 gambled - listOf(drtMissNine(), drtDoubleNine()), // 25, 7 gambled, OHW: 3 - ) + val expectedRounds = + listOf( + listOf(drtOuterOne(), drtInnerOne()), // 3, 1 gambled + listOf( + drtOuterFifteen(), + drtTrebleSeventeen(), + drtOuterSeventeen() + ), // 8, 1 gambled + listOf(drtInnerThree(), drtOuterThree(), drtDoubleThree()), // 9, 4 gambled, OHW: 1 + listOf(drtTrebleFour()), // 11, 4 gambled (tests first stopThreshold) + listOf(drtDoubleFive()), // 12, 4 gambled, OHW: 2 + listOf(drtOuterSix(), drtOuterSix(), drtOuterSix()), // 16, 6 gambled + listOf(drtOuterSeven(), drtOuterSixteen(), drtInnerSixteen()), // 21, 7 gambled + listOf(drtMissEight(), drtInnerEight()), // 24, 7 gambled + listOf(drtMissNine(), drtDoubleNine()), // 25, 7 gambled, OHW: 3 + ) val aimDarts = expectedRounds.flatten().map { it.toAimDart() } val aiModel = predictableDartsModel(aimDarts) @@ -113,42 +118,57 @@ class TestGolfE2E: AbstractRegistryTest() verifyState(gamePanel, listener, expectedRounds, finalScore = 25, expectedScorerRows = 10) - val expectedAchievementRows = listOf( - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "3"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "5"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "9"), - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "1"), - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 3, game.rowId, "3"), - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, game.rowId, "6"), - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "7"), - AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 3, game.rowId) - ) - - retrieveAchievementsForPlayer(player.rowId).shouldContainExactlyInAnyOrder(expectedAchievementRows) + val expectedAchievementRows = + listOf( + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "3"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "5"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "9"), + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "1"), + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 3, game.rowId, "3"), + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, game.rowId, "6"), + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "7"), + AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 3, game.rowId) + ) + + retrieveAchievementsForPlayer(player.rowId) + .shouldContainExactlyInAnyOrder(expectedAchievementRows) checkAchievementConversions(player.rowId) } @Test @Tag("e2e") - fun `E2E - 9 holes - Team of 2`() - { + fun `E2E - 9 holes - Team of 2`() { val game = insertGame(gameType = GameType.GOLF, gameParams = "9") val (gamePanel, listener) = setUpGamePanel(game) - val p1Rounds = listOf( - listOf(drtMissOne(), drtOuterOne(), drtOuterOne()), // Gambled 1 in round 1. Total: 4 - listOf(drtMissThree(), drtDoubleThree()), // CM: 3, OHW: 1, Total: 9 - listOf(drtDoubleFive()), // CM: 5, OHW: 2, Total: 13 - listOf(drtMissSeven(), drtInnerSeven()), // Total: 17 - listOf(drtOuterNine(), drtOuterNine(), drtDoubleNine()), // Gambled 2, CM: 9, OHW: 3, Total: 23 - ) - - val p2Rounds = listOf( - listOf(drtMissTwo(), drtOuterTwo()), // Total: 8 - listOf(drtOuterFour(), drtMissFour(), drtInnerFour()), // Gambled 1 in round 4, Total: 12 - listOf(drtDoubleSix()), // CM: 6, OHW: 1, Total: 14 - listOf(drtDoubleSixteen(), drtDoubleEleven(), drtMissEight()) // Total: 22 - ) + val p1Rounds = + listOf( + listOf( + drtMissOne(), + drtOuterOne(), + drtOuterOne() + ), // Gambled 1 in round 1. Total: 4 + listOf(drtMissThree(), drtDoubleThree()), // CM: 3, OHW: 1, Total: 9 + listOf(drtDoubleFive()), // CM: 5, OHW: 2, Total: 13 + listOf(drtMissSeven(), drtInnerSeven()), // Total: 17 + listOf( + drtOuterNine(), + drtOuterNine(), + drtDoubleNine() + ), // Gambled 2, CM: 9, OHW: 3, Total: 23 + ) + + val p2Rounds = + listOf( + listOf(drtMissTwo(), drtOuterTwo()), // Total: 8 + listOf( + drtOuterFour(), + drtMissFour(), + drtInnerFour() + ), // Gambled 1 in round 4, Total: 12 + listOf(drtDoubleSix()), // CM: 6, OHW: 1, Total: 14 + listOf(drtDoubleSixteen(), drtDoubleEleven(), drtMissEight()) // Total: 22 + ) val expectedRounds: List> = p1Rounds.zipDartRounds(p2Rounds) @@ -165,23 +185,32 @@ class TestGolfE2E: AbstractRegistryTest() gamePanel.startNewGame(participants) awaitGameFinish(game) - verifyState(gamePanel, listener, expectedRounds, finalScore = 23, pt = retrieveTeam(), expectedScorerRows = 10) - - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "1"), - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, game.rowId, "9"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "3"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "5"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "9"), - AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 3, game.rowId) + verifyState( + gamePanel, + listener, + expectedRounds, + finalScore = 23, + pt = retrieveTeam(), + expectedScorerRows = 10 ) - retrieveAchievementsForPlayer(p2.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "4"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "6"), - AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 1, game.rowId) - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "1"), + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, game.rowId, "9"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "3"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "5"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "9"), + AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 3, game.rowId) + ) + + retrieveAchievementsForPlayer(p2.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 1, game.rowId, "4"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, game.rowId, "6"), + AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 1, game.rowId) + ) checkAchievementConversions(listOf(p1.rowId, p2.rowId)) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/TestMatchE2E.kt b/src/test/kotlin/dartzee/e2e/TestMatchE2E.kt index b304e35df..c3682c4eb 100644 --- a/src/test/kotlin/dartzee/e2e/TestMatchE2E.kt +++ b/src/test/kotlin/dartzee/e2e/TestMatchE2E.kt @@ -24,26 +24,24 @@ import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe +import javax.swing.JTabbedPane import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import javax.swing.JTabbedPane -class TestMatchE2E: AbstractRegistryTest() -{ - override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED, PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) +class TestMatchE2E : AbstractRegistryTest() { + override fun getPreferencesAffected() = + listOf(PREFERENCES_INT_AI_SPEED, PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, 0) PreferenceUtil.saveBoolean(PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE, false) } @Test @Tag("e2e") - fun `E2E - Two game match`() - { + fun `E2E - Two game match`() { val match = insertDartsMatch(games = 2, matchParams = "", mode = MatchMode.FIRST_TO) match.gameType = GameType.X01 match.gameParams = "501" @@ -58,8 +56,7 @@ class TestMatchE2E: AbstractRegistryTest() verifyUi() } - private fun verifyDatabase(matchId: String, winner: PlayerEntity, loser: PlayerEntity) - { + private fun verifyDatabase(matchId: String, winner: PlayerEntity, loser: PlayerEntity) { val games = GameEntity().retrieveEntities() games.size shouldBe 2 games.forEach { @@ -91,8 +88,7 @@ class TestMatchE2E: AbstractRegistryTest() } } - private fun verifyUi() - { + private fun verifyUi() { val matchScreen = ScreenCache.getDartsGameScreens().first() as X01MatchScreen matchScreen.title shouldBe "Match #1 (First to 2 - 501)" @@ -108,4 +104,4 @@ class TestMatchE2E: AbstractRegistryTest() tabbedPane.selectedIndex = 1 matchScreen.title shouldBe "Game #1 (501 - 2 players)" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/TestResizeE2E.kt b/src/test/kotlin/dartzee/e2e/TestResizeE2E.kt index aeeef11d5..63beabc22 100644 --- a/src/test/kotlin/dartzee/e2e/TestResizeE2E.kt +++ b/src/test/kotlin/dartzee/e2e/TestResizeE2E.kt @@ -10,25 +10,22 @@ import dartzee.`object`.Dart import dartzee.utils.PREFERENCES_INT_AI_SPEED import dartzee.utils.PreferenceUtil import io.kotest.matchers.comparables.shouldBeLessThan +import java.awt.Dimension import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import java.awt.Dimension -class TestResizeE2E : AbstractRegistryTest() -{ +class TestResizeE2E : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, 100) } @Test @Tag("e2e") - fun `E2E - Small dartboard`() - { + fun `E2E - Small dartboard`() { val game = insertGame(gameType = GameType.X01, gameParams = "501") val aiModel = beastDartsModel(hmScoreToDart = mapOf(81 to AimDart(19, 3))) @@ -43,12 +40,13 @@ class TestResizeE2E : AbstractRegistryTest() gamePanel.dartboard.width shouldBeLessThan 100 - val expectedRounds = listOf( - listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), - listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), - listOf(Dart(20, 3), Dart(19, 3), Dart(12, 2)) - ) + val expectedRounds = + listOf( + listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), + listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), + listOf(Dart(20, 3), Dart(19, 3), Dart(12, 2)) + ) verifyState(gamePanel, listener, expectedRounds, scoreSuffix = " Darts", finalScore = 9) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/TestRoundTheClockE2E.kt b/src/test/kotlin/dartzee/e2e/TestRoundTheClockE2E.kt index 72a7fbbbf..4e1580acd 100644 --- a/src/test/kotlin/dartzee/e2e/TestRoundTheClockE2E.kt +++ b/src/test/kotlin/dartzee/e2e/TestRoundTheClockE2E.kt @@ -50,21 +50,22 @@ import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestRoundTheClockE2E: AbstractRegistryTest() -{ +class TestRoundTheClockE2E : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, 100) } @Test @Tag("e2e") - fun `E2E - RTC - perfect game`() - { - val game = insertGame(gameType = GameType.ROUND_THE_CLOCK, gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson()) + fun `E2E - RTC - perfect game`() { + val game = + insertGame( + gameType = GameType.ROUND_THE_CLOCK, + gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson() + ) val model = beastDartsModel() val player = insertPlayer(model = model) @@ -75,7 +76,8 @@ class TestRoundTheClockE2E: AbstractRegistryTest() val expectedDarts = (1..20).map { Dart(it, 1) }.chunked(4) verifyState(panel, listener, expectedDarts, 20, scoreSuffix = " Darts") - retrieveAchievementsForPlayer(player.rowId).shouldContainExactlyInAnyOrder( + retrieveAchievementsForPlayer(player.rowId) + .shouldContainExactlyInAnyOrder( AchievementSummary(AchievementType.CLOCK_BEST_GAME, 20, game.rowId), AchievementSummary(AchievementType.CLOCK_BEST_STREAK, 20, game.rowId), AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, game.rowId, "1"), @@ -83,29 +85,54 @@ class TestRoundTheClockE2E: AbstractRegistryTest() AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, game.rowId, "3"), AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, game.rowId, "4"), AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, game.rowId, "5") - ) + ) checkAchievementConversions(player.rowId) } @Test @Tag("e2e") - fun `E2E - RTC - unordered`() - { - val game = insertGame(gameType = GameType.ROUND_THE_CLOCK, gameParams = RoundTheClockConfig(ClockType.Standard, false).toJson()) + fun `E2E - RTC - unordered`() { + val game = + insertGame( + gameType = GameType.ROUND_THE_CLOCK, + gameParams = RoundTheClockConfig(ClockType.Standard, false).toJson() + ) val (gamePanel, listener) = setUpGamePanel(game) - val expectedRounds = listOf( - listOf(Dart(1, 1), Dart(5, 3), Dart(20, 1)), // 2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19 - listOf(Dart(3, 2), Dart(4, 0), Dart(7, 1)), // 2,4,6,8,9,10,11,12,13,14,15,16,17,18,19 - listOf(Dart(8, 1), Dart(5, 1), Dart(20, 1)), // 2,4,6,9,10,11,12,13,14,15,16,17,18,19 - listOf(Dart(2, 1), Dart(4, 1), Dart(6, 1), Dart(9, 1)), // 10,11,12,13,14,15,16,17,18,19 (streak of 4) - listOf(Dart(10, 1), Dart(12, 1), Dart(13, 2)), // 11,14,15,16,17,18,19 (broken streak of 5) - listOf(Dart(14, 1), Dart(16, 1), Dart(15, 2)), // 11,17,18,19 + val expectedRounds = + listOf( + listOf( + Dart(1, 1), + Dart(5, 3), + Dart(20, 1) + ), // 2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19 + listOf( + Dart(3, 2), + Dart(4, 0), + Dart(7, 1) + ), // 2,4,6,8,9,10,11,12,13,14,15,16,17,18,19 + listOf( + Dart(8, 1), + Dart(5, 1), + Dart(20, 1) + ), // 2,4,6,9,10,11,12,13,14,15,16,17,18,19 + listOf( + Dart(2, 1), + Dart(4, 1), + Dart(6, 1), + Dart(9, 1) + ), // 10,11,12,13,14,15,16,17,18,19 (streak of 4) + listOf( + Dart(10, 1), + Dart(12, 1), + Dart(13, 2) + ), // 11,14,15,16,17,18,19 (broken streak of 5) + listOf(Dart(14, 1), Dart(16, 1), Dart(15, 2)), // 11,17,18,19 listOf(Dart(11, 1), Dart(17, 1), Dart(18, 1), Dart(3, 0)), // 19 - listOf(Dart(19, 1)) // done. - ) + listOf(Dart(19, 1)) // done. + ) val aimDarts = expectedRounds.flatten().map { AimDart(it.score, it.multiplier) } val aiModel = predictableDartsModel(aimDarts, mercyThreshold = 7) @@ -116,35 +143,56 @@ class TestRoundTheClockE2E: AbstractRegistryTest() verifyState(gamePanel, listener, expectedRounds, scoreSuffix = " Darts", finalScore = 24) - retrieveAchievementsForPlayer(player.rowId).shouldContainExactlyInAnyOrder( + retrieveAchievementsForPlayer(player.rowId) + .shouldContainExactlyInAnyOrder( AchievementSummary(AchievementType.CLOCK_BEST_STREAK, 5, game.rowId), AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, game.rowId, "4") - ) + ) checkAchievementConversions(player.rowId) } @Test @Tag("e2e") - fun `E2E - In Order- Team of 2`() - { - val game = insertGame(gameType = GameType.ROUND_THE_CLOCK, gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson()) + fun `E2E - In Order- Team of 2`() { + val game = + insertGame( + gameType = GameType.ROUND_THE_CLOCK, + gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson() + ) val (gamePanel, listener) = setUpGamePanel(game) - val p1Rounds = listOf( - listOf(drtOuterOne(), drtOuterTwo(), drtMissThree()), // Target: 3 - listOf(drtOuterFive(), drtTrebleSix(), drtOuterSeven(), drtInnerEight()), // Target: 9 - listOf(drtOuterTwelve(), drtTrebleThirteen(), drtOuterEleven()), // Target: 14 - listOf(drtOuterSeventeen(), drtOuterEighteen(), drtInnerSeven()), // Target: 19 - listOf(drtOuterTwenty()) // Fin - ) - - val p2Rounds = listOf( - listOf(drtInnerSeventeen(), drtInnerThree(), drtOuterFour()), // Target: 5 - listOf(drtOuterNine(), drtInnerTen(), drtDoubleEleven(), drtMissTwelve()), // Target: 12 - listOf(drtInnerFourteen(), drtOuterFifteen(), drtOuterSixteen(), drtOuterThree()), // Target: 17 - listOf(drtTrebleNineteen(), drtOuterFive(), drtOuterOne()) // Target: 20 - ) + val p1Rounds = + listOf( + listOf(drtOuterOne(), drtOuterTwo(), drtMissThree()), // Target: 3 + listOf( + drtOuterFive(), + drtTrebleSix(), + drtOuterSeven(), + drtInnerEight() + ), // Target: 9 + listOf(drtOuterTwelve(), drtTrebleThirteen(), drtOuterEleven()), // Target: 14 + listOf(drtOuterSeventeen(), drtOuterEighteen(), drtInnerSeven()), // Target: 19 + listOf(drtOuterTwenty()) // Fin + ) + + val p2Rounds = + listOf( + listOf(drtInnerSeventeen(), drtInnerThree(), drtOuterFour()), // Target: 5 + listOf( + drtOuterNine(), + drtInnerTen(), + drtDoubleEleven(), + drtMissTwelve() + ), // Target: 12 + listOf( + drtInnerFourteen(), + drtOuterFifteen(), + drtOuterSixteen(), + drtOuterThree() + ), // Target: 17 + listOf(drtTrebleNineteen(), drtOuterFive(), drtOuterOne()) // Target: 20 + ) val expectedRounds: List> = p1Rounds.zipDartRounds(p2Rounds) @@ -161,14 +209,22 @@ class TestRoundTheClockE2E: AbstractRegistryTest() gamePanel.startNewGame(participants) awaitGameFinish(game) - verifyState(gamePanel, listener, expectedRounds, finalScore = 28, pt = retrieveTeam(), scoreSuffix = " Darts") - - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, game.rowId, "3"), + verifyState( + gamePanel, + listener, + expectedRounds, + finalScore = 28, + pt = retrieveTeam(), + scoreSuffix = " Darts" ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, game.rowId, "3"), + ) + retrieveAchievementsForPlayer(p2.rowId).shouldBeEmpty() checkAchievementConversions(listOf(p1.rowId, p2.rowId)) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/e2e/TestX01E2E.kt b/src/test/kotlin/dartzee/e2e/TestX01E2E.kt index 666e50ce8..ed0d420b9 100644 --- a/src/test/kotlin/dartzee/e2e/TestX01E2E.kt +++ b/src/test/kotlin/dartzee/e2e/TestX01E2E.kt @@ -22,20 +22,17 @@ import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestX01E2E : AbstractRegistryTest() -{ +class TestX01E2E : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_INT_AI_SPEED) @BeforeEach - fun beforeEach() - { + fun beforeEach() { PreferenceUtil.saveInt(PREFERENCES_INT_AI_SPEED, 100) } @Test @Tag("e2e") - fun `E2E - 501 - 9 dart game`() - { + fun `E2E - 501 - 9 dart game`() { val game = insertGame(gameType = GameType.X01, gameParams = "501") val aiModel = beastDartsModel(hmScoreToDart = mapOf(81 to AimDart(19, 3))) @@ -44,42 +41,49 @@ class TestX01E2E : AbstractRegistryTest() val (panel, listener) = setUpGamePanelAndStartGame(game, listOf(player)) awaitGameFinish(game) - val expectedRounds = listOf( - listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), - listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), - listOf(Dart(20, 3), Dart(19, 3), Dart(12, 2)) - ) + val expectedRounds = + listOf( + listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), + listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)), + listOf(Dart(20, 3), Dart(19, 3), Dart(12, 2)) + ) verifyState(panel, listener, expectedRounds, scoreSuffix = " Darts", finalScore = 9) - retrieveAchievementsForPlayer(player.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.X01_BEST_GAME, 9, game.rowId), - AchievementSummary(AchievementType.X01_BEST_FINISH, 141, game.rowId), - AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 180, game.rowId), - AchievementSummary(AchievementType.X01_CHECKOUT_COMPLETENESS, 12, game.rowId), - AchievementSummary(AchievementType.X01_STYLISH_FINISH, 141, game.rowId, "T20, T19, D12") - ) + retrieveAchievementsForPlayer(player.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.X01_BEST_GAME, 9, game.rowId), + AchievementSummary(AchievementType.X01_BEST_FINISH, 141, game.rowId), + AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 180, game.rowId), + AchievementSummary(AchievementType.X01_CHECKOUT_COMPLETENESS, 12, game.rowId), + AchievementSummary( + AchievementType.X01_STYLISH_FINISH, + 141, + game.rowId, + "T20, T19, D12" + ) + ) checkAchievementConversions(player.rowId) } @Test @Tag("e2e") - fun `E2E - 301 - bust and mercy rule`() - { + fun `E2E - 301 - bust and mercy rule`() { val game = insertGame(gameType = GameType.X01, gameParams = "301") val (gamePanel, listener) = setUpGamePanel(game) - val expectedRounds = listOf( - listOf(makeDart(20, 3), makeDart(20, 3), makeDart(20, 3)), //121 - listOf(makeDart(20, 3), makeDart(20, 2), makeDart(1, 1)), // 20 - listOf(makeDart(15, 2)), // 20 (bust) - listOf(makeDart(10, 1), makeDart(5, 1), makeDart(5, 0)), // 5 - listOf(makeDart(5, 0), makeDart(5, 0), makeDart(5, 0)), // 5 - listOf(makeDart(1, 1)), // 4 (mercy) - listOf(makeDart(2, 2)) // 0 - ) + val expectedRounds = + listOf( + listOf(makeDart(20, 3), makeDart(20, 3), makeDart(20, 3)), // 121 + listOf(makeDart(20, 3), makeDart(20, 2), makeDart(1, 1)), // 20 + listOf(makeDart(15, 2)), // 20 (bust) + listOf(makeDart(10, 1), makeDart(5, 1), makeDart(5, 0)), // 5 + listOf(makeDart(5, 0), makeDart(5, 0), makeDart(5, 0)), // 5 + listOf(makeDart(1, 1)), // 4 (mercy) + listOf(makeDart(2, 2)) // 0 + ) val aimDarts = expectedRounds.flatten().map { it.toAimDart() } val aiModel = predictableDartsModel(aimDarts, mercyThreshold = 7) @@ -90,40 +94,42 @@ class TestX01E2E : AbstractRegistryTest() verifyState(gamePanel, listener, expectedRounds, scoreSuffix = " Darts", finalScore = 19) - retrieveAchievementsForPlayer(player.rowId).shouldContainExactlyInAnyOrder( + retrieveAchievementsForPlayer(player.rowId) + .shouldContainExactlyInAnyOrder( AchievementSummary(AchievementType.X01_BEST_FINISH, 4, game.rowId), AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 180, game.rowId), AchievementSummary(AchievementType.X01_CHECKOUT_COMPLETENESS, 2, game.rowId), AchievementSummary(AchievementType.X01_HIGHEST_BUST, 20, game.rowId), AchievementSummary(AchievementType.X01_SUCH_BAD_LUCK, 1, game.rowId) - ) + ) checkAchievementConversions(player.rowId) } @Test @Tag("e2e") - fun `E2E - 501 - Team of 2`() - { + fun `E2E - 501 - Team of 2`() { val game = insertGame(gameType = GameType.X01, gameParams = "501") val (gamePanel, listener) = setUpGamePanel(game) - val p1Rounds = listOf( - listOf(makeDart(20, 3), makeDart(20, 3), makeDart(20, 3)), // 321 - listOf(makeDart(20, 1), makeDart(20, 3), makeDart(5, 3)), // 179 - listOf(makeDart(14, 1), makeDart(20, 1), makeDart(5, 1)), // 45 - listOf(makeDart(3, 0), makeDart(3, 1), makeDart(16, 2)), // 19 - listOf(makeDart(8, 0), makeDart(8, 0), makeDart(16, 0)), // 16 - listOf(makeDart(1, 1), makeDart(4, 0), makeDart(4, 2)), // Fin - ) - - val p2Rounds = listOf( - listOf(makeDart(19, 1), makeDart(3, 3), makeDart(19, 1)), // 274 - listOf(makeDart(19, 3), makeDart(17, 1), makeDart(7, 3)), // 84 - listOf(makeDart(17, 1), makeDart(14, 0), makeDart(9, 1)), // 19 - listOf(makeDart(3, 1)), // 16, mercied - listOf(makeDart(8, 0), makeDart(8, 0), makeDart(7, 1)) // 9 - ) + val p1Rounds = + listOf( + listOf(makeDart(20, 3), makeDart(20, 3), makeDart(20, 3)), // 321 + listOf(makeDart(20, 1), makeDart(20, 3), makeDart(5, 3)), // 179 + listOf(makeDart(14, 1), makeDart(20, 1), makeDart(5, 1)), // 45 + listOf(makeDart(3, 0), makeDart(3, 1), makeDart(16, 2)), // 19 + listOf(makeDart(8, 0), makeDart(8, 0), makeDart(16, 0)), // 16 + listOf(makeDart(1, 1), makeDart(4, 0), makeDart(4, 2)), // Fin + ) + + val p2Rounds = + listOf( + listOf(makeDart(19, 1), makeDart(3, 3), makeDart(19, 1)), // 274 + listOf(makeDart(19, 3), makeDart(17, 1), makeDart(7, 3)), // 84 + listOf(makeDart(17, 1), makeDart(14, 0), makeDart(9, 1)), // 19 + listOf(makeDart(3, 1)), // 16, mercied + listOf(makeDart(8, 0), makeDart(8, 0), makeDart(7, 1)) // 9 + ) val expectedRounds = p1Rounds.zipDartRounds(p2Rounds) @@ -140,21 +146,30 @@ class TestX01E2E : AbstractRegistryTest() gamePanel.startNewGame(participants) awaitGameFinish(game) - verifyState(gamePanel, listener, expectedRounds, scoreSuffix = " Darts", finalScore = 33, pt = retrieveTeam()) - - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 180, game.rowId), - AchievementSummary(AchievementType.X01_HIGHEST_BUST, 19, game.rowId), - AchievementSummary(AchievementType.X01_SUCH_BAD_LUCK, 1, game.rowId), - AchievementSummary(AchievementType.X01_NO_MERCY, -1, game.rowId, "9"), - AchievementSummary(AchievementType.X01_CHECKOUT_COMPLETENESS, 4, game.rowId), - AchievementSummary(AchievementType.X01_BEST_FINISH, 9, game.rowId), + verifyState( + gamePanel, + listener, + expectedRounds, + scoreSuffix = " Darts", + finalScore = 33, + pt = retrieveTeam() ) - retrieveAchievementsForPlayer(p2.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 95, game.rowId), - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 180, game.rowId), + AchievementSummary(AchievementType.X01_HIGHEST_BUST, 19, game.rowId), + AchievementSummary(AchievementType.X01_SUCH_BAD_LUCK, 1, game.rowId), + AchievementSummary(AchievementType.X01_NO_MERCY, -1, game.rowId, "9"), + AchievementSummary(AchievementType.X01_CHECKOUT_COMPLETENESS, 4, game.rowId), + AchievementSummary(AchievementType.X01_BEST_FINISH, 9, game.rowId), + ) + + retrieveAchievementsForPlayer(p2.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 95, game.rowId), + ) checkAchievementConversions(listOf(p1.rowId, p2.rowId)) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/TestGameLauncher.kt b/src/test/kotlin/dartzee/game/TestGameLauncher.kt index b2c50313c..fb2d6736e 100644 --- a/src/test/kotlin/dartzee/game/TestGameLauncher.kt +++ b/src/test/kotlin/dartzee/game/TestGameLauncher.kt @@ -32,39 +32,37 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestGameLauncher: AbstractTest() -{ +class TestGameLauncher : AbstractTest() { @Test - fun `Should launch a new game of X01 successfully`() - { + fun `Should launch a new game of X01 successfully`() { testNewGameLaunch(GameType.X01, "501") } @Test - fun `Should launch a new game of RTC successfully`() - { - testNewGameLaunch(GameType.ROUND_THE_CLOCK, RoundTheClockConfig(ClockType.Standard, true).toJson()) + fun `Should launch a new game of RTC successfully`() { + testNewGameLaunch( + GameType.ROUND_THE_CLOCK, + RoundTheClockConfig(ClockType.Standard, true).toJson() + ) } @Test - fun `Should launch a new game of Golf successfully`() - { + fun `Should launch a new game of Golf successfully`() { testNewGameLaunch(GameType.GOLF, "18") } @Test - fun `Should launch a new game of Dartzee successfully`() - { + fun `Should launch a new game of Dartzee successfully`() { val dartzeeDtos = listOf(twoBlackOneWhite, scoreEighteens) testNewGameLaunch(GameType.DARTZEE, "", dartzeeDtos) getCountFromTable(EntityName.DartzeeRule) shouldBe 2 } - private inline fun > testNewGameLaunch( + private inline fun > testNewGameLaunch( gameType: GameType, gameParams: String, - dartzeeDtos: List = emptyList()) - { + dartzeeDtos: List = emptyList() + ) { val p = insertPlayer(strategy = "") val params = GameLaunchParams(listOf(p), gameType, gameParams, false, dartzeeDtos) GameLauncher().launchNewGame(params) @@ -86,8 +84,7 @@ class TestGameLauncher: AbstractTest() } @Test - fun `Should launch a new match successfully`() - { + fun `Should launch a new match successfully`() { val match = DartsMatchEntity.factoryFirstTo(2) val p = insertPlayer() val p2 = insertPlayer() @@ -105,8 +102,7 @@ class TestGameLauncher: AbstractTest() } @Test - fun `Should bring up the window when loading an already visible game`() - { + fun `Should bring up the window when loading an already visible game`() { val scrn = mockk(relaxed = true) ScreenCache.addDartsGameScreen("foo", scrn) @@ -116,16 +112,14 @@ class TestGameLauncher: AbstractTest() } @Test - fun `Should show an error and return if no game exists for the id`() - { + fun `Should show an error and return if no game exists for the id`() { GameLauncher().loadAndDisplayGame("foo") dialogFactory.errorsShown.shouldContainExactly("Game foo does not exist.") } @Test - fun `Should handle an error when trying to load a single game`() - { + fun `Should handle an error when trying to load a single game`() { val g = insertGame() GameLauncher().loadAndDisplayGame(g.rowId) @@ -136,8 +130,7 @@ class TestGameLauncher: AbstractTest() } @Test - fun `Should handle an error when trying to load a game that's part of a match`() - { + fun `Should handle an error when trying to load a game that's part of a match`() { val match = insertDartsMatch() val g = insertGame(dartsMatchId = match.rowId) diff --git a/src/test/kotlin/dartzee/game/TestGameSqlUtils.kt b/src/test/kotlin/dartzee/game/TestGameSqlUtils.kt index 1ad494677..dd7d37f4c 100644 --- a/src/test/kotlin/dartzee/game/TestGameSqlUtils.kt +++ b/src/test/kotlin/dartzee/game/TestGameSqlUtils.kt @@ -23,17 +23,14 @@ import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -class TestGameSqlUtils : AbstractTest() -{ +class TestGameSqlUtils : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { InjectedCore.collectionShuffler = CollectionShuffler() } @Test - fun `Should prepare and load players for a non team game correctly`() - { + fun `Should prepare and load players for a non team game correctly`() { val players = preparePlayers(3) val (p1, p2, p3) = players val g = insertGame() @@ -52,8 +49,7 @@ class TestGameSqlUtils : AbstractTest() } @Test - fun `Should prepare and load players for a team game correctly`() - { + fun `Should prepare and load players for a team game correctly`() { val players = preparePlayers(4) val (p1, p2, p3, p4) = players val g = insertGame() @@ -71,8 +67,7 @@ class TestGameSqlUtils : AbstractTest() } @Test - fun `Should create a single participant if there are an odd number of players`() - { + fun `Should create a single participant if there are an odd number of players`() { val players = preparePlayers(3) val (p1, p2, p3) = players val g = insertGame() @@ -90,8 +85,7 @@ class TestGameSqlUtils : AbstractTest() } @Test - fun `Should prepare next participants correctly for a 2 player game`() - { + fun `Should prepare next participants correctly for a 2 player game`() { val match = insertDartsMatch() val g1 = insertGame(dartsMatchId = match.rowId, matchOrdinal = 1) val players = preparePlayers(2) @@ -110,8 +104,7 @@ class TestGameSqlUtils : AbstractTest() } @Test - fun `Should prepare next participants correctly for a 2 team game`() - { + fun `Should prepare next participants correctly for a 2 team game`() { val match = insertDartsMatch() val g1 = insertGame(dartsMatchId = match.rowId, matchOrdinal = 1) val players = preparePlayers(4) @@ -131,8 +124,7 @@ class TestGameSqlUtils : AbstractTest() } @Test - fun `Should prepare next participants correctly for a game with more than 2 teams`() - { + fun `Should prepare next participants correctly for a game with more than 2 teams`() { InjectedCore.collectionShuffler = DeterministicCollectionShuffler() val match = insertDartsMatch() @@ -161,8 +153,7 @@ class TestGameSqlUtils : AbstractTest() } @Test - fun `Should insert the right non-participant next entities`() - { + fun `Should insert the right non-participant next entities`() { val match = insertDartsMatch() val g1 = insertGame(dartsMatchId = match.rowId, matchOrdinal = 1) val firstGameParticipants = prepareParticipants(g1.rowId, preparePlayers(2), false) @@ -176,8 +167,7 @@ class TestGameSqlUtils : AbstractTest() } @Test - fun `Should insert dartzee rules as part of next entities if appropriate`() - { + fun `Should insert dartzee rules as part of next entities if appropriate`() { val match = insertDartsMatch() val g1 = insertGame(dartsMatchId = match.rowId, matchOrdinal = 1) val firstGameParticipants = prepareParticipants(g1.rowId, preparePlayers(2), false) @@ -189,11 +179,18 @@ class TestGameSqlUtils : AbstractTest() val rules = DartzeeRuleEntity().retrieveForGame(g2.rowId) rules.size shouldBe 2 - rules.map { it.toDto().generateRuleDescription() }.shouldContainExactly(originalRules.map { it.generateRuleDescription() }) + rules + .map { it.toDto().generateRuleDescription() } + .shouldContainExactly(originalRules.map { it.generateRuleDescription() }) } - private fun validateTeam(team: IWrappedParticipant, gameId: String, ordinal: Int, p1: PlayerEntity, p2: PlayerEntity) - { + private fun validateTeam( + team: IWrappedParticipant, + gameId: String, + ordinal: Int, + p1: PlayerEntity, + p2: PlayerEntity + ) { team.shouldBeInstanceOf() val teamEntity = team.participant teamEntity.gameId shouldBe gameId @@ -212,11 +209,14 @@ class TestGameSqlUtils : AbstractTest() pt2.ordinal shouldBe 1 pt2.playerId shouldBe p2.rowId pt2.retrievedFromDb shouldBe true - } - private fun validateSingleParticipant(pt: IWrappedParticipant, gameId: String, ordinal: Int, player: PlayerEntity) - { + private fun validateSingleParticipant( + pt: IWrappedParticipant, + gameId: String, + ordinal: Int, + player: PlayerEntity + ) { pt.shouldBeInstanceOf() pt.participant.gameId shouldBe gameId pt.participant.playerId shouldBe player.rowId @@ -224,4 +224,4 @@ class TestGameSqlUtils : AbstractTest() pt.participant.teamId shouldBe "" pt.participant.retrievedFromDb shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/TestGameType.kt b/src/test/kotlin/dartzee/game/TestGameType.kt index 85c903561..d590184ac 100644 --- a/src/test/kotlin/dartzee/game/TestGameType.kt +++ b/src/test/kotlin/dartzee/game/TestGameType.kt @@ -5,11 +5,9 @@ import dartzee.helper.insertDartzeeTemplate import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGameType: AbstractTest() -{ +class TestGameType : AbstractTest() { @Test - fun `Sensible descriptions when no params`() - { + fun `Sensible descriptions when no params`() { GameType.X01.getDescription() shouldBe "X01" GameType.GOLF.getDescription() shouldBe "Golf" GameType.ROUND_THE_CLOCK.getDescription() shouldBe "Round the Clock" @@ -17,18 +15,18 @@ class TestGameType: AbstractTest() } @Test - fun `Sensible descriptions with params`() - { + fun `Sensible descriptions with params`() { GameType.X01.getDescription("701") shouldBe "701" GameType.GOLF.getDescription("18") shouldBe "Golf - 18 holes" - GameType.ROUND_THE_CLOCK.getDescription(RoundTheClockConfig(ClockType.Trebles, true).toJson()) shouldBe "Round the Clock - Trebles - in order" + GameType.ROUND_THE_CLOCK.getDescription( + RoundTheClockConfig(ClockType.Trebles, true).toJson() + ) shouldBe "Round the Clock - Trebles - in order" GameType.DARTZEE.getDescription("ZZZZ") shouldBe "Dartzee" } @Test - fun `Dartzee description with valid template`() - { + fun `Dartzee description with valid template`() { val t = insertDartzeeTemplate(name = "Goomba") GameType.DARTZEE.getDescription(t.rowId) shouldBe "Dartzee - Goomba" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/TestMatchUtils.kt b/src/test/kotlin/dartzee/game/TestMatchUtils.kt index d6db87b6b..c0616ceea 100644 --- a/src/test/kotlin/dartzee/game/TestMatchUtils.kt +++ b/src/test/kotlin/dartzee/game/TestMatchUtils.kt @@ -9,11 +9,9 @@ import dartzee.helper.preparePlayers import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestMatchUtils : AbstractTest() -{ +class TestMatchUtils : AbstractTest() { @Test - fun `Should identify an incomplete FIRST_TO match`() - { + fun `Should identify an incomplete FIRST_TO match`() { val match = insertDartsMatch(mode = MatchMode.FIRST_TO, games = 3) val (p1, p2) = preparePlayers(2) @@ -23,8 +21,7 @@ class TestMatchUtils : AbstractTest() } @Test - fun `Should identify a complete FIRST_TO match`() - { + fun `Should identify a complete FIRST_TO match`() { val match = insertDartsMatch(mode = MatchMode.FIRST_TO, games = 4) val (p1, p2) = preparePlayers(2) @@ -34,8 +31,7 @@ class TestMatchUtils : AbstractTest() } @Test - fun `Should identify an incomplete POINTS match`() - { + fun `Should identify an incomplete POINTS match`() { val match = insertDartsMatch(mode = MatchMode.POINTS, games = 4) val (p1, p2) = preparePlayers(2) @@ -45,8 +41,7 @@ class TestMatchUtils : AbstractTest() } @Test - fun `Should identify a complete POINTS match`() - { + fun `Should identify a complete POINTS match`() { val match = insertDartsMatch(mode = MatchMode.POINTS, games = 4) val (p1, p2) = preparePlayers(2) @@ -55,9 +50,12 @@ class TestMatchUtils : AbstractTest() matchIsComplete(match, pts) shouldBe true } - private fun insertWinningParticipants(player: PlayerEntity, count: Int): List = + private fun insertWinningParticipants( + player: PlayerEntity, + count: Int + ): List = (1..count).map { val pt = insertParticipant(playerId = player.rowId, finishingPosition = 1) SingleParticipant(pt) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/TestRoundTheClockConfig.kt b/src/test/kotlin/dartzee/game/TestRoundTheClockConfig.kt index 041c35e75..431410a44 100644 --- a/src/test/kotlin/dartzee/game/TestRoundTheClockConfig.kt +++ b/src/test/kotlin/dartzee/game/TestRoundTheClockConfig.kt @@ -4,11 +4,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestRoundTheClockConfig: AbstractTest() -{ +class TestRoundTheClockConfig : AbstractTest() { @Test - fun `Should serialize and deserialize correctly`() - { + fun `Should serialize and deserialize correctly`() { val config = RoundTheClockConfig(ClockType.Doubles, true) val json = config.toJson() @@ -17,11 +15,10 @@ class TestRoundTheClockConfig: AbstractTest() } @Test - fun `Should deserialize correctly`() - { + fun `Should deserialize correctly`() { val json = """{ "clockType": "Trebles", "inOrder": false }""" val config = RoundTheClockConfig.fromJson(json) config.inOrder shouldBe false config.clockType shouldBe ClockType.Trebles } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/state/TestAbstractPlayerState.kt b/src/test/kotlin/dartzee/game/state/TestAbstractPlayerState.kt index f876f7206..aeb8b234e 100644 --- a/src/test/kotlin/dartzee/game/state/TestAbstractPlayerState.kt +++ b/src/test/kotlin/dartzee/game/state/TestAbstractPlayerState.kt @@ -26,11 +26,9 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestAbstractPlayerState: AbstractTest() -{ +class TestAbstractPlayerState : AbstractTest() { @Test - fun `it should take a copy of the darts that are added`() - { + fun `it should take a copy of the darts that are added`() { val state = TestPlayerState(insertParticipant()) val darts = mutableListOf(Dart(20, 1)) @@ -41,8 +39,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `should populate darts with the ParticipantId and RoundNumber`() - { + fun `should populate darts with the ParticipantId and RoundNumber`() { val pt = insertParticipant() val state = TestPlayerState(pt) @@ -57,8 +54,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `It should populate completed rounds with the ParticipantId`() - { + fun `It should populate completed rounds with the ParticipantId`() { val pt = insertParticipant() val state = TestPlayerState(pt) @@ -71,8 +67,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should support resetting the currently thrown darts`() - { + fun `Should support resetting the currently thrown darts`() { val state = TestPlayerState(insertParticipant()) state.dartThrown(Dart(20, 1)) @@ -83,8 +78,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should support committing a round of darts and saving them to the database`() - { + fun `Should support committing a round of darts and saving them to the database`() { val pt = insertParticipant() val dartOne = Dart(20, 1, SegmentType.OUTER_SINGLE) val dartTwo = Dart(5, 1, SegmentType.OUTER_SINGLE) @@ -97,7 +91,9 @@ class TestAbstractPlayerState: AbstractTest() state.commitRound() state.currentRound.shouldBeEmpty() - state.completedRounds.shouldContainExactly(listOf(listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1)))) + state.completedRounds.shouldContainExactly( + listOf(listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1))) + ) val entities = DartEntity().retrieveEntities() entities.forEach { @@ -115,8 +111,8 @@ class TestAbstractPlayerState: AbstractTest() val entityThree = entities.find { it.ordinal == 3 }!! validateDartEntity(entityThree, dartThree) } - private fun validateDartEntity(dartEntity: DartEntity, originalDart: Dart) - { + + private fun validateDartEntity(dartEntity: DartEntity, originalDart: Dart) { dartEntity.multiplier shouldBe originalDart.multiplier dartEntity.score shouldBe originalDart.score dartEntity.segmentType shouldBe originalDart.segmentType @@ -124,8 +120,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should correctly compute the current round number`() - { + fun `Should correctly compute the current round number`() { val state = TestPlayerState(insertParticipant()) state.currentRoundNumber() shouldBe 1 @@ -143,9 +138,13 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should mark a participant as finished`() - { - val participant = insertParticipant(dtFinished = DateStatics.END_OF_TIME, finalScore = -1, finishingPosition = -1) + fun `Should mark a participant as finished`() { + val participant = + insertParticipant( + dtFinished = DateStatics.END_OF_TIME, + finalScore = -1, + finishingPosition = -1 + ) val state = TestPlayerState(participant) state.participantFinished(1, 100) @@ -160,9 +159,13 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should update the finishing position`() - { - val participant = insertParticipant(dtFinished = DateStatics.END_OF_TIME, finalScore = -1, finishingPosition = -1) + fun `Should update the finishing position`() { + val participant = + insertParticipant( + dtFinished = DateStatics.END_OF_TIME, + finalScore = -1, + finishingPosition = -1 + ) val state = TestPlayerState(participant) state.setParticipantFinishPosition(4) @@ -177,8 +180,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should fire state changed`() - { + fun `Should fire state changed`() { val state = TestPlayerState(insertParticipant()) state.shouldFireStateChange { it.dartThrown(Dart(1, 1)) } @@ -193,8 +195,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should fire state changed at the point a listener is added`() - { + fun `Should fire state changed at the point a listener is added`() { val state = TestPlayerState(insertParticipant()) val listener = mockk>(relaxed = true) state.addListener(listener) @@ -203,8 +204,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should identify human vs ai`() - { + fun `Should identify human vs ai`() { val ai = insertPlayer(strategy = "foo") val human = insertPlayer(strategy = "") @@ -216,8 +216,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should correctly identify the current individual within a team`() - { + fun `Should correctly identify the current individual within a team`() { val pt1 = insertParticipant() val pt2 = insertParticipant() @@ -231,8 +230,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should correctly identify whether or not there are multiple participants`() - { + fun `Should correctly identify whether or not there are multiple participants`() { TestPlayerState(insertParticipant()).hasMultiplePlayers() shouldBe false val pt1 = insertParticipant() @@ -241,8 +239,7 @@ class TestAbstractPlayerState: AbstractTest() } @Test - fun `Should correctly extract the rounds for a player, including the current one`() - { + fun `Should correctly extract the rounds for a player, including the current one`() { val pt1 = insertParticipant() val pt2 = insertParticipant() val state = TestTeamState(listOf(pt1, pt2)) @@ -263,28 +260,31 @@ class TestAbstractPlayerState: AbstractTest() } } -data class TestPlayerState(val participant: ParticipantEntity, - override val completedRounds: MutableList> = mutableListOf(), - override val currentRound: MutableList = mutableListOf(), - override var isActive: Boolean = false, - private val scoreSoFar: Int = -1): AbstractPlayerState() -{ +data class TestPlayerState( + val participant: ParticipantEntity, + override val completedRounds: MutableList> = mutableListOf(), + override val currentRound: MutableList = mutableListOf(), + override var isActive: Boolean = false, + private val scoreSoFar: Int = -1 +) : AbstractPlayerState() { override val wrappedParticipant = SingleParticipant(participant) + override fun getScoreSoFar() = scoreSoFar } -data class TestTeamState(val participants: List, - override val completedRounds: MutableList> = mutableListOf(), - override val currentRound: MutableList = mutableListOf(), - override var isActive: Boolean = false, - private val scoreSoFar: Int = -1): AbstractPlayerState() -{ +data class TestTeamState( + val participants: List, + override val completedRounds: MutableList> = mutableListOf(), + override val currentRound: MutableList = mutableListOf(), + override var isActive: Boolean = false, + private val scoreSoFar: Int = -1 +) : AbstractPlayerState() { override val wrappedParticipant = TeamParticipant(insertTeam(), participants) + override fun getScoreSoFar() = scoreSoFar } -fun > S.shouldFireStateChange(fn: (state: S) -> Unit) -{ +fun > S.shouldFireStateChange(fn: (state: S) -> Unit) { val listener = mockk>(relaxed = true) addListener(listener) clearMocks(listener) @@ -295,8 +295,7 @@ fun > S.shouldFireStateChange(fn: (state: S) -> Unit) verify { listener.stateChanged(state) } } -fun > S.shouldNotFireStateChange(fn: (state: S) -> Unit) -{ +fun > S.shouldNotFireStateChange(fn: (state: S) -> Unit) { val listener = mockk>(relaxed = true) addListener(listener) clearMocks(listener) @@ -305,4 +304,4 @@ fun > S.shouldNotFireStateChange(fn: (state: S) -> Uni val state = this verifyNotCalled { listener.stateChanged(state) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/state/TestClockPlayerState.kt b/src/test/kotlin/dartzee/game/state/TestClockPlayerState.kt index 8f1eb7bdc..4ce4402b8 100644 --- a/src/test/kotlin/dartzee/game/state/TestClockPlayerState.kt +++ b/src/test/kotlin/dartzee/game/state/TestClockPlayerState.kt @@ -11,32 +11,33 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestClockPlayerState: AbstractTest() -{ +class TestClockPlayerState : AbstractTest() { @Test - fun `should correctly compute the current target based on clockType`() - { + fun `should correctly compute the current target based on clockType`() { val roundOne = listOf(makeDart(1, 2, startingScore = 1)) - makeClockPlayerState(ClockType.Standard, completedRounds = listOf(roundOne)).findCurrentTarget() shouldBe 2 - makeClockPlayerState(ClockType.Doubles, completedRounds = listOf(roundOne)).findCurrentTarget() shouldBe 2 - makeClockPlayerState(ClockType.Trebles, completedRounds = listOf(roundOne)).findCurrentTarget() shouldBe 1 + makeClockPlayerState(ClockType.Standard, completedRounds = listOf(roundOne)) + .findCurrentTarget() shouldBe 2 + makeClockPlayerState(ClockType.Doubles, completedRounds = listOf(roundOne)) + .findCurrentTarget() shouldBe 2 + makeClockPlayerState(ClockType.Trebles, completedRounds = listOf(roundOne)) + .findCurrentTarget() shouldBe 1 } @Test - fun `Should report a target of one when no darts thrown`() - { + fun `Should report a target of one when no darts thrown`() { val state = makeClockPlayerState() state.findCurrentTarget() shouldBe 1 } @Test - fun `Should combine all thrown darts to calculate current target`() - { - val roundOne = listOf( - makeDart(1, 1, startingScore = 1), - makeDart(2, 0, startingScore = 2), - makeDart(2, 3, startingScore = 2)) + fun `Should combine all thrown darts to calculate current target`() { + val roundOne = + listOf( + makeDart(1, 1, startingScore = 1), + makeDart(2, 0, startingScore = 2), + makeDart(2, 3, startingScore = 2) + ) val state = makeClockPlayerState(completedRounds = listOf(roundOne)) state.findCurrentTarget() shouldBe 3 @@ -49,15 +50,13 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should report a score of 0 when no darts thrown`() - { + fun `Should report a score of 0 when no darts thrown`() { val state = makeClockPlayerState() state.getScoreSoFar() shouldBe 0 } @Test - fun `Should report a score based on how many darts have been thrown, including uncommitted ones`() - { + fun `Should report a score based on how many darts have been thrown, including uncommitted ones`() { val roundOne = listOf(Dart(1, 1), Dart(2, 1), Dart(3, 1), Dart(4, 1)) val roundTwo = listOf(Dart(5, 0), Dart(5, 0), Dart(5, 0)) @@ -72,12 +71,13 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should update darts that are thrown with their starting score`() - { - val roundOne = listOf( - makeDart(1, 1, startingScore = 1), - makeDart(2, 0, startingScore = 2), - makeDart(2, 3, startingScore = 2)) + fun `Should update darts that are thrown with their starting score`() { + val roundOne = + listOf( + makeDart(1, 1, startingScore = 1), + makeDart(2, 0, startingScore = 2), + makeDart(2, 3, startingScore = 2) + ) val state = makeClockPlayerState(completedRounds = listOf(roundOne)) state.findCurrentTarget() shouldBe 3 @@ -91,8 +91,7 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should correctly count the longest streak, taking into account clockType`() - { + fun `Should correctly count the longest streak, taking into account clockType`() { val standardState = makeClockPlayerState(clockType = ClockType.Standard) standardState.getLongestStreak() shouldBe 0 standardState.dartThrown(Dart(1, 1)) @@ -107,8 +106,7 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should correctly report on track for Brucey throughout a successful round`() - { + fun `Should correctly report on track for Brucey throughout a successful round`() { val state = makeClockPlayerState() state.onTrackForBrucey() shouldBe true @@ -124,11 +122,15 @@ class TestClockPlayerState: AbstractTest() state.dartThrown(Dart(4, 3)) state.onTrackForBrucey() shouldBe true } - + @Test - fun `Longest streak should take into account previous rounds`() - { - val roundOne = listOf(makeDart(1, 0, startingScore = 1), makeDart(1, 1, startingScore = 1), makeDart(2, 1, startingScore = 2)) + fun `Longest streak should take into account previous rounds`() { + val roundOne = + listOf( + makeDart(1, 0, startingScore = 1), + makeDart(1, 1, startingScore = 1), + makeDart(2, 1, startingScore = 2) + ) val state = makeClockPlayerState(completedRounds = listOf(roundOne)) state.getLongestStreak() shouldBe 2 @@ -140,8 +142,7 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should report not on track for Brucey as soon as there has been a miss, taking into account clockType`() - { + fun `Should report not on track for Brucey as soon as there has been a miss, taking into account clockType`() { val state = makeClockPlayerState(clockType = ClockType.Doubles) state.dartThrown(Dart(1, 1)) @@ -156,24 +157,18 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should report a current target of null for a finished player, and throw an exception if another dart is thrown`() - { + fun `Should report a current target of null for a finished player, and throw an exception if another dart is thrown`() { val rounds = (1..20).map { makeDart(it, 1, startingScore = it) }.chunked(4) val state = makeClockPlayerState(completedRounds = rounds) state.findCurrentTarget() shouldBe null - shouldThrow { - state.dartThrown(Dart(1, 1)) - } + shouldThrow { state.dartThrown(Dart(1, 1)) } - shouldThrow { - state.getCurrentTarget() - } + shouldThrow { state.getCurrentTarget() } } @Test - fun `For out of order games, it should populate thrown darts with all remaining targets`() - { + fun `For out of order games, it should populate thrown darts with all remaining targets`() { val state = makeClockPlayerState(inOrder = false) val dartOne = Dart(5, 1) @@ -186,8 +181,7 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `For in order games, it should not populate thrown darts with all remaining targets`() - { + fun `For in order games, it should not populate thrown darts with all remaining targets`() { val state = makeClockPlayerState(inOrder = true) val dartOne = Dart(5, 1) @@ -200,16 +194,14 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should correctly report out of order targets as hit`() - { + fun `Should correctly report out of order targets as hit`() { val state = makeClockPlayerState(inOrder = false) state.dartThrown(Dart(5, 1)) state.hasHitTarget(5) shouldBe true } @Test - fun `Should not report out of order targets if in ordered mode`() - { + fun `Should not report out of order targets if in ordered mode`() { val state = makeClockPlayerState(inOrder = true) val dartOne = Dart(5, 1) @@ -221,8 +213,7 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should report the correct current target in out of order mode`() - { + fun `Should report the correct current target in out of order mode`() { val state = makeClockPlayerState(inOrder = false) state.dartThrown(Dart(2, 1)) @@ -240,8 +231,7 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should only report on track for brucey if hit in the right order`() - { + fun `Should only report on track for brucey if hit in the right order`() { val state = makeClockPlayerState(inOrder = false) state.dartThrown(Dart(2, 1)) @@ -264,8 +254,7 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `when loading completed rounds, startingScore and clockTargets should be correctly set`() - { + fun `when loading completed rounds, startingScore and clockTargets should be correctly set`() { val darts = listOf(Dart(2, 1), Dart(1, 1), Dart(4, 1)) val state = makeClockPlayerState(inOrder = false) @@ -282,32 +271,62 @@ class TestClockPlayerState: AbstractTest() } @Test - fun `Should report the correct segmentStatus for inOrder mode`() - { + fun `Should report the correct segmentStatus for inOrder mode`() { val state = makeClockPlayerState(inOrder = true) val status = state.getSegmentStatus() - status.scoringSegments.shouldContainExactly(getAllNonMissSegments().filter { it.score == 1 } ) - status.validSegments.shouldContainExactly(getAllNonMissSegments().filterNot { it.score == 1 } ) + status.scoringSegments.shouldContainExactly( + getAllNonMissSegments().filter { it.score == 1 } + ) + status.validSegments.shouldContainExactly( + getAllNonMissSegments().filterNot { it.score == 1 } + ) state.dartThrown(Dart(1, 1)) val newStatus = state.getSegmentStatus() - newStatus.scoringSegments.shouldContainExactly(getAllNonMissSegments().filter { it.score == 2 } ) - newStatus.validSegments.shouldContainExactly(getAllNonMissSegments().filterNot { it.score == 2 } ) + newStatus.scoringSegments.shouldContainExactly( + getAllNonMissSegments().filter { it.score == 2 } + ) + newStatus.validSegments.shouldContainExactly( + getAllNonMissSegments().filterNot { it.score == 2 } + ) } @Test - fun `Should report the correct segmentStatus for out of order mode`() - { + fun `Should report the correct segmentStatus for out of order mode`() { val state = makeClockPlayerState(inOrder = false) - state.getSegmentStatus().scoringSegments.shouldContainExactly(getAllNonMissSegments().filter { it.score == 1 }) - state.getSegmentStatus().validSegments.shouldContainExactly(getAllNonMissSegments().filterNot { it.score == 25 }) + state + .getSegmentStatus() + .scoringSegments + .shouldContainExactly(getAllNonMissSegments().filter { it.score == 1 }) + state + .getSegmentStatus() + .validSegments + .shouldContainExactly(getAllNonMissSegments().filterNot { it.score == 25 }) state.dartThrown(Dart(2, 1)) - state.getSegmentStatus().scoringSegments.shouldContainExactly(getAllNonMissSegments().filter { it.score == 1 }) - state.getSegmentStatus().validSegments.shouldContainExactly(getAllNonMissSegments().filterNot { it.score == 25 || it.score == 2 }) + state + .getSegmentStatus() + .scoringSegments + .shouldContainExactly(getAllNonMissSegments().filter { it.score == 1 }) + state + .getSegmentStatus() + .validSegments + .shouldContainExactly( + getAllNonMissSegments().filterNot { it.score == 25 || it.score == 2 } + ) state.dartThrown(Dart(1, 1)) - state.getSegmentStatus().scoringSegments.shouldContainExactly(getAllNonMissSegments().filter { it.score == 3 }) - state.getSegmentStatus().validSegments.shouldContainExactly(getAllNonMissSegments().filterNot { it.score == 25 || it.score == 2 || it.score == 1 }) + state + .getSegmentStatus() + .scoringSegments + .shouldContainExactly(getAllNonMissSegments().filter { it.score == 3 }) + state + .getSegmentStatus() + .validSegments + .shouldContainExactly( + getAllNonMissSegments().filterNot { + it.score == 25 || it.score == 2 || it.score == 1 + } + ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/state/TestDartzeePlayerState.kt b/src/test/kotlin/dartzee/game/state/TestDartzeePlayerState.kt index 95b809817..37a094921 100644 --- a/src/test/kotlin/dartzee/game/state/TestDartzeePlayerState.kt +++ b/src/test/kotlin/dartzee/game/state/TestDartzeePlayerState.kt @@ -17,24 +17,26 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.junit.jupiter.api.Test -class TestDartzeePlayerState: AbstractTest() -{ +class TestDartzeePlayerState : AbstractTest() { @Test - fun `Should report a score of 0 when no darts have been thrown`() - { + fun `Should report a score of 0 when no darts have been thrown`() { val state = makeDartzeePlayerState(completedRounds = emptyList()) state.getScoreSoFar() shouldBe 0 } @Test - fun `Should correctly calculate the cumulative score for a given round`() - { + fun `Should correctly calculate the cumulative score for a given round`() { val scoringRound = listOf(Dart(20, 1), Dart(7, 3), Dart(19, 1)) val resultTwo = DartzeeRoundResult(1, false, -30) val resultThree = DartzeeRoundResult(7, true, 75) val resultFour = DartzeeRoundResult(2, false, -52) val resultFive = DartzeeRoundResult(3, true, 50) - val state = makeDartzeePlayerState(completedRounds = listOf(scoringRound, emptyList(), emptyList(), emptyList(), emptyList()), roundResults = listOf(resultTwo, resultThree, resultFour, resultFive)) + val state = + makeDartzeePlayerState( + completedRounds = + listOf(scoringRound, emptyList(), emptyList(), emptyList(), emptyList()), + roundResults = listOf(resultTwo, resultThree, resultFour, resultFive) + ) state.getCumulativeScore(1) shouldBe 60 state.getCumulativeScore(2) shouldBe 30 @@ -46,16 +48,14 @@ class TestDartzeePlayerState: AbstractTest() } @Test - fun `Should fire state changed`() - { + fun `Should fire state changed`() { val state = makeDartzeePlayerState() state.shouldFireStateChange { it.addRoundResult(DartzeeRoundResultEntity()) } state.shouldFireStateChange { it.saveRoundResult(DartzeeRoundResult(1, true, 100)) } } @Test - fun `Should save a round result`() - { + fun `Should save a round result`() { val roundOne = listOf(Dart(20, 1), Dart(20, 1), Dart(1, 1)) val roundTwo = listOf(Dart(20, 1), Dart(20, 1), Dart(1, 1)) val state = makeDartzeePlayerState(completedRounds = listOf(roundOne, roundTwo)) @@ -73,10 +73,14 @@ class TestDartzeePlayerState: AbstractTest() } @Test - fun `Should update Halved achievement`() - { + fun `Should update Halved achievement`() { val p = insertPlayer() - insertAchievement(playerId = p.rowId, type = AchievementType.DARTZEE_HALVED, gameIdEarned = randomGuid(), achievementCounter = 50) + insertAchievement( + playerId = p.rowId, + type = AchievementType.DARTZEE_HALVED, + gameIdEarned = randomGuid(), + achievementCounter = 50 + ) val pt = insertParticipant(playerId = p.rowId) val state = makeDartzeePlayerState(pt) @@ -89,10 +93,14 @@ class TestDartzeePlayerState: AbstractTest() } @Test - fun `Should not update Halved achievement if point loss is not higher than existing row`() - { + fun `Should not update Halved achievement if point loss is not higher than existing row`() { val p = insertPlayer() - insertAchievement(playerId = p.rowId, type = AchievementType.DARTZEE_HALVED, gameIdEarned = randomGuid(), achievementCounter = 50) + insertAchievement( + playerId = p.rowId, + type = AchievementType.DARTZEE_HALVED, + gameIdEarned = randomGuid(), + achievementCounter = 50 + ) val pt = insertParticipant(playerId = p.rowId) val state = makeDartzeePlayerState(pt) @@ -105,8 +113,7 @@ class TestDartzeePlayerState: AbstractTest() } @Test - fun `Should not update Halved achievement if round was a success`() - { + fun `Should not update Halved achievement if round was a success`() { val p = insertPlayer() val pt = insertParticipant(playerId = p.rowId) val state = makeDartzeePlayerState(pt) @@ -117,8 +124,7 @@ class TestDartzeePlayerState: AbstractTest() } @Test - fun `Should add loaded round results`() - { + fun `Should add loaded round results`() { val result = DartzeeRoundResult(2, true, 50) val entity = DartzeeRoundResultEntity.factoryAndSave(result, insertParticipant(), 2) @@ -126,4 +132,4 @@ class TestDartzeePlayerState: AbstractTest() state.addRoundResult(entity) state.roundResults.shouldContainExactly(entity) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/state/TestGolfPlayerState.kt b/src/test/kotlin/dartzee/game/state/TestGolfPlayerState.kt index 6598d07d2..0ea2dac95 100644 --- a/src/test/kotlin/dartzee/game/state/TestGolfPlayerState.kt +++ b/src/test/kotlin/dartzee/game/state/TestGolfPlayerState.kt @@ -13,18 +13,15 @@ import dartzee.helper.makeGolfRound import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGolfPlayerState: AbstractTest() -{ +class TestGolfPlayerState : AbstractTest() { @Test - fun `Should report a score of 0 when no darts thrown`() - { + fun `Should report a score of 0 when no darts thrown`() { val state = makeGolfPlayerState() state.getScoreSoFar() shouldBe 0 } @Test - fun `Should only take into account committed darts`() - { + fun `Should only take into account committed darts`() { val state = makeGolfPlayerState() state.dartThrown(makeDart(1, 1, golfHole = 1)) state.dartThrown(makeDart(1, 2, golfHole = 1)) @@ -35,8 +32,7 @@ class TestGolfPlayerState: AbstractTest() } @Test - fun `Should sum the latest dart thrown from each round`() - { + fun `Should sum the latest dart thrown from each round`() { val roundOne = makeGolfRound(1, listOf(makeDart(1, 1), makeDart(1, 3))) val roundTwo = makeGolfRound(2, listOf(makeDart(2, 0), makeDart(2, 1), makeDart(17, 1))) @@ -45,8 +41,7 @@ class TestGolfPlayerState: AbstractTest() } @Test - fun `Should correctly report the score for each individual round`() - { + fun `Should correctly report the score for each individual round`() { val roundOne = makeGolfRound(1, listOf(makeDart(1, 1), makeDart(1, 3))) val roundTwo = makeGolfRound(2, listOf(makeDart(2, 0), makeDart(2, 1), makeDart(17, 1))) @@ -56,8 +51,7 @@ class TestGolfPlayerState: AbstractTest() } @Test - fun `Should calculate subtotals correctly`() - { + fun `Should calculate subtotals correctly`() { val roundOne = makeGolfRound(1, listOf(makeDart(1, 1), makeDart(1, 3))) val roundTwo = makeGolfRound(2, listOf(makeDart(2, 0), makeDart(2, 1), makeDart(17, 1))) val roundThree = makeGolfRound(3, listOf(makeDart(3, 2))) @@ -69,8 +63,7 @@ class TestGolfPlayerState: AbstractTest() } @Test - fun `Should count total hole in ones correctly`() - { + fun `Should count total hole in ones correctly`() { val roundOne = makeGolfRound(1, listOf(drtOuterOne(), drtDoubleOne())) val roundTwo = makeGolfRound(2, listOf(drtMissTwo(), drtInnerTwo())) val roundThree = makeGolfRound(3, listOf(drtDoubleThree())) @@ -81,4 +74,4 @@ class TestGolfPlayerState: AbstractTest() state.dartThrown(drtDoubleFour()) state.countHoleInOnes() shouldBe 3 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/state/TestSingleParticipant.kt b/src/test/kotlin/dartzee/game/state/TestSingleParticipant.kt index 3954e2cb9..c9e106bff 100644 --- a/src/test/kotlin/dartzee/game/state/TestSingleParticipant.kt +++ b/src/test/kotlin/dartzee/game/state/TestSingleParticipant.kt @@ -6,11 +6,9 @@ import dartzee.helper.insertPlayer import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSingleParticipant: AbstractTest() -{ +class TestSingleParticipant : AbstractTest() { @Test - fun `Should always return details about the individual participant`() - { + fun `Should always return details about the individual participant`() { val player = insertPlayer(name = "Alyssa") val pt = insertParticipant(playerId = player.rowId) @@ -22,4 +20,4 @@ class TestSingleParticipant: AbstractTest() singlePt.getParticipantNameHtml(false) shouldBe "Alyssa" singlePt.getParticipantNameHtml(true, pt) shouldBe "Alyssa" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/state/TestTeamParticipant.kt b/src/test/kotlin/dartzee/game/state/TestTeamParticipant.kt index ef830c124..dd9f3c94c 100644 --- a/src/test/kotlin/dartzee/game/state/TestTeamParticipant.kt +++ b/src/test/kotlin/dartzee/game/state/TestTeamParticipant.kt @@ -7,11 +7,9 @@ import dartzee.helper.insertTeam import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestTeamParticipant: AbstractTest() -{ +class TestTeamParticipant : AbstractTest() { @Test - fun `Should return a deterministic team name regardless of player order`() - { + fun `Should return a deterministic team name regardless of player order`() { val p1 = insertPlayer(name = "Alyssa") val p2 = insertPlayer(name = "Leah") @@ -26,8 +24,7 @@ class TestTeamParticipant: AbstractTest() } @Test - fun `Should return team name in throw order`() - { + fun `Should return team name in throw order`() { val p1 = insertPlayer(name = "Alyssa") val p2 = insertPlayer(name = "Leah") @@ -42,8 +39,7 @@ class TestTeamParticipant: AbstractTest() } @Test - fun `Should bold the right player when active`() - { + fun `Should bold the right player when active`() { val p1 = insertPlayer(name = "Alyssa") val p2 = insertPlayer(name = "Leah") @@ -58,8 +54,7 @@ class TestTeamParticipant: AbstractTest() } @Test - fun `Should return the correct participant based on round number`() - { + fun `Should return the correct participant based on round number`() { val pt1 = insertParticipant() val pt2 = insertParticipant() @@ -72,4 +67,4 @@ class TestTeamParticipant: AbstractTest() team.getIndividual(4) shouldBe pt2 team.getIndividual(6) shouldBe pt2 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/game/state/TestX01PlayerState.kt b/src/test/kotlin/dartzee/game/state/TestX01PlayerState.kt index 88f493fcb..ed2fa2141 100644 --- a/src/test/kotlin/dartzee/game/state/TestX01PlayerState.kt +++ b/src/test/kotlin/dartzee/game/state/TestX01PlayerState.kt @@ -18,40 +18,37 @@ import dartzee.`object`.Dart import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestX01PlayerState: AbstractTest() -{ +class TestX01PlayerState : AbstractTest() { @Test - fun `should report correct score if no darts thrown`() - { + fun `should report correct score if no darts thrown`() { val state = makeX01PlayerStateWithRounds(completedRounds = listOf()) state.getScoreSoFar() shouldBe 0 } @Test - fun `should count completed rounds as 3 darts, regardless of how many were actually thrown`() - { + fun `should count completed rounds as 3 darts, regardless of how many were actually thrown`() { val roundOne = listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)) val roundTwo = listOf(Dart(20, 3)) val roundThree = listOf(Dart(20, 1), Dart(20, 2)) - val state = makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) + val state = + makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) state.getScoreSoFar() shouldBe 9 } @Test - fun `Should not count the finishing round as 3 darts if it contains less`() - { + fun `Should not count the finishing round as 3 darts if it contains less`() { val roundOne = listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)) val roundTwo = listOf(Dart(20, 3)) val roundThree = listOf(Dart(20, 1), makeDart(20, 2, startingScore = 40)) - val state = makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) + val state = + makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) state.getScoreSoFar() shouldBe 8 } @Test - fun `should add on darts from the in progress round`() - { + fun `should add on darts from the in progress round`() { val roundOne = listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)) val roundTwo = listOf(Dart(20, 3)) @@ -69,8 +66,7 @@ class TestX01PlayerState: AbstractTest() } @Test - fun `The remaining score should be the starting score if no darts have been thrown`() - { + fun `The remaining score should be the starting score if no darts have been thrown`() { val state = makeX01PlayerStateWithRounds(501, completedRounds = listOf()) state.getRemainingScore() shouldBe 501 @@ -79,16 +75,16 @@ class TestX01PlayerState: AbstractTest() } @Test - fun `Should correctly compute the current remaining score, taking into account busts`() - { - val roundOne = listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)) //121 - val roundTwo = listOf(Dart(20, 3), Dart(20, 3)) //bust, 121 - val roundThree = listOf(Dart(20, 3), Dart(20, 1), Dart(1, 1)) //40 - val roundFour = listOf(Dart(20, 1), Dart(10, 1), Dart(5, 1)) //5 - val roundFive = listOf(Dart(20, 1)) //bust, 5 - val roundSix = listOf(Dart(1, 1)) //4, mercied + fun `Should correctly compute the current remaining score, taking into account busts`() { + val roundOne = listOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)) // 121 + val roundTwo = listOf(Dart(20, 3), Dart(20, 3)) // bust, 121 + val roundThree = listOf(Dart(20, 3), Dart(20, 1), Dart(1, 1)) // 40 + val roundFour = listOf(Dart(20, 1), Dart(10, 1), Dart(5, 1)) // 5 + val roundFive = listOf(Dart(20, 1)) // bust, 5 + val roundSix = listOf(Dart(1, 1)) // 4, mercied - val rounds = makeX01Rounds(301, roundOne, roundTwo, roundThree, roundFour, roundFive, roundSix) + val rounds = + makeX01Rounds(301, roundOne, roundTwo, roundThree, roundFour, roundFive, roundSix) val state = makeX01PlayerStateWithRounds(301, completedRounds = rounds) state.getRemainingScoreForRound(1) shouldBe 121 @@ -102,8 +98,7 @@ class TestX01PlayerState: AbstractTest() } @Test - fun `Should take into account current round when computing the remaining score`() - { + fun `Should take into account current round when computing the remaining score`() { val state = X01PlayerState(301, SingleParticipant(insertParticipant())) state.dartThrown(makeDart(20, 3)) state.dartThrown(makeDart(20, 3)) @@ -123,30 +118,29 @@ class TestX01PlayerState: AbstractTest() } @Test - fun `Should return a bad luck count of 0 if no darts thrown`() - { + fun `Should return a bad luck count of 0 if no darts thrown`() { val state = makeX01PlayerStateWithRounds(completedRounds = emptyList()) state.getBadLuckCount() shouldBe 0 } @Test - fun `Should compute bad luck count correctly based on all thrown darts`() - { - val roundOne = listOf( - makeDart(startingScore = 40, score = 5, multiplier = 2), //bad luck - makeDart(startingScore = 30, score = 10, multiplier = 1), - makeDart(startingScore = 20, score = 15, multiplier = 0) - ) - - val roundTwo = listOf( - makeDart(startingScore = 20, score = 17, multiplier = 2) - ) - - val roundThree = listOf( - makeDart(startingScore = 20, score = 15, multiplier = 2) //bad luck - ) - - val state = makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) + fun `Should compute bad luck count correctly based on all thrown darts`() { + val roundOne = + listOf( + makeDart(startingScore = 40, score = 5, multiplier = 2), // bad luck + makeDart(startingScore = 30, score = 10, multiplier = 1), + makeDart(startingScore = 20, score = 15, multiplier = 0) + ) + + val roundTwo = listOf(makeDart(startingScore = 20, score = 17, multiplier = 2)) + + val roundThree = + listOf( + makeDart(startingScore = 20, score = 15, multiplier = 2) // bad luck + ) + + val state = + makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) state.getBadLuckCount() shouldBe 2 val dart = makeDart(score = 6, multiplier = 2) @@ -159,8 +153,7 @@ class TestX01PlayerState: AbstractTest() } @Test - fun `Should compute bad luck count for the current player`() - { + fun `Should compute bad luck count for the current player`() { val team = insertTeam() val pt1 = insertParticipant(teamId = team.rowId) val pt2 = insertParticipant(teamId = team.rowId) @@ -168,19 +161,16 @@ class TestX01PlayerState: AbstractTest() val roundOne = listOf(drtTrebleTwenty(), drtOuterOne(), drtMissTwenty()) // Get down to 40 - val roundTwo = listOf( - drtDoubleFive(), //bad luck - drtOuterTen(), - drtMissFifteen() - ) + val roundTwo = + listOf( + drtDoubleFive(), // bad luck + drtOuterTen(), + drtMissFifteen() + ) - val roundThree = listOf( - drtDoubleSeventeen() - ) + val roundThree = listOf(drtDoubleSeventeen()) - val roundFour = listOf( - drtDoubleFifteen() - ) + val roundFour = listOf(drtDoubleFifteen()) roundOne.forEach(state::dartThrown) state.commitRound() @@ -200,19 +190,18 @@ class TestX01PlayerState: AbstractTest() } @Test - fun `Should return the last committed round`() - { + fun `Should return the last committed round`() { val roundOne = listOf(Dart(20, 1)) val roundTwo = listOf(Dart(5, 1), Dart(1, 1)) val roundThree = listOf(Dart(20, 1), Dart(20, 1), Dart(5, 1)) - val state = makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) + val state = + makeX01PlayerStateWithRounds(completedRounds = listOf(roundOne, roundTwo, roundThree)) state.getLastRound() shouldBe roundThree } @Test - fun `Should set startingScore on darts as they are added`() - { + fun `Should set startingScore on darts as they are added`() { val state = X01PlayerState(301, SingleParticipant(insertParticipant())) val dartOne = makeDart(20, 1) @@ -229,8 +218,7 @@ class TestX01PlayerState: AbstractTest() } @Test - fun `Should correctly determine whether the current round is completed`() - { + fun `Should correctly determine whether the current round is completed`() { val threeDartRound = listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)) val bustRound = listOf(Dart(20, 3), Dart(20, 3)) val finishedRound = listOf(Dart(17, 3), Dart(25, 2)) @@ -242,10 +230,10 @@ class TestX01PlayerState: AbstractTest() stateWithCurrentRound(incompleteRound).isCurrentRoundComplete() shouldBe false stateWithCurrentRound(emptyList()).isCurrentRoundComplete() shouldBe false } - private fun stateWithCurrentRound(darts: List): X01PlayerState - { + + private fun stateWithCurrentRound(darts: List): X01PlayerState { val state = X01PlayerState(101, SingleParticipant(insertParticipant())) darts.forEach { state.dartThrown(it) } return state } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/AbstractRegistryTest.kt b/src/test/kotlin/dartzee/helper/AbstractRegistryTest.kt index 71f582279..085548666 100644 --- a/src/test/kotlin/dartzee/helper/AbstractRegistryTest.kt +++ b/src/test/kotlin/dartzee/helper/AbstractRegistryTest.kt @@ -4,32 +4,26 @@ import dartzee.utils.PreferenceUtil import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach -abstract class AbstractRegistryTest: AbstractTest() -{ +abstract class AbstractRegistryTest : AbstractTest() { private val hmPreferenceToSetting = mutableMapOf() abstract fun getPreferencesAffected(): List @BeforeEach - fun cachePreferences() - { + fun cachePreferences() { getPreferencesAffected().forEach { hmPreferenceToSetting[it] = PreferenceUtil.getStringValue(it) } } - fun clearPreferences() - { - getPreferencesAffected().forEach { - PreferenceUtil.deleteSetting(it) - } + fun clearPreferences() { + getPreferencesAffected().forEach { PreferenceUtil.deleteSetting(it) } } @AfterEach - fun resetPreferences() - { + fun resetPreferences() { getPreferencesAffected().forEach { PreferenceUtil.saveString(it, hmPreferenceToSetting[it]) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/AbstractTest.kt b/src/test/kotlin/dartzee/helper/AbstractTest.kt index a922b60ac..87da99513 100644 --- a/src/test/kotlin/dartzee/helper/AbstractTest.kt +++ b/src/test/kotlin/dartzee/helper/AbstractTest.kt @@ -31,13 +31,11 @@ const val TEST_DB_DIRECTORY = "Test/Databases" @ExtendWith(BeforeAllTestsExtension::class) @ExtendWith(SwingTestCleanupExtension::class) -open class AbstractTest -{ +open class AbstractTest { val dialogFactory = TestMessageDialogFactory() @BeforeEach - fun beforeEachTest() - { + fun beforeEachTest() { ScreenCache.emptyCache() dialogFactory.reset() clearLogs() @@ -48,8 +46,7 @@ open class AbstractTest mainDatabase.localIdGenerator.clearCache() - if (logDestination.haveRunInsert) - { + if (logDestination.haveRunInsert) { wipeDatabase() logDestination.haveRunInsert = false } @@ -61,14 +58,13 @@ open class AbstractTest } @AfterEach - fun afterEachTest() - { - if (!checkedForExceptions) - { + fun afterEachTest() { + if (!checkedForExceptions) { val errors = getErrorsLogged() - if (errors.isNotEmpty()) - { - fail("Unexpected error(s) were logged during test: ${errors.map { it.toJsonString() } }") + if (errors.isNotEmpty()) { + fail( + "Unexpected error(s) were logged during test: ${errors.map { it.toJsonString() } }" + ) } errorLogged() shouldBe false } @@ -76,20 +72,18 @@ open class AbstractTest checkedForExceptions = false } - fun wipeDatabase() - { + fun wipeDatabase() { DartsDatabaseUtil.getAllEntitiesIncludingVersion().forEach { wipeTable(it.getTableName()) } } fun getLastLog() = flushAndGetLogRecords().last() - fun verifyLog(code: LoggingCode, severity: Severity = Severity.INFO): LogRecord - { - val record = flushAndGetLogRecords().findLast { it.loggingCode == code && it.severity == severity } + fun verifyLog(code: LoggingCode, severity: Severity = Severity.INFO): LogRecord { + val record = + flushAndGetLogRecords().findLast { it.loggingCode == code && it.severity == severity } record.shouldNotBeNull() - if (severity == Severity.ERROR) - { + if (severity == Severity.ERROR) { checkedForExceptions = true } @@ -99,13 +93,11 @@ open class AbstractTest protected fun findLog(code: LoggingCode, severity: Severity = Severity.INFO) = getLogRecordsSoFar().findLast { it.loggingCode == code && it.severity == severity } - fun verifyNoLogs(code: LoggingCode) - { + fun verifyNoLogs(code: LoggingCode) { flushAndGetLogRecords().any { it.loggingCode == code } shouldBe false } - fun errorLogged(): Boolean - { + fun errorLogged(): Boolean { checkedForExceptions = true return getErrorsLogged().isNotEmpty() } @@ -114,14 +106,13 @@ open class AbstractTest fun getLogRecordsSoFar() = logDestination.logRecords.toList() - fun flushAndGetLogRecords(): List - { + fun flushAndGetLogRecords(): List { logger.waitUntilLoggingFinished() return logDestination.logRecords.toList() } - fun clearLogs() - { + + fun clearLogs() { logger.waitUntilLoggingFinished() logDestination.clear() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/BeforeAllTestsExtension.kt b/src/test/kotlin/dartzee/helper/BeforeAllTestsExtension.kt index 28a8572f1..e71e8f2d9 100644 --- a/src/test/kotlin/dartzee/helper/BeforeAllTestsExtension.kt +++ b/src/test/kotlin/dartzee/helper/BeforeAllTestsExtension.kt @@ -7,27 +7,23 @@ import dartzee.logging.LoggerUncaughtExceptionHandler import dartzee.utils.DartsDatabaseUtil import dartzee.utils.Database import dartzee.utils.InjectedThings -import org.junit.jupiter.api.extension.BeforeAllCallback -import org.junit.jupiter.api.extension.ExtensionContext import java.time.Clock import java.time.ZoneId import javax.swing.UIManager +import org.junit.jupiter.api.extension.BeforeAllCallback +import org.junit.jupiter.api.extension.ExtensionContext var doneOneTimeSetup = false -class BeforeAllTestsExtension: BeforeAllCallback -{ - override fun beforeAll(context: ExtensionContext?) - { - if (!doneOneTimeSetup) - { +class BeforeAllTestsExtension : BeforeAllCallback { + override fun beforeAll(context: ExtensionContext?) { + if (!doneOneTimeSetup) { doOneTimeSetup() doneOneTimeSetup = true } } - private fun doOneTimeSetup() - { + private fun doOneTimeSetup() { DialogUtil.init(TestMessageDialogFactory()) Thread.setDefaultUncaughtExceptionHandler(LoggerUncaughtExceptionHandler()) @@ -41,4 +37,4 @@ class BeforeAllTestsExtension: BeforeAllCallback InjectedThings.mainDatabase = Database(inMemory = true) DartsDatabaseUtil.initialiseDatabase(InjectedThings.mainDatabase) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/DartboardSegmentFactory.kt b/src/test/kotlin/dartzee/helper/DartboardSegmentFactory.kt index 85c5005da..e4a4d8c98 100644 --- a/src/test/kotlin/dartzee/helper/DartboardSegmentFactory.kt +++ b/src/test/kotlin/dartzee/helper/DartboardSegmentFactory.kt @@ -4,6 +4,9 @@ import dartzee.`object`.DartboardSegment import dartzee.`object`.SegmentType fun miss(score: Int) = DartboardSegment(SegmentType.MISS, score) + fun outerSingle(score: Int) = DartboardSegment(SegmentType.OUTER_SINGLE, score) + fun double(score: Int) = DartboardSegment(SegmentType.DOUBLE, score) -fun treble(score: Int) = DartboardSegment(SegmentType.TREBLE, score) \ No newline at end of file + +fun treble(score: Int) = DartboardSegment(SegmentType.TREBLE, score) diff --git a/src/test/kotlin/dartzee/helper/DartsModelFactory.kt b/src/test/kotlin/dartzee/helper/DartsModelFactory.kt index 7eb91a682..c2066eafe 100644 --- a/src/test/kotlin/dartzee/helper/DartsModelFactory.kt +++ b/src/test/kotlin/dartzee/helper/DartsModelFactory.kt @@ -16,51 +16,59 @@ import io.mockk.every import io.mockk.mockk import io.mockk.slot -fun beastDartsModel(standardDeviationDoubles: Double? = null, - standardDeviationCentral: Double? = null, - maxRadius: Int = 450, - scoringDart: Int = 20, - hmScoreToDart: Map = emptyMap(), - mercyThreshold: Int? = null, - hmDartNoToSegmentType: Map = DartsAiModel.DEFAULT_GOLF_SEGMENT_TYPES.toMutableMap(), - hmDartNoToStopThreshold: Map = DartsAiModel.DEFAULT_GOLF_STOP_THRESHOLDS.toMutableMap(), - dartzeePlayStyle: DartzeePlayStyle = DartzeePlayStyle.CAUTIOUS): DartsAiModel -{ +fun beastDartsModel( + standardDeviationDoubles: Double? = null, + standardDeviationCentral: Double? = null, + maxRadius: Int = 450, + scoringDart: Int = 20, + hmScoreToDart: Map = emptyMap(), + mercyThreshold: Int? = null, + hmDartNoToSegmentType: Map = + DartsAiModel.DEFAULT_GOLF_SEGMENT_TYPES.toMutableMap(), + hmDartNoToStopThreshold: Map = + DartsAiModel.DEFAULT_GOLF_STOP_THRESHOLDS.toMutableMap(), + dartzeePlayStyle: DartzeePlayStyle = DartzeePlayStyle.CAUTIOUS +): DartsAiModel { return DartsAiModel( - 0.1, - standardDeviationDoubles, - standardDeviationCentral, - maxRadius, - scoringDart, - hmScoreToDart, - mercyThreshold, - hmDartNoToSegmentType, - hmDartNoToStopThreshold, - dartzeePlayStyle) + 0.1, + standardDeviationDoubles, + standardDeviationCentral, + maxRadius, + scoringDart, + hmScoreToDart, + mercyThreshold, + hmDartNoToSegmentType, + hmDartNoToStopThreshold, + dartzeePlayStyle + ) } -fun makeDartsModel(standardDeviation: Double = 50.0, - standardDeviationDoubles: Double? = null, - standardDeviationCentral: Double? = null, - maxRadius: Int = 250, - scoringDart: Int = 20, - hmScoreToDart: Map = emptyMap(), - mercyThreshold: Int? = null, - hmDartNoToSegmentType: Map = DartsAiModel.DEFAULT_GOLF_SEGMENT_TYPES.toMutableMap(), - hmDartNoToStopThreshold: Map = DartsAiModel.DEFAULT_GOLF_STOP_THRESHOLDS.toMutableMap(), - dartzeePlayStyle: DartzeePlayStyle = DartzeePlayStyle.CAUTIOUS): DartsAiModel -{ +fun makeDartsModel( + standardDeviation: Double = 50.0, + standardDeviationDoubles: Double? = null, + standardDeviationCentral: Double? = null, + maxRadius: Int = 250, + scoringDart: Int = 20, + hmScoreToDart: Map = emptyMap(), + mercyThreshold: Int? = null, + hmDartNoToSegmentType: Map = + DartsAiModel.DEFAULT_GOLF_SEGMENT_TYPES.toMutableMap(), + hmDartNoToStopThreshold: Map = + DartsAiModel.DEFAULT_GOLF_STOP_THRESHOLDS.toMutableMap(), + dartzeePlayStyle: DartzeePlayStyle = DartzeePlayStyle.CAUTIOUS +): DartsAiModel { return DartsAiModel( - standardDeviation, - standardDeviationDoubles, - standardDeviationCentral, - maxRadius, - scoringDart, - hmScoreToDart, - mercyThreshold, - hmDartNoToSegmentType, - hmDartNoToStopThreshold, - dartzeePlayStyle) + standardDeviation, + standardDeviationDoubles, + standardDeviationCentral, + maxRadius, + scoringDart, + hmScoreToDart, + mercyThreshold, + hmDartNoToSegmentType, + hmDartNoToStopThreshold, + dartzeePlayStyle + ) } fun predictableDartsModel( @@ -68,8 +76,7 @@ fun predictableDartsModel( dartzeePlayStyle: DartzeePlayStyle = DartzeePlayStyle.AGGRESSIVE, mercyThreshold: Int? = null, golfStopThresholds: Map? = null, -): DartsAiModel -{ +): DartsAiModel { val defaultModel = DartsAiModel.new() val hmDartNoToStopThreshold = golfStopThresholds ?: defaultModel.hmDartNoToStopThreshold @@ -89,8 +96,7 @@ fun predictableDartsModel( return model } -fun makeThrowDartFn(dartsToThrow: List): () -> ComputedPoint -{ +fun makeThrowDartFn(dartsToThrow: List): () -> ComputedPoint { val remainingDarts = dartsToThrow.toMutableList() val throwDartFn = { val dart = remainingDarts.removeAt(0) @@ -103,24 +109,36 @@ fun makeThrowDartFn(dartsToThrow: List): () -> ComputedPoint } private fun ComputationalDartboard.getMissPoint(score: Int): ComputedPoint { - val pt = translatePoint(computeCenter(), computeRadius() * (UPPER_BOUND_DOUBLE_RATIO + UPPER_BOUND_OUTSIDE_BOARD_RATIO) / 2.0, getAnglesForScore(score).let { (it.first + it.second) / 2.0 }) + val pt = + translatePoint( + computeCenter(), + computeRadius() * (UPPER_BOUND_DOUBLE_RATIO + UPPER_BOUND_OUTSIDE_BOARD_RATIO) / 2.0, + getAnglesForScore(score).let { (it.first + it.second) / 2.0 } + ) return toComputedPoint(pt) } - data class ScoreAndSegmentType(val score: Int, val segmentType: SegmentType) -fun predictableGolfModel(hmDartNoToStopThreshold: Map = DartsAiModel.DEFAULT_GOLF_STOP_THRESHOLDS.toMutableMap(), fn: (hole: Int, dartNo: Int) -> ScoreAndSegmentType): DartsAiModel -{ + +fun predictableGolfModel( + hmDartNoToStopThreshold: Map = + DartsAiModel.DEFAULT_GOLF_STOP_THRESHOLDS.toMutableMap(), + fn: (hole: Int, dartNo: Int) -> ScoreAndSegmentType +): DartsAiModel { val model = mockk(relaxed = true) val stopThresholdSlot = slot() - every { model.getStopThresholdForDartNo(capture(stopThresholdSlot)) } answers { hmDartNoToStopThreshold.getValue(stopThresholdSlot.captured) } + every { model.getStopThresholdForDartNo(capture(stopThresholdSlot)) } answers + { + hmDartNoToStopThreshold.getValue(stopThresholdSlot.captured) + } val holeSlot = slot() val dartNoSlot = slot() - every { model.throwGolfDart(capture(holeSlot), capture(dartNoSlot)) } answers { - val result = fn(holeSlot.captured, dartNoSlot.captured) - getComputedPointForScore(result.score, result.segmentType) - } + every { model.throwGolfDart(capture(holeSlot), capture(dartNoSlot)) } answers + { + val result = fn(holeSlot.captured, dartNoSlot.captured) + getComputedPointForScore(result.score, result.segmentType) + } return model -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/DartzeeTestUtils.kt b/src/test/kotlin/dartzee/helper/DartzeeTestUtils.kt index 108a5b2ac..3c8f75cb3 100644 --- a/src/test/kotlin/dartzee/helper/DartzeeTestUtils.kt +++ b/src/test/kotlin/dartzee/helper/DartzeeTestUtils.kt @@ -33,55 +33,114 @@ import java.awt.image.BufferedImage import javax.swing.ImageIcon import javax.swing.JLabel -val twoBlackOneWhite = makeDartzeeRuleDto(makeColourRule(black = true), makeColourRule(black = true), makeColourRule(white = true), +val twoBlackOneWhite = + makeDartzeeRuleDto( + makeColourRule(black = true), + makeColourRule(black = true), + makeColourRule(white = true), inOrder = false, - calculationResult = makeDartzeeRuleCalculationResult(getAllNonMissSegments().filter { it.getMultiplier() == 1 && it.score != 25 })) - -val scoreEighteens = makeDartzeeRuleDto(makeScoreRule(18), - calculationResult = makeDartzeeRuleCalculationResult(getAllNonMissSegments().filter { it.score == 18 }, - getAllNonMissSegments())) - -val innerOuterInner = makeDartzeeRuleDto(DartzeeDartRuleInner(), DartzeeDartRuleOuter(), DartzeeDartRuleInner(), + calculationResult = + makeDartzeeRuleCalculationResult( + getAllNonMissSegments().filter { it.getMultiplier() == 1 && it.score != 25 } + ) + ) + +val scoreEighteens = + makeDartzeeRuleDto( + makeScoreRule(18), + calculationResult = + makeDartzeeRuleCalculationResult( + getAllNonMissSegments().filter { it.score == 18 }, + getAllNonMissSegments() + ) + ) + +val innerOuterInner = + makeDartzeeRuleDto( + DartzeeDartRuleInner(), + DartzeeDartRuleOuter(), + DartzeeDartRuleInner(), inOrder = true, - calculationResult = makeDartzeeRuleCalculationResult(getInnerSegments())) - -val totalIsFifty = makeDartzeeRuleDto(aggregateRule = makeTotalScoreRule(50), - calculationResult = makeDartzeeRuleCalculationResult(getAllNonMissSegments())) - -val allTwenties = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(20), makeScoreRule(20), + calculationResult = makeDartzeeRuleCalculationResult(getInnerSegments()) + ) + +val totalIsFifty = + makeDartzeeRuleDto( + aggregateRule = makeTotalScoreRule(50), + calculationResult = makeDartzeeRuleCalculationResult(getAllNonMissSegments()) + ) + +val allTwenties = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(20), + makeScoreRule(20), inOrder = true, - calculationResult = makeDartzeeRuleCalculationResult(getAllNonMissSegments().filter { it.score == 20 })) + calculationResult = + makeDartzeeRuleCalculationResult(getAllNonMissSegments().filter { it.score == 20 }) + ) val testRules = listOf(twoBlackOneWhite, innerOuterInner, scoreEighteens, totalIsFifty) -fun makeDartzeeRuleDto(dart1Rule: AbstractDartzeeDartRule? = null, - dart2Rule: AbstractDartzeeDartRule? = null, - dart3Rule: AbstractDartzeeDartRule? = null, - aggregateRule: AbstractDartzeeAggregateRule? = null, - inOrder: Boolean = false, - allowMisses: Boolean = false, - calculationResult: DartzeeRuleCalculationResult = makeDartzeeRuleCalculationResult(), - ruleName: String? = null): DartzeeRuleDto -{ - val rule = DartzeeRuleDto(dart1Rule, dart2Rule, dart3Rule, aggregateRule, inOrder, allowMisses, ruleName) +fun makeDartzeeRuleDto( + dart1Rule: AbstractDartzeeDartRule? = null, + dart2Rule: AbstractDartzeeDartRule? = null, + dart3Rule: AbstractDartzeeDartRule? = null, + aggregateRule: AbstractDartzeeAggregateRule? = null, + inOrder: Boolean = false, + allowMisses: Boolean = false, + calculationResult: DartzeeRuleCalculationResult = makeDartzeeRuleCalculationResult(), + ruleName: String? = null +): DartzeeRuleDto { + val rule = + DartzeeRuleDto( + dart1Rule, + dart2Rule, + dart3Rule, + aggregateRule, + inOrder, + allowMisses, + ruleName + ) rule.calculationResult = calculationResult return rule } -fun makeDartzeeRuleCalculationResult(scoringSegments: List = emptyList(), - validSegments: List = scoringSegments, - validCombinations: Int = 10, - allCombinations: Int = 50, - validCombinationProbability: Double = 1.0, - allCombinationsProbability: Double = 6.0) = - DartzeeRuleCalculationResult(scoringSegments, validSegments, validCombinations, allCombinations, validCombinationProbability, allCombinationsProbability) +fun makeDartzeeRuleCalculationResult( + scoringSegments: List = emptyList(), + validSegments: List = scoringSegments, + validCombinations: Int = 10, + allCombinations: Int = 50, + validCombinationProbability: Double = 1.0, + allCombinationsProbability: Double = 6.0 +) = + DartzeeRuleCalculationResult( + scoringSegments, + validSegments, + validCombinations, + allCombinations, + validCombinationProbability, + allCombinationsProbability + ) fun makeDartzeeRuleCalculationResult(percentage: Int) = - DartzeeRuleCalculationResult(emptyList(), emptyList(), 10, 50, percentage.toDouble(), 100.toDouble()) + DartzeeRuleCalculationResult( + emptyList(), + emptyList(), + 10, + 50, + percentage.toDouble(), + 100.toDouble() + ) fun makeScoreRule(score: Int) = DartzeeDartRuleScore().also { it.score = score } -fun makeColourRule(red: Boolean = false, green: Boolean = false, black: Boolean = false, white: Boolean = false): DartzeeDartRuleColour -{ + +fun makeColourRule( + red: Boolean = false, + green: Boolean = false, + black: Boolean = false, + white: Boolean = false +): DartzeeDartRuleColour { val rule = DartzeeDartRuleColour() rule.black = black rule.white = white @@ -90,41 +149,61 @@ fun makeColourRule(red: Boolean = false, green: Boolean = false, black: Boolean return rule } -inline fun makeTotalScoreRule(score: Int) = getAllAggregateRules().find { it is T }.also { (it as T).target = score } +inline fun makeTotalScoreRule(score: Int) = + getAllAggregateRules().find { it is T }.also { (it as T).target = score } -fun getOuterSegments() = getAllNonMissSegments().filter { it.type == SegmentType.DOUBLE || it.type == SegmentType.OUTER_SINGLE }.filter { it.score != 25 } -fun getInnerSegments() = getAllNonMissSegments().filter { it.score == 25 || it.type == SegmentType.TREBLE || it.type == SegmentType.INNER_SINGLE } +fun getOuterSegments() = + getAllNonMissSegments() + .filter { it.type == SegmentType.DOUBLE || it.type == SegmentType.OUTER_SINGLE } + .filter { it.score != 25 } -fun makeRoundResultEntities(vararg roundResult: DartzeeRoundResult): List { +fun getInnerSegments() = + getAllNonMissSegments().filter { + it.score == 25 || it.type == SegmentType.TREBLE || it.type == SegmentType.INNER_SINGLE + } + +fun makeRoundResultEntities( + vararg roundResult: DartzeeRoundResult +): List { val pt = insertParticipant() - return roundResult.mapIndexed { index, result -> DartzeeRoundResultEntity.factoryAndSave(result, pt, index + 2) } + return roundResult.mapIndexed { index, result -> + DartzeeRoundResultEntity.factoryAndSave(result, pt, index + 2) + } } -fun makeDartzeePlayerStateForName(name: String = "Bob", - completedRounds: List> = emptyList(), - roundResults: List = emptyList()): DartzeePlayerState -{ +fun makeDartzeePlayerStateForName( + name: String = "Bob", + completedRounds: List> = emptyList(), + roundResults: List = emptyList() +): DartzeePlayerState { val p = insertPlayer(name = name) val pt = insertParticipant(playerId = p.rowId) return makeDartzeePlayerState(pt, completedRounds, roundResults) } -fun makeDartzeePlayerState(participant: ParticipantEntity = insertParticipant(), - completedRounds: List> = emptyList(), - roundResults: List = emptyList()): DartzeePlayerState -{ +fun makeDartzeePlayerState( + participant: ParticipantEntity = insertParticipant(), + completedRounds: List> = emptyList(), + roundResults: List = emptyList() +): DartzeePlayerState { val resultEntities = makeRoundResultEntities(*roundResults.toTypedArray()) - return DartzeePlayerState(SingleParticipant(participant), completedRounds.toMutableList(), mutableListOf(), false, resultEntities.toMutableList()) + return DartzeePlayerState( + SingleParticipant(participant), + completedRounds.toMutableList(), + mutableListOf(), + false, + resultEntities.toMutableList() + ) } -fun makeSegmentStatuses(scoringSegments: List = getAllPossibleSegments(), - validSegments: List = scoringSegments) - = SegmentStatuses(scoringSegments, validSegments) +fun makeSegmentStatuses( + scoringSegments: List = getAllPossibleSegments(), + validSegments: List = scoringSegments +) = SegmentStatuses(scoringSegments, validSegments) fun PresentationDartboard.markPoints(points: List) = markPoints(toBufferedImage(), points) -private fun markPoints(img: BufferedImage, points: List): JLabel -{ +private fun markPoints(img: BufferedImage, points: List): JLabel { val g = img.graphics as Graphics2D g.color = Color.BLUE g.stroke = BasicStroke(3f) @@ -137,4 +216,4 @@ private fun markPoints(img: BufferedImage, points: List): JLabel lbl.size = Dimension(500, 500) lbl.repaint() return lbl -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/ExitAssertions.kt b/src/test/kotlin/dartzee/helper/ExitAssertions.kt index 9dd53f47a..cf5fadf7a 100644 --- a/src/test/kotlin/dartzee/helper/ExitAssertions.kt +++ b/src/test/kotlin/dartzee/helper/ExitAssertions.kt @@ -4,62 +4,47 @@ import io.kotest.assertions.fail import io.kotest.matchers.shouldBe import java.security.Permission -private class ExitException(val status: Int): SecurityException("Nope") -private class NoExitSecurityManager(val originalSecurityManager: SecurityManager?): SecurityManager() -{ - override fun checkPermission(perm: Permission?) - { +private class ExitException(val status: Int) : SecurityException("Nope") + +private class NoExitSecurityManager(val originalSecurityManager: SecurityManager?) : + SecurityManager() { + override fun checkPermission(perm: Permission?) { originalSecurityManager?.checkPermission(perm) } - override fun checkPermission(perm: Permission?, context: Any?) - { + override fun checkPermission(perm: Permission?, context: Any?) { originalSecurityManager?.checkPermission(perm, context) } - override fun checkExit(status: Int) - { + override fun checkExit(status: Int) { super.checkExit(status) throw ExitException(status) } } - -fun assertExits(expectedStatus: Int, fn: () -> Unit) -{ +fun assertExits(expectedStatus: Int, fn: () -> Unit) { val originalSecurityManager = System.getSecurityManager() System.setSecurityManager(NoExitSecurityManager(originalSecurityManager)) - try - { + try { fn() fail("Expected exitProcess($expectedStatus), but it wasn't called") - } - catch (e: ExitException) - { + } catch (e: ExitException) { e.status shouldBe expectedStatus - } - finally - { + } finally { System.setSecurityManager(originalSecurityManager) } } -fun assertDoesNotExit(fn: () -> Unit) -{ +fun assertDoesNotExit(fn: () -> Unit) { val originalSecurityManager = System.getSecurityManager() System.setSecurityManager(NoExitSecurityManager(originalSecurityManager)) - try - { + try { fn() - } - catch (e: ExitException) - { + } catch (e: ExitException) { fail("Called exitProcess(${e.status})") - } - finally - { + } finally { System.setSecurityManager(originalSecurityManager) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/FakeDartzeeCalculator.kt b/src/test/kotlin/dartzee/helper/FakeDartzeeCalculator.kt index d1f323214..3d8c04524 100644 --- a/src/test/kotlin/dartzee/helper/FakeDartzeeCalculator.kt +++ b/src/test/kotlin/dartzee/helper/FakeDartzeeCalculator.kt @@ -10,32 +10,36 @@ import dartzee.`object`.SegmentType /** * Fast calculator for tests which assumes that the rule is always: * - * Inner single 1 -> Inner single 2 -> Inner single 3 + * Inner single 1 -> Inner single 2 -> Inner single 3 */ -class FakeDartzeeCalculator: IDartzeeCalculator -{ - override fun getValidSegments(rule: DartzeeRuleDto, dartsSoFar: List): DartzeeRuleCalculationResult - { +class FakeDartzeeCalculator : IDartzeeCalculator { + override fun getValidSegments( + rule: DartzeeRuleDto, + dartsSoFar: List + ): DartzeeRuleCalculationResult { val segments = mutableListOf() - if (isValidSoFar(dartsSoFar)) - { + if (isValidSoFar(dartsSoFar)) { val nextSegment = getFakeValidSegment(dartsSoFar.size) segments.add(nextSegment) } - if (rule.allowMisses) - { + if (rule.allowMisses) { segments.add(DartboardSegment(SegmentType.MISS, 20)) } - return DartzeeRuleCalculationResult(segments, segments, segments.size, 10, 1.0 + dartsSoFar.size, 10.0) + return DartzeeRuleCalculationResult( + segments, + segments, + segments.size, + 10, + 1.0 + dartsSoFar.size, + 10.0 + ) } - private fun isValidSoFar(dartsSoFar: List): Boolean - { + private fun isValidSoFar(dartsSoFar: List): Boolean { dartsSoFar.forEachIndexed { ix, drt -> - if (drt.score != ix + 1 || drt.segmentType != SegmentType.INNER_SINGLE) - { + if (drt.score != ix + 1 || drt.segmentType != SegmentType.INNER_SINGLE) { return false } } @@ -44,8 +48,9 @@ class FakeDartzeeCalculator: IDartzeeCalculator } } -fun getFakeValidSegment(dartsThrown: Int) = when (dartsThrown) { - 0 -> DartboardSegment(SegmentType.INNER_SINGLE, 1) - 1 -> DartboardSegment(SegmentType.INNER_SINGLE, 2) - else -> DartboardSegment(SegmentType.INNER_SINGLE, 3) -} \ No newline at end of file +fun getFakeValidSegment(dartsThrown: Int) = + when (dartsThrown) { + 0 -> DartboardSegment(SegmentType.INNER_SINGLE, 1) + 1 -> DartboardSegment(SegmentType.INNER_SINGLE, 2) + else -> DartboardSegment(SegmentType.INNER_SINGLE, 3) + } diff --git a/src/test/kotlin/dartzee/helper/FakeDartzeeFactories.kt b/src/test/kotlin/dartzee/helper/FakeDartzeeFactories.kt index 6b9795acc..27c927501 100644 --- a/src/test/kotlin/dartzee/helper/FakeDartzeeFactories.kt +++ b/src/test/kotlin/dartzee/helper/FakeDartzeeFactories.kt @@ -5,18 +5,18 @@ import dartzee.dartzee.IDartzeeRuleFactory import dartzee.dartzee.IDartzeeSegmentFactory import dartzee.`object`.DartboardSegment -class FakeDartzeeRuleFactory(private val ret: DartzeeRuleDto?): IDartzeeRuleFactory -{ +class FakeDartzeeRuleFactory(private val ret: DartzeeRuleDto?) : IDartzeeRuleFactory { override fun newRule() = ret + override fun amendRule(rule: DartzeeRuleDto) = ret ?: rule } -class FakeDartzeeSegmentFactory(private val desiredSegments: Set): IDartzeeSegmentFactory -{ +class FakeDartzeeSegmentFactory(private val desiredSegments: Set) : + IDartzeeSegmentFactory { var segmentsPassedIn: Set = emptySet() override fun selectSegments(segments: Set): Set { segmentsPassedIn = segments return desiredSegments } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/FakeLogDestination.kt b/src/test/kotlin/dartzee/helper/FakeLogDestination.kt index 1b3f791af..efe98aa43 100644 --- a/src/test/kotlin/dartzee/helper/FakeLogDestination.kt +++ b/src/test/kotlin/dartzee/helper/FakeLogDestination.kt @@ -4,25 +4,21 @@ import dartzee.logging.CODE_SQL import dartzee.logging.ILogDestination import dartzee.logging.LogRecord -class FakeLogDestination: ILogDestination -{ +class FakeLogDestination : ILogDestination { val logRecords: MutableList = mutableListOf() var haveRunInsert = false - override fun log(record: LogRecord) - { + override fun log(record: LogRecord) { logRecords.add(record) - if (record.loggingCode == CODE_SQL && record.message.contains("INSERT")) - { + if (record.loggingCode == CODE_SQL && record.message.contains("INSERT")) { haveRunInsert = true } } override fun contextUpdated(context: Map) {} - fun clear() - { + fun clear() { logRecords.clear() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/GolfGameTestFactory.kt b/src/test/kotlin/dartzee/helper/GolfGameTestFactory.kt index ab9db09f7..215806473 100644 --- a/src/test/kotlin/dartzee/helper/GolfGameTestFactory.kt +++ b/src/test/kotlin/dartzee/helper/GolfGameTestFactory.kt @@ -60,133 +60,155 @@ import java.sql.Timestamp private fun golfFrontNine22Rounds(): List> = listOf( - listOf(drtDoubleOne()), // 1 - listOf(drtOuterFifteen(), drtOuterTwo()), // 4 - listOf(drtDoubleThree()), // 1 - listOf(drtOuterEighteen(), drtMissFour(), drtOuterFour()), // 4 - listOf(drtMissFive(), drtOuterFive()), // 4 - listOf(drtDoubleSix()), // 1 - listOf(drtMissSeven(), drtDoubleSeven()), // 1 - listOf(drtInnerSixteen(), drtDoubleEight()), // 1 - listOf(drtOuterTwelve(), drtTrebleFourteen(), drtMissNine()), // 5 - ).also(::setRoundNumbers) + listOf(drtDoubleOne()), // 1 + listOf(drtOuterFifteen(), drtOuterTwo()), // 4 + listOf(drtDoubleThree()), // 1 + listOf(drtOuterEighteen(), drtMissFour(), drtOuterFour()), // 4 + listOf(drtMissFive(), drtOuterFive()), // 4 + listOf(drtDoubleSix()), // 1 + listOf(drtMissSeven(), drtDoubleSeven()), // 1 + listOf(drtInnerSixteen(), drtDoubleEight()), // 1 + listOf(drtOuterTwelve(), drtTrebleFourteen(), drtMissNine()), // 5 + ) + .also(::setRoundNumbers) -fun golfFrontNine22(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper -{ +fun golfFrontNine22(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper { val rounds = golfFrontNine22Rounds() - return makeGolfGameWrapper(localId, gameParams = "9", expectedScore = 22, dartRounds = rounds, dtStart = dtStart) + return makeGolfGameWrapper( + localId, + gameParams = "9", + expectedScore = 22, + dartRounds = rounds, + dtStart = dtStart + ) } -fun golfFrontNine22EvenRounds(): GameWrapper -{ +fun golfFrontNine22EvenRounds(): GameWrapper { val rounds = golfFrontNine22Rounds().filterIndexed { ix, _ -> ix % 2 != 0 } return makeGameWrapper(gameParams = "9", teamGame = true).also { rounds.forEach { round -> round.forEach(it::addDart) } } } -fun golfFrontNine29(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper -{ - val rounds = listOf( - listOf(drtMissOne(), drtMissTwenty(), drtOuterOne()), // 4 - listOf(drtOuterTwo()), // 4 - listOf(drtOuterThree(), drtOuterThree()), // 4 - listOf(drtOuterEighteen(), drtMissFour(), drtOuterFour()), // 4 - listOf(drtMissFive(), drtTrebleFive()), // 2 - listOf(drtDoubleTen(), drtDoubleSix()), // 1 - listOf(drtMissSeven(), drtOuterNineteen(), drtTrebleSeven()), // 2 - listOf(drtInnerSixteen(), drtOuterSixteen(), drtOuterEight()), // 4 - listOf(drtOuterNine()), // 4 - ) +fun golfFrontNine29(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper { + val rounds = + listOf( + listOf(drtMissOne(), drtMissTwenty(), drtOuterOne()), // 4 + listOf(drtOuterTwo()), // 4 + listOf(drtOuterThree(), drtOuterThree()), // 4 + listOf(drtOuterEighteen(), drtMissFour(), drtOuterFour()), // 4 + listOf(drtMissFive(), drtTrebleFive()), // 2 + listOf(drtDoubleTen(), drtDoubleSix()), // 1 + listOf(drtMissSeven(), drtOuterNineteen(), drtTrebleSeven()), // 2 + listOf(drtInnerSixteen(), drtOuterSixteen(), drtOuterEight()), // 4 + listOf(drtOuterNine()), // 4 + ) - return makeGolfGameWrapper(localId, gameParams = "9", expectedScore = 29, dartRounds = rounds, dtStart = dtStart) + return makeGolfGameWrapper( + localId, + gameParams = "9", + expectedScore = 29, + dartRounds = rounds, + dtStart = dtStart + ) } -fun golfFull31_22(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper -{ - val rounds = listOf( - listOf(drtMissOne(), drtMissTwenty(), drtInnerOne()), // 3 - listOf(drtMissTwo(), drtDoubleTwo()), // 1 - listOf(drtInnerThree()), // 3 - listOf(drtOuterFour(), drtOuterFour()), // 4 - listOf(drtOuterFive(), drtMissFive(), drtMissFive()), // 5 - listOf(drtOuterSix(), drtMissSix(), drtOuterSix()), // 4 - listOf(drtOuterSeven(), drtTrebleSeven()), // 2 - listOf(drtMissEight(), drtOuterEight(), drtOuterSixteen()), // 5 - listOf(drtMissNine(), drtOuterNine()), // 4 - // Halfway - 31 - listOf(drtMissTen(), drtDoubleTen()), // 1 - listOf(drtDoubleEleven()), // 1 - listOf(drtInnerTwelve()), // 3 - listOf(drtMissThirteen(), drtOuterFour(), drtOuterSix()), // 5 - listOf(drtOuterEleven(), drtMissFourteen(), drtMissFourteen()), // 5 - listOf(drtOuterFifteen(), drtOuterTen(), drtOuterFifteen()), // 4 - listOf(drtMissSixteen(), drtDoubleSixteen()), // 1 - listOf(drtMissSeventeen(), drtOuterThree(), drtDoubleSeventeen()), // 1 - listOf(drtDoubleEighteen()), // 1 - ) +fun golfFull31_22(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper { + val rounds = + listOf( + listOf(drtMissOne(), drtMissTwenty(), drtInnerOne()), // 3 + listOf(drtMissTwo(), drtDoubleTwo()), // 1 + listOf(drtInnerThree()), // 3 + listOf(drtOuterFour(), drtOuterFour()), // 4 + listOf(drtOuterFive(), drtMissFive(), drtMissFive()), // 5 + listOf(drtOuterSix(), drtMissSix(), drtOuterSix()), // 4 + listOf(drtOuterSeven(), drtTrebleSeven()), // 2 + listOf(drtMissEight(), drtOuterEight(), drtOuterSixteen()), // 5 + listOf(drtMissNine(), drtOuterNine()), // 4 + // Halfway - 31 + listOf(drtMissTen(), drtDoubleTen()), // 1 + listOf(drtDoubleEleven()), // 1 + listOf(drtInnerTwelve()), // 3 + listOf(drtMissThirteen(), drtOuterFour(), drtOuterSix()), // 5 + listOf(drtOuterEleven(), drtMissFourteen(), drtMissFourteen()), // 5 + listOf(drtOuterFifteen(), drtOuterTen(), drtOuterFifteen()), // 4 + listOf(drtMissSixteen(), drtDoubleSixteen()), // 1 + listOf(drtMissSeventeen(), drtOuterThree(), drtDoubleSeventeen()), // 1 + listOf(drtDoubleEighteen()), // 1 + ) - return makeGolfGameWrapper(localId, gameParams = "18", expectedScore = 53, dartRounds = rounds, dtStart = dtStart) + return makeGolfGameWrapper( + localId, + gameParams = "18", + expectedScore = 53, + dartRounds = rounds, + dtStart = dtStart + ) } -fun golfFull28_29(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper -{ - val rounds = listOf( - listOf(drtMissOne(), drtOuterOne()), // 4 - listOf(drtTrebleTwo()), // 2 - listOf(drtDoubleThree()), // 1 - listOf(drtDoubleFour()), // 1 - listOf(drtMissFive(), drtMissFive(), drtInnerFive()), // 3 - listOf(drtMissSix(), drtOuterSix()), // 4 - listOf(drtOuterSeven()), // 4 - listOf(drtMissEight(), drtOuterSeven(), drtOuterSixteen()), // 5 - listOf(drtMissNine(), drtOuterTwelve(), drtOuterNine()), // 4 - // Halfway - 28 - listOf(drtDoubleTen()), // 1 - listOf(drtOuterEleven()), // 4 - listOf(drtInnerTwelve()), // 3 - listOf(drtOuterThirteen()), // 4 - listOf(drtInnerFourteen()), // 3 - listOf(drtOuterFifteen()), // 4 - listOf(drtMissSixteen(), drtMissSixteen(), drtMissSixteen()), // 5 - listOf(drtMissSeventeen(), drtOuterSeventeen()), // 4 - listOf(drtDoubleEighteen()), // 1 - ) +fun golfFull28_29(localId: Long = 1L, dtStart: Timestamp = Timestamp(1000)): GameWrapper { + val rounds = + listOf( + listOf(drtMissOne(), drtOuterOne()), // 4 + listOf(drtTrebleTwo()), // 2 + listOf(drtDoubleThree()), // 1 + listOf(drtDoubleFour()), // 1 + listOf(drtMissFive(), drtMissFive(), drtInnerFive()), // 3 + listOf(drtMissSix(), drtOuterSix()), // 4 + listOf(drtOuterSeven()), // 4 + listOf(drtMissEight(), drtOuterSeven(), drtOuterSixteen()), // 5 + listOf(drtMissNine(), drtOuterTwelve(), drtOuterNine()), // 4 + // Halfway - 28 + listOf(drtDoubleTen()), // 1 + listOf(drtOuterEleven()), // 4 + listOf(drtInnerTwelve()), // 3 + listOf(drtOuterThirteen()), // 4 + listOf(drtInnerFourteen()), // 3 + listOf(drtOuterFifteen()), // 4 + listOf(drtMissSixteen(), drtMissSixteen(), drtMissSixteen()), // 5 + listOf(drtMissSeventeen(), drtOuterSeventeen()), // 4 + listOf(drtDoubleEighteen()), // 1 + ) - return makeGolfGameWrapper(localId, gameParams = "18", expectedScore = 57, dartRounds = rounds, dtStart = dtStart) + return makeGolfGameWrapper( + localId, + gameParams = "18", + expectedScore = 57, + dartRounds = rounds, + dtStart = dtStart + ) } -fun golfFullOptimal(): Pair> -{ - val rounds = listOf( - listOf(drtDoubleOne()), // 1, from G1 - listOf(drtMissTwo(), drtDoubleTwo()), // 1, from G3 - listOf(drtDoubleThree()), // 1, from G1 - listOf(drtDoubleFour()), // 1, from G4 - listOf(drtMissFive(), drtTrebleFive()), // 2, from G2 - listOf(drtDoubleSix()), // 1, from G1 - listOf(drtMissSeven(), drtDoubleSeven()), // 1, from G1 - listOf(drtInnerSixteen(), drtDoubleEight()), // 1, from G1 - listOf(drtOuterNine()), // 4, from G2 - // Halfway - 13 - listOf(drtDoubleTen()), // 1, from G4 (fewer darts) - listOf(drtDoubleEleven()), // 1, from G3 - listOf(drtInnerTwelve()), // 3, from G3 (equivalent, but G3 happened first) - listOf(drtOuterThirteen()), // 4, from G4 - listOf(drtInnerFourteen()), // 3, from G4 - listOf(drtOuterFifteen()), // 4, from G4 (fewer darts) - listOf(drtMissSixteen(), drtDoubleSixteen()), // 1, from G3 - listOf(drtMissSeventeen(), drtOuterThree(), drtDoubleSeventeen()), // 1, from G3 - listOf(drtDoubleEighteen()), // 1, from G3 - ) +fun golfFullOptimal(): Pair> { + val rounds = + listOf( + listOf(drtDoubleOne()), // 1, from G1 + listOf(drtMissTwo(), drtDoubleTwo()), // 1, from G3 + listOf(drtDoubleThree()), // 1, from G1 + listOf(drtDoubleFour()), // 1, from G4 + listOf(drtMissFive(), drtTrebleFive()), // 2, from G2 + listOf(drtDoubleSix()), // 1, from G1 + listOf(drtMissSeven(), drtDoubleSeven()), // 1, from G1 + listOf(drtInnerSixteen(), drtDoubleEight()), // 1, from G1 + listOf(drtOuterNine()), // 4, from G2 + // Halfway - 13 + listOf(drtDoubleTen()), // 1, from G4 (fewer darts) + listOf(drtDoubleEleven()), // 1, from G3 + listOf(drtInnerTwelve()), // 3, from G3 (equivalent, but G3 happened first) + listOf(drtOuterThirteen()), // 4, from G4 + listOf(drtInnerFourteen()), // 3, from G4 + listOf(drtOuterFifteen()), // 4, from G4 (fewer darts) + listOf(drtMissSixteen(), drtDoubleSixteen()), // 1, from G3 + listOf(drtMissSeventeen(), drtOuterThree(), drtDoubleSeventeen()), // 1, from G3 + listOf(drtDoubleEighteen()), // 1, from G3 + ) return makeGolfGameWrapper(1L, gameParams = "18", expectedScore = 32, dartRounds = rounds) to - listOf(1L, 3L, 1L, 4L, 2L, 1L, 1L, 1L, 2L, 4L, 3L, 3L, 4L, 4L, 4L, 3L, 3L, 3L) + listOf(1L, 3L, 1L, 4L, 2L, 1L, 1L, 1L, 2L, 4L, 3L, 3L, 4L, 4L, 4L, 3L, 3L, 3L) } -fun golfAllMisses(): GameWrapper -{ +fun golfAllMisses(): GameWrapper { val rounds = (1..18).map { listOf(Dart(20, 0), Dart(20, 0), Dart(20, 0)) } return makeGolfGameWrapper(-1, gameParams = "18", expectedScore = 90, dartRounds = rounds) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/InMemoryDatabaseHelper.kt b/src/test/kotlin/dartzee/helper/InMemoryDatabaseHelper.kt index 33a334526..acce86c3f 100644 --- a/src/test/kotlin/dartzee/helper/InMemoryDatabaseHelper.kt +++ b/src/test/kotlin/dartzee/helper/InMemoryDatabaseHelper.kt @@ -36,37 +36,35 @@ import java.sql.Timestamp import java.util.* import javax.sql.rowset.serial.SerialBlob -fun wipeTable(entityName: EntityName) -{ +fun wipeTable(entityName: EntityName) { mainDatabase.executeUpdate("DELETE FROM $entityName") } fun randomGuid() = UUID.randomUUID().toString() -fun insertPlayerForGame(name: String, gameId: String, strategy: String = "foo"): PlayerEntity -{ +fun insertPlayerForGame(name: String, gameId: String, strategy: String = "foo"): PlayerEntity { val player = insertPlayer(name = name, strategy = strategy) insertParticipant(playerId = player.rowId, gameId = gameId) return player } -fun factoryPlayer(name: String): PlayerEntity -{ +fun factoryPlayer(name: String): PlayerEntity { val p = PlayerEntity() p.name = name p.assignRowId() return p } -fun insertDartsMatch(uuid: String = randomGuid(), - database: Database = mainDatabase, - localId: Long = database.generateLocalId(EntityName.DartsMatch), - games: Int = 3, - mode: MatchMode = MatchMode.FIRST_TO, - dtFinish: Timestamp = DateStatics.END_OF_TIME, - matchParams: String = "", - gameParams: String = ""): DartsMatchEntity -{ +fun insertDartsMatch( + uuid: String = randomGuid(), + database: Database = mainDatabase, + localId: Long = database.generateLocalId(EntityName.DartsMatch), + games: Int = 3, + mode: MatchMode = MatchMode.FIRST_TO, + dtFinish: Timestamp = DateStatics.END_OF_TIME, + matchParams: String = "", + gameParams: String = "" +): DartsMatchEntity { val m = DartsMatchEntity(database) m.rowId = uuid m.localId = localId @@ -80,25 +78,32 @@ fun insertDartsMatch(uuid: String = randomGuid(), return m } -fun insertGameForPlayer(player: PlayerEntity, - gameType: GameType = GameType.X01, - finalScore: Int = -1, - dtFinished: Timestamp = DateStatics.END_OF_TIME) -{ +fun insertGameForPlayer( + player: PlayerEntity, + gameType: GameType = GameType.X01, + finalScore: Int = -1, + dtFinished: Timestamp = DateStatics.END_OF_TIME +) { val game = insertGame(gameType = gameType) - insertParticipant(playerId = player.rowId, gameId = game.rowId, finalScore = finalScore, dtFinished = dtFinished) + insertParticipant( + playerId = player.rowId, + gameId = game.rowId, + finalScore = finalScore, + dtFinished = dtFinished + ) } fun insertPlayer(model: DartsAiModel, name: String = "Clive") = - insertPlayer(strategy = model.toJson(), name = name) - -fun insertPlayer(uuid: String = randomGuid(), - name: String = "Clive", - strategy: String = "", - dtDeleted: Timestamp = DateStatics.END_OF_TIME, - playerImageId: String? = null, - database: Database = mainDatabase): PlayerEntity -{ + insertPlayer(strategy = model.toJson(), name = name) + +fun insertPlayer( + uuid: String = randomGuid(), + name: String = "Clive", + strategy: String = "", + dtDeleted: Timestamp = DateStatics.END_OF_TIME, + playerImageId: String? = null, + database: Database = mainDatabase +): PlayerEntity { val p = PlayerEntity(database) p.rowId = uuid p.name = name @@ -110,8 +115,7 @@ fun insertPlayer(uuid: String = randomGuid(), return p } -fun preparePlayers(count: Int): List -{ +fun preparePlayers(count: Int): List { val p1 = insertPlayer(name = "Alice") val p2 = insertPlayer(name = "Bob") val p3 = insertPlayer(name = "Clara") @@ -121,8 +125,13 @@ fun preparePlayers(count: Int): List return listOf(p1, p2, p3, p4, p5).subList(0, count) } -fun insertFinishForPlayer(player: PlayerEntity, finish: Int, dtCreation: Timestamp = getSqlDateNow(), game: GameEntity = insertGame(gameType = GameType.X01), database: Database = mainDatabase): GameEntity -{ +fun insertFinishForPlayer( + player: PlayerEntity, + finish: Int, + dtCreation: Timestamp = getSqlDateNow(), + game: GameEntity = insertGame(gameType = GameType.X01), + database: Database = mainDatabase +): GameEntity { val entity = X01FinishEntity(database) entity.assignRowId() entity.playerId = player.rowId @@ -133,16 +142,17 @@ fun insertFinishForPlayer(player: PlayerEntity, finish: Int, dtCreation: Timesta return game } -fun insertParticipant(uuid: String = randomGuid(), - gameId: String = randomGuid(), - playerId: String = insertPlayer().rowId, - ordinal: Int = 1, - finishingPosition: Int = -1, - finalScore: Int = -1, - dtFinished: Timestamp = DateStatics.END_OF_TIME, - teamId: String = "", - database: Database = mainDatabase): ParticipantEntity -{ +fun insertParticipant( + uuid: String = randomGuid(), + gameId: String = randomGuid(), + playerId: String = insertPlayer().rowId, + ordinal: Int = 1, + finishingPosition: Int = -1, + finalScore: Int = -1, + dtFinished: Timestamp = DateStatics.END_OF_TIME, + teamId: String = "", + database: Database = mainDatabase +): ParticipantEntity { val pe = ParticipantEntity(database) pe.rowId = uuid pe.gameId = gameId @@ -158,14 +168,15 @@ fun insertParticipant(uuid: String = randomGuid(), return pe } -fun insertTeam(uuid: String = randomGuid(), - gameId: String = randomGuid(), - ordinal: Int = 1, - finishingPosition: Int = -1, - finalScore: Int = -1, - dtFinished: Timestamp = DateStatics.END_OF_TIME, - database: Database = mainDatabase): TeamEntity -{ +fun insertTeam( + uuid: String = randomGuid(), + gameId: String = randomGuid(), + ordinal: Int = 1, + finishingPosition: Int = -1, + finalScore: Int = -1, + dtFinished: Timestamp = DateStatics.END_OF_TIME, + database: Database = mainDatabase +): TeamEntity { val t = TeamEntity(database) t.rowId = uuid t.gameId = gameId @@ -179,8 +190,12 @@ fun insertTeam(uuid: String = randomGuid(), return t } -fun insertDart(participant: ParticipantEntity, dart: Dart, dtCreation: Timestamp = getSqlDateNow(), database: Database = mainDatabase) -{ +fun insertDart( + participant: ParticipantEntity, + dart: Dart, + dtCreation: Timestamp = getSqlDateNow(), + database: Database = mainDatabase +) { insertDart( participant, randomGuid(), @@ -191,21 +206,23 @@ fun insertDart(participant: ParticipantEntity, dart: Dart, dtCreation: Timestamp dart.multiplier, dart.segmentType, dtCreation = dtCreation, - database = database) + database = database + ) } -fun insertDart(participant: ParticipantEntity, - uuid: String = randomGuid(), - roundNumber: Int = 1, - ordinal: Int = 1, - startingScore: Int = 501, - score: Int = 20, - multiplier: Int = 3, - segmentType: SegmentType = getSegmentTypeForMultiplier(multiplier), - dtCreation: Timestamp = getSqlDateNow(), - dtLastUpdate: Timestamp = getSqlDateNow(), - database: Database = mainDatabase): DartEntity -{ +fun insertDart( + participant: ParticipantEntity, + uuid: String = randomGuid(), + roundNumber: Int = 1, + ordinal: Int = 1, + startingScore: Int = 501, + score: Int = 20, + multiplier: Int = 3, + segmentType: SegmentType = getSegmentTypeForMultiplier(multiplier), + dtCreation: Timestamp = getSqlDateNow(), + dtLastUpdate: Timestamp = getSqlDateNow(), + database: Database = mainDatabase +): DartEntity { val drt = DartEntity(database) drt.dtCreation = dtCreation drt.rowId = uuid @@ -222,16 +239,16 @@ fun insertDart(participant: ParticipantEntity, return drt } -fun getSegmentTypeForMultiplier(multiplier: Int) = when(multiplier) -{ - 1 -> SegmentType.OUTER_SINGLE - 2 -> SegmentType.DOUBLE - 3 -> SegmentType.TREBLE - else -> SegmentType.MISS -} -fun List>.insertIntoDatabase(player: PlayerEntity, participant: ParticipantEntity) -{ +fun getSegmentTypeForMultiplier(multiplier: Int) = + when (multiplier) { + 1 -> SegmentType.OUTER_SINGLE + 2 -> SegmentType.DOUBLE + 3 -> SegmentType.TREBLE + else -> SegmentType.MISS + } + +fun List>.insertIntoDatabase(player: PlayerEntity, participant: ParticipantEntity) { val state = makeGolfPlayerState(player, participant) forEach { round -> round.forEach(state::dartThrown) @@ -239,15 +256,16 @@ fun List>.insertIntoDatabase(player: PlayerEntity, participant: Parti } } -fun insertDartzeeRoundResult(participant: ParticipantEntity = insertParticipant(), - uuid: String = randomGuid(), - success: Boolean = true, - score: Int = 100, - roundNumber: Int = 2, - ruleNumber: Int = 2, - dtCreation: Timestamp = getSqlDateNow(), - database: Database = mainDatabase): DartzeeRoundResultEntity -{ +fun insertDartzeeRoundResult( + participant: ParticipantEntity = insertParticipant(), + uuid: String = randomGuid(), + success: Boolean = true, + score: Int = 100, + roundNumber: Int = 2, + ruleNumber: Int = 2, + dtCreation: Timestamp = getSqlDateNow(), + database: Database = mainDatabase +): DartzeeRoundResultEntity { val drr = DartzeeRoundResultEntity(database) drr.rowId = uuid drr.playerId = participant.playerId @@ -262,34 +280,48 @@ fun insertDartzeeRoundResult(participant: ParticipantEntity = insertParticipant( return drr } -fun insertGameForReport(uuid: String = randomGuid(), - localId: Long = mainDatabase.generateLocalId(EntityName.Game), - gameType: GameType = GameType.X01, - gameParams: String = "501", - dtFinish: Timestamp = DateStatics.END_OF_TIME, - dartsMatchId: String = "", - matchOrdinal: Int = -1, - dtCreation: Timestamp = getSqlDateNow(), - dtLastUpdate: Timestamp = getSqlDateNow()): GameEntity -{ - val game = insertGame(uuid, mainDatabase, localId, gameType, gameParams, dtFinish, dartsMatchId, matchOrdinal, dtCreation, dtLastUpdate) +fun insertGameForReport( + uuid: String = randomGuid(), + localId: Long = mainDatabase.generateLocalId(EntityName.Game), + gameType: GameType = GameType.X01, + gameParams: String = "501", + dtFinish: Timestamp = DateStatics.END_OF_TIME, + dartsMatchId: String = "", + matchOrdinal: Int = -1, + dtCreation: Timestamp = getSqlDateNow(), + dtLastUpdate: Timestamp = getSqlDateNow() +): GameEntity { + val game = + insertGame( + uuid, + mainDatabase, + localId, + gameType, + gameParams, + dtFinish, + dartsMatchId, + matchOrdinal, + dtCreation, + dtLastUpdate + ) val player = insertPlayer() insertParticipant(gameId = game.rowId, playerId = player.rowId) return game } -fun insertGame(uuid: String = randomGuid(), - database: Database = mainDatabase, - localId: Long = database.generateLocalId(EntityName.Game), - gameType: GameType = GameType.X01, - gameParams: String = "501", - dtFinish: Timestamp = DateStatics.END_OF_TIME, - dartsMatchId: String = "", - matchOrdinal: Int = -1, - dtCreation: Timestamp = getSqlDateNow(), - dtLastUpdate: Timestamp = getSqlDateNow()): GameEntity -{ +fun insertGame( + uuid: String = randomGuid(), + database: Database = mainDatabase, + localId: Long = database.generateLocalId(EntityName.Game), + gameType: GameType = GameType.X01, + gameParams: String = "501", + dtFinish: Timestamp = DateStatics.END_OF_TIME, + dartsMatchId: String = "", + matchOrdinal: Int = -1, + dtCreation: Timestamp = getSqlDateNow(), + dtLastUpdate: Timestamp = getSqlDateNow() +): GameEntity { val ge = GameEntity(database) ge.rowId = uuid ge.localId = localId @@ -305,14 +337,15 @@ fun insertGame(uuid: String = randomGuid(), return ge } -fun insertDartzeeRule(uuid: String = randomGuid(), - entityName: EntityName = EntityName.DartzeeTemplate, - entityId: String = "", - ordinal: Int = 1, - calculationResult: DartzeeRuleCalculationResult = makeDartzeeRuleCalculationResult(), - dtCreation: Timestamp = getSqlDateNow(), - dtLastUpdate: Timestamp = getSqlDateNow()): DartzeeRuleEntity -{ +fun insertDartzeeRule( + uuid: String = randomGuid(), + entityName: EntityName = EntityName.DartzeeTemplate, + entityId: String = "", + ordinal: Int = 1, + calculationResult: DartzeeRuleCalculationResult = makeDartzeeRuleCalculationResult(), + dtCreation: Timestamp = getSqlDateNow(), + dtLastUpdate: Timestamp = getSqlDateNow() +): DartzeeRuleEntity { val de = DartzeeRuleEntity() de.rowId = uuid de.dtCreation = dtCreation @@ -326,11 +359,12 @@ fun insertDartzeeRule(uuid: String = randomGuid(), return de } -fun insertDartzeeTemplate(uuid: String = randomGuid(), - name: String = "Template", - dtCreation: Timestamp = getSqlDateNow(), - dtLastUpdate: Timestamp = getSqlDateNow()): DartzeeTemplateEntity -{ +fun insertDartzeeTemplate( + uuid: String = randomGuid(), + name: String = "Template", + dtCreation: Timestamp = getSqlDateNow(), + dtLastUpdate: Timestamp = getSqlDateNow() +): DartzeeTemplateEntity { val de = DartzeeTemplateEntity() de.rowId = uuid de.dtCreation = dtCreation @@ -341,23 +375,23 @@ fun insertDartzeeTemplate(uuid: String = randomGuid(), return de } -fun insertTemplateAndRule(name: String = "Template"): DartzeeTemplateEntity -{ +fun insertTemplateAndRule(name: String = "Template"): DartzeeTemplateEntity { val template = insertDartzeeTemplate(name = name) insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = template.rowId) insertDartzeeRule(entityName = EntityName.DartzeeTemplate, entityId = template.rowId) return template } -fun insertAchievement(uuid: String = randomGuid(), - playerId: String = randomGuid(), - type: AchievementType = AchievementType.X01_BEST_FINISH, - gameIdEarned: String = "", - achievementCounter: Int = -1, - achievementDetail: String = "", - dtAchieved: Timestamp = getSqlDateNow(), - database: Database = mainDatabase): AchievementEntity -{ +fun insertAchievement( + uuid: String = randomGuid(), + playerId: String = randomGuid(), + type: AchievementType = AchievementType.X01_BEST_FINISH, + gameIdEarned: String = "", + achievementCounter: Int = -1, + achievementDetail: String = "", + dtAchieved: Timestamp = getSqlDateNow(), + database: Database = mainDatabase +): AchievementEntity { val a = AchievementEntity(database) a.rowId = uuid a.playerId = playerId @@ -372,8 +406,10 @@ fun insertAchievement(uuid: String = randomGuid(), return a } -fun insertPlayerImage(resource: String = "BaboOne", database: Database = mainDatabase): PlayerImageEntity -{ +fun insertPlayerImage( + resource: String = "BaboOne", + database: Database = mainDatabase +): PlayerImageEntity { val fileBytes = FileUtil.getByteArrayForResource("/avatars/$resource.png") val pi = PlayerImageEntity(database) pi.assignRowId() @@ -386,58 +422,80 @@ fun insertPlayerImage(resource: String = "BaboOne", database: Database = mainDat return pi } -fun getCountFromTable(table: EntityName, database: Database = mainDatabase) = getCountFromTable(table.name, database) +fun getCountFromTable(table: EntityName, database: Database = mainDatabase) = + getCountFromTable(table.name, database) + fun getCountFromTable(table: String, database: Database = mainDatabase) = database.executeQueryAggregate("SELECT COUNT(1) FROM $table") -/** - * Retrieve - */ +/** Retrieve */ fun retrieveGame() = GameEntity().retrieveEntities().maxByOrNull { it.dtLastUpdate }!! + fun retrieveDart() = DartEntity().retrieveEntities().first() + fun retrieveDartsMatch() = DartsMatchEntity().retrieveEntities().first() + fun retrieveParticipant() = ParticipantEntity().retrieveEntities().first() + fun retrieveAchievement() = AchievementEntity().retrieveEntities().first() -fun retrieveX01Finish() = X01FinishEntity().retrieveEntities().first() + +fun retrieveX01Finish() = X01FinishEntity().retrieveEntities().first() + fun retrieveDeletionAudit() = DeletionAuditEntity().retrieveEntities().first() + fun retrieveTeam() = TeamEntity().retrieveEntities().first() fun getAchievementCount(type: AchievementType) = - mainDatabase.executeQueryAggregate("SELECT COUNT(1) FROM Achievement WHERE AchievementType = '$type'") + mainDatabase.executeQueryAggregate( + "SELECT COUNT(1) FROM Achievement WHERE AchievementType = '$type'" + ) + +fun getAchievementRows(type: AchievementType) = + AchievementEntity().retrieveEntities("AchievementType = '$type'") + +fun retrieveParticipant(gameId: String, playerId: String) = + ParticipantEntity().retrieveEntities("GameId = '$gameId' AND PlayerId = '$playerId'").first() -fun getAchievementRows(type: AchievementType) = AchievementEntity().retrieveEntities("AchievementType = '$type'") -fun retrieveParticipant(gameId: String, playerId: String) = ParticipantEntity().retrieveEntities("GameId = '$gameId' AND PlayerId = '$playerId'").first() +data class AchievementSummary( + val achievementType: AchievementType, + val achievementCounter: Int, + val gameIdEarned: String, + val achievementDetail: String = "" +) -data class AchievementSummary(val achievementType: AchievementType, val achievementCounter: Int, val gameIdEarned: String, val achievementDetail: String = "") -fun retrieveAchievementsForPlayer(playerId: String): List -{ +fun retrieveAchievementsForPlayer(playerId: String): List { val achievements = AchievementEntity.retrieveAchievements(playerId) - return achievements.map { AchievementSummary(it.achievementType, it.achievementCounter, it.gameIdEarned, it.achievementDetail) } + return achievements.map { + AchievementSummary( + it.achievementType, + it.achievementCounter, + it.gameIdEarned, + it.achievementDetail + ) + } } private fun makeInMemoryDatabase(dbName: String = UUID.randomUUID().toString()) = Database(dbName = dbName, inMemory = true).also { it.initialiseConnectionPool(1) } -fun usingInMemoryDatabase(dbName: String = UUID.randomUUID().toString(), - withSchema: Boolean = false, - testBlock: (inMemoryDatabase: Database) -> Unit) -{ +fun usingInMemoryDatabase( + dbName: String = UUID.randomUUID().toString(), + withSchema: Boolean = false, + testBlock: (inMemoryDatabase: Database) -> Unit +) { val db = makeInMemoryDatabase(dbName) - try - { + try { db.getDirectory().mkdirs() - if (withSchema) - { + if (withSchema) { val migrator = DatabaseMigrator(emptyMap()) migrator.migrateToLatest(db, "Test") } testBlock(db) - } - finally - { - // Open a test connection so the tidy-up doesn't freak out if we shut it down in the test block + } finally { + // Open a test connection so the tidy-up doesn't freak out if we shut it down in the test + // block db.testConnection() db.getDirectory().deleteRecursively() @@ -445,25 +503,19 @@ fun usingInMemoryDatabase(dbName: String = UUID.randomUUID().toString(), } } -fun Database.closeConnectionsAndDrop() -{ +fun Database.closeConnectionsAndDrop() { shutDown() - try - { + try { DriverManager.getConnection("${getQualifiedDbName()};drop=true") - } - catch (sqle: SQLException) - { - if (sqle.message != "Database 'memory:$databaseDirectory/$dbName' dropped.") - { + } catch (sqle: SQLException) { + if (sqle.message != "Database 'memory:$databaseDirectory/$dbName' dropped.") { logger.error(LoggingCode("dropInMemoryDatabase"), "Caught: ${sqle.message}", sqle) } } } -fun Database.getTableNames(): List -{ +fun Database.getTableNames(): List { val sb = StringBuilder() sb.append(" SELECT TableName") sb.append(" FROM sys.systables") @@ -471,8 +523,7 @@ fun Database.getTableNames(): List val list = mutableListOf() executeQuery(sb).use { rs -> - while (rs.next()) - { + while (rs.next()) { list.add(rs.getString("TableName")) } } @@ -480,8 +531,7 @@ fun Database.getTableNames(): List return list.toList() } -fun runConversion(fromVersion: Int) -{ +fun runConversion(fromVersion: Int) { val conversions = DatabaseMigrations.getConversionsMap().getValue(fromVersion) conversions.forEach { it(mainDatabase) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/RoundTheClockTestConstants.kt b/src/test/kotlin/dartzee/helper/RoundTheClockTestConstants.kt index feefae8fb..db4a11ed5 100644 --- a/src/test/kotlin/dartzee/helper/RoundTheClockTestConstants.kt +++ b/src/test/kotlin/dartzee/helper/RoundTheClockTestConstants.kt @@ -4,57 +4,124 @@ import dartzee.game.ClockType import dartzee.game.RoundTheClockConfig import dartzee.`object`.Dart -val inOrderGameDarts = makeClockRounds( - true, - Dart(1, 1), Dart(2, 1), Dart(3, 0), - Dart(3, 1), Dart(18, 1), Dart(4, 1), - Dart(5, 0), Dart(5, 2), Dart(6, 1), - Dart(7, 3), Dart(8, 1), Dart(9, 3), Dart(10, 1), - Dart(14, 1), Dart(9, 1), Dart(11, 1), - Dart(12, 1), Dart(13, 1), Dart(11, 1), - Dart(14, 1), Dart(15, 3), Dart(16, 0), - Dart(16, 1), Dart(3, 1), Dart(19, 1), - Dart(17, 1), Dart(18, 2), Dart(19, 1), Dart(20, 3) -) +val inOrderGameDarts = + makeClockRounds( + true, + Dart(1, 1), + Dart(2, 1), + Dart(3, 0), + Dart(3, 1), + Dart(18, 1), + Dart(4, 1), + Dart(5, 0), + Dart(5, 2), + Dart(6, 1), + Dart(7, 3), + Dart(8, 1), + Dart(9, 3), + Dart(10, 1), + Dart(14, 1), + Dart(9, 1), + Dart(11, 1), + Dart(12, 1), + Dart(13, 1), + Dart(11, 1), + Dart(14, 1), + Dart(15, 3), + Dart(16, 0), + Dart(16, 1), + Dart(3, 1), + Dart(19, 1), + Dart(17, 1), + Dart(18, 2), + Dart(19, 1), + Dart(20, 3) + ) -val GAME_WRAPPER_RTC_IN_ORDER = makeGameWrapper( - gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson(), - finalScore = inOrderGameDarts.size -).also { inOrderGameDarts.forEach(it::addDart) } +val GAME_WRAPPER_RTC_IN_ORDER = + makeGameWrapper( + gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson(), + finalScore = inOrderGameDarts.size + ) + .also { inOrderGameDarts.forEach(it::addDart) } -val inOrderGameDarts2 = makeClockRounds( - true, - Dart(20, 1), Dart(18, 1), Dart(5, 1), - Dart(1, 0), Dart(1, 3), Dart(2, 1), - Dart(3, 0), Dart(19, 3), Dart(17, 1), - Dart(3, 1), Dart(4, 1), Dart(5, 1), Dart(6, 1), - Dart(7, 0), Dart(7, 1), Dart(8, 0), - Dart(8, 1), Dart(9, 1), Dart(10, 1), - Dart(14, 1), Dart(11, 1), Dart(12, 2), - Dart(13, 3), Dart(11, 1), Dart(14, 1), - Dart(15, 3), Dart(16, 1), Dart(17, 1), Dart(18, 0), - Dart(18, 0), Dart(18, 1), Dart(19, 1), - Dart(20, 0), Dart(20, 2) -) +val inOrderGameDarts2 = + makeClockRounds( + true, + Dart(20, 1), + Dart(18, 1), + Dart(5, 1), + Dart(1, 0), + Dart(1, 3), + Dart(2, 1), + Dart(3, 0), + Dart(19, 3), + Dart(17, 1), + Dart(3, 1), + Dart(4, 1), + Dart(5, 1), + Dart(6, 1), + Dart(7, 0), + Dart(7, 1), + Dart(8, 0), + Dart(8, 1), + Dart(9, 1), + Dart(10, 1), + Dart(14, 1), + Dart(11, 1), + Dart(12, 2), + Dart(13, 3), + Dart(11, 1), + Dart(14, 1), + Dart(15, 3), + Dart(16, 1), + Dart(17, 1), + Dart(18, 0), + Dart(18, 0), + Dart(18, 1), + Dart(19, 1), + Dart(20, 0), + Dart(20, 2) + ) -val GAME_WRAPPER_RTC_IN_ORDER_2 = makeGameWrapper( - gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson(), - finalScore = inOrderGameDarts2.size -).also { inOrderGameDarts2.forEach(it::addDart) } +val GAME_WRAPPER_RTC_IN_ORDER_2 = + makeGameWrapper( + gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson(), + finalScore = inOrderGameDarts2.size + ) + .also { inOrderGameDarts2.forEach(it::addDart) } -val outOfOrderGameDarts = makeClockRounds( - false, - Dart(14, 1), Dart(11, 1), Dart(9, 1), - Dart(14, 1), Dart(12, 1), Dart(20, 1), - Dart(5, 1), Dart(1, 1), Dart(18, 1), - Dart(2, 1), Dart(3, 1), Dart(7, 3), - Dart(13, 1), Dart(12, 1), Dart(16, 1), - Dart(4, 1), Dart(6, 1), Dart(8, 3), Dart(10, 2), - Dart(17, 1), Dart(2, 1), Dart(15, 1), - Dart(19, 1) -) +val outOfOrderGameDarts = + makeClockRounds( + false, + Dart(14, 1), + Dart(11, 1), + Dart(9, 1), + Dart(14, 1), + Dart(12, 1), + Dart(20, 1), + Dart(5, 1), + Dart(1, 1), + Dart(18, 1), + Dart(2, 1), + Dart(3, 1), + Dart(7, 3), + Dart(13, 1), + Dart(12, 1), + Dart(16, 1), + Dart(4, 1), + Dart(6, 1), + Dart(8, 3), + Dart(10, 2), + Dart(17, 1), + Dart(2, 1), + Dart(15, 1), + Dart(19, 1) + ) -val GAME_WRAPPER_RTC_OUT_OF_ORDER = makeGameWrapper( - gameParams = RoundTheClockConfig(ClockType.Standard, false).toJson(), - finalScore = 23 -).also { outOfOrderGameDarts.forEach(it::addDart) } +val GAME_WRAPPER_RTC_OUT_OF_ORDER = + makeGameWrapper( + gameParams = RoundTheClockConfig(ClockType.Standard, false).toJson(), + finalScore = 23 + ) + .also { outOfOrderGameDarts.forEach(it::addDart) } diff --git a/src/test/kotlin/dartzee/helper/SyncAssertions.kt b/src/test/kotlin/dartzee/helper/SyncAssertions.kt index d2aa96bc4..983555073 100644 --- a/src/test/kotlin/dartzee/helper/SyncAssertions.kt +++ b/src/test/kotlin/dartzee/helper/SyncAssertions.kt @@ -13,8 +13,7 @@ import java.io.File const val REMOTE_NAME = "Goomba" const val REMOTE_NAME_2 = "Koopa" -fun shouldUpdateSyncScreen(testFn: () -> Unit) -{ +fun shouldUpdateSyncScreen(testFn: () -> Unit) { val menuScreen = mockk(relaxed = true) ScreenCache.hmClassToScreen[SyncManagementScreen::class.java] = menuScreen @@ -23,12 +22,12 @@ fun shouldUpdateSyncScreen(testFn: () -> Unit) verify { menuScreen.initialise() } } -fun syncDirectoryShouldNotExist() -{ +fun syncDirectoryShouldNotExist() { File(SYNC_DIR).shouldNotExist() } -fun makeSyncAudit(database: Database) = SyncAuditEntity(database).also { - it.assignRowId() - it.remoteName = REMOTE_NAME -} \ No newline at end of file +fun makeSyncAudit(database: Database) = + SyncAuditEntity(database).also { + it.assignRowId() + it.remoteName = REMOTE_NAME + } diff --git a/src/test/kotlin/dartzee/helper/TestFactory.kt b/src/test/kotlin/dartzee/helper/TestFactory.kt index eb45a063b..45ceb82a9 100644 --- a/src/test/kotlin/dartzee/helper/TestFactory.kt +++ b/src/test/kotlin/dartzee/helper/TestFactory.kt @@ -21,33 +21,33 @@ import dartzee.utils.isBust import io.kotest.matchers.shouldBe import java.sql.Timestamp -fun factoryClockHit(score: Int, multiplier: Int = 1): Dart -{ +fun factoryClockHit(score: Int, multiplier: Int = 1): Dart { val dart = Dart(score, multiplier) dart.startingScore = score return dart } -fun factoryClockMiss(score: Int): Dart -{ +fun factoryClockMiss(score: Int): Dart { val dart = Dart(score, 0) dart.startingScore = score return dart } -fun List.insertDarts(pt: ParticipantEntity, roundNumber: Int) -{ - val entities = mapIndexed { ix, drt -> DartEntity.factory(drt, pt.playerId, pt.rowId, roundNumber, ix) } +fun List.insertDarts(pt: ParticipantEntity, roundNumber: Int) { + val entities = mapIndexed { ix, drt -> + DartEntity.factory(drt, pt.playerId, pt.rowId, roundNumber, ix) + } entities.forEach { it.saveToDatabase() } } -fun makeDart(score: Int = 20, - multiplier: Int = 1, - segmentType: SegmentType = getSegmentTypeForMultiplier(multiplier), - startingScore: Int = -1, - golfHole: Int = -1, - clockTargets: List = emptyList()): Dart -{ +fun makeDart( + score: Int = 20, + multiplier: Int = 1, + segmentType: SegmentType = getSegmentTypeForMultiplier(multiplier), + startingScore: Int = -1, + golfHole: Int = -1, + clockTargets: List = emptyList() +): Dart { val dart = Dart(score, multiplier, segmentType) dart.startingScore = startingScore dart.roundNumber = golfHole @@ -56,15 +56,10 @@ fun makeDart(score: Int = 20, } fun setRoundNumbers(rounds: List>) { - rounds.forEachIndexed { ix, round -> - round.forEach { dart -> - dart.roundNumber = ix + 1 - } - } + rounds.forEachIndexed { ix, round -> round.forEach { dart -> dart.roundNumber = ix + 1 } } } -fun makeGolfRound(golfHole: Int, darts: List): List -{ +fun makeGolfRound(golfHole: Int, darts: List): List { darts.forEachIndexed { ix, drt -> drt.ordinal = ix + 1 drt.roundNumber = golfHole @@ -72,20 +67,16 @@ fun makeGolfRound(golfHole: Int, darts: List): List return darts } -fun makeX01RoundsMap(startingScore: Int = 501, vararg darts: List): HashMapList -{ +fun makeX01RoundsMap(startingScore: Int = 501, vararg darts: List): HashMapList { val rounds = makeX01Rounds(startingScore, *darts) val map = HashMapList() - rounds.forEachIndexed { ix, round -> - map[ix+1] = round.toMutableList() - } + rounds.forEachIndexed { ix, round -> map[ix + 1] = round.toMutableList() } return map } -fun makeX01Round(startingScore: Int = 501, roundNumber: Int = 1, vararg darts: Dart): List -{ +fun makeX01Round(startingScore: Int = 501, roundNumber: Int = 1, vararg darts: Dart): List { var roundScore = startingScore darts.forEachIndexed { dartIx, dart -> dart.startingScore = roundScore @@ -97,23 +88,21 @@ fun makeX01Round(startingScore: Int = 501, roundNumber: Int = 1, vararg darts: D return darts.toList() } -fun makeX01Rounds(startingScore: Int = 501, vararg darts: List): List> -{ +fun makeX01Rounds(startingScore: Int = 501, vararg darts: List): List> { var currentScore = startingScore darts.forEachIndexed { ix, dartRound -> makeX01Round(currentScore, ix + 1, *dartRound.toTypedArray()) val lastDartForRound = dartRound.last() - if (!isBust(lastDartForRound)) - { + if (!isBust(lastDartForRound)) { currentScore = lastDartForRound.startingScore - lastDartForRound.getTotal() } } return darts.toList() } -fun makeX01Rounds(startingScore: Int = 501, vararg darts: Dart): List> -{ + +fun makeX01Rounds(startingScore: Int = 501, vararg darts: Dart): List> { var currentTotal = startingScore darts.forEach { it.startingScore = currentTotal @@ -123,15 +112,16 @@ fun makeX01Rounds(startingScore: Int = 501, vararg darts: Dart): List return darts.toList().chunked(3) } -fun makeClockRounds(inOrder: Boolean, vararg darts: Dart): List -{ +fun makeClockRounds(inOrder: Boolean, vararg darts: Dart): List { val targets: MutableSet = (1..20).toMutableSet() darts.forEach { dart -> dart.startingScore = targets.minOf { it } dart.clockTargets = targets.toList() - val hit = if (inOrder) dart.hitClockTarget(ClockType.Standard) else dart.hitAnyClockTarget(ClockType.Standard) + val hit = + if (inOrder) dart.hitClockTarget(ClockType.Standard) + else dart.hitAnyClockTarget(ClockType.Standard) if (hit) { targets.remove(dart.score) } @@ -140,42 +130,63 @@ fun makeClockRounds(inOrder: Boolean, vararg darts: Dart): List return darts.toList() } -fun makeClockPlayerState(clockType: ClockType = ClockType.Standard, - inOrder: Boolean = true, - isActive: Boolean = false, - player: PlayerEntity = insertPlayer(), - participant: ParticipantEntity = insertParticipant(playerId = player.rowId), - completedRounds: List> = emptyList(), - currentRound: List = emptyList()): ClockPlayerState -{ +fun makeClockPlayerState( + clockType: ClockType = ClockType.Standard, + inOrder: Boolean = true, + isActive: Boolean = false, + player: PlayerEntity = insertPlayer(), + participant: ParticipantEntity = insertParticipant(playerId = player.rowId), + completedRounds: List> = emptyList(), + currentRound: List = emptyList() +): ClockPlayerState { val config = RoundTheClockConfig(clockType, inOrder) completedRounds.flatten().forEach { it.participantId = participant.rowId } - return ClockPlayerState(config, SingleParticipant(participant), completedRounds.toMutableList(), currentRound.toMutableList(), isActive) + return ClockPlayerState( + config, + SingleParticipant(participant), + completedRounds.toMutableList(), + currentRound.toMutableList(), + isActive + ) } -fun makeX01PlayerState(startingScore: Int = 501, - player: PlayerEntity = insertPlayer(), - participant: ParticipantEntity = insertParticipant(playerId = player.rowId), - completedRound: List = listOf()): X01PlayerState = +fun makeX01PlayerState( + startingScore: Int = 501, + player: PlayerEntity = insertPlayer(), + participant: ParticipantEntity = insertParticipant(playerId = player.rowId), + completedRound: List = listOf() +): X01PlayerState = X01PlayerState(startingScore, SingleParticipant(participant), mutableListOf(completedRound)) -fun makeX01PlayerStateWithRounds(startingScore: Int = 501, - player: PlayerEntity = insertPlayer(), - participant: ParticipantEntity = insertParticipant(playerId = player.rowId), - completedRounds: List> = emptyList(), - isActive: Boolean = false): X01PlayerState -{ +fun makeX01PlayerStateWithRounds( + startingScore: Int = 501, + player: PlayerEntity = insertPlayer(), + participant: ParticipantEntity = insertParticipant(playerId = player.rowId), + completedRounds: List> = emptyList(), + isActive: Boolean = false +): X01PlayerState { completedRounds.flatten().forEach { it.participantId = participant.rowId } - return X01PlayerState(startingScore, SingleParticipant(participant), completedRounds.toMutableList(), mutableListOf(), isActive) + return X01PlayerState( + startingScore, + SingleParticipant(participant), + completedRounds.toMutableList(), + mutableListOf(), + isActive + ) } -fun makeGolfPlayerState(player: PlayerEntity = insertPlayer(), - participant: ParticipantEntity = insertParticipant(playerId = player.rowId), - completedRounds: List> = emptyList(), - currentRound: List = emptyList()): GolfPlayerState -{ +fun makeGolfPlayerState( + player: PlayerEntity = insertPlayer(), + participant: ParticipantEntity = insertParticipant(playerId = player.rowId), + completedRounds: List> = emptyList(), + currentRound: List = emptyList() +): GolfPlayerState { completedRounds.flatten().forEach { it.participantId = participant.rowId } - return GolfPlayerState(SingleParticipant(participant), completedRounds.toMutableList(), currentRound.toMutableList()) + return GolfPlayerState( + SingleParticipant(participant), + completedRounds.toMutableList(), + currentRound.toMutableList() + ) } fun makeGameWrapper( @@ -187,37 +198,60 @@ fun makeGameWrapper( dartRounds: HashMapList = HashMapList(), totalRounds: Int = dartRounds.size, teamGame: Boolean = false -) = GameWrapper(localId, gameParams, dtStart, dtFinish, finalScore, teamGame, totalRounds, dartRounds) +) = + GameWrapper( + localId, + gameParams, + dtStart, + dtFinish, + finalScore, + teamGame, + totalRounds, + dartRounds + ) fun makeGolfGameWrapper( localId: Long = 1L, gameParams: String = "18", dartRounds: List>, expectedScore: Int, - dtStart: Timestamp = Timestamp(1000)): GameWrapper -{ + dtStart: Timestamp = Timestamp(1000) +): GameWrapper { val golfRounds = makeGolfRounds(dartRounds) val score = golfRounds.sumOf { it.last().getGolfScore() } score shouldBe expectedScore - val wrapper = makeGameWrapper(localId = localId, gameParams = gameParams, finalScore = score, dtStart = dtStart) + val wrapper = + makeGameWrapper( + localId = localId, + gameParams = gameParams, + finalScore = score, + dtStart = dtStart + ) golfRounds.flatten().forEach(wrapper::addDart) return wrapper } -fun makeGolfRounds(rounds: List>) = rounds.mapIndexed { ix, round -> makeGolfRound(ix+1, round) } +fun makeGolfRounds(rounds: List>) = + rounds.mapIndexed { ix, round -> makeGolfRound(ix + 1, round) } fun makeClockGameWrapper( localId: Long = 1L, config: RoundTheClockConfig = RoundTheClockConfig(ClockType.Standard, true), dartRounds: List = emptyList(), finalScore: Int = -1, - dtStart: Timestamp = Timestamp(1000)): GameWrapper -{ + dtStart: Timestamp = Timestamp(1000) +): GameWrapper { val rounds = makeClockRounds(config.inOrder, *dartRounds.toTypedArray()) - val wrapper = makeGameWrapper(localId = localId, gameParams = config.toJson(), finalScore = finalScore, dtStart = dtStart) + val wrapper = + makeGameWrapper( + localId = localId, + gameParams = config.toJson(), + finalScore = finalScore, + dtStart = dtStart + ) rounds.forEach(wrapper::addDart) return wrapper -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/helper/X01TestConstants.kt b/src/test/kotlin/dartzee/helper/X01TestConstants.kt index d755d90b0..961eee23c 100644 --- a/src/test/kotlin/dartzee/helper/X01TestConstants.kt +++ b/src/test/kotlin/dartzee/helper/X01TestConstants.kt @@ -2,26 +2,30 @@ package dartzee.helper import dartzee.`object`.Dart -private val gameOneRounds = makeX01Rounds( - 301, - listOf(Dart(20, 3), Dart(20, 2), Dart(20, 1)), // 120 (181) - listOf(Dart(20, 1), Dart(5, 1), Dart(20, 1)), // 45 (136) - listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)), // 60 (76) - listOf(Dart(12, 3), Dart(20, 2)) // 76 (0) -) -val GAME_WRAPPER_301_1 = makeGameWrapper(gameParams = "301", finalScore = 11, localId = 1L).also { - gameOneRounds.flatten().forEach(it::addDart) -} +private val gameOneRounds = + makeX01Rounds( + 301, + listOf(Dart(20, 3), Dart(20, 2), Dart(20, 1)), // 120 (181) + listOf(Dart(20, 1), Dart(5, 1), Dart(20, 1)), // 45 (136) + listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1)), // 60 (76) + listOf(Dart(12, 3), Dart(20, 2)) // 76 (0) + ) +val GAME_WRAPPER_301_1 = + makeGameWrapper(gameParams = "301", finalScore = 11, localId = 1L).also { + gameOneRounds.flatten().forEach(it::addDart) + } -private val gameTwoRounds = makeX01Rounds( - 301, - listOf(Dart(5, 1), Dart(20, 1), Dart(20, 1)), // 45 (256) - listOf(Dart(12, 3), Dart(20, 1), Dart(4, 1)), // 60 (196) - listOf(Dart(19, 1), Dart(19, 1), Dart(19, 1)), // 57 (139) - listOf(Dart(1, 0), Dart(1, 1), Dart(1, 0)), // 1 (138) - listOf(Dart(20, 1), Dart(20, 1), Dart(18, 1)), // 58 (80) - listOf(Dart(20, 2), Dart(20, 2)) // 80 (0) -) -val GAME_WRAPPER_301_2 = makeGameWrapper(gameParams = "301", finalScore = 17, localId = 2L).also { - gameTwoRounds.flatten().forEach(it::addDart) -} +private val gameTwoRounds = + makeX01Rounds( + 301, + listOf(Dart(5, 1), Dart(20, 1), Dart(20, 1)), // 45 (256) + listOf(Dart(12, 3), Dart(20, 1), Dart(4, 1)), // 60 (196) + listOf(Dart(19, 1), Dart(19, 1), Dart(19, 1)), // 57 (139) + listOf(Dart(1, 0), Dart(1, 1), Dart(1, 0)), // 1 (138) + listOf(Dart(20, 1), Dart(20, 1), Dart(18, 1)), // 58 (80) + listOf(Dart(20, 2), Dart(20, 2)) // 80 (0) + ) +val GAME_WRAPPER_301_2 = + makeGameWrapper(gameParams = "301", finalScore = 17, localId = 2L).also { + gameTwoRounds.flatten().forEach(it::addDart) + } diff --git a/src/test/kotlin/dartzee/logging/TestElasticsearchPoster.kt b/src/test/kotlin/dartzee/logging/TestElasticsearchPoster.kt index d7cad09f0..d12cf8205 100644 --- a/src/test/kotlin/dartzee/logging/TestElasticsearchPoster.kt +++ b/src/test/kotlin/dartzee/logging/TestElasticsearchPoster.kt @@ -17,7 +17,7 @@ import org.junit.jupiter.api.Assumptions import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestElasticsearchPoster: AbstractTest() { +class TestElasticsearchPoster : AbstractTest() { @Test @Tag("integration") fun `Should report as online`() { @@ -87,11 +87,11 @@ class TestElasticsearchPoster: AbstractTest() { fun `Should log an error if we fail to construct the RestClient, and not attempt to post any logs`() { val poster = makePoster(credentials = null) - //lazy initialisation means we won't hit the error yet + // lazy initialisation means we won't hit the error yet errorLogged() shouldBe false poster.postLog("foo") - //We've attempted to post a log, so we'll hit the RestClient error now + // We've attempted to post a log, so we'll hit the RestClient error now val log = verifyLog(CODE_ELASTICSEARCH_ERROR, Severity.ERROR) log.message shouldBe "Failed to set up RestClient - won't post logs to ES" log.errorObject.shouldBeInstanceOf() @@ -166,6 +166,5 @@ class TestElasticsearchPoster: AbstractTest() { url: String = ELASTICSEARCH_URL, index: String = "unittest", client: RestClient? = null - ) = - ElasticsearchPoster(credentials, url, index, client) -} \ No newline at end of file + ) = ElasticsearchPoster(credentials, url, index, client) +} diff --git a/src/test/kotlin/dartzee/logging/TestLogDestinationElasticsearch.kt b/src/test/kotlin/dartzee/logging/TestLogDestinationElasticsearch.kt index 0a4537db2..41aad81d7 100644 --- a/src/test/kotlin/dartzee/logging/TestLogDestinationElasticsearch.kt +++ b/src/test/kotlin/dartzee/logging/TestLogDestinationElasticsearch.kt @@ -1,34 +1,31 @@ package dartzee.logging -import dartzee.`object`.DartsClient import dartzee.core.helper.verifyNotCalled import dartzee.db.PendingLogsEntity import dartzee.helper.AbstractTest import dartzee.helper.getCountFromTable import dartzee.makeLogRecord -import io.kotest.matchers.shouldBe +import dartzee.`object`.DartsClient import io.kotest.assertions.throwables.shouldNotThrowAny +import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestLogDestinationElasticsearch: AbstractTest() -{ +class TestLogDestinationElasticsearch : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { DartsClient.devMode = false } @Test - fun `Should not post logs in dev mode`() - { + fun `Should not post logs in dev mode`() { DartsClient.devMode = true val poster = mockPoster() @@ -41,8 +38,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should queue up logs to be posted in the next run`() - { + fun `Should queue up logs to be posted in the next run`() { val poster = mockPoster() val dest = makeLogDestination(poster) @@ -63,8 +59,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should remove a log from the queue if it is successful`() - { + fun `Should remove a log from the queue if it is successful`() { val poster = mockPoster() val dest = makeLogDestination(poster) @@ -81,8 +76,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should leave a log on the queue to be reattempted if it fails`() - { + fun `Should leave a log on the queue to be reattempted if it fails`() { val poster = mockPoster(false) val dest = makeLogDestination(poster) @@ -99,8 +93,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should not bother attempting to post any logs if not online`() - { + fun `Should not bother attempting to post any logs if not online`() { val poster = mockPoster(online = false) val dest = makeLogDestination(poster) dest.log(makeLogRecord()) @@ -112,8 +105,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should handle not having a poster if something goes wrong during startup`() - { + fun `Should handle not having a poster if something goes wrong during startup`() { shouldNotThrowAny { val dest = makeLogDestination(null) dest.log(makeLogRecord()) @@ -122,8 +114,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should kick off posting logs immediately`() - { + fun `Should kick off posting logs immediately`() { val poster = mockPoster() val pool = Executors.newScheduledThreadPool(1) val dest = LogDestinationElasticsearch(poster, pool) @@ -139,8 +130,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should schedule the posting of logs`() - { + fun `Should schedule the posting of logs`() { val scheduler = mockk(relaxed = true) val dest = LogDestinationElasticsearch(mockPoster(), scheduler) @@ -150,8 +140,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should read in and delete from the pending logs table`() - { + fun `Should read in and delete from the pending logs table`() { val logJson = makeLogRecord().toJsonString() PendingLogsEntity.factory(logJson).saveToDatabase() @@ -166,8 +155,7 @@ class TestLogDestinationElasticsearch: AbstractTest() } @Test - fun `Should shut down and write out unsent logs`() - { + fun `Should shut down and write out unsent logs`() { val scheduler = mockk(relaxed = true) val dest = makeLogDestination(mockPoster(), scheduler) @@ -183,12 +171,12 @@ class TestLogDestinationElasticsearch: AbstractTest() pendingLogs.first().logJson shouldBe record.toJsonString() } - private fun makeLogDestination(poster: ElasticsearchPoster?, - scheduler: ScheduledExecutorService = mockk(relaxed = true)) = - LogDestinationElasticsearch(poster, scheduler) + private fun makeLogDestination( + poster: ElasticsearchPoster?, + scheduler: ScheduledExecutorService = mockk(relaxed = true) + ) = LogDestinationElasticsearch(poster, scheduler) - private fun mockPoster(success: Boolean = true, online: Boolean = true): ElasticsearchPoster - { + private fun mockPoster(success: Boolean = true, online: Boolean = true): ElasticsearchPoster { val poster = mockk(relaxed = true) every { poster.postLog(any()) } returns success every { poster.isOnline() } returns online diff --git a/src/test/kotlin/dartzee/logging/TestLogDestinationSystemOut.kt b/src/test/kotlin/dartzee/logging/TestLogDestinationSystemOut.kt index f1081c433..a6b91a216 100644 --- a/src/test/kotlin/dartzee/logging/TestLogDestinationSystemOut.kt +++ b/src/test/kotlin/dartzee/logging/TestLogDestinationSystemOut.kt @@ -4,36 +4,37 @@ import dartzee.CURRENT_TIME_STRING import dartzee.helper.AbstractTest import dartzee.makeLogRecord import io.kotest.matchers.string.shouldContain +import java.io.ByteArrayOutputStream +import java.io.PrintStream import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import java.io.ByteArrayOutputStream -import java.io.PrintStream -class TestLogDestinationSystemOut: AbstractTest() -{ +class TestLogDestinationSystemOut : AbstractTest() { private val originalOut = System.out private val newOut = ByteArrayOutputStream() @BeforeEach - fun beforeEach() - { + fun beforeEach() { System.setOut(PrintStream(newOut)) } @AfterEach - fun afterEach() - { + fun afterEach() { System.setOut(originalOut) } @Test - fun `Should log the record to system out`() - { + fun `Should log the record to system out`() { val dest = LogDestinationSystemOut() - val record = makeLogRecord(severity = Severity.INFO, loggingCode = LoggingCode("some.event"), message = "blah") + val record = + makeLogRecord( + severity = Severity.INFO, + loggingCode = LoggingCode("some.event"), + message = "blah" + ) dest.log(record) val output = newOut.toString() @@ -41,12 +42,17 @@ class TestLogDestinationSystemOut: AbstractTest() } @Test - fun `Should print the stack trace for errors`() - { + fun `Should print the stack trace for errors`() { val dest = LogDestinationSystemOut() val error = Throwable("oh no") - val record = makeLogRecord(severity = Severity.ERROR, loggingCode = LoggingCode("some.event"), message = "blah", errorObject = error) + val record = + makeLogRecord( + severity = Severity.ERROR, + loggingCode = LoggingCode("some.event"), + message = "blah", + errorObject = error + ) dest.log(record) val output = newOut.toString() @@ -55,18 +61,20 @@ class TestLogDestinationSystemOut: AbstractTest() } @Test - fun `Should print the stack for a thread dump`() - { + fun `Should print the stack for a thread dump`() { val dest = LogDestinationSystemOut() - val record = makeLogRecord(severity = Severity.INFO, + val record = + makeLogRecord( + severity = Severity.INFO, loggingCode = LoggingCode("some.event"), message = "blah", - keyValuePairs = mapOf(KEY_STACK to "at Something.blah")) + keyValuePairs = mapOf(KEY_STACK to "at Something.blah") + ) dest.log(record) val output = newOut.toString() output shouldContain "$CURRENT_TIME_STRING [some.event] blah" output shouldContain "at Something.blah" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/logging/TestLogRecord.kt b/src/test/kotlin/dartzee/logging/TestLogRecord.kt index e3f2653c0..6f3cec81b 100644 --- a/src/test/kotlin/dartzee/logging/TestLogRecord.kt +++ b/src/test/kotlin/dartzee/logging/TestLogRecord.kt @@ -6,27 +6,23 @@ import dartzee.makeLogRecord import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestLogRecord: AbstractTest() -{ +class TestLogRecord : AbstractTest() { @Test - fun `Should render as a string for the logging console`() - { - val record = makeLogRecord(loggingCode = LoggingCode("some.code"), - message = "This is a log") + fun `Should render as a string for the logging console`() { + val record = + makeLogRecord(loggingCode = LoggingCode("some.code"), message = "This is a log") record.toString() shouldBe "$CURRENT_TIME_STRING [some.code] This is a log" } @Test - fun `Should return NULL if no error object`() - { + fun `Should return NULL if no error object`() { val record = makeLogRecord() record.getThrowableStr() shouldBe null } @Test - fun `Should return the dated stack trace if it exists`() - { + fun `Should return the dated stack trace if it exists`() { val t = Throwable("Boom") val record = makeLogRecord(errorObject = t) @@ -34,11 +30,15 @@ class TestLogRecord: AbstractTest() } @Test - fun `Should convert to valid JSON string`() - { - val record = makeLogRecord(loggingCode = LoggingCode("someEvent"), keyValuePairs = mapOf("devMode" to true, "currentScreen" to null)) + fun `Should convert to valid JSON string`() { + val record = + makeLogRecord( + loggingCode = LoggingCode("someEvent"), + keyValuePairs = mapOf("devMode" to true, "currentScreen" to null) + ) val str = record.toJsonString() - str shouldBe """{"timestamp":"2020-04-13T11:04:00Z","severity":"INFO","loggingCode":"someEvent","message":"A thing happened","devMode":"true","currentScreen":"null"}""" + str shouldBe + """{"timestamp":"2020-04-13T11:04:00Z","severity":"INFO","loggingCode":"someEvent","message":"A thing happened","devMode":"true","currentScreen":"null"}""" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/logging/TestLogger.kt b/src/test/kotlin/dartzee/logging/TestLogger.kt index d00cbf964..bd0b6f7ac 100644 --- a/src/test/kotlin/dartzee/logging/TestLogger.kt +++ b/src/test/kotlin/dartzee/logging/TestLogger.kt @@ -9,14 +9,12 @@ import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.sql.SQLException +import org.junit.jupiter.api.Test -class TestLogger: AbstractTest() -{ +class TestLogger : AbstractTest() { @Test - fun `Should log INFO`() - { + fun `Should log INFO`() { val destination = FakeLogDestination() val logger = Logger(listOf(destination)) @@ -34,8 +32,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should support extra key values when logging INFO`() - { + fun `Should support extra key values when logging INFO`() { val destination = FakeLogDestination() val logger = Logger(listOf(destination)) @@ -53,8 +50,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should log WARN`() - { + fun `Should log WARN`() { val destination = FakeLogDestination() val logger = Logger(listOf(destination)) @@ -72,14 +68,18 @@ class TestLogger: AbstractTest() } @Test - fun `Should log ERROR`() - { + fun `Should log ERROR`() { val destination = FakeLogDestination() val logger = Logger(listOf(destination)) val loggingCode = LoggingCode("bad.thing") val throwable = Throwable("Boo") - logger.error(LoggingCode("bad.thing"), "An exception happened!", throwable, "other.info" to 60) + logger.error( + LoggingCode("bad.thing"), + "An exception happened!", + throwable, + "other.info" to 60 + ) logger.waitUntilLoggingFinished() val record = destination.logRecords.first() @@ -91,8 +91,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should log SQL statements`() - { + fun `Should log SQL statements`() { val destination = FakeLogDestination() val logger = Logger(listOf(destination)) @@ -108,17 +107,18 @@ class TestLogger: AbstractTest() record.message shouldBe sql record.errorObject shouldBe null record.timestamp shouldBe CURRENT_TIME - record.shouldContainKeyValues(KEY_DURATION to 150L, + record.shouldContainKeyValues( + KEY_DURATION to 150L, KEY_GENERIC_SQL to genericSql, KEY_SQL to sql, KEY_ROW_COUNT to 20, KEY_DATABASE_NAME to "some_database", - KEY_STATEMENT_TYPE to "INSERT") + KEY_STATEMENT_TYPE to "INSERT" + ) } @Test - fun `Should log SQLExceptions`() - { + fun `Should log SQLExceptions`() { val sqle = SQLException("Unable to drop table FOO", "State.ROLLBACK", 403) val destination = FakeLogDestination() @@ -136,16 +136,17 @@ class TestLogger: AbstractTest() record.message shouldBe "Caught SQLException for statement: DROP TABLE Foo" record.errorObject shouldBe sqle record.timestamp shouldBe CURRENT_TIME - record.shouldContainKeyValues(KEY_GENERIC_SQL to genericSql, - KEY_SQL to sql, - KEY_SQL_STATE to "State.ROLLBACK", - KEY_ERROR_CODE to 403, - KEY_EXCEPTION_MESSAGE to "Unable to drop table FOO") + record.shouldContainKeyValues( + KEY_GENERIC_SQL to genericSql, + KEY_SQL to sql, + KEY_SQL_STATE to "State.ROLLBACK", + KEY_ERROR_CODE to 403, + KEY_EXCEPTION_MESSAGE to "Unable to drop table FOO" + ) } @Test - fun `Should log progress correctly`() - { + fun `Should log progress correctly`() { val destination = FakeLogDestination() val logger = Logger(listOf(destination)) logger.logProgress(LoggingCode("progress"), 9, 100) @@ -160,8 +161,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should log to all destinations`() - { + fun `Should log to all destinations`() { val destinationOne = FakeLogDestination() val destinationTwo = FakeLogDestination() val logger = Logger(listOf(destinationOne, destinationTwo)) @@ -173,8 +173,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should not log on the current thread, but should be possible to await all logging having finished`() - { + fun `Should not log on the current thread, but should be possible to await all logging having finished`() { val destination = SleepyLogDestination() val logger = Logger(listOf(destination)) @@ -186,8 +185,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should be possible to continue logging after awaiting logging to finish`() - { + fun `Should be possible to continue logging after awaiting logging to finish`() { val destination = SleepyLogDestination() val logger = Logger(listOf(destination)) @@ -201,8 +199,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should automatically include logging context fields`() - { + fun `Should automatically include logging context fields`() { val destination = FakeLogDestination() val logger = Logger(listOf(destination)) @@ -215,8 +212,7 @@ class TestLogger: AbstractTest() } @Test - fun `Should notify destinations when context is updated`() - { + fun `Should notify destinations when context is updated`() { val destination = mockk(relaxed = true) val logger = Logger(listOf(destination)) @@ -226,20 +222,17 @@ class TestLogger: AbstractTest() } } -class SleepyLogDestination: ILogDestination -{ +class SleepyLogDestination : ILogDestination { val logRecords: MutableList = mutableListOf() - override fun log(record: LogRecord) - { + override fun log(record: LogRecord) { Thread.sleep(500) logRecords.add(record) } override fun contextUpdated(context: Map) {} - fun clear() - { + fun clear() { logRecords.clear() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/logging/TestLoggerUncaughtExceptionHandler.kt b/src/test/kotlin/dartzee/logging/TestLoggerUncaughtExceptionHandler.kt index 0ca1249a7..68ef4f018 100644 --- a/src/test/kotlin/dartzee/logging/TestLoggerUncaughtExceptionHandler.kt +++ b/src/test/kotlin/dartzee/logging/TestLoggerUncaughtExceptionHandler.kt @@ -4,16 +4,14 @@ import dartzee.helper.AbstractTest import dartzee.logging.exceptions.ApplicationFault import dartzee.logging.exceptions.WrappedSqlException import dartzee.shouldContainKeyValues -import io.kotest.matchers.string.shouldContain import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test +import io.kotest.matchers.string.shouldContain import java.sql.SQLException +import org.junit.jupiter.api.Test -class TestLoggerUncaughtExceptionHandler: AbstractTest() -{ +class TestLoggerUncaughtExceptionHandler : AbstractTest() { @Test - fun `Should log a single WARN line for suppressed errors`() - { + fun `Should log a single WARN line for suppressed errors`() { val handler = LoggerUncaughtExceptionHandler() val message = "javax.swing.plaf.FontUIResource cannot be cast to class javax.swing.Painter" @@ -23,12 +21,14 @@ class TestLoggerUncaughtExceptionHandler: AbstractTest() val log = verifyLog(CODE_UNCAUGHT_EXCEPTION, Severity.WARN) log.errorObject shouldBe null log.message shouldBe "Suppressing uncaught exception: $ex" - log.shouldContainKeyValues(KEY_THREAD to Thread.currentThread().toString(), KEY_EXCEPTION_MESSAGE to message) + log.shouldContainKeyValues( + KEY_THREAD to Thread.currentThread().toString(), + KEY_EXCEPTION_MESSAGE to message + ) } @Test - fun `Should not suppress errors without a message`() - { + fun `Should not suppress errors without a message`() { val handler = LoggerUncaughtExceptionHandler() val ex = Exception() @@ -36,13 +36,15 @@ class TestLoggerUncaughtExceptionHandler: AbstractTest() val log = verifyLog(CODE_UNCAUGHT_EXCEPTION, Severity.ERROR) log.errorObject shouldBe ex - log.shouldContainKeyValues(KEY_THREAD to Thread.currentThread().toString(), KEY_EXCEPTION_MESSAGE to null) + log.shouldContainKeyValues( + KEY_THREAD to Thread.currentThread().toString(), + KEY_EXCEPTION_MESSAGE to null + ) log.message shouldContain "Uncaught exception: $ex" } @Test - fun `Should not suppress errors with an unrecognised message`() - { + fun `Should not suppress errors with an unrecognised message`() { val t = Thread("Foo") val handler = LoggerUncaughtExceptionHandler() @@ -56,8 +58,7 @@ class TestLoggerUncaughtExceptionHandler: AbstractTest() } @Test - fun `Should log the code and message from an ApplicationFault`() - { + fun `Should log the code and message from an ApplicationFault`() { val t = Thread("Foo") val handler = LoggerUncaughtExceptionHandler() @@ -71,21 +72,27 @@ class TestLoggerUncaughtExceptionHandler: AbstractTest() } @Test - fun `Should log a WrappedSqlException correctly`() - { + fun `Should log a WrappedSqlException correctly`() { val t = Thread("Foo") val handler = LoggerUncaughtExceptionHandler() val sqle = SQLException("Unable to select from table FOO", "State.ROLLBACK", 403) - val ex = WrappedSqlException("SELECT * FROM Foo WHERE Id = 'id'", "SELECT * FROM Foo WHERE Id = ?", sqle) + val ex = + WrappedSqlException( + "SELECT * FROM Foo WHERE Id = 'id'", + "SELECT * FROM Foo WHERE Id = ?", + sqle + ) handler.uncaughtException(t, ex) val log = verifyLog(CODE_SQL_EXCEPTION, Severity.ERROR) log.errorObject shouldBe sqle - log.shouldContainKeyValues(KEY_GENERIC_SQL to "SELECT * FROM Foo WHERE Id = ?", - KEY_SQL to "SELECT * FROM Foo WHERE Id = 'id'", - KEY_SQL_STATE to "State.ROLLBACK", - KEY_ERROR_CODE to 403, - KEY_EXCEPTION_MESSAGE to "Unable to select from table FOO") + log.shouldContainKeyValues( + KEY_GENERIC_SQL to "SELECT * FROM Foo WHERE Id = ?", + KEY_SQL to "SELECT * FROM Foo WHERE Id = 'id'", + KEY_SQL_STATE to "State.ROLLBACK", + KEY_ERROR_CODE to 403, + KEY_EXCEPTION_MESSAGE to "Unable to select from table FOO" + ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/logging/TestLoggingConsole.kt b/src/test/kotlin/dartzee/logging/TestLoggingConsole.kt index 5e620f411..0fb7a0929 100644 --- a/src/test/kotlin/dartzee/logging/TestLoggingConsole.kt +++ b/src/test/kotlin/dartzee/logging/TestLoggingConsole.kt @@ -9,16 +9,14 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.comparables.shouldBeGreaterThan import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.JLabel import javax.swing.text.StyleConstants +import org.junit.jupiter.api.Test -class TestLoggingConsole: AbstractTest() -{ +class TestLoggingConsole : AbstractTest() { @Test - fun `Should separate log records with a new line`() - { + fun `Should separate log records with a new line`() { val recordOne = makeLogRecord(loggingCode = LoggingCode("foo"), message = "log one") val recordTwo = makeLogRecord(loggingCode = LoggingCode("bar"), message = "log two") @@ -31,8 +29,7 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log a regular INFO log in green`() - { + fun `Should log a regular INFO log in green`() { val console = LoggingConsole() val infoLog = makeLogRecord(severity = Severity.INFO) @@ -41,8 +38,7 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log an ERROR log in red`() - { + fun `Should log an ERROR log in red`() { val console = LoggingConsole() val errorLog = makeLogRecord(severity = Severity.ERROR) @@ -51,12 +47,16 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log the error message and stack trace`() - { + fun `Should log the error message and stack trace`() { val console = LoggingConsole() val t = Throwable("Boom") - val errorLog = makeLogRecord(severity = Severity.ERROR, message = "Failed to load screen", errorObject = t) + val errorLog = + makeLogRecord( + severity = Severity.ERROR, + message = "Failed to load screen", + errorObject = t + ) console.log(errorLog) console.getText() shouldContain "Failed to load screen" @@ -67,11 +67,15 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log thread stacks`() - { + fun `Should log thread stacks`() { val console = LoggingConsole() - val threadStackLock = makeLogRecord(severity = Severity.INFO, message = "AWT Thread", keyValuePairs = mapOf(KEY_STACK to "at Foo.bar(58)")) + val threadStackLock = + makeLogRecord( + severity = Severity.INFO, + message = "AWT Thread", + keyValuePairs = mapOf(KEY_STACK to "at Foo.bar(58)") + ) console.log(threadStackLock) console.getText() shouldContain "AWT Thread" @@ -79,8 +83,7 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log SELECT statements in blue`() - { + fun `Should log SELECT statements in blue`() { val console = LoggingConsole() val record = makeLogRecord(loggingCode = CODE_SQL, message = "SELECT * FROM Game") console.log(record) @@ -89,8 +92,7 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log INSERT statements in orange`() - { + fun `Should log INSERT statements in orange`() { val console = LoggingConsole() val record = makeLogRecord(loggingCode = CODE_SQL, message = "INSERT INTO Game") console.log(record) @@ -99,8 +101,7 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log UPDATE statements in orange`() - { + fun `Should log UPDATE statements in orange`() { val console = LoggingConsole() val record = makeLogRecord(loggingCode = CODE_SQL, message = "UPDATE Game") console.log(record) @@ -109,8 +110,7 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log DELETE statements in pink`() - { + fun `Should log DELETE statements in pink`() { val console = LoggingConsole() val record = makeLogRecord(loggingCode = CODE_SQL, message = "DELETE FROM Game") console.log(record) @@ -119,34 +119,33 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should log SQL run on a different DB with a grey background`() - { + fun `Should log SQL run on a different DB with a grey background`() { val console = LoggingConsole() - val record = makeLogRecord(loggingCode = CODE_SQL, message = "DELETE FROM Game", keyValuePairs = mapOf(KEY_DATABASE_NAME to "otherDb")) + val record = + makeLogRecord( + loggingCode = CODE_SQL, + message = "DELETE FROM Game", + keyValuePairs = mapOf(KEY_DATABASE_NAME to "otherDb") + ) console.log(record) console.getBackgroundColour() shouldBe Color.DARK_GRAY } @Test - fun `Should scroll to the bottom when a new log is added`() - { + fun `Should scroll to the bottom when a new log is added`() { val console = LoggingConsole() console.pack() console.scrollPane.verticalScrollBar.value shouldBe 0 - repeat(50) - { - console.log(makeLogRecord()) - } + repeat(50) { console.log(makeLogRecord()) } flushEdt() console.scrollPane.verticalScrollBar.value shouldBeGreaterThan 0 } @Test - fun `Should support clearing the logs`() - { + fun `Should support clearing the logs`() { val console = LoggingConsole() console.log(makeLogRecord()) @@ -156,8 +155,7 @@ class TestLoggingConsole: AbstractTest() } @Test - fun `Should update when logging context changes`() - { + fun `Should update when logging context changes`() { val console = LoggingConsole() console.contextUpdated(mapOf()) console.getAllChildComponentsForType().shouldBeEmpty() @@ -175,24 +173,19 @@ class TestLoggingConsole: AbstractTest() } private fun LoggingConsole.getText(): String = - try - { + try { doc.getText(0, doc.length) - } - catch (t: Throwable) - { + } catch (t: Throwable) { "" } - private fun LoggingConsole.getTextColour(position: Int = 0): Color - { + private fun LoggingConsole.getTextColour(position: Int = 0): Color { val style = doc.getCharacterElement(position) return StyleConstants.getForeground(style.attributes) } - private fun LoggingConsole.getBackgroundColour(): Color - { + + private fun LoggingConsole.getBackgroundColour(): Color { val style = doc.getCharacterElement(0) return StyleConstants.getBackground(style.attributes) } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/logging/TestLoggingUtils.kt b/src/test/kotlin/dartzee/logging/TestLoggingUtils.kt index ada9f8577..994c1532b 100644 --- a/src/test/kotlin/dartzee/logging/TestLoggingUtils.kt +++ b/src/test/kotlin/dartzee/logging/TestLoggingUtils.kt @@ -1,16 +1,14 @@ package dartzee.logging import dartzee.helper.AbstractTest -import io.kotest.matchers.string.shouldContain import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test +import io.kotest.matchers.string.shouldContain import java.sql.SQLException +import org.junit.jupiter.api.Test -class TestLoggingUtils: AbstractTest() -{ +class TestLoggingUtils : AbstractTest() { @Test - fun `Should extract stack trace`() - { + fun `Should extract stack trace`() { var stackTrace = "" val runnable = { val t = Throwable("Boom.") @@ -22,12 +20,12 @@ class TestLoggingUtils: AbstractTest() thread.join() stackTrace shouldContain "java.lang.Throwable: Boom." - stackTrace shouldContain "\tat dartzee.logging.TestLoggingUtils\$Should extract stack trace\$runnable\$1.invoke" + stackTrace shouldContain + "\tat dartzee.logging.TestLoggingUtils\$Should extract stack trace\$runnable\$1.invoke" } @Test - fun `Extracted stack should include cause`() - { + fun `Extracted stack should include cause`() { val cause = KotlinNullPointerException("Oh dear") val t = Throwable("boom", cause) @@ -37,8 +35,7 @@ class TestLoggingUtils: AbstractTest() } @Test - fun `Should include nested SQLExceptions`() - { + fun `Should include nested SQLExceptions`() { val innermostSqle = SQLException("Hard Disk Error") val innerSqle = SQLException("Permission Denied") innerSqle.nextException = innermostSqle @@ -50,11 +47,14 @@ class TestLoggingUtils: AbstractTest() stackTrace.shouldContain("Child: java.sql.SQLException: Permission Denied") stackTrace.shouldContain("Child: java.sql.SQLException: Hard Disk Error") } - + @Test - fun `Should extract a string from a stack trace array`() - { - val stackTrace = arrayOf(StackTraceElement("SomeClass", "doStuff", "SomeClass.kt", 58), StackTraceElement("SomeClass", "maybeDoStuff", "SomeClass.kt", 40)) + fun `Should extract a string from a stack trace array`() { + val stackTrace = + arrayOf( + StackTraceElement("SomeClass", "doStuff", "SomeClass.kt", 58), + StackTraceElement("SomeClass", "maybeDoStuff", "SomeClass.kt", 40) + ) val result = extractThreadStack(stackTrace) val lines = result.lines() diff --git a/src/test/kotlin/dartzee/main/TestApplicationExit.kt b/src/test/kotlin/dartzee/main/TestApplicationExit.kt index 4afa75795..b50a98207 100644 --- a/src/test/kotlin/dartzee/main/TestApplicationExit.kt +++ b/src/test/kotlin/dartzee/main/TestApplicationExit.kt @@ -10,57 +10,48 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JOptionPane +import org.junit.jupiter.api.Test -class TestApplicationExit: AbstractTest() -{ +class TestApplicationExit : AbstractTest() { @Test - fun `Should exit without prompt if no games are open`() - { - assertExits(0) { - exitApplication() - } + fun `Should exit without prompt if no games are open`() { + assertExits(0) { exitApplication() } dialogFactory.questionsShown.shouldBeEmpty() } @Test - fun `Should not exit if there are open windows and user does not confirm`() - { + fun `Should not exit if there are open windows and user does not confirm`() { dialogFactory.questionOption = JOptionPane.NO_OPTION ScreenCache.addDartsGameScreen("foo", mockk(relaxed = true)) - assertDoesNotExit { - exitApplication() - } + assertDoesNotExit { exitApplication() } - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to exit? There are 1 game window(s) still open.") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to exit? There are 1 game window(s) still open." + ) } @Test - fun `Should exit if there are open windows and user does confirms`() - { + fun `Should exit if there are open windows and user does confirms`() { dialogFactory.questionOption = JOptionPane.YES_OPTION ScreenCache.addDartsGameScreen("foo", mockk(relaxed = true)) - assertExits(0) { - exitApplication() - } + assertExits(0) { exitApplication() } - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to exit? There are 1 game window(s) still open.") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to exit? There are 1 game window(s) still open." + ) } @Test - fun `Should shut down the elasticsearch service`() - { + fun `Should shut down the elasticsearch service`() { val mockEsDestination = mockk(relaxed = true) InjectedThings.esDestination = mockEsDestination - assertExits(0) { - exitApplication() - } + assertExits(0) { exitApplication() } verify { mockEsDestination.shutDown() } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/main/TestMainUtil.kt b/src/test/kotlin/dartzee/main/TestMainUtil.kt index 1d7e780c2..41f4e7c29 100644 --- a/src/test/kotlin/dartzee/main/TestMainUtil.kt +++ b/src/test/kotlin/dartzee/main/TestMainUtil.kt @@ -19,25 +19,22 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import io.kotest.matchers.string.shouldNotBeEmpty import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.Test import javax.swing.UIManager import javax.swing.plaf.metal.MetalLookAndFeel import javax.swing.plaf.nimbus.NimbusLookAndFeel +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test -class TestMainUtil: AbstractTest() -{ +class TestMainUtil : AbstractTest() { private val originalDeviceId = instance.get(INSTANCE_STRING_DEVICE_ID, "") @AfterEach - fun afterEach() - { + fun afterEach() { instance.put(INSTANCE_STRING_DEVICE_ID, originalDeviceId) } @Test - fun `Should not attempt to set look and feel for Apple OS`() - { + fun `Should not attempt to set look and feel for Apple OS`() { UIManager.setLookAndFeel(MetalLookAndFeel()) DartsClient.operatingSystem = "Mac" @@ -48,8 +45,7 @@ class TestMainUtil: AbstractTest() } @Test - fun `Should successfully set Nimbus look and feel for other OS`() - { + fun `Should successfully set Nimbus look and feel for other OS`() { UIManager.setLookAndFeel(MetalLookAndFeel()) DartsClient.operatingSystem = "Windows" @@ -61,8 +57,7 @@ class TestMainUtil: AbstractTest() } @Test - fun `Should log an error if it fails to set look and feel`() - { + fun `Should log an error if it fails to set look and feel`() { setLookAndFeel("invalid") val error = verifyLog(CODE_LOOK_AND_FEEL_ERROR, Severity.ERROR) @@ -71,8 +66,7 @@ class TestMainUtil: AbstractTest() } @Test - fun `Should generate a device ID if not present, then return it in subsequent calls`() - { + fun `Should generate a device ID if not present, then return it in subsequent calls`() { instance.remove(INSTANCE_STRING_DEVICE_ID) val deviceId = getDeviceId() @@ -83,23 +77,20 @@ class TestMainUtil: AbstractTest() } @Test - fun `Should just return the value of the device ID in the registry if present`() - { + fun `Should just return the value of the device ID in the registry if present`() { instance.put(INSTANCE_STRING_DEVICE_ID, "foo") getDeviceId() shouldBe "foo" } @Test - fun `Should just return the value for the corresponding system property`() - { + fun `Should just return the value for the corresponding system property`() { System.setProperty("user.name", "some.user") getUsername() shouldBe "some.user" } @Test - fun `Should set up logging context fields`() - { + fun `Should set up logging context fields`() { System.setProperty("user.name", "some.user") instance.put(INSTANCE_STRING_DEVICE_ID, "some.device") DartsClient.operatingSystem = "Windows 10" @@ -107,9 +98,15 @@ class TestMainUtil: AbstractTest() setLoggingContextFields() - val expectedContextFields = mapOf(KEY_USERNAME to "some.user", KEY_DEVICE_ID to "some.device", - KEY_OPERATING_SYSTEM to "Windows 10", KEY_APP_VERSION to DARTS_VERSION_NUMBER, KEY_DEV_MODE to true) + val expectedContextFields = + mapOf( + KEY_USERNAME to "some.user", + KEY_DEVICE_ID to "some.device", + KEY_OPERATING_SYSTEM to "Windows 10", + KEY_APP_VERSION to DARTS_VERSION_NUMBER, + KEY_DEV_MODE to true + ) logger.loggingContext.shouldContainAll(expectedContextFields) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/object/TestCheckoutSuggester.kt b/src/test/kotlin/dartzee/object/TestCheckoutSuggester.kt index 7f4cb915f..ca7f3c6af 100644 --- a/src/test/kotlin/dartzee/object/TestCheckoutSuggester.kt +++ b/src/test/kotlin/dartzee/object/TestCheckoutSuggester.kt @@ -3,20 +3,18 @@ package dartzee.`object` import dartzee.helper.AbstractTest import dartzee.utils.getCheckoutScores import dartzee.utils.sumScore +import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.booleans.shouldBeTrue import io.kotest.matchers.collections.shouldHaveAtMostSize import io.kotest.matchers.collections.shouldHaveSingleElement import io.kotest.matchers.maps.shouldContain import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import io.kotest.assertions.throwables.shouldThrow import org.junit.jupiter.api.Test -class TestCheckoutSuggester: AbstractTest() -{ +class TestCheckoutSuggester : AbstractTest() { @Test - fun `should parse checkouts for one, two or three darts`() - { + fun `should parse checkouts for one, two or three darts`() { val list = listOf("170=T20,T20,D25") val map = CheckoutSuggester.parseCheckouts(list) @@ -27,29 +25,22 @@ class TestCheckoutSuggester: AbstractTest() } @Test - fun `should throw an error if a checkout is invalid`() - { + fun `should throw an error if a checkout is invalid`() { val list = listOf("170=XXX") - shouldThrow{ - CheckoutSuggester.parseCheckouts(list) - } + shouldThrow { CheckoutSuggester.parseCheckouts(list) } } @Test - fun `should return null if no checkout exists`() - { + fun `should return null if no checkout exists`() { CheckoutSuggester.suggestCheckout(180, 3) shouldBe null CheckoutSuggester.suggestCheckout(60, 1) shouldBe null } @Test - fun `should only suggest legitimate checkouts`() - { - for (i in 0..171) - { - for (darts in 1..3) - { + fun `should only suggest legitimate checkouts`() { + for (i in 0..171) { + for (darts in 1..3) { val checkout = CheckoutSuggester.suggestCheckout(i, darts) ?: continue checkout.shouldHaveAtMostSize(darts) @@ -60,13 +51,10 @@ class TestCheckoutSuggester: AbstractTest() } @Test - fun `should have suggestions for everything up to 150`() - { - for (i in 2..150) - { + fun `should have suggestions for everything up to 150`() { + for (i in 2..150) { val checkout = CheckoutSuggester.suggestCheckout(i, 3) - if (checkout == null) - { + if (checkout == null) { println(i) } checkout shouldNotBe null @@ -74,11 +62,10 @@ class TestCheckoutSuggester: AbstractTest() } @Test - fun `should suggest straight doubles when you're on one`() - { - getCheckoutScores().forEach{ + fun `should suggest straight doubles when you're on one`() { + getCheckoutScores().forEach { val checkout = CheckoutSuggester.suggestCheckout(it, 3)!! - checkout.shouldHaveSingleElement(DartHint(it/2, 2)) + checkout.shouldHaveSingleElement(DartHint(it / 2, 2)) } } } diff --git a/src/test/kotlin/dartzee/object/TestComputationalDartboard.kt b/src/test/kotlin/dartzee/object/TestComputationalDartboard.kt index c767ff592..a558ca250 100644 --- a/src/test/kotlin/dartzee/object/TestComputationalDartboard.kt +++ b/src/test/kotlin/dartzee/object/TestComputationalDartboard.kt @@ -5,30 +5,26 @@ import dartzee.bean.PresentationDartboard import dartzee.helper.AbstractTest import dartzee.helper.markPoints import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Tag -import org.junit.jupiter.api.Test import java.awt.Dimension import java.awt.Point +import org.junit.jupiter.api.Tag +import org.junit.jupiter.api.Test -class TestComputationalDartboard: AbstractTest() -{ +class TestComputationalDartboard : AbstractTest() { @Test - fun `Should return the correct radius`() - { + fun `Should return the correct radius`() { val dartboard = ComputationalDartboard(100, 100) dartboard.computeRadius() shouldBe 35 } @Test - fun `Should return the correct center`() - { + fun `Should return the correct center`() { val dartboard = ComputationalDartboard(100, 100) dartboard.computeCenter() shouldBe Point(50, 50) } @Test - fun `Should return the correct deliberate miss point`() - { + fun `Should return the correct deliberate miss point`() { val dartboard = ComputationalDartboard(100, 100) val computedPoint = dartboard.getDeliberateMissPoint() computedPoint.pt shouldBe Point(50, 96) @@ -37,8 +33,7 @@ class TestComputationalDartboard: AbstractTest() } @Test - fun `Should convert to a computed point`() - { + fun `Should convert to a computed point`() { val dartboard = ComputationalDartboard(100, 100) val center = dartboard.toComputedPoint(Point(50, 50)) center.pt shouldBe Point(50, 50) @@ -54,25 +49,25 @@ class TestComputationalDartboard: AbstractTest() @Test @Tag("screenshot") - fun `Should get all the correct aim points`() - { + fun `Should get all the correct aim points`() { val dartboard = ComputationalDartboard(400, 400) val pts = dartboard.getPotentialAimPoints().map { it.point } - val presentationDartboard = PresentationDartboard(WIREFRAME_COLOUR_WRAPPER).also { it.size = Dimension(400, 400) } + val presentationDartboard = + PresentationDartboard(WIREFRAME_COLOUR_WRAPPER).also { it.size = Dimension(400, 400) } val lbl = presentationDartboard.markPoints(pts) lbl.shouldMatchImage("aim points") } @Test @Tag("screenshot") - fun `Should return a sensible individual aim point`() - { + fun `Should return a sensible individual aim point`() { val dartboard = ComputationalDartboard(400, 400) val pt = dartboard.getPointToAimAt(DartboardSegment(SegmentType.INNER_SINGLE, 6)) - val presentationDartboard = PresentationDartboard(WIREFRAME_COLOUR_WRAPPER).also { it.size = Dimension(400, 400) } + val presentationDartboard = + PresentationDartboard(WIREFRAME_COLOUR_WRAPPER).also { it.size = Dimension(400, 400) } val lbl = presentationDartboard.markPoints(listOf(pt.pt)) lbl.shouldMatchImage("inner 6 aim") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/object/TestDart.kt b/src/test/kotlin/dartzee/object/TestDart.kt index e0ed972c1..85098a79e 100644 --- a/src/test/kotlin/dartzee/object/TestDart.kt +++ b/src/test/kotlin/dartzee/object/TestDart.kt @@ -7,27 +7,23 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.junit.jupiter.api.Test -class TestDart: AbstractTest() -{ +class TestDart : AbstractTest() { @Test - fun `Should correctly report a double`() - { + fun `Should correctly report a double`() { Dart(1, 1).isDouble() shouldBe false Dart(1, 2).isDouble() shouldBe true Dart(1, 3).isDouble() shouldBe false } @Test - fun `Should correctly report a treble`() - { + fun `Should correctly report a treble`() { Dart(1, 1).isTreble() shouldBe false Dart(1, 2).isTreble() shouldBe false Dart(1, 3).isTreble() shouldBe true } @Test - fun `Should correctly report the total`() - { + fun `Should correctly report the total`() { Dart(20, 0).getTotal() shouldBe 0 Dart(17, 2).getTotal() shouldBe 34 Dart(19, 3).getTotal() shouldBe 57 @@ -35,10 +31,11 @@ class TestDart: AbstractTest() } @Test - fun `Should correctly report golf score`() - { - makeDart(1, 1, segmentType = SegmentType.OUTER_SINGLE, golfHole = 1).getGolfScore() shouldBe 4 - makeDart(1, 1, segmentType = SegmentType.OUTER_SINGLE, golfHole = 2).getGolfScore() shouldBe 5 + fun `Should correctly report golf score`() { + makeDart(1, 1, segmentType = SegmentType.OUTER_SINGLE, golfHole = 1).getGolfScore() shouldBe + 4 + makeDart(1, 1, segmentType = SegmentType.OUTER_SINGLE, golfHole = 2).getGolfScore() shouldBe + 5 makeDart(3, 0, segmentType = SegmentType.MISS, golfHole = 3).getGolfScore() shouldBe 5 val outerOne = makeDart(1, 1, SegmentType.OUTER_SINGLE) @@ -47,8 +44,7 @@ class TestDart: AbstractTest() } @Test - fun `Should report hit score correctly`() - { + fun `Should report hit score correctly`() { Dart(19, 0).getHitScore() shouldBe 0 Dart(19, 1).getHitScore() shouldBe 19 Dart(19, 2).getHitScore() shouldBe 19 @@ -56,8 +52,7 @@ class TestDart: AbstractTest() } @Test - fun `Should render correctly`() - { + fun `Should render correctly`() { Dart(19, 0).format() shouldBe "0" Dart(19, 1).format() shouldBe "19" Dart(20, 2).format() shouldBe "D20" @@ -67,16 +62,14 @@ class TestDart: AbstractTest() } @Test - fun `Should report the correct segment type to aim for`() - { + fun `Should report the correct segment type to aim for`() { Dart(19, 1).getSegmentTypeToAimAt() shouldBe SegmentType.OUTER_SINGLE Dart(20, 2).getSegmentTypeToAimAt() shouldBe SegmentType.DOUBLE Dart(3, 3).getSegmentTypeToAimAt() shouldBe SegmentType.TREBLE } @Test - fun `equals and hashcode`() - { + fun `equals and hashcode`() { val dart = Dart(2, 3).also { it.ordinal = 1 } val dartMatch = Dart(2, 3).also { it.ordinal = 1 } val wrongScore = Dart(3, 3).also { it.ordinal = 1 } @@ -97,8 +90,7 @@ class TestDart: AbstractTest() } @Test - fun `hit clock target - single`() - { + fun `hit clock target - single`() { makeDart(1, 0, startingScore = 1).hitClockTarget(ClockType.Standard) shouldBe false makeDart(1, 1, startingScore = 1).hitClockTarget(ClockType.Standard) shouldBe true makeDart(1, 2, startingScore = 1).hitClockTarget(ClockType.Standard) shouldBe true @@ -108,8 +100,7 @@ class TestDart: AbstractTest() } @Test - fun `hit clock target - double`() - { + fun `hit clock target - double`() { makeDart(1, 0, startingScore = 1).hitClockTarget(ClockType.Doubles) shouldBe false makeDart(1, 1, startingScore = 1).hitClockTarget(ClockType.Doubles) shouldBe false makeDart(1, 2, startingScore = 1).hitClockTarget(ClockType.Doubles) shouldBe true @@ -119,8 +110,7 @@ class TestDart: AbstractTest() } @Test - fun `hit clock target - treble`() - { + fun `hit clock target - treble`() { makeDart(1, 0, startingScore = 1).hitClockTarget(ClockType.Trebles) shouldBe false makeDart(1, 1, startingScore = 1).hitClockTarget(ClockType.Trebles) shouldBe false makeDart(1, 2, startingScore = 1).hitClockTarget(ClockType.Trebles) shouldBe false @@ -130,14 +120,12 @@ class TestDart: AbstractTest() } @Test - fun `hit any clock target should be true if hit clock target`() - { + fun `hit any clock target should be true if hit clock target`() { makeDart(1, 1, startingScore = 1).hitAnyClockTarget(ClockType.Standard) shouldBe true } @Test - fun `hit any clock target should take into account all targets`() - { + fun `hit any clock target should take into account all targets`() { val targets = listOf(5, 8) makeDart(5, 1, clockTargets = targets).hitAnyClockTarget(ClockType.Standard) shouldBe true @@ -146,8 +134,7 @@ class TestDart: AbstractTest() } @Test - fun `hit any clock target should take multiplier into account`() - { + fun `hit any clock target should take multiplier into account`() { val targets = listOf(5, 8) val dart = makeDart(5, 3, clockTargets = targets) @@ -155,4 +142,4 @@ class TestDart: AbstractTest() dart.hitAnyClockTarget(ClockType.Trebles) shouldBe true dart.hitAnyClockTarget(ClockType.Doubles) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/object/TestDartHint.kt b/src/test/kotlin/dartzee/object/TestDartHint.kt index 347031b66..f60ea1901 100644 --- a/src/test/kotlin/dartzee/object/TestDartHint.kt +++ b/src/test/kotlin/dartzee/object/TestDartHint.kt @@ -1,41 +1,34 @@ package dartzee.`object` import dartzee.helper.AbstractTest -import io.kotest.matchers.shouldBe import io.kotest.assertions.throwables.shouldThrow +import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartHint: AbstractTest() -{ +class TestDartHint : AbstractTest() { @Test - fun `should factory doubles`() - { + fun `should factory doubles`() { val dart = factoryDartHintFromString("D20") dart shouldBe DartHint(20, 2) } @Test - fun `should factory trebles`() - { + fun `should factory trebles`() { val dart = factoryDartHintFromString("T15") dart shouldBe DartHint(15, 3) } @Test - fun `should factory singles`() - { + fun `should factory singles`() { val dart = factoryDartHintFromString("18") dart shouldBe DartHint(18, 1) } @Test - fun `should throw an error for invalid input`() - { - shouldThrow{ - factoryDartHintFromString("X20") - } + fun `should throw an error for invalid input`() { + shouldThrow { factoryDartHintFromString("X20") } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/object/TestDartboardSegment.kt b/src/test/kotlin/dartzee/object/TestDartboardSegment.kt index 1c5219e35..c25890f8d 100644 --- a/src/test/kotlin/dartzee/object/TestDartboardSegment.kt +++ b/src/test/kotlin/dartzee/object/TestDartboardSegment.kt @@ -13,19 +13,16 @@ import dartzee.trebleTwenty import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartboardSegment: AbstractTest() -{ +class TestDartboardSegment : AbstractTest() { @Test - fun `Should correctly report whether a segment type represents a miss`() - { + fun `Should correctly report whether a segment type represents a miss`() { doubleNineteen.isMiss() shouldBe false singleTwenty.isMiss() shouldBe false missTwenty.isMiss() shouldBe true } @Test - fun `Should correctly report whether a segment is a double excluding bull`() - { + fun `Should correctly report whether a segment is a double excluding bull`() { doubleNineteen.isDoubleExcludingBull() shouldBe true doubleTwenty.isDoubleExcludingBull() shouldBe true bullseye.isDoubleExcludingBull() shouldBe false @@ -35,8 +32,7 @@ class TestDartboardSegment: AbstractTest() } @Test - fun `Should report the correct multiplier`() - { + fun `Should report the correct multiplier`() { doubleNineteen.getMultiplier() shouldBe 2 trebleNineteen.getMultiplier() shouldBe 3 singleTwenty.getMultiplier() shouldBe 1 @@ -44,11 +40,10 @@ class TestDartboardSegment: AbstractTest() } @Test - fun `Should compute the segment score correctly`() - { + fun `Should compute the segment score correctly`() { doubleNineteen.getTotal() shouldBe 38 trebleTwenty.getTotal() shouldBe 60 singleEighteen.getTotal() shouldBe 18 missTwenty.getTotal() shouldBe 0 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/object/TestDartsClient.kt b/src/test/kotlin/dartzee/object/TestDartsClient.kt index 017b2e64d..2732815b3 100644 --- a/src/test/kotlin/dartzee/object/TestDartsClient.kt +++ b/src/test/kotlin/dartzee/object/TestDartsClient.kt @@ -10,20 +10,18 @@ import dartzee.utils.DARTS_VERSION_NUMBER import dartzee.utils.PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES import dartzee.utils.PreferenceUtil import dartzee.utils.UpdateManager +import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import io.kotest.matchers.string.shouldNotBeEmpty -import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestDartsClient: AbstractRegistryTest() -{ +class TestDartsClient : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES) @Test - fun `Should log unexpected arguments`() - { + fun `Should log unexpected arguments`() { DartsClient.parseProgramArguments(arrayOf("foo")) val log = verifyLog(CODE_UNEXPECTED_ARGUMENT, Severity.WARN) @@ -31,8 +29,7 @@ class TestDartsClient: AbstractRegistryTest() } @Test - fun `Should leave the fields alone when no arguments passed`() - { + fun `Should leave the fields alone when no arguments passed`() { DartsClient.devMode = false DartsClient.justUpdated = false @@ -43,16 +40,14 @@ class TestDartsClient: AbstractRegistryTest() } @Test - fun `Should parse devMode argument`() - { + fun `Should parse devMode argument`() { DartsClient.parseProgramArguments(arrayOf("devMode")) DartsClient.devMode shouldBe true } @Test - fun `Should parse justUpdated argument`() - { + fun `Should parse justUpdated argument`() { DartsClient.parseProgramArguments(arrayOf("justUpdated")) DartsClient.logArgumentState() @@ -61,14 +56,12 @@ class TestDartsClient: AbstractRegistryTest() } @Test - fun `Should parse a value for the OS`() - { + fun `Should parse a value for the OS`() { DartsClient.operatingSystem.shouldNotBeEmpty() } @Test - fun `Should report correctly whether on apple OS`() - { + fun `Should report correctly whether on apple OS`() { val actualOs = DartsClient.operatingSystem DartsClient.operatingSystem = "windows" @@ -84,8 +77,7 @@ class TestDartsClient: AbstractRegistryTest() } @Test - fun `Should not bother checking for updates in dev mode`() - { + fun `Should not bother checking for updates in dev mode`() { DartsClient.devMode = true val mock = mockk(relaxed = true) @@ -99,8 +91,7 @@ class TestDartsClient: AbstractRegistryTest() } @Test - fun `Should not bother checking for updates if just updated`() - { + fun `Should not bother checking for updates if just updated`() { DartsClient.devMode = false DartsClient.justUpdated = true @@ -115,8 +106,7 @@ class TestDartsClient: AbstractRegistryTest() } @Test - fun `Should not check for updates if preference is unset`() - { + fun `Should not check for updates if preference is unset`() { DartsClient.devMode = false DartsClient.justUpdated = false PreferenceUtil.saveBoolean(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES, false) @@ -131,10 +121,8 @@ class TestDartsClient: AbstractRegistryTest() verifyNotCalled { mock.checkForUpdates(any()) } } - @Test - fun `Should check for updates if necessary`() - { + fun `Should check for updates if necessary`() { DartsClient.devMode = false DartsClient.justUpdated = false PreferenceUtil.saveBoolean(PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES, true) @@ -146,4 +134,4 @@ class TestDartsClient: AbstractRegistryTest() verify { mock.checkForUpdates(DARTS_VERSION_NUMBER) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/object/TestSegmentType.kt b/src/test/kotlin/dartzee/object/TestSegmentType.kt index ce96b2ee9..4203bd241 100644 --- a/src/test/kotlin/dartzee/object/TestSegmentType.kt +++ b/src/test/kotlin/dartzee/object/TestSegmentType.kt @@ -5,11 +5,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSegmentType: AbstractTest() -{ +class TestSegmentType : AbstractTest() { @Test - fun `Should return the correct multiplier based on segment type`() - { + fun `Should return the correct multiplier based on segment type`() { SegmentType.DOUBLE.getMultiplier() shouldBe 2 SegmentType.TREBLE.getMultiplier() shouldBe 3 SegmentType.INNER_SINGLE.getMultiplier() shouldBe 1 @@ -18,8 +16,7 @@ class TestSegmentType: AbstractTest() } @Test - fun `Should return the right golf score based on segment type`() - { + fun `Should return the right golf score based on segment type`() { SegmentType.DOUBLE.getGolfScore() shouldBe 1 SegmentType.TREBLE.getGolfScore() shouldBe 2 SegmentType.INNER_SINGLE.getGolfScore() shouldBe 3 @@ -28,11 +25,9 @@ class TestSegmentType: AbstractTest() } @Test - fun `Should get the right segment type to aim for in RTC`() - { + fun `Should get the right segment type to aim for in RTC`() { getSegmentTypeForClockType(ClockType.Standard) shouldBe SegmentType.OUTER_SINGLE getSegmentTypeForClockType(ClockType.Doubles) shouldBe SegmentType.DOUBLE getSegmentTypeForClockType(ClockType.Trebles) shouldBe SegmentType.TREBLE } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/reporting/TestIncludedPlayerParameters.kt b/src/test/kotlin/dartzee/reporting/TestIncludedPlayerParameters.kt index 0a4be7b6a..5c67d508a 100644 --- a/src/test/kotlin/dartzee/reporting/TestIncludedPlayerParameters.kt +++ b/src/test/kotlin/dartzee/reporting/TestIncludedPlayerParameters.kt @@ -10,18 +10,15 @@ import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.string.shouldBeEmpty import org.junit.jupiter.api.Test -class TestIncludedPlayerParameters: AbstractTest() -{ +class TestIncludedPlayerParameters : AbstractTest() { @Test - fun `Should be blank by default`() - { + fun `Should be blank by default`() { val ipp = IncludedPlayerParameters() ipp.generateExtraWhereSql("foo").shouldBeEmpty() } @Test - fun `Should filter by finishing position`() - { + fun `Should filter by finishing position`() { val player = insertPlayer("Bob") val winningGameId = insertGame(localId = 1).rowId @@ -32,7 +29,11 @@ class TestIncludedPlayerParameters: AbstractTest() insertParticipant(playerId = player.rowId, finishingPosition = 1, gameId = winningGameId) insertParticipant(playerId = player.rowId, finishingPosition = 2, gameId = secondGameId) insertParticipant(playerId = player.rowId, finishingPosition = 3, gameId = thirdGameId) - insertParticipant(playerId = player.rowId, finishingPosition = -1, gameId = unfinishedGameId) + insertParticipant( + playerId = player.rowId, + finishingPosition = -1, + gameId = unfinishedGameId + ) val ipp = IncludedPlayerParameters() ipp.finishingPositions = listOf(1, 3) @@ -43,12 +44,11 @@ class TestIncludedPlayerParameters: AbstractTest() val results = runReport(rp) results shouldHaveSize 2 - results.map{ it.localId }.shouldContainExactlyInAnyOrder(1, 2) + results.map { it.localId }.shouldContainExactlyInAnyOrder(1, 2) } @Test - fun `Should filter by final score`() - { + fun `Should filter by final score`() { val rp = ReportParameters() val player = insertPlayer("Bob") @@ -57,31 +57,55 @@ class TestIncludedPlayerParameters: AbstractTest() val gUnfinished = insertGame(localId = 3).rowId val g25 = insertGame(localId = 4).rowId - insertParticipant(playerId = player.rowId, finishingPosition = 1, finalScore = 40, gameId = g40) - insertParticipant(playerId = player.rowId, finishingPosition = 2, finalScore = 30, gameId = g30) - insertParticipant(playerId = player.rowId, finishingPosition = 3, finalScore = 25, gameId = g25) - insertParticipant(playerId = player.rowId, finishingPosition = -1, finalScore = -1, gameId = gUnfinished) - - //Greater than 25 - val ipp = IncludedPlayerParameters(finalScore = 25, finalScoreComparator = ComboBoxNumberComparison.FILTER_MODE_GREATER_THAN) + insertParticipant( + playerId = player.rowId, + finishingPosition = 1, + finalScore = 40, + gameId = g40 + ) + insertParticipant( + playerId = player.rowId, + finishingPosition = 2, + finalScore = 30, + gameId = g30 + ) + insertParticipant( + playerId = player.rowId, + finishingPosition = 3, + finalScore = 25, + gameId = g25 + ) + insertParticipant( + playerId = player.rowId, + finishingPosition = -1, + finalScore = -1, + gameId = gUnfinished + ) + + // Greater than 25 + val ipp = + IncludedPlayerParameters( + finalScore = 25, + finalScoreComparator = ComboBoxNumberComparison.FILTER_MODE_GREATER_THAN + ) rp.hmIncludedPlayerToParms = mapOf(player to ipp) var results = runReport(rp) results.map { it.localId }.shouldContainExactlyInAnyOrder(1, 2) - //Equal to 25 + // Equal to 25 ipp.finalScoreComparator = ComboBoxNumberComparison.FILTER_MODE_EQUAL_TO results = runReport(rp) results.map { it.localId }.shouldContainExactlyInAnyOrder(4) - //Undecided + // Undecided ipp.finalScoreComparator = COMPARATOR_SCORE_UNSET results = runReport(rp) results.map { it.localId }.shouldContainExactlyInAnyOrder(3) - //Less than 31 + // Less than 31 ipp.finalScore = 31 ipp.finalScoreComparator = ComboBoxNumberComparison.FILTER_MODE_LESS_THAN results = runReport(rp) results.map { it.localId }.shouldContainExactlyInAnyOrder(2, 4) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/reporting/TestParticipantWrapper.kt b/src/test/kotlin/dartzee/reporting/TestParticipantWrapper.kt index 594acb285..da7c1deae 100644 --- a/src/test/kotlin/dartzee/reporting/TestParticipantWrapper.kt +++ b/src/test/kotlin/dartzee/reporting/TestParticipantWrapper.kt @@ -4,11 +4,9 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestParticipantWrapper: AbstractTest() -{ +class TestParticipantWrapper : AbstractTest() { @Test - fun `Should describe the player and their position correctly`() - { + fun `Should describe the player and their position correctly`() { ParticipantWrapper("Alice", 3).toString() shouldBe "Alice (3)" ParticipantWrapper("Bob", 6).toString() shouldBe "Bob (6)" ParticipantWrapper("Clive", -1).toString() shouldBe "Clive (-)" diff --git a/src/test/kotlin/dartzee/reporting/TestReportParameters.kt b/src/test/kotlin/dartzee/reporting/TestReportParameters.kt index 39c834dcf..b07adf75d 100644 --- a/src/test/kotlin/dartzee/reporting/TestReportParameters.kt +++ b/src/test/kotlin/dartzee/reporting/TestReportParameters.kt @@ -17,14 +17,12 @@ import dartzee.utils.InjectedThings.mainDatabase import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestReportParameters: AbstractTest() -{ +class TestReportParameters : AbstractTest() { @Test - fun `Should be able to filter by game type`() - { + fun `Should be able to filter by game type`() { val gameOne = insertGameForReport(gameType = GameType.X01) val gameTwo = insertGameForReport(gameType = GameType.GOLF) @@ -40,8 +38,7 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to filter by game params`() - { + fun `Should be able to filter by game params`() { val gameOne = insertGameForReport(gameParams = "foo") val gameTwo = insertGameForReport(gameParams = "bar") @@ -57,8 +54,7 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to report on only unfinished games`() - { + fun `Should be able to report on only unfinished games`() { val gameOne = insertGameForReport(dtFinish = DateStatics.END_OF_TIME) val gameTwo = insertGameForReport(dtFinish = getSqlDateNow()) @@ -74,15 +70,18 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to report on creation date`() - { + fun `Should be able to report on creation date`() { val gameOne = insertGameForReport(dtCreation = Timestamp(999)) val gameTwo = insertGameForReport(dtCreation = Timestamp(1000)) val gameThree = insertGameForReport(dtCreation = Timestamp(1001)) val rpAll = ReportParameters() val resultsAll = runReportForTest(rpAll) - resultsAll.shouldContainExactlyInAnyOrder(gameOne.localId, gameTwo.localId, gameThree.localId) + resultsAll.shouldContainExactlyInAnyOrder( + gameOne.localId, + gameTwo.localId, + gameThree.localId + ) val rpAfter = ReportParameters() rpAfter.dtStartFrom = Timestamp(1000) @@ -98,15 +97,18 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to report on finish date`() - { + fun `Should be able to report on finish date`() { val gameOne = insertGameForReport(dtFinish = Timestamp(999)) val gameTwo = insertGameForReport(dtFinish = Timestamp(1000)) val gameThree = insertGameForReport(dtFinish = Timestamp(1001)) val rpAll = ReportParameters() val resultsAll = runReportForTest(rpAll) - resultsAll.shouldContainExactlyInAnyOrder(gameOne.localId, gameTwo.localId, gameThree.localId) + resultsAll.shouldContainExactlyInAnyOrder( + gameOne.localId, + gameTwo.localId, + gameThree.localId + ) val rpAfter = ReportParameters() rpAfter.dtFinishFrom = Timestamp(1000) @@ -122,8 +124,7 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to report on whether a game was part of a match`() - { + fun `Should be able to report on whether a game was part of a match`() { val singleGame = insertGameForReport(dartsMatchId = "") val matchGame = insertGameForReport(dartsMatchId = randomGuid()) @@ -143,8 +144,7 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to report on sync status`() - { + fun `Should be able to report on sync status`() { val lastSynced = SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME).dtLastUpdate val syncedGame = insertGameForReport(dtLastUpdate = getPastTime(lastSynced)) @@ -164,8 +164,7 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should cope with reporting on sync status when never synced`() - { + fun `Should cope with reporting on sync status when never synced`() { val now = getSqlDateNow() val gameOne = insertGameForReport(dtLastUpdate = getPastTime(now)) val gameTwo = insertGameForReport(dtLastUpdate = getFutureTime(now)) @@ -180,8 +179,7 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to exclude games with certain players`() - { + fun `Should be able to exclude games with certain players`() { val gAllPlayers = insertGame() val alice = insertPlayerForGame("Alice", gAllPlayers.rowId) val bob = insertPlayerForGame("Bob", gAllPlayers.rowId) @@ -207,7 +205,13 @@ class TestReportParameters: AbstractTest() val rpAll = ReportParameters() val resultsAll = runReportForTest(rpAll) - resultsAll.shouldContainExactlyInAnyOrder(gAllPlayers.localId, gAliceAndBob.localId, gAliceCliveDaisy.localId, gBobAndDaisy.localId, gCliveDaisy.localId) + resultsAll.shouldContainExactlyInAnyOrder( + gAllPlayers.localId, + gAliceAndBob.localId, + gAliceCliveDaisy.localId, + gBobAndDaisy.localId, + gCliveDaisy.localId + ) val rpExcludeAlice = ReportParameters() rpExcludeAlice.excludedPlayers = listOf(alice) @@ -221,8 +225,7 @@ class TestReportParameters: AbstractTest() } @Test - fun `Should be able to only include games with the specified players`() - { + fun `Should be able to only include games with the specified players`() { val gAllPlayers = insertGame() val alice = insertPlayerForGame("Alice", gAllPlayers.rowId) val bob = insertPlayerForGame("Bob", gAllPlayers.rowId) @@ -249,17 +252,21 @@ class TestReportParameters: AbstractTest() val rpIncludeAlice = ReportParameters() rpIncludeAlice.hmIncludedPlayerToParms = mapOf(alice to IncludedPlayerParameters()) val resultsAlice = runReportForTest(rpIncludeAlice) - resultsAlice.shouldContainExactlyInAnyOrder(gAllPlayers.localId, gAliceAndBob.localId, gAliceCliveDaisy.localId) + resultsAlice.shouldContainExactlyInAnyOrder( + gAllPlayers.localId, + gAliceAndBob.localId, + gAliceCliveDaisy.localId + ) val rpIncludeAliceAndBob = ReportParameters() - rpIncludeAliceAndBob.hmIncludedPlayerToParms = mapOf(alice to IncludedPlayerParameters(), bob to IncludedPlayerParameters()) + rpIncludeAliceAndBob.hmIncludedPlayerToParms = + mapOf(alice to IncludedPlayerParameters(), bob to IncludedPlayerParameters()) val resultsAliceAndBob = runReportForTest(rpIncludeAliceAndBob) resultsAliceAndBob.shouldContainExactly(gAllPlayers.localId, gAliceAndBob.localId) } @Test - fun `Should only include games with at least one human player if specified`() - { + fun `Should only include games with at least one human player if specified`() { val gAllPlayers = insertGame() val ai = insertPlayerForGame("AI", gAllPlayers.rowId, strategy = "foo") val aiTwo = insertPlayerForGame("AI2", gAllPlayers.rowId, strategy = "foo") @@ -284,12 +291,13 @@ class TestReportParameters: AbstractTest() rp.excludeOnlyAi = true val results = runReportForTest(rp) - results.shouldContainExactlyInAnyOrder(listOf(gAllPlayers.localId, gHumanAndBothAI.localId, gSingleHuman.localId)) + results.shouldContainExactlyInAnyOrder( + listOf(gAllPlayers.localId, gHumanAndBothAI.localId, gSingleHuman.localId) + ) } - private fun runReportForTest(rp: ReportParameters): List - { + private fun runReportForTest(rp: ReportParameters): List { val wrappers = runReport(rp) return wrappers.map { it.localId }.toList() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/reporting/TestReportingSqlUtil.kt b/src/test/kotlin/dartzee/reporting/TestReportingSqlUtil.kt index af10986e5..22828059e 100644 --- a/src/test/kotlin/dartzee/reporting/TestReportingSqlUtil.kt +++ b/src/test/kotlin/dartzee/reporting/TestReportingSqlUtil.kt @@ -12,11 +12,9 @@ import dartzee.helper.insertPlayerForGame import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestReportingSqlUtil: AbstractTest() -{ +class TestReportingSqlUtil : AbstractTest() { @Test - fun `Should parse participants and finishing positions correctly`() - { + fun `Should parse participants and finishing positions correctly`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") val clive = insertPlayer(name = "Clive") @@ -32,12 +30,19 @@ class TestReportingSqlUtil: AbstractTest() val wrapper = results.first() val row = wrapper.getTableRow() - row shouldBe arrayOf(g1.localId, "501", "Alice (1), Clive (2), Bob (3)", g1.dtCreation, g1.dtFinish, "#7 (Game 1)") + row shouldBe + arrayOf( + g1.localId, + "501", + "Alice (1), Clive (2), Bob (3)", + g1.dtCreation, + g1.dtFinish, + "#7 (Game 1)" + ) } @Test - fun `Should return a game not part of a match`() - { + fun `Should return a game not part of a match`() { val alice = insertPlayer(name = "Alice") val g = insertGame(dartsMatchId = "", gameType = GameType.GOLF, gameParams = "18") @@ -48,12 +53,12 @@ class TestReportingSqlUtil: AbstractTest() val wrapper = results.first() val row = wrapper.getTableRow() - row shouldBe arrayOf(g.localId, "Golf - 18 holes", "Alice (-)", g.dtCreation, g.dtFinish, "") + row shouldBe + arrayOf(g.localId, "Golf - 18 holes", "Alice (-)", g.dtCreation, g.dtFinish, "") } @Test - fun `Should separate participants into the correct rows`() - { + fun `Should separate participants into the correct rows`() { val gAlice = insertGame() insertPlayerForGame("Alice", gAlice.rowId) @@ -64,15 +69,16 @@ class TestReportingSqlUtil: AbstractTest() results.size shouldBe 2 val rows = ReportResultWrapper.getTableRowsFromWrappers(results) - rows[0] shouldBe arrayOf(gAlice.localId, "501", "Alice (-)", gAlice.dtCreation, gAlice.dtFinish, "") + rows[0] shouldBe + arrayOf(gAlice.localId, "501", "Alice (-)", gAlice.dtCreation, gAlice.dtFinish, "") rows[1] shouldBe arrayOf(gBob.localId, "501", "Bob (-)", gBob.dtCreation, gBob.dtFinish, "") } @Test - fun `Should retrieve Dartzee template names when appropriate`() - { + fun `Should retrieve Dartzee template names when appropriate`() { val template = insertDartzeeTemplate(name = "BTBF's House Party") - val dartzeeGameWithTemplate = insertGame(gameType = GameType.DARTZEE, gameParams = template.rowId) + val dartzeeGameWithTemplate = + insertGame(gameType = GameType.DARTZEE, gameParams = template.rowId) val dartzeeGameStandalone = insertGame(gameType = GameType.DARTZEE, gameParams = "") val x01Game = insertGame(gameType = GameType.X01, gameParams = "501") @@ -86,8 +92,25 @@ class TestReportingSqlUtil: AbstractTest() results.first { it.localId == 3L }.templateName shouldBe null val rows = ReportResultWrapper.getTableRowsFromWrappers(results) - rows[0] shouldBe arrayOf(dartzeeGameWithTemplate.localId, "Dartzee - BTBF's House Party", "Alice (-)", dartzeeGameWithTemplate.dtCreation, dartzeeGameWithTemplate.dtFinish, "") - rows[1] shouldBe arrayOf(dartzeeGameStandalone.localId, "Dartzee", "Bob (-)", dartzeeGameStandalone.dtCreation, dartzeeGameStandalone.dtFinish, "") - rows[2] shouldBe arrayOf(x01Game.localId, "501", "Clive (-)", x01Game.dtCreation, x01Game.dtFinish, "") + rows[0] shouldBe + arrayOf( + dartzeeGameWithTemplate.localId, + "Dartzee - BTBF's House Party", + "Alice (-)", + dartzeeGameWithTemplate.dtCreation, + dartzeeGameWithTemplate.dtFinish, + "" + ) + rows[1] shouldBe + arrayOf( + dartzeeGameStandalone.localId, + "Dartzee", + "Bob (-)", + dartzeeGameStandalone.dtCreation, + dartzeeGameStandalone.dtFinish, + "" + ) + rows[2] shouldBe + arrayOf(x01Game.localId, "501", "Clive (-)", x01Game.dtCreation, x01Game.dtFinish, "") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestAbstractPlayerConfigurationDialog.kt b/src/test/kotlin/dartzee/screen/TestAbstractPlayerConfigurationDialog.kt index 7e88eaa42..a100b7ef0 100644 --- a/src/test/kotlin/dartzee/screen/TestAbstractPlayerConfigurationDialog.kt +++ b/src/test/kotlin/dartzee/screen/TestAbstractPlayerConfigurationDialog.kt @@ -1,9 +1,9 @@ package dartzee.screen -import com.github.alyssaburlton.swingtest.getChild -import dartzee.bean.PlayerAvatar import com.github.alyssaburlton.swingtest.clickCancel import com.github.alyssaburlton.swingtest.clickOk +import com.github.alyssaburlton.swingtest.getChild +import dartzee.bean.PlayerAvatar import dartzee.core.helper.verifyNotCalled import dartzee.db.PlayerEntity import dartzee.helper.AbstractTest @@ -13,14 +13,12 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestAbstractPlayerConfigurationDialog: AbstractTest() -{ +class TestAbstractPlayerConfigurationDialog : AbstractTest() { @Test - fun `Should not allow an empty player name, and should not call save with a validation error`() - { + fun `Should not allow an empty player name, and should not call save with a validation error`() { val callback = mockCallback() val dlg = DummyPlayerConfigurationDialog(callback) @@ -31,8 +29,7 @@ class TestAbstractPlayerConfigurationDialog: AbstractTest() } @Test - fun `Should call save for a valid player`() - { + fun `Should call save for a valid player`() { val callback = mockCallback() val dlg = DummyPlayerConfigurationDialog(callback) dlg.getChild("nameField").text = "Clive" @@ -45,8 +42,7 @@ class TestAbstractPlayerConfigurationDialog: AbstractTest() } @Test - fun `Should call save with the player originally passed`() - { + fun `Should call save with the player originally passed`() { val player = insertPlayer() val callback = mockCallback() @@ -61,8 +57,7 @@ class TestAbstractPlayerConfigurationDialog: AbstractTest() } @Test - fun `Should not invoke callback on cancel`() - { + fun `Should not invoke callback on cancel`() { val callback = mockCallback() val dlg = DummyPlayerConfigurationDialog(callback) dlg.clickCancel() @@ -71,42 +66,44 @@ class TestAbstractPlayerConfigurationDialog: AbstractTest() } @Test - fun `Should not allow a name with fewer than 3 characters`() - { + fun `Should not allow a name with fewer than 3 characters`() { val dlg = DummyPlayerConfigurationDialog() dlg.getChild("nameField").text = "AA" dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("The player name must be at least 3 characters long.") + dialogFactory.errorsShown.shouldContainExactly( + "The player name must be at least 3 characters long." + ) } @Test - fun `Should not allow a name with more than 25 characters`() - { + fun `Should not allow a name with more than 25 characters`() { val dlg = DummyPlayerConfigurationDialog() dlg.getChild("nameField").text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("The player name cannot be more than 25 characters long.") + dialogFactory.errorsShown.shouldContainExactly( + "The player name cannot be more than 25 characters long." + ) } @Test - fun `Should not allow creation of a player that already exists`() - { + fun `Should not allow creation of a player that already exists`() { insertPlayer(name = "Barry") val dlg = DummyPlayerConfigurationDialog() dlg.getChild("nameField").text = "Barry" dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("A player with the name Barry already exists.") + dialogFactory.errorsShown.shouldContainExactly( + "A player with the name Barry already exists." + ) } @Test - fun `Should allow an edit of an existing player that makes no changes`() - { + fun `Should allow an edit of an existing player that makes no changes`() { val p = insertPlayer(name = "Barry") val dlg = DummyPlayerConfigurationDialog(mockCallback(), p) @@ -119,8 +116,7 @@ class TestAbstractPlayerConfigurationDialog: AbstractTest() } @Test - fun `Should not allow a player with no avatar`() - { + fun `Should not allow a player with no avatar`() { val dlg = DummyPlayerConfigurationDialog() dlg.getChild("nameField").text = "Derek" @@ -131,15 +127,15 @@ class TestAbstractPlayerConfigurationDialog: AbstractTest() private fun mockCallback() = mockk<(player: PlayerEntity) -> Unit>(relaxed = true) - class DummyPlayerConfigurationDialog(callback: (player: PlayerEntity) -> Unit = mockk(relaxed = true), player: PlayerEntity = PlayerEntity.factoryCreate()) : - AbstractPlayerConfigurationDialog(callback, player) - { - init - { + class DummyPlayerConfigurationDialog( + callback: (player: PlayerEntity) -> Unit = mockk(relaxed = true), + player: PlayerEntity = PlayerEntity.factoryCreate() + ) : AbstractPlayerConfigurationDialog(callback, player) { + init { add(avatar) add(textFieldName) } override fun savePlayer() {} } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestAchievementConversionDialog.kt b/src/test/kotlin/dartzee/screen/TestAchievementConversionDialog.kt index 1396281c5..014985149 100644 --- a/src/test/kotlin/dartzee/screen/TestAchievementConversionDialog.kt +++ b/src/test/kotlin/dartzee/screen/TestAchievementConversionDialog.kt @@ -25,25 +25,24 @@ import dartzee.logging.KEY_PLAYER_IDS import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test import javax.swing.JButton import javax.swing.JComboBox import javax.swing.JOptionPane import javax.swing.JRadioButton +import org.junit.jupiter.api.Test -class TestAchievementConversionDialog : AbstractTest() -{ +class TestAchievementConversionDialog : AbstractTest() { @Test - fun `Should populate the player selector from the db`() - { + fun `Should populate the player selector from the db`() { val players = preparePlayers(5).map { it.name } val dlg = AchievementConversionDialog() - dlg.getChild().tablePlayersToSelectFrom.getAllPlayers().map { it.name } shouldBe players + dlg.getChild().tablePlayersToSelectFrom.getAllPlayers().map { + it.name + } shouldBe players } @Test - fun `Achievement dropdown should enable based on radio selection`() - { + fun `Achievement dropdown should enable based on radio selection`() { val dlg = AchievementConversionDialog() val comboBox = dlg.getChild>() comboBox.shouldBeDisabled() @@ -56,8 +55,7 @@ class TestAchievementConversionDialog : AbstractTest() } @Test - fun `Should validate and not dispose if cancelling running on all players`() - { + fun `Should validate and not dispose if cancelling running on all players`() { preparePlayers(2) dialogFactory.questionOption = JOptionPane.NO_OPTION @@ -66,12 +64,13 @@ class TestAchievementConversionDialog : AbstractTest() dlg.clickOk() dlg.shouldBeVisible() - dialogFactory.questionsShown.shouldContainExactly("This will run the conversion(s) for ALL players. Proceed?") + dialogFactory.questionsShown.shouldContainExactly( + "This will run the conversion(s) for ALL players. Proceed?" + ) } @Test - fun `Should run for all achievements and players`() - { + fun `Should run for all achievements and players`() { preparePlayers(3) dialogFactory.questionOption = JOptionPane.YES_OPTION @@ -85,14 +84,15 @@ class TestAchievementConversionDialog : AbstractTest() findWindow()!!.shouldNotBeVisible() val log = findLog(CODE_ACHIEVEMENT_CONVERSION_STARTED)!! - log.message shouldBe "Regenerating ${getAllAchievements().size} achievements for all players" - log.keyValuePairs[KEY_ACHIEVEMENT_TYPES] shouldBe getAllAchievements().map { it.achievementType } + log.message shouldBe + "Regenerating ${getAllAchievements().size} achievements for all players" + log.keyValuePairs[KEY_ACHIEVEMENT_TYPES] shouldBe + getAllAchievements().map { it.achievementType } log.keyValuePairs[KEY_PLAYER_IDS] shouldBe emptyList() } @Test - fun `Should run for a subset of players and achievements`() - { + fun `Should run for a subset of players and achievements`() { preparePlayers(4) val dlg = AchievementConversionDialog() @@ -114,14 +114,13 @@ class TestAchievementConversionDialog : AbstractTest() val log = findLog(CODE_ACHIEVEMENT_CONVERSION_STARTED)!! log.message shouldBe "Regenerating 1 achievements for 2 players" - log.keyValuePairs[KEY_ACHIEVEMENT_TYPES] shouldBe listOf(selectedAchievement.achievementType) + log.keyValuePairs[KEY_ACHIEVEMENT_TYPES] shouldBe + listOf(selectedAchievement.achievementType) log.keyValuePairs[KEY_PLAYER_IDS] shouldBe players.map { it.rowId } - } - private fun waitForConversionToFinish() - { + private fun waitForConversionToFinish() { waitForAssertion { findLog(CODE_ACHIEVEMENT_CONVERSION_FINISHED) shouldNotBe null } flushEdt() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestChangeLog.kt b/src/test/kotlin/dartzee/screen/TestChangeLog.kt index 688b613a0..448d53861 100644 --- a/src/test/kotlin/dartzee/screen/TestChangeLog.kt +++ b/src/test/kotlin/dartzee/screen/TestChangeLog.kt @@ -4,17 +4,15 @@ import com.github.alyssaburlton.swingtest.getChild import dartzee.helper.AbstractTest import dartzee.utils.DARTS_VERSION_NUMBER import io.kotest.matchers.string.shouldContain -import org.junit.jupiter.api.Test import javax.swing.JTextArea +import org.junit.jupiter.api.Test -class TestChangeLog: AbstractTest() -{ +class TestChangeLog : AbstractTest() { @Test - fun `Should include the current version number`() - { + fun `Should include the current version number`() { val changeLog = ChangeLog() val contents = changeLog.getChild().text contents.lines().first() shouldContain DARTS_VERSION_NUMBER } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestFocusableWindow.kt b/src/test/kotlin/dartzee/screen/TestFocusableWindow.kt index cd631a39a..0ff02f322 100644 --- a/src/test/kotlin/dartzee/screen/TestFocusableWindow.kt +++ b/src/test/kotlin/dartzee/screen/TestFocusableWindow.kt @@ -7,11 +7,9 @@ import io.kotest.matchers.shouldBe import io.mockk.mockk import org.junit.jupiter.api.Test -class TestFocusableWindow: AbstractTest() -{ +class TestFocusableWindow : AbstractTest() { @Test - fun `Should update logging context when gains focus`() - { + fun `Should update logging context when gains focus`() { val window = FakeFocusableWindow() logger.addToContext(KEY_ACTIVE_WINDOW, "Foo") @@ -19,8 +17,7 @@ class TestFocusableWindow: AbstractTest() logger.loggingContext[KEY_ACTIVE_WINDOW] shouldBe "Fake Window" } - private inner class FakeFocusableWindow: FocusableWindow() - { + private inner class FakeFocusableWindow : FocusableWindow() { override val windowName = "Fake Window" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestGameSetupScreen.kt b/src/test/kotlin/dartzee/screen/TestGameSetupScreen.kt index f8e47b94c..9821dc6b2 100644 --- a/src/test/kotlin/dartzee/screen/TestGameSetupScreen.kt +++ b/src/test/kotlin/dartzee/screen/TestGameSetupScreen.kt @@ -39,19 +39,16 @@ import io.mockk.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -class TestGameSetupScreen: AbstractTest() -{ +class TestGameSetupScreen : AbstractTest() { private val gameLauncher = mockk(relaxed = true) @BeforeEach - fun beforeEach() - { + fun beforeEach() { InjectedThings.gameLauncher = gameLauncher } @Test - fun `Should respond to changing game type`() - { + fun `Should respond to changing game type`() { val screen = GameSetupScreen() screen.gameParamFilterPanel.shouldBeInstanceOf() @@ -60,8 +57,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should perform player selector validation when attempting to launch a game`() - { + fun `Should perform player selector validation when attempting to launch a game`() { val screen = GameSetupScreen() screen.btnLaunch.doClick() @@ -69,8 +65,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should initialise the player selector with players from the DB`() - { + fun `Should initialise the player selector with players from the DB`() { insertPlayer(name = "Alice") insertPlayer(name = "Bob") insertPlayer(name = "Clive") @@ -83,8 +78,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should launch a single game with the selected players and game params`() - { + fun `Should launch a single game with the selected players and game params`() { val alice = insertPlayer(name = "Alice") insertPlayer(name = "Bob") val clive = insertPlayer(name = "Clive") @@ -98,17 +92,17 @@ class TestGameSetupScreen: AbstractTest() screen.btnLaunch.doClick() - val expectedParams = GameLaunchParams(listOf(alice, clive), GameType.X01, "701", false, null) + val expectedParams = + GameLaunchParams(listOf(alice, clive), GameType.X01, "701", false, null) verify { gameLauncher.launchNewGame(expectedParams) } } @Test - fun `Should toggle the right components when switching between match types`() - { + fun `Should toggle the right components when switching between match types`() { val screen = GameSetupScreen() screen.initialise() - //Default - single game + // Default - single game screen.lblWins.isVisible shouldBe false screen.spinnerWins.isVisible shouldBe false screen.lblGames.isVisible shouldBe false @@ -116,7 +110,7 @@ class TestGameSetupScreen: AbstractTest() screen.matchConfigPanel.components.toList() shouldNotContain screen.panelPointBreakdown screen.btnLaunch.text shouldBe "Launch Game" - //First to + // First to screen.rdbtnFirstTo.doClick() screen.lblWins.isVisible shouldBe true screen.spinnerWins.isVisible shouldBe true @@ -125,7 +119,7 @@ class TestGameSetupScreen: AbstractTest() screen.matchConfigPanel.components.toList() shouldNotContain screen.panelPointBreakdown screen.btnLaunch.text shouldBe "Launch Match" - //Points-based + // Points-based screen.rdbtnPoints.doClick() screen.lblWins.isVisible shouldBe false screen.spinnerWins.isVisible shouldBe false @@ -134,7 +128,7 @@ class TestGameSetupScreen: AbstractTest() screen.matchConfigPanel.components.toList() shouldContain screen.panelPointBreakdown screen.btnLaunch.text shouldBe "Launch Match" - //Back to single game + // Back to single game screen.rdbtnSingleGame.doClick() screen.lblWins.isVisible shouldBe false screen.spinnerWins.isVisible shouldBe false @@ -145,8 +139,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should update based on whether a Dartzee template is selected`() - { + fun `Should update based on whether a Dartzee template is selected`() { insertDartzeeTemplate(name = "Template") val screen = GameSetupScreen() @@ -163,11 +156,11 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should retrieve Dartzee rules when launching a Dartzee game from a template`() - { + fun `Should retrieve Dartzee rules when launching a Dartzee game from a template`() { val templateId = insertDartzeeTemplate().rowId - val ruleOne = makeDartzeeRuleDto(DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleEven()) + val ruleOne = + makeDartzeeRuleDto(DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleEven()) val ruleTwo = makeDartzeeRuleDto(aggregateRule = DartzeeTotalRulePrime()) ruleOne.toEntity(1, EntityName.DartzeeTemplate, templateId).saveToDatabase() @@ -181,13 +174,13 @@ class TestGameSetupScreen: AbstractTest() screen.btnLaunch.doClick() - val expectedParams = GameLaunchParams(players, GameType.DARTZEE, templateId, false, listOf(ruleOne, ruleTwo)) + val expectedParams = + GameLaunchParams(players, GameType.DARTZEE, templateId, false, listOf(ruleOne, ruleTwo)) verify { gameLauncher.launchNewGame(launchParamsEqual(expectedParams)) } } @Test - fun `Should launch a first-to match with the right parameters`() - { + fun `Should launch a first-to match with the right parameters`() { val slot = slot() every { gameLauncher.launchNewMatch(capture(slot), any()) } just runs @@ -199,7 +192,7 @@ class TestGameSetupScreen: AbstractTest() scrn.btnLaunch.doClick() val launchParams = GameLaunchParams(players, GameType.X01, "501", false) - verify { gameLauncher.launchNewMatch(any(), launchParams)} + verify { gameLauncher.launchNewMatch(any(), launchParams) } val match = slot.captured match.mode shouldBe MatchMode.FIRST_TO @@ -208,8 +201,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should launch a points based match with the right parameters`() - { + fun `Should launch a points based match with the right parameters`() { val slot = slot() every { gameLauncher.launchNewMatch(capture(slot), any()) } just runs @@ -227,7 +219,7 @@ class TestGameSetupScreen: AbstractTest() scrn.btnLaunch.doClick() - verify { gameLauncher.launchNewMatch(any(), any())} + verify { gameLauncher.launchNewMatch(any(), any()) } val match = slot.captured match.mode shouldBe MatchMode.POINTS @@ -236,8 +228,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should perform validation on Dartzee mode when trying to hit Next`() - { + fun `Should perform validation on Dartzee mode when trying to hit Next`() { val setupScreen = GameSetupScreen() setupScreen.initialise() setupScreen.playerSelector.init(listOf()) @@ -249,8 +240,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should switch to the DartzeeRuleSetupScreen on Next, passing through the right parameters`() - { + fun `Should switch to the DartzeeRuleSetupScreen on Next, passing through the right parameters`() { val p1 = insertPlayer(strategy = "") val p2 = insertPlayer(strategy = "") @@ -268,13 +258,13 @@ class TestGameSetupScreen: AbstractTest() currentScreen.btnNext.text shouldBe "Launch Game >" currentScreen.nextPressed() - val expectedParams = GameLaunchParams(listOf(p1, p2), GameType.DARTZEE, "", false, emptyList()) + val expectedParams = + GameLaunchParams(listOf(p1, p2), GameType.DARTZEE, "", false, emptyList()) verify { gameLauncher.launchNewGame(expectedParams) } } @Test - fun `Should switch to the DartzeeRuleSetupScreen for a match`() - { + fun `Should switch to the DartzeeRuleSetupScreen for a match`() { val slot = slot() every { gameLauncher.launchNewMatch(capture(slot), any()) } just runs @@ -296,7 +286,8 @@ class TestGameSetupScreen: AbstractTest() currentScreen.btnNext.text shouldBe "Launch Match >" currentScreen.nextPressed() - val expectedParams = GameLaunchParams(listOf(p1, p2), GameType.DARTZEE, "", false, emptyList()) + val expectedParams = + GameLaunchParams(listOf(p1, p2), GameType.DARTZEE, "", false, emptyList()) verify { gameLauncher.launchNewMatch(any(), expectedParams) } val match = slot.captured @@ -305,8 +296,7 @@ class TestGameSetupScreen: AbstractTest() } @Test - fun `Should update the game parameters panel on initialise`() - { + fun `Should update the game parameters panel on initialise`() { val setupScreen = GameSetupScreen() setupScreen.initialise() setupScreen.gameTypeComboBox.updateSelection(GameType.DARTZEE) @@ -320,8 +310,7 @@ class TestGameSetupScreen: AbstractTest() newFilterPanel.comboBox.items().mapNotNull { it.hiddenData }.shouldHaveSize(1) } - private fun makeGameSetupScreenReadyToLaunch(): Pair> - { + private fun makeGameSetupScreenReadyToLaunch(): Pair> { val p1 = insertPlayer(strategy = "") val p2 = insertPlayer(strategy = "") @@ -331,4 +320,4 @@ class TestGameSetupScreen: AbstractTest() return setupScreen to listOf(p1, p2) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestGameplayDartboard.kt b/src/test/kotlin/dartzee/screen/TestGameplayDartboard.kt index 7c1452cd8..b5ec1bf56 100644 --- a/src/test/kotlin/dartzee/screen/TestGameplayDartboard.kt +++ b/src/test/kotlin/dartzee/screen/TestGameplayDartboard.kt @@ -25,23 +25,20 @@ import io.mockk.verify import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -class TestGameplayDartboard : AbstractTest() -{ +class TestGameplayDartboard : AbstractTest() { @Test - fun `Dartboard listener should be notified if set`() - { + fun `Dartboard listener should be notified if set`() { val dartboard = factoryGameplayDartboard() val listener = mockk(relaxed = true) dartboard.addDartboardListener(listener) dartboard.throwDartByClick() - verify { listener.dartThrown(Dart(20, 1))} + verify { listener.dartThrown(Dart(20, 1)) } } @Test - fun `Should support disabling and re-enabling interaction`() - { + fun `Should support disabling and re-enabling interaction`() { val dartboard = factoryGameplayDartboard() val listener = mockk(relaxed = true) @@ -55,12 +52,11 @@ class TestGameplayDartboard : AbstractTest() dartboard.ensureListening() dartboard.throwDartByClick() dartboard.findChild().shouldNotBeNull() - verify { listener.dartThrown(Dart(20, 1))} + verify { listener.dartThrown(Dart(20, 1)) } } @Test - fun `Should suppress adding a dart on the first click if parent window has lost focus`() - { + fun `Should suppress adding a dart on the first click if parent window has lost focus`() { val dartboard = factoryGameplayDartboard() val parent = FakeDartsScreen() parent.add(dartboard) @@ -75,8 +71,7 @@ class TestGameplayDartboard : AbstractTest() } @Test - fun `Should support clearing darts`() - { + fun `Should support clearing darts`() { val dartboard = factoryGameplayDartboard() dartboard.throwDartByClick() @@ -87,8 +82,7 @@ class TestGameplayDartboard : AbstractTest() } @Test - fun `Should not render darts if too small`() - { + fun `Should not render darts if too small`() { val dartboard = factoryGameplayDartboard() dartboard.throwDartByClick() dartboard.findChild().shouldNotBeNull() @@ -104,12 +98,12 @@ class TestGameplayDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should handle layering darts on top of hover state`() - { + fun `Should handle layering darts on top of hover state`() { val dartboard = factoryGameplayDartboard() val interactiveDartboard = dartboard.getChild() - val pt = interactiveDartboard.getPointForSegment(DartboardSegment(SegmentType.OUTER_SINGLE, 20)) + val pt = + interactiveDartboard.getPointForSegment(DartboardSegment(SegmentType.OUTER_SINGLE, 20)) interactiveDartboard.doClick(pt.x, pt.y) interactiveDartboard.highlightDartboard(pt) @@ -119,12 +113,12 @@ class TestGameplayDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should get rid of hover state when a dart is thrown`() - { + fun `Should get rid of hover state when a dart is thrown`() { val dartboard = factoryGameplayDartboard() val interactiveDartboard = dartboard.getChild() - val pt = interactiveDartboard.getPointForSegment(DartboardSegment(SegmentType.OUTER_SINGLE, 1)) + val pt = + interactiveDartboard.getPointForSegment(DartboardSegment(SegmentType.OUTER_SINGLE, 1)) interactiveDartboard.highlightDartboard(pt) interactiveDartboard.doClick(pt.x, pt.y) @@ -134,8 +128,7 @@ class TestGameplayDartboard : AbstractTest() @Test @Tag("screenshot") - fun `Should re-render darts in the right places on resize`() - { + fun `Should re-render darts in the right places on resize`() { val dartboard = factoryGameplayDartboard() dartboard.throwDartByClick(DartboardSegment(SegmentType.OUTER_SINGLE, 20)) dartboard.throwDartByClick(DartboardSegment(SegmentType.DOUBLE, 14)) @@ -156,4 +149,4 @@ class TestGameplayDartboard : AbstractTest() flushEdt() return dartboard } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestHumanConfigurationDialog.kt b/src/test/kotlin/dartzee/screen/TestHumanConfigurationDialog.kt index 6a1f06b7d..4e33569f7 100644 --- a/src/test/kotlin/dartzee/screen/TestHumanConfigurationDialog.kt +++ b/src/test/kotlin/dartzee/screen/TestHumanConfigurationDialog.kt @@ -1,8 +1,8 @@ package dartzee.screen +import com.github.alyssaburlton.swingtest.clickOk import com.github.alyssaburlton.swingtest.getChild import dartzee.bean.PlayerAvatar -import com.github.alyssaburlton.swingtest.clickOk import dartzee.db.PlayerEntity import dartzee.helper.AbstractTest import dartzee.helper.insertPlayer @@ -11,14 +11,12 @@ import dartzee.helper.randomGuid import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestHumanConfigurationDialog: AbstractTest() -{ +class TestHumanConfigurationDialog : AbstractTest() { @Test - fun `Should start with correct state for new player`() - { + fun `Should start with correct state for new player`() { val dlg = HumanConfigurationDialog(mockk()) dlg.getChild("nameField").text shouldBe "" dlg.getChild().avatarId shouldBe "" @@ -27,8 +25,7 @@ class TestHumanConfigurationDialog: AbstractTest() } @Test - fun `Should start with correct state for amending a player`() - { + fun `Should start with correct state for amending a player`() { val avatar = insertPlayerImage() val player = insertPlayer(name = "Bongo", playerImageId = avatar.rowId) @@ -40,8 +37,7 @@ class TestHumanConfigurationDialog: AbstractTest() } @Test - fun `Should save a new player`() - { + fun `Should save a new player`() { val avatarId = randomGuid() val dlg = HumanConfigurationDialog(mockCallback()) @@ -55,8 +51,7 @@ class TestHumanConfigurationDialog: AbstractTest() } @Test - fun `Should save changes to an existing player`() - { + fun `Should save changes to an existing player`() { val oldAvatar = insertPlayerImage() val newAvatar = insertPlayerImage() val player = insertPlayer(name = "Alex", playerImageId = oldAvatar.rowId) @@ -75,4 +70,4 @@ class TestHumanConfigurationDialog: AbstractTest() } private fun mockCallback() = mockk<(player: PlayerEntity) -> Unit>(relaxed = true) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestMenuScreen.kt b/src/test/kotlin/dartzee/screen/TestMenuScreen.kt index ed1b4f0b2..58223f345 100644 --- a/src/test/kotlin/dartzee/screen/TestMenuScreen.kt +++ b/src/test/kotlin/dartzee/screen/TestMenuScreen.kt @@ -14,79 +14,69 @@ import dartzee.screen.stats.overall.LeaderboardsScreen import dartzee.screen.sync.SyncManagementScreen import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.Test import javax.swing.JButton import javax.swing.JLabel +import org.junit.jupiter.api.Test -class TestMenuScreen: AbstractTest() -{ +class TestMenuScreen : AbstractTest() { @Test - fun `Should go to Sync Management screen`() - { + fun `Should go to Sync Management screen`() { val scrn = MenuScreen() scrn.clickChild(text = "Sync Setup") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go to the game setup screen`() - { + fun `Should go to the game setup screen`() { val scrn = MenuScreen() scrn.clickChild(text = "New Game") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go to the player management screen`() - { + fun `Should go to the player management screen`() { val scrn = MenuScreen() scrn.clickChild(text = "Manage Players") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go to the reporting setup screen`() - { + fun `Should go to the reporting setup screen`() { val scrn = MenuScreen() scrn.clickChild(text = "Game Report") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go to the leaderboards screen`() - { + fun `Should go to the leaderboards screen`() { val scrn = MenuScreen() scrn.clickChild(text = "Leaderboards") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go to the utilities screen`() - { + fun `Should go to the utilities screen`() { val scrn = MenuScreen() scrn.clickChild(text = "Utilities") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go to the preferences screen`() - { + fun `Should go to the preferences screen`() { val scrn = MenuScreen() scrn.clickChild(text = "Preferences") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go to the dartzee template setup screen`() - { + fun `Should go to the dartzee template setup screen`() { val scrn = MenuScreen() scrn.clickChild(text = "Dartzee Rules") ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should launch the ChangeLog if the link is clicked`() - { + fun `Should launch the ChangeLog if the link is clicked`() { val scrn = MenuScreen() val lbl = scrn.getChild { it.text.contains("Dartzee v") } @@ -96,4 +86,4 @@ class TestMenuScreen: AbstractTest() changeLog.shouldNotBeNull() changeLog.shouldBeVisible() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestPlayerImageDialog.kt b/src/test/kotlin/dartzee/screen/TestPlayerImageDialog.kt index ef0fb590c..d1a8a6d0c 100644 --- a/src/test/kotlin/dartzee/screen/TestPlayerImageDialog.kt +++ b/src/test/kotlin/dartzee/screen/TestPlayerImageDialog.kt @@ -1,10 +1,10 @@ package dartzee.screen +import com.github.alyssaburlton.swingtest.clickOk import com.github.alyssaburlton.swingtest.getChild import com.github.alyssaburlton.swingtest.shouldMatch import com.github.alyssaburlton.swingtest.shouldMatchImage import dartzee.bean.PlayerImageRadio -import com.github.alyssaburlton.swingtest.clickOk import dartzee.core.bean.FileUploader import dartzee.core.helper.verifyNotCalled import dartzee.core.util.getAllChildComponentsForType @@ -22,16 +22,14 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Tag -import org.junit.jupiter.api.Test import javax.swing.JPanel import javax.swing.JTabbedPane +import org.junit.jupiter.api.Tag +import org.junit.jupiter.api.Test -class TestPlayerImageDialog : AbstractTest() -{ +class TestPlayerImageDialog : AbstractTest() { @Test - fun `Should populate correctly with pre-existing images`() - { + fun `Should populate correctly with pre-existing images`() { PlayerImageEntity().createPresets() insertPlayerImage("dibble") @@ -40,13 +38,13 @@ class TestPlayerImageDialog : AbstractTest() val presetTab = tabbedPane.getChild("presetTab") val uploadTab = tabbedPane.getChild("uploadTab") - presetTab.getAllChildComponentsForType().size shouldBe PlayerImageEntity.avatarPresets.size + presetTab.getAllChildComponentsForType().size shouldBe + PlayerImageEntity.avatarPresets.size uploadTab.getAllChildComponentsForType().size shouldBe 1 } @Test - fun `Should show an error if no selection is made`() - { + fun `Should show an error if no selection is made`() { val callback = makeCallback() val dlg = PlayerImageDialog(callback) dlg.clickOk() @@ -57,8 +55,7 @@ class TestPlayerImageDialog : AbstractTest() @Test @Tag("screenshot") - fun `Should accept and crop a valid new avatar`() - { + fun `Should accept and crop a valid new avatar`() { val dlg = PlayerImageDialog(makeCallback()) dlg.isVisible = true dlg.getChild().selectTab("uploadTab") @@ -76,8 +73,7 @@ class TestPlayerImageDialog : AbstractTest() } @Test - fun `Should reject uploading a non-image file`() - { + fun `Should reject uploading a non-image file`() { val dlg = PlayerImageDialog(makeCallback()) dlg.getChild().selectTab("uploadTab") dlg.uploadResource("/aiModel.json") @@ -87,21 +83,21 @@ class TestPlayerImageDialog : AbstractTest() } @Test - fun `Should reject uploading an image that is too small`() - { + fun `Should reject uploading an image that is too small`() { val dlg = PlayerImageDialog(makeCallback()) dlg.getChild().selectTab("uploadTab") dlg.uploadResource("/stats_large.png") - dialogFactory.errorsShown.shouldContainExactly("The image is too small - it must be at least $PLAYER_IMAGE_WIDTH x $PLAYER_IMAGE_HEIGHT px.") + dialogFactory.errorsShown.shouldContainExactly( + "The image is too small - it must be at least $PLAYER_IMAGE_WIDTH x $PLAYER_IMAGE_HEIGHT px." + ) dlg.getAllChildComponentsForType().shouldBeEmpty() PlayerImageEntity().retrieveEntities().shouldBeEmpty() } @Test - fun `Should invoke callback when Ok is pressed with an image selected`() - { + fun `Should invoke callback when Ok is pressed with an image selected`() { val img = insertPlayerImage("dibble") val callback = makeCallback() val dlg = PlayerImageDialog(callback) @@ -111,11 +107,10 @@ class TestPlayerImageDialog : AbstractTest() verify { callback(img.rowId) } } - private fun PlayerImageDialog.uploadResource(resourceName: String) - { + private fun PlayerImageDialog.uploadResource(resourceName: String) { val uploader = getChild() uploader.uploadFileFromResource(resourceName) } private fun makeCallback(): (String) -> Unit = mockk(relaxed = true) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestPlayerSelectDialog.kt b/src/test/kotlin/dartzee/screen/TestPlayerSelectDialog.kt index d5350a247..ba428640f 100644 --- a/src/test/kotlin/dartzee/screen/TestPlayerSelectDialog.kt +++ b/src/test/kotlin/dartzee/screen/TestPlayerSelectDialog.kt @@ -1,7 +1,7 @@ package dartzee.screen -import dartzee.bean.getAllPlayers import com.github.alyssaburlton.swingtest.clickOk +import dartzee.bean.getAllPlayers import dartzee.core.helper.doubleClick import dartzee.helper.AbstractTest import dartzee.helper.insertPlayer @@ -9,14 +9,12 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.ListSelectionModel +import org.junit.jupiter.api.Test -class TestPlayerSelectDialog: AbstractTest() -{ +class TestPlayerSelectDialog : AbstractTest() { @Test - fun `Should not display excluded players`() - { + fun `Should not display excluded players`() { val bob = insertPlayer(name = "Bob") insertPlayer(name = "Alice") @@ -29,8 +27,7 @@ class TestPlayerSelectDialog: AbstractTest() } @Test - fun `Should respond to radio button selection`() - { + fun `Should respond to radio button selection`() { insertPlayer(name = "AI", strategy = "foo") insertPlayer(name = "Bob", strategy = "") @@ -47,8 +44,7 @@ class TestPlayerSelectDialog: AbstractTest() } @Test - fun `Should show an error if okayed with no selection`() - { + fun `Should show an error if okayed with no selection`() { val dlg = PlayerSelectDialog(ListSelectionModel.SINGLE_SELECTION) dlg.buildTable() @@ -57,8 +53,7 @@ class TestPlayerSelectDialog: AbstractTest() } @Test - fun `Should not show an error and update selectedPlayers when okayed with a selection`() - { + fun `Should not show an error and update selectedPlayers when okayed with a selection`() { insertPlayer(name = "Bob") val dlg = PlayerSelectDialog(ListSelectionModel.SINGLE_SELECTION) @@ -72,8 +67,7 @@ class TestPlayerSelectDialog: AbstractTest() } @Test - fun `Should respond to double-click`() - { + fun `Should respond to double-click`() { insertPlayer(name = "Bob") val dlg = PlayerSelectDialog(ListSelectionModel.SINGLE_SELECTION) @@ -86,11 +80,9 @@ class TestPlayerSelectDialog: AbstractTest() dlg.selectedPlayers.size shouldBe 1 } - private fun getAvailablePlayerNames(dlg: PlayerSelectDialog): List - { + private fun getAvailablePlayerNames(dlg: PlayerSelectDialog): List { val players = dlg.tablePlayers.getAllPlayers() - return players.map{ it.name } + return players.map { it.name } } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/TestScreenCache.kt b/src/test/kotlin/dartzee/screen/TestScreenCache.kt index 97ce56d5b..f119df272 100644 --- a/src/test/kotlin/dartzee/screen/TestScreenCache.kt +++ b/src/test/kotlin/dartzee/screen/TestScreenCache.kt @@ -12,21 +12,18 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestScreenCache: AbstractTest() -{ +class TestScreenCache : AbstractTest() { @Test - fun `Should construct an instance and return it on subsequent calls`() - { + fun `Should construct an instance and return it on subsequent calls`() { val scrn = ScreenCache.get() scrn.shouldNotBeNull() val other = ScreenCache.get() - other shouldBeSameInstanceAs scrn + other shouldBeSameInstanceAs scrn } @Test - fun `Should clear the cache`() - { + fun `Should clear the cache`() { ScreenCache.addDartsGameScreen("Game 1", mockk()) val scrn = ScreenCache.get() ScreenCache.emptyCache() @@ -37,8 +34,7 @@ class TestScreenCache: AbstractTest() } @Test - fun `Should switch the current screen to the new one and init it`() - { + fun `Should switch the current screen to the new one and init it`() { val scrn = mockk(relaxed = true) ScreenCache.switch(scrn) @@ -48,8 +44,7 @@ class TestScreenCache: AbstractTest() } @Test - fun `Should not init the switched screen if specified`() - { + fun `Should not init the switched screen if specified`() { val scrn = mockk(relaxed = true) ScreenCache.switch(scrn, false) @@ -59,8 +54,7 @@ class TestScreenCache: AbstractTest() } @Test - fun `Should support switching by type`() - { + fun `Should support switching by type`() { val scrn = ScreenCache.get() ScreenCache.switch() @@ -68,8 +62,7 @@ class TestScreenCache: AbstractTest() } @Test - fun `Should return the unique count of darts game screens`() - { + fun `Should return the unique count of darts game screens`() { val screenOne = mockk(relaxed = true) val screenTwo = mockk(relaxed = true) @@ -83,8 +76,7 @@ class TestScreenCache: AbstractTest() } @Test - fun `Should be able to get the screen for a particular GameId`() - { + fun `Should be able to get the screen for a particular GameId`() { ScreenCache.getDartsGameScreen("Game 1") shouldBe null val screenOne = mockk(relaxed = true) @@ -93,8 +85,7 @@ class TestScreenCache: AbstractTest() } @Test - fun `Should be able to remove a screen`() - { + fun `Should be able to remove a screen`() { val screenOne = mockk(relaxed = true) val screenTwo = mockk(relaxed = true) @@ -108,4 +99,4 @@ class TestScreenCache: AbstractTest() ScreenCache.getDartsGameScreen("Game 2") shouldBe null ScreenCache.getDartsGameScreen("Game 3") shouldBe screenTwo } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationDialog.kt b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationDialog.kt index 0a68cc51b..bffda071b 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationDialog.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationDialog.kt @@ -1,11 +1,11 @@ package dartzee.screen.ai import com.github.alyssaburlton.swingtest.clickChild +import com.github.alyssaburlton.swingtest.clickOk import com.github.alyssaburlton.swingtest.getChild import dartzee.ai.DartsAiModel import dartzee.ai.DartzeePlayStyle import dartzee.bean.PlayerAvatar -import com.github.alyssaburlton.swingtest.clickOk import dartzee.core.bean.ComboBoxItem import dartzee.core.bean.selectedItemTyped import dartzee.db.PlayerEntity @@ -18,17 +18,15 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JButton import javax.swing.JComboBox import javax.swing.JRadioButton import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestAIConfigurationDialog: AbstractTest() -{ +class TestAIConfigurationDialog : AbstractTest() { @Test - fun `Should populate correctly for a new player`() - { + fun `Should populate correctly for a new player`() { val dlg = AIConfigurationDialog(mockk()) dlg.getChild().readOnly shouldBe false @@ -48,13 +46,19 @@ class TestAIConfigurationDialog: AbstractTest() } @Test - fun `Should populate correctly for an existing player`() - { - val strategy = makeDartsModel( + fun `Should populate correctly for an existing player`() { + val strategy = + makeDartsModel( standardDeviation = 75.0, dartzeePlayStyle = DartzeePlayStyle.AGGRESSIVE, mercyThreshold = 17, - hmDartNoToSegmentType = mapOf(1 to SegmentType.INNER_SINGLE, 2 to SegmentType.INNER_SINGLE, 3 to SegmentType.INNER_SINGLE)) + hmDartNoToSegmentType = + mapOf( + 1 to SegmentType.INNER_SINGLE, + 2 to SegmentType.INNER_SINGLE, + 3 to SegmentType.INNER_SINGLE + ) + ) val player = insertPlayer(name = "Robot", strategy = strategy.toJson()) val dlg = AIConfigurationDialog(mockk(), player) @@ -72,12 +76,14 @@ class TestAIConfigurationDialog: AbstractTest() x01Panel.spinnerMercyThreshold.value shouldBe 17 val golfPanel = dlg.getChild().getPanelForDartNo(1) - golfPanel.getChild>>().selectedItemTyped().hiddenData shouldBe SegmentType.INNER_SINGLE + golfPanel + .getChild>>() + .selectedItemTyped() + .hiddenData shouldBe SegmentType.INNER_SINGLE } @Test - fun `Should successfully save changes to an AI player`() - { + fun `Should successfully save changes to an AI player`() { val player = insertPlayer(name = "Sid", strategy = DartsAiModel.new().toJson()) val callback = mockCallback() @@ -97,8 +103,7 @@ class TestAIConfigurationDialog: AbstractTest() } @Test - fun `Should enforce name and avatar for a new player`() - { + fun `Should enforce name and avatar for a new player`() { insertPlayer(name = "Duplicate") val dlg = AIConfigurationDialog(mockCallback()) @@ -108,7 +113,9 @@ class TestAIConfigurationDialog: AbstractTest() dialogFactory.errorsShown.clear() dlg.getChild("nameField").text = "Duplicate" dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("A player with the name Duplicate already exists.") + dialogFactory.errorsShown.shouldContainExactly( + "A player with the name Duplicate already exists." + ) dialogFactory.errorsShown.clear() dlg.getChild("nameField").text = "Valid" @@ -125,8 +132,7 @@ class TestAIConfigurationDialog: AbstractTest() } @Test - fun `Should calculate stats for the configured model`() - { + fun `Should calculate stats for the configured model`() { val dlg = AIConfigurationDialog(mockk()) val normalDistPanel = dlg.getChild() @@ -147,4 +153,4 @@ class TestAIConfigurationDialog: AbstractTest() } private fun mockCallback() = mockk<(player: PlayerEntity) -> Unit>(relaxed = true) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationGolfDartPanel.kt b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationGolfDartPanel.kt index 9d0ad448e..00ce9bfdd 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationGolfDartPanel.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationGolfDartPanel.kt @@ -12,24 +12,21 @@ import dartzee.helper.AbstractTest import dartzee.helper.makeDartsModel import dartzee.`object`.SegmentType import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JComboBox import javax.swing.JLabel import javax.swing.JSpinner +import org.junit.jupiter.api.Test -class TestAIConfigurationGolfDartPanel: AbstractTest() -{ +class TestAIConfigurationGolfDartPanel : AbstractTest() { @Test - fun `Should hide the spinner for dart 3, but not the others`() - { + fun `Should hide the spinner for dart 3, but not the others`() { AIConfigurationGolfDartPanel(1).getChild().parent.shouldBeVisible() AIConfigurationGolfDartPanel(2).getChild().parent.shouldBeVisible() AIConfigurationGolfDartPanel(3).getChild().parent.shouldNotBeVisible() } @Test - fun `Should not populate the map for stop threshold if dart 3`() - { + fun `Should not populate the map for stop threshold if dart 3`() { val panel = AIConfigurationGolfDartPanel(3) panel.getChild().value = 2 @@ -39,8 +36,7 @@ class TestAIConfigurationGolfDartPanel: AbstractTest() } @Test - fun `Should disable the 'or better' label appropriately`() - { + fun `Should disable the 'or better' label appropriately`() { val panel = AIConfigurationGolfDartPanel(1) panel.getChild().value = 2 panel.getChild(text = "or better").shouldBeEnabled() @@ -50,31 +46,39 @@ class TestAIConfigurationGolfDartPanel: AbstractTest() } @Test - fun `Should initialise from a model correctly`() - { + fun `Should initialise from a model correctly`() { val hmDartNoToSegmentType = mapOf(1 to SegmentType.TREBLE, 2 to SegmentType.INNER_SINGLE) val hmDartNoToStopThreshold = mapOf(1 to 2, 2 to 4) - val model = makeDartsModel(hmDartNoToSegmentType = hmDartNoToSegmentType, hmDartNoToStopThreshold = hmDartNoToStopThreshold) + val model = + makeDartsModel( + hmDartNoToSegmentType = hmDartNoToSegmentType, + hmDartNoToStopThreshold = hmDartNoToStopThreshold + ) val dartOnePanel = AIConfigurationGolfDartPanel(1) dartOnePanel.initialiseFromModel(model) - dartOnePanel.getChild>>().selectedItemTyped().hiddenData shouldBe SegmentType.TREBLE + dartOnePanel + .getChild>>() + .selectedItemTyped() + .hiddenData shouldBe SegmentType.TREBLE dartOnePanel.getChild().value shouldBe 2 val dartTwoPanel = AIConfigurationGolfDartPanel(2) dartTwoPanel.initialiseFromModel(model) - dartTwoPanel.getChild>>().selectedItemTyped().hiddenData shouldBe SegmentType.INNER_SINGLE + dartTwoPanel + .getChild>>() + .selectedItemTyped() + .hiddenData shouldBe SegmentType.INNER_SINGLE dartTwoPanel.getChild().value shouldBe 4 } @Test - fun `Should populate model correctly`() - { + fun `Should populate model correctly`() { val panel = AIConfigurationGolfDartPanel(1) panel.getChild().value = 2 panel.selectSegmentType(SegmentType.DOUBLE) - val hmDartNoToSegmentType = mutableMapOf() + val hmDartNoToSegmentType = mutableMapOf() val hmDartNoToStopThreshold = mutableMapOf() panel.populateMaps(hmDartNoToSegmentType, hmDartNoToStopThreshold) @@ -88,10 +92,8 @@ class TestAIConfigurationGolfDartPanel: AbstractTest() hmDartNoToStopThreshold[1] shouldBe 3 } - - private fun AIConfigurationGolfDartPanel.selectSegmentType(segmentType: SegmentType) - { + private fun AIConfigurationGolfDartPanel.selectSegmentType(segmentType: SegmentType) { val comboBox = getChild>>() comboBox.items().find { it.hiddenData == segmentType }?.let { comboBox.selectedItem = it } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationPanelNormalDistribution.kt b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationPanelNormalDistribution.kt index 28f3580df..a0072ad32 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationPanelNormalDistribution.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationPanelNormalDistribution.kt @@ -8,15 +8,13 @@ import dartzee.ai.DartsAiModel import dartzee.helper.AbstractTest import dartzee.helper.makeDartsModel import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JCheckBox import javax.swing.JSlider +import org.junit.jupiter.api.Test -class TestAIConfigurationPanelNormalDistribution: AbstractTest() -{ +class TestAIConfigurationPanelNormalDistribution : AbstractTest() { @Test - fun `Should enable and disable doubles spinner`() - { + fun `Should enable and disable doubles spinner`() { val panel = AIConfigurationPanelNormalDistribution() panel.initialiseFromModel(DartsAiModel.new()) panel.nfStandardDeviationDoubles.shouldBeDisabled() @@ -29,8 +27,7 @@ class TestAIConfigurationPanelNormalDistribution: AbstractTest() } @Test - fun `Should enable and disable central skew spinner`() - { + fun `Should enable and disable central skew spinner`() { val panel = AIConfigurationPanelNormalDistribution() panel.initialiseFromModel(DartsAiModel.new()) panel.nfCentralBias.shouldBeDisabled() @@ -43,12 +40,14 @@ class TestAIConfigurationPanelNormalDistribution: AbstractTest() } @Test - fun `Should populate correctly from populated model`() - { - val model = makeDartsModel(standardDeviation = 100.0, - standardDeviationDoubles = 17.5, - standardDeviationCentral = 5.2, - maxRadius = 270) + fun `Should populate correctly from populated model`() { + val model = + makeDartsModel( + standardDeviation = 100.0, + standardDeviationDoubles = 17.5, + standardDeviationCentral = 5.2, + maxRadius = 270 + ) val panel = AIConfigurationPanelNormalDistribution() panel.initialiseFromModel(model) @@ -56,15 +55,22 @@ class TestAIConfigurationPanelNormalDistribution: AbstractTest() panel.nfStandardDeviation.value shouldBe 100.0 panel.getChild(text = "Standard Deviation (Doubles)").isSelected shouldBe true panel.nfStandardDeviationDoubles.value shouldBe 17.5 - panel.getChild(text = "Standard Deviation (skew towards center)").isSelected shouldBe true + panel + .getChild(text = "Standard Deviation (skew towards center)") + .isSelected shouldBe true panel.nfCentralBias.value shouldBe 5.2 panel.getChild().value shouldBe 270 } @Test - fun `Should populate from empty model`() - { - val model = makeDartsModel(standardDeviation = 100.0, standardDeviationDoubles = null, standardDeviationCentral = null, maxRadius = 250) + fun `Should populate from empty model`() { + val model = + makeDartsModel( + standardDeviation = 100.0, + standardDeviationDoubles = null, + standardDeviationCentral = null, + maxRadius = 250 + ) val panel = AIConfigurationPanelNormalDistribution() panel.initialiseFromModel(model) @@ -73,15 +79,16 @@ class TestAIConfigurationPanelNormalDistribution: AbstractTest() panel.getChild(text = "Standard Deviation (Doubles)").isSelected shouldBe false panel.nfStandardDeviationDoubles.value shouldBe 50.0 panel.nfStandardDeviationDoubles.shouldBeDisabled() - panel.getChild(text = "Standard Deviation (skew towards center)").isSelected shouldBe false + panel + .getChild(text = "Standard Deviation (skew towards center)") + .isSelected shouldBe false panel.nfCentralBias.value shouldBe 50.0 panel.nfCentralBias.shouldBeDisabled() panel.getChild().value shouldBe 250 } @Test - fun `Should create populated model`() - { + fun `Should create populated model`() { val panel = AIConfigurationPanelNormalDistribution() panel.nfStandardDeviation.value = 57.5 @@ -100,8 +107,7 @@ class TestAIConfigurationPanelNormalDistribution: AbstractTest() } @Test - fun `Should create a model with null fields if boxes left unchecked`() - { + fun `Should create a model with null fields if boxes left unchecked`() { val panel = AIConfigurationPanelNormalDistribution() panel.nfStandardDeviation.value = 57.5 @@ -110,4 +116,4 @@ class TestAIConfigurationPanelNormalDistribution: AbstractTest() model.standardDeviationDoubles shouldBe null model.standardDeviationCentral shouldBe null } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelDartzee.kt b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelDartzee.kt index 3443a358e..f7552abf0 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelDartzee.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelDartzee.kt @@ -6,14 +6,12 @@ import dartzee.ai.DartzeePlayStyle import dartzee.helper.AbstractTest import dartzee.helper.makeDartsModel import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JRadioButton +import org.junit.jupiter.api.Test -class TestAIConfigurationSubPanelDartzee: AbstractTest() -{ +class TestAIConfigurationSubPanelDartzee : AbstractTest() { @Test - fun `Should initialise from model correctly`() - { + fun `Should initialise from model correctly`() { val model = makeDartsModel(dartzeePlayStyle = DartzeePlayStyle.AGGRESSIVE) val panel = AIConfigurationSubPanelDartzee() @@ -28,8 +26,7 @@ class TestAIConfigurationSubPanelDartzee: AbstractTest() } @Test - fun `Should populate model correctly`() - { + fun `Should populate model correctly`() { val model = makeDartsModel() val panel = AIConfigurationSubPanelDartzee() @@ -39,4 +36,4 @@ class TestAIConfigurationSubPanelDartzee: AbstractTest() panel.clickChild(text = "Aggressive") panel.populateModel(model).dartzeePlayStyle shouldBe DartzeePlayStyle.AGGRESSIVE } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelGolf.kt b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelGolf.kt index e40fca3dd..08b958210 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelGolf.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelGolf.kt @@ -8,38 +8,53 @@ import dartzee.helper.AbstractTest import dartzee.helper.makeDartsModel import dartzee.`object`.SegmentType import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JComboBox import javax.swing.JSpinner import javax.swing.border.TitledBorder +import org.junit.jupiter.api.Test -class TestAIConfigurationSubPanelGolf: AbstractTest() -{ +class TestAIConfigurationSubPanelGolf : AbstractTest() { @Test - fun `Should initialise from a model correctly`() - { - val hmDartNoToSegmentType = mapOf(1 to SegmentType.TREBLE, 2 to SegmentType.INNER_SINGLE, 3 to SegmentType.OUTER_SINGLE) + fun `Should initialise from a model correctly`() { + val hmDartNoToSegmentType = + mapOf( + 1 to SegmentType.TREBLE, + 2 to SegmentType.INNER_SINGLE, + 3 to SegmentType.OUTER_SINGLE + ) val hmDartNoToStopThreshold = mapOf(1 to 2, 2 to 4) - val model = makeDartsModel(hmDartNoToSegmentType = hmDartNoToSegmentType, hmDartNoToStopThreshold = hmDartNoToStopThreshold) + val model = + makeDartsModel( + hmDartNoToSegmentType = hmDartNoToSegmentType, + hmDartNoToStopThreshold = hmDartNoToStopThreshold + ) val panel = AIConfigurationSubPanelGolf() panel.initialiseFromModel(model) val dartOnePanel = panel.getPanelForDartNo(1) - dartOnePanel.getChild>>().selectedItemTyped().hiddenData shouldBe SegmentType.TREBLE + dartOnePanel + .getChild>>() + .selectedItemTyped() + .hiddenData shouldBe SegmentType.TREBLE dartOnePanel.getChild().value shouldBe 2 val dartTwoPanel = panel.getPanelForDartNo(2) - dartTwoPanel.getChild>>().selectedItemTyped().hiddenData shouldBe SegmentType.INNER_SINGLE + dartTwoPanel + .getChild>>() + .selectedItemTyped() + .hiddenData shouldBe SegmentType.INNER_SINGLE dartTwoPanel.getChild().value shouldBe 4 val dartThreePanel = panel.getPanelForDartNo(3) - dartThreePanel.getChild>>().selectedItemTyped().hiddenData shouldBe SegmentType.OUTER_SINGLE + dartThreePanel + .getChild>>() + .selectedItemTyped() + .hiddenData shouldBe SegmentType.OUTER_SINGLE } @Test - fun `Should populate the model correctly`() - { + fun `Should populate the model correctly`() { val panel = AIConfigurationSubPanelGolf() panel.selectSegmentType(1, SegmentType.DOUBLE) @@ -59,13 +74,15 @@ class TestAIConfigurationSubPanelGolf: AbstractTest() model.hmDartNoToSegmentType[3] shouldBe SegmentType.TREBLE } - private fun AIConfigurationSubPanelGolf.selectSegmentType(dartNo: Int, segmentType: SegmentType) - { + private fun AIConfigurationSubPanelGolf.selectSegmentType( + dartNo: Int, + segmentType: SegmentType + ) { val panel = getPanelForDartNo(dartNo) val comboBox = panel.getChild>>() comboBox.items().find { it.hiddenData == segmentType }?.let { comboBox.selectedItem = it } } } -fun AIConfigurationSubPanelGolf.getPanelForDartNo(dartNo: Int) - = getChild { (it.border as TitledBorder).title == "Dart #$dartNo" } \ No newline at end of file +fun AIConfigurationSubPanelGolf.getPanelForDartNo(dartNo: Int) = + getChild { (it.border as TitledBorder).title == "Dart #$dartNo" } diff --git a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelX01.kt b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelX01.kt index cba11c428..d99cc8814 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelX01.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAIConfigurationSubPanelX01.kt @@ -6,11 +6,9 @@ import dartzee.helper.makeDartsModel import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAIConfigurationSubPanelX01: AbstractTest() -{ +class TestAIConfigurationSubPanelX01 : AbstractTest() { @Test - fun `Should populate the scoring dart onto the model`() - { + fun `Should populate the scoring dart onto the model`() { val panel = AIConfigurationSubPanelX01() panel.spinnerScoringDart.value = 18 @@ -19,8 +17,7 @@ class TestAIConfigurationSubPanelX01: AbstractTest() } @Test - fun `Should populate the mercy threshold onto the model`() - { + fun `Should populate the mercy threshold onto the model`() { val panel = AIConfigurationSubPanelX01() panel.chckbxMercyRule.isSelected = true panel.spinnerMercyThreshold.value = 13 @@ -30,8 +27,7 @@ class TestAIConfigurationSubPanelX01: AbstractTest() } @Test - fun `Should not populate the mercy threshold if the box is unticked`() - { + fun `Should not populate the mercy threshold if the box is unticked`() { val panel = AIConfigurationSubPanelX01() panel.chckbxMercyRule.isSelected = false panel.spinnerMercyThreshold.value = 13 @@ -41,8 +37,7 @@ class TestAIConfigurationSubPanelX01: AbstractTest() } @Test - fun `Should populate the model with the setup darts`() - { + fun `Should populate the model with the setup darts`() { val panel = AIConfigurationSubPanelX01() panel.hmScoreToDart[20] = AimDart(10, 2) @@ -51,8 +46,7 @@ class TestAIConfigurationSubPanelX01: AbstractTest() } @Test - fun `Should initialise the scoringDart from the model`() - { + fun `Should initialise the scoringDart from the model`() { val model = makeDartsModel(scoringDart = 15) val panel = AIConfigurationSubPanelX01() @@ -62,8 +56,7 @@ class TestAIConfigurationSubPanelX01: AbstractTest() } @Test - fun `Should initialise the mercy threshold from the model`() - { + fun `Should initialise the mercy threshold from the model`() { val model = makeDartsModel(mercyThreshold = 11) val panel = AIConfigurationSubPanelX01() @@ -75,8 +68,7 @@ class TestAIConfigurationSubPanelX01: AbstractTest() } @Test - fun `Should initialise an unset mercy threshold from the model`() - { + fun `Should initialise an unset mercy threshold from the model`() { val model = makeDartsModel(mercyThreshold = null) val panel = AIConfigurationSubPanelX01() @@ -88,8 +80,7 @@ class TestAIConfigurationSubPanelX01: AbstractTest() } @Test - fun `Mercy rule checkbox should toggle other components`() - { + fun `Mercy rule checkbox should toggle other components`() { val panel = AIConfigurationSubPanelX01() panel.chckbxMercyRule.doClick() panel.spinnerMercyThreshold.isEnabled shouldBe true @@ -99,4 +90,4 @@ class TestAIConfigurationSubPanelX01: AbstractTest() panel.spinnerMercyThreshold.isEnabled shouldBe false panel.lblWhenScoreLess.isEnabled shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestAISetupConfigurationDialog.kt b/src/test/kotlin/dartzee/screen/ai/TestAISetupConfigurationDialog.kt index 565347b14..27b6d9760 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAISetupConfigurationDialog.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAISetupConfigurationDialog.kt @@ -13,14 +13,12 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.maps.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestAISetupConfigurationDialog: AbstractTest() -{ +class TestAISetupConfigurationDialog : AbstractTest() { @Test - fun `Should populate the table with rows from existing hashmap`() - { + fun `Should populate the table with rows from existing hashmap`() { val map = mutableMapOf(48 to AimDart(16, 1), 100 to AimDart(25, 2)) val dlg = AISetupConfigurationDialog(map) @@ -31,14 +29,13 @@ class TestAISetupConfigurationDialog: AbstractTest() val rows = table.getRows() rows.shouldContainExactlyInAnyOrder( - listOf(48, AimDart(16, 1), 32), - listOf(100, AimDart(25, 2), 50) + listOf(48, AimDart(16, 1), 32), + listOf(100, AimDart(25, 2), 50) ) } @Test - fun `Should support removing setup rules`() - { + fun `Should support removing setup rules`() { val dlg = AISetupConfigurationDialog(mutableMapOf(48 to AimDart(16, 1))) val table = dlg.getChild() @@ -51,8 +48,7 @@ class TestAISetupConfigurationDialog: AbstractTest() } @Test - fun `Should show an error if removing rules with no selection`() - { + fun `Should show an error if removing rules with no selection`() { val dlg = AISetupConfigurationDialog(mutableMapOf(48 to AimDart(16, 1))) dlg.clickChild(text = "Remove") @@ -62,14 +58,12 @@ class TestAISetupConfigurationDialog: AbstractTest() } @Test - fun `Should support adding a new rule to the table`() - { + fun `Should support adding a new rule to the table`() { InjectedThings.aiSetupRuleFactory = MockAiSetupRuleFactory() val dlg = AISetupConfigurationDialog(mutableMapOf(48 to AimDart(16, 1))) dlg.clickChild(text = "Add Rule...") - val table = dlg.getChild() table.rowCount shouldBe 2 @@ -81,8 +75,7 @@ class TestAISetupConfigurationDialog: AbstractTest() } @Test - fun `Should commit modifications to the hash map when Ok is pressed`() - { + fun `Should commit modifications to the hash map when Ok is pressed`() { InjectedThings.aiSetupRuleFactory = MockAiSetupRuleFactory() val map = mutableMapOf(48 to AimDart(16, 1)) val dlg = AISetupConfigurationDialog(map) @@ -94,8 +87,7 @@ class TestAISetupConfigurationDialog: AbstractTest() } @Test - fun `Should discard modifications when cancelled`() - { + fun `Should discard modifications when cancelled`() { InjectedThings.aiSetupRuleFactory = MockAiSetupRuleFactory() val map = mutableMapOf(48 to AimDart(16, 1)) val dlg = AISetupConfigurationDialog(map) @@ -106,10 +98,9 @@ class TestAISetupConfigurationDialog: AbstractTest() map.shouldContainExactly(mapOf(48 to AimDart(16, 1))) } - private class MockAiSetupRuleFactory: IAISetupRuleFactory - { + private class MockAiSetupRuleFactory : IAISetupRuleFactory { override fun newSetupRule(currentRules: MutableMap) { currentRules[10] = AimDart(2, 1) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestAISimulationSetupDialog.kt b/src/test/kotlin/dartzee/screen/ai/TestAISimulationSetupDialog.kt index fd4db3c38..efe7bf29d 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestAISimulationSetupDialog.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestAISimulationSetupDialog.kt @@ -20,14 +20,12 @@ import io.mockk.just import io.mockk.mockk import io.mockk.runs import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JRadioButton +import org.junit.jupiter.api.Test -class TestAISimulationSetupDialog: AbstractTest() -{ +class TestAISimulationSetupDialog : AbstractTest() { @Test - fun `Should kick off an X01 simulation`() - { + fun `Should kick off an X01 simulation`() { val slot = CapturingSlot() val mockRunner = mockk(relaxed = true) every { mockRunner.runSimulation(capture(slot), any(), any()) } just runs @@ -51,8 +49,7 @@ class TestAISimulationSetupDialog: AbstractTest() } @Test - fun `Should kick off a Golf simulation`() - { + fun `Should kick off a Golf simulation`() { val slot = CapturingSlot() val mockRunner = mockk(relaxed = true) every { mockRunner.runSimulation(capture(slot), any(), any()) } just runs @@ -74,4 +71,4 @@ class TestAISimulationSetupDialog: AbstractTest() sim.model shouldBe model sim.player shouldBe player } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestNewSetupRuleDialog.kt b/src/test/kotlin/dartzee/screen/ai/TestNewSetupRuleDialog.kt index 3e3c3a6a4..a858d07de 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestNewSetupRuleDialog.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestNewSetupRuleDialog.kt @@ -1,8 +1,8 @@ package dartzee.screen.ai -import dartzee.ai.AimDart import com.github.alyssaburlton.swingtest.clickCancel import com.github.alyssaburlton.swingtest.clickOk +import dartzee.ai.AimDart import dartzee.helper.AbstractTest import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly @@ -11,11 +11,9 @@ import io.kotest.matchers.shouldBe import net.miginfocom.swing.MigLayout import org.junit.jupiter.api.Test -class TestNewSetupRuleDialog: AbstractTest() -{ +class TestNewSetupRuleDialog : AbstractTest() { @Test - fun `Should move the spinner to the correct cell when radio selection changes`() - { + fun `Should move the spinner to the correct cell when radio selection changes`() { val dlg = NewSetupRuleDialog(mutableMapOf()) val layout = dlg.panel.layout as MigLayout @@ -31,17 +29,17 @@ class TestNewSetupRuleDialog: AbstractTest() } @Test - fun `Should not allow the score field to be left blank`() - { + fun `Should not allow the score field to be left blank`() { val dlg = NewSetupRuleDialog(mutableMapOf()) dlg.valid() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("You must enter a score for this rule to apply to.") + dialogFactory.errorsShown.shouldContainExactly( + "You must enter a score for this rule to apply to." + ) } @Test - fun `Should not allow treble 25 to be entered as a target`() - { + fun `Should not allow treble 25 to be entered as a target`() { val dlg = NewSetupRuleDialog(mutableMapOf()) dlg.nfScore.value = 50 @@ -53,8 +51,7 @@ class TestNewSetupRuleDialog: AbstractTest() } @Test - fun `Should not allow a target that would bust the player`() - { + fun `Should not allow a target that would bust the player`() { val dlg = NewSetupRuleDialog(mutableMapOf()) dlg.nfScore.value = 50 @@ -67,8 +64,7 @@ class TestNewSetupRuleDialog: AbstractTest() } @Test - fun `Should not allow a rule that overlaps with the existing default`() - { + fun `Should not allow a rule that overlaps with the existing default`() { val dlg = NewSetupRuleDialog(mutableMapOf()) dlg.nfScore.value = 60 @@ -76,12 +72,13 @@ class TestNewSetupRuleDialog: AbstractTest() dlg.rdbtnSingle.doClick() dlg.valid() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("The selected dart is already the default for this starting score.") + dialogFactory.errorsShown.shouldContainExactly( + "The selected dart is already the default for this starting score." + ) } @Test - fun `Should add a valid rule to the HashMap`() - { + fun `Should add a valid rule to the HashMap`() { val hm = mutableMapOf() val dlg = NewSetupRuleDialog(hm) @@ -96,8 +93,7 @@ class TestNewSetupRuleDialog: AbstractTest() } @Test - fun `Should not add to the HashMap when cancelled`() - { + fun `Should not add to the HashMap when cancelled`() { val hm = mutableMapOf() val dlg = NewSetupRuleDialog(hm) @@ -111,14 +107,13 @@ class TestNewSetupRuleDialog: AbstractTest() } @Test - fun `Should set the correct score and multiplier on the target dart`() - { + fun `Should set the correct score and multiplier on the target dart`() { verifyDart("Single", 1) verifyDart("Double", 2) verifyDart("Treble", 3) } - private fun verifyDart(rdbtn: String, multiplier: Int) - { + + private fun verifyDart(rdbtn: String, multiplier: Int) { val hm = mutableMapOf() val dlg = NewSetupRuleDialog(hm) diff --git a/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelDensity.kt b/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelDensity.kt index 40f652ffe..084901d42 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelDensity.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelDensity.kt @@ -3,16 +3,14 @@ package dartzee.screen.ai import com.github.alyssaburlton.swingtest.shouldMatchImage import dartzee.helper.AbstractTest import dartzee.helper.makeDartsModel +import java.awt.Dimension import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import java.awt.Dimension -class TestVisualisationPanelDensity: AbstractTest() -{ +class TestVisualisationPanelDensity : AbstractTest() { @Test @Tag("screenshot") - fun `Should match snapshot - T20`() - { + fun `Should match snapshot - T20`() { val model = makeDartsModel(scoringDart = 20, standardDeviation = 50.0, maxRadius = 250) val panel = VisualisationPanelDensity() @@ -24,8 +22,7 @@ class TestVisualisationPanelDensity: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - bullseye`() - { + fun `Should match snapshot - bullseye`() { val model = makeDartsModel(scoringDart = 25, standardDeviation = 100.0, maxRadius = 500) val panel = VisualisationPanelDensity() @@ -37,8 +34,7 @@ class TestVisualisationPanelDensity: AbstractTest() @Test @Tag("screenshot") - fun `Should adjust for low erraticness`() - { + fun `Should adjust for low erraticness`() { val model = makeDartsModel(scoringDart = 25, standardDeviation = 100.0, maxRadius = 150) val panel = VisualisationPanelDensity() @@ -50,8 +46,7 @@ class TestVisualisationPanelDensity: AbstractTest() @Test @Tag("screenshot") - fun `Should match snapshot - key`() - { + fun `Should match snapshot - key`() { val model = makeDartsModel(scoringDart = 25, standardDeviation = 100.0) val panel = VisualisationPanelDensity() @@ -60,4 +55,4 @@ class TestVisualisationPanelDensity: AbstractTest() panel.panelKey.shouldMatchImage("Key") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelScatter.kt b/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelScatter.kt index 28d79f342..f4b588c9b 100644 --- a/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelScatter.kt +++ b/src/test/kotlin/dartzee/screen/ai/TestVisualisationPanelScatter.kt @@ -8,21 +8,22 @@ import com.github.alyssaburlton.swingtest.shouldMatchImage import dartzee.core.util.jsonMapper import dartzee.helper.AbstractTest import dartzee.helper.makeDartsModel -import org.junit.jupiter.api.Tag -import org.junit.jupiter.api.Test import java.awt.Dimension import java.awt.Point +import org.junit.jupiter.api.Tag +import org.junit.jupiter.api.Test -class TestVisualisationPanelScatter: AbstractTest() -{ +class TestVisualisationPanelScatter : AbstractTest() { private data class ScatterPreset(val hmPointToCount: Map) @Test @Tag("screenshot") - fun `Should match its snapshot`() - { + fun `Should match its snapshot`() { val jsonString = javaClass.getResource("/scatterPreset.json").readText() - val module = SimpleModule().also { it.addKeyDeserializer(Point::class.java, JsonPointDeserializer()) } + val module = + SimpleModule().also { + it.addKeyDeserializer(Point::class.java, JsonPointDeserializer()) + } val mapper = jsonMapper().also { it.registerModule(module) } val scatterPreset = mapper.readValue(jsonString) @@ -34,14 +35,12 @@ class TestVisualisationPanelScatter: AbstractTest() panel.shouldMatchImage("scatter") } - internal inner class JsonPointDeserializer : KeyDeserializer() - { - override fun deserializeKey(key: String, ctxt: DeserializationContext): Any? - { + internal inner class JsonPointDeserializer : KeyDeserializer() { + override fun deserializeKey(key: String, ctxt: DeserializationContext): Any? { val x = key.substringAfter("x=").substringBefore(",").toInt() val y = key.substringAfter("y=").substringBefore(")").toInt() return Point(x, y) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartboardSegmentSelectDialog.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartboardSegmentSelectDialog.kt index 3d3cea76a..d9630dcc1 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartboardSegmentSelectDialog.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartboardSegmentSelectDialog.kt @@ -20,18 +20,16 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.ints.shouldBeGreaterThan import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Component import java.awt.Point import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestDartboardSegmentSelectDialog : AbstractTest() -{ +class TestDartboardSegmentSelectDialog : AbstractTest() { private val segment = DartboardSegment(SegmentType.OUTER_SINGLE, 20) @Test - fun `clicking the same segment should toggle it on and off`() - { + fun `clicking the same segment should toggle it on and off`() { val (dlg, dartboard) = setup() val pt = dartboard.getPointForSegment(segment) @@ -44,8 +42,7 @@ class TestDartboardSegmentSelectDialog : AbstractTest() } @Test - fun `should be able to select all`() - { + fun `should be able to select all`() { val allSegments = getAllNonMissSegments() val (dlg, dartboard) = setup() @@ -59,8 +56,7 @@ class TestDartboardSegmentSelectDialog : AbstractTest() } @Test - fun `should be able to select none`() - { + fun `should be able to select none`() { val (dlg, dartboard) = setup() dlg.clickChild(text = "Select None") @@ -73,16 +69,14 @@ class TestDartboardSegmentSelectDialog : AbstractTest() } @Test - fun `clicking outside the board should do nothing`() - { + fun `clicking outside the board should do nothing`() { val (dlg, dartboard) = setup() dartboard.doClick(Point(1, 1)) dlg.getSelection().shouldBeEmpty() } @Test - fun `dragging on the same segment should not toggle it again`() - { + fun `dragging on the same segment should not toggle it again`() { val (dlg, dartboard) = setup() val pt = dartboard.getPointForSegment(segment) @@ -93,8 +87,7 @@ class TestDartboardSegmentSelectDialog : AbstractTest() } @Test - fun `dragging on a new segment should toggle it`() - { + fun `dragging on a new segment should toggle it`() { val (dlg, dartboard) = setup() val pt = dartboard.getPointForSegment(segment) @@ -103,12 +96,12 @@ class TestDartboardSegmentSelectDialog : AbstractTest() val newPt = dartboard.getPointForSegment(DartboardSegment(SegmentType.OUTER_SINGLE, 1)) dartboard.doDrag(newPt.x, newPt.y) - dlg.getSelection().shouldContainExactly(segment, DartboardSegment(SegmentType.OUTER_SINGLE, 1)) + dlg.getSelection() + .shouldContainExactly(segment, DartboardSegment(SegmentType.OUTER_SINGLE, 1)) } @Test - fun `initial state should work correctly`() - { + fun `initial state should work correctly`() { val (dlg, dartboard) = setup(setOf(segment)) dlg.getSelection().shouldContainExactlyInAnyOrder(segment) @@ -117,8 +110,7 @@ class TestDartboardSegmentSelectDialog : AbstractTest() } @Test - fun `initial state should respond to drags`() - { + fun `initial state should respond to drags`() { val (dlg, dartboard) = setup(setOf(segment)) dlg.getSelection().shouldContainExactlyInAnyOrder(segment) @@ -130,8 +122,7 @@ class TestDartboardSegmentSelectDialog : AbstractTest() } @Test - fun `selecting segments should update their colour`() - { + fun `selecting segments should update their colour`() { val (_, dartboard) = setup() waitForAssertion { dartboard.width shouldBeGreaterThan 0 } @@ -141,8 +132,7 @@ class TestDartboardSegmentSelectDialog : AbstractTest() } @Test - fun `cancelling should revert back to initial selection`() - { + fun `cancelling should revert back to initial selection`() { val (dlg, dartboard) = setup(setOf(segment)) val pt = dartboard.getPointForSegment(segment) @@ -153,8 +143,9 @@ class TestDartboardSegmentSelectDialog : AbstractTest() dlg.getSelection().shouldContainExactlyInAnyOrder(segment) } - private fun setup(initialSelection: Set = emptySet()): Pair - { + private fun setup( + initialSelection: Set = emptySet() + ): Pair { val dlg = DartboardSegmentSelectDialog(initialSelection) dlg.isModal = false dlg.isVisible = true @@ -163,15 +154,11 @@ class TestDartboardSegmentSelectDialog : AbstractTest() return dlg to dartboard } - /** - * TODO - Bake into swingtest - */ + /** TODO - Bake into swingtest */ private fun Component.doDrag(x: Int = 0, y: Int = 0) { runOnEventThreadBlocking { val me = makeMouseEvent(this, x = x, y = y) - mouseMotionListeners.forEach { - it.mouseDragged(me) - } + mouseMotionListeners.forEach { it.mouseDragged(me) } } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCarousel.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCarousel.kt index 889c3c73f..b3151b8ee 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCarousel.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCarousel.kt @@ -32,17 +32,16 @@ import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.Color import java.util.concurrent.locks.ReentrantLock +import org.junit.jupiter.api.Test -class TestDartzeeRuleCarousel: AbstractTest() -{ - private val dtos = listOf(twoBlackOneWhite, scoreEighteens, innerOuterInner, totalIsFifty, allTwenties) +class TestDartzeeRuleCarousel : AbstractTest() { + private val dtos = + listOf(twoBlackOneWhite, scoreEighteens, innerOuterInner, totalIsFifty, allTwenties) @Test - fun `Should display the correct initial state`() - { + fun `Should display the correct initial state`() { val carousel = makeCarousel() carousel.update(emptyList(), emptyList(), 20) @@ -56,8 +55,7 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Should remove pending rules that are invalid based on darts thrown`() - { + fun `Should remove pending rules that are invalid based on darts thrown`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val carousel = makeCarousel() @@ -66,17 +64,22 @@ class TestDartzeeRuleCarousel: AbstractTest() carousel.dartsThrown.shouldContainExactly(dart) carousel.completeTiles.shouldBeEmpty() - carousel.getPendingRules().shouldContainExactly(twoBlackOneWhite, scoreEighteens, totalIsFifty) + carousel + .getPendingRules() + .shouldContainExactly(twoBlackOneWhite, scoreEighteens, totalIsFifty) } @Test - fun `Should use round results to separate pending and completed rules`() - { + fun `Should use round results to separate pending and completed rules`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val carousel = makeCarousel() - val results = makeRoundResultEntities(DartzeeRoundResult(3, true, 36), DartzeeRoundResult(1, false, -38)) + val results = + makeRoundResultEntities( + DartzeeRoundResult(3, true, 36), + DartzeeRoundResult(1, false, -38) + ) carousel.update(results, emptyList(), 38) carousel.getPendingRules().shouldContainExactly(scoreEighteens, totalIsFifty, allTwenties) @@ -95,18 +98,22 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `If three darts have been thrown, any remaining rules should get a pending result of success`() - { + fun `If three darts have been thrown, any remaining rules should get a pending result of success`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val carousel = makeCarousel() - val darts = listOf(makeDart(18, 1, SegmentType.INNER_SINGLE), + val darts = + listOf( + makeDart(18, 1, SegmentType.INNER_SINGLE), makeDart(20, 1, SegmentType.OUTER_SINGLE), - makeDart(1, 1, SegmentType.INNER_SINGLE)) + makeDart(1, 1, SegmentType.INNER_SINGLE) + ) carousel.update(emptyList(), darts, 50) - carousel.getPendingRules().shouldContainExactly(twoBlackOneWhite, scoreEighteens, innerOuterInner) + carousel + .getPendingRules() + .shouldContainExactly(twoBlackOneWhite, scoreEighteens, innerOuterInner) val pendingTiles = carousel.pendingTiles.filter { it.isVisible } pendingTiles.forEach { it.pendingResult shouldBe true @@ -115,8 +122,7 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `If no remaining rules are valid, then the first should be shown with a pending result of false`() - { + fun `If no remaining rules are valid, then the first should be shown with a pending result of false`() { val carousel = makeCarousel() carousel.update(emptyList(), listOf(makeDart(20, 0, SegmentType.MISS)), 20) @@ -130,8 +136,7 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Should round up when calculating a failure score`() - { + fun `Should round up when calculating a failure score`() { val carousel = makeCarousel() carousel.update(emptyList(), listOf(makeDart(20, 0, SegmentType.MISS)), 41) @@ -143,8 +148,7 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Should return the union of valid segments based on pending rules`() - { + fun `Should return the union of valid segments based on pending rules`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val dartOne = makeDart(19, 1, SegmentType.OUTER_SINGLE) @@ -163,13 +167,16 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Should toggle between pending and complete tiles`() - { + fun `Should toggle between pending and complete tiles`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val carousel = makeCarousel() - val results = makeRoundResultEntities(DartzeeRoundResult(3, true, 36), DartzeeRoundResult(1, false, -38)) + val results = + makeRoundResultEntities( + DartzeeRoundResult(3, true, 36), + DartzeeRoundResult(1, false, -38) + ) carousel.update(results, emptyList(), 38) carousel.getDisplayedRules().shouldContainExactly(scoreEighteens, totalIsFifty, allTwenties) @@ -182,13 +189,16 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Should hide pending tiles and toggle buttons on gameFinished`() - { + fun `Should hide pending tiles and toggle buttons on gameFinished`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val carousel = makeCarousel() - val results = makeRoundResultEntities(DartzeeRoundResult(3, true, 36), DartzeeRoundResult(1, false, -38)) + val results = + makeRoundResultEntities( + DartzeeRoundResult(3, true, 36), + DartzeeRoundResult(1, false, -38) + ) carousel.update(results, emptyList(), 38) carousel.gameFinished() @@ -199,23 +209,19 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Clicking a tile with no pending result should have no effect`() - { + fun `Clicking a tile with no pending result should have no effect`() { val listener = mockk(relaxed = true) val carousel = makeCarousel(listener) carousel.update(emptyList(), emptyList(), 50) - carousel.pendingTiles.forEach { - it.doClick() - } + carousel.pendingTiles.forEach { it.doClick() } verifyNotCalled { listener.tilePressed(any()) } } @Test - fun `Clicking a tile with a pendingResult should notify the listener`() - { + fun `Clicking a tile with a pendingResult should notify the listener`() { val listener = mockk(relaxed = true) val carousel = makeCarousel(listener) carousel.update(emptyList(), listOf(makeDart(20, 0, SegmentType.MISS)), 20) @@ -230,8 +236,7 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Hovering over a pending tile should notify the listener of that rule's valid segments`() - { + fun `Hovering over a pending tile should notify the listener of that rule's valid segments`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val dartOne = makeDart(19, 1, SegmentType.OUTER_SINGLE) @@ -258,20 +263,22 @@ class TestDartzeeRuleCarousel: AbstractTest() listener.segmentStatuses.validSegments.shouldContainExactlyInAnyOrder(allTwelves) carousel.mouseExited(makeMouseEvent(totalFiftyTile)) - listener.segmentStatuses.validSegments.shouldContainExactlyInAnyOrder(eighteens + allTwelves) + listener.segmentStatuses.validSegments.shouldContainExactlyInAnyOrder( + eighteens + allTwelves + ) } @Test - fun `Should correctly report whether or not it is initialised`() - { + fun `Should correctly report whether or not it is initialised`() { val lock = ReentrantLock() // Mock up a result which will block until we release our hold on the lock val result = mockk(relaxed = true) - every { result.ruleNumber } answers { - lock.lock() - 1 - } + every { result.ruleNumber } answers + { + lock.lock() + 1 + } // Initial value should be false val carousel = makeCarousel() @@ -288,15 +295,15 @@ class TestDartzeeRuleCarousel: AbstractTest() Thread.sleep(1000) carousel.initialised shouldBe false - // Let the other thread go and wait for it to complete. We should see initialised update immediately. + // Let the other thread go and wait for it to complete. We should see initialised update + // immediately. lock.unlock() updateThread.join() carousel.initialised shouldBe true } @Test - fun `Should select the 'hardest' rule for a cautious AI`() - { + fun `Should select the 'hardest' rule for a cautious AI`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val dtos = listOf(twoBlackOneWhite, innerOuterInner, scoreEighteens) @@ -304,12 +311,17 @@ class TestDartzeeRuleCarousel: AbstractTest() val listener = TrackingCarouselListener() val carousel = makeCarousel(listener, dtos) - val darts = listOf(makeDart(18, 1, SegmentType.INNER_SINGLE), + val darts = + listOf( + makeDart(18, 1, SegmentType.INNER_SINGLE), makeDart(20, 1, SegmentType.OUTER_SINGLE), - makeDart(1, 1, SegmentType.INNER_SINGLE)) + makeDart(1, 1, SegmentType.INNER_SINGLE) + ) carousel.update(emptyList(), darts, 50) - carousel.getPendingRules().shouldContainExactly(twoBlackOneWhite, innerOuterInner, scoreEighteens) + carousel + .getPendingRules() + .shouldContainExactly(twoBlackOneWhite, innerOuterInner, scoreEighteens) val ai = makeDartsModel(dartzeePlayStyle = DartzeePlayStyle.CAUTIOUS) carousel.selectRule(ai) @@ -321,8 +333,7 @@ class TestDartzeeRuleCarousel: AbstractTest() } @Test - fun `Should select the highest scoring hardest rule for an aggressive AI`() - { + fun `Should select the highest scoring hardest rule for an aggressive AI`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val dtos = listOf(twoBlackOneWhite, innerOuterInner, scoreEighteens) @@ -330,12 +341,17 @@ class TestDartzeeRuleCarousel: AbstractTest() val listener = TrackingCarouselListener() val carousel = makeCarousel(listener, dtos) - val darts = listOf(makeDart(18, 1, SegmentType.INNER_SINGLE), + val darts = + listOf( + makeDart(18, 1, SegmentType.INNER_SINGLE), makeDart(20, 1, SegmentType.OUTER_SINGLE), - makeDart(1, 1, SegmentType.INNER_SINGLE)) + makeDart(1, 1, SegmentType.INNER_SINGLE) + ) carousel.update(emptyList(), darts, 50) - carousel.getPendingRules().shouldContainExactly(twoBlackOneWhite, innerOuterInner, scoreEighteens) + carousel + .getPendingRules() + .shouldContainExactly(twoBlackOneWhite, innerOuterInner, scoreEighteens) val ai = makeDartsModel(dartzeePlayStyle = DartzeePlayStyle.AGGRESSIVE) carousel.selectRule(ai) @@ -346,26 +362,28 @@ class TestDartzeeRuleCarousel: AbstractTest() result.success shouldBe true } - private class TrackingCarouselListener: IDartzeeCarouselListener - { + private class TrackingCarouselListener : IDartzeeCarouselListener { var segmentStatuses: SegmentStatuses = SegmentStatuses(emptySet(), emptySet()) var roundResult: DartzeeRoundResult? = null - override fun hoverChanged(segmentStatuses: SegmentStatuses) - { + override fun hoverChanged(segmentStatuses: SegmentStatuses) { this.segmentStatuses = segmentStatuses } - override fun tilePressed(dartzeeRoundResult: DartzeeRoundResult) - { + override fun tilePressed(dartzeeRoundResult: DartzeeRoundResult) { this.roundResult = dartzeeRoundResult } } - private fun DartzeeRuleCarousel.getDisplayedTiles() = tilePanel.getAllChildComponentsForType().filter { it.isVisible } + private fun DartzeeRuleCarousel.getDisplayedTiles() = + tilePanel.getAllChildComponentsForType().filter { it.isVisible } + private fun DartzeeRuleCarousel.getDisplayedRules() = getDisplayedTiles().map { it.dto } - private fun makeCarousel(listener: IDartzeeCarouselListener = mockk(relaxed = true), dtos: List = this.dtos) = DartzeeRuleCarousel( - dtos - ).also { it.listener = listener } + + private fun makeCarousel( + listener: IDartzeeCarouselListener = mockk(relaxed = true), + dtos: List = this.dtos + ) = DartzeeRuleCarousel(dtos).also { it.listener = listener } + private fun DartzeeRuleCarousel.getPendingRules() = getAvailableRuleTiles().map { it.dto } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCreationDialog.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCreationDialog.kt index 80a3275a0..b50b8f98f 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCreationDialog.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleCreationDialog.kt @@ -41,15 +41,13 @@ import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.clearAllMocks import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JCheckBox import javax.swing.SwingUtilities +import org.junit.jupiter.api.Test -class TestDartzeeRuleAmendment: AbstractTest() -{ +class TestDartzeeRuleAmendment : AbstractTest() { @Test - fun `Should adjust the dialog title appropriately`() - { + fun `Should adjust the dialog title appropriately`() { val dlg = DartzeeRuleCreationDialog() dlg.amendRule(makeDartzeeRuleDto()) @@ -57,8 +55,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate the ruleName correctly`() - { + fun `Should populate the ruleName correctly`() { val dlg = DartzeeRuleCreationDialog() dlg.amendRule(makeDartzeeRuleDto(ruleName = "My Rule")) @@ -71,8 +68,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate from a 'no darts' rule correctly`() - { + fun `Should populate from a 'no darts' rule correctly`() { val rule = makeDartzeeRuleDto() val dlg = DartzeeRuleCreationDialog() @@ -82,8 +78,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate from an 'at least one' rule correctly`() - { + fun `Should populate from an 'at least one' rule correctly`() { val rule = makeDartzeeRuleDto(makeScoreRule(12)) val dlg = DartzeeRuleCreationDialog() @@ -97,9 +92,14 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate from a 'three darts' rule correctly`() - { - val rule = makeDartzeeRuleDto(makeScoreRule(13), makeColourRule(red = true, green = true), DartzeeDartRuleOdd(), inOrder = false) + fun `Should populate from a 'three darts' rule correctly`() { + val rule = + makeDartzeeRuleDto( + makeScoreRule(13), + makeColourRule(red = true, green = true), + DartzeeDartRuleOdd(), + inOrder = false + ) val dlg = DartzeeRuleCreationDialog() dlg.amendRule(rule) @@ -119,9 +119,14 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate an in order rule correctly`() - { - val rule = makeDartzeeRuleDto(DartzeeDartRuleEven(), DartzeeDartRuleOdd(), DartzeeDartRuleEven(), inOrder = true) + fun `Should populate an in order rule correctly`() { + val rule = + makeDartzeeRuleDto( + DartzeeDartRuleEven(), + DartzeeDartRuleOdd(), + DartzeeDartRuleEven(), + inOrder = true + ) val dlg = DartzeeRuleCreationDialog() dlg.amendRule(rule) @@ -131,8 +136,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate no total rule correctly`() - { + fun `Should populate no total rule correctly`() { val dlg = DartzeeRuleCreationDialog() dlg.amendRule(makeDartzeeRuleDto()) @@ -140,10 +144,11 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate a total rule correctly`() - { + fun `Should populate a total rule correctly`() { val dlg = DartzeeRuleCreationDialog() - dlg.amendRule(makeDartzeeRuleDto(aggregateRule = makeTotalScoreRule(48))) + dlg.amendRule( + makeDartzeeRuleDto(aggregateRule = makeTotalScoreRule(48)) + ) dlg.aggregateSelector.cbDesc.isSelected shouldBe true val totalRule = dlg.aggregateSelector.getSelection() as DartzeeTotalRuleEqualTo @@ -151,8 +156,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should update the rule description`() - { + fun `Should update the rule description`() { val dlg = DartzeeRuleCreationDialog() dlg.amendRule(makeDartzeeRuleDto(DartzeeDartRuleOuter())) @@ -162,8 +166,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should populate allow misses correctly`() - { + fun `Should populate allow misses correctly`() { val dlg = DartzeeRuleCreationDialog() val allowMisses = makeDartzeeRuleDto(allowMisses = true) val disallowMisses = makeDartzeeRuleDto(allowMisses = false) @@ -176,8 +179,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should replace the darzeeRule with new values if Ok is pressed`() - { + fun `Should replace the darzeeRule with new values if Ok is pressed`() { val dlg = DartzeeRuleCreationDialog() val rule = makeDartzeeRuleDto() @@ -193,8 +195,7 @@ class TestDartzeeRuleAmendment: AbstractTest() } @Test - fun `Should leave the old dartzeeRule alone if cancelled`() - { + fun `Should leave the old dartzeeRule alone if cancelled`() { val dlg = DartzeeRuleCreationDialog() val rule = makeDartzeeRuleDto() @@ -209,11 +210,9 @@ class TestDartzeeRuleAmendment: AbstractTest() } } -class TestDartzeeRuleCreationDialogValidation: AbstractTest() -{ +class TestDartzeeRuleCreationDialogValidation : AbstractTest() { @Test - fun `Should prevent an empty rule name`() - { + fun `Should prevent an empty rule name`() { val dlg = showRuleCreationDialog() dlg.clickChild(text = "Custom rule name") dlg.clickOk() @@ -224,8 +223,7 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } @Test - fun `Should prevent a rule name that is too long`() - { + fun `Should prevent a rule name that is too long`() { val ruleName = "a".repeat(1001) val dlg = showRuleCreationDialog() @@ -239,8 +237,7 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } @Test - fun `Should validate all three dart selectors for an all darts rule`() - { + fun `Should validate all three dart selectors for an all darts rule`() { val dlg = showRuleCreationDialog() SwingUtilities.invokeAndWait { @@ -248,7 +245,9 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("Dart 1: You must select at least one colour.") + dialogFactory.errorsShown.shouldContainExactly( + "Dart 1: You must select at least one colour." + ) dlg.dartzeeRule shouldBe null dlg.shouldBeVisible() @@ -259,7 +258,9 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("Dart 2: You must select at least one colour.") + dialogFactory.errorsShown.shouldContainExactly( + "Dart 2: You must select at least one colour." + ) dlg.dartzeeRule shouldBe null dlg.shouldBeVisible() @@ -270,14 +271,15 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("Dart 3: You must select at least one colour.") + dialogFactory.errorsShown.shouldContainExactly( + "Dart 3: You must select at least one colour." + ) dlg.dartzeeRule shouldBe null dlg.shouldBeVisible() } @Test - fun `Should validate the target selector for an 'at least one' dart rule`() - { + fun `Should validate the target selector for an 'at least one' dart rule`() { val dlg = showRuleCreationDialog() SwingUtilities.invokeAndWait { @@ -286,14 +288,15 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } dlg.clickOk() - dialogFactory.errorsShown.shouldContainExactly("Target: You must select at least one colour.") + dialogFactory.errorsShown.shouldContainExactly( + "Target: You must select at least one colour." + ) dlg.dartzeeRule shouldBe null dlg.shouldBeVisible() } @Test - fun `Should detect impossible rules and not return a rule`() - { + fun `Should detect impossible rules and not return a rule`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val dlg = showRuleCreationDialog() @@ -313,8 +316,7 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } @Test - fun `Should dispose if valid`() - { + fun `Should dispose if valid`() { val dlg = showRuleCreationDialog() dlg.clickOk() @@ -322,8 +324,7 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() dlg.shouldNotBeVisible() } - private fun showRuleCreationDialog(): DartzeeRuleCreationDialog - { + private fun showRuleCreationDialog(): DartzeeRuleCreationDialog { val dlg = DartzeeRuleCreationDialog() dlg.isModal = false dlg.isVisible = true @@ -332,11 +333,9 @@ class TestDartzeeRuleCreationDialogValidation: AbstractTest() } } -class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() -{ +class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() { @Test - fun `Should populate an 'at least one' rule correctly`() - { + fun `Should populate an 'at least one' rule correctly`() { val dlg = DartzeeRuleCreationDialog() dlg.rdbtnAtLeastOne.doClick() dlg.targetSelector.comboBoxRuleType.selectByClass() @@ -351,8 +350,7 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } @Test - fun `Should populate an 'all darts' rule correctly`() - { + fun `Should populate an 'all darts' rule correctly`() { val dlg = DartzeeRuleCreationDialog() dlg.rdbtnAllDarts.isSelected = true dlg.cbInOrder.isSelected = false @@ -371,8 +369,7 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } @Test - fun `Should populate in order correctly when checked`() - { + fun `Should populate in order correctly when checked`() { val dlg = DartzeeRuleCreationDialog() dlg.clickOk() @@ -381,8 +378,7 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } @Test - fun `Should populate allowMisses correctly when checked`() - { + fun `Should populate allowMisses correctly when checked`() { val dlg = DartzeeRuleCreationDialog() dlg.cbAllowMisses.isSelected = true @@ -393,8 +389,7 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } @Test - fun `Should populate ruleName correctly when checked`() - { + fun `Should populate ruleName correctly when checked`() { val dlg = DartzeeRuleCreationDialog() dlg.clickChild(text = "Custom rule name") dlg.tfRuleName.text = "My Rule" @@ -405,8 +400,7 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } @Test - fun `Should not populate ruleName when unchecked`() - { + fun `Should not populate ruleName when unchecked`() { val dlg = DartzeeRuleCreationDialog() dlg.clickChild(text = "Custom rule name") dlg.tfRuleName.text = "My Rule" @@ -418,8 +412,7 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } @Test - fun `Should populate a 'no darts' rule correctly`() - { + fun `Should populate a 'no darts' rule correctly`() { val dlg = DartzeeRuleCreationDialog() dlg.rdbtnNoDarts.doClick() dlg.clickOk() @@ -429,8 +422,7 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } @Test - fun `Should populate the total rule correctly`() - { + fun `Should populate the total rule correctly`() { val dlg = DartzeeRuleCreationDialog() dlg.aggregateSelector.cbDesc.doClick() dlg.aggregateSelector.comboBoxRuleType.selectByClass() @@ -441,19 +433,16 @@ class TestDartzeeRuleCreationDialogDtoPopulation : AbstractTest() } } -class TestDartzeeRuleCreationDialogInteraction : AbstractTest() -{ +class TestDartzeeRuleCreationDialogInteraction : AbstractTest() { @Test - fun `Should not return a rule when cancelled`() - { + fun `Should not return a rule when cancelled`() { val dlg = DartzeeRuleCreationDialog() dlg.clickCancel() dlg.dartzeeRule shouldBe null } @Test - fun `Should toggle rule name text field based on checkbox`() - { + fun `Should toggle rule name text field based on checkbox`() { val dlg = DartzeeRuleCreationDialog() dlg.tfRuleName.shouldBeDisabled() @@ -465,12 +454,15 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() } @Test - fun `Should toggle the rule selectors based on radio selection`() - { + fun `Should toggle the rule selectors based on radio selection`() { val dlg = DartzeeRuleCreationDialog() var children = dlg.getAllChildComponentsForType() - children.shouldContainExactlyInAnyOrder(dlg.dartOneSelector, dlg.dartTwoSelector, dlg.dartThreeSelector) + children.shouldContainExactlyInAnyOrder( + dlg.dartOneSelector, + dlg.dartTwoSelector, + dlg.dartThreeSelector + ) children.shouldNotContain(dlg.targetSelector) dlg.rdbtnAtLeastOne.doClick() @@ -479,7 +471,11 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() dlg.rdbtnAllDarts.doClick() children = dlg.getAllChildComponentsForType() - children.shouldContainExactlyInAnyOrder(dlg.dartOneSelector, dlg.dartTwoSelector, dlg.dartThreeSelector) + children.shouldContainExactlyInAnyOrder( + dlg.dartOneSelector, + dlg.dartTwoSelector, + dlg.dartThreeSelector + ) children.shouldNotContain(dlg.targetSelector) dlg.rdbtnNoDarts.doClick() @@ -488,8 +484,7 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() } @Test - fun `Should update the verification panel on initialisation`() - { + fun `Should update the verification panel on initialisation`() { val verificationPanel = mockk(relaxed = true) val dlg = DartzeeRuleCreationDialog(verificationPanel) @@ -499,8 +494,7 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() } @Test - fun `Should update the verification panel when things change`() - { + fun `Should update the verification panel when things change`() { val verificationPanel = mockk(relaxed = true) val dlg = DartzeeRuleCreationDialog(verificationPanel) @@ -514,8 +508,7 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() } @Test - fun `Should update the rule description when combo boxes change`() - { + fun `Should update the rule description when combo boxes change`() { val dlg = DartzeeRuleCreationDialog() dlg.dartOneSelector.comboBoxRuleType.selectByClass() dlg.dartTwoSelector.comboBoxRuleType.selectByClass() @@ -534,9 +527,8 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() } @Test - fun `Should update rule difficulty when the rule changes`() - { - //Need a real calculator for this to actually change + fun `Should update rule difficulty when the rule changes`() { + // Need a real calculator for this to actually change InjectedThings.dartzeeCalculator = DartzeeCalculator() val dlg = DartzeeRuleCreationDialog() @@ -550,8 +542,7 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() } @Test - fun `Should update the rule description when score config changes`() - { + fun `Should update the rule description when score config changes`() { val dlg = DartzeeRuleCreationDialog() val scoreRule = dlg.dartOneSelector.comboBoxRuleType.selectByClass()!! @@ -566,11 +557,11 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() } @Test - fun `Should update the rule description when custom config changes`() - { + fun `Should update the rule description when custom config changes`() { val dlg = DartzeeRuleCreationDialog() - val customRule = dlg.dartOneSelector.comboBoxRuleType.selectByClass()!! + val customRule = + dlg.dartOneSelector.comboBoxRuleType.selectByClass()!! flushEdt() dlg.tfDescription.text shouldBe "Custom → Any → Any" @@ -581,4 +572,4 @@ class TestDartzeeRuleCreationDialogInteraction : AbstractTest() dlg.tfDescription.text shouldBe "Foo → Any → Any" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleRenderer.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleRenderer.kt index 96d5f4b13..3b5edb7a7 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleRenderer.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleRenderer.kt @@ -7,34 +7,35 @@ import dartzee.helper.makeDartzeeRuleDto import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeRuleRenderer: AbstractTest() -{ +class TestDartzeeRuleRenderer : AbstractTest() { @Test - fun `Should render the rule name, falling back on the description for the first column`() - { + fun `Should render the rule name, falling back on the description for the first column`() { val renderer = DartzeeRuleRenderer(0) renderer.getReplacementValue(makeDartzeeRuleDto(ruleName = "My Rule")) shouldBe "My Rule" renderer.getReplacementValue(makeDartzeeRuleDto()) shouldBe "Anything" - renderer.getReplacementValue(makeDartzeeRuleDto(DartzeeDartRuleInner())) shouldBe "Score Inners" + renderer.getReplacementValue(makeDartzeeRuleDto(DartzeeDartRuleInner())) shouldBe + "Score Inners" } @Test - fun `Should render the difficulty for the second column`() - { + fun `Should render the difficulty for the second column`() { val renderer = DartzeeRuleRenderer(1) - val veryEasyRule = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(50)) - val veryHardRule = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(2)) + val veryEasyRule = + makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(50)) + val veryHardRule = + makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(2)) renderer.getReplacementValue(veryEasyRule) shouldBe "Very Easy" renderer.getReplacementValue(veryHardRule) shouldBe "Very Hard" } @Test - fun `Should set cell colours based on rule difficulty`() - { + fun `Should set cell colours based on rule difficulty`() { val renderer = DartzeeRuleRenderer(1) - val veryEasyRule = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(50)) - val veryHardRule = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(2)) + val veryEasyRule = + makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(50)) + val veryHardRule = + makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(2)) renderer.setCellColours(veryEasyRule, true) renderer.foreground shouldBe veryEasyRule.calculationResult!!.getForeground() @@ -46,11 +47,10 @@ class TestDartzeeRuleRenderer: AbstractTest() } @Test - fun `Should use size 20 font`() - { + fun `Should use size 20 font`() { val renderer = DartzeeRuleRenderer(0) renderer.setFontsAndAlignment() renderer.font.size shouldBe 20 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupPanel.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupPanel.kt index 6c5253ab6..4d775ab01 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupPanel.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupPanel.kt @@ -13,21 +13,18 @@ import dartzee.utils.InjectedThings import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe +import java.awt.event.KeyEvent import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test -import java.awt.event.KeyEvent -class TestDartzeeRuleSetupPanel: AbstractTest() -{ +class TestDartzeeRuleSetupPanel : AbstractTest() { @AfterEach - fun afterEach() - { + fun afterEach() { InjectedThings.dartzeeRuleFactory = DartzeeRuleFactory() } @Test - fun `should allow pre-populated rules to be added`() - { + fun `should allow pre-populated rules to be added`() { val rule = makeDartzeeRuleDto(DartzeeDartRuleEven()) val ruleTwo = makeDartzeeRuleDto(DartzeeDartRuleOdd()) @@ -39,11 +36,22 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `should sort rules into difficulty order`() - { - val tenPercentRule = makeDartzeeRuleDto(DartzeeDartRuleEven(), calculationResult = makeDartzeeRuleCalculationResult(10)) - val twentyPercentRule = makeDartzeeRuleDto(DartzeeDartRuleOdd(), calculationResult = makeDartzeeRuleCalculationResult(20)) - val thirtyPercentRule = makeDartzeeRuleDto(DartzeeDartRuleOuter(), calculationResult = makeDartzeeRuleCalculationResult(30)) + fun `should sort rules into difficulty order`() { + val tenPercentRule = + makeDartzeeRuleDto( + DartzeeDartRuleEven(), + calculationResult = makeDartzeeRuleCalculationResult(10) + ) + val twentyPercentRule = + makeDartzeeRuleDto( + DartzeeDartRuleOdd(), + calculationResult = makeDartzeeRuleCalculationResult(20) + ) + val thirtyPercentRule = + makeDartzeeRuleDto( + DartzeeDartRuleOuter(), + calculationResult = makeDartzeeRuleCalculationResult(30) + ) val panel = DartzeeRuleSetupPanel() panel.addRulesToTable(listOf(tenPercentRule, thirtyPercentRule, twentyPercentRule)) @@ -54,8 +62,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should toggle amend & remove buttons based on whether a row is selected`() - { + fun `Should toggle amend & remove buttons based on whether a row is selected`() { val rule = makeDartzeeRuleDto() val panel = DartzeeRuleSetupPanel() @@ -74,8 +81,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should remove the selected rule from the table`() - { + fun `Should remove the selected rule from the table`() { val rule = makeDartzeeRuleDto(DartzeeDartRuleEven()) val ruleTwo = makeDartzeeRuleDto(DartzeeDartRuleOdd()) @@ -89,8 +95,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should remove the selected rule when delete key pressed`() - { + fun `Should remove the selected rule when delete key pressed`() { val rule = makeDartzeeRuleDto(DartzeeDartRuleEven()) val ruleTwo = makeDartzeeRuleDto(DartzeeDartRuleOdd()) @@ -104,8 +109,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should do nothing if delete is pressed with no row selected`() - { + fun `Should do nothing if delete is pressed with no row selected`() { val rule = makeDartzeeRuleDto(DartzeeDartRuleEven()) val ruleTwo = makeDartzeeRuleDto(DartzeeDartRuleOdd()) @@ -118,8 +122,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should support creation of rules`() - { + fun `Should support creation of rules`() { val newRule = makeDartzeeRuleDto() InjectedThings.dartzeeRuleFactory = FakeDartzeeRuleFactory(newRule) @@ -131,8 +134,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should handle cancelling a new rule`() - { + fun `Should handle cancelling a new rule`() { InjectedThings.dartzeeRuleFactory = FakeDartzeeRuleFactory(null) val panel = DartzeeRuleSetupPanel() @@ -143,8 +145,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should handle amending a rule`() - { + fun `Should handle amending a rule`() { val originalRule = makeDartzeeRuleDto(DartzeeDartRuleEven()) val newRule = makeDartzeeRuleDto(DartzeeDartRuleOdd()) @@ -160,8 +161,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should amend a rule when Enter pressed`() - { + fun `Should amend a rule when Enter pressed`() { val originalRule = makeDartzeeRuleDto(DartzeeDartRuleEven()) val newRule = makeDartzeeRuleDto(DartzeeDartRuleOdd()) @@ -177,8 +177,7 @@ class TestDartzeeRuleSetupPanel: AbstractTest() } @Test - fun `Should do nothing if Enter pressed with no row selected`() - { + fun `Should do nothing if Enter pressed with no row selected`() { val originalRule = makeDartzeeRuleDto(DartzeeDartRuleEven()) val newRule = makeDartzeeRuleDto(DartzeeDartRuleOdd()) @@ -191,5 +190,4 @@ class TestDartzeeRuleSetupPanel: AbstractTest() panel.tableRules.rowCount shouldBe 1 panel.getRules() shouldBe listOf(originalRule) } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupScreen.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupScreen.kt index b591863cb..b2631294a 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupScreen.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSetupScreen.kt @@ -20,11 +20,9 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestDartzeeRuleSetupScreen: AbstractTest() -{ +class TestDartzeeRuleSetupScreen : AbstractTest() { @Test - fun `Should have the right title n stuff`() - { + fun `Should have the right title n stuff`() { val scrn = makeDartzeeRuleSetupScreen() scrn.getScreenName() shouldBe "Dartzee - Custom Setup" scrn.getBackTarget().shouldBeInstanceOf() @@ -32,8 +30,7 @@ class TestDartzeeRuleSetupScreen: AbstractTest() } @Test - fun `Should update the next button text based on whether there is a match or not`() - { + fun `Should update the next button text based on whether there is a match or not`() { val scrn = makeDartzeeRuleSetupScreen(match = null) scrn.getNextText() shouldBe "Launch Game" @@ -42,8 +39,7 @@ class TestDartzeeRuleSetupScreen: AbstractTest() } @Test - fun `Should launch a match`() - { + fun `Should launch a match`() { val launcher = mockk(relaxed = true) InjectedThings.gameLauncher = launcher @@ -53,17 +49,20 @@ class TestDartzeeRuleSetupScreen: AbstractTest() val scrn = makeDartzeeRuleSetupScreen(players, match = match) scrn.btnNext.doClick() - verify { launcher.launchNewMatch(match, any())} + verify { launcher.launchNewMatch(match, any()) } } @Test - fun `Should launch a single game and pass pairMode`() - { + fun `Should launch a single game and pass pairMode`() { val launcher = mockk(relaxed = true) InjectedThings.gameLauncher = launcher val players = listOf(insertPlayer(), insertPlayer()) - val rules = listOf(makeDartzeeRuleDto(DartzeeDartRuleOdd()), makeDartzeeRuleDto(DartzeeDartRuleEven())) + val rules = + listOf( + makeDartzeeRuleDto(DartzeeDartRuleOdd()), + makeDartzeeRuleDto(DartzeeDartRuleEven()) + ) val scrn = makeDartzeeRuleSetupScreen(players, true) val panel = scrn.getChild() @@ -80,4 +79,4 @@ class TestDartzeeRuleSetupScreen: AbstractTest() pairMode: Boolean = false, match: DartsMatchEntity? = null ) = DartzeeRuleSetupScreen(match, players, pairMode) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSummaryPanel.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSummaryPanel.kt index 8aba7eea3..d46cb1e3e 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSummaryPanel.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleSummaryPanel.kt @@ -21,24 +21,26 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestDartzeeRuleSummaryPanel: AbstractTest() -{ +class TestDartzeeRuleSummaryPanel : AbstractTest() { @Test - fun `Should show the high score panel by default`() - { + fun `Should show the high score panel by default`() { val summaryPanel = makeSummaryPanel() summaryPanel.components.toList().shouldContainExactly(summaryPanel.panelHighScore) } @Test - fun `Should swap out the high score panel and update the carousel for roundnumber greater than 1`() - { + fun `Should swap out the high score panel and update the carousel for roundnumber greater than 1`() { val carousel = mockk(relaxed = true) val summaryPanel = DartzeeRuleSummaryPanel(carousel) val results = makeRoundResultEntities(DartzeeRoundResult(2, true, 35)) - val darts = listOf(makeDart(19, 1, SegmentType.OUTER_SINGLE), makeDart(7, 1, SegmentType.DOUBLE), makeDart(2, 1, SegmentType.INNER_SINGLE)) + val darts = + listOf( + makeDart(19, 1, SegmentType.OUTER_SINGLE), + makeDart(7, 1, SegmentType.DOUBLE), + makeDart(2, 1, SegmentType.INNER_SINGLE) + ) summaryPanel.update(results, darts, 103, 2) summaryPanel.components.toList().shouldContainExactly(carousel) @@ -46,28 +48,28 @@ class TestDartzeeRuleSummaryPanel: AbstractTest() } @Test - fun `Should return all valid segments if on the scoring round`() - { + fun `Should return all valid segments if on the scoring round`() { val summaryPanel = makeSummaryPanel() - summaryPanel.getSegmentStatus() shouldBe SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) + summaryPanel.getSegmentStatus() shouldBe + SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) } @Test - fun `Should return the carousel segments once past round one`() - { + fun `Should return the carousel segments once past round one`() { val carousel = mockk(relaxed = true) - every { carousel.getSegmentStatus() } returns SegmentStatuses(getOuterSegments(), getOuterSegments()) + every { carousel.getSegmentStatus() } returns + SegmentStatuses(getOuterSegments(), getOuterSegments()) val summaryPanel = DartzeeRuleSummaryPanel(carousel) summaryPanel.update(listOf(), listOf(), 103, 2) - summaryPanel.getSegmentStatus() shouldBe SegmentStatuses(getOuterSegments(), getOuterSegments()) + summaryPanel.getSegmentStatus() shouldBe + SegmentStatuses(getOuterSegments(), getOuterSegments()) } @Test - fun `Should swap in the carousel and call gameFinished`() - { + fun `Should swap in the carousel and call gameFinished`() { val carousel = mockk(relaxed = true) val summaryPanel = DartzeeRuleSummaryPanel(carousel) @@ -78,8 +80,7 @@ class TestDartzeeRuleSummaryPanel: AbstractTest() } @Test - fun `Should call through to the carousel to select a tile`() - { + fun `Should call through to the carousel to select a tile`() { val carousel = mockk(relaxed = true) val model = beastDartsModel() @@ -90,15 +91,15 @@ class TestDartzeeRuleSummaryPanel: AbstractTest() } @Test - fun `Should wait for the carousel to be initialised`() - { + fun `Should wait for the carousel to be initialised`() { val carousel = mockk(relaxed = true) var repetitions = 0 - every { carousel.initialised } answers { - repetitions++ - repetitions == 6 - } + every { carousel.initialised } answers + { + repetitions++ + repetitions == 6 + } val panel = DartzeeRuleSummaryPanel(carousel) @@ -112,6 +113,5 @@ class TestDartzeeRuleSummaryPanel: AbstractTest() repetitions shouldBe 6 } - private fun makeSummaryPanel() = - DartzeeRuleSummaryPanel(mockk(relaxed = true)) -} \ No newline at end of file + private fun makeSummaryPanel() = DartzeeRuleSummaryPanel(mockk(relaxed = true)) +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTile.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTile.kt index 17cf32ffe..021f196e5 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTile.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTile.kt @@ -10,11 +10,9 @@ import dartzee.screen.game.dartzee.DartzeeRuleTile import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartzeeRuleTile: AbstractTest() -{ +class TestDartzeeRuleTile : AbstractTest() { @Test - fun `Should initialise with the rule number and description`() - { + fun `Should initialise with the rule number and description`() { val dto = makeDartzeeRuleDto() val tile = FakeDartzeeRuleTile(dto, 2) @@ -22,9 +20,9 @@ class TestDartzeeRuleTile: AbstractTest() } @Test - fun `Should escape special characters in the description`() - { - val dto = makeDartzeeRuleDto(aggregateRule = makeTotalScoreRule(20)) + fun `Should escape special characters in the description`() { + val dto = + makeDartzeeRuleDto(aggregateRule = makeTotalScoreRule(20)) val tile = FakeDartzeeRuleTile(dto, 3) @@ -32,18 +30,17 @@ class TestDartzeeRuleTile: AbstractTest() } @Test - fun `Should initialise with the rule number and name, escaping special characters`() - { + fun `Should initialise with the rule number and name, escaping special characters`() { val dto = makeDartzeeRuleDto(ruleName = "> Awesome Rule <") val tile = FakeDartzeeRuleTile(dto, 4) - tile.text shouldBe "
#4

> Awesome Rule <
" + tile.text shouldBe + "
#4

> Awesome Rule <
" } @Test - fun `Should show rule description on hover if no score is set`() - { + fun `Should show rule description on hover if no score is set`() { val dto = makeDartzeeRuleDto(ruleName = "Awesome Rule") val tile = FakeDartzeeRuleTile(dto, 2) @@ -54,8 +51,7 @@ class TestDartzeeRuleTile: AbstractTest() } @Test - fun `Should change the button text to the score on hover, and revert it on mouse exited`() - { + fun `Should change the button text to the score on hover, and revert it on mouse exited`() { val dto = makeDartzeeRuleDto() val tile = FakeDartzeeRuleTile(dto, 2) @@ -71,8 +67,7 @@ class TestDartzeeRuleTile: AbstractTest() } @Test - fun `Should set the button text on hover correctly for negative scores`() - { + fun `Should set the button text on hover correctly for negative scores`() { val dto = makeDartzeeRuleDto() val tile = FakeDartzeeRuleTile(dto, 2) tile.score = -10 @@ -81,10 +76,10 @@ class TestDartzeeRuleTile: AbstractTest() tile.text shouldBe "
- 10
" } - private class FakeDartzeeRuleTile(dto: DartzeeRuleDto, ruleNumber: Int): DartzeeRuleTile(dto, ruleNumber) - { + private class FakeDartzeeRuleTile(dto: DartzeeRuleDto, ruleNumber: Int) : + DartzeeRuleTile(dto, ruleNumber) { var score: Int? = null override fun getScoreForHover() = score } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTileComplete.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTileComplete.kt index aeb85b988..c38bca2d1 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTileComplete.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTileComplete.kt @@ -4,18 +4,15 @@ import dartzee.helper.AbstractTest import dartzee.helper.makeDartzeeRuleDto import dartzee.screen.game.dartzee.DartzeeRuleTileComplete import dartzee.screen.game.dartzee.SoftDisableButtonModel -import io.kotest.matchers.types.shouldBeInstanceOf import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test +import io.kotest.matchers.types.shouldBeInstanceOf import java.awt.Color +import org.junit.jupiter.api.Test -class TestDartzeeRuleTileComplete: AbstractTest() -{ +class TestDartzeeRuleTileComplete : AbstractTest() { @Test - fun `Should use a disabled button model and set the colours to green for success`() - { - val tile = - DartzeeRuleTileComplete(makeDartzeeRuleDto(), 2, true, 5) + fun `Should use a disabled button model and set the colours to green for success`() { + val tile = DartzeeRuleTileComplete(makeDartzeeRuleDto(), 2, true, 5) tile.model.shouldBeInstanceOf() tile.isFocusable shouldBe false @@ -25,12 +22,10 @@ class TestDartzeeRuleTileComplete: AbstractTest() } @Test - fun `Should set the colours to red for a failed rule`() - { - val tile = - DartzeeRuleTileComplete(makeDartzeeRuleDto(), 2, false, -15) + fun `Should set the colours to red for a failed rule`() { + val tile = DartzeeRuleTileComplete(makeDartzeeRuleDto(), 2, false, -15) tile.background shouldBe Color.RED tile.getScoreForHover() shouldBe -15 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTilePending.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTilePending.kt index fcc2eda76..344389a8e 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTilePending.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleTilePending.kt @@ -15,14 +15,12 @@ import dartzee.utils.getAllNonMissSegments import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color +import org.junit.jupiter.api.Test -class TestDartzeeRuleTilePending: AbstractTest() -{ +class TestDartzeeRuleTilePending : AbstractTest() { @Test - fun `Should initially have no pending result or score`() - { + fun `Should initially have no pending result or score`() { val tile = DartzeeRuleTilePending(makeDartzeeRuleDto(), 5) tile.pendingScore shouldBe null @@ -31,14 +29,11 @@ class TestDartzeeRuleTilePending: AbstractTest() } @Test - fun `Should show or hide based on whether the rule is valid for the darts thrown`() - { + fun `Should show or hide based on whether the rule is valid for the darts thrown`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() - val tile = DartzeeRuleTilePending( - makeDartzeeRuleDto(makeScoreRule(15), allowMisses = false), - 5 - ) + val tile = + DartzeeRuleTilePending(makeDartzeeRuleDto(makeScoreRule(15), allowMisses = false), 5) tile.updateState(listOf(makeDart(20, 0, SegmentType.MISS))) tile.isVisible shouldBe false @@ -47,36 +42,55 @@ class TestDartzeeRuleTilePending: AbstractTest() } @Test - fun `Should use the cached calculation result when getting valid segments and no darts have been thrown`() - { + fun `Should use the cached calculation result when getting valid segments and no darts have been thrown`() { val segments = listOf(doubleNineteen, trebleTwenty) - val rule = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(validSegments = segments)) + val rule = + makeDartzeeRuleDto( + calculationResult = makeDartzeeRuleCalculationResult(validSegments = segments) + ) val tile = DartzeeRuleTilePending(rule, 2) - tile.getSegmentStatus(listOf()).validSegments.shouldContainExactlyInAnyOrder(doubleNineteen, trebleTwenty) + tile + .getSegmentStatus(listOf()) + .validSegments + .shouldContainExactlyInAnyOrder(doubleNineteen, trebleTwenty) } @Test - fun `Should calculate valid segments based on the rule if one or more darts have been thrown`() - { + fun `Should calculate valid segments based on the rule if one or more darts have been thrown`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() - val rule = makeDartzeeRuleDto(makeScoreRule(20), makeScoreRule(18), makeScoreRule(19), inOrder = true) + val rule = + makeDartzeeRuleDto( + makeScoreRule(20), + makeScoreRule(18), + makeScoreRule(19), + inOrder = true + ) val tile = DartzeeRuleTilePending(rule, 2) - tile.getSegmentStatus(listOf(makeDart(18, 1, SegmentType.OUTER_SINGLE))).validSegments.shouldBeEmpty() + tile + .getSegmentStatus(listOf(makeDart(18, 1, SegmentType.OUTER_SINGLE))) + .validSegments + .shouldBeEmpty() val eighteenSegments = getAllNonMissSegments().filter { it.score == 18 }.toTypedArray() - tile.getSegmentStatus(listOf(makeDart(20, 1, SegmentType.OUTER_SINGLE))).validSegments.shouldContainExactlyInAnyOrder(*eighteenSegments) + tile + .getSegmentStatus(listOf(makeDart(20, 1, SegmentType.OUTER_SINGLE))) + .validSegments + .shouldContainExactlyInAnyOrder(*eighteenSegments) - val twoDarts = listOf(makeDart(20, 2, SegmentType.DOUBLE), makeDart(18, 2, SegmentType.DOUBLE)) + val twoDarts = + listOf(makeDart(20, 2, SegmentType.DOUBLE), makeDart(18, 2, SegmentType.DOUBLE)) val nineteenSegments = getAllNonMissSegments().filter { it.score == 19 }.toTypedArray() - tile.getSegmentStatus(twoDarts).validSegments.shouldContainExactlyInAnyOrder(*nineteenSegments) + tile + .getSegmentStatus(twoDarts) + .validSegments + .shouldContainExactlyInAnyOrder(*nineteenSegments) } @Test - fun `Should set colour to red or green when a pending result is set`() - { + fun `Should set colour to red or green when a pending result is set`() { val tile = DartzeeRuleTilePending(makeDartzeeRuleDto(), 2) tile.setPendingResult(true, 50) @@ -91,4 +105,4 @@ class TestDartzeeRuleTilePending: AbstractTest() tile.getScoreForHover() shouldBe -25 tile.background shouldBe Color.RED } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleVerificationPanel.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleVerificationPanel.kt index 5d544f15e..167b16011 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleVerificationPanel.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeRuleVerificationPanel.kt @@ -18,28 +18,34 @@ import dartzee.utils.getAllNonMissSegments import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import java.awt.Dimension import javax.swing.JFrame +import org.junit.jupiter.api.Test -class TestDartzeeRuleVerificationPanel: AbstractTest() -{ +class TestDartzeeRuleVerificationPanel : AbstractTest() { @Test - fun `Should not re-run rule calculation if 0 darts thrown`() - { + fun `Should not re-run rule calculation if 0 darts thrown`() { val panel = DartzeeRuleVerificationPanel() - val dto = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(listOf(DartboardSegment(SegmentType.DOUBLE, 20)))) + val dto = + makeDartzeeRuleDto( + calculationResult = + makeDartzeeRuleCalculationResult( + listOf(DartboardSegment(SegmentType.DOUBLE, 20)) + ) + ) panel.updateRule(dto) - panel.dartboard.segmentStatuses()!!.scoringSegments.shouldContainExactly(DartboardSegment(SegmentType.DOUBLE, 20)) + panel.dartboard + .segmentStatuses()!! + .scoringSegments + .shouldContainExactly(DartboardSegment(SegmentType.DOUBLE, 20)) } @Test - fun `Should update the dart history and clear it on reset`() - { + fun `Should update the dart history and clear it on reset`() { val panel = DartzeeRuleVerificationPanel() panel.updateRule(makeDartzeeRuleDto()) @@ -52,8 +58,7 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() } @Test - fun `Should calculate the total based on the rule`() - { + fun `Should calculate the total based on the rule`() { val panel = DartzeeRuleVerificationPanel() panel.updateRule(makeDartzeeRuleDto(dart1Rule = makeScoreRule(2))) @@ -63,8 +68,7 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() } @Test - fun `Should update the dartboard with valid segments as darts are thrown`() - { + fun `Should update the dartboard with valid segments as darts are thrown`() { val panel = DartzeeRuleVerificationPanel() val dartboard = panel.dartboard @@ -82,13 +86,12 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() dartboard.segmentStatuses()!!.validSegments.shouldContainExactly(getFakeValidSegment(2)) panel.dartThrown(makeDart(20, 2, SegmentType.DOUBLE)) - //Shouldn't update on the last dart thrown + // Shouldn't update on the last dart thrown dartboard.segmentStatuses()!!.validSegments.shouldContainExactly(getFakeValidSegment(2)) } @Test - fun `Should stay blue while the rule is still possible, and go green when 3 valid darts are thrown`() - { + fun `Should stay blue while the rule is still possible, and go green when 3 valid darts are thrown`() { val panel = DartzeeRuleVerificationPanel() val rule = makeDartzeeRuleDto() @@ -108,8 +111,7 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() } @Test - fun `Should go red and invalidate the total as soon as an invalid dart is thrown`() - { + fun `Should go red and invalidate the total as soon as an invalid dart is thrown`() { val panel = DartzeeRuleVerificationPanel() val rule = makeDartzeeRuleDto() @@ -124,8 +126,7 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() } @Test - fun `Should update dartboard colour when the rule changes`() - { + fun `Should update dartboard colour when the rule changes`() { val panel = DartzeeRuleVerificationPanel() val rule = makeDartzeeRuleDto() @@ -143,8 +144,7 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() } @Test - fun `Should reset color when darts are cleared`() - { + fun `Should reset color when darts are cleared`() { val panel = DartzeeRuleVerificationPanel() val rule = makeDartzeeRuleDto() @@ -160,9 +160,8 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() } @Test - fun `Should update combinations text when darts are thrown`() - { - val panel = DartzeeRuleVerificationPanel() + fun `Should update combinations text when darts are thrown`() { + val panel = DartzeeRuleVerificationPanel() val rule = makeDartzeeRuleDto() rule.runStrengthCalculation() @@ -174,8 +173,7 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() } @Test - fun `Should stop listening for clicks once three darts have been thrown, and listen again when reset is pressed`() - { + fun `Should stop listening for clicks once three darts have been thrown, and listen again when reset is pressed`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val panel = DartzeeRuleVerificationPanel() @@ -185,7 +183,10 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() frame.isVisible = true flushEdt() - val rule = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(getAllNonMissSegments())) + val rule = + makeDartzeeRuleDto( + calculationResult = makeDartzeeRuleCalculationResult(getAllNonMissSegments()) + ) panel.updateRule(rule) panel.dartboard.throwDartByClick() @@ -204,19 +205,18 @@ class TestDartzeeRuleVerificationPanel: AbstractTest() panel.dartsThrown.size shouldBe 1 } - private fun DartzeeRuleVerificationPanel.shouldBeBlue() - { + private fun DartzeeRuleVerificationPanel.shouldBeBlue() { tfResult.foreground shouldBe Color.WHITE background shouldBe DartsColour.COLOUR_PASTEL_BLUE } - private fun DartzeeRuleVerificationPanel.shouldBeRed() - { + + private fun DartzeeRuleVerificationPanel.shouldBeRed() { tfResult.foreground shouldBe Color.RED background shouldBe DartsColour.getDarkenedColour(Color.RED) } - private fun DartzeeRuleVerificationPanel.shouldBeGreen() - { + + private fun DartzeeRuleVerificationPanel.shouldBeGreen() { tfResult.foreground shouldBe Color.GREEN background shouldBe DartsColour.getDarkenedColour(Color.GREEN) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateDialog.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateDialog.kt index 1b5875175..d9131b141 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateDialog.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateDialog.kt @@ -1,11 +1,11 @@ package dartzee.screen.dartzee +import com.github.alyssaburlton.swingtest.clickCancel +import com.github.alyssaburlton.swingtest.clickOk import com.github.alyssaburlton.swingtest.getChild import com.github.alyssaburlton.swingtest.shouldBeVisible import com.github.alyssaburlton.swingtest.shouldNotBeVisible import com.github.alyssaburlton.swingtest.typeText -import com.github.alyssaburlton.swingtest.clickCancel -import com.github.alyssaburlton.swingtest.clickOk import dartzee.core.helper.verifyNotCalled import dartzee.dartzee.dart.DartzeeDartRuleEven import dartzee.dartzee.dart.DartzeeDartRuleOdd @@ -23,14 +23,12 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestDartzeeTemplateDialog: AbstractTest() -{ +class TestDartzeeTemplateDialog : AbstractTest() { @Test - fun `Should show an error if template name not specified`() - { + fun `Should show an error if template name not specified`() { val (dialog, callback) = showDialog() dialog.clickOk() @@ -40,8 +38,7 @@ class TestDartzeeTemplateDialog: AbstractTest() } @Test - fun `Should show an error if 0 rules are specified`() - { + fun `Should show an error if 0 rules are specified`() { val (dialog) = showDialog() dialog.getChild().typeText("My template") dialog.clickOk() @@ -51,8 +48,7 @@ class TestDartzeeTemplateDialog: AbstractTest() } @Test - fun `Should show an error if only 1 rule is specified`() - { + fun `Should show an error if only 1 rule is specified`() { val (dialog) = showDialog() dialog.getChild().typeText("My template") @@ -64,14 +60,21 @@ class TestDartzeeTemplateDialog: AbstractTest() } @Test - fun `Should insert the template and rules and dispose if valid`() - { + fun `Should insert the template and rules and dispose if valid`() { val (dialog, callback) = showDialog() dialog.getChild().typeText("ABC") - val tenPercentRule = makeDartzeeRuleDto(DartzeeDartRuleEven(), calculationResult = makeDartzeeRuleCalculationResult(10)) - val twentyPercentRule = makeDartzeeRuleDto(DartzeeDartRuleOdd(), calculationResult = makeDartzeeRuleCalculationResult(20)) + val tenPercentRule = + makeDartzeeRuleDto( + DartzeeDartRuleEven(), + calculationResult = makeDartzeeRuleCalculationResult(10) + ) + val twentyPercentRule = + makeDartzeeRuleDto( + DartzeeDartRuleOdd(), + calculationResult = makeDartzeeRuleCalculationResult(20) + ) dialog.rulePanel.addRulesToTable(listOf(twentyPercentRule, tenPercentRule)) dialog.clickOk() @@ -80,7 +83,7 @@ class TestDartzeeTemplateDialog: AbstractTest() dialog.shouldNotBeVisible() verify { callback() } - //Template should be set on the dialog, and should have been saved to the DB + // Template should be set on the dialog, and should have been saved to the DB val template = DartzeeTemplateEntity().retrieveEntities().only() template.name shouldBe "ABC" template.retrievedFromDb shouldBe true @@ -88,13 +91,13 @@ class TestDartzeeTemplateDialog: AbstractTest() val rules = DartzeeRuleEntity().retrieveForTemplate(template.rowId).sortedBy { it.ordinal } rules.size shouldBe 2 - rules[0].toDto().generateRuleDescription() shouldBe twentyPercentRule.generateRuleDescription() + rules[0].toDto().generateRuleDescription() shouldBe + twentyPercentRule.generateRuleDescription() rules[1].toDto().generateRuleDescription() shouldBe tenPercentRule.generateRuleDescription() } @Test - fun `Should not create a template if cancelled`() - { + fun `Should not create a template if cancelled`() { val (dialog, callback) = showDialog() dialog.clickCancel() @@ -105,8 +108,7 @@ class TestDartzeeTemplateDialog: AbstractTest() } @Test - fun `Should copy the name and rules from the provided template`() - { + fun `Should copy the name and rules from the provided template`() { val template = insertDartzeeTemplate(name = "ABC") val rule = makeDartzeeRuleDto(DartzeeDartRuleEven()) @@ -125,11 +127,10 @@ class TestDartzeeTemplateDialog: AbstractTest() rules[1].generateRuleDescription() shouldBe ruleTwo.generateRuleDescription() } - private fun showDialog(): Pair Unit> - { + private fun showDialog(): Pair Unit> { val callback = mockk<() -> Unit>(relaxed = true) val dialog = DartzeeTemplateDialog(callback) dialog.isVisible = true return dialog to callback } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateRuleRenderer.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateRuleRenderer.kt index 8fa47db48..bc73ff5f5 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateRuleRenderer.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateRuleRenderer.kt @@ -6,15 +6,13 @@ import dartzee.helper.AbstractTest import dartzee.helper.makeDartzeeRuleCalculationResult import dartzee.helper.makeDartzeeRuleDto import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.JLabel +import org.junit.jupiter.api.Test -class TestDartzeeTemplateRuleRenderer: AbstractTest() -{ +class TestDartzeeTemplateRuleRenderer : AbstractTest() { @Test - fun `Should render squares of the right colour based on rule difficulty`() - { + fun `Should render squares of the right colour based on rule difficulty`() { val renderer = DartzeeTemplateRuleRenderer() val ruleOne = makeDartzeeRuleDto(calculationResult = makeDartzeeRuleCalculationResult(20)) @@ -34,8 +32,7 @@ class TestDartzeeTemplateRuleRenderer: AbstractTest() } @Test - fun `Should supply a tooltip for the number of rules`() - { + fun `Should supply a tooltip for the number of rules`() { val renderer = DartzeeTemplateRuleRenderer() val lbl = renderer.getLabel(listOf(makeDartzeeRuleDto())) @@ -45,6 +42,6 @@ class TestDartzeeTemplateRuleRenderer: AbstractTest() lbl2.toolTipText shouldBe "2 rules" } - fun DartzeeTemplateRuleRenderer.getLabel(rules: List) = getReplacementValue(rules) as JLabel - + fun DartzeeTemplateRuleRenderer.getLabel(rules: List) = + getReplacementValue(rules) as JLabel } diff --git a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateSetupScreen.kt b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateSetupScreen.kt index 116288880..fc6d47fa1 100644 --- a/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateSetupScreen.kt +++ b/src/test/kotlin/dartzee/screen/dartzee/TestDartzeeTemplateSetupScreen.kt @@ -29,17 +29,15 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.event.KeyEvent import javax.swing.JButton import javax.swing.JOptionPane import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestDartzeeTemplateSetupScreen: AbstractTest() -{ +class TestDartzeeTemplateSetupScreen : AbstractTest() { @Test - fun `Should pull through a game count of 0 for templates where no games have been played`() - { + fun `Should pull through a game count of 0 for templates where no games have been played`() { insertTemplateAndRule() val scrn = DartzeeTemplateSetupScreen() @@ -49,8 +47,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should pull through the right game count for templates where games have been played`() - { + fun `Should pull through the right game count for templates where games have been played`() { val templateId = insertTemplateAndRule().rowId insertGame(gameType = GameType.DARTZEE, gameParams = templateId) @@ -63,8 +60,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should toggle copy, remove and rename buttons based on whether a row is selected`() - { + fun `Should toggle copy, remove and rename buttons based on whether a row is selected`() { insertTemplateAndRule() val scrn = DartzeeTemplateSetupScreen() @@ -86,8 +82,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should leave template alone if delete is cancelled`() - { + fun `Should leave template alone if delete is cancelled`() { insertTemplateAndRule(name = "ABC") dialogFactory.questionOption = JOptionPane.NO_OPTION @@ -97,14 +92,15 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() scrn.getChild().selectRow(0) scrn.clickChild("delete") - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to delete the ABC Template?") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to delete the ABC Template?" + ) scrn.getChild().rowCount shouldBe 1 getCountFromTable(EntityName.DartzeeTemplate) shouldBe 1 } @Test - fun `Should delete a template and associated rules on confirmation`() - { + fun `Should delete a template and associated rules on confirmation`() { insertTemplateAndRule(name = "ABC") dialogFactory.questionOption = JOptionPane.YES_OPTION @@ -114,7 +110,9 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() scrn.getChild().selectRow(0) scrn.clickChild("delete") - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to delete the ABC Template?") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to delete the ABC Template?" + ) scrn.getChild().rowCount shouldBe 0 getCountFromTable(EntityName.DartzeeTemplate) shouldBe 0 @@ -122,8 +120,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should support deleting by using the keyboard shortcut`() - { + fun `Should support deleting by using the keyboard shortcut`() { insertTemplateAndRule(name = "ABC") dialogFactory.questionOption = JOptionPane.YES_OPTION @@ -133,7 +130,9 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() scrn.getChild().selectRow(0) scrn.getChild().processKeyPress(KeyEvent.VK_DELETE) - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to delete the ABC Template?") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to delete the ABC Template?" + ) scrn.getChild().rowCount shouldBe 0 getCountFromTable(EntityName.DartzeeTemplate) shouldBe 0 @@ -141,8 +140,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Pressing delete with no row selected should do nothing`() - { + fun `Pressing delete with no row selected should do nothing`() { insertTemplateAndRule(name = "ABC") dialogFactory.questionOption = JOptionPane.YES_OPTION @@ -158,8 +156,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should revert games to Custom on deletion and show a different confirmation message`() - { + fun `Should revert games to Custom on deletion and show a different confirmation message`() { dialogFactory.questionOption = JOptionPane.YES_OPTION val templateId = insertTemplateAndRule(name = "ABC").rowId @@ -173,15 +170,16 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() scrn.getChild().selectRow(0) scrn.clickChild("delete") - dialogFactory.questionsShown.shouldContainExactly("You have played 2 games using the ABC Template." + - "\n\nThese will become custom games if you delete it. Are you sure you want to continue?") + dialogFactory.questionsShown.shouldContainExactly( + "You have played 2 games using the ABC Template." + + "\n\nThese will become custom games if you delete it. Are you sure you want to continue?" + ) GameEntity().retrieveEntities().forEach { it.gameParams shouldBe "" } } @Test - fun `Should not add a template if cancelled`() - { + fun `Should not add a template if cancelled`() { val scrn = DartzeeTemplateSetupScreen() scrn.initialise() scrn.clickChild("add") @@ -193,8 +191,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should add a template to the table upon creation`() - { + fun `Should add a template to the table upon creation`() { val scrn = DartzeeTemplateSetupScreen() scrn.initialise() @@ -211,8 +208,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should do nothing if template copying is cancelled`() - { + fun `Should do nothing if template copying is cancelled`() { insertTemplateAndRule(name = "ABC") val scrn = DartzeeTemplateSetupScreen() @@ -228,8 +224,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should copy a template and add it to the table`() - { + fun `Should copy a template and add it to the table`() { insertTemplateAndRule(name = "ABC") val scrn = DartzeeTemplateSetupScreen() @@ -248,8 +243,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should support renaming a template`() - { + fun `Should support renaming a template`() { val id = insertTemplateAndRule(name = "Old").rowId dialogFactory.inputSelection = "New" @@ -268,8 +262,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should do nothing if rename is cancelled`() - { + fun `Should do nothing if rename is cancelled`() { insertTemplateAndRule(name = "ABC") dialogFactory.inputSelection = null @@ -284,8 +277,7 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() } @Test - fun `Should render the rules associated to the template`() - { + fun `Should render the rules associated to the template`() { val template = insertDartzeeTemplate() val ruleOne = makeDartzeeRuleDto(DartzeeDartRuleEven()) @@ -298,7 +290,12 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() scrn.initialise() val rules = scrn.getChild().getValueAt(0, 1) as List<*> - rules.map { (it as DartzeeRuleDto).generateRuleDescription() }.shouldContainExactly(ruleOne.generateRuleDescription(), ruleTwo.generateRuleDescription()) + rules + .map { (it as DartzeeRuleDto).generateRuleDescription() } + .shouldContainExactly( + ruleOne.generateRuleDescription(), + ruleTwo.generateRuleDescription() + ) } private fun DartzeeTemplateSetupScreen.getTemplate(row: Int) = @@ -306,4 +303,4 @@ class TestDartzeeTemplateSetupScreen: AbstractTest() private fun DartzeeTemplateSetupScreen.getGameCount(row: Int) = getChild().getValueAt(row, 2) as Int -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/AbstractGameStatisticsPanelTest.kt b/src/test/kotlin/dartzee/screen/game/AbstractGameStatisticsPanelTest.kt index 231ce5972..fcf24dbc1 100644 --- a/src/test/kotlin/dartzee/screen/game/AbstractGameStatisticsPanelTest.kt +++ b/src/test/kotlin/dartzee/screen/game/AbstractGameStatisticsPanelTest.kt @@ -8,50 +8,50 @@ import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -abstract class AbstractGameStatisticsPanelTest, S: AbstractGameStatisticsPanel>: AbstractTest() -{ +abstract class AbstractGameStatisticsPanelTest< + PlayerState : AbstractPlayerState, + S : AbstractGameStatisticsPanel +> : AbstractTest() { abstract fun factoryStatsPanel(): S + abstract fun makePlayerState(): PlayerState - protected fun S.shouldHaveBreakdownState(expected: Map) - { + protected fun S.shouldHaveBreakdownState(expected: Map) { val breakdownRows = getHistogramRows() - breakdownRows.forEach { - getValueForRow(it) shouldBe (expected[it] ?: 0) - } + breakdownRows.forEach { getValueForRow(it) shouldBe (expected[it] ?: 0) } } @Test - fun `Categorised rows should all exist in the table model`() - { + fun `Categorised rows should all exist in the table model`() { val statsPanel = factoryStatsPanel() statsPanel.showStats(listOf(makePlayerState())) val rowNames = statsPanel.getAllRowNames() - val categorisedRows = statsPanel.getRankedRowsHighestWins() + statsPanel.getRankedRowsLowestWins() + statsPanel.getHistogramRows() + val categorisedRows = + statsPanel.getRankedRowsHighestWins() + + statsPanel.getRankedRowsLowestWins() + + statsPanel.getHistogramRows() rowNames.shouldContainAll(categorisedRows) } } -private fun AbstractGameStatisticsPanel<*>.getAllRowNames(): List -{ +private fun AbstractGameStatisticsPanel<*>.getAllRowNames(): List { val rows = 0 until tm.rowCount return rows.map { tm.getValueAt(it, 0) as String } } fun AbstractGameStatisticsPanel<*>.getRowIndex(rowName: String) = getAllRowNames().indexOf(rowName) -fun AbstractGameStatisticsPanel<*>.getValueForRow(rowIndex: Int, column: Int = 1): Any? = tm.getValueAt(rowIndex, column) +fun AbstractGameStatisticsPanel<*>.getValueForRow(rowIndex: Int, column: Int = 1): Any? = + tm.getValueAt(rowIndex, column) -fun AbstractGameStatisticsPanel<*>.getValueForRow(rowName: String, column: Int = 1): Any? -{ +fun AbstractGameStatisticsPanel<*>.getValueForRow(rowName: String, column: Int = 1): Any? { val rowIndex = getAllRowNames().indexOf(rowName) - if (rowIndex > -1) - { + if (rowIndex > -1) { return tm.getValueAt(rowIndex, column) } logger.error(LoggingCode("invalidRow"), "No row called $rowName") return null -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/GameTestFactory.kt b/src/test/kotlin/dartzee/screen/game/GameTestFactory.kt index ef888f8cd..1581113cc 100644 --- a/src/test/kotlin/dartzee/screen/game/GameTestFactory.kt +++ b/src/test/kotlin/dartzee/screen/game/GameTestFactory.kt @@ -26,11 +26,13 @@ import dartzee.screen.game.x01.GamePanelX01 import dartzee.screen.game.x01.GameStatisticsPanelX01 fun makeSingleParticipant(player: PlayerEntity, gameId: String? = null) = - makeSingleParticipant(insertParticipant(playerId = player.rowId, gameId = gameId ?: insertGame().rowId)) + makeSingleParticipant( + insertParticipant(playerId = player.rowId, gameId = gameId ?: insertGame().rowId) + ) + fun makeSingleParticipant(pt: ParticipantEntity = insertParticipant()) = SingleParticipant(pt) -fun makeTeam(vararg players: PlayerEntity, gameId: String = randomGuid()): TeamParticipant -{ +fun makeTeam(vararg players: PlayerEntity, gameId: String = randomGuid()): TeamParticipant { val team = insertTeam(gameId = gameId) val pts = players.map { insertParticipant(playerId = it.rowId, gameId = gameId) } return TeamParticipant(team, pts) @@ -38,70 +40,76 @@ fun makeTeam(vararg players: PlayerEntity, gameId: String = randomGuid()): TeamP fun makeGolfGamePanel(currentPlayerId: String = randomGuid(), gameParams: String = "18") = GamePanelGolf( - FakeDartsScreen(), - insertGame(gameType = GameType.GOLF, gameParams = gameParams), - 1).apply { testInit(currentPlayerId) } + FakeDartsScreen(), + insertGame(gameType = GameType.GOLF, gameParams = gameParams), + 1 + ) + .apply { testInit(currentPlayerId) } fun makeGolfGamePanel(pt: IWrappedParticipant) = - GamePanelGolf( - FakeDartsScreen(), - insertGame(gameType = GameType.GOLF, gameParams = "18"), - 1).apply { testInit(pt) } + GamePanelGolf(FakeDartsScreen(), insertGame(gameType = GameType.GOLF, gameParams = "18"), 1) + .apply { testInit(pt) } fun makeX01GamePanel(currentPlayerId: String = randomGuid(), gameParams: String = "501") = - GamePanelX01(FakeDartsScreen(), insertGame(gameType = GameType.X01, gameParams = gameParams), 1).apply { testInit(currentPlayerId) } + GamePanelX01(FakeDartsScreen(), insertGame(gameType = GameType.X01, gameParams = gameParams), 1) + .apply { testInit(currentPlayerId) } fun makeX01GamePanel(pt: IWrappedParticipant, gameParams: String = "501") = - GamePanelX01(FakeDartsScreen(), insertGame(gameType = GameType.X01, gameParams = gameParams), 1).apply { testInit(pt) } + GamePanelX01(FakeDartsScreen(), insertGame(gameType = GameType.X01, gameParams = gameParams), 1) + .apply { testInit(pt) } fun makeRoundTheClockGamePanel(playerId: String = randomGuid()) = GamePanelRoundTheClock( - FakeDartsScreen(), - insertGame(gameType = GameType.ROUND_THE_CLOCK, gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson()), - 1).apply { testInit(playerId) } + FakeDartsScreen(), + insertGame( + gameType = GameType.ROUND_THE_CLOCK, + gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson() + ), + 1 + ) + .apply { testInit(playerId) } fun makeRoundTheClockGamePanel(pt: IWrappedParticipant) = GamePanelRoundTheClock( - FakeDartsScreen(), - insertGame(gameType = GameType.ROUND_THE_CLOCK, gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson()), - 1).apply { testInit(pt) } - -fun DartsGamePanel<*, *>.testInit(playerId: String) -{ + FakeDartsScreen(), + insertGame( + gameType = GameType.ROUND_THE_CLOCK, + gameParams = RoundTheClockConfig(ClockType.Standard, true).toJson() + ), + 1 + ) + .apply { testInit(pt) } + +fun DartsGamePanel<*, *>.testInit(playerId: String) { val player = insertPlayer(playerId) val pt = makeSingleParticipant(player) startNewGame(listOf(pt)) } -fun DartsGamePanel<*, *>.testInit(pt: IWrappedParticipant) -{ +fun DartsGamePanel<*, *>.testInit(pt: IWrappedParticipant) { startNewGame(listOf(pt)) } -fun DartsGamePanel<*, *>.setDartsThrown(dartsThrown: List) -{ +fun DartsGamePanel<*, *>.setDartsThrown(dartsThrown: List) { btnReset.doClick() dartsThrown.forEach(::dartThrown) } -fun DartsGamePanel<*, *>.addCompletedRound(vararg dartsThrown: Dart) -{ +fun DartsGamePanel<*, *>.addCompletedRound(vararg dartsThrown: Dart) { addCompletedRound(dartsThrown.toList()) } -fun DartsGamePanel<*, *>.addCompletedRound(dartsThrown: List) -{ +fun DartsGamePanel<*, *>.addCompletedRound(dartsThrown: List) { setDartsThrown(dartsThrown) btnConfirm.doClick() } -fun > DartsGamePanel<*, PlayerState>.updateAchievementsForFinish(finishingPosition: Int, score: Int) -{ +fun > DartsGamePanel<*, PlayerState> + .updateAchievementsForFinish(finishingPosition: Int, score: Int) { updateAchievementsForFinish(getPlayerStates().first(), finishingPosition, score) } -fun DartsGamePanel<*, *>.doAiTurn(model: DartsAiModel) -{ +fun DartsGamePanel<*, *>.doAiTurn(model: DartsAiModel) { val pt = computeAiDart(model) ?: return dartboard.dartThrown(pt) } @@ -111,8 +119,7 @@ fun makeMatchSummaryPanel( statsPanel: GameStatisticsPanelX01 = GameStatisticsPanelX01("501") ) = MatchSummaryPanel(match, statsPanel) -class FakeDartsScreen : AbstractDartsGameScreen() -{ +class FakeDartsScreen : AbstractDartsGameScreen() { override val windowName = "Fake" var gameId: String? = null @@ -120,16 +127,16 @@ class FakeDartsScreen : AbstractDartsGameScreen() var achievementType: AchievementType? = null var attainedValue: Int? = null - override fun achievementUnlocked(gameId: String, playerId: String, achievement: AbstractAchievement) - { + override fun achievementUnlocked( + gameId: String, + playerId: String, + achievement: AbstractAchievement + ) { this.gameId = gameId this.playerId = playerId this.achievementType = achievement.achievementType this.attainedValue = achievement.attainedValue } - override fun fireAppearancePreferencesChanged() - { - - } -} \ No newline at end of file + override fun fireAppearancePreferencesChanged() {} +} diff --git a/src/test/kotlin/dartzee/screen/game/TestAbstractGameStatisticsPanel.kt b/src/test/kotlin/dartzee/screen/game/TestAbstractGameStatisticsPanel.kt index b2584d31b..11f6de500 100644 --- a/src/test/kotlin/dartzee/screen/game/TestAbstractGameStatisticsPanel.kt +++ b/src/test/kotlin/dartzee/screen/game/TestAbstractGameStatisticsPanel.kt @@ -10,22 +10,28 @@ import dartzee.helper.makeX01PlayerState import dartzee.shouldHaveColours import dartzee.utils.DartsColour import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JComponent +import org.junit.jupiter.api.Test - -class TestAbstractGameStatisticsPanel: AbstractTest() -{ +class TestAbstractGameStatisticsPanel : AbstractTest() { @Test - fun `Should combine like participants and preserve original player order`() - { + fun `Should combine like participants and preserve original player order`() { val clive = insertPlayer(name = "Clive") val alice = insertPlayer(name = "Alice") - val cliveState1 = makeX01PlayerState(player = clive, completedRound = listOf(makeDart(), makeDart(), makeDart())) + val cliveState1 = + makeX01PlayerState( + player = clive, + completedRound = listOf(makeDart(), makeDart(), makeDart()) + ) val aliceState1 = makeX01PlayerState(player = alice, completedRound = listOf(makeDart())) - val aliceState2 = makeX01PlayerState(player = alice, completedRound = listOf(makeDart(), makeDart())) - val cliveState2 = makeX01PlayerState(player = clive, completedRound = listOf(makeDart(), makeDart(), makeDart(), makeDart(), makeDart())) + val aliceState2 = + makeX01PlayerState(player = alice, completedRound = listOf(makeDart(), makeDart())) + val cliveState2 = + makeX01PlayerState( + player = clive, + completedRound = listOf(makeDart(), makeDart(), makeDart(), makeDart(), makeDart()) + ) val panel = FakeGameStatisticsPanel() panel.showStats(listOf(cliveState1, aliceState1, aliceState2, cliveState2)) @@ -40,10 +46,13 @@ class TestAbstractGameStatisticsPanel: AbstractTest() } @Test - fun `Should clear down previous stats`() - { + fun `Should clear down previous stats`() { val clive = insertPlayer(name = "Clive") - val cliveState1 = makeX01PlayerState(player = clive, completedRound = listOf(makeDart(), makeDart(), makeDart())) + val cliveState1 = + makeX01PlayerState( + player = clive, + completedRound = listOf(makeDart(), makeDart(), makeDart()) + ) val panel = FakeGameStatisticsPanel() panel.showStats(listOf(cliveState1)) @@ -54,10 +63,8 @@ class TestAbstractGameStatisticsPanel: AbstractTest() panel.getValueForRow("Darts Thrown", 1) shouldBe 1 } - @Test - fun `Should show nothing if there is insufficient data`() - { + fun `Should show nothing if there is insufficient data`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") @@ -71,17 +78,41 @@ class TestAbstractGameStatisticsPanel: AbstractTest() } @Test - fun `Should calculate best game correctly`() - { + fun `Should calculate best game correctly`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") - val aliceState1 = makeX01PlayerState(player = alice, participant = insertParticipant(playerId = alice.rowId, finalScore = 50), completedRound = listOf(makeDart())) - val aliceState2 = makeX01PlayerState(player = alice, participant = insertParticipant(playerId = alice.rowId, finalScore = 35), completedRound = listOf(makeDart())) - - val bobState1 = makeX01PlayerState(player = bob, participant = insertParticipant(playerId = bob.rowId, finalScore = 28), completedRound = listOf(makeDart())) - val bobState2 = makeX01PlayerState(player = bob, participant = insertParticipant(playerId = bob.rowId, finalScore = 70), completedRound = listOf(makeDart())) - val bobState3 = makeX01PlayerState(player = bob, participant = insertParticipant(playerId = bob.rowId, finalScore = -1), completedRound = listOf(makeDart())) + val aliceState1 = + makeX01PlayerState( + player = alice, + participant = insertParticipant(playerId = alice.rowId, finalScore = 50), + completedRound = listOf(makeDart()) + ) + val aliceState2 = + makeX01PlayerState( + player = alice, + participant = insertParticipant(playerId = alice.rowId, finalScore = 35), + completedRound = listOf(makeDart()) + ) + + val bobState1 = + makeX01PlayerState( + player = bob, + participant = insertParticipant(playerId = bob.rowId, finalScore = 28), + completedRound = listOf(makeDart()) + ) + val bobState2 = + makeX01PlayerState( + player = bob, + participant = insertParticipant(playerId = bob.rowId, finalScore = 70), + completedRound = listOf(makeDart()) + ) + val bobState3 = + makeX01PlayerState( + player = bob, + participant = insertParticipant(playerId = bob.rowId, finalScore = -1), + completedRound = listOf(makeDart()) + ) val panel = FakeGameStatisticsPanel() panel.showStats(listOf(aliceState1, bobState1, bobState2, aliceState2, bobState3)) @@ -91,16 +122,35 @@ class TestAbstractGameStatisticsPanel: AbstractTest() } @Test - fun `Should calculate avg game correctly`() - { + fun `Should calculate avg game correctly`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") - val aliceState1 = makeX01PlayerState(player = alice, participant = insertParticipant(playerId = alice.rowId, finalScore = 50), completedRound = listOf(makeDart())) - val aliceState2 = makeX01PlayerState(player = alice, participant = insertParticipant(playerId = alice.rowId, finalScore = 35), completedRound = listOf(makeDart())) - - val bobState1 = makeX01PlayerState(player = bob, participant = insertParticipant(playerId = bob.rowId, finalScore = 28), completedRound = listOf(makeDart())) - val bobState2 = makeX01PlayerState(player = bob, participant = insertParticipant(playerId = bob.rowId, finalScore = 70), completedRound = listOf(makeDart())) + val aliceState1 = + makeX01PlayerState( + player = alice, + participant = insertParticipant(playerId = alice.rowId, finalScore = 50), + completedRound = listOf(makeDart()) + ) + val aliceState2 = + makeX01PlayerState( + player = alice, + participant = insertParticipant(playerId = alice.rowId, finalScore = 35), + completedRound = listOf(makeDart()) + ) + + val bobState1 = + makeX01PlayerState( + player = bob, + participant = insertParticipant(playerId = bob.rowId, finalScore = 28), + completedRound = listOf(makeDart()) + ) + val bobState2 = + makeX01PlayerState( + player = bob, + participant = insertParticipant(playerId = bob.rowId, finalScore = 70), + completedRound = listOf(makeDart()) + ) val panel = FakeGameStatisticsPanel() panel.showStats(listOf(aliceState1, bobState1, bobState2, aliceState2)) @@ -110,8 +160,7 @@ class TestAbstractGameStatisticsPanel: AbstractTest() } @Test - fun `Should replace NULL values with NA`() - { + fun `Should replace NULL values with NA`() { val state = makeX01PlayerState(completedRound = listOf(makeDart())) val panel = FakeGameStatisticsPanel() @@ -120,16 +169,29 @@ class TestAbstractGameStatisticsPanel: AbstractTest() panel.getValueForRow("Nulls", 1) shouldBe "N/A" } - /** - * Couple of renderer tests just to prove it's being set on all appropriate columns - */ + /** Couple of renderer tests just to prove it's being set on all appropriate columns */ @Test - fun `Should colour highest wins rows correctly`() - { - val state1 = makeX01PlayerState(player = insertPlayer(name = "Alice"), completedRound = listOf(makeDart(), makeDart(), makeDart())) - val state2 = makeX01PlayerState(player = insertPlayer(name = "Bob"), completedRound = listOf(makeDart())) - val state3 = makeX01PlayerState(player = insertPlayer(name = "Clive"), completedRound = listOf(makeDart(), makeDart())) - val state4 = makeX01PlayerState(player = insertPlayer(name = "Derek"), completedRound = listOf(makeDart(), makeDart(), makeDart(), makeDart())) + fun `Should colour highest wins rows correctly`() { + val state1 = + makeX01PlayerState( + player = insertPlayer(name = "Alice"), + completedRound = listOf(makeDart(), makeDart(), makeDart()) + ) + val state2 = + makeX01PlayerState( + player = insertPlayer(name = "Bob"), + completedRound = listOf(makeDart()) + ) + val state3 = + makeX01PlayerState( + player = insertPlayer(name = "Clive"), + completedRound = listOf(makeDart(), makeDart()) + ) + val state4 = + makeX01PlayerState( + player = insertPlayer(name = "Derek"), + completedRound = listOf(makeDart(), makeDart(), makeDart(), makeDart()) + ) val panel = FakeGameStatisticsPanel(highestWins = listOf("Darts Thrown")) panel.showStats(listOf(state1, state2, state3, state4)) @@ -141,12 +203,27 @@ class TestAbstractGameStatisticsPanel: AbstractTest() } @Test - fun `Should colour lowest wins rows correctly`() - { - val state1 = makeX01PlayerState(player = insertPlayer(name = "Alice"), completedRound = listOf(makeDart(), makeDart(), makeDart())) - val state2 = makeX01PlayerState(player = insertPlayer(name = "Bob"), completedRound = listOf(makeDart())) - val state3 = makeX01PlayerState(player = insertPlayer(name = "Clive"), completedRound = listOf(makeDart(), makeDart())) - val state4 = makeX01PlayerState(player = insertPlayer(name = "Derek"), completedRound = listOf(makeDart(), makeDart(), makeDart(), makeDart())) + fun `Should colour lowest wins rows correctly`() { + val state1 = + makeX01PlayerState( + player = insertPlayer(name = "Alice"), + completedRound = listOf(makeDart(), makeDart(), makeDart()) + ) + val state2 = + makeX01PlayerState( + player = insertPlayer(name = "Bob"), + completedRound = listOf(makeDart()) + ) + val state3 = + makeX01PlayerState( + player = insertPlayer(name = "Clive"), + completedRound = listOf(makeDart(), makeDart()) + ) + val state4 = + makeX01PlayerState( + player = insertPlayer(name = "Derek"), + completedRound = listOf(makeDart(), makeDart(), makeDart(), makeDart()) + ) val panel = FakeGameStatisticsPanel(lowestWins = listOf("Darts Thrown")) panel.showStats(listOf(state1, state2, state3, state4)) @@ -158,12 +235,16 @@ class TestAbstractGameStatisticsPanel: AbstractTest() } } -private class FakeGameStatisticsPanel(private val highestWins: List = emptyList(), - private val lowestWins: List = emptyList()): AbstractGameStatisticsPanel() -{ +private class FakeGameStatisticsPanel( + private val highestWins: List = emptyList(), + private val lowestWins: List = emptyList() +) : AbstractGameStatisticsPanel() { override fun getRankedRowsHighestWins() = highestWins + override fun getRankedRowsLowestWins() = lowestWins + override fun getHistogramRows() = emptyList() + override fun getStartOfSectionRows() = emptyList() override fun addRowsToTable() { @@ -173,17 +254,17 @@ private class FakeGameStatisticsPanel(private val highestWins: List = em addRow(getNullRow()) } - private fun getDartsThrownRow() = prepareRow("Darts Thrown") { playerName -> - val darts = hmPlayerToDarts[playerName].orEmpty() - darts.map { it.size }.sum() - } + private fun getDartsThrownRow() = + prepareRow("Darts Thrown") { playerName -> + val darts = hmPlayerToDarts[playerName].orEmpty() + darts.map { it.size }.sum() + } private fun getNullRow() = prepareRow("Nulls") { null } - fun getCellComponent(row: Int, column: Int): JComponent - { + fun getCellComponent(row: Int, column: Int): JComponent { val renderer = table.getColumn(column).cellRenderer - return renderer.getTableCellRendererComponent(table.table, null, false, false, row, column) as JComponent + return renderer.getTableCellRendererComponent(table.table, null, false, false, row, column) + as JComponent } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestDartsGamePanel.kt b/src/test/kotlin/dartzee/screen/game/TestDartsGamePanel.kt index c23687c9c..fe6eea4d7 100644 --- a/src/test/kotlin/dartzee/screen/game/TestDartsGamePanel.kt +++ b/src/test/kotlin/dartzee/screen/game/TestDartsGamePanel.kt @@ -21,11 +21,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartsGamePanel : AbstractTest() -{ +class TestDartsGamePanel : AbstractTest() { @Test - fun `Should insert a win achievement for both players on a team`() - { + fun `Should insert a win achievement for both players on a team`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val panel = TestGamePanel() @@ -33,18 +31,29 @@ class TestDartsGamePanel : AbstractTest() panel.updateAchievementsForFinish(1, 50) - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactly( - AchievementSummary(AchievementType.X01_TEAM_GAMES_WON, -1, panel.gameEntity.rowId, "50"), - ) - - retrieveAchievementsForPlayer(p2.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.X01_TEAM_GAMES_WON, -1, panel.gameEntity.rowId, "50"), - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactly( + AchievementSummary( + AchievementType.X01_TEAM_GAMES_WON, + -1, + panel.gameEntity.rowId, + "50" + ), + ) + + retrieveAchievementsForPlayer(p2.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary( + AchievementType.X01_TEAM_GAMES_WON, + -1, + panel.gameEntity.rowId, + "50" + ), + ) } @Test - fun `Should not unlock team win achievement if game was not won`() - { + fun `Should not unlock team win achievement if game was not won`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val panel = TestGamePanel() @@ -56,32 +65,32 @@ class TestDartsGamePanel : AbstractTest() } @Test - fun `Should unlock individual win achievement`() - { + fun `Should unlock individual win achievement`() { val panel = TestGamePanel() val pt = makeSingleParticipant(insertPlayer(), panel.gameEntity.rowId) panel.startNewGame(listOf(pt)) panel.updateAchievementsForFinish(1, 50) - retrieveAchievementsForPlayer(pt.participant.playerId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.X01_GAMES_WON, -1, panel.gameEntity.rowId, "50"), - AchievementSummary(AchievementType.X01_BEST_GAME, 50, panel.gameEntity.rowId), - ) + retrieveAchievementsForPlayer(pt.participant.playerId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.X01_GAMES_WON, -1, panel.gameEntity.rowId, "50"), + AchievementSummary(AchievementType.X01_BEST_GAME, 50, panel.gameEntity.rowId), + ) } @Test - fun `Should not unlock individual win achievement if they did not place first`() - { + fun `Should not unlock individual win achievement if they did not place first`() { val panel = TestGamePanel() val pt = makeSingleParticipant(insertPlayer(), panel.gameEntity.rowId) panel.startNewGame(listOf(pt)) panel.updateAchievementsForFinish(3, 50) - retrieveAchievementsForPlayer(pt.participant.playerId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.X01_BEST_GAME, 50, panel.gameEntity.rowId), - ) + retrieveAchievementsForPlayer(pt.participant.playerId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.X01_BEST_GAME, 50, panel.gameEntity.rowId), + ) } class TestGamePanel(gameParams: String = "501") : @@ -89,12 +98,10 @@ class TestDartsGamePanel : AbstractTest() FakeDartsScreen(), insertGame(gameType = GameType.X01, gameParams = gameParams), 1 - ) - { + ) { override fun factoryState(pt: IWrappedParticipant) = X01PlayerState(501, pt) - override fun computeAiDart(model: DartsAiModel): ComputedPoint? - { + override fun computeAiDart(model: DartsAiModel): ComputedPoint? { val currentScore = getCurrentPlayerState().getRemainingScore() return model.throwX01Dart(currentScore) } @@ -105,7 +112,7 @@ class TestDartsGamePanel : AbstractTest() override fun factoryStatsPanel(gameParams: String) = GameStatisticsPanelX01(gameParams) - override fun factoryScorer(participant: IWrappedParticipant) = DartsScorerX01(this, gameEntity.gameParams, participant) + override fun factoryScorer(participant: IWrappedParticipant) = + DartsScorerX01(this, gameEntity.gameParams, participant) } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestDartsGameScreen.kt b/src/test/kotlin/dartzee/screen/game/TestDartsGameScreen.kt index fb30cacfd..9d82ff4b1 100644 --- a/src/test/kotlin/dartzee/screen/game/TestDartsGameScreen.kt +++ b/src/test/kotlin/dartzee/screen/game/TestDartsGameScreen.kt @@ -9,11 +9,9 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestDartsGameScreen: AbstractTest() -{ +class TestDartsGameScreen : AbstractTest() { @Test - fun `Should initialise correctly`() - { + fun `Should initialise correctly`() { val game = insertGame() val scrn = DartsGameScreen(game, 4) @@ -22,8 +20,7 @@ class TestDartsGameScreen: AbstractTest() } @Test - fun `Should pass through to its gamePanel`() - { + fun `Should pass through to its gamePanel`() { val game = insertGame() val scrn = DartsGameScreen(game, 4) @@ -36,4 +33,4 @@ class TestDartsGameScreen: AbstractTest() scrn.achievementUnlocked("foo", "bar", achievement) verify { scrn.gamePanel.achievementUnlocked("bar", achievement) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestDartsMatchScreen.kt b/src/test/kotlin/dartzee/screen/game/TestDartsMatchScreen.kt index 7a39d3bcc..a3029afec 100644 --- a/src/test/kotlin/dartzee/screen/game/TestDartsMatchScreen.kt +++ b/src/test/kotlin/dartzee/screen/game/TestDartsMatchScreen.kt @@ -24,16 +24,14 @@ import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.awt.Dimension import javax.swing.JTabbedPane import javax.swing.SwingUtilities +import org.junit.jupiter.api.Test -class TestDartsMatchScreen: AbstractTest() -{ +class TestDartsMatchScreen : AbstractTest() { @Test - fun `Should pop up achievement unlocks on the correct tab`() - { + fun `Should pop up achievement unlocks on the correct tab`() { val scrn = setUpMatchScreen() val g1 = insertGame() @@ -48,10 +46,9 @@ class TestDartsMatchScreen: AbstractTest() verifyNotCalled { panelOne.achievementUnlocked(any(), any()) } verify { panelTwo.achievementUnlocked("player", achievement) } } - + @Test - fun `Should add games to the tabbed pane, as well as the screen cache`() - { + fun `Should add games to the tabbed pane, as well as the screen cache`() { val scrn = setUpMatchScreen() val game = insertGame() @@ -62,8 +59,7 @@ class TestDartsMatchScreen: AbstractTest() } @Test - fun `Should update title based on selected tab`() - { + fun `Should update title based on selected tab`() { val match = insertDartsMatch(gameParams = "501") val scrn = setUpMatchScreen(match) @@ -85,8 +81,7 @@ class TestDartsMatchScreen: AbstractTest() } @Test - fun `Should fire appearance updates to child tabs`() - { + fun `Should fire appearance updates to child tabs`() { val scrn = setUpMatchScreen() val g = insertGame() @@ -97,8 +92,7 @@ class TestDartsMatchScreen: AbstractTest() } @Test - fun `Should flick to the correct tab when told to display a certain game`() - { + fun `Should flick to the correct tab when told to display a certain game`() { val scrn = setUpMatchScreen() val tabbedPane = scrn.getChild() @@ -115,12 +109,10 @@ class TestDartsMatchScreen: AbstractTest() } @Test - fun `Should pass certain fns through to the match summary panel`() - { + fun `Should pass certain fns through to the match summary panel`() { val matchSummaryPanel = mockk>(relaxed = true) val scrn = setUpMatchScreen(matchSummaryPanel = matchSummaryPanel) - val state = makeX01PlayerState() scrn.addParticipant(500L, state) verify { matchSummaryPanel.addParticipant(500L, state) } @@ -130,8 +122,7 @@ class TestDartsMatchScreen: AbstractTest() } @Test - fun `Should mark the match as complete if no more games need to be played`() - { + fun `Should mark the match as complete if no more games need to be played`() { val match = insertDartsMatch(games = 1, gameParams = "501") val scrn = setUpMatchScreen(match = match) @@ -148,8 +139,7 @@ class TestDartsMatchScreen: AbstractTest() } @Test - fun `Should start a new game if the match is not yet complete`() - { + fun `Should start a new game if the match is not yet complete`() { val p1 = insertPlayer(name = "Amy") val p2 = insertPlayer(name = "Billie") val gameOneStates = listOf(p1, p2).map { makeX01PlayerState(player = it) } @@ -164,7 +154,7 @@ class TestDartsMatchScreen: AbstractTest() scrn.startNextGameIfNecessaryOnEdt() - //Game panel should have been added and had a game kicked off + // Game panel should have been added and had a game kicked off val gamePanel = scrn.getChild { it.gameEntity != firstGame } verify { gamePanel.startNewGame(any()) } @@ -178,8 +168,7 @@ class TestDartsMatchScreen: AbstractTest() } @Test - fun `Should not repack the screen when a new game is launched`() - { + fun `Should not repack the screen when a new game is launched`() { val p1 = insertPlayer(name = "Amy") val p2 = insertPlayer(name = "Billie") val gameOneStates = listOf(p1, p2).map { makeX01PlayerState(player = it) } @@ -199,20 +188,23 @@ class TestDartsMatchScreen: AbstractTest() private fun setUpMatchScreen( match: DartsMatchEntity = insertDartsMatch(gameParams = "501"), - matchSummaryPanel: MatchSummaryPanel = MatchSummaryPanel(match, MatchStatisticsPanelX01(match.gameParams)) - ): FakeMatchScreen - { + matchSummaryPanel: MatchSummaryPanel = + MatchSummaryPanel(match, MatchStatisticsPanelX01(match.gameParams)) + ): FakeMatchScreen { PlayerImageEntity().createPresets() return FakeMatchScreen(match, matchSummaryPanel) } } -private class FakeMatchScreen(match: DartsMatchEntity, - matchSummaryPanel: MatchSummaryPanel): - DartsMatchScreen(matchSummaryPanel, match) -{ - override fun factoryGamePanel(parent: AbstractDartsGameScreen, game: GameEntity, totalPlayers: Int): GamePanelX01 - { +private class FakeMatchScreen( + match: DartsMatchEntity, + matchSummaryPanel: MatchSummaryPanel +) : DartsMatchScreen(matchSummaryPanel, match) { + override fun factoryGamePanel( + parent: AbstractDartsGameScreen, + game: GameEntity, + totalPlayers: Int + ): GamePanelX01 { val panel = mockk(relaxed = true) every { panel.gameEntity } returns game every { panel.gameTitle } returns "${game.localId}" @@ -220,19 +212,14 @@ private class FakeMatchScreen(match: DartsMatchEntity, return panel } - fun addGameToMatchOnEdt(gameEntity: GameEntity): DartsGamePanel<*, *> - { + fun addGameToMatchOnEdt(gameEntity: GameEntity): DartsGamePanel<*, *> { var panel: DartsGamePanel<*, *>? = null - SwingUtilities.invokeAndWait { - panel = addGameToMatch(gameEntity, 2) - } + SwingUtilities.invokeAndWait { panel = addGameToMatch(gameEntity, 2) } return panel!! } - fun startNextGameIfNecessaryOnEdt() - { + fun startNextGameIfNecessaryOnEdt() { SwingUtilities.invokeAndWait { startNextGameIfNecessary() } } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestGamePanelDartzee.kt b/src/test/kotlin/dartzee/screen/game/TestGamePanelDartzee.kt index 73eab1d10..9deea9684 100644 --- a/src/test/kotlin/dartzee/screen/game/TestGamePanelDartzee.kt +++ b/src/test/kotlin/dartzee/screen/game/TestGamePanelDartzee.kt @@ -69,28 +69,26 @@ import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.mockk.verifySequence -import org.junit.jupiter.api.Test import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestGamePanelDartzee: AbstractTest() -{ - private val ruleResults = listOf( - DartzeeRoundResult(2, true, 50), - DartzeeRoundResult(1, false, -115), - DartzeeRoundResult(3, true, 18), - DartzeeRoundResult(4, true, -66), - ) +class TestGamePanelDartzee : AbstractTest() { + private val ruleResults = + listOf( + DartzeeRoundResult(2, true, 50), + DartzeeRoundResult(1, false, -115), + DartzeeRoundResult(3, true, 18), + DartzeeRoundResult(4, true, -66), + ) @Test - fun `Should initialise totalRounds based on the number of rules`() - { + fun `Should initialise totalRounds based on the number of rules`() { makeGamePanel(listOf(makeDartzeeRuleDto())).totalRounds shouldBe 2 makeGamePanel(listOf(makeDartzeeRuleDto(), makeDartzeeRuleDto())).totalRounds shouldBe 3 } @Test - fun `Should register itself as a listener on the carousel`() - { + fun `Should register itself as a listener on the carousel`() { val carousel = DartzeeRuleCarousel(testRules) val summaryPanel = DartzeeRuleSummaryPanel(carousel) @@ -99,8 +97,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should not show the convert to template button if game is already part of a template`() - { + fun `Should not show the convert to template button if game is already part of a template`() { val template = insertDartzeeTemplate() val g = insertGame(gameType = GameType.DARTZEE, gameParams = template.rowId) val panel = makeGamePanel(testRules, game = g) @@ -108,8 +105,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should convert to a template, hiding the button and updating the window title`() - { + fun `Should convert to a template, hiding the button and updating the window title`() { val g = insertGame(gameType = GameType.DARTZEE, gameParams = "") val parentWindow = FakeDartsScreen() @@ -128,8 +124,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should not hide the button or update window title if template generation is cancelled`() - { + fun `Should not hide the button or update window title if template generation is cancelled`() { val g = insertGame(gameType = GameType.DARTZEE, gameParams = "") val parentWindow = FakeDartsScreen() @@ -146,8 +141,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should tell the summaryPanel to finish and select the first player when loading a finished game`() - { + fun `Should tell the summaryPanel to finish and select the first player when loading a finished game`() { val game = setUpDartzeeGameOnDatabase(5) val summaryPanel = mockk(relaxed = true) @@ -160,8 +154,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should load scores and results correctly`() - { + fun `Should load scores and results correctly`() { val game = setUpDartzeeGameOnDatabase(5) val carousel = DartzeeRuleCarousel(testRules) val summaryPanel = DartzeeRuleSummaryPanel(carousel) @@ -190,8 +183,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should not update best game achievement for too few rules`() - { + fun `Should not update best game achievement for too few rules`() { val shorterRules = testRules.subList(0, 2) val player = insertPlayer() @@ -208,12 +200,12 @@ class TestGamePanelDartzee: AbstractTest() gamePanel.dartThrown(makeDart(20, 0, SegmentType.MISS)) carousel.getDisplayedTiles().first().doClick() - retrieveAchievementForDetail(AchievementType.DARTZEE_BEST_GAME, player.rowId, "") shouldBe null + retrieveAchievementForDetail(AchievementType.DARTZEE_BEST_GAME, player.rowId, "") shouldBe + null } @Test - fun `Should update best game achievement if there are 5 or more rules`() - { + fun `Should update best game achievement if there are 5 or more rules`() { val player = insertPlayer() val game = setUpDartzeeGameOnDatabase(4, player) val carousel = DartzeeRuleCarousel(testRules) @@ -228,20 +220,21 @@ class TestGamePanelDartzee: AbstractTest() gamePanel.dartThrown(makeDart(20, 0, SegmentType.MISS)) carousel.getDisplayedTiles().first().doClick() - val achievement = retrieveAchievementForDetail(AchievementType.DARTZEE_BEST_GAME, player.rowId, "")!! + val achievement = + retrieveAchievementForDetail(AchievementType.DARTZEE_BEST_GAME, player.rowId, "")!! achievement.achievementCounter shouldBe 13 achievement.gameIdEarned shouldBe game.rowId } @Test - fun `Should update flawless achievement if all rules passed`() - { - val allPassed = listOf( - DartzeeRoundResult(2, true, 50), - DartzeeRoundResult(1, true, 35), - DartzeeRoundResult(3, true, 18), - DartzeeRoundResult(4, true, 40), - ) + fun `Should update flawless achievement if all rules passed`() { + val allPassed = + listOf( + DartzeeRoundResult(2, true, 50), + DartzeeRoundResult(1, true, 35), + DartzeeRoundResult(3, true, 18), + DartzeeRoundResult(4, true, 40), + ) val player = insertPlayer() val game = setUpDartzeeGameOnDatabase(5, player, allPassed) @@ -252,15 +245,15 @@ class TestGamePanelDartzee: AbstractTest() gamePanel.loadGame(loadParticipants(game.rowId)) gamePanel.updateAchievementsForFinish(-1, 180) - val achievement = retrieveAchievementForDetail(AchievementType.DARTZEE_FLAWLESS, player.rowId, "")!! + val achievement = + retrieveAchievementForDetail(AchievementType.DARTZEE_FLAWLESS, player.rowId, "")!! achievement.achievementCounter shouldBe 180 achievement.achievementDetail shouldBe "" achievement.gameIdEarned shouldBe game.rowId } @Test - fun `Should not update flawless achievement if a rule was failed`() - { + fun `Should not update flawless achievement if a rule was failed`() { val player = insertPlayer() val game = setUpDartzeeGameOnDatabase(5, player) val carousel = DartzeeRuleCarousel(testRules) @@ -274,14 +267,14 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should update under pressure achievement if hardest rule passed last`() - { - val hardestPassedLast = listOf( - DartzeeRoundResult(2, true, 50), - DartzeeRoundResult(1, true, 35), - DartzeeRoundResult(3, true, 18), - DartzeeRoundResult(4, true, 50), - ) + fun `Should update under pressure achievement if hardest rule passed last`() { + val hardestPassedLast = + listOf( + DartzeeRoundResult(2, true, 50), + DartzeeRoundResult(1, true, 35), + DartzeeRoundResult(3, true, 18), + DartzeeRoundResult(4, true, 50), + ) val player = insertPlayer() val game = setUpDartzeeGameOnDatabase(5, player, hardestPassedLast) @@ -292,21 +285,26 @@ class TestGamePanelDartzee: AbstractTest() gamePanel.loadGame(loadParticipants(game.rowId)) gamePanel.updateAchievementsForFinish(-1, 180) - val achievement = retrieveAchievementForDetail(AchievementType.DARTZEE_UNDER_PRESSURE, player.rowId, totalIsFifty.getDisplayName())!! + val achievement = + retrieveAchievementForDetail( + AchievementType.DARTZEE_UNDER_PRESSURE, + player.rowId, + totalIsFifty.getDisplayName() + )!! achievement.achievementCounter shouldBe 50 achievement.achievementDetail shouldBe totalIsFifty.getDisplayName() achievement.gameIdEarned shouldBe game.rowId } @Test - fun `Should not update under pressure achievement if last round was a fail`() - { - val hardestPassedLast = listOf( - DartzeeRoundResult(2, true, 50), - DartzeeRoundResult(1, true, 35), - DartzeeRoundResult(3, true, 18), - DartzeeRoundResult(4, false, -100), - ) + fun `Should not update under pressure achievement if last round was a fail`() { + val hardestPassedLast = + listOf( + DartzeeRoundResult(2, true, 50), + DartzeeRoundResult(1, true, 35), + DartzeeRoundResult(3, true, 18), + DartzeeRoundResult(4, false, -100), + ) val player = insertPlayer() val game = setUpDartzeeGameOnDatabase(5, player, hardestPassedLast) @@ -321,14 +319,14 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should not update under pressure achievement if last round was not the hardest rule`() - { - val hardestPassedLast = listOf( - DartzeeRoundResult(2, true, 50), - DartzeeRoundResult(1, true, 35), - DartzeeRoundResult(4, true, 50), - DartzeeRoundResult(3, true, 18), - ) + fun `Should not update under pressure achievement if last round was not the hardest rule`() { + val hardestPassedLast = + listOf( + DartzeeRoundResult(2, true, 50), + DartzeeRoundResult(1, true, 35), + DartzeeRoundResult(4, true, 50), + DartzeeRoundResult(3, true, 18), + ) val player = insertPlayer() val game = setUpDartzeeGameOnDatabase(5, player, hardestPassedLast) @@ -343,8 +341,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should insert a row for bingo, calculating the score correctly and not adding duplicates`() - { + fun `Should insert a row for bingo, calculating the score correctly and not adding duplicates`() { val player = insertPlayer() val game = setUpDartzeeGameOnDatabase(5, player) val carousel = DartzeeRuleCarousel(testRules) @@ -364,8 +361,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should update the carousel and dartboard on readyForThrow and each time a dart is thrown`() - { + fun `Should update the carousel and dartboard on readyForThrow and each time a dart is thrown`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val reducedRules = testRules.subList(0, 2) @@ -379,24 +375,33 @@ class TestGamePanelDartzee: AbstractTest() carousel.pendingTiles.size shouldBe reducedRules.size val expectedSegments = getAllNonMissSegments().filter { !it.isDoubleExcludingBull() } - panel.dartboard.segmentStatuses()!!.scoringSegments.shouldContainExactlyInAnyOrder(*expectedSegments.toTypedArray()) + panel.dartboard + .segmentStatuses()!! + .scoringSegments + .shouldContainExactlyInAnyOrder(*expectedSegments.toTypedArray()) panel.dartThrown(makeDart(20, 1, SegmentType.OUTER_SINGLE)) - val twoBlackOneWhiteSegments = twoBlackOneWhite.calculationResult!!.scoringSegments.toTypedArray() - panel.dartboard.segmentStatuses()!!.scoringSegments.shouldContainExactlyInAnyOrder(*twoBlackOneWhiteSegments) + val twoBlackOneWhiteSegments = + twoBlackOneWhite.calculationResult!!.scoringSegments.toTypedArray() + panel.dartboard + .segmentStatuses()!! + .scoringSegments + .shouldContainExactlyInAnyOrder(*twoBlackOneWhiteSegments) panel.dartThrown(makeDart(20, 0, SegmentType.MISS)) panel.dartboard.segmentStatuses()!!.scoringSegments.shouldBeEmpty() panel.btnReset.isEnabled = true panel.btnReset.doClick() - panel.dartboard.segmentStatuses()!!.scoringSegments.shouldContainExactlyInAnyOrder(*expectedSegments.toTypedArray()) + panel.dartboard + .segmentStatuses()!! + .scoringSegments + .shouldContainExactlyInAnyOrder(*expectedSegments.toTypedArray()) } @Test - fun `Should save darts on confirm pressed, then hide it after the first round`() - { + fun `Should save darts on confirm pressed, then hide it after the first round`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val game = insertGame(gameType = GameType.DARTZEE) @@ -436,31 +441,33 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should update valid segments on hover changed if fewer than 3 darts thrown`() - { + fun `Should update valid segments on hover changed if fewer than 3 darts thrown`() { val carousel = DartzeeRuleCarousel(testRules) val summaryPanel = DartzeeRuleSummaryPanel(carousel) val panel = makeGamePanel(testRules, summaryPanel) panel.startNewGame(listOf(makeSingleParticipant())) panel.hoverChanged(SegmentStatuses(listOf(doubleNineteen), listOf(doubleNineteen))) - panel.dartboard.segmentStatuses() shouldBe SegmentStatuses(listOf(doubleNineteen), listOf(doubleNineteen)) + panel.dartboard.segmentStatuses() shouldBe + SegmentStatuses(listOf(doubleNineteen), listOf(doubleNineteen)) panel.dartThrown(makeDart(20, 1, SegmentType.OUTER_SINGLE)) panel.dartThrown(makeDart(20, 1, SegmentType.OUTER_SINGLE)) panel.hoverChanged(SegmentStatuses(listOf(doubleTwenty), listOf(doubleTwenty))) - panel.dartboard.segmentStatuses() shouldBe SegmentStatuses(listOf(doubleTwenty), listOf(doubleTwenty)) + panel.dartboard.segmentStatuses() shouldBe + SegmentStatuses(listOf(doubleTwenty), listOf(doubleTwenty)) panel.dartThrown(makeDart(20, 1, SegmentType.OUTER_SINGLE)) - panel.dartboard.segmentStatuses() shouldBe SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) + panel.dartboard.segmentStatuses() shouldBe + SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) panel.hoverChanged(SegmentStatuses(listOf(bullseye), listOf(bullseye))) - panel.dartboard.segmentStatuses() shouldBe SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) + panel.dartboard.segmentStatuses() shouldBe + SegmentStatuses(getAllPossibleSegments(), getAllPossibleSegments()) } @Test - fun `Should select the right player when a scorer is selected`() - { + fun `Should select the right player when a scorer is selected`() { val summaryPanel = mockk(relaxed = true) val panel = makeGamePanel(testRules, summaryPanel, totalPlayers = 2) panel.startNewGame(listOf(makeSingleParticipant(), makeSingleParticipant())) @@ -481,8 +488,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `AI should throw scoring darts during the scoring round`() - { + fun `AI should throw scoring darts during the scoring round`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val game = insertGame(gameType = GameType.DARTZEE) @@ -502,14 +508,14 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `AI should throw based on segment status, and adjust correctly for number of darts thrown`() - { + fun `AI should throw based on segment status, and adjust correctly for number of darts thrown`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val game = setUpDartzeeGameOnDatabase(1) val carousel = mockk(relaxed = true) - every { carousel.getSegmentStatus() } returns SegmentStatuses(listOf(singleTwenty), getAllNonMissSegments()) + every { carousel.getSegmentStatus() } returns + SegmentStatuses(listOf(singleTwenty), getAllNonMissSegments()) every { carousel.initialised } returns true val summaryPanel = DartzeeRuleSummaryPanel(carousel) @@ -532,8 +538,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `AI turn should complete normally, and the highest passed rule should be selected`() - { + fun `AI turn should complete normally, and the highest passed rule should be selected`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val model = beastDartsModel(dartzeePlayStyle = DartzeePlayStyle.CAUTIOUS) @@ -565,8 +570,7 @@ class TestGamePanelDartzee: AbstractTest() } @Test - fun `Should update achievements correctly for a team game`() - { + fun `Should update achievements correctly for a team game`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val (p1, p2) = preparePlayers(2) @@ -613,18 +617,24 @@ class TestGamePanelDartzee: AbstractTest() carousel.getDisplayedTiles().first().doClick() panel.getPlayerState().getScoreSoFar() shouldBe 94 - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactly( - AchievementSummary(AchievementType.DARTZEE_UNDER_PRESSURE, 50, game.rowId, totalIsFifty.getDisplayName()) - ) - - retrieveAchievementsForPlayer(p2.rowId).shouldContainExactly( - AchievementSummary(AchievementType.DARTZEE_HALVED, 44, game.rowId) - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactly( + AchievementSummary( + AchievementType.DARTZEE_UNDER_PRESSURE, + 50, + game.rowId, + totalIsFifty.getDisplayName() + ) + ) + + retrieveAchievementsForPlayer(p2.rowId) + .shouldContainExactly( + AchievementSummary(AchievementType.DARTZEE_HALVED, 44, game.rowId) + ) } @Test - fun `Should not unlock flawless achievement for a team game`() - { + fun `Should not unlock flawless achievement for a team game`() { InjectedThings.dartzeeCalculator = DartzeeCalculator() val (p1, p2) = preparePlayers(2) @@ -671,75 +681,129 @@ class TestGamePanelDartzee: AbstractTest() carousel.getDisplayedTiles().first().doClick() panel.getPlayerState().getScoreSoFar() shouldBe 181 - AchievementEntity().countWhere("AchievementType = '${AchievementType.DARTZEE_FLAWLESS}'") shouldBe 0 + AchievementEntity() + .countWhere("AchievementType = '${AchievementType.DARTZEE_FLAWLESS}'") shouldBe 0 } private fun GamePanelDartzee.getPlayerState() = getPlayerStates().first() - private fun DartzeeRuleCarousel.getDisplayedTiles() = tilePanel.getAllChildComponentsForType().filter { it.isVisible } + private fun DartzeeRuleCarousel.getDisplayedTiles() = + tilePanel.getAllChildComponentsForType().filter { it.isVisible } - private fun setUpDartzeeGameOnDatabase(rounds: Int, player: PlayerEntity = insertPlayer(), results: List = ruleResults): GameEntity - { + private fun setUpDartzeeGameOnDatabase( + rounds: Int, + player: PlayerEntity = insertPlayer(), + results: List = ruleResults + ): GameEntity { val dtFinish = if (rounds > 4) getSqlDateNow() else DateStatics.END_OF_TIME val game = insertGame(gameType = GameType.DARTZEE, dtFinish = dtFinish) insertDartzeeRules(game.rowId, testRules) - val participant = insertParticipant(gameId = game.rowId, ordinal = 0, playerId = player.rowId) + val participant = + insertParticipant(gameId = game.rowId, ordinal = 0, playerId = player.rowId) - if (rounds > 0) - { + if (rounds > 0) { insertDart(participant = participant, roundNumber = 1, ordinal = 1) insertDart(participant = participant, roundNumber = 1, ordinal = 2) insertDart(participant = participant, roundNumber = 1, ordinal = 3) } - if (rounds > 1) - { - insertDart(participant = participant, roundNumber = 2, ordinal = 1, score = 18, multiplier = 1) - insertDart(participant = participant, roundNumber = 2, ordinal = 2, score = 12, multiplier = 1) - insertDart(participant = participant, roundNumber = 2, ordinal = 3, score = 20, multiplier = 1) + if (rounds > 1) { + insertDart( + participant = participant, + roundNumber = 2, + ordinal = 1, + score = 18, + multiplier = 1 + ) + insertDart( + participant = participant, + roundNumber = 2, + ordinal = 2, + score = 12, + multiplier = 1 + ) + insertDart( + participant = participant, + roundNumber = 2, + ordinal = 3, + score = 20, + multiplier = 1 + ) DartzeeRoundResultEntity.factoryAndSave(results[0], participant, 2) } - if (rounds > 2) - { - insertDart(participant = participant, roundNumber = 3, ordinal = 1, score = 20, multiplier = 0) + if (rounds > 2) { + insertDart( + participant = participant, + roundNumber = 3, + ordinal = 1, + score = 20, + multiplier = 0 + ) DartzeeRoundResultEntity.factoryAndSave(results[1], participant, 3) } - if (rounds > 3) - { - insertDart(participant = participant, roundNumber = 4, ordinal = 1, score = 18, multiplier = 1) - insertDart(participant = participant, roundNumber = 4, ordinal = 2, score = 4, multiplier = 1) - insertDart(participant = participant, roundNumber = 4, ordinal = 3, score = 13, multiplier = 1) + if (rounds > 3) { + insertDart( + participant = participant, + roundNumber = 4, + ordinal = 1, + score = 18, + multiplier = 1 + ) + insertDart( + participant = participant, + roundNumber = 4, + ordinal = 2, + score = 4, + multiplier = 1 + ) + insertDart( + participant = participant, + roundNumber = 4, + ordinal = 3, + score = 13, + multiplier = 1 + ) DartzeeRoundResultEntity.factoryAndSave(results[2], participant, 4) } - if (rounds > 4) - { - insertDart(participant = participant, roundNumber = 5, ordinal = 1, score = 20, multiplier = 1) - insertDart(participant = participant, roundNumber = 5, ordinal = 2, score = 20, multiplier = 0) - insertDart(participant = participant, roundNumber = 5, ordinal = 3, score = 15, multiplier = 0) + if (rounds > 4) { + insertDart( + participant = participant, + roundNumber = 5, + ordinal = 1, + score = 20, + multiplier = 1 + ) + insertDart( + participant = participant, + roundNumber = 5, + ordinal = 2, + score = 20, + multiplier = 0 + ) + insertDart( + participant = participant, + roundNumber = 5, + ordinal = 3, + score = 15, + multiplier = 0 + ) DartzeeRoundResultEntity.factoryAndSave(results[3], participant, 5) } return game } - private fun makeGamePanel(dtos: List, - summaryPanel: DartzeeRuleSummaryPanel = mockk(relaxed = true), - game: GameEntity = insertGame(), - totalPlayers: Int = 1, - parentWindow: AbstractDartsGameScreen = mockk(relaxed = true)): GamePanelDartzee - { - return GamePanelDartzee( - parentWindow, - game, - totalPlayers, - dtos, - summaryPanel - ) - } -} \ No newline at end of file + private fun makeGamePanel( + dtos: List, + summaryPanel: DartzeeRuleSummaryPanel = mockk(relaxed = true), + game: GameEntity = insertGame(), + totalPlayers: Int = 1, + parentWindow: AbstractDartsGameScreen = mockk(relaxed = true) + ) = GamePanelDartzee(parentWindow, game, totalPlayers, dtos, summaryPanel) +} diff --git a/src/test/kotlin/dartzee/screen/game/TestGamePanelGolf.kt b/src/test/kotlin/dartzee/screen/game/TestGamePanelGolf.kt index b0d70aa36..6e409f7f4 100644 --- a/src/test/kotlin/dartzee/screen/game/TestGamePanelGolf.kt +++ b/src/test/kotlin/dartzee/screen/game/TestGamePanelGolf.kt @@ -40,166 +40,194 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGamePanelGolf: AbstractTest() -{ +class TestGamePanelGolf : AbstractTest() { @Test - fun `It should not update gambler achievement for missed darts`() - { + fun `It should not update gambler achievement for missed darts`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) - val darts = listOf( + val darts = + listOf( Dart(1, 0, segmentType = SegmentType.MISS), Dart(20, 3, segmentType = SegmentType.TREBLE), - Dart(1, 1, segmentType = SegmentType.OUTER_SINGLE)) + Dart(1, 1, segmentType = SegmentType.OUTER_SINGLE) + ) panel.addCompletedRound(darts) - AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId) shouldBe + null } @Test - fun `It should sum up all the points gambled in that round`() - { + fun `It should sum up all the points gambled in that round`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) - val darts = listOf( + val darts = + listOf( Dart(1, 3, segmentType = SegmentType.TREBLE), Dart(1, 3, segmentType = SegmentType.OUTER_SINGLE), - Dart(1, 1, segmentType = SegmentType.TREBLE)) + Dart(1, 1, segmentType = SegmentType.TREBLE) + ) panel.addCompletedRound(darts) - val a = AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId)!! + val a = + AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId)!! a.achievementCounter shouldBe 4 } @Test - fun `It should compute correctly when just two darts thrown`() - { + fun `It should compute correctly when just two darts thrown`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) - val darts = listOf( - Dart(1, 1, segmentType = SegmentType.OUTER_SINGLE), - Dart(1, 1, segmentType = SegmentType.INNER_SINGLE)) + val darts = + listOf( + Dart(1, 1, segmentType = SegmentType.OUTER_SINGLE), + Dart(1, 1, segmentType = SegmentType.INNER_SINGLE) + ) panel.addCompletedRound(darts) - val a = AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId)!! + val a = + AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId)!! a.achievementCounter shouldBe 1 } @Test - fun `It should do nothing for a single dart hit`() - { + fun `It should do nothing for a single dart hit`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) val darts = listOf(Dart(1, 1, segmentType = SegmentType.TREBLE)) panel.addCompletedRound(darts) - AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_POINTS_RISKED, playerId) shouldBe + null } @Test - fun `Should not count darts that aren't a hole in one`() - { + fun `Should not count darts that aren't a hole in one`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) val darts = listOf(Dart(1, 3, segmentType = SegmentType.TREBLE)) panel.addCompletedRound(darts) - AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId) shouldBe + null } @Test - fun `Should not count darts for the wrong hole`() - { + fun `Should not count darts for the wrong hole`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) val darts = listOf(Dart(2, 2, segmentType = SegmentType.DOUBLE)) panel.addCompletedRound(darts) - AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId) shouldBe + null } @Test - fun `Should only count the last dart thrown`() - { + fun `Should only count the last dart thrown`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) - val darts = listOf(Dart(1, 2, segmentType = SegmentType.DOUBLE), Dart(1, 3, segmentType = SegmentType.TREBLE)) + val darts = + listOf( + Dart(1, 2, segmentType = SegmentType.DOUBLE), + Dart(1, 3, segmentType = SegmentType.TREBLE) + ) panel.addCompletedRound(darts) - AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId) shouldBe + null } @Test - fun `Should insert a row for a new hole in one`() - { + fun `Should insert a row for a new hole in one`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) - insertAchievement(playerId = playerId, type = AchievementType.GOLF_COURSE_MASTER, achievementDetail = "2") + insertAchievement( + playerId = playerId, + type = AchievementType.GOLF_COURSE_MASTER, + achievementDetail = "2" + ) val darts = listOf(Dart(1, 2, segmentType = SegmentType.DOUBLE)) panel.addCompletedRound(darts) - val rows = AchievementEntity().retrieveEntities("PlayerId = '$playerId' AND AchievementType = '${AchievementType.GOLF_COURSE_MASTER}'") + val rows = + AchievementEntity() + .retrieveEntities( + "PlayerId = '$playerId' AND AchievementType = '${AchievementType.GOLF_COURSE_MASTER}'" + ) rows.size shouldBe 2 rows.map { it.achievementDetail }.shouldContainExactlyInAnyOrder("1", "2") } @Test - fun `Should not insert a row for a hole in one already attained`() - { + fun `Should not insert a row for a hole in one already attained`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId) - val originalRow = insertAchievement(playerId = playerId, type = AchievementType.GOLF_COURSE_MASTER, achievementDetail = "1") + val originalRow = + insertAchievement( + playerId = playerId, + type = AchievementType.GOLF_COURSE_MASTER, + achievementDetail = "1" + ) val darts = listOf(Dart(1, 2, segmentType = SegmentType.DOUBLE)) panel.addCompletedRound(darts) - val newRow = AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId)!! + val newRow = + AchievementEntity.retrieveAchievement(AchievementType.GOLF_COURSE_MASTER, playerId)!! newRow.rowId shouldBe originalRow.rowId } @Test - fun `Should update one hit wonder achievement when record is exceeded`() - { + fun `Should update one hit wonder achievement when record is exceeded`() { val playerId = randomGuid() val otherGameId = randomGuid() val panel = makeGolfGamePanel(playerId) - val originalRow = insertAchievement(playerId = playerId, type = AchievementType.GOLF_ONE_HIT_WONDER, gameIdEarned = otherGameId, achievementCounter = 2) + val originalRow = + insertAchievement( + playerId = playerId, + type = AchievementType.GOLF_ONE_HIT_WONDER, + gameIdEarned = otherGameId, + achievementCounter = 2 + ) val roundOne = listOf(drtDoubleOne()) val roundTwo = listOf(drtTrebleTwo(), drtDoubleTwo()) panel.addCompletedRound(roundOne) panel.addCompletedRound(roundTwo) - val currentRow = AchievementEntity.retrieveAchievement(AchievementType.GOLF_ONE_HIT_WONDER, playerId)!! + val currentRow = + AchievementEntity.retrieveAchievement(AchievementType.GOLF_ONE_HIT_WONDER, playerId)!! currentRow.gameIdEarned shouldBe originalRow.gameIdEarned currentRow.achievementCounter shouldBe originalRow.achievementCounter panel.addCompletedRound(listOf(drtDoubleThree())) - val newRow = AchievementEntity.retrieveAchievement(AchievementType.GOLF_ONE_HIT_WONDER, playerId)!! + val newRow = + AchievementEntity.retrieveAchievement(AchievementType.GOLF_ONE_HIT_WONDER, playerId)!! newRow.gameIdEarned shouldBe panel.gameEntity.rowId newRow.achievementCounter shouldBe 3 } @Test - fun `Should unlock the correct achievements for team play`() - { + fun `Should unlock the correct achievements for team play`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val panel = makeGolfGamePanel(team) val gameId = panel.gameEntity.rowId - val roundOne = listOf(drtOuterOne(), drtOuterOne(), drtDoubleOne()) // P1: Risked 2, CM: 1, OHW: 1 + val roundOne = + listOf(drtOuterOne(), drtOuterOne(), drtDoubleOne()) // P1: Risked 2, CM: 1, OHW: 1 panel.addCompletedRound(roundOne) val roundTwo = listOf(drtDoubleTwo()) // P2: Risked 0, CM: 2, OHW: 1 @@ -208,23 +236,24 @@ class TestGamePanelGolf: AbstractTest() val roundThree = listOf(drtInnerThree(), drtDoubleThree()) // P1: Risked 4, CM: 1, 3, OHW: 2 panel.addCompletedRound(roundThree) - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, gameId, "1"), - AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, gameId, "3"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, gameId, "1"), - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, gameId, "3"), - AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 2, gameId) - ) - - retrieveAchievementsForPlayer(p2.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, gameId, "2"), - AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 1, gameId) - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, gameId, "1"), + AchievementSummary(AchievementType.GOLF_POINTS_RISKED, 2, gameId, "3"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, gameId, "1"), + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, gameId, "3"), + AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 2, gameId) + ) + + retrieveAchievementsForPlayer(p2.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.GOLF_COURSE_MASTER, -1, gameId, "2"), + AchievementSummary(AchievementType.GOLF_ONE_HIT_WONDER, 1, gameId) + ) } @Test - fun `Should update In Bounds achievement`() - { + fun `Should update In Bounds achievement`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId, gameParams = "18") @@ -254,8 +283,7 @@ class TestGamePanelGolf: AbstractTest() } @Test - fun `Should not update In Bounds achievement if a number is missed`() - { + fun `Should not update In Bounds achievement if a number is missed`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId, gameParams = "18") @@ -279,12 +307,12 @@ class TestGamePanelGolf: AbstractTest() panel.addCompletedRound(drtOuterEighteen()) panel.gameEntity.isFinished() shouldBe true - AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, playerId) shouldBe + null } @Test - fun `Should not update In Bounds achievement for a team`() - { + fun `Should not update In Bounds achievement for a team`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val panel = makeGolfGamePanel(team) @@ -309,13 +337,14 @@ class TestGamePanelGolf: AbstractTest() panel.addCompletedRound(drtOuterEighteen()) panel.gameEntity.isFinished() shouldBe true - AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, p1.rowId) shouldBe null - AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, p2.rowId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, p1.rowId) shouldBe + null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, p2.rowId) shouldBe + null } @Test - fun `Should not add to In Bounds achievement for a 9-hole game`() - { + fun `Should not add to In Bounds achievement for a 9-hole game`() { val playerId = randomGuid() val panel = makeGolfGamePanel(playerId, gameParams = "9") @@ -330,6 +359,7 @@ class TestGamePanelGolf: AbstractTest() panel.addCompletedRound(drtInnerNine()) panel.gameEntity.isFinished() shouldBe true - AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_IN_BOUNDS, playerId) shouldBe + null } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestGamePanelRoundTheClock.kt b/src/test/kotlin/dartzee/screen/game/TestGamePanelRoundTheClock.kt index 7a09dcf56..945d856a2 100644 --- a/src/test/kotlin/dartzee/screen/game/TestGamePanelRoundTheClock.kt +++ b/src/test/kotlin/dartzee/screen/game/TestGamePanelRoundTheClock.kt @@ -15,11 +15,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGamePanelRoundTheClock: AbstractTest() -{ +class TestGamePanelRoundTheClock : AbstractTest() { @Test - fun `Should not update the achievement for a completed hit streak of 1`() - { + fun `Should not update the achievement for a completed hit streak of 1`() { val playerId = randomGuid() val panel = makeRoundTheClockGamePanel(playerId) @@ -30,8 +28,7 @@ class TestGamePanelRoundTheClock: AbstractTest() } @Test - fun `Should not update the achievement for a partial hit streak of 1`() - { + fun `Should not update the achievement for a partial hit streak of 1`() { val playerId = randomGuid() val panel = makeRoundTheClockGamePanel(playerId) @@ -42,8 +39,7 @@ class TestGamePanelRoundTheClock: AbstractTest() } @Test - fun `Should save the best streak even when the player has subsequently missed`() - { + fun `Should save the best streak even when the player has subsequently missed`() { val playerId = randomGuid() val panel = makeRoundTheClockGamePanel(playerId) @@ -56,71 +52,77 @@ class TestGamePanelRoundTheClock: AbstractTest() } @Test - fun `Should add on to the current streak if one exists`() - { + fun `Should add on to the current streak if one exists`() { val playerId = randomGuid() val panel = makeRoundTheClockGamePanel(playerId) - val dartsThrown = listOf(factoryClockHit(1), factoryClockHit(2), factoryClockHit(3), factoryClockHit(4)) + val dartsThrown = + listOf(factoryClockHit(1), factoryClockHit(2), factoryClockHit(3), factoryClockHit(4)) panel.addCompletedRound(dartsThrown) - val achievement = AchievementEntity.retrieveAchievement(AchievementType.CLOCK_BEST_STREAK, playerId)!! + val achievement = + AchievementEntity.retrieveAchievement(AchievementType.CLOCK_BEST_STREAK, playerId)!! achievement.achievementCounter shouldBe 4 achievement.gameIdEarned shouldBe panel.getGameId() val roundTwo = listOf(factoryClockHit(5), Dart(20, 1), Dart(20, 1)) panel.addCompletedRound(roundTwo) - val updatedAchievement = AchievementEntity.retrieveAchievement(AchievementType.CLOCK_BEST_STREAK, playerId)!! + val updatedAchievement = + AchievementEntity.retrieveAchievement(AchievementType.CLOCK_BEST_STREAK, playerId)!! updatedAchievement.achievementCounter shouldBe 5 } @Test - fun `Should update the dartboard when ready for throw`() - { + fun `Should update the dartboard when ready for throw`() { val panel = makeRoundTheClockGamePanel() panel.readyForThrow() - panel.dartboard.segmentStatuses()!!.scoringSegments.shouldContainExactly(getAllNonMissSegments().filter { it.score == 1 }) + panel.dartboard + .segmentStatuses()!! + .scoringSegments + .shouldContainExactly(getAllNonMissSegments().filter { it.score == 1 }) } @Test - fun `Should update the dartboard when a dart is thrown`() - { + fun `Should update the dartboard when a dart is thrown`() { val panel = makeRoundTheClockGamePanel() panel.dartThrown(Dart(1, 1)) - panel.dartboard.segmentStatuses()!!.scoringSegments.shouldContainExactly(getAllNonMissSegments().filter { it.score == 2 }) + panel.dartboard + .segmentStatuses()!! + .scoringSegments + .shouldContainExactly(getAllNonMissSegments().filter { it.score == 2 }) } - /** - * Team achievements - */ + /** Team achievements */ @Test - fun `Should unlock the correct achievements for team play`() - { + fun `Should unlock the correct achievements for team play`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val panel = makeRoundTheClockGamePanel(team) val gameId = panel.gameEntity.rowId - val roundOne = listOf(factoryClockHit(1), factoryClockHit(2), factoryClockHit(3), factoryClockHit(4)) + val roundOne = + listOf(factoryClockHit(1), factoryClockHit(2), factoryClockHit(3), factoryClockHit(4)) panel.addCompletedRound(roundOne) - val roundTwo = listOf(factoryClockHit(5), factoryClockHit(6), factoryClockHit(7), factoryClockHit(8)) + val roundTwo = + listOf(factoryClockHit(5), factoryClockHit(6), factoryClockHit(7), factoryClockHit(8)) panel.addCompletedRound(roundTwo) - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, gameId, "1"), - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, gameId, "1"), + ) - retrieveAchievementsForPlayer(p2.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, gameId, "2"), - ) + retrieveAchievementsForPlayer(p2.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.CLOCK_BRUCEY_BONUSES, -1, gameId, "2"), + ) } - private fun factoryClockHit(clockTarget: Int): Dart - { + private fun factoryClockHit(clockTarget: Int): Dart { val dart = Dart(clockTarget, 1) dart.startingScore = clockTarget return dart } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestGamePanelX01.kt b/src/test/kotlin/dartzee/screen/game/TestGamePanelX01.kt index 351f0a68b..211055fb5 100644 --- a/src/test/kotlin/dartzee/screen/game/TestGamePanelX01.kt +++ b/src/test/kotlin/dartzee/screen/game/TestGamePanelX01.kt @@ -18,11 +18,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGamePanelX01: AbstractTest() -{ +class TestGamePanelX01 : AbstractTest() { @Test - fun `Should update BTBF achievement if the game was finished on D1`() - { + fun `Should update BTBF achievement if the game was finished on D1`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) @@ -35,8 +33,7 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should not update BTBF achievement if the game was finished on a different double`() - { + fun `Should not update BTBF achievement if the game was finished on a different double`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) @@ -49,8 +46,7 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should update the best finish achievement for a player`() - { + fun `Should update the best finish achievement for a player`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) @@ -65,8 +61,7 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should update X01Finish table`() - { + fun `Should update X01Finish table`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) @@ -82,15 +77,13 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should update No Mercy achievement if the game was finished on from 3, 5, 7 or 9`() - { + fun `Should update No Mercy achievement if the game was finished on from 3, 5, 7 or 9`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) - for (i in listOf(3, 5, 7, 9)) - { + for (i in listOf(3, 5, 7, 9)) { wipeTable(EntityName.Achievement) - val darts = listOf(Dart(1, 1), Dart((i-1)/2, 2)) + val darts = listOf(Dart(1, 1), Dart((i - 1) / 2, 2)) panel.addCompletedRound(darts) panel.updateAchievementsForFinish(1, 30) @@ -102,8 +95,7 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should not update No Mercy achievement if the game was finished from a higher finish`() - { + fun `Should not update No Mercy achievement if the game was finished from a higher finish`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) @@ -116,8 +108,7 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should not update No Mercy achievement if the game was finished from an even number`() - { + fun `Should not update No Mercy achievement if the game was finished from an even number`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) @@ -130,8 +121,7 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should unlock the achievements correctly for a team finish, and put the right row into X01Finish`() - { + fun `Should unlock the achievements correctly for a team finish, and put the right row into X01Finish`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val panel = makeX01GamePanel(team) @@ -146,19 +136,21 @@ class TestGamePanelX01: AbstractTest() panel.updateAchievementsForFinish(1, 30) - retrieveAchievementsForPlayer(p1.rowId).shouldContainExactly( - AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 60, gameId), - AchievementSummary(AchievementType.X01_TEAM_GAMES_WON, -1, gameId, "30"), - ) - - retrieveAchievementsForPlayer(p2.rowId).shouldContainExactlyInAnyOrder( - AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 9, gameId), - AchievementSummary(AchievementType.X01_BEST_FINISH, 9, gameId), - AchievementSummary(AchievementType.X01_NO_MERCY, -1, gameId, "9"), - AchievementSummary(AchievementType.X01_CHECKOUT_COMPLETENESS, 1, gameId), - AchievementSummary(AchievementType.X01_BTBF, -1, gameId), - AchievementSummary(AchievementType.X01_TEAM_GAMES_WON, -1, gameId, "30"), - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContainExactly( + AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 60, gameId), + AchievementSummary(AchievementType.X01_TEAM_GAMES_WON, -1, gameId, "30"), + ) + + retrieveAchievementsForPlayer(p2.rowId) + .shouldContainExactlyInAnyOrder( + AchievementSummary(AchievementType.X01_BEST_THREE_DART_SCORE, 9, gameId), + AchievementSummary(AchievementType.X01_BEST_FINISH, 9, gameId), + AchievementSummary(AchievementType.X01_NO_MERCY, -1, gameId, "9"), + AchievementSummary(AchievementType.X01_CHECKOUT_COMPLETENESS, 1, gameId), + AchievementSummary(AchievementType.X01_BTBF, -1, gameId), + AchievementSummary(AchievementType.X01_TEAM_GAMES_WON, -1, gameId, "30"), + ) val finishes = X01FinishEntity().retrieveEntities() finishes.size shouldBe 1 @@ -166,31 +158,29 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should correctly update such bad luck achievement for a team`() - { + fun `Should correctly update such bad luck achievement for a team`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val panel = makeX01GamePanel(team, gameParams = "101") val gameId = panel.gameEntity.rowId - panel.addCompletedRound(listOf(Dart(20, 3), Dart(20, 1), Dart(19, 1))) // Score 99, to put them on 2 + panel.addCompletedRound( + listOf(Dart(20, 3), Dart(20, 1), Dart(19, 1)) + ) // Score 99, to put them on 2 panel.addCompletedRound(listOf(Dart(20, 2))) // 1 for P2 panel.addCompletedRound(listOf(Dart(20, 1))) panel.addCompletedRound(listOf(Dart(20, 2))) // 1 for P2 panel.addCompletedRound(listOf(Dart(18, 2))) // 1 for P1 - retrieveAchievementsForPlayer(p1.rowId).shouldContain( - AchievementSummary(AchievementType.X01_SUCH_BAD_LUCK, 1, gameId) - ) + retrieveAchievementsForPlayer(p1.rowId) + .shouldContain(AchievementSummary(AchievementType.X01_SUCH_BAD_LUCK, 1, gameId)) - retrieveAchievementsForPlayer(p2.rowId).shouldContain( - AchievementSummary(AchievementType.X01_SUCH_BAD_LUCK, 2, gameId) - ) + retrieveAchievementsForPlayer(p2.rowId) + .shouldContain(AchievementSummary(AchievementType.X01_SUCH_BAD_LUCK, 2, gameId)) } @Test - fun `Should update the hotel inspector achievement for a unique 3-dart method of scoring of 26`() - { + fun `Should update the hotel inspector achievement for a unique 3-dart method of scoring of 26`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) val gameId = panel.gameEntity.rowId @@ -200,7 +190,10 @@ class TestGamePanelX01: AbstractTest() panel.addCompletedRound(listOf(Dart(20, 1), Dart(3, 1), Dart(3, 1))) panel.addCompletedRound(listOf(Dart(20, 1), Dart(3, 2))) - val hotelInspectorRows = retrieveAchievementsForPlayer(playerId).filter { it.achievementType == AchievementType.X01_HOTEL_INSPECTOR } + val hotelInspectorRows = + retrieveAchievementsForPlayer(playerId).filter { + it.achievementType == AchievementType.X01_HOTEL_INSPECTOR + } hotelInspectorRows.shouldContainExactlyInAnyOrder( AchievementSummary(AchievementType.X01_HOTEL_INSPECTOR, -1, gameId, "20, 5, 1"), AchievementSummary(AchievementType.X01_HOTEL_INSPECTOR, -1, gameId, "20, 3, 3") @@ -208,8 +201,7 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should not update hotel inspector achievement if board is missed, or player is bust`() - { + fun `Should not update hotel inspector achievement if board is missed, or player is bust`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId, gameParams = "101") @@ -217,13 +209,15 @@ class TestGamePanelX01: AbstractTest() panel.addCompletedRound(listOf(Dart(20, 1), Dart(20, 1), Dart(20, 1))) panel.addCompletedRound(listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1))) - val hotelInspectorRows = retrieveAchievementsForPlayer(playerId).filter { it.achievementType == AchievementType.X01_HOTEL_INSPECTOR } + val hotelInspectorRows = + retrieveAchievementsForPlayer(playerId).filter { + it.achievementType == AchievementType.X01_HOTEL_INSPECTOR + } hotelInspectorRows.shouldBeEmpty() } @Test - fun `Should update the chucklevision achievement for a unique 3-dart method of scoring of 69`() - { + fun `Should update the chucklevision achievement for a unique 3-dart method of scoring of 69`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId) val gameId = panel.gameEntity.rowId @@ -233,7 +227,10 @@ class TestGamePanelX01: AbstractTest() panel.addCompletedRound(listOf(Dart(19, 3), Dart(7, 1), Dart(5, 1))) panel.addCompletedRound(listOf(Dart(20, 3), Dart(3, 3))) - val chucklevisionRows = retrieveAchievementsForPlayer(playerId).filter { it.achievementType == AchievementType.X01_CHUCKLEVISION } + val chucklevisionRows = + retrieveAchievementsForPlayer(playerId).filter { + it.achievementType == AchievementType.X01_CHUCKLEVISION + } chucklevisionRows.shouldContainExactlyInAnyOrder( AchievementSummary(AchievementType.X01_CHUCKLEVISION, -1, gameId, "T20, 5, 4"), AchievementSummary(AchievementType.X01_CHUCKLEVISION, -1, gameId, "T19, 7, 5") @@ -241,57 +238,67 @@ class TestGamePanelX01: AbstractTest() } @Test - fun `Should not update chucklevision achievement if board is missed, or player is bust`() - { + fun `Should not update chucklevision achievement if board is missed, or player is bust`() { val playerId = randomGuid() val panel = makeX01GamePanel(playerId, gameParams = "101") panel.addCompletedRound(listOf(Dart(20, 3), Dart(3, 3), Dart(19, 0))) panel.addCompletedRound(listOf(Dart(5, 1), Dart(4, 1), Dart(20, 3))) - val chucklevisionRows = retrieveAchievementsForPlayer(playerId).filter { it.achievementType == AchievementType.X01_CHUCKLEVISION } + val chucklevisionRows = + retrieveAchievementsForPlayer(playerId).filter { + it.achievementType == AchievementType.X01_CHUCKLEVISION + } chucklevisionRows.shouldBeEmpty() } @Test - fun `Should update stylish finish achievement for first dart`() - { + fun `Should update stylish finish achievement for first dart`() { verifyStylishFinish(listOf(Dart(6, 3), Dart(1, 2))) verifyStylishFinish(listOf(Dart(6, 2), Dart(4, 0), Dart(4, 2))) verifyStylishFinish(listOf(Dart(0, 0), Dart(6, 3), Dart(1, 2))) verifyStylishFinish(listOf(Dart(10, 1), Dart(1, 2), Dart(4, 2))) } - private fun verifyStylishFinish(finalRound: List) - { + private fun verifyStylishFinish(finalRound: List) { val playerId = randomGuid() val panel = makeX01GamePanel(playerId, gameParams = "101") panel.addCompletedRound(listOf(Dart(20, 3), Dart(1, 1), Dart(20, 1))) panel.addCompletedRound(finalRound) - val stylishFinishes = retrieveAchievementsForPlayer(playerId).filter { it.achievementType == AchievementType.X01_STYLISH_FINISH } + val stylishFinishes = + retrieveAchievementsForPlayer(playerId).filter { + it.achievementType == AchievementType.X01_STYLISH_FINISH + } stylishFinishes.shouldContainExactly( - AchievementSummary(AchievementType.X01_STYLISH_FINISH, 20, panel.gameEntity.rowId, finalRound.joinToString()) + AchievementSummary( + AchievementType.X01_STYLISH_FINISH, + 20, + panel.gameEntity.rowId, + finalRound.joinToString() + ) ) } @Test - fun `Should not add to stylish finish achievement if conditions are not right`() - { + fun `Should not add to stylish finish achievement if conditions are not right`() { verifyNotStylishFinish(listOf(Dart(10, 2))) // Just 1 dart verifyNotStylishFinish(listOf(Dart(10, 1), Dart(5, 2))) verifyNotStylishFinish(listOf(Dart(10, 1), Dart(2, 1), Dart(4, 2))) } - private fun verifyNotStylishFinish(finalRound: List) - { + + private fun verifyNotStylishFinish(finalRound: List) { val playerId = randomGuid() val panel = makeX01GamePanel(playerId, gameParams = "101") panel.addCompletedRound(listOf(Dart(20, 3), Dart(1, 1), Dart(20, 1))) panel.addCompletedRound(finalRound) - val stylishFinishes = retrieveAchievementsForPlayer(playerId).filter { it.achievementType == AchievementType.X01_STYLISH_FINISH } + val stylishFinishes = + retrieveAchievementsForPlayer(playerId).filter { + it.achievementType == AchievementType.X01_STYLISH_FINISH + } stylishFinishes.shouldBeEmpty() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestGameStatisticsCellRenderer.kt b/src/test/kotlin/dartzee/screen/game/TestGameStatisticsCellRenderer.kt index ed06fdd70..f0ebec77a 100644 --- a/src/test/kotlin/dartzee/screen/game/TestGameStatisticsCellRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/TestGameStatisticsCellRenderer.kt @@ -5,25 +5,24 @@ import dartzee.shouldHaveBorderThickness import dartzee.shouldHaveColours import dartzee.utils.DartsColour import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.JComponent import javax.swing.JTable import javax.swing.table.DefaultTableModel +import org.junit.jupiter.api.Test -class TestGameStatisticsCellRenderer: AbstractTest() -{ - private fun makeGameStatisticsCellRenderer(sectionStarts: List = emptyList(), - highestWins: List = emptyList(), - lowestWins: List = emptyList(), - histogramRows: List = emptyList()) = - GameStatisticsCellRenderer(sectionStarts, highestWins, lowestWins, histogramRows) +class TestGameStatisticsCellRenderer : AbstractTest() { + private fun makeGameStatisticsCellRenderer( + sectionStarts: List = emptyList(), + highestWins: List = emptyList(), + lowestWins: List = emptyList(), + histogramRows: List = emptyList() + ) = GameStatisticsCellRenderer(sectionStarts, highestWins, lowestWins, histogramRows) private fun GameStatisticsCellRenderer.apply(tm: DefaultTableModel, row: Int, col: Int) = getTableCellRendererComponent(JTable(tm), null, false, false, row, col) as JComponent - private fun prepareTableModel(playerCount: Int): DefaultTableModel - { + private fun prepareTableModel(playerCount: Int): DefaultTableModel { val tm = DefaultTableModel() tm.addColumn("") @@ -33,8 +32,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should colour highest wins rows correctly`() - { + fun `Should colour highest wins rows correctly`() { val tm = prepareTableModel(6) tm.addRow(arrayOf("Example", 4, 2, 3, 5, 1, 0)) @@ -49,8 +47,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should colour lowest wins rows correctly`() - { + fun `Should colour lowest wins rows correctly`() { val tm = prepareTableModel(6) tm.addRow(arrayOf("Example", 4, 2, 3, 5, 1, 0)) @@ -65,8 +62,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should colour highest wins rows correctly when there is a tie`() - { + fun `Should colour highest wins rows correctly when there is a tie`() { val tm = prepareTableModel(4) tm.addRow(arrayOf("Example", 4, 2, 4, 5)) @@ -79,8 +75,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should set correct edge borders`() - { + fun `Should set correct edge borders`() { val tm = prepareTableModel(2) tm.addRow(arrayOf("Row 0", 3, 1)) tm.addRow(arrayOf("Row 1", 2, 0)) @@ -92,8 +87,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should additionally set top borders if row is start of section`() - { + fun `Should additionally set top borders if row is start of section`() { val tm = prepareTableModel(2) tm.addRow(arrayOf("Row 0", 3, 1)) tm.addRow(arrayOf("Row 1", 2, 0)) @@ -106,8 +100,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should additionally set bottom borders for the last row`() - { + fun `Should additionally set bottom borders for the last row`() { val tm = prepareTableModel(2) tm.addRow(arrayOf("Row 0", 3, 1)) tm.addRow(arrayOf("Row 1", 2, 0)) @@ -120,8 +113,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should render the title column correctly`() - { + fun `Should render the title column correctly`() { val tm = prepareTableModel(2) tm.addRow(arrayOf("Row 0", 3, 1)) @@ -132,8 +124,7 @@ class TestGameStatisticsCellRenderer: AbstractTest() } @Test - fun `Should colour histogram rows correctly`() - { + fun `Should colour histogram rows correctly`() { val tm = prepareTableModel(2) tm.addRow(arrayOf("Irrelevant", 7, 8)) tm.addRow(arrayOf("Row 1", 2, 1)) @@ -142,12 +133,20 @@ class TestGameStatisticsCellRenderer: AbstractTest() val renderer = makeGameStatisticsCellRenderer(histogramRows = listOf("Row 1", "Row 2")) - //Column 1: 40% - 60% - renderer.apply(tm, 1, 1).shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.4f, 1f) , null)) - renderer.apply(tm, 2, 1).shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.6f, 1f) , null)) - - //Column 2: 25% - 75% - renderer.apply(tm, 1, 2).shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.25f, 1f) , null)) - renderer.apply(tm, 2, 2).shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.75f, 1f) , null)) + // Column 1: 40% - 60% + renderer + .apply(tm, 1, 1) + .shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.4f, 1f), null)) + renderer + .apply(tm, 2, 1) + .shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.6f, 1f), null)) + + // Column 2: 25% - 75% + renderer + .apply(tm, 1, 2) + .shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.25f, 1f), null)) + renderer + .apply(tm, 2, 2) + .shouldHaveColours(Pair(Color.getHSBColor(0.5.toFloat(), 0.75f, 1f), null)) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestGameStatisticsHeaderRenderer.kt b/src/test/kotlin/dartzee/screen/game/TestGameStatisticsHeaderRenderer.kt index e527116ec..45d8b59b8 100644 --- a/src/test/kotlin/dartzee/screen/game/TestGameStatisticsHeaderRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/TestGameStatisticsHeaderRenderer.kt @@ -4,28 +4,26 @@ import dartzee.helper.AbstractTest import dartzee.shouldHaveBorderThickness import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.JComponent import javax.swing.JTable import javax.swing.table.DefaultTableModel +import org.junit.jupiter.api.Test -class TestGameStatisticsHeaderRenderer: AbstractTest() -{ - private fun GameStatisticsHeaderRenderer.apply(column: Int): JComponent - { +class TestGameStatisticsHeaderRenderer : AbstractTest() { + private fun GameStatisticsHeaderRenderer.apply(column: Int): JComponent { val tm = DefaultTableModel() tm.addColumn("") tm.addColumn("Player 1") tm.addColumn("Player 2") tm.addColumn("Player 3") - return getTableCellRendererComponent(JTable(tm), "Foo", false, false, -1, column) as JComponent + return getTableCellRendererComponent(JTable(tm), "Foo", false, false, -1, column) + as JComponent } @Test - fun `Should set correct borders`() - { + fun `Should set correct borders`() { val renderer = GameStatisticsHeaderRenderer() renderer.apply(0).shouldHaveBorderThickness(0, 1, 0, 2) @@ -35,8 +33,7 @@ class TestGameStatisticsHeaderRenderer: AbstractTest() } @Test - fun `Should make first header column transparent, leaving the rest white`() - { + fun `Should make first header column transparent, leaving the rest white`() { val firstHeader = GameStatisticsHeaderRenderer().apply(0) firstHeader.isOpaque shouldBe false @@ -46,5 +43,4 @@ class TestGameStatisticsHeaderRenderer: AbstractTest() otherHeader.isOpaque shouldBe true otherHeader.background.alpha shouldNotBe 0 } - } diff --git a/src/test/kotlin/dartzee/screen/game/TestMatchSummaryPanel.kt b/src/test/kotlin/dartzee/screen/game/TestMatchSummaryPanel.kt index 4eee81f6f..966689278 100644 --- a/src/test/kotlin/dartzee/screen/game/TestMatchSummaryPanel.kt +++ b/src/test/kotlin/dartzee/screen/game/TestMatchSummaryPanel.kt @@ -13,11 +13,9 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestMatchSummaryPanel : AbstractTest() -{ +class TestMatchSummaryPanel : AbstractTest() { @Test - fun `Should correctly assign scorers and then reuse for existing participants`() - { + fun `Should correctly assign scorers and then reuse for existing participants`() { val panel = makeMatchSummaryPanel() val p1 = insertPlayer(name = "Alyssa") @@ -48,14 +46,16 @@ class TestMatchSummaryPanel : AbstractTest() otherRows[0] shouldBe listOf(1L, qwiAndNatalie, qwiAndNatalie, qwiAndNatalie) otherRows[1] shouldBe listOf(2L, natalieAndQwi, natalieAndQwi, natalieAndQwi) } - private fun MatchSummaryPanel.addParticipant(localId: Long, participant: IWrappedParticipant) - { + + private fun MatchSummaryPanel.addParticipant( + localId: Long, + participant: IWrappedParticipant + ) { addParticipant(localId, X01PlayerState(501, participant)) } @Test - fun `Should add listeners to player states, and update stats using all of them`() - { + fun `Should add listeners to player states, and update stats using all of them`() { val statsPanel = mockk(relaxed = true) val matchPanel = makeMatchSummaryPanel(statsPanel = statsPanel) @@ -63,11 +63,15 @@ class TestMatchSummaryPanel : AbstractTest() val gameTwo = makeX01GamePanel() matchPanel.addGameTab(gameOne) - gameOne.getPlayerStates().forEach { matchPanel.addParticipant(gameOne.gameEntity.localId, it) } + gameOne.getPlayerStates().forEach { + matchPanel.addParticipant(gameOne.gameEntity.localId, it) + } matchPanel.finaliseScorers(mockk(relaxed = true)) matchPanel.addGameTab(gameTwo) - gameTwo.getPlayerStates().forEach { matchPanel.addParticipant(gameTwo.gameEntity.localId, it) } + gameTwo.getPlayerStates().forEach { + matchPanel.addParticipant(gameTwo.gameEntity.localId, it) + } // Now trigger a state change for one of the player states val state = gameOne.getPlayerStates().first() @@ -78,8 +82,7 @@ class TestMatchSummaryPanel : AbstractTest() } @Test - fun `Should return all participants as a flat list`() - { + fun `Should return all participants as a flat list`() { val gamePanelOne = makeX01GamePanel() val gamePanelTwo = makeX01GamePanel() @@ -89,4 +92,4 @@ class TestMatchSummaryPanel : AbstractTest() panel.getAllParticipants().shouldHaveSize(2) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestPanelWithScorers.kt b/src/test/kotlin/dartzee/screen/game/TestPanelWithScorers.kt index a2debbfc5..8e8c75234 100644 --- a/src/test/kotlin/dartzee/screen/game/TestPanelWithScorers.kt +++ b/src/test/kotlin/dartzee/screen/game/TestPanelWithScorers.kt @@ -10,11 +10,9 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import org.junit.jupiter.api.Test -class TestPanelWithScorers: AbstractTest() -{ +class TestPanelWithScorers : AbstractTest() { @Test - fun `Assigning a scorer should initialise it`() - { + fun `Assigning a scorer should initialise it`() { val scrn = FakePanelWithScorers() val singleParticipant = makeSingleParticipant() @@ -25,21 +23,21 @@ class TestPanelWithScorers: AbstractTest() } @Test - fun `Should split 5 scorers correctly`() - { + fun `Should split 5 scorers correctly`() { val scrn = FakePanelWithScorers() scrn.assignScorers(5) scrn.finaliseScorers(FakeDartsScreen()) scrn.scorerCount() shouldBe 5 - scrn.getWestScorers().shouldContainExactly(scrn.getScorer(0), scrn.getScorer(1), scrn.getScorer(2)) + scrn + .getWestScorers() + .shouldContainExactly(scrn.getScorer(0), scrn.getScorer(1), scrn.getScorer(2)) scrn.getEastScorers().shouldContainExactly(scrn.getScorer(3), scrn.getScorer(4)) } @Test - fun `Should split 4 scorers correctly`() - { + fun `Should split 4 scorers correctly`() { val scrn = FakePanelWithScorers() scrn.assignScorers(4) @@ -51,8 +49,7 @@ class TestPanelWithScorers: AbstractTest() } @Test - fun `Should handle just a single scorer`() - { + fun `Should handle just a single scorer`() { val scrn = FakePanelWithScorers() scrn.assignScorer(makeSingleParticipant()) @@ -64,8 +61,7 @@ class TestPanelWithScorers: AbstractTest() } @Test - fun `Should assign scorers in order`() - { + fun `Should assign scorers in order`() { val scrn = FakePanelWithScorers() scrn.assignScorer(makeSingleParticipant(insertPlayer(name = "Player One"))) @@ -77,18 +73,17 @@ class TestPanelWithScorers: AbstractTest() scrn.getScorer(2).lblName.text shouldContain "Player Three" } - inner class FakeScorer(participant: IWrappedParticipant) : AbstractScorer(participant) - { + inner class FakeScorer(participant: IWrappedParticipant) : AbstractScorer(participant) { var initted = false override fun getNumberOfColumns() = 4 + override fun initImpl() { initted = true } } - inner class FakePanelWithScorers : PanelWithScorers() - { + inner class FakePanelWithScorers : PanelWithScorers() { override fun factoryScorer(participant: IWrappedParticipant) = FakeScorer(participant) fun assignScorers(scorerCount: Int) { @@ -96,9 +91,11 @@ class TestPanelWithScorers: AbstractTest() } fun scorerCount() = scorersOrdered.size + fun getScorer(i: Int) = scorersOrdered[i] fun getEastScorers() = panelEast.components.toList() + fun getWestScorers() = panelWest.components.toList() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/TestSegmentStatuses.kt b/src/test/kotlin/dartzee/screen/game/TestSegmentStatuses.kt index 3386f46db..2f2f0e49a 100644 --- a/src/test/kotlin/dartzee/screen/game/TestSegmentStatuses.kt +++ b/src/test/kotlin/dartzee/screen/game/TestSegmentStatuses.kt @@ -12,28 +12,30 @@ import dartzee.utils.getAllNonMissSegments import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSegmentStatuses : AbstractTest() -{ +class TestSegmentStatuses : AbstractTest() { @Test - fun `Should report the correct status for a segment`() - { + fun `Should report the correct status for a segment`() { val validSegments = getAllNonMissSegments().filter { it.score > 10 } val scoringSegments = validSegments.filter { it.score >= 20 } val segmentStatuses = SegmentStatuses(scoringSegments, validSegments) - segmentStatuses.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 20)) shouldBe SegmentStatus.SCORING - segmentStatuses.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 15)) shouldBe SegmentStatus.VALID - segmentStatuses.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 1)) shouldBe SegmentStatus.INVALID + segmentStatuses.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 20)) shouldBe + SegmentStatus.SCORING + segmentStatuses.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 15)) shouldBe + SegmentStatus.VALID + segmentStatuses.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 1)) shouldBe + SegmentStatus.INVALID val nullStatus: SegmentStatuses? = null - nullStatus.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 1)) shouldBe SegmentStatus.SCORING + nullStatus.getSegmentStatus(DartboardSegment(SegmentType.OUTER_SINGLE, 1)) shouldBe + SegmentStatus.SCORING } @Test - fun `Should correctly report whether missing is allowed`() - { + fun `Should correctly report whether missing is allowed`() { SegmentStatuses(emptyList(), listOf(missTwenty)).allowsMissing() shouldBe true SegmentStatuses(listOf(missSeventeen), listOf(missSeventeen)).allowsMissing() shouldBe true - SegmentStatuses(listOf(), listOf(singleTwenty, doubleTwenty, trebleTwenty)).allowsMissing() shouldBe false + SegmentStatuses(listOf(), listOf(singleTwenty, doubleTwenty, trebleTwenty)) + .allowsMissing() shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/dartzee/TestGameStatisticsPanelDartzee.kt b/src/test/kotlin/dartzee/screen/game/dartzee/TestGameStatisticsPanelDartzee.kt index d870ccdc7..65fbb11b9 100644 --- a/src/test/kotlin/dartzee/screen/game/dartzee/TestGameStatisticsPanelDartzee.kt +++ b/src/test/kotlin/dartzee/screen/game/dartzee/TestGameStatisticsPanelDartzee.kt @@ -10,29 +10,30 @@ import dartzee.screen.game.getValueForRow import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGameStatisticsPanelDartzee: AbstractGameStatisticsPanelTest() -{ - override fun makePlayerState(): DartzeePlayerState - { - //Initial score of 26 +class TestGameStatisticsPanelDartzee : + AbstractGameStatisticsPanelTest() { + override fun makePlayerState(): DartzeePlayerState { + // Initial score of 26 val firstRound = listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1)) - //Score of 83 + // Score of 83 val secondRound = listOf(Dart(19, 3), Dart(17, 1), Dart(3, 1)) val secondResult = DartzeeRoundResult(4, true, 57) - //Score of 42 + // Score of 42 val thirdRound = listOf(Dart(20, 3), Dart(20, 0), Dart(5, 1)) val thirdResult = DartzeeRoundResult(1, false, -41) - return makeDartzeePlayerStateForName(completedRounds = listOf(firstRound, secondRound, thirdRound), roundResults = listOf(secondResult, thirdResult)) + return makeDartzeePlayerStateForName( + completedRounds = listOf(firstRound, secondRound, thirdRound), + roundResults = listOf(secondResult, thirdResult) + ) } override fun factoryStatsPanel() = GameStatisticsPanelDartzee() @Test - fun `Should correctly identify the peak score for a player`() - { + fun `Should correctly identify the peak score for a player`() { val statsPanel = GameStatisticsPanelDartzee() val state = makePlayerState() statsPanel.showStats(listOf(state)) @@ -41,8 +42,7 @@ class TestGameStatisticsPanelDartzee: AbstractGameStatisticsPanelTest() -{ +class TestGameStatisticsPanelGolf : + AbstractGameStatisticsPanelTest() { override fun factoryStatsPanel() = GameStatisticsPanelGolf() - override fun makePlayerState(): GolfPlayerState - { + override fun makePlayerState(): GolfPlayerState { val roundOne = makeGolfRound(1, listOf(makeDart(1, 1), makeDart(1, 1))) val roundTwo = makeGolfRound(2, listOf(makeDart(17, 1), makeDart(2, 3))) @@ -23,20 +22,20 @@ class TestGameStatisticsPanelGolf: AbstractGameStatisticsPanelTest() -{ - override fun factoryStatsPanel() = GameStatisticsPanelRoundTheClock(RoundTheClockConfig(ClockType.Standard, true).toJson()) - - override fun makePlayerState(): ClockPlayerState - { - val roundOne = listOf(makeDart(5, 1, startingScore = 1), makeDart(1, 1, startingScore = 1), makeDart(2, 3, startingScore = 2)) - val roundTwo = listOf(makeDart(3, 1, startingScore = 3), makeDart(4, 1, startingScore = 4), makeDart(5, 1, startingScore = 5), makeDart(6, 0, startingScore = 6)) +class TestGameStatisticsPanelRoundTheClock : + AbstractGameStatisticsPanelTest() { + override fun factoryStatsPanel() = + GameStatisticsPanelRoundTheClock(RoundTheClockConfig(ClockType.Standard, true).toJson()) + + override fun makePlayerState(): ClockPlayerState { + val roundOne = + listOf( + makeDart(5, 1, startingScore = 1), + makeDart(1, 1, startingScore = 1), + makeDart(2, 3, startingScore = 2) + ) + val roundTwo = + listOf( + makeDart(3, 1, startingScore = 3), + makeDart(4, 1, startingScore = 4), + makeDart(5, 1, startingScore = 5), + makeDart(6, 0, startingScore = 6) + ) return makeClockPlayerState(completedRounds = listOf(roundOne, roundTwo)) } @Test - fun `Most darts thrown should include unfinished rounds`() - { - val roundOne = listOf(makeDart(5, 1, startingScore = 1), makeDart(1, 1, startingScore = 1), makeDart(3, 1, startingScore = 2)) + fun `Most darts thrown should include unfinished rounds`() { + val roundOne = + listOf( + makeDart(5, 1, startingScore = 1), + makeDart(1, 1, startingScore = 1), + makeDart(3, 1, startingScore = 2) + ) val state = makeClockPlayerState(completedRounds = listOf(roundOne)) val statsPanel = factoryStatsPanel() @@ -34,20 +49,36 @@ class TestGameStatisticsPanelRoundTheClock: AbstractGameStatisticsPanelTest.findAchievementOverlay() = findChild() + fun AbstractDartsScorer<*>.getAchievementOverlay() = getChild() + fun AchievementOverlay.getAchievementName(): String = getChild("achievementName").text + fun AchievementOverlay.getPlayerName(): String = getChild("playerName").text -fun AchievementOverlay.close() = clickChild(text = "X") \ No newline at end of file + +fun AchievementOverlay.close() = clickChild(text = "X") diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorer.kt index b5e8c10b4..fab408b57 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorer.kt @@ -18,14 +18,16 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestAbstractDartsScorer: AbstractTest() -{ +class TestAbstractDartsScorer : AbstractTest() { @Test - fun `Should clear the data model on stateChanged, and call child implementation`() - { + fun `Should clear the data model on stateChanged, and call child implementation`() { val roundOne = listOf(Dart(1, 1), Dart(1, 1), Dart(2, 1)) val roundTwo = listOf(Dart(2, 3), Dart(2, 2), Dart(2, 3)) - val state = TestPlayerState(insertParticipant(), completedRounds = mutableListOf(roundOne, roundTwo)) + val state = + TestPlayerState( + insertParticipant(), + completedRounds = mutableListOf(roundOne, roundTwo) + ) val scorer = TestDartsScorer() scorer.init() @@ -33,15 +35,13 @@ class TestAbstractDartsScorer: AbstractTest() scorer.stateChanged(state) - scorer.tableScores.getRows().shouldContainExactly( - roundOne + listOf(null, null), - roundTwo + listOf(null, null) - ) + scorer.tableScores + .getRows() + .shouldContainExactly(roundOne + listOf(null, null), roundTwo + listOf(null, null)) } @Test - fun `Should set score and finishing position if it is set`() - { + fun `Should set score and finishing position if it is set`() { val state = TestPlayerState(insertParticipant(finishingPosition = 3), scoreSoFar = 30) val scorer = TestDartsScorer() @@ -53,8 +53,7 @@ class TestAbstractDartsScorer: AbstractTest() } @Test - fun `Should correctly update bold text when selected and deselected`() - { + fun `Should correctly update bold text when selected and deselected`() { val scorer = TestDartsScorer() scorer.init() @@ -71,8 +70,7 @@ class TestAbstractDartsScorer: AbstractTest() } @Test - fun `Should not set score if it is unset`() - { + fun `Should not set score if it is unset`() { val state = TestPlayerState(insertParticipant(finishingPosition = -1), scoreSoFar = -1) val scorer = TestDartsScorer(state.wrappedParticipant) @@ -83,10 +81,9 @@ class TestAbstractDartsScorer: AbstractTest() scorer.lblResult.shouldHaveColours(startingColours) scorer.lblResult.text shouldBe "" } - + @Test - fun `Should layer achievements, and show them in sequence as they are closed`() - { + fun `Should layer achievements, and show them in sequence as they are closed`() { val scorer = TestDartsScorer() scorer.init() @@ -114,8 +111,7 @@ class TestAbstractDartsScorer: AbstractTest() } @Test - fun `Should pass player name when achievement unlocked for a team`() - { + fun `Should pass player name when achievement unlocked for a team`() { val (alice, bob) = preparePlayers(2) val team = makeTeam(alice, bob) @@ -132,20 +128,17 @@ class TestAbstractDartsScorer: AbstractTest() scorer.getAchievementOverlay().getPlayerName() shouldBe "Bob" } - private class TestDartsScorer(participant: IWrappedParticipant = makeSingleParticipant()) : AbstractDartsScorer(participant) - { + private class TestDartsScorer(participant: IWrappedParticipant = makeSingleParticipant()) : + AbstractDartsScorer(participant) { override fun getNumberOfColumns() = 5 - override fun getNumberOfColumnsForAddingNewDart() = 3 - override fun initImpl() - { + override fun getNumberOfColumnsForAddingNewDart() = 3 - } + override fun initImpl() {} - override fun stateChangedImpl(state: TestPlayerState) - { + override fun stateChangedImpl(state: TestPlayerState) { setScoreAndFinishingPosition(state) state.completedRounds.forEach(::addDartRound) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorerPausable.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorerPausable.kt index e01b1befb..ee1297288 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorerPausable.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractDartsScorerPausable.kt @@ -20,22 +20,19 @@ import io.kotest.matchers.shouldBe import io.mockk.clearMocks import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestAbstractDartsScorerPausable: AbstractTest() -{ +class TestAbstractDartsScorerPausable : AbstractTest() { @Test - fun `Should not be paused by default, when button is not visible`() - { + fun `Should not be paused by default, when button is not visible`() { val scorer = factoryScorer() scorer.getPaused() shouldBe false scorer.getChild { it.icon == ICON_RESUME }.shouldNotBeVisible() } @Test - fun `Should show the right result for an unfinished player`() - { + fun `Should show the right result for an unfinished player`() { val scorer = factoryScorer() val defaultLabelColours = Pair(scorer.lblResult.background, scorer.lblResult.foreground) val state = TestPlayerState(insertParticipant(), scoreSoFar = 25) @@ -47,10 +44,13 @@ class TestAbstractDartsScorerPausable: AbstractTest() } @Test - fun `Should show the correct state for a completely finished player`() - { + fun `Should show the correct state for a completely finished player`() { val scorer = factoryScorer() - val state = TestPlayerState(insertParticipant(finishingPosition = 2, dtFinished = getSqlDateNow()), scoreSoFar = 30) + val state = + TestPlayerState( + insertParticipant(finishingPosition = 2, dtFinished = getSqlDateNow()), + scoreSoFar = 30 + ) scorer.stateChanged(state) scorer.lblResult.text shouldBe "30 Darts" @@ -59,10 +59,13 @@ class TestAbstractDartsScorerPausable: AbstractTest() } @Test - fun `Should show the correct paused state for a player who came last but has not finished`() - { + fun `Should show the correct paused state for a player who came last but has not finished`() { val scorer = factoryScorer() - val state = TestPlayerState(insertParticipant(finishingPosition = 2, dtFinished = DateStatics.END_OF_TIME), scoreSoFar = 30) + val state = + TestPlayerState( + insertParticipant(finishingPosition = 2, dtFinished = DateStatics.END_OF_TIME), + scoreSoFar = 30 + ) scorer.stateChanged(state) scorer.lblResult.text shouldBe "Unfinished" @@ -72,11 +75,14 @@ class TestAbstractDartsScorerPausable: AbstractTest() } @Test - fun `Unpausing and pausing should update the state`() - { + fun `Unpausing and pausing should update the state`() { val scorer = factoryScorer() val defaultLabelColours = Pair(scorer.lblResult.background, scorer.lblResult.foreground) - val state = TestPlayerState(insertParticipant(finishingPosition = 2, dtFinished = DateStatics.END_OF_TIME), scoreSoFar = 30) + val state = + TestPlayerState( + insertParticipant(finishingPosition = 2, dtFinished = DateStatics.END_OF_TIME), + scoreSoFar = 30 + ) scorer.stateChanged(state) scorer.clickChild { it.icon == ICON_RESUME } @@ -91,11 +97,14 @@ class TestAbstractDartsScorerPausable: AbstractTest() } @Test - fun `Should notify parent of pause and unpause`() - { + fun `Should notify parent of pause and unpause`() { val parent = mockk>(relaxed = true) val scorer = factoryScorer(parent) - val state = TestPlayerState(insertParticipant(finishingPosition = 2, dtFinished = DateStatics.END_OF_TIME), scoreSoFar = 30) + val state = + TestPlayerState( + insertParticipant(finishingPosition = 2, dtFinished = DateStatics.END_OF_TIME), + scoreSoFar = 30 + ) scorer.stateChanged(state) scorer.clickChild { it.icon == ICON_RESUME } @@ -108,17 +117,17 @@ class TestAbstractDartsScorerPausable: AbstractTest() verify { parent.pauseLastPlayer() } } - private fun factoryScorer(parent: GamePanelPausable<*, *> = mockk(relaxed = true)) = FakeDartsScorerPausable(parent).also { it.init() } + private fun factoryScorer(parent: GamePanelPausable<*, *> = mockk(relaxed = true)) = + FakeDartsScorerPausable(parent).also { it.init() } - - private class FakeDartsScorerPausable(parent: GamePanelPausable<*, *>): AbstractDartsScorerPausable(parent, makeSingleParticipant()) - { + private class FakeDartsScorerPausable(parent: GamePanelPausable<*, *>) : + AbstractDartsScorerPausable(parent, makeSingleParticipant()) { override fun getNumberOfColumns() = 4 + override fun initImpl() {} - override fun stateChangedImpl(state: TestPlayerState) - { + override fun stateChangedImpl(state: TestPlayerState) { finalisePlayerResult(state) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractScorer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractScorer.kt index 56d6f0be8..799e44375 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractScorer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestAbstractScorer.kt @@ -11,11 +11,9 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import org.junit.jupiter.api.Test -class TestAbstractScorer: AbstractTest() -{ +class TestAbstractScorer : AbstractTest() { @Test - fun `Should initialise correctly with a single participant`() - { + fun `Should initialise correctly with a single participant`() { val player = insertPlayer(name = "Bob") val participant = makeSingleParticipant(player) val scorer = TestScorer(participant) @@ -28,9 +26,8 @@ class TestAbstractScorer: AbstractTest() } @Test - fun `Should initialise with the right number of columns`() - { - val twoCols = TestScorer(columnCount = 2) + fun `Should initialise with the right number of columns`() { + val twoCols = TestScorer(columnCount = 2) twoCols.init() twoCols.tableScores.model.columnCount shouldBe 2 @@ -40,24 +37,23 @@ class TestAbstractScorer: AbstractTest() } @Test - fun `Should call init implementation`() - { + fun `Should call init implementation`() { val scorer = TestScorer() scorer.initted shouldBe false scorer.init() scorer.initted shouldBe true } - private class TestScorer(participant: IWrappedParticipant = makeSingleParticipant(), val columnCount: Int = 4): AbstractScorer(participant) - { + private class TestScorer( + participant: IWrappedParticipant = makeSingleParticipant(), + val columnCount: Int = 4 + ) : AbstractScorer(participant) { var initted = false override fun getNumberOfColumns() = columnCount - override fun initImpl() - { + override fun initImpl() { initted = true } - } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestDartRenderer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestDartRenderer.kt index eb00d3c31..469bc5aee 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestDartRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestDartRenderer.kt @@ -1,18 +1,16 @@ package dartzee.screen.game.scorer +import dartzee.helper.AbstractTest import dartzee.`object`.Dart import dartzee.`object`.DartHint -import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import java.awt.Font +import org.junit.jupiter.api.Test -class TestDartRenderer: AbstractTest() -{ +class TestDartRenderer : AbstractTest() { @Test - fun `Should render DartHints in brackets, and regular darts without`() - { + fun `Should render DartHints in brackets, and regular darts without`() { val renderer = DartRenderer() renderer.getReplacementValue(DartHint(20, 3)) shouldBe "(T20)" @@ -20,8 +18,7 @@ class TestDartRenderer: AbstractTest() } @Test - fun `Should render normal darts correctly, and be responsive to selection`() - { + fun `Should render normal darts correctly, and be responsive to selection`() { val renderer = DartRenderer() renderer.setCellColours(Dart(20, 3), false) @@ -34,8 +31,7 @@ class TestDartRenderer: AbstractTest() } @Test - fun `Should render dart hints in red italic, and be responsive to selection`() - { + fun `Should render dart hints in red italic, and be responsive to selection`() { val renderer = DartRenderer() renderer.setCellColours(DartHint(20, 3), false) @@ -46,4 +42,4 @@ class TestDartRenderer: AbstractTest() renderer.foreground shouldBe Color.CYAN renderer.font.style shouldBe Font.ITALIC } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerDartzee.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerDartzee.kt index daf5cf48a..341d0702e 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerDartzee.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerDartzee.kt @@ -27,11 +27,9 @@ import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.Test -class TestDartsScorerDartzee: AbstractTest() -{ +class TestDartsScorerDartzee : AbstractTest() { @Test - fun `Should listen to mouse events once the game has finished`() - { + fun `Should listen to mouse events once the game has finished`() { val game = insertGame(dtFinish = getSqlDateNow()) val parent = mockk(relaxed = true) every { parent.gameEntity } returns game @@ -43,8 +41,7 @@ class TestDartsScorerDartzee: AbstractTest() } @Test - fun `Should not pass on mouse clicks if the game is ongoing`() - { + fun `Should not pass on mouse clicks if the game is ongoing`() { val game = insertGame(dtFinish = DateStatics.END_OF_TIME) val parent = mockk(relaxed = true) every { parent.gameEntity } returns game @@ -56,8 +53,7 @@ class TestDartsScorerDartzee: AbstractTest() } @Test - fun `Should be selectable post-game`() - { + fun `Should be selectable post-game`() { val (p1, p2) = preparePlayers(2) val team = makeTeam(p1, p2) val scorer = makeScorer(participant = team) @@ -70,15 +66,13 @@ class TestDartsScorerDartzee: AbstractTest() } @Test - fun `Should return 0 for score so far when no entries`() - { + fun `Should return 0 for score so far when no entries`() { val scorer = makeScorer() scorer.lblResult.text shouldBe "" } @Test - fun `Should set the score and finishing position`() - { + fun `Should set the score and finishing position`() { val scorer = makeScorer() val pt = insertParticipant(finishingPosition = 2) @@ -94,33 +88,36 @@ class TestDartsScorerDartzee: AbstractTest() } @Test - fun `Table should contain the correct darts and results for completed rounds`() - { + fun `Table should contain the correct darts and results for completed rounds`() { val scorer = makeScorer() - val roundOne = listOf(Dart(20, 1), Dart(20, 2), Dart(20, 3)) //120 - val roundTwo = listOf(Dart(5, 1), Dart(5, 1), Dart(5, 1)) //60 - val roundThree = listOf(Dart(25, 2), Dart(10, 1), Dart(12, 1)) //110 + val roundOne = listOf(Dart(20, 1), Dart(20, 2), Dart(20, 3)) // 120 + val roundTwo = listOf(Dart(5, 1), Dart(5, 1), Dart(5, 1)) // 60 + val roundThree = listOf(Dart(25, 2), Dart(10, 1), Dart(12, 1)) // 110 val resultOne = DartzeeRoundResult(1, false, -60) val resultTwo = DartzeeRoundResult(7, true, 50) - val state = makeDartzeePlayerState(insertParticipant(), listOf(roundOne, roundTwo, roundThree), listOf(resultOne, resultTwo)) + val state = + makeDartzeePlayerState( + insertParticipant(), + listOf(roundOne, roundTwo, roundThree), + listOf(resultOne, resultTwo) + ) scorer.stateChanged(state) val rows = scorer.tableScores.getRows() rows.shouldContainExactly( - roundOne + factoryHighScoreResult(roundOne) + 120, - roundTwo + resultOne + 60, - roundThree + resultTwo + 110 + roundOne + factoryHighScoreResult(roundOne) + 120, + roundTwo + resultOne + 60, + roundThree + resultTwo + 110 ) } @Test - fun `Should include the in progress round`() - { + fun `Should include the in progress round`() { val scorer = makeScorer() - val roundOne = listOf(Dart(20, 1), Dart(20, 2), Dart(20, 3)) //120 + val roundOne = listOf(Dart(20, 1), Dart(20, 2), Dart(20, 3)) // 120 val state = makeDartzeePlayerState(insertParticipant(), listOf(roundOne)) state.dartThrown(Dart(5, 1)) state.dartThrown(Dart(10, 1)) @@ -128,33 +125,41 @@ class TestDartsScorerDartzee: AbstractTest() val rows = scorer.tableScores.getRows() rows.shouldContainExactly( - roundOne + factoryHighScoreResult(roundOne) + 120, - listOf(Dart(5, 1), Dart(10, 1), null, null, null) + roundOne + factoryHighScoreResult(roundOne) + 120, + listOf(Dart(5, 1), Dart(10, 1), null, null, null) ) } @Test - fun `Should update the result renderer based on the current maximum score`() - { + fun `Should update the result renderer based on the current maximum score`() { val scorer = makeScorer() val roundOne = listOf(Dart(20, 1), Dart(20, 2), Dart(20, 3)) val roundTwo = listOf(Dart(5, 1), Dart(5, 1), Dart(5, 1)) val resultOne = DartzeeRoundResult(1, false, -60) - val state = makeDartzeePlayerState(insertParticipant(), listOf(roundOne, roundTwo), listOf(resultOne)) + val state = + makeDartzeePlayerState( + insertParticipant(), + listOf(roundOne, roundTwo), + listOf(resultOne) + ) scorer.stateChanged(state) scorer.getRendererMaximum() shouldBe 120 val otherResult = DartzeeRoundResult(5, true, 60) - val improvedState = makeDartzeePlayerState(insertParticipant(), listOf(roundOne, roundTwo), listOf(otherResult)) + val improvedState = + makeDartzeePlayerState( + insertParticipant(), + listOf(roundOne, roundTwo), + listOf(otherResult) + ) scorer.stateChanged(improvedState) scorer.getRendererMaximum() shouldBe 180 } @Test - fun `Table should have the right columns and renderers`() - { + fun `Table should have the right columns and renderers`() { val scorer = makeScorer() scorer.getNumberOfColumns() shouldBe 5 @@ -162,12 +167,14 @@ class TestDartsScorerDartzee: AbstractTest() scorer.tableScores.getColumn(0).cellRenderer.shouldBeInstanceOf() scorer.tableScores.getColumn(1).cellRenderer.shouldBeInstanceOf() scorer.tableScores.getColumn(2).cellRenderer.shouldBeInstanceOf() - scorer.tableScores.getColumn(3).cellRenderer.shouldBeInstanceOf() + scorer.tableScores + .getColumn(3) + .cellRenderer + .shouldBeInstanceOf() } @Test - fun `Should cope with empty state`() - { + fun `Should cope with empty state`() { val scorer = makeScorer() val state = makeDartzeePlayerState() @@ -175,13 +182,14 @@ class TestDartsScorerDartzee: AbstractTest() scorer.tableScores.rowCount shouldBe 0 } - private fun makeScorer(parent: GamePanelDartzee = mockk(), participant: IWrappedParticipant = makeSingleParticipant()) = - DartsScorerDartzee(parent, participant).also { it.init() } + private fun makeScorer( + parent: GamePanelDartzee = mockk(), + participant: IWrappedParticipant = makeSingleParticipant() + ) = DartsScorerDartzee(parent, participant).also { it.init() } - private fun DartsScorerDartzee.getRendererMaximum(): Int - { + private fun DartsScorerDartzee.getRendererMaximum(): Int { val renderer = tableScores.getColumn(4).cellRenderer renderer.shouldBeInstanceOf() return renderer.maxScore } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerGolf.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerGolf.kt index 93534f811..d6fdc0026 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerGolf.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerGolf.kt @@ -15,15 +15,12 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestDartsScorerGolf: AbstractTest() -{ +class TestDartsScorerGolf : AbstractTest() { @Test - fun `Should add a subtotal row after 9 and 18 holes`() - { + fun `Should add a subtotal row after 9 and 18 holes`() { val scorer = factoryScorer() val state = makeGolfPlayerState() - for (i in 1..9) - { + for (i in 1..9) { addRound(state, i) } @@ -38,8 +35,7 @@ class TestDartsScorerGolf: AbstractTest() scorer.tableScores.getValueAt(9, 4) shouldBe 9 scorer.lblResult.text shouldBe "10" - for (i in 11..18) - { + for (i in 11..18) { addRound(state, i) } @@ -48,24 +44,42 @@ class TestDartsScorerGolf: AbstractTest() scorer.tableScores.getValueAt(19, 4) shouldBe 18 scorer.lblResult.text shouldBe "18" } - private fun addRound(state: GolfPlayerState, hole: Int) - { + + private fun addRound(state: GolfPlayerState, hole: Int) { val drt = Dart(hole, 2, segmentType = SegmentType.DOUBLE) drt.roundNumber = hole state.addCompletedRound(listOf(drt)) } @Test - fun `Should set the score and finishing position`() - { + fun `Should set the score and finishing position`() { val scorer = factoryScorer() val pt = insertParticipant(finishingPosition = 2) val roundOne = makeGolfRound(1, listOf(Dart(1, 3, segmentType = SegmentType.TREBLE))) - val roundTwo = makeGolfRound(2, listOf(Dart(2, 0, segmentType = SegmentType.MISS), Dart(2, 1, segmentType = SegmentType.OUTER_SINGLE))) - val roundThree = makeGolfRound(3, listOf(Dart(3, 0, segmentType = SegmentType.MISS), Dart(3, 0, segmentType = SegmentType.MISS), Dart(3, 0, segmentType = SegmentType.MISS))) - - val state = makeGolfPlayerState(participant = pt, completedRounds = listOf(roundOne, roundTwo, roundThree)) + val roundTwo = + makeGolfRound( + 2, + listOf( + Dart(2, 0, segmentType = SegmentType.MISS), + Dart(2, 1, segmentType = SegmentType.OUTER_SINGLE) + ) + ) + val roundThree = + makeGolfRound( + 3, + listOf( + Dart(3, 0, segmentType = SegmentType.MISS), + Dart(3, 0, segmentType = SegmentType.MISS), + Dart(3, 0, segmentType = SegmentType.MISS) + ) + ) + + val state = + makeGolfPlayerState( + participant = pt, + completedRounds = listOf(roundOne, roundTwo, roundThree) + ) scorer.stateChanged(state) scorer.lblResult.text shouldBe "11" @@ -73,11 +87,25 @@ class TestDartsScorerGolf: AbstractTest() } @Test - fun `Should render completed rounds correctly`() - { + fun `Should render completed rounds correctly`() { val roundOne = makeGolfRound(1, listOf(Dart(1, 3, segmentType = SegmentType.TREBLE))) - val roundTwo = makeGolfRound(2, listOf(Dart(2, 0, segmentType = SegmentType.MISS), Dart(2, 1, segmentType = SegmentType.OUTER_SINGLE))) - val roundThree = makeGolfRound(3, listOf(Dart(3, 0, segmentType = SegmentType.MISS), Dart(3, 0, segmentType = SegmentType.MISS), Dart(3, 0, segmentType = SegmentType.MISS))) + val roundTwo = + makeGolfRound( + 2, + listOf( + Dart(2, 0, segmentType = SegmentType.MISS), + Dart(2, 1, segmentType = SegmentType.OUTER_SINGLE) + ) + ) + val roundThree = + makeGolfRound( + 3, + listOf( + Dart(3, 0, segmentType = SegmentType.MISS), + Dart(3, 0, segmentType = SegmentType.MISS), + Dart(3, 0, segmentType = SegmentType.MISS) + ) + ) val state = makeGolfPlayerState(completedRounds = listOf(roundOne, roundTwo, roundThree)) @@ -86,15 +114,14 @@ class TestDartsScorerGolf: AbstractTest() val rows = scorer.tableScores.getRows() rows.shouldContainExactlyInAnyOrder( - listOf(1) + roundOne + listOf(null, null) + 2, - listOf(2) + roundTwo + listOf(null) + 4, - listOf(3) + roundThree + 5 + listOf(1) + roundOne + listOf(null, null) + 2, + listOf(2) + roundTwo + listOf(null) + 4, + listOf(3) + roundThree + 5 ) } @Test - fun `Should render the current round`() - { + fun `Should render the current round`() { val roundOne = makeGolfRound(1, listOf(Dart(1, 3, segmentType = SegmentType.TREBLE))) val state = makeGolfPlayerState(completedRounds = listOf(roundOne)) @@ -105,14 +132,13 @@ class TestDartsScorerGolf: AbstractTest() val rows = scorer.tableScores.getRows() rows.shouldContainExactlyInAnyOrder( - listOf(1) + roundOne + listOf(null, null) + 2, - listOf(2) + Dart(2, 0) + listOf(null, null, null) + listOf(1) + roundOne + listOf(null, null) + 2, + listOf(2) + Dart(2, 0) + listOf(null, null, null) ) } @Test - fun `Should cope with empty state`() - { + fun `Should cope with empty state`() { val scorer = factoryScorer() val state = makeGolfPlayerState() @@ -120,10 +146,9 @@ class TestDartsScorerGolf: AbstractTest() scorer.tableScores.rowCount shouldBe 0 } - private fun factoryScorer(): DartsScorerGolf - { + private fun factoryScorer(): DartsScorerGolf { val scorer = DartsScorerGolf(makeSingleParticipant()) scorer.init() return scorer } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerRoundTheClock.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerRoundTheClock.kt index ae820d2e9..071386f85 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerRoundTheClock.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerRoundTheClock.kt @@ -18,11 +18,9 @@ import io.kotest.matchers.shouldBe import io.mockk.mockk import org.junit.jupiter.api.Test -class TestDartsScorerRoundTheClock: AbstractTest() -{ +class TestDartsScorerRoundTheClock : AbstractTest() { @Test - fun `Should cope with empty state`() - { + fun `Should cope with empty state`() { val state = makeClockPlayerState() val scorer = factoryScorer() @@ -31,8 +29,7 @@ class TestDartsScorerRoundTheClock: AbstractTest() } @Test - fun `Should render completed rounds correctly`() - { + fun `Should render completed rounds correctly`() { val roundOne = listOf(Dart(1, 1), Dart(2, 1), Dart(3, 1), Dart(4, 0)) val roundTwo = listOf(Dart(4, 1), Dart(5, 0), Dart(5, 3)) @@ -41,17 +38,13 @@ class TestDartsScorerRoundTheClock: AbstractTest() scorer.stateChanged(state) val rows = scorer.tableScores.getRows() - rows.shouldContainExactly( - roundOne, - roundTwo + DartNotThrown() - ) + rows.shouldContainExactly(roundOne, roundTwo + DartNotThrown()) scorer.lblResult.text shouldBe "7 Darts" } @Test - fun `Should include the in progress round`() - { + fun `Should include the in progress round`() { val roundOne = listOf(Dart(1, 0), Dart(20, 1), Dart(5, 1)) val state = makeClockPlayerState(completedRounds = listOf(roundOne)) @@ -60,36 +53,29 @@ class TestDartsScorerRoundTheClock: AbstractTest() scorer.stateChanged(state) val rows = scorer.tableScores.getRows() - rows.shouldContainExactly( - roundOne + DartNotThrown(), - listOf(Dart(1, 1), null, null, null) - ) + rows.shouldContainExactly(roundOne + DartNotThrown(), listOf(Dart(1, 1), null, null, null)) scorer.lblResult.text shouldBe "4 Darts" } @Test - fun `Should signal when brucey bonus is no longer possible for the current round`() - { + fun `Should signal when brucey bonus is no longer possible for the current round`() { val scorer = factoryScorer() val state = makeClockPlayerState() state.dartThrown(Dart(1, 1)) scorer.stateChanged(state) - scorer.tableScores.firstRow().shouldContainExactly( - Dart(1, 1), null, null, null - ) + scorer.tableScores.firstRow().shouldContainExactly(Dart(1, 1), null, null, null) state.dartThrown(Dart(17, 1)) scorer.stateChanged(state) - scorer.tableScores.firstRow().shouldContainExactly( - Dart(1, 1), Dart(17, 1), null, DartNotThrown() - ) + scorer.tableScores + .firstRow() + .shouldContainExactly(Dart(1, 1), Dart(17, 1), null, DartNotThrown()) } @Test - fun `Should not black out brucey bonus for current round if 4th dart was thrown`() - { + fun `Should not black out brucey bonus for current round if 4th dart was thrown`() { val scorer = factoryScorer() val state = makeClockPlayerState() @@ -97,14 +83,11 @@ class TestDartsScorerRoundTheClock: AbstractTest() darts.forEach { state.dartThrown(it) } scorer.stateChanged(state) - scorer.tableScores.firstRow().shouldContainExactly( - darts - ) + scorer.tableScores.firstRow().shouldContainExactly(darts) } @Test - fun `Should only add the scorecard if not in order`() - { + fun `Should only add the scorecard if not in order`() { val scorerInOrder = factoryScorer(inOrder = true) scorerInOrder.findChild().shouldBeNull() @@ -113,8 +96,7 @@ class TestDartsScorerRoundTheClock: AbstractTest() } @Test - fun `Should add back the scorecard when achievement popup is dismissed`() - { + fun `Should add back the scorecard when achievement popup is dismissed`() { val scorer = factoryScorer(inOrder = false) scorer.achievementUnlocked(AchievementClockBestGame(), "") @@ -125,10 +107,15 @@ class TestDartsScorerRoundTheClock: AbstractTest() private fun factoryScorer( clockType: ClockType = ClockType.Standard, - inOrder: Boolean = true): DartsScorerRoundTheClock - { - val scorer = DartsScorerRoundTheClock(mockk(relaxed = true), RoundTheClockConfig(clockType, inOrder), makeSingleParticipant()) + inOrder: Boolean = true + ): DartsScorerRoundTheClock { + val scorer = + DartsScorerRoundTheClock( + mockk(relaxed = true), + RoundTheClockConfig(clockType, inOrder), + makeSingleParticipant() + ) scorer.init() return scorer } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerX01.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerX01.kt index f394615e3..2d30fe162 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerX01.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestDartsScorerX01.kt @@ -16,21 +16,18 @@ import dartzee.utils.ResourceCache.ICON_RESUME import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.mockk -import org.junit.jupiter.api.Test import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestDartsScorerX01: AbstractTest() -{ +class TestDartsScorerX01 : AbstractTest() { @Test - fun `should have 4 columns`() - { + fun `should have 4 columns`() { val scorer = factoryScorer() scorer.getNumberOfColumns() shouldBe 4 } @Test - fun `Should cope with empty state`() - { + fun `Should cope with empty state`() { val scorer = factoryScorer() val state = makeX01PlayerStateWithRounds() @@ -39,8 +36,7 @@ class TestDartsScorerX01: AbstractTest() } @Test - fun `Should render historic rounds correctly`() - { + fun `Should render historic rounds correctly`() { val scorer = factoryScorer() val roundOne = listOf(Dart(20, 1), Dart(1, 1), Dart(20, 0)) @@ -51,17 +47,13 @@ class TestDartsScorerX01: AbstractTest() scorer.stateChanged(state) val rows = scorer.tableScores.getRows() - rows.shouldContainExactly( - roundOne + 480, - roundTwo + 380 - ) + rows.shouldContainExactly(roundOne + 480, roundTwo + 380) scorer.lblResult.text shouldBe "6 Darts" } @Test - fun `Should include the current round`() - { + fun `Should include the current round`() { val scorer = factoryScorer() val roundOne = listOf(Dart(20, 1), Dart(1, 1), Dart(20, 0)) @@ -73,41 +65,39 @@ class TestDartsScorerX01: AbstractTest() scorer.stateChanged(state) val rows = scorer.tableScores.getRows() - rows.shouldContainExactly( - roundOne + 480, - listOf(Dart(20, 1), Dart(20, 1), null, null) - ) + rows.shouldContainExactly(roundOne + 480, listOf(Dart(20, 1), Dart(20, 1), null, null)) scorer.lblResult.text shouldBe "5 Darts" } @Test - fun `Should include checkout suggestions when appropriate`() - { + fun `Should include checkout suggestions when appropriate`() { val scorer = factoryScorer() val state = makeX01PlayerStateWithRounds(101, isActive = true) scorer.stateChanged(state) - scorer.tableScores.getRows().first().shouldContainExactly( - DartHint(17, 3), DartHint(25, 2), null, null - ) + scorer.tableScores + .getRows() + .first() + .shouldContainExactly(DartHint(17, 3), DartHint(25, 2), null, null) state.dartThrown(Dart(20, 3)) scorer.stateChanged(state) - scorer.tableScores.getRows().first().shouldContainExactly( - Dart(20, 3), DartHint(1, 1), DartHint(20, 2), null - ) + scorer.tableScores + .getRows() + .first() + .shouldContainExactly(Dart(20, 3), DartHint(1, 1), DartHint(20, 2), null) state.dartThrown(Dart(20, 1)) scorer.stateChanged(state) - scorer.tableScores.getRows().first().shouldContainExactly( - Dart(20, 3), Dart(20, 1), null, null - ) + scorer.tableScores + .getRows() + .first() + .shouldContainExactly(Dart(20, 3), Dart(20, 1), null, null) } @Test - fun `Should not include checkout suggestions if player is inactive`() - { + fun `Should not include checkout suggestions if player is inactive`() { val scorer = factoryScorer() val state = makeX01PlayerStateWithRounds(101, isActive = false) scorer.stateChanged(state) @@ -116,9 +106,9 @@ class TestDartsScorerX01: AbstractTest() } @Test - fun `Should toggle checkout suggestions on pause`() - { - val participant = insertParticipant(finishingPosition = 4, dtFinished = DateStatics.END_OF_TIME) + fun `Should toggle checkout suggestions on pause`() { + val participant = + insertParticipant(finishingPosition = 4, dtFinished = DateStatics.END_OF_TIME) val state = makeX01PlayerStateWithRounds(101, participant = participant, isActive = true) val scorer = factoryScorer(participant) @@ -127,23 +117,25 @@ class TestDartsScorerX01: AbstractTest() scorer.getPaused() shouldBe true scorer.tableScores.rowCount shouldBe 0 - //Unpause + // Unpause scorer.clickChild { it.icon == ICON_RESUME } scorer.getPaused() shouldBe false - scorer.tableScores.getRows().first().shouldContainExactly( - DartHint(17, 3), DartHint(25, 2), null, null - ) + scorer.tableScores + .getRows() + .first() + .shouldContainExactly(DartHint(17, 3), DartHint(25, 2), null, null) - //Pause again + // Pause again scorer.clickChild { it.icon == ICON_PAUSE } scorer.getPaused() shouldBe true scorer.tableScores.rowCount shouldBe 0 } - private fun factoryScorer(participant: ParticipantEntity = insertParticipant()): DartsScorerX01 - { + private fun factoryScorer( + participant: ParticipantEntity = insertParticipant() + ): DartsScorerX01 { val scorer = DartsScorerX01(mockk(relaxed = true), "501", SingleParticipant(participant)) scorer.init() return scorer } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeRoundResultRenderer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeRoundResultRenderer.kt index 4ac5abad3..05183b00c 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeRoundResultRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeRoundResultRenderer.kt @@ -3,14 +3,12 @@ package dartzee.screen.game.scorer import dartzee.dartzee.DartzeeRoundResult import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color +import org.junit.jupiter.api.Test -class TestDartzeeRoundResultRenderer: AbstractTest() -{ +class TestDartzeeRoundResultRenderer : AbstractTest() { @Test - fun `Should allow nulls`() - { + fun `Should allow nulls`() { val renderer = DartzeeRoundResultRenderer() renderer.allowNulls() shouldBe true @@ -20,16 +18,14 @@ class TestDartzeeRoundResultRenderer: AbstractTest() } @Test - fun `Should display a hyphen if ruleNumber is not set`() - { + fun `Should display a hyphen if ruleNumber is not set`() { val result = DartzeeRoundResult(-1, true) val renderer = DartzeeRoundResultRenderer() renderer.getReplacementValue(result) shouldBe "-" } @Test - fun `Should render the rule number in green for success`() - { + fun `Should render the rule number in green for success`() { val result = DartzeeRoundResult(5, true) val renderer = DartzeeRoundResultRenderer() @@ -40,8 +36,7 @@ class TestDartzeeRoundResultRenderer: AbstractTest() } @Test - fun `Should render the rule number in red for failure`() - { + fun `Should render the rule number in red for failure`() { val result = DartzeeRoundResult(7, false) val renderer = DartzeeRoundResultRenderer() diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeScoreRenderer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeScoreRenderer.kt index e4241addc..5245178f5 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeScoreRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestDartzeeScoreRenderer.kt @@ -3,15 +3,13 @@ package dartzee.screen.game.scorer import dartzee.helper.AbstractTest import dartzee.shouldBeBetween import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.SwingConstants +import org.junit.jupiter.api.Test -class TestDartzeeScoreRenderer: AbstractTest() -{ +class TestDartzeeScoreRenderer : AbstractTest() { @Test - fun `Should set the background colour saturation to a percentage of the maximum`() - { + fun `Should set the background colour saturation to a percentage of the maximum`() { val renderer = DartzeeScoreRenderer(50) renderer.setCellColours(0, false) @@ -28,15 +26,13 @@ class TestDartzeeScoreRenderer: AbstractTest() } @Test - fun `Should just render the value`() - { + fun `Should just render the value`() { val renderer = DartzeeScoreRenderer(50) renderer.getReplacementValue(20) shouldBe 20 } @Test - fun `Should set font and alignment, and allow nulls`() - { + fun `Should set font and alignment, and allow nulls`() { val renderer = DartzeeScoreRenderer(20) renderer.setFontsAndAlignment() @@ -45,9 +41,8 @@ class TestDartzeeScoreRenderer: AbstractTest() renderer.allowNulls() shouldBe true } - private fun Color.getSaturation(): Float - { + private fun Color.getSaturation(): Float { val hsb = Color.RGBtoHSB(red, green, blue, null) return hsb[1] } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestGolfDartRenderer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestGolfDartRenderer.kt index 89993f713..4317985b4 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestGolfDartRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestGolfDartRenderer.kt @@ -9,23 +9,21 @@ import dartzee.drtTrebleOne import dartzee.helper.AbstractTest import dartzee.`object`.Dart import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JLabel import javax.swing.JTable +import org.junit.jupiter.api.Test -class TestGolfDartRenderer : AbstractTest() -{ +class TestGolfDartRenderer : AbstractTest() { @Test - fun `Should replace dart values with their golf score`() - { + fun `Should replace dart values with their golf score`() { checkDartConversion(drtDoubleOne(), 1) checkDartConversion(drtOuterOne(), 4) checkDartConversion(drtTrebleOne(), 2) checkDartConversion(drtInnerOne(), 3) checkDartConversion(drtOuterEighteen(), 5) } - private fun checkDartConversion(dart: Dart, expectedValue: Int) - { + + private fun checkDartConversion(dart: Dart, expectedValue: Int) { val model = TableUtil.DefaultModel() model.addColumn("") model.addColumn("Dart") @@ -38,4 +36,4 @@ class TestGolfDartRenderer : AbstractTest() val c = renderer.getTableCellRendererComponent(table, dart, false, false, 0, 0) as JLabel c.text shouldBe "$expectedValue" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockDartRenderer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockDartRenderer.kt index 950e3403c..7b7dd456e 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockDartRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockDartRenderer.kt @@ -1,30 +1,28 @@ package dartzee.screen.game.scorer -import dartzee.`object`.DartNotThrown import dartzee.game.ClockType import dartzee.helper.AbstractRegistryTest import dartzee.helper.makeDart +import dartzee.`object`.DartNotThrown import dartzee.utils.PREFERENCES_DOUBLE_BG_BRIGHTNESS import dartzee.utils.PREFERENCES_DOUBLE_FG_BRIGHTNESS import dartzee.utils.PreferenceUtil import io.kotest.matchers.shouldBe +import java.awt.Color import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import java.awt.Color -class TestRoundTheClockDartRenderer: AbstractRegistryTest() -{ - override fun getPreferencesAffected() = listOf(PREFERENCES_DOUBLE_FG_BRIGHTNESS, PREFERENCES_DOUBLE_BG_BRIGHTNESS) +class TestRoundTheClockDartRenderer : AbstractRegistryTest() { + override fun getPreferencesAffected() = + listOf(PREFERENCES_DOUBLE_FG_BRIGHTNESS, PREFERENCES_DOUBLE_BG_BRIGHTNESS) @BeforeEach - fun beforeEach() - { + fun beforeEach() { clearPreferences() } @Test - fun `Should render hits as normal darts, and misses as an X`() - { + fun `Should render hits as normal darts, and misses as an X`() { val renderer = RoundTheClockDartRenderer(ClockType.Standard) val dart = makeDart(1, 1, startingScore = 1) renderer.getReplacementValue(dart) shouldBe "1" @@ -37,16 +35,14 @@ class TestRoundTheClockDartRenderer: AbstractRegistryTest() } @Test - fun `Should render out of order hits as normal darts`() - { + fun `Should render out of order hits as normal darts`() { val renderer = RoundTheClockDartRenderer(ClockType.Standard) val dart = makeDart(2, 1, startingScore = 1, clockTargets = (1..20).toList()) renderer.getReplacementValue(dart) shouldBe "2" } @Test - fun `Should take into account clockType when rendering darts`() - { + fun `Should take into account clockType when rendering darts`() { val renderer = RoundTheClockDartRenderer(ClockType.Doubles) val doubleOne = makeDart(1, 2, startingScore = 1) val singleOne = makeDart(1, 1, startingScore = 1) @@ -56,8 +52,7 @@ class TestRoundTheClockDartRenderer: AbstractRegistryTest() } @Test - fun `Should have no cell colours for a null entry`() - { + fun `Should have no cell colours for a null entry`() { val renderer = RoundTheClockDartRenderer(ClockType.Standard) renderer.setCellColours(null, false) renderer.foreground shouldBe null @@ -65,8 +60,7 @@ class TestRoundTheClockDartRenderer: AbstractRegistryTest() } @Test - fun `Should render an unthrown dart as a black box`() - { + fun `Should render an unthrown dart as a black box`() { val renderer = RoundTheClockDartRenderer(ClockType.Standard) renderer.setCellColours(DartNotThrown(), false) renderer.foreground shouldBe Color.BLACK @@ -74,8 +68,7 @@ class TestRoundTheClockDartRenderer: AbstractRegistryTest() } @Test - fun `Should render misses in red, hits in green and out of order hits in yellow`() - { + fun `Should render misses in red, hits in green and out of order hits in yellow`() { val renderer = RoundTheClockDartRenderer(ClockType.Standard) val hit = makeDart(1, 1, startingScore = 1) val outOfOrderHit = makeDart(2, 1, startingScore = 1, clockTargets = (1..20).toList()) @@ -95,8 +88,7 @@ class TestRoundTheClockDartRenderer: AbstractRegistryTest() } @Test - fun `Should adhere to brightness preferences`() - { + fun `Should adhere to brightness preferences`() { PreferenceUtil.saveDouble(PREFERENCES_DOUBLE_FG_BRIGHTNESS, 0.8) PreferenceUtil.saveDouble(PREFERENCES_DOUBLE_BG_BRIGHTNESS, 0.1) @@ -106,4 +98,4 @@ class TestRoundTheClockDartRenderer: AbstractRegistryTest() renderer.foreground shouldBe Color.getHSBColor(0.3f, 1f, 0.8f) renderer.background shouldBe Color.getHSBColor(0.3f, 1f, 0.1f) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecard.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecard.kt index 153302d05..20c4697f3 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecard.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecard.kt @@ -1,18 +1,16 @@ package dartzee.screen.game.scorer -import dartzee.`object`.Dart import dartzee.getRows import dartzee.helper.AbstractTest import dartzee.helper.makeClockPlayerState +import dartzee.`object`.Dart import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestRoundTheClockScorecard: AbstractTest() -{ +class TestRoundTheClockScorecard : AbstractTest() { @Test - fun `Should have correct rows for empty state`() - { + fun `Should have correct rows for empty state`() { val scorecard = RoundTheClockScorecard() scorecard.stateChanged(makeClockPlayerState(isActive = false), false) @@ -21,8 +19,7 @@ class TestRoundTheClockScorecard: AbstractTest() } @Test - fun `Should flag as current target if unpaused and active`() - { + fun `Should flag as current target if unpaused and active`() { val state = makeClockPlayerState(isActive = true) val scorecard = RoundTheClockScorecard() scorecard.stateChanged(state, false) @@ -30,8 +27,7 @@ class TestRoundTheClockScorecard: AbstractTest() } @Test - fun `Should not flag as current target if paused`() - { + fun `Should not flag as current target if paused`() { val state = makeClockPlayerState(isActive = true) val scorecard = RoundTheClockScorecard() scorecard.stateChanged(state, true) @@ -39,8 +35,7 @@ class TestRoundTheClockScorecard: AbstractTest() } @Test - fun `Should flag as current target if inactive`() - { + fun `Should flag as current target if inactive`() { val state = makeClockPlayerState(isActive = false) val scorecard = RoundTheClockScorecard() scorecard.stateChanged(state, false) @@ -48,22 +43,24 @@ class TestRoundTheClockScorecard: AbstractTest() } @Test - fun `Should flag results that have been hit`() - { + fun `Should flag results that have been hit`() { val state = makeClockPlayerState(isActive = false, inOrder = false) state.dartThrown(Dart(1, 1)) state.dartThrown(Dart(4, 1)) val scorecard = RoundTheClockScorecard() scorecard.stateChanged(state, false) - scorecard.getRows().first().shouldContainExactly( - makeClockResult(1, hit = true), - makeClockResult(2, hit = false), - makeClockResult(3, hit = false), - makeClockResult(4, hit = true) - ) + scorecard + .getRows() + .first() + .shouldContainExactly( + makeClockResult(1, hit = true), + makeClockResult(2, hit = false), + makeClockResult(3, hit = false), + makeClockResult(4, hit = true) + ) } } fun makeClockResult(value: Int = 1, hit: Boolean = false, isCurrentTarget: Boolean = false) = - ClockResult(value, hit, isCurrentTarget) \ No newline at end of file + ClockResult(value, hit, isCurrentTarget) diff --git a/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecardRenderer.kt b/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecardRenderer.kt index d3266fdb5..6de9aa5b9 100644 --- a/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecardRenderer.kt +++ b/src/test/kotlin/dartzee/screen/game/scorer/TestRoundTheClockScorecardRenderer.kt @@ -4,29 +4,27 @@ import dartzee.helper.AbstractRegistryTest import dartzee.utils.PREFERENCES_DOUBLE_BG_BRIGHTNESS import dartzee.utils.PREFERENCES_DOUBLE_FG_BRIGHTNESS import dartzee.utils.PreferenceUtil -import io.kotest.matchers.types.shouldBeInstanceOf import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test +import io.kotest.matchers.types.shouldBeInstanceOf import java.awt.Color import java.awt.Font import javax.swing.SwingConstants import javax.swing.border.LineBorder +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestRoundTheClockScorecardRenderer: AbstractRegistryTest() -{ - override fun getPreferencesAffected() = listOf(PREFERENCES_DOUBLE_FG_BRIGHTNESS, PREFERENCES_DOUBLE_BG_BRIGHTNESS) +class TestRoundTheClockScorecardRenderer : AbstractRegistryTest() { + override fun getPreferencesAffected() = + listOf(PREFERENCES_DOUBLE_FG_BRIGHTNESS, PREFERENCES_DOUBLE_BG_BRIGHTNESS) @BeforeEach - fun beforeEach() - { + fun beforeEach() { clearPreferences() } @Test - fun `Should have right font and alignment`() - { + fun `Should have right font and alignment`() { val renderer = RoundTheClockScorecardRenderer() renderer.setFontsAndAlignment() renderer.font.size shouldBe 15 @@ -35,8 +33,7 @@ class TestRoundTheClockScorecardRenderer: AbstractRegistryTest() } @Test - fun `Should set neutral colours for an unhit target`() - { + fun `Should set neutral colours for an unhit target`() { val renderer = RoundTheClockScorecardRenderer() renderer.setCellColours(makeClockResult(1, false), false) renderer.foreground shouldBe Color.BLACK @@ -44,8 +41,7 @@ class TestRoundTheClockScorecardRenderer: AbstractRegistryTest() } @Test - fun `Should set green colours for a hit`() - { + fun `Should set green colours for a hit`() { val renderer = RoundTheClockScorecardRenderer() renderer.setCellColours(makeClockResult(1, true), false) renderer.foreground shouldBe Color.getHSBColor(0.3f, 1f, 0.5f) @@ -53,8 +49,7 @@ class TestRoundTheClockScorecardRenderer: AbstractRegistryTest() } @Test - fun `Should adhere to brightness preferences`() - { + fun `Should adhere to brightness preferences`() { PreferenceUtil.saveDouble(PREFERENCES_DOUBLE_FG_BRIGHTNESS, 0.8) PreferenceUtil.saveDouble(PREFERENCES_DOUBLE_BG_BRIGHTNESS, 0.1) @@ -65,8 +60,7 @@ class TestRoundTheClockScorecardRenderer: AbstractRegistryTest() } @Test - fun `Should add a border if currentTarget, and not otherwise`() - { + fun `Should add a border if currentTarget, and not otherwise`() { val currentTarget = makeClockResult(isCurrentTarget = true) val nonTarget = makeClockResult(isCurrentTarget = false) @@ -79,8 +73,7 @@ class TestRoundTheClockScorecardRenderer: AbstractRegistryTest() } @Test - fun `Should use the number as its rendered value`() - { + fun `Should use the number as its rendered value`() { val renderer = RoundTheClockScorecardRenderer() val hitOne = makeClockResult(1, hit = true) val missTwo = makeClockResult(2, hit = false) @@ -88,4 +81,4 @@ class TestRoundTheClockScorecardRenderer: AbstractRegistryTest() renderer.getReplacementValue(hitOne) shouldBe "1" renderer.getReplacementValue(missTwo) shouldBe "2" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/game/x01/TestGameStatisticsPanelX01.kt b/src/test/kotlin/dartzee/screen/game/x01/TestGameStatisticsPanelX01.kt index f86c1eb3d..7b8ac528a 100644 --- a/src/test/kotlin/dartzee/screen/game/x01/TestGameStatisticsPanelX01.kt +++ b/src/test/kotlin/dartzee/screen/game/x01/TestGameStatisticsPanelX01.kt @@ -1,25 +1,26 @@ package dartzee.screen.game.x01 -import dartzee.`object`.Dart import dartzee.game.state.X01PlayerState import dartzee.helper.insertPlayer import dartzee.helper.makeX01PlayerState import dartzee.helper.makeX01PlayerStateWithRounds import dartzee.helper.makeX01Rounds +import dartzee.`object`.Dart import dartzee.screen.game.AbstractGameStatisticsPanelTest import dartzee.screen.game.getRowIndex import dartzee.screen.game.getValueForRow import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGameStatisticsPanelX01: AbstractGameStatisticsPanelTest() -{ +class TestGameStatisticsPanelX01 : + AbstractGameStatisticsPanelTest() { override fun factoryStatsPanel() = GameStatisticsPanelX01("501") - override fun makePlayerState() = makeX01PlayerState(completedRound = listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1))) + + override fun makePlayerState() = + makeX01PlayerState(completedRound = listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1))) @Test - fun `Should set the maximum setupThreshold to be 1 less than the starting score`() - { + fun `Should set the maximum setupThreshold to be 1 less than the starting score`() { val panel = GameStatisticsPanelX01("501") panel.nfSetupThreshold.getMaximum() shouldBe 500 @@ -28,16 +29,41 @@ class TestGameStatisticsPanelX01: AbstractGameStatisticsPanelTest() -{ +class TestMatchStatisticsPanelX01 : + AbstractGameStatisticsPanelTest() { override fun factoryStatsPanel() = MatchStatisticsPanelX01("501") - override fun makePlayerState() = makeX01PlayerState(completedRound = listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1))) + + override fun makePlayerState() = + makeX01PlayerState(completedRound = listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1))) @Test - fun `Should get the correct value for best finish`() - { + fun `Should get the correct value for best finish`() { val finishOne = listOf(makeDart(17, 1), makeDart(20, 0), makeDart(20, 2)) makeX01Rounds(57, finishOne) @@ -35,4 +36,4 @@ class TestMatchStatisticsPanelX01: AbstractGameStatisticsPanelTest

Achievements

7 / ${getAchievementMaximum()}
" + button.text shouldBe + "

Achievements

7 / ${getAchievementMaximum()}
" } @Test - fun `Should switch to the achievements screen on click`() - { + fun `Should switch to the achievements screen on click`() { val startingScreen = ScreenCache.currentScreen() val player = insertPlayer() @@ -52,8 +65,7 @@ class TestPlayerAchievementsButton: AbstractTest() } @Test - fun `Should change text on hover`() - { + fun `Should change text on hover`() { val player = insertPlayer() val button = PlayerAchievementsButton(player, listOf()) val text = button.text @@ -64,4 +76,4 @@ class TestPlayerAchievementsButton: AbstractTest() button.doHoverAway() button.text shouldBe text } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/player/TestPlayerManagementPanel.kt b/src/test/kotlin/dartzee/screen/player/TestPlayerManagementPanel.kt index 6ce7cfd0a..efd95bc92 100644 --- a/src/test/kotlin/dartzee/screen/player/TestPlayerManagementPanel.kt +++ b/src/test/kotlin/dartzee/screen/player/TestPlayerManagementPanel.kt @@ -35,16 +35,14 @@ import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import io.kotest.matchers.string.shouldContain -import org.junit.jupiter.api.Test import javax.swing.JButton import javax.swing.JOptionPane import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestPlayerManagementPanel: AbstractTest() -{ +class TestPlayerManagementPanel : AbstractTest() { @Test - fun `Should clear down when refreshed with a null player`() - { + fun `Should clear down when refreshed with a null player`() { val player = insertPlayer() val panel = PlayerManagementPanel() panel.refresh(player) @@ -59,8 +57,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should not delete a player if cancelled`() - { + fun `Should not delete a player if cancelled`() { val player = insertPlayer(name = "Leah") val managementScreen = ScreenCache.get() managementScreen.initialise() @@ -78,8 +75,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should delete a player and update management screen`() - { + fun `Should delete a player and update management screen`() { val player = insertPlayer(name = "BTBF") val managementScreen = ScreenCache.get() managementScreen.initialise() @@ -97,8 +93,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should initialise correctly for a human player`() - { + fun `Should initialise correctly for a human player`() { val image = insertPlayerImage(resource = "Sid") val player = insertPlayer(name = "Alex", playerImageId = image.rowId, strategy = "") @@ -113,8 +108,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should initialise correctly for an AI player`() - { + fun `Should initialise correctly for an AI player`() { val image = insertPlayerImage(resource = "Dennis") val player = insertPlayer(name = "Dennis", playerImageId = image.rowId, strategy = "foo") @@ -129,14 +123,12 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should handle a player with 0 games or achievements`() - { + fun `Should handle a player with 0 games or achievements`() { val player = insertPlayer() val panel = PlayerManagementPanel() panel.refresh(player) - val x01Button = panel.getChild { it.text.contains("X01") } x01Button.isEnabled shouldBe false x01Button.text.shouldContain("Played: 0") @@ -148,8 +140,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should pull through total games played by type`() - { + fun `Should pull through total games played by type`() { val player = insertPlayer() insertGameForPlayer(player, GameType.X01) @@ -174,11 +165,18 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should pull through a players best game per type`() - { + fun `Should pull through a players best game per type`() { val player = insertPlayer() - insertAchievement(playerId = player.rowId, type = AchievementType.X01_BEST_GAME, achievementCounter = 25) - insertAchievement(playerId = player.rowId, type = AchievementType.GOLF_BEST_GAME, achievementCounter = 55) + insertAchievement( + playerId = player.rowId, + type = AchievementType.X01_BEST_GAME, + achievementCounter = 25 + ) + insertAchievement( + playerId = player.rowId, + type = AchievementType.GOLF_BEST_GAME, + achievementCounter = 55 + ) val panel = PlayerManagementPanel() panel.refresh(player) @@ -194,13 +192,20 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should pull through a players total achievement count`() - { + fun `Should pull through a players total achievement count`() { val player = insertPlayer() - //1 pink, 1 green = 10 total - insertAchievement(playerId = player.rowId, type = AchievementType.X01_BEST_GAME, achievementCounter = AchievementX01BestGame().pinkThreshold) - insertAchievement(playerId = player.rowId, type = AchievementType.GOLF_BEST_GAME, achievementCounter = AchievementGolfBestGame().greenThreshold) + // 1 pink, 1 green = 10 total + insertAchievement( + playerId = player.rowId, + type = AchievementType.X01_BEST_GAME, + achievementCounter = AchievementX01BestGame().pinkThreshold + ) + insertAchievement( + playerId = player.rowId, + type = AchievementType.GOLF_BEST_GAME, + achievementCounter = AchievementGolfBestGame().greenThreshold + ) val panel = PlayerManagementPanel() panel.refresh(player) @@ -210,8 +215,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should support editing a human player`() - { + fun `Should support editing a human player`() { val player = insertPlayer(name = "Old name") val panel = PlayerManagementPanel() @@ -229,8 +233,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should support editing an AI player`() - { + fun `Should support editing an AI player`() { val player = insertPlayer(model = makeDartsModel(), name = "Old name") val panel = PlayerManagementPanel() @@ -248,8 +251,7 @@ class TestPlayerManagementPanel: AbstractTest() } @Test - fun `Should run a simulation for a player`() - { + fun `Should run a simulation for a player`() { val player = insertPlayer(makeDartsModel()) val panel = PlayerManagementPanel() @@ -258,4 +260,4 @@ class TestPlayerManagementPanel: AbstractTest() findWindow().shouldNotBeNull() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/player/TestPlayerManagementScreen.kt b/src/test/kotlin/dartzee/screen/player/TestPlayerManagementScreen.kt index f9ad2e519..7230dc3f0 100644 --- a/src/test/kotlin/dartzee/screen/player/TestPlayerManagementScreen.kt +++ b/src/test/kotlin/dartzee/screen/player/TestPlayerManagementScreen.kt @@ -18,15 +18,13 @@ import dartzee.screen.ai.AIConfigurationDialog import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JButton import javax.swing.JTextField +import org.junit.jupiter.api.Test -class TestPlayerManagementScreen: AbstractTest() -{ +class TestPlayerManagementScreen : AbstractTest() { @Test - fun `Should load players from the database`() - { + fun `Should load players from the database`() { val p1 = insertPlayer() val p2 = insertPlayer() @@ -38,8 +36,7 @@ class TestPlayerManagementScreen: AbstractTest() } @Test - fun `Should refresh the summary panel as rows are selected or deselected`() - { + fun `Should refresh the summary panel as rows are selected or deselected`() { insertPlayer(name = "Alex") insertPlayer(name = "Leah") @@ -59,8 +56,7 @@ class TestPlayerManagementScreen: AbstractTest() } @Test - fun `Should reset the summary panel when reinitialised`() - { + fun `Should reset the summary panel when reinitialised`() { insertPlayer(name = "Alex") val scrn = PlayerManagementScreen() @@ -73,8 +69,7 @@ class TestPlayerManagementScreen: AbstractTest() } @Test - fun `Should create a new human player and update the table`() - { + fun `Should create a new human player and update the table`() { val scrn = PlayerManagementScreen() scrn.initialise() @@ -94,8 +89,7 @@ class TestPlayerManagementScreen: AbstractTest() } @Test - fun `Should create a new AI player and update the table`() - { + fun `Should create a new AI player and update the table`() { val scrn = PlayerManagementScreen() scrn.initialise() @@ -115,8 +109,7 @@ class TestPlayerManagementScreen: AbstractTest() } @Test - fun `Should not reinitialise the table if player creation is cancelled`() - { + fun `Should not reinitialise the table if player creation is cancelled`() { val scrn = PlayerManagementScreen() scrn.initialise() @@ -137,9 +130,8 @@ class TestPlayerManagementScreen: AbstractTest() table.rowCount shouldBe 0 } - private fun PlayerManagementScreen.getSummaryPlayerName(): String - { + private fun PlayerManagementScreen.getSummaryPlayerName(): String { val summaryPanel = getChild() return summaryPanel.lblPlayerName.text } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/player/TestPlayerStatsButton.kt b/src/test/kotlin/dartzee/screen/player/TestPlayerStatsButton.kt index f51567226..cdf91c242 100644 --- a/src/test/kotlin/dartzee/screen/player/TestPlayerStatsButton.kt +++ b/src/test/kotlin/dartzee/screen/player/TestPlayerStatsButton.kt @@ -11,28 +11,28 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.Test -class TestPlayerStatsButton: AbstractTest() -{ +class TestPlayerStatsButton : AbstractTest() { @Test - fun `Should have the correct text based on values passed in`() - { + fun `Should have the correct text based on values passed in`() { val player = insertPlayer() val button = PlayerStatsButton(player, GameType.X01, 10, 35) - button.text shouldBe "

X01

Played: 10
Best game: 35
" + button.text shouldBe + "

X01

Played: 10
Best game: 35
" button.isEnabled shouldBe true val golfButton = PlayerStatsButton(player, GameType.GOLF, 25, 18) - golfButton.text shouldBe "

Golf

Played: 25
Best game: 18
" + golfButton.text shouldBe + "

Golf

Played: 25
Best game: 18
" golfButton.isEnabled shouldBe true } @Test - fun `Should be disabled if 0 games played, and not do anything on hover`() - { + fun `Should be disabled if 0 games played, and not do anything on hover`() { val player = insertPlayer() - val expectedText = "

X01

Played: 0
Best game: -
" + val expectedText = + "

X01

Played: 0
Best game: -
" val button = PlayerStatsButton(player, GameType.X01, 0, 0) button.text shouldBe expectedText @@ -43,8 +43,7 @@ class TestPlayerStatsButton: AbstractTest() } @Test - fun `Should change text on hover if enabled`() - { + fun `Should change text on hover if enabled`() { val player = insertPlayer() val button = PlayerStatsButton(player, GameType.X01, 10, 35) @@ -58,8 +57,7 @@ class TestPlayerStatsButton: AbstractTest() } @Test - fun `Should switch to the players stats on click, and reset button text`() - { + fun `Should switch to the players stats on click, and reset button text`() { val player = insertPlayer() val button = PlayerStatsButton(player, GameType.X01, 10, 35) val text = button.text @@ -74,4 +72,4 @@ class TestPlayerStatsButton: AbstractTest() currentScreen.player shouldBe player currentScreen.gameType shouldBe GameType.X01 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/preference/AbstractPreferencePanelTest.kt b/src/test/kotlin/dartzee/screen/preference/AbstractPreferencePanelTest.kt index 2e496e675..a8b5b2cde 100644 --- a/src/test/kotlin/dartzee/screen/preference/AbstractPreferencePanelTest.kt +++ b/src/test/kotlin/dartzee/screen/preference/AbstractPreferencePanelTest.kt @@ -5,20 +5,22 @@ import com.github.alyssaburlton.swingtest.getChild import com.github.alyssaburlton.swingtest.shouldBeDisabled import com.github.alyssaburlton.swingtest.shouldBeEnabled import dartzee.helper.AbstractRegistryTest -import org.junit.jupiter.api.Test import javax.swing.JButton +import org.junit.jupiter.api.Test -abstract class AbstractPreferencePanelTest: AbstractRegistryTest() -{ +abstract class AbstractPreferencePanelTest : AbstractRegistryTest() { abstract fun checkUiFieldValuesAreDefaults(panel: T) + abstract fun checkUiFieldValuesAreNonDefaults(panel: T) + abstract fun setUiFieldValuesToNonDefaults(panel: T) + abstract fun checkPreferencesAreSetToNonDefaults() + abstract fun factory(): T @Test - fun `should restore defaults appropriately`() - { + fun `should restore defaults appropriately`() { val panel = factory() setUiFieldValuesToNonDefaults(panel) @@ -29,8 +31,7 @@ abstract class AbstractPreferencePanelTest: Abstrac } @Test - fun `should set fields to their defaults when first loaded`() - { + fun `should set fields to their defaults when first loaded`() { clearPreferences() val panel = factory() @@ -40,8 +41,7 @@ abstract class AbstractPreferencePanelTest: Abstrac } @Test - fun `should save preferences appropriately`() - { + fun `should save preferences appropriately`() { clearPreferences() val panel = factory() @@ -52,8 +52,7 @@ abstract class AbstractPreferencePanelTest: Abstrac } @Test - fun `should display stored preferences correctly`() - { + fun `should display stored preferences correctly`() { val panel = factory() setUiFieldValuesToNonDefaults(panel) panel.clickChild(text = "Apply") @@ -65,8 +64,7 @@ abstract class AbstractPreferencePanelTest: Abstrac } @Test - fun `apply button should be disabled by default`() - { + fun `apply button should be disabled by default`() { val panel = factory() panel.refresh(false) @@ -74,8 +72,7 @@ abstract class AbstractPreferencePanelTest: Abstrac } @Test - fun `apply button should respond to UI changes correctly`() - { + fun `apply button should respond to UI changes correctly`() { clearPreferences() val panel = factory() @@ -101,4 +98,4 @@ abstract class AbstractPreferencePanelTest: Abstrac setUiFieldValuesToNonDefaults(panel) panel.getChild(text = "Apply").shouldBeDisabled() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/preference/TestPreferencesPanelDartboard.kt b/src/test/kotlin/dartzee/screen/preference/TestPreferencesPanelDartboard.kt index 6b78ba2a3..aafe1582a 100644 --- a/src/test/kotlin/dartzee/screen/preference/TestPreferencesPanelDartboard.kt +++ b/src/test/kotlin/dartzee/screen/preference/TestPreferencesPanelDartboard.kt @@ -15,17 +15,15 @@ import dartzee.utils.PREFERENCES_STRING_ODD_TREBLE_COLOUR import dartzee.utils.PreferenceUtil import io.kotest.matchers.ints.shouldBeGreaterThan import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.BorderLayout import java.awt.Color import java.awt.Dimension import javax.swing.JFrame +import org.junit.jupiter.api.Test -class TestPreferencesPanelDartboard: AbstractPreferencePanelTest() -{ +class TestPreferencesPanelDartboard : AbstractPreferencePanelTest() { @Test - fun `Dartboard should refresh when settings are changed`() - { + fun `Dartboard should refresh when settings are changed`() { val frame = JFrame() val panel = PreferencesPanelDartboard() @@ -59,18 +57,18 @@ class TestPreferencesPanelDartboard: AbstractPreferencePanelTest - { - return mutableListOf(PREFERENCES_STRING_EVEN_SINGLE_COLOUR, - PREFERENCES_STRING_EVEN_DOUBLE_COLOUR, - PREFERENCES_STRING_EVEN_TREBLE_COLOUR, - PREFERENCES_STRING_ODD_SINGLE_COLOUR, - PREFERENCES_STRING_ODD_DOUBLE_COLOUR, - PREFERENCES_STRING_ODD_TREBLE_COLOUR) + override fun getPreferencesAffected(): MutableList { + return mutableListOf( + PREFERENCES_STRING_EVEN_SINGLE_COLOUR, + PREFERENCES_STRING_EVEN_DOUBLE_COLOUR, + PREFERENCES_STRING_EVEN_TREBLE_COLOUR, + PREFERENCES_STRING_ODD_SINGLE_COLOUR, + PREFERENCES_STRING_ODD_DOUBLE_COLOUR, + PREFERENCES_STRING_ODD_TREBLE_COLOUR + ) } - override fun checkUiFieldValuesAreDefaults(panel: PreferencesPanelDartboard) - { + override fun checkUiFieldValuesAreDefaults(panel: PreferencesPanelDartboard) { panel.cpOddSingle.selectedColour shouldBe DartsColour.DARTBOARD_WHITE panel.cpOddDouble.selectedColour shouldBe DartsColour.DARTBOARD_GREEN panel.cpOddTreble.selectedColour shouldBe DartsColour.DARTBOARD_GREEN @@ -80,8 +78,7 @@ class TestPreferencesPanelDartboard: AbstractPreferencePanelTest() -{ - override fun getPreferencesAffected(): MutableList - { - return mutableListOf(PREFERENCES_INT_AI_SPEED, - PREFERENCES_INT_LEADERBOARD_SIZE, - PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE, - PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES, - PREFERENCES_BOOLEAN_SHOW_ANIMATIONS) +class TestPreferencesPanelMisc : AbstractPreferencePanelTest() { + override fun getPreferencesAffected(): MutableList { + return mutableListOf( + PREFERENCES_INT_AI_SPEED, + PREFERENCES_INT_LEADERBOARD_SIZE, + PREFERENCES_BOOLEAN_AI_AUTO_CONTINUE, + PREFERENCES_BOOLEAN_CHECK_FOR_UPDATES, + PREFERENCES_BOOLEAN_SHOW_ANIMATIONS + ) } override fun factory() = PreferencesPanelMisc() - override fun setUiFieldValuesToNonDefaults(panel: PreferencesPanelMisc) - { + override fun setUiFieldValuesToNonDefaults(panel: PreferencesPanelMisc) { panel.slider.value = 20 panel.nfLeaderboardSize.value = 100 @@ -32,8 +31,7 @@ class TestPreferencesPanelMisc: AbstractPreferencePanelTest() -{ - override fun getPreferencesAffected(): MutableList - { - return mutableListOf(PREFERENCES_DOUBLE_HUE_FACTOR, - PREFERENCES_DOUBLE_BG_BRIGHTNESS, - PREFERENCES_DOUBLE_FG_BRIGHTNESS) +class TestPreferencesPanelScorer : AbstractPreferencePanelTest() { + override fun getPreferencesAffected(): MutableList { + return mutableListOf( + PREFERENCES_DOUBLE_HUE_FACTOR, + PREFERENCES_DOUBLE_BG_BRIGHTNESS, + PREFERENCES_DOUBLE_FG_BRIGHTNESS + ) } override fun factory() = PreferencesPanelScorer() - override fun checkUiFieldValuesAreDefaults(panel: PreferencesPanelScorer) - { + override fun checkUiFieldValuesAreDefaults(panel: PreferencesPanelScorer) { panel.spinnerHueFactor.value shouldBe 0.8 panel.spinnerFgBrightness.value shouldBe 0.5 panel.spinnerBgBrightness.value shouldBe 1.0 } - override fun setUiFieldValuesToNonDefaults(panel: PreferencesPanelScorer) - { + override fun setUiFieldValuesToNonDefaults(panel: PreferencesPanelScorer) { panel.spinnerHueFactor.value = 0.5 panel.spinnerFgBrightness.value = 0.9 panel.spinnerBgBrightness.value = 0.6 } - override fun checkUiFieldValuesAreNonDefaults(panel: PreferencesPanelScorer) - { + override fun checkUiFieldValuesAreNonDefaults(panel: PreferencesPanelScorer) { panel.spinnerHueFactor.value shouldBe 0.5 panel.spinnerFgBrightness.value shouldBe 0.9 panel.spinnerBgBrightness.value shouldBe 0.6 } - override fun checkPreferencesAreSetToNonDefaults() - { + override fun checkPreferencesAreSetToNonDefaults() { PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_HUE_FACTOR) shouldBe 0.5 PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_FG_BRIGHTNESS) shouldBe 0.9 PreferenceUtil.getDoubleValue(PREFERENCES_DOUBLE_BG_BRIGHTNESS) shouldBe 0.6 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/preference/TestPreferencesScreen.kt b/src/test/kotlin/dartzee/screen/preference/TestPreferencesScreen.kt index 1b34e6fe5..f0941dc05 100644 --- a/src/test/kotlin/dartzee/screen/preference/TestPreferencesScreen.kt +++ b/src/test/kotlin/dartzee/screen/preference/TestPreferencesScreen.kt @@ -5,19 +5,17 @@ import dartzee.screen.MenuScreen import dartzee.screen.ScreenCache import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly -import io.kotest.matchers.types.shouldBeInstanceOf import io.kotest.matchers.shouldBe +import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JOptionPane +import org.junit.jupiter.api.Test -class TestPreferencesScreen: AbstractTest() -{ +class TestPreferencesScreen : AbstractTest() { @Test - fun `Should refresh panels on init`() - { + fun `Should refresh panels on init`() { val mockPanel = mockk(relaxed = true) val screen = PreferencesScreen(listOf(mockPanel)) screen.initialise() @@ -26,8 +24,7 @@ class TestPreferencesScreen: AbstractTest() } @Test - fun `Should not go back if there are outstanding changes and user cancels`() - { + fun `Should not go back if there are outstanding changes and user cancels`() { dialogFactory.questionOption = JOptionPane.NO_OPTION val mockPanel = mockk(relaxed = true) every { mockPanel.hasOutstandingChanges() } returns true @@ -37,14 +34,15 @@ class TestPreferencesScreen: AbstractTest() ScreenCache.switch(screen, true) screen.btnBack.doClick() - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to go back?\n\nYou have unsaved changes that will be discarded.") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to go back?\n\nYou have unsaved changes that will be discarded." + ) ScreenCache.currentScreen() shouldBe screen } @Test - fun `Should not go back if there are outstanding changes and user confirms`() - { + fun `Should not go back if there are outstanding changes and user confirms`() { dialogFactory.questionOption = JOptionPane.YES_OPTION val mockPanel = mockk(relaxed = true) every { mockPanel.hasOutstandingChanges() } returns true @@ -54,14 +52,15 @@ class TestPreferencesScreen: AbstractTest() ScreenCache.switch(screen, true) screen.btnBack.doClick() - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to go back?\n\nYou have unsaved changes that will be discarded.") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to go back?\n\nYou have unsaved changes that will be discarded." + ) ScreenCache.currentScreen().shouldBeInstanceOf() } @Test - fun `Should go back as normal if there are no outstanding changes`() - { + fun `Should go back as normal if there are no outstanding changes`() { val mockPanel = mockk(relaxed = true) every { mockPanel.hasOutstandingChanges() } returns false diff --git a/src/test/kotlin/dartzee/screen/reporting/TestConfigureReportColumnsDialog.kt b/src/test/kotlin/dartzee/screen/reporting/TestConfigureReportColumnsDialog.kt index 3bfbaa4cc..718178913 100644 --- a/src/test/kotlin/dartzee/screen/reporting/TestConfigureReportColumnsDialog.kt +++ b/src/test/kotlin/dartzee/screen/reporting/TestConfigureReportColumnsDialog.kt @@ -6,14 +6,12 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JCheckBox +import org.junit.jupiter.api.Test -class TestConfigureReportColumnsDialog: AbstractTest() -{ +class TestConfigureReportColumnsDialog : AbstractTest() { @Test - fun `Should start with all options checked`() - { + fun `Should start with all options checked`() { val dlg = ConfigureReportColumnsDialog() val checkBoxes = dlg.getAllChildComponentsForType() checkBoxes.forEach { it.isSelected shouldBe true } @@ -22,12 +20,11 @@ class TestConfigureReportColumnsDialog: AbstractTest() } @Test - fun `Should exclude unticked options`() - { + fun `Should exclude unticked options`() { val dlg = ConfigureReportColumnsDialog() dlg.clickChild(text = "Type") dlg.clickChild(text = "Match") dlg.excludedColumns().shouldContainExactly("Type", "Match") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/reporting/TestPlayerParametersPanel.kt b/src/test/kotlin/dartzee/screen/reporting/TestPlayerParametersPanel.kt index 63d778840..8c1a7339d 100644 --- a/src/test/kotlin/dartzee/screen/reporting/TestPlayerParametersPanel.kt +++ b/src/test/kotlin/dartzee/screen/reporting/TestPlayerParametersPanel.kt @@ -9,14 +9,12 @@ import dartzee.reporting.IncludedPlayerParameters import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JCheckBox +import org.junit.jupiter.api.Test -class TestPlayerParametersPanel: AbstractTest() -{ +class TestPlayerParametersPanel : AbstractTest() { @Test - fun `Should support disabling all components`() - { + fun `Should support disabling all components`() { val panel = PlayerParametersPanel() panel.disableAll() @@ -24,8 +22,7 @@ class TestPlayerParametersPanel: AbstractTest() } @Test - fun `Should having nothing selected by default, and generate empty parameters`() - { + fun `Should having nothing selected by default, and generate empty parameters`() { val panel = PlayerParametersPanel() panel.chckbxPosition.isSelected shouldBe false panel.chckbxFinalScore.isSelected shouldBe false @@ -34,8 +31,7 @@ class TestPlayerParametersPanel: AbstractTest() } @Test - fun `Should enable and disable the position checkboxes`() - { + fun `Should enable and disable the position checkboxes`() { val panel = PlayerParametersPanel() panel.positionCheckboxes.forEach { it.isEnabled shouldBe false } panel.cbUndecided.isEnabled shouldBe false @@ -50,8 +46,7 @@ class TestPlayerParametersPanel: AbstractTest() } @Test - fun `Should enable and disable the score options`() - { + fun `Should enable and disable the score options`() { val panel = PlayerParametersPanel() panel.comboBox.isEnabled shouldBe false panel.spinner.isEnabled shouldBe false @@ -66,8 +61,7 @@ class TestPlayerParametersPanel: AbstractTest() } @Test - fun `Should enable and disable the spinner based on combo selection`() - { + fun `Should enable and disable the spinner based on combo selection`() { val panel = PlayerParametersPanel() panel.chckbxFinalScore.doClick() panel.spinner.isEnabled shouldBe true @@ -80,8 +74,7 @@ class TestPlayerParametersPanel: AbstractTest() } @Test - fun `Should not be valid if position is selected but nothing ticked`() - { + fun `Should not be valid if position is selected but nothing ticked`() { val player = insertPlayer(name = "Gordon") val panel = PlayerParametersPanel() @@ -89,7 +82,9 @@ class TestPlayerParametersPanel: AbstractTest() panel.clickChild(text = "Position") panel.valid(player) shouldBe false - dialogFactory.errorsShown.shouldContainExactly("You must select at least one finishing position for player Gordon") + dialogFactory.errorsShown.shouldContainExactly( + "You must select at least one finishing position for player Gordon" + ) dialogFactory.errorsShown.clear() panel.clickChild(text = "Undecided") @@ -103,8 +98,7 @@ class TestPlayerParametersPanel: AbstractTest() } @Test - fun `Should generate the correct parameters for final score`() - { + fun `Should generate the correct parameters for final score`() { val panel = PlayerParametersPanel() panel.clickChild(text = "Game Score") panel.spinner.value = 20 @@ -116,16 +110,14 @@ class TestPlayerParametersPanel: AbstractTest() } @Test - fun `Should generate the correct parameters for position`() - { + fun `Should generate the correct parameters for position`() { val panel = PlayerParametersPanel() panel.clickChild(text = "Position") panel.clickChild(text = "1st") panel.clickChild(text = "5th") panel.clickChild(text = "Undecided") - val params = panel.generateParameters() params.finishingPositions.shouldContainExactly(1, 5, -1) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/reporting/TestReportingGameTab.kt b/src/test/kotlin/dartzee/screen/reporting/TestReportingGameTab.kt index 7f61c516f..412486db9 100644 --- a/src/test/kotlin/dartzee/screen/reporting/TestReportingGameTab.kt +++ b/src/test/kotlin/dartzee/screen/reporting/TestReportingGameTab.kt @@ -21,19 +21,17 @@ import dartzee.updateSelection import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.Test import java.sql.Timestamp import java.time.LocalDate import javax.swing.JCheckBox import javax.swing.JComboBox import javax.swing.JLabel import javax.swing.JRadioButton +import org.junit.jupiter.api.Test -class TestReportingGameTab: AbstractTest() -{ +class TestReportingGameTab : AbstractTest() { @Test - fun `Should have the correct initial state`() - { + fun `Should have the correct initial state`() { val scrn = ReportingGameTab() val checkBoxes = scrn.getAllChildComponentsForType() checkBoxes.forEach { it.isSelected shouldBe false } @@ -45,8 +43,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should toggle game type combo box correctly`() - { + fun `Should toggle game type combo box correctly`() { val scrn = ReportingGameTab() scrn.clickChild(text = "Game") scrn.getChild().shouldBeEnabled() @@ -56,20 +53,20 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should swap in the right game param filter panel`() - { + fun `Should swap in the right game param filter panel`() { val scrn = ReportingGameTab() scrn.getChild().shouldBeInstanceOf() scrn.clickChild(text = "Game") val comboBox = scrn.getChild() comboBox.updateSelection(GameType.ROUND_THE_CLOCK) - scrn.getChild().shouldBeInstanceOf() + scrn + .getChild() + .shouldBeInstanceOf() } @Test - fun `Should toggle the game param filter panel correctly`() - { + fun `Should toggle the game param filter panel correctly`() { val scrn = ReportingGameTab() scrn.clickChild(text = "Type") scrn.getChild().shouldBeEnabled() @@ -79,8 +76,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should toggle the start date filter panel correctly`() - { + fun `Should toggle the start date filter panel correctly`() { val scrn = ReportingGameTab() scrn.clickChild(text = "Start Date") scrn.getStartDateFilterPanel().cbDateFrom.shouldBeEnabled() @@ -90,8 +86,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should toggle the finish date filter panel correctly`() - { + fun `Should toggle the finish date filter panel correctly`() { val scrn = ReportingGameTab() scrn.clickChild(text = "Finish Date") scrn.getFinishDateFilterPanel().cbDateTo.shouldBeEnabled() @@ -111,8 +106,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should toggle match radio buttons correctly`() - { + fun `Should toggle match radio buttons correctly`() { val tab = ReportingGameTab() tab.clickChild(text = "Part of Match") tab.getChild(text = "Yes").shouldBeEnabled() @@ -124,8 +118,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should toggle the sync status radio buttons correctly`() - { + fun `Should toggle the sync status radio buttons correctly`() { val tab = ReportingGameTab() tab.clickChild(text = "Sync Status") tab.getChild(text = "Pending changes").shouldBeEnabled() @@ -136,44 +129,40 @@ class TestReportingGameTab: AbstractTest() tab.getChild(text = "Synced").shouldBeDisabled() } - /** - * Validation - */ + /** Validation */ @Test - fun `Should validate against the start date filters`() - { + fun `Should validate against the start date filters`() { val tab = ReportingGameTab() tab.clickChild(text = "Start Date") tab.getStartDateFilterPanel().makeInvalid() tab.valid() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("The 'date from' cannot be after the 'date to'") + dialogFactory.errorsShown.shouldContainExactly( + "The 'date from' cannot be after the 'date to'" + ) } @Test - fun `Should validate against the finish date filters`() - { + fun `Should validate against the finish date filters`() { val tab = ReportingGameTab() tab.clickChild(text = "Finish Date") tab.getFinishDateFilterPanel().makeInvalid() tab.valid() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("The 'date from' cannot be after the 'date to'") + dialogFactory.errorsShown.shouldContainExactly( + "The 'date from' cannot be after the 'date to'" + ) } @Test - fun `Should be valid by default`() - { + fun `Should be valid by default`() { val tab = ReportingGameTab() tab.valid() shouldBe true } - /** - * Population - */ + /** Population */ @Test - fun `Should populate game type correctly`() - { + fun `Should populate game type correctly`() { val rp = ReportParameters() val tab = ReportingGameTab() @@ -190,8 +179,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should populate gameParams correctly`() - { + fun `Should populate gameParams correctly`() { val rp = ReportParameters() val tab = ReportingGameTab() @@ -208,8 +196,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should populate part of match correctly`() - { + fun `Should populate part of match correctly`() { val rp = ReportParameters() val tab = ReportingGameTab() @@ -226,8 +213,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should populate sync status correctly`() - { + fun `Should populate sync status correctly`() { val rp = ReportParameters() val tab = ReportingGameTab() @@ -244,8 +230,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should populate start date correctly`() - { + fun `Should populate start date correctly`() { val rp = ReportParameters() val tab = ReportingGameTab() @@ -264,8 +249,7 @@ class TestReportingGameTab: AbstractTest() } @Test - fun `Should populate finish date correctly`() - { + fun `Should populate finish date correctly`() { var rp = ReportParameters() val tab = ReportingGameTab() @@ -292,6 +276,9 @@ class TestReportingGameTab: AbstractTest() rp.unfinishedOnly shouldBe true } - private fun ReportingGameTab.getStartDateFilterPanel() = getAllChildComponentsForType().first() - private fun ReportingGameTab.getFinishDateFilterPanel() = getAllChildComponentsForType()[1] -} \ No newline at end of file + private fun ReportingGameTab.getStartDateFilterPanel() = + getAllChildComponentsForType().first() + + private fun ReportingGameTab.getFinishDateFilterPanel() = + getAllChildComponentsForType()[1] +} diff --git a/src/test/kotlin/dartzee/screen/reporting/TestReportingPlayersTab.kt b/src/test/kotlin/dartzee/screen/reporting/TestReportingPlayersTab.kt index 1bb156086..169a2548c 100644 --- a/src/test/kotlin/dartzee/screen/reporting/TestReportingPlayersTab.kt +++ b/src/test/kotlin/dartzee/screen/reporting/TestReportingPlayersTab.kt @@ -12,18 +12,15 @@ import io.kotest.matchers.maps.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestReportingPlayersTab: AbstractTest() -{ +class TestReportingPlayersTab : AbstractTest() { @Test - fun `Should initialise with an empty player table`() - { + fun `Should initialise with an empty player table`() { val tab = ReportingPlayersTab() tab.scrollTable.lblRowCount.text shouldBe "0 players" } @Test - fun `Should show an error if trying to remove without a selected row`() - { + fun `Should show an error if trying to remove without a selected row`() { val tab = ReportingPlayersTab() tab.addPlayers(listOf(insertPlayer())) tab.scrollTable.selectRow(-1) @@ -35,8 +32,7 @@ class TestReportingPlayersTab: AbstractTest() } @Test - fun `Should remove a player and reset their included parameters`() - { + fun `Should remove a player and reset their included parameters`() { val p = insertPlayer() val tab = ReportingPlayersTab() tab.addPlayers(listOf(p)) @@ -53,8 +49,7 @@ class TestReportingPlayersTab: AbstractTest() } @Test - fun `Should enable, disable and hide the player parameter panel as appropriate`() - { + fun `Should enable, disable and hide the player parameter panel as appropriate`() { val p1 = insertPlayer() val p2 = insertPlayer() val tab = ReportingPlayersTab() @@ -91,8 +86,7 @@ class TestReportingPlayersTab: AbstractTest() } @Test - fun `Should populate report parameters correctly with no players selected`() - { + fun `Should populate report parameters correctly with no players selected`() { val tab = ReportingPlayersTab() val rp = ReportParameters() @@ -107,8 +101,7 @@ class TestReportingPlayersTab: AbstractTest() } @Test - fun `Should populate excludeOnlyAi correctly`() - { + fun `Should populate excludeOnlyAi correctly`() { val tab = ReportingPlayersTab() val rp = ReportParameters() @@ -125,8 +118,7 @@ class TestReportingPlayersTab: AbstractTest() } @Test - fun `Should populate included players correctly`() - { + fun `Should populate included players correctly`() { val playerOne = insertPlayer() val playerTwo = insertPlayer() @@ -138,12 +130,16 @@ class TestReportingPlayersTab: AbstractTest() tab.populateReportParameters(rp) rp.excludedPlayers.shouldBeEmpty() - rp.hmIncludedPlayerToParms.shouldContainExactly(mapOf(playerOne to IncludedPlayerParameters(listOf(), "=", 3), playerTwo to IncludedPlayerParameters())) + rp.hmIncludedPlayerToParms.shouldContainExactly( + mapOf( + playerOne to IncludedPlayerParameters(listOf(), "=", 3), + playerTwo to IncludedPlayerParameters() + ) + ) } @Test - fun `Should populate excluded players correctly`() - { + fun `Should populate excluded players correctly`() { val playerOne = insertPlayer() val playerTwo = insertPlayer() @@ -160,27 +156,30 @@ class TestReportingPlayersTab: AbstractTest() } @Test - fun `Should validate all the included player parameters`() - { + fun `Should validate all the included player parameters`() { val playerOne = insertPlayer(name = "Alice") val playerTwo = insertPlayer(name = "Bob") val tab = ReportingPlayersTab() tab.addPlayers(listOf(playerOne, playerTwo)) - //Make both invalid + // Make both invalid tab.includedPlayerPanel.chckbxPosition.doClick() tab.scrollTable.selectRow(1) tab.includedPlayerPanel.chckbxPosition.doClick() tab.valid() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("You must select at least one finishing position for player Alice") + dialogFactory.errorsShown.shouldContainExactly( + "You must select at least one finishing position for player Alice" + ) dialogFactory.errorsShown.clear() tab.scrollTable.selectRow(0) tab.includedPlayerPanel.chckbxPosition.doClick() tab.valid() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("You must select at least one finishing position for player Bob") + dialogFactory.errorsShown.shouldContainExactly( + "You must select at least one finishing position for player Bob" + ) dialogFactory.errorsShown.clear() tab.scrollTable.selectRow(1) @@ -190,14 +189,13 @@ class TestReportingPlayersTab: AbstractTest() } @Test - fun `Should not do any validation in exclude mode`() - { + fun `Should not do any validation in exclude mode`() { val playerOne = insertPlayer() val tab = ReportingPlayersTab() tab.addPlayers(listOf(playerOne)) - //Make invalid, but then swap to exclude mode + // Make invalid, but then swap to exclude mode tab.includedPlayerPanel.chckbxPosition.doClick() tab.rdbtnExclude.doClick() @@ -206,4 +204,4 @@ class TestReportingPlayersTab: AbstractTest() } private fun PlayerParametersPanel.enabled() = chckbxFinalScore.isEnabled -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/reporting/TestReportingResultsScreen.kt b/src/test/kotlin/dartzee/screen/reporting/TestReportingResultsScreen.kt index b71bf7ffb..5243735ec 100644 --- a/src/test/kotlin/dartzee/screen/reporting/TestReportingResultsScreen.kt +++ b/src/test/kotlin/dartzee/screen/reporting/TestReportingResultsScreen.kt @@ -16,15 +16,13 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.every import io.mockk.mockk -import org.junit.jupiter.api.Test import java.sql.Timestamp import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestReportingResultsScreen: AbstractTest() -{ +class TestReportingResultsScreen : AbstractTest() { @Test - fun `Should initialise with results based on the report parameters`() - { + fun `Should initialise with results based on the report parameters`() { val rp = ReportParameters() rp.gameType = GameType.X01 @@ -44,8 +42,7 @@ class TestReportingResultsScreen: AbstractTest() } @Test - fun `Should adjust columns based on the configure dialog, without rerunning SQL`() - { + fun `Should adjust columns based on the configure dialog, without rerunning SQL`() { val gX01 = insertGame(localId = 1, gameType = GameType.X01, gameParams = "501") insertPlayerForGame("Bob", gX01.rowId) @@ -58,7 +55,8 @@ class TestReportingResultsScreen: AbstractTest() val table = scrn.getChild() table.rowCount shouldBe 1 - table.getColumnNames() shouldBe listOf("Game", "Type", "Players", "Start Date", "Finish Date", "Match") + table.getColumnNames() shouldBe + listOf("Game", "Type", "Players", "Start Date", "Finish Date", "Match") clearLogs() every { dlg.excludedColumns() } returns listOf("Players", "Finish Date") @@ -70,8 +68,7 @@ class TestReportingResultsScreen: AbstractTest() } @Test - fun `Should sort by timestamps correctly`() - { + fun `Should sort by timestamps correctly`() { val g1 = insertGame(dtCreation = Timestamp.valueOf("2020-03-04 15:00:00")) val g2 = insertGame(dtCreation = Timestamp.valueOf("2020-01-01 00:00:00")) val g3 = insertGame(dtCreation = Timestamp.valueOf("2020-03-03 12:00:00")) @@ -96,12 +93,10 @@ class TestReportingResultsScreen: AbstractTest() } @Test - fun `Should go back to setup screen`() - { + fun `Should go back to setup screen`() { val scrn = ReportingResultsScreen() scrn.btnBack.doClick() ScreenCache.currentScreen().shouldBeInstanceOf() } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/reporting/TestReportingSetupScreen.kt b/src/test/kotlin/dartzee/screen/reporting/TestReportingSetupScreen.kt index 6a22fc633..2110cf31d 100644 --- a/src/test/kotlin/dartzee/screen/reporting/TestReportingSetupScreen.kt +++ b/src/test/kotlin/dartzee/screen/reporting/TestReportingSetupScreen.kt @@ -13,14 +13,12 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldNotBeEmpty import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf -import org.junit.jupiter.api.Test import javax.swing.JCheckBox +import org.junit.jupiter.api.Test -class TestReportingSetupScreen: AbstractTest() -{ +class TestReportingSetupScreen : AbstractTest() { @Test - fun `Should not progress if game tab is invalid`() - { + fun `Should not progress if game tab is invalid`() { val scrn = ReportingSetupScreen() ScreenCache.switch(scrn) @@ -35,8 +33,7 @@ class TestReportingSetupScreen: AbstractTest() } @Test - fun `Should not progress if players tab is invalid`() - { + fun `Should not progress if players tab is invalid`() { val scrn = ReportingSetupScreen() ScreenCache.switch(scrn) @@ -48,12 +45,13 @@ class TestReportingSetupScreen: AbstractTest() scrn.btnNext.doClick() ScreenCache.currentScreen() shouldBe scrn - dialogFactory.errorsShown.shouldContainExactly("You must select at least one finishing position for player Alice") + dialogFactory.errorsShown.shouldContainExactly( + "You must select at least one finishing position for player Alice" + ) } @Test - fun `Should populate report parameters from both tabs and progress to results screen`() - { + fun `Should populate report parameters from both tabs and progress to results screen`() { val scrn = ReportingSetupScreen() val gameTab = scrn.getChild() @@ -71,5 +69,6 @@ class TestReportingSetupScreen: AbstractTest() rp.excludeOnlyAi shouldBe true } - private fun ReportingGameTab.getStartDateFilterPanel() = getAllChildComponentsForType().first() -} \ No newline at end of file + private fun ReportingGameTab.getStartDateFilterPanel() = + getAllChildComponentsForType().first() +} diff --git a/src/test/kotlin/dartzee/screen/stats/TestStatsUtils.kt b/src/test/kotlin/dartzee/screen/stats/TestStatsUtils.kt index 07e8b7c49..acabca3ab 100644 --- a/src/test/kotlin/dartzee/screen/stats/TestStatsUtils.kt +++ b/src/test/kotlin/dartzee/screen/stats/TestStatsUtils.kt @@ -4,15 +4,13 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestStatsUtils : AbstractTest() -{ +class TestStatsUtils : AbstractTest() { @Test - fun `Should correctly compute the median`() - { + fun `Should correctly compute the median`() { listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).shuffled().median() shouldBe 5.5 listOf(1, 2, 3, 4, 5, 6, 7, 8, 9).shuffled().median() shouldBe 5.0 listOf(4).median() shouldBe 4.0 listOf(1, 1, 1, 5).median() shouldBe 1.0 emptyList().median() shouldBe 0.0 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardAchievements.kt b/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardAchievements.kt index 08282afef..697ac8990 100644 --- a/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardAchievements.kt +++ b/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardAchievements.kt @@ -12,19 +12,16 @@ import dartzee.helper.insertPlayer import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestLeaderboardAchievements: AbstractTest() -{ +class TestLeaderboardAchievements : AbstractTest() { @Test - fun `Combo box should be disabled by default`() - { + fun `Combo box should be disabled by default`() { val leaderboard = LeaderboardAchievements() leaderboard.cbSpecificAchievement.isSelected shouldBe false leaderboard.comboBox.isEnabled shouldBe false } @Test - fun `Should enable combo box based on checkbox`() - { + fun `Should enable combo box based on checkbox`() { val leaderboard = LeaderboardAchievements() leaderboard.cbSpecificAchievement.isSelected = true @@ -33,33 +30,36 @@ class TestLeaderboardAchievements: AbstractTest() } @Test - fun `Should initialise combobox with all achievements`() - { + fun `Should initialise combobox with all achievements`() { val leaderboard = LeaderboardAchievements() leaderboard.comboBox.itemCount shouldBe getAllAchievements().size } @Test - fun `Should show overall achievement progress by default`() - { + fun `Should show overall achievement progress by default`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") val bestFinish = AchievementX01BestFinish() val bestGolfGame = AchievementGolfBestGame() - insertAchievement(type = AchievementType.X01_BEST_FINISH, - achievementCounter = bestFinish.pinkThreshold, - playerId = alice.rowId) - - insertAchievement(type = AchievementType.GOLF_BEST_GAME, - achievementCounter = bestGolfGame.blueThreshold, - playerId = alice.rowId) + insertAchievement( + type = AchievementType.X01_BEST_FINISH, + achievementCounter = bestFinish.pinkThreshold, + playerId = alice.rowId + ) - insertAchievement(type = AchievementType.X01_BEST_FINISH, - achievementCounter = bestFinish.greenThreshold, - playerId = bob.rowId) + insertAchievement( + type = AchievementType.GOLF_BEST_GAME, + achievementCounter = bestGolfGame.blueThreshold, + playerId = alice.rowId + ) + insertAchievement( + type = AchievementType.X01_BEST_FINISH, + achievementCounter = bestFinish.greenThreshold, + playerId = bob.rowId + ) val leaderboard = LeaderboardAchievements() leaderboard.buildTable() @@ -75,19 +75,22 @@ class TestLeaderboardAchievements: AbstractTest() } @Test - fun `Should respond to changing player filters`() - { + fun `Should respond to changing player filters`() { val alice = insertPlayer(name = "Alice", strategy = "") val bob = insertPlayer(name = "Bob", strategy = "foo") val bestFinish = AchievementX01BestFinish() - insertAchievement(type = AchievementType.X01_BEST_FINISH, - achievementCounter = bestFinish.pinkThreshold, - playerId = alice.rowId) + insertAchievement( + type = AchievementType.X01_BEST_FINISH, + achievementCounter = bestFinish.pinkThreshold, + playerId = alice.rowId + ) - insertAchievement(type = AchievementType.X01_BEST_FINISH, - achievementCounter = bestFinish.greenThreshold, - playerId = bob.rowId) + insertAchievement( + type = AchievementType.X01_BEST_FINISH, + achievementCounter = bestFinish.greenThreshold, + playerId = bob.rowId + ) val leaderboard = LeaderboardAchievements() leaderboard.buildTable() @@ -103,24 +106,29 @@ class TestLeaderboardAchievements: AbstractTest() } @Test - fun `Should include rankings`() - { + fun `Should include rankings`() { val alice = insertPlayer(name = "Alice") val bob = insertPlayer(name = "Bob") val clive = insertPlayer(name = "Clive") val bestFinish = AchievementX01BestFinish() - insertAchievement(type = AchievementType.X01_BEST_FINISH, + insertAchievement( + type = AchievementType.X01_BEST_FINISH, achievementCounter = bestFinish.pinkThreshold, - playerId = alice.rowId) + playerId = alice.rowId + ) - insertAchievement(type = AchievementType.X01_BEST_FINISH, + insertAchievement( + type = AchievementType.X01_BEST_FINISH, achievementCounter = bestFinish.greenThreshold, - playerId = bob.rowId) + playerId = bob.rowId + ) - insertAchievement(type = AchievementType.X01_BEST_FINISH, + insertAchievement( + type = AchievementType.X01_BEST_FINISH, achievementCounter = bestFinish.pinkThreshold, - playerId = clive.rowId) + playerId = clive.rowId + ) val leaderboard = LeaderboardAchievements() leaderboard.buildTable() diff --git a/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardTopX01Finishes.kt b/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardTopX01Finishes.kt index 09441b8d4..7f7a1c179 100644 --- a/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardTopX01Finishes.kt +++ b/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardTopX01Finishes.kt @@ -6,16 +6,14 @@ import dartzee.helper.insertPlayer import dartzee.utils.PREFERENCES_INT_LEADERBOARD_SIZE import dartzee.utils.PreferenceUtil import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestLeaderboardTopX01Finishes: AbstractRegistryTest() -{ +class TestLeaderboardTopX01Finishes : AbstractRegistryTest() { override fun getPreferencesAffected() = listOf(PREFERENCES_INT_LEADERBOARD_SIZE) @Test - fun `Should get the correct local game ids`() - { + fun `Should get the correct local game ids`() { val p = insertPlayer() val g1 = insertFinishForPlayer(p, 150) @@ -29,8 +27,7 @@ class TestLeaderboardTopX01Finishes: AbstractRegistryTest() } @Test - fun `Should respect the preference value for the number of rows to be returned`() - { + fun `Should respect the preference value for the number of rows to be returned`() { PreferenceUtil.saveInt(PREFERENCES_INT_LEADERBOARD_SIZE, 2) val p = insertPlayer() @@ -53,8 +50,7 @@ class TestLeaderboardTopX01Finishes: AbstractRegistryTest() } @Test - fun `Should respond to changing player filters, and pull through player names`() - { + fun `Should respond to changing player filters, and pull through player names`() { val robot = insertPlayer(name = "Robot", strategy = "foo") val human = insertPlayer(name = "Human", strategy = "") @@ -78,8 +74,7 @@ class TestLeaderboardTopX01Finishes: AbstractRegistryTest() } @Test - fun `Should use dtCreation as a tie-breaker when there are multiple rows with the same score`() - { + fun `Should use dtCreation as a tie-breaker when there are multiple rows with the same score`() { val p = insertPlayer() val g1 = insertFinishForPlayer(p, 100, Timestamp(20)) @@ -94,10 +89,12 @@ class TestLeaderboardTopX01Finishes: AbstractRegistryTest() leaderboard.getGameIdAt(2) shouldBe g3.localId } - - private fun LeaderboardTopX01Finishes.rowCount() = tableTopFinishes.rowCount + private fun LeaderboardTopX01Finishes.getNameAt(row: Int) = tableTopFinishes.getValueAt(row, 2) - private fun LeaderboardTopX01Finishes.getGameIdAt(row: Int) = tableTopFinishes.getValueAt(row, 3) + + private fun LeaderboardTopX01Finishes.getGameIdAt(row: Int) = + tableTopFinishes.getValueAt(row, 3) + private fun LeaderboardTopX01Finishes.getScoreAt(row: Int) = tableTopFinishes.getValueAt(row, 4) -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardUtils.kt b/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardUtils.kt index 7786237f1..11983cea1 100644 --- a/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardUtils.kt +++ b/src/test/kotlin/dartzee/screen/stats/overall/TestLeaderboardUtils.kt @@ -5,25 +5,25 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestLeaderboardUtils: AbstractTest() -{ +class TestLeaderboardUtils : AbstractTest() { @Test - fun `Should add rankings correctly`() - { - val entries = listOf(50, 49, 49, 30, 30, 30, 25, 24).map { LeaderboardEntry(it, emptyList()) } + fun `Should add rankings correctly`() { + val entries = + listOf(50, 49, 49, 30, 30, 30, 25, 24).map { LeaderboardEntry(it, emptyList()) } val results = getRankedRowsForTable(entries) - results.map { it[0] } shouldBe listOf (1, 2, 2, 4, 4, 4, 7, 8) + results.map { it[0] } shouldBe listOf(1, 2, 2, 4, 4, 4, 7, 8) } @Test - fun `Should preserve the rest of the row entries`() - { + fun `Should preserve the rest of the row entries`() { val entryOne = LeaderboardEntry(50, listOf("Alice", "#55")) val entryTwo = LeaderboardEntry(34, listOf("Bob", "#27")) val results = getRankedRowsForTable(listOf(entryOne, entryTwo)) - results.map { it.toList() }.shouldContainExactly(listOf(1, "Alice", "#55"), listOf(2, "Bob", "#27")) + results + .map { it.toList() } + .shouldContainExactly(listOf(1, "Alice", "#55"), listOf(2, "Bob", "#27")) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/AbstractPlayerStatisticsTest.kt b/src/test/kotlin/dartzee/screen/stats/player/AbstractPlayerStatisticsTest.kt index 9d206aca0..64a7e01e4 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/AbstractPlayerStatisticsTest.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/AbstractPlayerStatisticsTest.kt @@ -7,61 +7,52 @@ import dartzee.helper.makeGameWrapper import dartzee.stats.GameWrapper import io.kotest.assertions.throwables.shouldNotThrowAny import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import java.awt.Component +import org.junit.jupiter.api.Test -abstract class AbstractPlayerStatisticsTest: AbstractTest() -{ +abstract class AbstractPlayerStatisticsTest : AbstractTest() { abstract fun factoryTab(): E + abstract fun getComponentsForComparison(tab: E): List + open fun factoryGameWrapper(): GameWrapper = makeGameWrapper() @Test - fun `Components for comparison should have red foregrounds`() - { + fun `Components for comparison should have red foregrounds`() { val components = getComponentsForComparison(factoryTab()) - components.forEach{ - when(it) - { + components.forEach { + when (it) { is ScrollTable -> it.tableForeground shouldBe Color.RED } } } @Test - fun `Should show or hide comparison components`() - { + fun `Should show or hide comparison components`() { val tab = factoryTab() val components = getComponentsForComparison(tab) tab.setFilteredGames(listOf(factoryGameWrapper()), listOf()) tab.populateStats() - components.forEach{ - tab.containsComponent(it) shouldBe false - } + components.forEach { tab.containsComponent(it) shouldBe false } tab.setFilteredGames(listOf(factoryGameWrapper()), listOf(factoryGameWrapper())) tab.populateStats() - components.forEach{ - tab.containsComponent(it) shouldBe true - } + components.forEach { tab.containsComponent(it) shouldBe true } tab.setFilteredGames(listOf(factoryGameWrapper()), listOf()) tab.populateStats() - components.forEach{ - tab.containsComponent(it) shouldBe false - } + components.forEach { tab.containsComponent(it) shouldBe false } } @Test - fun `It should handle displaying no games`() - { - shouldNotThrowAny{ + fun `It should handle displaying no games`() { + shouldNotThrowAny { val tab = factoryTab() tab.setFilteredGames(listOf(), listOf()) tab.populateStats() } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/AbstractStatsPieBreakdownTest.kt b/src/test/kotlin/dartzee/screen/stats/player/AbstractStatsPieBreakdownTest.kt index 58abf9bae..118090983 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/AbstractStatsPieBreakdownTest.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/AbstractStatsPieBreakdownTest.kt @@ -3,34 +3,31 @@ package dartzee.screen.stats.player import io.kotest.matchers.collections.shouldContainNoNulls import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Component +import org.junit.jupiter.api.Test -abstract class AbstractStatsPieBreakdownTest: AbstractPlayerStatisticsTest() -{ +abstract class AbstractStatsPieBreakdownTest : + AbstractPlayerStatisticsTest() { abstract fun getAllPossibilitiesForScores(): IntRange override fun getComponentsForComparison(tab: E): List = listOf(tab.otherPieChartPanel, tab.tableHoleBreakdownOther) @Test - fun `Ranges should be distinct and cover all possibilities`() - { + fun `Ranges should be distinct and cover all possibilities`() { val ranges = factoryTab().ranges - for (i in getAllPossibilitiesForScores()) - { - ranges.filter{ it.contains(i) }.shouldHaveSize(1) + for (i in getAllPossibilitiesForScores()) { + ranges.filter { it.contains(i) }.shouldHaveSize(1) } } @Test - fun `Should return a different, valid colour for all ranges`() - { + fun `Should return a different, valid colour for all ranges`() { val tab = factoryTab() - val colours = tab.ranges.map{ tab.getColorForRange(it) }.distinct() + val colours = tab.ranges.map { tab.getColorForRange(it) }.distinct() colours.size shouldBe tab.ranges.size colours.shouldContainNoNulls() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/TestPlayerAchievementsScreen.kt b/src/test/kotlin/dartzee/screen/stats/player/TestPlayerAchievementsScreen.kt index df3a80ad1..4b1382ab3 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/TestPlayerAchievementsScreen.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/TestPlayerAchievementsScreen.kt @@ -21,16 +21,14 @@ import dartzee.screen.ScreenCache import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.ImageIcon import javax.swing.JLabel +import org.junit.jupiter.api.Test -class TestPlayerAchievementsScreen: AbstractTest() -{ +class TestPlayerAchievementsScreen : AbstractTest() { @Test - fun `Should go back to the desired previous screen`() - { + fun `Should go back to the desired previous screen`() { val p = insertPlayer() val startingScreen = ScreenCache.currentScreen() @@ -41,18 +39,17 @@ class TestPlayerAchievementsScreen: AbstractTest() } @Test - fun `Should update title with player name and achievement progress`() - { + fun `Should update title with player name and achievement progress`() { val p = insertPlayer(name = "Bob") setUpAchievements(p) val achievementsScrn = ScreenCache.switchToAchievementsScreen(p) - achievementsScrn.getScreenName() shouldBe "Achievements - Bob - 11/${getAchievementMaximum()}" + achievementsScrn.getScreenName() shouldBe + "Achievements - Bob - 11/${getAchievementMaximum()}" } @Test - fun `Should show achievement details on hover, and clear them when hovered away`() - { + fun `Should show achievement details on hover, and clear them when hovered away`() { val p = insertPlayer() val g = insertGame() @@ -68,7 +65,8 @@ class TestPlayerAchievementsScreen: AbstractTest() achievementsScrn.nameLabel().background shouldBe Color.MAGENTA achievementsScrn.nameLabel().text shouldBe achievement.name achievementsScrn.descriptionLabel().text shouldBe achievement.desc - achievementsScrn.extraDetailsLabel()!!.text shouldBe "Earned on 01/01/1900 in Game #${g.localId}" + achievementsScrn.extraDetailsLabel()!!.text shouldBe + "Earned on 01/01/1900 in Game #${g.localId}" achievementsScrn.individualIndicator().shouldBeVisible() achievementsScrn.teamIndicator().shouldBeVisible() @@ -82,8 +80,7 @@ class TestPlayerAchievementsScreen: AbstractTest() } @Test - fun `Should not show description or extra details if achievement is locked`() - { + fun `Should not show description or extra details if achievement is locked`() { val achievementsScrn = ScreenCache.switchToAchievementsScreen(insertPlayer()) achievementsScrn.toggleAchievementDesc(true, AchievementX01BestFinish()) @@ -93,12 +90,14 @@ class TestPlayerAchievementsScreen: AbstractTest() } @Test - fun `Should show correct icons based on whether achievement is available for individuals or teams`() - { - val individualAllowed = ImageIcon(javaClass.getResource("/achievements/singlePlayerEnabled.png")) - val individualNotAllowed = ImageIcon(javaClass.getResource("/achievements/singlePlayerDisabled.png")) + fun `Should show correct icons based on whether achievement is available for individuals or teams`() { + val individualAllowed = + ImageIcon(javaClass.getResource("/achievements/singlePlayerEnabled.png")) + val individualNotAllowed = + ImageIcon(javaClass.getResource("/achievements/singlePlayerDisabled.png")) val teamAllowed = ImageIcon(javaClass.getResource("/achievements/multiPlayerEnabled.png")) - val teamNotAllowed = ImageIcon(javaClass.getResource("/achievements/multiPlayerDisabled.png")) + val teamNotAllowed = + ImageIcon(javaClass.getResource("/achievements/multiPlayerDisabled.png")) val achievementsScrn = ScreenCache.switchToAchievementsScreen(insertPlayer()) achievementsScrn.toggleAchievementDesc(true, AchievementX01BestFinish()) @@ -115,8 +114,7 @@ class TestPlayerAchievementsScreen: AbstractTest() } @Test - fun `Should show achievement progress for the right player and right achievement`() - { + fun `Should show achievement progress for the right player and right achievement`() { val p1 = insertPlayer() val p2 = insertPlayer() @@ -127,27 +125,54 @@ class TestPlayerAchievementsScreen: AbstractTest() AchievementEntity.updateAchievement(AchievementType.X01_BEST_FINISH, p2.rowId, g.rowId, 75) val p1AchievementScreen = ScreenCache.switchToAchievementsScreen(p1) - p1AchievementScreen.findAchievementMedal(AchievementType.X01_BEST_FINISH)?.achievement?.attainedValue shouldBe 40 - p1AchievementScreen.findAchievementMedal(AchievementType.X01_HIGHEST_BUST)?.achievement?.attainedValue shouldBe 80 + p1AchievementScreen + .findAchievementMedal(AchievementType.X01_BEST_FINISH) + ?.achievement + ?.attainedValue shouldBe 40 + p1AchievementScreen + .findAchievementMedal(AchievementType.X01_HIGHEST_BUST) + ?.achievement + ?.attainedValue shouldBe 80 val p2AchievementScreen = ScreenCache.switchToAchievementsScreen(p2) - p2AchievementScreen.findAchievementMedal(AchievementType.X01_BEST_FINISH)?.achievement?.attainedValue shouldBe 75 - p2AchievementScreen.findAchievementMedal(AchievementType.X01_HIGHEST_BUST)?.achievement?.isLocked() shouldBe true + p2AchievementScreen + .findAchievementMedal(AchievementType.X01_BEST_FINISH) + ?.achievement + ?.attainedValue shouldBe 75 + p2AchievementScreen + .findAchievementMedal(AchievementType.X01_HIGHEST_BUST) + ?.achievement + ?.isLocked() shouldBe true } private fun PlayerAchievementsScreen.nameLabel() = getChild("name") + private fun PlayerAchievementsScreen.descriptionLabel() = getChild("description") + private fun PlayerAchievementsScreen.extraDetailsLabel() = findChild("extraDetails") - private fun PlayerAchievementsScreen.individualIndicator() = getChild("individualIndicator") + + private fun PlayerAchievementsScreen.individualIndicator() = + getChild("individualIndicator") + private fun PlayerAchievementsScreen.teamIndicator() = getChild("teamIndicator") - private fun PlayerAchievementsScreen.findAchievementMedal(type: AchievementType) = findChild { it.achievement.achievementType == type } + private fun PlayerAchievementsScreen.findAchievementMedal(type: AchievementType) = + findChild { it.achievement.achievementType == type } - private fun setUpAchievements(player: PlayerEntity) - { + private fun setUpAchievements(player: PlayerEntity) { val g = insertGame() - AchievementEntity.updateAchievement(AchievementType.X01_BEST_FINISH, player.rowId, g.rowId, AchievementX01BestFinish().blueThreshold) - AchievementEntity.updateAchievement(AchievementType.X01_HIGHEST_BUST, player.rowId, g.rowId, AchievementX01HighestBust().pinkThreshold) + AchievementEntity.updateAchievement( + AchievementType.X01_BEST_FINISH, + player.rowId, + g.rowId, + AchievementX01BestFinish().blueThreshold + ) + AchievementEntity.updateAchievement( + AchievementType.X01_HIGHEST_BUST, + player.rowId, + g.rowId, + AchievementX01HighestBust().pinkThreshold + ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/golf/TestGolfStatsScorecard.kt b/src/test/kotlin/dartzee/screen/stats/player/golf/TestGolfStatsScorecard.kt index f364a139f..096d0cec2 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/golf/TestGolfStatsScorecard.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/golf/TestGolfStatsScorecard.kt @@ -9,23 +9,27 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGolfStatsScorecard : AbstractTest() -{ +class TestGolfStatsScorecard : AbstractTest() { @Test - fun `Should show the right number of columns`() - { + fun `Should show the right number of columns`() { factoryScorecard(showGameIds = false).getNumberOfColumns() shouldBe 5 factoryScorecard(showGameIds = true).getNumberOfColumns() shouldBe 6 } @Test - fun `Should render an extra column with gameIds`() - { + fun `Should render an extra column with gameIds`() { val scorer = factoryScorecard(showGameIds = true) scorer.getNumberOfColumns() shouldBe 6 val roundOne = makeGolfRound(1, listOf(Dart(1, 3, segmentType = SegmentType.TREBLE))) - val roundTwo = makeGolfRound(2, listOf(Dart(2, 0, segmentType = SegmentType.MISS), Dart(2, 1, segmentType = SegmentType.OUTER_SINGLE))) + val roundTwo = + makeGolfRound( + 2, + listOf( + Dart(2, 0, segmentType = SegmentType.MISS), + Dart(2, 1, segmentType = SegmentType.OUTER_SINGLE) + ) + ) val gameIds = listOf(50L, 350L) scorer.populateTable(listOf(roundOne, roundTwo)) @@ -39,8 +43,7 @@ class TestGolfStatsScorecard : AbstractTest() } @Test - fun `Should split gameIds if more than 9 rounds`() - { + fun `Should split gameIds if more than 9 rounds`() { val scorer = factoryScorecard(showGameIds = true) val rounds = (1..10).map { makeGolfRound(it, listOf(Dart(it, 2))) } @@ -54,10 +57,11 @@ class TestGolfStatsScorecard : AbstractTest() } @Test - fun `Should render a back 9`() - { - val roundOne = makeGolfRound(10, listOf(Dart(15, 1), Dart(10, 2, segmentType = SegmentType.DOUBLE))) - val roundTwo = makeGolfRound(11, listOf(Dart(11, 1), Dart(11, 3, segmentType = SegmentType.TREBLE))) + fun `Should render a back 9`() { + val roundOne = + makeGolfRound(10, listOf(Dart(15, 1), Dart(10, 2, segmentType = SegmentType.DOUBLE))) + val roundTwo = + makeGolfRound(11, listOf(Dart(11, 1), Dart(11, 3, segmentType = SegmentType.TREBLE))) val scorer = factoryScorecard(9) scorer.populateTable(listOf(roundOne, roundTwo)) @@ -68,5 +72,6 @@ class TestGolfStatsScorecard : AbstractTest() ) } - private fun factoryScorecard(fudgeFactor: Int = 0, showGameIds: Boolean = false) = GolfStatsScorecard(fudgeFactor, showGameIds) -} \ No newline at end of file + private fun factoryScorecard(fudgeFactor: Int = 0, showGameIds: Boolean = false) = + GolfStatsScorecard(fudgeFactor, showGameIds) +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfHoleBreakdown.kt b/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfHoleBreakdown.kt index d69198d6f..99a9781fa 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfHoleBreakdown.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfHoleBreakdown.kt @@ -2,8 +2,9 @@ package dartzee.screen.stats.player.golf import dartzee.screen.stats.player.AbstractStatsPieBreakdownTest -class TestStatisticsTabGolfHoleBreakdown: AbstractStatsPieBreakdownTest() -{ +class TestStatisticsTabGolfHoleBreakdown : + AbstractStatsPieBreakdownTest() { override fun factoryTab() = StatisticsTabGolfHoleBreakdown() + override fun getAllPossibilitiesForScores() = 1..5 -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfOptimalScorecard.kt b/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfOptimalScorecard.kt index 5abba742f..baf3ee8f1 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfOptimalScorecard.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfOptimalScorecard.kt @@ -17,22 +17,19 @@ import dartzee.stats.GolfMode import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestStatisticsTabGolfOptimalScorecard : AbstractTest() -{ +class TestStatisticsTabGolfOptimalScorecard : AbstractTest() { @Test - fun `Should cope with 0 games`() - { + fun `Should cope with 0 games`() { val tab = StatisticsTabGolfOptimalScorecard() tab.populateStats() tab.scorecardShouldMatch(golfAllMisses(), emptyList()) } @Test - fun `Should show appropriate screen state for individual stats`() - { + fun `Should show appropriate screen state for individual stats`() { val game = golfFull28_29() val tab = StatisticsTabGolfOptimalScorecard() tab.setFilteredGames(listOf(game), emptyList()) @@ -43,8 +40,7 @@ class TestStatisticsTabGolfOptimalScorecard : AbstractTest() } @Test - fun `Should show appropriate screen state when a comparison is included`() - { + fun `Should show appropriate screen state when a comparison is included`() { val myGame = golfFull28_29(1L) val otherGame = golfFull31_22(2L) val mine = listOf(myGame) @@ -61,8 +57,7 @@ class TestStatisticsTabGolfOptimalScorecard : AbstractTest() } @Test - fun `Should optimise across games`() - { + fun `Should optimise across games`() { val gameOne = golfFrontNine22(1L, Timestamp(500)) val gameTwo = golfFrontNine29(2L, Timestamp(1000)) val gameThree = golfFull31_22(3L, Timestamp(1500)) @@ -77,8 +72,7 @@ class TestStatisticsTabGolfOptimalScorecard : AbstractTest() } @Test - fun `Should cope with team games that have partial rounds`() - { + fun `Should cope with team games that have partial rounds`() { val game = golfFrontNine22EvenRounds() val tab = StatisticsTabGolfOptimalScorecard() @@ -93,13 +87,24 @@ class TestStatisticsTabGolfOptimalScorecard : AbstractTest() scorecardRows[3][5] shouldBe 1 // game } - private fun StatisticsTabGolfOptimalScorecard.scorecardMine() = getChild { it.testId == "scorecardMine" } - private fun StatisticsTabGolfOptimalScorecard.scorecardOther() = findChild { it.testId == "scorecardOther" } - private fun StatisticsTabGolfOptimalScorecard.scorecardShouldMatch(game: GameWrapper, gameIds: List, testId: String = "scorecardMine") { - val expected = GolfStatsScorecard(0, true).also { it.populateTable(game.getGolfRounds(GolfMode.FULL_18)) } + private fun StatisticsTabGolfOptimalScorecard.scorecardMine() = + getChild { it.testId == "scorecardMine" } + + private fun StatisticsTabGolfOptimalScorecard.scorecardOther() = + findChild { it.testId == "scorecardOther" } + + private fun StatisticsTabGolfOptimalScorecard.scorecardShouldMatch( + game: GameWrapper, + gameIds: List, + testId: String = "scorecardMine" + ) { + val expected = + GolfStatsScorecard(0, true).also { + it.populateTable(game.getGolfRounds(GolfMode.FULL_18)) + } expected.addGameIds(gameIds) val scorecard = getChild { it.testId == testId } scorecard.tableScores.getRenderedRows() shouldBe expected.tableScores.getRenderedRows() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfScorecards.kt b/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfScorecards.kt index 60a7707f6..4cb659b80 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfScorecards.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/golf/TestStatisticsTabGolfScorecards.kt @@ -18,14 +18,12 @@ import dartzee.stats.GolfMode import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JComboBox +import org.junit.jupiter.api.Test -class TestStatisticsTabGolfScorecards : AbstractTest() -{ +class TestStatisticsTabGolfScorecards : AbstractTest() { @Test - fun `Should cope with 0 games`() - { + fun `Should cope with 0 games`() { val tab = StatisticsTabGolfScorecards() tab.populateStats() @@ -34,8 +32,7 @@ class TestStatisticsTabGolfScorecards : AbstractTest() } @Test - fun `Should ignore team games`() - { + fun `Should ignore team games`() { val tab = StatisticsTabGolfScorecards() tab.setFilteredGames(listOf(golfFrontNine22EvenRounds()), emptyList()) tab.populateStats() @@ -45,8 +42,7 @@ class TestStatisticsTabGolfScorecards : AbstractTest() } @Test - fun `Should populate combo box based on game types that are available`() - { + fun `Should populate combo box based on game types that are available`() { val tab = StatisticsTabGolfScorecards() tab.setFilteredGames(listOf(golfFrontNine22()), emptyList()) tab.populateStats() @@ -57,16 +53,17 @@ class TestStatisticsTabGolfScorecards : AbstractTest() tab.setFilteredGames(listOf(golfFull31_22()), emptyList()) tab.populateStats() - comboBox.items().shouldContainExactly( - ComboBoxItem(GolfMode.FRONT_9, "Front 9"), - ComboBoxItem(GolfMode.BACK_9, "Back 9"), - ComboBoxItem(GolfMode.FULL_18, "Full 18") - ) + comboBox + .items() + .shouldContainExactly( + ComboBoxItem(GolfMode.FRONT_9, "Front 9"), + ComboBoxItem(GolfMode.BACK_9, "Back 9"), + ComboBoxItem(GolfMode.FULL_18, "Full 18") + ) } @Test - fun `Should show appropriate screen state for individual stats`() - { + fun `Should show appropriate screen state for individual stats`() { val game = golfFrontNine22() val tab = StatisticsTabGolfScorecards() tab.setFilteredGames(listOf(game), emptyList()) @@ -77,8 +74,7 @@ class TestStatisticsTabGolfScorecards : AbstractTest() } @Test - fun `Should show appropriate screen state when a comparison is included`() - { + fun `Should show appropriate screen state when a comparison is included`() { val myGame = golfFrontNine29() val otherGame = golfFrontNine22() val mine = listOf(myGame) @@ -96,8 +92,7 @@ class TestStatisticsTabGolfScorecards : AbstractTest() } @Test - fun `Mode combo box should work as expected`() - { + fun `Mode combo box should work as expected`() { val gameOne = golfFrontNine22(1L) val gameThree = golfFull31_22(3L) val games = listOf(gameOne, golfFrontNine29(2L), gameThree, golfFull28_29(4L)) @@ -107,32 +102,31 @@ class TestStatisticsTabGolfScorecards : AbstractTest() tab.populateStats() tab.comboBoxMode().selectedIndex = 0 - tab.scorecardsMine().getRows().shouldContainExactly( - listOf(1L, 22), - listOf(2L, 29), - listOf(3L, 31), - listOf(4L, 28) - ) + tab.scorecardsMine() + .getRows() + .shouldContainExactly( + listOf(1L, 22), + listOf(2L, 29), + listOf(3L, 31), + listOf(4L, 28) + ) tab.scorecardShouldMatch(0, GolfMode.FRONT_9, gameOne) tab.comboBoxMode().selectedIndex = 1 // Back 9 - tab.scorecardsMine().getRows().shouldContainExactly( - listOf(3L, 22), - listOf(4L, 29) - ) + tab.scorecardsMine() + .getRows() + .shouldContainExactly(listOf(3L, 22), listOf(4L, 29)) tab.scorecardShouldMatch(9, GolfMode.BACK_9, gameThree) tab.comboBoxMode().selectedIndex = 2 // Full 18 - tab.scorecardsMine().getRows().shouldContainExactly( - listOf(3L, 53), - listOf(4L, 57) - ) + tab.scorecardsMine() + .getRows() + .shouldContainExactly(listOf(3L, 53), listOf(4L, 57)) tab.scorecardShouldMatch(0, GolfMode.FULL_18, gameThree) } @Test - fun `Selecting a row should populate the scorecard`() - { + fun `Selecting a row should populate the scorecard`() { val gameOne = golfFull31_22(1L) val gameTwo = golfFull28_29(2L) val games = listOf(gameOne, gameTwo) @@ -141,23 +135,38 @@ class TestStatisticsTabGolfScorecards : AbstractTest() tab.populateStats() tab.comboBoxMode().selectedIndex = 2 // Full 18 - tab.scorecardsMine().getRows().shouldContainExactly( - listOf(1L, 53), - listOf(2L, 57) - ) + tab.scorecardsMine() + .getRows() + .shouldContainExactly(listOf(1L, 53), listOf(2L, 57)) tab.scorecardShouldMatch(0, GolfMode.FULL_18, gameOne) tab.scorecardsMine().selectRow(1) tab.scorecardShouldMatch(0, GolfMode.FULL_18, gameTwo) } - private fun StatisticsTabGolfScorecards.comboBoxMode() = getChild>>() - private fun StatisticsTabGolfScorecards.scorecardsMine() = getChild { it.testId == "ScorecardsMine" } - private fun StatisticsTabGolfScorecards.scorecardsOther() = findChild { it.testId == "ScorecardsOther" } - private fun StatisticsTabGolfScorecards.displayedScorecard(testId: String) = getChild { it.testId == testId } - private fun StatisticsTabGolfScorecards.scorecardShouldMatch(fudgeFactor: Int, golfMode: GolfMode, game: GameWrapper, testId: String = "scorecardMine") { + private fun StatisticsTabGolfScorecards.comboBoxMode() = + getChild>>() + + private fun StatisticsTabGolfScorecards.scorecardsMine() = + getChild { it.testId == "ScorecardsMine" } + + private fun StatisticsTabGolfScorecards.scorecardsOther() = + findChild { it.testId == "ScorecardsOther" } + + private fun StatisticsTabGolfScorecards.displayedScorecard(testId: String) = + getChild { it.testId == testId } + + private fun StatisticsTabGolfScorecards.scorecardShouldMatch( + fudgeFactor: Int, + golfMode: GolfMode, + game: GameWrapper, + testId: String = "scorecardMine" + ) { val displayed = displayedScorecard(testId) - val expected = GolfStatsScorecard(fudgeFactor, false).also { it.populateTable(game.getGolfRounds(golfMode)) } + val expected = + GolfStatsScorecard(fudgeFactor, false).also { + it.populateTable(game.getGolfRounds(golfMode)) + } displayed.tableScores.getRows() shouldBe expected.tableScores.getRows() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/rtc/TestStatisticsTabRoundTheClockHitRate.kt b/src/test/kotlin/dartzee/screen/stats/player/rtc/TestStatisticsTabRoundTheClockHitRate.kt index 27f51b03a..ba67664c0 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/rtc/TestStatisticsTabRoundTheClockHitRate.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/rtc/TestStatisticsTabRoundTheClockHitRate.kt @@ -12,17 +12,21 @@ import dartzee.screen.stats.player.AbstractStatsPieBreakdownTest import io.kotest.matchers.collections.shouldContainExactly import org.junit.jupiter.api.Test -class TestStatisticsTabRoundTheClockHitRate: AbstractStatsPieBreakdownTest() -{ +class TestStatisticsTabRoundTheClockHitRate : + AbstractStatsPieBreakdownTest() { override fun factoryTab() = StatisticsTabRoundTheClockHitRate() + override fun getAllPossibilitiesForScores() = 1..1000 + override fun factoryGameWrapper() = makeClockGameWrapper() @Test - fun `Should exclude games that were not in order`() - { + fun `Should exclude games that were not in order`() { val tab = factoryTab() - tab.setFilteredGames(listOf(GAME_WRAPPER_RTC_IN_ORDER, GAME_WRAPPER_RTC_OUT_OF_ORDER), emptyList()) + tab.setFilteredGames( + listOf(GAME_WRAPPER_RTC_IN_ORDER, GAME_WRAPPER_RTC_OUT_OF_ORDER), + emptyList() + ) tab.populateStats() val breakdownTable = tab.getChild { it.testId == "BreakdownMine" } @@ -31,10 +35,12 @@ class TestStatisticsTabRoundTheClockHitRate: AbstractStatsPieBreakdownTest { it.testId == "BreakdownMine" } @@ -45,4 +51,4 @@ class TestStatisticsTabRoundTheClockHitRate: AbstractStatsPieBreakdownTest() - scrollTable.getRows().shouldContainExactly( - listOf(1, 47.5, 501, g1.localId), - listOf(2, 67.0, 501, g2.localId) - ) + scrollTable + .getRows() + .shouldContainExactly( + listOf(1, 47.5, 501, g1.localId), + listOf(2, 67.0, 501, g2.localId) + ) val plot = tab.chart() val dataset = plot.getDataset(0) @@ -116,16 +124,25 @@ class TestStatisticsTabX01ThreeDartAverage: AbstractTest() } @Test - fun `Should respect changes to the scoring threshold`() - { - val rounds = makeX01RoundsMap(301, - listOf(drtOuterFourteen(), drtInnerEleven(), drtTrebleFourteen()), // 67 | 234 remaining - listOf(drtInnerNineteen(), drtOuterNineteen(), drtOuterFifteen()), // 53 | 181 remaining - listOf(drtOuterTwenty(), drtOuterTwenty(), drtOuterOne()), // 41 | 140 remaining - listOf(drtOuterTwenty(), drtTrebleOne(), drtInnerFive()), // 28 | 112 remaining - listOf(drtTrebleTwenty(), drtOuterTwenty(), drtMissSixteen()), // 80 | 32 remaining - listOf(drtDoubleSixteen()) // Fin. - ) + fun `Should respect changes to the scoring threshold`() { + val rounds = + makeX01RoundsMap( + 301, + listOf( + drtOuterFourteen(), + drtInnerEleven(), + drtTrebleFourteen() + ), // 67 | 234 remaining + listOf( + drtInnerNineteen(), + drtOuterNineteen(), + drtOuterFifteen() + ), // 53 | 181 remaining + listOf(drtOuterTwenty(), drtOuterTwenty(), drtOuterOne()), // 41 | 140 remaining + listOf(drtOuterTwenty(), drtTrebleOne(), drtInnerFive()), // 28 | 112 remaining + listOf(drtTrebleTwenty(), drtOuterTwenty(), drtMissSixteen()), // 80 | 32 remaining + listOf(drtDoubleSixteen()) // Fin. + ) val g = makeGameWrapper(gameParams = "301", dartRounds = rounds) val tab = StatisticsTabX01ThreeDartAverage() @@ -141,13 +158,23 @@ class TestStatisticsTabX01ThreeDartAverage: AbstractTest() tab.overallAverage().text shouldBe "47.3" } - private fun StatisticsTabX01ThreeDartAverage.overallAverage() = getChild { it.testId == "overallAverage" } - private fun StatisticsTabX01ThreeDartAverage.overallAverageOther() = getChild { it.testId == "overallAverageOther" } - private fun StatisticsTabX01ThreeDartAverage.missPercent() = getChild { it.testId == "missPercent" } - private fun StatisticsTabX01ThreeDartAverage.missPercentOther() = getChild { it.testId == "missPercentOther" } - private fun StatisticsTabX01ThreeDartAverage.chart() = getChild().chart.plot as XYPlot + private fun StatisticsTabX01ThreeDartAverage.overallAverage() = + getChild { it.testId == "overallAverage" } + + private fun StatisticsTabX01ThreeDartAverage.overallAverageOther() = + getChild { it.testId == "overallAverageOther" } + + private fun StatisticsTabX01ThreeDartAverage.missPercent() = + getChild { it.testId == "missPercent" } + + private fun StatisticsTabX01ThreeDartAverage.missPercentOther() = + getChild { it.testId == "missPercentOther" } + + private fun StatisticsTabX01ThreeDartAverage.chart() = + getChild().chart.plot as XYPlot + private fun StatisticsTabX01ThreeDartAverage.changeSetupThreshold(threshold: Int) { val field = getChild { it.testId == "setupThreshold" } field.value = threshold } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/stats/player/x01/TestStatisticsTabX01ThreeDartScores.kt b/src/test/kotlin/dartzee/screen/stats/player/x01/TestStatisticsTabX01ThreeDartScores.kt index 5770b87f0..b70bf7d35 100644 --- a/src/test/kotlin/dartzee/screen/stats/player/x01/TestStatisticsTabX01ThreeDartScores.kt +++ b/src/test/kotlin/dartzee/screen/stats/player/x01/TestStatisticsTabX01ThreeDartScores.kt @@ -15,11 +15,9 @@ import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestStatisticsTabX01ThreeDartScores: AbstractTest() -{ +class TestStatisticsTabX01ThreeDartScores : AbstractTest() { @Test - fun `Should show correct screen state for individual stats`() - { + fun `Should show correct screen state for individual stats`() { val tab = StatisticsTabX01ThreeDartScores() tab.setFilteredGames(listOf(GAME_WRAPPER_301_1), emptyList()) tab.populateStats() @@ -29,8 +27,7 @@ class TestStatisticsTabX01ThreeDartScores: AbstractTest() } @Test - fun `Should show correct screen state when a comparison is included`() - { + fun `Should show correct screen state when a comparison is included`() { val tab = StatisticsTabX01ThreeDartScores() tab.setFilteredGames(listOf(GAME_WRAPPER_301_1), listOf(GAME_WRAPPER_301_2)) tab.populateStats() @@ -40,8 +37,7 @@ class TestStatisticsTabX01ThreeDartScores: AbstractTest() } @Test - fun `Should respond correctly when threshold is updated`() - { + fun `Should respond correctly when threshold is updated`() { val tab = StatisticsTabX01ThreeDartScores() tab.setFilteredGames(listOf(GAME_WRAPPER_301_1, GAME_WRAPPER_301_2), emptyList()) tab.populateStats() @@ -55,8 +51,7 @@ class TestStatisticsTabX01ThreeDartScores: AbstractTest() } @Test - fun `Breakdown table should update correctly when rows are selected from the summary`() - { + fun `Breakdown table should update correctly when rows are selected from the summary`() { val tab = StatisticsTabX01ThreeDartScores() tab.getChild().value = 62 tab.setFilteredGames(listOf(GAME_WRAPPER_301_1, GAME_WRAPPER_301_2), emptyList()) @@ -69,13 +64,17 @@ class TestStatisticsTabX01ThreeDartScores: AbstractTest() breakdownTable.getRows() shouldBe listOf(listOf("20, 20, 5", 2, 1L)) scoresTable.selectRow(4) - breakdownTable.getRows().shouldContainExactly( - listOf("20, 20, 20", 1, 1L), - listOf("T12, 20, 4", 1, 2L) - ) + breakdownTable + .getRows() + .shouldContainExactly(listOf("20, 20, 20", 1, 1L), listOf("T12, 20, 4", 1, 2L)) } - private fun StatisticsTabX01ThreeDartScores.myScores() = findChild { it.testId == "PlayerScores" } - private fun StatisticsTabX01ThreeDartScores.myBreakdown() = findChild { it.testId == "PlayerBreakdown" } - private fun StatisticsTabX01ThreeDartScores.otherScores() = findChild { it.testId == "OtherScores" } -} \ No newline at end of file + private fun StatisticsTabX01ThreeDartScores.myScores() = + findChild { it.testId == "PlayerScores" } + + private fun StatisticsTabX01ThreeDartScores.myBreakdown() = + findChild { it.testId == "PlayerBreakdown" } + + private fun StatisticsTabX01ThreeDartScores.otherScores() = + findChild { it.testId == "OtherScores" } +} diff --git a/src/test/kotlin/dartzee/screen/sync/TestSyncManagementPanel.kt b/src/test/kotlin/dartzee/screen/sync/TestSyncManagementPanel.kt index ddc8effd6..c754c6fcf 100644 --- a/src/test/kotlin/dartzee/screen/sync/TestSyncManagementPanel.kt +++ b/src/test/kotlin/dartzee/screen/sync/TestSyncManagementPanel.kt @@ -27,46 +27,44 @@ import io.kotest.matchers.string.shouldContain import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.sql.Timestamp import java.time.Duration import javax.swing.JButton import javax.swing.JLabel import javax.swing.JOptionPane +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestSyncManagementPanel : AbstractTest() -{ +class TestSyncManagementPanel : AbstractTest() { private val syncManager = mockk(relaxed = true) @BeforeEach - fun before() - { + fun before() { InjectedThings.syncManager = syncManager - + SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME) } - /** - * Status Panel - */ + /** Status Panel */ @Test - fun `Should render the correct remote name, last synced date and pending game count`() - { + fun `Should render the correct remote name, last synced date and pending game count`() { setUpModifiedGames(2) val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(PAST_TIME)) val panel = SyncManagementPanel() panel.updateStatus(data) - panel.sharedDatabaseLabel().text shouldBe "Shared Database: $REMOTE_NAME_2" - panel.lastSyncedLabel().text.shouldContain("Last Synced: ${Timestamp.from(PAST_TIME).formatTimestamp()}") + panel.sharedDatabaseLabel().text shouldBe + "Shared Database: $REMOTE_NAME_2" + panel + .lastSyncedLabel() + .text + .shouldContain("Last Synced: ${Timestamp.from(PAST_TIME).formatTimestamp()}") panel.pendingGamesLabel().text.shouldContain("Pending Games: 2") } @Test - fun `Should render pending games in green if none pending`() - { + fun `Should render pending games in green if none pending`() { val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(PAST_TIME)) val panel = SyncManagementPanel() panel.updateStatus(data) @@ -75,8 +73,7 @@ class TestSyncManagementPanel : AbstractTest() } @Test - fun `Should render pending games in orange if 1 pending`() - { + fun `Should render pending games in orange if 1 pending`() { setUpModifiedGames(1) val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(PAST_TIME)) @@ -87,8 +84,7 @@ class TestSyncManagementPanel : AbstractTest() } @Test - fun `Should render pending games in orange if 9 pending`() - { + fun `Should render pending games in orange if 9 pending`() { setUpModifiedGames(9) val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(PAST_TIME)) @@ -99,8 +95,7 @@ class TestSyncManagementPanel : AbstractTest() } @Test - fun `Should render pending games in orange if 10 or more pending`() - { + fun `Should render pending games in orange if 10 or more pending`() { setUpModifiedGames(10) val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(PAST_TIME)) @@ -111,8 +106,7 @@ class TestSyncManagementPanel : AbstractTest() } @Test - fun `Should render last synced in green if within last 24 hours`() - { + fun `Should render last synced in green if within last 24 hours`() { val syncTime = CURRENT_TIME.minus(Duration.ofHours(24)) val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(syncTime)) @@ -122,8 +116,7 @@ class TestSyncManagementPanel : AbstractTest() } @Test - fun `Should render last synced in orange if within last week`() - { + fun `Should render last synced in orange if within last week`() { val syncTime = CURRENT_TIME.minus(Duration.ofDays(4)) val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(syncTime)) @@ -133,8 +126,7 @@ class TestSyncManagementPanel : AbstractTest() } @Test - fun `Should render last synced in red if over a week ago`() - { + fun `Should render last synced in red if over a week ago`() { val syncTime = CURRENT_TIME.minus(Duration.ofDays(8)) val data = LastSyncData(REMOTE_NAME_2, Timestamp.from(syncTime)) @@ -143,64 +135,66 @@ class TestSyncManagementPanel : AbstractTest() panel.lastSyncedLabel().text.shouldContain("color=\"red\"") } - private fun setUpModifiedGames(count: Int) - { + private fun setUpModifiedGames(count: Int) { resetRemote() makeSyncAudit(mainDatabase).saveToDatabase(Timestamp.from(PAST_TIME)) - repeat(count) { - insertGame(dtLastUpdate = Timestamp.from(CURRENT_TIME)) - } + repeat(count) { insertGame(dtLastUpdate = Timestamp.from(CURRENT_TIME)) } } - private fun SyncManagementPanel.sharedDatabaseLabel() = getChild { it.text.contains("Shared Database") } - private fun SyncManagementPanel.lastSyncedLabel() = getChild { it.text.contains("Last Synced") } - private fun SyncManagementPanel.pendingGamesLabel() = getChild { it.text.contains("Pending Games") } + private fun SyncManagementPanel.sharedDatabaseLabel() = + getChild { it.text.contains("Shared Database") } + + private fun SyncManagementPanel.lastSyncedLabel() = + getChild { it.text.contains("Last Synced") } - /** - * Push - */ + private fun SyncManagementPanel.pendingGamesLabel() = + getChild { it.text.contains("Pending Games") } + + /** Push */ @Test - fun `Should validate no open games before pushing`() - { + fun `Should validate no open games before pushing`() { ScreenCache.addDartsGameScreen("foo", mockk(relaxed = true)) val panel = makeSyncManagementPanel() panel.clickChild(text = "Push") - dialogFactory.errorsShown.shouldContainExactly("You must close all open games before performing this action.") + dialogFactory.errorsShown.shouldContainExactly( + "You must close all open games before performing this action." + ) verifyNotCalled { syncManager.doPush(any()) } } @Test - fun `Should not push if confirmation is cancelled`() - { + fun `Should not push if confirmation is cancelled`() { dialogFactory.questionOption = JOptionPane.NO_OPTION every { syncManager.databaseExists(REMOTE_NAME) } returns true val panel = makeSyncManagementPanel() panel.clickChild(text = "Push") - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to push to $REMOTE_NAME? \n\nThis will overwrite any data that hasn't been synced to this device.") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to push to $REMOTE_NAME? \n\nThis will overwrite any data that hasn't been synced to this device." + ) verifyNotCalled { syncManager.doPush(any()) } } @Test - fun `Should overwrite remote if push is confirmed`() - { + fun `Should overwrite remote if push is confirmed`() { dialogFactory.questionOption = JOptionPane.YES_OPTION every { syncManager.databaseExists(REMOTE_NAME) } returns true val panel = makeSyncManagementPanel() panel.clickChild(text = "Push") - dialogFactory.questionsShown.shouldContainExactly("Are you sure you want to push to $REMOTE_NAME? \n\nThis will overwrite any data that hasn't been synced to this device.") + dialogFactory.questionsShown.shouldContainExactly( + "Are you sure you want to push to $REMOTE_NAME? \n\nThis will overwrite any data that hasn't been synced to this device." + ) verify { syncManager.doPush(REMOTE_NAME) } } @Test - fun `Should push without confirmation if no remote version exists`() - { + fun `Should push without confirmation if no remote version exists`() { every { syncManager.databaseExists(REMOTE_NAME) } returns false val panel = makeSyncManagementPanel() panel.clickChild(text = "Push") @@ -209,65 +203,62 @@ class TestSyncManagementPanel : AbstractTest() verify { syncManager.doPush(REMOTE_NAME) } } - /** - * Pull - */ + /** Pull */ @Test - fun `Should validate no open games before pulling`() - { + fun `Should validate no open games before pulling`() { ScreenCache.addDartsGameScreen("foo", mockk(relaxed = true)) val panel = makeSyncManagementPanel() panel.clickChild(text = "Pull") - dialogFactory.errorsShown.shouldContainExactly("You must close all open games before performing this action.") + dialogFactory.errorsShown.shouldContainExactly( + "You must close all open games before performing this action." + ) verifyNotCalled { syncManager.doPull(any()) } } @Test - fun `Should not pull if confirmation is cancelled`() - { + fun `Should not pull if confirmation is cancelled`() { dialogFactory.questionOption = JOptionPane.NO_OPTION val panel = makeSyncManagementPanel() panel.clickChild(text = "Pull") dialogFactory.questionsShown.shouldContainExactly( - "Are you sure you want to pull from $REMOTE_NAME? \n\nThis will overwrite any local data that hasn't been synced to $REMOTE_NAME from this device.") + "Are you sure you want to pull from $REMOTE_NAME? \n\nThis will overwrite any local data that hasn't been synced to $REMOTE_NAME from this device." + ) verifyNotCalled { syncManager.doPull(any()) } } @Test - fun `Should overwrite local if pull is confirmed`() - { + fun `Should overwrite local if pull is confirmed`() { dialogFactory.questionOption = JOptionPane.YES_OPTION val panel = makeSyncManagementPanel() panel.clickChild(text = "Pull") dialogFactory.questionsShown.shouldContainExactly( - "Are you sure you want to pull from $REMOTE_NAME? \n\nThis will overwrite any local data that hasn't been synced to $REMOTE_NAME from this device.") + "Are you sure you want to pull from $REMOTE_NAME? \n\nThis will overwrite any local data that hasn't been synced to $REMOTE_NAME from this device." + ) verify { syncManager.doPull(REMOTE_NAME) } } - /** - * Sync - */ + /** Sync */ @Test - fun `Should validate no open games before syncing`() - { + fun `Should validate no open games before syncing`() { ScreenCache.addDartsGameScreen("foo", mockk(relaxed = true)) val panel = makeSyncManagementPanel() panel.clickChild(text = "Perform Sync") - dialogFactory.errorsShown.shouldContainExactly("You must close all open games before performing this action.") + dialogFactory.errorsShown.shouldContainExactly( + "You must close all open games before performing this action." + ) verifyNotCalled { syncManager.doSyncIfNecessary(any()) } } @Test - fun `Should carry out a sync`() - { + fun `Should carry out a sync`() { val panel = makeSyncManagementPanel() panel.clickChild(text = "Perform Sync") @@ -275,43 +266,38 @@ class TestSyncManagementPanel : AbstractTest() verify { syncManager.doSyncIfNecessary(REMOTE_NAME) } } - /** - * Reset - */ + /** Reset */ @Test - fun `Should not carry out a reset if cancelled`() - { + fun `Should not carry out a reset if cancelled`() { dialogFactory.questionOption = JOptionPane.NO_OPTION val panel = makeSyncManagementPanel() panel.clickChild(text = "Reset") dialogFactory.questionsShown.shouldContainExactly( - "Are you sure you want to reset?\n\nThis will not delete any local data, but will sever the link with $REMOTE_NAME, requiring you to set it up again." + "Are you sure you want to reset?\n\nThis will not delete any local data, but will sever the link with $REMOTE_NAME, requiring you to set it up again." ) SyncAuditEntity.getLastSyncData(mainDatabase).shouldNotBeNull() } @Test - fun `Should reset if confirmed`() - { + fun `Should reset if confirmed`() { dialogFactory.questionOption = JOptionPane.YES_OPTION val panel = makeSyncManagementPanel() panel.clickChild(text = "Reset") dialogFactory.questionsShown.shouldContainExactly( - "Are you sure you want to reset?\n\nThis will not delete any local data, but will sever the link with $REMOTE_NAME, requiring you to set it up again." + "Are you sure you want to reset?\n\nThis will not delete any local data, but will sever the link with $REMOTE_NAME, requiring you to set it up again." ) SyncAuditEntity.getLastSyncData(mainDatabase).shouldBeNull() } - private fun makeSyncManagementPanel(): SyncManagementPanel - { + private fun makeSyncManagementPanel(): SyncManagementPanel { val panel = SyncManagementPanel() panel.updateStatus(SyncAuditEntity.getLastSyncData(mainDatabase)!!) return panel } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/sync/TestSyncManagementScreen.kt b/src/test/kotlin/dartzee/screen/sync/TestSyncManagementScreen.kt index b12553270..a0fd8ba1b 100644 --- a/src/test/kotlin/dartzee/screen/sync/TestSyncManagementScreen.kt +++ b/src/test/kotlin/dartzee/screen/sync/TestSyncManagementScreen.kt @@ -9,14 +9,12 @@ import dartzee.sync.resetRemote import dartzee.utils.InjectedThings.mainDatabase import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull -import org.junit.jupiter.api.Test import javax.swing.JLabel +import org.junit.jupiter.api.Test -class TestSyncManagementScreen: AbstractTest() -{ +class TestSyncManagementScreen : AbstractTest() { @Test - fun `Should show the setup screen if never synced before`() - { + fun `Should show the setup screen if never synced before`() { val scrn = SyncManagementScreen() scrn.initialise() @@ -25,8 +23,7 @@ class TestSyncManagementScreen: AbstractTest() } @Test - fun `Should show the config screen if a sync has occurred`() - { + fun `Should show the config screen if a sync has occurred`() { SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME) val scrn = SyncManagementScreen() @@ -37,8 +34,7 @@ class TestSyncManagementScreen: AbstractTest() } @Test - fun `Should show the right child after multiple initialisations`() - { + fun `Should show the right child after multiple initialisations`() { val scrn = SyncManagementScreen() scrn.initialise() scrn.findChild().shouldBeNull() @@ -56,8 +52,7 @@ class TestSyncManagementScreen: AbstractTest() } @Test - fun `Should update sync management panel when initialised`() - { + fun `Should update sync management panel when initialised`() { SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME) val scrn = SyncManagementScreen() scrn.initialise() @@ -68,4 +63,4 @@ class TestSyncManagementScreen: AbstractTest() scrn.initialise() scrn.findChild { it.text.contains(REMOTE_NAME_2) }.shouldNotBeNull() } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/sync/TestSyncProgressDialog.kt b/src/test/kotlin/dartzee/screen/sync/TestSyncProgressDialog.kt index cd79519fb..a92321b06 100644 --- a/src/test/kotlin/dartzee/screen/sync/TestSyncProgressDialog.kt +++ b/src/test/kotlin/dartzee/screen/sync/TestSyncProgressDialog.kt @@ -7,14 +7,12 @@ import com.github.alyssaburlton.swingtest.shouldNotBeVisible import dartzee.helper.AbstractTest import dartzee.sync.SyncStage import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import javax.swing.JProgressBar +import org.junit.jupiter.api.Test -class TestSyncProgressDialog: AbstractTest() -{ +class TestSyncProgressDialog : AbstractTest() { @Test - fun `Should show and hide`() - { + fun `Should show and hide`() { val dlg = SyncProgressDialog() dlg.setVisibleLater() flushEdt() @@ -26,8 +24,7 @@ class TestSyncProgressDialog: AbstractTest() } @Test - fun `Should update correctly when progressing to stages`() - { + fun `Should update correctly when progressing to stages`() { val dlg = SyncProgressDialog() val progressBar = dlg.getChild() @@ -66,4 +63,4 @@ class TestSyncProgressDialog: AbstractTest() progressBar.value shouldBe 6 progressBar.string shouldBe "Stage 7: Finalise" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/screen/sync/TestSyncSetupPanel.kt b/src/test/kotlin/dartzee/screen/sync/TestSyncSetupPanel.kt index 7f1ad3500..89c002abe 100644 --- a/src/test/kotlin/dartzee/screen/sync/TestSyncSetupPanel.kt +++ b/src/test/kotlin/dartzee/screen/sync/TestSyncSetupPanel.kt @@ -14,14 +14,12 @@ import io.kotest.matchers.collections.shouldContainExactly import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestSyncSetupPanel: AbstractTest() -{ +class TestSyncSetupPanel : AbstractTest() { @Test - fun `Should validate there are no open games`() - { + fun `Should validate there are no open games`() { ScreenCache.addDartsGameScreen("foo", mockk(relaxed = true)) val configurer = mockk(relaxed = true) @@ -30,13 +28,14 @@ class TestSyncSetupPanel: AbstractTest() val panel = SyncSetupPanel() panel.clickChild(text = "Get Started > ") - dialogFactory.errorsShown.shouldContainExactly("You must close all open games before performing this action.") + dialogFactory.errorsShown.shouldContainExactly( + "You must close all open games before performing this action." + ) verifyNotCalled { configurer.doFirstTimeSetup() } } @Test - fun `Should not perform any sync actions if input is cancelled`() - { + fun `Should not perform any sync actions if input is cancelled`() { val configurer = mockk(relaxed = true) every { configurer.doFirstTimeSetup() } returns null val syncManager = mockk(relaxed = true) @@ -52,10 +51,10 @@ class TestSyncSetupPanel: AbstractTest() } @Test - fun `Should perform a pull`() - { + fun `Should perform a pull`() { val configurer = mockk(relaxed = true) - every { configurer.doFirstTimeSetup() } returns SyncConfig(SyncMode.OVERWRITE_LOCAL, REMOTE_NAME) + every { configurer.doFirstTimeSetup() } returns + SyncConfig(SyncMode.OVERWRITE_LOCAL, REMOTE_NAME) val syncManager = mockk(relaxed = true) InjectedThings.syncManager = syncManager InjectedThings.syncConfigurer = configurer @@ -67,10 +66,10 @@ class TestSyncSetupPanel: AbstractTest() } @Test - fun `Should perform a push`() - { + fun `Should perform a push`() { val configurer = mockk(relaxed = true) - every { configurer.doFirstTimeSetup() } returns SyncConfig(SyncMode.CREATE_REMOTE, REMOTE_NAME) + every { configurer.doFirstTimeSetup() } returns + SyncConfig(SyncMode.CREATE_REMOTE, REMOTE_NAME) val syncManager = mockk(relaxed = true) InjectedThings.syncManager = syncManager InjectedThings.syncConfigurer = configurer @@ -82,10 +81,10 @@ class TestSyncSetupPanel: AbstractTest() } @Test - fun `Should perform a sync`() - { + fun `Should perform a sync`() { val configurer = mockk(relaxed = true) - every { configurer.doFirstTimeSetup() } returns SyncConfig(SyncMode.NORMAL_SYNC, REMOTE_NAME) + every { configurer.doFirstTimeSetup() } returns + SyncConfig(SyncMode.NORMAL_SYNC, REMOTE_NAME) val syncManager = mockk(relaxed = true) InjectedThings.syncManager = syncManager InjectedThings.syncConfigurer = configurer @@ -95,4 +94,4 @@ class TestSyncSetupPanel: AbstractTest() verify { syncManager.doSync(REMOTE_NAME) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/stats/TestGameWrapper.kt b/src/test/kotlin/dartzee/stats/TestGameWrapper.kt index 4a097e0a0..19f69325a 100644 --- a/src/test/kotlin/dartzee/stats/TestGameWrapper.kt +++ b/src/test/kotlin/dartzee/stats/TestGameWrapper.kt @@ -8,17 +8,11 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGameWrapper : AbstractTest() -{ +class TestGameWrapper : AbstractTest() { @Test - fun `Should capture darts accurately`() - { + fun `Should capture darts accurately`() { val roundTwo = listOf(Dart(20, 1), Dart(5, 1), Dart(1, 1)) - val rounds = makeX01Rounds( - 501, - listOf(Dart(20, 1), Dart(20, 1), Dart(20, 3)), - roundTwo - ) + val rounds = makeX01Rounds(501, listOf(Dart(20, 1), Dart(20, 1), Dart(20, 3)), roundTwo) val gameWrapper = makeGameWrapper() rounds.flatten().forEach(gameWrapper::addDart) @@ -26,4 +20,4 @@ class TestGameWrapper : AbstractTest() gameWrapper.getDartsForFinalRound() shouldBe roundTwo gameWrapper.getAllDarts().shouldContainExactly(rounds.flatten()) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/stats/TestGameWrapperGolfUtils.kt b/src/test/kotlin/dartzee/stats/TestGameWrapperGolfUtils.kt index 77a7caa99..ff10695fb 100644 --- a/src/test/kotlin/dartzee/stats/TestGameWrapperGolfUtils.kt +++ b/src/test/kotlin/dartzee/stats/TestGameWrapperGolfUtils.kt @@ -9,11 +9,9 @@ import dartzee.screen.stats.player.golf.makeOptimalScorecardStartingMap import io.kotest.matchers.collections.shouldContainExactly import org.junit.jupiter.api.Test -class TestGameWrapperGolfUtils : AbstractTest() -{ +class TestGameWrapperGolfUtils : AbstractTest() { @Test - fun `Should populate optimal scorecard map correctly`() - { + fun `Should populate optimal scorecard map correctly`() { val hm = makeOptimalScorecardStartingMap() golfFrontNine22(1L).populateOptimalScorecardMaps(hm) @@ -33,8 +31,7 @@ class TestGameWrapperGolfUtils : AbstractTest() } @Test - fun `Optimal scorecard should cope with missing rounds (due to a team game)`() - { + fun `Optimal scorecard should cope with missing rounds (due to a team game)`() { val hm = makeOptimalScorecardStartingMap() golfFrontNine22EvenRounds().populateOptimalScorecardMaps(hm) @@ -43,11 +40,13 @@ class TestGameWrapperGolfUtils : AbstractTest() getDataRowForHole(hm, 4).shouldContainExactly(1L, 5, 5, 4) } - private fun getDataRowForHole(optimalHoleMap: MutableMap, hole: Int): List - { + private fun getDataRowForHole( + optimalHoleMap: MutableMap, + hole: Int + ): List { val stat = optimalHoleMap.getValue(hole) val scores = stat.darts.map { it.getGolfScore() } return listOf(stat.localGameId) + scores } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/stats/TestGameWrapperX01Utils.kt b/src/test/kotlin/dartzee/stats/TestGameWrapperX01Utils.kt index 6ee9f031d..04c27a171 100644 --- a/src/test/kotlin/dartzee/stats/TestGameWrapperX01Utils.kt +++ b/src/test/kotlin/dartzee/stats/TestGameWrapperX01Utils.kt @@ -12,11 +12,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestGameWrapperX01Utils : AbstractTest() -{ +class TestGameWrapperX01Utils : AbstractTest() { @Test - fun `Should report three dart average correctly`() - { + fun `Should report three dart average correctly`() { val gameWrapper = makeGameWrapper() gameWrapper.getThreeDartAverage(70) shouldBe -1.0 @@ -31,11 +29,10 @@ class TestGameWrapperX01Utils : AbstractTest() } @Test - fun `Should return scoring darts correctly based on threshold`() - { + fun `Should return scoring darts correctly based on threshold`() { val round1 = listOf(Dart(20, 3), Dart(20, 1), Dart(5, 1)) // 115 val round2 = listOf(Dart(20, 1), Dart(20, 1), Dart(1, 1)) // 74 - val round3 = listOf(Dart(9, 1), Dart(14, 1), Dart(1, 1)) // 50 + val round3 = listOf(Dart(9, 1), Dart(14, 1), Dart(1, 1)) // 50 val rounds = makeX01Rounds(200, round1, round2, round3) val wrapper = makeGameWrapper() @@ -46,8 +43,7 @@ class TestGameWrapperX01Utils : AbstractTest() } @Test - fun `Should populate the three dart score map correctly`() - { + fun `Should populate the three dart score map correctly`() { // Full map with the lowest threshold possible val map = mutableMapOf() GAME_WRAPPER_301_1.populateThreeDartScoreMap(map, 62) @@ -59,10 +55,9 @@ class TestGameWrapperX01Utils : AbstractTest() fortyFive.createRows().shouldContainExactly(arrayOf("20, 20, 5", 2, 1L)) val sixty = map.getValue(60) - sixty.createRows().shouldContainExactly( - arrayOf("20, 20, 20", 1, 1L), - arrayOf("T12, 20, 4", 1, 2L) - ) + sixty + .createRows() + .shouldContainExactly(arrayOf("20, 20, 20", 1, 1L), arrayOf("T12, 20, 4", 1, 2L)) // Higher threshold - test rounds are knocked out val shorterMap = mutableMapOf() @@ -71,4 +66,4 @@ class TestGameWrapperX01Utils : AbstractTest() shorterMap.keys.shouldContainExactlyInAnyOrder(120, 60, 57, 45) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/stats/TestStatsSqlUtil.kt b/src/test/kotlin/dartzee/stats/TestStatsSqlUtil.kt index 50b6e1359..6d694d76a 100644 --- a/src/test/kotlin/dartzee/stats/TestStatsSqlUtil.kt +++ b/src/test/kotlin/dartzee/stats/TestStatsSqlUtil.kt @@ -13,11 +13,9 @@ import dartzee.`object`.Dart import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestStatsSqlUtil : AbstractTest() -{ +class TestStatsSqlUtil : AbstractTest() { @Test - fun `Should return the counts by game type for a particular player`() - { + fun `Should return the counts by game type for a particular player`() { val playerA = insertPlayer() val playerB = insertPlayer() @@ -40,17 +38,17 @@ class TestStatsSqlUtil : AbstractTest() } @Test - fun `Should retrieve a single game wrapper successfully`() - { + fun `Should retrieve a single game wrapper successfully`() { val game = insertGame(gameType = GameType.GOLF, gameParams = "9") val player = insertPlayer() val pt = insertParticipant(playerId = player.rowId, gameId = game.rowId) - val rounds = listOf( - listOf(Dart(1, 0), Dart(1, 3)), - listOf(Dart(17, 1), Dart(15, 1), Dart(15, 2)), - listOf(Dart(3, 2)) - ) + val rounds = + listOf( + listOf(Dart(1, 0), Dart(1, 3)), + listOf(Dart(17, 1), Dart(15, 1), Dart(15, 2)), + listOf(Dart(3, 2)) + ) rounds.insertIntoDatabase(player, pt) retrieveGameData(player.rowId, GameType.X01).size shouldBe 0 @@ -67,17 +65,18 @@ class TestStatsSqlUtil : AbstractTest() } @Test - fun `Should identify a team game`() - { + fun `Should identify a team game`() { val game = insertGame(gameType = GameType.GOLF, gameParams = "9") val player = insertPlayer() - val pt = insertParticipant(playerId = player.rowId, gameId = game.rowId, teamId = randomGuid()) + val pt = + insertParticipant(playerId = player.rowId, gameId = game.rowId, teamId = randomGuid()) - val rounds = listOf( - listOf(Dart(1, 0), Dart(1, 3)), - listOf(Dart(17, 1), Dart(15, 1), Dart(15, 2)), - listOf(Dart(3, 2)) - ) + val rounds = + listOf( + listOf(Dart(1, 0), Dart(1, 3)), + listOf(Dart(17, 1), Dart(15, 1), Dart(15, 2)), + listOf(Dart(3, 2)) + ) rounds.insertIntoDatabase(player, pt) val wrapper = retrieveGameData(player.rowId, game.gameType).getValue(game.localId) diff --git a/src/test/kotlin/dartzee/stats/TestThreeDartScoreWrapper.kt b/src/test/kotlin/dartzee/stats/TestThreeDartScoreWrapper.kt index a22802ab7..fefd2a9dc 100644 --- a/src/test/kotlin/dartzee/stats/TestThreeDartScoreWrapper.kt +++ b/src/test/kotlin/dartzee/stats/TestThreeDartScoreWrapper.kt @@ -5,11 +5,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestThreeDartScoreWrapper: AbstractTest() -{ +class TestThreeDartScoreWrapper : AbstractTest() { @Test - fun `Should report the correct total across all methods`() - { + fun `Should report the correct total across all methods`() { val wrapper = ThreeDartScoreWrapper() wrapper.getTotalCount() shouldBe 0 @@ -21,8 +19,7 @@ class TestThreeDartScoreWrapper: AbstractTest() } @Test - fun `Should return one row per method, with the first example game ID`() - { + fun `Should return one row per method, with the first example game ID`() { val wrapper = ThreeDartScoreWrapper() wrapper.addDartStr("20, 5, 1", 100) @@ -31,6 +28,11 @@ class TestThreeDartScoreWrapper: AbstractTest() val rows = wrapper.createRows() rows.size shouldBe 2 - rows.map { it.toList() }.shouldContainExactlyInAnyOrder(listOf("20, 5, 1", 2, 100L), listOf("20, 3, 3", 1, 102L)) + rows + .map { it.toList() } + .shouldContainExactlyInAnyOrder( + listOf("20, 5, 1", 2, 100L), + listOf("20, 3, 3", 1, 102L) + ) } } diff --git a/src/test/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStoreTest.kt b/src/test/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStoreTest.kt index 6206240a9..a524f7559 100644 --- a/src/test/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStoreTest.kt +++ b/src/test/kotlin/dartzee/sync/AmazonS3RemoteDatabaseStoreTest.kt @@ -10,36 +10,32 @@ import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.file.shouldExist import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain +import java.io.File +import java.util.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Assumptions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import java.io.File -import java.util.* -class AmazonS3RemoteDatabaseStoreTest: AbstractTest() -{ +class AmazonS3RemoteDatabaseStoreTest : AbstractTest() { private val testFileText = "This isn't a database!" @BeforeEach - fun beforeEach() - { + fun beforeEach() { File(SYNC_DIR).deleteRecursively() File(SYNC_DIR).mkdirs() } @AfterEach - fun afterEach() - { + fun afterEach() { File(SYNC_DIR).deleteRecursively() File("${databaseDirectory}/$OTHER_DATABASE_NAME").deleteRecursively() } @Test @Tag("integration") - fun `Should support pushing, checking existence and fetching the same database`() - { + fun `Should support pushing, checking existence and fetching the same database`() { Assumptions.assumeTrue { AwsUtils.readCredentials("AWS_SYNC") != null } usingInMemoryDatabase(withSchema = true) { db -> @@ -65,8 +61,7 @@ class AmazonS3RemoteDatabaseStoreTest: AbstractTest() @Test @Tag("integration") - fun `Should return false for a remote database that does not exist`() - { + fun `Should return false for a remote database that does not exist`() { Assumptions.assumeTrue { AwsUtils.readCredentials("AWS_SYNC") != null } val store = AmazonS3RemoteDatabaseStore("dartzee-unit-test") @@ -75,8 +70,7 @@ class AmazonS3RemoteDatabaseStoreTest: AbstractTest() @Test @Tag("integration") - fun `Should create a backup version, with filename including schema version`() - { + fun `Should create a backup version, with filename including schema version`() { Assumptions.assumeTrue { AwsUtils.readCredentials("AWS_SYNC") != null } val s3Client = AwsUtils.makeS3Client() @@ -88,7 +82,8 @@ class AmazonS3RemoteDatabaseStoreTest: AbstractTest() val remoteName = UUID.randomUUID().toString() store.pushDatabase(remoteName, db, null) - val objects = s3Client.listObjects("dartzee-unit-test", "$remoteName/backups/").objectSummaries + val objects = + s3Client.listObjects("dartzee-unit-test", "$remoteName/backups/").objectSummaries objects.size shouldBe 1 objects.first().key shouldContain "V${DATABASE_VERSION}.zip" } @@ -96,8 +91,7 @@ class AmazonS3RemoteDatabaseStoreTest: AbstractTest() @Test @Tag("integration") - fun `Should throw an error if trying to overwrite database which has been modified since it was fetched`() - { + fun `Should throw an error if trying to overwrite database which has been modified since it was fetched`() { Assumptions.assumeTrue { AwsUtils.readCredentials("AWS_SYNC") != null } usingInMemoryDatabase(withSchema = true) { db -> @@ -118,11 +112,13 @@ class AmazonS3RemoteDatabaseStoreTest: AbstractTest() val updatedModified = store.fetchDatabase(remoteName).lastModified - val e = shouldThrow { - store.pushDatabase(remoteName, db, lastModified) - } + val e = + shouldThrow { + store.pushDatabase(remoteName, db, lastModified) + } - e.message shouldBe "Remote database $remoteName was last modified $updatedModified, which is after $lastModified - aborting" + e.message shouldBe + "Remote database $remoteName was last modified $updatedModified, which is after $lastModified - aborting" } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/sync/InMemoryRemoteDatabaseStore.kt b/src/test/kotlin/dartzee/sync/InMemoryRemoteDatabaseStore.kt index 2b9912563..1080f78df 100644 --- a/src/test/kotlin/dartzee/sync/InMemoryRemoteDatabaseStore.kt +++ b/src/test/kotlin/dartzee/sync/InMemoryRemoteDatabaseStore.kt @@ -3,26 +3,24 @@ package dartzee.sync import dartzee.utils.Database import java.util.* -class InMemoryRemoteDatabaseStore(vararg initialEntries: Pair) : IRemoteDatabaseStore -{ +class InMemoryRemoteDatabaseStore(vararg initialEntries: Pair) : + IRemoteDatabaseStore { private val hmNameToDatabase = mutableMapOf() - init - { + init { hmNameToDatabase.putAll(initialEntries) } - fun clear() - { + fun clear() { hmNameToDatabase.clear() } override fun databaseExists(remoteName: String) = hmNameToDatabase.containsKey(remoteName) - override fun fetchDatabase(remoteName: String) = FetchDatabaseResult(hmNameToDatabase.getValue(remoteName), Date()) + override fun fetchDatabase(remoteName: String) = + FetchDatabaseResult(hmNameToDatabase.getValue(remoteName), Date()) - override fun pushDatabase(remoteName: String, database: Database, lastModified: Date?) - { + override fun pushDatabase(remoteName: String, database: Database, lastModified: Date?) { hmNameToDatabase[remoteName] = database } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/sync/TestSyncConfigurer.kt b/src/test/kotlin/dartzee/sync/TestSyncConfigurer.kt index cfe10e6a7..c92deb032 100644 --- a/src/test/kotlin/dartzee/sync/TestSyncConfigurer.kt +++ b/src/test/kotlin/dartzee/sync/TestSyncConfigurer.kt @@ -6,44 +6,45 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSyncConfigurer: AbstractTest() -{ +class TestSyncConfigurer : AbstractTest() { @Test - fun `Should return return correct config when creating remote database for the first time`() - { + fun `Should return return correct config when creating remote database for the first time`() { dialogFactory.inputSelection = "Goomba" dialogFactory.optionSequence.add("Create 'Goomba'") val result = makeSyncConfigurer().doFirstTimeSetup() - dialogFactory.optionsShown.shouldContainExactly("No shared database found called 'Goomba'. Would you like to create it?") + dialogFactory.optionsShown.shouldContainExactly( + "No shared database found called 'Goomba'. Would you like to create it?" + ) result shouldBe SyncConfig(SyncMode.CREATE_REMOTE, "Goomba") } @Test - fun `Should return null if prompt to create new remote database is cancelled`() - { + fun `Should return null if prompt to create new remote database is cancelled`() { dialogFactory.inputSelection = "Goomba" dialogFactory.optionSequence.add("Cancel") val result = makeSyncConfigurer().doFirstTimeSetup() - dialogFactory.optionsShown.shouldContainExactly("No shared database found called 'Goomba'. Would you like to create it?") + dialogFactory.optionsShown.shouldContainExactly( + "No shared database found called 'Goomba'. Would you like to create it?" + ) result shouldBe null } @Test - fun `Should return null if prompt to create new remote database is escaped`() - { + fun `Should return null if prompt to create new remote database is escaped`() { dialogFactory.inputSelection = "Goomba" dialogFactory.optionSequence.add(null) val result = makeSyncConfigurer().doFirstTimeSetup() - dialogFactory.optionsShown.shouldContainExactly("No shared database found called 'Goomba'. Would you like to create it?") + dialogFactory.optionsShown.shouldContainExactly( + "No shared database found called 'Goomba'. Would you like to create it?" + ) result shouldBe null } @Test - fun `Should return the right config when remote already exists and simple overwrite is chosen`() - { + fun `Should return the right config when remote already exists and simple overwrite is chosen`() { val store = InMemoryRemoteDatabaseStore() store.pushDatabase("Goomba", mainDatabase) @@ -52,13 +53,14 @@ class TestSyncConfigurer: AbstractTest() val configurer = makeSyncConfigurer(store) val result = configurer.doFirstTimeSetup() - dialogFactory.optionsShown.shouldContainExactly("Shared database 'Goomba' already exists. How would you like to proceed?") + dialogFactory.optionsShown.shouldContainExactly( + "Shared database 'Goomba' already exists. How would you like to proceed?" + ) result shouldBe SyncConfig(SyncMode.OVERWRITE_LOCAL, "Goomba") } @Test - fun `Should return the right config when remote already exists and regular sync is chosen`() - { + fun `Should return the right config when remote already exists and regular sync is chosen`() { val store = InMemoryRemoteDatabaseStore() store.pushDatabase("Goomba", mainDatabase) @@ -67,13 +69,14 @@ class TestSyncConfigurer: AbstractTest() val configurer = makeSyncConfigurer(store) val result = configurer.doFirstTimeSetup() - dialogFactory.optionsShown.shouldContainExactly("Shared database 'Goomba' already exists. How would you like to proceed?") + dialogFactory.optionsShown.shouldContainExactly( + "Shared database 'Goomba' already exists. How would you like to proceed?" + ) result shouldBe SyncConfig(SyncMode.NORMAL_SYNC, "Goomba") } @Test - fun `Should return null when remote already exists and option is cancelled`() - { + fun `Should return null when remote already exists and option is cancelled`() { val store = InMemoryRemoteDatabaseStore() store.pushDatabase("Goomba", mainDatabase) @@ -82,13 +85,14 @@ class TestSyncConfigurer: AbstractTest() val configurer = makeSyncConfigurer(store) val result = configurer.doFirstTimeSetup() - dialogFactory.optionsShown.shouldContainExactly("Shared database 'Goomba' already exists. How would you like to proceed?") + dialogFactory.optionsShown.shouldContainExactly( + "Shared database 'Goomba' already exists. How would you like to proceed?" + ) result shouldBe null } @Test - fun `Should return null when remote already exists and option is escaped`() - { + fun `Should return null when remote already exists and option is escaped`() { val store = InMemoryRemoteDatabaseStore() store.pushDatabase("Goomba", mainDatabase) @@ -97,10 +101,12 @@ class TestSyncConfigurer: AbstractTest() val configurer = makeSyncConfigurer(store) val result = configurer.doFirstTimeSetup() - dialogFactory.optionsShown.shouldContainExactly("Shared database 'Goomba' already exists. How would you like to proceed?") + dialogFactory.optionsShown.shouldContainExactly( + "Shared database 'Goomba' already exists. How would you like to proceed?" + ) result shouldBe null } - private fun makeSyncConfigurer(dbStore: IRemoteDatabaseStore = InMemoryRemoteDatabaseStore()) - = SyncConfigurer(dbStore) -} \ No newline at end of file + private fun makeSyncConfigurer(dbStore: IRemoteDatabaseStore = InMemoryRemoteDatabaseStore()) = + SyncConfigurer(dbStore) +} diff --git a/src/test/kotlin/dartzee/sync/TestSyncManager.kt b/src/test/kotlin/dartzee/sync/TestSyncManager.kt index c2159873b..ef7b8f0a0 100644 --- a/src/test/kotlin/dartzee/sync/TestSyncManager.kt +++ b/src/test/kotlin/dartzee/sync/TestSyncManager.kt @@ -29,31 +29,27 @@ import io.mockk.every import io.mockk.mockk import io.mockk.spyk import io.mockk.verify -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.io.File import java.io.IOException import java.net.SocketException import java.sql.Timestamp +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestSyncManager: AbstractTest() -{ +class TestSyncManager : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { File(TEST_DB_DIRECTORY).mkdirs() } @AfterEach - fun afterEach() - { + fun afterEach() { File(TEST_DB_DIRECTORY).deleteRecursively() } @Test - fun `Should revert to a PULL if no local changes`() - { + fun `Should revert to a PULL if no local changes`() { val syncManager = spyk(SyncManager(mockk(relaxed = true))) val t = syncManager.doSyncIfNecessary(REMOTE_NAME) t.join() @@ -63,8 +59,7 @@ class TestSyncManager: AbstractTest() } @Test - fun `Should process with a sync if there are local changes`() - { + fun `Should process with a sync if there are local changes`() { insertGame() val syncManager = spyk(SyncManager(mockk(relaxed = true))) @@ -75,8 +70,7 @@ class TestSyncManager: AbstractTest() } @Test - fun `Should show an error and log a warning if there is a connection error`() - { + fun `Should show an error and log a warning if there is a connection error`() { val exception = SocketException("Failed to connect.") val store = mockk() every { store.fetchDatabase(any()) } throws exception @@ -84,15 +78,16 @@ class TestSyncManager: AbstractTest() val t = SyncManager(store).doSync(REMOTE_NAME) t.join() - dialogFactory.errorsShown.shouldContainExactly("A connection error occurred. Check your internet connection and try again.") + dialogFactory.errorsShown.shouldContainExactly( + "A connection error occurred. Check your internet connection and try again." + ) val log = verifyLog(CODE_SYNC_ERROR, Severity.WARN) log.message shouldBe "Caught network error during sync: $exception" syncDirectoryShouldNotExist() } @Test - fun `Should abort sync if merger validation fails`() - { + fun `Should abort sync if merger validation fails`() { val remoteDb = mockk() every { remoteDb.testConnection() } returns false @@ -101,13 +96,14 @@ class TestSyncManager: AbstractTest() val t = SyncManager(store).doSync("Goomba") t.join() - dialogFactory.errorsShown.shouldContainExactly("An error occurred connecting to the remote database.") + dialogFactory.errorsShown.shouldContainExactly( + "An error occurred connecting to the remote database." + ) syncDirectoryShouldNotExist() } @Test - fun `Should abort if a SQL error occurs during database merge`() - { + fun `Should abort if a SQL error occurs during database merge`() { usingDbWithTestFile { remoteDb -> insertPlayer(database = mainDatabase) remoteDb.dropTable(EntityName.Player) @@ -117,7 +113,9 @@ class TestSyncManager: AbstractTest() val t = SyncManager(store).doSync(REMOTE_NAME) t.join() - dialogFactory.errorsShown.shouldContainExactly("An unexpected error occurred - no data has been changed.") + dialogFactory.errorsShown.shouldContainExactly( + "An unexpected error occurred - no data has been changed." + ) val log = verifyLog(CODE_SQL_EXCEPTION, Severity.ERROR) log.message shouldContain "Caught SQLException for statement" @@ -130,8 +128,7 @@ class TestSyncManager: AbstractTest() } @Test - fun `Should throw an error if games from the original database have not made it through the merge`() - { + fun `Should throw an error if games from the original database have not made it through the merge`() { usingDbWithTestFile { remoteDb -> val g = insertGame(dtLastUpdate = Timestamp(1000), database = mainDatabase) SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME) @@ -141,7 +138,9 @@ class TestSyncManager: AbstractTest() val t = SyncManager(store).doSync(REMOTE_NAME) t.join() - dialogFactory.errorsShown.shouldContainExactly("Sync resulted in missing data. \n\nResults have been discarded.") + dialogFactory.errorsShown.shouldContainExactly( + "Sync resulted in missing data. \n\nResults have been discarded." + ) val log = verifyLog(CODE_SYNC_ERROR, Severity.ERROR) log.message shouldContain "1 game(s) missing from resulting database after merge" @@ -154,8 +153,7 @@ class TestSyncManager: AbstractTest() } @Test - fun `Should not throw an error if game from original database was explicitly deleted on another device`() - { + fun `Should not throw an error if game from original database was explicitly deleted on another device`() { usingDbWithTestFile { remoteDb -> val g = insertGame(dtLastUpdate = Timestamp(1000), database = mainDatabase) SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME) @@ -173,20 +171,22 @@ class TestSyncManager: AbstractTest() } @Test - fun `Should show an error and log a warning if remote db has been modified since it was pulled`() - { + fun `Should show an error and log a warning if remote db has been modified since it was pulled`() { usingDbWithTestFile { remoteDb -> val exception = ConcurrentModificationException("Oh no") val store = mockk() - every { store.fetchDatabase(any()) } returns FetchDatabaseResult(remoteDb, getSqlDateNow()) + every { store.fetchDatabase(any()) } returns + FetchDatabaseResult(remoteDb, getSqlDateNow()) every { store.pushDatabase(any(), any(), any()) } throws exception val t = SyncManager(store).doSync(REMOTE_NAME) t.join() - dialogFactory.errorsShown.shouldContainExactly("Another sync has been performed since this one started. \n" + + dialogFactory.errorsShown.shouldContainExactly( + "Another sync has been performed since this one started. \n" + "\n" + - "Results have been discarded.") + "Results have been discarded." + ) val log = verifyLog(CODE_SYNC_ERROR, Severity.WARN) log.message shouldBe "$exception" @@ -198,8 +198,7 @@ class TestSyncManager: AbstractTest() } @Test - fun `Should show an error if something goes wrong swapping the database in`() - { + fun `Should show an error if something goes wrong swapping the database in`() { usingDbWithTestFile { remoteDb -> remoteDb.getDirectory().deleteRecursively() @@ -207,17 +206,19 @@ class TestSyncManager: AbstractTest() val t = SyncManager(store).doSync(REMOTE_NAME) t.join() - dialogFactory.errorsShown.shouldContainExactly("Failed to restore database. Error: Failed to rename new file to ${mainDatabase.dbName}") + dialogFactory.errorsShown.shouldContainExactly( + "Failed to restore database. Error: Failed to rename new file to ${mainDatabase.dbName}" + ) dialogFactory.infosShown.shouldBeEmpty() - // Open a test connection so the tidy-up doesn't freak out about the db already being shut down + // Open a test connection so the tidy-up doesn't freak out about the db already being + // shut down remoteDb.testConnection() } } @Test - fun `Should update sync screen regardless of an error occurring`() - { + fun `Should update sync screen regardless of an error occurring`() { shouldUpdateSyncScreen { val exception = IOException("Boom.") val dbStore = mockk() @@ -232,8 +233,7 @@ class TestSyncManager: AbstractTest() } @Test - fun `Should successfully sync data between remote and local db, pushing up the result and swapping in locally`() - { + fun `Should successfully sync data between remote and local db, pushing up the result and swapping in locally`() { usingDbWithTestFile { remoteDb -> insertGame(database = mainDatabase) insertGame(database = remoteDb) @@ -254,8 +254,7 @@ class TestSyncManager: AbstractTest() } } - private fun usingDbWithTestFile(testBlock: (inMemoryDatabase: Database) -> Unit) - { + private fun usingDbWithTestFile(testBlock: (inMemoryDatabase: Database) -> Unit) { usingInMemoryDatabase(withSchema = true) { remoteDb -> val f = File("${remoteDb.getDirectoryStr()}/SomeFile.txt") f.createNewFile() @@ -264,5 +263,6 @@ class TestSyncManager: AbstractTest() } } - private fun databasesSwapped() = File("${InjectedThings.databaseDirectory}/Darts/SomeFile.txt").exists() -} \ No newline at end of file + private fun databasesSwapped() = + File("${InjectedThings.databaseDirectory}/Darts/SomeFile.txt").exists() +} diff --git a/src/test/kotlin/dartzee/sync/TestSyncManagerPull.kt b/src/test/kotlin/dartzee/sync/TestSyncManagerPull.kt index 82b914d69..11dd348b3 100644 --- a/src/test/kotlin/dartzee/sync/TestSyncManagerPull.kt +++ b/src/test/kotlin/dartzee/sync/TestSyncManagerPull.kt @@ -17,29 +17,25 @@ import io.kotest.matchers.file.shouldExist import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk +import java.io.File +import java.io.IOException import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import java.io.File -import java.io.IOException -class TestSyncManagerPull: AbstractTest() -{ +class TestSyncManagerPull : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { File(TEST_DB_DIRECTORY).mkdirs() } @AfterEach - fun afterEach() - { + fun afterEach() { File(TEST_DB_DIRECTORY).deleteRecursively() } @Test - fun `Should log an error and dismiss the loading dialog if an error occurs`() - { + fun `Should log an error and dismiss the loading dialog if an error occurs`() { val exception = IOException("Boom.") val dbStore = mockk() every { dbStore.fetchDatabase(any()) } throws exception @@ -55,14 +51,15 @@ class TestSyncManagerPull: AbstractTest() val log = verifyLog(CODE_PULL_ERROR, Severity.ERROR) log.errorObject shouldBe exception - dialogFactory.errorsShown.shouldContainExactly("An unexpected error occurred - no data has been changed.") + dialogFactory.errorsShown.shouldContainExactly( + "An unexpected error occurred - no data has been changed." + ) syncDirectoryShouldNotExist() } @Test - fun `Should abort the pull if test connection cannot be established`() - { + fun `Should abort the pull if test connection cannot be established`() { val db = mockk(relaxed = true) every { db.testConnection() } returns false @@ -72,12 +69,13 @@ class TestSyncManagerPull: AbstractTest() val t = manager.doPull(REMOTE_NAME) t.join() - dialogFactory.errorsShown.shouldContainExactly("An error occurred connecting to the remote database.") + dialogFactory.errorsShown.shouldContainExactly( + "An error occurred connecting to the remote database." + ) } @Test - fun `Should abort the pull if some other validation error occurs with the database`() - { + fun `Should abort the pull if some other validation error occurs with the database`() { usingInMemoryDatabase { db -> val store = InMemoryRemoteDatabaseStore(REMOTE_NAME to db) @@ -86,14 +84,16 @@ class TestSyncManagerPull: AbstractTest() t.join() val log = verifyLog(CODE_MERGE_ERROR, Severity.ERROR) - log.message shouldBe "Unable to ascertain remote database version (but could connect) - this is unexpected." - dialogFactory.errorsShown.shouldContainExactly("An error occurred connecting to the remote database.") + log.message shouldBe + "Unable to ascertain remote database version (but could connect) - this is unexpected." + dialogFactory.errorsShown.shouldContainExactly( + "An error occurred connecting to the remote database." + ) } } @Test - fun `Should pull and swap in remote database`() - { + fun `Should pull and swap in remote database`() { usingInMemoryDatabase(withSchema = true) { db -> val store = InMemoryRemoteDatabaseStore(REMOTE_NAME to db) @@ -109,8 +109,7 @@ class TestSyncManagerPull: AbstractTest() } @Test - fun `Should update sync screen regardless of an error occurring`() - { + fun `Should update sync screen regardless of an error occurring`() { shouldUpdateSyncScreen { val exception = IOException("Boom.") val dbStore = mockk() @@ -123,4 +122,4 @@ class TestSyncManagerPull: AbstractTest() errorLogged() shouldBe true } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/sync/TestSyncManagerPush.kt b/src/test/kotlin/dartzee/sync/TestSyncManagerPush.kt index f95e0b546..2622ae82e 100644 --- a/src/test/kotlin/dartzee/sync/TestSyncManagerPush.kt +++ b/src/test/kotlin/dartzee/sync/TestSyncManagerPush.kt @@ -13,14 +13,12 @@ import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk -import org.junit.jupiter.api.Test import java.io.IOException +import org.junit.jupiter.api.Test -class TestSyncManagerPush: AbstractTest() -{ +class TestSyncManagerPush : AbstractTest() { @Test - fun `Should log an error, dismiss the loading dialog and tidy up SyncAudit if an error occurs`() - { + fun `Should log an error, dismiss the loading dialog and tidy up SyncAudit if an error occurs`() { val exception = IOException("Boom.") val dbStore = mockk() every { dbStore.pushDatabase(any(), any()) } throws exception @@ -36,15 +34,16 @@ class TestSyncManagerPush: AbstractTest() val log = verifyLog(CODE_PUSH_ERROR, Severity.ERROR) log.errorObject shouldBe exception - dialogFactory.errorsShown.shouldContainExactly("An unexpected error occurred - no data has been changed.") + dialogFactory.errorsShown.shouldContainExactly( + "An unexpected error occurred - no data has been changed." + ) SyncAuditEntity.getLastSyncData(mainDatabase) shouldBe null syncDirectoryShouldNotExist() } @Test - fun `Should insert into sync audit and push the current database`() - { + fun `Should insert into sync audit and push the current database`() { val store = InMemoryRemoteDatabaseStore() val manager = SyncManager(store) @@ -63,8 +62,7 @@ class TestSyncManagerPush: AbstractTest() } @Test - fun `Should update sync screen regardless of an error occurring`() - { + fun `Should update sync screen regardless of an error occurring`() { shouldUpdateSyncScreen { val exception = IOException("Boom.") val dbStore = mockk() @@ -77,4 +75,4 @@ class TestSyncManagerPush: AbstractTest() errorLogged() shouldBe true } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/sync/TestSyncUtils.kt b/src/test/kotlin/dartzee/sync/TestSyncUtils.kt index 323370748..25d4d13c7 100644 --- a/src/test/kotlin/dartzee/sync/TestSyncUtils.kt +++ b/src/test/kotlin/dartzee/sync/TestSyncUtils.kt @@ -24,14 +24,12 @@ import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.mockk.mockk -import org.junit.jupiter.api.Test import java.sql.Timestamp +import org.junit.jupiter.api.Test -class TestSyncUtils: AbstractTest() -{ +class TestSyncUtils : AbstractTest() { @Test - fun `Should return the count of games modified since last sync`() - { + fun `Should return the count of games modified since last sync`() { makeSyncAudit(mainDatabase).saveToDatabase(Timestamp(2000)) insertGame(dtLastUpdate = Timestamp(1500)) @@ -42,8 +40,7 @@ class TestSyncUtils: AbstractTest() } @Test - fun `Should return all games if never synced before`() - { + fun `Should return all games if never synced before`() { insertGame(dtLastUpdate = Timestamp(150)) insertGame(dtLastUpdate = Timestamp(250)) insertGame(dtLastUpdate = Timestamp(500)) @@ -52,8 +49,7 @@ class TestSyncUtils: AbstractTest() } @Test - fun `Should delete all sync audits and refresh sync screen`() - { + fun `Should delete all sync audits and refresh sync screen`() { shouldUpdateSyncScreen { mainDatabase.updateDatabaseVersion(16) makeSyncAudit(mainDatabase).saveToDatabase(Timestamp(200)) @@ -66,24 +62,23 @@ class TestSyncUtils: AbstractTest() } @Test - fun `Should allow sync action when no open games`() - { + fun `Should allow sync action when no open games`() { validateSyncAction() shouldBe true dialogFactory.errorsShown.shouldBeEmpty() } @Test - fun `Should not allow sync action if there are open games`() - { + fun `Should not allow sync action if there are open games`() { ScreenCache.addDartsGameScreen("foo", mockk(relaxed = true)) validateSyncAction() shouldBe false - dialogFactory.errorsShown.shouldContainExactly("You must close all open games before performing this action.") + dialogFactory.errorsShown.shouldContainExactly( + "You must close all open games before performing this action." + ) } @Test - fun `Should consider all relevant entities when checking whether a full sync is required`() - { + fun `Should consider all relevant entities when checking whether a full sync is required`() { validateSyncIsNecessary { insertPlayer() } validateSyncIsNecessary { insertAchievement() } validateSyncIsNecessary { insertGame() } @@ -95,16 +90,15 @@ class TestSyncUtils: AbstractTest() validateSyncIsNecessary { insertDart(ParticipantEntity()) } validateSyncIsNecessary { insertGame().also { it.deleteFromDatabase() } } } - private fun validateSyncIsNecessary(setupFn: () -> Unit) - { + + private fun validateSyncIsNecessary(setupFn: () -> Unit) { wipeDatabase() setupFn() needsSync() shouldBe true } @Test - fun `Should not perform a sync if there are no local changes`() - { + fun `Should not perform a sync if there are no local changes`() { needsSync() shouldBe false SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME) @@ -113,10 +107,9 @@ class TestSyncUtils: AbstractTest() } @Test - fun `Should perform a sync if changes since last sync date`() - { + fun `Should perform a sync if changes since last sync date`() { val syncAuditEntity = SyncAuditEntity.insertSyncAudit(mainDatabase, REMOTE_NAME) insertGame(dtLastUpdate = getFutureTime(syncAuditEntity.dtLastUpdate)) needsSync() shouldBe true } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/types/TestStringMicrotype.kt b/src/test/kotlin/dartzee/types/TestStringMicrotype.kt index 63ad97a5f..40b175065 100644 --- a/src/test/kotlin/dartzee/types/TestStringMicrotype.kt +++ b/src/test/kotlin/dartzee/types/TestStringMicrotype.kt @@ -5,13 +5,11 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe import org.junit.jupiter.api.Test -class TestStringMicrotype: AbstractTest() -{ +class TestStringMicrotype : AbstractTest() { @Test - fun `Should correctly identify whether microtypes are equal, and implement toString`() - { - class MicrotypeOne(value: String): StringMicrotype(value) - class MicrotypeTwo(value: String): StringMicrotype(value) + fun `Should correctly identify whether microtypes are equal, and implement toString`() { + class MicrotypeOne(value: String) : StringMicrotype(value) + class MicrotypeTwo(value: String) : StringMicrotype(value) MicrotypeOne("Foo") shouldNotBe "Foo" MicrotypeOne("Foo") shouldNotBe MicrotypeTwo("Foo") @@ -21,4 +19,4 @@ class TestStringMicrotype: AbstractTest() MicrotypeOne("Hello").toString() shouldBe "Hello" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestAwsUtil.kt b/src/test/kotlin/dartzee/utils/TestAwsUtil.kt index 7e902194f..8a6395ae2 100644 --- a/src/test/kotlin/dartzee/utils/TestAwsUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestAwsUtil.kt @@ -4,15 +4,14 @@ import dartzee.helper.AbstractTest import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain -import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import java.io.ByteArrayOutputStream import java.io.File import java.io.PrintStream +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test -class TestAwsUtil: AbstractTest() -{ +class TestAwsUtil : AbstractTest() { private val rsrcPath = File(javaClass.getResource("/ChangeLog")!!.file).absolutePath private val newRsrcPath = rsrcPath.replace("ChangeLog", "foo") private val testFile: File = File(newRsrcPath) @@ -20,21 +19,18 @@ class TestAwsUtil: AbstractTest() private val newOut = ByteArrayOutputStream() @BeforeEach - fun beforeEach() - { + fun beforeEach() { System.setOut(PrintStream(newOut)) } @AfterEach - fun afterEach() - { + fun afterEach() { testFile.delete() System.setOut(originalOut) } @Test - fun `Should print an error and return null if file does not exist`() - { + fun `Should print an error and return null if file does not exist`() { clearLogs() val credentials = AwsUtils.readCredentials("foo") @@ -45,8 +41,7 @@ class TestAwsUtil: AbstractTest() } @Test - fun `Should print an error and return null for invalid file contents`() - { + fun `Should print an error and return null for invalid file contents`() { testFile.writeText("foo") clearLogs() @@ -54,6 +49,8 @@ class TestAwsUtil: AbstractTest() credentials shouldBe null flushAndGetLogRecords().shouldBeEmpty() - newOut.toString().shouldContain("Failed to read in AWS credentials: java.lang.IndexOutOfBoundsException") + newOut + .toString() + .shouldContain("Failed to read in AWS credentials: java.lang.IndexOutOfBoundsException") } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestDartboardUtil.kt b/src/test/kotlin/dartzee/utils/TestDartboardUtil.kt index a04eb869f..53d00f681 100644 --- a/src/test/kotlin/dartzee/utils/TestDartboardUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestDartboardUtil.kt @@ -12,79 +12,71 @@ import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.collections.shouldNotContain import io.kotest.matchers.collections.shouldNotContainAnyOf import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import java.awt.Point +import org.junit.jupiter.api.Test private const val MAX_DARTBOARD_RADIUS = 325 -class TestDartboardUtil : AbstractRegistryTest() -{ - override fun getPreferencesAffected(): MutableList - { - return mutableListOf(PREFERENCES_STRING_EVEN_SINGLE_COLOUR, - PREFERENCES_STRING_EVEN_DOUBLE_COLOUR, - PREFERENCES_STRING_EVEN_TREBLE_COLOUR, - PREFERENCES_STRING_ODD_SINGLE_COLOUR, - PREFERENCES_STRING_ODD_DOUBLE_COLOUR, - PREFERENCES_STRING_ODD_TREBLE_COLOUR) +class TestDartboardUtil : AbstractRegistryTest() { + override fun getPreferencesAffected(): MutableList { + return mutableListOf( + PREFERENCES_STRING_EVEN_SINGLE_COLOUR, + PREFERENCES_STRING_EVEN_DOUBLE_COLOUR, + PREFERENCES_STRING_EVEN_TREBLE_COLOUR, + PREFERENCES_STRING_ODD_SINGLE_COLOUR, + PREFERENCES_STRING_ODD_DOUBLE_COLOUR, + PREFERENCES_STRING_ODD_TREBLE_COLOUR + ) } - /** - * X X X X - * X O O X - * X O O X - * X X X X - */ + /** X X X X X O O X X O O X X X X X */ @Test - fun `Should report edge points correctly - square`() - { + fun `Should report edge points correctly - square`() { val xRange = 0..3 val yRange = 0..3 val pts = xRange.map { x -> yRange.map { y -> Point(x, y) } }.flatten() val edgePts = computeEdgePoints(pts) - //Corners + // Corners edgePts.shouldContainAll(Point(0, 0), Point(0, 3), Point(3, 0), Point(3, 3)) - //Random other edges + // Random other edges edgePts.shouldContainAll( - Point(0, 1), Point(0, 2), - Point(3, 1), Point(3, 2), - Point(1, 0), Point(2, 0), - Point(1, 3), Point(2, 3) + Point(0, 1), + Point(0, 2), + Point(3, 1), + Point(3, 2), + Point(1, 0), + Point(2, 0), + Point(1, 3), + Point(2, 3) ) // Inner points edgePts.shouldNotContainAnyOf(Point(1, 1), Point(1, 2), Point(2, 1), Point(2, 2)) } - /** X - * X X - * X O X - * X O O X - * X X X X X - */ + /** X X X X O X X O O X X X X X X */ @Test - fun `Should report edge points correctly - triangle`() - { + fun `Should report edge points correctly - triangle`() { val xRange = 0..4 val yRange = 0..4 - val pts = xRange.map { x -> yRange.filter{ it <= x }.map { y -> Point(x, y) } }.flatten() + val pts = xRange.map { x -> yRange.filter { it <= x }.map { y -> Point(x, y) } }.flatten() val edgePts = computeEdgePoints(pts) - //Bottom edge + // Bottom edge edgePts.shouldContainAll(Point(0, 0), Point(1, 0), Point(2, 0), Point(3, 0), Point(4, 0)) - //Right edge + // Right edge edgePts.shouldContainAll(Point(4, 0), Point(4, 1), Point(4, 2), Point(4, 3), Point(4, 4)) - //Diagonal + // Diagonal edgePts.shouldContainAll(Point(1, 1), Point(2, 2), Point(3, 3), Point(4, 4)) - //Inner points + // Inner points edgePts.shouldNotContainAnyOf(Point(2, 1), Point(3, 1), Point(3, 2)) } @@ -100,9 +92,10 @@ class TestDartboardUtil : AbstractRegistryTest() @Test fun `Should return non-overlapping sets of points`() { - val allPoints = getAllNonMissSegments().flatMap { - computePointsForSegment(it, Point(0, 0), MAX_DARTBOARD_RADIUS.toDouble()) - } + val allPoints = + getAllNonMissSegments().flatMap { + computePointsForSegment(it, Point(0, 0), MAX_DARTBOARD_RADIUS.toDouble()) + } allPoints.size shouldBe allPoints.distinct().size } @@ -111,12 +104,14 @@ class TestDartboardUtil : AbstractRegistryTest() val centre = Point(0, 0) val radius = 50.0 - getAllNonMissSegments().filterNot { it.type == SegmentType.DOUBLE && it.score == 25 }.flatMap { segment -> - val pts = computePointsForSegment(segment, centre, radius) - withClue("$segment should not contain the origin point") { - pts.shouldNotContain(Point(0, 0)) + getAllNonMissSegments() + .filterNot { it.type == SegmentType.DOUBLE && it.score == 25 } + .flatMap { segment -> + val pts = computePointsForSegment(segment, centre, radius) + withClue("$segment should not contain the origin point") { + pts.shouldNotContain(Point(0, 0)) + } } - } } @Test @@ -124,8 +119,12 @@ class TestDartboardUtil : AbstractRegistryTest() val radius = MAX_DARTBOARD_RADIUS val centre = Point(radius, radius) - val allPointsInCircle = getPointList(radius * 2, radius * 2).filter { it.distance(centre) < radius }.toSet() - val allPointsInSegments = getAllNonMissSegments().flatMap { computePointsForSegment(it, centre, radius.toDouble()) }.toSet() + val allPointsInCircle = + getPointList(radius * 2, radius * 2).filter { it.distance(centre) < radius }.toSet() + val allPointsInSegments = + getAllNonMissSegments() + .flatMap { computePointsForSegment(it, centre, radius.toDouble()) } + .toSet() val missedPoints = allPointsInCircle - allPointsInSegments missedPoints.forEach { @@ -135,40 +134,41 @@ class TestDartboardUtil : AbstractRegistryTest() } @Test - fun `Should get consistent results when recalculating segment type`() - { + fun `Should get consistent results when recalculating segment type`() { val centre = Point(0, 0) val radius = 200.0 - // Remove the outer bull because we currently don't calculate edge points for it correctly (the hole in the middle wrecks it) - getAllNonMissSegments().filterNot { it.score == 25 && it.type == SegmentType.OUTER_SINGLE }.forEach { segment -> - val pts = computePointsForSegment(segment, centre, radius) + // Remove the outer bull because we currently don't calculate edge points for it correctly + // (the hole in the middle wrecks it) + getAllNonMissSegments() + .filterNot { it.score == 25 && it.type == SegmentType.OUTER_SINGLE } + .forEach { segment -> + val pts = computePointsForSegment(segment, centre, radius) - pts.forEach { pt -> - val calculatedSegment = factorySegmentForPoint(pt, centre, radius) + pts.forEach { pt -> + val calculatedSegment = factorySegmentForPoint(pt, centre, radius) - withClue("$pt should produce the same segment as $segment") { - calculatedSegment shouldBe segment + withClue("$pt should produce the same segment as $segment") { + calculatedSegment shouldBe segment + } } } - } } @Test - fun testFactorySegmentKeyForPoint() - { + fun testFactorySegmentKeyForPoint() { clearPreferences() resetCachedDartboardValues() - //Bullseyes + // Bullseyes assertSegment(Point(0, 0), SegmentType.DOUBLE, 25, 2) assertSegment(Point(37, 0), SegmentType.DOUBLE, 25, 2) assertSegment(Point(38, 0), SegmentType.OUTER_SINGLE, 25, 1) assertSegment(Point(48, 55), SegmentType.OUTER_SINGLE, 25, 1) assertSegment(Point(0, -93), SegmentType.OUTER_SINGLE, 25, 1) - //Boundary conditions for varying radius + // Boundary conditions for varying radius assertSegment(Point(0, 94), SegmentType.INNER_SINGLE, 3, 1) assertSegment(Point(0, 581), SegmentType.INNER_SINGLE, 3, 1) assertSegment(Point(0, -582), SegmentType.TREBLE, 20, 3) @@ -180,15 +180,14 @@ class TestDartboardUtil : AbstractRegistryTest() assertSegment(Point(0, -1000), SegmentType.MISS, 20, 0) assertSegment(Point(0, -1299), SegmentType.MISS, 20, 0) - //Test 45 degrees etc + // Test 45 degrees etc assertSegment(Point(100, -100), SegmentType.INNER_SINGLE, 4, 1) assertSegment(Point(-100, -100), SegmentType.INNER_SINGLE, 9, 1) assertSegment(Point(-100, 100), SegmentType.INNER_SINGLE, 7, 1) assertSegment(Point(100, 100), SegmentType.INNER_SINGLE, 15, 1) } - private fun assertSegment(pt: Point, segmentType: SegmentType, score: Int, multiplier: Int) - { + private fun assertSegment(pt: Point, segmentType: SegmentType, score: Int, multiplier: Int) { val segment = factorySegmentForPoint(pt, Point(0, 0), 1000.0) val segmentStr = "" + segment @@ -202,27 +201,26 @@ class TestDartboardUtil : AbstractRegistryTest() } @Test - fun testResetCachedValues() - { + fun testResetCachedValues() { resetCachedDartboardValues() val pink = Color.pink - PreferenceUtil.saveString(PREFERENCES_STRING_EVEN_SINGLE_COLOUR, DartsColour.toPrefStr(pink)) + PreferenceUtil.saveString( + PREFERENCES_STRING_EVEN_SINGLE_COLOUR, + DartsColour.toPrefStr(pink) + ) assertSegment(Point(0, -629), SegmentType.OUTER_SINGLE, 20, 1) } @Test - fun testGetAdjacentNumbersSize() - { - for (i in 1..20) - { + fun testGetAdjacentNumbersSize() { + for (i in 1..20) { val adjacents = getAdjacentNumbers(i) adjacents.shouldHaveSize(2) } } @Test - fun testGetAdjacentNumbers() - { + fun testGetAdjacentNumbers() { val adjacentTo20 = getAdjacentNumbers(20) val adjacentTo3 = getAdjacentNumbers(3) val adjacentTo6 = getAdjacentNumbers(6) @@ -235,8 +233,7 @@ class TestDartboardUtil : AbstractRegistryTest() } @Test - fun `Should return all numbers within N segments`() - { + fun `Should return all numbers within N segments`() { getNumbersWithinN(20, 1).shouldContainExactly(5, 20, 1) getNumbersWithinN(20, 2).shouldContainExactly(12, 5, 20, 1, 18) getNumbersWithinN(20, 3).shouldContainExactly(9, 12, 5, 20, 1, 18, 4) @@ -245,8 +242,7 @@ class TestDartboardUtil : AbstractRegistryTest() } @Test - fun `Should return the right number of segments`() - { + fun `Should return the right number of segments`() { getAllPossibleSegments().size shouldBe (20 * 5) + 2 getAllNonMissSegments().size shouldBe (20 * 4) + 2 } diff --git a/src/test/kotlin/dartzee/utils/TestDartsColour.kt b/src/test/kotlin/dartzee/utils/TestDartsColour.kt index 12cc6d182..d9f5cd7a1 100644 --- a/src/test/kotlin/dartzee/utils/TestDartsColour.kt +++ b/src/test/kotlin/dartzee/utils/TestDartsColour.kt @@ -2,15 +2,13 @@ package dartzee.utils import dartzee.helper.AbstractTest import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.JLabel +import org.junit.jupiter.api.Test -class TestDartsColour: AbstractTest() -{ +class TestDartsColour : AbstractTest() { @Test - fun `Should return a darker version of the supplied colour`() - { + fun `Should return a darker version of the supplied colour`() { val c1 = Color(100, 100, 100) val c1Result = DartsColour.getDarkenedColour(c1) @@ -20,8 +18,7 @@ class TestDartsColour: AbstractTest() } @Test - fun `Should set the right fg and bg colours based on finishing position`() - { + fun `Should set the right fg and bg colours based on finishing position`() { val component = JLabel() DartsColour.setFgAndBgColoursForPosition(component, 1) @@ -49,4 +46,3 @@ class TestDartsColour: AbstractTest() component.background shouldBe null } } - diff --git a/src/test/kotlin/dartzee/utils/TestDartsDatabaseUtil.kt b/src/test/kotlin/dartzee/utils/TestDartsDatabaseUtil.kt index d934ca470..3f3f33f6e 100644 --- a/src/test/kotlin/dartzee/utils/TestDartsDatabaseUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestDartsDatabaseUtil.kt @@ -28,19 +28,17 @@ import io.kotest.matchers.file.shouldNotExist import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk +import java.io.File +import javax.swing.JOptionPane import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import java.io.File -import javax.swing.JOptionPane const val BACKUP_LOCATION = "Test/Backup/Databases" -class TestDartsDatabaseUtil: AbstractTest() -{ +class TestDartsDatabaseUtil : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { File(TEST_DB_DIRECTORY).deleteRecursively() File(BACKUP_LOCATION).deleteRecursively() @@ -50,25 +48,20 @@ class TestDartsDatabaseUtil: AbstractTest() } @AfterEach - fun afterEach() - { + fun afterEach() { File(TEST_ROOT).deleteRecursively() } @Test - fun `Should exit if DB version is too old`() - { + fun `Should exit if DB version is too old`() { val migrator = mockk(relaxed = true) every { migrator.migrateToLatest(any(), any()) } returns MigrationResult.TOO_OLD - assertExits(1) { - DartsDatabaseUtil.migrateDatabase(migrator, mainDatabase) - } + assertExits(1) { DartsDatabaseUtil.migrateDatabase(migrator, mainDatabase) } } @Test - fun `Should initialise a fresh database if no version is found`() - { + fun `Should initialise a fresh database if no version is found`() { clearLogs() usingInMemoryDatabase { db -> @@ -82,8 +75,7 @@ class TestDartsDatabaseUtil: AbstractTest() } @Test - fun `Should not back up any files if file selection cancelled`() - { + fun `Should not back up any files if file selection cancelled`() { dialogFactory.directoryToSelect = null DartsDatabaseUtil.backupCurrentDatabase() @@ -93,8 +85,7 @@ class TestDartsDatabaseUtil: AbstractTest() } @Test - fun `Should show an error if an error is thrown when copying the files`() - { + fun `Should show an error if an error is thrown when copying the files`() { File(TEST_DB_DIRECTORY).deleteRecursively() dialogFactory.directoryToSelect = File(TEST_DB_DIRECTORY) @@ -105,8 +96,7 @@ class TestDartsDatabaseUtil: AbstractTest() } @Test - fun `Should successfully back up files to the chosen destination`() - { + fun `Should successfully back up files to the chosen destination`() { val file = File("$TEST_DB_DIRECTORY/$DATABASE_NAME/File.txt") file.createNewFile() @@ -115,23 +105,25 @@ class TestDartsDatabaseUtil: AbstractTest() DartsDatabaseUtil.backupCurrentDatabase() - dialogFactory.infosShown.shouldContainExactly("Database successfully backed up to ${File("${selectedDir.absolutePath}/$DATABASE_NAME")}") + dialogFactory.infosShown.shouldContainExactly( + "Database successfully backed up to ${File("${selectedDir.absolutePath}/$DATABASE_NAME")}" + ) dialogFactory.errorsShown.shouldBeEmpty() File("${selectedDir.absolutePath}/$DATABASE_NAME/File.txt").shouldExist() } @Test - fun `Should abort the restore if there are open games`() - { + fun `Should abort the restore if there are open games`() { ScreenCache.addDartsGameScreen("foo", mockk()) DartsDatabaseUtil.restoreDatabase() - dialogFactory.errorsShown.shouldContainExactly("You must close all open games before continuing.") + dialogFactory.errorsShown.shouldContainExactly( + "You must close all open games before continuing." + ) } @Test - fun `Should not do a restore if file selection is cancelled`() - { + fun `Should not do a restore if file selection is cancelled`() { dialogFactory.directoryToSelect = null DartsDatabaseUtil.restoreDatabase() @@ -140,32 +132,33 @@ class TestDartsDatabaseUtil: AbstractTest() } @Test - fun `Should show an error and not do the restore if the selected folder has the wrong name`() - { + fun `Should show an error and not do the restore if the selected folder has the wrong name`() { dialogFactory.directoryToSelect = File(BACKUP_LOCATION) DartsDatabaseUtil.restoreDatabase() - dialogFactory.errorsShown.shouldContainExactly("Selected path is not valid - you must select a folder named '$DATABASE_NAME'") + dialogFactory.errorsShown.shouldContainExactly( + "Selected path is not valid - you must select a folder named '$DATABASE_NAME'" + ) } @Test - fun `Should show an error and tidy up if an exception is thrown during the copy`() - { + fun `Should show an error and tidy up if an exception is thrown during the copy`() { Database(DartsDatabaseUtil.OTHER_DATABASE_NAME).getDirectory().mkdirs() dialogFactory.directoryToSelect = File("$BACKUP_LOCATION/Darts") DartsDatabaseUtil.restoreDatabase() - dialogFactory.errorsShown.shouldContainExactly("There was a problem restoring the database.") + dialogFactory.errorsShown.shouldContainExactly( + "There was a problem restoring the database." + ) verifyLog(CODE_RESTORE_ERROR, Severity.ERROR) Database(DartsDatabaseUtil.OTHER_DATABASE_NAME).getDirectory().shouldNotExist() } @Test - fun `Should abort the restore if validation of the selected database fails`() - { + fun `Should abort the restore if validation of the selected database fails`() { val backupLocation = File("$BACKUP_LOCATION/Darts") backupLocation.mkdirs() @@ -175,23 +168,25 @@ class TestDartsDatabaseUtil: AbstractTest() verifyLog(CODE_TEST_CONNECTION_ERROR, Severity.ERROR) - dialogFactory.errorsShown.shouldContainExactly("An error occurred connecting to the selected database.") + dialogFactory.errorsShown.shouldContainExactly( + "An error occurred connecting to the selected database." + ) } @Test - fun `Should abort the restore if cancelled after validation succeeds`() - { + fun `Should abort the restore if cancelled after validation succeeds`() { usingInMemoryDatabase(withSchema = true) { db -> dialogFactory.questionOption = JOptionPane.NO_OPTION DartsDatabaseUtil.validateAndRestoreDatabase(db) - dialogFactory.questionsShown.shouldContainExactly("Successfully connected to target database.\n\nAre you sure you want to restore this database? All current data will be lost.") + dialogFactory.questionsShown.shouldContainExactly( + "Successfully connected to target database.\n\nAre you sure you want to restore this database? All current data will be lost." + ) dialogFactory.infosShown.shouldBeEmpty() } } @Test - fun `Should swap in the selected database if confirmed, and clear localId cache`() - { + fun `Should swap in the selected database if confirmed, and clear localId cache`() { usingInMemoryDatabase(withSchema = true) { db -> mainDatabase.generateLocalId(EntityName.Game) shouldBe 1L insertGame(localId = 5L) @@ -204,7 +199,9 @@ class TestDartsDatabaseUtil: AbstractTest() File("${InjectedThings.databaseDirectory}/Darts/SomeFile.txt").shouldExist() - dialogFactory.questionsShown.shouldContainExactly("Successfully connected to target database.\n\nAre you sure you want to restore this database? All current data will be lost.") + dialogFactory.questionsShown.shouldContainExactly( + "Successfully connected to target database.\n\nAre you sure you want to restore this database? All current data will be lost." + ) dialogFactory.infosShown.shouldContainExactly("Database restored successfully.") mainDatabase.generateLocalId(EntityName.Game) shouldBe 6L @@ -212,11 +209,11 @@ class TestDartsDatabaseUtil: AbstractTest() } @Test - fun `Should correctly list all entities`() - { + fun `Should correctly list all entities`() { val entityNameStatics = EntityName.values().toList() - val entityNames = DartsDatabaseUtil.getAllEntitiesIncludingVersion().map { it.getTableName() } + val entityNames = + DartsDatabaseUtil.getAllEntitiesIncludingVersion().map { it.getTableName() } entityNames.shouldContainExactlyInAnyOrder(entityNameStatics) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestDartzeeUtils.kt b/src/test/kotlin/dartzee/utils/TestDartzeeUtils.kt index e58f4a6a3..bbebf62e8 100644 --- a/src/test/kotlin/dartzee/utils/TestDartzeeUtils.kt +++ b/src/test/kotlin/dartzee/utils/TestDartzeeUtils.kt @@ -13,15 +13,13 @@ import dartzee.`object`.Dart import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Color import javax.swing.JButton +import org.junit.jupiter.api.Test -class TestDartzeeUtils: AbstractTest() -{ +class TestDartzeeUtils : AbstractTest() { @Test - fun `Should set the right colours based on dartzee result`() - { + fun `Should set the right colours based on dartzee result`() { val c = JButton() c.setColoursForDartzeeResult(true) @@ -34,8 +32,7 @@ class TestDartzeeUtils: AbstractTest() } @Test - fun `Should create a high score round result`() - { + fun `Should create a high score round result`() { val darts = listOf(Dart(20, 1), Dart(15, 2), Dart(3, 2)) val rr = factoryHighScoreResult(darts) @@ -45,8 +42,7 @@ class TestDartzeeUtils: AbstractTest() } @Test - fun `Should insert dartzee rules for a game`() - { + fun `Should insert dartzee rules for a game`() { val dtos = listOf(innerOuterInner, twoBlackOneWhite) val dtoDescs = dtos.map { it.generateRuleDescription() } @@ -55,19 +51,26 @@ class TestDartzeeUtils: AbstractTest() val entities = DartzeeRuleEntity().retrieveEntities("") - entities.map { it.toDto().generateRuleDescription() }.shouldContainExactlyInAnyOrder(*dtoDescs.toTypedArray()) + entities + .map { it.toDto().generateRuleDescription() } + .shouldContainExactlyInAnyOrder(*dtoDescs.toTypedArray()) entities.forEach { it.entityName shouldBe EntityName.Game it.entityId shouldBe game.rowId } - entities.filter { it.ordinal == 1 }.map { it.toDto().generateRuleDescription() }.shouldContainExactly(innerOuterInner.generateRuleDescription()) - entities.filter { it.ordinal == 2 }.map { it.toDto().generateRuleDescription() }.shouldContainExactly(twoBlackOneWhite.generateRuleDescription()) + entities + .filter { it.ordinal == 1 } + .map { it.toDto().generateRuleDescription() } + .shouldContainExactly(innerOuterInner.generateRuleDescription()) + entities + .filter { it.ordinal == 2 } + .map { it.toDto().generateRuleDescription() } + .shouldContainExactly(twoBlackOneWhite.generateRuleDescription()) } @Test - fun `Should do nothing if empty list of rules is passed`() - { + fun `Should do nothing if empty list of rules is passed`() { val game = insertGame() insertDartzeeRules(game.rowId) @@ -75,18 +78,21 @@ class TestDartzeeUtils: AbstractTest() } @Test - fun `Should save a dartzee template`() - { + fun `Should save a dartzee template`() { val dtos = listOf(innerOuterInner, twoBlackOneWhite) val template = saveDartzeeTemplate("Template", dtos) - val retrievedRuleDescriptions = DartzeeRuleEntity().retrieveForTemplate(template.rowId).map { it.toDto().generateRuleDescription() } - retrievedRuleDescriptions.shouldContainExactlyInAnyOrder(dtos.map { it.generateRuleDescription() }) + val retrievedRuleDescriptions = + DartzeeRuleEntity().retrieveForTemplate(template.rowId).map { + it.toDto().generateRuleDescription() + } + retrievedRuleDescriptions.shouldContainExactlyInAnyOrder( + dtos.map { it.generateRuleDescription() } + ) } @Test - fun `Should return null when generating a template if no name is entered`() - { + fun `Should return null when generating a template if no name is entered`() { dialogFactory.inputSelection = null val result = generateDartzeeTemplateFromGame(insertGame(), listOf()) @@ -95,8 +101,7 @@ class TestDartzeeUtils: AbstractTest() } @Test - fun `Should generate a template and update the game to point at it`() - { + fun `Should generate a template and update the game to point at it`() { dialogFactory.inputSelection = "My Template" val g = insertGame(gameType = GameType.DARTZEE, gameParams = "") @@ -107,8 +112,15 @@ class TestDartzeeUtils: AbstractTest() val retrievedGame = GameEntity().retrieveForId(g.rowId)!! retrievedGame.gameParams shouldBe result.rowId - val retrievedRuleDescriptions = DartzeeRuleEntity().retrieveForTemplate(result.rowId).map { it.toDto().generateRuleDescription() } - retrievedRuleDescriptions.shouldContainExactlyInAnyOrder(dtos.map { it.generateRuleDescription() }) - dialogFactory.infosShown.shouldContainExactly("Template 'My Template' successfully created.") + val retrievedRuleDescriptions = + DartzeeRuleEntity().retrieveForTemplate(result.rowId).map { + it.toDto().generateRuleDescription() + } + retrievedRuleDescriptions.shouldContainExactlyInAnyOrder( + dtos.map { it.generateRuleDescription() } + ) + dialogFactory.infosShown.shouldContainExactly( + "Template 'My Template' successfully created." + ) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestDatabase.kt b/src/test/kotlin/dartzee/utils/TestDatabase.kt index 9d0ddd6b1..001be5d31 100644 --- a/src/test/kotlin/dartzee/utils/TestDatabase.kt +++ b/src/test/kotlin/dartzee/utils/TestDatabase.kt @@ -21,46 +21,45 @@ import io.kotest.matchers.string.shouldContain import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -class TestDatabase: AbstractTest() -{ +class TestDatabase : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { mainDatabase.dropUnexpectedTables() } @Test - fun `Should create a new connection if the pool is depleted`() - { + fun `Should create a new connection if the pool is depleted`() { usingInMemoryDatabase { db -> db.initialiseConnectionPool(1) clearLogs() - //Should borrow from the pool when non-empty + // Should borrow from the pool when non-empty val conn = db.borrowConnection() verifyNoLogs(CODE_NEW_CONNECTION) - //Should create a new one now that there are none left + // Should create a new one now that there are none left val conn2 = db.borrowConnection() verifyLog(CODE_NEW_CONNECTION) db.returnConnection(conn2) db.returnConnection(conn) - //Should have returned the connection successfully + // Should have returned the connection successfully clearLogs() db.borrowConnection() verifyNoLogs(CODE_NEW_CONNECTION) } - } @Test - fun `Should execute all updates and log them to the console`() - { + fun `Should execute all updates and log them to the console`() { clearLogs() - val updates = listOf("CREATE TABLE zzUpdateTest(str VARCHAR(50))", "INSERT INTO zzUpdateTest VALUES ('5')") + val updates = + listOf( + "CREATE TABLE zzUpdateTest(str VARCHAR(50))", + "INSERT INTO zzUpdateTest VALUES ('5')" + ) mainDatabase.executeUpdates(updates) shouldBe true val records = flushAndGetLogRecords().filter { it.loggingCode == CODE_SQL } @@ -72,8 +71,7 @@ class TestDatabase: AbstractTest() } @Test - fun `Should abort if any updates fail`() - { + fun `Should abort if any updates fail`() { val updates = listOf("bollocks", "CREATE TABLE zzUpdateTest(str VARCHAR(50))") mainDatabase.executeUpdates(updates) shouldBe false @@ -83,8 +81,7 @@ class TestDatabase: AbstractTest() } @Test - fun `Should log SQLExceptions for failed updates`() - { + fun `Should log SQLExceptions for failed updates`() { val update = "CREATE TABLE zzUpdateTest(str INVALID(50))" mainDatabase.executeUpdate(update) shouldBe false @@ -94,18 +91,19 @@ class TestDatabase: AbstractTest() } @Test - fun `Should execute queries and log them to the console`() - { - val updates = listOf("CREATE TABLE zzQueryTest(str VARCHAR(50))", - "INSERT INTO zzQueryTest VALUES ('RowOne')", - "INSERT INTO zzQueryTest VALUES ('RowTwo')") + fun `Should execute queries and log them to the console`() { + val updates = + listOf( + "CREATE TABLE zzQueryTest(str VARCHAR(50))", + "INSERT INTO zzQueryTest VALUES ('RowOne')", + "INSERT INTO zzQueryTest VALUES ('RowTwo')" + ) mainDatabase.executeUpdates(updates) val retrievedValues = mutableListOf() mainDatabase.executeQuery("SELECT * FROM zzQueryTest").use { rs -> - while (rs.next()) - { + while (rs.next()) { retrievedValues.add(rs.getString(1)) } } @@ -118,21 +116,17 @@ class TestDatabase: AbstractTest() } @Test - fun `Should throw an error for failed queries`() - { + fun `Should throw an error for failed queries`() { val query = "SELECT * FROM zzQueryTest" - val ex = shouldThrow { - mainDatabase.executeQuery(query) - } + val ex = shouldThrow { mainDatabase.executeQuery(query) } ex.sqlStatement shouldBe query ex.sqlException.message shouldContain "does not exist" } @Test - fun `Should be possible to connect to separate databases concurrently`() - { + fun `Should be possible to connect to separate databases concurrently`() { usingInMemoryDatabase { dbOne -> usingInMemoryDatabase { dbTwo -> shouldNotThrowAny { @@ -144,14 +138,12 @@ class TestDatabase: AbstractTest() } @Test - fun `Should return null version if version has never been set`() - { + fun `Should return null version if version has never been set`() { mainDatabase.getDatabaseVersion() shouldBe null } @Test - fun `Should return the right existing version and support updating it`() - { + fun `Should return the right existing version and support updating it`() { mainDatabase.updateDatabaseVersion(5) mainDatabase.getDatabaseVersion() shouldBe 5 @@ -162,29 +154,29 @@ class TestDatabase: AbstractTest() } @Test - fun `Should support generating local IDs`() - { + fun `Should support generating local IDs`() { mainDatabase.generateLocalId(EntityName.Game) shouldBe 1 mainDatabase.generateLocalId(EntityName.Game) shouldBe 2 mainDatabase.generateLocalId(EntityName.DartsMatch) shouldBe 1 } @Test - fun `Should not drop any schema tables`() - { + fun `Should not drop any schema tables`() { mainDatabase.dropUnexpectedTables().shouldBeEmpty() - val expectedTableNames = DartsDatabaseUtil.getAllEntitiesIncludingVersion().map { it.getTableNameUpperCase() } + val expectedTableNames = + DartsDatabaseUtil.getAllEntitiesIncludingVersion().map { it.getTableNameUpperCase() } val tableNames = mainDatabase.getTableNames() tableNames.shouldContainExactlyInAnyOrder(expectedTableNames) } @Test - fun `Should drop unexpected tables`() - { + fun `Should drop unexpected tables`() { mainDatabase.createTableIfNotExists("SomeTable", "RowId INT") val tmpName = mainDatabase.createTempTable("TempTable", "RowId INT") - mainDatabase.dropUnexpectedTables().shouldContainExactlyInAnyOrder("SOMETABLE", tmpName?.uppercase()) + mainDatabase + .dropUnexpectedTables() + .shouldContainExactlyInAnyOrder("SOMETABLE", tmpName?.uppercase()) } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestDevUtilities.kt b/src/test/kotlin/dartzee/utils/TestDevUtilities.kt index b2733f3ae..70b4afcbc 100644 --- a/src/test/kotlin/dartzee/utils/TestDevUtilities.kt +++ b/src/test/kotlin/dartzee/utils/TestDevUtilities.kt @@ -40,11 +40,9 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import org.junit.jupiter.api.Test -class TestDevUtilities: AbstractTest() -{ +class TestDevUtilities : AbstractTest() { @Test - fun `Should show an error and return out if there are no games in the DB`() - { + fun `Should show an error and return out if there are no games in the DB`() { DevUtilities.purgeGame() dialogFactory.errorsShown.shouldContainExactly("No games to delete.") @@ -52,8 +50,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should not delete any games if info dialog is cancelled`() - { + fun `Should not delete any games if info dialog is cancelled`() { dialogFactory.inputSelection = null insertGame(localId = 1) @@ -66,8 +63,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should purge the game that was selected on the input dialog`() - { + fun `Should purge the game that was selected on the input dialog`() { insertGame(localId = 1) insertGame(localId = 2) @@ -86,8 +82,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should show an error for trying to delete a game that doesnt exist`() - { + fun `Should show an error for trying to delete a game that doesnt exist`() { insertGame(localId = 5) runAsync { DevUtilities.purgeGame(10) } @@ -99,8 +94,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should not delete a game which is open`() - { + fun `Should not delete a game which is open`() { val game = insertGame(localId = 5) ScreenCache.addDartsGameScreen(game.rowId, FakeDartsScreen()) @@ -114,8 +108,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should not delete a game if cancelled`() - { + fun `Should not delete a game if cancelled`() { insertGame(localId = 5) runAsync { DevUtilities.purgeGame(5) } @@ -128,8 +121,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should delete from X01Finish`() - { + fun `Should delete from X01Finish`() { val player = insertPlayer() val gameOne = insertFinishForPlayer(player, 25) val gameTwo = insertFinishForPlayer(player, 80) @@ -142,8 +134,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should delete the specified game, along with associated Participants and Darts`() - { + fun `Should delete the specified game, along with associated Participants and Darts`() { val g1 = insertGame(localId = 1) val g2 = insertGame(localId = 2) @@ -172,8 +163,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should delete teams associated with a game`() - { + fun `Should delete teams associated with a game`() { val players = preparePlayers(5) val gameA = insertGame() @@ -194,8 +184,7 @@ class TestDevUtilities: AbstractTest() } @Test - fun `Should purge Dartzee gubbins`() - { + fun `Should purge Dartzee gubbins`() { val player = insertPlayer() val g1 = insertGame() val g2 = insertGame() @@ -223,4 +212,4 @@ class TestDevUtilities: AbstractTest() val remainingResult = DartzeeRoundResultEntity().retrieveEntities().only() remainingResult.participantId shouldBe pt2.rowId } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestGameUtil.kt b/src/test/kotlin/dartzee/utils/TestGameUtil.kt index 9c7a5d4aa..daddbc542 100644 --- a/src/test/kotlin/dartzee/utils/TestGameUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestGameUtil.kt @@ -17,20 +17,18 @@ import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.junit.jupiter.api.Test -class TestGameUtil: AbstractTest() -{ +class TestGameUtil : AbstractTest() { @Test - fun `Filter panel mappings`() - { + fun `Filter panel mappings`() { getFilterPanel(GameType.X01).shouldBeInstanceOf() getFilterPanel(GameType.GOLF).shouldBeInstanceOf() - getFilterPanel(GameType.ROUND_THE_CLOCK).shouldBeInstanceOf() + getFilterPanel(GameType.ROUND_THE_CLOCK) + .shouldBeInstanceOf() getFilterPanel(GameType.DARTZEE).shouldBeInstanceOf() } @Test - fun `Does highest win`() - { + fun `Does highest win`() { doesHighestWin(GameType.X01) shouldBe false doesHighestWin(GameType.GOLF) shouldBe false doesHighestWin(GameType.ROUND_THE_CLOCK) shouldBe false @@ -38,8 +36,7 @@ class TestGameUtil: AbstractTest() } @Test - fun `Should save a finishing position of -1 if there is only one participant`() - { + fun `Should save a finishing position of -1 if there is only one participant`() { val pt = insertParticipant() setFinishingPositions(listOf(pt), insertGame()) @@ -48,8 +45,7 @@ class TestGameUtil: AbstractTest() } @Test - fun `Should correctly assign finishing positions when lowest wins`() - { + fun `Should correctly assign finishing positions when lowest wins`() { val pt = insertParticipant(finalScore = 25) val pt2 = insertParticipant(finalScore = 40) val pt3 = insertParticipant(finalScore = 55) @@ -62,8 +58,7 @@ class TestGameUtil: AbstractTest() } @Test - fun `Should correctly handle ties when lowest wins`() - { + fun `Should correctly handle ties when lowest wins`() { val pt = insertParticipant(finalScore = 25) val pt2 = insertParticipant(finalScore = 40) val pt3 = insertParticipant(finalScore = 55) @@ -78,8 +73,7 @@ class TestGameUtil: AbstractTest() } @Test - fun `Should correctly assign finishing positions when highest wins`() - { + fun `Should correctly assign finishing positions when highest wins`() { val pt = insertParticipant(finalScore = 25) val pt2 = insertParticipant(finalScore = 40) val pt3 = insertParticipant(finalScore = 55) @@ -92,8 +86,7 @@ class TestGameUtil: AbstractTest() } @Test - fun `Should correctly handle ties when highest wins`() - { + fun `Should correctly handle ties when highest wins`() { val pt = insertParticipant(finalScore = 25) val pt2 = insertParticipant(finalScore = 40) val pt3 = insertParticipant(finalScore = 55) @@ -108,8 +101,7 @@ class TestGameUtil: AbstractTest() } @Test - fun `Should save the finish positions to the database`() - { + fun `Should save the finish positions to the database`() { val pt = insertParticipant(finalScore = 25) val pt2 = insertParticipant(finalScore = 40) @@ -123,8 +115,7 @@ class TestGameUtil: AbstractTest() } @Test - fun `Should update the relevant total wins achievement for all winners`() - { + fun `Should update the relevant total wins achievement for all winners`() { val pt = insertParticipant(finalScore = 29) val pt2 = insertParticipant(finalScore = 29) val pt3 = insertParticipant(finalScore = 50) @@ -142,6 +133,7 @@ class TestGameUtil: AbstractTest() a2.gameIdEarned shouldBe game.rowId a2.achievementDetail shouldBe "29" - AchievementEntity.retrieveAchievement(AchievementType.GOLF_GAMES_WON, pt3.playerId) shouldBe null + AchievementEntity.retrieveAchievement(AchievementType.GOLF_GAMES_WON, pt3.playerId) shouldBe + null } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestGeometryUtil.kt b/src/test/kotlin/dartzee/utils/TestGeometryUtil.kt index 042b306b0..c3c3b0c94 100644 --- a/src/test/kotlin/dartzee/utils/TestGeometryUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestGeometryUtil.kt @@ -5,21 +5,18 @@ import io.kotest.matchers.doubles.shouldBeBetween import io.kotest.matchers.doubles.shouldBeGreaterThanOrEqual import io.kotest.matchers.doubles.shouldBeLessThanOrEqual import io.kotest.matchers.shouldBe -import org.junit.jupiter.api.Test import java.awt.Point +import org.junit.jupiter.api.Test /** * My first unit test. Woop! * - * 20/04/2018 - for posterity... - * 14/01/2019 - Now brought to you with Kotlin! - * 23/04/2019 - Class under test is now Kotlin, and this now uses Kotlintest - * */ -class TestGeometryUtil: AbstractTest() -{ + * 20/04/2018 - for posterity... 14/01/2019 - Now brought to you with Kotlin! 23/04/2019 - Class + * under test is now Kotlin, and this now uses Kotlintest + */ +class TestGeometryUtil : AbstractTest() { @Test - fun testTranslatePoint() - { + fun testTranslatePoint() { assertPointTranslation(5.0, 0.0, Point(0, -5)) assertPointTranslation(3.0, 90.0, Point(3, 0)) assertPointTranslation(-3.0, 90.0, Point(-3, 0)) @@ -31,14 +28,13 @@ class TestGeometryUtil: AbstractTest() assertPointTranslation(5.0, 126.87, Point(4, 3)) assertPointTranslation(5.0, 216.87, Point(-3, 4)) assertPointTranslation(5.0, 306.87, Point(-4, -3)) - assertPointTranslation(5.0, -53.13, Point(-4, -3)) + assertPointTranslation(5.0, -53.13, Point(-4, -3)) // Edge case. We'll mod the angle so we translate it as if it were 0 assertPointTranslation(100.0, 720.0, Point(0, -100)) } - private fun assertPointTranslation(radius: Double, degrees: Double, expected: Point) - { + private fun assertPointTranslation(radius: Double, degrees: Double, expected: Point) { val result = translatePoint(Point(0, 0), radius, degrees) result shouldBe expected } @@ -46,20 +42,14 @@ class TestGeometryUtil: AbstractTest() /** * Measures the angle like below: * - * | X - * | X - * |^^ X - * | X - * | X - * |X + * | X | X |^^ X | X | X |X * ------------------- */ @Test - fun testGetAngleForPoint() - { + fun testGetAngleForPoint() { val centerPt = Point(0, 0) - //Go around in 45 degree increments + // Go around in 45 degree increments assertAngle(Point(1, 0), centerPt, 90.0) assertAngle(Point(1, 1), centerPt, 45.0) assertAngle(Point(0, 1), centerPt, 0.0) @@ -69,39 +59,34 @@ class TestGeometryUtil: AbstractTest() assertAngle(Point(0, -1), centerPt, 180.0) assertAngle(Point(1, -1), centerPt, 135.0) - //Some inexact examples + // Some inexact examples assertAngle(Point(1, 2), centerPt, 26.565) assertAngle(Point(1, 5), centerPt, 11.310) } - private fun assertAngle(pt: Point, centerPt: Point, expected: Double) - { - //Because Java points are stupid, and so "increasing" y takes you downwards. - //We've passed in the intuitive value. Transform it to java in here. + private fun assertAngle(pt: Point, centerPt: Point, expected: Double) { + // Because Java points are stupid, and so "increasing" y takes you downwards. + // We've passed in the intuitive value. Transform it to java in here. pt.setLocation(pt.getX(), -pt.getY()) getAngleForPoint(pt, centerPt).shouldBeBetween(expected - 0.01, expected + 0.01, 0.0) } @Test - fun testGetAverage() - { + fun testGetAverage() { assertAverage(Point(0, 0), Point(0, 0)) assertAverage(Point(0, 0), Point(1, 0), Point(-1, 0)) assertAverage(Point(1, 1), Point(0, 0), Point(0, 2), Point(2, 0), Point(2, 2)) } - private fun assertAverage(expected: Point, vararg points: Point) - { + private fun assertAverage(expected: Point, vararg points: Point) { val list = points.toSet() getAverage(list) shouldBe expected } @Test - fun testGenerateRandomAngle() - { - repeat(999) - { + fun testGenerateRandomAngle() { + repeat(999) { val angle = generateRandomAngle() angle.shouldBeGreaterThanOrEqual(0.0) angle.shouldBeLessThanOrEqual(360.0) diff --git a/src/test/kotlin/dartzee/utils/TestPlayerImageUtils.kt b/src/test/kotlin/dartzee/utils/TestPlayerImageUtils.kt index f8ef7dd1a..e5919a37d 100644 --- a/src/test/kotlin/dartzee/utils/TestPlayerImageUtils.kt +++ b/src/test/kotlin/dartzee/utils/TestPlayerImageUtils.kt @@ -6,18 +6,16 @@ import dartzee.db.PlayerEntity import dartzee.helper.AbstractTest import dartzee.helper.insertPlayer import dartzee.helper.insertPlayerImage -import org.junit.jupiter.api.Tag -import org.junit.jupiter.api.Test import java.awt.Dimension import javax.swing.ImageIcon import javax.swing.JLabel +import org.junit.jupiter.api.Tag +import org.junit.jupiter.api.Test -class TestPlayerImageUtils : AbstractTest() -{ +class TestPlayerImageUtils : AbstractTest() { @Test @Tag("screenshot") - fun `Should match screenshot - 50-50 split, inactive`() - { + fun `Should match screenshot - 50-50 split, inactive`() { val (p1, p2) = setUpPlayers() val result = splitAvatar(p1, p2, null, false) @@ -29,8 +27,7 @@ class TestPlayerImageUtils : AbstractTest() @Test @Tag("screenshot") - fun `Should match screenshot - game over`() - { + fun `Should match screenshot - game over`() { val (p1, p2) = setUpPlayers() val result = splitAvatar(p1, p2, null, true) @@ -42,8 +39,7 @@ class TestPlayerImageUtils : AbstractTest() @Test @Tag("screenshot") - fun `Should match screenshot - game over with player selected`() - { + fun `Should match screenshot - game over with player selected`() { val (p1, p2) = setUpPlayers() val result = splitAvatar(p1, p2, p1, true) @@ -55,8 +51,7 @@ class TestPlayerImageUtils : AbstractTest() @Test @Tag("screenshot") - fun `Should match screenshot - player one selected`() - { + fun `Should match screenshot - player one selected`() { val (p1, p2) = setUpPlayers() val result = splitAvatar(p1, p2, p1, false) @@ -68,8 +63,7 @@ class TestPlayerImageUtils : AbstractTest() @Test @Tag("screenshot") - fun `Should match screenshot - player two selected`() - { + fun `Should match screenshot - player two selected`() { val (p1, p2) = setUpPlayers() val result = splitAvatar(p1, p2, p2, false) @@ -81,8 +75,7 @@ class TestPlayerImageUtils : AbstractTest() @Test @Tag("screenshot") - fun `Should crop and scale an image to avatar dimensions`() - { + fun `Should crop and scale an image to avatar dimensions`() { val bytes = FileUtil.getByteArrayForResource("/outer-wilds.jpeg")!! val result = convertImageToAvatarDimensions(bytes) @@ -92,8 +85,7 @@ class TestPlayerImageUtils : AbstractTest() label.shouldMatchImage("outer-wilds-avatar") } - private fun setUpPlayers(): Pair - { + private fun setUpPlayers(): Pair { val imgOne = insertPlayerImage(resource = "Sid") val imgTwo = insertPlayerImage(resource = "Minion") val playerOne = insertPlayer(playerImageId = imgOne.rowId) @@ -101,4 +93,4 @@ class TestPlayerImageUtils : AbstractTest() return playerOne to playerTwo } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestPreferenceUtil.kt b/src/test/kotlin/dartzee/utils/TestPreferenceUtil.kt index 68e5483ab..88484de78 100644 --- a/src/test/kotlin/dartzee/utils/TestPreferenceUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestPreferenceUtil.kt @@ -10,11 +10,9 @@ private const val INT_PREF = "FAKE_INT;20" private const val DOUBLE_PREF = "FAKE_DOUBLE;2.7" private const val BOOLEAN_PREF = "FAKE_BOOLEAN;false" -class TestPreferenceUtil: AbstractTest() -{ +class TestPreferenceUtil : AbstractTest() { @AfterEach - fun afterEach() - { + fun afterEach() { PreferenceUtil.deleteSetting(STRING_PREF) PreferenceUtil.deleteSetting(INT_PREF) PreferenceUtil.deleteSetting(DOUBLE_PREF) @@ -22,8 +20,7 @@ class TestPreferenceUtil: AbstractTest() } @Test - fun `Getting and setting Strings`() - { + fun `Getting and setting Strings`() { PreferenceUtil.getStringValue(STRING_PREF) shouldBe "foo" PreferenceUtil.saveString(STRING_PREF, "newValue") @@ -33,8 +30,7 @@ class TestPreferenceUtil: AbstractTest() } @Test - fun `Getting and setting Ints`() - { + fun `Getting and setting Ints`() { PreferenceUtil.getIntValue(INT_PREF) shouldBe 20 PreferenceUtil.saveInt(INT_PREF, 50) @@ -44,8 +40,7 @@ class TestPreferenceUtil: AbstractTest() } @Test - fun `Getting and setting Doubles`() - { + fun `Getting and setting Doubles`() { PreferenceUtil.getDoubleValue(DOUBLE_PREF) shouldBe 2.7 PreferenceUtil.saveDouble(DOUBLE_PREF, 5.4) @@ -55,8 +50,7 @@ class TestPreferenceUtil: AbstractTest() } @Test - fun `Getting and setting Booleans`() - { + fun `Getting and setting Booleans`() { PreferenceUtil.getBooleanValue(BOOLEAN_PREF) shouldBe false PreferenceUtil.saveBoolean(BOOLEAN_PREF, true) @@ -64,4 +58,4 @@ class TestPreferenceUtil: AbstractTest() PreferenceUtil.getBooleanValue(BOOLEAN_PREF) shouldBe true PreferenceUtil.getBooleanValue(BOOLEAN_PREF, true) shouldBe false } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestResourceCache.kt b/src/test/kotlin/dartzee/utils/TestResourceCache.kt index 9de21984c..a988e8629 100644 --- a/src/test/kotlin/dartzee/utils/TestResourceCache.kt +++ b/src/test/kotlin/dartzee/utils/TestResourceCache.kt @@ -6,36 +6,31 @@ import dartzee.logging.Severity import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNotBe +import java.io.BufferedReader +import java.io.InputStreamReader import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test -import java.io.BufferedReader -import java.io.InputStreamReader -class TestResourceCache : AbstractTest() -{ +class TestResourceCache : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { ResourceCache.resetCache() } @AfterEach - fun afterEach() - { + fun afterEach() { ResourceCache.resetCache() } @Test - fun `Should pre-load all the WAVs in the appropriate resource directory`() - { + fun `Should pre-load all the WAVs in the appropriate resource directory`() { val resources = mutableListOf() javaClass.getResourceAsStream("/wav").use { stream -> BufferedReader(InputStreamReader(stream)).use { br -> var resource = br.readLine() - while (resource != null) - { + while (resource != null) { resources.add(resource) resource = br.readLine() } @@ -51,8 +46,7 @@ class TestResourceCache : AbstractTest() } @Test - fun `Should pre-load 3 instances of each WAV`() - { + fun `Should pre-load 3 instances of each WAV`() { ResourceCache.initialiseResources() ResourceCache.borrowInputStream("100") shouldNotBe null @@ -66,15 +60,14 @@ class TestResourceCache : AbstractTest() } @Test - fun `Should re-use WAVs that are returned to the pool`() - { + fun `Should re-use WAVs that are returned to the pool`() { ResourceCache.initialiseResources() val wav1 = ResourceCache.borrowInputStream("100")!! ResourceCache.borrowInputStream("100") ResourceCache.borrowInputStream("100") - //Return one and borrow again, check we get the same instance + // Return one and borrow again, check we get the same instance ResourceCache.returnInputStream("100", wav1) val newWav = ResourceCache.borrowInputStream("100") newWav shouldBe wav1 @@ -83,19 +76,16 @@ class TestResourceCache : AbstractTest() } @Test - fun `Should show a loading dialog whilst initialising`() - { + fun `Should show a loading dialog whilst initialising`() { ResourceCache.initialiseResources() dialogFactory.loadingsShown.shouldContainExactly("Loading resources...") } @Test - fun `Should return null for a resource that isn't in the cache`() - { + fun `Should return null for a resource that isn't in the cache`() { ResourceCache.initialiseResources() ResourceCache.borrowInputStream("50") shouldBe null } - -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestRoundTheClockUtil.kt b/src/test/kotlin/dartzee/utils/TestRoundTheClockUtil.kt index 01cabd55e..c9b7d1de2 100644 --- a/src/test/kotlin/dartzee/utils/TestRoundTheClockUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestRoundTheClockUtil.kt @@ -1,34 +1,32 @@ package dartzee.utils -import dartzee.`object`.Dart import dartzee.game.ClockType import dartzee.helper.AbstractTest import dartzee.helper.factoryClockHit import dartzee.helper.randomGuid +import dartzee.`object`.Dart import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestRoundTheClockUtil: AbstractTest() -{ +class TestRoundTheClockUtil : AbstractTest() { @Test - fun `getLongestStreak should return 0 for an empty list`() - { + fun `getLongestStreak should return 0 for an empty list`() { getLongestStreak(listOf()).shouldBeEmpty() } @Test - fun `getLongestStreak should take into account the game params`() - { + fun `getLongestStreak should take into account the game params`() { getLongestStreak(listOf(factoryClockHit(1, 1)), ClockType.Doubles) shouldHaveSize 0 getLongestStreak(listOf(factoryClockHit(1, 2)), ClockType.Doubles) shouldHaveSize 1 } @Test - fun `getLongestStreak should find the longest streak if multiple`() - { - val darts = listOf(factoryClockHit(1), + fun `getLongestStreak should find the longest streak if multiple`() { + val darts = + listOf( + factoryClockHit(1), factoryClockHit(2), Dart(0, 0), factoryClockHit(3), @@ -36,42 +34,44 @@ class TestRoundTheClockUtil: AbstractTest() factoryClockHit(5), Dart(0, 0), factoryClockHit(6), - factoryClockHit(7)) + factoryClockHit(7) + ) val streak = getLongestStreak(darts) streak shouldHaveSize 3 - streak.joinToString{ it.format() } shouldBe "3, 4, 5" + streak.joinToString { it.format() } shouldBe "3, 4, 5" } @Test - fun `Should return the first instance if multiple longest streaks`() - { - val darts = listOf(factoryClockHit(1), + fun `Should return the first instance if multiple longest streaks`() { + val darts = + listOf( + factoryClockHit(1), factoryClockHit(2), Dart(0, 0), factoryClockHit(3), factoryClockHit(4), Dart(20, 1), factoryClockHit(6), - factoryClockHit(7)) + factoryClockHit(7) + ) val streak = getLongestStreak(darts) streak shouldHaveSize 2 - streak.joinToString{ it.format() } shouldBe "1, 2" + streak.joinToString { it.format() } shouldBe "1, 2" } @Test - fun `Should partition by participant`() - { + fun `Should partition by participant`() { val firstDarts = listOf(factoryClockHit(1), factoryClockHit(2)) val secondDarts = listOf(factoryClockHit(1), factoryClockHit(2), factoryClockHit(3)) val ptOne = randomGuid() val ptTwo = randomGuid() - firstDarts.forEach{ it.participantId = ptOne } - secondDarts.forEach{ it.participantId = ptTwo } + firstDarts.forEach { it.participantId = ptOne } + secondDarts.forEach { it.participantId = ptTwo } val streak = getLongestStreak(firstDarts + secondDarts) streak shouldHaveSize 3 } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestSqlUtil.kt b/src/test/kotlin/dartzee/utils/TestSqlUtil.kt index 8430f6fad..8f859811c 100644 --- a/src/test/kotlin/dartzee/utils/TestSqlUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestSqlUtil.kt @@ -5,18 +5,15 @@ import dartzee.helper.insertParticipant import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestSqlUtil: AbstractTest() -{ +class TestSqlUtil : AbstractTest() { @Test - fun `Should get quoted ID strings`() - { + fun `Should get quoted ID strings`() { val list = listOf("foo", "bar") list.getQuotedIdStr() shouldBe "('foo', 'bar')" } @Test - fun `Should get correct quoted ID strings of objects`() - { + fun `Should get correct quoted ID strings of objects`() { val ptOne = insertParticipant(uuid = "foo", playerId = "playerA") val ptTwo = insertParticipant(uuid = "bar", playerId = "playerB") @@ -26,4 +23,4 @@ class TestSqlUtil: AbstractTest() listOf(ptOne).getQuotedIdStr { it.rowId } shouldBe "('foo')" } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestUpdateManager.kt b/src/test/kotlin/dartzee/utils/TestUpdateManager.kt index 016e95a26..a98bc654e 100644 --- a/src/test/kotlin/dartzee/utils/TestUpdateManager.kt +++ b/src/test/kotlin/dartzee/utils/TestUpdateManager.kt @@ -32,6 +32,10 @@ import io.kotest.matchers.string.shouldStartWith import io.kotest.matchers.types.shouldBeInstanceOf import io.mockk.every import io.mockk.mockk +import java.io.File +import java.io.IOException +import java.util.concurrent.atomic.AtomicBoolean +import javax.swing.SwingUtilities import kong.unirest.Unirest import kong.unirest.UnirestException import kong.unirest.json.JSONException @@ -39,29 +43,21 @@ import kong.unirest.json.JSONObject import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Tag import org.junit.jupiter.api.Test -import java.io.File -import java.io.IOException -import java.util.concurrent.atomic.AtomicBoolean -import javax.swing.SwingUtilities -class TestUpdateManager: AbstractTest() -{ +class TestUpdateManager : AbstractTest() { @BeforeEach - fun beforeEach() - { + fun beforeEach() { Unirest.config().reset() Unirest.config().connectTimeout(2000) Unirest.config().socketTimeout(2000) } - /** - * Communication - */ + /** Communication */ @Test @Tag("integration") - fun `Should log out an unexpected HTTP response, along with the full JSON payload`() - { - val errorMessage = queryLatestReleastJsonExpectingError("https://api.github.com/repos/alyssaburlton/foo") + fun `Should log out an unexpected HTTP response, along with the full JSON payload`() { + val errorMessage = + queryLatestReleastJsonExpectingError("https://api.github.com/repos/alyssaburlton/foo") errorMessage shouldBe "Failed to check for updates (unable to connect)." val log = verifyLog(CODE_UPDATE_ERROR, Severity.ERROR) @@ -73,8 +69,7 @@ class TestUpdateManager: AbstractTest() @Test @Tag("integration") - fun `Should catch and log any exceptions communicating over HTTPS`() - { + fun `Should catch and log any exceptions communicating over HTTPS`() { Unirest.config().connectTimeout(100) Unirest.config().socketTimeout(100) @@ -102,8 +97,7 @@ class TestUpdateManager: AbstractTest() @Test @Tag("integration") - fun `Should retrieve a valid latest asset from the remote repo`() - { + fun `Should retrieve a valid latest asset from the remote repo`() { val responseJson = UpdateManager.queryLatestReleaseJson(DARTZEE_REPOSITORY_URL)!! val version = responseJson.getString("tag_name") @@ -117,13 +111,11 @@ class TestUpdateManager: AbstractTest() asset.getLong("size") shouldNotBe null } - /** - * Parsing - */ + /** Parsing */ @Test - fun `Should parse correctly formed JSON`() - { - val json = """{ + fun `Should parse correctly formed JSON`() { + val json = + """{ "tag_name": "foo", "assets": [ { @@ -142,8 +134,7 @@ class TestUpdateManager: AbstractTest() } @Test - fun `Should log an error if no tag_name is present`() - { + fun `Should log an error if no tag_name is present`() { val json = "{\"other_tag\":\"foo\"}" val metadata = UpdateManager.parseUpdateMetadata(JSONObject(json)) metadata shouldBe null @@ -154,8 +145,7 @@ class TestUpdateManager: AbstractTest() } @Test - fun `Should log an error if no assets are found`() - { + fun `Should log an error if no assets are found`() { val json = """{"assets":[],"tag_name":"foo"}""" val metadata = UpdateManager.parseUpdateMetadata(JSONObject(json)) metadata shouldBe null @@ -165,12 +155,9 @@ class TestUpdateManager: AbstractTest() log.keyValuePairs[KEY_RESPONSE_BODY].toString() shouldBe json } - /** - * Should update? - */ + /** Should update? */ @Test - fun `Should not proceed with the update if the versions match`() - { + fun `Should not proceed with the update if the versions match`() { val metadata = UpdateMetadata(DARTS_VERSION_NUMBER, 123456, "Dartzee_x_y.jar", 100) UpdateManager.shouldUpdate(DARTS_VERSION_NUMBER, metadata) shouldBe false @@ -179,8 +166,7 @@ class TestUpdateManager: AbstractTest() } @Test - fun `Should show an info and not proceed to auto update if OS is not windows`() - { + fun `Should show an info and not proceed to auto update if OS is not windows`() { DartsClient.operatingSystem = "foo" val metadata = UpdateMetadata("v100", 123456, "Dartzee_x_y.jar", 100) @@ -195,15 +181,15 @@ class TestUpdateManager: AbstractTest() } @Test - fun `Should not proceed with the update if user selects 'No'`() - { + fun `Should not proceed with the update if user selects 'No'`() { DartsClient.operatingSystem = "windows" val metadata = UpdateMetadata("foo", 123456, "Dartzee_x_y.jar", 100) val result = shouldUpdateAsync("bar", metadata) val question = getQuestionDialog() - question.getDialogMessage() shouldBe "An update is available (foo). Would you like to download it now?" + question.getDialogMessage() shouldBe + "An update is available (foo). Would you like to download it now?" question.clickNo() flushEdt() @@ -211,23 +197,22 @@ class TestUpdateManager: AbstractTest() } @Test - fun `Should proceed with the update if user selects 'Yes'`() - { + fun `Should proceed with the update if user selects 'Yes'`() { DartsClient.operatingSystem = "windows" val metadata = UpdateMetadata("foo", 123456, "Dartzee_x_y.jar", 100) val result = shouldUpdateAsync("bar", metadata) val question = getQuestionDialog() - question.getDialogMessage() shouldBe "An update is available (foo). Would you like to download it now?" + question.getDialogMessage() shouldBe + "An update is available (foo). Would you like to download it now?" question.clickYes() flushEdt() result.get() shouldBe true } - private fun shouldUpdateAsync(currentVersion: String, metadata: UpdateMetadata): AtomicBoolean - { + private fun shouldUpdateAsync(currentVersion: String, metadata: UpdateMetadata): AtomicBoolean { val result = AtomicBoolean(false) SwingUtilities.invokeLater { result.set(UpdateManager.shouldUpdate(currentVersion, metadata)) @@ -237,12 +222,9 @@ class TestUpdateManager: AbstractTest() return result } - /** - * Prepare batch file - */ + /** Prepare batch file */ @Test - fun `Should overwrite existing batch file with the correct contents`() - { + fun `Should overwrite existing batch file with the correct contents`() { val updateFile = File("update.bat") updateFile.writeText("blah") @@ -252,36 +234,27 @@ class TestUpdateManager: AbstractTest() updateFile.delete() } - /** - * Run update - */ + /** Run update */ @Test - fun `Should log an error and not exit if batch file goes wrong`() - { + fun `Should log an error and not exit if batch file goes wrong`() { val runtime = mockk() val error = IOException("Argh") every { runtime.exec(any()) } throws error - runAsync { - assertDoesNotExit { - UpdateManager.startUpdate("foo", runtime) - } - } + runAsync { assertDoesNotExit { UpdateManager.startUpdate("foo", runtime) } } val errorDialog = getErrorDialog() - errorDialog.getDialogMessage() shouldBe "Failed to launch update.bat - call the following manually to perform the update: \n\nupdate.bat foo" + errorDialog.getDialogMessage() shouldBe + "Failed to launch update.bat - call the following manually to perform the update: \n\nupdate.bat foo" val log = verifyLog(CODE_BATCH_ERROR, Severity.ERROR) log.errorObject shouldBe error } @Test - fun `Should exit normally if batch file succeeds`() - { + fun `Should exit normally if batch file succeeds`() { val runtime = mockk(relaxed = true) - assertExits(0) { - UpdateManager.startUpdate("foo", runtime) - } + assertExits(0) { UpdateManager.startUpdate("foo", runtime) } } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestUrlUtil.kt b/src/test/kotlin/dartzee/utils/TestUrlUtil.kt index 80e6a7e4e..cb16255e3 100644 --- a/src/test/kotlin/dartzee/utils/TestUrlUtil.kt +++ b/src/test/kotlin/dartzee/utils/TestUrlUtil.kt @@ -7,14 +7,12 @@ import io.kotest.matchers.shouldBe import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.junit.jupiter.api.Test import java.io.IOException +import org.junit.jupiter.api.Test -class TestUrlUtil: AbstractTest() -{ +class TestUrlUtil : AbstractTest() { @Test - fun `Should execute the expected command`() - { + fun `Should execute the expected command`() { val runtime = mockk(relaxed = true) launchUrl("foo.bar", runtime) @@ -22,8 +20,7 @@ class TestUrlUtil: AbstractTest() } @Test - fun `Should log an appropriate error if launching the URL fails`() - { + fun `Should log an appropriate error if launching the URL fails`() { val error = IOException("Oops") val runtime = mockk() @@ -35,4 +32,4 @@ class TestUrlUtil: AbstractTest() log.message shouldBe "Failed to launch foo.bar" log.errorObject shouldBe error } -} \ No newline at end of file +} diff --git a/src/test/kotlin/dartzee/utils/TestX01Util.kt b/src/test/kotlin/dartzee/utils/TestX01Util.kt index ed002cca9..83930f361 100644 --- a/src/test/kotlin/dartzee/utils/TestX01Util.kt +++ b/src/test/kotlin/dartzee/utils/TestX01Util.kt @@ -13,11 +13,9 @@ import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test -class TestX01Util: AbstractTest() -{ +class TestX01Util : AbstractTest() { @Test - fun `isBust should return the right values when just passed a dart`() - { + fun `isBust should return the right values when just passed a dart`() { isBust(makeDart(3, 1, startingScore = 5)) shouldBe false isBust(makeDart(3, 1, startingScore = 4)) shouldBe true isBust(makeDart(3, 1, startingScore = 3)) shouldBe true @@ -28,8 +26,7 @@ class TestX01Util: AbstractTest() } @Test - fun testIsBust() - { + fun testIsBust() { isBust(5, Dart(3, 2)).shouldBeTrue() isBust(10, Dart(10, 1)).shouldBeTrue() isBust(60, Dart(20, 3)).shouldBeTrue() @@ -44,8 +41,7 @@ class TestX01Util: AbstractTest() } @Test - fun testShouldStopForMercyRule() - { + fun testShouldStopForMercyRule() { var model = makeDartsModel(mercyThreshold = 19) shouldStopForMercyRule(model, 19, 16).shouldBeFalse() @@ -66,8 +62,7 @@ class TestX01Util: AbstractTest() } @Test - fun testIsCheckoutDart() - { + fun testIsCheckoutDart() { assertCheckout(52, false) assertCheckout(50, true) assertCheckout(45, false) @@ -78,8 +73,7 @@ class TestX01Util: AbstractTest() assertCheckout(2, true) } - private fun assertCheckout(startingScore: Int, expected: Boolean) - { + private fun assertCheckout(startingScore: Int, expected: Boolean) { val drt = Dart(20, 2) drt.startingScore = startingScore @@ -87,24 +81,21 @@ class TestX01Util: AbstractTest() } @Test - fun testIsFinishRound() - { + fun testIsFinishRound() { isFinishRound(listOf(Dart(2, 1), makeDart(20, 1, startingScore = 20))).shouldBeFalse() isFinishRound(listOf(Dart(2, 1), makeDart(20, 2, startingScore = 20))).shouldBeFalse() isFinishRound(listOf(Dart(2, 1), makeDart(10, 2, startingScore = 20))).shouldBeTrue() } @Test - fun testGetScoringDartsNull() - { + fun testGetScoringDartsNull() { val result = getScoringDarts(null, 20) result.shouldBeEmpty() } @Test - fun testGetScoringDarts() - { + fun testGetScoringDarts() { val d1 = makeDart(1, 1, startingScore = 51) val d2 = makeDart(1, 1, startingScore = 50) val d3 = makeDart(20, 1, startingScore = 49) @@ -116,11 +107,10 @@ class TestX01Util: AbstractTest() } @Test - fun `getScoringRounds should exclude rounds correctly`() - { + fun `getScoringRounds should exclude rounds correctly`() { val round1 = listOf(Dart(20, 3), Dart(20, 1), Dart(5, 1)) // 115 val round2 = listOf(Dart(20, 1), Dart(20, 1), Dart(1, 1)) // 74 - val round3 = listOf(Dart(9, 1), Dart(14, 1), Dart(1, 1)) // 50 + val round3 = listOf(Dart(9, 1), Dart(14, 1), Dart(1, 1)) // 50 val rounds = makeX01Rounds(200, round1, round2, round3) getScoringRounds(rounds, 200).shouldBeEmpty() @@ -131,8 +121,7 @@ class TestX01Util: AbstractTest() } @Test - fun testCalculateThreeDartAverage() - { + fun testCalculateThreeDartAverage() { val d1 = makeDart(20, 1, startingScore = 100) val d2 = makeDart(20, 2, startingScore = 100) val d3 = makeDart(10, 0, startingScore = 80) @@ -140,8 +129,8 @@ class TestX01Util: AbstractTest() val list = listOf(d1, d2, d3, d4) val result = calculateThreeDartAverage(list, 70) - val resultTwo = calculateThreeDartAverage(list, 90) //The miss should be excluded - val resultThree = calculateThreeDartAverage(list, 200) //Test an empty list + val resultTwo = calculateThreeDartAverage(list, 90) // The miss should be excluded + val resultThree = calculateThreeDartAverage(list, 200) // Test an empty list result shouldBe 56.25 resultTwo shouldBe 75.0 @@ -149,8 +138,7 @@ class TestX01Util: AbstractTest() } @Test - fun testSumScore() - { + fun testSumScore() { val d1 = Dart(20, 2) val d2 = Dart(13, 0) val d3 = Dart(11, 1) @@ -161,8 +149,7 @@ class TestX01Util: AbstractTest() } @Test - fun testIsShanghai() - { + fun testIsShanghai() { val tooShort = mutableListOf(Dart(20, 3), Dart(20, 3)) val miss = mutableListOf(Dart(20, 3), Dart(20, 3), Dart(20, 0)) val wrongSum = mutableListOf(Dart(20, 1), Dart(20, 3), Dart(20, 3)) @@ -180,8 +167,7 @@ class TestX01Util: AbstractTest() } @Test - fun testGetSortedDartStr() - { + fun testGetSortedDartStr() { val listOne = mutableListOf(Dart(2, 3), Dart(3, 2), Dart(20, 1)) val listTwo = mutableListOf(Dart(1, 1), Dart(7, 1), Dart(5, 1)) val listThree = mutableListOf(Dart(20, 3), Dart(20, 3), Dart(20, 3)) @@ -194,8 +180,7 @@ class TestX01Util: AbstractTest() } @Test - fun testIsNearMissDouble() - { + fun testIsNearMissDouble() { val nonCheckoutDart = Dart(16, 2) nonCheckoutDart.startingScore = 48 @@ -226,4 +211,4 @@ class TestX01Util: AbstractTest() isNearMissDouble(nonDoubleDoubleTop).shouldBeFalse() isNearMissDouble(nearMissDoubleTop).shouldBeTrue() } -} \ No newline at end of file +}