diff --git a/.scalafmt.conf b/.scalafmt.conf index ca34726ad9..7b8e7ce668 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,12 +1,41 @@ version = "3.9.9" runner.dialect = scala3 rewrite.scala3.convertToNewSyntax = true +# Keep braces, don't use significant indentation # rewrite.scala3.removeOptionalBraces = yes rewrite.scala3.insertEndMarkerMinLines = 15 rewrite.scala3.removeEndMarkerMaxLines = 14 +# Strip margin settings +assumeStandardLibraryStripMargin = false +align.stripMargin = true + +# Code Style & Formatting +align.preset = more +align.multiline = true +align.arrowEnumeratorGenerator = true +spaces.inImportCurlyBraces = false +spaces.beforeContextBoundColon = Never +maxColumn = 120 +docstrings.style = Asterisk +docstrings.wrap = yes + +# Method chaining +newlines.beforeCurlyLambdaParams = multilineWithCaseOnly +optIn.breakChainOnFirstMethodDot = true +includeCurlyBraceInSelectChains = false + +# Advanced Scala 3 Features +rewrite.scala3.countEndMarkerLines = all +rewrite.redundantBraces.stringInterpolation = true +rewrite.redundantBraces.parensForOneLineApply = true + +# Project-Specific Considerations +optIn.annotationNewlines = true +runner.optimizer.forceConfigStyleMinArgCount = 3 + # Import sorting configuration -rewrite.rules = [SortImports] +rewrite.rules = [SortImports, RedundantBraces, RedundantParens] rewrite.imports.sort = scalastyle rewrite.imports.groups = [ ["java\\..*"], diff --git a/src/main/scala/net/eagle0/common/FunctionalRandom.scala b/src/main/scala/net/eagle0/common/FunctionalRandom.scala index 703fdf77d5..c4d552ef2f 100644 --- a/src/main/scala/net/eagle0/common/FunctionalRandom.scala +++ b/src/main/scala/net/eagle0/common/FunctionalRandom.scala @@ -7,7 +7,7 @@ case class RandomState[+T]( newValue: T, nextRandom: FunctionalRandom ) { - def map[U](f: T => U): RandomState[U] = RandomState(f(newValue), nextRandom) + def map[U](f: T => U): RandomState[U] = RandomState(f(newValue), nextRandom) def continue[U](f: (T, FunctionalRandom) => RandomState[U]): RandomState[U] = f(newValue, nextRandom) @@ -62,10 +62,9 @@ abstract class FunctionalRandom { else ni.nextRandom.nextInt(atLeast = atLeast, lessThan = lessThan) } else { val diff = lessThan - atLeast - val max = (Int.MaxValue / diff) * diff - val np = nextPositiveInt - if np.newValue > max then - np.nextRandom.nextInt(atLeast = atLeast, lessThan = lessThan) + val max = (Int.MaxValue / diff) * diff + val np = nextPositiveInt + if np.newValue > max then np.nextRandom.nextInt(atLeast = atLeast, lessThan = lessThan) else RandomState(np.newValue % diff + atLeast, np.nextRandom) } } @@ -106,7 +105,7 @@ abstract class FunctionalRandom { nextItems[Double](count, _.nextDouble) def nextPositiveInt: RandomState[Int] = { - val ni = nextInt + val ni = nextInt val nonNegative = if ni.newValue < 0 then -(ni.newValue + 1) else ni.newValue @@ -127,12 +126,11 @@ abstract class FunctionalRandom { shuffledHead: Vector[T], unshuffledTail: Vector[T], fr: FunctionalRandom - ): RandomState[Vector[T]] = { + ): RandomState[Vector[T]] = if unshuffledTail.isEmpty then RandomState(shuffledHead, fr) - else if unshuffledTail.length == 1 then - RandomState(shuffledHead ++ unshuffledTail, fr) + else if unshuffledTail.length == 1 then RandomState(shuffledHead ++ unshuffledTail, fr) else { - val ni = fr.nextInt(0, unshuffledTail.length) + val ni = fr.nextInt(0, unshuffledTail.length) val index = ni.newValue if index == 0 then { @@ -143,20 +141,19 @@ abstract class FunctionalRandom { ) } else { val nextHead = shuffledHead :+ unshuffledTail(index) - val newTail = unshuffledTail.splitAt(index) match { + val newTail = unshuffledTail.splitAt(index) match { case (l, r) => (l.drop(1) :+ unshuffledTail.head) ++ r.drop(1) } go(nextHead, newTail, ni.nextRandom) } } - } go(Vector(), seq, this) } def nextRandomSubset[T](size: Int, seq: Vector[T]): RandomState[Vector[T]] = - nextShuffled(seq).map { _.take(size) } + nextShuffled(seq).map(_.take(size)) private def nextFlatMapImpl[T, U, S[X] <: Seq[X], FACT <: SeqFactory[S]]( seq: S[T] @@ -164,8 +161,9 @@ abstract class FunctionalRandom { f: (T, FunctionalRandom) => RandomState[S[U]] )(using xFactory: FACT): RandomState[S[U]] = { @nowarn def foldGen(rsU: RandomState[S[U]], t: T): RandomState[S[U]] = - rsU.continue { case (us: S[U], fr: FunctionalRandom) => - f(t, fr).map(x => (us ++ x).asInstanceOf[S[U]]) + rsU.continue { + case (us: S[U], fr: FunctionalRandom) => + f(t, fr).map(x => (us ++ x).asInstanceOf[S[U]]) } FunctionalRandom.nextFoldLeft( seq, @@ -189,8 +187,9 @@ abstract class FunctionalRandom { rsU: RandomState[S[U]], t: T ): RandomState[S[U]] = - rsU.continue { case (us: S[U], fr: FunctionalRandom) => - f(t, fr).map(x => (us :+ x).asInstanceOf[S[U]]) + rsU.continue { + case (us: S[U], fr: FunctionalRandom) => + f(t, fr).map(x => (us :+ x).asInstanceOf[S[U]]) } FunctionalRandom.nextFoldLeft(seq, RandomState(xFactory.empty[U], this))( @@ -213,11 +212,10 @@ abstract class FunctionalRandom { ): RandomState[Vector[U]] = remVec match { case head +: tail => val newAccRS = - if pf.isDefinedAt(head) then - pf(head)(accRS.nextRandom).map(accRS.newValue :+ _) + if pf.isDefinedAt(head) then pf(head)(accRS.nextRandom).map(accRS.newValue :+ _) else accRS go(tail, newAccRS) - case _ => accRS + case _ => accRS } go(vec, RandomState(Vector(), this)) @@ -232,7 +230,7 @@ abstract class FunctionalRandom { case head +: tail => if pf.isDefinedAt(head) then pf(head)(this).map(Option(_)) else go(tail) - case _ => ??? // above cases should cover + case _ => ??? // above cases should cover } go(seq) @@ -249,11 +247,10 @@ abstract class FunctionalRandom { case items if items.isEmpty => accRS case head +: tail => val newAccRS = - if pf.isDefinedAt(head) then - pf(head)(accRS.nextRandom).map(accRS.newValue ++ _) + if pf.isDefinedAt(head) then pf(head)(accRS.nextRandom).map(accRS.newValue ++ _) else accRS go(tail, newAccRS) - case _ => ??? // above cases should cover + case _ => ??? // above cases should cover } go(vec, RandomState(Vector(), this)) @@ -281,13 +278,13 @@ abstract class FunctionalRandom { case class SeededRandom(override val seed: Long) extends FunctionalRandom { private val magicMultiplier = 0x5deece66dL - private val magicAdder = 0xbL - private val mask = 0xffffffffffffffffL + private val magicAdder = 0xbL + private val mask = 0xffffffffffffffffL override def nextInt: RandomState[Int] = { // borrowed from Functional Programming in Scala - val newSeed = (seed * magicMultiplier + magicAdder) & mask - val next = SeededRandom(newSeed) + val newSeed = (seed * magicMultiplier + magicAdder) & mask + val next = SeededRandom(newSeed) val newValue = (newSeed >>> 16).toInt RandomState(newValue, next) } diff --git a/src/main/scala/net/eagle0/common/GrpcRetrier.scala b/src/main/scala/net/eagle0/common/GrpcRetrier.scala index 3cf2ea1453..c9d81dc53e 100644 --- a/src/main/scala/net/eagle0/common/GrpcRetrier.scala +++ b/src/main/scala/net/eagle0/common/GrpcRetrier.scala @@ -12,35 +12,31 @@ final case class GrpcRetrier[Stub <: AbstractStub[Stub]](grpcClient: Stub) { ExecutionContext.fromExecutor(Executors.newFixedThreadPool(4)) private val firstDelayMillis = TimeUnit.SECONDS.toMillis(1) - private val maxDelayMillis = TimeUnit.SECONDS.toMillis(10) - private val timeoutSeconds = 1200 + private val maxDelayMillis = TimeUnit.SECONDS.toMillis(10) + private val timeoutSeconds = 1200 private def go[Response]( clientOp: Stub => Future[Response], delayMillis: Long - ): Future[Response] = { - clientOp(grpcClient.withDeadlineAfter(timeoutSeconds, TimeUnit.SECONDS)) - .recoverWith { - case sre: StatusRuntimeException - if sre.getStatus.getCode == Status.Code.UNAVAILABLE => - println( - s"Unavailable, retrying in ${TimeUnit.MILLISECONDS.toSeconds(delayMillis)}s..." - ) - Thread.sleep(delayMillis) - go( - clientOp = clientOp, - delayMillis = Math.min(delayMillis * 2, maxDelayMillis) - ) - case sre: StatusRuntimeException - if sre.getStatus.getCode == Status.Code.CANCELLED => - println("Cancelled, reconnecting...") - go( - clientOp = clientOp, - delayMillis = firstDelayMillis - ) - case fr: Throwable => throw fr - } - } + ): Future[Response] = + clientOp(grpcClient.withDeadlineAfter(timeoutSeconds, TimeUnit.SECONDS)).recoverWith { + case sre: StatusRuntimeException if sre.getStatus.getCode == Status.Code.UNAVAILABLE => + println( + s"Unavailable, retrying in ${TimeUnit.MILLISECONDS.toSeconds(delayMillis)}s..." + ) + Thread.sleep(delayMillis) + go( + clientOp = clientOp, + delayMillis = Math.min(delayMillis * 2, maxDelayMillis) + ) + case sre: StatusRuntimeException if sre.getStatus.getCode == Status.Code.CANCELLED => + println("Cancelled, reconnecting...") + go( + clientOp = clientOp, + delayMillis = firstDelayMillis + ) + case fr: Throwable => throw fr + } def withRetries[Response]( clientOp: Stub => Future[Response] diff --git a/src/main/scala/net/eagle0/common/JsonUtils.scala b/src/main/scala/net/eagle0/common/JsonUtils.scala index 12eb237aa1..14cc12dcac 100644 --- a/src/main/scala/net/eagle0/common/JsonUtils.scala +++ b/src/main/scala/net/eagle0/common/JsonUtils.scala @@ -11,7 +11,7 @@ import org.json4s.DefaultFormats object JsonUtils { implicit val jsonFormats: DefaultFormats.type = DefaultFormats - private val json = new Json(jsonFormats) + private val json = new Json(jsonFormats) // This will just crash if the source url is not available, or if the // json is not a String:Vector[String] map diff --git a/src/main/scala/net/eagle0/common/Metrics.scala b/src/main/scala/net/eagle0/common/Metrics.scala index dddfcffc54..b56fb814bc 100644 --- a/src/main/scala/net/eagle0/common/Metrics.scala +++ b/src/main/scala/net/eagle0/common/Metrics.scala @@ -3,9 +3,9 @@ package net.eagle0.common import scala.collection.mutable case class Metrics[T](logFrequency: Int) { - private var counters = mutable.Map[T, Int]() + private var counters = mutable.Map[T, Int]() private var totalCount = 0 - private var lastLog = 0 + private var lastLog = 0 def increment(counter: T): Unit = this.synchronized { @@ -19,15 +19,15 @@ case class Metrics[T](logFrequency: Int) { } def logCounters: Unit = this.synchronized { - counters.toVector.sortBy(-_._2).foreach { case (t, count) => - println(s"$count $t") + counters.toVector.sortBy(-_._2).foreach { + case (t, count) => + println(s"$count $t") } } - def maybeLogCounters: Unit = { + def maybeLogCounters: Unit = if totalCount - lastLog > logFrequency then { logCounters lastLog = totalCount } - } } diff --git a/src/main/scala/net/eagle0/common/MoreSeq.scala b/src/main/scala/net/eagle0/common/MoreSeq.scala index 880d5a3943..25c9f235dd 100644 --- a/src/main/scala/net/eagle0/common/MoreSeq.scala +++ b/src/main/scala/net/eagle0/common/MoreSeq.scala @@ -17,11 +17,13 @@ object MoreSeq { def irregularTranspose[A](coll: Iterable[Seq[A]]): Vector[Vector[A]] = { val maxLength = coll.map(_.length).max - coll.foldLeft(Vector.fill(maxLength)(Vector[A]())) { case (acc, nextLine) => - acc.zipWithIndex.map { case (vec, idx) => - if idx < nextLine.length then vec :+ nextLine(idx) - else vec - } + coll.foldLeft(Vector.fill(maxLength)(Vector[A]())) { + case (acc, nextLine) => + acc.zipWithIndex.map { + case (vec, idx) => + if idx < nextLine.length then vec :+ nextLine(idx) + else vec + } } } } diff --git a/src/main/scala/net/eagle0/common/SimpleTimedLogger.scala b/src/main/scala/net/eagle0/common/SimpleTimedLogger.scala index 1f6f043219..3090b7d349 100644 --- a/src/main/scala/net/eagle0/common/SimpleTimedLogger.scala +++ b/src/main/scala/net/eagle0/common/SimpleTimedLogger.scala @@ -35,7 +35,7 @@ object SimpleTimedLogger { private def format(string: String): String = s"${formatter.format(Instant.now())} $string" - private def formatLine(string: String): String = s"${format(string)}\n" + private def formatLine(string: String): String = s"${format(string)}\n" private def formatNoLine(string: String): String = s"${format(string)} " private class PrintLogger extends SimpleTimedLoggerT { @@ -44,15 +44,14 @@ object SimpleTimedLogger { override def logLine(str: String): Unit = print(formatLine(str)) } - private class SimpleTimedLogger(osConstructor: () => OutputStream) - extends SimpleTimedLoggerT { + private class SimpleTimedLogger(osConstructor: () => OutputStream) extends SimpleTimedLoggerT { def log(str: String): Unit = write(formatNoLine(str)) def logLine(str: String): Unit = write(formatLine(str)) private def write(str: String): Unit = - Using(new OutputStreamWriter(osConstructor(), StandardCharsets.UTF_8)) { - fw => fw.write(str) + Using(new OutputStreamWriter(osConstructor(), StandardCharsets.UTF_8)) { fw => + fw.write(str) } match { case Success(_) => () case Failure(exception) => @@ -69,7 +68,7 @@ trait SimpleTimedLoggerT { def logLine(str: String): Unit def withStopwatch[T](str: String)(f: => T): T = { - val start = System.currentTimeMillis() + val start = System.currentTimeMillis() val result = f logLine(s"Finished $str in ${System.currentTimeMillis() - start} ms") result diff --git a/src/main/scala/net/eagle0/common/TsvUtils.scala b/src/main/scala/net/eagle0/common/TsvUtils.scala index e208b5326b..488a69c499 100644 --- a/src/main/scala/net/eagle0/common/TsvUtils.scala +++ b/src/main/scala/net/eagle0/common/TsvUtils.scala @@ -34,11 +34,11 @@ object TsvUtils { } def loadLines(url: URL): Try[Vector[Vector[String]]] = - Using(Source.fromURL(url, "UTF-8")) { loadLines } + Using(Source.fromURL(url, "UTF-8"))(loadLines) // Loads a tsv and returns a Vector of arrays of strings. def loadLines(path: String): Try[Vector[Vector[String]]] = - Using(Source.fromFile(path, "UTF-8")) { loadLines } + Using(Source.fromFile(path, "UTF-8"))(loadLines) def loadMaps(url: URL): Try[Vector[ListMap[String, String]]] = loadLines(url).map(linesToMaps) @@ -80,7 +80,7 @@ object TsvUtils { private def mapsToLines( maps: Vector[Map[String, String]] ): Vector[Vector[String]] = { - val headers = maps.head.keys.toVector + val headers = maps.head.keys.toVector val otherLines = maps.map(oneMap => headers.map(oneMap)) headers +: otherLines @@ -88,12 +88,11 @@ object TsvUtils { private def saveLines(lines: Vector[Vector[String]], url: URL): Unit = { val file = new File(url.getPath) - val pw = new PrintWriter(file) + val pw = new PrintWriter(file) - try { + try lines.foreach(line => pw.write(line.mkString("\t") + "\n")) - } finally { + finally pw.close() - } } } diff --git a/src/main/scala/net/eagle0/common/ZipUtils.scala b/src/main/scala/net/eagle0/common/ZipUtils.scala index c17dfcfbe7..c33c699799 100644 --- a/src/main/scala/net/eagle0/common/ZipUtils.scala +++ b/src/main/scala/net/eagle0/common/ZipUtils.scala @@ -9,7 +9,7 @@ object ZipUtils { val os = new ByteArrayOutputStream() val buf = new Array[Byte](1024) - var n = gz.read(buf) + var n = gz.read(buf) while n > 0 do { os.write(buf, 0, n) n = gz.read(buf) diff --git a/src/main/scala/net/eagle0/common/llm_integration/ApiKeys.scala b/src/main/scala/net/eagle0/common/llm_integration/ApiKeys.scala index 6a27519915..301a752ec8 100644 --- a/src/main/scala/net/eagle0/common/llm_integration/ApiKeys.scala +++ b/src/main/scala/net/eagle0/common/llm_integration/ApiKeys.scala @@ -8,10 +8,10 @@ object ApiKeys { "src/main/scala/net/eagle0/common/llm_integration/api_keys.txt" // These must have valid values set in api_keys.txt - private val openAIKeyName = "openai_api_key" + private val openAIKeyName = "openai_api_key" private val anthropicKeyName = "anthropic_api_key" - private def readDictionary(): Map[String, String] = { + private def readDictionary(): Map[String, String] = Using(scala.io.Source.fromFile(apiKeyFilePath)) { source => val lines = source.getLines().filterNot(_.startsWith("#")).toList lines.map { line => @@ -27,21 +27,19 @@ object ApiKeys { "Failed to read api_keys.txt. Make sure you have copied api_keys_template.txt to api_keys.txt and set the keys." ) } - } private val dictionary = readDictionary() - private def getKey(key: String): String = { + private def getKey(key: String): String = dictionary.get(key) match { - case None => + case None => throw new ApiKeyException(s"$key not found") case Some(value) if value.startsWith("your_") => throw new ApiKeyException( s"API key for $key is not set. Please set it in $apiKeyFilePath." ) - case Some(value) => value + case Some(value) => value } - } lazy val openAI: String = getKey(openAIKeyName) diff --git a/src/main/scala/net/eagle0/common/llm_integration/ClaudeServiceImpl.scala b/src/main/scala/net/eagle0/common/llm_integration/ClaudeServiceImpl.scala index 34d7ec7ae2..8da22a201e 100644 --- a/src/main/scala/net/eagle0/common/llm_integration/ClaudeServiceImpl.scala +++ b/src/main/scala/net/eagle0/common/llm_integration/ClaudeServiceImpl.scala @@ -7,10 +7,7 @@ import java.time.{Duration, ZonedDateTime} import java.time.format.DateTimeFormatter import java.util.function.Consumer -import net.eagle0.common.llm_integration.ClaudeServiceImpl.{ - dictionaryFor, - messageVector -} +import net.eagle0.common.llm_integration.ClaudeServiceImpl.{dictionaryFor, messageVector} import org.json4s.{DefaultFormats, JString} import org.json4s.jvalue2extractable import org.json4s.jvalue2monadic @@ -18,22 +15,22 @@ import org.json4s.native.{Json, Serialization} object ClaudeServiceImpl { val model: String = "claude-sonnet-4-20250514" - val maxTokens = 2048 + val maxTokens = 2048 - private val apiKey = ApiKeys.anthropic + private val apiKey = ApiKeys.anthropic private val baseURL = new URL("https://api.anthropic.com/v1/messages") private def dictionaryFor( modelName: String - ): Map[String, Any] = Map( - "model" -> modelName, + ): Map[String, Any] = Map( + "model" -> modelName, "max_tokens" -> maxTokens, - "stream" -> true + "stream" -> true ) private def messageVector(inputText: String): Vector[Map[String, String]] = Vector( Map( - "role" -> "user", + "role" -> "user", "content" -> inputText ) ) @@ -83,14 +80,14 @@ class ClaudeServiceImpl( private class ClaudeStringConsumer( streamingConsumer: Consumer[StreamingTextResults] ) extends Consumer[String] { - private val json = new Json(DefaultFormats) + private val json = new Json(DefaultFormats) private var streamId = "" override def accept(t: String): Unit = { val parsedJson = json.parse(t) parsedJson \ "type" match { - case JString("message_start") => + case JString("message_start") => streamId = (parsedJson \ "message" \ "id").extract[String] case JString("content_block_delta") => (parsedJson \ "delta" \ "text") match { @@ -102,7 +99,7 @@ class ClaudeServiceImpl( completed = false ) ) - case _ => ??? + case _ => ??? } case JString("content_block_start") => () case JString("content_block_stop") => () @@ -116,12 +113,12 @@ class ClaudeServiceImpl( completed = true ) ) - case JString("error") => + case JString("error") => val errorDetails = parsedJson \ "error" - val errorType = (errorDetails \ "type").extract[String] + val errorType = (errorDetails \ "type").extract[String] val errorMessage = (errorDetails \ "message").extract[String] println(s"Got an \"($errorType)\" error from Claude: $errorMessage") - case _ => ??? + case _ => ??? } } } @@ -136,26 +133,24 @@ class ClaudeServiceImpl( headers: Map[String, Vector[String]] ): Option[RateLimits] = for { - requestLimit <- headers.get("anthropic-ratelimit-requests-limit") - tokenLimit <- headers.get("anthropic-ratelimit-tokens-limit") + requestLimit <- headers.get("anthropic-ratelimit-requests-limit") + tokenLimit <- headers.get("anthropic-ratelimit-tokens-limit") requestsRemaining <- headers.get("anthropic-ratelimit-requests-remaining") - tokensRemaining <- headers.get("anthropic-ratelimit-tokens-remaining") - requestResetTime <- headers.get("anthropic-ratelimit-requests-reset") - tokenResetTime <- headers.get("anthropic-ratelimit-tokens-reset") - } yield { - RateLimits( - requestLimit = requestLimit.head.toInt, - tokenLimit = tokenLimit.head.toInt, - requestsRemaining = requestsRemaining.head.toInt, - tokensRemaining = tokensRemaining.head.toInt, - requestResetTime = ZonedDateTime.parse( - requestResetTime.head, - rfc3339formatter - ), - tokenResetTime = ZonedDateTime.parse( - tokenResetTime.head, - rfc3339formatter - ) + tokensRemaining <- headers.get("anthropic-ratelimit-tokens-remaining") + requestResetTime <- headers.get("anthropic-ratelimit-requests-reset") + tokenResetTime <- headers.get("anthropic-ratelimit-tokens-reset") + } yield RateLimits( + requestLimit = requestLimit.head.toInt, + tokenLimit = tokenLimit.head.toInt, + requestsRemaining = requestsRemaining.head.toInt, + tokensRemaining = tokensRemaining.head.toInt, + requestResetTime = ZonedDateTime.parse( + requestResetTime.head, + rfc3339formatter + ), + tokenResetTime = ZonedDateTime.parse( + tokenResetTime.head, + rfc3339formatter ) - } + ) } diff --git a/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCaller.scala b/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCaller.scala index ccf7f2fc51..89543dc762 100644 --- a/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCaller.scala +++ b/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCaller.scala @@ -1,11 +1,6 @@ package net.eagle0.common.llm_integration -import java.net.http.{ - HttpClient, - HttpRequest, - HttpResponse, - HttpTimeoutException -} +import java.net.http.{HttpClient, HttpRequest, HttpResponse, HttpTimeoutException} import java.net.http.HttpClient.{Redirect, Version} import java.net.http.HttpResponse.ResponseInfo import java.net.HttpURLConnection @@ -49,10 +44,10 @@ final class ExternalTextGenerationCaller( private var inProgressCount = 0 def maxConcurrentStreams: Int = serviceImpl.maxConcurrentStreams - def getInProgressCount: Int = inProgressCount + def getInProgressCount: Int = inProgressCount private var currentRateLimits: Option[RateLimits] = None - private var currentRateLimitTime: ZonedDateTime = ZonedDateTime.now() + private var currentRateLimitTime: ZonedDateTime = ZonedDateTime.now() def millisUntilReset: Long = ChronoUnit.MILLIS.between( @@ -76,9 +71,8 @@ final class ExternalTextGenerationCaller( inputText: String, partialCompletion: Option[String], streamingConsumer: Consumer[StreamingTextResults], - backoffSeconds: Double = - ExternalTextGenerationCaller.initialBackoffSeconds - ): Future[HttpResponse[Unit]] = { + backoffSeconds: Double = ExternalTextGenerationCaller.initialBackoffSeconds + ): Future[HttpResponse[Unit]] = streamCompletion( inputText = inputText, request = serviceImpl.makeRequest( @@ -88,7 +82,6 @@ final class ExternalTextGenerationCaller( backoffSeconds = backoffSeconds, streamingConsumer = streamingConsumer ) - } private def streamCompletion( inputText: String, @@ -102,20 +95,18 @@ final class ExternalTextGenerationCaller( println(s"Trying again after $backoffSeconds seconds...") val promise = Promise[HttpResponse[Unit]]() - val t = new Timer() + val t = new Timer() t.schedule( new TimerTask { - override def run(): Unit = { + override def run(): Unit = promise.completeWith( streamCompletion( inputText = inputText, request = request, - backoffSeconds = - ExternalTextGenerationCaller.nextBackoff(backoffSeconds), + backoffSeconds = ExternalTextGenerationCaller.nextBackoff(backoffSeconds), streamingConsumer = streamingConsumer ) ) - } }, (backoffSeconds * 1000).toLong ) @@ -126,19 +117,19 @@ final class ExternalTextGenerationCaller( httpClient .sendAsync( request, - (respInfo: ResponseInfo) => { + (respInfo: ResponseInfo) => if respInfo.statusCode() == HttpURLConnection.HTTP_OK then new SseSubscriber(serviceImpl.stringConsumer(streamingConsumer)) else throw new RuntimeException( s"Unexpected response code: ${respInfo.statusCode()}" ) - } ) .asScala - .andThen { case x => - inProgressCount -= 1 - x + .andThen { + case x => + inProgressCount -= 1 + x } .transform { case Success(httpResponse) => @@ -196,7 +187,7 @@ final class ExternalTextGenerationCaller( case e: CompletionException => println(s"CompletionException error $e") tryAgain() - case e: Throwable => + case e: Throwable => println(s"error $e") tryAgain() } diff --git a/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCallerApp.scala b/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCallerApp.scala index 45f302b7ec..99b03c267c 100644 --- a/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCallerApp.scala +++ b/src/main/scala/net/eagle0/common/llm_integration/ExternalTextGenerationCallerApp.scala @@ -66,13 +66,11 @@ object ExternalTextGenerationCallerApp { |Alakanda's faction controls Atfordia. |Roger the Shrubber's faction controls Chapellia.""".stripMargin - val startTime = System.currentTimeMillis() - val completion = caller.streamCompletion( + val startTime = System.currentTimeMillis() + val completion = caller.streamCompletion( inputText = inputText, partialCompletion = None, - streamingConsumer = results => { - print(results.value) - } + streamingConsumer = results => print(results.value) ) Await.result(completion, Duration(500, SECONDS)) println("") diff --git a/src/main/scala/net/eagle0/common/llm_integration/OpenAIChatCompletionsServiceImpl.scala b/src/main/scala/net/eagle0/common/llm_integration/OpenAIChatCompletionsServiceImpl.scala index 2597b5af98..0ed808338e 100644 --- a/src/main/scala/net/eagle0/common/llm_integration/OpenAIChatCompletionsServiceImpl.scala +++ b/src/main/scala/net/eagle0/common/llm_integration/OpenAIChatCompletionsServiceImpl.scala @@ -6,10 +6,7 @@ import java.net.http.HttpRequest.BodyPublishers import java.time.{Duration, ZonedDateTime} import java.util.function.Consumer -import net.eagle0.common.llm_integration.OpenAIChatCompletionsServiceImpl.{ - dictionaryFor, - messageVector -} +import net.eagle0.common.llm_integration.OpenAIChatCompletionsServiceImpl.{dictionaryFor, messageVector} import org.json4s.{DefaultFormats, JArray, JObject, JString} import org.json4s.jvalue2extractable import org.json4s.jvalue2monadic @@ -18,16 +15,16 @@ import org.json4s.native.{Json, Serialization} object OpenAIChatCompletionsServiceImpl { val gpt5: String = "gpt-5" - private val apiKey = ApiKeys.openAI - private val baseURL = new URL("https://api.openai.com/v1/chat/completions") + private val apiKey = ApiKeys.openAI + private val baseURL = new URL("https://api.openai.com/v1/chat/completions") private val temperature: Double = 1.0 private def dictionaryFor( modelName: String - ): Map[String, Any] = Map( - "model" -> modelName, - "temperature" -> temperature, - "stream" -> true, + ): Map[String, Any] = Map( + "model" -> modelName, + "temperature" -> temperature, + "stream" -> true, "reasoning_effort" -> "minimal" ) @@ -37,12 +34,12 @@ object OpenAIChatCompletionsServiceImpl { ): Vector[Map[String, String]] = Vector( Map( - "role" -> "user", + "role" -> "user", "content" -> inputText ) ) ++ partialCompletion.map(pc => Map( - "role" -> "assistant", + "role" -> "assistant", "content" -> pc ) ) @@ -99,18 +96,18 @@ class OpenAIChatCompletionsServiceImpl( override def stringConsumer( streamingConsumer: Consumer[StreamingTextResults] ): Consumer[String] = (t: String) => { - val json = new Json(DefaultFormats) + val json = new Json(DefaultFormats) val parsedJson = - try { + try json.parse(t) - } catch { + catch { case pe: org.json4s.ParserUtil.ParseException => println(s"Failed to parse JSON: $t") throw pe } val streamId = (parsedJson \ "id").extract[String] - val choice = (parsedJson \ "choices") + val choice = (parsedJson \ "choices") .asInstanceOf[JArray] .arr .head @@ -126,7 +123,7 @@ class OpenAIChatCompletionsServiceImpl( case JString(str) => println(s"Unexpected finish reason $str") true - case _ => false + case _ => false } (choice \ "delta" \ "content") match { @@ -138,7 +135,7 @@ class OpenAIChatCompletionsServiceImpl( completed = completed ) ) - case _ => + case _ => if completed then streamingConsumer.accept( StreamingTextResults( @@ -154,32 +151,30 @@ class OpenAIChatCompletionsServiceImpl( headers: Map[String, Vector[String]] ): Option[RateLimits] = for { - requestLimit <- headers.get("x-ratelimit-limit-requests") - tokenLimit <- headers.get("x-ratelimit-limit-tokens") + requestLimit <- headers.get("x-ratelimit-limit-requests") + tokenLimit <- headers.get("x-ratelimit-limit-tokens") requestsRemaining <- headers.get("x-ratelimit-remaining-requests") - tokensRemaining <- headers.get("x-ratelimit-remaining-tokens") - requestResetTime <- headers.get("x-ratelimit-reset-requests") - tokenResetTime <- headers.get("x-ratelimit-reset-tokens") - } yield { - RateLimits( - requestLimit = requestLimit.head.toInt, - tokenLimit = tokenLimit.head.toInt, - requestsRemaining = requestsRemaining.head.toInt, - tokensRemaining = tokensRemaining.head.toInt, - requestResetTime = ZonedDateTime - .now() - .plus( - OpenAiDurationParser - .parseDuration(requestResetTime.head) - .getOrElse(Duration.ZERO) - ), - tokenResetTime = ZonedDateTime - .now() - .plus( - OpenAiDurationParser - .parseDuration(tokenResetTime.head) - .getOrElse(Duration.ZERO) - ) - ) - } + tokensRemaining <- headers.get("x-ratelimit-remaining-tokens") + requestResetTime <- headers.get("x-ratelimit-reset-requests") + tokenResetTime <- headers.get("x-ratelimit-reset-tokens") + } yield RateLimits( + requestLimit = requestLimit.head.toInt, + tokenLimit = tokenLimit.head.toInt, + requestsRemaining = requestsRemaining.head.toInt, + tokensRemaining = tokensRemaining.head.toInt, + requestResetTime = ZonedDateTime + .now() + .plus( + OpenAiDurationParser + .parseDuration(requestResetTime.head) + .getOrElse(Duration.ZERO) + ), + tokenResetTime = ZonedDateTime + .now() + .plus( + OpenAiDurationParser + .parseDuration(tokenResetTime.head) + .getOrElse(Duration.ZERO) + ) + ) } diff --git a/src/main/scala/net/eagle0/common/llm_integration/OpenAiDurationParser.scala b/src/main/scala/net/eagle0/common/llm_integration/OpenAiDurationParser.scala index 69078dd9a4..26acc380b3 100644 --- a/src/main/scala/net/eagle0/common/llm_integration/OpenAiDurationParser.scala +++ b/src/main/scala/net/eagle0/common/llm_integration/OpenAiDurationParser.scala @@ -4,13 +4,13 @@ import java.time.Duration object OpenAiDurationParser { private val durationRegex = """(\d+)((ms)|[smhdy])""".r - private val durationMap = Map( + private val durationMap = Map( "ms" -> Duration.ofMillis(1), - "s" -> Duration.ofSeconds(1), - "m" -> Duration.ofMinutes(1), - "h" -> Duration.ofHours(1), - "d" -> Duration.ofDays(1), - "y" -> Duration.ofDays(365) + "s" -> Duration.ofSeconds(1), + "m" -> Duration.ofMinutes(1), + "h" -> Duration.ofHours(1), + "d" -> Duration.ofDays(1), + "y" -> Duration.ofDays(365) ) def parseDuration(duration: String): Option[Duration] = @@ -18,7 +18,7 @@ object OpenAiDurationParser { .findAllMatchIn(duration) .map { m => val amount = m.group(1).toInt - val unit = m.group(2) + val unit = m.group(2) durationMap(unit).multipliedBy(amount) } .toSeq match { diff --git a/src/main/scala/net/eagle0/common/name_generation/NameGenerator.scala b/src/main/scala/net/eagle0/common/name_generation/NameGenerator.scala index 565ad958bd..b80568dcbc 100644 --- a/src/main/scala/net/eagle0/common/name_generation/NameGenerator.scala +++ b/src/main/scala/net/eagle0/common/name_generation/NameGenerator.scala @@ -7,14 +7,14 @@ import scala.util.Random import net.eagle0.common.{SeededRandom, TsvUtils} class NameGenerator { - private val random = SeededRandom(Random.nextLong()) - private val emptySubstitutions = Map[String, String]() + private val random = SeededRandom(Random.nextLong()) + private val emptySubstitutions = Map[String, String]() private val nameConstructionUrl = new File( "/opt/nameConstruction.txt" ).toURI.toURL - private val namesFileUrl = new File("/opt/names.tsv").toURI.toURL + private val namesFileUrl = new File("/opt/names.tsv").toURI.toURL - private val namesMap = TsvUtils.loadColumnMaps(namesFileUrl).get + private val namesMap = TsvUtils.loadColumnMaps(namesFileUrl).get private val formatString = StringConstructionTokenGenerator.formatStringFromUrl( nameConstructionUrl @@ -41,17 +41,17 @@ class NameGenerator { atSpecializations = Vector("male") ) - def nextFemaleName(): String = + def nextFemaleName(): String = femaleTok.nextString(random, emptySubstitutions).newValue - def nextMaleName(): String = + def nextMaleName(): String = maleTok.nextString(random, emptySubstitutions).newValue def nextNeutralName(): String = allTok.nextString(random, emptySubstitutions).newValue def nextName(): String = { - val intR = random.nextInt(0, 20) + val intR = random.nextInt(0, 20) val newInt = intR.newValue - val tok = + val tok = if newInt == 0 then allTok else if newInt <= 10 then femaleTok else maleTok diff --git a/src/main/scala/net/eagle0/common/name_generation/StringConstructionParser.scala b/src/main/scala/net/eagle0/common/name_generation/StringConstructionParser.scala index 881d65dff8..b6ce5b4dec 100644 --- a/src/main/scala/net/eagle0/common/name_generation/StringConstructionParser.scala +++ b/src/main/scala/net/eagle0/common/name_generation/StringConstructionParser.scala @@ -10,8 +10,9 @@ class StringConstructionParser( import ParseSequence.* private def charString(seq: Seq[CharacterOrToken]): String = - seq.collect { case C(char) => - char + seq.collect { + case C(char) => + char }.mkString def parseLiteral(fmt: String): Option[(String, StringConstructionToken)] = { @@ -25,12 +26,11 @@ class StringConstructionParser( def parseRemaining(str: String, acc: String): ParseStatus = str.head match { case '\\' => - if str.length < 2 then - throw new IllegalArgumentException("Found \\ at end of literal") + if str.length < 2 then throw new IllegalArgumentException("Found \\ at end of literal") else parseRemaining(str.drop(2), acc + str.charAt(1)) case '\"' => ParseStatus(str.drop(1), acc) - case _ => + case _ => parseRemaining(str.drop(1), acc + str.head) } @@ -41,44 +41,44 @@ class StringConstructionParser( private def parseOptional( ts: ParseSequence - ): Try[(ParseSequence, StringConstructionToken)] = { + ): Try[(ParseSequence, StringConstructionToken)] = insideBalanced(ts, open = '{', closed = '}').flatMap { case (remainAfter, inWithOdds) => val DecimalParseResults(inAfterOdds, odds) = readDecimal(inWithOdds) - parsePossiblyParsed(inAfterOdds).flatMap { case (rem, parsed) => - if rem.nonEmpty then - Failure( - new IllegalArgumentException( - "Found extra characters inside optional" + parsePossiblyParsed(inAfterOdds).flatMap { + case (rem, parsed) => + if rem.nonEmpty then + Failure( + new IllegalArgumentException( + "Found extra characters inside optional" + ) ) - ) - else Success((remainAfter, OptionalToken(parsed, odds))) + else Success((remainAfter, OptionalToken(parsed, odds))) } } - } private def parseOneof( ts: ParseSequence - ): Try[(ParseSequence, StringConstructionToken)] = { + ): Try[(ParseSequence, StringConstructionToken)] = insideBalanced(ts, open = '[', closed = ']').map { case (remainAfter, inside) => var entries = Vector.empty[OneofListEntry] - var pos = inside + var pos = inside while pos.nonEmpty do { val t = pos.head if t == ',' then pos = pos.drop(1) else { val DecimalParseResults(remIn, weight) = readDecimal(pos) - parsePossiblyParsed(remIn).map { case (rem, parsed) => - entries = entries :+ OneofListEntry(parsed, weight) - pos = rem + parsePossiblyParsed(remIn).map { + case (rem, parsed) => + entries = entries :+ OneofListEntry(parsed, weight) + pos = rem } } } (remainAfter, OneofListToken(entries)) } - } def parseListSelector( ts: ParseSequence @@ -112,12 +112,11 @@ class StringConstructionParser( def parseCapitalized( ts: ParseSequence - ): Try[(ParseSequence, StringConstructionToken)] = { + ): Try[(ParseSequence, StringConstructionToken)] = for { (remainAfter, inside) <- insideBalanced(ts, open = '-', closed = '+') - (_, parsed) <- parsePossiblyParsed(inside) + (_, parsed) <- parsePossiblyParsed(inside) } yield (remainAfter, TitleCaseToken(parsed)) - } def parseOrdinal( ts: ParseSequence @@ -146,7 +145,7 @@ class StringConstructionParser( def go( tokens: ParseSequence, acc: Seq[StringConstructionToken] - ): Try[(ParseSequence, Seq[StringConstructionToken])] = { + ): Try[(ParseSequence, Seq[StringConstructionToken])] = if tokens.isEmpty then Success((Vector.empty, acc)) else { tokens.head match { @@ -168,10 +167,10 @@ class StringConstructionParser( case T(t) => go(tokens.drop(1), acc :+ t) } } - } - go(tokens, Vector.empty).map { case (rem, ts) => - (rem, if ts.size == 1 then ts.head else SequenceToken(ts)) + go(tokens, Vector.empty).map { + case (rem, ts) => + (rem, if ts.size == 1 then ts.head else SequenceToken(ts)) } } @@ -180,7 +179,7 @@ class StringConstructionParser( def parseNext( remainingString: String, acc: ParseSequence - ): ParseSequence = { + ): ParseSequence = if remainingString.isEmpty then acc else remainingString.head match { @@ -192,19 +191,18 @@ class StringConstructionParser( throw new IllegalArgumentException( s"Illegal literal in $remainingString" ) - case _ => + case _ => parseNext( remainingString.drop(1), acc :+ C(remainingString.head) ) } - } val tokens = parseNext(formatString, Vector.empty) - parsePossiblyParsed(tokens).flatMap { case (rem, tok) => - if rem.nonEmpty then - Failure(new IllegalArgumentException("Failed to parse")) - else Success(tok) + parsePossiblyParsed(tokens).flatMap { + case (rem, tok) => + if rem.nonEmpty then Failure(new IllegalArgumentException("Failed to parse")) + else Success(tok) } } @@ -213,8 +211,8 @@ class StringConstructionParser( open: Char, closed: Char ): Try[(ParseSequence, ParseSequence)] = { - var pos = ts.drop(1) - var level = 1 + var pos = ts.drop(1) + var level = 1 var inside = Vector.empty[CharacterOrToken] while level > 0 && pos.nonEmpty do { @@ -226,8 +224,7 @@ class StringConstructionParser( pos = pos.drop(1) } - if level > 0 then - Failure(new IllegalArgumentException("Did not find closing character")) + if level > 0 then Failure(new IllegalArgumentException("Did not find closing character")) Success((pos, inside)) } diff --git a/src/main/scala/net/eagle0/common/name_generation/StringConstructionTester.scala b/src/main/scala/net/eagle0/common/name_generation/StringConstructionTester.scala index 0ee8564be4..9048bd5bd4 100644 --- a/src/main/scala/net/eagle0/common/name_generation/StringConstructionTester.scala +++ b/src/main/scala/net/eagle0/common/name_generation/StringConstructionTester.scala @@ -26,7 +26,7 @@ object StringConstructionTester { "longbowmen" ) types.foreach { typeName => - val adj = s"${typeName}_adj" + val adj = s"${typeName}_adj" val newSubs = substitutions + ("BATTALION_NAME" -> typeName) + ("BATTALION_ADJECTIVE" -> adj) @@ -41,7 +41,7 @@ object StringConstructionTester { val random = new JankyRandom(new Random()) print(s"---\n$typeName\n---\n") - ((1 to 20).toVector).foreach { _ => + (1 to 20).toVector.foreach { _ => println(token.nextString(random, Map("PLACE" -> "Pieska")).newValue) } print("\n\n\n") diff --git a/src/main/scala/net/eagle0/common/name_generation/StringConstructionToken.scala b/src/main/scala/net/eagle0/common/name_generation/StringConstructionToken.scala index f38960843c..abffd60507 100644 --- a/src/main/scala/net/eagle0/common/name_generation/StringConstructionToken.scala +++ b/src/main/scala/net/eagle0/common/name_generation/StringConstructionToken.scala @@ -19,8 +19,7 @@ case class LiteralToken(literal: String) extends StringConstructionToken { RandomState(literal, random) } -class MissingLiteralKeyException(key: String) - extends Exception(s"Missing literal key $key") {} +class MissingLiteralKeyException(key: String) extends Exception(s"Missing literal key $key") {} case class SubstitutionToken(key: String) extends StringConstructionToken { override def nextString( @@ -34,27 +33,25 @@ case class SubstitutionToken(key: String) extends StringConstructionToken { ) } -case class SequenceToken(tokens: Seq[StringConstructionToken]) - extends StringConstructionToken { +case class SequenceToken(tokens: Seq[StringConstructionToken]) extends StringConstructionToken { override def nextString( random: FunctionalRandom, literalSubstitutions: Map[String, String] ): RandomState[String] = - tokens.foldLeft(RandomState[String]("", random)) { case (state, tok) => - val nextStr = tok.nextString(state.nextRandom, literalSubstitutions) - RandomState(state.newValue + nextStr.newValue, nextStr.nextRandom) + tokens.foldLeft(RandomState[String]("", random)) { + case (state, tok) => + val nextStr = tok.nextString(state.nextRandom, literalSubstitutions) + RandomState(state.newValue + nextStr.newValue, nextStr.nextRandom) } } -case class OptionalToken(token: StringConstructionToken, odds: Double) - extends StringConstructionToken { +case class OptionalToken(token: StringConstructionToken, odds: Double) extends StringConstructionToken { override def nextString( random: FunctionalRandom, literalSubstitutions: Map[String, String] ): RandomState[String] = { val state = random.nextDouble - if state.newValue < odds then - token.nextString(state.nextRandom, literalSubstitutions) + if state.newValue < odds then token.nextString(state.nextRandom, literalSubstitutions) else RandomState("", state.nextRandom) } } @@ -67,33 +64,32 @@ case class OneofListEntry(token: StringConstructionToken, weight: Double) { token.nextString(random, literalSubstitutions) } -case class OneofListToken(entries: Seq[OneofListEntry]) - extends StringConstructionToken { +case class OneofListToken(entries: Seq[OneofListEntry]) extends StringConstructionToken { override def nextString( random: FunctionalRandom, literalSubstitutions: Map[String, String] ): RandomState[String] = { val totalWeight = entries.map(_.weight).sum - random.nextDouble.continue { case (double, fr) => - @tailrec - def go( - remainingEntries: Seq[OneofListEntry], - remainingD: Double - ): RandomState[String] = remainingEntries match { - case Nil => - throw new IllegalStateException("Failed to find a valid oneof") - case w +: tail => - if remainingD < w.weight then w.toString(fr, literalSubstitutions) - else go(tail, remainingD - w.weight) - } + random.nextDouble.continue { + case (double, fr) => + @tailrec + def go( + remainingEntries: Seq[OneofListEntry], + remainingD: Double + ): RandomState[String] = remainingEntries match { + case Nil => + throw new IllegalStateException("Failed to find a valid oneof") + case w +: tail => + if remainingD < w.weight then w.toString(fr, literalSubstitutions) + else go(tail, remainingD - w.weight) + } - go(entries, double * totalWeight) + go(entries, double * totalWeight) } } } -case class ListSelectionToken(choices: Seq[String]) - extends StringConstructionToken { +case class ListSelectionToken(choices: Seq[String]) extends StringConstructionToken { override def nextString( random: FunctionalRandom, literalSubstitutions: Map[String, String] @@ -104,7 +100,7 @@ case class OrdinalSelectionToken(max: Int) extends StringConstructionToken { override def nextString( random: FunctionalRandom, literalSubstitutions: Map[String, String] - ): RandomState[String] = { + ): RandomState[String] = random.nextInt(1, max).map { value => if value == 11 then "11th" else { @@ -116,11 +112,9 @@ case class OrdinalSelectionToken(max: Int) extends StringConstructionToken { }) } } - } } -case class TitleCaseToken(base: StringConstructionToken) - extends StringConstructionToken { +case class TitleCaseToken(base: StringConstructionToken) extends StringConstructionToken { val uncapitalizedWords: Set[String] = Set("and", "but", "for", "or", "nor", "the", "a", "an", "to", "as", "of") @@ -128,8 +122,8 @@ case class TitleCaseToken(base: StringConstructionToken) words match { case first +: middle :+ last => first.capitalize +: middle :+ last.capitalize - case Vector(only: String) => Vector(only.capitalize) - case Vector() => Vector() + case Vector(only: String) => Vector(only.capitalize) + case Vector() => Vector() } private def byWordCapitalized(string: String): Vector[String] = @@ -141,9 +135,8 @@ case class TitleCaseToken(base: StringConstructionToken) override def nextString( random: FunctionalRandom, literalSubstitutions: Map[String, String] - ): RandomState[String] = { + ): RandomState[String] = base.nextString(random, literalSubstitutions).map { cap => firstAndLastCapitalized(byWordCapitalized(cap)).mkString(" ") } - } } diff --git a/src/main/scala/net/eagle0/common/name_generation/StringConstructionTokenGenerator.scala b/src/main/scala/net/eagle0/common/name_generation/StringConstructionTokenGenerator.scala index b3562314f6..16790f0bb9 100644 --- a/src/main/scala/net/eagle0/common/name_generation/StringConstructionTokenGenerator.scala +++ b/src/main/scala/net/eagle0/common/name_generation/StringConstructionTokenGenerator.scala @@ -23,8 +23,8 @@ object StringConstructionTokenGenerator { } val (stringsMap, unfilteredStringsMap) = { - val allSpecializations = namesMap - .map { case (key, words) => + val allSpecializations = namesMap.map { + case (key, words) => key.split("@", 2) match { case Array(realKey) => (realKey, "", words) case Array(realKey, spec) => (realKey, spec, words) @@ -33,17 +33,14 @@ object StringConstructionTokenGenerator { "Too many @s in column name" ) } - } - .toVector - .groupBy { _._1 } + }.toVector.groupBy(_._1) - val stringsMap = allSpecializations - .map { case (realWord, specializations) => - val includedSpecializations = specializations.filter(spec => - spec._2.isEmpty || atSpecializations.contains(spec._2) - ) + val stringsMap = allSpecializations.map { + case (realWord, specializations) => + val includedSpecializations = + specializations.filter(spec => spec._2.isEmpty || atSpecializations.contains(spec._2)) (realWord, includedSpecializations.flatMap(_._3)) - } + } val unfilteredStringsMap = allSpecializations.map { case (realWord, specializations) => diff --git a/src/main/scala/net/eagle0/common/sse/SseEventReader.scala b/src/main/scala/net/eagle0/common/sse/SseEventReader.scala index f26b6326d7..8325c4dc27 100644 --- a/src/main/scala/net/eagle0/common/sse/SseEventReader.scala +++ b/src/main/scala/net/eagle0/common/sse/SseEventReader.scala @@ -5,10 +5,10 @@ import scala.annotation.tailrec // Functions for parsing events from an SSE stream. Uses spec as defined in // https://html.spec.whatwg.org/multipage/server-sent-events.html object SseEventReader { - private val DataKey = "data" - private val EventKey = "event" - private val IdKey = "id" - private val RetryKey = "retry" + private val DataKey = "data" + private val EventKey = "event" + private val IdKey = "id" + private val RetryKey = "retry" private val DefaultEventValue = "message" sealed trait ReadResult @@ -36,8 +36,7 @@ object SseEventReader { else readLines( IncompleteEvent( - eventType = - carryoverEvent.map(_.eventType).getOrElse(DefaultEventValue), + eventType = carryoverEvent.map(_.eventType).getOrElse(DefaultEventValue), metadata = carryoverEvent.map(_.metadata).getOrElse(Map.empty), data = carryoverEvent.map(_.data).getOrElse(""), carryover = carryoverEvent.map(_.carryover).getOrElse("") + text @@ -53,14 +52,14 @@ object SseEventReader { if value.startsWith(" ") then value.drop(1) else value key match { - case DataKey => + case DataKey => IncompleteEvent( eventType = acc.eventType, metadata = acc.metadata, data = acc.data + trimmedSpaceValue, carryover = acc.carryover ) - case EventKey => + case EventKey => IncompleteEvent( eventType = trimmedSpaceValue, metadata = acc.metadata, @@ -74,23 +73,23 @@ object SseEventReader { data = acc.data, carryover = acc.carryover ) - case _ => + case _ => // The spec actually says to ignore fields except if the key is "event", "data", "id", or "retry" acc } } @tailrec - private def readLines(acc: IncompleteEvent): ReadResult = { + private def readLines(acc: IncompleteEvent): ReadResult = acc.carryover.split("\n", 2) match { - case Array("", moreText) => // blank line indicates end of event + case Array("", moreText) => // blank line indicates end of event CompleteEvent( eventType = acc.eventType, metadata = acc.metadata, data = acc.data, remainingText = moreText ) - case Array(singleLine) => // did not end in a newline + case Array(singleLine) => // did not end in a newline IncompleteEvent( eventType = acc.eventType, metadata = acc.metadata, @@ -101,7 +100,7 @@ object SseEventReader { case Array(kv, newCarryover) => val accWithNewCarryover = acc.copy(carryover = newCarryover) kv.split(":", 2) match { - case Array("", _) => + case Array("", _) => // Line started with a colon; ignore line readLines(accWithNewCarryover) case Array(key, value) => @@ -109,14 +108,13 @@ object SseEventReader { readLines( withSingleKeyValuePair(accWithNewCarryover, key, value) ) - case Array(key) => + case Array(key) => // Line contained a key with no value, use empty string readLines( withSingleKeyValuePair(accWithNewCarryover, key, "") ) - case _ => ??? + case _ => ??? } - case _ => ??? + case _ => ??? } - } } diff --git a/src/main/scala/net/eagle0/common/sse/SseSubscriber.scala b/src/main/scala/net/eagle0/common/sse/SseSubscriber.scala index 9c1d1c5912..56f5a8aba8 100644 --- a/src/main/scala/net/eagle0/common/sse/SseSubscriber.scala +++ b/src/main/scala/net/eagle0/common/sse/SseSubscriber.scala @@ -12,15 +12,13 @@ import scala.jdk.CollectionConverters.CollectionHasAsScala import org.json4s.ParserUtil -class SseException(message: String, cause: Throwable = null) - extends Exception(message, cause) +class SseException(message: String, cause: Throwable = null) extends Exception(message, cause) -class SseSubscriber(messageDataConsumer: Consumer[String]) - extends BodySubscriber[Unit] { +class SseSubscriber(messageDataConsumer: Consumer[String]) extends BodySubscriber[Unit] { @volatile private var subscription: Flow.Subscription = _ - private val future: CompletableFuture[Unit] = new CompletableFuture[Unit] + private val future: CompletableFuture[Unit] = new CompletableFuture[Unit] - private val DoneToken = "[DONE]" + private val DoneToken = "[DONE]" private val MessageType = "message" override def getBody: CompletionStage[Unit] = future @@ -42,7 +40,7 @@ class SseSubscriber(messageDataConsumer: Consumer[String]) @volatile private var incompleteText: Option[SseEventReader.IncompleteEvent] = None - override def onNext(buffers: util.List[ByteBuffer]): Unit = try { + override def onNext(buffers: util.List[ByteBuffer]): Unit = try { val newText = buffers.asScala .map(StandardCharsets.UTF_8.decode) .mkString @@ -51,7 +49,7 @@ class SseSubscriber(messageDataConsumer: Consumer[String]) def consumeEvents( incompleteEvent: Option[SseEventReader.IncompleteEvent], remainingText: String - ): Option[SseEventReader.IncompleteEvent] = { + ): Option[SseEventReader.IncompleteEvent] = SseEventReader.readOneEvent(incompleteEvent, remainingText) match { case SseEventReader.EndOfStream => None @@ -92,7 +90,6 @@ class SseSubscriber(messageDataConsumer: Consumer[String]) case incomplete: SseEventReader.IncompleteEvent => Some(incomplete) } - } this.incompleteText = consumeEvents(this.incompleteText, newText) @@ -107,7 +104,7 @@ class SseSubscriber(messageDataConsumer: Consumer[String]) println(fullBuffer) future.completeExceptionally(pe) subscription.cancel() - case e: Exception => + case e: Exception => future.completeExceptionally(e) subscription.cancel() } diff --git a/src/main/scala/net/eagle0/eagle/Main.scala b/src/main/scala/net/eagle0/eagle/Main.scala index 64e6323659..afdd38b25e 100644 --- a/src/main/scala/net/eagle0/eagle/Main.scala +++ b/src/main/scala/net/eagle0/eagle/Main.scala @@ -12,10 +12,10 @@ import net.eagle0.eagle.service.* object Main { import ServerSetupHelpers.* - private val eagleGrpcPortKey = Symbol("eagleGrpcPort") + private val eagleGrpcPortKey = Symbol("eagleGrpcPort") private val defaultEagleGrpcPort = "40032" - private val shardokInterfaceRemoteAddressKey = Symbol( + private val shardokInterfaceRemoteAddressKey = Symbol( "shardokInterfaceRemoteAddress" ) private val defaultShardokInterfaceRemoteAddress = "eagle0.net:443" @@ -26,26 +26,25 @@ object Main { def nextOption( map: Map[Symbol, String], list: Vector[String] - ): Map[Symbol, String] = { + ): Map[Symbol, String] = list match { - case "--eagle-grpc-port" +: value +: tail => + case "--eagle-grpc-port" +: value +: tail => nextOption(map ++ Map(eagleGrpcPortKey -> value), tail) case "--shardok-interface-remote-address" +: value +: tail => nextOption( map ++ Map(shardokInterfaceRemoteAddressKey -> value), tail ) - case "--gpt-model-name" +: value +: tail => + case "--gpt-model-name" +: value +: tail => nextOption( map ++ Map(gptModelNameKey -> value), tail ) - case option +: _ => + case option +: _ => throw new IllegalArgumentException("Unknown option " + option) case _ => map } - } nextOption(Map(), args.toVector) } diff --git a/src/main/scala/net/eagle0/eagle/RemoveActions.scala b/src/main/scala/net/eagle0/eagle/RemoveActions.scala index 7ab8de0e19..a761aa328f 100644 --- a/src/main/scala/net/eagle0/eagle/RemoveActions.scala +++ b/src/main/scala/net/eagle0/eagle/RemoveActions.scala @@ -23,7 +23,7 @@ object RemoveActions { val persister = new LocalFilePersister( path + gameId.toHexString ) - val history = + val history = PersistedHistory.gameHistoryFromPersister(gameId).get val found = history.recentHistory.indexWhere( @@ -53,8 +53,8 @@ object RemoveActions { } def main(args: Array[String]): Unit = { - val path = args(0) - val gameId = BigInt(args(1), 16).toLong + val path = args(0) + val gameId = BigInt(args(1), 16).toLong val countToTruncate = args(2).toInt truncate(path = path, gameId = gameId, countToTruncate = countToTruncate) diff --git a/src/main/scala/net/eagle0/eagle/SavedGameUtils.scala b/src/main/scala/net/eagle0/eagle/SavedGameUtils.scala index e0b9bdc7bc..2485de880e 100644 --- a/src/main/scala/net/eagle0/eagle/SavedGameUtils.scala +++ b/src/main/scala/net/eagle0/eagle/SavedGameUtils.scala @@ -18,14 +18,13 @@ object MessageComparators { acc: Vector[FieldDescriptor] = Vector() ): Vector[FieldDescriptor] = fieldNames match { case name +: tail => - val field = { + val field = comp.scalaDescriptor.fields .find(_.name == name) .getOrElse { println(s"No field $name in ${comp.scalaDescriptor.name}") sys.exit(1) } - } if tail.isEmpty then acc :+ field else @@ -34,7 +33,7 @@ object MessageComparators { tail, acc :+ field ) - case _ => acc + case _ => acc } def nestedPValue( @@ -50,7 +49,7 @@ object MessageComparators { gm.getFieldByNumber(fd.number).asInstanceOf[GeneratedMessage], tail ) - case _ => gm.toPMessage + case _ => gm.toPMessage } def typedComparison[T]( @@ -59,19 +58,17 @@ object MessageComparators { value: String ): (GeneratedMessage => Boolean) = comparator match { case "=" => - ( - gm => - nestedPValue(gm, fieldDescriptors) match { - case PInt(i) => i == value.toInt - case PDouble(d) => d == value.toDouble - case PString(s) => s == value - case PBoolean(b) => b == value.toBoolean - case PEmpty => value.isEmpty - case x => - throw new NotImplementedError(s"$x pvalue not implemented") - } - ) - case x => throw new NotImplementedError(s"$x comparator not implemented") + gm => + nestedPValue(gm, fieldDescriptors) match { + case PInt(i) => i == value.toInt + case PDouble(d) => d == value.toDouble + case PString(s) => s == value + case PBoolean(b) => b == value.toBoolean + case PEmpty => value.isEmpty + case x => + throw new NotImplementedError(s"$x pvalue not implemented") + } + case x => throw new NotImplementedError(s"$x comparator not implemented") } } @@ -80,9 +77,9 @@ object GameStateFilters { def filter(filter: String): ActionWithResultingState => Boolean = { val (left, rightWithComparator) = filter.span(!comparisonChars.contains(_)) - val (comparator, right) = rightWithComparator.splitAt(1) + val (comparator, right) = rightWithComparator.splitAt(1) - val fieldNames = left.split('.').toVector + val fieldNames = left.split('.').toVector val (prefix, remaining) = fieldNames.splitAt(1) prefix.head match { case "gs" => @@ -121,11 +118,11 @@ object SavedGameUtils { def filterOne( results: Vector[ActionWithResultingState], filter: String - ): Vector[ActionWithResultingState] = { - results.filter { case awrs => - GameStateFilters.filter(filter)(awrs) + ): Vector[ActionWithResultingState] = + results.filter { + case awrs => + GameStateFilters.filter(filter)(awrs) } - } def filteredResults( results: Vector[ActionWithResultingState], @@ -141,9 +138,9 @@ object SavedGameUtils { def fieldValues( results: Vector[ActionWithResultingState], fields: Vector[String] - ): Vector[FieldWithValue] = { + ): Vector[FieldWithValue] = for { - result <- results + result <- results qualifiedFieldName <- fields } yield { val (ident, subfieldNames) = qualifiedFieldName.split('.').splitAt(1) @@ -172,7 +169,6 @@ object SavedGameUtils { ) } } - } def main(args: Array[String]): Unit = { val argList = args.toList @@ -207,8 +203,7 @@ object SavedGameUtils { ) def withoutFilterIndices(indices: Vector[Int]): FilteredResultsState = { - val newFilters = filters.zipWithIndex - .filterNot { case (_, idx) => indices.contains(idx) } + val newFilters = filters.zipWithIndex.filterNot { case (_, idx) => indices.contains(idx) } .map(_._1) this.copy( filters = newFilters, @@ -218,8 +213,7 @@ object SavedGameUtils { def withoutPrintIndices(indices: Vector[Int]): FilteredResultsState = this.copy( - prints = prints.zipWithIndex - .filterNot { case (_, idx) => indices.contains(idx) } + prints = prints.zipWithIndex.filterNot { case (_, idx) => indices.contains(idx) } .map(_._1) ) } @@ -228,12 +222,14 @@ object SavedGameUtils { state: FilteredResultsState ): FilteredResultsState = { println("Your filters:") - state.filters.zipWithIndex.foreach { case (filt, idx) => - println(s" ($idx) $filt") + state.filters.zipWithIndex.foreach { + case (filt, idx) => + println(s" ($idx) $filt") } println("Your prints:") - state.prints.zipWithIndex.foreach { case (pf, idx) => - println(s" ($idx) $pf") + state.prints.zipWithIndex.foreach { + case (pf, idx) => + println(s" ($idx) $pf") } println(s"${state.partialResults.size} filtered results") @@ -248,8 +244,8 @@ object SavedGameUtils { state.withoutFilterIndices(idxStrings.map(_.toInt).toVector) case "dp" :: idxStrings => state.withoutPrintIndices(idxStrings.map(_.toInt).toVector) - case "q" :: _ => sys.exit(0) - case x :: _ => + case "q" :: _ => sys.exit(0) + case x :: _ => println(s"Unknown command $x, stopping") state } diff --git a/src/main/scala/net/eagle0/eagle/TestAIGame.scala b/src/main/scala/net/eagle0/eagle/TestAIGame.scala index b6a341ee5f..eb1ec2e983 100644 --- a/src/main/scala/net/eagle0/eagle/TestAIGame.scala +++ b/src/main/scala/net/eagle0/eagle/TestAIGame.scala @@ -18,8 +18,7 @@ object TestAIGame { (1 to gameCount).foreach { _ => gamesManager.synchronizedCreateGame( - expandedGameParameters = - GameParametersUtils.defaultExpandedGameParameters, + expandedGameParameters = GameParametersUtils.defaultExpandedGameParameters, gameId = Random.nextLong(), humanPlayers = Vector.empty, aiPlayerCount = 5 diff --git a/src/main/scala/net/eagle0/eagle/ai/AIClient.scala b/src/main/scala/net/eagle0/eagle/ai/AIClient.scala index 39dd7e822a..dcf10d77e6 100644 --- a/src/main/scala/net/eagle0/eagle/ai/AIClient.scala +++ b/src/main/scala/net/eagle0/eagle/ai/AIClient.scala @@ -118,7 +118,7 @@ case class AIClient( gs: GameState, functionalRandom: FunctionalRandom ): RandomState[AIClientWithSelectedCommand] = { - val opac = acs.head._2 + val opac = acs.head._2 val oneProvinceAcs = acs.head._2.commands CommandChooser.choose( @@ -215,7 +215,7 @@ case class AIClient( ) match { case RandomState(Some(cs), fr) => RandomState(AIClientWithSelectedCommand(this, Some(cs)), fr) - case RandomState(None, fr) => + case RandomState(None, fr) => if EarlyGameAIClient.isEarlyGame(gs, factionId) then EarlyGameAIClient .chooseEarlyGameCommand( diff --git a/src/main/scala/net/eagle0/eagle/ai/AIClientUtils.scala b/src/main/scala/net/eagle0/eagle/ai/AIClientUtils.scala index 43aaa23f01..69969b292a 100644 --- a/src/main/scala/net/eagle0/eagle/ai/AIClientUtils.scala +++ b/src/main/scala/net/eagle0/eagle/ai/AIClientUtils.scala @@ -14,11 +14,10 @@ object AIClientUtils { gs )).max(0) - def desiredHeroCount(pid: ProvinceId, fid: FactionId, gs: GameState): Int = { + def desiredHeroCount(pid: ProvinceId, fid: FactionId, gs: GameState): Int = if LegacyFactionUtils.hostileNeighbors(pid, fid, gs).nonEmpty then 3 else if gs.provinces(pid).support < 65 then 2 else 1 - } def desiredCountForMarchTowardFocus( originProvince: Province, @@ -55,8 +54,7 @@ object AIClientUtils { originProvince = originProvince, destinationProvince = destinationProvince, availableHeroIds = availableHeroIds, - factionLeaders = - gs.factions(originProvince.rulingFactionId.get).leaders.toVector, + factionLeaders = gs.factions(originProvince.rulingFactionId.get).leaders.toVector, favorLeaders = favorLeaders ), gs, @@ -78,8 +76,7 @@ object AIClientUtils { availableHeroes .sortBy(hero => ( - if favorLeaders then - !LegacyFactionUtils.isFactionLeader(hero.id, gs) + if favorLeaders then !LegacyFactionUtils.isFactionLeader(hero.id, gs) else LegacyFactionUtils.isFactionLeader(hero.id, gs), -LegacyHeroUtils.power(hero) ) diff --git a/src/main/scala/net/eagle0/eagle/ai/EarlyGameAIClient.scala b/src/main/scala/net/eagle0/eagle/ai/EarlyGameAIClient.scala index bb69762190..6dae92be3f 100644 --- a/src/main/scala/net/eagle0/eagle/ai/EarlyGameAIClient.scala +++ b/src/main/scala/net/eagle0/eagle/ai/EarlyGameAIClient.scala @@ -26,7 +26,7 @@ object EarlyGameAIClient { gs: GameState, acs: Vector[AvailableCommand], functionalRandom: FunctionalRandom - ): RandomState[CommandSelection] = { + ): RandomState[CommandSelection] = CommandChooser .choose( actingFactionId = actingFactionId, @@ -40,5 +40,4 @@ object EarlyGameAIClient { functionalRandom = functionalRandom ) .map(_.get) - } } diff --git a/src/main/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRanker.scala b/src/main/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRanker.scala index 611a327a29..68589b5c20 100644 --- a/src/main/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRanker.scala +++ b/src/main/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRanker.scala @@ -36,9 +36,7 @@ object FactionLeaderProvinceRanker { factionId: FactionId, gameState: GameState ): Ordering[Province] = Ordering - .by((p: Province) => - LegacyFactionUtils.hostileNeighbors(p, factionId, gameState).size - ) + .by((p: Province) => LegacyFactionUtils.hostileNeighbors(p, factionId, gameState).size) .reverse // Orders by most-neutral-neighbors-first diff --git a/src/main/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelector.scala b/src/main/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelector.scala index b1c7f1687a..30c9b916e6 100644 --- a/src/main/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelector.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.ai import net.eagle0.common.{FunctionalRandom, RandomState} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - MarchAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, MarchAvailableCommand} import net.eagle0.eagle.api.selected_command.MarchSelectedCommand import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.internal.game_state.GameState @@ -23,53 +20,53 @@ object FixLeaderAloneCommandSelector { randomSelectionForType[MarchAvailableCommand]( availableCommands, functionalRandom - ) { case (ac, frOuter) => - frOuter.nextFlatCollectFirst( - ac.oneProvinceCommands - .filter(opmc => - gameState - .provinces(opmc.originProvinceId) - .rulingFactionHeroIds - .filterNot(LegacyFactionUtils.isFactionLeader(_, gameState)) - .size > 1 - ) - ) { opmc => fr => - opmc.availableDestinationProvinces - .map(dest => gameState.provinces(dest.provinceId)) - .filter(_.rulingFactionId.contains(actingFactionId)) - .filter(_.rulingFactionHeroIds.size == 1) - .filter(dest => - LegacyFactionUtils - .isFactionLeader(dest.rulingFactionHeroIds.head, gameState) - ) - .map { destination => - fr.nextRandomElement(opmc.availableHeroIds) - .map { hid => - CombatUnit(factionId = actingFactionId, heroId = hid) - } - .map { combatUnit => - Some( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = ac.actingProvinceId, - available = ac, - selected = MarchSelectedCommand( - gold = 0, - food = 0, - originProvince = opmc.originProvinceId, - destinationProvinceId = destination.id, - marchingUnits = Vector( - combatUnit - ) - ), - reason = - "Moving a hero so that a faction leader won't be alone" + ) { + case (ac, frOuter) => + frOuter.nextFlatCollectFirst( + ac.oneProvinceCommands + .filter(opmc => + gameState + .provinces(opmc.originProvinceId) + .rulingFactionHeroIds + .filterNot(LegacyFactionUtils.isFactionLeader(_, gameState)) + .size > 1 + ) + ) { opmc => fr => + opmc.availableDestinationProvinces + .map(dest => gameState.provinces(dest.provinceId)) + .filter(_.rulingFactionId.contains(actingFactionId)) + .filter(_.rulingFactionHeroIds.size == 1) + .filter(dest => + LegacyFactionUtils + .isFactionLeader(dest.rulingFactionHeroIds.head, gameState) + ) + .map { destination => + fr.nextRandomElement(opmc.availableHeroIds) + .map { hid => + CombatUnit(factionId = actingFactionId, heroId = hid) + } + .map { combatUnit => + Some( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = ac.actingProvinceId, + available = ac, + selected = MarchSelectedCommand( + gold = 0, + food = 0, + originProvince = opmc.originProvinceId, + destinationProvinceId = destination.id, + marchingUnits = Vector( + combatUnit + ) + ), + reason = "Moving a hero so that a faction leader won't be alone" + ) ) - ) - } - } - .headOption - .getOrElse(RandomState(None, fr)) - } + } + } + .headOption + .getOrElse(RandomState(None, fr)) + } } } diff --git a/src/main/scala/net/eagle0/eagle/ai/InvitationCommandSelector.scala b/src/main/scala/net/eagle0/eagle/ai/InvitationCommandSelector.scala index d5cf307afe..f81ae462a0 100644 --- a/src/main/scala/net/eagle0/eagle/ai/InvitationCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/ai/InvitationCommandSelector.scala @@ -1,17 +1,11 @@ package net.eagle0.eagle.ai -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - DiplomacyAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, DiplomacyAvailableCommand} import net.eagle0.eagle.api.command.util.diplomacy_option.InvitationOption import net.eagle0.eagle.api.selected_command.DiplomacySelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.settings.MinChanceForAIInvite -import net.eagle0.eagle.library.util.command_choice_helpers.{ - ProvinceGoldSurplusCalculator, - TrustForDiplomacy -} +import net.eagle0.eagle.library.util.command_choice_helpers.{ProvinceGoldSurplusCalculator, TrustForDiplomacy} import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.flatSelectionForType import net.eagle0.eagle.library.util.CommandSelection import net.eagle0.eagle.FactionId @@ -27,48 +21,41 @@ object InvitationCommandSelector { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[DiplomacyAvailableCommand](acs = availableCommands) { - diplomacyAvailableCommand => - diplomacyAvailableCommand.options - .collect { case io: InvitationOption => io } - .filter { invitationOption => - TrustForDiplomacy.meetsConditionsForInvitation( - actingFactionId = actingFactionId, - targetFactionId = invitationOption.targetFactionId, - gameState = gameState - ) - } - .filter { invitationOption => - ProvinceGoldSurplusCalculator.provinceGoldSurplus( - diplomacyAvailableCommand.actingProvinceId, - gameState - ) >= invitationOption.goldCost - } - .map { invitationOption => - InvitationOptionWithChance( - invitationOption = invitationOption, - acceptanceChance = - ResolveDiplomacyCommandSelector.invitationAcceptanceChance( - actingFactionId, - invitationOption.targetFactionId, - gameState - ) - ) - } - .maxByOption { _.acceptanceChance } - .filter(_.acceptanceChance >= MinChanceForAIInvite.intValue) - .map { iowc => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = diplomacyAvailableCommand.actingProvinceId, - available = diplomacyAvailableCommand, - selected = DiplomacySelectedCommand( - selectedOption = iowc.invitationOption, - targetFactionId = iowc.invitationOption.targetFactionId, - sentHeroId = diplomacyAvailableCommand.recommendedHeroId - ), - reason = "maybeInviteOtherFaction" - ) - } + flatSelectionForType[DiplomacyAvailableCommand](acs = availableCommands) { diplomacyAvailableCommand => + diplomacyAvailableCommand.options.collect { case io: InvitationOption => io }.filter { invitationOption => + TrustForDiplomacy.meetsConditionsForInvitation( + actingFactionId = actingFactionId, + targetFactionId = invitationOption.targetFactionId, + gameState = gameState + ) + }.filter { invitationOption => + ProvinceGoldSurplusCalculator.provinceGoldSurplus( + diplomacyAvailableCommand.actingProvinceId, + gameState + ) >= invitationOption.goldCost + }.map { invitationOption => + InvitationOptionWithChance( + invitationOption = invitationOption, + acceptanceChance = ResolveDiplomacyCommandSelector.invitationAcceptanceChance( + actingFactionId, + invitationOption.targetFactionId, + gameState + ) + ) + }.maxByOption(_.acceptanceChance) + .filter(_.acceptanceChance >= MinChanceForAIInvite.intValue) + .map { iowc => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = diplomacyAvailableCommand.actingProvinceId, + available = diplomacyAvailableCommand, + selected = DiplomacySelectedCommand( + selectedOption = iowc.invitationOption, + targetFactionId = iowc.invitationOption.targetFactionId, + sentHeroId = diplomacyAvailableCommand.recommendedHeroId + ), + reason = "maybeInviteOtherFaction" + ) + } } } diff --git a/src/main/scala/net/eagle0/eagle/ai/MarchTowardProvinceCommandChooser.scala b/src/main/scala/net/eagle0/eagle/ai/MarchTowardProvinceCommandChooser.scala index 9e3ea8a5a4..6d2aaa18a4 100644 --- a/src/main/scala/net/eagle0/eagle/ai/MarchTowardProvinceCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/ai/MarchTowardProvinceCommandChooser.scala @@ -1,18 +1,11 @@ package net.eagle0.eagle.ai import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - MarchAvailableCommand, - MarchCommandFromOneProvince -} +import net.eagle0.eagle.api.available_command.{MarchAvailableCommand, MarchCommandFromOneProvince} import net.eagle0.eagle.api.selected_command.MarchSelectedCommand import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.util.{ - CommandSelection, - LegacyBattalionUtils, - ProvinceDistances -} +import net.eagle0.eagle.library.util.{CommandSelection, LegacyBattalionUtils, ProvinceDistances} import net.eagle0.eagle.library.util.command_choice_helpers.ProvinceGoldSurplusCalculator.provinceGoldSurplus import net.eagle0.eagle.library.util.EagleRequire.internalRequire @@ -28,79 +21,80 @@ object MarchTowardProvinceCommandChooser { val bestCommand = opmc.availableDestinationProvinces .map(dest => (opmc, gs.provinces(dest.provinceId))) - .flatMap { case (opmc, p) => - ProvinceDistances - .distanceThroughFriendliesOption( - destinationProvinceId, - p.id, - fid, - gs - ) - .map(distance => (opmc, p, distance)) + .flatMap { + case (opmc, p) => + ProvinceDistances + .distanceThroughFriendliesOption( + destinationProvinceId, + p.id, + fid, + gs + ) + .map(distance => (opmc, p, distance)) } .minByOption(_._3) val actingProvinceId = ac.actingProvinceId - bestCommand.flatMap { case (opmc, dest, _) => - internalRequire( - opmc.originProvinceId != destinationProvinceId, - s"Marching away from $destinationProvinceId in an effort to get to that province" - ) - - val originProvince = gs.provinces(opmc.originProvinceId) - - val takenHeroIds = - AIClientUtils.takenHeroIdsForMarchTowardFocus( - originProvince = originProvince, - destinationProvince = dest, - availableHeroIds = opmc.availableHeroIds.toVector, - favorLeaders = favorLeaders, - gs = gs + bestCommand.flatMap { + case (opmc, dest, _) => + internalRequire( + opmc.originProvinceId != destinationProvinceId, + s"Marching away from $destinationProvinceId in an effort to get to that province" ) - Option.when(takenHeroIds.nonEmpty) { - val takenBattalions = - if originProvince.battalionIds.size <= takenHeroIds.size then - originProvince.battalionIds.map(gs.battalions) - else - originProvince.battalionIds - .map(gs.battalions) - .sortBy(_.size) - .take(takenHeroIds.size) + val originProvince = gs.provinces(opmc.originProvinceId) - val takenUnits = takenHeroIds - .zipAll( - takenBattalions.map(batt => Some(batt.id)), - 0, - None + val takenHeroIds = + AIClientUtils.takenHeroIdsForMarchTowardFocus( + originProvince = originProvince, + destinationProvince = dest, + availableHeroIds = opmc.availableHeroIds.toVector, + favorLeaders = favorLeaders, + gs = gs ) - .map { case (hid, bid) => - CombatUnit(factionId = fid, heroId = hid, battalionId = bid) - } - val foodToTake = 2 * LegacyBattalionUtils.monthlyConsumedFood( - takenBattalions, - gs.battalionTypes.toVector - ) - val goldToTake = provinceGoldSurplus(originProvince.id, gs) - CommandSelection( - actingFactionId = fid, - actingProvinceId = actingProvinceId, - available = ac, - selected = MarchSelectedCommand( - marchingUnits = takenUnits, // Check the food cost here? - destinationProvinceId = dest.id, - originProvince = opmc.originProvinceId, - gold = Math.min(goldToTake, opmc.goldAvailable), - food = Math.min(foodToTake, opmc.foodAvailable) - ), - reason = if favorLeaders then - s"marching leaders toward ${gs.provinces(destinationProvinceId).name}" - else - s"marching heroes toward ${gs.provinces(destinationProvinceId).name}" - ) - } + Option.when(takenHeroIds.nonEmpty) { + val takenBattalions = + if originProvince.battalionIds.size <= takenHeroIds.size then originProvince.battalionIds.map(gs.battalions) + else + originProvince.battalionIds + .map(gs.battalions) + .sortBy(_.size) + .take(takenHeroIds.size) + + val takenUnits = takenHeroIds + .zipAll( + takenBattalions.map(batt => Some(batt.id)), + 0, + None + ) + .map { + case (hid, bid) => + CombatUnit(factionId = fid, heroId = hid, battalionId = bid) + } + + val foodToTake = 2 * LegacyBattalionUtils.monthlyConsumedFood( + takenBattalions, + gs.battalionTypes.toVector + ) + val goldToTake = provinceGoldSurplus(originProvince.id, gs) + CommandSelection( + actingFactionId = fid, + actingProvinceId = actingProvinceId, + available = ac, + selected = MarchSelectedCommand( + marchingUnits = takenUnits, // Check the food cost here? + destinationProvinceId = dest.id, + originProvince = opmc.originProvinceId, + gold = Math.min(goldToTake, opmc.goldAvailable), + food = Math.min(foodToTake, opmc.foodAvailable) + ), + reason = + if favorLeaders then s"marching leaders toward ${gs.provinces(destinationProvinceId).name}" + else s"marching heroes toward ${gs.provinces(destinationProvinceId).name}" + ) + } } } } diff --git a/src/main/scala/net/eagle0/eagle/ai/MidGameAIClient.scala b/src/main/scala/net/eagle0/eagle/ai/MidGameAIClient.scala index 93168419b9..73a44196b5 100644 --- a/src/main/scala/net/eagle0/eagle/ai/MidGameAIClient.scala +++ b/src/main/scala/net/eagle0/eagle/ai/MidGameAIClient.scala @@ -5,19 +5,13 @@ import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.ai.AIClientUtils.extraHeroCount import net.eagle0.eagle.api.available_command.* import net.eagle0.eagle.api.command.OneProvinceAvailableCommands -import net.eagle0.eagle.api.selected_command.{ - MarchSelectedCommand, - ReconSelectedCommand -} +import net.eagle0.eagle.api.selected_command.{MarchSelectedCommand, ReconSelectedCommand} import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.improvement_type.ImprovementType import net.eagle0.eagle.internal.faction_relationship.FactionRelationship import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - MinSupportForTaxes, - MonthsReconConsideredRecent -} +import net.eagle0.eagle.library.settings.{MinSupportForTaxes, MonthsReconConsideredRecent} import net.eagle0.eagle.library.util.* import net.eagle0.eagle.library.util.command_choice_helpers.{ AlmsCommandSelector, @@ -141,20 +135,20 @@ object MidGameAIClient { _ /* availableHeroIds */, _ /* unknownFieldSet */ ) => - val actingProvince = gameState.provinces(actingProvinceId) + val actingProvince = gameState.provinces(actingProvinceId) val foodMonthsToHoldBack = FoodConsumptionUtils.foodConsumptionMonthsToHold( actingProvinceId, gameState ) - val foodToHoldBack = + val foodToHoldBack = foodMonthsToHoldBack * LegacyProvinceUtils.monthlyFoodConsumption( actingProvinceId, gameState ) - val maxFoodToSend = + val maxFoodToSend = Math.min(actingProvince.food - foodToHoldBack, foodAvailable) - val maxGoldToSend = Math.min( + val maxGoldToSend = Math.min( ProvinceGoldSurplusCalculator .provinceGoldSurplus(actingProvinceId, gameState), goldAvailable @@ -172,12 +166,12 @@ object MidGameAIClient { .map(gameState.provinces) .filter(_.rulingFactionId.contains(factionId)) .map { province => - val consumption = LegacyProvinceUtils + val consumption = LegacyProvinceUtils .monthlyFoodConsumption(province.id, gameState) - val incomingFood = + val incomingFood = province.incomingShipments.flatMap(_.supplies).map(_.food).sum val availableFood = province.food + incomingFood - val monthsOfFood = + val monthsOfFood = if consumption == 0 then 120 else availableFood / consumption DestinationFoodStatus( @@ -189,29 +183,28 @@ object MidGameAIClient { .filter(_.monthsOfFood < 4) .minByOption(_.monthsOfFood) - bestDestination - .map { destinationFoodStatus => - val destinationProvince = destinationFoodStatus.province - val desiredFood = LegacyProvinceUtils.monthlyFoodConsumption( - destinationProvince.id, - gameState - ) * 6 - destinationProvince.food - val foodToSend = - if desiredFood > maxFoodToSend then maxFoodToSend - else (desiredFood + maxFoodToSend) / 2 + bestDestination.map { destinationFoodStatus => + val destinationProvince = destinationFoodStatus.province + val desiredFood = LegacyProvinceUtils.monthlyFoodConsumption( + destinationProvince.id, + gameState + ) * 6 - destinationProvince.food + val foodToSend = + if desiredFood > maxFoodToSend then maxFoodToSend + else (desiredFood + maxFoodToSend) / 2 - CommandChoiceHelpers - .chosenSendSuppliesCommandWithSuppliesAndDestination( - actingFactionId = factionId, - gameState = gameState, - ac = available, - supplies = Supplies( - gold = maxGoldToSend / 2, - food = foodToSend - ), - destination = destinationFoodStatus.province.id - ) - } + CommandChoiceHelpers + .chosenSendSuppliesCommandWithSuppliesAndDestination( + actingFactionId = factionId, + gameState = gameState, + ac = available, + supplies = Supplies( + gold = maxGoldToSend / 2, + food = foodToSend + ), + destination = destinationFoodStatus.province.id + ) + } } } .map(_.withReason("relay supplies")) @@ -335,71 +328,70 @@ object MidGameAIClient { availableCommands: Vector[AvailableCommand], functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = - provincesWithFactionLeader(actingFactionId, gameState) - .map { province => - MoreOption - .flatWhen(province.rulingFactionHeroIds.size < 4)( - maybeMoveHeroesTowardFactionLeaderCommand( - actingFactionId = actingFactionId, - gs = gameState, - acs = availableCommands - ) - ) match { - case Some(cs) => RandomState(Some(cs), functionalRandom) - case None => - chosenGenericCommandFromRankedOptions( - actingFactionId = actingFactionId, - gs = gameState, - acs = availableCommands, - choosersAndReasons = Vector( - ( - ExpandCommandSelector.maybeChosenExpandCommand, - "no hostile neighbors, expand" - ), - ( - maybeMoveToRecruitCommand, - "no hostile neighbors, travel to recruit" - ), - ( - ( - actingFactionId, - gameState, - availableCommands, - functionalRandom - ) => - RandomState( - ImproveCommandSelector.chosenImproveCommand( - actingFactionId, - gameState, - availableCommands - ), - functionalRandom - ), - "chosen neutral neighbors: Improve b/c nothing better" - ), - ( - ( - actingFactionId, - gameState, - availableCommands, - functionalRandom - ) => - RandomState( - chosenRestCommand( - actingFactionId, - gameState, - availableCommands, - "chosen neutral neighbors: rest" - ), - functionalRandom - ), - "chosen neutral neighbors: rest" - ) + provincesWithFactionLeader(actingFactionId, gameState).map { province => + MoreOption + .flatWhen(province.rulingFactionHeroIds.size < 4)( + maybeMoveHeroesTowardFactionLeaderCommand( + actingFactionId = actingFactionId, + gs = gameState, + acs = availableCommands + ) + ) match { + case Some(cs) => RandomState(Some(cs), functionalRandom) + case None => + chosenGenericCommandFromRankedOptions( + actingFactionId = actingFactionId, + gs = gameState, + acs = availableCommands, + choosersAndReasons = Vector( + ( + ExpandCommandSelector.maybeChosenExpandCommand, + "no hostile neighbors, expand" ), - functionalRandom = functionalRandom - ) - } + ( + maybeMoveToRecruitCommand, + "no hostile neighbors, travel to recruit" + ), + ( + ( + actingFactionId, + gameState, + availableCommands, + functionalRandom + ) => + RandomState( + ImproveCommandSelector.chosenImproveCommand( + actingFactionId, + gameState, + availableCommands + ), + functionalRandom + ), + "chosen neutral neighbors: Improve b/c nothing better" + ), + ( + ( + actingFactionId, + gameState, + availableCommands, + functionalRandom + ) => + RandomState( + chosenRestCommand( + actingFactionId, + gameState, + availableCommands, + "chosen neutral neighbors: rest" + ), + functionalRandom + ), + "chosen neutral neighbors: rest" + ) + ), + functionalRandom = functionalRandom + ) } + } .find(_.newValue.isDefined) .get @@ -410,85 +402,84 @@ object MidGameAIClient { functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = { import net.eagle0.eagle.library.util.command_choice_helpers.CommandChooserImplicits.DeterministicCommandChooser - provincesWithFactionLeader(actingFactionId, gameState) - .map { province => - MoreOption - .flatWhen(province.rulingFactionHeroIds.size < 4)( - maybeMoveHeroesTowardFactionLeaderCommand( - actingFactionId = actingFactionId, - gs = gameState, - acs = availableCommands - ) - ) match { - case Some(cs) => RandomState(Some(cs), functionalRandom) - case None => - chosenGenericCommandFromRankedOptions( - actingFactionId = actingFactionId, - gs = gameState, - acs = availableCommands, - choosersAndReasons = Vector( + provincesWithFactionLeader(actingFactionId, gameState).map { province => + MoreOption + .flatWhen(province.rulingFactionHeroIds.size < 4)( + maybeMoveHeroesTowardFactionLeaderCommand( + actingFactionId = actingFactionId, + gs = gameState, + acs = availableCommands + ) + ) match { + case Some(cs) => RandomState(Some(cs), functionalRandom) + case None => + chosenGenericCommandFromRankedOptions( + actingFactionId = actingFactionId, + gs = gameState, + acs = availableCommands, + choosersAndReasons = Vector( + ( + maybeMoveToRecruitCommand, + "chosen no neutral neighbors, travel to recruit" + ), + ( ( - maybeMoveToRecruitCommand, - "chosen no neutral neighbors, travel to recruit" - ), - ( - ( - actingFactionId, - gameState, - availableCommands, - functionalRandom - ) => - RandomState( - MoveLeaderToBetterProvinceCommandChooser - .maybeMoveLeaderToBetterProvinceCommand( - actingFactionId, - gameState, - availableCommands - ), - functionalRandom - ), - "chosen no neutral neighbors, travel to front" - ), - ( - ( - actingFactionId, - gameState, - availableCommands, - functionalRandom - ) => - RandomState( - ImproveCommandSelector.chosenImproveCommand( + actingFactionId, + gameState, + availableCommands, + functionalRandom + ) => + RandomState( + MoveLeaderToBetterProvinceCommandChooser + .maybeMoveLeaderToBetterProvinceCommand( actingFactionId, gameState, availableCommands ), - functionalRandom - ), - "chosen no neutral neighbors: Improve b/c nothing better" - ), + functionalRandom + ), + "chosen no neutral neighbors, travel to front" + ), + ( ( - ( + actingFactionId, + gameState, + availableCommands, + functionalRandom + ) => + RandomState( + ImproveCommandSelector.chosenImproveCommand( + actingFactionId, + gameState, + availableCommands + ), + functionalRandom + ), + "chosen no neutral neighbors: Improve b/c nothing better" + ), + ( + ( + actingFactionId, + gameState, + availableCommands, + functionalRandom + ) => + RandomState( + chosenRestCommand( actingFactionId, gameState, availableCommands, - functionalRandom - ) => - RandomState( - chosenRestCommand( - actingFactionId, - gameState, - availableCommands, - "chosen no neutral neighbors: rest" - ), - functionalRandom + "chosen no neutral neighbors: rest" ), - "chosen neutral neighbors: rest" - ) - ), - functionalRandom = functionalRandom - ) - } + functionalRandom + ), + "chosen neutral neighbors: rest" + ) + ), + functionalRandom = functionalRandom + ) } + } .find(_.newValue.isDefined) .get } @@ -503,11 +494,11 @@ object MidGameAIClient { .reconnedProvinces .find(_.id == provinceId) .flatMap(_.fullInfo) - def reconnedHeroCountFor(provinceId: ProvinceId): Int = + def reconnedHeroCountFor(provinceId: ProvinceId): Int = reconnedFullInfoFor(provinceId) .map(_.rulingFactionHeroIds.size) .getOrElse(0) - def reconnedBattalionsFor(provinceId: ProvinceId): Vector[BattalionView] = + def reconnedBattalionsFor(provinceId: ProvinceId): Vector[BattalionView] = reconnedFullInfoFor(provinceId) .map(_.battalions.toVector) .getOrElse(Vector()) @@ -673,8 +664,7 @@ object MidGameAIClient { } } ), - (fid, gs, acs, fr) => - chosenNoNeutralNeighborsCommand(fid, gs, acs, fr) + (fid, gs, acs, fr) => chosenNoNeutralNeighborsCommand(fid, gs, acs, fr) ), functionalRandom = functionalRandom ) @@ -696,7 +686,7 @@ object MidGameAIClient { factionId: FactionId ): Option[CommandSelection] = flatSelectionForType[ImproveAvailableCommand](acs) { availableCommand => - val province = gs.provinces(availableCommand.actingProvinceId) + val province = gs.provinces(availableCommand.actingProvinceId) val existingBattalions = province.battalionIds .map(gs.battalions) @@ -725,7 +715,7 @@ object MidGameAIClient { .map(_.minimumAgriculture - province.agriculture) .filter(_ > 0) .min - val neededEconomy = notAvailable + val neededEconomy = notAvailable .map(_.minimumEconomy - province.economy) .filter(_ > 0) .min @@ -870,7 +860,7 @@ object MidGameAIClient { case (None, fr2) => go(RandomState(tail, fr2)) } } - case (_, fr) => RandomState(None, fr) + case (_, fr) => RandomState(None, fr) } go( @@ -889,35 +879,34 @@ object MidGameAIClient { val factionLeaderProvincesNeedingHeroes = provincesWithFactionLeader(actingFactionId, gs) .filter(p => p.rulingFactionHeroIds.size < p.heroCap) - val cs = for { + val cs = for { (marchCommand, idx) <- acs.zipWithIndex.collectFirst { - case (ac: MarchAvailableCommand, idx) => (ac, idx) - } + case (ac: MarchAvailableCommand, idx) => (ac, idx) + } } yield { // Find the march command origin provinces that contain extra heroes val candidateCommands = marchCommand.oneProvinceCommands.filter { opmc => extraHeroCount(opmc.originProvinceId, actingFactionId, gs) > 0 } - val furthestOrigin = candidateCommands - .flatMap { opmc => - // distance to the faction leader province we're closest to - factionLeaderProvincesNeedingHeroes - .flatMap { flp => - ProvinceDistances - .distanceThroughFriendliesOption( - p1 = flp.id, - p2 = opmc.originProvinceId, - fid = actingFactionId, - gs = gs - ) - .map { - (_: Int, flp.id: ProvinceId) - } + val furthestOrigin = candidateCommands.flatMap { opmc => + // distance to the faction leader province we're closest to + factionLeaderProvincesNeedingHeroes.flatMap { flp => + ProvinceDistances + .distanceThroughFriendliesOption( + p1 = flp.id, + p2 = opmc.originProvinceId, + fid = actingFactionId, + gs = gs + ) + .map { + (_: Int, flp.id: ProvinceId) } - .minByOption(_._1) - .filterNot(_._1 == 0) // If distance is zero, we'd be moving away from the province we're trying to get to - .map { case (distance: Int, destinationProvinceId: ProvinceId) => + } + .minByOption(_._1) + .filterNot(_._1 == 0) // If distance is zero, we'd be moving away from the province we're trying to get to + .map { + case (distance: Int, destinationProvinceId: ProvinceId) => ( // distance to the faction leader province we're closest to distance, @@ -925,21 +914,22 @@ object MidGameAIClient { extraHeroCount(opmc.originProvinceId, actingFactionId, gs), opmc ) - } - } + } + } .maxByOption(tup => (tup._1, tup._3)) - .map { tup => (tup._2, tup._4) } + .map(tup => (tup._2, tup._4)) - furthestOrigin.flatMap { case (destinationProvinceId, opmc) => - MarchTowardProvinceCommandChooser - .marchTowardProvinceCommand( - ac = marchCommand, - fid = actingFactionId, - opmc = opmc, - destinationProvinceId = destinationProvinceId, - gs = gs, - favorLeaders = false - ) + furthestOrigin.flatMap { + case (destinationProvinceId, opmc) => + MarchTowardProvinceCommandChooser + .marchTowardProvinceCommand( + ac = marchCommand, + fid = actingFactionId, + opmc = opmc, + destinationProvinceId = destinationProvinceId, + gs = gs, + favorLeaders = false + ) } } @@ -957,8 +947,7 @@ object MidGameAIClient { actingProvinceId = ac.actingProvinceId, available = ac, selected = ReconSelectedCommand( - actingHeroId = - ac.availableHeroIds.maxBy(hid => gameState.heroes(hid).vigor), + actingHeroId = ac.availableHeroIds.maxBy(hid => gameState.heroes(hid).vigor), targetProvinceId = targetProvinceId ), reason = "selectedReconCommand" @@ -1046,11 +1035,11 @@ object MidGameAIClient { gameState: GameState, acs: Vector[AvailableCommand] ): Option[CommandSelection] = { - val faction = gameState.factions(actingFactionId) + val faction = gameState.factions(actingFactionId) val factionLeaders = faction.leaders flatSelectionForType[MarchAvailableCommand](acs) { marchAvailableCommand => marchAvailableCommand.oneProvinceCommands.flatMap { opmc => - val originProvince = gameState.provinces(opmc.originProvinceId) + val originProvince = gameState.provinces(opmc.originProvinceId) val leadersInOriginProvince = originProvince.rulingFactionHeroIds.intersect(factionLeaders) MoreOption.flatWhen( @@ -1058,7 +1047,7 @@ object MidGameAIClient { .intersect(factionLeaders) .nonEmpty ) { - val leaderIdToMove = + val leaderIdToMove = opmc.availableHeroIds .intersect(factionLeaders) .maxBy(hid => LegacyHeroUtils.seniorityOrder(faction, hid)) @@ -1074,27 +1063,26 @@ object MidGameAIClient { IncomingArmyUtils.isUnderAttack(province, gameState) ) // don't send a leader into a province under attack - validDestinations.minByOption(_.rulingFactionHeroIds.size).map { - destinationProvince => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = marchAvailableCommand.actingProvinceId, - available = marchAvailableCommand, - selected = MarchSelectedCommand( - gold = 0, - food = 0, - originProvince = originProvince.id, - destinationProvinceId = destinationProvince.id, - marchingUnits = Vector( - CombatUnit( - factionId = actingFactionId, - heroId = leaderIdToMove, - battalionId = None - ) + validDestinations.minByOption(_.rulingFactionHeroIds.size).map { destinationProvince => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = marchAvailableCommand.actingProvinceId, + available = marchAvailableCommand, + selected = MarchSelectedCommand( + gold = 0, + food = 0, + originProvince = originProvince.id, + destinationProvinceId = destinationProvince.id, + marchingUnits = Vector( + CombatUnit( + factionId = actingFactionId, + heroId = leaderIdToMove, + battalionId = None ) - ), - reason = "Spreading out the faction leaders" - ) + ) + ), + reason = "Spreading out the faction leaders" + ) } } }.headOption diff --git a/src/main/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooser.scala b/src/main/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooser.scala index 19c55a0071..5165696a60 100644 --- a/src/main/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooser.scala @@ -1,11 +1,7 @@ package net.eagle0.eagle.ai import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - MarchAvailableCommand, - MarchCommandFromOneProvince -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, MarchAvailableCommand, MarchCommandFromOneProvince} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.CommandSelection @@ -30,8 +26,7 @@ object MoveLeaderToBetterProvinceCommandChooser { actingFactionId = actingFactionId, gs = gs, acs = acs, - betterDestinationChooser = - FactionLeaderProvinceRanker.bestSettlementPidForFactionLeader + betterDestinationChooser = FactionLeaderProvinceRanker.bestSettlementPidForFactionLeader ) private def candidatesForMarchCommand( @@ -57,22 +52,21 @@ object MoveLeaderToBetterProvinceCommandChooser { actingFactionId, mcfop.originProvinceId, gs - ) - .flatMap { desiredPid => - ProvinceDistances - .closestProvinceThroughFriendliesOption( - desiredPid, - mcfop.availableDestinationProvinces.map(_.provinceId).toVector, - actingFactionId, - gs + ).flatMap { desiredPid => + ProvinceDistances + .closestProvinceThroughFriendliesOption( + desiredPid, + mcfop.availableDestinationProvinces.map(_.provinceId).toVector, + actingFactionId, + gs + ) + .map { provinceAndDistance => + MCFOPWithDestinationAndDistance( + mcfop = mcfop, + provinceAndDistance = provinceAndDistance ) - .map { provinceAndDistance => - MCFOPWithDestinationAndDistance( - mcfop = mcfop, - provinceAndDistance = provinceAndDistance - ) - } - } + } + } } def maybeMoveLeaderToBetterProvinceCommandWithChooser( @@ -82,15 +76,14 @@ object MoveLeaderToBetterProvinceCommandChooser { betterDestinationChooser: DestinationChooser ): Option[CommandSelection] = { val cs = for { - faction <- gs.factions.get(actingFactionId) + faction <- gs.factions.get(actingFactionId) marchCommand <- acs.collectFirst { case ac: MarchAvailableCommand => ac } } yield { // Find the march command origin provinces that contain a faction leader val candidatesWithDistances = candidateCommandsWithDistances( actingFactionId = actingFactionId, gs = gs, - candidateCommands = - candidatesForMarchCommand(marchCommand, gs, faction), + candidateCommands = candidatesForMarchCommand(marchCommand, gs, faction), betterDestinationChooser = betterDestinationChooser ) diff --git a/src/main/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelector.scala b/src/main/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelector.scala index 48c3f55f30..f9cdc07ade 100644 --- a/src/main/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelector.scala @@ -77,23 +77,24 @@ object ResolveDiplomacyCommandSelector { randomSelectionForType[ResolveInvitationAvailableCommand]( availableCommands, functionalRandom - ) { case (resolveInvitationAc, fr) => - selectionForResolveInvitationCommand( - actingFactionId = actingFactionId, - ac = resolveInvitationAc, - gs = gameState, - functionalRandom = fr - ).map { resolveInviteSelection => - Some( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = 0, - available = resolveInvitationAc, - selected = resolveInviteSelection, - reason = "resolving invitation" + ) { + case (resolveInvitationAc, fr) => + selectionForResolveInvitationCommand( + actingFactionId = actingFactionId, + ac = resolveInvitationAc, + gs = gameState, + functionalRandom = fr + ).map { resolveInviteSelection => + Some( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = 0, + available = resolveInvitationAc, + selected = resolveInviteSelection, + reason = "resolving invitation" + ) ) - ) - } + } } private def selectionForResolveInvitationCommand( @@ -102,11 +103,9 @@ object ResolveDiplomacyCommandSelector { gs: GameState, functionalRandom: FunctionalRandom ): RandomState[SelectedCommand] = functionalRandom.nextDouble.map { roll => - val invitedFid = actingFactionId + val invitedFid = actingFactionId val bestInvitation = ac.invitations - .maxBy(inv => - invitationAcceptanceChance(inv.originatingFactionId, invitedFid, gs) - ) + .maxBy(inv => invitationAcceptanceChance(inv.originatingFactionId, invitedFid, gs)) internalRequire( bestInvitation.eligibleStatuses.contains(DIPLOMACY_OFFER_STATUS_ACCEPTED), @@ -150,23 +149,24 @@ object ResolveDiplomacyCommandSelector { randomSelectionForType[ResolveTruceOfferAvailableCommand]( availableCommands, functionalRandom - ) { case (resolveTruceAc, fr) => - selectionForResolveTruceOfferSelectedCommand( - actingFactionId = actingFactionId, - ac = resolveTruceAc, - gs = gameState, - functionalRandom = fr - ).map { resolveTruceOfferSelection => - Some( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = 0, - available = resolveTruceAc, - selected = resolveTruceOfferSelection, - reason = "resolving truce offer" + ) { + case (resolveTruceAc, fr) => + selectionForResolveTruceOfferSelectedCommand( + actingFactionId = actingFactionId, + ac = resolveTruceAc, + gs = gameState, + functionalRandom = fr + ).map { resolveTruceOfferSelection => + Some( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = 0, + available = resolveTruceAc, + selected = resolveTruceOfferSelection, + reason = "resolving truce offer" + ) ) - ) - } + } } private def selectionForResolveTruceOfferSelectedCommand( @@ -177,9 +177,7 @@ object ResolveDiplomacyCommandSelector { ): RandomState[SelectedCommand] = functionalRandom.nextDouble.map { roll => val actingFid = actingFactionId val bestOffer = ac.offers - .maxBy(inv => - truceOfferAcceptanceChance(inv.originatingFactionId, actingFid, gs) - ) + .maxBy(inv => truceOfferAcceptanceChance(inv.originatingFactionId, actingFid, gs)) internalRequire( bestOffer.eligibleStatuses.contains(DIPLOMACY_OFFER_STATUS_ACCEPTED), @@ -225,7 +223,7 @@ object ResolveDiplomacyCommandSelector { originatingFid: FactionId, targetFid: FactionId, gs: GameState - ): Int = { + ): Int = // Always reject if the faction already has an alliance if gs .factions(targetFid) @@ -235,11 +233,10 @@ object ResolveDiplomacyCommandSelector { // reject if this is our only neighbor and we have no expansion possibilities else if LegacyFactionUtils.provinces(targetFid, gs).forall { province => - province.neighbors.map { n => gs.provinces(n.provinceId) }.forall { - neighborProvince => - neighborProvince.rulingFactionId.contains( - originatingFid - ) || neighborProvince.rulingFactionId.contains(targetFid) + province.neighbors.map(n => gs.provinces(n.provinceId)).forall { neighborProvince => + neighborProvince.rulingFactionId.contains( + originatingFid + ) || neighborProvince.rulingFactionId.contains(targetFid) } } then 0 @@ -254,26 +251,24 @@ object ResolveDiplomacyCommandSelector { gameState = gs ) ).floor.toInt.max(0) - } private def resolveRansomOfferSelectedCommand( actingFactionId: FactionId, gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[ResolveRansomOfferAvailableCommand](availableCommands) { - resolveRansomAc => - CommandSelection( + selectionForType[ResolveRansomOfferAvailableCommand](availableCommands) { resolveRansomAc => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = 0, + available = resolveRansomAc, + selected = selectionForResolveRansomOfferSelectedCommand( actingFactionId = actingFactionId, - actingProvinceId = 0, - available = resolveRansomAc, - selected = selectionForResolveRansomOfferSelectedCommand( - actingFactionId = actingFactionId, - ac = resolveRansomAc, - gs = gameState - ), - reason = "resolving ransom offer" - ) + ac = resolveRansomAc, + gs = gameState + ), + reason = "resolving ransom offer" + ) } private def selectionForResolveRansomOfferSelectedCommand( @@ -288,7 +283,7 @@ object ResolveDiplomacyCommandSelector { ransomOffer = Some(ac.offers.head), resolution = RansomOfferHelpers.chosenResolution(rod) ) - case _ => throw new EagleInternalException("Not a ransom offer") + case _ => throw new EagleInternalException("Not a ransom offer") } private def resolveAllianceOfferSelectedCommand( @@ -300,23 +295,24 @@ object ResolveDiplomacyCommandSelector { randomSelectionForType[ResolveAllianceOfferAvailableCommand]( availableCommands, functionalRandom - ) { case (resolveAllianceAc, fr) => - selectionForResolveAllianceOfferSelectedCommand( - actingFactionId = actingFactionId, - ac = resolveAllianceAc, - gs = gameState, - functionalRandom = fr - ).map { resolveAllianceOfferSelection => - Some( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = 0, - available = resolveAllianceAc, - selected = resolveAllianceOfferSelection, - reason = "resolving alliance offer" + ) { + case (resolveAllianceAc, fr) => + selectionForResolveAllianceOfferSelectedCommand( + actingFactionId = actingFactionId, + ac = resolveAllianceAc, + gs = gameState, + functionalRandom = fr + ).map { resolveAllianceOfferSelection => + Some( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = 0, + available = resolveAllianceAc, + selected = resolveAllianceOfferSelection, + reason = "resolving alliance offer" + ) ) - ) - } + } } private def resolveBreakAllianceSelectedCommand( @@ -328,23 +324,24 @@ object ResolveDiplomacyCommandSelector { randomSelectionForType[ResolveBreakAllianceAvailableCommand]( availableCommands, functionalRandom - ) { case (resolveBreakAllianceAc, fr) => - selectionForResolveBreakAllianceSelectedCommand( - actingFactionId = actingFactionId, - ac = resolveBreakAllianceAc, - gs = gameState, - functionalRandom = fr - ).map { resolveBreakAllianceSelection => - Some( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = 0, - available = resolveBreakAllianceAc, - selected = resolveBreakAllianceSelection, - reason = "resolving break alliance" + ) { + case (resolveBreakAllianceAc, fr) => + selectionForResolveBreakAllianceSelectedCommand( + actingFactionId = actingFactionId, + ac = resolveBreakAllianceAc, + gs = gameState, + functionalRandom = fr + ).map { resolveBreakAllianceSelection => + Some( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = 0, + available = resolveBreakAllianceAc, + selected = resolveBreakAllianceSelection, + reason = "resolving break alliance" + ) ) - ) - } + } } private def selectionForResolveAllianceOfferSelectedCommand( @@ -355,9 +352,7 @@ object ResolveDiplomacyCommandSelector { ): RandomState[SelectedCommand] = functionalRandom.nextDouble.map { roll => val actingFid = actingFactionId val bestOffer = ac.offers - .maxBy(inv => - allianceOfferAcceptanceChance(inv.originatingFactionId, actingFid, gs) - ) + .maxBy(inv => allianceOfferAcceptanceChance(inv.originatingFactionId, actingFid, gs)) internalRequire( bestOffer.eligibleStatuses.contains(DIPLOMACY_OFFER_STATUS_ACCEPTED), diff --git a/src/main/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooser.scala b/src/main/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooser.scala index 67e4759e21..47cdc1af60 100644 --- a/src/main/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooser.scala @@ -1,19 +1,13 @@ package net.eagle0.eagle.ai import net.eagle0.common.MoreOption -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - MarchAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, MarchAvailableCommand} import net.eagle0.eagle.api.selected_command.MarchSelectedCommand import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - LoyaltyGainFromFeast, - MinimumLoyaltyForSwearBrotherhood -} +import net.eagle0.eagle.library.settings.{LoyaltyGainFromFeast, MinimumLoyaltyForSwearBrotherhood} import net.eagle0.eagle.library.util.{CommandSelection, ProvinceDistances} import net.eagle0.eagle.library.util.command_choice_helpers.{ CommandChoiceHelpers, @@ -43,21 +37,22 @@ object SeekMoreLeadersCommandChooser { factionHeadProvince: Province, gameState: GameState ): Option[CommandSelection] = { - val opmc = command.oneProvinceCommands + val opmc = command.oneProvinceCommands .find(_.originProvinceId == startingProvince.id) .get val bestDestination = opmc.availableDestinationProvinces .map(dest => (opmc, gameState.provinces(dest.provinceId))) - .flatMap { case (opmc, p) => - ProvinceDistances - .distanceThroughFriendliesOption( - factionHeadProvince.id, - p.id, - factionHeadProvince.rulingFactionId.get, - gameState - ) - .map(distance => (opmc, p, distance)) + .flatMap { + case (opmc, p) => + ProvinceDistances + .distanceThroughFriendliesOption( + factionHeadProvince.id, + p.id, + factionHeadProvince.rulingFactionId.get, + gameState + ) + .map(distance => (opmc, p, distance)) } .minByOption(_._3) @@ -88,7 +83,7 @@ object SeekMoreLeadersCommandChooser { actingFactionId: FactionId, gameState: GameState, acs: Vector[AvailableCommand] - ): Option[CommandSelection] = { + ): Option[CommandSelection] = LegacyFactionUtils .provinces(actingFactionId, gameState) .find( @@ -106,36 +101,34 @@ object SeekMoreLeadersCommandChooser { province.rulingFactionHeroIds.map(gameState.heroes), gameState.factions(actingFactionId).leaders.toVector ) - .map { hero => Candidate(hero, province) } + .map(hero => Candidate(hero, province)) } - val marchACs = acs - .collect { case ac: MarchAvailableCommand => ac } + val marchACs = acs.collect { case ac: MarchAvailableCommand => ac } val marchableCandidates = candidates.flatMap { c => - marchACs - .find { mac => - mac.oneProvinceCommands.exists(opmc => - opmc.originProvinceId == c.province.id && opmc.availableHeroIds.toVector - .contains(c.hero.id) - ) - } + marchACs.find { mac => + mac.oneProvinceCommands.exists(opmc => + opmc.originProvinceId == c.province.id && opmc.availableHeroIds.toVector + .contains(c.hero.id) + ) + } .map(mac => (mac, c)) } marchableCandidates .maxByOption(x => LegacyHeroUtils.power(x._2.hero)) - .flatMap { case (command, candidate) => - maybeMoveTowardDestination( - command = command, - hero = candidate.hero, - startingProvince = candidate.province, - factionHeadProvince = provinceWithFactionHead, - gameState = gameState - ) + .flatMap { + case (command, candidate) => + maybeMoveTowardDestination( + command = command, + hero = candidate.hero, + startingProvince = candidate.province, + factionHeadProvince = provinceWithFactionHead, + gameState = gameState + ) } } - } def maybeSeekMoreLeadersCommand( actingFactionId: FactionId, @@ -154,37 +147,36 @@ object SeekMoreLeadersCommandChooser { faction.leaders.toVector ) - desiredHero - .flatMap { hero => - SwearBrotherhoodCommandSelector - .chosenCommandForSpecificHero( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = acs, - desiredHeroId = hero.id - ) - .orElse { - MoreOption.flatWhen( - MinimumLoyaltyForSwearBrotherhood.doubleValue - hero.loyalty < LoyaltyGainFromFeast.doubleValue - ) { - CommandChoiceHelpers.chosenFeastCommandIfAvailable( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = acs, - reason = s"want to make hero ${hero.id} a leader" - ) - } - } - .orElse { - HeroGiftCommandSelector.chosenCommandForSpecificHero( + desiredHero.flatMap { hero => + SwearBrotherhoodCommandSelector + .chosenCommandForSpecificHero( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = acs, + desiredHeroId = hero.id + ) + .orElse { + MoreOption.flatWhen( + MinimumLoyaltyForSwearBrotherhood.doubleValue - hero.loyalty < LoyaltyGainFromFeast.doubleValue + ) { + CommandChoiceHelpers.chosenFeastCommandIfAvailable( actingFactionId = actingFactionId, gameState = gameState, availableCommands = acs, - heroId = hero.id, - reason = "want to make this hero a leader" + reason = s"want to make hero ${hero.id} a leader" ) } - } + } + .orElse { + HeroGiftCommandSelector.chosenCommandForSpecificHero( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = acs, + heroId = hero.id, + reason = "want to make this hero a leader" + ) + } + } .orElse( // Then try moving a hero this way maybeMoveBestCandidateCommand( diff --git a/src/main/scala/net/eagle0/eagle/client_text/ClientText.scala b/src/main/scala/net/eagle0/eagle/client_text/ClientText.scala index 00ed807f8f..32e1316ac4 100644 --- a/src/main/scala/net/eagle0/eagle/client_text/ClientText.scala +++ b/src/main/scala/net/eagle0/eagle/client_text/ClientText.scala @@ -37,5 +37,5 @@ case class UnrequestedClientText( llmRequest: GeneratedTextRequest ) extends ClientText { def complete: Boolean = false - def text: String = "" + def text: String = "" } diff --git a/src/main/scala/net/eagle0/eagle/client_text/ClientTextStoreImpl.scala b/src/main/scala/net/eagle0/eagle/client_text/ClientTextStoreImpl.scala index bf2f9b1609..4d8db989a5 100644 --- a/src/main/scala/net/eagle0/eagle/client_text/ClientTextStoreImpl.scala +++ b/src/main/scala/net/eagle0/eagle/client_text/ClientTextStoreImpl.scala @@ -9,11 +9,7 @@ import scala.util.Try import net.eagle0.common.ProtoParser import net.eagle0.eagle.{ClientTextId, FactionId} -import net.eagle0.eagle.internal.client_text.{ - IncompleteText, - IncompleteTextStore, - UnrequestedText -} +import net.eagle0.eagle.internal.client_text.{IncompleteText, IncompleteTextStore, UnrequestedText} import net.eagle0.eagle.internal.generated_text_request.GeneratedTextRequest import net.eagle0.eagle.library.util.EagleRequire.internalRequire import net.eagle0.eagle.library.EagleInternalException @@ -56,7 +52,7 @@ case class ClientTextStoreImpl( requestedAfterHistoryCount = requestedAfterHistoryCount, llmRequest = llmRequest )), - accessibleTo = this.accessibleTo + (id -> accessibleTo), + accessibleTo = this.accessibleTo + (id -> accessibleTo), accessibleToIsSaved = false, incompleteTextsAreSaved = false ) @@ -73,8 +69,7 @@ case class ClientTextStoreImpl( id = id, partialText = "", llmRequest = unrequested.llmRequest, - requestedAfterHistoryCount = - unrequested.requestedAfterHistoryCount + requestedAfterHistoryCount = unrequested.requestedAfterHistoryCount )), unrequestedTexts = unrequestedTexts - id, incompleteTextsAreSaved = false @@ -98,7 +93,7 @@ case class ClientTextStoreImpl( .orElse { completeTexts.get(id).map(_.text) } - .map { text => TextGenerationSuccess(text) } + .map(text => TextGenerationSuccess(text)) .getOrElse { incompleteTexts .get(id) @@ -172,7 +167,7 @@ case class ClientTextStoreImpl( addedFactionIds: Vector[FactionId] ): ClientTextStore = { val originalFactionIds = accessibleTo.getOrElse(id, Vector()).sorted - val updatedFactionIds = + val updatedFactionIds = (originalFactionIds ++ addedFactionIds).distinct.sorted if updatedFactionIds == originalFactionIds then this @@ -206,22 +201,22 @@ case class ClientTextStoreImpl( } object ClientTextStoreImpl { - private val separator = "\n******\n" + private val separator = "\n******\n" private val separatorPattern = Pattern.quote(separator) - private def completeTextsKey = "completeText.txt" + private def completeTextsKey = "completeText.txt" private def incompleteTextsKey = "incompleteText.dat" - private def visibilityKey = "visibility.txt" + private def visibilityKey = "visibility.txt" def saved(clientTextStore: ClientTextStoreImpl): ClientTextStore = { val completeSaved = if clientTextStore.completeTexts.size > clientTextStore.savedCompleteCount then { // FIXME: make this append, will require Persister changes - val saveData = clientTextStore.completeTexts - .map { case (_: String, ct: CompleteClientText) => + val saveData = clientTextStore.completeTexts.map { + case (_: String, ct: CompleteClientText) => s"${ct.id}\n${ct.requestedAfterHistoryCount}\n${ct.text}$separator" - } + } .mkString("") .getBytes(StandardCharsets.UTF_8) @@ -231,9 +226,7 @@ object ClientTextStoreImpl { ) } - clientTextStore.copy(savedCompleteCount = - clientTextStore.completeTexts.size - ) + clientTextStore.copy(savedCompleteCount = clientTextStore.completeTexts.size) } else clientTextStore val incompleteSaved = @@ -270,10 +263,10 @@ object ClientTextStoreImpl { val accessibleToSaved = if !incompleteSaved.accessibleToIsSaved then { - val accessibleToData = incompleteSaved.accessibleTo - .map { case (id, factions) => + val accessibleToData = incompleteSaved.accessibleTo.map { + case (id, factions) => s"$id\n${factions.mkString(",")}$separator" - } + } .mkString("") .getBytes(StandardCharsets.UTF_8) @@ -316,9 +309,10 @@ object ClientTextStoreImpl { } .toVector } - .recover { case _: FileNotFoundException => - println("No complete text store found") - Vector() + .recover { + case _: FileNotFoundException => + println("No complete text store found") + Vector() } private def loadedIncompleteTexts( @@ -350,9 +344,10 @@ object ClientTextStoreImpl { } .getOrElse((Vector(), Vector())) } - .recover { case _: FileNotFoundException => - println("No incomplete text store found") - (Vector(), Vector()) + .recover { + case _: FileNotFoundException => + println("No incomplete text store found") + (Vector(), Vector()) } private def loadedAccessibleTo( @@ -376,9 +371,10 @@ object ClientTextStoreImpl { } .toMap } - .recover { case _: FileNotFoundException => - println("No accessibleTo store found") - Map() + .recover { + case _: FileNotFoundException => + println("No accessibleTo store found") + Map() } def loaded( @@ -386,22 +382,18 @@ object ClientTextStoreImpl { persister: Persister ): Try[ClientTextStore] = for { - loadedCompletedTexts <- loadedCompleteTexts(persister) + loadedCompletedTexts <- loadedCompleteTexts(persister) loadedIncompleteTexts <- loadedIncompleteTexts(persister) - loadedAccessibleTo <- loadedAccessibleTo(persister) - } yield { - ClientTextStoreImpl( - pregenerated = pregenerated, - persister = persister, - completeTexts = loadedCompletedTexts.map(ct => ct.id -> ct).toMap, - incompleteTexts = - loadedIncompleteTexts._1.map(ict => ict.id -> ict).toMap, - unrequestedTexts = - loadedIncompleteTexts._2.map(ut => ut.id -> ut).toMap, - accessibleTo = loadedAccessibleTo, - savedCompleteCount = loadedCompletedTexts.size, - incompleteTextsAreSaved = true, - accessibleToIsSaved = true - ) - } + loadedAccessibleTo <- loadedAccessibleTo(persister) + } yield ClientTextStoreImpl( + pregenerated = pregenerated, + persister = persister, + completeTexts = loadedCompletedTexts.map(ct => ct.id -> ct).toMap, + incompleteTexts = loadedIncompleteTexts._1.map(ict => ict.id -> ict).toMap, + unrequestedTexts = loadedIncompleteTexts._2.map(ut => ut.id -> ut).toMap, + accessibleTo = loadedAccessibleTo, + savedCompleteCount = loadedCompletedTexts.size, + incompleteTextsAreSaved = true, + accessibleToIsSaved = true + ) } diff --git a/src/main/scala/net/eagle0/eagle/client_text/TextGenerationResult.scala b/src/main/scala/net/eagle0/eagle/client_text/TextGenerationResult.scala index 0e3ec169aa..1c2a4f8738 100644 --- a/src/main/scala/net/eagle0/eagle/client_text/TextGenerationResult.scala +++ b/src/main/scala/net/eagle0/eagle/client_text/TextGenerationResult.scala @@ -22,7 +22,7 @@ object TextGenerationResult { acc :+ result, tail ) - case x => x + case x => x } } @@ -47,30 +47,28 @@ trait TextGenerationResult { } case class TextGenerationSuccess(result: String) extends TextGenerationResult { override def resolved: Boolean = true - override def get: String = result + override def get: String = result } case class TextGenerationDependencyInProgress( inProgressTextId: String, partialText: String ) extends TextGenerationResult { override def resolved: Boolean = false - override def get: String = + override def get: String = throw new EagleInternalException( s"Text generation dependency in progress: $inProgressTextId" ) } -case class TextGenerationDependencyWaiting(notSatisfiedTextId: String) - extends TextGenerationResult { +case class TextGenerationDependencyWaiting(notSatisfiedTextId: String) extends TextGenerationResult { override def resolved: Boolean = false - override def get: String = + override def get: String = throw new EagleInternalException( s"Text generation dependency not satisfied: $notSatisfiedTextId" ) } -case class TextGenerationDependencyUnknown(unknownTextId: String) - extends TextGenerationResult { +case class TextGenerationDependencyUnknown(unknownTextId: String) extends TextGenerationResult { override def resolved: Boolean = false - override def get: String = + override def get: String = throw new EagleInternalException( s"Text generation dependency unknown: $unknownTextId" ) diff --git a/src/main/scala/net/eagle0/eagle/library/ActionResultFilter.scala b/src/main/scala/net/eagle0/eagle/library/ActionResultFilter.scala index 6353d1bcec..7a0cf5dd46 100644 --- a/src/main/scala/net/eagle0/eagle/library/ActionResultFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/ActionResultFilter.scala @@ -84,8 +84,8 @@ object ActionResultFilter { RoundPhase.HERO_DEPARTURES, RoundPhase.UNCONTESTED_CONQUEST, RoundPhase.BATTLE_RESOLUTION, - RoundPhase.BATTLE_AFTERMATH, // MIGHT BE WRONG - RoundPhase.ATTACK_DECISION, // MIGHT BE WRONG + RoundPhase.BATTLE_AFTERMATH, // MIGHT BE WRONG + RoundPhase.ATTACK_DECISION, // MIGHT BE WRONG RoundPhase.DIPLOMACY_RESOLUTION // IS WRONG ) @@ -97,8 +97,7 @@ object ActionResultFilter { GameStateViewDiffer.diff( before = GameStateViewFilter .filteredGameState(gs = before, factionId = factionId), - after = - GameStateViewFilter.filteredGameState(gs = after, factionId = factionId) + after = GameStateViewFilter.filteredGameState(gs = after, factionId = factionId) ) private def transformOne( @@ -115,9 +114,7 @@ object ActionResultFilter { ) def shouldInclude(note: Notification): Boolean = - note.targetFactions.isEmpty || factionId.exists(fid => - note.targetFactions.exists(_.factionId == fid) - ) + note.targetFactions.isEmpty || factionId.exists(fid => note.targetFactions.exists(_.factionId == fid)) if gsDiff.isDefined && result.actionResult.player.isDefined && @@ -143,8 +140,7 @@ object ActionResultFilter { province = actionResult.province, leader = actionResult.leader, gameStateDiff = gsDiff, - notifications = - actionResult.notificationsToDeliver.filter(shouldInclude) + notifications = actionResult.notificationsToDeliver.filter(shouldInclude) ) } } @@ -154,10 +150,9 @@ object ActionResultFilter { results: Vector[ActionWithResultingState], factionId: Option[FactionId] ): Vector[ActionResultView] = - factionId - .map { pid => - filterForPlayer(startingState, results, pid) - } + factionId.map { pid => + filterForPlayer(startingState, results, pid) + } .getOrElse(filterForObserver(startingState, results)) def filterForPlayer( @@ -182,7 +177,5 @@ object ActionResultFilter { startingState: GameState, results: Vector[ActionWithResultingState] ): Vector[ActionResultView] = - results.flatMap(res => - observeOne(result = res, startingState = startingState) - ) + results.flatMap(res => observeOne(result = res, startingState = startingState)) } diff --git a/src/main/scala/net/eagle0/eagle/library/EagleValidationException.scala b/src/main/scala/net/eagle0/eagle/library/EagleValidationException.scala index e5ab9d42d8..8b86016a60 100644 --- a/src/main/scala/net/eagle0/eagle/library/EagleValidationException.scala +++ b/src/main/scala/net/eagle0/eagle/library/EagleValidationException.scala @@ -1,4 +1,3 @@ package net.eagle0.eagle.library -class EagleValidationException(message: String) - extends EagleInternalException(message) {} +class EagleValidationException(message: String) extends EagleInternalException(message) {} diff --git a/src/main/scala/net/eagle0/eagle/library/EngineImpl.scala b/src/main/scala/net/eagle0/eagle/library/EngineImpl.scala index 4a2e475b9b..0699ce4b55 100644 --- a/src/main/scala/net/eagle0/eagle/library/EngineImpl.scala +++ b/src/main/scala/net/eagle0/eagle/library/EngineImpl.scala @@ -8,24 +8,15 @@ import net.eagle0.eagle.api.command.AvailableCommands import net.eagle0.eagle.api.selected_command.SelectedCommand import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.actions.applier.{ - ActionResultProtoApplier, - ActionResultProtoApplierImpl -} +import net.eagle0.eagle.library.actions.applier.{ActionResultProtoApplier, ActionResultProtoApplierImpl} import net.eagle0.eagle.library.actions.availability.AvailableCommandsFactory import net.eagle0.eagle.library.actions.impl.action.{ CheckForFulfilledQuestsAction, HeroBackstoryUpdateActionGenerator, ResolveBattleAction } -import net.eagle0.eagle.library.actions.impl.command.{ - AvailableCommandTypeMap, - CommandFactory -} -import net.eagle0.eagle.library.actions.impl.common.{ - ActionWithResultingState, - RandomStateProtoSequencer -} +import net.eagle0.eagle.library.actions.impl.command.{AvailableCommandTypeMap, CommandFactory} +import net.eagle0.eagle.library.actions.impl.common.{ActionWithResultingState, RandomStateProtoSequencer} import net.eagle0.eagle.library.util.hero_generator.HeroGenerator import net.eagle0.eagle.library.util.validations.RuntimeValidator import net.eagle0.eagle.library.util.EagleRequire.internalRequire @@ -83,11 +74,9 @@ object EngineImpl { .toVector, battalions = eng.currentState.battalions.values.toVector .map(BattalionConverter.fromProto), - getHero = - hid => eng.currentState.heroes.get(hid).map(HeroConverter.fromProto), + getHero = hid => eng.currentState.heroes.get(hid).map(HeroConverter.fromProto), battalionTypes = eng.currentState.battalionTypes.toVector, - heroBackstoryTextIdLookup = - hid => eng.currentState.heroes(hid).backstoryVersions.last.textId + heroBackstoryTextIdLookup = hid => eng.currentState.heroes(hid).backstoryVersions.last.textId ).results ) @@ -99,8 +88,7 @@ object EngineImpl { withPhaseAdvancement(engineAndResults) ) - if newEar.results.length > engineAndResults.results.length then - withUpdateChecks(newEar) + if newEar.results.length > engineAndResults.results.length then withUpdateChecks(newEar) else newEar } @@ -110,8 +98,7 @@ object EngineImpl { ): EngineAndResults = withUpdateChecks( EngineAndResultsImpl( engine = engine.copy( - currentState = - results.lastOption.map(_.gameState).getOrElse(engine.currentState), + currentState = results.lastOption.map(_.gameState).getOrElse(engine.currentState), history = engine.history.withNewResults(results) ), results = results.map(_.actionResult) @@ -146,14 +133,14 @@ final case class EngineAndResultsImpl( def recursiveTransformT( f: EngineImpl => Vector[ActionResultT] - ): EngineAndResultsImpl = recursiveTransform(eng => { + ): EngineAndResultsImpl = recursiveTransform { eng => val results = f(eng) RandomStateProtoSequencer( initialStateProto = eng.currentState, actionResultProtoApplier = eng.actionResultProtoApplier, functionalRandom = SeededRandom(eng.currentState.randomSeed) ).withActionResultTs(_ => results).results.newValue - }) + } def saveNow: EngineAndResultsImpl = this.copy(engine = this.engine.saveNow) @@ -169,8 +156,7 @@ case class EngineImpl( override val currentState: GameState, heroGenerator: HeroGenerator, override val history: GameHistory, - actionResultProtoApplier: ActionResultProtoApplier = - new ActionResultProtoApplierImpl(validator = RuntimeValidator) + actionResultProtoApplier: ActionResultProtoApplier = new ActionResultProtoApplierImpl(validator = RuntimeValidator) ) extends Engine { import net.eagle0.eagle.library.util.EagleRequire.commandRequire @@ -298,7 +284,7 @@ case class EngineImpl( availableCommandOpt.isDefined, s"No matching available command for selected command $selectedCommand" ) - val availableCommand = availableCommandOpt.get + val availableCommand = availableCommandOpt.get val sequencer = RandomStateProtoSequencer( initialStateProto = this.currentState, @@ -326,9 +312,7 @@ case class EngineImpl( ) results - }.withProtolessSequentialResultsAction(gs => - HeroBackstoryUpdateActionGenerator.fromGameState(gs) - ) + }.withProtolessSequentialResultsAction(gs => HeroBackstoryUpdateActionGenerator.fromGameState(gs)) appliedResults( engine = this, diff --git a/src/main/scala/net/eagle0/eagle/library/GameHistory.scala b/src/main/scala/net/eagle0/eagle/library/GameHistory.scala index efeac2de4f..28a081b30c 100644 --- a/src/main/scala/net/eagle0/eagle/library/GameHistory.scala +++ b/src/main/scala/net/eagle0/eagle/library/GameHistory.scala @@ -17,8 +17,7 @@ trait GameHistory { def all: Vector[ActionWithResultingState] def since(count: Int): Vector[ActionWithResultingState] def sinceCapped(count: Int, resultSizeCap: Int): CappedResults = - if this.count - count <= resultSizeCap then - CappedResults(since(count), None) + if this.count - count <= resultSizeCap then CappedResults(since(count), None) else CappedResults( since(this.count - resultSizeCap), diff --git a/src/main/scala/net/eagle0/eagle/library/RoundPhaseAdvancer.scala b/src/main/scala/net/eagle0/eagle/library/RoundPhaseAdvancer.scala index 83d3aed517..876c8df79d 100644 --- a/src/main/scala/net/eagle0/eagle/library/RoundPhaseAdvancer.scala +++ b/src/main/scala/net/eagle0/eagle/library/RoundPhaseAdvancer.scala @@ -6,10 +6,7 @@ import net.eagle0.common.SeededRandom import net.eagle0.eagle.common.round_phase.RoundPhase import net.eagle0.eagle.common.round_phase.RoundPhase.* import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.actions.applier.{ - ActionResultProtoApplier, - ActionResultTApplierImpl -} +import net.eagle0.eagle.library.actions.applier.{ActionResultProtoApplier, ActionResultTApplierImpl} import net.eagle0.eagle.library.actions.availability.AvailableCommandsFactory import net.eagle0.eagle.library.actions.impl.action.* import net.eagle0.eagle.library.actions.impl.command.CommandFactory @@ -29,8 +26,8 @@ import net.eagle0.eagle.RoundId object RoundPhaseAdvancer { private val times: mutable.Map[RoundPhase, Long] = mutable.Map(RoundPhase.values.map(_ -> 0L)*) - private val print = false - private val roundsBetweenPrint = 100 + private val print = false + private val roundsBetweenPrint = 100 private def printTimings(roundId: RoundId): Unit = { val totalTime = times.values.sum.toDouble / 1000.0 @@ -39,7 +36,7 @@ object RoundPhaseAdvancer { case (phase, time) => val timeInSecs = time.toDouble / 1000.0 val msPerRound = time.toDouble / roundId.toDouble - val timePct = timeInSecs / totalTime * 100.0 + val timePct = timeInSecs / totalTime * 100.0 println( f"$phase%-25s: $timeInSecs%6.2fs ($msPerRound%4.2fms per round), $timePct%4.1f%%" ) @@ -56,7 +53,7 @@ object RoundPhaseAdvancer { commandFactory: CommandFactory ): Vector[ActionWithResultingState] = { val currentPhase = currentState.currentPhase - val startTime = System.currentTimeMillis + val startTime = System.currentTimeMillis if print && currentPhase == NEW_ROUND && currentState.currentRoundId % roundsBetweenPrint == 0 then { @@ -270,8 +267,7 @@ object RoundPhaseAdvancer { currentRoundId = currentState.currentRoundId, currentDate = DateConverter.fromProto(currentState.currentDate), battleCounter = currentState.battleCounter, - heroes = - currentState.heroes.view.mapValues(HeroConverter.fromProto).toMap, + heroes = currentState.heroes.view.mapValues(HeroConverter.fromProto).toMap, battalions = currentState.battalions.view .mapValues(BattalionConverter.fromProto) .toMap, @@ -286,7 +282,7 @@ object RoundPhaseAdvancer { converted.typeId -> converted }.toMap ) - val requestResults = actionResultProtoApplier.applyActionResults( + val requestResults = actionResultProtoApplier.applyActionResults( currentState, requestBattlesAction.results.map( ActionResultProtoConverter.toProto(_) @@ -337,8 +333,7 @@ object RoundPhaseAdvancer { currentState, EndDiplomacyResolutionPhaseAction( currentState, - actionResultTApplier = - ActionResultTApplierImpl(actionResultProtoApplier) + actionResultTApplier = ActionResultTApplierImpl(actionResultProtoApplier) ).randomResults(SeededRandom(currentState.randomSeed)) .newValue .map(ActionResultProtoConverter.toProto) @@ -352,7 +347,7 @@ object RoundPhaseAdvancer { case Unrecognized(x) => throw new IllegalStateException(s"Unknown round phase $x") } - val timeSpent = System.currentTimeMillis - startTime + val timeSpent = System.currentTimeMillis - startTime times(currentPhase) = times(currentPhase) + timeSpent validateResults(results, currentState, availableCommandsFactory) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImpl.scala b/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImpl.scala index 5bd61d5b78..f9ae7ea961 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImpl.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImpl.scala @@ -31,10 +31,7 @@ import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.{ import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.army.{HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion -import net.eagle0.eagle.internal.changed_faction.{ - ChangedFaction, - TrustLevelUpdate -} +import net.eagle0.eagle.internal.changed_faction.{ChangedFaction, TrustLevelUpdate} import net.eagle0.eagle.internal.changed_hero.ChangedHero import net.eagle0.eagle.internal.changed_hero.ChangedHero.{Loyalty, Vigor} import net.eagle0.eagle.internal.changed_province.ChangedProvince @@ -49,24 +46,19 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.run_status.RunStatus import net.eagle0.eagle.internal.shardok_battle.ShardokBattle import net.eagle0.eagle.library.actions.impl.common.ActionWithResultingState -import net.eagle0.eagle.library.settings.{ - ExtraXpForStatBumpOver100, - XpForStatBump -} +import net.eagle0.eagle.library.settings.{ExtraXpForStatBumpOver100, XpForStatBump} import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.validations.Validator import net.eagle0.eagle.library.util.EagleRequire.internalRequire import net.eagle0.eagle.library.util.ProvinceEventUtils import net.eagle0.eagle.library.EagleInternalException -class ActionResultProtoApplierImpl(validator: Validator) - extends ActionResultProtoApplier { +class ActionResultProtoApplierImpl(validator: Validator) extends ActionResultProtoApplier { import validator.validate override def xpForStatBump(stat: Int): Int = if stat <= 99 then XpForStatBump.intValue - else - XpForStatBump.intValue + ExtraXpForStatBumpOver100.intValue * (stat - 99) + else XpForStatBump.intValue + ExtraXpForStatBumpOver100.intValue * (stat - 99) private val trustMax: Int = 100 @@ -93,10 +85,11 @@ class ActionResultProtoApplierImpl(validator: Validator) if changedProvinces.isEmpty then gameState else changedProvinces - .foldLeft(gameState) { case (gs, cp) => - val after = gs.applyChangedProvince(cp) - validate(after.provinces(cp.id), gs.currentPhase) - after + .foldLeft(gameState) { + case (gs, cp) => + val after = gs.applyChangedProvince(cp) + validate(after.provinces(cp.id), gs.currentPhase) + after } def applyChangedProvince(cp: ChangedProvince): GameState = { @@ -134,7 +127,7 @@ class ActionResultProtoApplierImpl(validator: Validator) _.incomingShipments.modify { is => val holdovers = is.filterNot(sh => cp.removedIncomingShipmentIds.contains(sh.id)) - val nextId = holdovers + val nextId = holdovers .map(_.id) .reduceOption(_ max _) .getOrElse(0) + 1 @@ -149,9 +142,7 @@ class ActionResultProtoApplierImpl(validator: Validator) da.map { nda => nda.withUnits( nda.units - .filterNot(u => - cp.removedRulingPlayerHeroIds.contains(u.heroId) - ) + .filterNot(u => cp.removedRulingPlayerHeroIds.contains(u.heroId)) .map { case CombatUnit( pid, @@ -185,17 +176,11 @@ class ActionResultProtoApplierImpl(validator: Validator) newF }, _.priceIndex.setIfDefined(cp.newPriceIndex), - _.economy.modify(e => - (e + cp.economyDelta.getOrElse(0.0)).max(0.0).min(100.0) - ), + _.economy.modify(e => (e + cp.economyDelta.getOrElse(0.0)).max(0.0).min(100.0)), _.agriculture - .modify(a => - (a + cp.agricultureDelta.getOrElse(0.0)).max(0.0).min(100.0) - ), + .modify(a => (a + cp.agricultureDelta.getOrElse(0.0)).max(0.0).min(100.0)), _.infrastructure - .modify(i => - (i + cp.infrastructureDelta.getOrElse(0.0)).max(0.0).min(100.0) - ), + .modify(i => (i + cp.infrastructureDelta.getOrElse(0.0)).max(0.0).min(100.0)), _.economyDevastation.modify(d => (d + cp.economyDevastationDelta.getOrElse(0.0)) .max(0.0) @@ -211,16 +196,12 @@ class ActionResultProtoApplierImpl(validator: Validator) .max(0.0) .min(provinceBefore.infrastructure) ), - _.support.modify(s => - (s + cp.supportDelta.getOrElse(0.0)).max(0.0).min(100.0) - ), + _.support.modify(s => (s + cp.supportDelta.getOrElse(0.0)).max(0.0).min(100.0)), _.hasActed.setIfDefined(cp.setHasActed), _.rulerIsTraveling.setIfDefined(cp.setRulerIsTraveling), _.unaffiliatedHeroes.modify(uhs => uhs - .filterNot(uh => - cp.removedUnaffiliatedHeroIds.contains(uh.heroId) - ) + .filterNot(uh => cp.removedUnaffiliatedHeroIds.contains(uh.heroId)) .filterNot(uh => cp.changedUnaffiliatedHeroes .map(_.heroId) @@ -247,14 +228,14 @@ class ActionResultProtoApplierImpl(validator: Validator) cp.newProvinceEvents.exists( _.newEvents.exists(ProvinceEventUtils.isBeastsEvent) ) - ) { gameState.currentDate.get } + )(gameState.currentDate.get) ), _.lastRiotDate.setIfDefined( Option.when( cp.newProvinceEvents.exists( _.newEvents.exists(ProvinceEventUtils.isImminentRiotEvent) ) - ) { gameState.currentDate.get } + )(gameState.currentDate.get) ), _.incomingEndTurnActions :++= cp.addedIncomingEndTurnActions, _.incomingEndTurnActions.modify( @@ -265,9 +246,7 @@ class ActionResultProtoApplierImpl(validator: Validator) .map(idx => dcs.patch(idx, Nil, 1)) .getOrElse(dcs) ++ cp.addedDeferredChange.asNonEmpty ), - _.battleRevelations.modify(brs => - brs.diff(cp.removedBattleRevelations) ++ cp.addedBattleRevelations - ) + _.battleRevelations.modify(brs => brs.diff(cp.removedBattleRevelations) ++ cp.addedBattleRevelations) ) val provinceFixedForRuler = @@ -275,27 +254,27 @@ class ActionResultProtoApplierImpl(validator: Validator) then provinceApplied.update( _.optionalRulingFactionId := None, - _.optionalRulingHeroId := None, - _.rulingFactionHeroIds := Vector.empty, - _.support := 0, - _.provinceOrders := ProvinceOrderType.UNKNOWN_ORDERS, + _.optionalRulingHeroId := None, + _.rulingFactionHeroIds := Vector.empty, + _.support := 0, + _.provinceOrders := ProvinceOrderType.UNKNOWN_ORDERS, _.unaffiliatedHeroes.modify(uhs => uhs.map(uh => uh.update( _.recruitmentInfo := RecruitmentInfo( status = uh.`type` match { - case UNAFFILIATED_HERO_PRISONER => + case UNAFFILIATED_HERO_PRISONER => RECRUITMENT_STATUS_PRISONER - case UNAFFILIATED_HERO_MOVING_PRISONER => + case UNAFFILIATED_HERO_MOVING_PRISONER => RECRUITMENT_STATUS_MOVING_PRISONER - case UNAFFILIATED_HERO_RETURNING_PRISONER => + case UNAFFILIATED_HERO_RETURNING_PRISONER => RECRUITMENT_STATUS_NO_RULER_IN_PROVINCE - case UNAFFILIATED_HERO_OUTLAW => RECRUITMENT_STATUS_OUTLAW - case UNAFFILIATED_HERO_TRAVELER => + case UNAFFILIATED_HERO_OUTLAW => RECRUITMENT_STATUS_OUTLAW + case UNAFFILIATED_HERO_TRAVELER => RECRUITMENT_STATUS_TRAVELER - case UNAFFILIATED_HERO_RESIDENT => + case UNAFFILIATED_HERO_RESIDENT => RECRUITMENT_STATUS_NO_RULER_IN_PROVINCE - case UNAFFILIATED_HERO_UNKNOWN => + case UNAFFILIATED_HERO_UNKNOWN => throw new EagleInternalException( "Unknown unaffiliated hero type" ) @@ -325,12 +304,13 @@ class ActionResultProtoApplierImpl(validator: Validator) ): Vector[MovingArmy] = { val holdovers = existingArmies.filterNot(ma => removedIds.contains(ma.id)) - val nextId = holdovers + val nextId = holdovers .map(_.id) .reduceOption(_ max _) .getOrElse(0) + 1 - holdovers.toVector ++ addedArmies.zipWithIndex.map { case (army, index) => - army.withId(index + nextId) + holdovers.toVector ++ addedArmies.zipWithIndex.map { + case (army, index) => + army.withId(index + nextId) } } @@ -339,7 +319,7 @@ class ActionResultProtoApplierImpl(validator: Validator) removedFactionIds: Seq[FactionId], addedArmies: Seq[HostileArmyGroup], statusChanges: Seq[HostileArmyGroupStatusChange] - ): Vector[HostileArmyGroup] = { + ): Vector[HostileArmyGroup] = statusChanges .foldLeft( existingGroups @@ -360,9 +340,8 @@ class ActionResultProtoApplierImpl(validator: Validator) } } .toVector ++ addedArmies - } - def applyProvinceActed(actedProvince: Option[Int]): GameState = { + def applyProvinceActed(actedProvince: Option[Int]): GameState = { internalRequire( !actedProvince.contains(0), "Province acted has id 0" @@ -396,20 +375,19 @@ class ActionResultProtoApplierImpl(validator: Validator) ): GameState = if newBattalions.isEmpty then gameState else - provinceId - .map { pid => - val maxCurrentId = - if gameState.battalions.isEmpty then 0 - else gameState.battalions.keys.max - val newIds = - (maxCurrentId + 1) to (maxCurrentId + newBattalions.size) - gameState.update( - _.battalions :++= newIds.zip(newBattalions).map { - case (id, batt) => id -> batt.withId(id) - }, - _.provinces(pid).battalionIds :++= newIds - ) - } + provinceId.map { pid => + val maxCurrentId = + if gameState.battalions.isEmpty then 0 + else gameState.battalions.keys.max + val newIds = + (maxCurrentId + 1) to (maxCurrentId + newBattalions.size) + gameState.update( + _.battalions :++= newIds.zip(newBattalions).map { + case (id, batt) => id -> batt.withId(id) + }, + _.provinces(pid).battalionIds :++= newIds + ) + } .getOrElse( gameState .update(_.battalions :++= newBattalions.map(b => b.id -> b)) @@ -444,14 +422,15 @@ class ActionResultProtoApplierImpl(validator: Validator) _.battalions := gameState.battalions -- destroyedBattalionIds, _.destroyedBattalions :++= destroyedBattalionIds .filterNot(_ == -1) - .map { bid => bid -> gameState.battalions(bid) }, - _.provinces := gameState.provinces.map { case (pid, p) => - pid -> p.update( - _.battalionIds := p.battalionIds - .filterNot(destroyedBattalionIds.contains), - _.incomingArmies := p.incomingArmies - .map(a => movingArmyWithoutBattalions(a, destroyedBattalionIds)) - ) + .map(bid => bid -> gameState.battalions(bid)), + _.provinces := gameState.provinces.map { + case (pid, p) => + pid -> p.update( + _.battalionIds := p.battalionIds + .filterNot(destroyedBattalionIds.contains), + _.incomingArmies := p.incomingArmies + .map(a => movingArmyWithoutBattalions(a, destroyedBattalionIds)) + ) } ) @@ -484,14 +463,14 @@ class ActionResultProtoApplierImpl(validator: Validator) def applyChangedHeroes( changedHeroes: Seq[ChangedHero], date: Date - ): GameState = { + ): GameState = if changedHeroes.isEmpty then gameState else changedHeroes - .foldLeft(gameState) { case (gs, ch) => - gs.applyChangedHero(ch, date) + .foldLeft(gameState) { + case (gs, ch) => + gs.applyChangedHero(ch, date) } - } private def statBump( stat: Int, @@ -633,9 +612,10 @@ class ActionResultProtoApplierImpl(validator: Validator) ) } - def applyRemovedFactions(removedFactionIds: Set[FactionId]): GameState = { - gameState.factions.partition { case (fid, _) => - removedFactionIds(fid) + def applyRemovedFactions(removedFactionIds: Set[FactionId]): GameState = + gameState.factions.partition { + case (fid, _) => + removedFactionIds(fid) } match { case (removed, remaining) => gameState.update( @@ -643,16 +623,17 @@ class ActionResultProtoApplierImpl(validator: Validator) _.factions := remaining ) } - } def applyRemovedHeroes(removedHeroIds: Set[HeroId]): GameState = - gameState.heroes.partition { case (k, _) => - removedHeroIds(k) + gameState.heroes.partition { + case (k, _) => + removedHeroIds(k) } match { case (removed, remaining) => gameState.update( - _.killedHeroes :++= removed.map { case (hid, hero) => - (hid, hero.clearFactionId) + _.killedHeroes :++= removed.map { + case (hid, hero) => + (hid, hero.clearFactionId) }, _.heroes := remaining ) @@ -670,12 +651,11 @@ class ActionResultProtoApplierImpl(validator: Validator) actionResultType: ActionResultType, notification: Option[Notification] ): GameState = - notification - .map { note => - gameState.update( - _.deferredNotifications :+= note - ) - } + notification.map { note => + gameState.update( + _.deferredNotifications :+= note + ) + } .getOrElse(gameState) def applyRemovedNotifications( @@ -727,36 +707,34 @@ class ActionResultProtoApplierImpl(validator: Validator) ) ) ++ cf.updatedReconnedProvinces }, - _.factionRelationships - .modify { (relationships: Seq[FactionRelationship]) => - cf.trustLevelUpdates - .foldLeft(relationships) { - ( - relationships: Seq[FactionRelationship], - update: TrustLevelUpdate - ) => - val existingRelationship = - relationships - .find( - _.targetFactionId == update.targetFactionId + _.factionRelationships.modify { (relationships: Seq[FactionRelationship]) => + cf.trustLevelUpdates + .foldLeft(relationships) { + ( + relationships: Seq[FactionRelationship], + update: TrustLevelUpdate + ) => + val existingRelationship = + relationships + .find( + _.targetFactionId == update.targetFactionId + ) + .getOrElse( + FactionRelationship( + targetFactionId = update.targetFactionId, + relationshipLevel = FactionRelationship.RelationshipLevel.HOSTILE, + trustValue = 0 ) - .getOrElse( - FactionRelationship( - targetFactionId = update.targetFactionId, - relationshipLevel = - FactionRelationship.RelationshipLevel.HOSTILE, - trustValue = 0 - ) - ) - val newValue = Math.min( - trustMax, - update.delta + existingRelationship.trustValue - ) - relationships.filterNot( - _.targetFactionId == update.targetFactionId - ) :+ existingRelationship.withTrustValue(newValue) - } - }, + ) + val newValue = Math.min( + trustMax, + update.delta + existingRelationship.trustValue + ) + relationships.filterNot( + _.targetFactionId == update.targetFactionId + ) :+ existingRelationship.withTrustValue(newValue) + } + }, _.lastActedProvinceIdThisRound.modify { lpid => if cf.clearLastActedProvinceId then 0 else cf.newLastActedProvinceId.getOrElse(lpid) @@ -835,58 +813,53 @@ class ActionResultProtoApplierImpl(validator: Validator) ) def applyNewBattle(battle: Option[ShardokBattle]): GameState = - battle - .map { b => - gameState.update( - _.outstandingBattles.modify(_ :+ b), - _.battleCounter.modify(_.max(b.battleIndex)) - ) - } + battle.map { b => + gameState.update( + _.outstandingBattles.modify(_ :+ b), + _.battleCounter.modify(_.max(b.battleIndex)) + ) + } .getOrElse(gameState) def applyResolvedBattle(shardokGameId: Option[ShardokGameId]): GameState = gameState .withOutstandingBattles( - gameState.outstandingBattles.filterNot(batt => - shardokGameId.contains(batt.shardokGameId) - ) + gameState.outstandingBattles.filterNot(batt => shardokGameId.contains(batt.shardokGameId)) ) def applyNewSeed(newSeed: Option[Long]): GameState = - newSeed.map { s => gameState.withRandomSeed(s) }.getOrElse(gameState) + newSeed.map(s => gameState.withRandomSeed(s)).getOrElse(gameState) def applyChronicleEntry( chronicleEntry: Option[ChronicleEntry] ): GameState = - chronicleEntry - .map { ce => - gameState.update( - _.chronicleEntries.modify { ces => - ces.indexWhere(_.date == ce.date) match { - case -1 => ces :+ ce - case idx => ces.updated(idx, ce) - } + chronicleEntry.map { ce => + gameState.update( + _.chronicleEntries.modify { ces => + ces.indexWhere(_.date == ce.date) match { + case -1 => ces :+ ce + case idx => ces.updated(idx, ce) } - ) - } + } + ) + } .getOrElse(gameState) def applyCommandCountUpdate(actingFactionId: Option[FactionId]): GameState = - actingFactionId - .map { factionId => - val existingCount = - gameState.factionCommandCounts.getOrElse(factionId, 0) - gameState.update( - _.factionCommandCounts(factionId) := existingCount + 1 - ) - } + actingFactionId.map { factionId => + val existingCount = + gameState.factionCommandCounts.getOrElse(factionId, 0) + gameState.update( + _.factionCommandCounts(factionId) := existingCount + 1 + ) + } .getOrElse(gameState) } override def applyActionResults( startingState: GameState, results: Iterable[ActionResult] - ): Vector[ActionWithResultingState] = { + ): Vector[ActionWithResultingState] = results .foldLeft((startingState, Vector.empty[ActionWithResultingState])) { case ((gameState, acc), result) => @@ -896,7 +869,7 @@ class ActionResultProtoApplierImpl(validator: Validator) } } ._2 - }.toVector + .toVector override def applyActionResult( startingState: GameState, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultTApplierImpl.scala b/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultTApplierImpl.scala index 05eef46aac..33eb883657 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultTApplierImpl.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/applier/ActionResultTApplierImpl.scala @@ -13,8 +13,7 @@ object ActionResultTApplierImpl { new ActionResultTApplierImpl(protoApplier) } -class ActionResultTApplierImpl(protoApplier: ActionResultProtoApplier) - extends ActionResultTApplier { +class ActionResultTApplierImpl(protoApplier: ActionResultProtoApplier) extends ActionResultTApplier { override def xpForStatBump(stat: Int): Int = protoApplier.xpForStatBump(stat) override def applyActionResults( @@ -26,11 +25,12 @@ class ActionResultTApplierImpl(protoApplier: ActionResultProtoApplier) results.map(ActionResultProtoConverter.toProto) ) .zip(results) - .map { case (actionWithResultingState, actionResult) => - ActionResultTWithResultingState( - actionResult = actionResult, - resultingState = actionWithResultingState.gameState - ) + .map { + case (actionWithResultingState, actionResult) => + ActionResultTWithResultingState( + actionResult = actionResult, + resultingState = actionWithResultingState.gameState + ) } override def applyActionResult( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactory.scala index fc5e99925a..3ea4f2627c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactory.scala @@ -12,24 +12,21 @@ object AvailableAlmsCommandFactory extends AvailableCommandsFactoryForType { .rulingFactionHeroIds .toVector .filter(hid => gs.heroes(hid).vigor >= MinVigorForAlms.doubleValue) - .sortBy(hid => - (!gs.heroes(hid).profession.isPaladin, -gs.heroes(hid).vigor) - ) + .sortBy(hid => (!gs.heroes(hid).profession.isPaladin, -gs.heroes(hid).vigor)) override def availableCommand( gameState: GameState, factionId: FactionId, provinceId: ProvinceId ): Option[AlmsAvailableCommand] = { - val hids = availableHeroIds(gameState, provinceId) + val hids = availableHeroIds(gameState, provinceId) val province = gameState.provinces(provinceId) Option.when(hids.nonEmpty && province.food > 0) { AlmsAvailableCommand( availableHeroIds = hids, actingProvinceId = provinceId, - foodAvailable = - Math.min(MaxAlmsFood.intValue, gameState.provinces(provinceId).food) + foodAvailable = Math.min(MaxAlmsFood.intValue, gameState.provinces(provinceId).food) ) } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactory.scala index 0fb8132b68..0dcce4dd72 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactory.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - ApprehendOutlawAvailableCommand, - ResidentOutlaw -} +import net.eagle0.eagle.api.available_command.{ApprehendOutlawAvailableCommand, ResidentOutlaw} import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFFILIATED_HERO_OUTLAW import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -13,8 +10,7 @@ import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.settings.MinVigorForApprehendOutlaw import net.eagle0.eagle.library.util.view_filters.HeroViewFilter -object AvailableApprehendOutlawCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableApprehendOutlawCommandFactory extends AvailableCommandsFactoryForType { private def availableToCapture(province: Province): Vector[UnaffiliatedHero] = province.unaffiliatedHeroes @@ -36,8 +32,8 @@ object AvailableApprehendOutlawCommandFactory provinceId: ProvinceId ): Option[ApprehendOutlawAvailableCommand] = { val province = gameState.provinces(provinceId) - val outlaws = availableToCapture(province) - val actors = availableActors(gameState, province) + val outlaws = availableToCapture(province) + val actors = availableActors(gameState, province) Option.when(outlaws.nonEmpty && actors.nonEmpty) { ApprehendOutlawAvailableCommand( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactory.scala index d85a856515..7238a5fbcd 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactory.scala @@ -1,16 +1,12 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - ArmTroopsAvailableCommand, - ArmamentCost -} +import net.eagle0.eagle.api.available_command.{ArmTroopsAvailableCommand, ArmamentCost} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.library.util.LegacyBattalionUtils -object AvailableArmTroopsCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableArmTroopsCommandFactory extends AvailableCommandsFactoryForType { override def availableCommand( gameState: GameState, factionId: FactionId, @@ -59,8 +55,7 @@ object AvailableArmTroopsCommandFactory actingProvinceId = provinceId, availableBattalions = affordableBattalions.map(_.id), armamentCosts = armamentCosts, - maxArmament = - LegacyProvinceUtils.effectiveInfrastructure(province).floor.toInt, + maxArmament = LegacyProvinceUtils.effectiveInfrastructure(province).floor.toInt, availableBattalionTypeIds = gameState.battalionTypes.map(_.typeId) ) ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactory.scala index 4229e60a84..a2a8b2b512 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactory.scala @@ -19,8 +19,7 @@ import net.eagle0.eagle.library.util.{IncomingArmyUtils, ProvinceDistances} import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.EagleRequire.internalRequire -object AvailableAttackDecisionCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableAttackDecisionCommandFactory extends AvailableCommandsFactoryForType { // We need to include the armies that have already withdrawn or advanced, in a consistent sort order, // so that the player doesn't learn what others have done by the shifts. @@ -72,8 +71,7 @@ object AvailableAttackDecisionCommandFactory factionId = defenderFid, heroCount = heroCount, troopCount = troopCount, - hostility = - LegacyFactionUtils.hostilityStatus(defenderFid, attackerFid, gs), + hostility = LegacyFactionUtils.hostilityStatus(defenderFid, attackerFid, gs), originProvinceId = pid ) } @@ -219,24 +217,21 @@ object AvailableAttackDecisionCommandFactory s"Incoming armies in attack decision phase are not mutually allied in province $provinceId" ) - myDecidingHostileArmies(provinceId, factionId, gameState).flatMap { - hostileArmyGroup => - decisionOptions(gameState, provinceId, factionId) match { - case items if items.isEmpty => None - case nonemptyDecisionOptions => - Some( - AttackDecisionAvailableCommand( - actingProvinceId = provinceId, - armies = armyStats(factionId, provinceId, gameState), - actingUnits = hostileArmyGroup.armies - .flatMap(_.getArmy.units) - .map(cu => - ExpandedCombatUnitUtils.expandedCombatUnit(cu, gameState) - ), - availableDecisions = nonemptyDecisionOptions - ) + myDecidingHostileArmies(provinceId, factionId, gameState).flatMap { hostileArmyGroup => + decisionOptions(gameState, provinceId, factionId) match { + case items if items.isEmpty => None + case nonemptyDecisionOptions => + Some( + AttackDecisionAvailableCommand( + actingProvinceId = provinceId, + armies = armyStats(factionId, provinceId, gameState), + actingUnits = hostileArmyGroup.armies + .flatMap(_.getArmy.units) + .map(cu => ExpandedCombatUnitUtils.expandedCombatUnit(cu, gameState)), + availableDecisions = nonemptyDecisionOptions ) - } + ) + } } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactory.scala index b6b1b8f9a1..0f5addc6d9 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactory.scala @@ -38,7 +38,7 @@ object AvailableCommandsFactory { case (_: OrganizeTroopsSelectedCommand, _) => false case (_: ExileVassalSelectedCommand, _) => false case (_: SwearBrotherhoodSelectedCommand, _) => false - case (last, next) => AvailableCommandTypeMap.matches(next, last) + case (last, next) => AvailableCommandTypeMap.matches(next, last) } def suggestedProvinceId( @@ -74,22 +74,20 @@ object AvailableCommandsFactory { } class AvailableCommandsFactory( - private val travelingFactories: Vector[AvailableCommandsFactoryForType] = - Vector( - AvailableRecruitHeroesCommandFactory, - AvailableDeclineQuestCommandsFactory, - AvailableDivineCommandsFactory, - AvailableArmTroopsCommandFactory, - AvailableTradeCommandFactory, - AvailableManagePrisonersCommandFactory, - AvailableReturnCommandsFactory - ), - private val handleRiotFactories: Vector[AvailableCommandsFactoryForType] = - Vector( - AvailableHandleRiotCrackDownCommandFactory, - AvailableHandleRiotDoNothingCommandFactory, - AvailableHandleRiotGiveCommandFactory - ), + private val travelingFactories: Vector[AvailableCommandsFactoryForType] = Vector( + AvailableRecruitHeroesCommandFactory, + AvailableDeclineQuestCommandsFactory, + AvailableDivineCommandsFactory, + AvailableArmTroopsCommandFactory, + AvailableTradeCommandFactory, + AvailableManagePrisonersCommandFactory, + AvailableReturnCommandsFactory + ), + private val handleRiotFactories: Vector[AvailableCommandsFactoryForType] = Vector( + AvailableHandleRiotCrackDownCommandFactory, + AvailableHandleRiotDoNothingCommandFactory, + AvailableHandleRiotGiveCommandFactory + ), private val freeForAllDecisionPhaseFactories: Vector[ AvailableCommandsFactoryForType ] = Vector( @@ -100,33 +98,31 @@ class AvailableCommandsFactory( ] = Vector( AvailableAttackDecisionCommandFactory ), - private val defensePhaseFactories: Vector[AvailableCommandsFactoryForType] = - Vector( - AvailableResolveTributeCommandsFactory, - AvailableDefendCommandsFactory - ), - private val commandPhaseFactories: Vector[AvailableCommandsFactoryForType] = - Vector( - AvailableApprehendOutlawCommandFactory, - AvailableControlWeatherCommandsFactory, - AvailableDiplomacyCommandsFactory, - AvailableExileVassalCommandFactory, - AvailableFeastCommandFactory, - AvailableHeroGiftCommandFactory, - AvailableImproveCommandsFactory, - AvailableMarchCommandFactory, - AvailableIssueOrdersCommandFactory, - AvailableOrganizeTroopsCommandsFactory, - AvailableAlmsCommandFactory, - AvailableReconCommandFactory, - AvailableRestCommandsFactory, - AvailableSendSuppliesCommandFactory, - AvailableStartEpidemicCommandFactory, - AvailableSuppressBeastsCommandFactory, - AvailableSwearBrotherhoodCommandFactory, - AvailableTrainCommandsFactory, - AvailableTravelCommandsFactory - ) + private val defensePhaseFactories: Vector[AvailableCommandsFactoryForType] = Vector( + AvailableResolveTributeCommandsFactory, + AvailableDefendCommandsFactory + ), + private val commandPhaseFactories: Vector[AvailableCommandsFactoryForType] = Vector( + AvailableApprehendOutlawCommandFactory, + AvailableControlWeatherCommandsFactory, + AvailableDiplomacyCommandsFactory, + AvailableExileVassalCommandFactory, + AvailableFeastCommandFactory, + AvailableHeroGiftCommandFactory, + AvailableImproveCommandsFactory, + AvailableMarchCommandFactory, + AvailableIssueOrdersCommandFactory, + AvailableOrganizeTroopsCommandsFactory, + AvailableAlmsCommandFactory, + AvailableReconCommandFactory, + AvailableRestCommandsFactory, + AvailableSendSuppliesCommandFactory, + AvailableStartEpidemicCommandFactory, + AvailableSuppressBeastsCommandFactory, + AvailableSwearBrotherhoodCommandFactory, + AvailableTrainCommandsFactory, + AvailableTravelCommandsFactory + ) ) { private def allCommands( factories: Vector[AvailableCommandsFactoryForType], @@ -181,13 +177,13 @@ class AvailableCommandsFactory( pid: ProvinceId, commands: Vector[AvailableCommand] ): Int = - commands.zipWithIndex - .find { case (ac, _) => + commands.zipWithIndex.find { + case (ac, _) => gs.provinces .get(pid) .map(_.lastCommand) .forall(last => AvailableCommandsFactory.shouldFollow(last, ac)) - } + } .map(_._2) .getOrElse(0) @@ -220,8 +216,7 @@ class AvailableCommandsFactory( gs = gs, pid = pid, commands = - if gs.provinces(pid).rulerIsTraveling then - allCommands(travelingFactories, gs, fid(gs, pid).get, pid) + if gs.provinces(pid).rulerIsTraveling then allCommands(travelingFactories, gs, fid(gs, pid).get, pid) else allCommands( commandPhaseFactories, @@ -235,8 +230,7 @@ class AvailableCommandsFactory( gs: GameState, pid: ProvinceId ): Boolean = - if gs.provinces(pid).rulerIsTraveling then - hasCommand(travelingFactories, gs, fid(gs, pid).get, pid) + if gs.provinces(pid).rulerIsTraveling then hasCommand(travelingFactories, gs, fid(gs, pid).get, pid) else hasCommand( commandPhaseFactories, @@ -440,27 +434,19 @@ class AvailableCommandsFactory( gs: GameState, fid: FactionId ): Boolean = - factionLeaderProvinces(gs, fid).exists(p => - defensePhaseCommandsForProvince(gs, p.id).isDefined - ) + factionLeaderProvinces(gs, fid).exists(p => defensePhaseCommandsForProvince(gs, p.id).isDefined) def hasAvailableHandleRiotPhaseCommands(gs: GameState): Boolean = - gs.factions.keys.exists(fid => - handleRiotPhaseCommandsForFactionLeader(gs, fid).nonEmpty - ) + gs.factions.keys.exists(fid => handleRiotPhaseCommandsForFactionLeader(gs, fid).nonEmpty) def hasAvailablePlayerCommandsPhaseCommands(gs: GameState): Boolean = gs.factions.keys.exists(fid => hasCommandsPhaseCommandsForPlayer(gs, fid)) def hasAvailableFreeForAllDecisionPhaseCommands(gs: GameState): Boolean = - gs.factions.keys.exists(fid => - freeForAllDecisionPhasePlayerCommands(gs, fid).nonEmpty - ) + gs.factions.keys.exists(fid => freeForAllDecisionPhasePlayerCommands(gs, fid).nonEmpty) def hasAvailableAttackDecisionPhaseCommands(gs: GameState): Boolean = - gs.factions.keys.exists(fid => - attackDecisionPhasePlayerCommands(gs, fid).nonEmpty - ) + gs.factions.keys.exists(fid => attackDecisionPhasePlayerCommands(gs, fid).nonEmpty) def hasAvailablePlayerDefenseCommands(gs: GameState): Boolean = gs.factions.keys.exists(fid => hasPlayerDefenseCommandsForPlayer(gs, fid)) @@ -471,30 +457,30 @@ class AvailableCommandsFactory( ): SortedMap[ProvinceId, OneProvinceAvailableCommands] = ( for { - faction <- gs.factions.get(fid) - diplomacyCommand <- AvailableResolveInvitationCommandFactory - .availableCommand(gs, faction.id) - .orElse( - AvailableResolveTruceOfferCommandFactory - .availableCommand(gs, faction.id) - ) - .orElse( - AvailableResolveRansomOfferCommandFactory - .availableCommand(gs, faction.id) - ) - .orElse( - AvailableResolveAllianceOfferCommandFactory - .availableCommand(gs, faction.id) - ) - .orElse( - AvailableResolveBreakAllianceCommandFactory - .availableCommand(gs, faction.id) - ) + faction <- gs.factions.get(fid) + diplomacyCommand <- AvailableResolveInvitationCommandFactory + .availableCommand(gs, faction.id) + .orElse( + AvailableResolveTruceOfferCommandFactory + .availableCommand(gs, faction.id) + ) + .orElse( + AvailableResolveRansomOfferCommandFactory + .availableCommand(gs, faction.id) + ) + .orElse( + AvailableResolveAllianceOfferCommandFactory + .availableCommand(gs, faction.id) + ) + .orElse( + AvailableResolveBreakAllianceCommandFactory + .availableCommand(gs, faction.id) + ) oneProvinceAvailableCommand <- optionalOneProvinceAvailableCommands( - gs = gs, - 0, - Vector(diplomacyCommand) - ) + gs = gs, + 0, + Vector(diplomacyCommand) + ) } yield SortedMap(0 -> oneProvinceAvailableCommand) ).getOrElse(SortedMap.empty) @@ -504,14 +490,14 @@ class AvailableCommandsFactory( ): SortedMap[ProvinceId, OneProvinceAvailableCommands] = ( for { - faction <- gs.factions.get(fid) - pleaseRecruitMeCommand <- AvailablePleaseRecruitMeCommandFactory - .availableCommand(gs, faction.id) + faction <- gs.factions.get(fid) + pleaseRecruitMeCommand <- AvailablePleaseRecruitMeCommandFactory + .availableCommand(gs, faction.id) oneProvinceAvailableCommand <- optionalOneProvinceAvailableCommands( - gs = gs, - 0, - Vector(pleaseRecruitMeCommand) - ) + gs = gs, + 0, + Vector(pleaseRecruitMeCommand) + ) } yield SortedMap(0 -> oneProvinceAvailableCommand) ).getOrElse(SortedMap.empty) @@ -527,9 +513,7 @@ class AvailableCommandsFactory( LegacyFactionUtils .provinces(fid, gs) .map(_.id) - .flatMap(pid => - availableAftermathCommandsForProvince(gs, pid).map(pid -> _) - )* + .flatMap(pid => availableAftermathCommandsForProvince(gs, pid).map(pid -> _))* ) def availablePlayerCommands( @@ -537,42 +521,41 @@ class AvailableCommandsFactory( fid: FactionId ): SortedMap[ProvinceId, OneProvinceAvailableCommands] = gs.currentPhase match { - case HANDLE_RIOT => handleRiotPhaseCommandsForFactionLeader(gs, fid) - case PLEASE_RECRUIT_ME => pleaseRecruitMePhasePlayerCommands(gs, fid) - case PLAYER_COMMANDS => commandsPhasePlayerCommands(gs, fid) + case HANDLE_RIOT => handleRiotPhaseCommandsForFactionLeader(gs, fid) + case PLEASE_RECRUIT_ME => pleaseRecruitMePhasePlayerCommands(gs, fid) + case PLAYER_COMMANDS => commandsPhasePlayerCommands(gs, fid) case FREE_FOR_ALL_DECISION => freeForAllDecisionPhasePlayerCommands(gs, fid) - case ATTACK_DECISION => attackDecisionPhasePlayerCommands(gs, fid) - case DEFENSE_DECISION => defensePhasePlayerCommands(gs, fid) - case BATTLE_AFTERMATH => availableAftermathPhasePlayerCommands(gs, fid) - case DIPLOMACY_RESOLUTION => + case ATTACK_DECISION => attackDecisionPhasePlayerCommands(gs, fid) + case DEFENSE_DECISION => defensePhasePlayerCommands(gs, fid) + case BATTLE_AFTERMATH => availableAftermathPhasePlayerCommands(gs, fid) + case DIPLOMACY_RESOLUTION => diplomacyResolutionPhasePlayerCommands(gs, fid) - case _ => SortedMap.empty[ProvinceId, OneProvinceAvailableCommands] + case _ => SortedMap.empty[ProvinceId, OneProvinceAvailableCommands] } - def hasAvailablePlayerCommands(gs: GameState): Boolean = { + def hasAvailablePlayerCommands(gs: GameState): Boolean = gs.currentPhase match { - case DIPLOMACY_RESOLUTION => + case DIPLOMACY_RESOLUTION => hasAvailableDiplomacyResolutionPhaseCommands(gs) - case HANDLE_RIOT => + case HANDLE_RIOT => hasAvailableHandleRiotPhaseCommands(gs) - case PLEASE_RECRUIT_ME => + case PLEASE_RECRUIT_ME => hasAvailablePleaseRecruitMePhaseCommands(gs) - case DEFENSE_DECISION => + case DEFENSE_DECISION => hasAvailablePlayerDefenseCommands(gs) - case ATTACK_DECISION => + case ATTACK_DECISION => hasAvailableAttackDecisionPhaseCommands(gs) case FREE_FOR_ALL_DECISION => hasAvailableFreeForAllDecisionPhaseCommands(gs) - case PLAYER_COMMANDS => + case PLAYER_COMMANDS => gs.factions.keys.exists { fid => hasCommandsPhaseCommandsForPlayer(gs, fid) } - case BATTLE_AFTERMATH => + case BATTLE_AFTERMATH => gs.factions.keys.exists { fid => availableAftermathPhasePlayerCommands(gs, fid).nonEmpty } - case _ => false + case _ => false } - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactory.scala index 41850739fb..b917b3d5c0 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactory.scala @@ -14,8 +14,7 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.MinVigorForControlWeather import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableControlWeatherCommandsFactory - extends AvailableCommandsFactoryForType { +object AvailableControlWeatherCommandsFactory extends AvailableCommandsFactoryForType { private def makeControlWeatherCommand( gameState: GameState, @@ -34,12 +33,10 @@ object AvailableControlWeatherCommandsFactory TargetProvinceOptions( provinceId = pid, controlWeatherTypes = ( - if LegacyProvinceUtils.hasBlizzard(gameState.provinces(pid)) then - Vector(CONTROL_WEATHER_END_BLIZZARD) + if LegacyProvinceUtils.hasBlizzard(gameState.provinces(pid)) then Vector(CONTROL_WEATHER_END_BLIZZARD) else Vector(CONTROL_WEATHER_START_BLIZZARD) ) ++ ( - if LegacyProvinceUtils.hasDrought(gameState.provinces(pid)) then - Vector(CONTROL_WEATHER_END_DROUGHT) + if LegacyProvinceUtils.hasDrought(gameState.provinces(pid)) then Vector(CONTROL_WEATHER_END_DROUGHT) else Vector(CONTROL_WEATHER_START_DROUGHT) ) ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactory.scala index 1cec6eec49..71c3e81773 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactory.scala @@ -8,8 +8,7 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.availability.ExpandedUnaffiliatedHeroUtils.expandedUnaffiliatedHero import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableDeclineQuestCommandsFactory - extends AvailableCommandsFactoryForType { +object AvailableDeclineQuestCommandsFactory extends AvailableCommandsFactoryForType { override def availableCommand( gameState: GameState, factionId: FactionId, @@ -27,9 +26,7 @@ object AvailableDeclineQuestCommandsFactory Option.when(withQuests.nonEmpty) { DeclineQuestAvailableCommand( actingProvinceId = provinceId, - declinableHeroes = withQuests.map(uh => - expandedUnaffiliatedHero(gs = gameState, uh = uh) - ) + declinableHeroes = withQuests.map(uh => expandedUnaffiliatedHero(gs = gameState, uh = uh)) ) } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactory.scala index 9e19c47e8b..a291089bcc 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactory.scala @@ -6,14 +6,8 @@ import net.eagle0.eagle.api.command.util.battalion_with_food_cost.BattalionWithF import net.eagle0.eagle.internal.army.Attacking import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - MaxCombatUnitCountPerSide, - MinVigorForDefend -} -import net.eagle0.eagle.library.util.{ - BattalionSuitability, - LegacyBattalionUtils -} +import net.eagle0.eagle.library.settings.{MaxCombatUnitCountPerSide, MinVigorForDefend} +import net.eagle0.eagle.library.util.{BattalionSuitability, LegacyBattalionUtils} import net.eagle0.eagle.library.util.command_choice_helpers.CombatUnitSelector import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils @@ -52,7 +46,7 @@ object AvailableDefendCommandsFactory extends AvailableCommandsFactoryForType { army.status match { case Attacking(_) => true - case _ => false + case _ => false } } @@ -64,7 +58,7 @@ object AvailableDefendCommandsFactory extends AvailableCommandsFactoryForType { .filter(_.vigor >= MinVigorForDefend.doubleValue) if availableHeroes.isEmpty then return None - val availableBattalions = province.battalionIds.map(gameState.battalions) + val availableBattalions = province.battalionIds.map(gameState.battalions) val availableBattalionsWithCosts = availableBattalions.map(batt => BattalionWithFoodCost( battalionId = batt.id, @@ -76,13 +70,12 @@ object AvailableDefendCommandsFactory extends AvailableCommandsFactoryForType { ) val recommendedUnits = CombatUnitSelector.selectedCombatBattalions( - desiredCount = - availableHeroes.size.min(MaxCombatUnitCountPerSide.intValue), + desiredCount = availableHeroes.size.min(MaxCombatUnitCountPerSide.intValue), heroes = availableHeroes.toVector, battalions = availableBattalions.toVector, battalionTypes = gameState.battalionTypes.toVector ) - val hostileUnits = hostileArmies + val hostileUnits = hostileArmies .flatMap(_.armies) .flatMap(_.army) .flatMap(_.units) @@ -93,15 +86,13 @@ object AvailableDefendCommandsFactory extends AvailableCommandsFactoryForType { .toVector .map(_.id), actingProvinceId = province.id, - suitableBattalionsForHeroes = - BattalionSuitability.suitableBattalionsForHeroes( - hs = availableHeroes.toVector, - bs = availableBattalions.toVector, - bts = gameState.battalionTypes.toVector - ), + suitableBattalionsForHeroes = BattalionSuitability.suitableBattalionsForHeroes( + hs = availableHeroes.toVector, + bs = availableBattalions.toVector, + bts = gameState.battalionTypes.toVector + ), availableBattalions = availableBattalionsWithCosts, - availableFleeProvinceIds = - sortedFleeProvinces(from = province, gs = gameState), + availableFleeProvinceIds = sortedFleeProvinces(from = province, gs = gameState), recommendedUnits = recommendedUnits, hostileFactionIds = hostileArmies.toVector.map(_.factionId).distinct, hostileHeroCount = hostileUnits.size, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactory.scala index dbd97465dc..43cb0453c8 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactory.scala @@ -31,8 +31,7 @@ import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.library.util.ProvinceDistances -object AvailableDiplomacyCommandsFactory - extends AvailableCommandsFactoryForType { +object AvailableDiplomacyCommandsFactory extends AvailableCommandsFactoryForType { def availableHeroIds(gs: GameState, pid: ProvinceId): Vector[HeroId] = gs.provinces(pid) @@ -42,9 +41,7 @@ object AvailableDiplomacyCommandsFactory def recommendedHeroId(gs: GameState, availableHids: Seq[HeroId]): HeroId = availableHids - .sortBy(hid => - (LegacyHeroUtils.fatigue(gs.heroes(hid)), -gs.heroes(hid).vigor) - ) match { + .sortBy(hid => (LegacyHeroUtils.fatigue(gs.heroes(hid)), -gs.heroes(hid).vigor)) match { case sortedHeroes => sortedHeroes .find(hid => !LegacyFactionUtils.isFactionHead(hid, gs)) @@ -123,38 +120,36 @@ object AvailableDiplomacyCommandsFactory pid: ProvinceId, actingFid: FactionId, targetFid: FactionId - ): Boolean = { - LegacyFactionUtils.provinces(targetFid, gs).headOption.exists { - targetProvince => - val eligibleNeighbors: ProvinceId => Vector[ProvinceId] = - p => - gs.provinces(p) - .neighbors - .map(_.provinceId) - .map(gs.provinces) - .filter(neighborProvince => - // inviting across empty province - neighborProvince.rulingFactionId.isEmpty || - // inviting across your own province - neighborProvince.rulingFactionId.contains(actingFid) || - // inviting across the target's province - neighborProvince.rulingFactionId.contains(targetFid) || - // inviting across your ally's province - LegacyFactionUtils - .hasAlliance( - neighborProvince.rulingFactionId.get, - actingFid, - gs - ) - ) - .map(_.id) - .toVector + ): Boolean = + LegacyFactionUtils.provinces(targetFid, gs).headOption.exists { targetProvince => + val eligibleNeighbors: ProvinceId => Vector[ProvinceId] = + p => + gs.provinces(p) + .neighbors + .map(_.provinceId) + .map(gs.provinces) + .filter(neighborProvince => + // inviting across empty province + neighborProvince.rulingFactionId.isEmpty || + // inviting across your own province + neighborProvince.rulingFactionId.contains(actingFid) || + // inviting across the target's province + neighborProvince.rulingFactionId.contains(targetFid) || + // inviting across your ally's province + LegacyFactionUtils + .hasAlliance( + neighborProvince.rulingFactionId.get, + actingFid, + gs + ) + ) + .map(_.id) + .toVector - ProvinceDistances - .distance(pid, targetProvince.id, eligibleNeighbors) - .isDefined + ProvinceDistances + .distance(pid, targetProvince.id, eligibleNeighbors) + .isDefined } - } private def inviteOptionForTargetFaction( gs: GameState, @@ -191,8 +186,8 @@ object AvailableDiplomacyCommandsFactory targetFid: FactionId ): Vector[DiplomacyOption] = { val prisonersAvailableToOffer = availablePrisoners(gs.provinces(pid)) - val hostagesAvailableToOffer = availableHostages(gs, pid) - val goldAvailableToOffer = gs.provinces(pid).gold + val hostagesAvailableToOffer = availableHostages(gs, pid) + val goldAvailableToOffer = gs.provinces(pid).gold if prisonersAvailableToOffer.nonEmpty || hostagesAvailableToOffer.nonEmpty || goldAvailableToOffer > 0 then @@ -200,20 +195,19 @@ object AvailableDiplomacyCommandsFactory gs, factionId = actingFid, targetFactionId = targetFid - ) - .map { prisonerToBeRansomed => - RansomOfferOption( - targetFactionId = targetFid, - ransomOffer = Some( - RansomOfferDetails( - prisonerToBeRansomed = Some(prisonerToBeRansomed), - prisonersOffered = prisonersAvailableToOffer, - hostagesOffered = hostagesAvailableToOffer, - goldOffered = goldAvailableToOffer - ) + ).map { prisonerToBeRansomed => + RansomOfferOption( + targetFactionId = targetFid, + ransomOffer = Some( + RansomOfferDetails( + prisonerToBeRansomed = Some(prisonerToBeRansomed), + prisonersOffered = prisonersAvailableToOffer, + hostagesOffered = hostagesAvailableToOffer, + goldOffered = goldAvailableToOffer ) ) - } + ) + } else Vector() end if } @@ -264,10 +258,9 @@ object AvailableDiplomacyCommandsFactory gameState: GameState, factionId: FactionId, provinceId: ProvinceId - ): Option[DiplomacyAvailableCommand] = { + ): Option[DiplomacyAvailableCommand] = if availableHeroIds(gameState, provinceId).isEmpty then None - else if gameState.provinces(provinceId).rulingFactionHeroIds.size < 2 then - None + else if gameState.provinces(provinceId).rulingFactionHeroIds.size < 2 then None else { gameState.factions.keys .filterNot(_ == factionId) @@ -289,7 +282,7 @@ object AvailableDiplomacyCommandsFactory .toVector .sortBy(opt => LegacyFactionUtils.sortKey(gameState.factions(opt match { - case TruceOption(targetFactionId, _, _ /* unknownFieldSet */ ) => + case TruceOption(targetFactionId, _, _ /* unknownFieldSet */ ) => targetFactionId case InvitationOption( targetFactionId, @@ -311,7 +304,7 @@ object AvailableDiplomacyCommandsFactory _ /* unknownFieldSet */ ) => targetFactionId - case DiplomacyOption.Empty => ??? + case DiplomacyOption.Empty => ??? })) ) match { case items if items.isEmpty => None @@ -328,7 +321,6 @@ object AvailableDiplomacyCommandsFactory ) } } - } private def availablePrisoners( province: Province @@ -365,19 +357,18 @@ object AvailableDiplomacyCommandsFactory gameState: GameState, factionId: FactionId, targetFactionId: FactionId - ): Vector[PrisonerToBeRansomed] = { + ): Vector[PrisonerToBeRansomed] = for { province <- gameState.provinces.values - .filter(_.rulingFactionId.contains(targetFactionId)) - .toVector + .filter(_.rulingFactionId.contains(targetFactionId)) + .toVector prisoner <- province.unaffiliatedHeroes.filter( - _.`type` == UNAFFILIATED_HERO_PRISONER - ) + _.`type` == UNAFFILIATED_HERO_PRISONER + ) if prisoner.lastFaction.contains(factionId) if LegacyFactionUtils.isFactionLeader(prisoner.heroId, gameState) } yield PrisonerToBeRansomed( prisonerHeroId = prisoner.heroId, provinceIdForPrisoner = province.id ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactory.scala index bd6b462b93..eaa9e91230 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactory.scala @@ -7,8 +7,7 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableExileVassalCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableExileVassalCommandFactory extends AvailableCommandsFactoryForType { def exilableHeroIds( gameState: GameState, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactory.scala index 8c3dab0015..354fbd7a85 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactory.scala @@ -3,22 +3,13 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.api.available_command.FreeForAllDecisionAvailableCommand import net.eagle0.eagle.api.command.util.army_stats.ArmyStats -import net.eagle0.eagle.api.command.util.attack_decision_type.{ - AdvanceDecision, - AttackDecisionType, - WithdrawDecision -} +import net.eagle0.eagle.api.command.util.attack_decision_type.{AdvanceDecision, AttackDecisionType, WithdrawDecision} import net.eagle0.eagle.common.round_phase.RoundPhase -import net.eagle0.eagle.internal.army.{ - AwaitingDecision, - HostileArmyGroup, - MovingArmy -} +import net.eagle0.eagle.internal.army.{AwaitingDecision, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.IncomingArmyUtils -object AvailableFreeForAllDecisionCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableFreeForAllDecisionCommandFactory extends AvailableCommandsFactoryForType { private def decisionOptions( armies: Seq[MovingArmy] @@ -58,35 +49,29 @@ object AvailableFreeForAllDecisionCommandFactory pid: ProvinceId, gs: GameState ): Vector[ArmyStats] = - relevantArmies(pid, gs).map(ia => - IncomingArmyUtils.stats(toFid, ia.getArmy, gs, ia.originProvince) - ) + relevantArmies(pid, gs).map(ia => IncomingArmyUtils.stats(toFid, ia.getArmy, gs, ia.originProvince)) override def availableCommand( gameState: GameState, factionId: FactionId, provinceId: ProvinceId - ): Option[FreeForAllDecisionAvailableCommand] = { - myHostileArmies(provinceId, factionId, gameState).flatMap { - hostileArmyGroup => - Option.when( - gameState.currentPhase == RoundPhase.FREE_FOR_ALL_DECISION - && !IncomingArmyUtils.incomingArmiesAreMutuallyAllied( - gameState.provinces(provinceId), - gameState - ) - )( - FreeForAllDecisionAvailableCommand( - provinceId = provinceId, - armies = armyStats(factionId, provinceId, gameState), - actingUnits = hostileArmyGroup.armies - .flatMap(_.getArmy.units) - .map(cu => - ExpandedCombatUnitUtils.expandedCombatUnit(cu, gameState) - ), - availableDecisions = decisionOptions(hostileArmyGroup.armies) + ): Option[FreeForAllDecisionAvailableCommand] = + myHostileArmies(provinceId, factionId, gameState).flatMap { hostileArmyGroup => + Option.when( + gameState.currentPhase == RoundPhase.FREE_FOR_ALL_DECISION + && !IncomingArmyUtils.incomingArmiesAreMutuallyAllied( + gameState.provinces(provinceId), + gameState ) + )( + FreeForAllDecisionAvailableCommand( + provinceId = provinceId, + armies = armyStats(factionId, provinceId, gameState), + actingUnits = hostileArmyGroup.armies + .flatMap(_.getArmy.units) + .map(cu => ExpandedCombatUnitUtils.expandedCombatUnit(cu, gameState)), + availableDecisions = decisionOptions(hostileArmyGroup.armies) ) + ) } - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactory.scala index 2bbfbea974..993e1fe510 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactory.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - ExpandedCapturedHero, - HandleCapturedHeroAvailableCommand -} +import net.eagle0.eagle.api.available_command.{ExpandedCapturedHero, HandleCapturedHeroAvailableCommand} import net.eagle0.eagle.api.command.util.captured_hero_option.CapturedHeroOption.{ EXECUTE_CAPTURED_HERO_OPTION, EXILE_CAPTURED_HERO_OPTION, @@ -17,17 +14,15 @@ import net.eagle0.eagle.internal.unaffiliated_hero.CapturedHero import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.view_filters.HeroViewFilter -object AvailableHandleCapturedHeroCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableHandleCapturedHeroCommandFactory extends AvailableCommandsFactoryForType { - private val optionsWithoutRecruit = { + private val optionsWithoutRecruit = Vector( IMPRISON_CAPTURED_HERO_OPTION, EXILE_CAPTURED_HERO_OPTION, EXECUTE_CAPTURED_HERO_OPTION ) - } - private val optionsWithRecruit = + private val optionsWithRecruit = RECRUIT_CAPTURED_HERO_OPTION +: optionsWithoutRecruit private val optionsForFactionLeader = Vector( IMPRISON_CAPTURED_HERO_OPTION, @@ -72,14 +67,11 @@ object AvailableHandleCapturedHeroCommandFactory provinceId: ProvinceId ): Option[HandleCapturedHeroAvailableCommand] = capturedHeroes - .find(ch => - ch.recruitmentRefusedMessageId.nonEmpty || ch.messageId.nonEmpty - ) + .find(ch => ch.recruitmentRefusedMessageId.nonEmpty || ch.messageId.nonEmpty) .map { capturedHero => HandleCapturedHeroAvailableCommand( actingProvinceId = provinceId, - availableHeroes = - Vector(expandedCapturedHero(gameState, capturedHero)) + availableHeroes = Vector(expandedCapturedHero(gameState, capturedHero)) ) } @@ -87,15 +79,15 @@ object AvailableHandleCapturedHeroCommandFactory gameState: GameState, factionId: FactionId, provinceId: ProvinceId - ): Option[HandleCapturedHeroAvailableCommand] = { + ): Option[HandleCapturedHeroAvailableCommand] = // If we've already attempted to recruit one of the heroes, only show available commands for that one gameState .provinces(provinceId) .capturedHeroes .partition(_.recruitmentAttempted) match { - case (Vector(), Vector()) => None + case (Vector(), Vector()) => None // If the top hero in either set doesn't have a message, return nothing, otherwise return just the one option - case (Vector(), notRecruited) => + case (Vector(), notRecruited) => firstOption( gameState = gameState, capturedHeroes = notRecruited.toVector, @@ -108,5 +100,4 @@ object AvailableHandleCapturedHeroCommandFactory provinceId = provinceId ) } - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactory.scala index 93e20ed51e..6f15fd3ea9 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactory.scala @@ -7,17 +7,14 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.MinVigorForCrackDown import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableHandleRiotCrackDownCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableHandleRiotCrackDownCommandFactory extends AvailableCommandsFactoryForType { def crackDownHeroIds( province: Province, gameState: GameState ): Vector[HeroId] = province.rulingFactionHeroIds - .filter(hid => - gameState.heroes(hid).vigor >= MinVigorForCrackDown.doubleValue - ) + .filter(hid => gameState.heroes(hid).vigor >= MinVigorForCrackDown.doubleValue) .toVector override def availableCommand( @@ -26,7 +23,7 @@ object AvailableHandleRiotCrackDownCommandFactory provinceId: ProvinceId ): Option[HandleRiotCrackDownAvailableCommand] = { val province = gameState.provinces(provinceId) - val heroIds = crackDownHeroIds(province, gameState) + val heroIds = crackDownHeroIds(province, gameState) Option.when( LegacyProvinceUtils diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactory.scala index 0d7aff29c7..1f90d71c8c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactory.scala @@ -5,8 +5,7 @@ import net.eagle0.eagle.api.available_command.HandleRiotDoNothingAvailableComman import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableHandleRiotDoNothingCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableHandleRiotDoNothingCommandFactory extends AvailableCommandsFactoryForType { override def availableCommand( gameState: GameState, factionId: FactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactory.scala index 92e8212f46..e949edfe35 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactory.scala @@ -6,8 +6,7 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.settings.{RiotMaxFood, RiotMaxGold} import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableHandleRiotGiveCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableHandleRiotGiveCommandFactory extends AvailableCommandsFactoryForType { override def availableCommand( gameState: GameState, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactory.scala index 214bfdbef0..92b85dcf40 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactory.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - EligibleGift, - HeroGiftAvailableCommand -} +import net.eagle0.eagle.api.available_command.{EligibleGift, HeroGiftAvailableCommand} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.MaxGiftGold @@ -31,7 +28,7 @@ object AvailableHeroGiftCommandFactory extends AvailableCommandsFactoryForType { gameState: GameState, factionId: FactionId, provinceId: ProvinceId - ): Option[HeroGiftAvailableCommand] = { + ): Option[HeroGiftAvailableCommand] = consideredProvinces(gameState, factionId, provinceId) .filterNot(_.gold == 0) .flatMap(p => eligibleRecipients(p, gameState)) match { @@ -44,5 +41,4 @@ object AvailableHeroGiftCommandFactory extends AvailableCommandsFactoryForType { ) ) } - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactory.scala index b865c10de1..0ae7524f66 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactory.scala @@ -2,12 +2,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.api.available_command.ImproveAvailableCommand -import net.eagle0.eagle.common.improvement_type.ImprovementType.{ - AGRICULTURE, - DEVASTATION, - ECONOMY, - INFRASTRUCTURE -} +import net.eagle0.eagle.common.improvement_type.ImprovementType.{AGRICULTURE, DEVASTATION, ECONOMY, INFRASTRUCTURE} import net.eagle0.eagle.common.profession.Profession.ENGINEER import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -42,14 +37,14 @@ object AvailableImproveCommandsFactory extends AvailableCommandsFactoryForType { .filterNot(_.vigor < MinVigorForImprove.doubleValue) val availableTypes = - Option.when(province.economy < IMPROVEMENT_MAX) { ECONOMY } ++ - Option.when(province.agriculture < IMPROVEMENT_MAX) { AGRICULTURE } ++ + Option.when(province.economy < IMPROVEMENT_MAX)(ECONOMY) ++ + Option.when(province.agriculture < IMPROVEMENT_MAX)(AGRICULTURE) ++ Option.when(province.infrastructure < IMPROVEMENT_MAX) { INFRASTRUCTURE } ++ Option.when( province.economyDevastation > 0 || province.agricultureDevastation > 0 || province.infrastructureDevastation > 0 - ) { DEVASTATION } + )(DEVASTATION) Option.when(availableHeroes.nonEmpty && availableTypes.nonEmpty) { ImproveAvailableCommand( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactory.scala index d28c4d015d..f8810d8630 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactory.scala @@ -7,8 +7,7 @@ import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.* import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils -object AvailableIssueOrdersCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableIssueOrdersCommandFactory extends AvailableCommandsFactoryForType { override def availableCommand( gameState: GameState, @@ -28,9 +27,7 @@ object AvailableIssueOrdersCommandFactory .filter(_.rulingFactionId.contains(factionId)) .toVector .sortBy(_.name) - .map(p => - ProvinceOrders(provinceId = p.id, orders = p.provinceOrders) - ), + .map(p => ProvinceOrders(provinceId = p.id, orders = p.provinceOrders)), availableOrders = Vector(DEVELOP, MOBILIZE, EXPAND, ENTRUST) ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonersCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonersCommandFactory.scala index 3b6afcce11..5d263d84ef 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonersCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonersCommandFactory.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.common.MoreOption import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - ManagePrisonersAvailableCommand, - PrisonerToManage -} +import net.eagle0.eagle.api.available_command.{ManagePrisonersAvailableCommand, PrisonerToManage} import net.eagle0.eagle.api.command.util.prisoner_management_type.{ PrisonerManagementOption, PrisonerManagementOptionExecute, @@ -17,8 +14,7 @@ import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFF import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -object AvailableManagePrisonersCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableManagePrisonersCommandFactory extends AvailableCommandsFactoryForType { private def availableMoveToProvinceIds( fid: FactionId, @@ -51,9 +47,7 @@ object AvailableManagePrisonersCommandFactory _.rulingFactionId.contains(factionWithThisPrisonerAsLeader.get.id) ) )( - PrisonerManagementOptionReturn(toFactionId = - factionWithThisPrisonerAsLeader.get.id - ) + PrisonerManagementOptionReturn(toFactionId = factionWithThisPrisonerAsLeader.get.id) ) .toVector } else { diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactory.scala index ebefb95a58..805ddcf372 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactory.scala @@ -10,19 +10,9 @@ import net.eagle0.eagle.api.available_command.{ import net.eagle0.eagle.api.command.util.battalion_with_food_cost.BattalionWithFoodCost import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - MaxCombatUnitCountPerSide, - MinVigorForMarch -} -import net.eagle0.eagle.library.util.{ - BattalionSuitability, - LegacyBattalionUtils, - ShardokMapInfo -} -import net.eagle0.eagle.library.util.command_choice_helpers.{ - CombatUnitSelector, - MarchSuppliesHelpers -} +import net.eagle0.eagle.library.settings.{MaxCombatUnitCountPerSide, MinVigorForMarch} +import net.eagle0.eagle.library.util.{BattalionSuitability, LegacyBattalionUtils, ShardokMapInfo} +import net.eagle0.eagle.library.util.command_choice_helpers.{CombatUnitSelector, MarchSuppliesHelpers} import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils @@ -42,9 +32,9 @@ object AvailableMarchCommandFactory extends AvailableCommandsFactoryForType { .get .startingPositionIndex - val mapInfo = ShardokMapInfo.shardokMapInfos(destinationProvince.id) + val mapInfo = ShardokMapInfo.shardokMapInfos(destinationProvince.id) val destinationCastleCount = mapInfo.castleCount - val requiresRiverCrossing = mapInfo.waterCrossingRequirementsByPosition( + val requiresRiverCrossing = mapInfo.waterCrossingRequirementsByPosition( startingPositionIndex ) >= 10 @@ -73,7 +63,7 @@ object AvailableMarchCommandFactory extends AvailableCommandsFactoryForType { .min(availableBattalions.size) .min(originProvince.rulingFactionHeroIds.size - 2) .min(MaxCombatUnitCountPerSide.intValue) - val recommendedConfig = + val recommendedConfig = Option.when(recommendedSendCount > 0) { val units = CombatUnitSelector.selectedCombatBattalions( desiredCount = recommendedSendCount, @@ -128,9 +118,7 @@ object AvailableMarchCommandFactory extends AvailableCommandsFactoryForType { ): Option[MarchAvailableCommand] = LegacyHeroUtils .consideredProvinces(gameState, factionId, provinceId) - .flatMap(p => - oneOriginProvinceCommand(gameState = gameState, originProvince = p) - ) match { + .flatMap(p => oneOriginProvinceCommand(gameState = gameState, originProvince = p)) match { case items if items.isEmpty => None case opcs => Some( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactory.scala index 4d5ceb9a22..1f9d34faab 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactory.scala @@ -1,16 +1,12 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - OrganizeTroopsAvailableCommand, - TroopCost -} +import net.eagle0.eagle.api.available_command.{OrganizeTroopsAvailableCommand, TroopCost} import net.eagle0.eagle.api.available_command.OrganizeTroopsAvailableCommand.BattalionTypeStatus import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableOrganizeTroopsCommandsFactory - extends AvailableCommandsFactoryForType { +object AvailableOrganizeTroopsCommandsFactory extends AvailableCommandsFactoryForType { val maxBattalions = 10 // FIXME override def availableCommand( @@ -20,20 +16,19 @@ object AvailableOrganizeTroopsCommandsFactory ): Option[OrganizeTroopsAvailableCommand] = { val province = gameState.provinces(provinceId) - val availableTypeStatuses = gameState.battalionTypes.toVector - .map { bt => - BattalionTypeStatus( - typeId = bt.typeId, - minimumAgriculture = bt.minimumAgriculture, - minimumEconomy = bt.minimumEconomy, - meetsRequirements = LegacyProvinceUtils - .availableBattalionTypeIds( - province, - gameState.battalionTypes.toVector - ) - .contains(bt.typeId) - ) - } + val availableTypeStatuses = gameState.battalionTypes.toVector.map { bt => + BattalionTypeStatus( + typeId = bt.typeId, + minimumAgriculture = bt.minimumAgriculture, + minimumEconomy = bt.minimumEconomy, + meetsRequirements = LegacyProvinceUtils + .availableBattalionTypeIds( + province, + gameState.battalionTypes.toVector + ) + .contains(bt.typeId) + ) + } .sortBy(_.typeId.value) val troopCosts = gameState.battalionTypes.toVector.map(t => @@ -44,8 +39,7 @@ object AvailableOrganizeTroopsCommandsFactory ) if troopCosts.isEmpty then return None - if troopCosts.map(_.costPerTroop).min.ceil.toInt > province.gold then - return None + if troopCosts.map(_.costPerTroop).min.ceil.toInt > province.gold then return None val existingEligibleBattalions = province.battalionIds .map(bid => gameState.battalions(bid)) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactory.scala index 8d182df6ae..d2d2d52ca8 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactory.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.availability -import net.eagle0.eagle.api.available_command.{ - OneProvincePleaseRecruitMe, - PleaseRecruitMeAvailableCommand -} +import net.eagle0.eagle.api.available_command.{OneProvincePleaseRecruitMe, PleaseRecruitMeAvailableCommand} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.MinSupportForTaxes @@ -19,20 +16,19 @@ object AvailablePleaseRecruitMeCommandFactory { ): Option[OneProvincePleaseRecruitMe] = { val availableHeroes = for { targetUH <- p.unaffiliatedHeroes.filter(uh => - LegacyUnaffiliatedHeroUtils.willPleaseRecruitMe( - gameState = gs, - factionId = fid, - unaffiliatedHero = uh - ) - ) - } yield { + LegacyUnaffiliatedHeroUtils.willPleaseRecruitMe( + gameState = gs, + factionId = fid, + unaffiliatedHero = uh + ) + ) + } yield // FIXME: We should be generating the LLM request and its textID here instead of earlier in the round ExpandedUnaffiliatedHeroUtils .expandedUnaffiliatedHero( gs = gs, uh = targetUH ) - } Option.when(availableHeroes.nonEmpty)( OneProvincePleaseRecruitMe( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactory.scala index 606d87b51c..66d782877e 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactory.scala @@ -8,8 +8,7 @@ import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.library.util.recruitment_odds.LegacyRecruitmentOdds -object AvailableRecruitHeroesCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableRecruitHeroesCommandFactory extends AvailableCommandsFactoryForType { override def availableCommand( gameState: GameState, @@ -21,8 +20,7 @@ object AvailableRecruitHeroesCommandFactory if !province.rulerIsTraveling then return None val faction = gameState.factions(factionId) - if !LegacyProvinceUtils.ruledByFactionLeader(province, gameState) then - return None + if !LegacyProvinceUtils.ruledByFactionLeader(province, gameState) then return None val expandedRecruitable = province.unaffiliatedHeroes .filterNot(uh => LegacyFactionUtils.isFactionLeader(uh.heroId, gameState)) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactory.scala index 0a354c2b94..b1116daf01 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactory.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.ResolveAllianceOfferAvailableCommand -import net.eagle0.eagle.common.diplomacy_offer.{ - AllianceOfferDetails, - DiplomacyOffer -} +import net.eagle0.eagle.common.diplomacy_offer.{AllianceOfferDetails, DiplomacyOffer} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.DIPLOMACY_OFFER_STATUS_UNRESOLVED import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.FactionId @@ -52,12 +49,11 @@ object AvailableResolveAllianceOfferCommandFactory { messengerHeroId = messengerHeroId, messengerOriginProvinceId = messengerOriginProvinceId, status = status, - eligibleStatuses = - EligibleDiplomacyStatuses.acceptRejectStatuses ++ EligibleDiplomacyStatuses - .maybeImprisonStatus( - actingFactionId = factionId, - gameState = gameState - ), + eligibleStatuses = EligibleDiplomacyStatuses.acceptRejectStatuses ++ EligibleDiplomacyStatuses + .maybeImprisonStatus( + actingFactionId = factionId, + gameState = gameState + ), offerTextId = offerTextId ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactory.scala index 0cc1ab62b7..3016d2dbd0 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactory.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.ResolveBreakAllianceAvailableCommand -import net.eagle0.eagle.common.diplomacy_offer.{ - BreakAllianceDetails, - DiplomacyOffer -} +import net.eagle0.eagle.common.diplomacy_offer.{BreakAllianceDetails, DiplomacyOffer} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_ACCEPTED, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactory.scala index cf820aad20..f50a8af9e0 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactory.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.ResolveInvitationAvailableCommand -import net.eagle0.eagle.common.diplomacy_offer.{ - DiplomacyOffer, - InvitationDetails -} +import net.eagle0.eagle.common.diplomacy_offer.{DiplomacyOffer, InvitationDetails} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_ACCEPTED, DIPLOMACY_OFFER_STATUS_UNRESOLVED diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactory.scala index 37df51f9a1..432dc01f7c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactory.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.ResolveRansomOfferAvailableCommand -import net.eagle0.eagle.common.diplomacy_offer.{ - DiplomacyOffer, - InvitationDetails, - RansomOfferDetails -} +import net.eagle0.eagle.common.diplomacy_offer.{DiplomacyOffer, InvitationDetails, RansomOfferDetails} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_REJECTED, DIPLOMACY_OFFER_STATUS_UNRESOLVED diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactory.scala index 981f50f896..0b6c1f4116 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactory.scala @@ -1,17 +1,13 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - ResolveTributeAvailableCommand, - TributeAndFaction -} +import net.eagle0.eagle.api.available_command.{ResolveTributeAvailableCommand, TributeAndFaction} import net.eagle0.eagle.internal.army.{HostileArmyGroup, HostileArmyGroupStatus} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.util.ArmyUtils -object AvailableResolveTributeCommandsFactory - extends AvailableCommandsFactoryForType { +object AvailableResolveTributeCommandsFactory extends AvailableCommandsFactoryForType { private def makeResolveTributeCommand( province: Province, @@ -25,22 +21,20 @@ object AvailableResolveTributeCommandsFactory Option.when(incomingTributeDemands.nonEmpty) { ResolveTributeAvailableCommand( actingProvinceId = province.id, - demands = incomingTributeDemands - .map { - case ag @ HostileArmyGroup( - fid: FactionId, - _, - status: HostileArmyGroupStatus, - _ /* unknownFieldSet */ - ) => - TributeAndFaction( - demandingFactionId = fid, - tributeDemanded = - status.asMessage.getTributeDemanded.tributeAmount, - heroCount = ArmyUtils.heroCount(ag), - troopCount = ArmyUtils.troopCount(ag, gs) - ) - }, + demands = incomingTributeDemands.map { + case ag @ HostileArmyGroup( + fid: FactionId, + _, + status: HostileArmyGroupStatus, + _ /* unknownFieldSet */ + ) => + TributeAndFaction( + demandingFactionId = fid, + tributeDemanded = status.asMessage.getTributeDemanded.tributeAmount, + heroCount = ArmyUtils.heroCount(ag), + troopCount = ArmyUtils.troopCount(ag, gs) + ) + }, availableGold = province.gold, availableFood = province.food ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactory.scala index d3e8ece083..de168ea902 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactory.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.ResolveTruceOfferAvailableCommand -import net.eagle0.eagle.common.diplomacy_offer.{ - DiplomacyOffer, - TruceOfferDetails -} +import net.eagle0.eagle.common.diplomacy_offer.{DiplomacyOffer, TruceOfferDetails} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.DIPLOMACY_OFFER_STATUS_UNRESOLVED import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.settings.TruceMonths @@ -59,13 +56,12 @@ object AvailableResolveTruceOfferCommandFactory { messengerHeroId = messengerHeroId, messengerOriginProvinceId = messengerOriginProvinceId, status = status, - eligibleStatuses = - (EligibleDiplomacyStatuses.acceptRejectStatuses ++ EligibleDiplomacyStatuses - .maybeImprisonStatus( - actingFactionId = factionId, - gameState = gameState - ) - .toVector).toVector, + eligibleStatuses = (EligibleDiplomacyStatuses.acceptRejectStatuses ++ EligibleDiplomacyStatuses + .maybeImprisonStatus( + actingFactionId = factionId, + gameState = gameState + ) + .toVector).toVector, offerTextId = offerTextId ) }.toVector diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactory.scala index 6af9626531..6e5047c653 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactory.scala @@ -7,8 +7,7 @@ import net.eagle0.eagle.library.settings.MinVigorForSendSupplies import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableSendSuppliesCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableSendSuppliesCommandFactory extends AvailableCommandsFactoryForType { override def availableCommand( gameState: GameState, factionId: FactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactory.scala index f3093f7139..8e3233f6c5 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactory.scala @@ -8,8 +8,7 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.MinVigorForStartEpidemic import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableStartEpidemicCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableStartEpidemicCommandFactory extends AvailableCommandsFactoryForType { private def makeStartEpidemicCommand( gameState: GameState, @@ -38,9 +37,7 @@ object AvailableStartEpidemicCommandFactory availableHeroIds = necromancersWithSufficientVigor .sortBy(-_.vigor) .map(_.id), - options = targetProvinceIds.map(pid => - StartEpidemicOptions(targetProvinceId = pid) - ), + options = targetProvinceIds.map(pid => StartEpidemicOptions(targetProvinceId = pid)), actingProvinceId = province.id ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSuppressBeastsCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSuppressBeastsCommandFactory.scala index 10fa7efc7e..baeb6faa88 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSuppressBeastsCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSuppressBeastsCommandFactory.scala @@ -7,17 +7,14 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.MinVigorForSuppressBeasts import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -object AvailableSuppressBeastsCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableSuppressBeastsCommandFactory extends AvailableCommandsFactoryForType { private def makeSuppressBeastsCommand( gameState: GameState, province: Province ): Option[SuppressBeastsAvailableCommand] = { val availableHeroIds = province.rulingFactionHeroIds - .filter(hid => - gameState.heroes(hid).vigor >= MinVigorForSuppressBeasts.doubleValue - ) + .filter(hid => gameState.heroes(hid).vigor >= MinVigorForSuppressBeasts.doubleValue) Option.when( LegacyProvinceUtils.hasBeasts(province) && availableHeroIds.nonEmpty diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactory.scala index 4d14915b7a..48b2bdf6dd 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactory.scala @@ -4,13 +4,9 @@ import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} import net.eagle0.eagle.api.available_command.SwearBrotherhoodAvailableCommand import net.eagle0.eagle.api.available_command.SwearBrotherhoodAvailableCommand.HeroAndBackstory import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.settings.{ - MaximumFactionLeaders, - MinimumLoyaltyForSwearBrotherhood -} +import net.eagle0.eagle.library.settings.{MaximumFactionLeaders, MinimumLoyaltyForSwearBrotherhood} -object AvailableSwearBrotherhoodCommandFactory - extends AvailableCommandsFactoryForType { +object AvailableSwearBrotherhoodCommandFactory extends AvailableCommandsFactoryForType { def canHaveMoreLeaders(gameState: GameState, factionId: FactionId): Boolean = gameState diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactory.scala index 49c35628f8..9b3f7d352b 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactory.scala @@ -23,7 +23,7 @@ object AvailableTrainCommandsFactory extends AvailableCommandsFactoryForType { factionId: FactionId, provinceId: ProvinceId ): Option[TrainAvailableCommand] = { - val province = gameState.provinces(provinceId) + val province = gameState.provinces(provinceId) val availableHeroes = province.rulingFactionHeroIds .map(heroId => gameState.heroes(heroId)) .filter(_.vigor >= MinVigorForTrain.doubleValue) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/ExpandedCombatUnitUtils.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/ExpandedCombatUnitUtils.scala index 8ee051499a..e121fa27cf 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/ExpandedCombatUnitUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/ExpandedCombatUnitUtils.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.command.util.expanded_combat_unit.ExpandedCombatUnit import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.util.view_filters.{ - HeroViewFilter, - LegacyBattalionViewFilter -} +import net.eagle0.eagle.library.util.view_filters.{HeroViewFilter, LegacyBattalionViewFilter} object ExpandedCombatUnitUtils { def expandedCombatUnit( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/availability/package.scala b/src/main/scala/net/eagle0/eagle/library/actions/availability/package.scala index 239e4c42b8..3dc70161b1 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/availability/package.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/availability/package.scala @@ -34,21 +34,21 @@ package object availability { .toMap val professionOrdering: Map[Profession, Int] = Map( - PALADIN -> 1, - ENGINEER -> 2, - RANGER -> 3, - MAGE -> 4, - NECROMANCER -> 5, - CHAMPION -> 6, - NO_PROFESSION -> 7, + PALADIN -> 1, + ENGINEER -> 2, + RANGER -> 3, + MAGE -> 4, + NECROMANCER -> 5, + CHAMPION -> 6, + NO_PROFESSION -> 7, UNKNOWN_PROFESSION -> 8 ) val battalionTypeOrdering: Map[BattalionTypeId, Int] = Map( - HEAVY_CAVALRY -> 1, + HEAVY_CAVALRY -> 1, HEAVY_INFANTRY -> 2, - LONGBOWMEN -> 3, - LIGHT_CAVALRY -> 4, + LONGBOWMEN -> 3, + LIGHT_CAVALRY -> 4, LIGHT_INFANTRY -> 5 ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesAction.scala index 498a258321..f659283963 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesAction.scala @@ -7,11 +7,7 @@ import net.eagle0.eagle.library.util.province.ProvinceUtils import net.eagle0.eagle.library.util.ransom_validity.RansomValidity import net.eagle0.eagle.library.util.ReturningHeroes import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC} import net.eagle0.eagle.model.action_result.types.{ FactionDestroyedResultType, FactionLeaderRemovedResultType, @@ -25,10 +21,7 @@ import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.HeroT import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.Traveler import net.eagle0.eagle.model.state.Army @@ -95,10 +88,11 @@ case class CheckForFactionChangesAction( case (faction: FactionC, fr) => applyRemovedFactionResult(faction, fr) } - .continue { case (results, fr) => - maybeRansomInvalidResults(notDestroyed, fr).map { rirs => - results ++ rirs - } + .continue { + case (results, fr) => + maybeRansomInvalidResults(notDestroyed, fr).map { rirs => + results ++ rirs + } } .map { results => results ++ @@ -114,15 +108,15 @@ case class CheckForFactionChangesAction( functionalRandom: FunctionalRandom ): RandomState[Vector[ReturningHeroes.ReturningResult]] = functionalRandom - .nextMap(destroyedFaction.incomingDiplomacyOffers) { case (offer, fr) => - ReturningHeroes.heroesReturningToFaction( - hids = Vector(offer.messengerHeroId), - factionId = offer.originatingFactionId, - originProvince = - provinces.find(_.id == offer.messengerOriginProvinceId).get, - provinces = provinces, - functionalRandom = fr - ) + .nextMap(destroyedFaction.incomingDiplomacyOffers) { + case (offer, fr) => + ReturningHeroes.heroesReturningToFaction( + hids = Vector(offer.messengerHeroId), + factionId = offer.originatingFactionId, + originProvince = provinces.find(_.id == offer.messengerOriginProvinceId).get, + provinces = provinces, + functionalRandom = fr + ) } private def applyRemovedFactionResult( @@ -140,13 +134,14 @@ case class CheckForFactionChangesAction( provinceId = p.id, removedIncomingArmyIds = removedFactionArmies.map(_.id) ) - ) { case (cp, ma) => - cp.withNewUnaffiliatedHeroes( - armyToUnaffiliatedHeroes(ma.army) - ).copy( - foodDelta = deltaAugment(cp.foodDelta, ma.supplies.food), - goldDelta = deltaAugment(cp.goldDelta, ma.supplies.gold) - ) + ) { + case (cp, ma) => + cp.withNewUnaffiliatedHeroes( + armyToUnaffiliatedHeroes(ma.army) + ).copy( + foodDelta = deltaAugment(cp.foodDelta, ma.supplies.food), + goldDelta = deltaAugment(cp.goldDelta, ma.supplies.gold) + ) } ) @@ -193,9 +188,7 @@ case class CheckForFactionChangesAction( ): Option[ChangedFactionC] = Option.when( faction.factionRelationships.exists(_.targetFactionId == otherFid) - || faction.incomingDiplomacyOffers.exists(ioff => - ioff.originatingFactionId == otherFid - ) + || faction.incomingDiplomacyOffers.exists(ioff => ioff.originatingFactionId == otherFid) )( ChangedFactionC( factionId = faction.id, @@ -272,32 +265,30 @@ case class CheckForFactionChangesAction( functionalRandom: FunctionalRandom ): RandomState[Vector[ActionResultT]] = functionalRandom - .nextFlatMap(notDestroyedFactions.toVector) { case (faction, fr) => - fr.nextMap( - faction.incomingDiplomacyOffers - .collect { case diploOffer: RansomOffer => - diploOffer + .nextFlatMap(notDestroyedFactions.toVector) { + case (faction, fr) => + fr.nextMap( + faction.incomingDiplomacyOffers.collect { + case diploOffer: RansomOffer => + diploOffer } - .filterNot(ransomOffer => - RansomValidity.isStillValid(ransomOffer, provinces) - ) - ) { case (ransomOffer, innerFr) => - // Ransom offers don't remove the hero from the province - RandomState( - newValue = ActionResultC( - actionResultType = RansomInvalidatedResultType, - changedFactions = Vector( - ChangedFactionC( - factionId = faction.id, - removedIncomingDiplomacyOfferFactionIds = - Vector(ransomOffer.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(ransomOffer.withStatus(Invalidated)) - ) + .filterNot(ransomOffer => RansomValidity.isStillValid(ransomOffer, provinces)) + ) { + case (ransomOffer, innerFr) => + // Ransom offers don't remove the hero from the province + RandomState( + newValue = ActionResultC( + actionResultType = RansomInvalidatedResultType, + changedFactions = Vector( + ChangedFactionC( + factionId = faction.id, + removedIncomingDiplomacyOfferFactionIds = Vector(ransomOffer.originatingFactionId), + newIncomingDiplomacyOffers = Vector(ransomOffer.withStatus(Invalidated)) + ) + ) + ), + nextRandom = innerFr ) - ), - nextRandom = innerFr - ) - } + } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsAction.scala index 220e34cd7b..c185926079 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsAction.scala @@ -54,10 +54,9 @@ case class CheckForFailedQuestsAction( // check for the province being owned by a different faction else if imprisonedProvince.rulingFactionId != questFactionId then true // check for the hero being no longer a prisoner in the province - else if !imprisonedProvince.unaffiliatedHeroes - .exists { uh => - uh.heroId == prisonerHeroId && uh.unaffiliatedHeroType == Prisoner - } + else if !imprisonedProvince.unaffiliatedHeroes.exists { uh => + uh.heroId == prisonerHeroId && uh.unaffiliatedHeroType == Prisoner + } then true else false } @@ -67,7 +66,7 @@ case class CheckForFailedQuestsAction( province: ProvinceT ): Boolean = quest match { - case DefeatFactionQuest(targetFactionId) => + case DefeatFactionQuest(targetFactionId) => // Fails if the faction no longer exists, or if the ruling faction of this province has a truce with it !factions.exists(_.id == targetFactionId) || province.rulingFactionId .exists(rulingFid => @@ -78,13 +77,13 @@ case class CheckForFailedQuestsAction( factions = factions ) ) - case TruceWithFactionQuest(targetFactionId) => + case TruceWithFactionQuest(targetFactionId) => // Fails if the faction no longer exists !factions.exists(_.id == targetFactionId) - case TruceCountQuest(truceCount) => + case TruceCountQuest(truceCount) => // Fails if there are no longer enough factions to succeed factions.size <= truceCount - case DismissSpecificVassalQuest(targetHeroId) => + case DismissSpecificVassalQuest(targetHeroId) => // Fails if you swear brotherhood with the hero FactionUtils.isFactionLeader(targetHeroId, factions) case ExecutePrisonerQuest(prisonerHeroId, prisonerProvinceId) => @@ -93,7 +92,7 @@ case class CheckForFailedQuestsAction( prisonerHeroId = prisonerHeroId, prisonerProvinceId = prisonerProvinceId ) - case ExilePrisonerQuest(prisonerHeroId, prisonerProvinceId) => + case ExilePrisonerQuest(prisonerHeroId, prisonerProvinceId) => isPrisonerManagementQuestFailed( questFactionId = province.rulingFactionId, prisonerHeroId = prisonerHeroId, @@ -117,7 +116,7 @@ case class CheckForFailedQuestsAction( prisonerHeroId = prisonerHeroId, prisonerProvinceId = prisonerProvinceId ) - case _ => false + case _ => false } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsAction.scala index b7aec4f2dc..ffff0eb10e 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsAction.scala @@ -1,29 +1,16 @@ package net.eagle0.eagle.library.actions.impl.action -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.common.battalion_type.BattalionType import net.eagle0.eagle.library.actions.impl.common.ProtolessSequentialResultsAction -import net.eagle0.eagle.library.settings.{ - MinSupportForTaxes, - PortionOfCapacityForUpgradeBattalionQuest -} +import net.eagle0.eagle.library.settings.{MinSupportForTaxes, PortionOfCapacityForUpgradeBattalionQuest} import net.eagle0.eagle.library.util.province.ProvinceUtils import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentUtils import net.eagle0.eagle.library.util.BattalionTypeFinder import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{ - Ally, - Hostile -} +import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{Ally, Hostile} import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.HeroT import net.eagle0.eagle.model.state.province.ProvinceT @@ -93,24 +80,24 @@ case class CheckForFulfilledQuestsAction( province: ProvinceT ): Boolean = quest match { - case q: ComponentQuest => + case q: ComponentQuest => q.componentsFulfilled >= q.componentCount - case _: DefeatFactionQuest => + case _: DefeatFactionQuest => false // action quests - case DismissSpecificVassalQuest(targetHeroId) => + case DismissSpecificVassalQuest(targetHeroId) => !getHero(targetHeroId).exists( _.factionId .contains(province.rulingFactionId.get) ) - case _: ExecutePrisonerQuest => + case _: ExecutePrisonerQuest => false // action quests - case _: ExilePrisonerQuest => + case _: ExilePrisonerQuest => false // action quests - case _: ReleasePrisonerQuest => + case _: ReleasePrisonerQuest => false // action quests case ImproveAgricultureQuest(_: ProvinceId, desiredValue: Double) => ProvinceUtils.effectiveAgriculture(province) >= desiredValue - case ImproveEconomyQuest(_: ProvinceId, desiredValue: Double) => + case ImproveEconomyQuest(_: ProvinceId, desiredValue: Double) => ProvinceUtils.effectiveEconomy(province) >= desiredValue case ImproveInfrastructureQuest( _: ProvinceId, @@ -133,7 +120,7 @@ case class CheckForFulfilledQuestsAction( battalionTypeId ).capacity ) - case GrandArmyQuest(totalTroopCount) => + case GrandArmyQuest(totalTroopCount) => province.battalionIds .flatMap(battalionWithId) .map(_.size) @@ -147,21 +134,19 @@ case class CheckForFulfilledQuestsAction( expansionProvince.rulingFactionId == province.rulingFactionId && expansionProvince.support >= MinSupportForTaxes.doubleValue } - case WealthQuest(gold, food) => + case WealthQuest(gold, food) => province.gold >= gold && province.food >= food - case AllianceQuest => + case AllianceQuest => factionWithId(province.getRulingFactionId).get.factionRelationships .exists(fr => fr.relationshipLevel == Ally) case TruceWithFactionQuest(targetFactionId) => factionWithId(province.getRulingFactionId).get.factionRelationships - .exists(fr => - fr.targetFactionId == targetFactionId && fr.relationshipLevel != Hostile - ) - case TruceCountQuest(truceCount) => + .exists(fr => fr.targetFactionId == targetFactionId && fr.relationshipLevel != Hostile) + case TruceCountQuest(truceCount) => factionWithId(province.getRulingFactionId).get.factionRelationships .count(_.relationshipLevel != Hostile) >= truceCount - case _ => + case _ => throw new IllegalArgumentException(s"Unknown quest type: $quest") } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ChronicleEventGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ChronicleEventGenerator.scala index 548234d22c..ed9828d2e8 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ChronicleEventGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ChronicleEventGenerator.scala @@ -357,13 +357,13 @@ object ChronicleEventGenerator { factionId = factionId, provinceId = provinceId, reason = reason match { - case SHATTERED_ARMY_REASON_BLIZZARD => + case SHATTERED_ARMY_REASON_BLIZZARD => SHATTERED_ARMY_EVENT_REASON_BLIZZARD case SHATTERED_ARMY_REASON_UNKNOWN_UNSPECIFIED => SHATTERED_ARMY_EVENT_REASON_UNKNOWN_UNSPECIFIED - case SHATTERED_ARMY_REASON_WITHDRAW => + case SHATTERED_ARMY_REASON_WITHDRAW => SHATTERED_ARMY_EVENT_REASON_WITHDRAW - case Unrecognized(value) => + case Unrecognized(value) => ShatteredArmyEvent.Reason.Unrecognized(value) } ) @@ -407,9 +407,8 @@ object ChronicleEventGenerator { def eventTextEntries( gameHistory: GameHistory, since: Date - ): Vector[EventForChronicle] = { + ): Vector[EventForChronicle] = gameHistory.sinceDate(since).flatMap { (awrs: ActionWithResultingState) => notificationEntries(awrs) ++ basicActionResultEntries(awrs) } - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseAction.scala index 6f6fcaeda7..2a504d2914 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseAction.scala @@ -43,18 +43,19 @@ case class EndAttackDecisionPhaseAction( } private val incomingAttacks = for { - province <- provinces + province <- provinces defendingFactionId <- province.rulingFactionId.toVector - attackingArmy <- province.hostileArmies + attackingArmy <- province.hostileArmies } yield (defendingFactionId, attackingArmy.factionId) private def isFailedTruceQuest(q: QuestT, p: ProvinceT): Boolean = q match { case TruceWithFactionQuest(targetFactionId) => - incomingAttacks.exists { case (defendingFid, attackingFid) => - defendingFid == targetFactionId && p.rulingFactionId.contains( - attackingFid - ) + incomingAttacks.exists { + case (defendingFid, attackingFid) => + defendingFid == targetFactionId && p.rulingFactionId.contains( + attackingFid + ) } case _ => false diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseAction.scala index beaea1c0ae..9d8043fd1c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseAction.scala @@ -26,10 +26,7 @@ import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.actions.applier.ActionResultTApplier import net.eagle0.eagle.library.actions.generated_text_request_generators.captured_hero_helpers.CapturedHeroPleaGenerator import net.eagle0.eagle.library.actions.impl.action.EndBattleAftermathPhaseAction.RevelationChange -import net.eagle0.eagle.library.actions.impl.common.{ - ProtolessRandomSequentialResultsAction, - RandomStateTSequencer -} +import net.eagle0.eagle.library.actions.impl.common.{ProtolessRandomSequentialResultsAction, RandomStateTSequencer} import net.eagle0.eagle.library.settings.{ FactionBiasAgainstFormerOnExile, FactionBiasFromExile, @@ -41,22 +38,10 @@ import net.eagle0.eagle.library.util.unaffiliated_hero.LegacyUnaffiliatedHeroUti import net.eagle0.eagle.library.util.view_filters.ProvinceViewFilter import net.eagle0.eagle.library.util.EagleRequire.internalRequire import net.eagle0.eagle.library.EagleInternalException -import net.eagle0.eagle.model.action_result.{ - ActionResultT, - NotificationDetails, - NotificationT -} +import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - NotificationC -} -import net.eagle0.eagle.model.action_result.types.{ - CapturedHeroResolvedResultType, - EndAftermathPhaseResultType -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, NotificationC} +import net.eagle0.eagle.model.action_result.types.{CapturedHeroResolvedResultType, EndAftermathPhaseResultType} import net.eagle0.eagle.model.proto_converters.{ BattleRevelationConverter, NotificationConverter, @@ -74,11 +59,7 @@ import net.eagle0.eagle.model.state.hero.{ CapturedHeroReturnedBackstoryEvent, EventForHeroBackstoryT } -import net.eagle0.eagle.model.state.BattleRevelationType.{ - DidBattle, - Unknown, - Withdrew -} +import net.eagle0.eagle.model.state.BattleRevelationType.{DidBattle, Unknown, Withdrew} object EndBattleAftermathPhaseAction { case class RevelationChange( @@ -112,15 +93,13 @@ object EndBattleAftermathPhaseAction { `type` = uhType, lastFaction = gameState.heroes(capturedHeroId).factionId, factionBiases = ( - newFactionBias.map(b => actingFactionId -> b) ++ oldFactionBias.map( - b => capturedHeroFactionId -> b - ) + newFactionBias.map(b => actingFactionId -> b) ++ oldFactionBias.map(b => capturedHeroFactionId -> b) ).toMap ), hero = gameState.heroes(capturedHeroId), functionalRandom = functionalRandom ) - .map { UnaffiliatedHeroConverter.fromProto } + .map(UnaffiliatedHeroConverter.fromProto) .map { uh => ActionResultC( actionResultType = CapturedHeroResolvedResultType, @@ -129,8 +108,7 @@ object EndBattleAftermathPhaseAction { changedHeroes = Vector( ChangedHeroC( heroId = capturedHeroId, - newEventsForHeroBackstory = - Vector(newEventForHeroBackstoryDetails) + newEventsForHeroBackstory = Vector(newEventForHeroBackstoryDetails) ) ), changedProvinces = Vector( @@ -274,13 +252,12 @@ object EndBattleAftermathPhaseAction { oldFactionBias = None, gameState = gameState, functionalRandom = functionalRandom, - newEventForHeroBackstoryDetails = - CapturedHeroImprisonedBackstoryEvent( - date = DateConverter.fromProto(gameState.currentDate), - capturingFactionId = imprisoningFactionId, - capturingHeroId = imprisoningHeroId, - provinceId = provinceId - ) + newEventForHeroBackstoryDetails = CapturedHeroImprisonedBackstoryEvent( + date = DateConverter.fromProto(gameState.currentDate), + capturingFactionId = imprisoningFactionId, + capturingHeroId = imprisoningHeroId, + provinceId = provinceId + ) ).map { ar => ar.withNewGeneratedTextRequest(notificationLlmRequest) .withNotification( @@ -352,8 +329,7 @@ object EndBattleAftermathPhaseAction { factions = allFactionTs ) .copy( - relationshipLevel = - FactionRelationship.RelationshipLevel.Truce, + relationshipLevel = FactionRelationship.RelationshipLevel.Truce, resetDate = Some(truceEndDate) ) ) @@ -368,8 +344,7 @@ object EndBattleAftermathPhaseAction { factions = allFactionTs ) .copy( - relationshipLevel = - FactionRelationship.RelationshipLevel.Truce, + relationshipLevel = FactionRelationship.RelationshipLevel.Truce, resetDate = Some(truceEndDate) ) ) @@ -394,9 +369,8 @@ object EndBattleAftermathPhaseAction { throw new EagleInternalException("Empty deferred change") // the rest are not for this phase - case _: EpidemicStarted | _: DroughtStarted | _: DroughtEnded | - _: PrisonerMoved | _: PrisonerReturned | _: BlizzardStarted | - _: BlizzardEnded => + case _: EpidemicStarted | _: DroughtStarted | _: DroughtEnded | _: PrisonerMoved | _: PrisonerReturned | + _: BlizzardStarted | _: BlizzardEnded => throw new EagleInternalException( "Event should not be present in EndBattleAftermathPhaseAction" ) @@ -412,9 +386,9 @@ case class EndBattleAftermathPhaseAction( ): RevelationChange = RevelationChange( changedFaction = battleRevelation.revelationType match { - case Unknown => + case Unknown => throw new EagleInternalException("UNKNOWN revelation type") - case Withdrew => + case Withdrew => ChangedFactionC( factionId = battleRevelation.revealedToFactionId, updatedReconnedProvinces = Vector( @@ -450,7 +424,7 @@ case class EndBattleAftermathPhaseAction( def revelationChanges(gs: GameState): Vector[RevelationChange] = for { - province <- gs.provinces.values.toVector + province <- gs.provinces.values.toVector revelation <- province.battleRevelations if gs.factions.contains(revelation.revealedToFactionId) } yield revelationChange(BattleRevelationConverter.fromProto(revelation)) @@ -466,9 +440,7 @@ case class EndBattleAftermathPhaseAction( functionalRandom = functionalRandom ) .foldIn( - EndBattleAftermathPhaseAction.allDeferredChanges(gameState = - initialState - ) + EndBattleAftermathPhaseAction.allDeferredChanges(gameState = initialState) )( EndBattleAftermathPhaseAction.deferredChangeAR ) @@ -495,37 +467,30 @@ case class EndBattleAftermathPhaseAction( .withRandomActionResults((gs, fr) => CheckForFactionChangesAction( gameId = gs.gameId, - factions = - gs.factions.values.toVector.map(FactionConverter.fromProto), - provinces = - gs.provinces.values.toVector.map(ProvinceConverter.fromProto), + factions = gs.factions.values.toVector.map(FactionConverter.fromProto), + provinces = gs.provinces.values.toVector.map(ProvinceConverter.fromProto), heroes = gs.heroes.values.toVector.map(HeroConverter.fromProto), killedHeroIds = gs.killedHeroes.keys.toVector ).randomResults(fr) ) - .withProtolessSequentialResultsAction(gs => - HeroBackstoryUpdateActionGenerator.fromGameState(gs) - ) - .withRandomActionResult { case (gs, fr) => - RandomState( - ActionResultC( - actionResultType = EndAftermathPhaseResultType, - changedFactions = revelationChanges(gs).map(_.changedFaction), - changedProvinces = revelationChanges(gs).map(_.changedProvince), - newRoundPhase = Some(RoundPhase.DiplomacyResolution), - removedNotifications = gs.deferredNotifications - .map(note => - NotificationConverter.fromProto(note, deferred = true) - ) - .toVector, - newNotifications = gs.deferredNotifications - .map(note => - NotificationConverter.fromProto(note, deferred = false) - ) - .toVector - ), - fr - ) + .withProtolessSequentialResultsAction(gs => HeroBackstoryUpdateActionGenerator.fromGameState(gs)) + .withRandomActionResult { + case (gs, fr) => + RandomState( + ActionResultC( + actionResultType = EndAftermathPhaseResultType, + changedFactions = revelationChanges(gs).map(_.changedFaction), + changedProvinces = revelationChanges(gs).map(_.changedProvince), + newRoundPhase = Some(RoundPhase.DiplomacyResolution), + removedNotifications = gs.deferredNotifications + .map(note => NotificationConverter.fromProto(note, deferred = true)) + .toVector, + newNotifications = gs.deferredNotifications + .map(note => NotificationConverter.fromProto(note, deferred = false)) + .toVector + ), + fr + ) } .actionResults } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleRequestPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleRequestPhaseAction.scala index b4c62460d8..d87f8f0180 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleRequestPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleRequestPhaseAction.scala @@ -9,12 +9,12 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.impl.common.DeterministicSingleResultAction import net.eagle0.eagle.library.util.EagleRequire.internalRequire -case class EndBattleRequestPhaseAction(gameState: GameState) - extends DeterministicSingleResultAction(gameState) { +case class EndBattleRequestPhaseAction(gameState: GameState) extends DeterministicSingleResultAction(gameState) { override def immediateExecute: ActionResult = { internalRequire( - gameState.provinces.forall { case (_, province) => - province.hostileArmies.isEmpty + gameState.provinces.forall { + case (_, province) => + province.hostileArmies.isEmpty }, s"Province ${gameState.provinces.find(_._2.hostileArmies.nonEmpty).get._2.name} still has attacking armies!" ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleResolutionPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleResolutionPhaseAction.scala index a4e900a087..38234b7478 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleResolutionPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleResolutionPhaseAction.scala @@ -7,8 +7,7 @@ import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.impl.common.DeterministicSingleResultAction -case class EndBattleResolutionPhaseAction(gameState: GameState) - extends DeterministicSingleResultAction(gameState) { +case class EndBattleResolutionPhaseAction(gameState: GameState) extends DeterministicSingleResultAction(gameState) { override def immediateExecute: ActionResult = ActionResult( `type` = END_RESOLUTION_PHASE, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseAction.scala index 3af00c81de..cfa27334f0 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseAction.scala @@ -30,21 +30,19 @@ case class EndDefenseDecisionPhaseAction( ) val attackerCps = for { - ag <- tributePaidArmies + ag <- tributePaidArmies army <- ag.armies - } yield { - ChangedProvince( - id = army.originProvince, - addedIncomingArmies = Vector( - army.update( - _.destinationProvince := army.originProvince, - _.originProvince := payingProvince.id, - _.army.optionalFleeProvinceId := None, - _.arrivalRound := gameState.currentRoundId + 1 - ) + } yield ChangedProvince( + id = army.originProvince, + addedIncomingArmies = Vector( + army.update( + _.destinationProvince := army.originProvince, + _.originProvince := payingProvince.id, + _.army.optionalFleeProvinceId := None, + _.arrivalRound := gameState.currentRoundId + 1 ) ) - } + ) if attackerCps.isEmpty then Vector.empty else diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseAction.scala index 341b427f31..6744cbd4b2 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseAction.scala @@ -10,47 +10,23 @@ import net.eagle0.eagle.library.actions.impl.action.diplomacy_helpers.{ RansomResolutionHelpers, TruceResolutionHelpers } -import net.eagle0.eagle.library.actions.impl.common.{ - ProtolessRandomSequentialResultsAction, - RandomStateTSequencer -} +import net.eagle0.eagle.library.actions.impl.common.{ProtolessRandomSequentialResultsAction, RandomStateTSequencer} import net.eagle0.eagle.library.util.faction_utils.FactionUtils import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.util.ransom_validity.RansomValidity import net.eagle0.eagle.library.EagleInternalException -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC -} -import net.eagle0.eagle.model.action_result.types.{ - EndDiplomacyResolutionPhaseResultType, - RansomInvalidatedResultType -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC} +import net.eagle0.eagle.model.action_result.types.{EndDiplomacyResolutionPhaseResultType, RansomInvalidatedResultType} import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.proto_converters.{ - BattalionConverter, - NotificationConverter -} +import net.eagle0.eagle.model.proto_converters.{BattalionConverter, NotificationConverter} import net.eagle0.eagle.model.proto_converters.date.DateConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.hero.HeroConverter import net.eagle0.eagle.model.proto_converters.province.ProvinceConverter import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.{ - AllianceOffer, - BreakAlliance, - Invitation, - RansomOffer, - TruceOffer -} -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Invalidated, - Rejected, - Unresolved -} +import net.eagle0.eagle.model.state.diplomacy_offer.{AllianceOffer, BreakAlliance, Invitation, RansomOffer, TruceOffer} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Invalidated, Rejected, Unresolved} import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.HeroT import net.eagle0.eagle.model.state.province.ProvinceT @@ -120,58 +96,50 @@ case class EndDiplomacyResolutionPhaseAction( } -/** Companion object for EndDiplomacyResolutionPhaseAction containing helper - * methods. - * - * IMPORTANT: This is intentionally named differently from the case class to - * avoid Scala naming conflicts that prevent the class from being imported in - * other packages. When a case class and its companion object share the same - * name, the compiler can become confused about which one is being referenced - * during imports. - * - * All helper methods take explicit parameters for game state components to - * ensure they always operate on the current state as provided by - * RandomStateTSequencer, preventing use of stale data from the initial game - * state. - */ +/** + * Companion object for EndDiplomacyResolutionPhaseAction containing helper methods. + * + * IMPORTANT: This is intentionally named differently from the case class to avoid Scala naming conflicts that prevent + * the class from being imported in other packages. When a case class and its companion object share the same name, the + * compiler can become confused about which one is being referenced during imports. + * + * All helper methods take explicit parameters for game state components to ensure they always operate on the current + * state as provided by RandomStateTSequencer, preventing use of stale data from the initial game state. + */ private object EndDiplomacyResolutionPhaseActionHelpers { // Methods that use the updated game state from the sequencer def invalidationResultsForState( currentGameState: GameState ): Vector[ActionResultT] = { - val factions = + val factions = currentGameState.factions.values.map(FactionConverter.fromProto).toVector val provinces = currentGameState.provinces.values .map(ProvinceConverter.fromProto) .toVector for { - faction <- factions + faction <- factions diploOffer <- faction.incomingDiplomacyOffers.filter( - _.status == Unresolved - ) - } yield { - diploOffer match { - case ro: RansomOffer - if !RansomValidity.isStillValid(diploOffer, provinces) => - ActionResultC( - actionResultType = RansomInvalidatedResultType, - changedFactions = Vector( - ChangedFactionC( - factionId = faction.id, - removedIncomingDiplomacyOfferFactionIds = - Vector(ro.originatingFactionId), - newIncomingDiplomacyOffers = Vector(ro.withStatus(Invalidated)) - ) + _.status == Unresolved + ) + } yield diploOffer match { + case ro: RansomOffer if !RansomValidity.isStillValid(diploOffer, provinces) => + ActionResultC( + actionResultType = RansomInvalidatedResultType, + changedFactions = Vector( + ChangedFactionC( + factionId = faction.id, + removedIncomingDiplomacyOfferFactionIds = Vector(ro.originatingFactionId), + newIncomingDiplomacyOffers = Vector(ro.withStatus(Invalidated)) ) ) - case _ => - // This shouldn't be possible - throw new EagleInternalException( - s"Unresolved offer $diploOffer should not still be possible" - ) - } + ) + case _ => + // This shouldn't be possible + throw new EagleInternalException( + s"Unresolved offer $diploOffer should not still be possible" + ) } } @@ -198,7 +166,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { resolver: A => Vector[ActionResultT] )(factions: Vector[FactionT]): Vector[ActionResultT] = (for { - faction <- factions + faction <- factions outgoingDiplo <- getter(faction) } yield resolver(outgoingDiplo)).flatten @@ -207,10 +175,12 @@ private object EndDiplomacyResolutionPhaseActionHelpers { resolver: (A, FunctionalRandom) => RandomState[Vector[ActionResultT]], functionalRandom: FunctionalRandom )(factions: Vector[FactionT]): RandomState[Vector[ActionResultT]] = - functionalRandom.nextFlatMap(factions) { case (faction, fr) => - fr.nextMap(getter(faction)) { case (outgoingDiplo, innerFr) => - resolver(outgoingDiplo, innerFr) - }.map(_.flatten) + functionalRandom.nextFlatMap(factions) { + case (faction, fr) => + fr.nextMap(getter(faction)) { + case (outgoingDiplo, innerFr) => + resolver(outgoingDiplo, innerFr) + }.map(_.flatten) } def truceResolutionsForState( @@ -221,7 +191,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { randomResolutionsForType( _.incomingDiplomacyOffers.collect { case to: TruceOffer => to }, (to: TruceOffer, fr: FunctionalRandom) => { - val provinces = currentGameState.provinces.values + val provinces = currentGameState.provinces.values .map(ProvinceConverter.fromProto) .toVector val currentDate = DateConverter.fromProto(currentGameState.currentDate) @@ -246,10 +216,10 @@ private object EndDiplomacyResolutionPhaseActionHelpers { randomResolutionsForType( _.incomingDiplomacyOffers.collect { case ao: AllianceOffer => ao }, (ao: AllianceOffer, fr: FunctionalRandom) => { - val provinces = currentGameState.provinces.values + val provinces = currentGameState.provinces.values .map(ProvinceConverter.fromProto) .toVector - val heroes = + val heroes = currentGameState.heroes.values.map(HeroConverter.fromProto).toVector val currentDate = DateConverter.fromProto(currentGameState.currentDate) resultsForAllianceOffer( @@ -273,7 +243,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { randomResolutionsForType( _.incomingDiplomacyOffers.collect { case ba: BreakAlliance => ba }, (ba: BreakAlliance, fr: FunctionalRandom) => { - val provinces = currentGameState.provinces.values + val provinces = currentGameState.provinces.values .map(ProvinceConverter.fromProto) .toVector val currentDate = DateConverter.fromProto(currentGameState.currentDate) @@ -291,10 +261,10 @@ private object EndDiplomacyResolutionPhaseActionHelpers { randomResolutionsForType( _.incomingDiplomacyOffers.collect { case id: Invitation => id }, (id: Invitation, fr: FunctionalRandom) => { - val provinces = currentGameState.provinces.values + val provinces = currentGameState.provinces.values .map(ProvinceConverter.fromProto) .toVector - val battalions = currentGameState.battalions.values + val battalions = currentGameState.battalions.values .map(BattalionConverter.fromProto) .toVector val currentDate = DateConverter.fromProto(currentGameState.currentDate) @@ -337,7 +307,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { provinces: Vector[ProvinceT], gameState: GameState ): Vector[ActionResultT] = ransomOffer.status match { - case Accepted => + case Accepted => RansomResolutionHelpers.acceptedRansomResults( ransomOffer, currentDate, @@ -346,19 +316,18 @@ private object EndDiplomacyResolutionPhaseActionHelpers { gameId = gameState.gameId, currentDate = currentDate, currentRoundId = gameState.currentRoundId, - previousBackstoryTextIdLookup = - hid => gameState.heroes(hid).backstoryVersions.toVector.last.textId + previousBackstoryTextIdLookup = hid => gameState.heroes(hid).backstoryVersions.toVector.last.textId ) ) - case Rejected => + case Rejected => Vector( RansomResolutionHelpers.rejectedRansomResult(ransomOffer) ) - case Unresolved => + case Unresolved => throw new EagleInternalException( "UNRESOLVED ransom offer at the end of the round" ) - case Imprisoned => + case Imprisoned => throw new EagleInternalException( s"IMPRISONED is not valid for a ransom offer" ) @@ -377,7 +346,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { gameState: GameState ): RandomState[Vector[ActionResultT]] = truceOffer.status match { - case Accepted => + case Accepted => TruceResolutionHelpers .acceptedTruceResult( truceOffer = truceOffer, @@ -387,7 +356,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { functionalRandom = functionalRandom ) .map(Vector(_)) - case Rejected => + case Rejected => TruceResolutionHelpers .rejectedTruceResults( truceOffer = truceOffer, @@ -396,7 +365,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { eagleGameId = gameState.gameId, functionalRandom = functionalRandom ) - case Imprisoned => + case Imprisoned => RandomState( TruceResolutionHelpers.imprisonedAmbassadorResults( truceOffer = truceOffer, @@ -416,7 +385,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { eagleGameId = gameState.gameId, functionalRandom = functionalRandom ) - case Unresolved => + case Unresolved => throw new EagleInternalException( "UNRESOLVED truce offer at the end of the round" ) @@ -429,9 +398,9 @@ private object EndDiplomacyResolutionPhaseActionHelpers { factions: Vector[FactionT], heroes: Vector[HeroT], currentDate: Date - ): RandomState[Vector[ActionResultT]] = { + ): RandomState[Vector[ActionResultT]] = allianceOffer.status match { - case Accepted => + case Accepted => AllianceResolutionHelpers .acceptedAllianceResult( allianceOffer = allianceOffer, @@ -441,7 +410,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { factions = factions, functionalRandom = functionalRandom ) - case Rejected => + case Rejected => AllianceResolutionHelpers .rejectedAllianceResult( allianceOffer = allianceOffer, @@ -450,7 +419,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { functionalRandom = functionalRandom ) .map(Vector(_)) - case Imprisoned => + case Imprisoned => RandomState( AllianceResolutionHelpers .imprisonedAmbassadorResult( @@ -469,12 +438,11 @@ private object EndDiplomacyResolutionPhaseActionHelpers { functionalRandom = functionalRandom ) .map(Vector(_)) - case Unresolved => + case Unresolved => throw new EagleInternalException( "UNRESOLVED alliance offer at the end of the round" ) } - } private def resultsForBreakAlliance( breakAllianceOffer: BreakAlliance, @@ -482,9 +450,9 @@ private object EndDiplomacyResolutionPhaseActionHelpers { provinces: Vector[ProvinceT], factions: Vector[FactionT], currentDate: Date - ): RandomState[Vector[ActionResultT]] = { + ): RandomState[Vector[ActionResultT]] = breakAllianceOffer.status match { - case Accepted => + case Accepted => BreakAllianceResolutionHelpers .acceptedResult( breakAllianceOffer = breakAllianceOffer, @@ -494,7 +462,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { functionalRandom = functionalRandom ) .map(Vector(_)) - case Rejected => + case Rejected => // This one shouldn't be possible, but we'll resolve in the helper BreakAllianceResolutionHelpers .rejectedResult( @@ -502,7 +470,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { functionalRandom = functionalRandom ) .map(Vector(_)) - case Imprisoned => + case Imprisoned => RandomState( BreakAllianceResolutionHelpers .imprisonedAmbassadorResult( @@ -513,7 +481,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { ), functionalRandom ).map(Vector(_)) - case Unresolved => + case Unresolved => throw new EagleInternalException( "UNRESOLVED break alliance at the end of the round" ) @@ -526,7 +494,6 @@ private object EndDiplomacyResolutionPhaseActionHelpers { ) .map(Vector(_)) } - } private def resultsForInvitation( invitation: Invitation, @@ -536,7 +503,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { battalions: Vector[BattalionT], currentDate: Date ): RandomState[Vector[ActionResultT]] = invitation.status match { - case Accepted => + case Accepted => InvitationResolutionHelpers.acceptedInvitationResults( acceptedInvitation = invitation, currentDate = currentDate, @@ -545,7 +512,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { battalions = battalions, functionalRandom = functionalRandom ) - case Rejected => + case Rejected => InvitationResolutionHelpers .rejectedInvitationResult( rejectedInvitation = invitation, @@ -554,7 +521,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { functionalRandom = functionalRandom ) .map(Vector(_)) - case Imprisoned => + case Imprisoned => RandomState( Vector( InvitationResolutionHelpers.imprisonedAmbassadorResult( @@ -566,7 +533,7 @@ private object EndDiplomacyResolutionPhaseActionHelpers { ), functionalRandom ) - case Unresolved => + case Unresolved => throw new EagleInternalException( "UNRESOLVED invitation at the end of the round" ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllBattleRequestPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllBattleRequestPhaseAction.scala index 2c291d8a06..eaadabdcc0 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllBattleRequestPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllBattleRequestPhaseAction.scala @@ -12,7 +12,6 @@ case class EndFreeForAllBattleRequestPhaseAction(gameState: GameState) override def immediateExecute: ActionResult = ActionResult( `type` = END_FREE_FOR_ALL_BATTLE_REQUEST_PHASE, - newRoundPhase = - Some(NewRoundPhase(value = FREE_FOR_ALL_BATTLE_RESOLUTION)) + newRoundPhase = Some(NewRoundPhase(value = FREE_FOR_ALL_BATTLE_RESOLUTION)) ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllDecisionPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllDecisionPhaseAction.scala index 29d0748aee..a2eeb53107 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllDecisionPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndFreeForAllDecisionPhaseAction.scala @@ -8,8 +8,7 @@ import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.proto_converters.province.ProvinceConverter import net.eagle0.eagle.model.state.RoundPhase -case class EndFreeForAllDecisionPhaseAction(gameState: GameState) - extends ProtolessSequentialResultsAction { +case class EndFreeForAllDecisionPhaseAction(gameState: GameState) extends ProtolessSequentialResultsAction { override def results: Vector[ActionResultT] = WithdrawnArmiesReturnHomeAction( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseAction.scala index 424fed06a7..8412e7bd08 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseAction.scala @@ -9,14 +9,8 @@ import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.changed_province.ChangedProvince import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.command.{ - CommandFactory, - LegacyHandleRiotUtils -} -import net.eagle0.eagle.library.actions.impl.common.{ - RandomSequentialResultsAction, - RandomStateProtoSequencer -} +import net.eagle0.eagle.library.actions.impl.command.{CommandFactory, LegacyHandleRiotUtils} +import net.eagle0.eagle.library.actions.impl.common.{RandomSequentialResultsAction, RandomStateProtoSequencer} import net.eagle0.eagle.library.util.command_choice_helpers.CommandChoiceHelpers import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.model.proto_converters.game_state.GameStateConverter @@ -34,29 +28,31 @@ case class EndHandleRiotsPhaseAction( ars.lastStateProto.provinces.values .filter(LegacyProvinceUtils.hasImminentRiot) .filterNot(_.hasActed) - .foldLeft(ars) { case (sequencer, p) => - commandsForProvince(p.id).map { opac => - sequencer.withRandomAction { case (gs, fr) => - CommandChoiceHelpers - .handleRiotSelectedCommand( - actingFactionId = p.getRulingFactionId, - gameState = gs, - availableCommands = opac.commands.toVector, - functionalRandom = fr - ) - .map { optCS => - optCS.map { cs => - commandFactory - .makeCommand( - actingFactionId = p.getRulingFactionId, - gameState = GameStateConverter.fromProto(gs), - availableCommand = cs.available, - selectedCommand = cs.selected - ) - }.get - } - } - }.get + .foldLeft(ars) { + case (sequencer, p) => + commandsForProvince(p.id).map { opac => + sequencer.withRandomAction { + case (gs, fr) => + CommandChoiceHelpers + .handleRiotSelectedCommand( + actingFactionId = p.getRulingFactionId, + gameState = gs, + availableCommands = opac.commands.toVector, + functionalRandom = fr + ) + .map { optCS => + optCS.map { cs => + commandFactory + .makeCommand( + actingFactionId = p.getRulingFactionId, + gameState = GameStateConverter.fromProto(gs), + availableCommand = cs.available, + selectedCommand = cs.selected + ) + }.get + } + } + }.get } private def riotOccurredResults( @@ -64,14 +60,15 @@ case class EndHandleRiotsPhaseAction( ): RandomStateProtoSequencer = ars.lastStateProto.provinces.values .filter(LegacyProvinceUtils.hasImminentRiot) - .foldLeft(ars) { case (ars, p) => - ars.withActionResult(_ => - LegacyHandleRiotUtils - .riotOccurredAr( - p.getRulingFactionId, - ProvinceConverter.fromProto(p) - ) - ) + .foldLeft(ars) { + case (ars, p) => + ars.withActionResult(_ => + LegacyHandleRiotUtils + .riotOccurredAr( + p.getRulingFactionId, + ProvinceConverter.fromProto(p) + ) + ) } def endPhaseResult( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseAction.scala index 02a93b2f50..d9ce47ff94 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseAction.scala @@ -17,11 +17,7 @@ import net.eagle0.eagle.library.util.ProvinceEventUtils import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.changed_province.ChangedProvinceT -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC} import net.eagle0.eagle.model.action_result.types.{ EndPlayerCommandsPhaseResultType, EpidemicTookEffectResultType, @@ -30,27 +26,14 @@ import net.eagle0.eagle.model.action_result.types.{ WeatherTookEffectResultType } import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.proto_converters.{ - NotificationConverter, - UnaffiliatedHeroConverter -} +import net.eagle0.eagle.model.proto_converters.{NotificationConverter, UnaffiliatedHeroConverter} import net.eagle0.eagle.model.proto_converters.date.DateConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.hero.HeroConverter -import net.eagle0.eagle.model.proto_converters.province.{ - ProvinceConverter, - ProvinceEventConverter -} -import net.eagle0.eagle.model.state.province.{ - BlizzardEvent, - DroughtEvent, - EpidemicEvent -} +import net.eagle0.eagle.model.proto_converters.province.{ProvinceConverter, ProvinceEventConverter} +import net.eagle0.eagle.model.state.province.{BlizzardEvent, DroughtEvent, EpidemicEvent} import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Prisoner -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Prisoner} import net.eagle0.eagle.model.state.RoundPhase import net.eagle0.eagle.ProvinceId @@ -148,8 +131,7 @@ case class EndPlayerCommandsPhaseAction( actionResultType = PrisonerMoveTookEffectResultType, provinceId = Some(pid), actingFactionId = Some(prisonerReturned.fromFactionId), - affectedFactionIds = - Vector(prisonerReturned.fromFactionId, prisonerReturned.toFactionId), + affectedFactionIds = Vector(prisonerReturned.fromFactionId, prisonerReturned.toFactionId), changedHeroes = Vector( ChangedHeroC( heroId = prisonerReturned.heroId, @@ -181,13 +163,12 @@ case class EndPlayerCommandsPhaseAction( VigorXPApplier.withVigorXp( ActionResultC( actionResultType = deferredChange match { - case _: EpidemicStarted => EpidemicTookEffectResultType - case _: BlizzardEnded => WeatherTookEffectResultType - case _: BlizzardStarted => WeatherTookEffectResultType - case _: DroughtStarted => WeatherTookEffectResultType - case _: DroughtEnded => WeatherTookEffectResultType - case _: PrisonerMoved | _: PrisonerReturned | - _: CapturedHeroImprisoned | _: CapturedHeroExecuted | + case _: EpidemicStarted => EpidemicTookEffectResultType + case _: BlizzardEnded => WeatherTookEffectResultType + case _: BlizzardStarted => WeatherTookEffectResultType + case _: DroughtStarted => WeatherTookEffectResultType + case _: DroughtEnded => WeatherTookEffectResultType + case _: PrisonerMoved | _: PrisonerReturned | _: CapturedHeroImprisoned | _: CapturedHeroExecuted | _: CapturedHeroExiled | _: CapturedHeroReturned => throw new EagleInternalException( "Prisoner management changes should not be here" @@ -284,11 +265,11 @@ case class EndPlayerCommandsPhaseAction( fr: FunctionalRandom ): RandomState[ActionResultT] = deferredChange match { - case prisonerMoved: PrisonerMoved => + case prisonerMoved: PrisonerMoved => onePrisonerMovedChange(pid, prisonerMoved, gs, fr) case prisonerReturned: PrisonerReturned => onePrisonerReturnedChange(pid, prisonerReturned, gs, fr) - case _ => notPrisonerChange(pid, deferredChange, gs, fr) + case _ => notPrisonerChange(pid, deferredChange, gs, fr) } private def deferredProvinceChangesResultsForProvince( @@ -297,8 +278,9 @@ case class EndPlayerCommandsPhaseAction( ): RandomStateTSequencer = arsRS.lastStateProto.provinces(pid).deferredChanges.foldLeft(arsRS) { case (acc, dc) => - acc.withRandomActionResult { case (gs, fr) => - oneDeferredProvinceChange(pid, dc, gs, fr) + acc.withRandomActionResult { + case (gs, fr) => + oneDeferredProvinceChange(pid, dc, gs, fr) } } @@ -306,8 +288,9 @@ case class EndPlayerCommandsPhaseAction( ars: RandomStateTSequencer ): RandomStateTSequencer = ars.lastStateProto.provinces.keys - .foldLeft(ars) { case (newArs, pid) => - deferredProvinceChangesResultsForProvince(pid, newArs) + .foldLeft(ars) { + case (newArs, pid) => + deferredProvinceChangesResultsForProvince(pid, newArs) } override def randomResults( @@ -328,18 +311,14 @@ case class EndPlayerCommandsPhaseAction( .withRandomActionResults((gs, fr) => CheckForFactionChangesAction( gameId = gs.gameId, - factions = - gs.factions.values.toVector.map(FactionConverter.fromProto), - provinces = - gs.provinces.values.toVector.map(ProvinceConverter.fromProto), + factions = gs.factions.values.toVector.map(FactionConverter.fromProto), + provinces = gs.provinces.values.toVector.map(ProvinceConverter.fromProto), heroes = gs.heroes.values.toVector.map(HeroConverter.fromProto), killedHeroIds = gs.killedHeroes.keys.toVector ).randomResults(fr) ) .withContinuance(deferredProvinceChangesResults) - .withProtolessSequentialResultsAction(gs => - HeroBackstoryUpdateActionGenerator.fromGameState(gs) - ) + .withProtolessSequentialResultsAction(gs => HeroBackstoryUpdateActionGenerator.fromGameState(gs)) .withActionResult(endPhaseResult) .actionResults } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPleaseRecruitMePhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPleaseRecruitMePhaseAction.scala index 3c372ea45e..7610f56954 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPleaseRecruitMePhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndPleaseRecruitMePhaseAction.scala @@ -7,8 +7,7 @@ import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.impl.common.DeterministicSingleResultAction -case class EndPleaseRecruitMePhaseAction(gameState: GameState) - extends DeterministicSingleResultAction(gameState) { +case class EndPleaseRecruitMePhaseAction(gameState: GameState) extends DeterministicSingleResultAction(gameState) { override def immediateExecute: ActionResult = ActionResult( `type` = END_PLEASE_RECRUIT_ME_PHASE, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndUnaffiliatedHeroActionsPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndUnaffiliatedHeroActionsPhaseAction.scala index a25f825e10..10e9300a36 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndUnaffiliatedHeroActionsPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndUnaffiliatedHeroActionsPhaseAction.scala @@ -28,8 +28,8 @@ case class EndUnaffiliatedHeroActionsPhaseAction( private def heroRejoinResults: Vector[ActionResultT] = (for { province <- provinces.filter(_.rulingFactionId.isDefined) - uh <- province.unaffiliatedHeroes - .filter(_.unaffiliatedHeroType == Outlaw) + uh <- province.unaffiliatedHeroes + .filter(_.unaffiliatedHeroType == Outlaw) } yield UnaffiliatedHeroRejoinedAction.outlawRejoinResult( uh, province.id, @@ -38,45 +38,40 @@ case class EndUnaffiliatedHeroActionsPhaseAction( private def oneProvincePleaseRecruitMeRequests( province: ProvinceT - ): Vector[(LlmRequestT, UnaffiliatedHeroT)] = { - province.rulingFactionId - .map { fid => - val actingFaction = factions.find(_.id == fid).get - province.unaffiliatedHeroes - // Filter out outlaws that are going to rejoin the faction anyway - .filterNot(uh => - uh.unaffiliatedHeroType == Outlaw && uh.lastFactionId == province.rulingFactionId + ): Vector[(LlmRequestT, UnaffiliatedHeroT)] = + province.rulingFactionId.map { fid => + val actingFaction = factions.find(_.id == fid).get + province.unaffiliatedHeroes + // Filter out outlaws that are going to rejoin the faction anyway + .filterNot(uh => uh.unaffiliatedHeroType == Outlaw && uh.lastFactionId == province.rulingFactionId) + .filter(uh => + UnaffiliatedHeroUtils.willPleaseRecruitMe( + targetHero = heroes.find(_.id == uh.heroId).get, + unaffiliatedHero = uh, + actingFaction = actingFaction, + actingFactionLeader = heroes.find(_.id == actingFaction.factionHeadId).get, + allProvinces = provinces, + allFactions = factions, + currentDate = currentDate ) - .filter(uh => - UnaffiliatedHeroUtils.willPleaseRecruitMe( - targetHero = heroes.find(_.id == uh.heroId).get, - unaffiliatedHero = uh, - actingFaction = actingFaction, - actingFactionLeader = - heroes.find(_.id == actingFaction.factionHeadId).get, - allProvinces = provinces, - allFactions = factions, - currentDate = currentDate - ) + ) + .map { uh => + val textId = s"please recruit me $currentRoundId ${uh.heroId}" + ( + PleaseRecruitMeMessage( + requestId = textId, + eagleGameId = gameId, + recipientFactionIds = Vector(fid), + alwaysGenerate = false, + heroId = uh.heroId, + targetFactionId = fid, + provinceId = province.id + ), + uh.withPleaseRecruitMeTextId(textId) ) - .map { uh => - val textId = s"please recruit me $currentRoundId ${uh.heroId}" - ( - PleaseRecruitMeMessage( - requestId = textId, - eagleGameId = gameId, - recipientFactionIds = Vector(fid), - alwaysGenerate = false, - heroId = uh.heroId, - targetFactionId = fid, - provinceId = province.id - ), - uh.withPleaseRecruitMeTextId(textId) - ) - } - } + } + } .getOrElse(Vector()) - } override def results: Vector[ActionResultT] = { val cpsAndLlmRequests = provinces.map { p => diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndVassalCommandsPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndVassalCommandsPhaseAction.scala index 47487ded5a..78f7ea33df 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndVassalCommandsPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/EndVassalCommandsPhaseAction.scala @@ -7,22 +7,15 @@ import net.eagle0.eagle.common.round_phase.RoundPhase.PLAYER_COMMANDS import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - RandomSequentialResultsAction, - RandomStateProtoSequencer -} +import net.eagle0.eagle.library.actions.impl.common.{RandomSequentialResultsAction, RandomStateProtoSequencer} import net.eagle0.eagle.library.util.EagleRequire.internalRequire -import net.eagle0.eagle.model.proto_converters.{ - ActionResultProtoConverter, - BattalionConverter -} +import net.eagle0.eagle.model.proto_converters.{ActionResultProtoConverter, BattalionConverter} import net.eagle0.eagle.model.proto_converters.date.DateConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.hero.HeroConverter import net.eagle0.eagle.model.proto_converters.province.ProvinceConverter -case class EndVassalCommandsPhaseAction(gameState: GameState) - extends RandomSequentialResultsAction(gameState) { +case class EndVassalCommandsPhaseAction(gameState: GameState) extends RandomSequentialResultsAction(gameState) { override def randomResults( functionalRandom: FunctionalRandom, actionResultProtoApplier: ActionResultProtoApplier @@ -44,15 +37,12 @@ case class EndVassalCommandsPhaseAction(gameState: GameState) gameId = gs.gameId, currentDate = DateConverter.fromProto(gs.currentDate), currentRoundId = gs.currentRoundId, - provinces = - gs.provinces.values.map(ProvinceConverter.fromProto).toVector, + provinces = gs.provinces.values.map(ProvinceConverter.fromProto).toVector, factions = gs.factions.values .map(FactionConverter.fromProto) .toVector, - battalions = - gs.battalions.values.toVector.map(BattalionConverter.fromProto), - getHero = - hid => gameState.heroes.get(hid).map(HeroConverter.fromProto), + battalions = gs.battalions.values.toVector.map(BattalionConverter.fromProto), + getHero = hid => gameState.heroes.get(hid).map(HeroConverter.fromProto), battalionTypes = gs.battalionTypes.toVector, hid => gs.heroes(hid).backstoryVersions.last.textId ) @@ -62,8 +52,7 @@ case class EndVassalCommandsPhaseAction(gameState: GameState) gameId = gs.gameId, currentDate = DateConverter.fromProto(gs.currentDate), currentRoundId = gs.currentRoundId, - provinces = - gs.provinces.values.map(ProvinceConverter.fromProto).toVector, + provinces = gs.provinces.values.map(ProvinceConverter.fromProto).toVector, factions = gs.factions.values .map(FactionConverter.fromProto) .toVector, @@ -73,17 +62,13 @@ case class EndVassalCommandsPhaseAction(gameState: GameState) .withRandomActionResults((gs, fr) => CheckForFactionChangesAction( gameId = gs.gameId, - factions = - gs.factions.values.map(FactionConverter.fromProto).toVector, - provinces = - gs.provinces.values.map(ProvinceConverter.fromProto).toVector, + factions = gs.factions.values.map(FactionConverter.fromProto).toVector, + provinces = gs.provinces.values.map(ProvinceConverter.fromProto).toVector, heroes = gs.heroes.values.map(HeroConverter.fromProto).toVector, killedHeroIds = gs.killedHeroes.keys.toVector ).randomResults(fr).map(_.map(ActionResultProtoConverter.toProto)) ) - .withProtolessSequentialResultsAction(gs => - HeroBackstoryUpdateActionGenerator.fromGameState(gs) - ) + .withProtolessSequentialResultsAction(gs => HeroBackstoryUpdateActionGenerator.fromGameState(gs)) .withActionWithResultingState(gs => actionResultProtoApplier.applyActionResult( gs, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/FreeForAllDrawAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/FreeForAllDrawAction.scala index fa4f3c9eb8..2eb7d694fd 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/FreeForAllDrawAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/FreeForAllDrawAction.scala @@ -20,22 +20,22 @@ case class FreeForAllDrawAction( mas .groupBy(_.destinationProvinceId) - .map { case (pid, ms) => - ChangedProvinceC( - provinceId = pid, - newIncomingArmies = ms.toVector - ) + .map { + case (pid, ms) => + ChangedProvinceC( + provinceId = pid, + newIncomingArmies = ms.toVector + ) } .toVector } - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = ActionResultC( actionResultType = FreeForAllDrawResultType, provinceId = Some(defenderProvince), changedProvinces = changedProvincesFromRemainingUnits ) - } private def reversedMovingArmy(ma: MovingArmy): MovingArmy = ma.copy( @@ -43,9 +43,7 @@ case class FreeForAllDrawAction( destinationProvinceId = ma.destinationProvinceId, arrivalRound = ma.arrivalRound + 1, army = ma.army.copy( - units = ma.army.units.filter(cu => - remainingUnits.exists(_.hero.id == cu.heroId) - ), + units = ma.army.units.filter(cu => remainingUnits.exists(_.hero.id == cu.heroId)), fleeProvinceId = None ) ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateAction.scala index 04b5ad74ac..1d11c3c92e 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateAction.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.eagle.{FactionId, GameId, HeroId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSequentialResultsAction -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.HeroBackstoryUpdateRequest import net.eagle0.eagle.model.action_result.types.HeroBackstoriesUpdatedResultType @@ -41,12 +38,13 @@ case class HeroBackstoryUpdateAction( Vector( ActionResultC( actionResultType = HeroBackstoriesUpdatedResultType, - changedHeroes = heroesWithUpdates.map { case (heroId, llmRequest) => - ChangedHeroC( - heroId = heroId, - newBackstoryTextId = Some(llmRequest.requestId), - clearEventsForHeroBackstory = true - ) + changedHeroes = heroesWithUpdates.map { + case (heroId, llmRequest) => + ChangedHeroC( + heroId = heroId, + newBackstoryTextId = Some(llmRequest.requestId), + clearEventsForHeroBackstory = true + ) }, newGeneratedTextRequests = heroesWithUpdates.map(_._2) ) @@ -58,10 +56,9 @@ case class HeroBackstoryUpdateAction( heroFactionId: Option[FactionId], visibleToFactionIds: FactionId => Vector[FactionId] ): Vector[FactionId] = - heroFactionId - .map { hid => - visibleToFactionIds(hid) :+ hid - } + heroFactionId.map { hid => + visibleToFactionIds(hid) :+ hid + } .getOrElse(Vector.empty) private def generateHeroBackstoryUpdateLlmRequest( @@ -73,7 +70,7 @@ case class HeroBackstoryUpdateAction( events: Vector[EventForHeroBackstoryT] ): LlmRequestT = { val baseBackstoryUpdateTextId = s"backstoryUpdate-$heroId-$currentRoundId" - val previousBackstoryTextId = + val previousBackstoryTextId = previousBackstoryVersions.lastOption.map(_.textId).getOrElse("") val backstoryUpdateTextId = diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateActionGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateActionGenerator.scala index a0fc25e990..9e008cf8c9 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateActionGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/HeroBackstoryUpdateActionGenerator.scala @@ -11,8 +11,7 @@ object HeroBackstoryUpdateActionGenerator { gameId = gameState.gameId, roundId = gameState.currentRoundId, heroes = gameState.heroes.values.map(HeroConverter.fromProto).toVector, - visibleToFactionIds = - fid => LegacyFactionUtils.alliedFactions(fid, gameState), + visibleToFactionIds = fid => LegacyFactionUtils.alliedFactions(fid, gameState), heroInProvinceOwnedBy = heroId => gameState.provinces.values .find(province => diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundAction.scala index fd480ab509..c7165eedc8 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundAction.scala @@ -5,26 +5,17 @@ import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.round_phase.NewRoundPhase import net.eagle0.eagle.common.round_phase.RoundPhase.PRISONER_EXCHANGE import net.eagle0.eagle.internal.action_result.ActionResult -import net.eagle0.eagle.internal.changed_faction.{ - ChangedFaction, - TrustLevelUpdate -} +import net.eagle0.eagle.internal.changed_faction.{ChangedFaction, TrustLevelUpdate} import net.eagle0.eagle.internal.changed_hero.ChangedHero import net.eagle0.eagle.internal.changed_hero.ChangedHero.{Loyalty, Vigor} import net.eagle0.eagle.internal.changed_province.ChangedProvince import net.eagle0.eagle.internal.chronicle_entry.ChronicleEntry import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.HOSTILE import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.internal.generated_text_request.{ - ChronicleUpdateMessage, - GeneratedTextRequest -} +import net.eagle0.eagle.internal.generated_text_request.{ChronicleUpdateMessage, GeneratedTextRequest} import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - Action, - ActionWithResultingState -} +import net.eagle0.eagle.library.actions.impl.common.{Action, ActionWithResultingState} import net.eagle0.eagle.library.settings.{ EmptyProvinceMonthlyDevastationDelta, FactionBiasMinimumAdjustmentPerRound, @@ -41,11 +32,10 @@ import net.eagle0.eagle.library.util.PriceIndexUtils import net.eagle0.eagle.library.GameHistory import net.eagle0.eagle.RoundId -case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) - extends Action { +case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) extends Action { import net.eagle0.eagle.library.util.DateProtoUtils.* - private val maxMonth = 12 + private val maxMonth = 12 private val chronicleMonths = Vector(11) private def isChronicleMonth(newDate: Date): Boolean = @@ -57,15 +47,16 @@ case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) val newRoundId = startingState.currentRoundId + 1 // Verify no old incoming armies - startingState.provinces.foreach { case (pid, province) => - internalRequire( - province.incomingArmies.forall(_.arrivalRound >= newRoundId), - s"Province $pid has an army that should have already arrived" - ) - internalRequire( - province.hostileArmies.isEmpty, - s"Province $pid has hostile armies at the round start" - ) + startingState.provinces.foreach { + case (pid, province) => + internalRequire( + province.incomingArmies.forall(_.arrivalRound >= newRoundId), + s"Province $pid has an army that should have already arrived" + ) + internalRequire( + province.hostileArmies.isEmpty, + s"Province $pid has hostile armies at the round start" + ) } val oldDate = startingState.currentDate.get @@ -139,7 +130,7 @@ case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) val changes: Iterable[Changes] = startingState.provinces.values.map { p => - val changedUHs = + val changedUHs = p.unaffiliatedHeroes.map( _.update( _.recruitmentAttempted := false, @@ -178,8 +169,7 @@ case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) changedUnaffiliatedHeroes = changedUHs, foodDelta = Option.when(capFoodLoss != 0)(-capFoodLoss), goldDelta = Option.when(capGoldLoss != 0)(-capGoldLoss), - newPriceIndex = - Option.when(newPriceIndex != p.priceIndex)(newPriceIndex), + newPriceIndex = Option.when(newPriceIndex != p.priceIndex)(newPriceIndex), economyDevastationDelta = Option.when( p.rulingFactionId.isEmpty && p.economyDevastation > 0 )( @@ -212,12 +202,12 @@ case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) ) } - val changedProvinces = changes.map(_.changedProvince) + val changedProvinces = changes.map(_.changedProvince) val heroesAfterStipend = changes.flatMap(_.changedHeroes).map(h => h.id -> h).toMap - val uppedVigorHeroes = startingState.heroes - .map { case (hid, h) => + val uppedVigorHeroes = startingState.heroes.map { + case (hid, h) => heroesAfterStipend .getOrElse(hid, ChangedHero(id = hid)) .withVigor( @@ -228,7 +218,7 @@ case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) NewRoundVigorGain.doubleValue.min(h.constitution - h.vigor) ) ) - } + } val changedHeroes = uppedVigorHeroes.filter(ch => !(ch.loyalty.isEmpty && ch.vigor.isEmpty)) @@ -242,11 +232,9 @@ case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) changedFactionRelationships = removedTruces.map( _.update(_.optionalResetDate := None, _.relationshipLevel := HOSTILE) ), - trustLevelUpdates = - startingState.factions.keys.filterNot(_ == f.id).toVector.map { - targetFid => - TrustLevelUpdate(targetFid, TrustDeltaPerRound.intValue) - }, + trustLevelUpdates = startingState.factions.keys.filterNot(_ == f.id).toVector.map { targetFid => + TrustLevelUpdate(targetFid, TrustDeltaPerRound.intValue) + }, clearLastActedProvinceId = true ) } @@ -278,9 +266,7 @@ case class NewRoundAction(startingState: GameState, gameHistory: GameHistory) val notRecentHeroCount = province.rulingFactionHeroIds .map(gameState.heroes) .flatMap(_.roundIdJoined) - .count(roundId => - gameState.currentRoundId - roundId > MinimumRoundsBeforeLoyaltyDegrades.intValue - ) + .count(roundId => gameState.currentRoundId - roundId > MinimumRoundsBeforeLoyaltyDegrades.intValue) if province.heroCap >= notRecentHeroCount then Vector.empty else { val loyaltyHit = diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewYearAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewYearAction.scala index 5f4c6ce7c6..2f3b4400e0 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewYearAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/NewYearAction.scala @@ -21,8 +21,7 @@ import net.eagle0.eagle.library.settings.{ import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils -case class NewYearAction(gameState: GameState) - extends DeterministicSingleResultAction(gameState) { +case class NewYearAction(gameState: GameState) extends DeterministicSingleResultAction(gameState) { private def degradationMultiplier: Double = PercentDegradationPerYear.doubleValue / 100.0 @@ -36,8 +35,7 @@ case class NewYearAction(gameState: GameState) ( LegacyHeroUtils.discordance(vassal, factionLeader) + (if isProvinceLeader then 0 - else - AmbitionFactorForLoyaltyDegradation.doubleValue * vassal.ambition) + else AmbitionFactorForLoyaltyDegradation.doubleValue * vassal.ambition) - LoyaltyDiscordanceThreshold.doubleValue ) * LoyaltyDecreasePerDiscordance.doubleValue @@ -54,16 +52,16 @@ case class NewYearAction(gameState: GameState) def degradedLoyaltyHeroes: Iterable[ChangedHero] = for { - province <- gameState.provinces.values - heroId <- province.rulingFactionHeroIds + province <- gameState.provinces.values + heroId <- province.rulingFactionHeroIds provinceRulerId <- province.rulingHeroId hero = gameState.heroes(heroId) roundIdJoined <- hero.roundIdJoined currentRoundId = gameState.currentRoundId - if (currentRoundId - roundIdJoined > MinimumRoundsBeforeLoyaltyDegrades.intValue) + if currentRoundId - roundIdJoined > MinimumRoundsBeforeLoyaltyDegrades.intValue factionId <- hero.factionId - faction = gameState.factions(factionId) - if (!faction.leaders.contains(heroId)) + faction = gameState.factions(factionId) + if !faction.leaders.contains(heroId) factionLeader = gameState.heroes(faction.factionHeadId) } yield ChangedHero( id = hero.id, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseAction.scala index 041c472b13..d83f310a11 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseAction.scala @@ -14,8 +14,7 @@ import net.eagle0.eagle.library.settings.MaxBattalionReductionForFoodShortage import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.library.util.LegacyBattalionUtils -case class PerformFoodConsumptionPhaseAction(gs: GameState) - extends DeterministicSingleResultAction(gs) { +case class PerformFoodConsumptionPhaseAction(gs: GameState) extends DeterministicSingleResultAction(gs) { override def immediateExecute: ActionResult = { val (cps, cbs) = gs.provinces.values.map { p => @@ -60,14 +59,11 @@ case class PerformFoodConsumptionPhaseAction(gs: GameState) battalions, gameState.battalionTypes.toVector ) - val availableFood = movingArmy.supplies.map(_.food).getOrElse(0) + val availableFood = movingArmy.supplies.map(_.food).getOrElse(0) - val remainingSupplies = movingArmy.supplies.map(s => - s.withFood(Math.max(0, availableFood - foodConsumption)) - ) + val remainingSupplies = movingArmy.supplies.map(s => s.withFood(Math.max(0, availableFood - foodConsumption))) - if foodConsumption <= availableFood then - (movingArmy.update(_.optionalSupplies := remainingSupplies), Vector.empty) + if foodConsumption <= availableFood then (movingArmy.update(_.optionalSupplies := remainingSupplies), Vector.empty) else { val remainingProportion = (availableFood.toDouble / foodConsumption.toDouble) @@ -81,7 +77,6 @@ case class PerformFoodConsumptionPhaseAction(gs: GameState) newBattalions ) } - end if } private def foodDeltaAndChangedBattalionsAfterConsumingFood( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackAction.scala index e8e1ef57a2..c4ea647453 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackAction.scala @@ -20,14 +20,10 @@ import net.eagle0.eagle.library.actions.util.ShatteredArmyUtils import net.eagle0.eagle.library.settings.WinterSuppliesLoss import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.model.action_result.NotificationDetails.ShatteredArmy.Reason.Blizzard -import net.eagle0.eagle.model.proto_converters.{ - ActionResultProtoConverter, - ArmyConverter -} +import net.eagle0.eagle.model.proto_converters.{ActionResultProtoConverter, ArmyConverter} import net.eagle0.eagle.model.proto_converters.province.ProvinceConverter -case class PerformForcedTurnBackAction(gs: GameState) - extends DeterministicSequentialResultsAction(gs) { +case class PerformForcedTurnBackAction(gs: GameState) extends DeterministicSequentialResultsAction(gs) { val endPhaseResult: ActionResult = ActionResult( `type` = END_FORCED_TURN_BACK_PHASE, @@ -35,47 +31,46 @@ case class PerformForcedTurnBackAction(gs: GameState) ) private def oneTurnBackSuppliesResult(is: MovingSupplies, p: Province) = - is.originProvinceId - .map { originPid => - ActionResult( - `type` = WEATHER_FORCED_SUPPLIES_BACK, - player = Some(is.factionId), - province = Some(p.id), - changedProvinces = Vector( - ChangedProvince( - id = p.id, - removedIncomingShipmentIds = Vector(is.id) - ), - ChangedProvince( - id = originPid, - addedIncomingShipments = Vector( - MovingSupplies( - supplies = is.supplies.map { - _.update( - _.food.modify(f => - Math - .floor((1.0 - WinterSuppliesLoss.doubleValue) * f) - .toInt - ), - _.gold.modify(g => - Math - .floor((1.0 - WinterSuppliesLoss.doubleValue) * g) - .toInt - ) + is.originProvinceId.map { originPid => + ActionResult( + `type` = WEATHER_FORCED_SUPPLIES_BACK, + player = Some(is.factionId), + province = Some(p.id), + changedProvinces = Vector( + ChangedProvince( + id = p.id, + removedIncomingShipmentIds = Vector(is.id) + ), + ChangedProvince( + id = originPid, + addedIncomingShipments = Vector( + MovingSupplies( + supplies = is.supplies.map { + _.update( + _.food.modify(f => + Math + .floor((1.0 - WinterSuppliesLoss.doubleValue) * f) + .toInt + ), + _.gold.modify(g => + Math + .floor((1.0 - WinterSuppliesLoss.doubleValue) * g) + .toInt ) - }, - arrivalRound = gs.currentRoundId + 1, - destinationProvinceId = originPid, - originProvinceId = None, - factionId = is.factionId, - suppliesLoss = is.suppliesLoss, - id = is.id - ) + ) + }, + arrivalRound = gs.currentRoundId + 1, + destinationProvinceId = originPid, + originProvinceId = None, + factionId = is.factionId, + suppliesLoss = is.suppliesLoss, + id = is.id ) ) ) ) - } + ) + } .getOrElse( ActionResult( `type` = WEATHER_FORCED_SUPPLIES_LOST, @@ -91,34 +86,32 @@ case class PerformForcedTurnBackAction(gs: GameState) ) private def oneTurnBackArmyResult(ia: MovingArmy, p: Province): ActionResult = - ia.getArmy.fleeProvinceId - .map { fleePid => - ActionResult( - `type` = WEATHER_FORCED_TURN_BACK, - player = Some(ia.getArmy.factionId), - province = Some(ia.destinationProvince), - affectedPlayers = - (Vector(ia.getArmy.factionId) ++ p.rulingFactionId).distinct, - changedProvinces = Vector( - ChangedProvince(id = p.id, removedIncomingArmyIds = Vector(ia.id)), - ChangedProvince( - id = fleePid, - addedIncomingArmies = Vector( - MovingArmy( - army = ia.army.map(_.clearFleeProvinceId), - arrivalRound = gs.currentRoundId + 1, - destinationProvince = fleePid, - originProvince = p.id, - supplies = ia.supplies, - suppliesLoss = ia.suppliesLoss, - id = ia.id, - startingPositionIndex = None - ) + ia.getArmy.fleeProvinceId.map { fleePid => + ActionResult( + `type` = WEATHER_FORCED_TURN_BACK, + player = Some(ia.getArmy.factionId), + province = Some(ia.destinationProvince), + affectedPlayers = (Vector(ia.getArmy.factionId) ++ p.rulingFactionId).distinct, + changedProvinces = Vector( + ChangedProvince(id = p.id, removedIncomingArmyIds = Vector(ia.id)), + ChangedProvince( + id = fleePid, + addedIncomingArmies = Vector( + MovingArmy( + army = ia.army.map(_.clearFleeProvinceId), + arrivalRound = gs.currentRoundId + 1, + destinationProvince = fleePid, + originProvince = p.id, + supplies = ia.supplies, + suppliesLoss = ia.suppliesLoss, + id = ia.id, + startingPositionIndex = None ) ) ) ) - } + ) + } .getOrElse( ActionResultProtoConverter.toProto( ShatteredArmyUtils @@ -134,7 +127,7 @@ case class PerformForcedTurnBackAction(gs: GameState) private def turnBackArmiesResults: Vector[ActionResult] = ( for { - p <- gs.provinces.values.filter(LegacyProvinceUtils.hasBlizzard) + p <- gs.provinces.values.filter(LegacyProvinceUtils.hasBlizzard) ia <- p.incomingArmies.filter(_.arrivalRound == gs.currentRoundId) } yield oneTurnBackArmyResult(ia, p) ).toVector @@ -142,7 +135,7 @@ case class PerformForcedTurnBackAction(gs: GameState) private def turnBackSuppliesResults: Vector[ActionResult] = ( for { - p <- gs.provinces.values.filter(LegacyProvinceUtils.hasBlizzard) + p <- gs.provinces.values.filter(LegacyProvinceUtils.hasBlizzard) is <- p.incomingShipments.filter(_.arrivalRound == gs.currentRoundId) } yield oneTurnBackSuppliesResult(is, p) ).toVector diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesAction.scala index 3cd0175e96..b12d1b0e05 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesAction.scala @@ -2,15 +2,9 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.{FunctionalRandom, RandomState} import net.eagle0.eagle.{HeroId, ProvinceId, RoundId} -import net.eagle0.eagle.common.action_result_notification_details.{ - HeroDepartureDetails, - Notification -} +import net.eagle0.eagle.common.action_result_notification_details.{HeroDepartureDetails, Notification} import net.eagle0.eagle.common.action_result_notification_details.Notification.Llm -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_HERO_DEPARTURE_PHASE, - HEROES_DEPARTED -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_HERO_DEPARTURE_PHASE, HEROES_DEPARTED} import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.RECRUITMENT_STATUS_TRAVELER import net.eagle0.eagle.common.round_phase.NewRoundPhase @@ -19,22 +13,13 @@ import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFF import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.changed_hero.ChangedHero import net.eagle0.eagle.internal.changed_province.ChangedProvince -import net.eagle0.eagle.internal.event_for_hero_backstory.{ - EventForHeroBackstory, - HeroDepartedBackstoryEvent -} +import net.eagle0.eagle.internal.event_for_hero_backstory.{EventForHeroBackstory, HeroDepartedBackstoryEvent} import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.internal.generated_text_request.{ - GeneratedTextRequest, - HeroDepartureMessage -} +import net.eagle0.eagle.internal.generated_text_request.{GeneratedTextRequest, HeroDepartureMessage} import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier import net.eagle0.eagle.library.actions.impl.common.DeterministicSequentialResultsAction -import net.eagle0.eagle.library.settings.{ - FactionBiasFromDeparture, - LoyaltyThreshold -} +import net.eagle0.eagle.library.settings.{FactionBiasFromDeparture, LoyaltyThreshold} import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils @@ -100,7 +85,7 @@ object PerformHeroDeparturesAction { Math.max(0, LoyaltyThreshold.doubleValue - loyalty) / 100.0 private def notificationLlmId(currentRoundId: RoundId, hid: HeroId): String = - s"hero departed ${currentRoundId} $hid" + s"hero departed $currentRoundId $hid" private def notificationForHero( hid: HeroId, @@ -146,65 +131,66 @@ case class PerformHeroDeparturesAction( Vector[Option[(ChangedProvince, Vector[HeroId])]](), functionalRandom ) - ) { case (rs, p) => - rs.continue { case (acc, fr) => - PerformHeroDeparturesAction - .provinceWithDepartedHeroes( - startingState, - p.id, - fr - ) - .map { tup => acc :+ tup } - } + ) { + case (rs, p) => + rs.continue { + case (acc, fr) => + PerformHeroDeparturesAction + .provinceWithDepartedHeroes( + startingState, + p.id, + fr + ) + .map(tup => acc :+ tup) + } } .map(_.flatten) .map { - _.map { case (cp, hs) => - ActionResult( - `type` = HEROES_DEPARTED, - province = Some(cp.id), - player = startingState.provinces(cp.id).rulingFactionId, - changedProvinces = Vector(cp), - changedHeroes = hs.map { hid => - ChangedHero( - id = hid, - clearFactionId = true, - newBackstoryEvents = Vector( - EventForHeroBackstory( - date = startingState.currentDate, - details = HeroDepartedBackstoryEvent( - departedFromFactionId = - startingState.provinces(cp.id).getRulingFactionId, - departedFromProvinceId = cp.id + _.map { + case (cp, hs) => + ActionResult( + `type` = HEROES_DEPARTED, + province = Some(cp.id), + player = startingState.provinces(cp.id).rulingFactionId, + changedProvinces = Vector(cp), + changedHeroes = hs.map { hid => + ChangedHero( + id = hid, + clearFactionId = true, + newBackstoryEvents = Vector( + EventForHeroBackstory( + date = startingState.currentDate, + details = HeroDepartedBackstoryEvent( + departedFromFactionId = startingState.provinces(cp.id).getRulingFactionId, + departedFromProvinceId = cp.id + ) ) ) ) - ) - }, - notificationsToDeliver = hs.map { hid => - PerformHeroDeparturesAction.notificationForHero( - hid = hid, - pid = cp.id, - gameState = startingState - ) - }, - newGeneratedTextRequests = hs.flatMap { hid => - Vector( - PerformHeroDeparturesAction.notificationLlmRequestForHero( + }, + notificationsToDeliver = hs.map { hid => + PerformHeroDeparturesAction.notificationForHero( hid = hid, pid = cp.id, gameState = startingState ) - ) - } - ) + }, + newGeneratedTextRequests = hs.flatMap { hid => + Vector( + PerformHeroDeparturesAction.notificationLlmRequestForHero( + hid = hid, + pid = cp.id, + gameState = startingState + ) + ) + } + ) } } match { case RandomState(ars, fr) => ars :+ ActionResult( `type` = END_HERO_DEPARTURE_PHASE, - newRoundPhase = - Some(NewRoundPhase(value = UNAFFILIATED_HERO_ACTIONS)), + newRoundPhase = Some(NewRoundPhase(value = UNAFFILIATED_HERO_ACTIONS)), newRandomSeed = Some(fr.seed) ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupAction.scala index 36b1c42de0..54eb9a5b49 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupAction.scala @@ -30,20 +30,21 @@ case class PerformHostileArmySetupAction(startingState: GameState) _.arrivalRound == startingState.currentRoundId ) .groupBy(_.getArmy.factionId) - .map { case (fid, movingArmies) => - HostileArmyGroup( - factionId = fid, - armies = movingArmies.toVector.map { ma => - ma.update( - _.startingPositionIndex := attackerStartingPositionIndex( - defenderProvinceId = province.id, - attackerProvinceId = ma.originProvince, - gs = startingState + .map { + case (fid, movingArmies) => + HostileArmyGroup( + factionId = fid, + armies = movingArmies.toVector.map { ma => + ma.update( + _.startingPositionIndex := attackerStartingPositionIndex( + defenderProvinceId = province.id, + attackerProvinceId = ma.originProvince, + gs = startingState + ) ) - ) - }, - status = AwaitingDecision() - ) + }, + status = AwaitingDecision() + ) } .toVector @@ -58,8 +59,7 @@ case class PerformHostileArmySetupAction(startingState: GameState) override def immediateExecute: ActionResult = ActionResult( `type` = ActionResultType.SET_UP_HOSTILE_ARMIES, - changedProvinces = - startingState.provinces.values.flatMap(oneProvinceResult).toVector, + changedProvinces = startingState.provinces.values.flatMap(oneProvinceResult).toVector, newRoundPhase = Some(NewRoundPhase(RoundPhase.FREE_FOR_ALL_DECISION)) ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsAction.scala index 0847435652..20b3c7d706 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsAction.scala @@ -116,10 +116,10 @@ case class PerformProvinceEventsAction( import net.eagle0.eagle.library.util.DateProtoUtils.* private val blizzardMonths = Set(12, 1, 2) - private val floodMonths = Set(6, 7, 8) + private val floodMonths = Set(6, 7, 8) private val festivalMonths = Set(3, 9) private val epidemicMonths = Set(3, 4, 5, 6, 7, 8, 9, 10) - private val droughtMonths = Set(6, 7, 8, 9) + private val droughtMonths = Set(6, 7, 8, 9) override def randomResults( functionalRandom: FunctionalRandom, @@ -146,8 +146,9 @@ case class PerformProvinceEventsAction( changedBattalions = changedBattalions, changedHeroes = changedHeroes, changedFactions = startingState.provinces.values - .foldLeft(Map[FactionId, ChangedFaction]()) { case (acc, p) => - changedFaction(acc, p) + .foldLeft(Map[FactionId, ChangedFaction]()) { + case (acc, p) => + changedFaction(acc, p) } .values .toVector @@ -171,52 +172,52 @@ case class PerformProvinceEventsAction( cp: ChangedProvince, epidemicEndRoll: Double ): ChangedProvince = - p.activeEvents.foldLeft(cp) { case (cp, event) => - event match { - case _: BlizzardEvent => - cp.update( - _.optionalEconomyDevastationDelta.modify(dd => - Some( - dd.getOrElse(0.0) + BlizzardEconomyDevastationDelta.doubleValue - ) - ), - _.optionalAgricultureDevastationDelta.modify(dd => - Some( - dd.getOrElse( - 0.0 - ) + BlizzardAgricultureDevastationDelta.doubleValue - ) - ), - _.optionalInfrastructureDevastationDelta.modify(dd => - Some( - dd.getOrElse( - 0.0 - ) + BlizzardInfrastructureDevastationDelta.doubleValue + p.activeEvents.foldLeft(cp) { + case (cp, event) => + event match { + case _: BlizzardEvent => + cp.update( + _.optionalEconomyDevastationDelta.modify(dd => + Some( + dd.getOrElse(0.0) + BlizzardEconomyDevastationDelta.doubleValue + ) + ), + _.optionalAgricultureDevastationDelta.modify(dd => + Some( + dd.getOrElse( + 0.0 + ) + BlizzardAgricultureDevastationDelta.doubleValue + ) + ), + _.optionalInfrastructureDevastationDelta.modify(dd => + Some( + dd.getOrElse( + 0.0 + ) + BlizzardInfrastructureDevastationDelta.doubleValue + ) ) ) - ) - case _: FloodEvent => - cp.update( - _.optionalAgricultureDevastationDelta.modify(dd => - Some( - dd.getOrElse( - 0.0 - ) + (MaxFloodAgricultureDevastationDelta.doubleValue - p.infrastructure * FloodDevastationDeltaReductionPerInfrastructure.doubleValue) - .max(0.0) - ) - ), - _.optionalInfrastructureDevastationDelta.modify(dd => - Some( - dd.getOrElse( - 0.0 - ) + (MaxFloodInfrastructureDevastationDelta.doubleValue - p.infrastructure * FloodDevastationDeltaReductionPerInfrastructure.doubleValue) - .max(0.0) + case _: FloodEvent => + cp.update( + _.optionalAgricultureDevastationDelta.modify(dd => + Some( + dd.getOrElse( + 0.0 + ) + (MaxFloodAgricultureDevastationDelta.doubleValue - p.infrastructure * FloodDevastationDeltaReductionPerInfrastructure.doubleValue) + .max(0.0) + ) + ), + _.optionalInfrastructureDevastationDelta.modify(dd => + Some( + dd.getOrElse( + 0.0 + ) + (MaxFloodInfrastructureDevastationDelta.doubleValue - p.infrastructure * FloodDevastationDeltaReductionPerInfrastructure.doubleValue) + .max(0.0) + ) ) ) - ) - case BeastsEvent(_, _, _, beastInfo, _ /* unknownFieldSet */ ) => - beastInfo - .map { beast => + case BeastsEvent(_, _, _, beastInfo, _ /* unknownFieldSet */ ) => + beastInfo.map { beast => cp.update( _.optionalEconomyDevastationDelta.modify(dd => Some(dd.getOrElse(0.0) + beast.economyDevastation) @@ -230,51 +231,47 @@ case class PerformProvinceEventsAction( Some(dd.getOrElse(0.0) + beast.infrastructureDevastation) .filterNot(_ == 0.0) ), - _.optionalSupportDelta.modify(sd => - Some(sd.getOrElse(0.0) - BeastsSupportDamage.doubleValue) + _.optionalSupportDelta.modify(sd => Some(sd.getOrElse(0.0) - BeastsSupportDamage.doubleValue)) + ) + } + .getOrElse(cp) + case _: FestivalEvent => + cp.update( + _.optionalSupportDelta.modify(sd => Some(sd.getOrElse(0.0) + FestivalSupportDelta.doubleValue)) + ) + case _: EpidemicEvent => + cp.update( + _.optionalEconomyDevastationDelta.modify(dd => + Some( + dd.getOrElse(0.0) + EpidemicEconomyDevastationDelta.doubleValue + ) + ), + _.optionalNewProvinceEvents := Option.when( + !epidemicMonths.contains(startingState.currentDate.get.month) || + epidemicEndRoll < EpidemicEndChance.doubleValue + ) { + ProvinceEventsReplacement( + newEvents = cp.newProvinceEvents + .map(_.newEvents) + .getOrElse(p.activeEvents) + .filterNot(ProvinceEventUtils.isEpidemicEvent) + ) + } + ) + case _: DroughtEvent => + cp.update( + _.optionalAgricultureDevastationDelta.modify(dd => + Some( + dd.getOrElse( + 0.0 + ) + DroughtAgricultureDevastationDelta.doubleValue ) ) - } - .getOrElse(cp) - case _: FestivalEvent => - cp.update( - _.optionalSupportDelta.modify(sd => - Some(sd.getOrElse(0.0) + FestivalSupportDelta.doubleValue) ) - ) - case _: EpidemicEvent => - cp.update( - _.optionalEconomyDevastationDelta.modify(dd => - Some( - dd.getOrElse(0.0) + EpidemicEconomyDevastationDelta.doubleValue - ) - ), - _.optionalNewProvinceEvents := Option.when( - !epidemicMonths.contains(startingState.currentDate.get.month) || - epidemicEndRoll < EpidemicEndChance.doubleValue - ) { - ProvinceEventsReplacement( - newEvents = cp.newProvinceEvents - .map(_.newEvents) - .getOrElse(p.activeEvents) - .filterNot(ProvinceEventUtils.isEpidemicEvent) - ) - } - ) - case _: DroughtEvent => - cp.update( - _.optionalAgricultureDevastationDelta.modify(dd => - Some( - dd.getOrElse( - 0.0 - ) + DroughtAgricultureDevastationDelta.doubleValue - ) - ) - ) - case _: ImminentRiotEvent => cp - case ProvinceEvent.Empty => cp - } + case _: ImminentRiotEvent => cp + case ProvinceEvent.Empty => cp + } } def blizzardDurationMonths(currentMonth: Int): FactionId = @@ -365,7 +362,7 @@ case class PerformProvinceEventsAction( def newEpidemicEvent( province: Province, epidemicRoll: Double - ): Option[ProvinceEvent] = { + ): Option[ProvinceEvent] = Option.when( epidemicMonths .contains(startingState.currentDate.get.month) @@ -379,7 +376,6 @@ case class PerformProvinceEventsAction( ) { EpidemicEvent(startDate = Some(startingState.currentDate.get)) } - } def newBeastsEvent( province: Province, @@ -481,38 +477,34 @@ case class PerformProvinceEventsAction( def changedFaction( existingCFs: Map[FactionId, ChangedFaction], province: Province - ): Map[FactionId, ChangedFaction] = { - province.rulingFactionId - .map { fid => - val existingCf = - existingCFs.getOrElse(fid, ChangedFaction(id = fid)) + ): Map[FactionId, ChangedFaction] = + province.rulingFactionId.map { fid => + val existingCf = + existingCFs.getOrElse(fid, ChangedFaction(id = fid)) - val newCf = province.activeEvents.foldLeft(existingCf) { - case (cf, event) => - event match { - case _: FestivalEvent => - cf.update( - _.addedPrestigeModifiers :+= PrestigeModifier( - `type` = PrestigeModifier.Type.FESTIVAL, - value = FestivalPrestigeDelta.doubleValue - ) + val newCf = province.activeEvents.foldLeft(existingCf) { + case (cf, event) => + event match { + case _: FestivalEvent => + cf.update( + _.addedPrestigeModifiers :+= PrestigeModifier( + `type` = PrestigeModifier.Type.FESTIVAL, + value = FestivalPrestigeDelta.doubleValue ) - case _ => cf - } - } - - if newCf == existingCf then existingCFs - else existingCFs + (fid -> newCf) + ) + case _ => cf + } } + + if newCf == existingCf then existingCFs + else existingCFs + (fid -> newCf) + } .getOrElse(existingCFs) - } def changedHeroes: Vector[ChangedHero] = startingState.provinces.values .filter(LegacyProvinceUtils.hasEpidemic) - .flatMap(p => - p.rulingFactionHeroIds ++ p.unaffiliatedHeroes.map(_.heroId) - ) + .flatMap(p => p.rulingFactionHeroIds ++ p.unaffiliatedHeroes.map(_.heroId)) .map(startingState.heroes) .map(hero => ChangedHero( @@ -530,9 +522,7 @@ case class PerformProvinceEventsAction( .map(b => b.update( _.size - .modify(s => - (s * (1.0 - EpidemicBattalionLossPercentage.doubleValue)).toInt - ) + .modify(s => (s * (1.0 - EpidemicBattalionLossPercentage.doubleValue)).toInt) ) ) .toVector @@ -550,8 +540,8 @@ case class PerformProvinceEventsAction( ) val newProvinceEventSet = province.activeEvents.filter { - case ProvinceEvent.Empty => ??? - case DroughtEvent(startDate, endDate, _ /* unknownFieldSet */ ) => + case ProvinceEvent.Empty => ??? + case DroughtEvent(startDate, endDate, _ /* unknownFieldSet */ ) => endDate.exists(_ >= startingState.currentDate.get) case BeastsEvent( count, @@ -565,10 +555,10 @@ case class PerformProvinceEventsAction( endDate.exists(_ >= startingState.currentDate.get) case FestivalEvent(startDate, endDate, _ /* unknownFieldSet */ ) => endDate.exists(_ >= startingState.currentDate.get) - case FloodEvent(startDate, endDate, _ /* unknownFieldSet */ ) => + case FloodEvent(startDate, endDate, _ /* unknownFieldSet */ ) => endDate.exists(_ >= startingState.currentDate.get) - case EpidemicEvent(startDate, _ /* unknownFieldSet */ ) => true - case ImminentRiotEvent(_ /* unknownFieldSet */ ) => true + case EpidemicEvent(startDate, _ /* unknownFieldSet */ ) => true + case ImminentRiotEvent(_ /* unknownFieldSet */ ) => true } ++ newProvinceEvents( province, provinceEventRolls @@ -581,6 +571,6 @@ case class PerformProvinceEventsAction( ProvinceEventsReplacement(newProvinceEventSet) ) - Option.when(withEventsReplacement != startingCp) { withEventsReplacement } + Option.when(withEventsReplacement != startingCp)(withEventsReplacement) } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionAction.scala index 6af1fd2113..01d5b5d61b 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionAction.scala @@ -6,15 +6,8 @@ import net.eagle0.eagle.internal.army.MovingArmy import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - ActionWithResultingState, - RandomSequentialResultsAction -} -import net.eagle0.eagle.model.proto_converters.{ - ActionResultProtoConverter, - ArmyConverter, - SuppliesConverter -} +import net.eagle0.eagle.library.actions.impl.common.{ActionWithResultingState, RandomSequentialResultsAction} +import net.eagle0.eagle.model.proto_converters.{ActionResultProtoConverter, ArmyConverter, SuppliesConverter} import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.hero.HeroConverter import net.eagle0.eagle.model.proto_converters.province.ProvinceConverter @@ -45,16 +38,17 @@ case class PerformProvinceMoveResolutionAction( val movingFriendliesStates = provincesWithIncomingFriendlies .foldLeft(Vector(ActionWithResultingState(null, startingState))) { case (acc, (province, armies)) => - armies.foldLeft(acc) { case (acc2, army) => - acc2 :+ actionResultProtoApplier.applyActionResult( - acc2.last.gameState, - ActionResultProtoConverter.toProto( - FriendlyMoveAction( - ArmyConverter.fromProto(army), - province.id - ).immediateExecute + armies.foldLeft(acc) { + case (acc2, army) => + acc2 :+ actionResultProtoApplier.applyActionResult( + acc2.last.gameState, + ActionResultProtoConverter.toProto( + FriendlyMoveAction( + ArmyConverter.fromProto(army), + province.id + ).immediateExecute + ) ) - ) } } @@ -69,28 +63,28 @@ case class PerformProvinceMoveResolutionAction( .filter(_._2.nonEmpty) val states = provincesWithIncomingShipments - .foldLeft(movingFriendliesStates) { case (acc, (province, shipments)) => - shipments.foldLeft(acc) { case (acc2, supplies) => - acc2 :+ actionResultProtoApplier.applyActionResult( - acc2.last.gameState, - ActionResultProtoConverter.toProto( - ShipmentArrivedAction( - SuppliesConverter.fromProto(supplies), - province.id - ).immediateExecute - ) - ) - } + .foldLeft(movingFriendliesStates) { + case (acc, (province, shipments)) => + shipments.foldLeft(acc) { + case (acc2, supplies) => + acc2 :+ actionResultProtoApplier.applyActionResult( + acc2.last.gameState, + ActionResultProtoConverter.toProto( + ShipmentArrivedAction( + SuppliesConverter.fromProto(supplies), + province.id + ).immediateExecute + ) + ) + } } .drop(1) val lastState = states.lastOption.map(_.gameState).getOrElse(startingState) EndProvinceMoveResolutionPhaseAction( gameId = lastState.gameId, - factions = - lastState.factions.values.map(FactionConverter.fromProto).toVector, - provinces = - lastState.provinces.values.toVector.map(ProvinceConverter.fromProto), + factions = lastState.factions.values.map(FactionConverter.fromProto).toVector, + provinces = lastState.provinces.values.toVector.map(ProvinceConverter.fromProto), heroes = lastState.heroes.values.toVector.map(HeroConverter.fromProto) ).randomResults(functionalRandom) .map(_.map(ActionResultProtoConverter.toProto)) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionAction.scala index 606d5b1a9e..2e780d38ec 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionAction.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.{FunctionalRandom, RandomState} -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_RECON_RESOLUTION_PHASE, - RECON_SUCCEEDED -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_RECON_RESOLUTION_PHASE, RECON_SUCCEEDED} import net.eagle0.eagle.common.round_phase.{NewRoundPhase, RoundPhase} import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.action_result.ActionResult.ClientTextVisibilityExtension @@ -13,16 +10,10 @@ import net.eagle0.eagle.internal.changed_province.ChangedProvince import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.IncomingEndTurnAction import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - RandomSequentialResultsAction, - RandomStateProtoSequencer -} +import net.eagle0.eagle.library.actions.impl.common.{RandomSequentialResultsAction, RandomStateProtoSequencer} import net.eagle0.eagle.library.util.view_filters.ProvinceViewFilter import net.eagle0.eagle.library.util.ReturningHeroes -import net.eagle0.eagle.model.proto_converters.{ - ChangedHeroConverter, - ChangedProvinceConverter -} +import net.eagle0.eagle.model.proto_converters.{ChangedHeroConverter, ChangedProvinceConverter} import net.eagle0.eagle.model.proto_converters.province.ProvinceConverter import net.eagle0.eagle.ProvinceId @@ -41,14 +32,17 @@ case class PerformReconResolutionAction( actionResultProtoApplier = actionResultProtoApplier, functionalRandom = functionalRandom ) - ) { case (sequencer, province) => - province.incomingEndTurnActions - .filter(_.action.isRecon) - .foldLeft(sequencer) { case (innerSequencer, action) => - innerSequencer.withRandomActionResult { case (_, fr) => - oneResult(province.id, action, fr) + ) { + case (sequencer, province) => + province.incomingEndTurnActions + .filter(_.action.isRecon) + .foldLeft(sequencer) { + case (innerSequencer, action) => + innerSequencer.withRandomActionResult { + case (_, fr) => + oneResult(province.id, action, fr) + } } - } } .actionResults .map { ars => @@ -65,7 +59,7 @@ case class PerformReconResolutionAction( ): RandomState[ActionResult] = { val originProvince = startingGameState.provinces(incomingEndTurnAction.fromProvinceId) - val fromFactionId = incomingEndTurnAction.fromFactionId + val fromFactionId = incomingEndTurnAction.fromFactionId val targetProvince = startingGameState.provinces(provinceId) val recon = incomingEndTurnAction.getRecon @@ -83,8 +77,7 @@ case class PerformReconResolutionAction( .map { returningHeroes => ActionResult( `type` = RECON_SUCCEEDED, - changedHeroes = - returningHeroes.changedHeroes.map(ChangedHeroConverter.toProto), + changedHeroes = returningHeroes.changedHeroes.map(ChangedHeroConverter.toProto), changedProvinces = Vector( // the CP for the destination province ChangedProvince( @@ -109,17 +102,16 @@ case class PerformReconResolutionAction( ) ) ), - clientTextVisibilityExtensions = - targetProvince.rulingFactionHeroIds.map { hid => - ClientTextVisibilityExtension( - textId = startingGameState - .heroes(hid) - .backstoryVersions - .last - .textId, - recipientFactionIds = Vector(fromFactionId) - ) - } + clientTextVisibilityExtensions = targetProvince.rulingFactionHeroIds.map { hid => + ClientTextVisibilityExtension( + textId = startingGameState + .heroes(hid) + .backstoryVersions + .last + .textId, + recipientFactionIds = Vector(fromFactionId) + ) + } ) } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesAction.scala index 4d205edeb2..748e264162 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesAction.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.{FunctionalRandom, RandomState} import net.eagle0.eagle.{HeroId, ProvinceId} -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - HERO_CHANGED, - NEW_QUESTS -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{HERO_CHANGED, NEW_QUESTS} import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.{ RECRUITMENT_STATUS_NO_RULER_IN_PROVINCE, @@ -28,10 +25,7 @@ import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - RandomSequentialResultsAction, - RandomStateProtoSequencer -} +import net.eagle0.eagle.library.actions.impl.common.{RandomSequentialResultsAction, RandomStateProtoSequencer} import net.eagle0.eagle.library.actions.name_generation_request.NameGenerationRequestCreator import net.eagle0.eagle.library.settings.{ MinVigorForFreeHeroMove, @@ -49,10 +43,7 @@ import net.eagle0.eagle.library.util.hero_generator.HeroGenerator import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.library.util.unaffiliated_hero.LegacyUnaffiliatedHeroUtils import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.proto_converters.{ - ActionResultProtoConverter, - UnaffiliatedHeroConverter -} +import net.eagle0.eagle.model.proto_converters.{ActionResultProtoConverter, UnaffiliatedHeroConverter} import net.eagle0.eagle.model.proto_converters.date.DateConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.hero.HeroConverter @@ -95,42 +86,38 @@ case class PerformUnaffiliatedHeroesAction( initialStateProto = gameState, actionResultProtoApplier = actionResultProtoApplier, functionalRandom = functionalRandom - ) - .withRandomActionResults { case (gs, fr) => statusChangeResults(gs, fr) } - .withRandomActionResultTs { case (gs, fr) => heroAppearsResults(gs, fr) } - .withRandomContinuance { (randomSequencer: RandomStateProtoSequencer) => - val newHeroesMap = - randomSequencer.actionResults.newValue - .flatMap(_.newHeroes) - .map(h => h.id -> h) - .toMap + ).withRandomActionResults { case (gs, fr) => statusChangeResults(gs, fr) }.withRandomActionResultTs { + case (gs, fr) => heroAppearsResults(gs, fr) + }.withRandomContinuance { (randomSequencer: RandomStateProtoSequencer) => + val newHeroesMap = + randomSequencer.actionResults.newValue + .flatMap(_.newHeroes) + .map(h => h.id -> h) + .toMap - val qcpsOpt = questChangedProvinces( - pwrf = randomSequencer.lastStateProto.provinces.values.toVector, - newHeroesMap = newHeroesMap, - functionalRandom = randomSequencer.results.nextRandom - ).map { qcps => - Vector( - ActionResult( - `type` = NEW_QUESTS, - changedProvinces = qcps - ) + val qcpsOpt = questChangedProvinces( + pwrf = randomSequencer.lastStateProto.provinces.values.toVector, + newHeroesMap = newHeroesMap, + functionalRandom = randomSequencer.results.nextRandom + ).map { qcps => + Vector( + ActionResult( + `type` = NEW_QUESTS, + changedProvinces = qcps ) - } - randomSequencer.withRandomActionResults((_, _) => qcpsOpt) + ) } - .withActionResults { gs => - EndUnaffiliatedHeroActionsPhaseAction( - gameId = gs.gameId, - currentDate = currentDate, - currentRoundId = gs.currentRoundId, - provinces = - gs.provinces.values.map(ProvinceConverter.fromProto).toVector, - heroes = gs.heroes.values.map(HeroConverter.fromProto).toVector, - factions = gs.factions.values.map(FactionConverter.fromProto).toVector - ).results.map(ActionResultProtoConverter.toProto) - } - .actionResults + randomSequencer.withRandomActionResults((_, _) => qcpsOpt) + }.withActionResults { gs => + EndUnaffiliatedHeroActionsPhaseAction( + gameId = gs.gameId, + currentDate = currentDate, + currentRoundId = gs.currentRoundId, + provinces = gs.provinces.values.map(ProvinceConverter.fromProto).toVector, + heroes = gs.heroes.values.map(HeroConverter.fromProto).toVector, + factions = gs.factions.values.map(FactionConverter.fromProto).toVector + ).results.map(ActionResultProtoConverter.toProto) + }.actionResults private def restResult( unaffiliatedHero: UnaffiliatedHero, @@ -159,7 +146,7 @@ case class PerformUnaffiliatedHeroesAction( then RandomState(None, fr) else unaffiliatedHero.`type` match { - case UNAFFILIATED_HERO_PRISONER => + case UNAFFILIATED_HERO_PRISONER => RandomState( prisonerResult( provinceId = provinceId, @@ -170,21 +157,21 @@ case class PerformUnaffiliatedHeroesAction( ) case UNAFFILIATED_HERO_MOVING_PRISONER => RandomState(None, fr) - case UNAFFILIATED_HERO_RESIDENT => + case UNAFFILIATED_HERO_RESIDENT => residentResult( provinceId = provinceId, uh = unaffiliatedHero, gameState = gameState, functionalRandom = fr ) - case UNAFFILIATED_HERO_TRAVELER => + case UNAFFILIATED_HERO_TRAVELER => travelerResult( provinceId = provinceId, uh = unaffiliatedHero, gameState = gameState, functionalRandom = fr ) - case UNAFFILIATED_HERO_OUTLAW => + case UNAFFILIATED_HERO_OUTLAW => outlawResult( pid = provinceId, uh = unaffiliatedHero, @@ -195,7 +182,7 @@ case class PerformUnaffiliatedHeroesAction( case _ => RandomState(None, fr) } - maybeResult.map { _.getOrElse(restResult(unaffiliatedHero, provinceId)) } + maybeResult.map(_.getOrElse(restResult(unaffiliatedHero, provinceId))) } def oneProvinceResult( @@ -204,10 +191,12 @@ case class PerformUnaffiliatedHeroesAction( ): RandomState[Vector[ActionResult]] = province.unaffiliatedHeroes.foldLeft( RandomState[Vector[ActionResult]](Vector(), startingFr) - ) { case (rs, uh) => - rs.continue { case (ars, fr) => - oneUHResult(fr, uh, province.id).map { ar => ars :+ ar } - } + ) { + case (rs, uh) => + rs.continue { + case (ars, fr) => + oneUHResult(fr, uh, province.id).map(ar => ars :+ ar) + } } private def statusChangeResults( @@ -216,12 +205,14 @@ case class PerformUnaffiliatedHeroesAction( ): RandomState[Vector[ActionResult]] = gs.provinces.values.foldLeft( RandomState(Vector[ActionResult](), fr) - ) { case (rs, province) => - rs.continue { case (ars, fr0) => - oneProvinceResult(fr0, province).map { - ars ++ _ + ) { + case (rs, province) => + rs.continue { + case (ars, fr0) => + oneProvinceResult(fr0, province).map { + ars ++ _ + } } - } } private def provincesWithNewHeroes( @@ -233,37 +224,37 @@ case class PerformUnaffiliatedHeroesAction( nextHid: HeroId, acc: RandomState[Vector[(ProvinceId, HeroC, NameInfo)]] ): RandomState[Vector[(ProvinceId, HeroC, NameInfo)]] = - acc.continue { case (innerAcc, fr) => - if toCheck.isEmpty then acc - else - fr.nextDouble match { - case RandomState(d, nextFr) => - if d >= NewHeroChance.doubleValue then - go(toCheck.drop(1), nextHid, RandomState(innerAcc, nextFr)) - else - go( - toCheck.drop(1), - nextHid + 1, - heroGenerator - .getHero( - random = nextFr, - hid = nextHid, - date = currentDate - ) - .map { - case HeroGenerationResponse( - hero, + acc.continue { + case (innerAcc, fr) => + if toCheck.isEmpty then acc + else + fr.nextDouble match { + case RandomState(d, nextFr) => + if d >= NewHeroChance.doubleValue then go(toCheck.drop(1), nextHid, RandomState(innerAcc, nextFr)) + else + go( + toCheck.drop(1), + nextHid + 1, + heroGenerator + .getHero( + random = nextFr, + hid = nextHid, + date = currentDate + ) + .map { + case HeroGenerationResponse( + hero, + nameInfo + ) => + innerAcc :+ ( + toCheck.head, + hero + .copy(id = nextHid), nameInfo - ) => - innerAcc :+ ( - toCheck.head, - hero - .copy(id = nextHid), - nameInfo - ) - } - ) - } + ) + } + ) + } } go( @@ -278,21 +269,21 @@ case class PerformUnaffiliatedHeroesAction( fr: FunctionalRandom ): RandomState[Vector[ActionResultT]] = provincesWithNewHeroes(gs, fr).map { - _.map { case (pid, hero, nameInfo) => - UnaffiliatedHeroAppearedAction( - hero = hero, - provinceId = pid, - gameId = gs.gameId, - allFactionIds = gs.factions.keys.toVector, - currentRoundId = gs.currentRoundId, - currentDate = currentDate, - nameGenerationRequest = - NameGenerationRequestCreator.nameGenerationRequest( + _.map { + case (pid, hero, nameInfo) => + UnaffiliatedHeroAppearedAction( + hero = hero, + provinceId = pid, + gameId = gs.gameId, + allFactionIds = gs.factions.keys.toVector, + currentRoundId = gs.currentRoundId, + currentDate = currentDate, + nameGenerationRequest = NameGenerationRequestCreator.nameGenerationRequest( heroId = hero.id, gameId = gs.gameId, nameInfo = nameInfo ) - ).immediateExecute + ).immediateExecute } } @@ -310,34 +301,34 @@ case class PerformUnaffiliatedHeroesAction( pwrf: Vector[Province], newHeroesMap: Map[HeroId, Hero], functionalRandom: FunctionalRandom - ): RandomState[Vector[ChangedProvince]] = { - functionalRandom.nextFlatMap(pwrf) { case (p, outerFr) => - val oldUH = p.unaffiliatedHeroes - val changedUHRs = outerFr.nextFlatMap(oldUH.toVector) { case (uh, fr) => - LegacyUnaffiliatedHeroUtils - .maybeUpdatedForQuest( - gs = gameState, - pid = p.id, - uh = uh, - hero = - newHeroesMap.getOrElse(uh.heroId, gameState.heroes(uh.heroId)), - functionalRandom = fr - ) - .map(_.toVector) - } + ): RandomState[Vector[ChangedProvince]] = + functionalRandom.nextFlatMap(pwrf) { + case (p, outerFr) => + val oldUH = p.unaffiliatedHeroes + val changedUHRs = outerFr.nextFlatMap(oldUH.toVector) { + case (uh, fr) => + LegacyUnaffiliatedHeroUtils + .maybeUpdatedForQuest( + gs = gameState, + pid = p.id, + uh = uh, + hero = newHeroesMap.getOrElse(uh.heroId, gameState.heroes(uh.heroId)), + functionalRandom = fr + ) + .map(_.toVector) + } - changedUHRs.map { changedUHs => - Option - .when(changedUHs.nonEmpty) { - ChangedProvince( - id = p.id, - changedUnaffiliatedHeroes = changedUHs - ) - } - .toVector - } + changedUHRs.map { changedUHs => + Option + .when(changedUHs.nonEmpty) { + ChangedProvince( + id = p.id, + changedUnaffiliatedHeroes = changedUHs + ) + } + .toVector + } } - } private def provincesWithRulingFactions( gameState: GameState @@ -355,16 +346,16 @@ case class PerformUnaffiliatedHeroesAction( changes = Vector( if LegacyFactionUtils.isFactionLeader(prisoner.heroId, gameState) then prisoner.update( - _.`type` := UNAFFILIATED_HERO_OUTLAW, - _.roundsInType := 0, + _.`type` := UNAFFILIATED_HERO_OUTLAW, + _.roundsInType := 0, _.recruitmentInfo := RecruitmentInfo( status = RECRUITMENT_STATUS_OUTLAW ) ) else prisoner.update( - _.`type` := UNAFFILIATED_HERO_RESIDENT, - _.roundsInType := 0, + _.`type` := UNAFFILIATED_HERO_RESIDENT, + _.roundsInType := 0, _.recruitmentInfo := RecruitmentInfo( status = RECRUITMENT_STATUS_NO_RULER_IN_PROVINCE ) @@ -387,8 +378,8 @@ case class PerformUnaffiliatedHeroesAction( provinceId = provinceId, changes = Vector( uh.update( - _.`type` := UNAFFILIATED_HERO_TRAVELER, - _.roundsInType := 0, + _.`type` := UNAFFILIATED_HERO_TRAVELER, + _.roundsInType := 0, _.recruitmentInfo := RecruitmentInfo( status = RECRUITMENT_STATUS_TRAVELER ) @@ -407,22 +398,22 @@ case class PerformUnaffiliatedHeroesAction( gs: GameState, fr: FunctionalRandom ): RandomState[Option[ActionResult]] = - if LegacyProvinceUtils.hasBlizzard(gs.provinces(fromProvince)) then - RandomState(None, fr) + if LegacyProvinceUtils.hasBlizzard(gs.provinces(fromProvince)) then RandomState(None, fr) else PerformUnaffiliatedHeroesAction .randomMovableNeighbor(gameState, fromProvince, fr) - .continue { case (maybeNeighbor, fr) => - maybeNeighbor - .map(toProvince => - UnaffiliatedHeroMovedAction( - uh = uh, - fromProvinceId = fromProvince, - toProvinceId = toProvince, - gameState = gs - ).immediateExecute(functionalRandom = fr).map(Option(_)) - ) - .getOrElse(RandomState(None, fr)) + .continue { + case (maybeNeighbor, fr) => + maybeNeighbor + .map(toProvince => + UnaffiliatedHeroMovedAction( + uh = uh, + fromProvinceId = fromProvince, + toProvinceId = toProvince, + gameState = gs + ).immediateExecute(functionalRandom = fr).map(Option(_)) + ) + .getOrElse(RandomState(None, fr)) } private def outlawGoHomeResult( @@ -431,10 +422,8 @@ case class PerformUnaffiliatedHeroesAction( gs: GameState, fr: FunctionalRandom ): RandomState[Option[ActionResult]] = - if LegacyProvinceUtils.hasBlizzard(gs.provinces(pid)) then - RandomState(None, fr) - else if uh.lastFaction == gs.provinces(pid).rulingFactionId then - RandomState(None, fr) + if LegacyProvinceUtils.hasBlizzard(gs.provinces(pid)) then RandomState(None, fr) + else if uh.lastFaction == gs.provinces(pid).rulingFactionId then RandomState(None, fr) else uh.lastFaction .flatMap(fid => @@ -475,7 +464,7 @@ case class PerformUnaffiliatedHeroesAction( Some(ActionResultProtoConverter.toProto(orr)), functionalRandom ) - case None => + case None => outlawGoHomeResult(uh, pid, gs, functionalRandom).continue { case (oghrOpt, fr) => oghrOpt match { @@ -522,7 +511,7 @@ case class PerformUnaffiliatedHeroesAction( provinceId = provinceId, changes = Vector( uh.update( - _.`type` := UNAFFILIATED_HERO_RESIDENT, + _.`type` := UNAFFILIATED_HERO_RESIDENT, _.roundsInType := 0 ) ), diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestAction.scala index f507ac4502..f063d74e98 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestAction.scala @@ -1,13 +1,6 @@ package net.eagle0.eagle.library.actions.impl.action -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSequentialResultsAction import net.eagle0.eagle.library.util.faction_utils.FactionUtils import net.eagle0.eagle.library.util.EagleRequire.internalRequire @@ -132,7 +125,7 @@ case class PerformUncontestedConquestAction( removedHostileArmyFactionIds = fids ) +: (for { armyGroup <- multipleArmies - army <- armyGroup.armies + army <- armyGroup.armies } yield ChangedProvinceC( provinceId = army.originProvinceId, newIncomingArmies = Vector( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseAction.scala index d768ed6a41..a79144d0cb 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseAction.scala @@ -2,20 +2,14 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.{FunctionalRandom, MoreOption, RandomState} import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - RestAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, RestAvailableCommand} import net.eagle0.eagle.api.command.OneProvinceAvailableCommands import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.* import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier import net.eagle0.eagle.library.actions.impl.command.CommandFactory -import net.eagle0.eagle.library.actions.impl.common.{ - RandomSequentialResultsAction, - RandomStateProtoSequencer -} +import net.eagle0.eagle.library.actions.impl.common.{RandomSequentialResultsAction, RandomStateProtoSequencer} import net.eagle0.eagle.library.util.command_choice_helpers.CommandChooser import net.eagle0.eagle.library.util.command_choice_helpers.CommandChooserImplicits.* import net.eagle0.eagle.library.util.province.LegacyProvinceUtils @@ -44,23 +38,25 @@ case class PerformVassalCommandsPhaseAction( actionResultProtoApplier = actionResultProtoApplier, functionalRandom = functionalRandom ) - ) { case (sequencer, province) => - sequencer.withRandomActionResults { case (gs, fr) => - chooseCommand(province.id, fr) - .map( - _.map(cs => - commandFactory - .makeCommand( - actingFactionId = cs.actingFactionId, - gameState = GameStateConverter.fromProto(gameState), - availableCommand = cs.available, - selectedCommand = cs.selected - ) - .execute(actionResultProtoApplier) - .map(_.actionResult) - ).getOrElse(Vector()) - ) - } + ) { + case (sequencer, province) => + sequencer.withRandomActionResults { + case (gs, fr) => + chooseCommand(province.id, fr) + .map( + _.map(cs => + commandFactory + .makeCommand( + actingFactionId = cs.actingFactionId, + gameState = GameStateConverter.fromProto(gameState), + availableCommand = cs.available, + selectedCommand = cs.selected + ) + .execute(actionResultProtoApplier) + .map(_.actionResult) + ).getOrElse(Vector()) + ) + } } .actionResults @@ -77,8 +73,9 @@ case class PerformVassalCommandsPhaseAction( .rulingFactionHeroIds .map(gameState.heroes) MoreOption.flatWhen( - commandOptions.collectFirst { case ac: RestAvailableCommand => - ac + commandOptions.collectFirst { + case ac: RestAvailableCommand => + ac }.isDefined && shouldRest(heroes) ) { chosenRestCommand(actingFactionId, gameState, commandOptions, reason) @@ -93,7 +90,7 @@ case class PerformVassalCommandsPhaseAction( provinceId: ProvinceId ): RandomState[Option[CommandSelection]] = gameState.provinces(provinceId).provinceOrders match { - case ENTRUST => + case ENTRUST => chosenEntrustCommand( actingFactionId = actingFactionId, gameState = gameState, @@ -101,7 +98,7 @@ case class PerformVassalCommandsPhaseAction( actingProvinceId = provinceId, functionalRandom = functionalRandom ) - case DEVELOP => + case DEVELOP => chosenDevelopCommand( actingFactionId = actingFactionId, gameState = gameState, @@ -115,14 +112,14 @@ case class PerformVassalCommandsPhaseAction( availableCommands = commandOptions, functionalRandom = functionalRandom ) - case EXPAND => + case EXPAND => chosenExpandCommand( actingFactionId, gameState, commandOptions, functionalRandom ) - case x => + case x => println(s"Command type was $x; defaulting to rest") RandomState( chosenRestCommand( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalDefenseDecisionsAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalDefenseDecisionsAction.scala index 71cffa6bfb..ab0fa3e340 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalDefenseDecisionsAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalDefenseDecisionsAction.scala @@ -23,15 +23,16 @@ case class PerformVassalDefenseDecisionsAction( override def randomResults( functionalRandom: FunctionalRandom, actionResultProtoApplier: ActionResultProtoApplier - ): RandomState[Vector[ActionResult]] = { + ): RandomState[Vector[ActionResult]] = functionalRandom .nextFlatMap( gameState.provinces.values .filter(_.rulingFactionId.isDefined) .filterNot(LegacyProvinceUtils.ruledByFactionLeader(_, gameState)) .toVector - ) { case (p, fr) => - chooseCommand(p.id, fr).map(_.toVector) + ) { + case (p, fr) => + chooseCommand(p.id, fr).map(_.toVector) } .map { _.map(cs => @@ -44,35 +45,33 @@ case class PerformVassalDefenseDecisionsAction( ) ) } - - }.map( - _.flatMap(_.execute(actionResultProtoApplier)) - .map(_.actionResult) - ) + .map( + _.flatMap(_.execute(actionResultProtoApplier)) + .map(_.actionResult) + ) def chooseCommand( provinceId: ProvinceId, functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = - commandsForProvince(provinceId) - .map { oneProvinceAvailableCommands => - val commandOptions = oneProvinceAvailableCommands.commands + commandsForProvince(provinceId).map { oneProvinceAvailableCommands => + val commandOptions = oneProvinceAvailableCommands.commands - resolveTributeSelectedCommand( - actingFactionId = gameState.provinces(provinceId).getRulingFactionId, - gameState = gameState, - availableCommands = commandOptions.toVector, - functionalRandom = functionalRandom - ) match { - case rss @ RandomState(Some(_), _) => rss - case RandomState(None, fr) => - defendSelectedCommand( - gameState.provinces(provinceId).getRulingFactionId, - gameState, - commandOptions.toVector, - fr - ) - } + resolveTributeSelectedCommand( + actingFactionId = gameState.provinces(provinceId).getRulingFactionId, + gameState = gameState, + availableCommands = commandOptions.toVector, + functionalRandom = functionalRandom + ) match { + case rss @ RandomState(Some(_), _) => rss + case RandomState(None, fr) => + defendSelectedCommand( + gameState.provinces(provinceId).getRulingFactionId, + gameState, + commandOptions.toVector, + fr + ) } + } .getOrElse(RandomState(None, functionalRandom)) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeAction.scala index aa2cb9d640..0f17cde954 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeAction.scala @@ -3,14 +3,8 @@ package net.eagle0.eagle.library.actions.impl.action import scala.annotation.tailrec import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} -import net.eagle0.eagle.common.action_result_notification_details.{ - Notification, - PrisonerExchangeDetails -} -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_PRISONER_EXCHANGE_PHASE, - PRISONERS_EXCHANGED -} +import net.eagle0.eagle.common.action_result_notification_details.{Notification, PrisonerExchangeDetails} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_PRISONER_EXCHANGE_PHASE, PRISONERS_EXCHANGED} import net.eagle0.eagle.common.round_phase.NewRoundPhase import net.eagle0.eagle.common.round_phase.RoundPhase.PROVINCE_EVENTS import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFFILIATED_HERO_PRISONER @@ -40,13 +34,13 @@ object PrisonerExchangeAction { gameState: GameState ): Vector[ExchangeableHeroInfo] = (for { - p <- gameState.provinces.values.toVector + p <- gameState.provinces.values.toVector imprisoningFaction <- p.rulingFactionId.toVector - uh <- p.unaffiliatedHeroes + uh <- p.unaffiliatedHeroes if uh.`type` == UNAFFILIATED_HERO_PRISONER hid = uh.heroId prisonerFaction <- uh.lastFaction - faction <- gameState.factions.get(prisonerFaction) + faction <- gameState.factions.get(prisonerFaction) if faction.leaders.contains(hid) isFactionHead = faction.factionHeadId == hid } yield ExchangeableHeroInfo( @@ -77,7 +71,7 @@ object PrisonerExchangeAction { acc :+ ExchangeMatch(head, exchangeMatch), tail diff Vector(exchangeMatch) ) - case None => go(acc, tail) + case None => go(acc, tail) } case _ => acc @@ -89,48 +83,49 @@ object PrisonerExchangeAction { def exchangeResults( exchangeMatches: Vector[ExchangeMatch] ): Vector[ActionResult] = - exchangeMatches.map { case ExchangeMatch(ehi1, ehi2) => - internalRequire( - ehi1.prisonerFactionId == ehi2.imprisoningFactionId && ehi1.imprisoningFactionId == ehi2.prisonerFactionId, - s"Mismatched factions in prisoner exchange" - ) - ActionResult( - `type` = PRISONERS_EXCHANGED, - changedHeroes = Vector( - ChangedHero( - id = ehi1.hid, - newFactionId = Some(ehi1.prisonerFactionId) + exchangeMatches.map { + case ExchangeMatch(ehi1, ehi2) => + internalRequire( + ehi1.prisonerFactionId == ehi2.imprisoningFactionId && ehi1.imprisoningFactionId == ehi2.prisonerFactionId, + s"Mismatched factions in prisoner exchange" + ) + ActionResult( + `type` = PRISONERS_EXCHANGED, + changedHeroes = Vector( + ChangedHero( + id = ehi1.hid, + newFactionId = Some(ehi1.prisonerFactionId) + ), + ChangedHero( + id = ehi2.hid, + newFactionId = Some(ehi2.prisonerFactionId) + ) ), - ChangedHero( - id = ehi2.hid, - newFactionId = Some(ehi2.prisonerFactionId) - ) - ), - changedProvinces = Vector( - ChangedProvince( - id = ehi1.pid, - removedUnaffiliatedHeroIds = Vector(ehi1.hid), - addedRulingPlayerHeroIds = Vector(ehi2.hid) + changedProvinces = Vector( + ChangedProvince( + id = ehi1.pid, + removedUnaffiliatedHeroIds = Vector(ehi1.hid), + addedRulingPlayerHeroIds = Vector(ehi2.hid) + ), + ChangedProvince( + id = ehi2.pid, + removedUnaffiliatedHeroIds = Vector(ehi2.hid), + addedRulingPlayerHeroIds = Vector(ehi1.hid) + ) ), - ChangedProvince( - id = ehi2.pid, - removedUnaffiliatedHeroIds = Vector(ehi2.hid), - addedRulingPlayerHeroIds = Vector(ehi1.hid) - ) - ), - notificationsToDeliver = Vector( - Notification( - details = PrisonerExchangeDetails( - hero1Id = ehi1.hid, - hero1FactionId = ehi1.prisonerFactionId, - hero1ProvinceId = ehi1.pid, - hero2Id = ehi2.hid, - hero2FactionId = ehi2.prisonerFactionId, - hero2ProvinceId = ehi2.pid + notificationsToDeliver = Vector( + Notification( + details = PrisonerExchangeDetails( + hero1Id = ehi1.hid, + hero1FactionId = ehi1.prisonerFactionId, + hero1ProvinceId = ehi1.pid, + hero2Id = ehi2.hid, + hero2FactionId = ehi2.prisonerFactionId, + hero2ProvinceId = ehi2.pid + ) ) ) ) - ) } val endPhaseAr: ActionResult = ActionResult( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredAction.scala index 27506093db..283d2e6e55 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredAction.scala @@ -1,13 +1,6 @@ package net.eagle0.eagle.library.actions.impl.action -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.library.actions.generated_text_request_generators.captured_hero_helpers.CapturedHeroPleaGenerator import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.settings.FreedPrisonerLoyalty @@ -35,10 +28,7 @@ import net.eagle0.eagle.model.state.hero.ReleasedByProvinceCaptureBackstoryEvent import net.eagle0.eagle.model.state.province.ProvinceOrderType.Entrust import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Prisoner -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Prisoner} import net.eagle0.eagle.model.state.unit_status.UnitStatus import net.eagle0.eagle.model.state.CapturedHero import net.eagle0.eagle.model.state.CombatUnit @@ -96,39 +86,35 @@ case class ProvinceConqueredAction( battalions: Map[BattalionId, BattalionT], provinces: Map[ProvinceId, ProvinceT] ) extends ProtolessSimpleAction { - private def invalidatedRansomFactions: Vector[ChangedFactionC] = { - conqueredProvince.rulingFactionId - .map { rfid => - val incomingRansomOffers = factions - .get(rfid) - .map(_.incomingDiplomacyOffers) - .getOrElse(Vector.empty) - .collect { - case offer: RansomOffer - if offer.prisonerToBeRansomed.provinceIdForPrisoner == conqueredProvince.id => - offer - } - - if incomingRansomOffers.nonEmpty then { - Vector( - ChangedFactionC( - factionId = rfid, - removedIncomingDiplomacyOfferFactionIds = - incomingRansomOffers.map(_.originatingFactionId).toVector, - newIncomingDiplomacyOffers = incomingRansomOffers - .map(_.withStatus(Invalidated)) - .toVector - ) - ) - } else { - Vector.empty + private def invalidatedRansomFactions: Vector[ChangedFactionC] = + conqueredProvince.rulingFactionId.map { rfid => + val incomingRansomOffers = factions + .get(rfid) + .map(_.incomingDiplomacyOffers) + .getOrElse(Vector.empty) + .collect { + case offer: RansomOffer if offer.prisonerToBeRansomed.provinceIdForPrisoner == conqueredProvince.id => + offer } + + if incomingRansomOffers.nonEmpty then { + Vector( + ChangedFactionC( + factionId = rfid, + removedIncomingDiplomacyOfferFactionIds = incomingRansomOffers.map(_.originatingFactionId).toVector, + newIncomingDiplomacyOffers = incomingRansomOffers + .map(_.withStatus(Invalidated)) + .toVector + ) + ) + } else { + Vector.empty } + } .getOrElse(Vector.empty) - } override def immediateExecute: ActionResultT = { - val attackingPlayerId = notFledConquerors.head.hero.factionId.get + val attackingPlayerId = notFledConquerors.head.hero.factionId.get val seniorConquerorHeroId = notFledConquerors .map(_.hero) .min(HeroUtils.sortOrdering(factions(attackingPlayerId).leaderIds)) @@ -170,10 +156,8 @@ case class ProvinceConqueredAction( ChangedProvinceC( provinceId = conqueredProvince.id, newRulingFactionId = Some(attackingPlayerId), - removedRulingFactionHeroIds = - conqueredProvince.rulingFactionHeroIds.toVector, - newRulingFactionHeroIds = - notFledConquerors.toVector.map(_.hero.id), + removedRulingFactionHeroIds = conqueredProvince.rulingFactionHeroIds.toVector, + newRulingFactionHeroIds = notFledConquerors.toVector.map(_.hero.id), removedBattalionIds = conqueredProvince.battalionIds.toVector, removedHostileArmyFactionIds = Vector(attackingPlayerId), newBattalionIds = notFledConquerors @@ -195,31 +179,29 @@ case class ProvinceConqueredAction( ) ), newNotifications = Vector( - defendingFactionId - .map { defendingFid => - NotificationC( - deferred = true, - details = NotificationDetails.ProvinceConquered( - provinceId = conqueredProvince.id, - conqueringFactionId = attackingPlayerId, - otherAttackingFactionIds = notFledConquerors - .map(_.hero.factionId.get) - .distinct - .filterNot(_ == attackingPlayerId) - .toVector, - defendingFactionId = defendingFid - ) + defendingFactionId.map { defendingFid => + NotificationC( + deferred = true, + details = NotificationDetails.ProvinceConquered( + provinceId = conqueredProvince.id, + conqueringFactionId = attackingPlayerId, + otherAttackingFactionIds = notFledConquerors + .map(_.hero.factionId.get) + .distinct + .filterNot(_ == attackingPlayerId) + .toVector, + defendingFactionId = defendingFid ) - } - .getOrElse { - NotificationC( - deferred = true, - details = NotificationDetails.ProvinceExpansion( - provinceId = conqueredProvince.id, - expandingFactionId = attackingPlayerId - ) + ) + }.getOrElse { + NotificationC( + deferred = true, + details = NotificationDetails.ProvinceExpansion( + provinceId = conqueredProvince.id, + expandingFactionId = attackingPlayerId ) - } + ) + } ) ) ) @@ -252,8 +234,7 @@ case class ProvinceConqueredAction( .filter(_.rulingFactionId.contains(alliedFid)) .map(_.id) .toVector, - eligibleNeighbors = - pid => provinces(pid).neighbors.map(_.provinceId).toVector + eligibleNeighbors = pid => provinces(pid).neighbors.map(_.provinceId).toVector ) .map(_.provinceId) .map { targetPid => @@ -269,8 +250,7 @@ case class ProvinceConqueredAction( .withChangedProvince( ChangedProvinceC( provinceId = targetPid, - newRulingFactionHeroIds = - prisonersFromFaction.toVector.map(_.heroId) + newRulingFactionHeroIds = prisonersFromFaction.toVector.map(_.heroId) ) ) .withChangedHeroes( @@ -296,11 +276,10 @@ case class ProvinceConqueredAction( .copy( changedProvinces = actionResult.changedProvinces match { case (headCp: ChangedProvinceC) +: tail => - headCp.withChangedUnaffiliatedHeroes(prisonersFromFaction.map { - uh => - uh.copy(unaffiliatedHeroType = Outlaw) + headCp.withChangedUnaffiliatedHeroes(prisonersFromFaction.map { uh => + uh.copy(unaffiliatedHeroType = Outlaw) }.toVector) +: tail - case _ => + case _ => throw new EagleInternalException( "Expected at least one changed province" ) @@ -333,8 +312,9 @@ case class ProvinceConqueredAction( _.relationshipLevel == RelationshipLevel.Ally ) .map(_.targetFactionId) - .foldLeft(actionResult) { case (acc, alliedFid) => - afterFreeingAlliedPrisonersFromOneFaction(acc, alliedFid) + .foldLeft(actionResult) { + case (acc, alliedFid) => + afterFreeingAlliedPrisonersFromOneFaction(acc, alliedFid) } private def afterFreeingPrisoners( @@ -357,7 +337,7 @@ case class ProvinceConqueredAction( .withRulingFactionHeroIds( afterFreeingPrisoners.toVector.map(_.heroId) ) +: tail - case _ => + case _ => throw new EagleInternalException( "Expected at least one changed province" ) @@ -389,15 +369,12 @@ case class ProvinceConqueredAction( case cp: ChangedProvinceC => cp }.get - val remainingUHs = conqueredProvince.unaffiliatedHeroes.filterNot(uh => - headCp.removedUnaffiliatedHeroIds.contains(uh.heroId) - ) + val remainingUHs = + conqueredProvince.unaffiliatedHeroes.filterNot(uh => headCp.removedUnaffiliatedHeroIds.contains(uh.heroId)) val changedUHs = remainingUHs - .map(uh => - uh.copy(recruitmentInfo = RecruitmentInfo.NotDivined) - ) // Clear recruitment info + .map(uh => uh.copy(recruitmentInfo = RecruitmentInfo.NotDivined)) // Clear recruitment info actionResult.copy( changedProvinces = headCp.copy( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldAction.scala index 10f8358227..4086f92d5e 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldAction.scala @@ -5,10 +5,7 @@ import net.eagle0.eagle.library.actions.generated_text_request_generators.captur import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, NotificationC} import net.eagle0.eagle.model.action_result.types.ProvinceHeldResultType import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.CapturedHero diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesAction.scala index d6b774fd38..bc8276ab95 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesAction.scala @@ -2,42 +2,20 @@ package net.eagle0.eagle.library.actions.impl.action import scala.util.hashing.MurmurHash3 -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSequentialResultsAction import net.eagle0.eagle.library.util.BattalionUtils import net.eagle0.eagle.library.util.EagleRequire.internalRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.concrete.ActionResultC -import net.eagle0.eagle.model.action_result.types.{ - SentSuppliesResultType, - StartBattleResultType -} +import net.eagle0.eagle.model.action_result.types.{SentSuppliesResultType, StartBattleResultType} import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.{ - Army, - BattalionType, - BattalionTypeId, - HostileArmyGroup, - MovingArmy, - Supplies -} +import net.eagle0.eagle.model.state.{Army, BattalionType, BattalionTypeId, HostileArmyGroup, MovingArmy, Supplies} import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.HeroT import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.shardok_battle.{ - BattleType, - ShardokBattle, - ShardokPlayer, - VictoryCondition -} +import net.eagle0.eagle.model.state.shardok_battle.{BattleType, ShardokBattle, ShardokPlayer, VictoryCondition} import net.eagle0.eagle.model.state.unit_status.UnitStatus import net.eagle0.eagle.model.state.HostileArmyGroupStatus.Attacking import net.eagle0.eagle.shardok_interface.ResolvedEagleUnit @@ -54,8 +32,7 @@ case class RequestBattlesAction( battalionTypes: Map[BattalionTypeId, BattalionType] ) extends ProtolessSequentialResultsAction { override def results: Vector[ActionResultT] = - provincesWithAttackingArmies.zipWithIndex - .flatMap { case (pwaas, idx) => handleOneProvince(pwaas, idx) } + provincesWithAttackingArmies.zipWithIndex.flatMap { case (pwaas, idx) => handleOneProvince(pwaas, idx) } private def handleOneProvince( provinceWithAttackingArmies: ProvinceWithAttackingArmies, @@ -129,7 +106,7 @@ case class RequestBattlesAction( ) ) - def defenderFood(province: ProvinceT): Int = { + def defenderFood(province: ProvinceT): Int = Math.min( BattalionUtils.monthlyConsumedFood( battalions = province.defendingArmy.toVector @@ -140,7 +117,6 @@ case class RequestBattlesAction( ), province.food ) - } private def battleHash( battleProvinceId: ProvinceId, @@ -213,7 +189,7 @@ case class RequestBattlesAction( ) } - def attackerFood(armyGroup: HostileArmyGroup): Int = { + def attackerFood(armyGroup: HostileArmyGroup): Int = Math.min( BattalionUtils.monthlyConsumedFood( battalions = armyGroup.armies @@ -224,11 +200,10 @@ case class RequestBattlesAction( ), armyGroup.armies.map(_.supplies.food).sum ) - } private def uncontestedAttackResults( provinceWithAttackingArmies: ProvinceWithAttackingArmies - ): Vector[ActionResultT] = { + ): Vector[ActionResultT] = Vector( ActionResultC( actionResultType = SentSuppliesResultType, @@ -269,20 +244,16 @@ case class RequestBattlesAction( ) ), notFledDefenders = Vector.empty, - destroyedBattalions = - provinces(provinceWithAttackingArmies.provinceId).battalionIds, - defendingFactionId = - provinces(provinceWithAttackingArmies.provinceId).rulingFactionId, + destroyedBattalions = provinces(provinceWithAttackingArmies.provinceId).battalionIds, + defendingFactionId = provinces(provinceWithAttackingArmies.provinceId).rulingFactionId, factions = factions, heroes = heroes, battalions = battalions, provinces = provinces ).immediateExecute ) - } - private def provincesWithAttackingArmies - : Vector[ProvinceWithAttackingArmies] = + private def provincesWithAttackingArmies: Vector[ProvinceWithAttackingArmies] = provinces.values .filter(_.hostileArmies.nonEmpty) .map(p => diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestFreeForAllBattlesAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestFreeForAllBattlesAction.scala index 951d8937b6..9e470cec81 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestFreeForAllBattlesAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/RequestFreeForAllBattlesAction.scala @@ -26,7 +26,7 @@ case class RequestFreeForAllBattlesAction(startingGameState: GameState) override def results( actionResultProtoApplier: ActionResultProtoApplier - ): Vector[ActionResult] = { + ): Vector[ActionResult] = startingGameState.provinces.values .filter( _.hostileArmies.exists( @@ -34,20 +34,20 @@ case class RequestFreeForAllBattlesAction(startingGameState: GameState) ) ) .zipWithIndex - .map { case (province, index) => - CommenceImminentBattle( - eagleGameId = startingGameState.gameId, - battleIndex = startingGameState.battleCounter + index + 1, - roundId = startingGameState.currentRoundId, - battleProvince = startingGameState.provinces(province.id), - armies = province.hostileArmies - .filter(_.status.asMessage.sealedValue.isAwaitingFreeForAll) - .toVector, - battalionTypes = startingGameState.battalionTypes.toVector - ) + .map { + case (province, index) => + CommenceImminentBattle( + eagleGameId = startingGameState.gameId, + battleIndex = startingGameState.battleCounter + index + 1, + roundId = startingGameState.currentRoundId, + battleProvince = startingGameState.provinces(province.id), + armies = province.hostileArmies + .filter(_.status.asMessage.sealedValue.isAwaitingFreeForAll) + .toVector, + battalionTypes = startingGameState.battalionTypes.toVector + ) } .toVector - } private def CommenceImminentBattle( eagleGameId: GameId, @@ -74,8 +74,7 @@ case class RequestFreeForAllBattlesAction(startingGameState: GameState) battleIndex = battleIndex, battleType = BattleType.BATTLE_TYPE_FREE_FOR_ALL, players = armies.map(shardokPlayer).toVector, - hexMapName = - battleProvince.hexMapName, // FIXME: this should be fought on a "neutral" map" + hexMapName = battleProvince.hexMapName, // FIXME: this should be fought on a "neutral" map" eagleGameId = eagleGameId, defenderProvince = battleProvince.id, roundStarted = startingGameState.currentRoundId @@ -86,7 +85,7 @@ case class RequestFreeForAllBattlesAction(startingGameState: GameState) def defenderFood( province: Province, battalionTypes: Vector[BattalionType] - ): Int = { + ): Int = Math.min( LegacyBattalionUtils.monthlyConsumedFood( province.defendingArmy @@ -99,7 +98,6 @@ case class RequestFreeForAllBattlesAction(startingGameState: GameState) ), province.food ) - } private def battleHash( battleProvinceId: ProvinceId, @@ -120,11 +118,10 @@ case class RequestFreeForAllBattlesAction(startingGameState: GameState) isDefender = false, armyGroup = Some(armyGroup), food = attackerFood(armyGroup), - victoryConditions = - Vector(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING) + victoryConditions = Vector(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING) ) - def attackerFood(armyGroup: HostileArmyGroup): Int = { + def attackerFood(armyGroup: HostileArmyGroup): Int = Math.min( LegacyBattalionUtils.monthlyConsumedFood( battalions = armyGroup.armies @@ -135,5 +132,4 @@ case class RequestFreeForAllBattlesAction(startingGameState: GameState) ), armyGroup.armies.map(_.supplies.map(_.food).getOrElse(0)).sum ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleAction.scala index c1d8a6c392..7040e71715 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleAction.scala @@ -24,10 +24,7 @@ import net.eagle0.eagle.internal.battle_revelation.BattleRevelation.RevelationTy import net.eagle0.eagle.internal.changed_hero.ChangedHero import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor import net.eagle0.eagle.internal.changed_province.ChangedProvince -import net.eagle0.eagle.internal.event_for_hero_backstory.{ - EventForHeroBackstory, - FoughtInBattleBackstoryEvent -} +import net.eagle0.eagle.internal.event_for_hero_backstory.{EventForHeroBackstory, FoughtInBattleBackstoryEvent} import net.eagle0.eagle.internal.event_for_hero_backstory.FoughtInBattleBackstoryEvent.UnitStatus.{ UNIT_STATUS_CAPTURED, UNIT_STATUS_FLED, @@ -43,14 +40,8 @@ import net.eagle0.eagle.internal.shardok_battle.ShardokBattle.BattleType import net.eagle0.eagle.internal.shardok_battle.ShardokBattle.BattleType.BATTLE_TYPE_ASSAULT_PROVINCE import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.action.{ - ProvinceConqueredAction, - ProvinceHeldAction -} -import net.eagle0.eagle.library.actions.impl.common.{ - Action, - ActionWithResultingState -} +import net.eagle0.eagle.library.actions.impl.action.{ProvinceConqueredAction, ProvinceHeldAction} +import net.eagle0.eagle.library.actions.impl.common.{Action, ActionWithResultingState} import net.eagle0.eagle.library.actions.util.ShatteredArmyUtils import net.eagle0.eagle.library.settings.{ BattleAgricultureDevastationDelta, @@ -63,11 +54,7 @@ import net.eagle0.eagle.library.util.view_filters.LegacyBattalionViewFilter import net.eagle0.eagle.library.util.EagleRequire.internalRequire import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.proto_converters.{ - ActionResultProtoConverter, - ArmyConverter, - ChangedProvinceConverter -} +import net.eagle0.eagle.model.proto_converters.{ActionResultProtoConverter, ArmyConverter, ChangedProvinceConverter} import net.eagle0.eagle.model.proto_converters.date.DateConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.hero.HeroConverter @@ -78,11 +65,7 @@ import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.DefeatFactionQuest import net.eagle0.eagle.model.state.quest.QuestT import net.eagle0.eagle.model.state.unit_status.UnitStatus as ModelUnitStatus -import net.eagle0.eagle.shardok_interface.{ - BattleResolution, - ResolvedEagleUnit, - ResolvedShardokPlayer -} +import net.eagle0.eagle.shardok_interface.{BattleResolution, ResolvedEagleUnit, ResolvedShardokPlayer} case class ResolveBattleAction( startingGameState: GameState, @@ -104,24 +87,24 @@ case class ResolveBattleAction( actionResultProtoApplier: ActionResultProtoApplier ): Vector[ActionWithResultingState] = for { - rb <- resolvedBattles - sb <- outstandingBattle( - startingGameState.outstandingBattles.toVector, - rb - ).toVector + rb <- resolvedBattles + sb <- outstandingBattle( + startingGameState.outstandingBattles.toVector, + rb + ).toVector res <- resolveOneBattle( - startingState = startingGameState, - actionResultProtoApplier = actionResultProtoApplier, - battle = sb, - battleResolution = rb - ) + startingState = startingGameState, + actionResultProtoApplier = actionResultProtoApplier, + battle = sb, + battleResolution = rb + ) } yield res private def newOutlaws( battleResolution: BattleResolution ): Vector[UnaffiliatedHero] = (for { - rsp <- battleResolution.resolvedPlayers + rsp <- battleResolution.resolvedPlayers outlaw <- rsp.units.filter(_.status == ModelUnitStatus.Outlawed) } yield UnaffiliatedHero( heroId = outlaw.hero.id, @@ -143,8 +126,7 @@ case class ResolveBattleAction( ChangedProvince( id = battle.defenderProvince, newUnaffiliatedHeroes = newOutlaws(battleResolution), - removedHostileArmyFactionIds = - battle.players.filterNot(_.isDefender).map(_.eagleFid), + removedHostileArmyFactionIds = battle.players.filterNot(_.isDefender).map(_.eagleFid), removedRulingPlayerHeroIds = (for { rsp <- battleResolution.resolvedPlayers if startingGameState @@ -152,8 +134,8 @@ case class ResolveBattleAction( .rulingFactionId .contains(rsp.eagleFid) rse <- rsp.units - in <- battle.players - .find(sp => rse.hero.factionId.contains(sp.eagleFid)) + in <- battle.players + .find(sp => rse.hero.factionId.contains(sp.eagleFid)) if unitReturned( hid = rse.hero.id, in = in, @@ -168,8 +150,8 @@ case class ResolveBattleAction( .rulingFactionId .contains(rsp.eagleFid) rse <- rsp.units - in <- battle.players - .find(sp => rse.hero.factionId.contains(sp.eagleFid)) + in <- battle.players + .find(sp => rse.hero.factionId.contains(sp.eagleFid)) if unitReturned( hid = rse.hero.id, in = in, @@ -192,18 +174,15 @@ case class ResolveBattleAction( .sum ), economyDevastationDelta = Some(BattleEconomyDevastationDelta.doubleValue), - agricultureDevastationDelta = - Some(BattleAgricultureDevastationDelta.doubleValue), - infrastructureDevastationDelta = - Some(BattleInfrastructureDevastationDelta.doubleValue), - addedBattleRevelations = - battle.players.filterNot(_.isDefender).map { sp => - BattleRevelation( - provinceId = battle.defenderProvince, - revealedToFactionId = sp.eagleFid, - revelationType = DID_BATTLE - ) - } + agricultureDevastationDelta = Some(BattleAgricultureDevastationDelta.doubleValue), + infrastructureDevastationDelta = Some(BattleInfrastructureDevastationDelta.doubleValue), + addedBattleRevelations = battle.players.filterNot(_.isDefender).map { sp => + BattleRevelation( + provinceId = battle.defenderProvince, + revealedToFactionId = sp.eagleFid, + revelationType = DID_BATTLE + ) + } ) private def defeatLoserQuestCompletionCheck( @@ -213,7 +192,7 @@ case class ResolveBattleAction( q match { case DefeatFactionQuest(targetFactionId) => losingFids.contains(targetFactionId) - case _ => false + case _ => false } private def winnersFulfilledQuestActionResults( @@ -225,20 +204,15 @@ case class ResolveBattleAction( ) match { case (winners, losers) => winners - .flatMap(rsp => - LegacyFactionUtils.provinces(rsp.eagleFid, startingState) - ) + .flatMap(rsp => LegacyFactionUtils.provinces(rsp.eagleFid, startingState)) .flatMap(p => QuestFulfillmentUtils.fulfilledQuestResults( province = ProvinceConverter.fromProto(p), - isFulfilled = - defeatLoserQuestCompletionCheck(losers.map(_.eagleFid)), + isFulfilled = defeatLoserQuestCompletionCheck(losers.map(_.eagleFid)), gameId = startingState.gameId, currentDate = DateConverter.fromProto(startingState.currentDate), currentRoundId = startingState.currentRoundId, - previousBackstoryTextIdLookup = hid => { - startingState.heroes(hid).backstoryVersions.last.textId - } + previousBackstoryTextIdLookup = hid => startingState.heroes(hid).backstoryVersions.last.textId ) ) } @@ -246,29 +220,29 @@ case class ResolveBattleAction( private def verifyHidsOutMatchHidsIn( battle: ShardokBattle, battleResolution: BattleResolution - ): Unit = { + ): Unit = battle.players .sortBy(_.eagleFid) .zip(battleResolution.resolvedPlayers.sortBy(_.eagleFid)) - .foreach { case (setup, resolved) => - internalRequire( - resolved.eagleFid == setup.eagleFid, - s"FactionIds do not match for all players in ${battle.players}, ${battleResolution.resolvedPlayers}" - ) + .foreach { + case (setup, resolved) => + internalRequire( + resolved.eagleFid == setup.eagleFid, + s"FactionIds do not match for all players in ${battle.players}, ${battleResolution.resolvedPlayers}" + ) - val sentHids = - setup.getArmyGroup.armies - .flatMap(_.getArmy.units) - .map(_.heroId) - .toSet - val returnedHids = resolved.units.map(_.hero.id).toSet + val sentHids = + setup.getArmyGroup.armies + .flatMap(_.getArmy.units) + .map(_.heroId) + .toSet + val returnedHids = resolved.units.map(_.hero.id).toSet - internalRequire( - sentHids == returnedHids, - s"Sent $sentHids into battle but got $returnedHids back" - ) + internalRequire( + sentHids == returnedHids, + s"Sent $sentHids into battle but got $returnedHids back" + ) } - } private def battleEndedARs( startingState: GameState, @@ -365,7 +339,7 @@ case class ResolveBattleAction( .flatMap(fid => battle.players.find(_.eagleFid == fid)) val finalResult = battle.battleType match { - case BattleType.BATTLE_TYPE_UNKNOWN => + case BattleType.BATTLE_TYPE_UNKNOWN => throw new EagleInternalException("Unknown battle type") case BattleType.BATTLE_TYPE_ASSAULT_PROVINCE => internalRequire( @@ -375,7 +349,7 @@ case class ResolveBattleAction( val wsp = winningShardokPlayers.head if wsp.isDefender then - val gs = battleEndedResults.last.gameState + val gs = battleEndedResults.last.gameState val defendingProv = gs.provinces(battle.defenderProvince) val capturedUnits = battleResolution.resolvedPlayers.toVector .filterNot(_.eagleFid == wsp.eagleFid) @@ -408,7 +382,7 @@ case class ResolveBattleAction( .toMap ) else { - val gs = battleEndedResults.last.gameState + val gs = battleEndedResults.last.gameState val conqueredProv = gs.provinces(battle.defenderProvince) ProvinceConqueredAction( gameId = gs.gameId, @@ -427,11 +401,8 @@ case class ResolveBattleAction( .filterNot(_.status == ModelUnitStatus.Outlawed) .map(u => ResolvedEagleUnit( - hero = - HeroConverter.fromProto(startingState.heroes(u.hero.id)), - battalion = u.battalion.map(b => - BattalionConverter.fromProto(startingState.battalions(b.id)) - ), + hero = HeroConverter.fromProto(startingState.heroes(u.hero.id)), + battalion = u.battalion.map(b => BattalionConverter.fromProto(startingState.battalions(b.id))), status = u.status ) ) @@ -439,37 +410,31 @@ case class ResolveBattleAction( notFledDefenders = (for { sp <- battle.players.filter(_.isDefender) rsp = battleResolution.resolvedPlayers - .find(_.eagleFid == sp.eagleFid) - .get + .find(_.eagleFid == sp.eagleFid) + .get u <- rsp.units.filterNot(u => - unitReturned( - hid = u.hero.id, - in = sp, - out = rsp, - battleType = BATTLE_TYPE_ASSAULT_PROVINCE - ) - ) + unitReturned( + hid = u.hero.id, + in = sp, + out = rsp, + battleType = BATTLE_TYPE_ASSAULT_PROVINCE + ) + ) } yield ResolvedEagleUnit( hero = HeroConverter.fromProto(startingState.heroes(u.hero.id)), - battalion = u.battalion.map(b => - BattalionConverter.fromProto(startingState.battalions(b.id)) - ), + battalion = u.battalion.map(b => BattalionConverter.fromProto(startingState.battalions(b.id))), status = u.status )).toVector, destroyedBattalions = destroyedBattalionIds(battleResolution), - defendingFactionId = - battle.players.find(_.isDefender).map(_.eagleFid), - factions = - gs.factions.view.mapValues(FactionConverter.fromProto).toMap, + defendingFactionId = battle.players.find(_.isDefender).map(_.eagleFid), + factions = gs.factions.view.mapValues(FactionConverter.fromProto).toMap, heroes = gs.heroes.view.mapValues(HeroConverter.fromProto).toMap, - battalions = - gs.battalions.view.mapValues(BattalionConverter.fromProto).toMap, - provinces = - gs.provinces.view.mapValues(ProvinceConverter.fromProto).toMap + battalions = gs.battalions.view.mapValues(BattalionConverter.fromProto).toMap, + provinces = gs.provinces.view.mapValues(ProvinceConverter.fromProto).toMap ) } end if - case BattleType.BATTLE_TYPE_FREE_FOR_ALL => + case BattleType.BATTLE_TYPE_FREE_FOR_ALL => Option .when(winningShardokPlayers.nonEmpty) { WonFreeForAllAction( @@ -518,9 +483,9 @@ case class ResolveBattleAction( } ) ) - case BattleType.BATTLE_TYPE_SALLY => + case BattleType.BATTLE_TYPE_SALLY => throw new EagleInternalException("Sally battle unimplemented") - case BattleType.Unrecognized(value) => + case BattleType.Unrecognized(value) => throw new EagleInternalException(s"Unrecognized battle type $value") } @@ -541,9 +506,7 @@ case class ResolveBattleAction( .map(_.id) .filterNot(_ == 0) ++ battleResolution.resolvedPlayers .flatMap(_.units) - .filter(unit => - unit.status == ModelUnitStatus.Captured || unit.status == ModelUnitStatus.Outlawed - ) + .filter(unit => unit.status == ModelUnitStatus.Captured || unit.status == ModelUnitStatus.Outlawed) .flatMap(_.optionalBattalionId) .filterNot(_ == 0)).toVector @@ -583,14 +546,11 @@ case class ResolveBattleAction( ChangedHero( id = newHero.id, vigor = Vigor.VigorAbsolute(newHero.vigor), - strengthXpDelta = - maybeDelta(newHero.strengthXp, originalHero.strengthXp), + strengthXpDelta = maybeDelta(newHero.strengthXp, originalHero.strengthXp), agilityXpDelta = maybeDelta(newHero.agilityXp, originalHero.agilityXp), wisdomXpDelta = maybeDelta(newHero.wisdomXp, originalHero.wisdomXp), - charismaXpDelta = - maybeDelta(newHero.charismaXp, originalHero.charismaXp), - constitutionXpDelta = - maybeDelta(newHero.constitutionXp, originalHero.constitutionXp), + charismaXpDelta = maybeDelta(newHero.charismaXp, originalHero.charismaXp), + constitutionXpDelta = maybeDelta(newHero.constitutionXp, originalHero.constitutionXp), newBackstoryEvents = backstoryEvent.toVector ) } @@ -603,14 +563,14 @@ case class ResolveBattleAction( (for { sp <- batt.players rsp = br.resolvedPlayers.find(_.eagleFid == sp.eagleFid).get - ma <- sp.getArmyGroup.armies + ma <- sp.getArmyGroup.armies army <- armyFromResolvedArmy( - ma = ma, - sp = sp, - rsp = rsp, - bt = batt.battleType, - destroyedBattalionIds = destroyedBattalionIds - ) + ma = ma, + sp = sp, + rsp = rsp, + bt = batt.battleType, + destroyedBattalionIds = destroyedBattalionIds + ) } yield ma.getArmy.fleeProvinceId .map(fleeProvince => changedProvinceFromFledUnits( @@ -636,17 +596,14 @@ case class ResolveBattleAction( ): Option[Army] = armyFromResolvedUnits( units = ma.getArmy.units - .filter(u => - unitReturned(hid = u.heroId, in = sp, out = rsp, battleType = bt) - ) + .filter(u => unitReturned(hid = u.heroId, in = sp, out = rsp, battleType = bt)) .flatMap(cu => rsp.units.find(_.hero.id == cu.heroId)) .toVector, removedBattalionIds = destroyedBattalionIds, fid = ma.getArmy.factionId, - fleeProvinceId = - Option.when(rsp.endGameCondition.condition.isAllyVictory)( - ma.destinationProvince - ) + fleeProvinceId = Option.when(rsp.endGameCondition.condition.isAllyVictory)( + ma.destinationProvince + ) ) private def armyFromResolvedUnits( @@ -725,12 +682,12 @@ case class ResolveBattleAction( .fleeProvinceId .isDefined && !out.endGameCondition.condition.isVictory - case ModelUnitStatus.Captured => + case ModelUnitStatus.Captured => out.endGameCondition.condition.isDraw || out.endGameCondition.condition.isAllyVictory - case ModelUnitStatus.Normal => + case ModelUnitStatus.Normal => out.endGameCondition.condition.isDraw || out.endGameCondition.condition.isAllyVictory - case ModelUnitStatus.Retreated => false - case ModelUnitStatus.Outlawed => false + case ModelUnitStatus.Retreated => false + case ModelUnitStatus.Outlawed => false } private def outstandingBattle( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedAction.scala index a89c1c3658..191f2079e3 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedAction.scala @@ -16,18 +16,16 @@ case class SafePassageArmiesProceedAction( ) extends ProtolessSequentialResultsAction { override def results: Vector[ActionResultT] = provinces.flatMap { p => - p.hostileArmies - .collect { - case ha @ HostileArmyGroup( - _, - _, - SafePassageGranted(_) - ) => - ha - } - .map { ha => - oneArmyProceeds(p, ha) - } + p.hostileArmies.collect { + case ha @ HostileArmyGroup( + _, + _, + SafePassageGranted(_) + ) => + ha + }.map { ha => + oneArmyProceeds(p, ha) + } } private def oneArmyProceeds( @@ -61,7 +59,7 @@ case class SafePassageArmiesProceedAction( ) ) ) - case _ => + case _ => throw new IllegalStateException( s"Expected SafePassageGranted status, got ${ha.status}" ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseAction.scala index 7db618eec3..ac4f84b667 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseAction.scala @@ -12,15 +12,11 @@ import net.eagle0.eagle.internal.changed_province.ChangedProvince.HostileArmyGro import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - RandomSequentialResultsAction, - RandomStateProtoSequencer -} +import net.eagle0.eagle.library.actions.impl.common.{RandomSequentialResultsAction, RandomStateProtoSequencer} import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.model.proto_converters.province.ProvinceConverter -case class TruceTurnBackPhaseAction(startingState: GameState) - extends RandomSequentialResultsAction(startingState) { +case class TruceTurnBackPhaseAction(startingState: GameState) extends RandomSequentialResultsAction(startingState) { private def checkOneAttackingArmyGroup( attackingArmyGroup: HostileArmyGroup, @@ -56,30 +52,27 @@ case class TruceTurnBackPhaseAction(startingState: GameState) } private def checkOneProvince(province: Province): Vector[ActionResult] = - province.rulingFactionId - .map { defendingFid => - province.hostileArmies.flatMap { attackingArmy => - checkOneAttackingArmyGroup( - attackingArmyGroup = attackingArmy, - defendingFid = defendingFid, - provinceId = province.id - ) - }.toVector - } + province.rulingFactionId.map { defendingFid => + province.hostileArmies.flatMap { attackingArmy => + checkOneAttackingArmyGroup( + attackingArmyGroup = attackingArmy, + defendingFid = defendingFid, + provinceId = province.id + ) + }.toVector + } .getOrElse(Vector()) override def randomResults( functionalRandom: FunctionalRandom, actionResultProtoApplier: ActionResultProtoApplier - ): RandomState[Vector[ActionResult]] = { + ): RandomState[Vector[ActionResult]] = RandomStateProtoSequencer( initialStateProto = startingState, actionResultProtoApplier = actionResultProtoApplier, functionalRandom = functionalRandom ) - .withActionResults(_ => - startingState.provinces.values.toVector.flatMap(checkOneProvince) - ) + .withActionResults(_ => startingState.provinces.values.toVector.flatMap(checkOneProvince)) .withProtolessSequentialResultsAction(gs => WithdrawnArmiesReturnHomeAction( gs.currentRoundId, @@ -93,5 +86,4 @@ case class TruceTurnBackPhaseAction(startingState: GameState) ) ) .actionResults - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedAction.scala index 82f3cd3d7e..3f1e1f8557 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedAction.scala @@ -25,7 +25,7 @@ case class UnaffiliatedHeroAppearedAction( nameGenerationRequest: Option[GeneratedTextRequestT] ) extends ProtolessSimpleAction { private def newBackstoryTextId: String = - s"hero_${hero.id}_initial_backstory_${currentRoundId}" + s"hero_${hero.id}_initial_backstory_$currentRoundId" override def immediateExecute: ActionResultT = ActionResultC( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedAction.scala index ad98703653..29e16555cd 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedAction.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.{FunctionalRandom, RandomState} -import net.eagle0.eagle.common.action_result_notification_details.{ - Notification, - OutlawSpottedDetails -} +import net.eagle0.eagle.common.action_result_notification_details.{Notification, OutlawSpottedDetails} import net.eagle0.eagle.common.action_result_type.ActionResultType.HERO_MOVED import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFFILIATED_HERO_OUTLAW import net.eagle0.eagle.internal.action_result.ActionResult @@ -26,8 +23,8 @@ case class UnaffiliatedHeroMovedAction( private val affectedProvinces = Vector(fromProvinceId, toProvinceId).map(gameState.provinces) - private val affectedFactions = affectedProvinces.flatMap(_.rulingFactionId) - private val notifications = Option + private val affectedFactions = affectedProvinces.flatMap(_.rulingFactionId) + private val notifications = Option .when(uh.`type` == UNAFFILIATED_HERO_OUTLAW && affectedFactions.nonEmpty) { Notification( details = OutlawSpottedDetails( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroRejoinedAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroRejoinedAction.scala index b2e84e195f..b3e1f1efd1 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroRejoinedAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroRejoinedAction.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC} import net.eagle0.eagle.model.action_result.types.HeroRejoinedResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroT diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllAction.scala index 1837d8a7a0..51b1ae56f3 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllAction.scala @@ -21,7 +21,7 @@ case class WonFreeForAllAction( ) extends ProtolessSimpleAction { override def immediateExecute: ActionResultT = { - val notFledHids = winningUnits.map(_.hero.id) + val notFledHids = winningUnits.map(_.hero.id) val incomingArmies = winningArmyGroups .flatMap(_.armies) .map { movingArmy => @@ -48,16 +48,16 @@ case class WonFreeForAllAction( changedProvinces = Vector( ChangedProvinceC( provinceId = battleProvince.id, - removedHostileArmyFactionIds = - battleProvince.hostileArmies.map(_.factionId).toVector, + removedHostileArmyFactionIds = battleProvince.hostileArmies.map(_.factionId).toVector, newHostileArmies = incomingArmies .groupBy(_.army.factionId) - .map { case (fid, armies) => - HostileArmyGroup( - factionId = fid, - armies = armies, - status = AwaitingDecision - ) + .map { + case (fid, armies) => + HostileArmyGroup( + factionId = fid, + armies = armies, + status = AwaitingDecision + ) } .toVector ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpers.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpers.scala index 2b89686e6f..b509a61797 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpers.scala @@ -31,24 +31,13 @@ import net.eagle0.eagle.model.action_result.types.{ } import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected} import net.eagle0.eagle.model.state.diplomacy_offer.AllianceOffer import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.Ally import net.eagle0.eagle.model.state.faction.FactionT -import net.eagle0.eagle.model.state.hero.{ - AllianceAmbassadorBackstoryEvent, - HeroT, - ReleasedByAllianceBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{AllianceAmbassadorBackstoryEvent, HeroT, ReleasedByAllianceBackstoryEvent} import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.Prisoner @@ -62,8 +51,7 @@ object AllianceResolutionHelpers { .heroesReturningToFaction( hids = Vector(allianceOffer.messengerHeroId), factionId = allianceOffer.originatingFactionId, - originProvince = - provinces.find(_.id == allianceOffer.messengerOriginProvinceId).get, + originProvince = provinces.find(_.id == allianceOffer.messengerOriginProvinceId).get, provinces = provinces, functionalRandom = functionalRandom ) @@ -75,10 +63,10 @@ object AllianceResolutionHelpers { ): Vector[(HeroId, ProvinceId)] = for { province <- provinces - .filter(_.rulingFactionId.contains(freedByFactionId)) - uh <- province.unaffiliatedHeroes - .filter(_.unaffiliatedHeroType == Prisoner) - .filter(_.lastFactionId.contains(freedFromFactionId)) + .filter(_.rulingFactionId.contains(freedByFactionId)) + uh <- province.unaffiliatedHeroes + .filter(_.unaffiliatedHeroType == Prisoner) + .filter(_.lastFactionId.contains(freedFromFactionId)) } yield (uh.heroId, province.id) private def maybeFreedPrisonersResult( @@ -95,27 +83,29 @@ object AllianceResolutionHelpers { ActionResultC( actionResultType = HeroesReturnedByAllyResultType, actingFactionId = Some(freedByFactionId), - changedHeroes = heroProvincePairs.map { case (hid, pid) => - ChangedHeroC( - heroId = hid, - newFactionId = Some(freedFromFactionId), - newEventsForHeroBackstory = Vector( - ReleasedByAllianceBackstoryEvent( - date = currentDate, - releasingFactionId = freedByFactionId, - releasedFromProvinceId = pid + changedHeroes = heroProvincePairs.map { + case (hid, pid) => + ChangedHeroC( + heroId = hid, + newFactionId = Some(freedFromFactionId), + newEventsForHeroBackstory = Vector( + ReleasedByAllianceBackstoryEvent( + date = currentDate, + releasingFactionId = freedByFactionId, + releasedFromProvinceId = pid + ) ) ) - ) }, changedProvinces = heroProvincePairs .groupBy(_._2) .map { case (pid, vec) => (pid, vec.map(_._1)) } - .map { case (pid, heroIds) => - ChangedProvinceC( - provinceId = pid, - removedUnaffiliatedHeroIds = heroIds - ) + .map { + case (pid, heroIds) => + ChangedProvinceC( + provinceId = pid, + removedUnaffiliatedHeroIds = heroIds + ) } .toVector :+ ChangedProvinceC( provinceId = destinationProvinceId, @@ -169,8 +159,7 @@ object AllianceResolutionHelpers { .map { h => ClientTextVisibilityExtensionC( textId = h.backstoryVersions.last.textId, - recipientFactionIds = - Vector(allianceOffer.originatingFactionId) + recipientFactionIds = Vector(allianceOffer.originatingFactionId) ) } ++ heroes @@ -187,8 +176,7 @@ object AllianceResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = allianceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(allianceOffer.originatingFactionId), + removedIncomingDiplomacyOfferFactionIds = Vector(allianceOffer.originatingFactionId), changedFactionRelationships = Vector( FactionUtils .factionRelationship( @@ -237,35 +225,33 @@ object AllianceResolutionHelpers { provinces: Vector[ProvinceT], functionalRandom: FunctionalRandom ): RandomState[ActionResultT] = - returningHeroesForOffer(allianceOffer, provinces, functionalRandom).map { - returningHeroes => - val backstoryEvent = AllianceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = allianceOffer.originatingFactionId, - toFactionId = allianceOffer.targetFactionId, - outcome = Rejected - ) + returningHeroesForOffer(allianceOffer, provinces, functionalRandom).map { returningHeroes => + val backstoryEvent = AllianceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = allianceOffer.originatingFactionId, + toFactionId = allianceOffer.targetFactionId, + outcome = Rejected + ) - ActionResultC( - actionResultType = AllianceRejectedResultType, - actingFactionId = Some(allianceOffer.targetFactionId), - changedHeroes = Vector( - ChangedHeroC( - heroId = allianceOffer.messengerHeroId, - charismaXpDelta = Some(AllianceFailureCharismaXp.intValue), - wisdomXpDelta = Some(AllianceFailureWisdomXp.intValue), - newEventsForHeroBackstory = Vector(backstoryEvent) - ) - ) ++ returningHeroes.changedHeroes, - changedProvinces = Vector(returningHeroes.changedProvince), - changedFactions = Vector( - ChangedFactionC( - factionId = allianceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(allianceOffer.originatingFactionId) - ) + ActionResultC( + actionResultType = AllianceRejectedResultType, + actingFactionId = Some(allianceOffer.targetFactionId), + changedHeroes = Vector( + ChangedHeroC( + heroId = allianceOffer.messengerHeroId, + charismaXpDelta = Some(AllianceFailureCharismaXp.intValue), + wisdomXpDelta = Some(AllianceFailureWisdomXp.intValue), + newEventsForHeroBackstory = Vector(backstoryEvent) + ) + ) ++ returningHeroes.changedHeroes, + changedProvinces = Vector(returningHeroes.changedProvince), + changedFactions = Vector( + ChangedFactionC( + factionId = allianceOffer.targetFactionId, + removedIncomingDiplomacyOfferFactionIds = Vector(allianceOffer.originatingFactionId) ) ) + ) } def invalidatedAllianceResults( @@ -273,27 +259,25 @@ object AllianceResolutionHelpers { provinces: Vector[ProvinceT], functionalRandom: FunctionalRandom ): RandomState[ActionResultT] = - returningHeroesForOffer(allianceOffer, provinces, functionalRandom).map { - returningHeroes => - ActionResultC( - actionResultType = OfferInvalidatedResultType, - actingFactionId = Some(allianceOffer.targetFactionId), - changedHeroes = Vector( - ChangedHeroC( - heroId = allianceOffer.messengerHeroId, - charismaXpDelta = Some(AllianceFailureCharismaXp.intValue), - wisdomXpDelta = Some(AllianceFailureWisdomXp.intValue) - ) - ) ++ returningHeroes.changedHeroes, - changedProvinces = Vector(returningHeroes.changedProvince), - changedFactions = Vector( - ChangedFactionC( - factionId = allianceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(allianceOffer.originatingFactionId) - ) + returningHeroesForOffer(allianceOffer, provinces, functionalRandom).map { returningHeroes => + ActionResultC( + actionResultType = OfferInvalidatedResultType, + actingFactionId = Some(allianceOffer.targetFactionId), + changedHeroes = Vector( + ChangedHeroC( + heroId = allianceOffer.messengerHeroId, + charismaXpDelta = Some(AllianceFailureCharismaXp.intValue), + wisdomXpDelta = Some(AllianceFailureWisdomXp.intValue) + ) + ) ++ returningHeroes.changedHeroes, + changedProvinces = Vector(returningHeroes.changedProvince), + changedFactions = Vector( + ChangedFactionC( + factionId = allianceOffer.targetFactionId, + removedIncomingDiplomacyOfferFactionIds = Vector(allianceOffer.originatingFactionId) ) ) + ) } def prisoner(allianceOffer: AllianceOffer): UnaffiliatedHeroT = @@ -338,8 +322,7 @@ object AllianceResolutionHelpers { val pcp = prisonCp( prisoner = prisoner(allianceOffer), provinces = provinces, - imprisoningFaction = - factions.find(_.id == allianceOffer.targetFactionId).get + imprisoningFaction = factions.find(_.id == allianceOffer.targetFactionId).get ) ActionResultC( @@ -359,8 +342,7 @@ object AllianceResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = allianceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(allianceOffer.originatingFactionId) + removedIncomingDiplomacyOfferFactionIds = Vector(allianceOffer.originatingFactionId) ), ChangedFactionC( factionId = allianceOffer.originatingFactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpers.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpers.scala index 5dff62b809..f87dac015b 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpers.scala @@ -15,12 +15,7 @@ import net.eagle0.eagle.library.util.province.ProvinceUtils import net.eagle0.eagle.library.util.ReturningHeroes import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - TrustLevelUpdate -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, TrustLevelUpdate} import net.eagle0.eagle.model.action_result.types.{ AmbassadorImprisonedResultType, BreakAllianceAcceptedResultType, @@ -28,22 +23,13 @@ import net.eagle0.eagle.model.action_result.types.{ } import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned} import net.eagle0.eagle.model.state.diplomacy_offer.BreakAlliance -import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{ - Hostile, - Truce -} +import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{Hostile, Truce} import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.BreakAllianceAmbassadorBackstoryEvent import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.Prisoner import net.eagle0.eagle.FactionId @@ -71,57 +57,38 @@ object BreakAllianceResolutionHelpers { provinces: Vector[ProvinceT], factions: Vector[FactionT], functionalRandom: FunctionalRandom - ): RandomState[ActionResultT] = { - returningHeroesForOffer(breakAllianceOffer, provinces, functionalRandom) - .map { returningHeroes => - val backstoryEvent = BreakAllianceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = breakAllianceOffer.originatingFactionId, - toFactionId = breakAllianceOffer.targetFactionId, - outcome = Accepted - ) + ): RandomState[ActionResultT] = + returningHeroesForOffer(breakAllianceOffer, provinces, functionalRandom).map { returningHeroes => + val backstoryEvent = BreakAllianceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = breakAllianceOffer.originatingFactionId, + toFactionId = breakAllianceOffer.targetFactionId, + outcome = Accepted + ) - ActionResultC( - actionResultType = BreakAllianceAcceptedResultType, - actingFactionId = Some(breakAllianceOffer.targetFactionId), - changedHeroes = Vector( - ChangedHeroC( - heroId = breakAllianceOffer.messengerHeroId, - charismaXpDelta = Some(BreakAllianceCharismaXp.intValue), - wisdomXpDelta = Some(BreakAllianceWisdomXp.intValue), - newEventsForHeroBackstory = Vector(backstoryEvent) - ) - ) ++ returningHeroes.changedHeroes, - changedProvinces = Vector(returningHeroes.changedProvince), - changedFactions = Vector( - ChangedFactionC( - factionId = breakAllianceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(breakAllianceOffer.originatingFactionId), - changedFactionRelationships = Vector( - factionRelationship( - by = breakAllianceOffer.targetFactionId, - of = breakAllianceOffer.originatingFactionId, - factions = factions - ) - .copy( - relationshipLevel = Truce, - resetDate = Some( - currentDate.addMonths( - TruceMonthsAfterBreakingAlliance.intValue - ) - ) - ) + ActionResultC( + actionResultType = BreakAllianceAcceptedResultType, + actingFactionId = Some(breakAllianceOffer.targetFactionId), + changedHeroes = Vector( + ChangedHeroC( + heroId = breakAllianceOffer.messengerHeroId, + charismaXpDelta = Some(BreakAllianceCharismaXp.intValue), + wisdomXpDelta = Some(BreakAllianceWisdomXp.intValue), + newEventsForHeroBackstory = Vector(backstoryEvent) + ) + ) ++ returningHeroes.changedHeroes, + changedProvinces = Vector(returningHeroes.changedProvince), + changedFactions = Vector( + ChangedFactionC( + factionId = breakAllianceOffer.targetFactionId, + removedIncomingDiplomacyOfferFactionIds = Vector(breakAllianceOffer.originatingFactionId), + changedFactionRelationships = Vector( + factionRelationship( + by = breakAllianceOffer.targetFactionId, + of = breakAllianceOffer.originatingFactionId, + factions = factions ) - ), - ChangedFactionC( - factionId = breakAllianceOffer.originatingFactionId, - changedFactionRelationships = Vector( - factionRelationship( - by = breakAllianceOffer.originatingFactionId, - of = breakAllianceOffer.targetFactionId, - factions = factions - ).copy( + .copy( relationshipLevel = Truce, resetDate = Some( currentDate.addMonths( @@ -129,12 +96,28 @@ object BreakAllianceResolutionHelpers { ) ) ) + ) + ), + ChangedFactionC( + factionId = breakAllianceOffer.originatingFactionId, + changedFactionRelationships = Vector( + factionRelationship( + by = breakAllianceOffer.originatingFactionId, + of = breakAllianceOffer.targetFactionId, + factions = factions + ).copy( + relationshipLevel = Truce, + resetDate = Some( + currentDate.addMonths( + TruceMonthsAfterBreakingAlliance.intValue + ) + ) ) ) ) ) - } - } + ) + } def rejectedResult( breakAllianceOffer: BreakAlliance, @@ -148,27 +131,25 @@ object BreakAllianceResolutionHelpers { provinces: Vector[ProvinceT], functionalRandom: FunctionalRandom ): RandomState[ActionResultT] = - returningHeroesForOffer(offer, provinces, functionalRandom).map { - returningHeroes => - ActionResultC( - actionResultType = OfferInvalidatedResultType, - actingFactionId = Some(offer.targetFactionId), - changedHeroes = Vector( - ChangedHeroC( - heroId = offer.messengerHeroId, - charismaXpDelta = Some(BreakAllianceCharismaXp.intValue), - wisdomXpDelta = Some(BreakAllianceWisdomXp.intValue) - ) - ) ++ returningHeroes.changedHeroes, - changedProvinces = Vector(returningHeroes.changedProvince), - changedFactions = Vector( - ChangedFactionC( - factionId = offer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(offer.originatingFactionId) - ) + returningHeroesForOffer(offer, provinces, functionalRandom).map { returningHeroes => + ActionResultC( + actionResultType = OfferInvalidatedResultType, + actingFactionId = Some(offer.targetFactionId), + changedHeroes = Vector( + ChangedHeroC( + heroId = offer.messengerHeroId, + charismaXpDelta = Some(BreakAllianceCharismaXp.intValue), + wisdomXpDelta = Some(BreakAllianceWisdomXp.intValue) + ) + ) ++ returningHeroes.changedHeroes, + changedProvinces = Vector(returningHeroes.changedProvince), + changedFactions = Vector( + ChangedFactionC( + factionId = offer.targetFactionId, + removedIncomingDiplomacyOfferFactionIds = Vector(offer.originatingFactionId) ) ) + ) } def prisoner(breakAllianceOffer: BreakAlliance): UnaffiliatedHeroT = @@ -239,8 +220,7 @@ object BreakAllianceResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = breakAllianceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(breakAllianceOffer.originatingFactionId), + removedIncomingDiplomacyOfferFactionIds = Vector(breakAllianceOffer.originatingFactionId), changedFactionRelationships = Vector( FactionUtils .factionRelationship( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpers.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpers.scala index e1dda32c00..2ab491acac 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpers.scala @@ -33,28 +33,15 @@ import net.eagle0.eagle.model.action_result.types.{ import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected} import net.eagle0.eagle.model.state.diplomacy_offer.Invitation import net.eagle0.eagle.model.state.faction.FactionT -import net.eagle0.eagle.model.state.hero.{ - InvitationAmbassadorBackstoryEvent, - JoinedByInvitationBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{InvitationAmbassadorBackstoryEvent, JoinedByInvitationBackstoryEvent} import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.TruceWithFactionQuest -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Prisoner -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Prisoner} import net.eagle0.eagle.model.state.MovingArmy object InvitationResolutionHelpers { @@ -68,15 +55,14 @@ object InvitationResolutionHelpers { .filter(_.rulingFactionId.contains(invitingFid)) .flatMap { province => val changedUHs = - province.unaffiliatedHeroes - .flatMap { uh => - uh.quest.collect { - case TruceWithFactionQuest(targetFactionId) => - Option.when(targetFactionId == invitedFid) { - uh.copy(recruitmentInfo = RecruitmentInfo.NotDivined) - } - }.flatten - } + province.unaffiliatedHeroes.flatMap { uh => + uh.quest.collect { + case TruceWithFactionQuest(targetFactionId) => + Option.when(targetFactionId == invitedFid) { + uh.copy(recruitmentInfo = RecruitmentInfo.NotDivined) + } + }.flatten + } Option.when(changedUHs.nonEmpty) { ChangedProvinceC( @@ -100,11 +86,11 @@ object InvitationResolutionHelpers { messengerHid: HeroId, provinces: Vector[ProvinceT], currentDate: Date - ): Vector[ActionResultT] = { + ): Vector[ActionResultT] = for { province <- provinces if province.rulingFactionId.contains(invitingFid) - uh <- province.unaffiliatedHeroes + uh <- province.unaffiliatedHeroes if uh.unaffiliatedHeroType == Prisoner && uh.lastFactionId.contains( invitedFaction.id ) @@ -136,7 +122,6 @@ object InvitationResolutionHelpers { ) ) } - } case class BattalionOutcomes( joinedBattalionIds: Vector[BattalionId], @@ -155,16 +140,17 @@ object InvitationResolutionHelpers { .flatMap(_.battalionId), removedBattalionIds = Vector() ) - ) { case (acc, p) => - p.battalionIds - .sortBy(bid => -BattalionPower.power(battalions.find(_.id == bid).get)) - .splitAt(p.rulingFactionHeroIds.size) match { - case (joinedBids, removedBids) => - BattalionOutcomes( - joinedBattalionIds = acc.joinedBattalionIds ++ joinedBids, - removedBattalionIds = acc.removedBattalionIds ++ removedBids - ) - } + ) { + case (acc, p) => + p.battalionIds + .sortBy(bid => -BattalionPower.power(battalions.find(_.id == bid).get)) + .splitAt(p.rulingFactionHeroIds.size) match { + case (joinedBids, removedBids) => + BattalionOutcomes( + joinedBattalionIds = acc.joinedBattalionIds ++ joinedBids, + removedBattalionIds = acc.removedBattalionIds ++ removedBids + ) + } } def acceptedInvitationResults( @@ -182,14 +168,14 @@ object InvitationResolutionHelpers { outcome = Accepted ) - val invitingFid = acceptedInvitation.originatingFactionId - val acceptingFid = acceptedInvitation.targetFactionId - val acceptingFaction = factions.find(_.id == acceptingFid).get + val invitingFid = acceptedInvitation.originatingFactionId + val acceptingFid = acceptedInvitation.targetFactionId + val acceptingFaction = factions.find(_.id == acceptingFid).get val acceptingFactionProvinces = provinces.filter( _.rulingFactionId.contains(acceptingFid) ) - val messengerHid = acceptedInvitation.messengerHeroId - val messengerOriginPid = acceptedInvitation.messengerOriginProvinceId + val messengerHid = acceptedInvitation.messengerHeroId + val messengerOriginPid = acceptedInvitation.messengerOriginProvinceId val redirectedArmies = provinces .flatMap(_.incomingArmies) @@ -201,11 +187,11 @@ object InvitationResolutionHelpers { battalions = battalions ) - val changedInvitedHeroIds: Vector[HeroId] = redirectedArmies + val changedInvitedHeroIds: Vector[HeroId] = redirectedArmies .flatMap(_.army.units) .map(_.heroId) ++ acceptingFactionProvinces .flatMap(_.rulingFactionHeroIds) - val changedInvitedHeroes: Vector[ChangedHeroC] = + val changedInvitedHeroes: Vector[ChangedHeroC] = changedInvitedHeroIds.map { hid => val backstoryEvent = JoinedByInvitationBackstoryEvent( date = currentDate, @@ -222,7 +208,7 @@ object InvitationResolutionHelpers { newEventsForHeroBackstory = Vector(backstoryEvent) ) } - val changedActorProvinces: Vector[ChangedProvinceC] = + val changedActorProvinces: Vector[ChangedProvinceC] = acceptingFactionProvinces.map { p => ChangedProvinceC( provinceId = p.id, @@ -238,7 +224,7 @@ object InvitationResolutionHelpers { case RecruitmentInfo.Prisoner => RecruitmentInfo.Outlaw case RecruitmentInfo.HasQuest(_) => RecruitmentInfo.NoRulerInProvince - case x => x + case x => x } ) } @@ -275,25 +261,22 @@ object InvitationResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = acceptingFid, - removedIncomingDiplomacyOfferFactionIds = - acceptingFaction.incomingDiplomacyOffers - .map(_.originatingFactionId) - .distinct + removedIncomingDiplomacyOfferFactionIds = acceptingFaction.incomingDiplomacyOffers + .map(_.originatingFactionId) + .distinct ) ), - changedHeroes = - changedInvitedHeroes ++ returningHeroes.changedHeroes :+ ChangedHeroC( - heroId = messengerHid, - charismaXpDelta = Some(InviteSuccessCharismaXp.intValue), - wisdomXpDelta = Some(InviteSuccessWisdomXp.intValue), - newEventsForHeroBackstory = Vector(ambassadorBackstoryEvent) - ), - changedProvinces = - changedActorProvinces ++ changedIncomingArmyProvinces :+ ChangedProvinceC( - provinceId = returningHeroes.changedProvince.provinceId, - newRulingFactionHeroIds = changedInvitedHeroIds, - newBattalionIds = battOutcomes.joinedBattalionIds - ) :+ returningHeroes.changedProvince, + changedHeroes = changedInvitedHeroes ++ returningHeroes.changedHeroes :+ ChangedHeroC( + heroId = messengerHid, + charismaXpDelta = Some(InviteSuccessCharismaXp.intValue), + wisdomXpDelta = Some(InviteSuccessWisdomXp.intValue), + newEventsForHeroBackstory = Vector(ambassadorBackstoryEvent) + ), + changedProvinces = changedActorProvinces ++ changedIncomingArmyProvinces :+ ChangedProvinceC( + provinceId = returningHeroes.changedProvince.provinceId, + newRulingFactionHeroIds = changedInvitedHeroIds, + newBattalionIds = battOutcomes.joinedBattalionIds + ) :+ returningHeroes.changedProvince, destroyedBattalionIds = battOutcomes.removedBattalionIds ) ) ++ invalidatedQuestResults( @@ -316,10 +299,10 @@ object InvitationResolutionHelpers { provinces: Vector[ProvinceT], functionalRandom: FunctionalRandom ): RandomState[ActionResultT] = { - val invitingFid = rejectedInvitation.originatingFactionId - val rejectingFid = rejectedInvitation.targetFactionId - val messengerHid = rejectedInvitation.messengerHeroId - val messengerOriginPid = rejectedInvitation.messengerOriginProvinceId + val invitingFid = rejectedInvitation.originatingFactionId + val rejectingFid = rejectedInvitation.targetFactionId + val messengerHid = rejectedInvitation.messengerHeroId + val messengerOriginPid = rejectedInvitation.messengerOriginProvinceId val messengerOriginProvince = provinces .find( _.id == messengerOriginPid @@ -358,8 +341,7 @@ object InvitationResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = rejectingFid, - removedIncomingDiplomacyOfferFactionIds = - Vector(rejectedInvitation.originatingFactionId) + removedIncomingDiplomacyOfferFactionIds = Vector(rejectedInvitation.originatingFactionId) ) ) ) @@ -371,10 +353,10 @@ object InvitationResolutionHelpers { provinces: Vector[ProvinceT], functionalRandom: FunctionalRandom ): RandomState[ActionResultT] = { - val invitingFid = invalidatedInvitation.originatingFactionId - val rejectingFid = invalidatedInvitation.targetFactionId - val messengerHid = invalidatedInvitation.messengerHeroId - val messengerOriginPid = invalidatedInvitation.messengerOriginProvinceId + val invitingFid = invalidatedInvitation.originatingFactionId + val rejectingFid = invalidatedInvitation.targetFactionId + val messengerHid = invalidatedInvitation.messengerHeroId + val messengerOriginPid = invalidatedInvitation.messengerOriginProvinceId val messengerOriginProvince = provinces .find(_.id == messengerOriginPid) .get @@ -403,8 +385,7 @@ object InvitationResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = rejectingFid, - removedIncomingDiplomacyOfferFactionIds = - Vector(invalidatedInvitation.originatingFactionId) + removedIncomingDiplomacyOfferFactionIds = Vector(invalidatedInvitation.originatingFactionId) ) ) ) @@ -475,8 +456,7 @@ object InvitationResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = invitation.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(invitation.originatingFactionId) + removedIncomingDiplomacyOfferFactionIds = Vector(invitation.originatingFactionId) ), ChangedFactionC( factionId = invitation.originatingFactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpers.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpers.scala index dcbf6cd796..b02952b0a4 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpers.scala @@ -1,19 +1,11 @@ package net.eagle0.eagle.library.actions.impl.action.diplomacy_helpers -import net.eagle0.eagle.library.settings.{ - TrustDeltaFromAcceptingRansom, - TrustDeltaFromRejectingRansom -} +import net.eagle0.eagle.library.settings.{TrustDeltaFromAcceptingRansom, TrustDeltaFromRejectingRansom} import net.eagle0.eagle.library.util.quest_fulfillment.prisoner_management.PrisonerManagementQuestMatchers import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - TrustLevelUpdate -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, TrustLevelUpdate} import net.eagle0.eagle.model.action_result.types.{ RansomAcceptedResultType, RansomInvalidatedResultType, @@ -22,10 +14,7 @@ import net.eagle0.eagle.model.action_result.types.{ import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.diplomacy_offer.RansomOffer -import net.eagle0.eagle.model.state.hero.{ - ExchangedInRansomBackstoryEvent, - RansomedBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{ExchangedInRansomBackstoryEvent, RansomedBackstoryEvent} import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo @@ -79,8 +68,7 @@ object RansomResolutionHelpers { ransomPaidByFactionId = offer.originatingFactionId, ransomPaidToFactionId = offer.targetFactionId, ransomedHeroId = offer.prisonerToBeRansomed.prisonerHeroId, - imprisonedInProvinceId = - offer.prisonerToBeRansomed.provinceIdForPrisoner + imprisonedInProvinceId = offer.prisonerToBeRansomed.provinceIdForPrisoner ) ) ) @@ -89,11 +77,12 @@ object RansomResolutionHelpers { val prisonersRemovedCps = offer.prisonersOffered .groupBy(_.provinceIdWithHero) - .map { case (pid, prisoners) => - ChangedProvinceC( - provinceId = pid, - removedUnaffiliatedHeroIds = prisoners.map(_.heroId) - ) + .map { + case (pid, prisoners) => + ChangedProvinceC( + provinceId = pid, + removedUnaffiliatedHeroIds = prisoners.map(_.heroId) + ) } .toVector @@ -107,8 +96,7 @@ object RansomResolutionHelpers { ransomPaidByFactionId = offer.originatingFactionId, ransomPaidToFactionId = offer.targetFactionId, ransomedHeroId = offer.prisonerToBeRansomed.prisonerHeroId, - imprisonedInProvinceId = - offer.prisonerToBeRansomed.provinceIdForPrisoner + imprisonedInProvinceId = offer.prisonerToBeRansomed.provinceIdForPrisoner ) ) ) @@ -123,8 +111,7 @@ object RansomResolutionHelpers { date = currentDate, ransomPaidByFactionId = offer.originatingFactionId, ransomPaidToFactionId = offer.targetFactionId, - imprisonedInProvinceId = - offer.prisonerToBeRansomed.provinceIdForPrisoner, + imprisonedInProvinceId = offer.prisonerToBeRansomed.provinceIdForPrisoner, goldPaid = offer.goldOffered, heroIdsExchanged = offer.prisonersOffered.map( _.heroId @@ -137,8 +124,7 @@ object RansomResolutionHelpers { val releasedToCps = Vector( ChangedProvinceC( provinceId = offer.messengerOriginProvinceId, - newRulingFactionHeroIds = - Vector(offer.prisonerToBeRansomed.prisonerHeroId), + newRulingFactionHeroIds = Vector(offer.prisonerToBeRansomed.prisonerHeroId), goldDelta = Some(-offer.goldOffered).filterNot(_ == 0) ) ) @@ -167,8 +153,7 @@ object RansomResolutionHelpers { val releasedFromCp = ChangedProvinceC( provinceId = offer.prisonerToBeRansomed.provinceIdForPrisoner, - removedUnaffiliatedHeroIds = - Vector(offer.prisonerToBeRansomed.prisonerHeroId), + removedUnaffiliatedHeroIds = Vector(offer.prisonerToBeRansomed.prisonerHeroId), newUnaffiliatedHeroes = uhsFromHostages ++ uhsFromPrisoners, goldDelta = Some(offer.goldOffered).filterNot(_ == 0) ) @@ -182,20 +167,16 @@ object RansomResolutionHelpers { allProvinces.flatMap { questCheckProvince => questFulfillmentChecker.failedQuestResults( province = questCheckProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - matcher.executePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => matcher.executePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = questCheckProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - matcher.releasePrisonerMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => matcher.releasePrisonerMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = questCheckProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - matcher.exilePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => matcher.exilePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.fulfilledQuestResults( province = questCheckProvince, - isFulfilled = (quest, _ /*questHolderProvince*/ ) => - matcher.returnPrisonerQuestMatch(quest) + isFulfilled = (quest, _ /*questHolderProvince*/ ) => matcher.returnPrisonerQuestMatch(quest) ) } } @@ -203,45 +184,37 @@ object RansomResolutionHelpers { val resolvedQuestsForPrisonersExchanged = for { prisonerOfferedInExchange <- offer.prisonersOffered matcher = new PrisonerManagementQuestMatchers( - prisonerOfferedInExchange.heroId, - prisonerOfferedInExchange.provinceIdWithHero - ) + prisonerOfferedInExchange.heroId, + prisonerOfferedInExchange.provinceIdWithHero + ) questCheckProvince <- allProvinces - } yield { - questFulfillmentChecker.failedQuestResults( - province = questCheckProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - matcher.executePrisonerQuestMatch(quest) - ) ++ questFulfillmentChecker.failedQuestResults( - province = questCheckProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - matcher.releasePrisonerMatch(quest) - ) ++ questFulfillmentChecker.failedQuestResults( - province = questCheckProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - matcher.exilePrisonerQuestMatch(quest) - ) ++ questFulfillmentChecker.failedQuestResults( - province = questCheckProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - matcher.returnPrisonerQuestMatch(quest) - ) - } + } yield questFulfillmentChecker.failedQuestResults( + province = questCheckProvince, + isFailed = (quest, _ /*questHolderProvince*/ ) => matcher.executePrisonerQuestMatch(quest) + ) ++ questFulfillmentChecker.failedQuestResults( + province = questCheckProvince, + isFailed = (quest, _ /*questHolderProvince*/ ) => matcher.releasePrisonerMatch(quest) + ) ++ questFulfillmentChecker.failedQuestResults( + province = questCheckProvince, + isFailed = (quest, _ /*questHolderProvince*/ ) => matcher.exilePrisonerQuestMatch(quest) + ) ++ questFulfillmentChecker.failedQuestResults( + province = questCheckProvince, + isFailed = (quest, _ /*questHolderProvince*/ ) => matcher.returnPrisonerQuestMatch(quest) + ) ActionResultC( actionResultType = RansomAcceptedResultType, actingFactionId = Some(offer.targetFactionId), changedHeroes = hostagedChsWithBackstoryUpdates ++ releasedChs ++ prisonerChsWithBackstoryUpdates, - changedProvinces = - releasedToCps ++ hostagesRemovedCps.toVector ++ prisonersRemovedCps :+ releasedFromCp, + changedProvinces = releasedToCps ++ hostagesRemovedCps.toVector ++ prisonersRemovedCps :+ releasedFromCp, changedFactions = changedFactions( diplomacyOffer = offer, offeringFactionId = offer.originatingFactionId, targetFactionId = tfid, trustDelta = TrustDeltaFromAcceptingRansom.intValue ), - affectedFactionIds = - Vector(offer.targetFactionId, offer.originatingFactionId) + affectedFactionIds = Vector(offer.targetFactionId, offer.originatingFactionId) ) +: (resolvedQuestsForPrisonerToBeRansomed ++ resolvedQuestsForPrisonersExchanged.flatten) } @@ -257,8 +230,7 @@ object RansomResolutionHelpers { targetFactionId = offer.targetFactionId, trustDelta = TrustDeltaFromRejectingRansom.intValue ), - affectedFactionIds = - Vector(offer.targetFactionId, offer.originatingFactionId) + affectedFactionIds = Vector(offer.targetFactionId, offer.originatingFactionId) ) def invalidatedRansomResult( @@ -273,14 +245,12 @@ object RansomResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = tfid, - removedIncomingDiplomacyOfferFactionIds = - Vector(offer.originatingFactionId) + removedIncomingDiplomacyOfferFactionIds = Vector(offer.originatingFactionId) ) ), - affectedFactionIds = - Vector(offer.targetFactionId, offer.originatingFactionId) + affectedFactionIds = Vector(offer.targetFactionId, offer.originatingFactionId) ) - case _ => + case _ => throw new EagleInternalException( "Trying to match when it's not a ransom offer" ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpers.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpers.scala index a3faf2775c..2065d0a7d8 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpers.scala @@ -17,12 +17,7 @@ import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentUtils import net.eagle0.eagle.library.util.ReturningHeroes import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.changed_province.ChangedProvinceT -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - TrustLevelUpdate -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, TrustLevelUpdate} import net.eagle0.eagle.model.action_result.types.{ AmbassadorImprisonedResultType, OfferInvalidatedResultType, @@ -31,11 +26,7 @@ import net.eagle0.eagle.model.action_result.types.{ } import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected} import net.eagle0.eagle.model.state.diplomacy_offer.TruceOffer import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.Truce import net.eagle0.eagle.model.state.faction.FactionT @@ -43,11 +34,7 @@ import net.eagle0.eagle.model.state.hero.TruceAmbassadorBackstoryEvent import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.TruceWithFactionQuest import net.eagle0.eagle.model.state.quest.QuestT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo.Prisoner @@ -61,8 +48,7 @@ object TruceResolutionHelpers { .heroesReturningToFaction( hids = Vector(truceOffer.messengerHeroId), factionId = truceOffer.originatingFactionId, - originProvince = - provinces.find(_.id == truceOffer.messengerOriginProvinceId).get, + originProvince = provinces.find(_.id == truceOffer.messengerOriginProvinceId).get, provinces = provinces, functionalRandom = functionalRandom ) @@ -75,12 +61,11 @@ object TruceResolutionHelpers { .filter(_.rulingFactionId.contains(truceOffer.originatingFactionId)) .flatMap { province => val uhsWithQuest = province.unaffiliatedHeroes.filter( - _.quest - .exists { - case TruceWithFactionQuest(targetFactionId) => - targetFactionId == truceOffer.targetFactionId - case _ => false - } + _.quest.exists { + case TruceWithFactionQuest(targetFactionId) => + targetFactionId == truceOffer.targetFactionId + case _ => false + } ) Option.when(uhsWithQuest.nonEmpty) { @@ -108,7 +93,7 @@ object TruceResolutionHelpers { q match { case TruceWithFactionQuest(targetFactionId) => targetFactionId == truceOffer.targetFactionId - case _ => false + case _ => false }, gameId = eagleGameId, currentDate = currentDate @@ -121,65 +106,62 @@ object TruceResolutionHelpers { factions: Vector[FactionT], currentDate: Date, functionalRandom: FunctionalRandom - ): RandomState[ActionResultT] = { - returningHeroesForOffer(truceOffer, provinces, functionalRandom).map { - returningHeroes => - val backstoryEvent = TruceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = truceOffer.originatingFactionId, - toFactionId = truceOffer.targetFactionId, - outcome = Accepted - ) + ): RandomState[ActionResultT] = + returningHeroesForOffer(truceOffer, provinces, functionalRandom).map { returningHeroes => + val backstoryEvent = TruceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = truceOffer.originatingFactionId, + toFactionId = truceOffer.targetFactionId, + outcome = Accepted + ) - ActionResultC( - actionResultType = TruceAcceptedResultType, - actingFactionId = Some(truceOffer.targetFactionId), - changedHeroes = Vector( - ChangedHeroC( - heroId = truceOffer.messengerHeroId, - charismaXpDelta = Some(TruceSuccessCharismaXp.intValue), - wisdomXpDelta = Some(TruceSuccessWisdomXp.intValue), - newEventsForHeroBackstory = Vector(backstoryEvent) + ActionResultC( + actionResultType = TruceAcceptedResultType, + actingFactionId = Some(truceOffer.targetFactionId), + changedHeroes = Vector( + ChangedHeroC( + heroId = truceOffer.messengerHeroId, + charismaXpDelta = Some(TruceSuccessCharismaXp.intValue), + wisdomXpDelta = Some(TruceSuccessWisdomXp.intValue), + newEventsForHeroBackstory = Vector(backstoryEvent) + ) + ) ++ returningHeroes.changedHeroes, + changedProvinces = Vector(returningHeroes.changedProvince), + changedFactions = Vector( + ChangedFactionC( + factionId = truceOffer.targetFactionId, + removedIncomingDiplomacyOfferFactionIds = Vector(truceOffer.originatingFactionId), + changedFactionRelationships = Vector( + FactionUtils + .factionRelationship( + by = truceOffer.targetFactionId, + of = truceOffer.originatingFactionId, + factions = factions + ) + .copy( + relationshipLevel = Truce, + resetDate = Some(truceOffer.endDate) + ) ) - ) ++ returningHeroes.changedHeroes, - changedProvinces = Vector(returningHeroes.changedProvince), - changedFactions = Vector( - ChangedFactionC( - factionId = truceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(truceOffer.originatingFactionId), - changedFactionRelationships = Vector( - FactionUtils - .factionRelationship( - by = truceOffer.targetFactionId, - of = truceOffer.originatingFactionId, - factions = factions - ) - .copy( - relationshipLevel = Truce, - resetDate = Some(truceOffer.endDate) - ) - ) - ), - ChangedFactionC( - factionId = truceOffer.originatingFactionId, - changedFactionRelationships = Vector( - FactionUtils - .factionRelationship( - by = truceOffer.originatingFactionId, - of = truceOffer.targetFactionId, - factions = factions - ) - .copy( - relationshipLevel = Truce, - resetDate = Some(truceOffer.endDate) - ) - ) + ), + ChangedFactionC( + factionId = truceOffer.originatingFactionId, + changedFactionRelationships = Vector( + FactionUtils + .factionRelationship( + by = truceOffer.originatingFactionId, + of = truceOffer.targetFactionId, + factions = factions + ) + .copy( + relationshipLevel = Truce, + resetDate = Some(truceOffer.endDate) + ) ) ) ) + ) } - } def rejectedTruceResults( truceOffer: TruceOffer, @@ -188,44 +170,41 @@ object TruceResolutionHelpers { eagleGameId: GameId, functionalRandom: FunctionalRandom ): RandomState[Vector[ActionResultT]] = - returningHeroesForOffer(truceOffer, provinces, functionalRandom).map { - returningHeroes => - val backstoryEvent = TruceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = truceOffer.originatingFactionId, - toFactionId = truceOffer.targetFactionId, - outcome = Rejected - ) + returningHeroesForOffer(truceOffer, provinces, functionalRandom).map { returningHeroes => + val backstoryEvent = TruceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = truceOffer.originatingFactionId, + toFactionId = truceOffer.targetFactionId, + outcome = Rejected + ) - ActionResultC( - actionResultType = TruceRejectedResultType, - actingFactionId = Some(truceOffer.targetFactionId), - changedHeroes = Vector( - ChangedHeroC( - heroId = truceOffer.messengerHeroId, - charismaXpDelta = Some(TruceFailureCharismaXp.intValue), - wisdomXpDelta = Some(TruceFailureWisdomXp.intValue), - newEventsForHeroBackstory = Vector(backstoryEvent) - ) - ) ++ returningHeroes.changedHeroes, - changedProvinces = - Vector(returningHeroes.changedProvince) ++ removedQuestProvinces( - truceOffer, - provinces - ), - changedFactions = Vector( - ChangedFactionC( - factionId = truceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(truceOffer.originatingFactionId) - ) + ActionResultC( + actionResultType = TruceRejectedResultType, + actingFactionId = Some(truceOffer.targetFactionId), + changedHeroes = Vector( + ChangedHeroC( + heroId = truceOffer.messengerHeroId, + charismaXpDelta = Some(TruceFailureCharismaXp.intValue), + wisdomXpDelta = Some(TruceFailureWisdomXp.intValue), + newEventsForHeroBackstory = Vector(backstoryEvent) ) - ) +: failedQuestResults( + ) ++ returningHeroes.changedHeroes, + changedProvinces = Vector(returningHeroes.changedProvince) ++ removedQuestProvinces( truceOffer, - provinces, - currentDate, - eagleGameId + provinces + ), + changedFactions = Vector( + ChangedFactionC( + factionId = truceOffer.targetFactionId, + removedIncomingDiplomacyOfferFactionIds = Vector(truceOffer.originatingFactionId) + ) ) + ) +: failedQuestResults( + truceOffer, + provinces, + currentDate, + eagleGameId + ) } def invalidatedTruceResults( @@ -235,31 +214,28 @@ object TruceResolutionHelpers { eagleGameId: GameId, functionalRandom: FunctionalRandom ): RandomState[Vector[ActionResultT]] = - returningHeroesForOffer(truceOffer, provinces, functionalRandom).map { - returningHeroes => - ActionResultC( - actionResultType = OfferInvalidatedResultType, - actingFactionId = Some(truceOffer.targetFactionId), - changedHeroes = Vector( - ChangedHeroC( - heroId = truceOffer.messengerHeroId, - charismaXpDelta = Some(TruceFailureCharismaXp.intValue), - wisdomXpDelta = Some(TruceFailureWisdomXp.intValue) - ) - ) ++ returningHeroes.changedHeroes, - changedProvinces = - Vector(returningHeroes.changedProvince) ++ removedQuestProvinces( - truceOffer, - provinces - ), - changedFactions = Vector( - ChangedFactionC( - factionId = truceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(truceOffer.originatingFactionId) - ) + returningHeroesForOffer(truceOffer, provinces, functionalRandom).map { returningHeroes => + ActionResultC( + actionResultType = OfferInvalidatedResultType, + actingFactionId = Some(truceOffer.targetFactionId), + changedHeroes = Vector( + ChangedHeroC( + heroId = truceOffer.messengerHeroId, + charismaXpDelta = Some(TruceFailureCharismaXp.intValue), + wisdomXpDelta = Some(TruceFailureWisdomXp.intValue) ) - ) +: failedQuestResults(truceOffer, provinces, currentDate, eagleGameId) + ) ++ returningHeroes.changedHeroes, + changedProvinces = Vector(returningHeroes.changedProvince) ++ removedQuestProvinces( + truceOffer, + provinces + ), + changedFactions = Vector( + ChangedFactionC( + factionId = truceOffer.targetFactionId, + removedIncomingDiplomacyOfferFactionIds = Vector(truceOffer.originatingFactionId) + ) + ) + ) +: failedQuestResults(truceOffer, provinces, currentDate, eagleGameId) } def prisoner(truceOffer: TruceOffer): UnaffiliatedHeroT = @@ -330,8 +306,7 @@ object TruceResolutionHelpers { changedFactions = Vector( ChangedFactionC( factionId = truceOffer.targetFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(truceOffer.originatingFactionId) + removedIncomingDiplomacyOfferFactionIds = Vector(truceOffer.originatingFactionId) ), ChangedFactionC( factionId = truceOffer.originatingFactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommand.scala index 632c7205b6..a77a305966 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommand.scala @@ -12,28 +12,20 @@ import net.eagle0.eagle.library.settings.{ import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.util.QuestFulfillmentModelUpdaters import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.concrete.ActionResultC.ActionResultCUpdater import net.eagle0.eagle.model.action_result.types.GiftedProvinceResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.hero.{HeroT, Profession} import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.quest.concrete.{ - AlmsAcrossRealmQuest, - AlmsToProvinceQuest -} +import net.eagle0.eagle.model.state.quest.concrete.{AlmsAcrossRealmQuest, AlmsToProvinceQuest} import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroT object AlmsCommand { def supportIncreasePerFood(hero: HeroT): Double = AlmsSupportIncreasePerFood.doubleValue * (if hero.profession == Profession.Paladin - then - AlmsPaladinSupportMultiplier.doubleValue + then AlmsPaladinSupportMultiplier.doubleValue else 1.0) private def supportIncrease(hero: HeroT, foodAmount: Int): Double = @@ -51,18 +43,16 @@ object AlmsCommand { uh: UnaffiliatedHeroT, province: ProvinceT ): Boolean = - uh.quest - .collect { - case AlmsToProvinceQuest(_, _, pid, _) if pid == province.id => true - } + uh.quest.collect { + case AlmsToProvinceQuest(_, _, pid, _) if pid == province.id => true + } .getOrElse(false) private def almsAcrossRealmQuestCheck( uh: UnaffiliatedHeroT, province: ProvinceT ): Boolean = - uh.quest - .collect { case AlmsAcrossRealmQuest(_, _, _) => true } + uh.quest.collect { case AlmsAcrossRealmQuest(_, _, _) => true } .getOrElse(false) private def almsToThisProvinceCounterIncrementer: ActionResultCUpdater = @@ -79,7 +69,7 @@ object AlmsCommand { check = almsAcrossRealmQuestCheck ) - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = ActionResultC( actionResultType = GiftedProvinceResultType, actingFactionId = Some(factionId), @@ -108,7 +98,6 @@ object AlmsCommand { ) ).update(almsToThisProvinceCounterIncrementer) .update(almsAcrossRealmCounterIncrementer) - } } def make( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommand.scala index c3719af1fa..49cc303b1c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommand.scala @@ -2,26 +2,15 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, HeroId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction -import net.eagle0.eagle.library.settings.{ - ApprehendOutlawVigorCost, - FactionBiasFromImprisonment -} +import net.eagle0.eagle.library.settings.{ApprehendOutlawVigorCost, FactionBiasFromImprisonment} import net.eagle0.eagle.library.util.EagleRequire.clientRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - NotificationC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, NotificationC, StatDelta} import net.eagle0.eagle.model.action_result.types.OutlawApprehendedResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.action_result.NotificationDetails.OutlawApprehended import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} object ApprehendOutlawCommand { def make( @@ -58,7 +47,7 @@ object ApprehendOutlawCommand { targetedHeroId: HeroId ) extends ProtolessSimpleAction { - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = ActionResultC( actionResultType = OutlawApprehendedResultType, actingFactionId = Some(factionId), @@ -103,6 +92,5 @@ object ApprehendOutlawCommand { ) ) ) - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommand.scala index 95e19e7ed8..d0bba110f4 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommand.scala @@ -6,10 +6,7 @@ import net.eagle0.eagle.library.util.province.ProvinceUtils import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.util.PriceIndexUtils import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedBattalionC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedBattalionC} import net.eagle0.eagle.model.action_result.types.ArmTroopsResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.battalion.BattalionT @@ -133,8 +130,7 @@ object ArmTroopsCommand { provinceId = Some(province.id), actingFactionId = Some(factionId), changedProvinces = Vector(spentGoldProvince), - changedBattalions = - oldAndNewBattalions.map(cb => ChangedBattalionC(cb.newB)) + changedBattalions = oldAndNewBattalions.map(cb => ChangedBattalionC(cb.newB)) ) } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommand.scala index 74a9ff481f..5bc336d472 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommand.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire -import net.eagle0.eagle.model.action_result.changed_province.concrete.{ - ChangedProvinceC, - HostileArmyStatusChange -} +import net.eagle0.eagle.model.action_result.changed_province.concrete.{ChangedProvinceC, HostileArmyStatusChange} import net.eagle0.eagle.model.action_result.concrete.ActionResultC import net.eagle0.eagle.model.action_result.types.{ ArmyAdvancedResultType, @@ -17,19 +14,14 @@ import net.eagle0.eagle.model.action_result.types.{ import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.{BattleRevelation, TributeAmount} import net.eagle0.eagle.model.state.BattleRevelationType.Withdrew -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - Attacking, - SafePassageGranted, - TributeDemanded, - Withdrawing -} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{Attacking, SafePassageGranted, TributeDemanded, Withdrawing} object AttackDecisionCommand { sealed trait AttackDecision - case object Advance extends AttackDecision - case object Withdraw extends AttackDecision + case object Advance extends AttackDecision + case object Withdraw extends AttackDecision case class DemandTribute(tributeAmount: TributeAmount) extends AttackDecision - case class SafePassage(toProvinceId: ProvinceId) extends AttackDecision + case class SafePassage(toProvinceId: ProvinceId) extends AttackDecision private case class AdvanceArmyCommand( attackingFactionId: FactionId, @@ -143,9 +135,9 @@ object AttackDecisionCommand { availableDecisions: Vector[AttackDecision], selectedDecision: AttackDecision // selectedCommand: AttackDecisionSelectedCommand - ): ProtolessSimpleAction = { + ): ProtolessSimpleAction = selectedDecision match { - case Advance => + case Advance => commandRequire( availableDecisions.contains(selectedDecision), s"Selected decision $selectedDecision was not among $availableDecisions" @@ -191,7 +183,7 @@ object AttackDecisionCommand { provinceId = actingProvinceId, tribute = tributeDemanded ) - case Withdraw => + case Withdraw => commandRequire( availableDecisions.contains(selectedDecision), s"Selected decision $selectedDecision was not among $availableDecisions" @@ -200,7 +192,7 @@ object AttackDecisionCommand { attackingFactionId = actingFactionId, provinceId = actingProvinceId ) - case SafePassage(toProvinceId) => + case SafePassage(toProvinceId) => commandRequire( availableDecisions.contains(selectedDecision), s"Selected decision $selectedDecision was not among $availableDecisions" @@ -212,5 +204,4 @@ object AttackDecisionCommand { toProvinceId = toProvinceId ) } - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/Command.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/Command.scala index 29fe48295f..2d867f990a 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/Command.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/Command.scala @@ -4,10 +4,7 @@ import net.eagle0.eagle.api.selected_command.SelectedCommand import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.changed_faction.ChangedFaction import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - Action, - ActionWithResultingState -} +import net.eagle0.eagle.library.actions.impl.common.{Action, ActionWithResultingState} import net.eagle0.eagle.FactionId object Command { diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/CommandFactory.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/CommandFactory.scala index 9550f5f632..1f5f6ee678 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/CommandFactory.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/CommandFactory.scala @@ -25,10 +25,7 @@ import net.eagle0.eagle.api.command.util.prisoner_management_type.{ import net.eagle0.eagle.api.command.util.province_orders.ProvinceOrders as ProvinceOrdersProto import net.eagle0.eagle.api.selected_command.* import net.eagle0.eagle.api.selected_command.TradeSelectedCommand.TradeType -import net.eagle0.eagle.library.actions.impl.command.AttackDecisionCommand.{ - AttackDecision, - SafePassage -} +import net.eagle0.eagle.library.actions.impl.command.AttackDecisionCommand.{AttackDecision, SafePassage} import net.eagle0.eagle.library.actions.impl.command.FreeForAllDecisionCommand.FreeForAllDecision import net.eagle0.eagle.library.actions.impl.command.ManagePrisonersCommand.PrisonerManagementOption import net.eagle0.eagle.library.actions.impl.command.ManagePrisonersCommand.PrisonerToManage @@ -56,19 +53,11 @@ import net.eagle0.eagle.model.proto_converters.diplomacy_offer.DiplomacyOfferCon import net.eagle0.eagle.model.proto_converters.diplomacy_option.DiplomacyOptionConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.hero.HeroConverter -import net.eagle0.eagle.model.proto_converters.province.{ - ProvinceConverter, - ProvinceOrderTypeConverter -} +import net.eagle0.eagle.model.proto_converters.province.{ProvinceConverter, ProvinceOrderTypeConverter} import net.eagle0.eagle.model.proto_converters.BattalionTypeIdConverter import net.eagle0.eagle.model.proto_converters.CombatUnitConverter import net.eagle0.eagle.model.state.battalion.BattalionT -import net.eagle0.eagle.model.state.diplomacy_offer.{ - AllianceOffer, - BreakAlliance, - Invitation, - TruceOffer -} +import net.eagle0.eagle.model.state.diplomacy_offer.{AllianceOffer, BreakAlliance, Invitation, TruceOffer} import net.eagle0.eagle.model.state.diplomacy_option.DiplomacyOption import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.game_state.GameState @@ -91,7 +80,7 @@ class CommandFactory { private def convertAttackDecisionToFreeForAllDecision( attackDecision: AttackDecisionType - ): FreeForAllDecision = { + ): FreeForAllDecision = attackDecision match { case AdvanceDecision(_) => FreeForAllDecisionCommand.Advance case WithdrawDecision(_) => FreeForAllDecisionCommand.Withdraw @@ -99,23 +88,20 @@ class CommandFactory { throw new EagleCommandException( "Demand Tribute not allowed for free-for-all" ) - case SafePassageDecision(_, _) => + case SafePassageDecision(_, _) => throw new EagleCommandException( "Safe Passage not allowed for free-for-all" ) - case AttackDecisionType.Empty => + case AttackDecisionType.Empty => throw new EagleCommandException("Must specify an attack decision type") } - } private def factionHeroesInProvince( gameState: GameState, provinceId: ProvinceId ): Vector[HeroT] = gameState.heroes.values - .filter(h => - gameState.provinces(provinceId).rulingFactionHeroIds.contains(h.id) - ) + .filter(h => gameState.provinces(provinceId).rulingFactionHeroIds.contains(h.id)) .toVector private def questFulfillmentChecker( @@ -172,11 +158,9 @@ class CommandFactory { ) => AttackDecisionCommand.make( actingFactionId = actingFactionId, - defendingFactionId = - gameState.provinces(adac.actingProvinceId).rulingFactionId.get, + defendingFactionId = gameState.provinces(adac.actingProvinceId).rulingFactionId.get, actingProvinceId = adac.actingProvinceId, - availableDecisions = - adac.availableDecisions.map(attackDecision).toVector, + availableDecisions = adac.availableDecisions.map(attackDecision).toVector, selectedDecision = attackDecision(adsc.decision) ) case ( @@ -198,8 +182,7 @@ class CommandFactory { ) => ControlWeatherCommand.ControlWeatherOption( targetedProvinceId = targetedProvinceId, - controlWeatherTypes = - controlWeatherTypes.map(controlWeatherTypeMap).toVector + controlWeatherTypes = controlWeatherTypes.map(controlWeatherTypeMap).toVector ) }.toVector ) @@ -219,11 +202,10 @@ class CommandFactory { gameState.heroes(hid).backstoryTextId } ) - case (dfac: DefendAvailableCommand, dfsc: DefendSelectedCommand) => + case (dfac: DefendAvailableCommand, dfsc: DefendSelectedCommand) => DefendCommand.make( actingFactionId = actingFactionId, - defendingUnits = - dfsc.defendingUnits.map(CombatUnitConverter.fromProto).toVector, + defendingUnits = dfsc.defendingUnits.map(CombatUnitConverter.fromProto).toVector, fleeProvinceId = dfsc.fleeProvinceId, availableFleeProvinceIds = dfac.availableFleeProvinceIds.toVector, actingProvince = gameState.provinces(dfac.actingProvinceId) @@ -245,7 +227,7 @@ class CommandFactory { currentRoundId = gameState.currentRoundId, currentDate = gameState.currentDate.get ) - case (dvac: DivineAvailableCommand, dvsc: DivineSelectedCommand) => + case (dvac: DivineAvailableCommand, dvsc: DivineSelectedCommand) => DivineCommand.make( actingFactionId = actingFactionId, actingProvinceId = dvac.actingProvinceId, @@ -270,7 +252,7 @@ class CommandFactory { currentDate = gameState.currentDate.get, actingProvince = gameState.provinces(evac.actingProvinceId) ) - case (ac: FeastAvailableCommand, _: FeastSelectedCommand) => + case (ac: FeastAvailableCommand, _: FeastSelectedCommand) => val province = gameState.provinces(ac.actingProvinceId) FeastCommand.make( actingFactionId = actingFactionId, @@ -287,8 +269,7 @@ class CommandFactory { FreeForAllDecisionCommand.make( actingFactionId = actingFactionId, provinceId = ac.provinceId, - selectedDecision = - convertAttackDecisionToFreeForAllDecision(sc.decision), + selectedDecision = convertAttackDecisionToFreeForAllDecision(sc.decision), availableDecisions = ac.availableDecisions.toVector .map(convertAttackDecisionToFreeForAllDecision) ) @@ -309,7 +290,7 @@ class CommandFactory { HandleCapturedHeroesCommand.AvailableCapturedHeroWithOptions( heroId = ch.getHero.id, capturedFromFactionId = ch.previousFactionId, - options = ch.options.map { handleCapturedHeroOption }.toVector + options = ch.options.map(handleCapturedHeroOption).toVector ) }.toVector, selectedCapturedHero = gameState.heroes(sc.heroId), @@ -352,7 +333,7 @@ class CommandFactory { foodAvailable = ac.foodAvailable, goldAvailable = ac.goldAvailable ) - case (ac: HeroGiftAvailableCommand, sc: HeroGiftSelectedCommand) => + case (ac: HeroGiftAvailableCommand, sc: HeroGiftSelectedCommand) => HeroGiftCommand.make( actingFactionId = actingFactionId, actingProvince = gameState.provinces(ac.actingProvinceId), @@ -378,13 +359,12 @@ class CommandFactory { factionProvinces = gameState.provinces.values.toVector .filter(_.rulingFactionId.contains(actingFactionId)) ) - case (ac: ImproveAvailableCommand, sc: ImproveSelectedCommand) => + case (ac: ImproveAvailableCommand, sc: ImproveSelectedCommand) => ImproveCommand.make( actingFactionId = actingFactionId, actingHero = gameState.heroes(sc.actingHeroId), actingProvince = gameState.provinces(ac.actingProvinceId), - improvementType = - ImprovementTypeConverter.fromProto(sc.improvementType).get, + improvementType = ImprovementTypeConverter.fromProto(sc.improvementType).get, availableHeroIds = ac.availableHeroIds.toVector, availableImprovementTypes = ac.availableTypes .flatMap( @@ -425,7 +405,7 @@ class CommandFactory { allProvinces = allProvinces(gameState), questFulfillmentChecker = questFulfillmentChecker(gameState) ) - case (ac: MarchAvailableCommand, sc: MarchSelectedCommand) => + case (ac: MarchAvailableCommand, sc: MarchSelectedCommand) => val commandForOrigin = ac.oneProvinceCommands .find(_.originProvinceId == sc.originProvince) .get @@ -434,17 +414,14 @@ class CommandFactory { actingFactionId = actingFactionId, originProvinceId = sc.originProvince, destinationProvinceId = sc.destinationProvinceId, - marchingUnits = - sc.marchingUnits.map(CombatUnitConverter.fromProto).toVector, + marchingUnits = sc.marchingUnits.map(CombatUnitConverter.fromProto).toVector, gold = sc.gold, food = sc.food, - availableDestinationProvinceIds = - commandForOrigin.availableDestinationProvinces - .map(_.provinceId) - .toVector, + availableDestinationProvinceIds = commandForOrigin.availableDestinationProvinces + .map(_.provinceId) + .toVector, availableHeroIds = commandForOrigin.availableHeroIds.toVector, - availableBattalionIds = - commandForOrigin.availableBattalions.map(_.battalionId).toVector, + availableBattalionIds = commandForOrigin.availableBattalions.map(_.battalionId).toVector, goldAvailable = commandForOrigin.goldAvailable, foodAvailable = commandForOrigin.foodAvailable, currentRoundId = gameState.currentRoundId, @@ -479,8 +456,7 @@ class CommandFactory { id = cb.id, dismissedTroops = cb.dismissedTroops, newTroops = cb.newTroops, - troopsFromOtherBattalion = - cb.troopsFromOtherBattalion.map(tfobConverter).toVector + troopsFromOtherBattalion = cb.troopsFromOtherBattalion.map(tfobConverter).toVector ) ) .toVector, @@ -489,8 +465,7 @@ class CommandFactory { OrganizeTroopsCommand.NewBattalion( `type` = BattalionTypeIdConverter.fromProto(nb.`type`), newTroops = nb.newTroops, - troopsFromOtherBattalion = - nb.troopsFromOtherBattalion.map(tfobConverter).toVector + troopsFromOtherBattalion = nb.troopsFromOtherBattalion.map(tfobConverter).toVector ) ) .toVector, @@ -631,7 +606,7 @@ class CommandFactory { val domainOffer = DiplomacyOfferConverter.fromProto(selectedOffer) match { case truceOffer: TruceOffer => truceOffer - case _ => throw new EagleInternalException("Expected TruceOffer") + case _ => throw new EagleInternalException("Expected TruceOffer") } ResolveTruceOfferCommand.make( @@ -641,8 +616,7 @@ class CommandFactory { messengerOriginProvinceId = selectedOffer.messengerOriginProvinceId, truceOffer = domainOffer, resolution = StatusConverter.fromProto(sc.resolution), - availableOriginatingFactionIds = - ac.offers.map(_.originatingFactionId).toVector, + availableOriginatingFactionIds = ac.offers.map(_.originatingFactionId).toVector, availableResolutions = selectedOffer.eligibleStatuses .map(StatusConverter.fromProto) .toVector, @@ -656,7 +630,7 @@ class CommandFactory { ) => // TODO: after the Availability is migrated off protobuf, move these checks into the "make" method val originatingFid = sc.originatingFactionId - val selectedOffer = ac.offers + val selectedOffer = ac.offers .find(_.originatingFactionId == originatingFid) .getOrElse( throw new EagleCommandException( @@ -692,7 +666,7 @@ class CommandFactory { ) => // TODO: after the Availability is migrated off protobuf, move these checks into the "make" method val originatingFid = sc.originatingFactionId - val selectedOffer = ac.offers + val selectedOffer = ac.offers .find(_.originatingFactionId == originatingFid) .getOrElse( throw new EagleCommandException( @@ -729,7 +703,7 @@ class CommandFactory { import net.eagle0.eagle.model.proto_converters.TributeAmountConverter // TODO: after the Availability is migrated off protobuf, move these checks into the "make" method - val demandingFid = sc.demandingFactionId + val demandingFid = sc.demandingFactionId val selectedDemand = ac.demands .find(_.demandingFactionId == demandingFid) .getOrElse( @@ -737,7 +711,7 @@ class CommandFactory { s"Selected faction ID $demandingFid was not among options ${ac.demands.map(_.demandingFactionId)}" ) ) - val tributeAmount = + val tributeAmount = TributeAmountConverter.fromProto(selectedDemand.tributeDemanded.get) ResolveTributeCommand.make( @@ -745,8 +719,7 @@ class CommandFactory { demandingFactionId = demandingFid, tributeAmount = tributeAmount, paid = sc.paid, - availableDemandingFactionIds = - ac.demands.map(_.demandingFactionId).toVector, + availableDemandingFactionIds = ac.demands.map(_.demandingFactionId).toVector, actingProvinceId = ac.actingProvinceId, availableGold = ac.availableGold, availableFood = ac.availableFood, @@ -756,19 +729,17 @@ class CommandFactory { allProvinces = allProvinces(gameState) ) - case (ac: RestAvailableCommand, sc: RestSelectedCommand) => + case (ac: RestAvailableCommand, sc: RestSelectedCommand) => RestCommand.make( actingFactionId = actingFactionId, provinceId = ac.actingProvinceId, - factionHeroesInProvince = - factionHeroesInProvince(gameState, ac.actingProvinceId) + factionHeroesInProvince = factionHeroesInProvince(gameState, ac.actingProvinceId) ) case (ac: ReturnAvailableCommand, sc: ReturnSelectedCommand) => ReturnCommand.make( actingFactionId = actingFactionId, provinceId = ac.actingProvinceId, - rulerIsTraveling = - gameState.provinces(ac.actingProvinceId).rulerIsTraveling + rulerIsTraveling = gameState.provinces(ac.actingProvinceId).rulerIsTraveling ) case ( ac: SendSuppliesAvailableCommand, @@ -779,8 +750,7 @@ class CommandFactory { actingHeroId = sc.actingHeroId, originProvinceId = ac.actingProvinceId, destinationProvinceId = sc.destinationProvinceId, - availableDestinationProvinceIds = - ac.availableDestinationProvinceIds.toVector, + availableDestinationProvinceIds = ac.availableDestinationProvinceIds.toVector, availableHeroIds = ac.availableHeroIds.toVector, goldAvailable = ac.goldAvailable, foodAvailable = ac.foodAvailable, @@ -798,8 +768,7 @@ class CommandFactory { actingProvinceId = ac.actingProvinceId, targetProvinceId = sc.selectedProvinceId, availableHeroIds = ac.availableHeroIds.toVector, - availableTargetProvinceIds = - ac.options.map(_.targetProvinceId).toVector + availableTargetProvinceIds = ac.options.map(_.targetProvinceId).toVector ) case ( @@ -834,7 +803,7 @@ class CommandFactory { gameId = gameState.gameId ) - case (ac: TradeAvailableCommand, sc: TradeSelectedCommand) => + case (ac: TradeAvailableCommand, sc: TradeSelectedCommand) => TradeCommand.make( actingFactionId = actingFactionId, actingProvince = gameState.provinces(ac.actingProvinceId), @@ -847,7 +816,7 @@ class CommandFactory { }, amount = sc.amount ) - case (ac: TrainAvailableCommand, sc: TrainSelectedCommand) => + case (ac: TrainAvailableCommand, sc: TrainSelectedCommand) => val province = gameState.provinces(ac.actingProvinceId) TrainCommand.make( actingFactionId = actingFactionId, @@ -873,13 +842,13 @@ class CommandFactory { s"$x failed to match AvailableCommand / SelectedCommand pair: $availableCommand / $selectedCommand" ) }) match { - case protolessSimpleAction: ProtolessSimpleAction => + case protolessSimpleAction: ProtolessSimpleAction => new ProtolessSimpleActionWrapper( startingState = gameState, protolessSimpleAction = protolessSimpleAction, selectedCommand = selectedCommand ) - case protolessRandomSimpleAction: ProtolessRandomSimpleAction => + case protolessRandomSimpleAction: ProtolessRandomSimpleAction => new ProtolessRandomSimpleActionWrapper( startingState = gameState, protolessRandomSimpleAction = protolessRandomSimpleAction, @@ -896,14 +865,14 @@ class CommandFactory { private def attackDecision(proto: AttackDecisionType): AttackDecision = proto match { - case AdvanceDecision(_) => AttackDecisionCommand.Advance - case WithdrawDecision(_) => AttackDecisionCommand.Withdraw + case AdvanceDecision(_) => AttackDecisionCommand.Advance + case WithdrawDecision(_) => AttackDecisionCommand.Withdraw case DemandTributeDecision(tributeAmountProto, _) => AttackDecisionCommand.DemandTribute( TributeAmountConverter.fromProto(tributeAmountProto.get) ) - case SafePassageDecision(toProvinceId, _) => SafePassage(toProvinceId) - case AttackDecisionType.Empty => + case SafePassageDecision(toProvinceId, _) => SafePassage(toProvinceId) + case AttackDecisionType.Empty => throw new ProtoConversionException("Empty AttackDecisionType") } @@ -916,8 +885,7 @@ class CommandFactory { ) => PrisonerToManage( heroId = prisoner.get.getHero.id, - availableOptions = - availableOptions.map(prisonerManagementOption).toVector + availableOptions = availableOptions.map(prisonerManagementOption).toVector ) case _ => throw new ProtoConversionException("Empty PrisonerToManageProto") @@ -927,16 +895,16 @@ class CommandFactory { proto: PrisonerManagementOptionProto ): PrisonerManagementOption = proto match { - case PrisonerManagementOptionMove(toProvinceId, _) => + case PrisonerManagementOptionMove(toProvinceId, _) => PrisonerManagementOption.Move(toProvinceId) - case PrisonerManagementOptionExecute(_) => + case PrisonerManagementOptionExecute(_) => PrisonerManagementOption.Execute - case PrisonerManagementOptionExile(_) => PrisonerManagementOption.Exile - case PrisonerManagementOptionRelease(_) => + case PrisonerManagementOptionExile(_) => PrisonerManagementOption.Exile + case PrisonerManagementOptionRelease(_) => PrisonerManagementOption.Release case PrisonerManagementOptionReturn(toFactionId, _) => PrisonerManagementOption.Return(toFactionId) - case _ => + case _ => throw new ProtoConversionException( "Empty PrisonerManagementOptionProto" ) @@ -946,17 +914,17 @@ class CommandFactory { proto: CapturedHeroOption ): HandleCapturedHeroesCommand.CapturedHeroOption = proto match { - case CapturedHeroOption.UNKNOWN_CAPTURED_HERO_OPTION => + case CapturedHeroOption.UNKNOWN_CAPTURED_HERO_OPTION => HandleCapturedHeroesCommand.CapturedHeroOption.Unknown - case CapturedHeroOption.RECRUIT_CAPTURED_HERO_OPTION => + case CapturedHeroOption.RECRUIT_CAPTURED_HERO_OPTION => HandleCapturedHeroesCommand.CapturedHeroOption.Recruit - case CapturedHeroOption.IMPRISON_CAPTURED_HERO_OPTION => + case CapturedHeroOption.IMPRISON_CAPTURED_HERO_OPTION => HandleCapturedHeroesCommand.CapturedHeroOption.Imprison - case CapturedHeroOption.EXILE_CAPTURED_HERO_OPTION => + case CapturedHeroOption.EXILE_CAPTURED_HERO_OPTION => HandleCapturedHeroesCommand.CapturedHeroOption.Exile - case CapturedHeroOption.EXECUTE_CAPTURED_HERO_OPTION => + case CapturedHeroOption.EXECUTE_CAPTURED_HERO_OPTION => HandleCapturedHeroesCommand.CapturedHeroOption.Execute - case CapturedHeroOption.RETURN_CAPTURED_HERO_OPTION => + case CapturedHeroOption.RETURN_CAPTURED_HERO_OPTION => HandleCapturedHeroesCommand.CapturedHeroOption.Return case CapturedHeroOption.Unrecognized(unrecognizedValue) => throw new ProtoConversionException( @@ -967,11 +935,11 @@ class CommandFactory { private val controlWeatherTypeMap: Map[ ControlWeatherTypeProto, ControlWeatherCommand.ControlWeatherType - ] = Map( - ControlWeatherTypeProto.CONTROL_WEATHER_UNKNOWN -> ControlWeatherCommand.ControlWeatherType.Unknown, + ] = Map( + ControlWeatherTypeProto.CONTROL_WEATHER_UNKNOWN -> ControlWeatherCommand.ControlWeatherType.Unknown, ControlWeatherTypeProto.CONTROL_WEATHER_START_BLIZZARD -> ControlWeatherCommand.ControlWeatherType.StartBlizzard, - ControlWeatherTypeProto.CONTROL_WEATHER_END_BLIZZARD -> ControlWeatherCommand.ControlWeatherType.EndBlizzard, - ControlWeatherTypeProto.CONTROL_WEATHER_START_DROUGHT -> ControlWeatherCommand.ControlWeatherType.StartDrought, - ControlWeatherTypeProto.CONTROL_WEATHER_END_DROUGHT -> ControlWeatherCommand.ControlWeatherType.EndDrought + ControlWeatherTypeProto.CONTROL_WEATHER_END_BLIZZARD -> ControlWeatherCommand.ControlWeatherType.EndBlizzard, + ControlWeatherTypeProto.CONTROL_WEATHER_START_DROUGHT -> ControlWeatherCommand.ControlWeatherType.StartDrought, + ControlWeatherTypeProto.CONTROL_WEATHER_END_DROUGHT -> ControlWeatherCommand.ControlWeatherType.EndDrought ) } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommand.scala index 880ca91dc7..89aa77ca2a 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommand.scala @@ -11,11 +11,7 @@ import net.eagle0.eagle.library.settings.{ import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.WeatherAlteredResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.province.DeferredChange.{ @@ -28,11 +24,11 @@ import net.eagle0.eagle.model.state.province.DeferredChange.{ object ControlWeatherCommand { sealed trait ControlWeatherType object ControlWeatherType { - case object EndBlizzard extends ControlWeatherType + case object EndBlizzard extends ControlWeatherType case object StartBlizzard extends ControlWeatherType - case object StartDrought extends ControlWeatherType - case object EndDrought extends ControlWeatherType - case object Unknown extends ControlWeatherType + case object StartDrought extends ControlWeatherType + case object EndDrought extends ControlWeatherType + case object Unknown extends ControlWeatherType } case class ControlWeatherOption( @@ -49,31 +45,30 @@ object ControlWeatherCommand { ) extends ProtolessSimpleAction { import ControlWeatherType.* - private def changedTargetedProvince: ChangedProvinceC = { + private def changedTargetedProvince: ChangedProvinceC = ChangedProvinceC( provinceId = targetProvinceId, newDeferredChange = Some(actionType match { - case EndBlizzard => + case EndBlizzard => BlizzardEnded(responsibleFaction = factionId) case StartBlizzard => BlizzardStarted( responsibleFaction = factionId, durationMonths = ControlWeatherBlizzardDurationMonths.intValue ) - case StartDrought => + case StartDrought => DroughtStarted( responsibleFaction = factionId, durationMonths = ControlWeatherDroughtDurationMonths.intValue ) - case EndDrought => + case EndDrought => DroughtEnded(responsibleFaction = factionId) - case Unknown => + case Unknown => throw new EagleInternalException( s"Unknown control weather type: $actionType" ) }) ) - } private def changedHero: ChangedHeroC = ChangedHeroC( @@ -82,7 +77,7 @@ object ControlWeatherCommand { wisdomXpDelta = Some(ControlWeatherWisdomXp.intValue) ) - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = ActionResultC( actionResultType = WeatherAlteredResultType, actingFactionId = Some(factionId), @@ -92,7 +87,6 @@ object ControlWeatherCommand { changedProvinces = Vector(changedTargetedProvince), changedHeroes = Vector(changedHero) ) - } } def make( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommand.scala index ad9a7fb31d..bba43648e5 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommand.scala @@ -5,12 +5,7 @@ import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.settings.{ActionVigorCost, TruceMonths} import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.concrete.ChangedFactionC.{ OutgoingAllianceOfferFactionId, OutgoingInvitationFactionId, @@ -115,7 +110,7 @@ object DiplomacyCommand { ) // Validation logic for ransom offers - val prisonerHeroId = prisonerToBeRansomed.prisonerHeroId + val prisonerHeroId = prisonerToBeRansomed.prisonerHeroId val prisonerProvinceId = prisonerToBeRansomed.provinceIdForPrisoner // Basic validation that required fields are present @@ -260,7 +255,7 @@ object DiplomacyCommand { endDate = currentDate.addMonths(TruceMonths.intValue) ) - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = genericDiplomacyResult( actingProvince = actingProvince, actingHero = actingHero, @@ -274,8 +269,7 @@ object DiplomacyCommand { ), ChangedFactionC( factionId = fid, - newOutgoingTruceOfferFactionIds = - Vector(OutgoingTruceOfferFactionId(targetFid)) + newOutgoingTruceOfferFactionIds = Vector(OutgoingTruceOfferFactionId(targetFid)) ) ), newGeneratedTextRequests = Vector( @@ -290,7 +284,6 @@ object DiplomacyCommand { ) ) ) - } } private case class AllianceCommand( @@ -315,7 +308,7 @@ object DiplomacyCommand { offerTextId = textId ) - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = genericDiplomacyResult( actingProvince = actingProvince, actingHero = actingHero, @@ -329,8 +322,7 @@ object DiplomacyCommand { ), ChangedFactionC( factionId = fid, - newOutgoingAllianceOfferFactionIds = - Vector(OutgoingAllianceOfferFactionId(targetFid)) + newOutgoingAllianceOfferFactionIds = Vector(OutgoingAllianceOfferFactionId(targetFid)) ) ), newGeneratedTextRequests = Vector( @@ -345,7 +337,6 @@ object DiplomacyCommand { ) ) ) - } } private case class BreakAllianceCommand( @@ -370,7 +361,7 @@ object DiplomacyCommand { offerTextId = textId ) - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = genericDiplomacyResult( actingProvince = actingProvince, actingHero = actingHero, @@ -395,7 +386,6 @@ object DiplomacyCommand { ) ) ) - } } private case class InviteCommand( @@ -419,7 +409,7 @@ object DiplomacyCommand { offerTextId = textId ) - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = genericDiplomacyResult( actingProvince = actingProvince, actingHero = actingHero, @@ -433,8 +423,7 @@ object DiplomacyCommand { ), ChangedFactionC( factionId = fid, - newOutgoingInvitationFactionIds = - Vector(OutgoingInvitationFactionId(targetFid)) + newOutgoingInvitationFactionIds = Vector(OutgoingInvitationFactionId(targetFid)) ) ), newGeneratedTextRequests = Vector( @@ -449,7 +438,6 @@ object DiplomacyCommand { ) ) ) - } } private case class RansomCommand( @@ -480,7 +468,7 @@ object DiplomacyCommand { goldOffered = goldOffered ) - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = ActionResultC( actionResultType = RansomStartedResultType, provinceId = Some(pid), @@ -493,8 +481,7 @@ object DiplomacyCommand { ), ChangedFactionC( factionId = fid, - newOutgoingRansomOfferFactionIds = - Vector(OutgoingRansomOfferFactionId(targetFid)) + newOutgoingRansomOfferFactionIds = Vector(OutgoingRansomOfferFactionId(targetFid)) ) ), newGeneratedTextRequests = Vector( @@ -513,7 +500,6 @@ object DiplomacyCommand { ) ) ) - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommand.scala index 698eaa46f5..ad6438f07a 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommand.scala @@ -7,17 +7,11 @@ import net.eagle0.eagle.library.actions.impl.common.ProtolessRandomSimpleAction import net.eagle0.eagle.library.settings.GoldCostForDivine import net.eagle0.eagle.library.util.faction_utils.FactionUtils import net.eagle0.eagle.library.util.unaffiliated_hero.UnaffiliatedHeroUtils -import net.eagle0.eagle.library.util.EagleRequire.{ - commandRequire, - internalRequire -} +import net.eagle0.eagle.library.util.EagleRequire.{commandRequire, internalRequire} import net.eagle0.eagle.library.util.PriceIndexUtils import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.types.DivinedResultType import net.eagle0.eagle.model.action_result.NotificationDetails.Divined @@ -106,26 +100,27 @@ object DivineCommand { } functionalRandom - .nextFlatMap(divinedHeroIds) { case (hid, fr) => - actingProvince.unaffiliatedHeroes - .find(_.heroId == hid) - .map(uh => - UnaffiliatedHeroUtils - .randomNewRecruitmentInfo( - provinceId = actingProvince.id, - allProvinces = allProvinces, - factions = factions, - battalions = battalions, - functionalRandom = fr - ) - .map { newRI => - Vector( - if uh.quest.isDefined then uh - else uh.withRecruitmentInfo(newRI) + .nextFlatMap(divinedHeroIds) { + case (hid, fr) => + actingProvince.unaffiliatedHeroes + .find(_.heroId == hid) + .map(uh => + UnaffiliatedHeroUtils + .randomNewRecruitmentInfo( + provinceId = actingProvince.id, + allProvinces = allProvinces, + factions = factions, + battalions = battalions, + functionalRandom = fr ) - } - ) - .getOrElse(RandomState(Vector(), fr)) + .map { newRI => + Vector( + if uh.quest.isDefined then uh + else uh.withRecruitmentInfo(newRI) + ) + } + ) + .getOrElse(RandomState(Vector(), fr)) } .map { updatedUHRs => updatedUHRs.map { updatedUH => @@ -142,15 +137,14 @@ object DivineCommand { (updatedUhWithLlmRequestsRs: Vector[ (UnaffiliatedHeroT, LlmRequestT) ]) => - val notificationsWithLlmRequests - : Vector[(NotificationT, LlmRequestT)] = - updatedUhWithLlmRequestsRs.map { case (updatedUH, llmRequest) => - val updatedProvinceIds: Vector[ProvinceId] = - updatedUH.quest - .collect { - case SpecificExpansionQuest(provinceId) => + val notificationsWithLlmRequests: Vector[(NotificationT, LlmRequestT)] = + updatedUhWithLlmRequestsRs.map { + case (updatedUH, llmRequest) => + val updatedProvinceIds: Vector[ProvinceId] = + updatedUH.quest.collect { + case SpecificExpansionQuest(provinceId) => Vector(provinceId) - case DefeatFactionQuest(targetFactionId) => + case DefeatFactionQuest(targetFactionId) => FactionUtils .provinces(targetFactionId, allProvinces) .map(_.id) @@ -173,19 +167,19 @@ object DivineCommand { ) => Vector(provinceId) } - .getOrElse(Vector()) + .getOrElse(Vector()) - ( - NotificationC( - targetFactionIds = Vector(factionId), - llm = Llm.Id(llmRequest.requestId), - affectedProvinceIds = updatedProvinceIds, - affectedHeroIds = Vector(updatedUH.heroId), - details = Divined, - deferred = false - ), - llmRequest - ) + ( + NotificationC( + targetFactionIds = Vector(factionId), + llm = Llm.Id(llmRequest.requestId), + affectedProvinceIds = updatedProvinceIds, + affectedHeroIds = Vector(updatedUH.heroId), + details = Divined, + deferred = false + ), + llmRequest + ) } val cost = totalCost( @@ -201,13 +195,11 @@ object DivineCommand { ChangedProvinceC( provinceId = actingProvince.id, goldDelta = Some(-cost), - newPriceIndex = - PriceIndexUtils.maybeNewPriceIndexFromGoldSpend( - actingProvince.priceIndex, - cost - ), - changedUnaffiliatedHeroes = - updatedUhWithLlmRequestsRs.map(_._1) + newPriceIndex = PriceIndexUtils.maybeNewPriceIndexFromGoldSpend( + actingProvince.priceIndex, + cost + ), + changedUnaffiliatedHeroes = updatedUhWithLlmRequestsRs.map(_._1) ) ), newNotifications = notificationsWithLlmRequests.map(_._1), diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommand.scala index d58e2a161d..7664af6e93 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommand.scala @@ -4,33 +4,17 @@ import net.eagle0.eagle.{FactionId, GameId, HeroId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.settings.ExiledHeroFactionBias import net.eagle0.eagle.library.util.EagleRequire.clientRequire -import net.eagle0.eagle.model.action_result.{ - ActionResultT, - NotificationDetails, - NotificationT -} +import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.ExileVassalMessage import net.eagle0.eagle.model.action_result.types.VassalExiledResultType import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.hero.{ - EventForHeroBackstoryT, - ExiledBackstoryEvent, - HeroT -} +import net.eagle0.eagle.model.state.hero.{EventForHeroBackstoryT, ExiledBackstoryEvent, HeroT} import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.DismissSpecificVassalQuest -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC object ExileVassalCommand { @@ -74,8 +58,7 @@ object ExileVassalCommand { unaffiliatedHeroType = UnaffiliatedHeroType.Traveler, roundsInType = 0, recruitmentAttempted = false, - factionBiases = - Map(hero.factionId.get -> ExiledHeroFactionBias.doubleValue), + factionBiases = Map(hero.factionId.get -> ExiledHeroFactionBias.doubleValue), lastFactionId = None, recruitmentInfo = RecruitmentInfo.Exile, pleaseRecruitMeRejectionDate = None @@ -91,7 +74,7 @@ object ExileVassalCommand { ) extends ProtolessSimpleAction { override def immediateExecute: ActionResultT = { val notificationLlmId = - s"${currentRoundId} exile vassal ${exiledHeroBefore.id}" + s"$currentRoundId exile vassal ${exiledHeroBefore.id}" ActionResultC( actionResultType = VassalExiledResultType, actingFactionId = Some(factionId), @@ -111,8 +94,7 @@ object ExileVassalCommand { ChangedProvinceC( provinceId = actingProvince.id, removedRulingFactionHeroIds = Vector(exiledHeroBefore.id), - newUnaffiliatedHeroes = - Vector(exiledUnaffiliatedHero(exiledHeroBefore)) + newUnaffiliatedHeroes = Vector(exiledUnaffiliatedHero(exiledHeroBefore)) ) ), newNotifications = Vector( @@ -136,15 +118,13 @@ object ExileVassalCommand { actingHeroId = actingProvince.rulingHeroId.get, actingFactionId = factionId, provinceId = actingProvince.id, - requestingHeroIds = actingProvince.unaffiliatedHeroes - .filter { uh => - uh.quest - .exists { - case DismissSpecificVassalQuest(targetHeroId) => - targetHeroId == exiledHeroBefore.id - case _ => false - } + requestingHeroIds = actingProvince.unaffiliatedHeroes.filter { uh => + uh.quest.exists { + case DismissSpecificVassalQuest(targetHeroId) => + targetHeroId == exiledHeroBefore.id + case _ => false } + } .map(_.heroId) ) ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommand.scala index 91e41e5347..50463513c1 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommand.scala @@ -2,18 +2,10 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, HeroId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction -import net.eagle0.eagle.library.settings.{ - LoyaltyGainFromFeast, - VigorGainFromFeast -} +import net.eagle0.eagle.library.settings.{LoyaltyGainFromFeast, VigorGainFromFeast} import net.eagle0.eagle.library.util.PriceIndexUtils import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta, - StatNoChange -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta, StatNoChange} import net.eagle0.eagle.model.action_result.types.FeastResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.hero.HeroT diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommand.scala index 6ea3bb4eb2..4858ae328a 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommand.scala @@ -11,14 +11,11 @@ import net.eagle0.eagle.model.action_result.types.{ ArmyWithdrewFromFreeForAllResultType } import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - AwaitingFreeForAll, - Withdrawing -} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{AwaitingFreeForAll, Withdrawing} object FreeForAllDecisionCommand { sealed trait FreeForAllDecision - case object Advance extends FreeForAllDecision + case object Advance extends FreeForAllDecision case object Withdraw extends FreeForAllDecision private case class FreeForAllAttackCommand( @@ -81,7 +78,7 @@ object FreeForAllDecisionCommand { ) selectedDecision match { - case Advance => + case Advance => FreeForAllAttackCommand( attackingFactionId = actingFactionId, provinceId = provinceId diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommand.scala index 5c375eba37..52f2d6bc4a 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommand.scala @@ -18,11 +18,7 @@ import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.util.ProvinceDistances import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatAbsolute -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatAbsolute} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.RecruitmentRefusedMessage import net.eagle0.eagle.model.action_result.types.{ @@ -35,10 +31,7 @@ import net.eagle0.eagle.model.action_result.types.{ import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.faction.FactionT -import net.eagle0.eagle.model.state.hero.{ - CapturedHeroRecruitedBackstoryEvent, - HeroT -} +import net.eagle0.eagle.model.state.hero.{CapturedHeroRecruitedBackstoryEvent, HeroT} import net.eagle0.eagle.model.state.province.DeferredChange.{ CapturedHeroExecuted, CapturedHeroExiled, @@ -51,12 +44,12 @@ import net.eagle0.eagle.model.state.CapturedHero object HandleCapturedHeroesCommand { sealed trait CapturedHeroOption object CapturedHeroOption { - case object Unknown extends CapturedHeroOption - case object Recruit extends CapturedHeroOption + case object Unknown extends CapturedHeroOption + case object Recruit extends CapturedHeroOption case object Imprison extends CapturedHeroOption - case object Exile extends CapturedHeroOption - case object Execute extends CapturedHeroOption - case object Return extends CapturedHeroOption + case object Exile extends CapturedHeroOption + case object Execute extends CapturedHeroOption + case object Return extends CapturedHeroOption } case class AvailableCapturedHeroWithOptions( @@ -107,81 +100,82 @@ object HandleCapturedHeroesCommand { ): RandomState[ActionResultT] = functionalRandom .nextInt(0, 100) - .continue { case (roll, fr) => - val odds = scoreForCapturedHero( - /* factionLeader = */ actingFactionHead, - /* prestige = */ FactionUtils.prestige(actingFaction, allProvinces), - /* targetHero = */ capturedHero - ) - - val ar = if roll < odds then { - val recruitedBackstoryEvent = CapturedHeroRecruitedBackstoryEvent( - date = currentDate, - capturingFactionId = actingFaction.id, - capturingHeroId = actingHeroId, - provinceId = province.id + .continue { + case (roll, fr) => + val odds = scoreForCapturedHero( + /* factionLeader = */ actingFactionHead, + /* prestige = */ FactionUtils.prestige(actingFaction, allProvinces), + /* targetHero = */ capturedHero ) - withNextPlea( + val ar = if roll < odds then { + val recruitedBackstoryEvent = CapturedHeroRecruitedBackstoryEvent( + date = currentDate, + capturingFactionId = actingFaction.id, + capturingHeroId = actingHeroId, + provinceId = province.id + ) + + withNextPlea( + ActionResultC( + actingFactionId = Some(actingFaction.id), + actionResultType = RecruitHeroesResultType, + provinceId = Some(province.id), + changedHeroes = Vector( + ChangedHeroC( + heroId = capturedHero.id, + newFactionId = Some(actingFaction.id), + loyaltyChange = StatAbsolute(StartingLoyalty.doubleValue), + newEventsForHeroBackstory = Vector(recruitedBackstoryEvent) + ) + ), + changedProvinces = Vector( + ChangedProvinceC( + provinceId = province.id, + newRulingFactionHeroIds = Vector(capturedHero.id), + removedCapturedHeroIds = Vector(capturedHero.id) + ) + ), + newRandomSeed = Some(fr.seed) + ) + ) + } else { + val existingCh = province.capturedHeroes + .find(_.heroId == capturedHero.id) + .get + + val rrPlea = recruitmentRefusedPlea( + gameId = gameId, + currentRoundId = currentRoundId, + capturingHeroId = province.rulingHeroId.get, + capturingFactionId = actingFaction.id, + provinceId = province.id, + capturedHero = existingCh + ) + ActionResultC( actingFactionId = Some(actingFaction.id), actionResultType = RecruitHeroesResultType, provinceId = Some(province.id), - changedHeroes = Vector( - ChangedHeroC( - heroId = capturedHero.id, - newFactionId = Some(actingFaction.id), - loyaltyChange = StatAbsolute(StartingLoyalty.doubleValue), - newEventsForHeroBackstory = Vector(recruitedBackstoryEvent) - ) - ), changedProvinces = Vector( ChangedProvinceC( provinceId = province.id, - newRulingFactionHeroIds = Vector(capturedHero.id), - removedCapturedHeroIds = Vector(capturedHero.id) + removedCapturedHeroIds = Vector(capturedHero.id), + newCapturedHeroes = Vector( + existingCh + .copy( + recruitmentAttempted = true, + recruitmentRefusedMessageId = rrPlea.requestId + ) + ) ) ), - newRandomSeed = Some(fr.seed) + newRandomSeed = Some(fr.seed), + newGeneratedTextRequests = Vector(rrPlea) ) - ) - } else { - val existingCh = province.capturedHeroes - .find(_.heroId == capturedHero.id) - .get + } - val rrPlea = recruitmentRefusedPlea( - gameId = gameId, - currentRoundId = currentRoundId, - capturingHeroId = province.rulingHeroId.get, - capturingFactionId = actingFaction.id, - provinceId = province.id, - capturedHero = existingCh - ) - - ActionResultC( - actingFactionId = Some(actingFaction.id), - actionResultType = RecruitHeroesResultType, - provinceId = Some(province.id), - changedProvinces = Vector( - ChangedProvinceC( - provinceId = province.id, - removedCapturedHeroIds = Vector(capturedHero.id), - newCapturedHeroes = Vector( - existingCh - .copy( - recruitmentAttempted = true, - recruitmentRefusedMessageId = rrPlea.requestId - ) - ) - ) - ), - newRandomSeed = Some(fr.seed), - newGeneratedTextRequests = Vector(rrPlea) - ) - } - - RandomState(newValue = ar, nextRandom = fr) + RandomState(newValue = ar, nextRandom = fr) } private def imprisonHero: ActionResultT = @@ -232,7 +226,7 @@ object HandleCapturedHeroesCommand { ) ) - private lazy val destinationForReturnedHero: ProvinceId = { + private lazy val destinationForReturnedHero: ProvinceId = ProvinceDistances .closestProvinceOption( to = province.id, @@ -242,12 +236,10 @@ object HandleCapturedHeroesCommand { provinces = allProvinces ) .map(_.id), - eligibleNeighbors = pid => - allProvinces.find(_.id == pid).get.neighbors.map(_.provinceId) + eligibleNeighbors = pid => allProvinces.find(_.id == pid).get.neighbors.map(_.provinceId) ) .map(_.provinceId) .get // We shouldn't have had a Return option if there wasn't an eligible province - } private def returnHero: ActionResultT = withNextPlea( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommand.scala index 035a79c3c8..4c5c58428d 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommand.scala @@ -14,11 +14,7 @@ import net.eagle0.eagle.library.settings.{ import net.eagle0.eagle.library.util.BattalionPower import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedBattalionC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedBattalionC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.RiotSuppressedResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.battalion.BattalionT @@ -56,7 +52,7 @@ object HandleRiotCrackDownCommand { 0.0, roll - RiotRollCharismaReduction.doubleValue * rulingHero.charisma ) - val riotSize = + val riotSize = (reducedRoll * (MaxRiotSize.intValue - MinRiotSize.intValue)).toInt + MinRiotSize.intValue val rioterPower = riotSize * 1.0 @@ -99,8 +95,7 @@ object HandleRiotCrackDownCommand { Some( ChangedHeroC( heroId = actingHero.id, - vigorChange = - StatDelta(-ActionVigorCost.intValue - heroCasualties) + vigorChange = StatDelta(-ActionVigorCost.intValue - heroCasualties) ) ), optionalBattalion.map(_.id), @@ -168,7 +163,7 @@ object HandleRiotCrackDownCommand { val selectedHeroId = actingHero.id commandRequire( availableHeroIds.contains(selectedHeroId), - s"tried to send hero $selectedHeroId but ${availableHeroIds} were available" + s"tried to send hero $selectedHeroId but $availableHeroIds were available" ) val selectedBattalionIdOpt = optionalBattalion.map(_.id) @@ -176,7 +171,7 @@ object HandleRiotCrackDownCommand { selectedBattalionIdOpt.forall( availableBattalionIds.contains ), - s"tried to send battalion ${selectedBattalionIdOpt.get} but ${availableBattalionIds} were available" + s"tried to send battalion ${selectedBattalionIdOpt.get} but $availableBattalionIds were available" ) HandleRiotCrackDownCommand( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommand.scala index 7b10b76450..df5476fa9d 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommand.scala @@ -1,11 +1,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.common.{FunctionalRandom, RandomState} import net.eagle0.eagle.library.actions.impl.common.ProtolessRandomSimpleAction -import net.eagle0.eagle.library.settings.{ - RiotCharismaFactor, - RiotMaxFood, - RiotMaxGold -} +import net.eagle0.eagle.library.settings.{RiotCharismaFactor, RiotMaxFood, RiotMaxGold} import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.types.RiotAvertedResultType @@ -58,9 +54,8 @@ object HandleRiotGiveCommand { } } - def giftAvoidRiotChance(rulingHero: HeroT, giftFactor: Double): Double = { + def giftAvoidRiotChance(rulingHero: HeroT, giftFactor: Double): Double = rulingHero.charisma * RiotCharismaFactor.doubleValue / 100.0 + giftFactor * (1.0 - RiotCharismaFactor.doubleValue) - } case class HandleRiotGiveFoodCommand( factionId: FactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtils.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtils.scala index 6eed05f946..eea6a331fc 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtils.scala @@ -7,10 +7,7 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.concrete.ActionResultC -import net.eagle0.eagle.model.action_result.types.{ - RiotAversionFailedResultType, - RiotOccurredResultType -} +import net.eagle0.eagle.model.action_result.types.{RiotAversionFailedResultType, RiotOccurredResultType} import net.eagle0.eagle.model.action_result.types.base.ActionResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.province.{ImminentRiotEvent, ProvinceT} @@ -49,10 +46,8 @@ object HandleRiotUtils { } ), supportDelta = Some(RiotSupportDelta.doubleValue), - economyDevastationDelta = - Some(RiotEconomyDevastationDelta.doubleValue), - infrastructureDevastationDelta = - Some(RiotInfrastructureDevastationDelta.doubleValue) + economyDevastationDelta = Some(RiotEconomyDevastationDelta.doubleValue), + infrastructureDevastationDelta = Some(RiotInfrastructureDevastationDelta.doubleValue) ) ) ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommand.scala index 124ad98291..eee67b7804 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommand.scala @@ -9,20 +9,13 @@ import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentUtils import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.util.PriceIndexUtils import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.GiftedHeroResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.action_result.ActionResultT.ActionResultUpdater import net.eagle0.eagle.model.state.hero.HeroT import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.quest.concrete.{ - GiveToHeroesAcrossRealmQuest, - GiveToHeroesInProvinceQuest -} +import net.eagle0.eagle.model.state.quest.concrete.{GiveToHeroesAcrossRealmQuest, GiveToHeroesInProvinceQuest} import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroT object HeroGiftCommand { @@ -75,11 +68,12 @@ object HeroGiftCommand { private def giftInThisProvinceQuestCheck( uh: UnaffiliatedHeroT, province: ProvinceT - ): Boolean = { - uh.quest.collect { case GiveToHeroesInProvinceQuest(_, _, pid, _) => - pid == province.id + ): Boolean = + uh.quest.collect { + case GiveToHeroesInProvinceQuest(_, _, pid, _) => + pid == province.id } - }.getOrElse(false) + .getOrElse(false) private def giftInRecipientProvinceCounterIncrementer: ActionResultUpdater = QuestFulfillmentUtils.withCountersIncremented( @@ -92,8 +86,7 @@ object HeroGiftCommand { uh: UnaffiliatedHeroT, @unused province: ProvinceT ): Boolean = - uh.quest - .collect { case GiveToHeroesAcrossRealmQuest(_, _, _) => true } + uh.quest.collect { case GiveToHeroesAcrossRealmQuest(_, _, _) => true } .getOrElse(false) private def giftAcrossRealmCounterIncrementer: ActionResultUpdater = diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommand.scala index 246067539e..6b583e2c51 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommand.scala @@ -11,15 +11,8 @@ import net.eagle0.eagle.library.settings.{ ImprovementXpPerStat } import net.eagle0.eagle.library.util.EagleRequire.commandRequire -import net.eagle0.eagle.model.action_result.changed_province.concrete.{ - ChangedProvinceC, - NewLockedImprovementType -} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.changed_province.concrete.{ChangedProvinceC, NewLockedImprovementType} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.ImproveResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.hero.{HeroT, Profession} @@ -68,7 +61,7 @@ object ImproveCommand { val provinceId = province.id val unscaledImprovement = ImprovementFromZero(actingHero) - val scaledImprovement = ScaleImprovement( + val scaledImprovement = ScaleImprovement( unscaledImprovement, improvementType match { case ImprovementType.Economy => province.economy @@ -81,8 +74,7 @@ object ImproveCommand { ) val withProfessionBonus = - if actingHero.profession == Profession.Engineer then - scaledImprovement + EngineerImprovementBonus.doubleValue + if actingHero.profession == Profession.Engineer then scaledImprovement + EngineerImprovementBonus.doubleValue else scaledImprovement val supportDelta = @@ -94,7 +86,7 @@ object ImproveCommand { else NewLockedImprovementType.None val changedProvince = improvementType match { - case ImprovementType.Economy => + case ImprovementType.Economy => val improvement = withProfessionBonus.min(maxImprovement - province.economy) ChangedProvinceC( @@ -103,7 +95,7 @@ object ImproveCommand { supportDelta = Some(supportDelta), newLockedImprovementType = Some(lockedImprovementType) ) - case ImprovementType.Agriculture => + case ImprovementType.Agriculture => val improvement = withProfessionBonus.min(maxImprovement - province.agriculture) ChangedProvinceC( @@ -121,7 +113,7 @@ object ImproveCommand { supportDelta = Some(supportDelta), newLockedImprovementType = Some(lockedImprovementType) ) - case ImprovementType.Devastation => + case ImprovementType.Devastation => val improvement = withProfessionBonus ChangedProvinceC( provinceId = provinceId, @@ -131,7 +123,7 @@ object ImproveCommand { supportDelta = Some(supportDelta), newLockedImprovementType = Some(lockedImprovementType) ) - case _ => throw new IllegalArgumentException("Unknown Improvement type") + case _ => throw new IllegalArgumentException("Unknown Improvement type") } val leaderAfter = ChangedHeroC( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommand.scala index fe05eeff57..110624b40f 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommand.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC} import net.eagle0.eagle.model.action_result.types.OrdersIssuedResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.faction.FactionT @@ -28,11 +25,12 @@ object IssueOrdersCommand { actingFactionId = Some(actingFaction.id), provinceId = Some(actingProvinceId), provinceIdActed = None, - changedProvinces = newOrders.map { case ProvinceOrders(pid, ord) => - ChangedProvinceC( - provinceId = pid, - newProvinceOrders = Some(ord) - ) + changedProvinces = newOrders.map { + case ProvinceOrders(pid, ord) => + ChangedProvinceC( + provinceId = pid, + newProvinceOrders = Some(ord) + ) }, changedFactions = Option .when(actingFaction.focusProvinceId != newFocusProvinceId) { diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtils.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtils.scala index 1927fcf523..4b5161b07b 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtils.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.common.action_result_type.ActionResultType -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - RIOT_AVERSION_FAILED, - RIOT_OCCURRED -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{RIOT_AVERSION_FAILED, RIOT_OCCURRED} import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.changed_province.ChangedProvince import net.eagle0.eagle.internal.changed_province.ChangedProvince.ProvinceEventsReplacement @@ -44,19 +41,16 @@ object LegacyHandleRiotUtils { setHasActed = Some(true), newProvinceEvents = Some( ProvinceEventsReplacement( - newEvents = province.activeEvents - .flatMap { - case ImminentRiotEvent() => - None - case event => Some(ProvinceEventConverter.toProto(event)) - } + newEvents = province.activeEvents.flatMap { + case ImminentRiotEvent() => + None + case event => Some(ProvinceEventConverter.toProto(event)) + } ) ), supportDelta = Some(RiotSupportDelta.doubleValue), - economyDevastationDelta = - Some(RiotEconomyDevastationDelta.doubleValue), - infrastructureDevastationDelta = - Some(RiotInfrastructureDevastationDelta.doubleValue) + economyDevastationDelta = Some(RiotEconomyDevastationDelta.doubleValue), + infrastructureDevastationDelta = Some(RiotInfrastructureDevastationDelta.doubleValue) ) ) ) @@ -80,7 +74,7 @@ object LegacyHandleRiotUtils { newEvents = province.activeEvents.flatMap { case ImminentRiotEvent() => None - case event => Some(ProvinceEventConverter.toProto(event)) + case event => Some(ProvinceEventConverter.toProto(event)) } ) ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommand.scala index 7ade0b6409..3a9c5daced 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommand.scala @@ -14,10 +14,7 @@ import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, NotificationC} import net.eagle0.eagle.model.action_result.types.{ PrisonerExecutedResultType, PrisonerExiledResultType, @@ -25,15 +22,9 @@ import net.eagle0.eagle.model.action_result.types.{ PrisonerReleasedResultType, PrisonerReturnedResultType } -import net.eagle0.eagle.model.state.province.DeferredChange.{ - PrisonerMoved, - PrisonerReturned -} +import net.eagle0.eagle.model.state.province.DeferredChange.{PrisonerMoved, PrisonerReturned} import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ MovingPrisoner, Outlaw, @@ -75,7 +66,7 @@ object ManagePrisonersCommand { import questMatcher.* override def results: Vector[ActionResultT] = selectedOption match { - case Release => + case Release => ActionResultC( actionResultType = PrisonerReleasedResultType, actingFactionId = Some(actingFactionId), @@ -94,23 +85,19 @@ object ManagePrisonersCommand { ) +: allProvinces.flatMap { checkedProvince => questFulfillmentChecker.fulfilledQuestResults( province = checkedProvince, - isFulfilled = - (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) + isFulfilled = (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - executePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => executePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - exilePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => exilePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - returnPrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => returnPrisonerQuestMatch(quest) ) } - case Exile => + case Exile => ActionResultC( actionResultType = PrisonerExiledResultType, actingFactionId = Some(actingFactionId), @@ -129,20 +116,16 @@ object ManagePrisonersCommand { ) +: allProvinces.flatMap { checkedProvince => questFulfillmentChecker.fulfilledQuestResults( province = checkedProvince, - isFulfilled = (quest, _ /*questHolderProvince*/ ) => - exilePrisonerQuestMatch(quest) + isFulfilled = (quest, _ /*questHolderProvince*/ ) => exilePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - executePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => executePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = - (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - returnPrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => returnPrisonerQuestMatch(quest) ) } case Return(toFactionId) => @@ -165,30 +148,25 @@ object ManagePrisonersCommand { toFactionId = toFactionId ) ), - changedUnaffiliatedHeroes = - Vector(prisonerUnaffiliatedHero.withType(ReturningPrisoner)) + changedUnaffiliatedHeroes = Vector(prisonerUnaffiliatedHero.withType(ReturningPrisoner)) ) ) ) +: allProvinces.flatMap { checkedProvince => questFulfillmentChecker.fulfilledQuestResults( province = checkedProvince, - isFulfilled = (quest, _ /*questHolderProvince*/ ) => - returnPrisonerQuestMatch(quest) + isFulfilled = (quest, _ /*questHolderProvince*/ ) => returnPrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - executePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => executePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - exilePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => exilePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = - (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) ) } - case Move(toProvinceId) => + case Move(toProvinceId) => ActionResultC( actionResultType = PrisonerMovedResultType, actingFactionId = Some(actingFactionId), @@ -203,30 +181,25 @@ object ManagePrisonersCommand { toProvinceId = toProvinceId ) ), - changedUnaffiliatedHeroes = - Vector(prisonerUnaffiliatedHero.withType(MovingPrisoner)) + changedUnaffiliatedHeroes = Vector(prisonerUnaffiliatedHero.withType(MovingPrisoner)) ) ) ) +: allProvinces.flatMap { checkedProvince => questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = - (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - executePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => executePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - exilePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => exilePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - returnPrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => returnPrisonerQuestMatch(quest) ) } - case Execute => + case Execute => ActionResultC( actionResultType = PrisonerExecutedResultType, actingFactionId = Some(actingFactionId), @@ -235,8 +208,7 @@ object ManagePrisonersCommand { changedProvinces = Vector( ChangedProvinceC( provinceId = provinceId, - removedUnaffiliatedHeroIds = - Vector(prisonerUnaffiliatedHero.heroId) + removedUnaffiliatedHeroIds = Vector(prisonerUnaffiliatedHero.heroId) ) ), newNotifications = Vector( @@ -253,20 +225,16 @@ object ManagePrisonersCommand { ) +: allProvinces.flatMap { checkedProvince => questFulfillmentChecker.fulfilledQuestResults( province = checkedProvince, - isFulfilled = (quest, _ /*questHolderProvince*/ ) => - executePrisonerQuestMatch(quest) + isFulfilled = (quest, _ /*questHolderProvince*/ ) => executePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = - (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => releasePrisonerMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - exilePrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => exilePrisonerQuestMatch(quest) ) ++ questFulfillmentChecker.failedQuestResults( province = checkedProvince, - isFailed = (quest, _ /*questHolderProvince*/ ) => - returnPrisonerQuestMatch(quest) + isFailed = (quest, _ /*questHolderProvince*/ ) => returnPrisonerQuestMatch(quest) ) } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommand.scala index 947b3eac7d..4410a77844 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommand.scala @@ -1,13 +1,6 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.settings.{ ActionVigorCost, @@ -17,11 +10,7 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.MarchActionResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.{Army, MovingArmy, Supplies} @@ -65,7 +54,7 @@ object MarchCommand { s"Specified $food food but only $foodAvailable available" ) - val actingHeroes = marchingUnits.map(_.heroId) + val actingHeroes = marchingUnits.map(_.heroId) val actingBattalionIds = marchingUnits.flatMap(_.battalionId) commandRequire( @@ -138,8 +127,7 @@ object MarchCommand { ) val movingArmy = MovingArmy( - id = - 0, // ID will be generated by ActionResultProtoApplierImpl.modifyArmySet + id = 0, // ID will be generated by ActionResultProtoApplierImpl.modifyArmySet army = Army( factionId = actingFactionId, units = marchingUnits.toVector, @@ -164,8 +152,7 @@ object MarchCommand { provinceId = Some(originProvinceId), provinceIdActed = Some(originProvinceId), changedHeroes = heroChanges.toVector, - changedProvinces = - Vector(originProvinceChange, destinationProvinceChange) + changedProvinces = Vector(originProvinceChange, destinationProvinceChange) ) } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommand.scala index fb7660a765..2dc54fef0d 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommand.scala @@ -7,10 +7,7 @@ import net.eagle0.eagle.library.util.{BattalionNameGenerator, PriceIndexUtils} import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedBattalionC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedBattalionC} import net.eagle0.eagle.model.action_result.types.OrganizeTroopsResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.{BattalionType, BattalionTypeId} @@ -53,7 +50,7 @@ object OrganizeTroopsCommand { private def checkConstructible(battalionTypeId: BattalionTypeId): Unit = commandRequire( constructibleBattalionTypeIds.contains(battalionTypeId), - s"${battalionTypeId} was not among constructible battalion types ${constructibleBattalionTypeIds}" + s"$battalionTypeId was not among constructible battalion types $constructibleBattalionTypeIds" ) private def afterOneRemoval( @@ -101,7 +98,7 @@ object OrganizeTroopsCommand { ): BattalionT = { val mergedInBatt = existingBattalions.find(_.id == mergedIn.fromBattalionId).get - val newSize = battalion.size + mergedIn.countMoved + val newSize = battalion.size + mergedIn.countMoved val battalionType = allBattalionTypes @@ -148,7 +145,7 @@ object OrganizeTroopsCommand { s"No battalion type found for ${battalion.typeId}" ) ) - val newSize = battalion.size + count + val newSize = battalion.size + count commandRequire( newSize <= battalionType.capacity, s"New size $newSize is greater than battalion capacity after hiring new troops" @@ -181,8 +178,7 @@ object OrganizeTroopsCommand { ): BattalionsAndCost = { val thisBac = addTroops(battalionsAndCost.battalions(battalionId), count) BattalionsAndCost( - battalions = - battalionsAndCost.battalions + (battalionId -> thisBac.battalion), + battalions = battalionsAndCost.battalions + (battalionId -> thisBac.battalion), cost = battalionsAndCost.cost + thisBac.cost ) } @@ -204,7 +200,7 @@ object OrganizeTroopsCommand { s"No battalion type found for ${nb.`type`}" ) ) - val newSize = nb.newTroops + nb.troopsFromOtherBattalion + val newSize = nb.newTroops + nb.troopsFromOtherBattalion .map(_.countMoved) .sum @@ -217,12 +213,12 @@ object OrganizeTroopsCommand { nb.newTroops == 0 || constructibleBattalionTypeIds.contains( nb.`type` ), - s"${nb.`type`} was not among available battalion types ${constructibleBattalionTypeIds} and so cannot hire new troops" + s"${nb.`type`} was not among available battalion types $constructibleBattalionTypeIds and so cannot hire new troops" ) } changedBattalions.foreach { cb => - val batt = existingBattalions.find(_.id == cb.id).get + val batt = existingBattalions.find(_.id == cb.id).get if cb.newTroops > 0 then { checkConstructible(batt.typeId) } @@ -283,9 +279,10 @@ object OrganizeTroopsCommand { .toMap val afterDismissingTroops = - changedBattalions.foldLeft(startingBattalions) { case (battMap, cb) => - battMap + (cb.id -> battMap(cb.id) - .withSize(battMap(cb.id).size - cb.dismissedTroops)) + changedBattalions.foldLeft(startingBattalions) { + case (battMap, cb) => + battMap + (cb.id -> battMap(cb.id) + .withSize(battMap(cb.id).size - cb.dismissedTroops)) } // Remove troops from existing battalions to move to new battalions @@ -296,16 +293,17 @@ object OrganizeTroopsCommand { // Remove troops from existing battalions to move to changed battalions val afterRemovingForChanged = - changedBattalions.foldLeft(afterRemovingForNew) { case (battMap, cb) => - afterRemovals( - battMap, - cb.troopsFromOtherBattalion, - afterRemovingForNew(cb.id).typeId - ) + changedBattalions.foldLeft(afterRemovingForNew) { + case (battMap, cb) => + afterRemovals( + battMap, + cb.troopsFromOtherBattalion, + afterRemovingForNew(cb.id).typeId + ) } // create new battalions with moved troops - val maxCurrentId = + val maxCurrentId = if existingBattalions.isEmpty then 0 else existingBattalions.map(_.id).max val newBattalionsWithIds = @@ -319,24 +317,25 @@ object OrganizeTroopsCommand { newValue = Vector[BattalionT](), nextRandom = functionalRandom ) - ) { case (RandomState(acc, fr), (id, nb)) => - battalionNameGenerator - .nextName( - battalionTypeId = nb.`type`, - provinceName = province.name, - random = fr - ) - .map { name => - acc :+ mergeInMultiple( - BattalionC( - id = id, - typeId = nb.`type`, - size = 0, - name = name - ), - nb.troopsFromOtherBattalion + ) { + case (RandomState(acc, fr), (id, nb)) => + battalionNameGenerator + .nextName( + battalionTypeId = nb.`type`, + provinceName = province.name, + random = fr ) - } + .map { name => + acc :+ mergeInMultiple( + BattalionC( + id = id, + typeId = nb.`type`, + size = 0, + name = name + ), + nb.troopsFromOtherBattalion + ) + } } .map { addedBattalions => val afterAddingBattalions = @@ -345,13 +344,12 @@ object OrganizeTroopsCommand { // Merge in moved troops to existing battalions val afterChangingBattalions = - afterAddingBattalions ++ changedBattalions - .map { cb => - mergeInMultiple( - afterAddingBattalions(cb.id), - cb.troopsFromOtherBattalion - ) - } + afterAddingBattalions ++ changedBattalions.map { cb => + mergeInMultiple( + afterAddingBattalions(cb.id), + cb.troopsFromOtherBattalion + ) + } .map(b => b.id -> b) // Add new troops to new battalions @@ -362,8 +360,9 @@ object OrganizeTroopsCommand { // Add new troops to changed battalions val afterAddingForChanged = - changedBattalions.foldLeft(afterAddingForNew) { case (bac, cb) => - addTroops(bac, cb.id, cb.newTroops) + changedBattalions.foldLeft(afterAddingForNew) { + case (bac, cb) => + addTroops(bac, cb.id, cb.newTroops) } commandRequire( @@ -382,8 +381,7 @@ object OrganizeTroopsCommand { .map(b => ChangedBattalionC(to = b)) .toVector, newBattalions = newBatt.toVector, - destroyedBattalionIds = - changedBatt.filter(_.size == 0).map(_.id).toVector, + destroyedBattalionIds = changedBatt.filter(_.size == 0).map(_.id).toVector, changedProvinces = Vector( ChangedProvinceC( provinceId = province.id, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommand.scala index a960cd3cca..a6887120d5 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommand.scala @@ -6,18 +6,11 @@ import net.eagle0.eagle.library.settings.StartingLoyalty import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.ResolvePleaseRecruitMeResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.hero.{ - EventForHeroBackstoryT, - PleaseRecruitMeBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{EventForHeroBackstoryT, PleaseRecruitMeBackstoryEvent} import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.{ ExecutePrisonerQuest, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessRandomSimpleActionWrapper.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessRandomSimpleActionWrapper.scala index 72920c99c0..6f6ef03d84 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessRandomSimpleActionWrapper.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessRandomSimpleActionWrapper.scala @@ -27,13 +27,11 @@ class ProtolessRandomSimpleActionWrapper( initialState = startingState, actionResultProtoApplier = actionResultProtoApplier, functionalRandom = SeededRandom(startingState.randomSeed) - ) - .withRandomActionResult { case (gs, fr) => + ).withRandomActionResult { + case (gs, fr) => protolessRandomSimpleAction .immediateExecute(fr) - .map(ar => - VigorXPApplier.withVigorXp(ActionResultProtoConverter.toProto(ar)) - ) + .map(ar => VigorXPApplier.withVigorXp(ActionResultProtoConverter.toProto(ar))) .map { resultWithVigorXp => Command.resultWithLastCommand( result = resultWithVigorXp, @@ -43,8 +41,8 @@ class ProtolessRandomSimpleActionWrapper( .flatMap(_.rulingFactionId) ) } - } - .withRandomActionResult { case (gs, fr) => + }.withRandomActionResult { + case (gs, fr) => RandomState( ActionResult( `type` = NEW_RANDOM_SEED, @@ -52,7 +50,5 @@ class ProtolessRandomSimpleActionWrapper( ), fr ) - } - .results - .newValue + }.results.newValue } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSequentialResultsActionWrapper.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSequentialResultsActionWrapper.scala index 653c29f290..6aec471119 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSequentialResultsActionWrapper.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSequentialResultsActionWrapper.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.common.SeededRandom -import net.eagle0.eagle.library.actions.applier.{ - ActionResultProtoApplier, - ActionResultTApplierImpl -} +import net.eagle0.eagle.library.actions.applier.{ActionResultProtoApplier, ActionResultTApplierImpl} import net.eagle0.eagle.library.actions.impl.common.{ ActionWithResultingState, ProtolessSequentialResultsAction, @@ -26,15 +23,14 @@ class ProtolessSequentialResultsActionWrapper( throw new EagleInternalException( "ProtolessSequentialResultsActionWrapper must have at least one result" ) - case h +: t => + case h +: t => VigorXPApplier.withVigorXp(h) +: t - case _ => ??? // above cases should cover + case _ => ??? // above cases should cover } RandomStateTSequencer( initialState = startingState, - actionResultApplier = - new ActionResultTApplierImpl(actionResultProtoApplier), + actionResultApplier = new ActionResultTApplierImpl(actionResultProtoApplier), functionalRandom = SeededRandom(startingState.randomSeed) ).withActionResultTs(_ => arts).actionsWithResultingStates.newValue } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSimpleActionWrapper.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSimpleActionWrapper.scala index 2a888dc8eb..d00e989baf 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSimpleActionWrapper.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ProtolessSimpleActionWrapper.scala @@ -2,11 +2,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.api.selected_command.SelectedCommand import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - ActionWithResultingState, - ProtolessSimpleAction, - VigorXPApplier -} +import net.eagle0.eagle.library.actions.impl.common.{ActionWithResultingState, ProtolessSimpleAction, VigorXPApplier} import net.eagle0.eagle.model.proto_converters.game_state.GameStateConverter import net.eagle0.eagle.model.proto_converters.ActionResultProtoConverter import net.eagle0.eagle.model.state.game_state.GameState diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RandomSingleResultCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RandomSingleResultCommand.scala index 69a4c78012..05182c683c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RandomSingleResultCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RandomSingleResultCommand.scala @@ -27,20 +27,19 @@ abstract class RandomSingleResultCommand( initialStateProto = startingState, actionResultProtoApplier = actionResultProtoApplier, functionalRandom = SeededRandom(startingState.randomSeed) - ) - .withRandomActionResult { case (gs, fr) => - immediateExecute(fr).map(VigorXPApplier.withVigorXp).map { - resultWithVigorXp => - Command.resultWithLastCommand( - result = resultWithVigorXp, - selectedCommand = selectedCommand, - factionId = resultWithVigorXp.province - .map(startingState.provinces) - .flatMap(_.rulingFactionId) - ) + ).withRandomActionResult { + case (gs, fr) => + immediateExecute(fr).map(VigorXPApplier.withVigorXp).map { resultWithVigorXp => + Command.resultWithLastCommand( + result = resultWithVigorXp, + selectedCommand = selectedCommand, + factionId = resultWithVigorXp.province + .map(startingState.provinces) + .flatMap(_.rulingFactionId) + ) } - } - .withRandomActionResult { case (gs, fr) => + }.withRandomActionResult { + case (gs, fr) => RandomState( ActionResult( `type` = NEW_RANDOM_SEED, @@ -48,7 +47,5 @@ abstract class RandomSingleResultCommand( ), fr ) - } - .results - .newValue + }.results.newValue } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommand.scala index 528c365e17..4014419174 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommand.scala @@ -2,21 +2,14 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction -import net.eagle0.eagle.library.settings.{ - ReconAgilityXp, - ReconVigorCost, - ReconWisdomXp -} +import net.eagle0.eagle.library.settings.{ReconAgilityXp, ReconVigorCost, ReconWisdomXp} import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.concrete.ActionResultC import net.eagle0.eagle.model.action_result.types.ReconStartedResultType import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.province.{ - IncomingEndTurnAction, - IncomingRecon -} +import net.eagle0.eagle.model.state.province.{IncomingEndTurnAction, IncomingRecon} object ReconCommand { diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommand.scala index 565e73e46b..911399d4c4 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommand.scala @@ -6,18 +6,11 @@ import net.eagle0.eagle.library.settings.StartingLoyalty import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatAbsolute -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatAbsolute} import net.eagle0.eagle.model.action_result.types.RecruitHeroesResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.hero.{ - EventForHeroBackstoryT, - RecruitedBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{EventForHeroBackstoryT, RecruitedBackstoryEvent} import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.{ ExecutePrisonerQuest, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommand.scala index 48d9a898c2..6e453d6891 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommand.scala @@ -5,20 +5,11 @@ import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.AllianceOfferResolutionMessage import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected, - Status -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected, Status} import net.eagle0.eagle.model.state.diplomacy_offer.AllianceOffer object ResolveAllianceOfferCommand { @@ -55,7 +46,7 @@ object ResolveAllianceOfferCommand { ) extends ProtolessSimpleAction { override def immediateExecute: ActionResultT = { val llmRequestId = - s"${currentRoundId} resolve alliance offer ${allianceOffer.messengerHeroId}" + s"$currentRoundId resolve alliance offer ${allianceOffer.messengerHeroId}" resolution match { case Accepted => acceptAllianceOffer(llmRequestId) @@ -68,67 +59,55 @@ object ResolveAllianceOfferCommand { } } - private def acceptAllianceOffer(llmRequestId: String): ActionResultT = { + private def acceptAllianceOffer(llmRequestId: String): ActionResultT = ActionResultC( actionResultType = OfferResolvedResultType, actingFactionId = Some(actingFactionId), changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(allianceOffer.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(allianceOffer.copy(status = Accepted)) + removedIncomingDiplomacyOfferFactionIds = Vector(allianceOffer.originatingFactionId), + newIncomingDiplomacyOffers = Vector(allianceOffer.copy(status = Accepted)) ) ), newNotifications = Vector(createNotification(llmRequestId, Accepted)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Accepted)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Accepted)) ) - } - private def rejectAllianceOffer(llmRequestId: String): ActionResultT = { + private def rejectAllianceOffer(llmRequestId: String): ActionResultT = ActionResultC( actionResultType = OfferResolvedResultType, actingFactionId = Some(actingFactionId), changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(allianceOffer.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(allianceOffer.copy(status = Rejected)) + removedIncomingDiplomacyOfferFactionIds = Vector(allianceOffer.originatingFactionId), + newIncomingDiplomacyOffers = Vector(allianceOffer.copy(status = Rejected)) ) ), newNotifications = Vector(createNotification(llmRequestId, Rejected)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Rejected)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Rejected)) ) - } - private def imprisonAmbassador(llmRequestId: String): ActionResultT = { + private def imprisonAmbassador(llmRequestId: String): ActionResultT = ActionResultC( actionResultType = OfferResolvedResultType, actingFactionId = Some(actingFactionId), changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(allianceOffer.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(allianceOffer.copy(status = Imprisoned)) + removedIncomingDiplomacyOfferFactionIds = Vector(allianceOffer.originatingFactionId), + newIncomingDiplomacyOffers = Vector(allianceOffer.copy(status = Imprisoned)) ) ), newNotifications = Vector(createNotification(llmRequestId, Imprisoned)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Imprisoned)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Imprisoned)) ) - } private def createNotification( llmRequestId: String, status: Status - ): NotificationC = { + ): NotificationC = NotificationC( details = status match { case Accepted => @@ -160,12 +139,11 @@ object ResolveAllianceOfferCommand { llm = NotificationT.Llm.Id(llmRequestId), deferred = false ) - } private def createLlmRequest( llmRequestId: String, status: Status - ): AllianceOfferResolutionMessage = { + ): AllianceOfferResolutionMessage = AllianceOfferResolutionMessage( requestId = llmRequestId, eagleGameId = gameId, @@ -176,6 +154,5 @@ object ResolveAllianceOfferCommand { messengerHeroId = allianceOffer.messengerHeroId, resolution = status ) - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommand.scala index e056a79c60..b5cbb7c476 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommand.scala @@ -5,24 +5,12 @@ import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.BreakAllianceResolutionMessage import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.diplomacy_offer.{ - BreakAlliance, - DiplomacyOffer -} -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected, - Status -} +import net.eagle0.eagle.model.state.diplomacy_offer.{BreakAlliance, DiplomacyOffer} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected, Status} object ResolveBreakAllianceCommand { private case class ResolveBreakAllianceCommand( @@ -32,8 +20,8 @@ object ResolveBreakAllianceCommand { gameId: GameId, currentRoundId: RoundId ) extends ProtolessSimpleAction { - private val originatingFactionId = breakAllianceOffer.originatingFactionId - private val messengerHeroId = breakAllianceOffer.messengerHeroId + private val originatingFactionId = breakAllianceOffer.originatingFactionId + private val messengerHeroId = breakAllianceOffer.messengerHeroId private val messengerOriginProvinceId = breakAllianceOffer.messengerOriginProvinceId @@ -42,32 +30,30 @@ object ResolveBreakAllianceCommand { s"$currentRoundId resolve break alliance $messengerHeroId" resolution match { - case Accepted => + case Accepted => acceptBreakAlliance(llmRequestId) case Imprisoned => imprisonAmbassador(llmRequestId) - case Rejected => + case Rejected => throw new EagleCommandException( "REJECTED not valid for break alliance" ) - case _ => + case _ => throw new EagleCommandException( s"Invalid diplomacy offer status for command: $resolution" ) } } - private def acceptBreakAlliance(llmRequestId: String): ActionResultT = { + private def acceptBreakAlliance(llmRequestId: String): ActionResultT = ActionResultC( actionResultType = OfferResolvedResultType, actingFactionId = Some(actingFactionId), changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(originatingFactionId), - newIncomingDiplomacyOffers = - Vector(breakAllianceOffer.copy(status = Accepted)) + removedIncomingDiplomacyOfferFactionIds = Vector(originatingFactionId), + newIncomingDiplomacyOffers = Vector(breakAllianceOffer.copy(status = Accepted)) ) ), newNotifications = Vector( @@ -81,22 +67,18 @@ object ResolveBreakAllianceCommand { deferred = true ) ), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Accepted)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Accepted)) ) - } - private def imprisonAmbassador(llmRequestId: String): ActionResultT = { + private def imprisonAmbassador(llmRequestId: String): ActionResultT = ActionResultC( actionResultType = OfferResolvedResultType, actingFactionId = Some(actingFactionId), changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(originatingFactionId), - newIncomingDiplomacyOffers = - Vector(breakAllianceOffer.copy(status = Imprisoned)) + removedIncomingDiplomacyOfferFactionIds = Vector(originatingFactionId), + newIncomingDiplomacyOffers = Vector(breakAllianceOffer.copy(status = Imprisoned)) ) ), newNotifications = Vector( @@ -110,15 +92,13 @@ object ResolveBreakAllianceCommand { deferred = true ) ), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Imprisoned)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Imprisoned)) ) - } private def createLlmRequest( llmRequestId: String, status: Status - ): BreakAllianceResolutionMessage = { + ): BreakAllianceResolutionMessage = BreakAllianceResolutionMessage( requestId = llmRequestId, eagleGameId = gameId, @@ -129,7 +109,6 @@ object ResolveBreakAllianceCommand { messengerHeroId = messengerHeroId, resolution = status ) - } } def make( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommand.scala index fcf6f5a775..7023c53ec5 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommand.scala @@ -5,22 +5,12 @@ import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.InvitationResolutionMessage import net.eagle0.eagle.model.action_result.types.InvitationResolvedResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.diplomacy_offer.{DiplomacyOffer, Invitation} -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Invalidated, - Rejected, - Status -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Invalidated, Rejected, Status} import net.eagle0.eagle.model.state.faction.FactionT object ResolveInvitationCommand { @@ -44,12 +34,10 @@ object ResolveInvitationCommand { ) ) - val invitation = actingFaction.incomingDiplomacyOffers - .collectFirst { - case inv: Invitation - if inv.originatingFactionId == originatingFactionId => - inv - } + val invitation = actingFaction.incomingDiplomacyOffers.collectFirst { + case inv: Invitation if inv.originatingFactionId == originatingFactionId => + inv + } .getOrElse( throw new EagleCommandException( s"Invitation from faction $originatingFactionId not found" @@ -57,8 +45,9 @@ object ResolveInvitationCommand { ) // Derive available originating faction IDs from all invitations - val availableOriginatingFactionIds = actingFaction.incomingDiplomacyOffers - .collect { case inv: Invitation => inv.originatingFactionId } + val availableOriginatingFactionIds = actingFaction.incomingDiplomacyOffers.collect { + case inv: Invitation => inv.originatingFactionId + } // Validate the originating faction ID commandRequire( @@ -92,7 +81,7 @@ object ResolveInvitationCommand { ) extends ProtolessSimpleAction { override def immediateExecute: ActionResultT = { val llmRequestId = - s"${currentRoundId} resolve invitation ${invitation.messengerHeroId}" + s"$currentRoundId resolve invitation ${invitation.messengerHeroId}" resolution match { case Accepted => acceptInvitation(llmRequestId) @@ -111,7 +100,7 @@ object ResolveInvitationCommand { // 2. Remove ALL incoming offers TO the accepting faction and add them back invalidated // 3. Add the accepted invitation back with ACCEPTED status - val acceptingFaction = allFactions(actingFactionId) + val acceptingFaction = allFactions(actingFactionId) val acceptedInvitation = invitation.copy(status = Accepted) // Invalidate outgoing offers: Check all factions for incoming offers FROM accepting faction @@ -123,11 +112,9 @@ object ResolveInvitationCommand { ChangedFactionC( factionId = otherFaction.id, - newIncomingDiplomacyOffers = - outgoingOffersToInvalidate.map(_.withStatus(Invalidated)), + newIncomingDiplomacyOffers = outgoingOffersToInvalidate.map(_.withStatus(Invalidated)), removedIncomingDiplomacyOfferFactionIds = - if outgoingOffersToInvalidate.nonEmpty then - Vector(actingFactionId) + if outgoingOffersToInvalidate.nonEmpty then Vector(actingFactionId) else Vector.empty ) } @@ -136,8 +123,8 @@ object ResolveInvitationCommand { ) // Only include factions with changes // Handle accepting faction: invalidate all OTHER incoming offers, accept the selected one - val allIncomingOffers = acceptingFaction.incomingDiplomacyOffers - val otherIncomingOffers = allIncomingOffers.filterNot(offer => + val allIncomingOffers = acceptingFaction.incomingDiplomacyOffers + val otherIncomingOffers = allIncomingOffers.filterNot(offer => offer.originatingFactionId == invitation.originatingFactionId && offer.messengerHeroId == invitation.messengerHeroId ) @@ -146,10 +133,8 @@ object ResolveInvitationCommand { val acceptingFactionChange = ChangedFactionC( factionId = actingFactionId, - newIncomingDiplomacyOffers = - acceptedInvitation +: invalidatedIncomingOffers, - removedIncomingDiplomacyOfferFactionIds = - allIncomingOffers.map(_.originatingFactionId) + newIncomingDiplomacyOffers = acceptedInvitation +: invalidatedIncomingOffers, + removedIncomingDiplomacyOfferFactionIds = allIncomingOffers.map(_.originatingFactionId) ) ActionResultC( @@ -157,12 +142,11 @@ object ResolveInvitationCommand { actingFactionId = Some(actingFactionId), changedFactions = invalidatedOutgoingsChanges :+ acceptingFactionChange, newNotifications = Vector(createNotification(llmRequestId, Accepted)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Accepted)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Accepted)) ) } - private def rejectInvitation(llmRequestId: String): ActionResultT = { + private def rejectInvitation(llmRequestId: String): ActionResultT = // When rejecting, only update the single invitation being rejected ActionResultC( actionResultType = InvitationResolvedResultType, @@ -170,19 +154,15 @@ object ResolveInvitationCommand { changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(invitation.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(invitation.copy(status = Rejected)) + removedIncomingDiplomacyOfferFactionIds = Vector(invitation.originatingFactionId), + newIncomingDiplomacyOffers = Vector(invitation.copy(status = Rejected)) ) ), newNotifications = Vector(createNotification(llmRequestId, Rejected)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Rejected)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Rejected)) ) - } - private def imprisonAmbassador(llmRequestId: String): ActionResultT = { + private def imprisonAmbassador(llmRequestId: String): ActionResultT = // When imprisoning, only update the single invitation being rejected ActionResultC( actionResultType = InvitationResolvedResultType, @@ -190,22 +170,18 @@ object ResolveInvitationCommand { changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(invitation.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(invitation.copy(status = Imprisoned)) + removedIncomingDiplomacyOfferFactionIds = Vector(invitation.originatingFactionId), + newIncomingDiplomacyOffers = Vector(invitation.copy(status = Imprisoned)) ) ), newNotifications = Vector(createNotification(llmRequestId, Imprisoned)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Imprisoned)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Imprisoned)) ) - } private def createNotification( llmRequestId: String, status: Status - ): NotificationC = { + ): NotificationC = NotificationC( details = status match { case Accepted => @@ -233,15 +209,13 @@ object ResolveInvitationCommand { affectedProvinceIds = Vector(), affectedHeroIds = Vector(invitation.messengerHeroId), llm = NotificationT.Llm.Id(llmRequestId), - deferred = - status == Imprisoned // Only imprison notifications are deferred + deferred = status == Imprisoned // Only imprison notifications are deferred ) - } private def createLlmRequest( llmRequestId: String, status: Status - ): InvitationResolutionMessage = { + ): InvitationResolutionMessage = InvitationResolutionMessage( requestId = llmRequestId, eagleGameId = gameId, @@ -250,6 +224,5 @@ object ResolveInvitationCommand { messengerHeroId = invitation.messengerHeroId, resolution = status ) - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommand.scala index ce1a6c0154..a26a524422 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommand.scala @@ -5,23 +5,12 @@ import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.RansomResolutionMessage import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.diplomacy_offer.{ - DiplomacyOffer, - RansomOffer -} -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Rejected, - Status -} +import net.eagle0.eagle.model.state.diplomacy_offer.{DiplomacyOffer, RansomOffer} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Rejected, Status} import net.eagle0.eagle.model.state.faction.FactionT object ResolveRansomOfferCommand { @@ -45,12 +34,10 @@ object ResolveRansomOfferCommand { ) ) - val ransomOffer = actingFaction.incomingDiplomacyOffers - .collectFirst { - case offer: RansomOffer - if offer.originatingFactionId == originatingFactionId => - offer - } + val ransomOffer = actingFaction.incomingDiplomacyOffers.collectFirst { + case offer: RansomOffer if offer.originatingFactionId == originatingFactionId => + offer + } .getOrElse( throw new EagleCommandException( s"Ransom offer from faction $originatingFactionId not found" @@ -81,7 +68,7 @@ object ResolveRansomOfferCommand { ) extends ProtolessSimpleAction { override def immediateExecute: ActionResultT = { val llmRequestId = - s"${currentRoundId} resolve ransom offer ${ransomOffer.messengerHeroId}" + s"$currentRoundId resolve ransom offer ${ransomOffer.messengerHeroId}" resolution match { case Accepted => acceptRansomOffer(llmRequestId) @@ -93,48 +80,40 @@ object ResolveRansomOfferCommand { } } - private def acceptRansomOffer(llmRequestId: String): ActionResultT = { + private def acceptRansomOffer(llmRequestId: String): ActionResultT = ActionResultC( actionResultType = OfferResolvedResultType, actingFactionId = Some(actingFactionId), changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(ransomOffer.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(ransomOffer.copy(status = Accepted)) + removedIncomingDiplomacyOfferFactionIds = Vector(ransomOffer.originatingFactionId), + newIncomingDiplomacyOffers = Vector(ransomOffer.copy(status = Accepted)) ) ), newNotifications = Vector(createNotification(llmRequestId, Accepted)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Accepted)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Accepted)) ) - } - private def rejectRansomOffer(llmRequestId: String): ActionResultT = { + private def rejectRansomOffer(llmRequestId: String): ActionResultT = ActionResultC( actionResultType = OfferResolvedResultType, actingFactionId = Some(actingFactionId), changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(ransomOffer.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(ransomOffer.copy(status = Rejected)) + removedIncomingDiplomacyOfferFactionIds = Vector(ransomOffer.originatingFactionId), + newIncomingDiplomacyOffers = Vector(ransomOffer.copy(status = Rejected)) ) ), newNotifications = Vector(createNotification(llmRequestId, Rejected)), - newGeneratedTextRequests = - Vector(createLlmRequest(llmRequestId, Rejected)) + newGeneratedTextRequests = Vector(createLlmRequest(llmRequestId, Rejected)) ) - } private def createNotification( llmRequestId: String, status: Status - ): NotificationC = { + ): NotificationC = NotificationC( details = status match { case Accepted => @@ -159,12 +138,11 @@ object ResolveRansomOfferCommand { llm = NotificationT.Llm.Id(llmRequestId), deferred = false ) - } private def createLlmRequest( llmRequestId: String, status: Status - ): RansomResolutionMessage = { + ): RansomResolutionMessage = RansomResolutionMessage( requestId = llmRequestId, eagleGameId = gameId, @@ -174,6 +152,5 @@ object ResolveRansomOfferCommand { ransomedHeroId = ransomOffer.prisonerToBeRansomed.prisonerHeroId, resolution = status ) - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommand.scala index 2d8626e7ea..0825a767ef 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommand.scala @@ -3,28 +3,15 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, GameId, ProvinceId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire -import net.eagle0.eagle.model.action_result.changed_province.concrete.{ - ChangedProvinceC, - HostileArmyStatusChange -} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC -} -import net.eagle0.eagle.model.action_result.types.{ - TributePaidResultType, - TributeRefusedResultType -} +import net.eagle0.eagle.model.action_result.changed_province.concrete.{ChangedProvinceC, HostileArmyStatusChange} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC} +import net.eagle0.eagle.model.action_result.types.{TributePaidResultType, TributeRefusedResultType} import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.faction.FactionRelationship import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - Attacking, - TributeDemanded, - TributePaid -} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{Attacking, TributeDemanded, TributePaid} import net.eagle0.eagle.model.state.TributeAmount object ResolveTributeCommand { @@ -84,13 +71,12 @@ object ResolveTributeCommand { currentDate: Date, allProvinces: Vector[ProvinceT] ) extends ProtolessSimpleAction { - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = if paid then { payTribute() } else { rejectTribute() } - } private def payTribute(): ActionResultT = { // Create a truce that lasts for 12 months @@ -161,7 +147,7 @@ object ResolveTributeCommand { ) } - private def rejectTribute(): ActionResultT = { + private def rejectTribute(): ActionResultT = ActionResultC( actionResultType = TributeRefusedResultType, actingFactionId = Some(actingFactionId), @@ -177,7 +163,6 @@ object ResolveTributeCommand { ) ) ) - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommand.scala index d18bda92dc..cf6d851121 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommand.scala @@ -5,20 +5,11 @@ import net.eagle0.eagle.library.{EagleCommandException, EagleInternalException} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.TruceResolutionMessage import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected, - Status -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected, Status} import net.eagle0.eagle.model.state.diplomacy_offer.TruceOffer object ResolveTruceOfferCommand { @@ -64,7 +55,7 @@ object ResolveTruceOfferCommand { ) extends ProtolessSimpleAction { override def immediateExecute: ActionResultT = { val llmRequestId = - s"${currentRoundId} resolve truce ${truceOffer.messengerHeroId}" + s"$currentRoundId resolve truce ${truceOffer.messengerHeroId}" ActionResultC( actionResultType = OfferResolvedResultType, @@ -72,10 +63,8 @@ object ResolveTruceOfferCommand { changedFactions = Vector( ChangedFactionC( factionId = actingFactionId, - removedIncomingDiplomacyOfferFactionIds = - Vector(truceOffer.originatingFactionId), - newIncomingDiplomacyOffers = - Vector(truceOffer.copy(status = resolution)) + removedIncomingDiplomacyOfferFactionIds = Vector(truceOffer.originatingFactionId), + newIncomingDiplomacyOffers = Vector(truceOffer.copy(status = resolution)) ) ), newNotifications = Vector( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RestCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RestCommand.scala index 9d1ad122d3..43117bdc45 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RestCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/RestCommand.scala @@ -3,11 +3,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction import net.eagle0.eagle.library.settings.RestVigorGain -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.RestResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.hero.HeroT @@ -45,11 +41,10 @@ object RestCommand { actingFactionId: FactionId, provinceId: ProvinceId, factionHeroesInProvince: Vector[HeroT] - ): ProtolessSimpleAction = { + ): ProtolessSimpleAction = RestCommand( factionId = actingFactionId, provinceId = provinceId, factionHeroesInProvince = factionHeroesInProvince ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommand.scala index fe172978f2..672c81f6f6 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommand.scala @@ -39,11 +39,10 @@ object ReturnCommand { actingFactionId: FactionId, provinceId: ProvinceId, rulerIsTraveling: Boolean - ): ProtolessSimpleAction = { + ): ProtolessSimpleAction = ReturnCommand( factionId = actingFactionId, provinceId = provinceId, rulerIsTraveling = rulerIsTraveling ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommand.scala index 01446c1744..c07e8d45bf 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommand.scala @@ -10,11 +10,7 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.SentSuppliesResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.{MovingSupplies, Supplies} @@ -79,7 +75,7 @@ object SendSuppliesCommand { food: Int, currentRoundId: RoundId ) extends ProtolessSimpleAction { - override def immediateExecute: ActionResultT = { + override def immediateExecute: ActionResultT = ActionResultC( actionResultType = SentSuppliesResultType, actingFactionId = Some(factionId), @@ -115,7 +111,6 @@ object SendSuppliesCommand { ) ) ) - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SimpleActionWrapper.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SimpleActionWrapper.scala index fad9881908..51dc4ab2c0 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SimpleActionWrapper.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SimpleActionWrapper.scala @@ -3,11 +3,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.api.selected_command.SelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -import net.eagle0.eagle.library.actions.impl.common.{ - ActionWithResultingState, - SimpleAction, - VigorXPApplier -} +import net.eagle0.eagle.library.actions.impl.common.{ActionWithResultingState, SimpleAction, VigorXPApplier} class SimpleActionWrapper( startingState: GameState, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommand.scala index b8ab58606d..74c67b2a69 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommand.scala @@ -2,17 +2,10 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction -import net.eagle0.eagle.library.settings.{ - StartEpidemicCharismaXp, - StartEpidemicVigorDelta -} +import net.eagle0.eagle.library.settings.{StartEpidemicCharismaXp, StartEpidemicVigorDelta} import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.EpidemicStartedResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.province.DeferredChange diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommand.scala index e15d65b75c..fc66562f6c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommand.scala @@ -13,11 +13,7 @@ import net.eagle0.eagle.library.settings.{ import net.eagle0.eagle.library.util.view_filters.BattalionViewFilter import net.eagle0.eagle.library.util.BattalionPower import net.eagle0.eagle.library.util.EagleRequire.commandRequire -import net.eagle0.eagle.model.action_result.{ - ActionResultT, - NotificationDetails, - NotificationT -} +import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.concrete.{ ActionResultC, @@ -31,17 +27,10 @@ import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.{ SuppressBeastsFailedMessage, SuppressBeastsSucceededMessage } -import net.eagle0.eagle.model.action_result.types.{ - SuppressBeastsFailedResultType, - SuppressedBeastsResultType -} +import net.eagle0.eagle.model.action_result.types.{SuppressBeastsFailedResultType, SuppressedBeastsResultType} import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.hero.{ - HeroT, - Profession, - SuppressedBeastsBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{HeroT, Profession, SuppressedBeastsBackstoryEvent} import net.eagle0.eagle.model.state.province.{BeastsEvent, ProvinceT} import net.eagle0.eagle.model.state.BeastInfo @@ -154,8 +143,7 @@ object SuppressBeastsCommand { None, ChangedHeroC( heroId = hero.id, - vigorChange = - StatDelta(-ActionVigorCost.intValue - heroCasualties) + vigorChange = StatDelta(-ActionVigorCost.intValue - heroCasualties) ), optionalBattalion.map(_.id), None @@ -182,110 +170,109 @@ object SuppressBeastsCommand { if heroDied then RandomState((None, None), functionalRandom) else goldAndFoodGained(beastInfo, beastCount, functionalRandom) - goldAndFoodRS.map { case (goldDelta, foodDelta) => - val (notificationLlmRequest, notification) = - if heroDied then { - val notificationLlmRequest = SuppressBeastsFailedMessage( - requestId = s"suppress beasts failed $factionId ${hero.id}", - eagleGameId = gameId, - heroId = hero.id, - factionId = factionId, - battalionTypeId = optionalBattalion.map(_.id), - beastTypeId = 1, // TODO: beastInfo.id - beastCount = beastCount, - provinceId = province.id - ) - val notification = NotificationC( - details = NotificationDetails.SuppressBeastsFailed( + goldAndFoodRS.map { + case (goldDelta, foodDelta) => + val (notificationLlmRequest, notification) = + if heroDied then { + val notificationLlmRequest = SuppressBeastsFailedMessage( + requestId = s"suppress beasts failed $factionId ${hero.id}", + eagleGameId = gameId, heroId = hero.id, - provinceId = province.id, - beastTypeNameSingular = beastInfo.singularName, - beastTypeNamePlural = beastInfo.pluralName - ), - targetFactionIds = - Vector(), // all factions learn about eradications - llm = NotificationT.Llm.Id(notificationLlmRequest.requestId), - deferred = true - ) - (notificationLlmRequest, notification) - } else { - val notificationLlmRequest = SuppressBeastsSucceededMessage( - requestId = - s"suppressed beasts $currentRoundId $factionId ${hero.id}", - eagleGameId = gameId, - recipientFactionIds = Vector(factionId), - heroId = hero.id, - factionId = factionId, - battalionTypeId = optionalBattalion.map(_.id), - beastTypeId = beastInfo.id, - beastCount = beastCount, - provinceId = province.id, - casualtyCount = casualties, - goldGained = goldDelta.getOrElse(0), - foodGained = foodDelta.getOrElse(0) - ) - val notification = NotificationC( - details = NotificationDetails.SuppressedBeasts( + factionId = factionId, + battalionTypeId = optionalBattalion.map(_.id), + beastTypeId = 1, // TODO: beastInfo.id + beastCount = beastCount, + provinceId = province.id + ) + val notification = NotificationC( + details = NotificationDetails.SuppressBeastsFailed( + heroId = hero.id, + provinceId = province.id, + beastTypeNameSingular = beastInfo.singularName, + beastTypeNamePlural = beastInfo.pluralName + ), + targetFactionIds = Vector(), // all factions learn about eradications + llm = NotificationT.Llm.Id(notificationLlmRequest.requestId), + deferred = true + ) + (notificationLlmRequest, notification) + } else { + val notificationLlmRequest = SuppressBeastsSucceededMessage( + requestId = s"suppressed beasts $currentRoundId $factionId ${hero.id}", + eagleGameId = gameId, + recipientFactionIds = Vector(factionId), heroId = hero.id, + factionId = factionId, + battalionTypeId = optionalBattalion.map(_.id), + beastTypeId = beastInfo.id, + beastCount = beastCount, provinceId = province.id, - beastTypeNameSingular = beastInfo.singularName, - beastTypeNamePlural = beastInfo.pluralName, + casualtyCount = casualties, goldGained = goldDelta.getOrElse(0), foodGained = foodDelta.getOrElse(0) - ), - targetFactionIds = Vector(factionId), - llm = NotificationT.Llm.Id(notificationLlmRequest.requestId), - deferred = true - ) - (notificationLlmRequest, notification) - } + ) + val notification = NotificationC( + details = NotificationDetails.SuppressedBeasts( + heroId = hero.id, + provinceId = province.id, + beastTypeNameSingular = beastInfo.singularName, + beastTypeNamePlural = beastInfo.pluralName, + goldGained = goldDelta.getOrElse(0), + foodGained = foodDelta.getOrElse(0) + ), + targetFactionIds = Vector(factionId), + llm = NotificationT.Llm.Id(notificationLlmRequest.requestId), + deferred = true + ) + (notificationLlmRequest, notification) + } - // Create backstory event - val backstoryEvent = SuppressedBeastsBackstoryEvent( - date = currentDate, - provinceId = province.id, - beastType = beastInfo.singularName, - beastCount = beastCount, - battalion = optionalBattalion.map(battT => - BattalionViewFilter.filteredBattalionViewBelongingToPlayer( - battT - ) - ), - succeeded = !heroDied - ) + // Create backstory event + val backstoryEvent = SuppressedBeastsBackstoryEvent( + date = currentDate, + provinceId = province.id, + beastType = beastInfo.singularName, + beastCount = beastCount, + battalion = optionalBattalion.map(battT => + BattalionViewFilter.filteredBattalionViewBelongingToPlayer( + battT + ) + ), + succeeded = !heroDied + ) - ActionResultC( - actionResultType = - if heroDied then SuppressBeastsFailedResultType - else SuppressedBeastsResultType, - actingFactionId = Some(factionId), - provinceId = Some(province.id), - provinceIdActed = Some(province.id), - actingHeroId = Some(hero.id), - removedHeroIds = removedHero.toVector, - destroyedBattalionIds = destroyedBattalionId.toVector, - changedHeroes = Vector( - changedHero.copy(newEventsForHeroBackstory = Vector(backstoryEvent)) - ), - changedBattalions = changedBattalion.toVector, - changedProvinces = Vector( - ChangedProvinceC( - provinceId = province.id, - removedRulingFactionHeroIds = removedHero.toVector, - removedBattalionIds = destroyedBattalionId.toVector, - newProvinceEvents = Some( - province.activeEvents.filterNot(_.isInstanceOf[BeastsEvent]) - ), - goldDelta = goldDelta, - foodDelta = foodDelta, - supportDelta = - if !heroDied then Some(SuppressBeastsSupportBonus.doubleValue) - else None - ) - ), - newNotifications = Vector(notification), - newGeneratedTextRequests = Vector(notificationLlmRequest) - ) + ActionResultC( + actionResultType = + if heroDied then SuppressBeastsFailedResultType + else SuppressedBeastsResultType, + actingFactionId = Some(factionId), + provinceId = Some(province.id), + provinceIdActed = Some(province.id), + actingHeroId = Some(hero.id), + removedHeroIds = removedHero.toVector, + destroyedBattalionIds = destroyedBattalionId.toVector, + changedHeroes = Vector( + changedHero.copy(newEventsForHeroBackstory = Vector(backstoryEvent)) + ), + changedBattalions = changedBattalion.toVector, + changedProvinces = Vector( + ChangedProvinceC( + provinceId = province.id, + removedRulingFactionHeroIds = removedHero.toVector, + removedBattalionIds = destroyedBattalionId.toVector, + newProvinceEvents = Some( + province.activeEvents.filterNot(_.isInstanceOf[BeastsEvent]) + ), + goldDelta = goldDelta, + foodDelta = foodDelta, + supportDelta = + if !heroDied then Some(SuppressBeastsSupportBonus.doubleValue) + else None + ) + ), + newNotifications = Vector(notification), + newGeneratedTextRequests = Vector(notificationLlmRequest) + ) } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommand.scala index 5c0ccbcb56..4abcd24484 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommand.scala @@ -2,23 +2,12 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction -import net.eagle0.eagle.library.settings.{ - AcceptBrotherhoodCharismaXp, - SwearBrotherhoodCharismaXp -} +import net.eagle0.eagle.library.settings.{AcceptBrotherhoodCharismaXp, SwearBrotherhoodCharismaXp} import net.eagle0.eagle.library.util.EagleRequire.commandRequire import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.SwearBrotherhoodMessage -import net.eagle0.eagle.model.action_result.types.{ - FailedSwearBrotherhoodResultType, - SwearBrotherhoodResultType -} +import net.eagle0.eagle.model.action_result.types.{FailedSwearBrotherhoodResultType, SwearBrotherhoodResultType} import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.hero.SworeBrotherhoodBackstoryEvent @@ -27,7 +16,7 @@ object SwearBrotherhoodCommand { def accepts( heroId: HeroId, factionId: FactionId - ): Boolean = { + ): Boolean = true /* val vassal = gameState.heroes(heroId) @@ -36,7 +25,6 @@ object SwearBrotherhoodCommand { vassal, gameState.heroes(gameState.factions(factionId).factionHeadId) ) > ThresholdForSwearBrotherhood.doubleValue*/ - } def make( actingFactionId: FactionId, @@ -76,7 +64,7 @@ object SwearBrotherhoodCommand { override def immediateExecute: ActionResultT = if accepts(newBrotherId, factionId) then { val notificationLlmId = - s"${currentRoundId} swear brotherhood ${newBrotherId}" + s"$currentRoundId swear brotherhood $newBrotherId" val swornBrotherBackstoryEvent = SworeBrotherhoodBackstoryEvent( date = currentDate, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommand.scala index 352d8f3d7c..1bad03b386 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommand.scala @@ -14,8 +14,8 @@ import net.eagle0.eagle.FactionId sealed trait TradeCommandType object TradeCommandType { - case object Unknown extends TradeCommandType - case object BuyFood extends TradeCommandType + case object Unknown extends TradeCommandType + case object BuyFood extends TradeCommandType case object SellFood extends TradeCommandType } @@ -53,7 +53,7 @@ object TradeCommand { val supplyDeltas = tradeType match { case TradeCommandType.BuyFood => buy(actingProvince, amount) case TradeCommandType.SellFood => sell(actingProvince, amount) - case _ => throw new EagleCommandException("Unknown trade type") + case _ => throw new EagleCommandException("Unknown trade type") } ActionResultC( actionResultType = TradeResultType, @@ -75,13 +75,13 @@ object TradeCommand { private def buy(province: ProvinceT, amount: Int): SupplyDeltas = { val effectivePrice = BaseFoodBuyPrice.doubleValue * province.priceIndex - val cost = (amount * effectivePrice).ceil.toInt + val cost = (amount * effectivePrice).ceil.toInt commandRequire( cost <= province.gold, s"cost of $cost exceeds ${province.gold} available" ) // "true-up" if the amount didn't divide evenly, to spend same amount of gold for a bit more food - val truedUpAmount = (cost / effectivePrice).toInt + val truedUpAmount = (cost / effectivePrice).toInt SupplyDeltas(gold = -cost, food = truedUpAmount) } @@ -90,8 +90,8 @@ object TradeCommand { amount <= province.food, s"trying to sell $amount food but only ${province.food} available" ) - val effectivePrice = BaseFoodSellPrice.doubleValue * province.priceIndex - val income = (amount * effectivePrice).floor.toInt + val effectivePrice = BaseFoodSellPrice.doubleValue * province.priceIndex + val income = (amount * effectivePrice).floor.toInt // "true-down" if the amount didn't divide evenly, to sell a bit less food for the same income val truedDownAmount = (income / effectivePrice).toInt SupplyDeltas(gold = income, food = -truedDownAmount) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommand.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommand.scala index 41b2e69672..b3cd8489d9 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommand.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommand.scala @@ -12,12 +12,7 @@ import net.eagle0.eagle.library.settings.{ TrainStrengthXp } import net.eagle0.eagle.library.util.EagleRequire.commandRequire -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedBattalionC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedBattalionC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.TrainResultType import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.battalion.BattalionT @@ -99,14 +94,13 @@ object TrainCommand { agilityXpDelta = Some(TrainAgilityXp.intValue) ) - val increase = calcIncrease( + val increase = calcIncrease( trainableBattalions.map(_.size).sum, trainingHero.strength, trainingHero.charisma ) val trainingBonus = - if trainingHero.profession == Profession.Champion then - ChampionTrainingBonus.doubleValue + if trainingHero.profession == Profession.Champion then ChampionTrainingBonus.doubleValue else 0.0 val changedBattalions = trainableBattalions.map(batt => diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSequentialResultsAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSequentialResultsAction.scala index b6ca2aec0f..58f2d24133 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSequentialResultsAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSequentialResultsAction.scala @@ -5,8 +5,7 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier import net.eagle0.eagle.library.actions.impl.common -abstract class DeterministicSequentialResultsAction(startingState: GameState) - extends Action { +abstract class DeterministicSequentialResultsAction(startingState: GameState) extends Action { def results( actionResultProtoApplier: ActionResultProtoApplier ): Vector[ActionResult] diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSingleResultAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSingleResultAction.scala index c90d4bb64a..8bc6f4eb55 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSingleResultAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/DeterministicSingleResultAction.scala @@ -4,8 +4,7 @@ import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier -abstract class DeterministicSingleResultAction(startingState: GameState) - extends Action { +abstract class DeterministicSingleResultAction(startingState: GameState) extends Action { def immediateExecute: ActionResult override def execute( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomSequentialResultsAction.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomSequentialResultsAction.scala index 1891954c48..3883432a0c 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomSequentialResultsAction.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomSequentialResultsAction.scala @@ -7,8 +7,7 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplier import net.eagle0.eagle.library.actions.impl.common -abstract class RandomSequentialResultsAction(startingState: GameState) - extends Action { +abstract class RandomSequentialResultsAction(startingState: GameState) extends Action { def randomResults( functionalRandom: FunctionalRandom, actionResultProtoApplier: ActionResultProtoApplier diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateProtoSequencer.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateProtoSequencer.scala index aa42be08ea..a7b141b435 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateProtoSequencer.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateProtoSequencer.scala @@ -146,9 +146,7 @@ private case class RandomStateProtoSequencerImpl( override def withProtolessSequentialResultsAction( action: GameStateProto => ProtolessSequentialResultsAction ): RandomStateProtoSequencer = - withActionResults(gs => - action(gs).results.map(ActionResultProtoConverter.toProto) - ) + withActionResults(gs => action(gs).results.map(ActionResultProtoConverter.toProto)) override def withActionResultT( action: GameStateProto => ActionResultT @@ -187,8 +185,9 @@ private case class RandomStateProtoSequencerImpl( override def foldIn[T](ts: Iterable[T])( f: (T, GameStateProto, FunctionalRandom) => RandomState[ActionResultProto] ): RandomStateProtoSequencer = - ts.foldLeft(this) { case (sequencer, t) => - sequencer.withRandomActionResult { case (gs, fr) => f(t, gs, fr) } + ts.foldLeft(this) { + case (sequencer, t) => + sequencer.withRandomActionResult { case (gs, fr) => f(t, gs, fr) } } override def withActionWithResultingState( diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateTSequencer.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateTSequencer.scala index 24f6d71429..f24b7a0311 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateTSequencer.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/RandomStateTSequencer.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.impl.common import net.eagle0.common.{FunctionalRandom, RandomState} import net.eagle0.eagle.internal.game_state.GameState as GameStateProto -import net.eagle0.eagle.library.actions.applier.{ - ActionResultTApplier, - ActionResultTWithResultingState -} +import net.eagle0.eagle.library.actions.applier.{ActionResultTApplier, ActionResultTWithResultingState} import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.proto_converters.game_state.GameStateConverter import net.eagle0.eagle.model.proto_converters.ActionResultProtoConverter @@ -23,8 +20,9 @@ trait RandomStateTSequencer { def actionsWithResultingStates: RandomState[ Vector[ActionWithResultingState] ] = actionResultTsWithResultingStates.map { - _.map { case ActionResultTWithResultingState(art, gs) => - ActionWithResultingState(ActionResultProtoConverter.toProto(art), gs) + _.map { + case ActionResultTWithResultingState(art, gs) => + ActionWithResultingState(ActionResultProtoConverter.toProto(art), gs) } } @@ -151,10 +149,9 @@ private case class RandomStateTSequencerImpl( ): RandomStateTSequencer = actionResultGen(lastStateProto) match { case art => copy( - actionResultTsWithResultingStates = - actionResultTsWithResultingStates.map( - _ :+ ActionResultTWithResultingState(art, lastStateProto) - ) + actionResultTsWithResultingStates = actionResultTsWithResultingStates.map( + _ :+ ActionResultTWithResultingState(art, lastStateProto) + ) ) } @@ -176,8 +173,9 @@ private case class RandomStateTSequencerImpl( override def foldIn[T](ts: Iterable[T])( f: (T, GameStateProto, FunctionalRandom) => RandomState[ActionResultT] ): RandomStateTSequencer = - ts.foldLeft(this) { case (sequencer, t) => - sequencer.withRandomActionResult { case (gs, fr) => f(t, gs, fr) } + ts.foldLeft(this) { + case (sequencer, t) => + sequencer.withRandomActionResult { case (gs, fr) => f(t, gs, fr) } } override def withContinuance( @@ -220,7 +218,7 @@ private case class RandomStateTSequencerImpl( copy( actionResultTsWithResultingStates = RandomState(awrs, newFr) ) - case RandomState(arts, newFr) => + case RandomState(arts, newFr) => copy( actionResultTsWithResultingStates = RandomState( awrs ++ actionResultApplier diff --git a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplier.scala b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplier.scala index 98a454e07e..ee283f6efe 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplier.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplier.scala @@ -2,12 +2,7 @@ package net.eagle0.eagle.library.actions.impl.common import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.library.settings.VigorToConstitutionXpMultiplier -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedHeroC, - StatAbsolute, - StatDelta, - StatNoChange -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatAbsolute, StatDelta, StatNoChange} import net.eagle0.eagle.model.action_result.ActionResultT object VigorXPApplier { @@ -17,29 +12,27 @@ object VigorXPApplier { ch.update( _.optionalConstitutionXpDelta := ch.vigor.vigorDelta .filter(_ < 0) - .map(vigor => - (vigor * -VigorToConstitutionXpMultiplier.doubleValue).ceil.toInt - ) + .map(vigor => (vigor * -VigorToConstitutionXpMultiplier.doubleValue).ceil.toInt) ) }) ) - def withVigorXp(actionResult: ActionResultT): ActionResultT = { + def withVigorXp(actionResult: ActionResultT): ActionResultT = actionResult.copy( - changedHeroes = actionResult.changedHeroes.map { case ch: ChangedHeroC => - ch.vigorChange match { - case StatDelta(value) => - if value < 0 then - ch.copy( - constitutionXpDelta = Some( - (value * -VigorToConstitutionXpMultiplier.doubleValue).ceil.toInt + changedHeroes = actionResult.changedHeroes.map { + case ch: ChangedHeroC => + ch.vigorChange match { + case StatDelta(value) => + if value < 0 then + ch.copy( + constitutionXpDelta = Some( + (value * -VigorToConstitutionXpMultiplier.doubleValue).ceil.toInt + ) ) - ) - else ch - case StatAbsolute(_) => ch - case StatNoChange => ch - } + else ch + case StatAbsolute(_) => ch + case StatNoChange => ch + } } ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceOfferMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceOfferMessagePromptGenerator.scala index 0b632b9bae..6e89a1e11b 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceOfferMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceOfferMessagePromptGenerator.scala @@ -16,7 +16,7 @@ case class AllianceOfferMessagePromptGenerator( allianceOfferMessage.offeringFactionId, gameState ) - private val targetFaction = + private val targetFaction = FactionInfoUtilities.getFaction( allianceOfferMessage.targetFactionId, gameState @@ -33,30 +33,30 @@ case class AllianceOfferMessagePromptGenerator( override def generate: TextGenerationResult = for { offeringFactionLeaderDescription <- description( - heroId = offeringFaction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderDescription <- description( - heroId = targetFaction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - messengerHeroDescription <- description( - heroId = allianceOfferMessage.messengerHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + heroId = offeringFaction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderDescription <- description( + heroId = targetFaction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + messengerHeroDescription <- description( + heroId = allianceOfferMessage.messengerHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) offeringFactionLeaderName <- clientTextStore.getText( - offeringFactionLeader.nameTextId - ) + offeringFactionLeader.nameTextId + ) targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + targetFactionLeader.nameTextId + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val objP = HeroDescriptionGenerator.objectPronoun(messengerHero.pronounGender) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceResolutionMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceResolutionMessagePromptGenerator.scala index cb032d8837..b19ea7d8f8 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceResolutionMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/AllianceResolutionMessagePromptGenerator.scala @@ -19,7 +19,7 @@ case class AllianceResolutionMessagePromptGenerator( clientTextStore: ClientTextStore ) extends LLMPromptGenerator { import HeroDescriptionGenerator.description - private val offeringFaction = + private val offeringFaction = FactionInfoUtilities.getFaction( allianceOfferResolutionMessage.offeringFactionId, gameState @@ -27,7 +27,7 @@ case class AllianceResolutionMessagePromptGenerator( private val offeringFactionLeader = gameState.heroes(offeringFaction.factionHeadId) - private val targetFaction = + private val targetFaction = FactionInfoUtilities.getFaction( allianceOfferResolutionMessage.targetFactionId, gameState @@ -40,28 +40,28 @@ case class AllianceResolutionMessagePromptGenerator( override def generate: TextGenerationResult = for { offeringFactionLeaderDescription <- description( - heroId = offeringFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderDescription <- description( - heroId = targetFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - messengerHeroDescription <- description( - heroId = messengerHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - offeringFactionLeaderName <- clientTextStore.getText( - offeringFactionLeader.nameTextId - ) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = offeringFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderDescription <- description( + heroId = targetFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + messengerHeroDescription <- description( + heroId = messengerHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) + offeringFactionLeaderName <- clientTextStore.getText( + offeringFactionLeader.nameTextId + ) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val factionLeaderText = @@ -70,19 +70,19 @@ case class AllianceResolutionMessagePromptGenerator( val resolutionMessage = allianceOfferResolutionMessage.resolutionStatus match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"""$targetFactionLeaderName decided to accept the alliance. - | - |$offeringFactionLeaderName and $targetFactionLeaderName have signed an alliance, which is permanent until one decides to break it. They stand united against the other factions in the civil war. - |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this new alliance.""".stripMargin - case DIPLOMACY_OFFER_STATUS_REJECTED => + | + |$offeringFactionLeaderName and $targetFactionLeaderName have signed an alliance, which is permanent until one decides to break it. They stand united against the other factions in the civil war. + |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this new alliance.""".stripMargin + case DIPLOMACY_OFFER_STATUS_REJECTED => s"""$targetFactionLeaderName rejected the alliance. - | - |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this rejection.""".stripMargin - case DIPLOMACY_OFFER_STATUS_IMPRISONED => + | + |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this rejection.""".stripMargin + case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"""$targetFactionLeaderName not only rejected the alliance, but imprisoned the ambassador $messengerHeroName! - | - |Write a message that $messengerHeroName send to the world in reporting their imprisonment.""".stripMargin + | + |Write a message that $messengerHeroName send to the world in reporting their imprisonment.""".stripMargin case DIPLOMACY_OFFER_STATUS_INVALIDATED => ??? case DIPLOMACY_OFFER_STATUS_UNKNOWN => ??? case DIPLOMACY_OFFER_STATUS_UNRESOLVED => ??? diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceMessagePromptGenerator.scala index e7cffcb3eb..790bb66ea6 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceMessagePromptGenerator.scala @@ -14,14 +14,14 @@ case class BreakAllianceMessagePromptGenerator( private val messengerHero = gameState.heroes(breakAllianceMessage.messengerHeroId) - private val targetFaction = FactionInfoUtilities.getFaction( + private val targetFaction = FactionInfoUtilities.getFaction( breakAllianceMessage.targetFactionId, gameState ) private val targetFactionLeader = gameState.heroes(targetFaction.factionHeadId) - private val breakingFaction = + private val breakingFaction = FactionInfoUtilities.getFaction( breakAllianceMessage.breakingFactionId, gameState @@ -31,29 +31,29 @@ case class BreakAllianceMessagePromptGenerator( override def generate: TextGenerationResult = for { breakingFactionLeaderDescription <- description( - heroId = breakAllianceMessage.breakingFactionId, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderDescription <- description( - heroId = breakAllianceMessage.targetFactionId, - gameState = gameState, - clientTextStore = clientTextStore - ) - messengerHeroDescription <- description( - heroId = breakAllianceMessage.messengerHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) + heroId = breakAllianceMessage.breakingFactionId, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderDescription <- description( + heroId = breakAllianceMessage.targetFactionId, + gameState = gameState, + clientTextStore = clientTextStore + ) + messengerHeroDescription <- description( + heroId = breakAllianceMessage.messengerHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) breakingFactionLeaderName <- clientTextStore.getText( - breakingFactionLeader.nameTextId - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + breakingFactionLeader.nameTextId + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val breakingSubjP = HeroDescriptionGenerator.objectPronoun( breakingFactionLeader.pronounGender diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceResolutionMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceResolutionMessagePromptGenerator.scala index 167e58e19c..6a8415f74d 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceResolutionMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/BreakAllianceResolutionMessagePromptGenerator.scala @@ -21,21 +21,21 @@ case class BreakAllianceResolutionMessagePromptGenerator( ) extends LLMPromptGenerator { import HeroDescriptionGenerator.description - private val breakingFaction = + private val breakingFaction = FactionInfoUtilities.getFaction( breakAllianceResolutionMessage.breakingFactionId, gameState ) private val breakingFactionLeader = gameState.heroes(breakingFaction.factionHeadId) - private val breakingSubjP = HeroDescriptionGenerator.subjectPronoun( + private val breakingSubjP = HeroDescriptionGenerator.subjectPronoun( breakingFactionLeader.pronounGender ) - private val breakingObjP = HeroDescriptionGenerator.objectPronoun( + private val breakingObjP = HeroDescriptionGenerator.objectPronoun( breakingFactionLeader.pronounGender ) - private val targetFaction = + private val targetFaction = FactionInfoUtilities.getFaction( breakAllianceResolutionMessage.targetFactionId, gameState @@ -47,29 +47,29 @@ case class BreakAllianceResolutionMessagePromptGenerator( gameState.heroes(breakAllianceResolutionMessage.messengerHeroId) override def generate: TextGenerationResult = for { - messengerHeroDescription <- description( - heroId = messengerHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) + messengerHeroDescription <- description( + heroId = messengerHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) breakingFactionLeaderDescription <- description( - heroId = breakingFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderDescription <- description( - heroId = targetFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - breakingFactionLeaderName <- clientTextStore.getText( - breakingFactionLeader.nameTextId - ) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = breakingFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderDescription <- description( + heroId = targetFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) + breakingFactionLeaderName <- clientTextStore.getText( + breakingFactionLeader.nameTextId + ) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val factionLeaderText = if breakingFactionLeader.id == messengerHero.id then "" @@ -77,13 +77,13 @@ case class BreakAllianceResolutionMessagePromptGenerator( val resolutionMessage = breakAllianceResolutionMessage.resolutionStatus match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"""$targetFactionLeaderName had no choice but to accept the end of the alliance. | |Write a message that $breakingFactionLeaderName might tell $targetFactionLeaderName, and the world, about the end of their alliance.""".stripMargin - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => throw new EagleInternalException("Should not be possible") - case DIPLOMACY_OFFER_STATUS_IMPRISONED => + case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"""$targetFactionLeaderName, upset about this change, imprisoned the ambassador $messengerHeroName! | |Write a message that $breakingFactionLeaderName send to the world in reporting the end of the alliance and $messengerHeroName's imprisonment.""".stripMargin diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGenerator.scala index ed4428f87e..fd89258adb 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGenerator.scala @@ -15,23 +15,23 @@ case class CapturedHeroExecutedPromptGenerator( ) extends LLMPromptGenerator { private val capturedHero = HeroInfoUtilities.getHero(executedMessage.capturedHeroId, gameState) - private val actingHero = + private val actingHero = HeroInfoUtilities.getHero(executedMessage.actingHeroId, gameState) override def generate: TextGenerationResult = for { capturedHeroDescription <- HeroDescriptionGenerator.description( - executedMessage.capturedHeroId, - gameState, - clientTextStore - ) - actingHeroDescription <- HeroDescriptionGenerator.description( - executedMessage.actingHeroId, - gameState, - clientTextStore - ) - capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) - actingHeroName <- clientTextStore.getText(actingHero.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + executedMessage.capturedHeroId, + gameState, + clientTextStore + ) + actingHeroDescription <- HeroDescriptionGenerator.description( + executedMessage.actingHeroId, + gameState, + clientTextStore + ) + capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) + actingHeroName <- clientTextStore.getText(actingHero.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val province = gameState.provinces(executedMessage.provinceId) @@ -61,39 +61,39 @@ case class CapturedHeroImprisonedPromptGenerator( gameState: GameState, clientTextStore: ClientTextStore ) extends LLMPromptGenerator { - private val capturedHero = + private val capturedHero = HeroInfoUtilities.getHero(imprisonedMessage.capturedHeroId, gameState) private val capturedHeroFaction = FactionInfoUtilities.getFaction( imprisonedMessage.capturedHeroFactionId, gameState ) - private val chFactionLeader = + private val chFactionLeader = HeroInfoUtilities.getHero(capturedHeroFaction.factionHeadId, gameState) private val actingHero = HeroInfoUtilities.getHero(imprisonedMessage.actingHeroId, gameState) override def generate: TextGenerationResult = for { - capturedHeroDescription <- HeroDescriptionGenerator.description( - heroId = imprisonedMessage.capturedHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) + capturedHeroDescription <- HeroDescriptionGenerator.description( + heroId = imprisonedMessage.capturedHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) factionLeaderDescription <- HeroDescriptionGenerator.description( - heroId = chFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - actingHeroDescription <- HeroDescriptionGenerator.description( - heroId = imprisonedMessage.actingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) - actingHeroName <- clientTextStore.getText(actingHero.nameTextId) - chFactionLeaderName <- clientTextStore.getText(chFactionLeader.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = chFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + actingHeroDescription <- HeroDescriptionGenerator.description( + heroId = imprisonedMessage.actingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) + actingHeroName <- clientTextStore.getText(actingHero.nameTextId) + chFactionLeaderName <- clientTextStore.getText(chFactionLeader.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val province = gameState.provinces(imprisonedMessage.provinceId) @@ -103,7 +103,7 @@ case class CapturedHeroImprisonedPromptGenerator( val subjP = HeroDescriptionGenerator.subjectPronoun(capturedHero.pronounGender) - val capturedHeroIsFactionLeader = chFactionLeader.id == capturedHero.id + val capturedHeroIsFactionLeader = chFactionLeader.id == capturedHero.id val capturedHeroFactionIsDestroyed = gameState.destroyedFactions.contains( imprisonedMessage.capturedHeroFactionId ) @@ -153,34 +153,34 @@ case class CapturedHeroExiledPromptGenerator( exiledMessage.capturedHeroFactionId, gameState ) - private val chFactionLeader = + private val chFactionLeader = HeroInfoUtilities.getHero(capturedHeroFaction.factionHeadId, gameState) - private val capturedHero = + private val capturedHero = HeroInfoUtilities.getHero(exiledMessage.capturedHeroId, gameState) private val actingHero = HeroInfoUtilities.getHero(exiledMessage.actingHeroId, gameState) override def generate: TextGenerationResult = for { - capturedHeroDescription <- HeroDescriptionGenerator.description( - heroId = exiledMessage.capturedHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) + capturedHeroDescription <- HeroDescriptionGenerator.description( + heroId = exiledMessage.capturedHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) factionLeaderDescription <- HeroDescriptionGenerator.description( - heroId = chFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - actingHeroDescription <- HeroDescriptionGenerator.description( - heroId = exiledMessage.actingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) - actingHeroName <- clientTextStore.getText(actingHero.nameTextId) - chFactionLeaderName <- clientTextStore.getText(chFactionLeader.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = chFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + actingHeroDescription <- HeroDescriptionGenerator.description( + heroId = exiledMessage.actingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) + actingHeroName <- clientTextStore.getText(actingHero.nameTextId) + chFactionLeaderName <- clientTextStore.getText(chFactionLeader.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val factionLeaderIsDead = gameState.killedHeroes.contains(chFactionLeader.id) @@ -196,8 +196,7 @@ case class CapturedHeroExiledPromptGenerator( val serviceText = if factionLeaderIsDead then "" - else - s"As a condition of $possP release, $capturedHeroName will no longer serve their liege $chFactionLeaderName." + else s"As a condition of $possP release, $capturedHeroName will no longer serve their liege $chFactionLeaderName." val inputText = s"""$setup diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleEventTextGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleEventTextGenerator.scala index 358c271e6f..97f0e973a8 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleEventTextGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleEventTextGenerator.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators -import net.eagle0.eagle.client_text.{ - ClientTextStore, - TextGenerationResult, - TextGenerationSuccess -} +import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult, TextGenerationSuccess} import net.eagle0.eagle.internal.event_for_chronicle.{ AllianceAcceptedEvent, BreakAllianceAmbassadorImprisonedEvent, @@ -61,15 +57,13 @@ object ChronicleEventTextGenerator { ) => val offeringFactionName = getFaction(offeringFactionId, gameState).name - val targetFactionName = + val targetFactionName = getFaction(targetFactionId, gameState).name - val ambassador = maybeKilledHero(ambassadorHeroId, gameState) + val ambassador = maybeKilledHero(ambassadorHeroId, gameState) for { ambassadorName <- text(ambassador.nameTextId) - } yield { - s"$targetFactionName accepted an alliance offer from $offeringFactionName, with $ambassadorName as the ambassador." - } + } yield s"$targetFactionName accepted an alliance offer from $offeringFactionName, with $ambassadorName as the ambassador." case BreakAllianceEvent( offeringFactionId, @@ -79,17 +73,15 @@ object ChronicleEventTextGenerator { ) => val offeringFactionName = getFaction(offeringFactionId, gameState).name - val targetFactionName = + val targetFactionName = getFaction(targetFactionId, gameState).name - val ambassador = + val ambassador = maybeKilledHero(ambassadorHeroId, gameState) for { ambassadorBackstory <- text(ambassador.backstoryVersions.last.textId) - ambassadorName <- text(ambassador.nameTextId) - } yield { - s"$offeringFactionName broke their alliance with $targetFactionName. $ambassadorName was the ambassador. $ambassadorBackstory" - } + ambassadorName <- text(ambassador.nameTextId) + } yield s"$offeringFactionName broke their alliance with $targetFactionName. $ambassadorName was the ambassador. $ambassadorBackstory" case BreakAllianceAmbassadorImprisonedEvent( offeringFactionId, targetFactionId, @@ -98,18 +90,16 @@ object ChronicleEventTextGenerator { ) => val offeringFactionName = getFaction(offeringFactionId, gameState).name - val targetFactionName = + val targetFactionName = getFaction(targetFactionId, gameState).name - val ambassador = maybeKilledHero(ambassadorHeroId, gameState) + val ambassador = maybeKilledHero(ambassadorHeroId, gameState) for { ambassadorBackstory <- text( - ambassador.backstoryVersions.last.textId - ) - ambassadorName <- text(ambassador.nameTextId) - } yield { - s"$offeringFactionName broke their alliance with $targetFactionName, and $targetFactionName imprisoned the ambassador, $ambassadorName, in response. $ambassadorBackstory" - } + ambassador.backstoryVersions.last.textId + ) + ambassadorName <- text(ambassador.nameTextId) + } yield s"$offeringFactionName broke their alliance with $targetFactionName, and $targetFactionName imprisoned the ambassador, $ambassadorName, in response. $ambassadorBackstory" case CapturedHeroExiledEvent( capturedFromFactionId, @@ -120,18 +110,16 @@ object ChronicleEventTextGenerator { ) => val capturedFromFactionName = getFaction(capturedFromFactionId, gameState).name - val provinceName = gameState.provinces(provinceId).name - val exiledHero = maybeKilledHero(exiledHeroId, gameState) - val exilingFactionName = + val provinceName = gameState.provinces(provinceId).name + val exiledHero = maybeKilledHero(exiledHeroId, gameState) + val exilingFactionName = getFaction(exilingFactionId, gameState).name for { exiledHeroBackstory <- text(exiledHero.backstoryVersions.last.textId) - exiledHeroName <- text(exiledHero.nameTextId) - } yield { - s"$exilingFactionName captured $exiledHeroName, previously of $capturedFromFactionName, in battle in $provinceName and sent ${HeroDescriptionGenerator - .objectPronoun(exiledHero.pronounGender)} into exile. $exiledHeroBackstory" - } + exiledHeroName <- text(exiledHero.nameTextId) + } yield s"$exilingFactionName captured $exiledHeroName, previously of $capturedFromFactionName, in battle in $provinceName and sent ${HeroDescriptionGenerator + .objectPronoun(exiledHero.pronounGender)} into exile. $exiledHeroBackstory" case CapturedHeroExecutedEvent( capturedFromFactionId, @@ -142,20 +130,18 @@ object ChronicleEventTextGenerator { ) => val capturedFromFactionName = getFaction(capturedFromFactionId, gameState).name - val provinceName = gameState.provinces(provinceId).name - val executedHero = maybeKilledHero(executedHeroId, gameState) - val executingFactionName = + val provinceName = gameState.provinces(provinceId).name + val executedHero = maybeKilledHero(executedHeroId, gameState) + val executingFactionName = getFaction(executingFactionId, gameState).name for { executedHeroBackstory <- text( - executedHero.backstoryVersions.last.textId - ) - executedHeroName <- text(executedHero.nameTextId) - } yield { - s"$executingFactionName captured $executedHeroName, previously of $capturedFromFactionName, in battle in $provinceName and executed ${HeroDescriptionGenerator - .objectPronoun(executedHero.pronounGender)}! $executedHeroBackstory" - } + executedHero.backstoryVersions.last.textId + ) + executedHeroName <- text(executedHero.nameTextId) + } yield s"$executingFactionName captured $executedHeroName, previously of $capturedFromFactionName, in battle in $provinceName and executed ${HeroDescriptionGenerator + .objectPronoun(executedHero.pronounGender)}! $executedHeroBackstory" case CapturedHeroImprisonedEvent( capturedFromFactionId, @@ -166,20 +152,18 @@ object ChronicleEventTextGenerator { ) => val capturedFromFactionName = getFaction(capturedFromFactionId, gameState).name - val provinceName = gameState.provinces(provinceId).name - val imprisonedHero = maybeKilledHero(imprisonedHeroId, gameState) - val imprisoningFactionName = + val provinceName = gameState.provinces(provinceId).name + val imprisonedHero = maybeKilledHero(imprisonedHeroId, gameState) + val imprisoningFactionName = getFaction(imprisoningFactionId, gameState).name for { imprisonedHeroBackstory <- text( - imprisonedHero.backstoryVersions.last.textId - ) - imprisonedHeroName <- text(imprisonedHero.nameTextId) - } yield { - s"$imprisoningFactionName captured $imprisonedHeroName, previously of $capturedFromFactionName, in battle in $provinceName and imprisoned ${HeroDescriptionGenerator - .objectPronoun(imprisonedHero.pronounGender)}. $imprisonedHeroBackstory" - } + imprisonedHero.backstoryVersions.last.textId + ) + imprisonedHeroName <- text(imprisonedHero.nameTextId) + } yield s"$imprisoningFactionName captured $imprisonedHeroName, previously of $capturedFromFactionName, in battle in $provinceName and imprisoned ${HeroDescriptionGenerator + .objectPronoun(imprisonedHero.pronounGender)}. $imprisonedHeroBackstory" case FactionDestroyedEvent(factionId, _ /* unknownFieldSet */ ) => TextGenerationSuccess( @@ -193,17 +177,15 @@ object ChronicleEventTextGenerator { _ /* unknownFieldSet */ ) => val departingHero = maybeKilledHero(departingHeroId, gameState) - val fromFaction = getFaction(fromFactionId, gameState) - val province = gameState.provinces(provinceId) + val fromFaction = getFaction(fromFactionId, gameState) + val province = gameState.provinces(provinceId) for { departingHeroBackstory <- text( - departingHero.backstoryVersions.last.textId - ) - departingHeroName <- text(departingHero.nameTextId) - } yield { - s"$departingHeroName of ${province.name} left ${fromFaction.name}. $departingHeroBackstory" - } + departingHero.backstoryVersions.last.textId + ) + departingHeroName <- text(departingHero.nameTextId) + } yield s"$departingHeroName of ${province.name} left ${fromFaction.name}. $departingHeroBackstory" case InvitationAcceptedEvent( offeringFactionId, @@ -212,7 +194,7 @@ object ChronicleEventTextGenerator { ) => val offeringFactionName = getFaction(offeringFactionId, gameState).name - val invitedFactionName = + val invitedFactionName = getFaction(invitedFactionId, gameState).name TextGenerationSuccess( @@ -227,16 +209,14 @@ object ChronicleEventTextGenerator { ) => val offeringFactionName = getFaction(offeringFactionId, gameState).name - val invitedFactionName = + val invitedFactionName = getFaction(invitedFactionId, gameState).name - val ambassador = maybeKilledHero(ambassadorHeroId, gameState) + val ambassador = maybeKilledHero(ambassadorHeroId, gameState) for { ambassadorBackstory <- text(ambassador.backstoryVersions.last.textId) - ambassadorName <- text(ambassador.nameTextId) - } yield { - s"$offeringFactionName invited $invitedFactionName to join with them, but $invitedFactionName imprisoned the ambassador, $ambassadorName, instead. $ambassadorBackstory" - } + ambassadorName <- text(ambassador.nameTextId) + } yield s"$offeringFactionName invited $invitedFactionName to join with them, but $invitedFactionName imprisoned the ambassador, $ambassadorName, instead. $ambassadorBackstory" case OutlawApprehendedEvent( factionId, @@ -244,19 +224,17 @@ object ChronicleEventTextGenerator { apprehendedHeroId, _ /* unknownFieldSet */ ) => - val faction = getFaction(factionId, gameState) - val province = gameState.provinces(provinceId) + val faction = getFaction(factionId, gameState) + val province = gameState.provinces(provinceId) val apprehendedHero = maybeKilledHero(apprehendedHeroId, gameState) for { apprehendedHeroBackstory <- text( - apprehendedHero.backstoryVersions.last.textId - ) - apprehendedHeroName <- text(apprehendedHero.nameTextId) - } yield { - s"${faction.name} apprehended the outlaw $apprehendedHeroName in ${province.name}. $apprehendedHeroBackstory" - } + apprehendedHero.backstoryVersions.last.textId + ) + apprehendedHeroName <- text(apprehendedHero.nameTextId) + } yield s"${faction.name} apprehended the outlaw $apprehendedHeroName in ${province.name}. $apprehendedHeroBackstory" case PrisonerExecutedEvent( lastFactionId, @@ -265,29 +243,27 @@ object ChronicleEventTextGenerator { executingFactionId, _ /* unknownFieldSet */ ) => - val lastFactionName = + val lastFactionName = lastFactionId .map(fid => getFaction(fid, gameState)) .map(_.name) - val provinceName = gameState.provinces(provinceId).name - val executedHero = maybeKilledHero(executedHeroId, gameState) + val provinceName = gameState.provinces(provinceId).name + val executedHero = maybeKilledHero(executedHeroId, gameState) val executingFactionName = getFaction(executingFactionId, gameState).name for { executedHeroBackstory <- text( - executedHero.backstoryVersions.last.textId + executedHero.backstoryVersions.last.textId + ) + executedHeroName <- text(executedHero.nameTextId) + } yield lastFactionName + .map(lfn => + s"$executingFactionName executed $executedHeroName, previously of $lfn, in $provinceName. $executedHeroBackstory" + ) + .getOrElse( + s"$executingFactionName executed $executedHeroName in $provinceName. $executedHeroBackstory" ) - executedHeroName <- text(executedHero.nameTextId) - } yield { - lastFactionName - .map(lfn => - s"$executingFactionName executed $executedHeroName, previously of $lfn, in $provinceName. $executedHeroBackstory" - ) - .getOrElse( - s"$executingFactionName executed $executedHeroName in $provinceName. $executedHeroBackstory" - ) - } case PrisonersExchangedEvent( hero1Id, @@ -298,21 +274,19 @@ object ChronicleEventTextGenerator { hero2ProvinceId, _ /* unknownFieldSet */ ) => - val hero1 = maybeKilledHero(hero1Id, gameState) - val hero1Faction = + val hero1 = maybeKilledHero(hero1Id, gameState) + val hero1Faction = getFaction(hero1FactionId, gameState) val hero1Province = gameState.provinces(hero1ProvinceId) - val hero2 = maybeKilledHero(hero2Id, gameState) - val hero2Faction = + val hero2 = maybeKilledHero(hero2Id, gameState) + val hero2Faction = getFaction(hero2FactionId, gameState) val hero2Province = gameState.provinces(hero2ProvinceId) for { hero1Name <- text(hero1.nameTextId) hero2Name <- text(hero2.nameTextId) - } yield { - s"${hero1Faction.name} and ${hero2Faction.name} exchanged prisoners. ${hero1Faction.name}'s hero $hero1Name was returned to ${hero1Province.name} and ${hero2Faction.name}'s hero $hero2Name was returned to ${hero2Province.name}." - } + } yield s"${hero1Faction.name} and ${hero2Faction.name} exchanged prisoners. ${hero1Faction.name}'s hero $hero1Name was returned to ${hero1Province.name} and ${hero2Faction.name}'s hero $hero2Name was returned to ${hero2Province.name}." case ProvinceConqueredEvent( provinceId, @@ -321,13 +295,13 @@ object ChronicleEventTextGenerator { defendingFactionId, _ /* unknownFieldSet */ ) => - val provinceName = gameState.provinces(provinceId).name - val conqueringFactionName = + val provinceName = gameState.provinces(provinceId).name + val conqueringFactionName = getFaction(conqueringFactionId, gameState).name val otherAttackingFactions = otherAttackingFactionIds .map(fid => getFaction(fid, gameState)) - val defendingFactionName = + val defendingFactionName = getFaction(defendingFactionId, gameState).name TextGenerationSuccess( @@ -343,7 +317,7 @@ object ChronicleEventTextGenerator { expandingFactionId, _ /* unknownFieldSet */ ) => - val provinceName = gameState.provinces(provinceId).name + val provinceName = gameState.provinces(provinceId).name val expandingFactionName = getFaction(expandingFactionId, gameState).name @@ -357,14 +331,14 @@ object ChronicleEventTextGenerator { defendingFactionId, _ /* unknownFieldSet */ ) => - val provinceName = gameState.provinces(provinceId).name + val provinceName = gameState.provinces(provinceId).name val attackingFactionNames = GeneratorUtilities.conjunction( attackingFactionIds .map(fid => getFaction(fid, gameState)) .map(_.name) .toVector ) - val defendingFactionName = + val defendingFactionName = getFaction(defendingFactionId, gameState).name TextGenerationSuccess( @@ -377,7 +351,7 @@ object ChronicleEventTextGenerator { ransomPaidToFactionId, _ /* unknownFieldSet */ ) => - val ransomedHero = maybeKilledHero(ransomedHeroId, gameState) + val ransomedHero = maybeKilledHero(ransomedHeroId, gameState) val ransomPaidByFaction = getFaction(ransomPaidByFactionId, gameState) val ransomPaidToFaction = @@ -385,12 +359,10 @@ object ChronicleEventTextGenerator { for { ransomedHeroBackstory <- text( - ransomedHero.backstoryVersions.last.textId - ) - ransomedHeroName <- text(ransomedHero.nameTextId) - } yield { - s"${ransomPaidByFaction.name} paid a ransom to ${ransomPaidToFaction.name} for $ransomedHeroName's release. $ransomedHeroBackstory" - } + ransomedHero.backstoryVersions.last.textId + ) + ransomedHeroName <- text(ransomedHero.nameTextId) + } yield s"${ransomPaidByFaction.name} paid a ransom to ${ransomPaidToFaction.name} for $ransomedHeroName's release. $ransomedHeroBackstory" case RansomRejectedEvent( ransomedHeroId, @@ -398,20 +370,18 @@ object ChronicleEventTextGenerator { ransomOfferingFactionId, _ /* unknownFieldSet */ ) => - val ransomedHero = maybeKilledHero(ransomedHeroId, gameState) + val ransomedHero = maybeKilledHero(ransomedHeroId, gameState) val ransomRefusedByFaction = getFaction(ransomRejectedByFactionId, gameState) - val ransomOfferingFaction = + val ransomOfferingFaction = getFaction(ransomOfferingFactionId, gameState) for { notRansomedHeroBackstory <- text( - ransomedHero.backstoryVersions.last.textId - ) - ransomedHeroName <- text(ransomedHero.nameTextId) - } yield { - s"${ransomRefusedByFaction.name} refused a ransom offer from ${ransomOfferingFaction.name} for $ransomedHeroName. $notRansomedHeroBackstory" - } + ransomedHero.backstoryVersions.last.textId + ) + ransomedHeroName <- text(ransomedHero.nameTextId) + } yield s"${ransomRefusedByFaction.name} refused a ransom offer from ${ransomOfferingFaction.name} for $ransomedHeroName. $notRansomedHeroBackstory" case ShatteredArmyEvent( factionId, @@ -419,15 +389,15 @@ object ChronicleEventTextGenerator { reason, _ /* unknownFieldSet */ ) => - val faction = getFaction(factionId, gameState) - val province = gameState.provinces(provinceId) + val faction = getFaction(factionId, gameState) + val province = gameState.provinces(provinceId) val reasonString = reason match { - case SHATTERED_ARMY_EVENT_REASON_BLIZZARD => "a blizzard" - case SHATTERED_ARMY_EVENT_REASON_WITHDRAW => + case SHATTERED_ARMY_EVENT_REASON_BLIZZARD => "a blizzard" + case SHATTERED_ARMY_EVENT_REASON_WITHDRAW => "a retreat from the enemy" case SHATTERED_ARMY_EVENT_REASON_UNKNOWN_UNSPECIFIED => "unknown forces" - case ShatteredArmyEvent.Reason.Unrecognized(_) => + case ShatteredArmyEvent.Reason.Unrecognized(_) => "unknown forces" } @@ -442,35 +412,31 @@ object ChronicleEventTextGenerator { pluralName, _ /* unknownFieldSet */ ) => - val hero = maybeKilledHero(heroId, gameState) + val hero = maybeKilledHero(heroId, gameState) val province = gameState.provinces(provinceId) for { heroBackstory <- text(hero.backstoryVersions.last.textId) - heroName <- text(hero.nameTextId) - } yield { - s"$heroName was eradicated attempting to fight $pluralName in ${province.name}. $heroBackstory" - } + heroName <- text(hero.nameTextId) + } yield s"$heroName was eradicated attempting to fight $pluralName in ${province.name}. $heroBackstory" case SwearBrotherhoodEvent( factionId, newBrotherHeroId, _ /* unknownFieldSet */ ) => - val faction = FactionInfoUtilities.getFaction(factionId, gameState) + val faction = FactionInfoUtilities.getFaction(factionId, gameState) val factionHead = maybeKilledHero(faction.factionHeadId, gameState) - val newBrother = maybeKilledHero(newBrotherHeroId, gameState) + val newBrother = maybeKilledHero(newBrotherHeroId, gameState) for { newBrotherBackstory <- text( - newBrother.backstoryVersions.last.textId - ) - newBrotherName <- text(newBrother.nameTextId) - factionHeadName <- text(factionHead.nameTextId) - } yield { - s"${faction.name}'s leader $factionHeadName swore brotherhood with $newBrotherName. $newBrotherBackstory" - } + newBrother.backstoryVersions.last.textId + ) + newBrotherName <- text(newBrother.nameTextId) + factionHeadName <- text(factionHead.nameTextId) + } yield s"${faction.name}'s leader $factionHeadName swore brotherhood with $newBrotherName. $newBrotherBackstory" case TruceAcceptedEvent( offeringFactionId, @@ -480,19 +446,17 @@ object ChronicleEventTextGenerator { ) => val offeringFactionName = getFaction(offeringFactionId, gameState).name - val targetFactionName = + val targetFactionName = getFaction(targetFactionId, gameState).name - val ambassador = + val ambassador = maybeKilledHero(ambassadorHeroId, gameState) for { ambassadorBackstory <- text( - ambassador.backstoryVersions.last.textId - ) - ambassadorName <- text(ambassador.nameTextId) - } yield { - s"$targetFactionName accepted a truce offer from $offeringFactionName, with $ambassadorName as the ambassador. $ambassadorBackstory" - } + ambassador.backstoryVersions.last.textId + ) + ambassadorName <- text(ambassador.nameTextId) + } yield s"$targetFactionName accepted a truce offer from $offeringFactionName, with $ambassadorName as the ambassador. $ambassadorBackstory" case TruceAmbassadorImprisonedEvent( offeringFactionId, @@ -502,19 +466,17 @@ object ChronicleEventTextGenerator { ) => val offeringFactionName = getFaction(offeringFactionId, gameState).name - val targetFactionName = + val targetFactionName = getFaction(targetFactionId, gameState).name - val ambassador = + val ambassador = maybeKilledHero(ambassadorHeroId, gameState) for { ambassadorBackstory <- text( - ambassador.backstoryVersions.last.textId - ) - ambassadorName <- text(ambassador.nameTextId) - } yield { - s"$offeringFactionName offered a truce to $targetFactionName, but $targetFactionName imprisoned the ambassador, $ambassadorName, instead. $ambassadorBackstory" - } + ambassador.backstoryVersions.last.textId + ) + ambassadorName <- text(ambassador.nameTextId) + } yield s"$offeringFactionName offered a truce to $targetFactionName, but $targetFactionName imprisoned the ambassador, $ambassadorName, instead. $ambassadorBackstory" case VassalExiledEvent( factionId, @@ -522,18 +484,16 @@ object ChronicleEventTextGenerator { exiledHeroId, _ /* unknownFieldSet */ ) => - val faction = getFaction(factionId, gameState) - val province = gameState.provinces(provinceId) + val faction = getFaction(factionId, gameState) + val province = gameState.provinces(provinceId) val exiledHero = maybeKilledHero(exiledHeroId, gameState) for { exiledHeroBackstory <- text( - exiledHero.backstoryVersions.last.textId - ) - exiledHeroName <- text(exiledHero.nameTextId) - } yield { - s"${faction.name} exiled $exiledHeroName from ${province.name}. $exiledHeroBackstory" - } + exiledHero.backstoryVersions.last.textId + ) + exiledHeroName <- text(exiledHero.nameTextId) + } yield s"${faction.name} exiled $exiledHeroName from ${province.name}. $exiledHeroBackstory" case _ => throw new EagleInternalException(s"Unhandled event type: $details") diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGenerator.scala index e7245b5513..793cae2d04 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGenerator.scala @@ -73,13 +73,13 @@ case class ChronicleUpdatePromptGenerator( .replaceAll("\n", " ") s"""$intro - | - |${MapDescription.mapDescription} - | - |$sampleDescription - |This is a title - |===== - |This is the chronicle text""".stripMargin + | + |${MapDescription.mapDescription} + | + |$sampleDescription + |This is a title + |===== + |This is the chronicle text""".stripMargin } private def eventsString( @@ -107,7 +107,7 @@ case class ChronicleUpdatePromptGenerator( gameState.factions.values.toVector .sortBy(_.id) .map { faction => - val leader = gameState.heroes(faction.factionHeadId) + val leader = gameState.heroes(faction.factionHeadId) val controlledProvinceNames = LegacyFactionUtils .provinces(factionId = faction.id, gameState = gameState) @@ -115,61 +115,55 @@ case class ChronicleUpdatePromptGenerator( for { leaderBackstory <- clientTextStore.getText( - leader.backstoryVersions.last.textId - ) - leaderName <- clientTextStore.getText(leader.nameTextId) + leader.backstoryVersions.last.textId + ) + leaderName <- clientTextStore.getText(leader.nameTextId) } yield { val provinceDescription = - GeneratorUtilities.conjunction(controlledProvinceNames).map { - conj => - s"${faction.name}, led by $leaderName, controls $conj." + GeneratorUtilities.conjunction(controlledProvinceNames).map { conj => + s"${faction.name}, led by $leaderName, controls $conj." } s"${provinceDescription.getOrElse("")} $leaderBackstory" } - } ++ gameState.destroyedFactions.values.toVector.sortBy(_.id).map { - faction => - val (leader, alive) = { - gameState.heroes - .get(faction.factionHeadId) - .map { hero => - (hero, true) - } - .getOrElse { - (gameState.killedHeroes(faction.factionHeadId), false) - } - } - val statusText = - if alive then - s"is alive and in the service of ${leader.factionId.map(gameState.factions).map(_.name).getOrElse("no faction")}" - else "is dead" + } ++ gameState.destroyedFactions.values.toVector.sortBy(_.id).map { faction => + val (leader, alive) = + gameState.heroes + .get(faction.factionHeadId) + .map { hero => + (hero, true) + } + .getOrElse { + (gameState.killedHeroes(faction.factionHeadId), false) + } + val statusText = + if alive then + s"is alive and in the service of ${leader.factionId.map(gameState.factions).map(_.name).getOrElse("no faction")}" + else "is dead" - for { - leaderBackstory <- clientTextStore - .getText(leader.backstoryVersions.last.textId) - leaderName <- clientTextStore.getText(leader.nameTextId) - } yield { - s"${faction.name} was destroyed. Their former leader, $leaderName, $statusText. $leaderBackstory" - } + for { + leaderBackstory <- clientTextStore + .getText(leader.backstoryVersions.last.textId) + leaderName <- clientTextStore.getText(leader.nameTextId) + } yield s"${faction.name} was destroyed. Their former leader, $leaderName, $statusText. $leaderBackstory" }, "\n" ) private def previousEntryText: Vector[TextGenerationResult] = - chronicleUpdateMessage.previousEntries.toVector - .map { entry => - clientTextStore.getText(entry.generatedTextId).map { text => - s"${GeneratorUtilities.dateString(entry.date.get)}\n$text" - } + chronicleUpdateMessage.previousEntries.toVector.map { entry => + clientTextStore.getText(entry.generatedTextId).map { text => + s"${GeneratorUtilities.dateString(entry.date.get)}\n$text" } + } override def generate: TextGenerationResult = for { previousEntriesString <- TextGenerationResult.mkString( - previousEntryText, - "\n\n" - ) - factionText <- factionDescriptions(gameState) - eventsText <- eventsString(chronicleUpdateMessage.newEntries.toVector) + previousEntryText, + "\n\n" + ) + factionText <- factionDescriptions(gameState) + eventsText <- eventsString(chronicleUpdateMessage.newEntries.toVector) } yield { SimpleTimedLogger.printLogger.logLine(s"random style is $randomStyle") s"""${introString(chronicleUpdateMessage.currentDate.get)} diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/DivineMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/DivineMessagePromptGenerator.scala index 0dc7a845ed..b432fe0da1 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/DivineMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/DivineMessagePromptGenerator.scala @@ -1,11 +1,7 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} -import net.eagle0.eagle.client_text.{ - ClientTextStore, - TextGenerationResult, - TextGenerationSuccess -} +import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult, TextGenerationSuccess} import net.eagle0.eagle.common.battalion_type.BattalionTypeId import net.eagle0.eagle.common.unaffiliated_hero_quest.{ AllianceQuest, @@ -33,10 +29,7 @@ import net.eagle0.eagle.common.unaffiliated_hero_quest.QuestDetails.Empty import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.generated_text_request.DivineMessage import net.eagle0.eagle.internal.hero.Hero -import net.eagle0.eagle.library.actions.llm_prompt_generators.HeroDescriptionGenerator.{ - objectPronoun, - subjectPronoun -} +import net.eagle0.eagle.library.actions.llm_prompt_generators.HeroDescriptionGenerator.{objectPronoun, subjectPronoun} case class DivineMessagePromptGenerator( divineMessage: DivineMessage, @@ -46,10 +39,10 @@ case class DivineMessagePromptGenerator( import HeroDescriptionGenerator.{description, descriptionWithoutFaction} private val divinedHero = gameState.heroes(divineMessage.divinedHeroId) - private val faction = + private val faction = FactionInfoUtilities.getFaction(divineMessage.actingFactionId, gameState) - private val actingHero = gameState.heroes(divineMessage.actingHeroId) - private val province = gameState.provinces(divineMessage.provinceId) + private val actingHero = gameState.heroes(divineMessage.actingHeroId) + private val province = gameState.provinces(divineMessage.provinceId) def questDescription(divinedHero: Hero): TextGenerationResult = { val quest = province.unaffiliatedHeroes @@ -69,16 +62,15 @@ case class DivineMessagePromptGenerator( targetFactionId: FactionId, _ /* unknownFieldSet */ ) => - val targetFaction = + val targetFaction = FactionInfoUtilities.getFaction(targetFactionId, gameState) val targetFactionLeader = gameState.heroes(targetFaction.factionHeadId) - description(targetFactionLeader.id, gameState, clientTextStore) - .map { targetFactionLeaderDescription => - s"""$divinedHeroName wants ${faction.name} to defeat ${targetFaction.name} in battle. + description(targetFactionLeader.id, gameState, clientTextStore).map { targetFactionLeaderDescription => + s"""$divinedHeroName wants ${faction.name} to defeat ${targetFaction.name} in battle. |$targetFactionLeaderDescription""".stripMargin - } + } case AlmsAcrossRealmQuest(amount: Int, _ /* unknownFieldSet */ ) => TextGenerationSuccess( @@ -100,59 +92,53 @@ case class DivineMessagePromptGenerator( provinceId: ProvinceId, _ /* unknownFieldSet */ ) => - val prisonerHero = gameState.heroes(prisonerHeroId) + val prisonerHero = gameState.heroes(prisonerHeroId) val targetProvince = gameState.provinces(provinceId) for { prisonerDescription <- descriptionWithoutFaction( - hero = prisonerHero, - alive = true, - clientTextStore = clientTextStore - ) - prisonerHeroName <- clientTextStore - .getText(prisonerHero.nameTextId) - actingHeroName <- clientTextStore.getText(actingHero.nameTextId) - } yield { - s"$divinedHeroName wants $actingHeroName to execute the prisoner $prisonerHeroName in ${targetProvince.name}.\n\n$prisonerDescription" - } + hero = prisonerHero, + alive = true, + clientTextStore = clientTextStore + ) + prisonerHeroName <- clientTextStore + .getText(prisonerHero.nameTextId) + actingHeroName <- clientTextStore.getText(actingHero.nameTextId) + } yield s"$divinedHeroName wants $actingHeroName to execute the prisoner $prisonerHeroName in ${targetProvince.name}.\n\n$prisonerDescription" case ExilePrisonerQuest( prisonerHeroId: HeroId, provinceId: ProvinceId, _ /* unknownFieldSet */ ) => - val prisonerHero = gameState.heroes(prisonerHeroId) + val prisonerHero = gameState.heroes(prisonerHeroId) val targetProvince = gameState.provinces(provinceId) for { - prisonerHeroName <- clientTextStore - .getText(prisonerHero.nameTextId) + prisonerHeroName <- clientTextStore + .getText(prisonerHero.nameTextId) prisonerDescription <- descriptionWithoutFaction( - hero = prisonerHero, - alive = true, - clientTextStore = clientTextStore - ) - } yield { - s"$divinedHeroName wants $actingHeroName to exile the prisoner $prisonerHeroName from ${targetProvince.name}.\n\n$prisonerDescription" - } + hero = prisonerHero, + alive = true, + clientTextStore = clientTextStore + ) + } yield s"$divinedHeroName wants $actingHeroName to exile the prisoner $prisonerHeroName from ${targetProvince.name}.\n\n$prisonerDescription" case ReleasePrisonerQuest( prisonerHeroId: HeroId, provinceId: ProvinceId, _ /* unknownFieldSet */ ) => - val prisonerHero = gameState.heroes(prisonerHeroId) + val prisonerHero = gameState.heroes(prisonerHeroId) val targetProvince = gameState.provinces(provinceId) for { - prisonerHeroName <- clientTextStore - .getText(prisonerHero.nameTextId) + prisonerHeroName <- clientTextStore + .getText(prisonerHero.nameTextId) prisonerDescription <- descriptionWithoutFaction( - hero = prisonerHero, - alive = true, - clientTextStore = clientTextStore - ) - } yield { - s"$divinedHeroName wants $actingHeroName to free $prisonerHeroName from prison in ${targetProvince.name}.\n\n$prisonerDescription" - } + hero = prisonerHero, + alive = true, + clientTextStore = clientTextStore + ) + } yield s"$divinedHeroName wants $actingHeroName to free $prisonerHeroName from prison in ${targetProvince.name}.\n\n$prisonerDescription" case GiveToHeroesAcrossRealmQuest( amount: Int, _ /* unknownFieldSet */ @@ -207,14 +193,14 @@ case class DivineMessagePromptGenerator( minimumTraining: Double, _ /* unknownFieldSet */ ) => - val battType = + val battType = gameState.battalionTypes.find(_.typeId == battalionTypeId).get val targetProvince = gameState.provinces(provinceId) TextGenerationSuccess( s"$divinedHeroName wants to see a mighty ${battType.name}, with an armament of ${minimumArmament.ceil.toInt} and training of ${minimumTraining.ceil.toInt}, in ${targetProvince.name}." ) - case GrandArmyQuest(totalTroopCount, _ /* unknownFieldSet */ ) => + case GrandArmyQuest(totalTroopCount, _ /* unknownFieldSet */ ) => TextGenerationSuccess( s"$divinedHeroName wants to see a grand army of at least $totalTroopCount in ${province.name}." ) @@ -224,27 +210,25 @@ case class DivineMessagePromptGenerator( toFactionId: FactionId, _ /* unknownFieldSet */ ) => - val prisonerHero = gameState.heroes(prisonerHeroId) + val prisonerHero = gameState.heroes(prisonerHeroId) val targetProvince = gameState.provinces(provinceId) for { - prisonerHeroName <- clientTextStore - .getText(prisonerHero.nameTextId) + prisonerHeroName <- clientTextStore + .getText(prisonerHero.nameTextId) prisonerDescription <- descriptionWithoutFaction( - hero = prisonerHero, - alive = true, - clientTextStore = clientTextStore - ) - } yield { - s"$divinedHeroName wants $actingHeroName to free $prisonerHeroName from prison in ${targetProvince.name} and return them to the service of ${gameState - .factions(toFactionId) - .name}.\n\n$prisonerDescription" - } + hero = prisonerHero, + alive = true, + clientTextStore = clientTextStore + ) + } yield s"$divinedHeroName wants $actingHeroName to free $prisonerHeroName from prison in ${targetProvince.name} and return them to the service of ${gameState + .factions(toFactionId) + .name}.\n\n$prisonerDescription" case SpecificExpansionQuest(provinceId, _ /* unknownFieldSet */ ) => TextGenerationSuccess( s"$divinedHeroName wants ${faction.name} to expand their domain to include the province of ${gameState.provinces(provinceId).name}." ) - case WealthQuest(gold, food, _ /* unknownFieldSet */ ) => + case WealthQuest(gold, food, _ /* unknownFieldSet */ ) => TextGenerationSuccess( s"$divinedHeroName wants to see vast wealth of $gold gold and $food food in ${province.name}." ) @@ -256,15 +240,13 @@ case class DivineMessagePromptGenerator( for { targetHeroDescription <- descriptionWithoutFaction( - hero = targetHero, - alive = true, - clientTextStore = clientTextStore - ) - targetHeroName <- clientTextStore.getText(targetHero.nameTextId) - } yield { - s"""$divinedHeroName will not join as long as $targetHeroName is in ${faction.name}'s service. + hero = targetHero, + alive = true, + clientTextStore = clientTextStore + ) + targetHeroName <- clientTextStore.getText(targetHero.nameTextId) + } yield s"""$divinedHeroName will not join as long as $targetHeroName is in ${faction.name}'s service. |$targetHeroDescription""".stripMargin - } case TruceWithFactionQuest( targetFactionId, @@ -288,47 +270,47 @@ case class DivineMessagePromptGenerator( s"$truceCount other factions. ${subjectPronoun(divinedHero.pronounGender)} does not care *which* factions as " + s"long as there are at least $truceCount truces, but the soothsayer might have suggestions." ) - case Empty => TextGenerationSuccess("No quest was found.") + case Empty => TextGenerationSuccess("No quest was found.") } } } } override def generate: TextGenerationResult = for { - divinedHeroText <- descriptionWithoutFaction( - hero = divinedHero, - alive = true, - clientTextStore = clientTextStore - ) - divinedHeroName <- clientTextStore.getText(divinedHero.nameTextId) - actingHeroText <- descriptionWithoutFaction( - hero = actingHero, - alive = true, - clientTextStore = clientTextStore - ) - actingHeroName <- clientTextStore.getText(actingHero.nameTextId) + divinedHeroText <- descriptionWithoutFaction( + hero = divinedHero, + alive = true, + clientTextStore = clientTextStore + ) + divinedHeroName <- clientTextStore.getText(divinedHero.nameTextId) + actingHeroText <- descriptionWithoutFaction( + hero = actingHero, + alive = true, + clientTextStore = clientTextStore + ) + actingHeroName <- clientTextStore.getText(actingHero.nameTextId) questDescription <- questDescription(divinedHero) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val objP = objectPronoun(divinedHero.pronounGender) val inputText = s"""|$setup - | - |$actingHeroName wants to persuade $divinedHeroName, who is currently in the province of ${province.name}, to join ${faction.name}, but $actingHeroName is not yet ready to join. - | - |$divinedHeroText - |$actingHeroText - | - |$actingHeroName has consulted a local soothsayer or mystic in ${province.name} to determine what it would take to convince $divinedHeroName. - | - |$questDescription - | - |The soothsayer knows these requirements for $divinedHeroName to join, but $actingHeroName does not. - | - |Write something the soothsayer might say, consistent with $divinedHeroName's background, explaining what it would take to recruit $objP. They would only include the requirements listed above, and not make up any new ones. The soothsayer would always include all relevant details about those requirements, such as involved factions and the specific numbers given in their response. - | - |${GeneratorUtilities.limitations(wordCount = 50)}""".stripMargin + | + |$actingHeroName wants to persuade $divinedHeroName, who is currently in the province of ${province.name}, to join ${faction.name}, but $actingHeroName is not yet ready to join. + | + |$divinedHeroText + |$actingHeroText + | + |$actingHeroName has consulted a local soothsayer or mystic in ${province.name} to determine what it would take to convince $divinedHeroName. + | + |$questDescription + | + |The soothsayer knows these requirements for $divinedHeroName to join, but $actingHeroName does not. + | + |Write something the soothsayer might say, consistent with $divinedHeroName's background, explaining what it would take to recruit $objP. They would only include the requirements listed above, and not make up any new ones. The soothsayer would always include all relevant details about those requirements, such as involved factions and the specific numbers given in their response. + | + |${GeneratorUtilities.limitations(wordCount = 50)}""".stripMargin inputText } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ExileVassalPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ExileVassalPromptGenerator.scala index 90470191cf..ae5c197488 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ExileVassalPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ExileVassalPromptGenerator.scala @@ -15,44 +15,44 @@ case class ExileVassalPromptGenerator( ) extends LLMPromptGenerator { import HeroDescriptionGenerator.{description, descriptionWithoutFaction} - private val exiledHero = gameState.heroes(exileVassalMessage.exiledHeroId) - private val faction = FactionInfoUtilities.getFaction( + private val exiledHero = gameState.heroes(exileVassalMessage.exiledHeroId) + private val faction = FactionInfoUtilities.getFaction( exileVassalMessage.actingFactionId, gameState ) - private val factionLeader = gameState.heroes(faction.factionHeadId) - private val actingHero = gameState.heroes(exileVassalMessage.actingHeroId) - private val province = gameState.provinces(exileVassalMessage.provinceId) - private val requestingHeroes = + private val factionLeader = gameState.heroes(faction.factionHeadId) + private val actingHero = gameState.heroes(exileVassalMessage.actingHeroId) + private val province = gameState.provinces(exileVassalMessage.provinceId) + private val requestingHeroes = exileVassalMessage.requestingHeroIds.map(gameState.heroes) private val requestingHeroNameIds = requestingHeroes.map(h => clientTextStore.getText(h.nameTextId)).toVector override def generate: TextGenerationResult = for { - exiledHeroDescription <- descriptionWithoutFaction( - hero = exiledHero, - alive = true, - clientTextStore = clientTextStore - ) - exiledHeroName <- clientTextStore.getText(exiledHero.nameTextId) - actingHeroDescription <- description( - heroId = actingHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - actingHeroName <- clientTextStore.getText(actingHero.nameTextId) - factionLeaderName <- clientTextStore.getText(factionLeader.nameTextId) + exiledHeroDescription <- descriptionWithoutFaction( + hero = exiledHero, + alive = true, + clientTextStore = clientTextStore + ) + exiledHeroName <- clientTextStore.getText(exiledHero.nameTextId) + actingHeroDescription <- description( + heroId = actingHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + actingHeroName <- clientTextStore.getText(actingHero.nameTextId) + factionLeaderName <- clientTextStore.getText(factionLeader.nameTextId) requestingHeroesDescriptionText <- TextGenerationResult.mkString( - requestingHeroes.map { h => - description(h.id, gameState, clientTextStore) - }, - "\n" - ) - requestingHeroNamesConjunction <- GeneratorUtilities - .conjunctionResult(requestingHeroNameIds, "no one") - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + requestingHeroes.map { h => + description(h.id, gameState, clientTextStore) + }, + "\n" + ) + requestingHeroNamesConjunction <- GeneratorUtilities + .conjunctionResult(requestingHeroNameIds, "no one") + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { - val exiledObjP = objectPronoun(exiledHero.pronounGender) + val exiledObjP = objectPronoun(exiledHero.pronounGender) val exiledPossP = possessivePronoun(exiledHero.pronounGender) val requestingText = @@ -62,17 +62,17 @@ case class ExileVassalPromptGenerator( val inputText = s"""|$setup - | - |$exiledHeroDescription - |$actingHeroDescription - |$requestingHeroesDescriptionText - | - |$actingHeroName has decided to dismiss $exiledHeroName from $factionLeaderName's service and exile $exiledObjP from ${province.name}. - |$requestingText - | - |Write something that $exiledHeroName might say, consistent with $exiledPossP background, to $actingHeroName and to the world in response to this exile. - | - |${GeneratorUtilities.limitations(wordCount = 35)}""".stripMargin + | + |$exiledHeroDescription + |$actingHeroDescription + |$requestingHeroesDescriptionText + | + |$actingHeroName has decided to dismiss $exiledHeroName from $factionLeaderName's service and exile $exiledObjP from ${province.name}. + |$requestingText + | + |Write something that $exiledHeroName might say, consistent with $exiledPossP background, to $actingHeroName and to the world in response to this exile. + | + |${GeneratorUtilities.limitations(wordCount = 35)}""".stripMargin inputText } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilities.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilities.scala index 53ba73b1ac..52310262d9 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilities.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilities.scala @@ -29,20 +29,19 @@ object GeneratorUtilities { def conj( acc: Vector[String], words: Seq[TextGenerationResult] - ): TextGenerationResult = { + ): TextGenerationResult = words match { case items if items.isEmpty => TextGenerationSuccess(conjunction(acc).get) - case h +: t => + case h +: t => h match { case dip: TextGenerationDependencyInProgress => dip case du: TextGenerationDependencyUnknown => du case dw: TextGenerationDependencyWaiting => dw - case TextGenerationSuccess(result) => conj(acc :+ result, t) - case _ => ??? + case TextGenerationSuccess(result) => conj(acc :+ result, t) + case _ => ??? } } - } if words.isEmpty then TextGenerationSuccess(emptyAlternative) else conj(Vector.empty, words) @@ -64,7 +63,7 @@ object GeneratorUtilities { conjunctionResult( factionHeadNameIds(gameState).map(clientTextStore.getText), "unknown" - ).map { fns => s"The leaders of the factions are $fns." } + ).map(fns => s"The leaders of the factions are $fns.") val monthNames: Vector[String] = Vector( "", @@ -87,19 +86,17 @@ object GeneratorUtilities { def basicSetup( gameState: GameState, clientTextStore: ClientTextStore - ): TextGenerationResult = { - factionHeadsNamesResult(gameState, clientTextStore) - .map { factionDescriptions => - s"""This is a fantasy setting with a medieval technology level. Multiple factions are engaged in a civil war for + ): TextGenerationResult = + factionHeadsNamesResult(gameState, clientTextStore).map { factionDescriptions => + s"""This is a fantasy setting with a medieval technology level. Multiple factions are engaged in a civil war for |control of the kingdom after a mysterious stranger from afar, a powerful mage called The Eagle, invaded the realm. |King Bregos Fyar's right-hand man, Ikhaan Tarn, betrayed the King to join with The Eagle. |Several other factions arose under powerful heroes, allied with neither the King nor The Eagle. |$factionDescriptions |$academyName, where mages and other practitioners of arcane magics are trained and practice, has remained neutral, |though some of its members take part in the war.""".stripMargin - .replaceAll("\n", " ") - } - } + .replaceAll("\n", " ") + } def limitations(wordCount: Int): String = s"""Do not include any other context beyond the in-world text of the response itself. Limit your response to diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HandleCapturedHeroPleaPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HandleCapturedHeroPleaPromptGenerator.scala index ba6dd59924..8ed34d4d69 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HandleCapturedHeroPleaPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HandleCapturedHeroPleaPromptGenerator.scala @@ -19,55 +19,55 @@ case class HandleCapturedHeroPleaPromptGenerator( .map(clientTextStore.getText) private val capturedHero = gameState.heroes(plea.capturedHeroId) - private val actingFaction = + private val actingFaction = FactionInfoUtilities.getFaction(plea.actingFactionId, gameState) private val actingFactionLeader = gameState.heroes(actingFaction.factionHeadId) def generate: TextGenerationResult = for { capturedHeroDescription <- HeroDescriptionGenerator.description( - heroId = plea.capturedHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) + heroId = plea.capturedHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) actingFactionLeaderName <- clientTextStore.getText( - actingFactionLeader.nameTextId - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) - imprisonedHeroNames <- GeneratorUtilities - .conjunctionResult( - affectedHeroNameResults( - plea.alreadyImprisonedHeroIds.toVector - ), - "no one" - ) - exiledHeroNames <- GeneratorUtilities - .conjunctionResult( - affectedHeroNameResults(plea.alreadyExiledHeroIds.toVector), - "no one" - ) - executedHeroNames <- GeneratorUtilities - .conjunctionResult( - affectedHeroNameResults(plea.alreadyExecutedHeroIds.toVector), - "no one" - ) + actingFactionLeader.nameTextId + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + imprisonedHeroNames <- GeneratorUtilities + .conjunctionResult( + affectedHeroNameResults( + plea.alreadyImprisonedHeroIds.toVector + ), + "no one" + ) + exiledHeroNames <- GeneratorUtilities + .conjunctionResult( + affectedHeroNameResults(plea.alreadyExiledHeroIds.toVector), + "no one" + ) + executedHeroNames <- GeneratorUtilities + .conjunctionResult( + affectedHeroNameResults(plea.alreadyExecutedHeroIds.toVector), + "no one" + ) } yield { val province = gameState.provinces(plea.provinceId) val subjP = HeroDescriptionGenerator.subjectPronoun(capturedHero.pronounGender) - val objP = + val objP = HeroDescriptionGenerator.objectPronoun(capturedHero.pronounGender) val possP = HeroDescriptionGenerator.possessivePronoun(capturedHero.pronounGender) - val isV = HeroDescriptionGenerator.pronounIsVerb(capturedHero.pronounGender) + val isV = HeroDescriptionGenerator.pronounIsVerb(capturedHero.pronounGender) val imprisonedHeroText = s"$actingFactionLeaderName has already imprisoned $imprisonedHeroNames." - val exiledHeroText = + val exiledHeroText = s"$actingFactionLeaderName has already exiled $exiledHeroNames." - val executedHeroText = + val executedHeroText = s"$actingFactionLeaderName has already executed $executedHeroNames." val inputText = diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroBackstoryUpdatePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroBackstoryUpdatePromptGenerator.scala index 6e6cd0e8b4..781039bb82 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroBackstoryUpdatePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroBackstoryUpdatePromptGenerator.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators -import net.eagle0.eagle.client_text.{ - ClientTextStore, - TextGenerationResult, - TextGenerationSuccess -} +import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult, TextGenerationSuccess} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_ACCEPTED, DIPLOMACY_OFFER_STATUS_IMPRISONED, @@ -64,39 +60,38 @@ case class HeroBackstoryUpdatePromptGenerator( ) private def previousBackstories: Vector[TextGenerationResult] = - backstoryUpdateRequest.previousBackstoryVersions.toVector.map { - backstoryVersion => - clientTextStore.getText(backstoryVersion.textId).map { text => - GeneratorUtilities.dateString(backstoryVersion.date.get) + ": " + text - } + backstoryUpdateRequest.previousBackstoryVersions.toVector.map { backstoryVersion => + clientTextStore.getText(backstoryVersion.textId).map { text => + GeneratorUtilities.dateString(backstoryVersion.date.get) + ": " + text + } } override def generate: TextGenerationResult = for { - heroName <- clientTextStore - .getText(hero.nameTextId) + heroName <- clientTextStore + .getText(hero.nameTextId) previousBackstoryText <- clientTextStore.getText( - backstoryUpdateRequest.previousBackstoryVersions.last.textId - ) - heroDescription <- HeroDescriptionGenerator.descriptionWithoutBackstory( - hero = hero, - gameState = gameState, - alive = true, - clientTextStore = clientTextStore - ) - eventsText <- TextGenerationResult.mkString( - backstoryUpdateRequest.events.toVector - .map(ev => - textForEvent(ev, heroName).map { text => - s"${GeneratorUtilities.dateString(ev.date.get)}: $text" - } - ), - "\n" - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) - prevBack <- TextGenerationResult.mkString( - previousBackstories, - "\n----\n" - ) + backstoryUpdateRequest.previousBackstoryVersions.last.textId + ) + heroDescription <- HeroDescriptionGenerator.descriptionWithoutBackstory( + hero = hero, + gameState = gameState, + alive = true, + clientTextStore = clientTextStore + ) + eventsText <- TextGenerationResult.mkString( + backstoryUpdateRequest.events.toVector + .map(ev => + textForEvent(ev, heroName).map { text => + s"${GeneratorUtilities.dateString(ev.date.get)}: $text" + } + ), + "\n" + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + prevBack <- TextGenerationResult.mkString( + previousBackstories, + "\n----\n" + ) } yield { val newMaximumWordCount = previousBackstoryText.split("\\W+").length + maxWordCountIncrease @@ -129,29 +124,29 @@ case class HeroBackstoryUpdatePromptGenerator( outcome, _ /* unknownFieldSet */ ) => - val fromFaction = + val fromFaction = FactionInfoUtilities.getFaction(fromFactionId, gameState) - val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) + val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) val toFactionLeader = gameState.heroes(toFaction.factionHeadId) for { toLeaderDescription <- HeroDescriptionGenerator.description( - heroId = toFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) + heroId = toFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) toFactionLeaderName <- clientTextStore.getText( - toFactionLeader.nameTextId - ) + toFactionLeader.nameTextId + ) } yield { val resolution = outcome match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"${toFaction.name}'s leader $toFactionLeaderName accepted the alliance." - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => s"${toFaction.name}'s leader $toFactionLeaderName rejected the alliance." case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"${toFaction.name}'s leader $toFactionLeaderName rejected the alliance and imprisoned $heroName." - case _ => + case _ => throw new EagleInternalException( s"Unexpected outcome $outcome for alliance ambassador event" ) @@ -165,34 +160,34 @@ case class HeroBackstoryUpdatePromptGenerator( outcome, _ /* unknownFieldSet */ ) => - val fromFaction = + val fromFaction = FactionInfoUtilities.getFaction(fromFactionId, gameState) - val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) - val toFactionLeader = gameState.heroes(toFaction.factionHeadId) + val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) + val toFactionLeader = gameState.heroes(toFaction.factionHeadId) val toFactionLeaderSubjP = HeroDescriptionGenerator.subjectPronoun( toFactionLeader.pronounGender ) for { toLeaderDescription <- HeroDescriptionGenerator.description( - heroId = toFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) + heroId = toFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) toFactionLeaderName <- clientTextStore.getText( - toFactionLeader.nameTextId - ) + toFactionLeader.nameTextId + ) } yield { val resolution = outcome match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"${toFaction.name}'s leader $toFactionLeaderName had no choice but to accept the end of the alliance." - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => throw new EagleInternalException( s"Unexpected rejection for break alliance ambassador event" ) case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"${toFaction.name}'s leader $toFactionLeaderName was so furious that $toFactionLeaderSubjP imprisoned $heroName." - case _ => + case _ => throw new EagleInternalException( s"Unexpected outcome $outcome for alliance ambassador event" ) @@ -208,20 +203,18 @@ case class HeroBackstoryUpdatePromptGenerator( ) => val capturedByFaction = FactionInfoUtilities.getFaction(capturingFactionId, gameState) - val province = gameState.provinces(provinceId) - val capturingHero = gameState.heroes(capturingHeroId) + val province = gameState.provinces(provinceId) + val capturingHero = gameState.heroes(capturingHeroId) for { capturingHeroDescription <- HeroDescriptionGenerator.description( - heroId = capturingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) - } yield { - s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and " + - s"executed by $capturingHeroName. $capturingHeroDescription" - } + heroId = capturingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) + } yield s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and " + + s"executed by $capturingHeroName. $capturingHeroDescription" case CapturedHeroExiledBackstoryEvent( capturingFactionId, capturingHeroId, @@ -230,20 +223,18 @@ case class HeroBackstoryUpdatePromptGenerator( ) => val capturedByFaction = FactionInfoUtilities.getFaction(capturingFactionId, gameState) - val province = gameState.provinces(provinceId) - val capturingHero = gameState.heroes(capturingHeroId) + val province = gameState.provinces(provinceId) + val capturingHero = gameState.heroes(capturingHeroId) for { capturingHeroDescription <- HeroDescriptionGenerator.description( - heroId = capturingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) - } yield { - s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and sent into exile " + - s"by $capturingHeroName. $capturingHeroDescription" - } + heroId = capturingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) + } yield s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and sent into exile " + + s"by $capturingHeroName. $capturingHeroDescription" case CapturedHeroImprisonedBackstoryEvent( capturingFactionId, @@ -253,20 +244,18 @@ case class HeroBackstoryUpdatePromptGenerator( ) => val capturedByFaction = FactionInfoUtilities.getFaction(capturingFactionId, gameState) - val province = gameState.provinces(provinceId) - val capturingHero = gameState.heroes(capturingHeroId) + val province = gameState.provinces(provinceId) + val capturingHero = gameState.heroes(capturingHeroId) for { capturingHeroDescription <- HeroDescriptionGenerator.description( - heroId = capturingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) - } yield { - s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and imprisoned " + - s"by $capturingHeroName. $capturingHeroDescription" - } + heroId = capturingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) + } yield s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and imprisoned " + + s"by $capturingHeroName. $capturingHeroDescription" case CapturedHeroRecruitedBackstoryEvent( capturingFactionId, @@ -276,20 +265,18 @@ case class HeroBackstoryUpdatePromptGenerator( ) => val capturedByFaction = FactionInfoUtilities.getFaction(capturingFactionId, gameState) - val province = gameState.provinces(provinceId) - val capturingHero = gameState.heroes(capturingHeroId) + val province = gameState.provinces(provinceId) + val capturingHero = gameState.heroes(capturingHeroId) for { capturingHeroDescription <- HeroDescriptionGenerator.description( - heroId = capturingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) - } yield { - s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and recruited by $capturingHeroName to join " + - s"${capturedByFaction.name}. $capturingHeroDescription" - } + heroId = capturingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) + } yield s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name} and recruited by $capturingHeroName to join " + + s"${capturedByFaction.name}. $capturingHeroDescription" case CapturedHeroReturnedBackstoryEvent( capturingFactionId, @@ -297,25 +284,23 @@ case class HeroBackstoryUpdatePromptGenerator( provinceId, _ /* unknownFieldSet */ ) => - val capturedByFaction = + val capturedByFaction = FactionInfoUtilities.getFaction(capturingFactionId, gameState) val capturedFromFaction = FactionInfoUtilities.getFaction(hero.getFactionId, gameState) - val province = gameState.provinces(provinceId) - val capturingHero = gameState.heroes(capturingHeroId) + val province = gameState.provinces(provinceId) + val capturingHero = gameState.heroes(capturingHeroId) for { capturingHeroDescription <- HeroDescriptionGenerator.description( - heroId = capturingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) - } yield { - s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name}. " + - s"$capturingHeroName of ${capturedByFaction.name} magnanimously decided to return $heroName " + - s"to their previous faction, ${capturedFromFaction.name}. $capturingHeroDescription" - } + heroId = capturingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturingHeroName <- clientTextStore.getText(capturingHero.nameTextId) + } yield s"In the aftermath of the battle in ${province.name}, $heroName was captured by ${capturedByFaction.name}. " + + s"$capturingHeroName of ${capturedByFaction.name} magnanimously decided to return $heroName " + + s"to their previous faction, ${capturedFromFaction.name}. $capturingHeroDescription" case ExchangedInRansomBackstoryEvent( ransomPaidByFactionId, @@ -324,46 +309,42 @@ case class HeroBackstoryUpdatePromptGenerator( imprisonedInProvinceId, _ /* unknownFieldSet */ ) => - val ransomPaidByFaction = + val ransomPaidByFaction = FactionInfoUtilities.getFaction(ransomPaidByFactionId, gameState) - val ransomPaidToFaction = + val ransomPaidToFaction = FactionInfoUtilities.getFaction(ransomPaidToFactionId, gameState) - val ransomedHero = gameState.heroes(ransomedHeroId) + val ransomedHero = gameState.heroes(ransomedHeroId) val imprisonedInProvince = gameState.provinces(imprisonedInProvinceId) for { ransomedHeroDescription <- HeroDescriptionGenerator.description( - heroId = ransomedHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - ransomedHeroName <- clientTextStore.getText(ransomedHero.nameTextId) - } yield { - s"$heroName was offered up by $ransomPaidByFaction.name} to ${ransomPaidToFaction.name} as part of a ransom for $ransomedHeroName. $heroName is now imprisoned in ${imprisonedInProvince.name}. $ransomedHeroDescription" - } + heroId = ransomedHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + ransomedHeroName <- clientTextStore.getText(ransomedHero.nameTextId) + } yield s"$heroName was offered up by $ransomPaidByFaction.name} to ${ransomPaidToFaction.name} as part of a ransom for $ransomedHeroName. $heroName is now imprisoned in ${imprisonedInProvince.name}. $ransomedHeroDescription" case ExiledBackstoryEvent( exiledByFactionId, exiledInProvinceId, _ /* unknownFieldSet */ ) => - val exiledByFaction = + val exiledByFaction = FactionInfoUtilities.getFaction(exiledByFactionId, gameState) val exiledInProvince = gameState.provinces(exiledInProvinceId) - val provinceLeader = gameState.heroes(exiledInProvince.rulingHeroId.get) + val provinceLeader = gameState.heroes(exiledInProvince.rulingHeroId.get) for { - leaderDescription <- HeroDescriptionGenerator.description( - heroId = provinceLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) + leaderDescription <- HeroDescriptionGenerator.description( + heroId = provinceLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) provinceLeaderName <- clientTextStore.getText( - provinceLeader.nameTextId - ) - } yield { - s"$provinceLeaderName exiled $heroName from ${exiledInProvince.name}, and from the service of ${exiledByFaction.name}. $leaderDescription" - } + provinceLeader.nameTextId + ) + } yield s"$provinceLeaderName exiled $heroName from ${exiledInProvince.name}, and from the service of ${exiledByFaction.name}. $leaderDescription" case FoughtInBattleBackstoryEvent( provinceId, @@ -374,8 +355,8 @@ case class HeroBackstoryUpdatePromptGenerator( status, _ /* unknownFieldSet */ ) => - val province = gameState.provinces(provinceId) - val heroFaction = + val province = gameState.provinces(provinceId) + val heroFaction = FactionInfoUtilities.getFaction(hero.getFactionId, gameState) val enemyFactionList = GeneratorUtilities @@ -384,31 +365,29 @@ case class HeroBackstoryUpdatePromptGenerator( ) .getOrElse("unknown forces") - val foughtText = battalion - .map { batt => - s"led ${BattalionDescriptions.descriptionForBattalion(batt)}" - } + val foughtText = battalion.map { batt => + s"led ${BattalionDescriptions.descriptionForBattalion(batt)}" + } .getOrElse("fought without any supporting troops") val initial = if isAttacker then s"$heroName $foughtText in ${heroFaction.name}'s assault on $enemyFactionList in ${province.name}." - else - s"$heroName $foughtText in ${heroFaction.name}'s defense of ${province.name} against $enemyFactionList." + else s"$heroName $foughtText in ${heroFaction.name}'s defense of ${province.name} against $enemyFactionList." val result = if isVictorious then { val statusText = status match { - case UNIT_STATUS_NORMAL => s"fought valiantly as" - case UNIT_STATUS_CAPTURED => + case UNIT_STATUS_NORMAL => s"fought valiantly as" + case UNIT_STATUS_CAPTURED => s"was captured, but rescued when their compatriots in" - case UNIT_STATUS_NEVER_ENTERED => + case UNIT_STATUS_NEVER_ENTERED => s"never entered the battle, but their compatriots in" - case UNIT_STATUS_FLED => + case UNIT_STATUS_FLED => s"was outmatched and fled to friendly territory, but their compatriots in" - case UNIT_STATUS_OUTLAWED => + case UNIT_STATUS_OUTLAWED => s"was outmatched and fled and became an outlaw, but their former compatriots in" - case UNIT_STATUS_RETREATED => + case UNIT_STATUS_RETREATED => s"retreated behind the walls to avoid capture, but their compatriots in" case UNIT_STATUS_UNKNOWN => ??? case UnitStatus.Unrecognized(value) => ??? @@ -416,16 +395,16 @@ case class HeroBackstoryUpdatePromptGenerator( s"$heroName $statusText ${heroFaction.name} won the day." } else { val statusText = status match { - case UNIT_STATUS_NORMAL => s"fought valiantly as" - case UNIT_STATUS_CAPTURED => + case UNIT_STATUS_NORMAL => s"fought valiantly as" + case UNIT_STATUS_CAPTURED => s"was captured, and became a prisoner when" - case UNIT_STATUS_NEVER_ENTERED => + case UNIT_STATUS_NEVER_ENTERED => s"never entered the battle, as their compatriots in" - case UNIT_STATUS_FLED => + case UNIT_STATUS_FLED => s"was outmatched and fled to friendly territory, as their compatriots in" - case UNIT_STATUS_OUTLAWED => + case UNIT_STATUS_OUTLAWED => s"was outmatched and fled and became an outlaw, as their former compatriots in" - case UNIT_STATUS_RETREATED => + case UNIT_STATUS_RETREATED => s"retreated behind the walls to avoid capture, but was captured when their compatriots in" case UNIT_STATUS_UNKNOWN => ??? case UnitStatus.Unrecognized(value) => ??? @@ -442,7 +421,7 @@ case class HeroBackstoryUpdatePromptGenerator( departedFromProvinceId, _ /* unknownFieldSet */ ) => - val departedFromFaction = + val departedFromFaction = FactionInfoUtilities.getFaction(departedFromFactionId, gameState) val departedFromProvince = gameState.provinces(departedFromProvinceId) @@ -456,29 +435,29 @@ case class HeroBackstoryUpdatePromptGenerator( outcome, _ /* unknownFieldSet */ ) => - val fromFaction = + val fromFaction = FactionInfoUtilities.getFaction(fromFactionId, gameState) - val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) + val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) val toFactionLeader = gameState.heroes(toFaction.factionHeadId) for { toLeaderDescription <- HeroDescriptionGenerator.description( - heroId = toFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) + heroId = toFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) toFactionLeaderName <- clientTextStore.getText( - toFactionLeader.nameTextId - ) + toFactionLeader.nameTextId + ) } yield { val resolution = outcome match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"${toFaction.name}'s leader $toFactionLeaderName accepted the invitation. ${fromFaction.name} is dissolved, and all of their heroes have joined ${toFaction.name}." - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => s"${toFaction.name}'s leader $toFactionLeaderName rejected the invitation." case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"${toFaction.name}'s leader $toFactionLeaderName rejected the invitation and imprisoned $heroName." - case _ => + case _ => throw new EagleInternalException( s"Unexpected outcome $outcome for invitation ambassador event" ) @@ -493,56 +472,52 @@ case class HeroBackstoryUpdatePromptGenerator( previousFactionHeadHeroId, _ /* unknownFieldSet */ ) => - val invitedByFaction = + val invitedByFaction = FactionInfoUtilities.getFaction(invitedByFactionId, gameState) val invitedByFactionLeader = gameState.heroes(invitedByFaction.factionHeadId) - val invitedByHero = gameState.heroes(invitedByHeroId) - val previousFactionHead = gameState.heroes(previousFactionHeadHeroId) + val invitedByHero = gameState.heroes(invitedByHeroId) + val previousFactionHead = gameState.heroes(previousFactionHeadHeroId) if hero.id == previousFactionHeadHeroId then for { invitedByFactionLeaderDescription <- HeroDescriptionGenerator - .description( - heroId = invitedByFaction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - invitedByHeroName <- clientTextStore.getText( - invitedByHero.nameTextId - ) - invitedByFactionLeaderName <- clientTextStore.getText( - invitedByFactionLeader.nameTextId - ) - } yield { - s"$heroName joined ${invitedByFaction.name}, in the service of $invitedByFactionLeaderName, when they accepted an invitation carried by $invitedByHeroName to join ${invitedByFaction.name} and dissolve their previous faction. $invitedByFactionLeaderDescription" - } + .description( + heroId = invitedByFaction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + invitedByHeroName <- clientTextStore.getText( + invitedByHero.nameTextId + ) + invitedByFactionLeaderName <- clientTextStore.getText( + invitedByFactionLeader.nameTextId + ) + } yield s"$heroName joined ${invitedByFaction.name}, in the service of $invitedByFactionLeaderName, when they accepted an invitation carried by $invitedByHeroName to join ${invitedByFaction.name} and dissolve their previous faction. $invitedByFactionLeaderDescription" else for { invitedByFactionLeaderDescription <- HeroDescriptionGenerator - .description( - heroId = invitedByFaction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - previousFactionHeadDescription <- HeroDescriptionGenerator - .description( - heroId = previousFactionHeadHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - previousFactionHeadName <- clientTextStore.getText( - previousFactionHead.nameTextId - ) - invitedByHeroName <- clientTextStore.getText( - invitedByHero.nameTextId - ) - invitedByFactionLeaderName <- clientTextStore.getText( - invitedByFactionLeader.nameTextId - ) - } yield { - s"$heroName joined ${invitedByFaction.name}, in the service of $invitedByFactionLeaderName, when their previous liege lord $previousFactionHeadName accepted an invitation carried by $invitedByHeroName to join ${invitedByFaction.name} and dissolve their previous faction. $previousFactionHeadDescription $invitedByFactionLeaderDescription" - } + .description( + heroId = invitedByFaction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + previousFactionHeadDescription <- HeroDescriptionGenerator + .description( + heroId = previousFactionHeadHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + previousFactionHeadName <- clientTextStore.getText( + previousFactionHead.nameTextId + ) + invitedByHeroName <- clientTextStore.getText( + invitedByHero.nameTextId + ) + invitedByFactionLeaderName <- clientTextStore.getText( + invitedByFactionLeader.nameTextId + ) + } yield s"$heroName joined ${invitedByFaction.name}, in the service of $invitedByFactionLeaderName, when their previous liege lord $previousFactionHeadName accepted an invitation carried by $invitedByHeroName to join ${invitedByFaction.name} and dissolve their previous faction. $previousFactionHeadDescription $invitedByFactionLeaderDescription" end if case PleaseRecruitMeBackstoryEvent( @@ -553,22 +528,20 @@ case class HeroBackstoryUpdatePromptGenerator( ) => val desiredFaction = FactionInfoUtilities.getFaction(desiredFactionId, gameState) - val factionLeader = gameState.heroes(desiredFaction.factionHeadId) - val province = gameState.provinces(provinceId) + val factionLeader = gameState.heroes(desiredFaction.factionHeadId) + val province = gameState.provinces(provinceId) val action = if accepted then "accepted" else "rejected" for { leaderDescription <- HeroDescriptionGenerator.description( - heroId = factionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) + heroId = factionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) factionLeaderName <- clientTextStore.getText(factionLeader.nameTextId) - } yield { - s"$heroName asked to join ${desiredFaction.name} in ${province.name}. $factionLeaderName $action " + - s"this request. $leaderDescription" - } + } yield s"$heroName asked to join ${desiredFaction.name} in ${province.name}. $factionLeaderName $action " + + s"this request. $leaderDescription" case QuestFailedBackstoryEvent( provinceId, @@ -576,30 +549,28 @@ case class HeroBackstoryUpdatePromptGenerator( quest, _ /* unknownFieldSet */ ) => - val province = gameState.provinces(provinceId) - val faction = FactionInfoUtilities.getFaction(factionId, gameState) + val province = gameState.provinces(provinceId) + val faction = FactionInfoUtilities.getFaction(factionId, gameState) val factionHead = gameState.heroes(faction.factionHeadId) - val subjP = HeroDescriptionGenerator.subjectPronoun(hero.pronounGender) - val isV = HeroDescriptionGenerator.pronounIsVerb(hero.pronounGender) + val subjP = HeroDescriptionGenerator.subjectPronoun(hero.pronounGender) + val isV = HeroDescriptionGenerator.pronounIsVerb(hero.pronounGender) for { factionHeadDescription <- HeroDescriptionGenerator.description( - heroId = factionHead.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - questDescription <- QuestEndedGeneratorUtilities - .pastTenseQuestDescription( - unaffiliatedHero = hero, - quest = quest.get, - province = province, - faction = faction, - gameState = gameState, - clientTextStore = clientTextStore - ) - } yield { - s"$questDescription $heroName was disappointed when ${faction.name} failed in these aims. ${subjP.capitalize} $isV unlikely to join ${faction.name} any time soon. $factionHeadDescription" - } + heroId = factionHead.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + questDescription <- QuestEndedGeneratorUtilities + .pastTenseQuestDescription( + unaffiliatedHero = hero, + quest = quest.get, + province = province, + faction = faction, + gameState = gameState, + clientTextStore = clientTextStore + ) + } yield s"$questDescription $heroName was disappointed when ${faction.name} failed in these aims. ${subjP.capitalize} $isV unlikely to join ${faction.name} any time soon. $factionHeadDescription" case QuestFulfilledBackstoryEvent( provinceId, @@ -607,30 +578,28 @@ case class HeroBackstoryUpdatePromptGenerator( quest, _ /* unknownFieldSet */ ) => - val province = gameState.provinces(provinceId) - val faction = FactionInfoUtilities.getFaction(factionId, gameState) + val province = gameState.provinces(provinceId) + val faction = FactionInfoUtilities.getFaction(factionId, gameState) val factionHead = gameState.heroes(faction.factionHeadId) - val subjP = HeroDescriptionGenerator.subjectPronoun(hero.pronounGender) - val isV = HeroDescriptionGenerator.pronounIsVerb(hero.pronounGender) + val subjP = HeroDescriptionGenerator.subjectPronoun(hero.pronounGender) + val isV = HeroDescriptionGenerator.pronounIsVerb(hero.pronounGender) for { factionHeadDescription <- HeroDescriptionGenerator.description( - heroId = factionHead.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - questDescription <- QuestEndedGeneratorUtilities - .pastTenseQuestDescription( - unaffiliatedHero = hero, - quest = quest.get, - province = province, - faction = faction, - gameState = gameState, - clientTextStore = clientTextStore - ) - } yield { - s"$questDescription $heroName was pleased to witness as ${faction.name} succeed in these aims. ${subjP.capitalize} $isV still independent, but would probably join ${faction.name} if asked. $factionHeadDescription" - } + heroId = factionHead.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + questDescription <- QuestEndedGeneratorUtilities + .pastTenseQuestDescription( + unaffiliatedHero = hero, + quest = quest.get, + province = province, + faction = faction, + gameState = gameState, + clientTextStore = clientTextStore + ) + } yield s"$questDescription $heroName was pleased to witness as ${faction.name} succeed in these aims. ${subjP.capitalize} $isV still independent, but would probably join ${faction.name} if asked. $factionHeadDescription" case RansomedBackstoryEvent( ransomPaidByFactionId, @@ -640,25 +609,23 @@ case class HeroBackstoryUpdatePromptGenerator( heroIdsExchanged, _ /* unknownFieldSet */ ) => - val ransomPaidByFaction = + val ransomPaidByFaction = FactionInfoUtilities.getFaction(ransomPaidByFactionId, gameState) - val ransomPaidToFaction = + val ransomPaidToFaction = FactionInfoUtilities.getFaction(ransomPaidToFactionId, gameState) - val imprisonedInProvince = gameState.provinces(imprisonedInProvinceId) - val heroesExchanged = heroIdsExchanged.map(gameState.heroes) + val imprisonedInProvince = gameState.provinces(imprisonedInProvinceId) + val heroesExchanged = heroIdsExchanged.map(gameState.heroes) val heroesExchangedNameResults = heroesExchanged .map(_.nameTextId) .map(clientTextStore.getText) for { heroesExchangedNames <- GeneratorUtilities - .conjunctionResult( - heroesExchangedNameResults.toVector, - "no one" - ) - } yield { - s"$heroName, previously imprisoned by ${ransomPaidToFaction.name} in ${imprisonedInProvince.name} was ransomed from ${ransomPaidToFaction.name}. In exchange for their release, ${ransomPaidByFaction.name} paid $goldPaid gold and offered up as hostages $heroesExchangedNames." - } + .conjunctionResult( + heroesExchangedNameResults.toVector, + "no one" + ) + } yield s"$heroName, previously imprisoned by ${ransomPaidToFaction.name} in ${imprisonedInProvince.name} was ransomed from ${ransomPaidToFaction.name}. In exchange for their release, ${ransomPaidByFaction.name} paid $goldPaid gold and offered up as hostages $heroesExchangedNames." case RecruitedBackstoryEvent( recruitedByFactionId, @@ -666,32 +633,30 @@ case class HeroBackstoryUpdatePromptGenerator( recruitedInProvinceId, _ /* unknownFieldSet */ ) => - val recruitedByFaction = + val recruitedByFaction = FactionInfoUtilities.getFaction(recruitedByFactionId, gameState) - val recruitedByHero = gameState.heroes(recruitedByHeroId) + val recruitedByHero = gameState.heroes(recruitedByHeroId) val recruitedInProvince = gameState.provinces(recruitedInProvinceId) for { recruitedByHeroDescription <- HeroDescriptionGenerator.description( - heroId = recruitedByHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - recruitedByHeroName <- clientTextStore.getText( - recruitedByHero.nameTextId - ) - } yield { - s"$recruitedByHeroName recruited $heroName to join ${recruitedByFaction.name} in ${recruitedInProvince.name}. $recruitedByHeroDescription" - } + heroId = recruitedByHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + recruitedByHeroName <- clientTextStore.getText( + recruitedByHero.nameTextId + ) + } yield s"$recruitedByHeroName recruited $heroName to join ${recruitedByFaction.name} in ${recruitedInProvince.name}. $recruitedByHeroDescription" case ReleasedByAllianceBackstoryEvent( releasingFactionId, releasedFromProvinceId, _ /* unknownFieldSet */ ) => - val heroFaction = + val heroFaction = FactionInfoUtilities.getFaction(hero.getFactionId, gameState) - val releasingFaction = + val releasingFaction = FactionInfoUtilities.getFaction(releasingFactionId, gameState) val releasedFromProvince = gameState.provinces(releasedFromProvinceId) @@ -704,9 +669,9 @@ case class HeroBackstoryUpdatePromptGenerator( releasedFromProvinceId, _ /* unknownFieldSet */ ) => - val heroFaction = + val heroFaction = FactionInfoUtilities.getFaction(hero.getFactionId, gameState) - val releasingFaction = + val releasingFaction = FactionInfoUtilities.getFaction(releasingFactionId, gameState) val releasedFromProvince = gameState.provinces(releasedFromProvinceId) @@ -722,10 +687,9 @@ case class HeroBackstoryUpdatePromptGenerator( succeeded, _ /* unknownFieldSet */ ) => - val foughtText = battalion - .map { batt => - s"led ${BattalionDescriptions.descriptionForBattalion(batt)}" - } + val foughtText = battalion.map { batt => + s"led ${BattalionDescriptions.descriptionForBattalion(batt)}" + } .getOrElse("went alone") val initial = @@ -744,10 +708,10 @@ case class HeroBackstoryUpdatePromptGenerator( sworeInProvinceId, _ /* unknownFieldSet */ ) => - val sworeWithFaction = + val sworeWithFaction = FactionInfoUtilities.getFaction(sworeWithFactionId, gameState) - val sworeInProvince = gameState.provinces(sworeInProvinceId) - val factionHead = gameState.heroes(sworeWithFaction.factionHeadId) + val sworeInProvince = gameState.provinces(sworeInProvinceId) + val factionHead = gameState.heroes(sworeWithFaction.factionHeadId) val otherLeadersResults = gameState .factions(sworeWithFactionId) .leaders @@ -758,21 +722,19 @@ case class HeroBackstoryUpdatePromptGenerator( for { leaderDescription <- HeroDescriptionGenerator.description( - heroId = factionHead.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - factionHeadName <- clientTextStore.getText(factionHead.nameTextId) - otherLeaders <- GeneratorUtilities.conjunctionResult( - otherLeadersResults.toVector, - "no other leaders" - ) - } yield { - s"""$heroName swore brotherhood with ${sworeWithFaction.name}'s faction head $factionHeadName in + heroId = factionHead.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + factionHeadName <- clientTextStore.getText(factionHead.nameTextId) + otherLeaders <- GeneratorUtilities.conjunctionResult( + otherLeadersResults.toVector, + "no other leaders" + ) + } yield s"""$heroName swore brotherhood with ${sworeWithFaction.name}'s faction head $factionHeadName in |${sworeInProvince.name}. $heroName is now one of the leaders of ${sworeWithFaction.name}, along |with $otherLeaders. $leaderDescription""".stripMargin - .replace("\n", " ") - } + .replace("\n", " ") case TruceAmbassadorBackstoryEvent( fromFactionId, @@ -780,30 +742,30 @@ case class HeroBackstoryUpdatePromptGenerator( outcome, _ /* unknownFieldSet */ ) => - val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) + val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) val toFactionLeader = gameState.heroes(toFaction.factionHeadId) - val fromFaction = + val fromFaction = FactionInfoUtilities.getFaction(fromFactionId, gameState) for { - leaderDescription <- HeroDescriptionGenerator.description( - heroId = toFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) + leaderDescription <- HeroDescriptionGenerator.description( + heroId = toFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) toFactionLeaderName <- clientTextStore.getText( - toFactionLeader.nameTextId - ) + toFactionLeader.nameTextId + ) } yield { val resolution = outcome match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"${toFaction.name}'s leader $toFactionLeaderName accepted the truce." - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => s"${toFaction.name}'s leader $toFactionLeaderName rejected the truce." case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"${toFaction.name}'s leader $toFactionLeaderName rejected the truce and imprisoned $heroName." - case _ => + case _ => throw new EagleInternalException( s"Unexpected outcome $outcome for truce ambassador event" ) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDeparturePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDeparturePromptGenerator.scala index 047d083b32..cd7018aec5 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDeparturePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDeparturePromptGenerator.scala @@ -9,30 +9,30 @@ case class HeroDeparturePromptGenerator( gameState: GameState, clientTextStore: ClientTextStore ) extends LLMPromptGenerator { - private val departingHero = HeroInfoUtilities.getHero( + private val departingHero = HeroInfoUtilities.getHero( heroDepartureMessage.departingHeroId, gameState ) - private val fromFaction = FactionInfoUtilities.getFaction( + private val fromFaction = FactionInfoUtilities.getFaction( heroDepartureMessage.fromFactionId, gameState ) - private val chFactionLeader = + private val chFactionLeader = HeroInfoUtilities.getHero(fromFaction.factionHeadId, gameState) override def generate: TextGenerationResult = for { - factionLeaderText <- HeroDescriptionGenerator.description( - heroId = heroDepartureMessage.fromFactionId, - gameState = gameState, - clientTextStore = clientTextStore - ) - departingHeroText <- HeroDescriptionGenerator.description( - heroId = heroDepartureMessage.departingHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - departingHeroName <- clientTextStore.getText(departingHero.nameTextId) + factionLeaderText <- HeroDescriptionGenerator.description( + heroId = heroDepartureMessage.fromFactionId, + gameState = gameState, + clientTextStore = clientTextStore + ) + departingHeroText <- HeroDescriptionGenerator.description( + heroId = heroDepartureMessage.departingHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + departingHeroName <- clientTextStore.getText(departingHero.nameTextId) chFactionLeaderName <- clientTextStore.getText(chFactionLeader.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val departingHero = HeroInfoUtilities.getHero(heroDepartureMessage.departingHeroId, gameState) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDescriptionGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDescriptionGenerator.scala index 4018183321..18716d3938 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDescriptionGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroDescriptionGenerator.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators -import net.eagle0.eagle.client_text.{ - ClientTextStore, - TextGenerationResult, - TextGenerationSuccess -} +import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult, TextGenerationSuccess} import net.eagle0.eagle.common.gender.Gender import net.eagle0.eagle.common.profession.Profession import net.eagle0.eagle.internal.game_state.GameState @@ -57,7 +53,7 @@ object HeroDescriptionGenerator { alive: Boolean, clientTextStore: ClientTextStore ): Option[TextGenerationResult] = { - val isV = if alive then "is" else "was" + val isV = if alive then "is" else "was" val hasV = if alive then "has" else "had" hero.profession match { @@ -67,21 +63,19 @@ object HeroDescriptionGenerator { Some( for { heroName <- clientTextStore.getText(hero.nameTextId) - } yield { - hero.profession match { - case Profession.MAGE => s"$heroName $isV a powerful mage." - case Profession.NECROMANCER => - s"$heroName $isV a terrifying necromancer." - case Profession.ENGINEER => - s"$heroName $isV an engineer capable of making siege weapons." - case Profession.PALADIN => - s"$heroName $isV a noble paladin and healer." - case Profession.RANGER => s"$heroName $isV a cunning ranger." - case Profession.CHAMPION => s"$heroName $isV a mighty champion." - case Profession.NO_PROFESSION => - s"$heroName $hasV no dedicated profession." - case _ => ??? - } + } yield hero.profession match { + case Profession.MAGE => s"$heroName $isV a powerful mage." + case Profession.NECROMANCER => + s"$heroName $isV a terrifying necromancer." + case Profession.ENGINEER => + s"$heroName $isV an engineer capable of making siege weapons." + case Profession.PALADIN => + s"$heroName $isV a noble paladin and healer." + case Profession.RANGER => s"$heroName $isV a cunning ranger." + case Profession.CHAMPION => s"$heroName $isV a mighty champion." + case Profession.NO_PROFESSION => + s"$heroName $hasV no dedicated profession." + case _ => ??? } ) } @@ -94,7 +88,7 @@ object HeroDescriptionGenerator { clientTextStore: ClientTextStore ): TextGenerationResult = { val SubjP = subjectPronoun(hero.pronounGender).capitalize - val isV = + val isV = if alive then pronounIsVerb(hero.pronounGender) else pronounWasVerb(hero.pronounGender) @@ -106,13 +100,12 @@ object HeroDescriptionGenerator { for { heroName <- clientTextStore.getText(hero.nameTextId) profText <- professionText(hero, alive, clientTextStore) - .map(_.map(_ + " ")) - .getOrElse(TextGenerationSuccess("")) + .map(_.map(_ + " ")) + .getOrElse(TextGenerationSuccess("")) } yield { - val factionText = hero.factionId - .map { fid => - s"$heroName $isV in the service of the ${FactionInfoUtilities.getFaction(fid, gameState).name} faction." - } + val factionText = hero.factionId.map { fid => + s"$heroName $isV in the service of the ${FactionInfoUtilities.getFaction(fid, gameState).name} faction." + } .getOrElse(s"$heroName $isV a free agent, answerable to no one.") s"$profText$wordsText $factionText" @@ -125,18 +118,16 @@ object HeroDescriptionGenerator { alive: Boolean ): TextGenerationResult = for { backstory <- clientTextStore.getText(hero.backstoryVersions.last.textId) - profText <- professionText(hero, alive, clientTextStore) - .map(_.map(_ + " ")) - .getOrElse(TextGenerationSuccess("")) - } yield { - s"$profText$backstory" - } + profText <- professionText(hero, alive, clientTextStore) + .map(_.map(_ + " ")) + .getOrElse(TextGenerationSuccess("")) + } yield s"$profText$backstory" def description( heroId: HeroId, gameState: GameState, clientTextStore: ClientTextStore - ): TextGenerationResult = { + ): TextGenerationResult = gameState.heroes .get(heroId) .map(h => @@ -155,7 +146,6 @@ object HeroDescriptionGenerator { alive = false ) ) - } private def description( hero: Hero, @@ -166,48 +156,44 @@ object HeroDescriptionGenerator { val maybeFaction = hero.factionId.map(fid => FactionInfoUtilities.getFaction(fid, gameState)) - val possP = possessivePronoun(hero.pronounGender) - val isV = if alive then "is" else "was" + val possP = possessivePronoun(hero.pronounGender) + val isV = if alive then "is" else "was" val servesV = if alive then "serves" else "served" val heroNameResult = clientTextStore.getText(hero.nameTextId) - val factionDescriptionResult = maybeFaction - .map { faction => - val factionHead = - HeroInfoUtilities.getHero(faction.factionHeadId, gameState) + val factionDescriptionResult = maybeFaction.map { faction => + val factionHead = + HeroInfoUtilities.getHero(faction.factionHeadId, gameState) - for { - heroName <- heroNameResult - factionHeadName <- clientTextStore.getText(factionHead.nameTextId) - } yield { - if faction.factionHeadId == hero.id then { - s"$heroName $isV ruler of $possP own faction, ${faction.name}, and ${ - if alive then "answers" - else "answered" - } to no one." - } else if faction.leaders.contains(hero.id) then { - s"$heroName $isV a sworn brother to $factionHeadName and recognized as one of the leaders of ${possessivePronoun(factionHead.pronounGender)} faction, ${faction.name}." - } else { - s"$heroName $servesV as a vassal under $factionHeadName in ${faction.name}." - } + for { + heroName <- heroNameResult + factionHeadName <- clientTextStore.getText(factionHead.nameTextId) + } yield + if faction.factionHeadId == hero.id then { + s"$heroName $isV ruler of $possP own faction, ${faction.name}, and ${ + if alive then "answers" + else "answered" + } to no one." + } else if faction.leaders.contains(hero.id) then { + s"$heroName $isV a sworn brother to $factionHeadName and recognized as one of the leaders of ${possessivePronoun(factionHead.pronounGender)} faction, ${faction.name}." + } else { + s"$heroName $servesV as a vassal under $factionHeadName in ${faction.name}." } - } + } .getOrElse(heroNameResult.map { heroName => - s"$heroName $servesV no one and ${ - if alive then "rules" else "ruled" - } over no one." + s"$heroName $servesV no one and ${if alive then "rules" else "ruled"} over no one." }) for { factionDescription <- factionDescriptionResult withoutFaction <- descriptionWithoutFaction( - hero = hero, - clientTextStore = clientTextStore, - alive = alive - ) - heroName <- heroNameResult + hero = hero, + clientTextStore = clientTextStore, + alive = alive + ) + heroName <- heroNameResult } yield { val deadString = if alive then "" else s" $heroName is dead." diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroInitialBackstoryPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroInitialBackstoryPromptGenerator.scala index fa0dc2856a..c199cd9f25 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroInitialBackstoryPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/HeroInitialBackstoryPromptGenerator.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators -import net.eagle0.eagle.client_text.{ - ClientTextStore, - TextGenerationResult, - TextGenerationSuccess -} +import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult, TextGenerationSuccess} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.generated_text_request.HeroInitialBackstoryRequest @@ -13,33 +9,32 @@ case class HeroInitialBackstoryPromptGenerator( gameState: GameState, clientTextStore: ClientTextStore ) extends LLMPromptGenerator { - private val hero = gameState.heroes(initialBackstoryRequest.heroId) + private val hero = gameState.heroes(initialBackstoryRequest.heroId) private val factionHead = initialBackstoryRequest.factionId .map(gameState.factions) .map(_.factionHeadId) .map(gameState.heroes) override def generate: TextGenerationResult = for { - heroName <- clientTextStore - .getText(hero.nameTextId) + heroName <- clientTextStore + .getText(hero.nameTextId) factionHeadText <- factionHead - .map(fh => - HeroDescriptionGenerator.description( - heroId = fh.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - ) - .getOrElse(TextGenerationSuccess("")) + .map(fh => + HeroDescriptionGenerator.description( + heroId = fh.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + ) + .getOrElse(TextGenerationSuccess("")) heroDescription <- HeroDescriptionGenerator.descriptionWithoutBackstory( - hero = hero, - gameState = gameState, - alive = true, - clientTextStore = clientTextStore - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) - } yield { - s"""$setup + hero = hero, + gameState = gameState, + alive = true, + clientTextStore = clientTextStore + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + } yield s"""$setup | |$factionHeadText |$heroDescription @@ -47,5 +42,4 @@ case class HeroInitialBackstoryPromptGenerator( |Make up a backstory consistent with this setting for $heroName. | |${GeneratorUtilities.limitations(wordCount = 60)}""".stripMargin - } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationMessagePromptGenerator.scala index 63e7383913..d3177dc209 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationMessagePromptGenerator.scala @@ -12,14 +12,14 @@ case class InvitationMessagePromptGenerator( override def generate: TextGenerationResult = { import HeroDescriptionGenerator.* - val offeringFaction = + val offeringFaction = FactionInfoUtilities.getFaction( invitationMessage.offeringFactionId, gameState ) val offeringFactionLeader = gameState.heroes(offeringFaction.factionHeadId) - val targetFaction = FactionInfoUtilities.getFaction( + val targetFaction = FactionInfoUtilities.getFaction( invitationMessage.targetFactionId, gameState ) @@ -28,8 +28,8 @@ case class InvitationMessagePromptGenerator( val messengerHero = gameState.heroes(invitationMessage.messengerHeroId) val messengerObjP = objectPronoun(messengerHero.pronounGender) - val targetSubjP = subjectPronoun(targetFactionLeader.pronounGender) - val targetPossP = possessivePronoun(targetFactionLeader.pronounGender) + val targetSubjP = subjectPronoun(targetFactionLeader.pronounGender) + val targetPossP = possessivePronoun(targetFactionLeader.pronounGender) val factionLeaderText = if offeringFactionLeader.id == messengerHero.id then "" @@ -41,39 +41,37 @@ case class InvitationMessagePromptGenerator( ) for { - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) - messengerHeroDescription <- description( - heroId = messengerHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + messengerHeroDescription <- description( + heroId = messengerHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) targetFactionLeaderDescription <- description( - heroId = targetFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - offeringFactionLeaderName <- clientTextStore.getText( - offeringFactionLeader.nameTextId - ) - } yield { - s""" - |$setup - | - |$messengerHeroName brings an invitation from $offeringFactionLeaderName to $targetFactionLeaderName. - |$messengerHeroDescription - |$factionLeaderText - |$targetFactionLeaderDescription - | - |If $targetFactionLeaderName accepts, $targetPossP faction will be dissolved. ${targetSubjP.capitalize} and all $targetPossP followers will join ${offeringFaction.name}. - | - |Write a message that $messengerHeroName might deliver to $targetFactionLeaderName. - |If $targetFactionLeaderName is offended, $targetSubjP may imprison $messengerObjP. - | - |${GeneratorUtilities.limitations}""".stripMargin - } + heroId = targetFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + offeringFactionLeaderName <- clientTextStore.getText( + offeringFactionLeader.nameTextId + ) + } yield s""" + |$setup + | + |$messengerHeroName brings an invitation from $offeringFactionLeaderName to $targetFactionLeaderName. + |$messengerHeroDescription + |$factionLeaderText + |$targetFactionLeaderDescription + | + |If $targetFactionLeaderName accepts, $targetPossP faction will be dissolved. ${targetSubjP.capitalize} and all $targetPossP followers will join ${offeringFaction.name}. + | + |Write a message that $messengerHeroName might deliver to $targetFactionLeaderName. + |If $targetFactionLeaderName is offended, $targetSubjP may imprison $messengerObjP. + | + |${GeneratorUtilities.limitations}""".stripMargin } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationResolutionMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationResolutionMessagePromptGenerator.scala index 2214d48046..207a5077b4 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationResolutionMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/InvitationResolutionMessagePromptGenerator.scala @@ -23,7 +23,7 @@ case class InvitationResolutionMessagePromptGenerator( gameState: GameState, clientTextStore: ClientTextStore ) extends LLMPromptGenerator { - private val offeringFaction = + private val offeringFaction = FactionInfoUtilities.getFaction( invitationResolutionMessage.offeringFactionId, gameState @@ -31,7 +31,7 @@ case class InvitationResolutionMessagePromptGenerator( private val offeringFactionLeader = gameState.heroes(offeringFaction.factionHeadId) - private val targetFaction = + private val targetFaction = FactionInfoUtilities.getFaction( invitationResolutionMessage.targetFactionId, gameState @@ -43,29 +43,29 @@ case class InvitationResolutionMessagePromptGenerator( gameState.heroes(invitationResolutionMessage.messengerHeroId) override def generate: TextGenerationResult = for { - messengerHeroDescription <- description( - heroId = messengerHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) - targetFactionLeaderDescription <- description( - heroId = targetFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) + messengerHeroDescription <- description( + heroId = messengerHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + targetFactionLeaderDescription <- description( + heroId = targetFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) offeringFactionLeaderDescription <- description( - heroId = offeringFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - offeringFactionLeaderName <- clientTextStore.getText( - offeringFactionLeader.nameTextId - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = offeringFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + offeringFactionLeaderName <- clientTextStore.getText( + offeringFactionLeader.nameTextId + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val factionLeaderText = @@ -76,15 +76,15 @@ case class InvitationResolutionMessagePromptGenerator( val targetPossP = possessivePronoun(targetFactionLeader.pronounGender) val resolutionMessage = invitationResolutionMessage.resolutionStatus match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"""$targetFactionLeaderName decided to accept the invitation. ${targetPossP.capitalize} faction will be dissolved, and $targetSubjP and all of $targetPossP followers will now join ${offeringFaction.name}. | |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this new agreement.""".stripMargin - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => s"""$targetFactionLeaderName rejected the invitation. ${targetPossP.capitalize} faction will continue as it is. | |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this rejection.""".stripMargin - case DIPLOMACY_OFFER_STATUS_IMPRISONED => + case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"""$targetFactionLeaderName not only rejected the invitation, but imprisoned the ambassador $messengerHeroName! | |Write a message that $messengerHeroName send to the world in reporting their imprisonment.""".stripMargin diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/PleaseRecruitMePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/PleaseRecruitMePromptGenerator.scala index bb3e904927..fd6b0d8c1d 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/PleaseRecruitMePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/PleaseRecruitMePromptGenerator.scala @@ -11,45 +11,45 @@ case class PleaseRecruitMePromptGenerator( ) extends LLMPromptGenerator { import HeroDescriptionGenerator.* - private val unaffiliatedHero = gameState.heroes(pleaseRecruitMeMessage.heroId) - private val targetFaction = + private val unaffiliatedHero = gameState.heroes(pleaseRecruitMeMessage.heroId) + private val targetFaction = FactionInfoUtilities.getFaction( pleaseRecruitMeMessage.targetFactionId, gameState ) private val targetFactionLeader = gameState.heroes(targetFaction.factionHeadId) - private val province = gameState.provinces(pleaseRecruitMeMessage.provinceId) + private val province = gameState.provinces(pleaseRecruitMeMessage.provinceId) override def generate: TextGenerationResult = for { - unaffiliatedHeroDescription <- descriptionWithoutFaction( - hero = unaffiliatedHero, - clientTextStore = clientTextStore, - alive = true - ) - unaffiliatedHeroName <- clientTextStore.getText(unaffiliatedHero.nameTextId) + unaffiliatedHeroDescription <- descriptionWithoutFaction( + hero = unaffiliatedHero, + clientTextStore = clientTextStore, + alive = true + ) + unaffiliatedHeroName <- clientTextStore.getText(unaffiliatedHero.nameTextId) targetFactionLeaderDescription <- description( - heroId = targetFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = targetFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { - val possP = possessivePronoun(unaffiliatedHero.pronounGender) + val possP = possessivePronoun(unaffiliatedHero.pronounGender) val inputText: String = s"""|$setup - | - |$unaffiliatedHeroName, who is currently in ${targetFaction.name}'s province of ${province.name}, actively desires to join ${targetFaction.name}. - | - |$unaffiliatedHeroDescription - |$targetFactionLeaderDescription - | - |Write something the $unaffiliatedHeroName might say, consistent with $possP background, to $targetFactionLeaderName when begging to be allowed to join. - | - |${GeneratorUtilities.limitations(wordCount = 50)}""".stripMargin + | + |$unaffiliatedHeroName, who is currently in ${targetFaction.name}'s province of ${province.name}, actively desires to join ${targetFaction.name}. + | + |$unaffiliatedHeroDescription + |$targetFactionLeaderDescription + | + |Write something the $unaffiliatedHeroName might say, consistent with $possP background, to $targetFactionLeaderName when begging to be allowed to join. + | + |${GeneratorUtilities.limitations(wordCount = 50)}""".stripMargin inputText } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestEndedGeneratorUtilities.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestEndedGeneratorUtilities.scala index 0cb2469fdd..4acdb9783a 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestEndedGeneratorUtilities.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestEndedGeneratorUtilities.scala @@ -52,9 +52,7 @@ object QuestEndedGeneratorUtilities { case AllianceQuest(_ /* unknownFieldSet */ ) => for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted ${faction.name} to secure an alliance." - } + } yield s"$unaffiliatedHeroName wanted ${faction.name} to secure an alliance." case AlmsToProvinceQuest( provinceId: ProvinceId, amount: Int, @@ -63,93 +61,81 @@ object QuestEndedGeneratorUtilities { val targetProvince = gameState.provinces(provinceId) for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount food to the people of ${targetProvince.name}." - } + } yield s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount food to the people of ${targetProvince.name}." case AlmsAcrossRealmQuest(amount: Int, _ /* unknownFieldSet */ ) => for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount food to the people across their realm." - } + } yield s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount food to the people across their realm." case DefeatFactionQuest(targetFactionId, _ /* unknownFieldSet */ ) => for { targetFactionLeaderDescription <- description( - heroId = FactionInfoUtilities - .getFaction(targetFactionId, gameState) - .factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"""$unaffiliatedHeroName wanted ${faction.name} to defeat ${FactionInfoUtilities - .getFaction(targetFactionId, gameState) - .name} in battle. + heroId = FactionInfoUtilities + .getFaction(targetFactionId, gameState) + .factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + unaffiliatedHeroName <- unaffiliatedHeroNameResult + } yield s"""$unaffiliatedHeroName wanted ${faction.name} to defeat ${FactionInfoUtilities + .getFaction(targetFactionId, gameState) + .name} in battle. |$targetFactionLeaderDescription""".stripMargin - } case ExecutePrisonerQuest( prisonerHeroId: HeroId, provinceId: ProvinceId, _ /* unknownFieldSet */ ) => - val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) + val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) val targetProvince = gameState.provinces(provinceId) for { prisonerHeroDescription <- description( - heroId = prisonerHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - unaffiliatedHeroName <- unaffiliatedHeroNameResult - prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) - } yield { - s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName executed in ${targetProvince.name}. + heroId = prisonerHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + unaffiliatedHeroName <- unaffiliatedHeroNameResult + prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) + } yield s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName executed in ${targetProvince.name}. |$prisonerHeroDescription""".stripMargin - } case ExilePrisonerQuest( prisonerHeroId: HeroId, provinceId: ProvinceId, _ /* unknownFieldSet */ ) => - val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) + val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) val targetProvince = gameState.provinces(provinceId) for { prisonerHeroDescription <- description( - heroId = prisonerHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - unaffiliatedHeroName <- unaffiliatedHeroNameResult - prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) - } yield { - s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName exiled from ${targetProvince.name} and made into an outlaw. + heroId = prisonerHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + unaffiliatedHeroName <- unaffiliatedHeroNameResult + prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) + } yield s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName exiled from ${targetProvince.name} and made into an outlaw. |$prisonerHeroDescription""".stripMargin - } case ReleasePrisonerQuest( prisonerHeroId: HeroId, provinceId: ProvinceId, _ /* unknownFieldSet */ ) => - val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) + val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) val targetProvince = gameState.provinces(provinceId) for { prisonerHeroDescription <- description( - heroId = prisonerHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - unaffiliatedHeroName <- unaffiliatedHeroNameResult - prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) - } yield { - s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName freed from prison in ${targetProvince.name}. + heroId = prisonerHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + unaffiliatedHeroName <- unaffiliatedHeroNameResult + prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) + } yield s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName freed from prison in ${targetProvince.name}. |$prisonerHeroDescription""".stripMargin - } case GiveToHeroesInProvinceQuest( provinceId: ProvinceId, @@ -160,9 +146,7 @@ object QuestEndedGeneratorUtilities { for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount gold to the heroes of ${targetProvince.name}." - } + } yield s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount gold to the heroes of ${targetProvince.name}." case GiveToHeroesAcrossRealmQuest( amount: Int, @@ -170,9 +154,7 @@ object QuestEndedGeneratorUtilities { ) => for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount gold to heroes across their realm." - } + } yield s"$unaffiliatedHeroName wanted to see ${faction.name} give away $amount gold to heroes across their realm." case ImproveAgricultureQuest( provinceId, @@ -182,9 +164,7 @@ object QuestEndedGeneratorUtilities { val targetProvince = gameState.provinces(provinceId) for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see the agriculture of ${targetProvince.name} raised to ${desiredValue.ceil.toInt}." - } + } yield s"$unaffiliatedHeroName wanted to see the agriculture of ${targetProvince.name} raised to ${desiredValue.ceil.toInt}." case ImproveEconomyQuest( provinceId, @@ -195,9 +175,7 @@ object QuestEndedGeneratorUtilities { for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see the economy of ${targetProvince.name} raised to ${desiredValue.ceil.toInt}." - } + } yield s"$unaffiliatedHeroName wanted to see the economy of ${targetProvince.name} raised to ${desiredValue.ceil.toInt}." case ImproveInfrastructureQuest( provinceId, @@ -207,9 +185,7 @@ object QuestEndedGeneratorUtilities { val targetProvince = gameState.provinces(provinceId) for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see the infrastructure in ${targetProvince.name} raised to ${desiredValue.ceil.toInt}." - } + } yield s"$unaffiliatedHeroName wanted to see the infrastructure in ${targetProvince.name} raised to ${desiredValue.ceil.toInt}." case UpgradeBattalionQuest( provinceId: FactionId, @@ -218,21 +194,17 @@ object QuestEndedGeneratorUtilities { minimumTraining: Double, _ /* unknownFieldSet */ ) => - val battType = + val battType = gameState.battalionTypes.find(_.typeId == battalionTypeId).get val targetProvince = gameState.provinces(provinceId) for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see a mighty ${battType.name}, with an armament of ${minimumArmament.ceil.toInt} and training of ${minimumTraining.ceil.toInt}, in ${targetProvince.name}." - } + } yield s"$unaffiliatedHeroName wanted to see a mighty ${battType.name}, with an armament of ${minimumArmament.ceil.toInt} and training of ${minimumTraining.ceil.toInt}, in ${targetProvince.name}." case GrandArmyQuest(totalTroopCount, _ /* unknownFieldSet */ ) => for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see a grand army of at least $totalTroopCount troops in ${province.name}." - } + } yield s"$unaffiliatedHeroName wanted to see a grand army of at least $totalTroopCount troops in ${province.name}." case ReturnPrisonerQuest( prisonerHeroId, @@ -240,58 +212,50 @@ object QuestEndedGeneratorUtilities { toFactionId, _ /* unknownFieldSet */ ) => - val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) + val prisonerHero = HeroInfoUtilities.getHero(prisonerHeroId, gameState) val targetProvince = gameState.provinces(provinceId) - val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) + val toFaction = FactionInfoUtilities.getFaction(toFactionId, gameState) for { prisonerHeroDescription <- description( - heroId = prisonerHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - factionDescription <- description( - heroId = toFaction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - unaffiliatedHeroName <- unaffiliatedHeroNameResult - prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) - } yield { - s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName released from prison in ${targetProvince.name} and returned to the service of ${toFaction.name}. + heroId = prisonerHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + factionDescription <- description( + heroId = toFaction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + unaffiliatedHeroName <- unaffiliatedHeroNameResult + prisonerHeroName <- clientTextStore.getText(prisonerHero.nameTextId) + } yield s"""$unaffiliatedHeroName wanted to see the prisoner $prisonerHeroName released from prison in ${targetProvince.name} and returned to the service of ${toFaction.name}. |$prisonerHeroDescription |$factionDescription""".stripMargin - } case SpecificExpansionQuest(provinceId, _ /* unknownFieldSet */ ) => for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted ${faction.name} to expand their domain to include the province of ${gameState.provinces(provinceId).name}." - } + } yield s"$unaffiliatedHeroName wanted ${faction.name} to expand their domain to include the province of ${gameState.provinces(provinceId).name}." case WealthQuest(gold, food, _ /* unknownFieldSet */ ) => for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see vast wealth of $gold gold and $food food in ${province.name}." - } + } yield s"$unaffiliatedHeroName wanted to see vast wealth of $gold gold and $food food in ${province.name}." case DismissSpecificVassalQuest(targetHeroId, _ /* unknownFieldSet */ ) => val targetHero = HeroInfoUtilities.getHero(targetHeroId, gameState) for { targetHeroDescription <- descriptionWithoutFaction( - hero = targetHero, - clientTextStore = clientTextStore, - alive = true - ) - unaffiliatedHeroName <- unaffiliatedHeroNameResult - targetHeroName <- clientTextStore.getText(targetHero.nameTextId) - } yield { - s"""$unaffiliatedHeroName wanted to see $targetHeroName dismissed from ${faction.name}'s service. + hero = targetHero, + clientTextStore = clientTextStore, + alive = true + ) + unaffiliatedHeroName <- unaffiliatedHeroNameResult + targetHeroName <- clientTextStore.getText(targetHero.nameTextId) + } yield s"""$unaffiliatedHeroName wanted to see $targetHeroName dismissed from ${faction.name}'s service. |$targetHeroDescription |""".stripMargin - } case TruceWithFactionQuest(targetFactionId, _ /* unknownFieldSet */ ) => val targetFaction = @@ -299,23 +263,19 @@ object QuestEndedGeneratorUtilities { for { targetHeroDescription <- description( - heroId = targetFaction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"""$unaffiliatedHeroName wanted ${faction.name} to sign a truce with ${targetFaction.name}. + heroId = targetFaction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + unaffiliatedHeroName <- unaffiliatedHeroNameResult + } yield s"""$unaffiliatedHeroName wanted ${faction.name} to sign a truce with ${targetFaction.name}. |$targetHeroDescription |""".stripMargin - } case TruceCountQuest(truceCount, _ /* unknownFieldSet */ ) => for { unaffiliatedHeroName <- unaffiliatedHeroNameResult - } yield { - s"$unaffiliatedHeroName wanted to see the progress of peace, by seeing ${faction.name} sign truces with at least $truceCount other factions." - } + } yield s"$unaffiliatedHeroName wanted to see the progress of peace, by seeing ${faction.name} sign truces with at least $truceCount other factions." case Empty => throw new EagleInternalException("No quest specified!") } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFailedPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFailedPromptGenerator.scala index 87571cb4e2..029cee10f2 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFailedPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFailedPromptGenerator.scala @@ -12,12 +12,12 @@ case class QuestFailedPromptGenerator( ) extends LLMPromptGenerator { import HeroDescriptionGenerator.{description, descriptionWithoutFaction} - private val unaffiliatedHero = gameState.heroes(questFailedMessage.heroId) - private val faction = + private val unaffiliatedHero = gameState.heroes(questFailedMessage.heroId) + private val faction = FactionInfoUtilities.getFaction(questFailedMessage.factionId, gameState) - private val factionLeader = gameState.heroes(faction.factionHeadId) - private val province = gameState.provinces(questFailedMessage.provinceId) - private val quest = questFailedMessage.getQuest + private val factionLeader = gameState.heroes(faction.factionHeadId) + private val province = gameState.provinces(questFailedMessage.provinceId) + private val quest = questFailedMessage.getQuest private val questDescriptionResult = QuestEndedGeneratorUtilities.pastTenseQuestDescription( unaffiliatedHero = unaffiliatedHero, @@ -29,19 +29,19 @@ case class QuestFailedPromptGenerator( ) override def generate: TextGenerationResult = for { - questDescription <- questDescriptionResult + questDescription <- questDescriptionResult unaffiliatedHeroDescription <- descriptionWithoutFaction( - hero = unaffiliatedHero, - alive = true, - clientTextStore = clientTextStore - ) - unaffiliatedHeroName <- clientTextStore.getText(unaffiliatedHero.nameTextId) - factionLeaderDescription <- description( - heroId = factionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + hero = unaffiliatedHero, + alive = true, + clientTextStore = clientTextStore + ) + unaffiliatedHeroName <- clientTextStore.getText(unaffiliatedHero.nameTextId) + factionLeaderDescription <- description( + heroId = factionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val possP = possessivePronoun(unaffiliatedHero.pronounGender) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFulfilledPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFulfilledPromptGenerator.scala index ffbc265bc1..8f4a66bd8f 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFulfilledPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/QuestFulfilledPromptGenerator.scala @@ -12,12 +12,12 @@ case class QuestFulfilledPromptGenerator( ) extends LLMPromptGenerator { import HeroDescriptionGenerator.{description, descriptionWithoutFaction} - private val unaffiliatedHero = gameState.heroes(questFulfilledMessage.heroId) - private val faction = + private val unaffiliatedHero = gameState.heroes(questFulfilledMessage.heroId) + private val faction = FactionInfoUtilities.getFaction(questFulfilledMessage.factionId, gameState) - private val factionLeader = gameState.heroes(faction.factionHeadId) - private val province = gameState.provinces(questFulfilledMessage.provinceId) - private val quest = questFulfilledMessage.getQuest + private val factionLeader = gameState.heroes(faction.factionHeadId) + private val province = gameState.provinces(questFulfilledMessage.provinceId) + private val quest = questFulfilledMessage.getQuest private val questDescriptionResult = QuestEndedGeneratorUtilities.pastTenseQuestDescription( unaffiliatedHero = unaffiliatedHero, @@ -30,34 +30,34 @@ case class QuestFulfilledPromptGenerator( override def generate: TextGenerationResult = for { unaffiliatedHeroDescription <- descriptionWithoutFaction( - hero = unaffiliatedHero, - clientTextStore = clientTextStore, - alive = true - ) - unaffiliatedHeroName <- clientTextStore.getText(unaffiliatedHero.nameTextId) - factionLeaderDescription <- description( - heroId = factionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - questDescription <- questDescriptionResult - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + hero = unaffiliatedHero, + clientTextStore = clientTextStore, + alive = true + ) + unaffiliatedHeroName <- clientTextStore.getText(unaffiliatedHero.nameTextId) + factionLeaderDescription <- description( + heroId = factionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + questDescription <- questDescriptionResult + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val possP = possessivePronoun(unaffiliatedHero.pronounGender) s"""|$setup - | - |$unaffiliatedHeroName, who is currently in the province of ${province.name}, was not ready to join ${faction.name}. - | - |$unaffiliatedHeroDescription - |$factionLeaderDescription - | - |$questDescription - | - |${faction.name} has fulfilled these requirements, and now $unaffiliatedHeroName is willing to join if asked. - | - |Write something the $unaffiliatedHeroName might say, consistent with $possP background, indicating $possP satisfaction with ${faction.name}'s actions and $possP willingness to enter ${faction.name}'s service. - | - |${GeneratorUtilities.limitations(wordCount = 50)}""".stripMargin + | + |$unaffiliatedHeroName, who is currently in the province of ${province.name}, was not ready to join ${faction.name}. + | + |$unaffiliatedHeroDescription + |$factionLeaderDescription + | + |$questDescription + | + |${faction.name} has fulfilled these requirements, and now $unaffiliatedHeroName is willing to join if asked. + | + |Write something the $unaffiliatedHeroName might say, consistent with $possP background, indicating $possP satisfaction with ${faction.name}'s actions and $possP willingness to enter ${faction.name}'s service. + | + |${GeneratorUtilities.limitations(wordCount = 50)}""".stripMargin } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomOfferMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomOfferMessagePromptGenerator.scala index a80f01c8da..e5cb054d32 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomOfferMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomOfferMessagePromptGenerator.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators -import net.eagle0.eagle.client_text.{ - ClientTextStore, - TextGenerationResult, - TextGenerationSuccess -} +import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult, TextGenerationSuccess} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.generated_text_request.RansomOfferMessage @@ -14,16 +10,16 @@ case class RansomOfferMessagePromptGenerator( clientTextStore: ClientTextStore ) extends LLMPromptGenerator { import HeroDescriptionGenerator.* - private val offeringFaction = + private val offeringFaction = FactionInfoUtilities.getFaction( ransomOfferMessage.offeringFactionId, gameState ) private val offeringFactionLeader = gameState.heroes(offeringFaction.factionHeadId) - private val offeringHero = gameState.heroes(ransomOfferMessage.offeringHeroId) + private val offeringHero = gameState.heroes(ransomOfferMessage.offeringHeroId) - private val targetFaction = + private val targetFaction = FactionInfoUtilities.getFaction( ransomOfferMessage.targetFactionId, gameState @@ -33,8 +29,8 @@ case class RansomOfferMessagePromptGenerator( private val ransomedHero = gameState.heroes(ransomOfferMessage.ransomedHeroId) - private val gold = ransomOfferMessage.goldOffered - private val hostagesExchanged = + private val gold = ransomOfferMessage.goldOffered + private val hostagesExchanged = ransomOfferMessage.hostageHeroIdsOffered.map(gameState.heroes).toVector private val prisonersExchanged = ransomOfferMessage.prisonerHeroIdsOffered.map(gameState.heroes).toVector @@ -57,7 +53,7 @@ case class RansomOfferMessagePromptGenerator( .map { hName => s"$g gold and one prisoner in exchange: $hName" } - case (g, exch) => + case (g, exch) => GeneratorUtilities .conjunctionResult( exch.toVector @@ -66,41 +62,39 @@ case class RansomOfferMessagePromptGenerator( "no prisoners or hostages offered" // this shouldn't be possible ) .map { prisonersExchangedText => - if g == 0 then - s"${exch.size} prisoners in exchange: $prisonersExchangedText" - else - s"$g gold and ${exch.size} prisoners in exchange: $prisonersExchangedText" + if g == 0 then s"${exch.size} prisoners in exchange: $prisonersExchangedText" + else s"$g gold and ${exch.size} prisoners in exchange: $prisonersExchangedText" } } for { offeringFactionLeaderText <- description( - heroId = offeringFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderText <- description( - heroId = targetFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - offeringHeroText <- description( - heroId = offeringHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - offeringHeroName <- clientTextStore.getText(offeringHero.nameTextId) - ransomedHeroText <- description( - heroId = ransomedHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - ransomedHeroName <- clientTextStore.getText(ransomedHero.nameTextId) - exchangeText <- exchangeTextResult - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = offeringFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderText <- description( + heroId = targetFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) + offeringHeroText <- description( + heroId = offeringHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + offeringHeroName <- clientTextStore.getText(offeringHero.nameTextId) + ransomedHeroText <- description( + heroId = ransomedHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + ransomedHeroName <- clientTextStore.getText(ransomedHero.nameTextId) + exchangeText <- exchangeTextResult + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val factionLeaderText = if offeringHero.id == offeringFactionLeader.id then "" diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomResolutionMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomResolutionMessagePromptGenerator.scala index e4d72e4525..bf8b519475 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomResolutionMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RansomResolutionMessagePromptGenerator.scala @@ -20,7 +20,7 @@ case class RansomResolutionMessagePromptGenerator( ) extends LLMPromptGenerator { import HeroDescriptionGenerator.description - private val offeringFaction = + private val offeringFaction = FactionInfoUtilities.getFaction( ransomResolutionMessage.offeringFactionId, gameState @@ -28,7 +28,7 @@ case class RansomResolutionMessagePromptGenerator( private val offeringFactionLeader = gameState.heroes(offeringFaction.factionHeadId) - private val targetFaction = + private val targetFaction = FactionInfoUtilities.getFaction( ransomResolutionMessage.targetFactionId, gameState @@ -41,28 +41,28 @@ case class RansomResolutionMessagePromptGenerator( override def generate: TextGenerationResult = for { offeringFactionLeaderDescription <- description( - heroId = offeringFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - offeringFactionLeaderName <- clientTextStore.getText( - offeringFactionLeader.nameTextId - ) - targetFactionLeaderDescription <- description( - heroId = targetFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - ransomedHeroDescription <- description( - heroId = ransomedHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - ransomedHeroName <- clientTextStore.getText(ransomedHero.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = offeringFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + offeringFactionLeaderName <- clientTextStore.getText( + offeringFactionLeader.nameTextId + ) + targetFactionLeaderDescription <- description( + heroId = targetFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) + ransomedHeroDescription <- description( + heroId = ransomedHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + ransomedHeroName <- clientTextStore.getText(ransomedHero.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val factionLeaderText = @@ -70,11 +70,11 @@ case class RansomResolutionMessagePromptGenerator( else offeringFactionLeaderDescription val resolutionMessage = ransomResolutionMessage.resolutionStatus match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"""$targetFactionLeaderName decided to accept the ransom and release $ransomedHeroName. | |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this new agreement.""".stripMargin - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => s"""$targetFactionLeaderName rejected the ransom offer and will keep $ransomedHeroName in prison. | |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this rejection.""".stripMargin diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RecruitmentRefusedPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RecruitmentRefusedPromptGenerator.scala index 03c5d871ee..b873e55c24 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RecruitmentRefusedPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/RecruitmentRefusedPromptGenerator.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators -import net.eagle0.eagle.client_text.{ - ClientTextStore, - TextGenerationResult, - TextGenerationSuccess -} +import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult, TextGenerationSuccess} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.generated_text_request.RecruitmentRefusedMessage @@ -14,24 +10,23 @@ case class RecruitmentRefusedPromptGenerator( clientTextStore: ClientTextStore ) extends LLMPromptGenerator { override def generate: TextGenerationResult = { - val actingHero = gameState.heroes(recruitmentRefusedMessage.actingHeroId) + val actingHero = gameState.heroes(recruitmentRefusedMessage.actingHeroId) val capturedHero = gameState.heroes(recruitmentRefusedMessage.capturedHeroId) - val province = gameState.provinces(recruitmentRefusedMessage.provinceId) + val province = gameState.provinces(recruitmentRefusedMessage.provinceId) val subjP = HeroDescriptionGenerator.subjectPronoun(capturedHero.pronounGender) - val objP = + val objP = HeroDescriptionGenerator.objectPronoun(capturedHero.pronounGender) val possP = HeroDescriptionGenerator.possessivePronoun(capturedHero.pronounGender) - val capturedFactionLeaderId = gameState + val capturedFactionLeaderId = gameState .factions(recruitmentRefusedMessage.capturedHeroFactionId) .factionHeadId val capturedFactionLeaderTextResult = - if capturedFactionLeaderId == capturedHero.id then - TextGenerationSuccess("") + if capturedFactionLeaderId == capturedHero.id then TextGenerationSuccess("") else HeroDescriptionGenerator.description( heroId = capturedFactionLeaderId, @@ -40,22 +35,21 @@ case class RecruitmentRefusedPromptGenerator( ) for { - capturedHeroDescription <- HeroDescriptionGenerator.description( - heroId = capturedHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) - actingHeroDescription <- HeroDescriptionGenerator.description( - heroId = actingHero.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - actingHeroName <- clientTextStore.getText(actingHero.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + capturedHeroDescription <- HeroDescriptionGenerator.description( + heroId = capturedHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + capturedHeroName <- clientTextStore.getText(capturedHero.nameTextId) + actingHeroDescription <- HeroDescriptionGenerator.description( + heroId = actingHero.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + actingHeroName <- clientTextStore.getText(actingHero.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) capturedFactionLeaderText <- capturedFactionLeaderTextResult - } yield { - s""" + } yield s""" |$setup | |$capturedHeroName has been captured in battle by $possP enemy, $actingHeroName. @@ -69,6 +63,5 @@ case class RecruitmentRefusedPromptGenerator( |Write a message $capturedHeroName might say to $actingHeroName explaining $possP refusal to join. | |${GeneratorUtilities.limitations}""".stripMargin - } } } diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SuppressBeastsPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SuppressBeastsPromptGenerator.scala index 09b7ee4d92..3645f423ec 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SuppressBeastsPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SuppressBeastsPromptGenerator.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.actions.llm_prompt_generators import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationResult} import net.eagle0.eagle.common.beast_info.BeastInfo import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.internal.generated_text_request.{ - SuppressBeastsFailedMessage, - SuppressBeastsSucceededMessage -} +import net.eagle0.eagle.internal.generated_text_request.{SuppressBeastsFailedMessage, SuppressBeastsSucceededMessage} import net.eagle0.eagle.library.util.BeastUtils object SuppressBeastsPromptHelpers { @@ -51,18 +48,18 @@ case class SuppressBeastsFailedPromptGenerator( ) override def generate: TextGenerationResult = for { - factionLeaderText <- HeroDescriptionGenerator.description( - heroId = faction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) + factionLeaderText <- HeroDescriptionGenerator.description( + heroId = faction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) eradicatedHeroText <- HeroDescriptionGenerator.description( - heroId = suppressBeastsFailedMessage.heroId, - gameState = gameState, - clientTextStore = clientTextStore - ) + heroId = suppressBeastsFailedMessage.heroId, + gameState = gameState, + clientTextStore = clientTextStore + ) eradicatedHeroName <- clientTextStore.getText(eradicatedHero.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val eradicatedHero = HeroInfoUtilities.getHero(suppressBeastsFailedMessage.heroId, gameState) @@ -88,16 +85,14 @@ case class SuppressBeastsFailedPromptGenerator( BattalionDescriptions.descriptionForBattalion ) - val actorDescription = battalionDescription - .map { battD => - s"$eradicatedHeroName took $battD" - } - .getOrElse { - s"$eradicatedHeroName foolishly went alone" - } + val actorDescription = battalionDescription.map { battD => + s"$eradicatedHeroName took $battD" + }.getOrElse { + s"$eradicatedHeroName foolishly went alone" + } val actorSubjP = subjectPronoun(eradicatedHero.pronounGender) - val actorWas = pronounWasVerb(eradicatedHero.pronounGender) + val actorWas = pronounWasVerb(eradicatedHero.pronounGender) val inputText = s""" @@ -141,29 +136,29 @@ case class SuppressBeastsSucceededPromptGenerator( ) override def generate: TextGenerationResult = for { - factionLeaderText <- description( - heroId = actingFaction.factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - actingHeroText <- description( - heroId = suppressBeastsSucceededMessage.heroId, - gameState = gameState, - clientTextStore = clientTextStore - ) + factionLeaderText <- description( + heroId = actingFaction.factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + actingHeroText <- description( + heroId = suppressBeastsSucceededMessage.heroId, + gameState = gameState, + clientTextStore = clientTextStore + ) successfulHeroName <- clientTextStore.getText(successfulHero.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { - val successfulHero = + val successfulHero = HeroInfoUtilities.getHero( suppressBeastsSucceededMessage.heroId, gameState ) - val faction = FactionInfoUtilities.getFaction( + val faction = FactionInfoUtilities.getFaction( suppressBeastsSucceededMessage.factionId, gameState ) - val factionHead = + val factionHead = HeroInfoUtilities.getHero(faction.factionHeadId, gameState) val heroIsFactionHead = factionHead.id == successfulHero.id @@ -188,17 +183,15 @@ case class SuppressBeastsSucceededPromptGenerator( BattalionDescriptions.descriptionForBattalion ) - val actorDescription = battalionDescription - .map { battD => - s"$successfulHeroName took $battD" - } - .getOrElse { - s"$successfulHeroName valiantly went alone" - } + val actorDescription = battalionDescription.map { battD => + s"$successfulHeroName took $battD" + }.getOrElse { + s"$successfulHeroName valiantly went alone" + } val actorSubjP = subjectPronoun(successfulHero.pronounGender) val actorPossP = possessivePronoun(successfulHero.pronounGender) - val actorWas = pronounWasVerb(successfulHero.pronounGender) + val actorWas = pronounWasVerb(successfulHero.pronounGender) val casualtyText = if suppressBeastsSucceededMessage.casualtyCount > 0 then @@ -208,16 +201,15 @@ case class SuppressBeastsSucceededPromptGenerator( val command = if heroIsFactionHead then s"Write a message that $successfulHeroName would send to the world boasting of their success." - else - s"Write a message that $successfulHeroName would send to $actorPossP liege reporting on the success." + else s"Write a message that $successfulHeroName would send to $actorPossP liege reporting on the success." val resourcesGainedTest = ( suppressBeastsSucceededMessage.goldGained, suppressBeastsSucceededMessage.foodGained ) match { - case (0, 0) => "" - case (0, food) => s" ${actorSubjP.capitalize} won $food food in the hunt." - case (gold, 0) => + case (0, 0) => "" + case (0, food) => s" ${actorSubjP.capitalize} won $food food in the hunt." + case (gold, 0) => s" ${actorSubjP.capitalize} won $gold gold in loot and trophies." case (gold, food) => s" ${actorSubjP.capitalize} won $gold gold and $food food in loot and trophies." diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SwearBrotherhoodPromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SwearBrotherhoodPromptGenerator.scala index dc58db298b..9da2811b87 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SwearBrotherhoodPromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/SwearBrotherhoodPromptGenerator.scala @@ -14,7 +14,7 @@ case class SwearBrotherhoodPromptGenerator( private val newBrotherHero = gameState.heroes(swearBrotherhoodMessage.swornBrotherHeroId) - private val faction = FactionInfoUtilities.getFaction( + private val faction = FactionInfoUtilities.getFaction( swearBrotherhoodMessage.factionId, gameState ) @@ -22,20 +22,20 @@ case class SwearBrotherhoodPromptGenerator( override def generate: TextGenerationResult = for { newBrotherHeroDescription <- descriptionWithoutFaction( - hero = newBrotherHero, - alive = true, - clientTextStore = clientTextStore - ) - newBrotherHeroName <- clientTextStore.getText(newBrotherHero.nameTextId) - factionLeaderDescription <- description( - heroId = FactionInfoUtilities - .getFaction(swearBrotherhoodMessage.factionId, gameState) - .factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - factionLeaderName <- clientTextStore.getText(factionLeader.nameTextId) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + hero = newBrotherHero, + alive = true, + clientTextStore = clientTextStore + ) + newBrotherHeroName <- clientTextStore.getText(newBrotherHero.nameTextId) + factionLeaderDescription <- description( + heroId = FactionInfoUtilities + .getFaction(swearBrotherhoodMessage.factionId, gameState) + .factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + factionLeaderName <- clientTextStore.getText(factionLeader.nameTextId) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val newBrotherHero = gameState.heroes(swearBrotherhoodMessage.swornBrotherHeroId) diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceOfferMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceOfferMessagePromptGenerator.scala index cfc24b690e..8768257e00 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceOfferMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceOfferMessagePromptGenerator.scala @@ -11,7 +11,7 @@ case class TruceOfferMessagePromptGenerator( ) extends LLMPromptGenerator { import HeroDescriptionGenerator.* - private val offeringFaction = + private val offeringFaction = FactionInfoUtilities.getFaction( truceOfferMessage.offeringFactionId, gameState @@ -19,7 +19,7 @@ case class TruceOfferMessagePromptGenerator( private val offeringFactionLeader = gameState.heroes(offeringFaction.factionHeadId) - private val targetFaction = FactionInfoUtilities.getFaction( + private val targetFaction = FactionInfoUtilities.getFaction( truceOfferMessage.targetFactionId, gameState ) @@ -31,30 +31,30 @@ case class TruceOfferMessagePromptGenerator( override def generate: TextGenerationResult = for { offeringFactionLeaderDescription <- description( - heroId = offeringFactionLeader.id, - gameState = gameState, - clientTextStore = clientTextStore - ) - offeringFactionLeaderName <- clientTextStore.getText( - offeringFactionLeader.nameTextId - ) - messengerHeroDescription <- description( - heroId = truceOfferMessage.messengerHeroId, - gameState = gameState, - clientTextStore = clientTextStore - ) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) - targetFactionLeaderDescription <- description( - heroId = FactionInfoUtilities - .getFaction(truceOfferMessage.targetFactionId, gameState) - .factionHeadId, - gameState = gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + heroId = offeringFactionLeader.id, + gameState = gameState, + clientTextStore = clientTextStore + ) + offeringFactionLeaderName <- clientTextStore.getText( + offeringFactionLeader.nameTextId + ) + messengerHeroDescription <- description( + heroId = truceOfferMessage.messengerHeroId, + gameState = gameState, + clientTextStore = clientTextStore + ) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + targetFactionLeaderDescription <- description( + heroId = FactionInfoUtilities + .getFaction(truceOfferMessage.targetFactionId, gameState) + .factionHeadId, + gameState = gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val objP = @@ -76,7 +76,7 @@ case class TruceOfferMessagePromptGenerator( | |If accepted, the truce would end hostilities between $offeringFactionLeaderName and $targetFactionLeaderName, but each may have other enemies in the civil war. |Write a message that $messengerHeroName might deliver to $targetFactionLeaderName. - |If $targetFactionLeaderName is offended, ${targetSubjP} may imprison $objP. + |If $targetFactionLeaderName is offended, $targetSubjP may imprison $objP. | |${GeneratorUtilities.limitations}""".stripMargin diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceResolutionMessagePromptGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceResolutionMessagePromptGenerator.scala index 0484214d0c..9c434c2380 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceResolutionMessagePromptGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/TruceResolutionMessagePromptGenerator.scala @@ -19,7 +19,7 @@ case class TruceResolutionMessagePromptGenerator( clientTextStore: ClientTextStore ) extends LLMPromptGenerator { - private val offeringFaction = + private val offeringFaction = FactionInfoUtilities.getFaction( truceResolutionMessage.offeringFactionId, gameState @@ -27,7 +27,7 @@ case class TruceResolutionMessagePromptGenerator( private val offeringFactionLeader = gameState.heroes(offeringFaction.factionHeadId) - private val targetFaction = + private val targetFaction = FactionInfoUtilities.getFaction( truceResolutionMessage.targetFactionId, gameState @@ -40,44 +40,44 @@ case class TruceResolutionMessagePromptGenerator( override def generate: TextGenerationResult = for { offeringFactionLeaderDescription <- HeroDescriptionGenerator.description( - offeringFactionLeader.id, - gameState, - clientTextStore = clientTextStore - ) - offeringFactionLeaderName <- clientTextStore.getText( - offeringFactionLeader.nameTextId - ) - messengerHeroDescription <- HeroDescriptionGenerator.description( - messengerHero.id, - gameState, - clientTextStore = clientTextStore - ) - messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) - targetFactionLeaderDescription <- HeroDescriptionGenerator.description( - targetFactionLeader.id, - gameState, - clientTextStore = clientTextStore - ) - targetFactionLeaderName <- clientTextStore.getText( - targetFactionLeader.nameTextId - ) - setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) + offeringFactionLeader.id, + gameState, + clientTextStore = clientTextStore + ) + offeringFactionLeaderName <- clientTextStore.getText( + offeringFactionLeader.nameTextId + ) + messengerHeroDescription <- HeroDescriptionGenerator.description( + messengerHero.id, + gameState, + clientTextStore = clientTextStore + ) + messengerHeroName <- clientTextStore.getText(messengerHero.nameTextId) + targetFactionLeaderDescription <- HeroDescriptionGenerator.description( + targetFactionLeader.id, + gameState, + clientTextStore = clientTextStore + ) + targetFactionLeaderName <- clientTextStore.getText( + targetFactionLeader.nameTextId + ) + setup <- GeneratorUtilities.basicSetup(gameState, clientTextStore) } yield { val factionLeaderText = if offeringFactionLeader.id == messengerHero.id then "" else offeringFactionLeaderDescription val resolutionMessage = truceResolutionMessage.resolutionStatus match { - case DIPLOMACY_OFFER_STATUS_ACCEPTED => + case DIPLOMACY_OFFER_STATUS_ACCEPTED => s"""$targetFactionLeaderName decided to accept the truce. | |Hostilities between $offeringFactionLeaderName and $targetFactionLeaderName have ended for now, but there are other factions, and the civil war continues. |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this new agreement.""".stripMargin - case DIPLOMACY_OFFER_STATUS_REJECTED => + case DIPLOMACY_OFFER_STATUS_REJECTED => s"""$targetFactionLeaderName rejected the truce. | |Write a message that $targetFactionLeaderName might tell $offeringFactionLeaderName, and the world, about this rejection.""".stripMargin - case DIPLOMACY_OFFER_STATUS_IMPRISONED => + case DIPLOMACY_OFFER_STATUS_IMPRISONED => s"""$targetFactionLeaderName not only rejected the truce, but imprisoned the ambassador $messengerHeroName! | |Write a message that $messengerHeroName send to the world in reporting their imprisonment.""".stripMargin diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/captured_hero_helpers/CapturedHeroPleaGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/captured_hero_helpers/CapturedHeroPleaGenerator.scala index 25629135ac..ca4ea3c7bd 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/captured_hero_helpers/CapturedHeroPleaGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/captured_hero_helpers/CapturedHeroPleaGenerator.scala @@ -34,8 +34,7 @@ object CapturedHeroPleaGenerator { handled: AlreadyHandled ): LlmRequestT = HandleCapturedHeroPlea( - requestId = - s"$gameId $currentRoundId ${capturedHero.heroId} ${handled.countsString} 1", + requestId = s"$gameId $currentRoundId ${capturedHero.heroId} ${handled.countsString} 1", eagleGameId = gameId, recipientFactionIds = Vector(capturingFactionId), actingFactionId = capturingFactionId, @@ -88,18 +87,17 @@ object CapturedHeroPleaGenerator { ): ActionResultT = actionResult.changedProvinces.foldLeft(actionResult) { case (ar: ActionResultT, cp: ChangedProvinceC) => - cp.newCapturedHeroes.headOption - .map { ch => - withPleaForCapturedHero( - gameId = gameId, - currentRoundId = currentRoundId, - capturingHeroId = capturingHeroId, - capturingFactionId = capturingFactionId, - provinceId = cp.provinceId, - capturedHero = ch, - actionResult = ar - ) - } + cp.newCapturedHeroes.headOption.map { ch => + withPleaForCapturedHero( + gameId = gameId, + currentRoundId = currentRoundId, + capturingHeroId = capturingHeroId, + capturingFactionId = capturingFactionId, + provinceId = cp.provinceId, + capturedHero = ch, + actionResult = ar + ) + } .getOrElse(ar) case _ => throw new EagleInternalException("bad ChangedProvince type") diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/diplomacy_llm_helpers/DiplomacyResolutionLlmRequestGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/diplomacy_llm_helpers/DiplomacyResolutionLlmRequestGenerator.scala index 602f525ea2..f8e6d3afc4 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/diplomacy_llm_helpers/DiplomacyResolutionLlmRequestGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/diplomacy_llm_helpers/DiplomacyResolutionLlmRequestGenerator.scala @@ -21,8 +21,7 @@ object DiplomacyResolutionLlmRequestGenerator { resolution: DiplomacyOfferStatus ): GeneratedTextRequest = GeneratedTextRequest( - id = - s"$currentRoundId truce offer $originatingFactionId $targetFactionId resolution $resolution", + id = s"$currentRoundId truce offer $originatingFactionId $targetFactionId resolution $resolution", eagleGameId = gameId, details = TruceResolutionMessage( offeringFactionId = originatingFactionId, @@ -41,8 +40,7 @@ object DiplomacyResolutionLlmRequestGenerator { resolution: DiplomacyOfferStatus ): GeneratedTextRequest = GeneratedTextRequest( - id = - s"$currentRoundId alliance offer $originatingFactionId $targetFactionId resolution $resolution", + id = s"$currentRoundId alliance offer $originatingFactionId $targetFactionId resolution $resolution", eagleGameId = gameId, details = AllianceOfferResolutionMessage( offeringFactionId = originatingFactionId, @@ -61,8 +59,7 @@ object DiplomacyResolutionLlmRequestGenerator { resolution: DiplomacyOfferStatus ): GeneratedTextRequest = GeneratedTextRequest( - id = - s"$currentRoundId break alliance $originatingFactionId $targetFactionId resolution $resolution", + id = s"$currentRoundId break alliance $originatingFactionId $targetFactionId resolution $resolution", eagleGameId = gameId, details = BreakAllianceResolutionMessage( breakingFactionId = originatingFactionId, @@ -81,8 +78,7 @@ object DiplomacyResolutionLlmRequestGenerator { resolution: DiplomacyOfferStatus ): GeneratedTextRequest = GeneratedTextRequest( - id = - s"$currentRoundId invitation resolution $originatingFactionId $invitedFactionId resolution $resolution", + id = s"$currentRoundId invitation resolution $originatingFactionId $invitedFactionId resolution $resolution", eagleGameId = gameId, details = InvitationResolutionMessage( offeringFactionId = originatingFactionId, @@ -101,8 +97,7 @@ object DiplomacyResolutionLlmRequestGenerator { resolution: DiplomacyOfferStatus ): GeneratedTextRequest = GeneratedTextRequest( - id = - s"$currentRoundId ransom resolution $originatingFactionId $targetFactionId resolution $resolution", + id = s"$currentRoundId ransom resolution $originatingFactionId $targetFactionId resolution $resolution", eagleGameId = gameId, details = RansomResolutionMessage( offeringFactionId = originatingFactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/divine_llm_helpers/DivineLlmRequestGenerator.scala b/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/divine_llm_helpers/DivineLlmRequestGenerator.scala index 2911c51620..3636e5e783 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/divine_llm_helpers/DivineLlmRequestGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/llm_request_generators/divine_llm_helpers/DivineLlmRequestGenerator.scala @@ -13,8 +13,7 @@ object DivineLlmRequestGenerator { province: ProvinceT ): LlmRequestT = DivineMessage( - requestId = - s"$currentRoundId divine province ${province.id} uh $unaffiliatedHeroId", + requestId = s"$currentRoundId divine province ${province.id} uh $unaffiliatedHeroId", eagleGameId = gameId, divinedHeroId = unaffiliatedHeroId, actingHeroId = province.rulingHeroId.get, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/name_generation_request/NameGenerationRequestCreator.scala b/src/main/scala/net/eagle0/eagle/library/actions/name_generation_request/NameGenerationRequestCreator.scala index f932412d81..a477a24438 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/name_generation_request/NameGenerationRequestCreator.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/name_generation_request/NameGenerationRequestCreator.scala @@ -1,12 +1,7 @@ package net.eagle0.eagle.library.actions.name_generation_request import net.eagle0.eagle.{GameId, HeroId} -import net.eagle0.eagle.library.util.hero_generator.name_info.{ - FixedName, - NameInfo, - NameRequest, - NoNameRequest -} +import net.eagle0.eagle.library.util.hero_generator.name_info.{FixedName, NameInfo, NameRequest, NoNameRequest} import net.eagle0.eagle.model.action_result.generated_text_request.{ FixedHeroName, GeneratedHeroName, @@ -19,8 +14,8 @@ object NameGenerationRequestCreator { gameId: GameId, nameInfo: NameInfo ): Option[GeneratedTextRequestT] = nameInfo match { - case NoNameRequest => None - case FixedName(nameId, name) => + case NoNameRequest => None + case FixedName(nameId, name) => Some( FixedHeroName( requestId = nameId, diff --git a/src/main/scala/net/eagle0/eagle/library/actions/util/ShatteredArmyUtils.scala b/src/main/scala/net/eagle0/eagle/library/actions/util/ShatteredArmyUtils.scala index 2c916c34e7..92d2fee937 100644 --- a/src/main/scala/net/eagle0/eagle/library/actions/util/ShatteredArmyUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/actions/util/ShatteredArmyUtils.scala @@ -3,17 +3,11 @@ package net.eagle0.eagle.library.actions.util import net.eagle0.eagle.{BattalionId, RoundId} import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, NotificationC} import net.eagle0.eagle.model.action_result.types.ArmyShatteredResultType import net.eagle0.eagle.model.state.{CombatUnit, MovingArmy} import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.Outlaw @@ -75,9 +69,8 @@ object ShatteredArmyUtils { provinceId = province.id, newUnaffiliatedHeroes = incomingArmy.army.units .map(outlaw), - removedIncomingArmyIds = - incomingArmiesArrivingThisRound(currentRoundId, province) - .map(_.id), + removedIncomingArmyIds = incomingArmiesArrivingThisRound(currentRoundId, province) + .map(_.id), removedHostileArmyFactionIds = Vector(incomingArmy.army.factionId) ) diff --git a/src/main/scala/net/eagle0/eagle/library/settings/base/DoubleSetting.scala b/src/main/scala/net/eagle0/eagle/library/settings/base/DoubleSetting.scala index 9c5a263ba6..c505048062 100644 --- a/src/main/scala/net/eagle0/eagle/library/settings/base/DoubleSetting.scala +++ b/src/main/scala/net/eagle0/eagle/library/settings/base/DoubleSetting.scala @@ -1,6 +1,6 @@ package net.eagle0.eagle.library.settings.base class DoubleSetting(private var _doubleValue: Double) { - def doubleValue: Double = _doubleValue + def doubleValue: Double = _doubleValue def setDoubleValue(newValue: Double): Unit = _doubleValue = newValue } diff --git a/src/main/scala/net/eagle0/eagle/library/settings/base/IntSetting.scala b/src/main/scala/net/eagle0/eagle/library/settings/base/IntSetting.scala index 383e063ff3..effb2008f5 100644 --- a/src/main/scala/net/eagle0/eagle/library/settings/base/IntSetting.scala +++ b/src/main/scala/net/eagle0/eagle/library/settings/base/IntSetting.scala @@ -1,6 +1,6 @@ package net.eagle0.eagle.library.settings.base class IntSetting(private var _intValue: Int) { - def intValue: Int = _intValue + def intValue: Int = _intValue def setIntValue(newValue: Int): Unit = _intValue = newValue } diff --git a/src/main/scala/net/eagle0/eagle/library/settings/loaders/BattalionTypeLoader.scala b/src/main/scala/net/eagle0/eagle/library/settings/loaders/BattalionTypeLoader.scala index 0fc230a9fd..f27fb5be0d 100644 --- a/src/main/scala/net/eagle0/eagle/library/settings/loaders/BattalionTypeLoader.scala +++ b/src/main/scala/net/eagle0/eagle/library/settings/loaders/BattalionTypeLoader.scala @@ -11,11 +11,10 @@ object BattalionTypeLoader { private def loadBattalionTypesFromTsv( tsv: Vector[(String, Vector[String])] ): Vector[BattalionType] = - tsv - .map { case (str, arr) => + tsv.map { + case (str, arr) => arr.map((str, _)) - } - .transpose + }.transpose .map(_.toMap) .map(battalionTypeFromMap) diff --git a/src/main/scala/net/eagle0/eagle/library/util/BattalionNameGenerator.scala b/src/main/scala/net/eagle0/eagle/library/util/BattalionNameGenerator.scala index 3cbe54cb2f..f7d160541c 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/BattalionNameGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/BattalionNameGenerator.scala @@ -3,18 +3,15 @@ package net.eagle0.eagle.library.util import scala.io.Source import net.eagle0.common.{FunctionalRandom, JsonUtils, RandomState} -import net.eagle0.common.name_generation.{ - StringConstructionToken, - StringConstructionTokenGenerator -} +import net.eagle0.common.name_generation.{StringConstructionToken, StringConstructionTokenGenerator} import net.eagle0.eagle.model.state.BattalionTypeId class BattalionNameGenerator( var excludingNames: Vector[String] = Vector.empty[String] ) { - private val battalionTypePlaceholder = "BATTALION_NAME" + private val battalionTypePlaceholder = "BATTALION_NAME" private val battalionAdjectivePlaceholder = "BATTALION_ADJECTIVE" - private val placeNamePlaceholder = "PLACE" + private val placeNamePlaceholder = "PLACE" private val battalionNameConstructionString = { val fmt = @@ -23,11 +20,10 @@ class BattalionNameGenerator( "UTF-8" ) - try { + try fmt.getLines().reduce(_ + _) - } finally { + finally fmt.close() - } } private val namesMap = JsonUtils.mapFromJsonUrl( @@ -43,7 +39,7 @@ class BattalionNameGenerator( namesMap = namesMap, formatString = battalionNameConstructionString, substitutions = Map( - battalionTypePlaceholder -> battalionTypeName, + battalionTypePlaceholder -> battalionTypeName, battalionAdjectivePlaceholder -> battalionTypeAdjective ), atSpecializations = Vector("male", "female") @@ -53,10 +49,10 @@ class BattalionNameGenerator( tokenFor("light_infantry", "light_infantry_adj") private val heavyInfantryToken = tokenFor("heavy_infantry", "heavy_infantry_adj") - private val lightCavalryToken = tokenFor("light_cavalry", "light_cavalry_adj") - private val heavyCavalryToken = tokenFor("heavy_cavalry", "heavy_cavalry_adj") - private val longbowmenToken = tokenFor("longbowmen", "longbowmen_adj") - private val undeadToken = tokenFor("undead", "undead_adj") + private val lightCavalryToken = tokenFor("light_cavalry", "light_cavalry_adj") + private val heavyCavalryToken = tokenFor("heavy_cavalry", "heavy_cavalry_adj") + private val longbowmenToken = tokenFor("longbowmen", "longbowmen_adj") + private val undeadToken = tokenFor("undead", "undead_adj") def nextName( battalionTypeId: BattalionTypeId, diff --git a/src/main/scala/net/eagle0/eagle/library/util/BattalionPower.scala b/src/main/scala/net/eagle0/eagle/library/util/BattalionPower.scala index 6a9b641f5a..fc924c9343 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/BattalionPower.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/BattalionPower.scala @@ -12,10 +12,10 @@ object BattalionPower { val powerMultiplier: Map[BattalionTypeId, Double] = Map( BattalionTypeId.LightInfantry -> 1.0, BattalionTypeId.HeavyInfantry -> 1.5, - BattalionTypeId.LightCavalry -> 1.5, - BattalionTypeId.HeavyCavalry -> 2.0, - BattalionTypeId.Longbowmen -> 1.25, - BattalionTypeId.Undead -> 0.25 + BattalionTypeId.LightCavalry -> 1.5, + BattalionTypeId.HeavyCavalry -> 2.0, + BattalionTypeId.Longbowmen -> 1.25, + BattalionTypeId.Undead -> 0.25 ) private def powerForInfo( @@ -48,10 +48,9 @@ object BattalionPower { // Calculate power per troop for unknown enemy composition // Uses baseline unit type multiplier and 50/50 stats - def baselinePowerPerTroop: Double = { + def baselinePowerPerTroop: Double = // Power for 1 troop with baseline type (1.5) and baseline stats (50/50) // Formula: typeMultiplier * (0.5 + armament/100) * (0.5 + training/100) * size // = 1.5 * (0.5 + 0.5) * (0.5 + 0.5) * 1 = 1.5 * 1.0 * 1.0 * 1 = 1.5 BASELINE_UNIT_TYPE_MULTIPLIER * 1.0 * 1.0 * 1 - } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/BattalionSuitability.scala b/src/main/scala/net/eagle0/eagle/library/util/BattalionSuitability.scala index 77aa4b8cd9..19ab6e1f9f 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/BattalionSuitability.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/BattalionSuitability.scala @@ -11,18 +11,13 @@ import net.eagle0.eagle.api.command.util.appropriate_battalions.SuitableBattalio SUBOPTIMAL } import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.profession.Profession.{ - ENGINEER, - MAGE, - NECROMANCER, - RANGER -} +import net.eagle0.eagle.common.profession.Profession.{ENGINEER, MAGE, NECROMANCER, RANGER} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.HeroId object BattalionSuitability { - def suitabilityLevel(h: Hero, bt: BattalionType): SuitabilityLevel = { + def suitabilityLevel(h: Hero, bt: BattalionType): SuitabilityLevel = h.profession match { case MAGE | NECROMANCER => if !bt.allowsCasting then RESTRICTIVE @@ -39,7 +34,6 @@ object BattalionSuitability { case _ => OPTIMAL } - } def suitableBattalions( h: Hero, diff --git a/src/main/scala/net/eagle0/eagle/library/util/BeastUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/BeastUtils.scala index 6527f27f6b..aa8329f8ff 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/BeastUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/BeastUtils.scala @@ -23,23 +23,18 @@ object BeastUtils { def beastLikelihood(beastId: Int): Double = beastInfos(beastId).likelihood / totalLikelihood - private def beastInfoFromMap(map: Map[String, Any], index: Int): BeastInfo = { + private def beastInfoFromMap(map: Map[String, Any], index: Int): BeastInfo = BeastInfo( id = index, singularName = map("singularName").asInstanceOf[String], pluralName = map("pluralName").asInstanceOf[String], likelihood = map("likelihood").asInstanceOf[String].toDouble, - maxCountMultiplier = - map("maxCountMultiplier").asInstanceOf[String].toDouble, + maxCountMultiplier = map("maxCountMultiplier").asInstanceOf[String].toDouble, relativePower = map("relativePower").asInstanceOf[String].toDouble, - economyDevastation = - map("economyDevastation").asInstanceOf[String].toDouble, - agricultureDevastation = - map("agricultureDevastation").asInstanceOf[String].toDouble, - infrastructureDevastation = - map("infrastructureDevastation").asInstanceOf[String].toDouble, + economyDevastation = map("economyDevastation").asInstanceOf[String].toDouble, + agricultureDevastation = map("agricultureDevastation").asInstanceOf[String].toDouble, + infrastructureDevastation = map("infrastructureDevastation").asInstanceOf[String].toDouble, averageGoldPer = map("averageGoldPer").asInstanceOf[String].toDouble, averageFoodPer = map("averageFoodPer").asInstanceOf[String].toDouble ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/EagleRequire.scala b/src/main/scala/net/eagle0/eagle/library/util/EagleRequire.scala index 6f54e301bc..bdcdfb0ebf 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/EagleRequire.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/EagleRequire.scala @@ -1,15 +1,10 @@ package net.eagle0.eagle.library.util -import net.eagle0.eagle.library.{ - EagleClientException, - EagleCommandException, - EagleInternalException -} +import net.eagle0.eagle.library.{EagleClientException, EagleCommandException, EagleInternalException} object EagleRequire { @inline final def clientRequire(requirement: Boolean, message: => Any): Unit = - if !requirement then - throw new EagleClientException("requirement failed: " + message) + if !requirement then throw new EagleClientException("requirement failed: " + message) @inline final def internalValidated[Result]( result: Result, @@ -23,8 +18,7 @@ object EagleRequire { requirement: Boolean, message: => Any ): Unit = - if !requirement then - throw new EagleInternalException("requirement failed: " + message) + if !requirement then throw new EagleInternalException("requirement failed: " + message) @inline final def internalRequireNot( condition: Boolean, @@ -36,6 +30,5 @@ object EagleRequire { requirement: Boolean, message: => Any ): Unit = - if !requirement then - throw new EagleCommandException("requirement failed: " + message) + if !requirement then throw new EagleCommandException("requirement failed: " + message) } diff --git a/src/main/scala/net/eagle0/eagle/library/util/GameStateViewDiffer.scala b/src/main/scala/net/eagle0/eagle/library/util/GameStateViewDiffer.scala index 217b8fa721..24ad9e5c33 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/GameStateViewDiffer.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/GameStateViewDiffer.scala @@ -4,15 +4,9 @@ import net.eagle0.eagle.common.round_phase.NewRoundPhase import net.eagle0.eagle.views.faction_view.{FactionView, FactionViewDiff} import net.eagle0.eagle.views.game_state_view.{GameStateView, GameStateViewDiff} import net.eagle0.eagle.views.hero_view.{HeroView, HeroViewDiff} -import net.eagle0.eagle.views.hero_view.HeroViewDiff.{ - OptionalGender, - OptionalProfession -} +import net.eagle0.eagle.views.hero_view.HeroViewDiff.{OptionalGender, OptionalProfession} import net.eagle0.eagle.views.province_view.* -import net.eagle0.eagle.views.province_view.FullProvinceInfoDiff.{ - OrderedRulingFactionHeroIds, - ProvinceOrdersOption -} +import net.eagle0.eagle.views.province_view.FullProvinceInfoDiff.{OrderedRulingFactionHeroIds, ProvinceOrdersOption} object GameStateViewDiffer { private val emptyDiff = GameStateViewDiff() @@ -34,25 +28,20 @@ object GameStateViewDiffer { ).map(rp => NewRoundPhase(value = rp)), newDate = optionalDiff(before.currentDate.get, after.currentDate.get), newProvinces = newValues(before.provinces, after.provinces), - changedProvinces = - changedValues(before.provinces, after.provinces, provinceDiff), + changedProvinces = changedValues(before.provinces, after.provinces, provinceDiff), newHeroes = newValues(before.heroes, after.heroes), changedHeroes = changedValues(before.heroes, after.heroes, heroDiff), removedHeroIds = removedKeys(before.heroes, after.heroes), - newBattalionNames = - newEntries(before.battalionNames, after.battalionNames), + newBattalionNames = newEntries(before.battalionNames, after.battalionNames), newFactions = newValues(before.factions, after.factions), - changedFactions = - changedValues(before.factions, after.factions, factionDiff), + changedFactions = changedValues(before.factions, after.factions, factionDiff), removedFactionIds = removedKeys(before.factions, after.factions), newBattles = after.outstandingBattles.diff(before.outstandingBattles), removedBattleIds = before.outstandingBattles .map(_.getShardokGameId) .diff(after.outstandingBattles.map(_.getShardokGameId)), - newBattalionTypes = - newValues(before.battalionTypes, after.battalionTypes), - updatedChronicleEntries = - after.chronicleEntries.filterNot(before.chronicleEntries.contains) + newBattalionTypes = newValues(before.battalionTypes, after.battalionTypes), + updatedChronicleEntries = after.chronicleEntries.filterNot(before.chronicleEntries.contains) ) ) .filterNot(_ == emptyDiff) @@ -71,8 +60,7 @@ object GameStateViewDiffer { after: FullProvinceInfo ): FullProvinceInfoDiff = FullProvinceInfoDiff( - newRulingHeroId = - flatOptionalDiff(before.rulingHeroId, after.rulingHeroId), + newRulingHeroId = flatOptionalDiff(before.rulingHeroId, after.rulingHeroId), orderedRulingFactionHeroIds = Option.when( after.rulingFactionHeroIds != before.rulingFactionHeroIds )( @@ -82,17 +70,14 @@ object GameStateViewDiffer { ), addedBattalions = after.battalions.diff(before.battalions), removedBattalionIds = before.battalions.diff(after.battalions).map(_.id), - newDefendingArmy = - flatOptionalDiff(before.defendingArmy, after.defendingArmy), + newDefendingArmy = flatOptionalDiff(before.defendingArmy, after.defendingArmy), clearDefendingArmy = after.defendingArmy.isEmpty, gold = optionalDiff(before.gold, after.gold), food = optionalDiff(before.food, after.food), economy = optionalDiff(before.economy, after.economy), agriculture = optionalDiff(before.agriculture, after.agriculture), - infrastructure = - optionalDiff(before.infrastructure, after.infrastructure), - economyDevastation = - optionalDiff(before.economyDevastation, after.economyDevastation), + infrastructure = optionalDiff(before.infrastructure, after.infrastructure), + economyDevastation = optionalDiff(before.economyDevastation, after.economyDevastation), agricultureDevastation = optionalDiff( before.agricultureDevastation, after.agricultureDevastation @@ -103,11 +88,9 @@ object GameStateViewDiffer { ), newPriceIndex = optionalDiff(before.priceIndex, after.priceIndex), support = flatOptionalDiff(before.support, after.support), - newProvinceOrders = - optionalDiff(before.provinceOrders, after.provinceOrders) - .map(ord => ProvinceOrdersOption(orders = ord)), - foodConsumption = - optionalDiff(before.foodConsumption, after.foodConsumption), + newProvinceOrders = optionalDiff(before.provinceOrders, after.provinceOrders) + .map(ord => ProvinceOrdersOption(orders = ord)), + foodConsumption = optionalDiff(before.foodConsumption, after.foodConsumption), goldCap = optionalDiff(before.goldCap, after.goldCap), foodCap = optionalDiff(before.foodCap, after.foodCap), hexMapName = optionalDiff(before.hexMapName, after.hexMapName), @@ -118,16 +101,15 @@ object GameStateViewDiffer { .map(_.heroId), addedUnaffiliatedHeroes = after.unaffiliatedHeroes .filterNot(afterUH => before.unaffiliatedHeroes.contains(afterUH)), - setRulerIsTraveling = - optionalDiff(before.rulerIsTraveling, after.rulerIsTraveling) + setRulerIsTraveling = optionalDiff(before.rulerIsTraveling, after.rulerIsTraveling) ) private def fullProvinceInfoDiff( maybeBefore: Option[FullProvinceInfo], maybeAfter: Option[FullProvinceInfo] ): Option[FullProvinceInfoDiff] = (maybeBefore, maybeAfter) match { - case (_, None) => None - case (None, Some(after)) => + case (_, None) => None + case (None, Some(after)) => Some(diffImpl(FullProvinceInfo(), after)) case (Some(before), Some(after)) => Some(diffImpl(before, after)) } @@ -139,10 +121,8 @@ object GameStateViewDiffer { Option.when(before != after)( ProvinceViewDiff( id = after.id, - clearRulingFactionId = - after.rulingFactionId.isEmpty && before.rulingFactionId.nonEmpty, - newRulingFactionId = - flatOptionalDiff(before.rulingFactionId, after.rulingFactionId), + clearRulingFactionId = after.rulingFactionId.isEmpty && before.rulingFactionId.nonEmpty, + newRulingFactionId = flatOptionalDiff(before.rulingFactionId, after.rulingFactionId), clearFullInfo = after.fullInfo.isEmpty, newFullInfo = fullProvinceInfoDiff( before.fullInfo, @@ -179,31 +159,24 @@ object GameStateViewDiffer { newAgility = optionalDiff(before.agility, after.agility), newAgilityXp = optionalDiff(before.agilityXp, after.agilityXp), newConstitution = optionalDiff(before.constitution, after.constitution), - newConstitutionXp = - optionalDiff(before.constitutionXp, after.constitutionXp), + newConstitutionXp = optionalDiff(before.constitutionXp, after.constitutionXp), newCharisma = optionalDiff(before.charisma, after.charisma), newCharismaXp = optionalDiff(before.charismaXp, after.charismaXp), newWisdom = optionalDiff(before.wisdom, after.wisdom), newWisdomXp = optionalDiff(before.wisdomXp, after.wisdomXp), newIntegrity = optionalDiff(before.integrity, after.integrity), newAmbition = optionalDiff(before.ambition, after.ambition), - newGregariousness = - optionalDiff(before.gregariousness, after.gregariousness), + newGregariousness = optionalDiff(before.gregariousness, after.gregariousness), newBravery = optionalDiff(before.bravery, after.bravery), - newArcheryCapable = - optionalDiff(before.archeryCapable, after.archeryCapable), - newStartFireCapable = - optionalDiff(before.startFireCapable, after.startFireCapable), + newArcheryCapable = optionalDiff(before.archeryCapable, after.archeryCapable), + newStartFireCapable = optionalDiff(before.startFireCapable, after.startFireCapable), newImagePath = optionalDiff(before.imagePath, after.imagePath), newSortKeys = if before.sortKeys == after.sortKeys then Vector() else after.sortKeys, - newBackstoryTextId = - optionalDiff(before.backstoryTextId, after.backstoryTextId), + newBackstoryTextId = optionalDiff(before.backstoryTextId, after.backstoryTextId), newPronounGender = - optionalDiff(before.pronounGender, after.pronounGender).map(g => - OptionalGender(pronounGender = g) - ) + optionalDiff(before.pronounGender, after.pronounGender).map(g => OptionalGender(pronounGender = g)) ) ) @@ -215,16 +188,12 @@ object GameStateViewDiffer { FactionViewDiff( id = after.id, newPrestige = optionalDiff(before.prestige, after.prestige), - newFactionHeadId = - optionalDiff(before.factionHeadId, after.factionHeadId), + newFactionHeadId = optionalDiff(before.factionHeadId, after.factionHeadId), addedLeaders = after.leaders.diff(before.leaders), removedLeaders = before.leaders.diff(after.leaders), - changedFactionRelationships = - after.factionRelationships.diff(before.factionRelationships), - addedIncomingDiplomacyOffers = - after.incomingDiplomacyOffers.diff(before.incomingDiplomacyOffers), - removedIncomingDiplomacyOffers = - before.incomingDiplomacyOffers.diff(after.incomingDiplomacyOffers), + changedFactionRelationships = after.factionRelationships.diff(before.factionRelationships), + addedIncomingDiplomacyOffers = after.incomingDiplomacyOffers.diff(before.incomingDiplomacyOffers), + removedIncomingDiplomacyOffers = before.incomingDiplomacyOffers.diff(after.incomingDiplomacyOffers), newFocusProvinceId = after.focusProvinceId ) ) @@ -249,8 +218,9 @@ object GameStateViewDiffer { after: Map[K, V], differ: (V, V) => Option[DV] ): Vector[DV] = - after.flatMap { case (k, av) => - before.get(k).flatMap(b => differ(b, av)) + after.flatMap { + case (k, av) => + before.get(k).flatMap(b => differ(b, av)) }.toVector private def removedKeys[K, V]( diff --git a/src/main/scala/net/eagle0/eagle/library/util/IDable.scala b/src/main/scala/net/eagle0/eagle/library/util/IDable.scala index 49296314f9..74d2987240 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/IDable.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/IDable.scala @@ -7,11 +7,11 @@ import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province object IDable { - def mapifyHeroes(hs: Hero*): Map[HeroId, Hero] = hs.map(h => h.id -> h).toMap + def mapifyHeroes(hs: Hero*): Map[HeroId, Hero] = hs.map(h => h.id -> h).toMap def mapifyBattalions(hs: Battalion*): Map[BattalionId, Battalion] = hs.map(h => h.id -> h).toMap - def mapifyFactions(fs: Faction*): Map[FactionId, Faction] = + def mapifyFactions(fs: Faction*): Map[FactionId, Faction] = fs.map(h => h.id -> h).toMap - def mapifyProvinces(hs: Province*): Map[ProvinceId, Province] = + def mapifyProvinces(hs: Province*): Map[ProvinceId, Province] = hs.map(h => h.id -> h).toMap } diff --git a/src/main/scala/net/eagle0/eagle/library/util/IncomingArmyUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/IncomingArmyUtils.scala index 6b4edfc8c6..c5e1c0bc54 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/IncomingArmyUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/IncomingArmyUtils.scala @@ -15,9 +15,7 @@ object IncomingArmyUtils { factionId: FactionId, currentRoundId: RoundId ): Boolean = - province.incomingArmies.exists(ia => - ia.getArmy.factionId == factionId && ia.arrivalRound == currentRoundId - ) + province.incomingArmies.exists(ia => ia.getArmy.factionId == factionId && ia.arrivalRound == currentRoundId) def relevantIncomingArmies( province: Province, @@ -25,9 +23,7 @@ object IncomingArmyUtils { currentRoundId: RoundId ): Vector[MovingArmy] = province.incomingArmies - .filter(ia => - ia.getArmy.factionId == factionId && ia.arrivalRound == currentRoundId - ) + .filter(ia => ia.getArmy.factionId == factionId && ia.arrivalRound == currentRoundId) .toVector def incomingArmiesAreMutuallyAllied( @@ -50,9 +46,7 @@ object IncomingArmyUtils { factionId: FactionId, gameState: GameState ): Boolean = - province.rulingFactionId.exists(targetFid => - LegacyFactionUtils.factionsAreHostile(targetFid, factionId, gameState) - ) + province.rulingFactionId.exists(targetFid => LegacyFactionUtils.factionsAreHostile(targetFid, factionId, gameState)) def isUnderAttack( provinceId: ProvinceId, diff --git a/src/main/scala/net/eagle0/eagle/library/util/LegacyBattalionUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/LegacyBattalionUtils.scala index 1d9063cbb2..5bbaf4cb06 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/LegacyBattalionUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/LegacyBattalionUtils.scala @@ -15,9 +15,9 @@ object LegacyBattalionUtils { val powerMultiplier: Map[BattalionTypeId, Double] = Map( LIGHT_INFANTRY -> 1.0, HEAVY_INFANTRY -> 2.0, - LIGHT_CAVALRY -> 2.0, - HEAVY_CAVALRY -> 4.0, - LONGBOWMEN -> 1.5 + LIGHT_CAVALRY -> 2.0, + HEAVY_CAVALRY -> 4.0, + LONGBOWMEN -> 1.5 ) def battalionType( diff --git a/src/main/scala/net/eagle0/eagle/library/util/PriceIndexUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/PriceIndexUtils.scala index e13cff1d7e..0b434c1539 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/PriceIndexUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/PriceIndexUtils.scala @@ -12,8 +12,7 @@ object PriceIndexUtils { value: Double ): Double = if value < MinimumPriceIndex.doubleValue then MinimumPriceIndex.doubleValue - else if value > MaximumPriceIndex.doubleValue then - MaximumPriceIndex.doubleValue + else if value > MaximumPriceIndex.doubleValue then MaximumPriceIndex.doubleValue else value def steadyState( @@ -46,13 +45,11 @@ object PriceIndexUtils { agricultureDevastation, infrastructureDevastation ) - val difference = steadyStatePriceIndex - currentPriceIndex - val shifted = + val difference = steadyStatePriceIndex - currentPriceIndex + val shifted = currentPriceIndex + difference * PriceIndexReturnRate.doubleValue - if shifted < MinimumPriceIndex.doubleValue then - MinimumPriceIndex.doubleValue - else if shifted > MaximumPriceIndex.doubleValue then - MaximumPriceIndex.doubleValue + if shifted < MinimumPriceIndex.doubleValue then MinimumPriceIndex.doubleValue + else if shifted > MaximumPriceIndex.doubleValue then MaximumPriceIndex.doubleValue else shifted } diff --git a/src/main/scala/net/eagle0/eagle/library/util/ProvinceDistances.scala b/src/main/scala/net/eagle0/eagle/library/util/ProvinceDistances.scala index 82b33b3c06..215f1cdf2f 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/ProvinceDistances.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/ProvinceDistances.scala @@ -73,12 +73,10 @@ object ProvinceDistances { else go(acc :+ next) } - go(Vector(Set(province))).zipWithIndex - .flatMap { case (s, idx) => + go(Vector(Set(province))).zipWithIndex.flatMap { + case (s, idx) => s.map(pid => pid -> idx) - } - .toMap - .get + }.toMap.get } def closestNeighborToFaction( diff --git a/src/main/scala/net/eagle0/eagle/library/util/ProvinceEventUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/ProvinceEventUtils.scala index 6b5eee2d82..e4ffcc17d9 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/ProvinceEventUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/ProvinceEventUtils.scala @@ -33,6 +33,6 @@ object ProvinceEventUtils { def beastInfo(event: ProvinceEvent): Option[BeastInfo] = event match { case BeastsEvent(_, _, _, beastInfo, _ /* unknownFieldSet */ ) => beastInfo - case _ => None + case _ => None } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/QuestFulfillmentModelUpdaters.scala b/src/main/scala/net/eagle0/eagle/library/util/QuestFulfillmentModelUpdaters.scala index 2b78bb5243..01d0a55ae7 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/QuestFulfillmentModelUpdaters.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/QuestFulfillmentModelUpdaters.scala @@ -5,10 +5,7 @@ import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedPro import net.eagle0.eagle.model.action_result.concrete.ActionResultC.ActionResultCUpdater import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.ComponentQuest -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} object QuestFulfillmentModelUpdaters { // increases the completion counter if the check is passed for all unaffiliated heroes in the province @@ -27,11 +24,11 @@ object QuestFulfillmentModelUpdaters { quest.componentsFulfilled + incrementAmount ) ) - case RecruitmentInfo.HasQuest(quest) => + case RecruitmentInfo.HasQuest(quest) => throw new EagleInternalException( s"Trying to increment a quest for Unaffiliated hero ${uh.heroId} in province ${province.id}, who has a $quest" ) - case _ => + case _ => throw new EagleInternalException( s"Trying to increment a quest for Unaffiliated hero ${uh.heroId} in province ${province.id}, who does not have a quest" ) @@ -53,8 +50,6 @@ object QuestFulfillmentModelUpdaters { check: (UnaffiliatedHeroT, ProvinceT) => Boolean ): ActionResultCUpdater = arc => arc.copy( - changedProvinces = arc.changedProvinces ++ provinces.flatMap(p => - counterIncrementedCP(p, incrementAmount, check) - ) + changedProvinces = arc.changedProvinces ++ provinces.flatMap(p => counterIncrementedCP(p, incrementAmount, check)) ) } diff --git a/src/main/scala/net/eagle0/eagle/library/util/ReturningHeroes.scala b/src/main/scala/net/eagle0/eagle/library/util/ReturningHeroes.scala index 948960e909..2feba70846 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/ReturningHeroes.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/ReturningHeroes.scala @@ -28,22 +28,23 @@ object ReturningHeroes { factionId, provinces, functionalRandom - ).continue { case (optRes, innerFR) => - optRes match { - case Some(value) => RandomState(value, innerFR) - case None => - maybeJoinMovingArmy(hids, factionId, provinces, innerFR) - .continue { case (optRes2, innerFR2) => - optRes2 match { - case Some(value) => RandomState(value, innerFR2) - case None => - RandomState( - becomeExiles(hids, originProvince.id), - innerFR2 - ) - } + ).continue { + case (optRes, innerFR) => + optRes match { + case Some(value) => RandomState(value, innerFR) + case None => + maybeJoinMovingArmy(hids, factionId, provinces, innerFR).continue { + case (optRes2, innerFR2) => + optRes2 match { + case Some(value) => RandomState(value, innerFR2) + case None => + RandomState( + becomeExiles(hids, originProvince.id), + innerFR2 + ) + } } - } + } } ) @@ -94,9 +95,9 @@ object ReturningHeroes { provinces .filter(_.incomingArmies.exists(_.army.factionId == fid)) ) - .continue { case (optProvince, fr) => - optProvince - .map { province => + .continue { + case (optProvince, fr) => + optProvince.map { province => fr.nextRandomElement( province.incomingArmies .filter(_.army.factionId == fid) @@ -124,7 +125,7 @@ object ReturningHeroes { ) } } - .getOrElse(RandomState(None, fr)) + .getOrElse(RandomState(None, fr)) } def becomeExiles( @@ -142,8 +143,7 @@ object ReturningHeroes { ) ) ), - changedHeroes = - hids.map(hid => ChangedHeroC(heroId = hid, clearFactionId = true)) + changedHeroes = hids.map(hid => ChangedHeroC(heroId = hid, clearFactionId = true)) ) case class ReturningResult( diff --git a/src/main/scala/net/eagle0/eagle/library/util/ShardokMapInfo.scala b/src/main/scala/net/eagle0/eagle/library/util/ShardokMapInfo.scala index 600f144123..a2e0050a2c 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/ShardokMapInfo.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/ShardokMapInfo.scala @@ -22,14 +22,14 @@ object ShardokMapInfo { private val shardokMapInfoResourceName = "/net/eagle0/shardok/maps/map_info.json" - private val provinceInfoResourceName = "/net/eagle0/eagle/province_map.tsv" + private val provinceInfoResourceName = "/net/eagle0/eagle/province_map.tsv" // Key to the vector is provinceId lazy val shardokMapInfos: Vector[ExpandedShardokMapInfo] = parseMapInfo private def parseMapInfo: Vector[ExpandedShardokMapInfo] = { implicit val formats: DefaultFormats.type = DefaultFormats - val json = new Json(DefaultFormats) + val json = new Json(DefaultFormats) val fileContents = Using( Source @@ -44,12 +44,12 @@ object ShardokMapInfo { val extracted = parsedJson match { case JArray(items) => items.map { item => - val name = (item \ "name").extract[String] + val name = (item \ "name").extract[String] val castleCount = (item \ "castleCount").extract[Int] - val positions = (item \ "positions").extract[Map[Int, Int]] + val positions = (item \ "positions").extract[Map[Int, Int]] ShardokMapInfo(name, castleCount, positions) } - case _ => throw new Exception("Expected JSON array for map info") + case _ => throw new Exception("Expected JSON array for map info") } val provinceMapInfo = diff --git a/src/main/scala/net/eagle0/eagle/library/util/StatWithConditionUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/StatWithConditionUtils.scala index eb2e2ada0d..b27646f5e2 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/StatWithConditionUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/StatWithConditionUtils.scala @@ -1,11 +1,7 @@ package net.eagle0.eagle.library.util import net.eagle0.eagle.views.stat_with_condition.StatWithCondition -import net.eagle0.eagle.views.stat_with_condition.StatWithCondition.Condition.{ - HIGH, - LOW, - MEDIUM -} +import net.eagle0.eagle.views.stat_with_condition.StatWithCondition.Condition.{HIGH, LOW, MEDIUM} object StatWithConditionUtils { def supportSc(support: Double): StatWithCondition = diff --git a/src/main/scala/net/eagle0/eagle/library/util/TimingUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/TimingUtils.scala index b6a48a3603..7925cd7c67 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/TimingUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/TimingUtils.scala @@ -6,7 +6,7 @@ object TimingUtils { def timedResult[T](message: String, f: => T): T = { val startTime = System.currentTimeMillis() - val t = f + val t = f println(s"$message: ${System.currentTimeMillis() - startTime}ms") t } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelector.scala index 2d26fee9a5..1ed677e337 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelector.scala @@ -1,14 +1,8 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.{FactionId, HeroId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - DiplomacyAvailableCommand -} -import net.eagle0.eagle.api.command.util.diplomacy_option.{ - AllianceOption, - DiplomacyOption -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, DiplomacyAvailableCommand} +import net.eagle0.eagle.api.command.util.diplomacy_option.{AllianceOption, DiplomacyOption} import net.eagle0.eagle.api.selected_command.DiplomacySelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.ofType @@ -27,8 +21,7 @@ object AllianceOfferCommandSelector { targetFactionId: FactionId ): Option[AllianceOption] = options.collectFirst { - case x @ AllianceOption(tfid, _, _ /* unknownFieldSet */ ) - if tfid == targetFactionId => + case x @ AllianceOption(tfid, _, _ /* unknownFieldSet */ ) if tfid == targetFactionId => x } @@ -38,34 +31,30 @@ object AllianceOfferCommandSelector { availableCommands: Vector[AvailableCommand], targetFactionId: FactionId ): Option[CommandSelection] = - ofType[DiplomacyAvailableCommand](availableCommands) - .find { ac => - allianceOptionWithTarget( - ac.options.toVector, - targetFactionId - ).isDefined && usableHeroIds( - ac.availableHeroIds.toVector, - gameState - ).nonEmpty - } - .map { ac => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = ac.actingProvinceId, - available = ac, - selected = DiplomacySelectedCommand( - selectedOption = allianceOptionWithTarget( - ac.options.toVector, - targetFactionId - ).get, - targetFactionId = targetFactionId, - sentHeroId = - usableHeroIds(ac.availableHeroIds.toVector, gameState).maxBy { - hid => - gameState.heroes(hid).vigor - } - ), - reason = "chosenAllianceWithFactionCommand" - ) - } + ofType[DiplomacyAvailableCommand](availableCommands).find { ac => + allianceOptionWithTarget( + ac.options.toVector, + targetFactionId + ).isDefined && usableHeroIds( + ac.availableHeroIds.toVector, + gameState + ).nonEmpty + }.map { ac => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = ac.actingProvinceId, + available = ac, + selected = DiplomacySelectedCommand( + selectedOption = allianceOptionWithTarget( + ac.options.toVector, + targetFactionId + ).get, + targetFactionId = targetFactionId, + sentHeroId = usableHeroIds(ac.availableHeroIds.toVector, gameState).maxBy { hid => + gameState.heroes(hid).vigor + } + ), + reason = "chosenAllianceWithFactionCommand" + ) + } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelector.scala index ad7986e7bc..4d2951fa8a 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelector.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AlmsAvailableCommand, - AvailableCommand -} +import net.eagle0.eagle.api.available_command.{AlmsAvailableCommand, AvailableCommand} import net.eagle0.eagle.api.selected_command.AlmsSelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -24,11 +21,10 @@ object AlmsCommandSelector { availableHeroes: Vector[Hero] ): (Hero, Double) = availableHeroes - .map(h => - (h, AlmsCommand.supportIncreasePerFood(HeroConverter.fromProto(h))) - ) - .maxBy { case (hero, inc) => - (inc, -LegacyHeroUtils.fatigue(hero)) + .map(h => (h, AlmsCommand.supportIncreasePerFood(HeroConverter.fromProto(h)))) + .maxBy { + case (hero, inc) => + (inc, -LegacyHeroUtils.fatigue(hero)) } private def neededSupport(province: Province): Double = @@ -62,20 +58,19 @@ object AlmsCommandSelector { minimumFood: Int, provinceId: ProvinceId ): Option[CommandSelection] = - flatSelectionForType[AlmsAvailableCommand](availableCommands) { - availableCommand => - val province = gameState - .provinces(availableCommand.actingProvinceId) + flatSelectionForType[AlmsAvailableCommand](availableCommands) { availableCommand => + val province = gameState + .provinces(availableCommand.actingProvinceId) - if availableCommand.actingProvinceId == provinceId then - maybeAlmsCommandForProvince( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommand = availableCommand, - minimumFood = minimumFood, - province = province - ) - else None + if availableCommand.actingProvinceId == provinceId then + maybeAlmsCommandForProvince( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommand = availableCommand, + minimumFood = minimumFood, + province = province + ) + else None } def chosenAlmsForSupportWithMinimumCommand( @@ -84,18 +79,17 @@ object AlmsCommandSelector { availableCommands: Vector[AvailableCommand], minimumFood: Int ): Option[CommandSelection] = - flatSelectionForType[AlmsAvailableCommand](availableCommands) { - availableCommand => - val province = gameState - .provinces(availableCommand.actingProvinceId) + flatSelectionForType[AlmsAvailableCommand](availableCommands) { availableCommand => + val province = gameState + .provinces(availableCommand.actingProvinceId) - maybeAlmsCommandForProvince( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommand = availableCommand, - minimumFood = minimumFood, - province = province - ) + maybeAlmsCommandForProvince( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommand = availableCommand, + minimumFood = minimumFood, + province = province + ) } def maybeAlmsCommandForProvince( @@ -106,7 +100,7 @@ object AlmsCommandSelector { province: Province ): Option[CommandSelection] = { val foodAfterFeedingTroops = surplusFood(province, gameState) - val effectiveMinimumFood = minimumFood.min(foodAfterFeedingTroops) + val effectiveMinimumFood = minimumFood.min(foodAfterFeedingTroops) val (bestHero, supportPerFood) = bestHeroWithSupport( availableCommand.availableHeroIds @@ -116,9 +110,9 @@ object AlmsCommandSelector { val neededSupportPerMonth = neededSupport(province) / (13 - gameState.currentDate.get.month) - val neededFoodForSupport = + val neededFoodForSupport = neededSupport(province) / supportPerFood - val neededFoodPerMonth = + val neededFoodPerMonth = neededSupportPerMonth / supportPerFood // We don't want to give too early if we don't have enough food left over to quell a riot, so we need one of: @@ -127,9 +121,9 @@ object AlmsCommandSelector { // 3) we have enough left over // 4) we have a minimum amount we want to give, probably for a quest - val isPartialGift = + val isPartialGift = neededFoodForSupport > availableCommand.foodAvailable - val isDecember = gameState.currentDate.get.month == 12 + val isDecember = gameState.currentDate.get.month == 12 val haveExcessToQuellRiot = (foodAfterFeedingTroops - neededFoodForSupport > 1000) || province.gold > 700 @@ -141,7 +135,7 @@ object AlmsCommandSelector { ) { val desiredFood = Math.max(neededFoodForSupport, effectiveMinimumFood) - val foodToUse = + val foodToUse = Math .min(desiredFood, availableCommand.foodAvailable) .ceil diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooser.scala index 40499873b8..26ac1f898b 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooser.scala @@ -13,11 +13,7 @@ import net.eagle0.eagle.library.settings.{ RequiredRatioToAttack, RequiredRatioToAttackWithoutTakingCastles } -import net.eagle0.eagle.library.util.{ - CommandSelection, - LegacyBattalionUtils, - ShardokMapInfo -} +import net.eagle0.eagle.library.util.{CommandSelection, LegacyBattalionUtils, ShardokMapInfo} import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.views.battalion_view.BattalionView @@ -95,10 +91,10 @@ object AttackCommandChooser { ac: MarchAvailableCommand ): Vector[PossibleAttackCommandInfo] = (for { - opmc <- ac.oneProvinceCommands + opmc <- ac.oneProvinceCommands availableDestination <- opmc.availableDestinationProvinces destinationProvinceId = availableDestination.provinceId - destinationProvince = gameState.provinces(destinationProvinceId) + destinationProvince = gameState.provinces(destinationProvinceId) if destinationFactionIsEligible( actingFactionId = actingFactionId, destinationFactionId = destinationProvince.rulingFactionId, @@ -111,7 +107,7 @@ object AttackCommandChooser { } yield { val battalions = originProvince.battalionIds .map(gameState.battalions) - val heroes = + val heroes = heroesWithSufficientVigorForAttack(opmc.originProvinceId, gameState) val unitCount = Vector( @@ -268,7 +264,7 @@ object AttackCommandChooser { val isWinter = winterMonths.contains(gameState.currentDate.get.month) - val allMarchingCIs = + val allMarchingCIs = if isWinter || hasRiverCrossingProfession then commandInfos else commandInfos.filterNot(_.requiresRiverCrossing) val allMarchingUnits = allMarchingCIs.flatMap(_.sc.marchingUnits) @@ -286,7 +282,7 @@ object AttackCommandChooser { val worryAboutCastleCount = totalBattalionPower < (expectedEnemyBattalionPower * RequiredRatioToAttackWithoutTakingCastles.doubleValue).ceil.toInt - val destinationCastleCount = + val destinationCastleCount = ShardokMapInfo.shardokMapInfos(dPid).castleCount val hasSufficientHeroesForAttack = !worryAboutCastleCount || allMarchingUnits.size >= destinationCastleCount + 1 @@ -303,23 +299,20 @@ object AttackCommandChooser { } } - destinationsWithSufficientPower.values - .maxByOption { commandInfos => - commandInfos - .map(_.totalBattalionPower) - .sum - } - .flatMap { commandInfos => - commandInfos.maxByOption { _.totalBattalionPower } - } - .map { commandInfo => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = ac.actingProvinceId, - available = ac, - selected = commandInfo.sc, - reason = "Marching to attack" - ) - } + destinationsWithSufficientPower.values.maxByOption { commandInfos => + commandInfos + .map(_.totalBattalionPower) + .sum + }.flatMap { commandInfos => + commandInfos.maxByOption(_.totalBattalionPower) + }.map { commandInfo => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = ac.actingProvinceId, + available = ac, + selected = commandInfo.sc, + reason = "Marching to attack" + ) + } } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooser.scala index 381bbe9f61..1177a670a3 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooser.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.common.{FunctionalRandom, RandomState} import net.eagle0.common.hostility.Hostility -import net.eagle0.eagle.api.available_command.{ - AttackDecisionAvailableCommand, - AvailableCommand -} +import net.eagle0.eagle.api.available_command.{AttackDecisionAvailableCommand, AvailableCommand} import net.eagle0.eagle.api.command.util.attack_decision_type.{ AdvanceDecision, DemandTributeDecision, @@ -16,11 +13,7 @@ import net.eagle0.eagle.api.selected_command.AttackDecisionSelectedCommand import net.eagle0.eagle.common.tribute_amount.TributeAmount import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.settings.MinimumPercentageOfEnemyToAttack -import net.eagle0.eagle.library.util.{ - BattalionPower, - CommandSelection, - IncomingArmyUtils -} +import net.eagle0.eagle.library.util.{BattalionPower, CommandSelection, IncomingArmyUtils} import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.flatSelectionForType import net.eagle0.eagle.library.util.command_choice_helpers.CommandChooserImplicits.* import net.eagle0.eagle.FactionId @@ -82,26 +75,25 @@ object AttackDecisionCommandChooser { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { - withdrawAc => - Option.when( - withdrawAc.availableDecisions - .contains(WithdrawDecision()) && - (!okToAttack( - withdrawAc, - gameState - ) || withdrawAc.availableDecisions.size == 1) - )( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = withdrawAc.actingProvinceId, - available = withdrawAc, - selected = AttackDecisionSelectedCommand( - decision = WithdrawDecision() - ), - reason = "withdrawArmySelectedCommand" - ) + flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { withdrawAc => + Option.when( + withdrawAc.availableDecisions + .contains(WithdrawDecision()) && + (!okToAttack( + withdrawAc, + gameState + ) || withdrawAc.availableDecisions.size == 1) + )( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = withdrawAc.actingProvinceId, + available = withdrawAc, + selected = AttackDecisionSelectedCommand( + decision = WithdrawDecision() + ), + reason = "withdrawArmySelectedCommand" ) + ) } private def demandTributeSelectedCommand( @@ -109,44 +101,43 @@ object AttackDecisionCommandChooser { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { - availableCommand => - availableCommand.availableDecisions.collectFirst { - case DemandTributeDecision(maxTribute, _ /* unknownFieldSet */ ) => - tributeToDemand(maxTribute.get).flatMap { tribute => - Option.when( - (okToAttack( - availableCommand, - gameState - ) || availableCommand.availableDecisions.size == 1) && - availableCommand.availableDecisions - .contains(DemandTributeDecision()) - )( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = AttackDecisionSelectedCommand( - decision = DemandTributeDecision(Some(tribute)) - ), - reason = "demandTributeSelectedCommand" - ) + flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { availableCommand => + availableCommand.availableDecisions.collectFirst { + case DemandTributeDecision(maxTribute, _ /* unknownFieldSet */ ) => + tributeToDemand(maxTribute.get).flatMap { tribute => + Option.when( + (okToAttack( + availableCommand, + gameState + ) || availableCommand.availableDecisions.size == 1) && + availableCommand.availableDecisions + .contains(DemandTributeDecision()) + )( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = AttackDecisionSelectedCommand( + decision = DemandTributeDecision(Some(tribute)) + ), + reason = "demandTributeSelectedCommand" ) - } - }.flatten + ) + } + }.flatten } private def okToAttack( availableCommand: AttackDecisionAvailableCommand, gameState: GameState ): Boolean = { - val armies = availableCommand.armies + val armies = availableCommand.armies val province = gameState.provinces(availableCommand.actingProvinceId) // Calculate friendly power using actual battalion composition val friendlyPower: Double = armies .filter(_.hostility != Hostility.ENEMY_HOSTILITY) - .map(armyStats => { + .map(armyStats => // For friendly armies, we need to get the actual Army object to calculate real power province.hostileArmies .find(hag => hag.factionId == armyStats.factionId) @@ -154,15 +145,13 @@ object AttackDecisionCommandChooser { .getOrElse(Vector.empty) .map(ia => IncomingArmyUtils.armyPower(ia.getArmy, gameState)) .sum - }) + ) .sum // Calculate enemy power using baseline assumptions (since we don't know enemy composition) val enemyPower: Double = armies .filter(_.hostility == Hostility.ENEMY_HOSTILITY) - .map(armyStats => - armyStats.troopCount.toDouble * BattalionPower.baselinePowerPerTroop - ) + .map(armyStats => armyStats.troopCount.toDouble * BattalionPower.baselinePowerPerTroop) .sum friendlyPower > MinimumPercentageOfEnemyToAttack.doubleValue * enemyPower @@ -170,48 +159,45 @@ object AttackDecisionCommandChooser { private def tributeToDemand( maxTribute: TributeAmount - ): Option[TributeAmount] = { + ): Option[TributeAmount] = Option.when(2 * maxTribute.gold + maxTribute.food > 4000) { val goldDemanded = 0.max(maxTribute.gold - 200) val foodDemanded = 0.max(maxTribute.food - 400) - if goldDemanded == 0 && foodDemanded == 0 then - tributeToDemand(maxTribute).get + if goldDemanded == 0 && foodDemanded == 0 then tributeToDemand(maxTribute).get else TributeAmount( gold = goldDemanded, food = foodDemanded ) } - } private def advanceArmySelectedCommand( actingFactionId: FactionId, gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { - availableCommand => - Option.when( - availableCommand.availableDecisions - .contains(AdvanceDecision()) && ( - availableCommand.availableDecisions.size == 1 || - okToAttack( - availableCommand, - gameState - ) - ) - ) { - CommandSelection( - actingFactionId = actingFactionId, - available = availableCommand, - actingProvinceId = availableCommand.actingProvinceId, - selected = AttackDecisionSelectedCommand( - decision = AdvanceDecision() - ), - reason = "advanceArmySelectedCommand" - ) - } + flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { availableCommand => + Option.when( + availableCommand.availableDecisions + .contains(AdvanceDecision()) && ( + availableCommand.availableDecisions.size == 1 || + okToAttack( + availableCommand, + gameState + ) + ) + ) { + CommandSelection( + actingFactionId = actingFactionId, + available = availableCommand, + actingProvinceId = availableCommand.actingProvinceId, + selected = AttackDecisionSelectedCommand( + decision = AdvanceDecision() + ), + reason = "advanceArmySelectedCommand" + ) + } } private def safePassageSelectedCommand( @@ -219,19 +205,18 @@ object AttackDecisionCommandChooser { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { - availableCommand => - availableCommand.availableDecisions.collectFirst { - case spd: SafePassageDecision => - CommandSelection( - actingFactionId = actingFactionId, - available = availableCommand, - actingProvinceId = availableCommand.actingProvinceId, - selected = AttackDecisionSelectedCommand( - decision = spd - ), - reason = "safePassageSelectedCommand" - ) - } + flatSelectionForType[AttackDecisionAvailableCommand](availableCommands) { availableCommand => + availableCommand.availableDecisions.collectFirst { + case spd: SafePassageDecision => + CommandSelection( + actingFactionId = actingFactionId, + available = availableCommand, + actingProvinceId = availableCommand.actingProvinceId, + selected = AttackDecisionSelectedCommand( + decision = spd + ), + reason = "safePassageSelectedCommand" + ) + } } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelector.scala index 7c2b2a4470..7af31d7049 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelector.scala @@ -10,8 +10,9 @@ object AvailableCommandSelector { def ofType[T <: AvailableCommand: ClassTag]( acs: Vector[AvailableCommand] ): Vector[T] = - acs.collect { case ac: T => - ac + acs.collect { + case ac: T => + ac } def selectionForType[T <: AvailableCommand: ClassTag]( @@ -30,7 +31,8 @@ object AvailableCommandSelector { )( f: (T, FunctionalRandom) => RandomState[Option[CommandSelection]] ): RandomState[Option[CommandSelection]] = - functionalRandom.nextFlatCollectFirst(acs) { case ac: T => - fr => f(ac, fr) + functionalRandom.nextFlatCollectFirst(acs) { + case ac: T => + fr => f(ac, fr) } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelector.scala index 93a0f2db90..e46e79bf29 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelector.scala @@ -8,10 +8,7 @@ import net.eagle0.eagle.common.battalion_type.BattalionType import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.hero.Hero -import net.eagle0.eagle.library.util.{ - BattalionSuitability, - LegacyBattalionUtils -} +import net.eagle0.eagle.library.util.{BattalionSuitability, LegacyBattalionUtils} import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.EagleRequire.internalRequire @@ -39,17 +36,14 @@ object CombatUnitSelector { val bestBattalionOpt = bs .filter(b => hs.exists(h => suitability(h, b) != RESTRICTIVE)) .maxByOption(LegacyBattalionUtils.power) - bestBattalionOpt - .map { bestBattalion => - val bestHero = hs.minBy(h => - (suitability(h, bestBattalion).index, -LegacyHeroUtils.power(h)) - ) - CombatUnit( - heroId = bestHero.id, - battalionId = Some(bestBattalion.id), - factionId = bestHero.factionId.get - ) - } + bestBattalionOpt.map { bestBattalion => + val bestHero = hs.minBy(h => (suitability(h, bestBattalion).index, -LegacyHeroUtils.power(h))) + CombatUnit( + heroId = bestHero.id, + battalionId = Some(bestBattalion.id), + factionId = bestHero.factionId.get + ) + } .getOrElse( CombatUnit( heroId = hs.maxBy(LegacyHeroUtils.power).id, @@ -65,7 +59,7 @@ object CombatUnitSelector { hs: Vector[Hero], bs: Vector[Battalion], acc: Vector[CombatUnit] - ): Vector[CombatUnit] = { + ): Vector[CombatUnit] = if c == 0 then acc else if hs.isEmpty then acc else { @@ -77,7 +71,6 @@ object CombatUnitSelector { acc :+ unit ) } - } val units = go(desiredCount, heroes, battalions, Vector()) internalRequire( diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpers.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpers.scala index bcb5587d04..9e3b03439d 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpers.scala @@ -4,10 +4,7 @@ import net.eagle0.common.{FunctionalRandom, MoreOption, RandomState} import net.eagle0.eagle.{BattalionId, FactionId, HeroId, ProvinceId} import net.eagle0.eagle.api.available_command.* import net.eagle0.eagle.api.command.util.armed_battalion.ArmedBattalion -import net.eagle0.eagle.api.command.util.attack_decision_type.{ - AdvanceDecision, - WithdrawDecision -} +import net.eagle0.eagle.api.command.util.attack_decision_type.{AdvanceDecision, WithdrawDecision} import net.eagle0.eagle.api.command.util.captured_hero_option.CapturedHeroOption.{ EXECUTE_CAPTURED_HERO_OPTION, IMPRISON_CAPTURED_HERO_OPTION, @@ -15,10 +12,7 @@ import net.eagle0.eagle.api.command.util.captured_hero_option.CapturedHeroOption } import net.eagle0.eagle.api.command.util.diplomacy_option.RansomOfferOption import net.eagle0.eagle.api.selected_command.* -import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand.{ - ChangedBattalion, - NewBattalion -} +import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand.{ChangedBattalion, NewBattalion} import net.eagle0.eagle.common.battalion_type.{BattalionType, BattalionTypeId} import net.eagle0.eagle.common.battalion_type.BattalionTypeId.HEAVY_CAVALRY import net.eagle0.eagle.common.combat_unit.CombatUnit @@ -47,12 +41,7 @@ import net.eagle0.eagle.library.settings.{ VassalMinimumFoodToSendSupplies, VassalMinimumGoldToSendSupplies } -import net.eagle0.eagle.library.util.{ - BattalionTypeFinder, - CommandSelection, - IncomingArmyUtils, - ProvinceDistances -} +import net.eagle0.eagle.library.util.{BattalionTypeFinder, CommandSelection, IncomingArmyUtils, ProvinceDistances} import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.randomSelectionForType import net.eagle0.eagle.library.util.command_choice_helpers.CommandChooserImplicits.* import net.eagle0.eagle.library.util.command_choice_helpers.FoodConsumptionUtils.foodConsumptionMonthsToHold @@ -71,26 +60,23 @@ object CommandChoiceHelpers { actingFactionId: FactionId, gameState: GameState, availableCommands: Vector[AvailableCommand] - ): Option[CommandSelection] = { - flatSelectionForType[OrganizeTroopsAvailableCommand](availableCommands) { - organizeCommand => - MoreOption.flatWhen( - IncomingArmyUtils.isUnderAttack( - gameState.provinces(organizeCommand.actingProvinceId), - gameState - ) - ) { - OrganizeCommandSelector.selectedOrganizeCommand( - actingFactionId = actingFactionId, - availableCommand = organizeCommand, - gameState = gameState, - extraFoodSurplus = - gameState.provinces(organizeCommand.actingProvinceId).food, - reason = "organizing because we're under attack" - ) - } + ): Option[CommandSelection] = + flatSelectionForType[OrganizeTroopsAvailableCommand](availableCommands) { organizeCommand => + MoreOption.flatWhen( + IncomingArmyUtils.isUnderAttack( + gameState.provinces(organizeCommand.actingProvinceId), + gameState + ) + ) { + OrganizeCommandSelector.selectedOrganizeCommand( + actingFactionId = actingFactionId, + availableCommand = organizeCommand, + gameState = gameState, + extraFoodSurplus = gameState.provinces(organizeCommand.actingProvinceId).food, + reason = "organizing because we're under attack" + ) + } } - } def excessBeyondMaximumSupplies( actingProvinceId: ProvinceId, @@ -105,11 +91,11 @@ object CommandChoiceHelpers { val province = gameState.provinces(actingProvinceId) MoreOption.flatWhen(province.support >= MinSupportForTaxes.doubleValue) { - val heroCount = province.rulingFactionHeroIds.size - val battalionCount = province.battalionIds.size + val heroCount = province.rulingFactionHeroIds.size + val battalionCount = province.battalionIds.size val neededNewBattalions: Int = (heroCount - battalionCount).max(0) - val existingBattalions = province.battalionIds.map(gameState.battalions) - val newBattalions = (1 to neededNewBattalions).map { _ => + val existingBattalions = province.battalionIds.map(gameState.battalions) + val newBattalions = (1 to neededNewBattalions).map { _ => Battalion(`type` = HEAVY_CAVALRY) } @@ -149,7 +135,7 @@ object CommandChoiceHelpers { }.sum val riotFoodHeldBack = 1000 - val foodExcess = + val foodExcess = (province.food - 12 * maxMonthlyFoodCost - riotFoodHeldBack) .max(0) .floor @@ -165,20 +151,17 @@ object CommandChoiceHelpers { actingFactionId: FactionId, gameState: GameState, availableCommands: Vector[AvailableCommand] - ): Option[CommandSelection] = { - flatSelectionForType[SendSuppliesAvailableCommand](availableCommands) { - ac => - excessBeyondMaximumSupplies(ac.actingProvinceId, gameState).flatMap { - supplies => - chosenSendSuppliesCommandWithSupplies( - actingFactionId = actingFactionId, - gameState = gameState, - ac = ac, - supplies = supplies - ) - } + ): Option[CommandSelection] = + flatSelectionForType[SendSuppliesAvailableCommand](availableCommands) { ac => + excessBeyondMaximumSupplies(ac.actingProvinceId, gameState).flatMap { supplies => + chosenSendSuppliesCommandWithSupplies( + actingFactionId = actingFactionId, + gameState = gameState, + ac = ac, + supplies = supplies + ) + } } - } // Commands that should be done first regardless of the province's orders. def chosenUniversalCommand( @@ -408,51 +391,50 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[SuppressBeastsAvailableCommand](availableCommands) { - suppressAc => - val actingPid = suppressAc.actingProvinceId + flatSelectionForType[SuppressBeastsAvailableCommand](availableCommands) { suppressAc => + val actingPid = suppressAc.actingProvinceId - val province = gameState.provinces(actingPid) - val beastCount = LegacyProvinceUtils.beastCount(province) - val beastInfo = LegacyProvinceUtils.beastInfo(province).get - val beastPower = - (beastCount * beastInfo.relativePower).ceil.toInt + val province = gameState.provinces(actingPid) + val beastCount = LegacyProvinceUtils.beastCount(province) + val beastInfo = LegacyProvinceUtils.beastInfo(province).get + val beastPower = + (beastCount * beastInfo.relativePower).ceil.toInt - if province.battalionIds - .exists(b => gameState.battalions(b).size >= beastPower) - then { - val leaderId = HeroSelector - .minimallyFatiguedHeroes( - suppressAc.availableHeroIds - .map(gameState.heroes) - .toVector - ) - .maxBy(suppressBeastsValue(_)) - .id - - Some( - CommandSelection( - actingFactionId = actingFactionId, - available = suppressAc, - actingProvinceId = actingPid, - selected = SuppressBeastsSelectedCommand( - heroId = leaderId, - battalionId = Some( - province.battalionIds - .maxBy(b => gameState.battalions(b).size) - ) - ), - reason = "suppressing beasts" - ) + if province.battalionIds + .exists(b => gameState.battalions(b).size >= beastPower) + then { + val leaderId = HeroSelector + .minimallyFatiguedHeroes( + suppressAc.availableHeroIds + .map(gameState.heroes) + .toVector ) - } else - organizeForFightingBeastsCommand( + .maxBy(suppressBeastsValue(_)) + .id + + Some( + CommandSelection( actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - beastPower = beastPower + available = suppressAc, + actingProvinceId = actingPid, + selected = SuppressBeastsSelectedCommand( + heroId = leaderId, + battalionId = Some( + province.battalionIds + .maxBy(b => gameState.battalions(b).size) + ) + ), + reason = "suppressing beasts" ) - end if + ) + } else + organizeForFightingBeastsCommand( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + beastPower = beastPower + ) + end if } private def chosenMobilizeIfAdjacentEnemyCommand( @@ -537,13 +519,14 @@ object CommandChoiceHelpers { gameState = gs, availableCommands = acs, reason = reason - ).filter { case CommandSelection(_, _, ac, _, _) => - shouldRest( - gs.provinces( - ac.asInstanceOf[RestAvailableCommand].actingProvinceId - ).rulingFactionHeroIds - .map(gs.heroes) - ) + ).filter { + case CommandSelection(_, _, ac, _, _) => + shouldRest( + gs.provinces( + ac.asInstanceOf[RestAvailableCommand].actingProvinceId + ).rulingFactionHeroIds + .map(gs.heroes) + ) } def shouldRest(heroes: Iterable[Hero]): Boolean = @@ -578,17 +561,17 @@ object CommandChoiceHelpers { randomSelectionForType[HandleCapturedHeroAvailableCommand]( acs, functionalRandom - ) { case (ac, fr) => - ac.availableHeroes.head match { - case ExpandedCapturedHero( - hero, - options, - _, - _, - _ /* unknownFieldSet */ - ) => - fr.nextDouble - .map { roll => + ) { + case (ac, fr) => + ac.availableHeroes.head match { + case ExpandedCapturedHero( + hero, + options, + _, + _, + _ /* unknownFieldSet */ + ) => + fr.nextDouble.map { roll => Some( CommandSelection( actingFactionId = actingFactionId, @@ -609,7 +592,7 @@ object CommandChoiceHelpers { ) ) } - } + } } def resolvePleaseRecruitMeSelectedCommand( @@ -617,20 +600,18 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[PleaseRecruitMeAvailableCommand](availableCommands) { - pleaseRecruitMeAc => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = 0, - available = pleaseRecruitMeAc, - selected = PleaseRecruitMeSelectedCommand( - provinceId = pleaseRecruitMeAc.availableProvinces.head.provinceId, - heroId = - pleaseRecruitMeAc.availableProvinces.head.availableHeroes.head.getHero.id, - accept = true - ), - reason = "resolvePleaseRecruitMeSelectedCommand" - ) + selectionForType[PleaseRecruitMeAvailableCommand](availableCommands) { pleaseRecruitMeAc => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = 0, + available = pleaseRecruitMeAc, + selected = PleaseRecruitMeSelectedCommand( + provinceId = pleaseRecruitMeAc.availableProvinces.head.provinceId, + heroId = pleaseRecruitMeAc.availableProvinces.head.availableHeroes.head.getHero.id, + accept = true + ), + reason = "resolvePleaseRecruitMeSelectedCommand" + ) } private def handleRiotGiveSelectedCommand( @@ -638,25 +619,24 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[HandleRiotGiveAvailableCommand](availableCommands) { - availableCommand => - CommandSelection( - actingFactionId = actingFactionId, - available = availableCommand, - actingProvinceId = availableCommand.actingProvinceId, - selected = - if availableCommand.foodAvailable >= 2 * availableCommand.goldAvailable - then - HandleRiotGiveSelectedCommand( - foodAmount = availableCommand.foodAvailable - ) - else - HandleRiotGiveSelectedCommand( - goldAmount = availableCommand.goldAvailable - ) - , - reason = "handleRiotGiveSelectedCommand" - ) + selectionForType[HandleRiotGiveAvailableCommand](availableCommands) { availableCommand => + CommandSelection( + actingFactionId = actingFactionId, + available = availableCommand, + actingProvinceId = availableCommand.actingProvinceId, + selected = + if availableCommand.foodAvailable >= 2 * availableCommand.goldAvailable + then + HandleRiotGiveSelectedCommand( + foodAmount = availableCommand.foodAvailable + ) + else + HandleRiotGiveSelectedCommand( + goldAmount = availableCommand.goldAvailable + ) + , + reason = "handleRiotGiveSelectedCommand" + ) } private def handleRiotCrackDownSelectedCommand( @@ -664,20 +644,19 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[HandleRiotCrackDownAvailableCommand](availableCommands) { - availableCommand => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = HandleRiotCrackDownSelectedCommand( - heroId = availableCommand.availableHeroIds - .maxBy(hid => gameState.heroes(hid).vigor), - battalionId = availableCommand.battalionIdsAvailable - .maxByOption(bid => gameState.battalions(bid).size) - ), - reason = "handleRiotCrackDownSelectedCommand" - ) + selectionForType[HandleRiotCrackDownAvailableCommand](availableCommands) { availableCommand => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = HandleRiotCrackDownSelectedCommand( + heroId = availableCommand.availableHeroIds + .maxBy(hid => gameState.heroes(hid).vigor), + battalionId = availableCommand.battalionIdsAvailable + .maxByOption(bid => gameState.battalions(bid).size) + ), + reason = "handleRiotCrackDownSelectedCommand" + ) } private def handleRiotDoNothingSelectedCommand( @@ -685,15 +664,14 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[HandleRiotDoNothingAvailableCommand](availableCommands) { - availableCommand => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = HandleRiotDoNothingSelectedCommand(), - reason = "handleRiotDoNothingSelectedCommand" - ) + selectionForType[HandleRiotDoNothingAvailableCommand](availableCommands) { availableCommand => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = HandleRiotDoNothingSelectedCommand(), + reason = "handleRiotDoNothingSelectedCommand" + ) } def handleRiotSelectedCommand( @@ -828,29 +806,30 @@ object CommandChoiceHelpers { randomSelectionForType[ResolveTributeAvailableCommand]( availableCommands, functionalRandom - ) { case (availableCommand, fr) => - fr.nextRandomElement(availableCommand.demands).map { - case TributeAndFaction( - demandingFactionId: FactionId, - Some(_: TributeAmount), - _: Int, - _: Int, - _ /* unknownFieldSet */ - ) => - Some( - CommandSelection( - actingFactionId = actingFactionId, - available = availableCommand, - actingProvinceId = availableCommand.actingProvinceId, - selected = ResolveTributeSelectedCommand( - demandingFactionId = demandingFactionId, - paid = false - ), - reason = "resolveTributeSelectedCommand" + ) { + case (availableCommand, fr) => + fr.nextRandomElement(availableCommand.demands).map { + case TributeAndFaction( + demandingFactionId: FactionId, + Some(_: TributeAmount), + _: Int, + _: Int, + _ /* unknownFieldSet */ + ) => + Some( + CommandSelection( + actingFactionId = actingFactionId, + available = availableCommand, + actingProvinceId = availableCommand.actingProvinceId, + selected = ResolveTributeSelectedCommand( + demandingFactionId = demandingFactionId, + paid = false + ), + reason = "resolveTributeSelectedCommand" + ) ) - ) - case TributeAndFaction(_, None, _, _, _) => None - } + case TributeAndFaction(_, None, _, _, _) => None + } } def defendSelectedCommand( @@ -862,9 +841,9 @@ object CommandChoiceHelpers { randomSelectionForType[DefendAvailableCommand]( availableCommands, functionalRandom - ) { case (defendCommand, fr) => - fr.nextShuffled(defendCommand.availableFleeProvinceIds.toVector).map { - shuffledFleeProvinceIds => + ) { + case (defendCommand, fr) => + fr.nextShuffled(defendCommand.availableFleeProvinceIds.toVector).map { shuffledFleeProvinceIds => Some( CommandSelection( actingFactionId = actingFactionId, @@ -888,7 +867,7 @@ object CommandChoiceHelpers { reason = "defendSelectedCommand" ) ) - } + } } def defendingUnits( @@ -932,19 +911,18 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[TravelAvailableCommand](availableCommands) { - availableCommand => - val province = gameState.provinces(availableCommand.actingProvinceId) - foodAmountToBuy( - province = province, - gameState = gameState, - goldAvailable = province.gold, - foodBuyPrice = BaseFoodBuyPrice.doubleValue * province.priceIndex - ).map { _ => - chosenTravelCommand(actingFactionId, availableCommand).withReason( - "travel to buy food" - ) - } + flatSelectionForType[TravelAvailableCommand](availableCommands) { availableCommand => + val province = gameState.provinces(availableCommand.actingProvinceId) + foodAmountToBuy( + province = province, + gameState = gameState, + goldAvailable = province.gold, + foodBuyPrice = BaseFoodBuyPrice.doubleValue * province.priceIndex + ).map { _ => + chosenTravelCommand(actingFactionId, availableCommand).withReason( + "travel to buy food" + ) + } } def chosenBuyFoodCommand( @@ -952,28 +930,27 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[TradeAvailableCommand](availableCommands) { - availableCommand => - val province = gameState - .provinces(availableCommand.actingProvinceId) + flatSelectionForType[TradeAvailableCommand](availableCommands) { availableCommand => + val province = gameState + .provinces(availableCommand.actingProvinceId) - foodAmountToBuy( - province, - gameState, - availableCommand.goldAvailable, - availableCommand.foodBuyPrice - ).map { amount => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = TradeSelectedCommand( - tradeType = TradeSelectedCommand.TradeType.BUY_FOOD, - amount = amount - ), - reason = "chosenBuyFoodCommand" - ) - } + foodAmountToBuy( + province, + gameState, + availableCommand.goldAvailable, + availableCommand.foodBuyPrice + ).map { amount => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = TradeSelectedCommand( + tradeType = TradeSelectedCommand.TradeType.BUY_FOOD, + amount = amount + ), + reason = "chosenBuyFoodCommand" + ) + } } def chosenImproveInfrastructureIfBelowTrainingCommand( @@ -981,33 +958,32 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[ImproveAvailableCommand](availableCommands) { - availableCommand => - // If we don't have enough gold that we would arm troops anyway, bail - if provinceGoldSurplus( - availableCommand.actingProvinceId, - gameState - ) < MinGoldSurplusForArm.intValue - then None - else { - val province = - gameState.provinces(availableCommand.actingProvinceId) - val battalions = province.battalionIds.map(gameState.battalions) - val battalionCount = battalions.size - // If fewer than half the battalions have training > infrastructure, raise the infrastructure so that we can arm - MoreOption.flatWhen( - battalions.count( - _.training > LegacyProvinceUtils.effectiveInfrastructure(province) - ) < battalionCount / 2 - ) { - ImproveCommandSelector.chosenSpecificImprovementCommand( - actingFactionId, - gameState, - availableCommands, - INFRASTRUCTURE - ) - } + flatSelectionForType[ImproveAvailableCommand](availableCommands) { availableCommand => + // If we don't have enough gold that we would arm troops anyway, bail + if provinceGoldSurplus( + availableCommand.actingProvinceId, + gameState + ) < MinGoldSurplusForArm.intValue + then None + else { + val province = + gameState.provinces(availableCommand.actingProvinceId) + val battalions = province.battalionIds.map(gameState.battalions) + val battalionCount = battalions.size + // If fewer than half the battalions have training > infrastructure, raise the infrastructure so that we can arm + MoreOption.flatWhen( + battalions.count( + _.training > LegacyProvinceUtils.effectiveInfrastructure(province) + ) < battalionCount / 2 + ) { + ImproveCommandSelector.chosenSpecificImprovementCommand( + actingFactionId, + gameState, + availableCommands, + INFRASTRUCTURE + ) } + } } def suppliesToSend(provinceId: ProvinceId, gameState: GameState): Supplies = @@ -1020,7 +996,7 @@ object CommandChoiceHelpers { actingFactionId: FactionId, gameState: GameState, actingProvinceId: ProvinceId - ): Option[(HeroId, ProvinceId)] = { + ): Option[(HeroId, ProvinceId)] = gameState .factions(actingFactionId) .leaders @@ -1029,22 +1005,23 @@ object CommandChoiceHelpers { .locationOf(leaderId, gameState.provinces.values) .map(pid => (leaderId, pid)) ) - .filter { case (_, pid) => - gameState.provinces(pid).rulingFactionId.contains(actingFactionId) + .filter { + case (_, pid) => + gameState.provinces(pid).rulingFactionId.contains(actingFactionId) } - .flatMap { case (leaderId, pid) => - ProvinceDistances - .distanceThroughFriendliesOption( - p1 = actingProvinceId, - p2 = pid, - fid = actingFactionId, - gs = gameState - ) - .map(distance => (leaderId, pid, distance)) + .flatMap { + case (leaderId, pid) => + ProvinceDistances + .distanceThroughFriendliesOption( + p1 = actingProvinceId, + p2 = pid, + fid = actingFactionId, + gs = gameState + ) + .map(distance => (leaderId, pid, distance)) } .minByOption(_._3) .map(tup => (tup._1, tup._2)) - } def preferredSuppliesDestination( actingFactionId: FactionId, @@ -1143,13 +1120,12 @@ object CommandChoiceHelpers { availableCommands: Vector[AvailableCommand], reason: String ): Option[CommandSelection] = - selectionForType[FeastAvailableCommand](availableCommands) { - feastAvailableCommand => - chosenFeastCommand( - actingFactionId = actingFactionId, - ac = feastAvailableCommand, - reason = reason - ) + selectionForType[FeastAvailableCommand](availableCommands) { feastAvailableCommand => + chosenFeastCommand( + actingFactionId = actingFactionId, + ac = feastAvailableCommand, + reason = reason + ) } private def chosenFeastCommand( @@ -1171,18 +1147,16 @@ object CommandChoiceHelpers { availableCommands: Vector[AvailableCommand], reason: String ): Option[CommandSelection] = - flatSelectionForType[FeastAvailableCommand](availableCommands) { - feastAvailableCommand => - val actingProvinceId = feastAvailableCommand.actingProvinceId - val heroes = lowLoyaltyHeroes( - provinceId = actingProvinceId, - heroIds = - gameState.provinces(actingProvinceId).rulingFactionHeroIds.toVector, - gameState = gameState - ) - Option.when(heroes.length > 1)( - chosenFeastCommand(actingFactionId, feastAvailableCommand, reason) - ) + flatSelectionForType[FeastAvailableCommand](availableCommands) { feastAvailableCommand => + val actingProvinceId = feastAvailableCommand.actingProvinceId + val heroes = lowLoyaltyHeroes( + provinceId = actingProvinceId, + heroIds = gameState.provinces(actingProvinceId).rulingFactionHeroIds.toVector, + gameState = gameState + ) + Option.when(heroes.length > 1)( + chosenFeastCommand(actingFactionId, feastAvailableCommand, reason) + ) } private def maybeChosenGiftCommand( @@ -1191,23 +1165,22 @@ object CommandChoiceHelpers { availableCommands: Vector[AvailableCommand], reason: String ): Option[CommandSelection] = - flatSelectionForType[HeroGiftAvailableCommand](availableCommands) { - heroGiftAvailableCommand => - lowLoyaltyHeroes( - provinceId = heroGiftAvailableCommand.actingProvinceId, - heroIds = heroGiftAvailableCommand.eligibleGifts - .map(_.recipientHeroId) - .toVector, - gameState = gameState - ).headOption.flatMap { hero => - HeroGiftCommandSelector.chosenCommandForSpecificHero( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - heroId = hero.id, - reason = reason - ) - } + flatSelectionForType[HeroGiftAvailableCommand](availableCommands) { heroGiftAvailableCommand => + lowLoyaltyHeroes( + provinceId = heroGiftAvailableCommand.actingProvinceId, + heroIds = heroGiftAvailableCommand.eligibleGifts + .map(_.recipientHeroId) + .toVector, + gameState = gameState + ).headOption.flatMap { hero => + HeroGiftCommandSelector.chosenCommandForSpecificHero( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + heroId = hero.id, + reason = reason + ) + } } private def maybeSpreadIntoOwnedProvince( @@ -1271,10 +1244,10 @@ object CommandChoiceHelpers { ac: MarchAvailableCommand, functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = { - val originProvince = gameState.provinces(opmc.originProvinceId) - val sendingHeroCount = (originProvince.rulingFactionHeroIds.length - + val originProvince = gameState.provinces(opmc.originProvinceId) + val sendingHeroCount = (originProvince.rulingFactionHeroIds.length - originProvince.heroCap).min(opmc.availableHeroIds.length) - val sendingRatio = + val sendingRatio = sendingHeroCount.toDouble / originProvince.rulingFactionHeroIds.length.toDouble val remainingHeroCount = originProvince.rulingFactionHeroIds.length - sendingHeroCount @@ -1314,19 +1287,20 @@ object CommandChoiceHelpers { 0, None ) - .map { case (hid: HeroId, optBid: Option[BattalionId]) => - CombatUnit( - factionId = actingFactionId, - heroId = hid, - battalionId = optBid - ) + .map { + case (hid: HeroId, optBid: Option[BattalionId]) => + CombatUnit( + factionId = actingFactionId, + heroId = hid, + battalionId = optBid + ) } ), reason = "maybeSpreadIntoEmptyProvince" ) ) } - case RandomState(None, fr) => RandomState(None, fr) + case RandomState(None, fr) => RandomState(None, fr) } } @@ -1339,33 +1313,34 @@ object CommandChoiceHelpers { randomSelectionForType[MarchAvailableCommand]( availableCommands, functionalRandom - ) { case (ac, outerFR) => - outerFR.nextFlatCollectFirst( - ac.oneProvinceCommands - .filter(opmc => - gameState - .provinces(opmc.originProvinceId) - .rulingFactionHeroIds - .length > gameState.provinces(opmc.originProvinceId).heroCap - ) - ) { opmc => fr => - maybeSpreadIntoOwnedProvince( - opmc, - actingFactionId, - gameState, - ac - ) match { - case Some(value) => RandomState(Some(value), fr) - case None => - maybeSpreadIntoEmptyProvince( - opmc = opmc, - actingFactionId = actingFactionId, - gameState = gameState, - ac = ac, - functionalRandom = fr + ) { + case (ac, outerFR) => + outerFR.nextFlatCollectFirst( + ac.oneProvinceCommands + .filter(opmc => + gameState + .provinces(opmc.originProvinceId) + .rulingFactionHeroIds + .length > gameState.provinces(opmc.originProvinceId).heroCap ) + ) { opmc => fr => + maybeSpreadIntoOwnedProvince( + opmc, + actingFactionId, + gameState, + ac + ) match { + case Some(value) => RandomState(Some(value), fr) + case None => + maybeSpreadIntoEmptyProvince( + opmc = opmc, + actingFactionId = actingFactionId, + gameState = gameState, + ac = ac, + functionalRandom = fr + ) + } } - } } private def maybeChosenAttackToSaveLeaderCommand( @@ -1385,58 +1360,58 @@ object CommandChoiceHelpers { .filter(_.rulingFactionId.contains(actingFactionId)) .toVector val chosenIndex = gameState.currentRoundId % myProvinces.length - val chosenPid = myProvinces(chosenIndex).id + val chosenPid = myProvinces(chosenIndex).id randomSelectionForType[DiplomacyAvailableCommand]( availableCommands, functionalRandom - ) { case (ac, fr) => - val ransomOfferOptions = ac.options - .collect { case roo: RansomOfferOption => - roo - } - .sortBy { roo => + ) { + case (ac, fr) => + val ransomOfferOptions = ac.options.collect { + case roo: RansomOfferOption => + roo + }.sortBy { roo => LegacyHeroUtils.seniorityOrder( gameState.factions(actingFactionId), roo.getRansomOffer.getPrisonerToBeRansomed.prisonerHeroId ) } - if ac.actingProvinceId == chosenPid then - fr.nextFlatCollectFirst(ransomOfferOptions) { - case RansomOfferOption( - targetFactionId, - Some(ransomOffer), - _ /* unknownFieldSet */ - ) => - innerFR => - innerFR.nextRandomElement(ac.availableHeroIds).map { sentHeroId => - RansomOfferHelpers - .chosenOffer( - originatingFactionId = actingFactionId, - targetFactionId = targetFactionId, - availableOffer = ransomOffer, - gameState = gameState - ) - .map { chosenOffer => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = ac.actingProvinceId, - available = ac, - selected = DiplomacySelectedCommand( - selectedOption = RansomOfferOption( - targetFactionId = targetFactionId, - ransomOffer = Some(chosenOffer) - ), - targetFactionId = targetFactionId, - sentHeroId = sentHeroId - ), - reason = "maybeRansomLeaderCommand" + if ac.actingProvinceId == chosenPid then + fr.nextFlatCollectFirst(ransomOfferOptions) { + case RansomOfferOption( + targetFactionId, + Some(ransomOffer), + _ /* unknownFieldSet */ + ) => + innerFR => + innerFR.nextRandomElement(ac.availableHeroIds).map { sentHeroId => + RansomOfferHelpers + .chosenOffer( + originatingFactionId = actingFactionId, + targetFactionId = targetFactionId, + availableOffer = ransomOffer, + gameState = gameState ) - } - } - } - else RandomState(None, fr) - end if + .map { chosenOffer => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = ac.actingProvinceId, + available = ac, + selected = DiplomacySelectedCommand( + selectedOption = RansomOfferOption( + targetFactionId = targetFactionId, + ransomOffer = Some(chosenOffer) + ), + targetFactionId = targetFactionId, + sentHeroId = sentHeroId + ), + reason = "maybeRansomLeaderCommand" + ) + } + } + } + else RandomState(None, fr) + end if } } @@ -1453,20 +1428,16 @@ object CommandChoiceHelpers { .forall(hid => gameState.provinces.values.exists( _.unaffiliatedHeroes - .exists(uh => - uh.heroId == hid && uh.`type` == UNAFFILIATED_HERO_PRISONER - ) + .exists(uh => uh.heroId == hid && uh.`type` == UNAFFILIATED_HERO_PRISONER) ) ) then - ( - chosenRescueLeaderCommand( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - functionalRandom = functionalRandom - ) - ) + chosenRescueLeaderCommand( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + functionalRandom = functionalRandom + ) else RandomState(None, functionalRandom)) .map(_.map(_.withReason("all leaders are prisoners, trying to rescue"))) @@ -1540,17 +1511,16 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[SendSuppliesAvailableCommand](availableCommands) { - ac => - chosenSendSuppliesCommandWithSupplies( - actingFactionId = actingFactionId, - gameState = gameState, - ac = ac, - supplies = suppliesToSend( - ac.actingProvinceId, - gameState - ) + flatSelectionForType[SendSuppliesAvailableCommand](availableCommands) { ac => + chosenSendSuppliesCommandWithSupplies( + actingFactionId = actingFactionId, + gameState = gameState, + ac = ac, + supplies = suppliesToSend( + ac.actingProvinceId, + gameState ) + ) } def chosenCommandWhileTraveling( @@ -1621,20 +1591,19 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[RecruitHeroesAvailableCommand](availableCommands) { - availableCommand => - val availableHeroes = availableCommand.availableHeroes - Option.when(availableHeroes.nonEmpty) { - CommandSelection( - actingFactionId = actingFactionId, - available = availableCommand, - actingProvinceId = availableCommand.actingProvinceId, - selected = RecruitHeroesSelectedCommand( - heroIds = availableHeroes.map(_.hero.get.id) - ), - reason = "maybeChosenRecruitCommand" - ) - } + flatSelectionForType[RecruitHeroesAvailableCommand](availableCommands) { availableCommand => + val availableHeroes = availableCommand.availableHeroes + Option.when(availableHeroes.nonEmpty) { + CommandSelection( + actingFactionId = actingFactionId, + available = availableCommand, + actingProvinceId = availableCommand.actingProvinceId, + selected = RecruitHeroesSelectedCommand( + heroIds = availableHeroes.map(_.hero.get.id) + ), + reason = "maybeChosenRecruitCommand" + ) + } } private def maybeChosenDivineCommand( @@ -1642,29 +1611,26 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[DivineAvailableCommand](availableCommands) { - availableCommand => - val divinableHeroes = availableCommand.divinableHeroes - val availableGold = - provinceGoldSurplus(availableCommand.actingProvinceId, gameState) - val heroCountToDivine = availableGold / availableCommand.costPerHero + flatSelectionForType[DivineAvailableCommand](availableCommands) { availableCommand => + val divinableHeroes = availableCommand.divinableHeroes + val availableGold = + provinceGoldSurplus(availableCommand.actingProvinceId, gameState) + val heroCountToDivine = availableGold / availableCommand.costPerHero - Option.unless(divinableHeroes.isEmpty || heroCountToDivine < 1) { - CommandSelection( - actingFactionId = actingFactionId, - available = availableCommand, - actingProvinceId = availableCommand.actingProvinceId, - selected = DivineSelectedCommand( - heroIds = divinableHeroes - .sortBy(uh => - LegacyHeroUtils.power(gameState.heroes(uh.getHero.id)) - ) - .takeRight(heroCountToDivine) - .map(_.getHero.id) - ), - reason = "maybeChosenDivineCommand" - ) - } + Option.unless(divinableHeroes.isEmpty || heroCountToDivine < 1) { + CommandSelection( + actingFactionId = actingFactionId, + available = availableCommand, + actingProvinceId = availableCommand.actingProvinceId, + selected = DivineSelectedCommand( + heroIds = divinableHeroes + .sortBy(uh => LegacyHeroUtils.power(gameState.heroes(uh.getHero.id))) + .takeRight(heroCountToDivine) + .map(_.getHero.id) + ), + reason = "maybeChosenDivineCommand" + ) + } } private def chosenReturnCommand( @@ -1672,15 +1638,14 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[ReturnAvailableCommand](availableCommands) { - availableCommand => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = ReturnSelectedCommand(), - reason = "chosenReturnCommand" - ) + selectionForType[ReturnAvailableCommand](availableCommands) { availableCommand => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = ReturnSelectedCommand(), + reason = "chosenReturnCommand" + ) } def maybeChosenTravelToArmTroopsCommand( @@ -1688,29 +1653,28 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[TravelAvailableCommand](availableCommands) { - availableCommand => - val actingProvinceId = availableCommand.actingProvinceId + flatSelectionForType[TravelAvailableCommand](availableCommands) { availableCommand => + val actingProvinceId = availableCommand.actingProvinceId - // Don't travel if you don't have much extra gold to spend anyway - if provinceGoldSurplus( - actingProvinceId, - gameState - ) < MinGoldSurplusForArm.intValue - then None - else { - val province = gameState.provinces(actingProvinceId) - val battalions = province.battalionIds.map(gameState.battalions) - val highestArmamentWeShouldUpgrade = - if LegacyProvinceUtils.effectiveInfrastructure(province) > 90 then - LegacyProvinceUtils.effectiveInfrastructure(province) - 3 - else LegacyProvinceUtils.effectiveInfrastructure(province) - 10 + // Don't travel if you don't have much extra gold to spend anyway + if provinceGoldSurplus( + actingProvinceId, + gameState + ) < MinGoldSurplusForArm.intValue + then None + else { + val province = gameState.provinces(actingProvinceId) + val battalions = province.battalionIds.map(gameState.battalions) + val highestArmamentWeShouldUpgrade = + if LegacyProvinceUtils.effectiveInfrastructure(province) > 90 then + LegacyProvinceUtils.effectiveInfrastructure(province) - 3 + else LegacyProvinceUtils.effectiveInfrastructure(province) - 10 - Option.when( - battalions.exists(_.armament < highestArmamentWeShouldUpgrade) - ) { chosenTravelCommand(actingFactionId, availableCommand) } - } - end if + Option.when( + battalions.exists(_.armament < highestArmamentWeShouldUpgrade) + )(chosenTravelCommand(actingFactionId, availableCommand)) + } + end if } def maybeMoveToRecruitCommand( @@ -1746,9 +1710,7 @@ object CommandChoiceHelpers { fromHere.get.availableDestinationProvinces .map(dest => gs.provinces(dest.provinceId)) .filter(_.rulingFactionId.contains(actingFactionId)) - .filterNot(p => - LegacyProvinceUtils.containsFactionLeader(p.id, gs) - ) + .filterNot(p => LegacyProvinceUtils.containsFactionLeader(p.id, gs)) .filter(p => hasInterestingUH(p.id, gs)) val moveableLeaders = fromHere.get.availableHeroIds @@ -1759,17 +1721,16 @@ object CommandChoiceHelpers { else { // Target the province with the most interesting heroes, or if there is a tie, the sum of the total power // of the interesting heroes - val target = interestingDestinations - .maxBy { province => - val interestingUHs = - province.unaffiliatedHeroes.filter(isInterestingUH) - ( - interestingUHs.length, - interestingUHs - .map(uh => LegacyHeroUtils.power(gs.heroes(uh.heroId))) - .sum - ) - } + val target = interestingDestinations.maxBy { province => + val interestingUHs = + province.unaffiliatedHeroes.filter(isInterestingUH) + ( + interestingUHs.length, + interestingUHs + .map(uh => LegacyHeroUtils.power(gs.heroes(uh.heroId))) + .sum + ) + } fr.nextRandomElement(moveableLeaders).map { heroId => Option( @@ -1815,22 +1776,21 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - flatSelectionForType[TravelAvailableCommand](availableCommands) { - availableCommand => - val actingProvinceId = availableCommand.actingProvinceId + flatSelectionForType[TravelAvailableCommand](availableCommands) { availableCommand => + val actingProvinceId = availableCommand.actingProvinceId - Option.when( - LegacyProvinceUtils - .containsFactionLeader( - actingProvinceId, - gameState - ) && hasInterestingUH( + Option.when( + LegacyProvinceUtils + .containsFactionLeader( actingProvinceId, gameState - ) - ) { - chosenTravelCommand(actingFactionId, availableCommand) - } + ) && hasInterestingUH( + actingProvinceId, + gameState + ) + ) { + chosenTravelCommand(actingFactionId, availableCommand) + } } .map(_.withReason("travel to recruit")) @@ -1851,17 +1811,16 @@ object CommandChoiceHelpers { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[TrainAvailableCommand](availableCommands) { - availableCommand => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = TrainSelectedCommand( - actingHeroId = availableCommand.recommendedHeroId - ), - reason = "chosenTrainCommand" - ) + selectionForType[TrainAvailableCommand](availableCommands) { availableCommand => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = TrainSelectedCommand( + actingHeroId = availableCommand.recommendedHeroId + ), + reason = "chosenTrainCommand" + ) } private def organizeForFightingBeastsCommand( @@ -1870,35 +1829,34 @@ object CommandChoiceHelpers { availableCommands: Vector[AvailableCommand], beastPower: Int ): Option[CommandSelection] = - flatSelectionForType[OrganizeTroopsAvailableCommand](availableCommands) { - availableCommand => - val province = gameState.provinces( - availableCommand.actingProvinceId - ) - val costs = availableCommand.troopCosts - .map(tc => tc.`type` -> tc.costPerTroop) - .toMap - if province.food <= 0 then None - else { - topUpBattalionToFightBeastsCommand( + flatSelectionForType[OrganizeTroopsAvailableCommand](availableCommands) { availableCommand => + val province = gameState.provinces( + availableCommand.actingProvinceId + ) + val costs = availableCommand.troopCosts + .map(tc => tc.`type` -> tc.costPerTroop) + .toMap + if province.food <= 0 then None + else { + topUpBattalionToFightBeastsCommand( + actingFactionId = actingFactionId, + gameState = gameState, + organizeCommand = availableCommand, + province = province, + costs = costs, + beastPower = beastPower + ).orElse( + newBattalionToFightBeastsCommand( actingFactionId = actingFactionId, gameState = gameState, organizeCommand = availableCommand, province = province, costs = costs, beastPower = beastPower - ).orElse( - newBattalionToFightBeastsCommand( - actingFactionId = actingFactionId, - gameState = gameState, - organizeCommand = availableCommand, - province = province, - costs = costs, - beastPower = beastPower - ) - ).map(_.withReason("preparing to fight beasts")) - } - end if + ) + ).map(_.withReason("preparing to fight beasts")) + } + end if } private def maybeChosenArmTroopsCommand( @@ -1907,51 +1865,50 @@ object CommandChoiceHelpers { availableCommands: Vector[AvailableCommand], reason: String ): Option[CommandSelection] = - flatSelectionForType[ArmTroopsAvailableCommand](availableCommands) { - availableCommand => - val provinceId = availableCommand.actingProvinceId - val goldSurplus = provinceGoldSurplus(provinceId, gameState) - val lowestBattalion = availableCommand.availableBattalions - .map(gameState.battalions) - .minBy(_.armament) + flatSelectionForType[ArmTroopsAvailableCommand](availableCommands) { availableCommand => + val provinceId = availableCommand.actingProvinceId + val goldSurplus = provinceGoldSurplus(provinceId, gameState) + val lowestBattalion = availableCommand.availableBattalions + .map(gameState.battalions) + .minBy(_.armament) - val provinceInfrastructure = - LegacyProvinceUtils - .effectiveInfrastructure(gameState.provinces(provinceId)) - .floor - .toInt - if lowestBattalion.armament >= provinceInfrastructure then None - else { - val costPerPointPerTroop = availableCommand.armamentCosts - .find(cost => cost.`type` == lowestBattalion.`type`) - .get - .cost + val provinceInfrastructure = + LegacyProvinceUtils + .effectiveInfrastructure(gameState.provinces(provinceId)) + .floor + .toInt + if lowestBattalion.armament >= provinceInfrastructure then None + else { + val costPerPointPerTroop = availableCommand.armamentCosts + .find(cost => cost.`type` == lowestBattalion.`type`) + .get + .cost - val costPerPoint = lowestBattalion.size * costPerPointPerTroop + val costPerPoint = lowestBattalion.size * costPerPointPerTroop - val newArmament = Math.min( - provinceInfrastructure, - (lowestBattalion.armament + (goldSurplus.toDouble / costPerPoint)).floor.toInt - ) + val newArmament = Math.min( + provinceInfrastructure, + (lowestBattalion.armament + (goldSurplus.toDouble / costPerPoint)).floor.toInt + ) - Option.when(newArmament > lowestBattalion.armament) { - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = provinceId, - available = availableCommand, - selected = ArmTroopsSelectedCommand( - armedBattalions = Vector( - ArmedBattalion( - id = lowestBattalion.id, - newArmament = newArmament - ) + Option.when(newArmament > lowestBattalion.armament) { + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = provinceId, + available = availableCommand, + selected = ArmTroopsSelectedCommand( + armedBattalions = Vector( + ArmedBattalion( + id = lowestBattalion.id, + newArmament = newArmament ) - ), - reason = reason - ) - } + ) + ), + reason = reason + ) } - end if + } + end if } private def provinceFoodSurplus(provinceId: ProvinceId, gs: GameState): Int = @@ -1973,14 +1930,13 @@ object CommandChoiceHelpers { LegacyFactionUtils.ownedNeighbors(gs, actingFactionId) ) - distances(actingProvinceId) - .flatMap { startingDistance => - availableProvinceIds - .map(pid => (pid, distances(pid))) - .filter(_._2.exists(_ < startingDistance)) - .map(_._1) - .headOption - } + distances(actingProvinceId).flatMap { startingDistance => + availableProvinceIds + .map(pid => (pid, distances(pid))) + .filter(_._2.exists(_ < startingDistance)) + .map(_._1) + .headOption + } } private def topUpBattalionToFightBeastsCommand( @@ -2002,16 +1958,16 @@ object CommandChoiceHelpers { if topUpCandidates.isEmpty then None else { val neededTroops = topUpCandidates.map(b => (b, beastPower - b.size)) - val lowestCost = neededTroops - .map { case (batt, needed) => + val lowestCost = neededTroops.map { + case (batt, needed) => (batt, needed, needed * costs(batt.`type`)) - } + } .minBy(_._3) Option.when(lowestCost._3 <= province.gold) { // Hire up to at least beastsCount, but if there's surplus gold, hire more. - val batt = lowestCost._1 - val capacity = + val batt = lowestCost._1 + val capacity = BattalionTypeFinder .battalionType(batt.`type`, gameState.battalionTypes.toVector) .capacity @@ -2049,18 +2005,18 @@ object CommandChoiceHelpers { costs: Map[BattalionTypeId, Double], beastPower: Int ): Option[CommandSelection] = { - val lowestCost = costs.minBy(_._2) + val lowestCost = costs.minBy(_._2) val costForMinimalBattalion = (lowestCost._2 * beastPower).ceil.toInt Option.when(costForMinimalBattalion <= province.gold) { - val goldSurplus = provinceGoldSurplus(province.id, gameState) + val goldSurplus = provinceGoldSurplus(province.id, gameState) val battalionType = BattalionTypeFinder.battalionType( lowestCost._1, gameState.battalionTypes.toVector ) - val couldAfford = (goldSurplus / lowestCost._2).floor.toInt + val couldAfford = (goldSurplus / lowestCost._2).floor.toInt .min(battalionType.capacity) - val countToBuy = couldAfford.max(beastPower).min(battalionType.capacity) + val countToBuy = couldAfford.max(beastPower).min(battalionType.capacity) CommandSelection( actingFactionId = actingFactionId, diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChooser.scala index 90e20f553b..e0e3df2d8f 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChooser.scala @@ -33,7 +33,7 @@ object CommandChooser { case RandomState(None, nextFr) => choose(actingFactionId, gameState, availableCommands, t, nextFr) } - case _ => RandomState(None, functionalRandom) + case _ => RandomState(None, functionalRandom) } } @@ -50,12 +50,11 @@ object CommandChooserImplicits { gameState: GameState, availableCommands: Vector[AvailableCommand], functionalRandom: FunctionalRandom - ): RandomState[Option[CommandSelection]] = { + ): RandomState[Option[CommandSelection]] = RandomState( deterministicChooser(factionId, gameState, availableCommands), functionalRandom ) - } } implicit class RandomCommandChooser( diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExileVassalCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExileVassalCommandSelector.scala index 279c53dee5..cbe80056de 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExileVassalCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExileVassalCommandSelector.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - ExileVassalAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, ExileVassalAvailableCommand} import net.eagle0.eagle.api.selected_command.ExileVassalSelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.ofType diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelector.scala index 3d398a7264..35bd6d1129 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelector.scala @@ -4,11 +4,7 @@ import scala.annotation.tailrec import net.eagle0.common.{FunctionalRandom, RandomState} import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - MarchAvailableCommand, - MarchCommandFromOneProvince -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, MarchAvailableCommand, MarchCommandFromOneProvince} import net.eagle0.eagle.api.selected_command.MarchSelectedCommand import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.internal.game_state.GameState @@ -33,60 +29,61 @@ object ExpandCommandSelector { randomSelectionForType[MarchAvailableCommand]( availableCommands, functionalRandom - ) { case (marchCommand, fr) => - val province = gameState.provinces(marchCommand.actingProvinceId) - val rulingFactionHeroIds = province.rulingFactionHeroIds - val randomNone = RandomState(None, functionalRandom) + ) { + case (marchCommand, fr) => + val province = gameState.provinces(marchCommand.actingProvinceId) + val rulingFactionHeroIds = province.rulingFactionHeroIds + val randomNone = RandomState(None, functionalRandom) - if (rulingFactionHeroIds.size < 2) // Don't abandon this province - || (rulingFactionHeroIds.size - rulingFactionHeroIds.count( - LegacyFactionUtils.isFactionLeader(_, gameState) - ) < 2) // Don't leave a faction leader alone - then randomNone - else - marchCommand.oneProvinceCommands - .find(_.originProvinceId == marchCommand.actingProvinceId) - .map { oneProvinceCommand => - val (adjacentEnemyProvinces, safeProvinces) = - expansionCandidateProvinces( - gameState, - oneProvinceCommand.originProvinceId, - oneProvinceCommand.availableDestinationProvinces - .map(_.provinceId) - .toVector - ).partition(p => - LegacyProvinceUtils - .isAdjacentEnemy(p.id, actingFactionId, gameState) - ) - - // First try to expand into a "safe" province - safeExpansionSelectedCommand( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommand = marchCommand, - oneProvinceCommand = oneProvinceCommand, - safeExpansionCandidateProvinces = safeProvinces, - functionalRandom = fr - ).continue { case (safeCommand, innerFr) => - safeCommand - .map { safeCommand => - RandomState(Some(safeCommand), innerFr) - } - .getOrElse( - // Otherwise march into a province adjacent to an enemy - expansionAdjacentToEnemySelectedCommand( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommand = marchCommand, - oneProvinceCommand = oneProvinceCommand, - adjacentEnemyCandidateProvinces = adjacentEnemyProvinces, - functionalRandom = innerFr - ) + if (rulingFactionHeroIds.size < 2) // Don't abandon this province + || (rulingFactionHeroIds.size - rulingFactionHeroIds.count( + LegacyFactionUtils.isFactionLeader(_, gameState) + ) < 2) // Don't leave a faction leader alone + then randomNone + else + marchCommand.oneProvinceCommands + .find(_.originProvinceId == marchCommand.actingProvinceId) + .map { oneProvinceCommand => + val (adjacentEnemyProvinces, safeProvinces) = + expansionCandidateProvinces( + gameState, + oneProvinceCommand.originProvinceId, + oneProvinceCommand.availableDestinationProvinces + .map(_.provinceId) + .toVector + ).partition(p => + LegacyProvinceUtils + .isAdjacentEnemy(p.id, actingFactionId, gameState) ) + + // First try to expand into a "safe" province + safeExpansionSelectedCommand( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommand = marchCommand, + oneProvinceCommand = oneProvinceCommand, + safeExpansionCandidateProvinces = safeProvinces, + functionalRandom = fr + ).continue { + case (safeCommand, innerFr) => + safeCommand.map { safeCommand => + RandomState(Some(safeCommand), innerFr) + } + .getOrElse( + // Otherwise march into a province adjacent to an enemy + expansionAdjacentToEnemySelectedCommand( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommand = marchCommand, + oneProvinceCommand = oneProvinceCommand, + adjacentEnemyCandidateProvinces = adjacentEnemyProvinces, + functionalRandom = innerFr + ) + ) + } } - } - .getOrElse(randomNone) - end if + .getOrElse(randomNone) + end if } def expansionCandidateProvinces( @@ -119,10 +116,10 @@ object ExpandCommandSelector { safeExpansionCandidateProvinces: Vector[Province], functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = { - val province = gameState.provinces(availableCommand.actingProvinceId) + val province = gameState.provinces(availableCommand.actingProvinceId) val rulingFactionHeroIds = province.rulingFactionHeroIds - val candidateCount = safeExpansionCandidateProvinces.size + val candidateCount = safeExpansionCandidateProvinces.size val minHeroesToSend = (rulingFactionHeroIds.size.toDouble / (candidateCount + 1).toDouble).floor.toInt if oneProvinceCommand.availableHeroIds.size < minHeroesToSend || candidateCount == 0 @@ -163,7 +160,7 @@ object ExpandCommandSelector { adjacentEnemyCandidateProvinces: Vector[Province], functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = { - val province = gameState.provinces(availableCommand.actingProvinceId) + val province = gameState.provinces(availableCommand.actingProvinceId) val rulingFactionHeroIds = province.rulingFactionHeroIds val minHeroesToSend = rulingFactionHeroIds.size / 2 @@ -224,28 +221,29 @@ object ExpandCommandSelector { factionLeaders = factionLeaders, otherCountLeftBehind = otherCountLeftBehind, functionalRandom = functionalRandom - ).continue { case (heroIds, fr) => - fr.nextShuffled(opmc.availableBattalions.toVector) - .map(_.take(battalionCount)) - .map { battalionIdsWithFoodCosts => - val food = - battalionIdsWithFoodCosts.map(_.monthlyFood).sum.ceil.toInt * 2 + ).continue { + case (heroIds, fr) => + fr.nextShuffled(opmc.availableBattalions.toVector) + .map(_.take(battalionCount)) + .map { battalionIdsWithFoodCosts => + val food = + battalionIdsWithFoodCosts.map(_.monthlyFood).sum.ceil.toInt * 2 - val battalionIds = - battalionIdsWithFoodCosts.map(_.battalionId).sorted.map(Option(_)) + val battalionIds = + battalionIdsWithFoodCosts.map(_.battalionId).sorted.map(Option(_)) - val combatUnits = heroIds - .zipAll(battalionIds, 0, None) - .map { pair => - CombatUnit( - heroId = pair._1, - battalionId = pair._2, - factionId = fid - ) - } + val combatUnits = heroIds + .zipAll(battalionIds, 0, None) + .map { pair => + CombatUnit( + heroId = pair._1, + battalionId = pair._2, + factionId = fid + ) + } - MarchUnitsWithFood(combatUnits, food) - } + MarchUnitsWithFood(combatUnits, food) + } } } @@ -261,7 +259,7 @@ object ExpandCommandSelector { functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = { val rulingFactionHeroIds = originatingProvince.rulingFactionHeroIds - val randomNone = RandomState(None, functionalRandom) + val randomNone = RandomState(None, functionalRandom) val heroCountLeftBehind = rulingFactionHeroIds.size - heroCountToSend @@ -279,106 +277,105 @@ object ExpandCommandSelector { (functionalRandom.nextRandomElementOpt( candidateDestinationProvinces ) match { - case RandomState(Some(province), fr) => + case RandomState(Some(province), fr) => RandomState(Some(province), fr) case RandomState(None, fr) if heroCountToSend >= 2 => fr.nextRandomElementOpt(candidateDestinationProvinces) - case rs => rs - }) - .continue { case (provinceOpt, innerFr) => - provinceOpt - .map { chosenCandidateProvince => - val battalionCountToSend = - (originatingProvince.battalionIds.size - heroCountLeftBehind).max( - 0 + case rs => rs + }).continue { + case (provinceOpt, innerFr) => + provinceOpt.map { chosenCandidateProvince => + val battalionCountToSend = + (originatingProvince.battalionIds.size - heroCountLeftBehind).max( + 0 + ) + + randomMarchUnits( + opmc = oneProvinceCommand, + heroCount = heroCountToSend, + battalionCount = battalionCountToSend.min(heroCountToSend), + fid = actingFactionId, + factionLeaders = gameState + .factions(actingFactionId) + .leaders + .intersect(originatingProvince.rulingFactionHeroIds) + .toVector, + otherCountLeftBehind = + originatingProvince.rulingFactionHeroIds.length - oneProvinceCommand.availableHeroIds.length, + functionalRandom = innerFr + ).map { marchingUnitsWithFood => + val takenHeroes = + marchingUnitsWithFood.units.map(_.heroId) + val leftHeroes = + rulingFactionHeroIds.filterNot(takenHeroes.contains) + + internalRequire( + takenHeroes.length > 1 || !LegacyFactionUtils + .isFactionLeader( + heroId = takenHeroes.head, + gameState = gameState + ), + "trying to take only a faction leader!" + ) + + internalRequire( + leftHeroes.length > 1 || !LegacyFactionUtils + .isFactionLeader( + heroId = leftHeroes.head, + gameState = gameState + ), + "trying to leave a faction leader alone!" + ) + + // Calculate the amount of food we need to leave behind and make a smarter calculation about whether + // we can send enough food to make the expansion worth it. + val battalionsHeldBack = originatingProvince.battalionIds + .diff( + marchingUnitsWithFood.units.map(_.battalionId) + ) + .map(gameState.battalions) + val monthlyFoodConsumptionInOrigin = + LegacyBattalionUtils.monthlyConsumedFood( + battalionsHeldBack, + gameState.battalionTypes.toVector + ) + val foodToHoldBack = monthlyFoodConsumptionInOrigin * + FoodConsumptionUtils.foodConsumptionMonthsToHold( + originatingProvince.id, + gameState ) - randomMarchUnits( - opmc = oneProvinceCommand, - heroCount = heroCountToSend, - battalionCount = battalionCountToSend.min(heroCountToSend), - fid = actingFactionId, - factionLeaders = gameState - .factions(actingFactionId) - .leaders - .intersect(originatingProvince.rulingFactionHeroIds) - .toVector, - otherCountLeftBehind = - originatingProvince.rulingFactionHeroIds.length - oneProvinceCommand.availableHeroIds.length, - functionalRandom = innerFr - ).map { marchingUnitsWithFood => - val takenHeroes = - marchingUnitsWithFood.units.map(_.heroId) - val leftHeroes = - rulingFactionHeroIds.filterNot(takenHeroes.contains) + val foodAvailableToSend = + originatingProvince.food - foodToHoldBack - internalRequire( - takenHeroes.length > 1 || !LegacyFactionUtils - .isFactionLeader( - heroId = takenHeroes.head, - gameState = gameState - ), - "trying to take only a faction leader!" - ) - - internalRequire( - leftHeroes.length > 1 || !LegacyFactionUtils - .isFactionLeader( - heroId = leftHeroes.head, - gameState = gameState - ), - "trying to leave a faction leader alone!" - ) - - // Calculate the amount of food we need to leave behind and make a smarter calculation about whether - // we can send enough food to make the expansion worth it. - val battalionsHeldBack = originatingProvince.battalionIds - .diff( - marchingUnitsWithFood.units.map(_.battalionId) - ) - .map(gameState.battalions) - val monthlyFoodConsumptionInOrigin = - LegacyBattalionUtils.monthlyConsumedFood( - battalionsHeldBack, - gameState.battalionTypes.toVector - ) - val foodToHoldBack = monthlyFoodConsumptionInOrigin * - FoodConsumptionUtils.foodConsumptionMonthsToHold( - originatingProvince.id, + val monthlyFoodConsumptionInDestination = + marchingUnitsWithFood.food + val minFoodToSend = + monthlyFoodConsumptionInDestination * FoodConsumptionUtils + .foodConsumptionMonthsToHold( + chosenCandidateProvince.id, gameState ) - val foodAvailableToSend = - originatingProvince.food - foodToHoldBack - - val monthlyFoodConsumptionInDestination = - marchingUnitsWithFood.food - val minFoodToSend = - monthlyFoodConsumptionInDestination * FoodConsumptionUtils - .foodConsumptionMonthsToHold( - chosenCandidateProvince.id, - gameState - ) - - Option.when(minFoodToSend <= foodAvailableToSend) { - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = MarchSelectedCommand( - marchingUnits = marchingUnitsWithFood.units, - destinationProvinceId = chosenCandidateProvince.id, - originProvince = oneProvinceCommand.originProvinceId, - gold = goldToSend, - food = (minFoodToSend + foodAvailableToSend) / 2 - ), - reason = "expandSelectedCommand" - ) - } + Option.when(minFoodToSend <= foodAvailableToSend) { + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = MarchSelectedCommand( + marchingUnits = marchingUnitsWithFood.units, + destinationProvinceId = chosenCandidateProvince.id, + originProvince = oneProvinceCommand.originProvinceId, + gold = goldToSend, + food = (minFoodToSend + foodAvailableToSend) / 2 + ), + reason = "expandSelectedCommand" + ) } } + } .getOrElse(randomNone) - } + } } private def spreadHeroesCommand( @@ -387,67 +384,66 @@ object ExpandCommandSelector { availableCommand: MarchAvailableCommand, functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = - availableCommand.oneProvinceCommands - .flatMap { opmc => - spreadHeroesMarchCandidates( - gameState, - opmc.originProvinceId, - opmc.availableDestinationProvinces.map(_.provinceId).toVector - ).map( - (opmc, _) - ) - } + availableCommand.oneProvinceCommands.flatMap { opmc => + spreadHeroesMarchCandidates( + gameState, + opmc.originProvinceId, + opmc.availableDestinationProvinces.map(_.provinceId).toVector + ).map( + (opmc, _) + ) + } .minByOption(_._2.rulingFactionHeroIds.length) - .map { case (opmc, destinationProvince) => - val originProvince = - gameState.provinces(opmc.originProvinceId) + .map { + case (opmc, destinationProvince) => + val originProvince = + gameState.provinces(opmc.originProvinceId) - val heroCountToSend = - ((originProvince.rulingFactionHeroIds.length - destinationProvince.rulingFactionHeroIds.length) / 2) - .min(MaxCombatUnitCountPerSide.intValue) + val heroCountToSend = + ((originProvince.rulingFactionHeroIds.length - destinationProvince.rulingFactionHeroIds.length) / 2) + .min(MaxCombatUnitCountPerSide.intValue) - val goldToSend = Math.max( - 0, - Math.min( - opmc.goldAvailable, - (provinceGoldSurplus( - originProvince.id, - gameState: GameState - ) - destinationProvince.gold) / 2 - ) - ) - - val battalionCountToSend = Math.min( - heroCountToSend, - (heroCountToSend * originProvince.battalionIds.size) / originProvince.rulingFactionHeroIds.size - ) - - randomMarchUnits( - opmc = opmc, - heroCount = heroCountToSend, - battalionCount = battalionCountToSend, - fid = actingFactionId, - factionLeaders = gameState.factions(actingFactionId).leaders.toVector, - otherCountLeftBehind = - originProvince.rulingFactionHeroIds.length - opmc.availableHeroIds.length, - functionalRandom = functionalRandom - ).map { marchingUnitsWithFood => - Some( - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = availableCommand.actingProvinceId, - available = availableCommand, - selected = MarchSelectedCommand( - marchingUnits = marchingUnitsWithFood.units, - destinationProvinceId = destinationProvince.id, - originProvince = opmc.originProvinceId, - gold = goldToSend, - food = Math.min(marchingUnitsWithFood.food, originProvince.food) - ), - reason = "spreadHeroesCommand" + val goldToSend = Math.max( + 0, + Math.min( + opmc.goldAvailable, + (provinceGoldSurplus( + originProvince.id, + gameState: GameState + ) - destinationProvince.gold) / 2 ) ) - } + + val battalionCountToSend = Math.min( + heroCountToSend, + (heroCountToSend * originProvince.battalionIds.size) / originProvince.rulingFactionHeroIds.size + ) + + randomMarchUnits( + opmc = opmc, + heroCount = heroCountToSend, + battalionCount = battalionCountToSend, + fid = actingFactionId, + factionLeaders = gameState.factions(actingFactionId).leaders.toVector, + otherCountLeftBehind = originProvince.rulingFactionHeroIds.length - opmc.availableHeroIds.length, + functionalRandom = functionalRandom + ).map { marchingUnitsWithFood => + Some( + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = availableCommand.actingProvinceId, + available = availableCommand, + selected = MarchSelectedCommand( + marchingUnits = marchingUnitsWithFood.units, + destinationProvinceId = destinationProvince.id, + originProvince = opmc.originProvinceId, + gold = goldToSend, + food = Math.min(marchingUnitsWithFood.food, originProvince.food) + ), + reason = "spreadHeroesCommand" + ) + ) + } } .getOrElse(RandomState(None, functionalRandom)) diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelector.scala index b5c8cb8789..87d02f500c 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelector.scala @@ -29,15 +29,16 @@ object FulfillQuestsCommandSelector { uhsWithQuests: Vector[UnaffiliatedHeroWithQuest], functionalRandom: FunctionalRandom ): RandomState[Option[CommandSelection]] = - functionalRandom.nextFlatCollectFirst(choosers) { case chooser => - fr => - chooser.chosenCommand( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - uhsWithQuests = uhsWithQuests, - functionalRandom = fr - ) + functionalRandom.nextFlatCollectFirst(choosers) { + case chooser => + fr => + chooser.chosenCommand( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + uhsWithQuests = uhsWithQuests, + functionalRandom = fr + ) } def chosenFulfillEasyQuestsCommand( @@ -48,15 +49,13 @@ object FulfillQuestsCommandSelector { ): RandomState[Option[CommandSelection]] = { val myProvinces = gameState.provinces.values .filter(_.rulingFactionId.contains(actingFactionId)) - .filter(province => - LegacyProvinceUtils.ruledByFactionLeader(province, gameState) - ) + .filter(province => LegacyProvinceUtils.ruledByFactionLeader(province, gameState)) val uhsWithQuests = (for { - province <- myProvinces - uh <- province.unaffiliatedHeroes + province <- myProvinces + uh <- province.unaffiliatedHeroes recruitmentInfo <- uh.recruitmentInfo - quest <- recruitmentInfo.quest + quest <- recruitmentInfo.quest } yield UnaffiliatedHeroWithQuest(province.id, uh, quest)).toVector choiceFrom( diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/HeroGiftCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/HeroGiftCommandSelector.scala index e8d7c24e3c..08549d1973 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/HeroGiftCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/HeroGiftCommandSelector.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - HeroGiftAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, HeroGiftAvailableCommand} import net.eagle0.eagle.api.selected_command.HeroGiftSelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.flatSelectionForType @@ -18,26 +15,22 @@ object HeroGiftCommandSelector { provinceId: ProvinceId, maxAmount: Int ): Option[CommandSelection] = - flatSelectionForType[HeroGiftAvailableCommand](availableCommands) { - heroGiftAvailableCommand => - heroGiftAvailableCommand.eligibleGifts - .filter(_.recipientProvinceId == provinceId) - .minByOption(eligibleGift => - gameState.heroes(eligibleGift.recipientHeroId).loyalty + flatSelectionForType[HeroGiftAvailableCommand](availableCommands) { heroGiftAvailableCommand => + heroGiftAvailableCommand.eligibleGifts + .filter(_.recipientProvinceId == provinceId) + .minByOption(eligibleGift => gameState.heroes(eligibleGift.recipientHeroId).loyalty) + .map { eligibleGift => + CommandSelection( + actingFactionId = actingFactionId, + available = heroGiftAvailableCommand, + actingProvinceId = heroGiftAvailableCommand.actingProvinceId, + selected = HeroGiftSelectedCommand( + recipientHeroId = eligibleGift.recipientHeroId, + amount = eligibleGift.goldAvailable.min(maxAmount) + ), + reason = s"giving to lowest loyalty hero (${eligibleGift.recipientHeroId})" ) - .map { eligibleGift => - CommandSelection( - actingFactionId = actingFactionId, - available = heroGiftAvailableCommand, - actingProvinceId = heroGiftAvailableCommand.actingProvinceId, - selected = HeroGiftSelectedCommand( - recipientHeroId = eligibleGift.recipientHeroId, - amount = eligibleGift.goldAvailable.min(maxAmount) - ), - reason = - s"giving to lowest loyalty hero (${eligibleGift.recipientHeroId})" - ) - } + } } def chosenCommandForSpecificHero( @@ -47,21 +40,20 @@ object HeroGiftCommandSelector { heroId: HeroId, reason: String ): Option[CommandSelection] = - flatSelectionForType[HeroGiftAvailableCommand](availableCommands) { - heroGiftAvailableCommand => - heroGiftAvailableCommand.eligibleGifts - .find(_.recipientHeroId == heroId) - .map { eligibleGift => - CommandSelection( - actingFactionId = actingFactionId, - available = heroGiftAvailableCommand, - actingProvinceId = heroGiftAvailableCommand.actingProvinceId, - selected = HeroGiftSelectedCommand( - recipientHeroId = heroId, - amount = eligibleGift.goldAvailable - ), - reason = reason - ) - } + flatSelectionForType[HeroGiftAvailableCommand](availableCommands) { heroGiftAvailableCommand => + heroGiftAvailableCommand.eligibleGifts + .find(_.recipientHeroId == heroId) + .map { eligibleGift => + CommandSelection( + actingFactionId = actingFactionId, + available = heroGiftAvailableCommand, + actingProvinceId = heroGiftAvailableCommand.actingProvinceId, + selected = HeroGiftSelectedCommand( + recipientHeroId = heroId, + amount = eligibleGift.goldAvailable + ), + reason = reason + ) + } } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelector.scala index 7a2c5747ad..70b900b7d8 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelector.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - ImproveAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, ImproveAvailableCommand} import net.eagle0.eagle.api.selected_command.ImproveSelectedCommand import net.eagle0.eagle.common.improvement_type.ImprovementType import net.eagle0.eagle.common.improvement_type.ImprovementType.DEVASTATION @@ -29,7 +26,7 @@ object ImproveCommandSelector { case ImprovementType.INFRASTRUCTURE => province.infrastructure case ImprovementType.DEVASTATION => province.economyDevastation + province.agricultureDevastation + province.infrastructureDevastation - case _ => throw new IllegalArgumentException("Illegal improvement type") + case _ => throw new IllegalArgumentException("Illegal improvement type") } private def chosenType( @@ -45,24 +42,23 @@ object ImproveCommandSelector { availableCommands: Vector[AvailableCommand], improvementType: ImprovementType ): Option[CommandSelection] = - flatSelectionForType[ImproveAvailableCommand](availableCommands) { - improveCommand => - val actingPid = improveCommand.actingProvinceId - Option.when( - actingPid == actingProvinceId && improveCommand.availableTypes - .contains(improvementType) - ) { - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = actingPid, - available = improveCommand, - selected = ImproveSelectedCommand( - improvementType = improvementType, - actingHeroId = improveCommand.recommendedHeroId - ), - reason = "chosenSpecificImprovementCommandForProvince" - ) - } + flatSelectionForType[ImproveAvailableCommand](availableCommands) { improveCommand => + val actingPid = improveCommand.actingProvinceId + Option.when( + actingPid == actingProvinceId && improveCommand.availableTypes + .contains(improvementType) + ) { + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = actingPid, + available = improveCommand, + selected = ImproveSelectedCommand( + improvementType = improvementType, + actingHeroId = improveCommand.recommendedHeroId + ), + reason = "chosenSpecificImprovementCommandForProvince" + ) + } } def chosenSpecificImprovementCommand( @@ -71,25 +67,24 @@ object ImproveCommandSelector { availableCommands: Vector[AvailableCommand], improvementType: ImprovementType ): Option[CommandSelection] = - flatSelectionForType[ImproveAvailableCommand](availableCommands) { - improveCommand => - val actingPid = improveCommand.actingProvinceId - Option.when(improveCommand.availableTypes.contains(improvementType)) { - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = actingPid, - available = improveCommand, - selected = ImproveSelectedCommand( - improvementType = improvementType, - actingHeroId = minimallyFatiguedHeroes( - improveCommand.availableHeroIds.toVector.map( - gameState.heroes(_) - ) - ).maxBy(LegacyHeroUtils.power(_)).id - ), - reason = "chosenSpecificImprovementCommand" - ) - } + flatSelectionForType[ImproveAvailableCommand](availableCommands) { improveCommand => + val actingPid = improveCommand.actingProvinceId + Option.when(improveCommand.availableTypes.contains(improvementType)) { + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = actingPid, + available = improveCommand, + selected = ImproveSelectedCommand( + improvementType = improvementType, + actingHeroId = minimallyFatiguedHeroes( + improveCommand.availableHeroIds.toVector.map( + gameState.heroes(_) + ) + ).maxBy(LegacyHeroUtils.power(_)).id + ), + reason = "chosenSpecificImprovementCommand" + ) + } } def commandSelection( @@ -120,8 +115,7 @@ object ImproveCommandSelector { gameState: GameState, availableCommands: Vector[AvailableCommand] ): Option[CommandSelection] = - selectionForType[ImproveAvailableCommand](availableCommands) { - improveCommand => - commandSelection(gameState, actingFactionId, improveCommand) + selectionForType[ImproveAvailableCommand](availableCommands) { improveCommand => + commandSelection(gameState, actingFactionId, improveCommand) } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelector.scala index d6f89c92e4..766da3dff5 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelector.scala @@ -2,15 +2,9 @@ package net.eagle0.eagle.library.util.command_choice_helpers import scala.annotation.tailrec -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - OrganizeTroopsAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, OrganizeTroopsAvailableCommand} import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand -import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand.{ - ChangedBattalion, - NewBattalion -} +import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand.{ChangedBattalion, NewBattalion} import net.eagle0.eagle.common.battalion_type.{BattalionType, BattalionTypeId} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.game_state.GameState @@ -50,7 +44,7 @@ object OrganizeCommandSelector { acc: Vector[ChangedBattalion] ): ChangedBattalionsResult = battalionsInNeed match { case b +: bs => - val missing = battalionType(b.`type`, battalionTypes).capacity - b.size + val missing = battalionType(b.`type`, battalionTypes).capacity - b.size val goldCost = (missing * costs(b.`type`)).ceil.toInt val foodCost = (missing * battalionType( @@ -99,8 +93,9 @@ object OrganizeCommandSelector { existingBattalions: Vector[Battalion], maxCount: Int = 100 ): NewBattalionsResult = { - val eligibleCosts = costs.filter { case (bid: BattalionTypeId, _: Double) => - eligibleBattalionTypeIds.contains(bid) + val eligibleCosts = costs.filter { + case (bid: BattalionTypeId, _: Double) => + eligibleBattalionTypeIds.contains(bid) } @tailrec @@ -109,7 +104,7 @@ object OrganizeCommandSelector { foodSurplus: Int, existingBattalionTypeCounts: Map[BattalionTypeId, Int], acc: Vector[NewBattalion] - ): NewBattalionsResult = { + ): NewBattalionsResult = if acc.size >= maxCount then NewBattalionsResult( newBattalions = acc, @@ -123,17 +118,17 @@ object OrganizeCommandSelector { monthlyFoodCost: Int ) - eligibleCosts.toVector - .map { case (tid, costPerTroop) => + eligibleCosts.toVector.map { + case (tid, costPerTroop) => val battalionType = BattalionTypeFinder.battalionType(tid, allBattalionTypes) - val cap = battalionType.capacity + val cap = battalionType.capacity FoodAndGoldCosts( battalionTypeId = tid, goldCost = (costPerTroop * cap).ceil.toInt, monthlyFoodCost = (cap * battalionType.monthlyFoodCost).ceil.toInt ) - } + } .filter(_.goldCost <= gold) .filter(_.monthlyFoodCost <= foodSurplus) .sortBy(fgc => @@ -148,8 +143,7 @@ object OrganizeCommandSelector { case Some(x) => val newBattalion = NewBattalion( `type` = x.battalionTypeId, - newTroops = - battalionType(x.battalionTypeId, allBattalionTypes).capacity + newTroops = battalionType(x.battalionTypeId, allBattalionTypes).capacity ) go( gold = gold - x.goldCost, @@ -159,7 +153,7 @@ object OrganizeCommandSelector { .getOrElse(x.battalionTypeId, 0) + 1)), acc = newBattalion +: acc ) - case None => + case None => NewBattalionsResult( newBattalions = acc, remainingGold = gold, @@ -167,14 +161,12 @@ object OrganizeCommandSelector { ) } } - } go( gold = gold, foodSurplus = foodSurplus, acc = Vector(), - existingBattalionTypeCounts = - existingBattalions.groupBy(_.`type`).map { case (k, v) => k -> v.size } + existingBattalionTypeCounts = existingBattalions.groupBy(_.`type`).map { case (k, v) => k -> v.size } ) } @@ -265,15 +257,14 @@ object OrganizeCommandSelector { extraFoodSurplus: Int, reason: String ): Option[CommandSelection] = - flatSelectionForType[OrganizeTroopsAvailableCommand](availableCommands) { - availableCommand => - selectedOrganizeCommand( - actingFactionId = actingFactionId, - availableCommand = availableCommand, - gameState = gameState, - extraFoodSurplus = extraFoodSurplus, - reason = reason - ) + flatSelectionForType[OrganizeTroopsAvailableCommand](availableCommands) { availableCommand => + selectedOrganizeCommand( + actingFactionId = actingFactionId, + availableCommand = availableCommand, + gameState = gameState, + extraFoodSurplus = extraFoodSurplus, + reason = reason + ) } def chosenOrganizeCommand( diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpers.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpers.scala index cb3b32d47d..ca24f5f4b8 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpers.scala @@ -28,8 +28,7 @@ object RansomOfferHelpers { RansomOfferBaseNegative.intValue def chosenResolution(ransomOffer: RansomOfferDetails): DiplomacyOfferStatus = - if RansomOfferHelpers.ransomOfferScore(ransomOffer) > 0 then - DIPLOMACY_OFFER_STATUS_ACCEPTED + if RansomOfferHelpers.ransomOfferScore(ransomOffer) > 0 then DIPLOMACY_OFFER_STATUS_ACCEPTED else DIPLOMACY_OFFER_STATUS_REJECTED private def sufficientTrust( @@ -74,9 +73,7 @@ object RansomOfferHelpers { _ /* unknownFieldSet */ ) => val nonFactionLeaderHostages = - hostagesOffered.filterNot(hoie => - LegacyFactionUtils.isFactionLeader(hoie.heroId, gameState) - ) + hostagesOffered.filterNot(hoie => LegacyFactionUtils.isFactionLeader(hoie.heroId, gameState)) Option.when( sufficientTrust( @@ -90,7 +87,7 @@ object RansomOfferHelpers { ) && (goldOffered > 0 || prisonersOffered.nonEmpty || nonFactionLeaderHostages.nonEmpty) ) { // first send all the prisoners - val minimalGold = Math.min(500, goldOffered) + val minimalGold = Math.min(500, goldOffered) val prisonerScore = prisonersOffered.size * RansomOfferScorePerPrisoner.intValue + minimalGold * RansomOfferScorePerGold.intValue + @@ -99,10 +96,10 @@ object RansomOfferHelpers { if prisonerScore > 0 then { availableOffer.update( _.hostagesOffered := Vector(), - _.goldOffered := minimalGold + _.goldOffered := minimalGold ) } else { - val moreGold = Math.max(0, goldOffered - 500) + val moreGold = Math.max(0, goldOffered - 500) val goldScore = prisonersOffered.size * RansomOfferScorePerPrisoner.intValue + minimalGold * RansomOfferScorePerGold.intValue + @@ -116,7 +113,7 @@ object RansomOfferHelpers { _.hostagesOffered := nonFactionLeaderHostages.take( hostageCount ), - _.goldOffered := moreGold + _.goldOffered := moreGold ) else availableOffer.update( diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwearBrotherhoodCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwearBrotherhoodCommandSelector.scala index 4da4750d9b..b128beab17 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwearBrotherhoodCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwearBrotherhoodCommandSelector.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.{FactionId, HeroId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - SwearBrotherhoodAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, SwearBrotherhoodAvailableCommand} import net.eagle0.eagle.api.selected_command.SwearBrotherhoodSelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.flatSelectionForType @@ -17,22 +14,19 @@ object SwearBrotherhoodCommandSelector { availableCommands: Vector[AvailableCommand], desiredHeroId: HeroId ): Option[CommandSelection] = - flatSelectionForType[SwearBrotherhoodAvailableCommand](availableCommands) { - swearBrotherhoodAvailableCommand => - Option.when( - swearBrotherhoodAvailableCommand.availableHeroes - .map(_.heroId) - .contains(desiredHeroId) - ) { - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = - swearBrotherhoodAvailableCommand.actingProvinceId, - available = swearBrotherhoodAvailableCommand, - selected = - SwearBrotherhoodSelectedCommand(newBrotherHeroId = desiredHeroId), - reason = "chose swear brotherhood" - ) - } + flatSelectionForType[SwearBrotherhoodAvailableCommand](availableCommands) { swearBrotherhoodAvailableCommand => + Option.when( + swearBrotherhoodAvailableCommand.availableHeroes + .map(_.heroId) + .contains(desiredHeroId) + ) { + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = swearBrotherhoodAvailableCommand.actingProvinceId, + available = swearBrotherhoodAvailableCommand, + selected = SwearBrotherhoodSelectedCommand(newBrotherHeroId = desiredHeroId), + reason = "chose swear brotherhood" + ) + } } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooser.scala index da9b115159..0954e29f15 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooser.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.internal.hero.Hero -import net.eagle0.eagle.library.settings.{ - AiMinimumCharismaForSwornBrother, - AiMinimumConstitutionForSwornBrother -} +import net.eagle0.eagle.library.settings.{AiMinimumCharismaForSwornBrother, AiMinimumConstitutionForSwornBrother} import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.HeroId @@ -13,7 +10,7 @@ object SwornBrotherChooser { def bestChoice( heroes: Iterable[Hero], leaders: Vector[HeroId] - ): Option[Hero] = { + ): Option[Hero] = heroes .filter(_.charisma >= AiMinimumCharismaForSwornBrother.doubleValue) .filter( @@ -21,13 +18,11 @@ object SwornBrotherChooser { ) .filterNot(h => leaders.contains(h.id)) .maxByOption(LegacyHeroUtils.power) - } - def desiredNumberOfLeaders(provinceCount: Int): Int = { + def desiredNumberOfLeaders(provinceCount: Int): Int = if provinceCount < 3 then 1 else if provinceCount < 6 then 2 else if provinceCount < 10 then 3 else if provinceCount < 15 then 4 else 5 - } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelector.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelector.scala index ebdc51eaa1..7d76d1d5b5 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelector.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelector.scala @@ -1,14 +1,8 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.{FactionId, HeroId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - DiplomacyAvailableCommand -} -import net.eagle0.eagle.api.command.util.diplomacy_option.{ - DiplomacyOption, - TruceOption -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, DiplomacyAvailableCommand} +import net.eagle0.eagle.api.command.util.diplomacy_option.{DiplomacyOption, TruceOption} import net.eagle0.eagle.api.selected_command.DiplomacySelectedCommand import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.AvailableCommandSelector.ofType @@ -27,8 +21,7 @@ object TruceOfferCommandSelector { targetFactionId: FactionId ): Option[TruceOption] = options.collectFirst { - case x @ TruceOption(tfid, _, _ /* unknownFieldSet */ ) - if tfid == targetFactionId => + case x @ TruceOption(tfid, _, _ /* unknownFieldSet */ ) if tfid == targetFactionId => x } @@ -38,32 +31,27 @@ object TruceOfferCommandSelector { availableCommands: Vector[AvailableCommand], targetFactionId: FactionId ): Option[CommandSelection] = - ofType[DiplomacyAvailableCommand](availableCommands) - .find { ac => - truceOptionWithTarget( - ac.options.toVector, - targetFactionId - ).isDefined && usableHeroIds( - ac.availableHeroIds.toVector, - gameState - ).nonEmpty - } - .map { ac => - CommandSelection( - actingFactionId = actingFactionId, - actingProvinceId = ac.actingProvinceId, - available = ac, - selected = DiplomacySelectedCommand( - selectedOption = - truceOptionWithTarget(ac.options.toVector, targetFactionId).get, - targetFactionId = targetFactionId, - sentHeroId = - usableHeroIds(ac.availableHeroIds.toVector, gameState).maxBy { - hid => - gameState.heroes(hid).vigor - } - ), - reason = "chosenTruceWithFactionCommand" - ) - } + ofType[DiplomacyAvailableCommand](availableCommands).find { ac => + truceOptionWithTarget( + ac.options.toVector, + targetFactionId + ).isDefined && usableHeroIds( + ac.availableHeroIds.toVector, + gameState + ).nonEmpty + }.map { ac => + CommandSelection( + actingFactionId = actingFactionId, + actingProvinceId = ac.actingProvinceId, + available = ac, + selected = DiplomacySelectedCommand( + selectedOption = truceOptionWithTarget(ac.options.toVector, targetFactionId).get, + targetFactionId = targetFactionId, + sentHeroId = usableHeroIds(ac.availableHeroIds.toVector, gameState).maxBy { hid => + gameState.heroes(hid).vigor + } + ), + reason = "chosenTruceWithFactionCommand" + ) + } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooser.scala index 379fda7c96..5ba16294f6 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooser.scala @@ -1,18 +1,12 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selectors import net.eagle0.common.{FunctionalRandom, RandomState} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - DiplomacyAvailableCommand -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, DiplomacyAvailableCommand} import net.eagle0.eagle.api.command.util.diplomacy_option.AllianceOption import net.eagle0.eagle.common.unaffiliated_hero_quest.AllianceQuest import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.ALLY import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.util.command_choice_helpers.{ - AllianceOfferCommandSelector, - TrustForDiplomacy -} +import net.eagle0.eagle.library.util.command_choice_helpers.{AllianceOfferCommandSelector, TrustForDiplomacy} import net.eagle0.eagle.library.util.CommandSelection import net.eagle0.eagle.FactionId @@ -26,17 +20,17 @@ object AllianceQuestCommandChooser extends QuestCommandChooser { ): RandomState[Option[CommandSelection]] = { val allianceTargets: Vector[FactionId] = availableCommands.collect { case cmd: DiplomacyAvailableCommand => - cmd.options - .collect { case alliance: AllianceOption => + cmd.options.collect { + case alliance: AllianceOption => alliance.targetFactionId - } + } }.flatten functionalRandom .nextFlatCollectFirst(uhsWithQuests.map(_.quest.details)) { case _: AllianceQuest => fr => - val actingFaction = gameState.factions(actingFactionId) + val actingFaction = gameState.factions(actingFactionId) val factionChoices = gameState.factions.values // only include factions that have eligible commands @@ -59,22 +53,20 @@ object AllianceQuestCommandChooser extends QuestCommandChooser { fr .nextShuffled(factionChoices) .map { factions => - factions - .maxByOption { faction => - actingFaction.factionRelationships - .find(_.targetFactionId == faction.id) - .map(_.trustValue) - .getOrElse(0) - } - .flatMap { faction => - AllianceOfferCommandSelector - .chosenAllianceWithFactionCommand( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - targetFactionId = faction.id - ) - } + factions.maxByOption { faction => + actingFaction.factionRelationships + .find(_.targetFactionId == faction.id) + .map(_.trustValue) + .getOrElse(0) + }.flatMap { faction => + AllianceOfferCommandSelector + .chosenAllianceWithFactionCommand( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + targetFactionId = faction.id + ) + } } } .map(_.map(_.withReason("fulfill Alliance quest"))) diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooser.scala index ad40ad0467..e02089ac50 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooser.scala @@ -1,17 +1,13 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selectors import net.eagle0.eagle.api.available_command.AvailableCommand -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - AlmsAcrossRealmQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{AlmsAcrossRealmQuest, Quest} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.AlmsCommandSelector import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.CommandSelection import net.eagle0.eagle.FactionId -object AlmsAcrossRealmQuestCommandChooser - extends DeterministicQuestCommandChooser { +object AlmsAcrossRealmQuestCommandChooser extends DeterministicQuestCommandChooser { private def maxRequestedAmount( uhsWithQuests: Seq[UnaffiliatedHeroWithQuest] ): Option[Int] = uhsWithQuests @@ -59,14 +55,13 @@ object AlmsAcrossRealmQuestCommandChooser availableCommands: Vector[AvailableCommand], uhsWithQuests: Vector[UnaffiliatedHeroWithQuest] ): Option[CommandSelection] = - maxRequestedAmount(uhsWithQuests) - .flatMap { amount => - bestCommand( - desiredAmount = amount, - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands - ) - } + maxRequestedAmount(uhsWithQuests).flatMap { amount => + bestCommand( + desiredAmount = amount, + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands + ) + } .map(_.withReason("fulfill AlmsAcrossRealm quest")) } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooser.scala index 8c8d0bb36d..fac9104749 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooser.scala @@ -6,8 +6,7 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.AlmsCommandSelector import net.eagle0.eagle.library.util.CommandSelection -object AlmsToProvinceQuestCommandChooser - extends DeterministicQuestCommandChooser { +object AlmsToProvinceQuestCommandChooser extends DeterministicQuestCommandChooser { override def chosenDeterministicCommand( actingFactionId: FactionId, gameState: GameState, @@ -29,14 +28,15 @@ object AlmsToProvinceQuestCommandChooser } .groupBy(_._1) .map { case (pid, amts) => (pid, amts.map(_._2).max) } - .flatMap { case (pid, amount) => - AlmsCommandSelector.chosenAlmsForSupportWithMinimumCommandForProvince( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - minimumFood = amount, - provinceId = pid - ) + .flatMap { + case (pid, amount) => + AlmsCommandSelector.chosenAlmsForSupportWithMinimumCommandForProvince( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + minimumFood = amount, + provinceId = pid + ) } .headOption .map(_.withReason("fulfill AlmsToProvince quest")) diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooser.scala index 68a75cef73..4c4fe8247e 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooser.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selec import net.eagle0.common.MoreOption import net.eagle0.common.MoreSeq.flatCollectFirst import net.eagle0.eagle.api.available_command.AvailableCommand -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - DismissSpecificVassalQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{DismissSpecificVassalQuest, Quest} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.settings.RequiredPowerMultiplierForDismiss import net.eagle0.eagle.library.util.command_choice_helpers.ExileVassalCommandSelector @@ -14,8 +11,7 @@ import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.CommandSelection import net.eagle0.eagle.FactionId -object DismissSpecificVassalCommandChooser - extends DeterministicQuestCommandChooser { +object DismissSpecificVassalCommandChooser extends DeterministicQuestCommandChooser { override def chosenDeterministicCommand( actingFactionId: FactionId, @@ -23,40 +19,39 @@ object DismissSpecificVassalCommandChooser availableCommands: Vector[AvailableCommand], uhsWithQuests: Vector[UnaffiliatedHeroWithQuest] ): Option[CommandSelection] = - uhsWithQuests - .flatCollectFirst { - case UnaffiliatedHeroWithQuest( - pid, - uh, - Quest( - _, - _, - DismissSpecificVassalQuest( - targetHeroId, - _ /* unknownFieldSet */ - ), + uhsWithQuests.flatCollectFirst { + case UnaffiliatedHeroWithQuest( + pid, + uh, + Quest( + _, + _, + DismissSpecificVassalQuest( + targetHeroId, _ /* unknownFieldSet */ + ), + _ /* unknownFieldSet */ + ) + ) => + MoreOption.flatWhen( + // Don't exile a vassal that would leave the faction leader here by themselves + gameState.provinces(pid).rulingFactionHeroIds.size > 2 && + // Don't exile a vassal unless they're much less powerful than the hero that would replace them + LegacyHeroUtils.power(gameState.heroes(uh.heroId)) >= + RequiredPowerMultiplierForDismiss.doubleValue * LegacyHeroUtils + .power( + gameState.heroes(targetHeroId) ) - ) => - MoreOption.flatWhen( - // Don't exile a vassal that would leave the faction leader here by themselves - gameState.provinces(pid).rulingFactionHeroIds.size > 2 && - // Don't exile a vassal unless they're much less powerful than the hero that would replace them - LegacyHeroUtils.power(gameState.heroes(uh.heroId)) >= - RequiredPowerMultiplierForDismiss.doubleValue * LegacyHeroUtils - .power( - gameState.heroes(targetHeroId) - ) - ) { - ExileVassalCommandSelector - .chosenSpecificDismissVassalCommandForProvince( - actingFactionId = actingFactionId, - actingProvinceId = pid, - gameState = gameState, - availableCommands = availableCommands, - dismissedHeroId = targetHeroId, - reason = "fulfill DismissSpecificVassal quest" - ) - } - } + ) { + ExileVassalCommandSelector + .chosenSpecificDismissVassalCommandForProvince( + actingFactionId = actingFactionId, + actingProvinceId = pid, + gameState = gameState, + availableCommands = availableCommands, + dismissedHeroId = targetHeroId, + reason = "fulfill DismissSpecificVassal quest" + ) + } + } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooser.scala index c855acc443..e31dca27c1 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooser.scala @@ -1,17 +1,13 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selectors import net.eagle0.eagle.api.available_command.AvailableCommand -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - GiveToHeroesAcrossRealmQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{GiveToHeroesAcrossRealmQuest, Quest} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.HeroGiftCommandSelector import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.CommandSelection import net.eagle0.eagle.FactionId -object GiveToHeroesAcrossRealmQuestCommandChooser - extends DeterministicQuestCommandChooser { +object GiveToHeroesAcrossRealmQuestCommandChooser extends DeterministicQuestCommandChooser { private def maxRequestedAmount( uhsWithQuests: Seq[UnaffiliatedHeroWithQuest] ): Option[Int] = uhsWithQuests @@ -55,14 +51,13 @@ object GiveToHeroesAcrossRealmQuestCommandChooser availableCommands: Vector[AvailableCommand], uhsWithQuests: Vector[UnaffiliatedHeroWithQuest] ): Option[CommandSelection] = - maxRequestedAmount(uhsWithQuests) - .flatMap { amount => - bestCommand( - desiredAmount = amount, - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands - ) - } + maxRequestedAmount(uhsWithQuests).flatMap { amount => + bestCommand( + desiredAmount = amount, + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands + ) + } .map(_.withReason("fulfill GiveToHeroesAcrossRealm quest")) } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooser.scala index e09a3807b7..991e012f04 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooser.scala @@ -7,8 +7,7 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.library.util.command_choice_helpers.HeroGiftCommandSelector import net.eagle0.eagle.library.util.CommandSelection -object GiveToHeroesInProvinceQuestCommandChooser - extends DeterministicQuestCommandChooser { +object GiveToHeroesInProvinceQuestCommandChooser extends DeterministicQuestCommandChooser { override def chosenDeterministicCommand( actingFactionId: FactionId, gameState: GameState, @@ -16,9 +15,7 @@ object GiveToHeroesInProvinceQuestCommandChooser uhsWithQuests: Vector[UnaffiliatedHeroWithQuest] ): Option[CommandSelection] = uhsWithQuests - .map(uhwq => - (uhwq.pid, uhwq.quest.details, uhwq.quest.componentsFulfilled) - ) + .map(uhwq => (uhwq.pid, uhwq.quest.details, uhwq.quest.componentsFulfilled)) .collect { case ( pid, @@ -32,17 +29,19 @@ object GiveToHeroesInProvinceQuestCommandChooser (pid, amount - amountCompleted) } .groupBy(_._1) // Group all the quests of this type for this province - .map { case (pid, amts) => - (pid, amts.map(_._2).max) + .map { + case (pid, amts) => + (pid, amts.map(_._2).max) } // Grab the maximum amount desired for all such quests for this province - .flatMap { case (pid, amountRemaining) => - HeroGiftCommandSelector.chosenCommandForLowestLoyaltyHero( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - provinceId = pid, - maxAmount = amountRemaining - ) + .flatMap { + case (pid, amountRemaining) => + HeroGiftCommandSelector.chosenCommandForLowestLoyaltyHero( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + provinceId = pid, + maxAmount = amountRemaining + ) } .headOption .map(_.withReason("fulfill GiveToHeroesInProvince quest")) diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/ImproveQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/ImproveQuestCommandChooser.scala index e270d6c609..50d3fd5b7d 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/ImproveQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/ImproveQuestCommandChooser.scala @@ -1,11 +1,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selectors import net.eagle0.eagle.api.available_command.AvailableCommand -import net.eagle0.eagle.common.improvement_type.ImprovementType.{ - AGRICULTURE, - ECONOMY, - INFRASTRUCTURE -} +import net.eagle0.eagle.common.improvement_type.ImprovementType.{AGRICULTURE, ECONOMY, INFRASTRUCTURE} import net.eagle0.eagle.common.unaffiliated_hero_quest.{ ImproveAgricultureQuest, ImproveEconomyQuest, @@ -30,13 +26,14 @@ object ImproveQuestCommandChooser extends DeterministicQuestCommandChooser { case (pid, _: ImproveAgricultureQuest) => (pid, AGRICULTURE) case (pid, _: ImproveInfrastructureQuest) => (pid, INFRASTRUCTURE) } - .flatMap { case (pid, it) => - ImproveCommandSelector.chosenSpecificImprovementCommandForProvince( - actingFactionId = actingFactionId, - actingProvinceId = pid, - availableCommands = availableCommands, - improvementType = it - ) + .flatMap { + case (pid, it) => + ImproveCommandSelector.chosenSpecificImprovementCommandForProvince( + actingFactionId = actingFactionId, + actingProvinceId = pid, + availableCommands = availableCommands, + improvementType = it + ) } .headOption .map(_.withReason("fulfill Improve quest")) diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceCountQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceCountQuestCommandChooser.scala index 3dd141536e..a8aa41f68f 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceCountQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceCountQuestCommandChooser.scala @@ -4,10 +4,7 @@ import net.eagle0.common.{FunctionalRandom, RandomState} import net.eagle0.eagle.api.available_command.AvailableCommand import net.eagle0.eagle.common.unaffiliated_hero_quest.TruceCountQuest import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.util.command_choice_helpers.{ - TruceOfferCommandSelector, - TrustForDiplomacy -} +import net.eagle0.eagle.library.util.command_choice_helpers.{TruceOfferCommandSelector, TrustForDiplomacy} import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.CommandSelection import net.eagle0.eagle.FactionId @@ -19,12 +16,12 @@ object TruceCountQuestCommandChooser extends QuestCommandChooser { availableCommands: Vector[AvailableCommand], uhsWithQuests: Vector[UnaffiliatedHeroWithQuest], functionalRandom: FunctionalRandom - ): RandomState[Option[CommandSelection]] = { + ): RandomState[Option[CommandSelection]] = functionalRandom .nextFlatCollectFirst(uhsWithQuests.map(_.quest.details)) { case _: TruceCountQuest => fr => - val actingFaction = gameState.factions(actingFactionId) + val actingFaction = gameState.factions(actingFactionId) val factionChoices = gameState.factions.values .filterNot(_.id == actingFactionId) @@ -44,28 +41,26 @@ object TruceCountQuestCommandChooser extends QuestCommandChooser { fr .nextShuffled(factionChoices) .map { factions => - factions - .flatMap { faction => - TruceOfferCommandSelector - .chosenTruceWithFactionCommand( - actingFactionId = actingFactionId, - gameState = gameState, - availableCommands = availableCommands, - targetFactionId = faction.id - ) - .map { cmd => - (faction.id, cmd) - } - } - .maxByOption { case (fid, _) => + factions.flatMap { faction => + TruceOfferCommandSelector + .chosenTruceWithFactionCommand( + actingFactionId = actingFactionId, + gameState = gameState, + availableCommands = availableCommands, + targetFactionId = faction.id + ) + .map { cmd => + (faction.id, cmd) + } + }.maxByOption { + case (fid, _) => actingFaction.factionRelationships .find(_.targetFactionId == fid) .map(_.trustValue) .getOrElse(0) - } + } .map(_._2) } } .map(_.map(_.withReason("fulfill TruceCount quest"))) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceWithFactionQuestCommandChooser.scala b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceWithFactionQuestCommandChooser.scala index 92fec516fa..27325112de 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceWithFactionQuestCommandChooser.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/TruceWithFactionQuestCommandChooser.scala @@ -3,15 +3,11 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selec import net.eagle0.eagle.api.available_command.AvailableCommand import net.eagle0.eagle.common.unaffiliated_hero_quest.TruceWithFactionQuest import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.util.command_choice_helpers.{ - TruceOfferCommandSelector, - TrustForDiplomacy -} +import net.eagle0.eagle.library.util.command_choice_helpers.{TruceOfferCommandSelector, TrustForDiplomacy} import net.eagle0.eagle.library.util.CommandSelection import net.eagle0.eagle.FactionId -object TruceWithFactionQuestCommandChooser - extends DeterministicQuestCommandChooser { +object TruceWithFactionQuestCommandChooser extends DeterministicQuestCommandChooser { override def chosenDeterministicCommand( actingFactionId: FactionId, gameState: GameState, diff --git a/src/main/scala/net/eagle0/eagle/library/util/faction_utils/FactionUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/faction_utils/FactionUtils.scala index 112f3952c2..ca7ec4cd65 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/faction_utils/FactionUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/faction_utils/FactionUtils.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.faction_utils import net.eagle0.eagle.{FactionId, HeroId} -import net.eagle0.eagle.library.settings.{ - MinSupportForTaxes, - PrestigePerSupportedProvince -} +import net.eagle0.eagle.library.settings.{MinSupportForTaxes, PrestigePerSupportedProvince} import net.eagle0.eagle.model.state.faction.{FactionRelationship, FactionT} import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.Ally import net.eagle0.eagle.model.state.province.ProvinceT @@ -74,9 +71,7 @@ object FactionUtils { else if province.rulingFactionHeroIds .exists(hid => faction.leaderIds.contains(hid)) then 3 - else if incomingHids(province).exists(hid => - faction.leaderIds.contains(hid) - ) + else if incomingHids(province).exists(hid => faction.leaderIds.contains(hid)) then 2 else 1 diff --git a/src/main/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtils.scala index 05d04f6b42..15daa8fdf3 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtils.scala @@ -8,14 +8,11 @@ import net.eagle0.eagle.internal.faction_relationship.FactionRelationship import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - MinSupportForTaxes, - PrestigePerSupportedProvince -} +import net.eagle0.eagle.library.settings.{MinSupportForTaxes, PrestigePerSupportedProvince} object LegacyFactionUtils { private val sortIgnoredChars: Set[Char] = "\"“”\'‘’".toSet - def sortKey(faction: Faction): String = + def sortKey(faction: Faction): String = faction.name.filterNot(sortIgnoredChars) def factionRelationship( @@ -121,9 +118,7 @@ object LegacyFactionUtils { fids: Vector[FactionId], gs: GameState ): Boolean = - fids.forall(fid1 => - fids.forall(fid2 => !factionsAreHostile(fid1, fid2, gs)) - ) + fids.forall(fid1 => fids.forall(fid2 => !factionsAreHostile(fid1, fid2, gs))) def hostileNeighbors( pid: ProvinceId, @@ -142,9 +137,7 @@ object LegacyFactionUtils { .map(gs.provinces) .filter(_.rulingFactionId.isDefined) .filterNot(_.rulingFactionId.contains(fid)) - .filterNot(neighbor => - hasTruceOrAlliance(fid, neighbor.rulingFactionId.get, gs) - ) + .filterNot(neighbor => hasTruceOrAlliance(fid, neighbor.rulingFactionId.get, gs)) .toVector def neutralNeighbors( @@ -162,7 +155,7 @@ object LegacyFactionUtils { fid1: FactionId, fid2: FactionId, gs: GameState - ): Option[Date] = { + ): Option[Date] = factionRelationship(fid1, fid2, gs) match { case FactionRelationship( _: FactionId, @@ -174,7 +167,6 @@ object LegacyFactionUtils { resetDate case _ => None } - } def hasTruce( fid1: FactionId, @@ -230,8 +222,7 @@ object LegacyFactionUtils { gs: GameState ): Hostility = if fid1 == fid2 then Hostility.SELF_HOSTILITY - else if LegacyFactionUtils.factionsAreHostile(fid1, fid2, gs) then - Hostility.ENEMY_HOSTILITY + else if LegacyFactionUtils.factionsAreHostile(fid1, fid2, gs) then Hostility.ENEMY_HOSTILITY else Hostility.ALLIED_HOSTILITY def factionsAreHostile( diff --git a/src/main/scala/net/eagle0/eagle/library/util/hero/HeroUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/hero/HeroUtils.scala index eed78d4c03..b98dcbb821 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/hero/HeroUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/hero/HeroUtils.scala @@ -16,7 +16,7 @@ object HeroUtils { + professionPower(hero) ) - private def professionPowerValue = 200.0 + private def professionPowerValue = 200.0 private def professionPower(hero: HeroT): Double = if hero.profession == NoProfession then 0.0 else professionPowerValue @@ -50,15 +50,16 @@ object HeroUtils { def sortOrderer( factionLeaderIds: Vector[HeroId] - ): (HeroT, HeroT) => Boolean = { case (h1, h2) => - @tailrec def go(keys: Vector[(Int, Int)]): Boolean = keys match { - case (key1, key2) +: t => - if key1 == key2 then go(t) - else key1 > key2 - case _ => false - } + ): (HeroT, HeroT) => Boolean = { + case (h1, h2) => + @tailrec def go(keys: Vector[(Int, Int)]): Boolean = keys match { + case (key1, key2) +: t => + if key1 == key2 then go(t) + else key1 > key2 + case _ => false + } - go(sortKeys(h1, factionLeaderIds).zip(sortKeys(h2, factionLeaderIds))) + go(sortKeys(h1, factionLeaderIds).zip(sortKeys(h2, factionLeaderIds))) } def sortOrdering(factionLeaderIds: Vector[HeroId]): Ordering[HeroT] = diff --git a/src/main/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtils.scala index b079adad17..51db01f966 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtils.scala @@ -64,7 +64,7 @@ object LegacyHeroUtils { case (key1, key2) +: t => if key1 == key2 then go(t) else key1 > key2 - case _ => false + case _ => false } go(sortKeys(gameState, hid1).zip(sortKeys(gameState, hid2))) } @@ -117,8 +117,7 @@ object LegacyHeroUtils { gs.heroes(hid).factionId.map(gs.factions) def effectiveLoyalty(hid: HeroId, gs: GameState): Double = - if LegacyFactionUtils.isFactionLeader(gameState = gs, heroId = hid) then - 100.0 + if LegacyFactionUtils.isFactionLeader(gameState = gs, heroId = hid) then 100.0 else gs.heroes(hid).loyalty def loyaltyAsStatWithCondition( @@ -165,7 +164,7 @@ object LegacyHeroUtils { def fatigue(hero: Hero): Double = hero.constitution - hero.vigor - def archeryCapable(hero: Hero): Boolean = + def archeryCapable(hero: Hero): Boolean = hero.agility >= MinimumAgilityForArchery.doubleValue def startFireCapable(hero: Hero): Boolean = hero.profession.isMage || diff --git a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/HeroGenerator.scala b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/HeroGenerator.scala index 757817c4ce..e9c992dca2 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/HeroGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/HeroGenerator.scala @@ -42,8 +42,7 @@ class HeroGenerator( private var remainingPregeneratedHeroes: Vector[HeroWithName] = if shuffledPregeneratedHeroes == null || shuffledPregeneratedHeroes.isEmpty then Vector() - else - shuffledPregeneratedHeroes.filterNot(h => excludingNames.contains(h.name)) + else shuffledPregeneratedHeroes.filterNot(h => excludingNames.contains(h.name)) private def getPregeneratedHero(hid: HeroId): HeroGenerationResponse = { if remainingPregeneratedHeroes.isEmpty then diff --git a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/image_paths/ImagePaths.scala b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/image_paths/ImagePaths.scala index 4be93637ad..46c962a109 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/image_paths/ImagePaths.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/image_paths/ImagePaths.scala @@ -14,12 +14,12 @@ object ImagePaths { private val professionStringMap: Map[String, Profession] = Map( "no_profession" -> NoProfession, - "mage" -> Mage, - "engineer" -> Engineer, - "necromancer" -> Necromancer, - "paladin" -> Paladin, - "ranger" -> Ranger, - "champion" -> Champion + "mage" -> Mage, + "engineer" -> Engineer, + "necromancer" -> Necromancer, + "paladin" -> Paladin, + "ranger" -> Ranger, + "champion" -> Champion ) val imagePathsByProfession: Map[(Profession, Gender), Set[String]] = { @@ -38,9 +38,8 @@ object ImagePaths { case "fixed" => acc case profName => // grab "male" or "female" out of the path - val byGender = thisSet - .groupBy { path => path.split("/")(1) } - .map { case (genderString, paths) => + val byGender = thisSet.groupBy(path => path.split("/")(1)).map { + case (genderString, paths) => ( ( professionStringMap(profName), @@ -48,7 +47,7 @@ object ImagePaths { ), paths.toSet ) - } + } acc ++ byGender } ) @@ -66,6 +65,6 @@ object ImagePaths { case "male" => Gender.Male case "other" => Gender.Other case "nonbinary" => Gender.Other - case _ => throw new EagleInternalException("unknown gender string") + case _ => throw new EagleInternalException("unknown gender string") } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/name_info/NameInfo.scala b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/name_info/NameInfo.scala index 49c9f70682..1e9843564a 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/name_info/NameInfo.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/name_info/NameInfo.scala @@ -3,6 +3,6 @@ package net.eagle0.eagle.library.util.hero_generator.name_info import net.eagle0.eagle.model.state.hero.Gender sealed trait NameInfo -case object NoNameRequest extends NameInfo -case class FixedName(nameId: String, name: String) extends NameInfo +case object NoNameRequest extends NameInfo +case class FixedName(nameId: String, name: String) extends NameInfo case class NameRequest(nameId: String, gender: Gender) extends NameInfo diff --git a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/random_hero_generator/RandomHeroGenerator.scala b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/random_hero_generator/RandomHeroGenerator.scala index bbc4169188..24bc23dcf9 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/hero_generator/random_hero_generator/RandomHeroGenerator.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/hero_generator/random_hero_generator/RandomHeroGenerator.scala @@ -23,20 +23,20 @@ import net.eagle0.eagle.model.state.hero.Profession.{ import net.eagle0.eagle.HeroId object RandomHeroGenerator { - private val primeStatMin = 85 + private val primeStatMin = 85 private val constitutionMin = 60 - private val statMax = 100 - private val statMin = 1 + private val statMax = 100 + private val statMin = 1 private def withProfessionAndPrimeStat( bh: HeroC, fr: FunctionalRandom ): RandomState[HeroC] = - primeStat(fr) - .continue { case (ps, nextRandom) => + primeStat(fr).continue { + case (ps, nextRandom) => nextRandom.nextInt(0, 125).map { - case 1 | 2 => bh.withProfession(Mage).copy(wisdom = ps) - case 3 | 4 => + case 1 | 2 => bh.withProfession(Mage).copy(wisdom = ps) + case 3 | 4 => bh.withProfession(Necromancer).copy(charisma = ps) case 5 | 6 | 7 | 8 | 9 => bh.withProfession(Engineer).copy(agility = ps) @@ -46,9 +46,9 @@ object RandomHeroGenerator { bh.withProfession(Ranger).copy(agility = ps) case 18 | 19 | 20 | 21 => bh.withProfession(Champion).copy(strength = ps) - case _ => bh.withProfession(NoProfession) + case _ => bh.withProfession(NoProfession) } - } + } def withNoProfession(bh: HeroC, fr: FunctionalRandom): RandomState[HeroC] = RandomState(bh.withProfession(NoProfession), fr) @@ -72,19 +72,18 @@ object RandomHeroGenerator { else RandomState(gender, fr) private def gender(random: FunctionalRandom): RandomState[Gender] = - random.nextDouble - .map { d => - if d < 0.47 then Female - else if d < 0.94 then Male - else Other - } + random.nextDouble.map { d => + if d < 0.47 then Female + else if d < 0.94 then Male + else Other + } private def heroWithBaseStats( gender: Gender, fr: FunctionalRandom ): RandomState[HeroC] = - fr.nextInt(constitutionMin, 100) - .continue { case (constitution, fr) => + fr.nextInt(constitutionMin, 100).continue { + case (constitution, fr) => fr.nextItems(8, normalStat).continue { case ( Vector( @@ -99,61 +98,56 @@ object RandomHeroGenerator { ), innerFr ) => - RandomHeroPersonalities.randomPersonalityWords(3, innerFr).map { - personalityWords => - HeroC( - id = -1, - strength = strength, - agility = agility, - constitution = constitution, - charisma = charisma, - wisdom = wisdom, - integrity = integrity, - ambition = ambition, - gregariousness = gregariousness, - bravery = bravery, - vigor = constitution, - pronounGender = gender, - personalityWords = personalityWords - ) + RandomHeroPersonalities.randomPersonalityWords(3, innerFr).map { personalityWords => + HeroC( + id = -1, + strength = strength, + agility = agility, + constitution = constitution, + charisma = charisma, + wisdom = wisdom, + integrity = integrity, + ambition = ambition, + gregariousness = gregariousness, + bravery = bravery, + vigor = constitution, + pronounGender = gender, + personalityWords = personalityWords + ) } case _ => throw new EagleInternalException("Got a bad set of stats") } - } + } private def createOne( functionalRandom: FunctionalRandom, gender: Gender, remainingImagePathsByProfession: (Profession, Gender) => Set[String] ): RandomState[HeroC] = - heroWithBaseStats(gender, functionalRandom) - .continue { withProfessionAndPrimeStat } - .continue { case (hero, nextRandom) => + heroWithBaseStats(gender, functionalRandom).continue(withProfessionAndPrimeStat).continue { + case (hero, nextRandom) => imagePathForProfessionAndGender( random = nextRandom, profession = hero.profession, gender = gender, remainingImagePathsByProfession = remainingImagePathsByProfession - ) - .map { ip => hero.copy(imagePath = ip) } - } + ).map(ip => hero.copy(imagePath = ip)) + } private def createOneWithNoProfession( functionalRandom: FunctionalRandom, gender: Gender, remainingImagePathsByProfession: (Profession, Gender) => Set[String] ): RandomState[HeroC] = - heroWithBaseStats(gender, functionalRandom) - .continue { withNoProfession } - .continue { case (hero, nextRandom) => + heroWithBaseStats(gender, functionalRandom).continue(withNoProfession).continue { + case (hero, nextRandom) => imagePathForProfessionAndGender( random = nextRandom, profession = hero.profession, gender = gender, remainingImagePathsByProfession = remainingImagePathsByProfession - ) - .map { ip => hero.copy(imagePath = ip) } - } + ).map(ip => hero.copy(imagePath = ip)) + } // Caller should update remainingImagePathsByProfession based on the result def createHeroes( @@ -166,34 +160,34 @@ object RandomHeroGenerator { .foldLeft( RandomState(Vector[HeroGenerationResponse](), functionalRandom), remainingImagePathsByProfession - ) { case ((RandomState(accHeroes, fr), accPaths), hid) => - gender(fr) match { - case RandomState(g, newFr) => - createOne(newFr, g, accPaths) match { - case RandomState(newHero, innerFr) => - val nameTextId = s"hn_$hid" - ( - RandomState( - accHeroes :+ HeroGenerationResponse( - hero = newHero.copy( - id = hid, - nameTextId = nameTextId, - backstoryVersions = Vector( - BackstoryVersion( - textId = s"hero_${hid}_backstory_0", - date = date + ) { + case ((RandomState(accHeroes, fr), accPaths), hid) => + gender(fr) match { + case RandomState(g, newFr) => + createOne(newFr, g, accPaths) match { + case RandomState(newHero, innerFr) => + val nameTextId = s"hn_$hid" + ( + RandomState( + accHeroes :+ HeroGenerationResponse( + hero = newHero.copy( + id = hid, + nameTextId = nameTextId, + backstoryVersions = Vector( + BackstoryVersion( + textId = s"hero_${hid}_backstory_0", + date = date + ) ) - ) + ), + nameInfo = NameRequest(nameId = nameTextId, gender = g) ), - nameInfo = NameRequest(nameId = nameTextId, gender = g) + innerFr ), - innerFr - ), - (p: Profession, g: Gender) => - accPaths(p, g) - newHero.imagePath - ) - } - } + (p: Profession, g: Gender) => accPaths(p, g) - newHero.imagePath + ) + } + } } ._1 @@ -208,34 +202,34 @@ object RandomHeroGenerator { .foldLeft( RandomState(Vector[HeroGenerationResponse](), functionalRandom), remainingImagePathsByProfession - ) { case ((RandomState(accHeroes, fr), accPaths), hid) => - gender(fr) match { - case RandomState(g, newFr) => - createOneWithNoProfession(newFr, g, accPaths) match { - case RandomState(newHero, innerFr) => - val nameTextId = s"hn_$hid" - ( - RandomState( - accHeroes :+ HeroGenerationResponse( - hero = newHero.copy( - id = hid, - nameTextId = nameTextId, - backstoryVersions = Vector( - BackstoryVersion( - textId = s"hero_${hid}_backstory_0", - date = date + ) { + case ((RandomState(accHeroes, fr), accPaths), hid) => + gender(fr) match { + case RandomState(g, newFr) => + createOneWithNoProfession(newFr, g, accPaths) match { + case RandomState(newHero, innerFr) => + val nameTextId = s"hn_$hid" + ( + RandomState( + accHeroes :+ HeroGenerationResponse( + hero = newHero.copy( + id = hid, + nameTextId = nameTextId, + backstoryVersions = Vector( + BackstoryVersion( + textId = s"hero_${hid}_backstory_0", + date = date + ) ) - ) + ), + nameInfo = NameRequest(nameId = nameTextId, gender = g) ), - nameInfo = NameRequest(nameId = nameTextId, gender = g) + innerFr ), - innerFr - ), - (p: Profession, g: Gender) => - accPaths(p, g) - newHero.imagePath - ) - } - } + (p: Profession, g: Gender) => accPaths(p, g) - newHero.imagePath + ) + } + } } ._1 @@ -245,8 +239,8 @@ object RandomHeroGenerator { gender: Gender, remainingImagePathsByProfession: (Profession, Gender) => Set[String] ): RandomState[String] = - imageGender(gender, random) - .continue { case (imageGender, rand0) => + imageGender(gender, random).continue { + case (imageGender, rand0) => val paths = remainingImagePathsByProfession(profession, imageGender) if paths.isEmpty then throw new InsufficientResourcesException( @@ -254,5 +248,5 @@ object RandomHeroGenerator { ) rand0.nextRandomElement(paths.toVector) - } + } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/hero_name_fetcher/HeroNameFetcher.scala b/src/main/scala/net/eagle0/eagle/library/util/hero_name_fetcher/HeroNameFetcher.scala index c2b435f57d..71ff26dc3c 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/hero_name_fetcher/HeroNameFetcher.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/hero_name_fetcher/HeroNameFetcher.scala @@ -65,7 +65,7 @@ object HeroNameFetcher { } then names(genderStrings, excludingNames) else Success(retrievedNames) - case f: Failure[?] => f + case f: Failure[?] => f } } @@ -78,11 +78,11 @@ object HeroNameFetcher { parsedJson \ "names" match { case JArray(nameArray) => nameArray.map { nameObj => - val id = (nameObj \ "id").extract[String] + val id = (nameObj \ "id").extract[String] val name = (nameObj \ "name").extract[String] NameResponse(id, name) }.toVector - case _ => throw new Exception("Expected 'names' array in response") + case _ => throw new Exception("Expected 'names' array in response") } }.map { names => names.map(_.name) diff --git a/src/main/scala/net/eagle0/eagle/library/util/province/LegacyProvinceUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/province/LegacyProvinceUtils.scala index ac3c7bd868..e03a07080f 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/province/LegacyProvinceUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/province/LegacyProvinceUtils.scala @@ -72,9 +72,9 @@ object LegacyProvinceUtils { province ) + effectiveInfrastructure(province))).toInt - def effectiveEconomy(province: Province): Double = + def effectiveEconomy(province: Province): Double = (province.economy - province.economyDevastation).max(0.0) - def effectiveAgriculture(province: Province): Double = + def effectiveAgriculture(province: Province): Double = (province.agriculture - province.agricultureDevastation).max(0.0) def effectiveInfrastructure(province: Province): Double = (province.infrastructure - province.infrastructureDevastation).max(0.0) @@ -87,7 +87,7 @@ object LegacyProvinceUtils { def annualGoldProduction( provinceId: ProvinceId, gameState: GameState - ): Option[Int] = { + ): Option[Int] = Option.when( gameState.provinces(provinceId).support >= MinSupportForTaxes.doubleValue )( @@ -95,13 +95,12 @@ object LegacyProvinceUtils { gameState.provinces(provinceId) ) * GoldIncreasePerEconomy.doubleValue).toInt ) - } def monthlyFoodSurplus(gameState: GameState, provinceId: ProvinceId): Int = { val monthlyConsumption = monthlyFoodConsumption(provinceId, gameState) - val monthsRemaining = 12 - gameState.currentDate.get.month - val monthlyAvailable = + val monthsRemaining = 12 - gameState.currentDate.get.month + val monthlyAvailable = if monthsRemaining == 0 then Int.MaxValue else gameState.provinces(provinceId).food / monthsRemaining val monthlyProduction = annualFoodProduction(provinceId, gameState) @@ -135,7 +134,7 @@ object LegacyProvinceUtils { ) * FoodIncreasePerAgriculture.doubleValue).toInt ) - def absoluteFoodSurplus(provinceId: ProvinceId, gameState: GameState): Int = { + def absoluteFoodSurplus(provinceId: ProvinceId, gameState: GameState): Int = if annualFoodProduction(provinceId, gameState).getOrElse( 0 ) / 12 < monthlyFoodConsumption( @@ -148,7 +147,6 @@ object LegacyProvinceUtils { provinceId, gameState ) * (12 - gameState.currentDate.get.month)).max(0) - } def provinceLeader( startingProvince: Province, @@ -157,17 +155,16 @@ object LegacyProvinceUtils { for { rulingFactionId <- startingProvince.rulingFactionId rulingFactionHeroIds = startingProvince.rulingFactionHeroIds - rulingPlayerHeroes = rulingFactionHeroIds.map(gameState.heroes) - faction = gameState.factions(rulingFactionId) - factionHead = faction.factionHeadId - presentLeaders = rulingFactionHeroIds - .intersect(faction.leaders) - .map(gameState.heroes) - } yield { + rulingPlayerHeroes = rulingFactionHeroIds.map(gameState.heroes) + faction = gameState.factions(rulingFactionId) + factionHead = faction.factionHeadId + presentLeaders = rulingFactionHeroIds + .intersect(faction.leaders) + .map(gameState.heroes) + } yield if rulingFactionHeroIds.contains(factionHead) then factionHead else if presentLeaders.nonEmpty then preferredLeader(presentLeaders).id else preferredLeader(rulingPlayerHeroes).id - } private def preferredLeader(heroes: Iterable[Hero]): Hero = heroes.maxBy(_.wisdom) @@ -175,8 +172,8 @@ object LegacyProvinceUtils { def rulerSenioritySortOrder(province: Province, gameState: GameState): Int = (for { rulingFactionId <- province.rulingFactionId - rulingHeroId <- province.rulingHeroId - faction <- gameState.factions.get(rulingFactionId) + rulingHeroId <- province.rulingHeroId + faction <- gameState.factions.get(rulingFactionId) } yield faction.leaders.indexOf(rulingHeroId) match { case -1 => Int.MaxValue case x => x @@ -185,8 +182,8 @@ object LegacyProvinceUtils { def ruledByFactionLeader(province: Province, gameState: GameState): Boolean = (for { rulingFactionId <- province.rulingFactionId - rulingHeroId <- province.rulingHeroId - faction <- gameState.factions.get(rulingFactionId) + rulingHeroId <- province.rulingHeroId + faction <- gameState.factions.get(rulingFactionId) } yield faction.leaders.contains(rulingHeroId)) .getOrElse(false) @@ -239,23 +236,22 @@ object LegacyProvinceUtils { changedProvince: ChangedProvince ): ChangedProvince = changedProvince.update( - _.clearRulingFactionId := true, - _.removedBattalionIds := province.battalionIds, - _.supportDelta := -province.support, - _.newProvinceOrders := ProvinceOrdersOption(UNKNOWN_ORDERS), - _.goldDelta := -province.gold, - _.foodDelta := -province.food, + _.clearRulingFactionId := true, + _.removedBattalionIds := province.battalionIds, + _.supportDelta := -province.support, + _.newProvinceOrders := ProvinceOrdersOption(UNKNOWN_ORDERS), + _.goldDelta := -province.gold, + _.foodDelta := -province.food, _.removedRulingPlayerHeroIds := province.rulingFactionHeroIds, - _.newUnaffiliatedHeroes := province.rulingFactionHeroIds.map(hid => + _.newUnaffiliatedHeroes := province.rulingFactionHeroIds.map(hid => UnaffiliatedHero( heroId = hid, `type` = UNAFFILIATED_HERO_TRAVELER, roundsInType = 0, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ) ), - _.changedUnaffiliatedHeroes := province.unaffiliatedHeroes.map { uh => + _.changedUnaffiliatedHeroes := province.unaffiliatedHeroes.map { uh => uh.update( _.`type`.modify { case UNAFFILIATED_HERO_PRISONER => UNAFFILIATED_HERO_OUTLAW @@ -263,14 +259,14 @@ object LegacyProvinceUtils { case x => x }, _.recruitmentInfo := RecruitmentInfo(status = uh.`type` match { - case UNAFFILIATED_HERO_TRAVELER => RECRUITMENT_STATUS_TRAVELER - case UNAFFILIATED_HERO_OUTLAW => RECRUITMENT_STATUS_OUTLAW - case UNAFFILIATED_HERO_PRISONER => RECRUITMENT_STATUS_PRISONER + case UNAFFILIATED_HERO_TRAVELER => RECRUITMENT_STATUS_TRAVELER + case UNAFFILIATED_HERO_OUTLAW => RECRUITMENT_STATUS_OUTLAW + case UNAFFILIATED_HERO_PRISONER => RECRUITMENT_STATUS_PRISONER case UNAFFILIATED_HERO_MOVING_PRISONER => RECRUITMENT_STATUS_MOVING_PRISONER - case UNAFFILIATED_HERO_RESIDENT => + case UNAFFILIATED_HERO_RESIDENT => RECRUITMENT_STATUS_NO_RULER_IN_PROVINCE - case _ => + case _ => throw new EagleInternalException("Unknown unaffiliated hero type") }) ) diff --git a/src/main/scala/net/eagle0/eagle/library/util/province/ProvinceUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/province/ProvinceUtils.scala index 65a2012c6f..870898e698 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/province/ProvinceUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/province/ProvinceUtils.scala @@ -15,11 +15,7 @@ import net.eagle0.eagle.model.action_result.changed_province.ChangedProvinceT import net.eagle0.eagle.model.state.{BattalionTypeId, BeastInfo, MovingArmy} import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.HeroT -import net.eagle0.eagle.model.state.province.{ - BeastsEvent, - ProvinceEvent, - ProvinceT -} +import net.eagle0.eagle.model.state.province.{BeastsEvent, ProvinceEvent, ProvinceT} import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ProvinceOrderType.UnknownOrderType import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC @@ -38,9 +34,9 @@ object ProvinceUtils { province ) + effectiveInfrastructure(province))).toInt - def effectiveEconomy(province: ProvinceT): Double = + def effectiveEconomy(province: ProvinceT): Double = (province.economy - province.economyDevastation).max(0.0) - def effectiveAgriculture(province: ProvinceT): Double = + def effectiveAgriculture(province: ProvinceT): Double = (province.agriculture - province.agricultureDevastation).max(0.0) def effectiveInfrastructure(province: ProvinceT): Double = (province.infrastructure - province.infrastructureDevastation).max(0.0) @@ -52,11 +48,10 @@ object ProvinceUtils { def annualGoldProduction( province: ProvinceT - ): Option[Int] = { + ): Option[Int] = Option.when(province.support >= MinSupportForTaxes.doubleValue)( (effectiveEconomy(province) * GoldIncreasePerEconomy.doubleValue).toInt ) - } def annualFoodProduction( province: ProvinceT @@ -76,9 +71,9 @@ object ProvinceUtils { ): Option[HeroId] = rulingFactionOpt.map { rulingFaction => val rulingFactionHeroIds = startingProvince.rulingFactionHeroIds - val rulingPlayerHeroes = rulingFactionHeroIds.map(heroFetcher) - val factionHead = rulingFaction.factionHeadId - val presentLeaders = rulingFactionHeroIds + val rulingPlayerHeroes = rulingFactionHeroIds.map(heroFetcher) + val factionHead = rulingFaction.factionHeadId + val presentLeaders = rulingFactionHeroIds .intersect(rulingFaction.leaderIds) .map(heroFetcher) if rulingFactionHeroIds.contains(factionHead) then factionHead @@ -123,8 +118,8 @@ object ProvinceUtils { ): Boolean = (for { rulingFactionId <- province.rulingFactionId - rulingHeroId <- province.rulingHeroId - faction <- factions.find(_.id == rulingFactionId) + rulingHeroId <- province.rulingHeroId + faction <- factions.find(_.id == rulingFactionId) } yield faction.leaderIds.contains(rulingHeroId)) .getOrElse(false) @@ -167,7 +162,7 @@ object ProvinceUtils { def clearRulingFaction( province: ProvinceT, changedProvince: ChangedProvinceT - ): ChangedProvinceT = { + ): ChangedProvinceT = (province: ProvinceT, changedProvince: ChangedProvinceT) match { case (p: ProvinceC, cp: ChangedProvinceC) => cp.copy( @@ -178,15 +173,14 @@ object ProvinceUtils { goldDelta = Some(-p.gold), foodDelta = Some(-p.food), newProvinceOrders = Some(UnknownOrderType), - newUnaffiliatedHeroes = - cp.newUnaffiliatedHeroes ++ p.rulingFactionHeroIds.map(hid => - UnaffiliatedHeroC( - heroId = hid, - unaffiliatedHeroType = Traveler, - roundsInType = 0, - recruitmentInfo = RecruitmentInfo.Traveler - ) - ), + newUnaffiliatedHeroes = cp.newUnaffiliatedHeroes ++ p.rulingFactionHeroIds.map(hid => + UnaffiliatedHeroC( + heroId = hid, + unaffiliatedHeroType = Traveler, + roundsInType = 0, + recruitmentInfo = RecruitmentInfo.Traveler + ) + ), changedUnaffiliatedHeroes = province.unaffiliatedHeroes.map { uh => uh.copy( unaffiliatedHeroType = uh.unaffiliatedHeroType match { @@ -208,12 +202,11 @@ object ProvinceUtils { ) } ) - case _ => + case _ => throw new EagleInternalException( "Unsupported ProvinceT or ChangedProvinceT type" ) } - } private def abandonedProvinceCP(province: ProvinceT): ChangedProvinceT = clearRulingFaction(province, ChangedProvinceC(provinceId = province.id)) diff --git a/src/main/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtils.scala index d5bc7bc761..ae507598fc 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtils.scala @@ -96,7 +96,7 @@ object QuestCreationUtils { factions: Vector[FactionT], battalions: Vector[BattalionT], functionalRandom: FunctionalRandom - ): RandomState[Vector[QuestT]] = { + ): RandomState[Vector[QuestT]] = functionalRandom.nextFlatMap( Vector[QuestCreator]( improvementQuests, @@ -118,13 +118,13 @@ object QuestCreationUtils { QuestCreatorFrom(exilePrisonerQuests), QuestCreatorFrom(returnPrisonerQuests) ) - ) { case (questCreator, fr) => - questCreator(province, allProvinces, factions, battalions, fr).continue { - case (newAcc, fr) => - fr.nextRandomSubset(maxCandidateCountPerType, newAcc) - } + ) { + case (questCreator, fr) => + questCreator(province, allProvinces, factions, battalions, fr).continue { + case (newAcc, fr) => + fr.nextRandomSubset(maxCandidateCountPerType, newAcc) + } } - } private def improvementQuests( province: ProvinceT, @@ -132,29 +132,26 @@ object QuestCreationUtils { @unused factions: Vector[FactionT], @unused battalions: Vector[BattalionT], functionalRandom: FunctionalRandom - ): RandomState[Vector[QuestT]] = { + ): RandomState[Vector[QuestT]] = functionalRandom.nextFlatMap( Vector( ( province.agriculture, - (province: ProvinceT, value: Double) => - ImproveAgricultureQuest(province.id, value) + (province: ProvinceT, value: Double) => ImproveAgricultureQuest(province.id, value) ), ( province.economy, - (province: ProvinceT, value: Double) => - ImproveEconomyQuest(province.id, value) + (province: ProvinceT, value: Double) => ImproveEconomyQuest(province.id, value) ), ( province.infrastructure, - (province: ProvinceT, value: Double) => - ImproveInfrastructureQuest(province.id, value) + (province: ProvinceT, value: Double) => ImproveInfrastructureQuest(province.id, value) ) ) - ) { case ((value, maker), fr) => - randomImprovementQuest(province, value, maker, fr).map(_.toVector) + ) { + case ((value, maker), fr) => + randomImprovementQuest(province, value, maker, fr).map(_.toVector) } - } private def randomImprovementQuest( province: ProvinceT, @@ -162,7 +159,7 @@ object QuestCreationUtils { detailsMaker: (ProvinceT, Double) => QuestC, functionalRandom: FunctionalRandom ): RandomState[Option[QuestT]] = { - val currentValueFloor = currentValue.floor.toInt + val currentValueFloor = currentValue.floor.toInt val maximumRaiseAmount = Math.min( 100 - currentValueFloor, @@ -241,13 +238,13 @@ object QuestCreationUtils { factions: Vector[FactionT], @unused battalions: Vector[BattalionT] ): Vector[QuestT] = - prisonersOfFaction(province.getRulingFactionId, allProvinces, factions) - .map { case (prisoner, prisonerProvinceId) => + prisonersOfFaction(province.getRulingFactionId, allProvinces, factions).map { + case (prisoner, prisonerProvinceId) => ExecutePrisonerQuest( prisonerHeroId = prisoner.heroId, prisonerProvinceId = prisonerProvinceId ) - } + } private def exilePrisonerQuests( province: ProvinceT, @@ -255,13 +252,13 @@ object QuestCreationUtils { factions: Vector[FactionT], @unused battalions: Vector[BattalionT] ): Vector[QuestT] = - prisonersOfFaction(province.getRulingFactionId, allProvinces, factions) - .map { case (prisoner, prisonerProvinceId) => + prisonersOfFaction(province.getRulingFactionId, allProvinces, factions).map { + case (prisoner, prisonerProvinceId) => ExilePrisonerQuest( prisonerHeroId = prisoner.heroId, prisonerProvinceId = prisonerProvinceId ) - } + } private def releasePrisonerQuests( province: ProvinceT, @@ -269,8 +266,8 @@ object QuestCreationUtils { factions: Vector[FactionT], @unused battalions: Vector[BattalionT] ): Vector[QuestT] = - prisonersOfFaction(province.getRulingFactionId, allProvinces, factions) - .flatMap { case (prisoner, prisonerProvinceId) => + prisonersOfFaction(province.getRulingFactionId, allProvinces, factions).flatMap { + case (prisoner, prisonerProvinceId) => Option.when( factions.exists(_.leaderIds.contains(prisoner.heroId)) ) { @@ -279,7 +276,7 @@ object QuestCreationUtils { prisonerProvinceId = prisonerProvinceId ) } - } + } private def returnPrisonerQuests( province: ProvinceT, @@ -287,20 +284,19 @@ object QuestCreationUtils { factions: Vector[FactionT], @unused battalions: Vector[BattalionT] ): Vector[QuestT] = - prisonersOfFaction(province.getRulingFactionId, allProvinces, factions) - .collect { - case (prisoner, prisonerProvinceId) - if prisoner.lastFactionId.exists(lfid => - factions - .find(_.id == lfid) - .exists(_.leaderIds.contains(prisoner.heroId)) - ) => - ReturnPrisonerQuest( - prisonerHeroId = prisoner.heroId, - prisonerProvinceId = prisonerProvinceId, - toFactionId = prisoner.lastFactionId.get - ) - } + prisonersOfFaction(province.getRulingFactionId, allProvinces, factions).collect { + case (prisoner, prisonerProvinceId) + if prisoner.lastFactionId.exists(lfid => + factions + .find(_.id == lfid) + .exists(_.leaderIds.contains(prisoner.heroId)) + ) => + ReturnPrisonerQuest( + prisonerHeroId = prisoner.heroId, + prisonerProvinceId = prisonerProvinceId, + toFactionId = prisoner.lastFactionId.get + ) + } private def wealthQuests( province: ProvinceT, @@ -316,13 +312,14 @@ object QuestCreationUtils { MaxDesiredIncreaseForWealthQuest.intValue ) ) - .map { case (goldIncrease, foodIncrease) => - Vector( - WealthQuest( - food = province.food + foodIncrease, - gold = province.gold + goldIncrease + .map { + case (goldIncrease, foodIncrease) => + Vector( + WealthQuest( + food = province.food + foodIncrease, + gold = province.gold + goldIncrease + ) ) - ) } private def upgradeBattalionQuests( @@ -331,50 +328,51 @@ object QuestCreationUtils { @unused factions: Vector[FactionT], battalions: Vector[BattalionT], functionalRandom: FunctionalRandom - ): RandomState[Vector[QuestT]] = { - functionalRandom.nextFlatMap(questableBattalionTypes) { case (typeId, fr) => - val existingBattalions = province.battalionIds - .flatMap(bid => battalions.find(_.id == bid)) - .filter(_.typeId == typeId) + ): RandomState[Vector[QuestT]] = + functionalRandom.nextFlatMap(questableBattalionTypes) { + case (typeId, fr) => + val existingBattalions = province.battalionIds + .flatMap(bid => battalions.find(_.id == bid)) + .filter(_.typeId == typeId) - val currentMaxArmament = existingBattalions - .map(_.armament) - .maxOption - .getOrElse(0.0) + val currentMaxArmament = existingBattalions + .map(_.armament) + .maxOption + .getOrElse(0.0) - val currentMaxTraining = existingBattalions - .map(_.training) - .minOption - .getOrElse(0.0) + val currentMaxTraining = existingBattalions + .map(_.training) + .minOption + .getOrElse(0.0) - Option - .when( - currentMaxArmament + MinDesiredIncreaseForUpgradeBattalionQuest.intValue < 100.0 && currentMaxTraining + MinDesiredIncreaseForUpgradeBattalionQuest.intValue < 100.0 - ) { - fr.nextPair( - _.nextIntInclusive( - MinDesiredIncreaseForUpgradeBattalionQuest.intValue, - MaxDesiredIncreaseForUpgradeBattalionQuest.intValue - ) - ).map { case (armamentIncrease, trainingIncrease) => - val desiredArmament = - (currentMaxArmament + armamentIncrease).min(100) - val desiredTraining = - (currentMaxTraining + trainingIncrease).min(100) - - Vector( - UpgradeBattalionQuest( - provinceId = province.id, - battalionTypeId = typeId, - minimumTraining = desiredTraining, - minimumArmament = desiredArmament + Option + .when( + currentMaxArmament + MinDesiredIncreaseForUpgradeBattalionQuest.intValue < 100.0 && currentMaxTraining + MinDesiredIncreaseForUpgradeBattalionQuest.intValue < 100.0 + ) { + fr.nextPair( + _.nextIntInclusive( + MinDesiredIncreaseForUpgradeBattalionQuest.intValue, + MaxDesiredIncreaseForUpgradeBattalionQuest.intValue ) - ) + ).map { + case (armamentIncrease, trainingIncrease) => + val desiredArmament = + (currentMaxArmament + armamentIncrease).min(100) + val desiredTraining = + (currentMaxTraining + trainingIncrease).min(100) + + Vector( + UpgradeBattalionQuest( + provinceId = province.id, + battalionTypeId = typeId, + minimumTraining = desiredTraining, + minimumArmament = desiredArmament + ) + ) + } } - } - .getOrElse(RandomState(Vector(), fr)) + .getOrElse(RandomState(Vector(), fr)) } - } private def grandArmyQuests( province: ProvinceT, @@ -430,7 +428,7 @@ object QuestCreationUtils { ) .exists(_.distance > MaxDistanceForDefeatFactionQuest.intValue) } - .map { f => DefeatFactionQuest(targetFactionId = f.id) } + .map(f => DefeatFactionQuest(targetFactionId = f.id)) private def allianceQuests( province: ProvinceT, @@ -460,7 +458,7 @@ object QuestCreationUtils { factions ) ) - .map { f => TruceWithFactionQuest(targetFactionId = f.id) } + .map(f => TruceWithFactionQuest(targetFactionId = f.id)) def truceCountQuests( province: ProvinceT, diff --git a/src/main/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreation.scala b/src/main/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreation.scala index fdd1fbd73e..cb5c3d6f75 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreation.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreation.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.quest_creation import net.eagle0.common.{FunctionalRandom, RandomState} -import net.eagle0.eagle.library.settings.{ - MaxDesiredTruceCountForQuest, - MinDesiredNewTruceCountForQuest -} +import net.eagle0.eagle.library.settings.{MaxDesiredTruceCountForQuest, MinDesiredNewTruceCountForQuest} import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.Hostile import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.quest.concrete.TruceCountQuest diff --git a/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtils.scala index 1e6030c337..7bad23a648 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtils.scala @@ -1,31 +1,17 @@ package net.eagle0.eagle.library.util.quest_fulfillment import net.eagle0.eagle.{FactionId, GameId, HeroId, ProvinceId, RoundId} -import net.eagle0.eagle.library.settings.{ - QuestFailedRecruitmentPenalty, - QuestRecruitmentBonus -} +import net.eagle0.eagle.library.settings.{QuestFailedRecruitmentPenalty, QuestRecruitmentBonus} import net.eagle0.eagle.library.EagleInternalException -import net.eagle0.eagle.model.action_result.{ - ActionResultT, - NotificationDetails, - NotificationT -} +import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.{ QuestFailedMessage, QuestFulfilledMessage } -import net.eagle0.eagle.model.action_result.types.{ - QuestFailedResultType, - QuestFulfilledResultType -} +import net.eagle0.eagle.model.action_result.types.{QuestFailedResultType, QuestFulfilledResultType} import net.eagle0.eagle.model.action_result.types.base.ActionResultType import net.eagle0.eagle.model.action_result.ActionResultT.ActionResultUpdater import net.eagle0.eagle.model.state.date.Date @@ -37,11 +23,7 @@ import net.eagle0.eagle.model.state.hero.{ import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.ComponentQuest import net.eagle0.eagle.model.state.quest.QuestT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT, UnaffiliatedHeroType} class QuestFulfillmentChecker( gameId: GameId, @@ -83,20 +65,19 @@ object QuestFulfillmentUtils { currentDate: Date, currentRoundId: RoundId, previousBackstoryTextIdLookup: HeroId => String - ): Vector[ActionResultT] = { + ): Vector[ActionResultT] = for { uh <- province.unaffiliatedHeroes ar <- maybeFulfilledQuestResult( - uh = uh, - province = province, - isFulfilled = isFulfilled, - gameId = gameId, - currentDate = currentDate, - currentRoundId = currentRoundId, - previousBackstoryTextId = previousBackstoryTextIdLookup(uh.heroId) - ) + uh = uh, + province = province, + isFulfilled = isFulfilled, + gameId = gameId, + currentDate = currentDate, + currentRoundId = currentRoundId, + previousBackstoryTextId = previousBackstoryTextIdLookup(uh.heroId) + ) } yield ar - } def uhWithFulfilledQuest( uh: UnaffiliatedHeroT, @@ -228,18 +209,17 @@ object QuestFulfillmentUtils { isFailed: (QuestT, ProvinceT) => Boolean, gameId: GameId, currentDate: Date - ): Vector[ActionResultT] = { + ): Vector[ActionResultT] = for { uh <- province.unaffiliatedHeroes ar <- maybeFailedQuestResult( - uh = uh, - province = province, - isFailed = isFailed, - gameId = gameId, - currentDate = currentDate - ) + uh = uh, + province = province, + isFailed = isFailed, + gameId = gameId, + currentDate = currentDate + ) } yield ar - } def questFailedNotificationRequest( uh: UnaffiliatedHeroT, @@ -288,7 +268,7 @@ object QuestFulfillmentUtils { ): ActionResultT = { val notificationRequest = questFailedNotificationRequest(uhWithFailedQuest, province, gameId) - val backstoryEvent = questFailedBackstoryEvent( + val backstoryEvent = questFailedBackstoryEvent( uh = uhWithFailedQuest, province = province, currentDate = currentDate @@ -322,16 +302,14 @@ object QuestFulfillmentUtils { ): Option[ChangedProvinceC] = { val changedUHs = province.unaffiliatedHeroes.flatMap { uh => Option.when(check(uh, province)) { - uh.quest - .map { - case q: ComponentQuest => - q.withComponentsFulfilled(q.componentsFulfilled + incrementAmount) - case _ => - throw new EagleInternalException( - s"Trying to increment a quest for Unaffiliated hero ${uh.heroId} in province ${province.id}, who has a ${uh.quest.get} quest" - ) - } - .map { newQ => uh.withQuest(newQ) } + uh.quest.map { + case q: ComponentQuest => + q.withComponentsFulfilled(q.componentsFulfilled + incrementAmount) + case _ => + throw new EagleInternalException( + s"Trying to increment a quest for Unaffiliated hero ${uh.heroId} in province ${province.id}, who has a ${uh.quest.get} quest" + ) + }.map(newQ => uh.withQuest(newQ)) .getOrElse(uh) } } @@ -370,8 +348,7 @@ object QuestFulfillmentUtils { changedProvinces = Vector( ChangedProvinceC( provinceId = province.id, - changedUnaffiliatedHeroes = - Vector(uhMutator(uh, province.rulingFactionId.get)) + changedUnaffiliatedHeroes = Vector(uhMutator(uh, province.rulingFactionId.get)) ) ) ) diff --git a/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/prisoner_management/PrisonerManagementQuestMatchers.scala b/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/prisoner_management/PrisonerManagementQuestMatchers.scala index ff3b11cbe0..4fa3c4461d 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/prisoner_management/PrisonerManagementQuestMatchers.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/quest_fulfillment/prisoner_management/PrisonerManagementQuestMatchers.scala @@ -17,21 +17,21 @@ class PrisonerManagementQuestMatchers( quest match { case ExecutePrisonerQuest(prisonerHeroId, prisonerProvinceId) => prisonerHeroId == questPrisonerHeroId && prisonerProvinceId == questPrisonerProvinceId - case _ => false + case _ => false } def exilePrisonerQuestMatch(quest: QuestT): Boolean = quest match { case ExilePrisonerQuest(prisonerHeroId, prisonerProvinceId) => prisonerHeroId == questPrisonerHeroId && prisonerProvinceId == questPrisonerProvinceId - case _ => false + case _ => false } def releasePrisonerMatch(quest: QuestT): Boolean = quest match { case ReleasePrisonerQuest(prisonerHeroId, prisonerProvinceId) => prisonerHeroId == questPrisonerHeroId && prisonerProvinceId == questPrisonerProvinceId - case _ => false + case _ => false } def returnPrisonerQuestMatch(quest: QuestT): Boolean = diff --git a/src/main/scala/net/eagle0/eagle/library/util/ransom_validity/RansomValidity.scala b/src/main/scala/net/eagle0/eagle/library/util/ransom_validity/RansomValidity.scala index 3f5436d665..28d3345c50 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/ransom_validity/RansomValidity.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/ransom_validity/RansomValidity.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.ransom_validity import net.eagle0.eagle.library.EagleInternalException -import net.eagle0.eagle.model.state.diplomacy_offer.{ - DiplomacyOffer, - RansomOffer -} +import net.eagle0.eagle.model.state.diplomacy_offer.{DiplomacyOffer, RansomOffer} import net.eagle0.eagle.model.state.diplomacy_offer.RansomOfferDetails.{ HostageOfferedInExchange, PrisonerOfferedInExchange, @@ -46,12 +43,8 @@ object RansomValidity { provinces ).rulingFactionId.contains(offer.targetFactionId) && prisonerToBeRansomedIsValid(prisonerToBeRansomed, provinces) && - prisonersOffered.forall(poie => - prisonerOfferedInExchangeIsValid(poie, provinces) - ) && - hostagesOffered.forall(hoie => - hostageOfferedInExchangeIsValid(hoie, provinces) - ) && + prisonersOffered.forall(poie => prisonerOfferedInExchangeIsValid(poie, provinces)) && + hostagesOffered.forall(hoie => hostageOfferedInExchangeIsValid(hoie, provinces)) && province( offer.messengerOriginProvinceId, provinces @@ -64,19 +57,16 @@ object RansomValidity { ptbr: PrisonerToBeRansomed, provinces: Vector[ProvinceT] ): Boolean = - province(ptbr.provinceIdForPrisoner, provinces).unaffiliatedHeroes - .exists { uh => - uh.heroId == ptbr.prisonerHeroId && uh.unaffiliatedHeroType == Prisoner - } + province(ptbr.provinceIdForPrisoner, provinces).unaffiliatedHeroes.exists { uh => + uh.heroId == ptbr.prisonerHeroId && uh.unaffiliatedHeroType == Prisoner + } private def prisonerOfferedInExchangeIsValid( poie: PrisonerOfferedInExchange, provinces: Vector[ProvinceT] ): Boolean = province(poie.provinceIdWithHero, provinces).unaffiliatedHeroes - .exists(uh => - uh.heroId == poie.heroId && uh.unaffiliatedHeroType == Prisoner - ) + .exists(uh => uh.heroId == poie.heroId && uh.unaffiliatedHeroType == Prisoner) private def hostageOfferedInExchangeIsValid( hoie: HostageOfferedInExchange, diff --git a/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOdds.scala b/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOdds.scala index ea6d3aa2ec..146bda6168 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOdds.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOdds.scala @@ -46,17 +46,17 @@ object LegacyRecruitmentOdds { roundsInState: Int ): Double = status match { - case UNAFFILIATED_HERO_UNKNOWN => + case UNAFFILIATED_HERO_UNKNOWN => throw new EagleInternalException("Invalid hero status UNKNOWN") - case UNAFFILIATED_HERO_PRISONER => + case UNAFFILIATED_HERO_PRISONER => RecruitmentAdjustmentPerTurnForPrisoner.doubleValue * roundsInState - case UNAFFILIATED_HERO_MOVING_PRISONER => -100.0 - case UNAFFILIATED_HERO_RETURNING_PRISONER => -100.0 - case UNAFFILIATED_HERO_TRAVELER => + case UNAFFILIATED_HERO_MOVING_PRISONER => -100.0 + case UNAFFILIATED_HERO_RETURNING_PRISONER => -100.0 + case UNAFFILIATED_HERO_TRAVELER => RecruitmentAdjustmentForTraveler.doubleValue - case UNAFFILIATED_HERO_RESIDENT => + case UNAFFILIATED_HERO_RESIDENT => RecruitmentAdjustmentForResident.doubleValue - case UNAFFILIATED_HERO_OUTLAW => + case UNAFFILIATED_HERO_OUTLAW => RecruitmentAdjustmentForOutlaw.doubleValue case UnaffiliatedHeroType.Unrecognized(value) => throw new EagleInternalException(s"Unrecognized hero status $value") diff --git a/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOdds.scala b/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOdds.scala index e3de91941c..ede9d4ca4d 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOdds.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOdds.scala @@ -16,10 +16,7 @@ import net.eagle0.eagle.library.util.hero.HeroUtils import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.HeroT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{UnaffiliatedHeroT, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ MovingPrisoner, Outlaw, @@ -48,17 +45,17 @@ object RecruitmentOdds { roundsInState: Int ): Double = status match { - case Unknown => + case Unknown => throw new EagleInternalException("Invalid hero status UNKNOWN") - case Prisoner => + case Prisoner => RecruitmentAdjustmentPerTurnForPrisoner.doubleValue * roundsInState case MovingPrisoner => -100.0 case ReturningPrisoner => -100.0 case Traveler => RecruitmentAdjustmentForTraveler.doubleValue - case Resident => + case Resident => RecruitmentAdjustmentForResident.doubleValue - case Outlaw => + case Outlaw => RecruitmentAdjustmentForOutlaw.doubleValue } diff --git a/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/LegacyUnaffiliatedHeroUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/LegacyUnaffiliatedHeroUtils.scala index 74e553f845..5d55c9920a 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/LegacyUnaffiliatedHeroUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/LegacyUnaffiliatedHeroUtils.scala @@ -74,14 +74,14 @@ object LegacyUnaffiliatedHeroUtils { RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER), functionalRandom ) - case UNAFFILIATED_HERO_OUTLAW => + case UNAFFILIATED_HERO_OUTLAW => RandomState( RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW), functionalRandom ) case UNAFFILIATED_HERO_PRISONER => newRecruitmentInfo(gs, provinceId, uh, hero, functionalRandom) - case _ => + case _ => throw new EagleInternalException( s"Unknown unaffiliated hero type ${uh.`type`}" ) @@ -145,10 +145,10 @@ object LegacyUnaffiliatedHeroUtils { ): Boolean = { import DateProtoUtils.* - val targetHero = gameState.heroes(unaffiliatedHero.heroId) - val actingFaction = gameState.factions(factionId) + val targetHero = gameState.heroes(unaffiliatedHero.heroId) + val actingFaction = gameState.factions(factionId) val actingFactionLeader = gameState.heroes(actingFaction.factionHeadId) - val odds = LegacyRecruitmentOdds.scoreForUnaffiliatedHero( + val odds = LegacyRecruitmentOdds.scoreForUnaffiliatedHero( faction = actingFaction, factionLeader = Some(actingFactionLeader), prestige = LegacyFactionUtils.prestige(factionId, gameState), diff --git a/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/UnaffiliatedHeroUtils.scala b/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/UnaffiliatedHeroUtils.scala index eae69cb9c7..14982965b3 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/UnaffiliatedHeroUtils.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/unaffiliated_hero/UnaffiliatedHeroUtils.scala @@ -13,14 +13,8 @@ import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.model.state.hero.HeroT import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - MovingPrisoner, - Prisoner -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{MovingPrisoner, Prisoner} import net.eagle0.eagle.ProvinceId object UnaffiliatedHeroUtils { diff --git a/src/main/scala/net/eagle0/eagle/library/util/validations/RuntimeValidator.scala b/src/main/scala/net/eagle0/eagle/library/util/validations/RuntimeValidator.scala index e14b73a12b..a18ae4e455 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/validations/RuntimeValidator.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/validations/RuntimeValidator.scala @@ -7,10 +7,7 @@ import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.{ RECRUITMENT_STATUS_UNKNOWN } import net.eagle0.eagle.common.round_phase.RoundPhase -import net.eagle0.eagle.common.round_phase.RoundPhase.{ - FREE_FOR_ALL_BATTLE_REQUEST, - FREE_FOR_ALL_DECISION -} +import net.eagle0.eagle.common.round_phase.RoundPhase.{FREE_FOR_ALL_BATTLE_REQUEST, FREE_FOR_ALL_DECISION} import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction_relationship.FactionRelationship @@ -25,8 +22,7 @@ object RuntimeValidator extends Validator { requirement: Boolean, message: => Any ): Unit = - if !requirement then - throw new EagleValidationException("validation failed: " + message) + if !requirement then throw new EagleValidationException("validation failed: " + message) @inline private final def validationRequireNot( condition: Boolean, @@ -186,28 +182,29 @@ object RuntimeValidator extends Validator { case class HeroProvincePair(hid: HeroId, pid: ProvinceId, pos: Int) val rph = for { - p <- gameState.provinces.values + p <- gameState.provinces.values hid <- p.rulingFactionHeroIds } yield HeroProvincePair(hid = hid, pid = p.id, pos = 0) val uafh = for { - p <- gameState.provinces.values + p <- gameState.provinces.values uh <- p.unaffiliatedHeroes } yield HeroProvincePair(hid = uh.heroId, pid = p.id, pos = 1) val iah = for { - p <- gameState.provinces.values + p <- gameState.provinces.values ia <- p.incomingArmies - u <- ia.getArmy.units + u <- ia.getArmy.units } yield HeroProvincePair(hid = u.heroId, pid = p.id, pos = 2) val accountedForHeroes = rph ++ uafh ++ iah - accountedForHeroes.groupBy(_.hid).foreach { case (hid, pairs) => - validationRequireNot( - pairs.size > 1, - s"HeroId $hid found in multiple provinces (${pairs.map(_.pid).mkString(", ")}): $pairs" - ) + accountedForHeroes.groupBy(_.hid).foreach { + case (hid, pairs) => + validationRequireNot( + pairs.size > 1, + s"HeroId $hid found in multiple provinces (${pairs.map(_.pid).mkString(", ")}): $pairs" + ) } gameState @@ -222,11 +219,12 @@ object RuntimeValidator extends Validator { .map((p.id, _)) ) - accountedForBattalions.groupBy(_._2).foreach { case (bid, tups) => - validationRequireNot( - tups.size > 1, - s"BattalionId $bid found in multiple provinces: ${tups.map(_._1)}" - ) + accountedForBattalions.groupBy(_._2).foreach { + case (bid, tups) => + validationRequireNot( + tups.size > 1, + s"BattalionId $bid found in multiple provinces: ${tups.map(_._1)}" + ) } gameState @@ -250,12 +248,10 @@ object RuntimeValidator extends Validator { army = movingArmy.getArmy unit <- army.units hero = gameState.heroes(unit.heroId) - } yield { - validationRequire( - hero.factionId.contains(army.factionId), - s"Army factionId in $army does not match hero $hero" - ) - } + } yield validationRequire( + hero.factionId.contains(army.factionId), + s"Army factionId in $army does not match hero $hero" + ) } gameState @@ -276,11 +272,10 @@ object RuntimeValidator extends Validator { s"HeroId $hid is not present in game state" ) - private def validateBattalionExistence(gs: GameState): Unit = { + private def validateBattalionExistence(gs: GameState): Unit = gs.provinces.values .flatMap(_.battalionIds) .foreach(validateBidExists(_, gs)) - } private def validateBidExists(bid: BattalionId, gs: GameState): Unit = validationRequireNot( @@ -315,9 +310,7 @@ object RuntimeValidator extends Validator { validationRequireNot( gs.outstandingBattles .map(_.shardokGameId) - .exists(sgid => - Integer.parseInt(sgid.split("_")(1), 16) > gs.battleCounter - ), + .exists(sgid => Integer.parseInt(sgid.split("_")(1), 16) > gs.battleCounter), s"Something's wrong with the battle counter" ) } @@ -330,7 +323,7 @@ object RuntimeValidator extends Validator { attackerFidSet = p.hostileArmies.map(_.factionId).toSet; fid <- attackerFidSet; faction = gs.factions(fid) - do { + do validationRequire( (attackerFidSet - faction.id) .subsetOf( @@ -343,20 +336,17 @@ object RuntimeValidator extends Validator { ), s"Attacking faction ${faction.id} is not allied with other attackers in ${p.toString}" ) - } } override def validateIncomingArmies( province: Province, currentRoundId: RoundId - ): Unit = { - for ia <- province.incomingArmies do { + ): Unit = + for ia <- province.incomingArmies do validationRequireNot( currentRoundId > ia.arrivalRound, s"MovingArmy ${ia.id} was supposed to arrive in round ${ia.arrivalRound}, but it is round $currentRoundId" ) - } - } override def validate(actionResult: ActionResult): ActionResult = { validationRequireNot( @@ -368,31 +358,32 @@ object RuntimeValidator extends Validator { } override def validateFactions(gameState: GameState): GameState = { - gameState.factions.foreach { case (fid, faction) => - // all focus provinces are owned provinces - faction.focusProvinceId.foreach { pid => - validationRequire( - gameState.provinces(pid).rulingFactionId.contains(fid), - s"Unowned focus province for faction $faction" - ) - } - - // all faction relationships are real factions - faction.factionRelationships.foreach { fr => - validationRequire( - gameState.factions.contains(fr.targetFactionId), - s"Invalid target faction id ${fr.targetFactionId} in faction relationship $fr" - ) - } - - // at most one incoming diplomacy offer per faction - faction.incomingDiplomacyOffers.groupBy(_.originatingFactionId).foreach { - case (fid, offers) => + gameState.factions.foreach { + case (fid, faction) => + // all focus provinces are owned provinces + faction.focusProvinceId.foreach { pid => validationRequire( - offers.size == 1, - s"Multiple incoming diplomacy offers from $fid: ${offers}" + gameState.provinces(pid).rulingFactionId.contains(fid), + s"Unowned focus province for faction $faction" ) - } + } + + // all faction relationships are real factions + faction.factionRelationships.foreach { fr => + validationRequire( + gameState.factions.contains(fr.targetFactionId), + s"Invalid target faction id ${fr.targetFactionId} in faction relationship $fr" + ) + } + + // at most one incoming diplomacy offer per faction + faction.incomingDiplomacyOffers.groupBy(_.originatingFactionId).foreach { + case (fid, offers) => + validationRequire( + offers.size == 1, + s"Multiple incoming diplomacy offers from $fid: $offers" + ) + } } gameState } diff --git a/src/main/scala/net/eagle0/eagle/library/util/view_filters/ArmyFilter.scala b/src/main/scala/net/eagle0/eagle/library/util/view_filters/ArmyFilter.scala index 8e0f839539..98a2a369fa 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/view_filters/ArmyFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/view_filters/ArmyFilter.scala @@ -10,15 +10,13 @@ object ArmyFilter { army: Army, battalions: Map[BattalionId, Battalion], factionId: Option[FactionId] - ): ArmyView = { + ): ArmyView = ArmyView( factionId = army.factionId, units = if factionId.forall(_ == army.factionId) then army.units else Vector.empty, unitCount = army.units.length, - troopCount = - army.units.flatMap(_.battalionId).map(battalions).map(_.size).sum + troopCount = army.units.flatMap(_.battalionId).map(battalions).map(_.size).sum ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattalionNameFilter.scala b/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattalionNameFilter.scala index 7e5159943d..be31970910 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattalionNameFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattalionNameFilter.scala @@ -12,61 +12,59 @@ object BattalionNameFilter { gs: GameState, factionId: Option[FactionId] ): Map[BattalionId, String] = - factionId - .map { fid => - val battalionIdsInVisibleProvinces = gs.factions.keys - .filter(fid => Visibility.hasFullVisibility(factionId, fid, gs)) - .flatMap(LegacyFactionUtils.provinces(_, gs)) - .flatMap(_.battalionIds) - .toVector + factionId.map { fid => + val battalionIdsInVisibleProvinces = gs.factions.keys + .filter(fid => Visibility.hasFullVisibility(factionId, fid, gs)) + .flatMap(LegacyFactionUtils.provinces(_, gs)) + .flatMap(_.battalionIds) + .toVector - val battalionIdsIncomingToMyProvinces = LegacyFactionUtils - .provinces(fid, gs) - .flatMap( - _.incomingArmies - .filter(_.arrivalRound == gs.currentRoundId) - .map(_.getArmy) - .flatMap(_.units) - .flatMap(_.battalionId) - ) + val battalionIdsIncomingToMyProvinces = LegacyFactionUtils + .provinces(fid, gs) + .flatMap( + _.incomingArmies + .filter(_.arrivalRound == gs.currentRoundId) + .map(_.getArmy) + .flatMap(_.units) + .flatMap(_.battalionId) + ) - val myMovingBattalionIds = gs.provinces.values - .flatMap(allTypesOfArriving) - .filter(_.factionId == fid) - .flatMap(_.units) - .flatMap(_.battalionId) - val provincesWithMyMovingArmies = gs.provinces.values - .filter(p => allTypesOfArriving(p).exists(_.factionId == fid)) - val battalionIdsInProvincesWithMyMovingArmies = - provincesWithMyMovingArmies.flatMap(p => - p.battalionIds ++ allTypesOfArriving(p) - .flatMap(_.units) - .flatMap(_.battalionId) - ) + val myMovingBattalionIds = gs.provinces.values + .flatMap(allTypesOfArriving) + .filter(_.factionId == fid) + .flatMap(_.units) + .flatMap(_.battalionId) + val provincesWithMyMovingArmies = gs.provinces.values + .filter(p => allTypesOfArriving(p).exists(_.factionId == fid)) + val battalionIdsInProvincesWithMyMovingArmies = + provincesWithMyMovingArmies.flatMap(p => + p.battalionIds ++ allTypesOfArriving(p) + .flatMap(_.units) + .flatMap(_.battalionId) + ) - val battalionIdsInBattles = gs.outstandingBattles - .flatMap(_.players) - .map(_.getArmyGroup) - .flatMap(_.armies) - .map(_.getArmy) - .flatMap(_.units) - .flatMap(_.battalionId) + val battalionIdsInBattles = gs.outstandingBattles + .flatMap(_.players) + .map(_.getArmyGroup) + .flatMap(_.armies) + .map(_.getArmy) + .flatMap(_.units) + .flatMap(_.battalionId) - ( - battalionIdsInVisibleProvinces ++ - battalionIdsIncomingToMyProvinces ++ - myMovingBattalionIds ++ - battalionIdsInProvincesWithMyMovingArmies ++ - battalionIdsInBattles - ).distinct - .map(gs.battalions) - .map(b => b.id -> b.name) - .toMap - } + ( + battalionIdsInVisibleProvinces ++ + battalionIdsIncomingToMyProvinces ++ + myMovingBattalionIds ++ + battalionIdsInProvincesWithMyMovingArmies ++ + battalionIdsInBattles + ).distinct + .map(gs.battalions) + .map(b => b.id -> b.name) + .toMap + } .getOrElse(gs.battalions.values.map(b => b.id -> b.name).toMap) - private def allTypesOfArriving(p: Province): Vector[Army] = { + private def allTypesOfArriving(p: Province): Vector[Army] = (p.incomingArmies.flatMap(_.army) ++ p.hostileArmies.flatMap(_.armies).flatMap(_.army)).toVector - } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattleFilter.scala b/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattleFilter.scala index 9e9a68e0f2..39167e3fb8 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattleFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/view_filters/BattleFilter.scala @@ -4,10 +4,7 @@ import net.eagle0.common.hostility.Hostility import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.shardok_battle.ShardokBattle import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils -import net.eagle0.eagle.views.shardok_battle_view.{ - ShardokBattlePlayerInfo, - ShardokBattleView -} +import net.eagle0.eagle.views.shardok_battle_view.{ShardokBattlePlayerInfo, ShardokBattleView} import net.eagle0.eagle.FactionId object BattleFilter { @@ -16,20 +13,18 @@ object BattleFilter { gs: GameState, fid: Option[FactionId] ): ShardokBattleView = { - val shardokPlayer = { + val shardokPlayer = battle.players.find(sp => fid.contains(sp.eagleFid)) + shardokPlayer.map { sp => + val spi = battle.players.indexOf(sp) + ShardokBattleView( + defenderProvince = battle.defenderProvince, + shardokGameId = Some(battle.shardokGameId), + myPlayerId = Some(spi), + playerInfos = shardokBattlePlayerInfos(battle, fid, gs), + mapName = Some(battle.hexMapName) + ) } - shardokPlayer - .map { sp => - val spi = battle.players.indexOf(sp) - ShardokBattleView( - defenderProvince = battle.defenderProvince, - shardokGameId = Some(battle.shardokGameId), - myPlayerId = Some(spi), - playerInfos = shardokBattlePlayerInfos(battle, fid, gs), - mapName = Some(battle.hexMapName) - ) - } .getOrElse( ShardokBattleView( shardokGameId = Some(battle.shardokGameId), @@ -46,13 +41,14 @@ object BattleFilter { fid: Option[FactionId], gs: GameState ): Vector[ShardokBattlePlayerInfo] = - battle.players.zipWithIndex.map { case (sp, i) => - ShardokBattlePlayerInfo( - playerId = i, - eagleFactionId = sp.eagleFid, - hostility = fid - .map(f => LegacyFactionUtils.hostilityStatus(f, sp.eagleFid, gs)) - .getOrElse(Hostility.UNKNOWN_HOSTILITY) - ) + battle.players.zipWithIndex.map { + case (sp, i) => + ShardokBattlePlayerInfo( + playerId = i, + eagleFactionId = sp.eagleFid, + hostility = fid + .map(f => LegacyFactionUtils.hostilityStatus(f, sp.eagleFid, gs)) + .getOrElse(Hostility.UNKNOWN_HOSTILITY) + ) }.toVector } diff --git a/src/main/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilter.scala b/src/main/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilter.scala index afc4bda18f..f86a255d4f 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilter.scala @@ -14,13 +14,13 @@ object FactionViewFilter { relationshipLevel: FactionRelationship.RelationshipLevel ): FactionRelationshipView.RelationshipLevel = relationshipLevel match { - case RelationshipLevel.UNKNOWN => + case RelationshipLevel.UNKNOWN => FactionRelationshipView.RelationshipLevel.UNKNOWN - case RelationshipLevel.ALLY => + case RelationshipLevel.ALLY => FactionRelationshipView.RelationshipLevel.ALLY - case RelationshipLevel.TRUCE => + case RelationshipLevel.TRUCE => FactionRelationshipView.RelationshipLevel.TRUCE - case RelationshipLevel.HOSTILE => + case RelationshipLevel.HOSTILE => FactionRelationshipView.RelationshipLevel.HOSTILE case RelationshipLevel.Unrecognized(value) => ??? } @@ -30,8 +30,7 @@ object FactionViewFilter { ): FactionRelationshipView = FactionRelationshipView( targetFactionId = factionRelationship.targetFactionId, - relationshipLevel = - filteredRelationshipLevel(factionRelationship.relationshipLevel), + relationshipLevel = filteredRelationshipLevel(factionRelationship.relationshipLevel), resetDate = factionRelationship.resetDate ) @@ -47,12 +46,9 @@ object FactionViewFilter { leaders = faction.leaders, name = faction.name, prestige = LegacyFactionUtils.prestige(faction.id, gs).toInt, - factionRelationships = - faction.factionRelationships.map(filteredFactionRelationshipView), + factionRelationships = faction.factionRelationships.map(filteredFactionRelationshipView), // You can see *your incoming diplomacy offers on them*, but they cannot - incomingDiplomacyOffers = faction.incomingDiplomacyOffers.filter(dof => - fid.contains(dof.originatingFactionId) - ), + incomingDiplomacyOffers = faction.incomingDiplomacyOffers.filter(dof => fid.contains(dof.originatingFactionId)), focusProvinceId = faction.focusProvinceId ) else @@ -61,10 +57,7 @@ object FactionViewFilter { factionHeadId = faction.factionHeadId, leaders = faction.leaders, name = faction.name, - factionRelationships = - faction.factionRelationships.map(filteredFactionRelationshipView), - incomingDiplomacyOffers = faction.incomingDiplomacyOffers.filter(dof => - fid.contains(dof.originatingFactionId) - ) + factionRelationships = faction.factionRelationships.map(filteredFactionRelationshipView), + incomingDiplomacyOffers = faction.incomingDiplomacyOffers.filter(dof => fid.contains(dof.originatingFactionId)) ) } diff --git a/src/main/scala/net/eagle0/eagle/library/util/view_filters/GameStateViewFilter.scala b/src/main/scala/net/eagle0/eagle/library/util/view_filters/GameStateViewFilter.scala index 1305cbbf4e..2a94fe81fa 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/view_filters/GameStateViewFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/view_filters/GameStateViewFilter.scala @@ -9,26 +9,29 @@ object GameStateViewFilter { def filteredGameState( gs: GameState, factionId: Option[FactionId] - ): GameStateView = { + ): GameStateView = GameStateView( currentRoundId = gs.currentRoundId, currentPhase = gs.currentPhase, currentDate = gs.currentDate, - provinces = gs.provinces.map { case (pid, prov) => - pid -> factionId - .map(fid => ProvinceViewFilter.filteredProvinceView(prov, gs, fid)) - .getOrElse(ProvinceViewFilter.filteredProvinceView(prov, gs)) + provinces = gs.provinces.map { + case (pid, prov) => + pid -> factionId + .map(fid => ProvinceViewFilter.filteredProvinceView(prov, gs, fid)) + .getOrElse(ProvinceViewFilter.filteredProvinceView(prov, gs)) }, - heroes = (gs.heroes ++ gs.killedHeroes).map { case (hid, hero) => - hid -> HeroViewFilter.filteredHeroView(hero, gs, factionId) + heroes = (gs.heroes ++ gs.killedHeroes).map { + case (hid, hero) => + hid -> HeroViewFilter.filteredHeroView(hero, gs, factionId) }, - battalionNames = - BattalionNameFilter.filteredBattalionNames(gs, factionId), - factions = gs.factions.map { case (pid, faction) => - pid -> FactionViewFilter.filteredFactionView(faction, gs, factionId) + battalionNames = BattalionNameFilter.filteredBattalionNames(gs, factionId), + factions = gs.factions.map { + case (pid, faction) => + pid -> FactionViewFilter.filteredFactionView(faction, gs, factionId) }, - destroyedFactions = gs.destroyedFactions.map { case (pid, faction) => - pid -> FactionView(id = pid, name = faction.name) + destroyedFactions = gs.destroyedFactions.map { + case (pid, faction) => + pid -> FactionView(id = pid, name = faction.name) }, outstandingBattles = gs.outstandingBattles .map(ob => BattleFilter.filterBattle(ob, gs, factionId)), @@ -36,5 +39,4 @@ object GameStateViewFilter { battalionTypes = gs.battalionTypes, chronicleEntries = gs.chronicleEntries ) - } } diff --git a/src/main/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilter.scala b/src/main/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilter.scala index 45774b812d..87e2663af5 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilter.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.view_filters import net.eagle0.eagle.{FactionId, HeroId} -import net.eagle0.eagle.common.diplomacy_offer.{ - DiplomacyOffer, - RansomOfferDetails -} +import net.eagle0.eagle.common.diplomacy_offer.{DiplomacyOffer, RansomOfferDetails} import net.eagle0.eagle.common.round_phase.RoundPhase.DIPLOMACY_RESOLUTION import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -128,8 +125,7 @@ object HeroViewFilter { .sortKeys(gameState = gs, heroId = hero.id) .map(keyInt => HeroSortKey(keyInt)), imagePath = hero.imagePath, - backstoryTextId = - hero.backstoryVersions.lastOption.map(_.textId).getOrElse(""), + backstoryTextId = hero.backstoryVersions.lastOption.map(_.textId).getOrElse(""), pronounGender = hero.pronounGender ) else diff --git a/src/main/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilter.scala b/src/main/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilter.scala index 48bb5e797b..bfe61a0388 100644 --- a/src/main/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilter.scala +++ b/src/main/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilter.scala @@ -12,11 +12,7 @@ import net.eagle0.eagle.library.util.hero.LegacyHeroUtils import net.eagle0.eagle.library.util.province.LegacyProvinceUtils import net.eagle0.eagle.library.util.StatWithConditionUtils.supportSc import net.eagle0.eagle.views.incoming_army_view.IncomingArmyView -import net.eagle0.eagle.views.province_view.{ - FullProvinceInfo, - ProvinceView, - UnaffiliatedHeroBasics -} +import net.eagle0.eagle.views.province_view.{FullProvinceInfo, ProvinceView, UnaffiliatedHeroBasics} import net.eagle0.eagle.FactionId object ProvinceViewFilter { @@ -79,12 +75,11 @@ object ProvinceViewFilter { Visibility.hasFullVisibility(factionId, rfid, gs) } - val knownEvents = province.activeEvents - .filter { pe => - if showAll then true - else if reconnedView.exists(_.knownEvents.contains(pe)) then true - else eventIsUniversallyVisible(pe) - } + val knownEvents = province.activeEvents.filter { pe => + if showAll then true + else if reconnedView.exists(_.knownEvents.contains(pe)) then true + else eventIsUniversallyVisible(pe) + } val incomingAttackers = myIncomingArmies(province, gs, factionId) ++ (if showAll then @@ -138,14 +133,13 @@ object ProvinceViewFilter { ): ProvinceView = { val reconnedView = for { faction <- gs.factions.get(factionId) - pv <- faction.reconnedProvinces.find(_.id == province.id) + pv <- faction.reconnedProvinces.find(_.id == province.id) } yield pv - val knownEvents = province.activeEvents - .filter { pe => - if reconnedView.exists(_.knownEvents.contains(pe)) then true - else eventIsUniversallyVisible(pe) - } + val knownEvents = province.activeEvents.filter { pe => + if reconnedView.exists(_.knownEvents.contains(pe)) then true + else eventIsUniversallyVisible(pe) + } val incomingAttackers = myIncomingArmies(province, gs, factionId) @@ -197,14 +191,12 @@ object ProvinceViewFilter { goldCap = LegacyProvinceUtils.goldCap(province), foodCap = LegacyProvinceUtils.foodCap(province), support = Some(supportSc(province.support)), - foodConsumption = - LegacyProvinceUtils.monthlyFoodConsumption(province.id, gs), + foodConsumption = LegacyProvinceUtils.monthlyFoodConsumption(province.id, gs), provinceOrders = province.provinceOrders, hexMapName = province.hexMapName, castleCount = province.castleCount, heroCap = province.heroCap, - unaffiliatedHeroes = - province.unaffiliatedHeroes.map(unaffiliatedHeroInfo(_, gs)), + unaffiliatedHeroes = province.unaffiliatedHeroes.map(unaffiliatedHeroInfo(_, gs)), rulerIsTraveling = province.rulerIsTraveling ) diff --git a/src/main/scala/net/eagle0/eagle/model/action_result/ActionResultT.scala b/src/main/scala/net/eagle0/eagle/model/action_result/ActionResultT.scala index 2fda22996a..6f0dae7510 100644 --- a/src/main/scala/net/eagle0/eagle/model/action_result/ActionResultT.scala +++ b/src/main/scala/net/eagle0/eagle/model/action_result/ActionResultT.scala @@ -88,10 +88,8 @@ trait ActionResultT { destroyedBattalionIds: Vector[BattalionId] = destroyedBattalionIds, removedHeroes: Vector[HeroId] = removedHeroIds, removedFactionIds: Vector[FactionId] = removedFactionIds, - clientTextVisibilityExtensions: Vector[ClientTextVisibilityExtensionT] = - clientTextVisibilityExtensions, - newGeneratedTextRequests: Vector[GeneratedTextRequestT] = - newGeneratedTextRequests, + clientTextVisibilityExtensions: Vector[ClientTextVisibilityExtensionT] = clientTextVisibilityExtensions, + newGeneratedTextRequests: Vector[GeneratedTextRequestT] = newGeneratedTextRequests, newNotifications: Vector[NotificationT] = newNotifications, removedNotifications: Vector[NotificationT] = removedNotifications, newVictorFactionId: Option[FactionId] = newVictorFactionId, @@ -128,9 +126,7 @@ trait ActionResultT { def withDestroyedBattalionIds( destroyedBattalionIds: Iterable[BattalionId] ): ActionResultT = - copy(destroyedBattalionIds = - this.destroyedBattalionIds ++ destroyedBattalionIds - ) + copy(destroyedBattalionIds = this.destroyedBattalionIds ++ destroyedBattalionIds) def withRemovedHero(removedHero: HeroId): ActionResultT = copy(removedHeroes = removedHeroIds :+ removedHero) @@ -141,16 +137,12 @@ trait ActionResultT { def withNewGeneratedTextRequest( generatedTextRequest: GeneratedTextRequestT ): ActionResultT = - copy(newGeneratedTextRequests = - newGeneratedTextRequests :+ generatedTextRequest - ) + copy(newGeneratedTextRequests = newGeneratedTextRequests :+ generatedTextRequest) def withNewGeneratedTextRequests( generatedTextRequests: Iterable[GeneratedTextRequestT] ): ActionResultT = - copy(newGeneratedTextRequests = - this.newGeneratedTextRequests ++ generatedTextRequests - ) + copy(newGeneratedTextRequests = this.newGeneratedTextRequests ++ generatedTextRequests) def withNotification(notification: NotificationT): ActionResultT = copy(newNotifications = newNotifications :+ notification) diff --git a/src/main/scala/net/eagle0/eagle/model/action_result/NotificationT.scala b/src/main/scala/net/eagle0/eagle/model/action_result/NotificationT.scala index 1ba239ece7..8d45a9c852 100644 --- a/src/main/scala/net/eagle0/eagle/model/action_result/NotificationT.scala +++ b/src/main/scala/net/eagle0/eagle/model/action_result/NotificationT.scala @@ -6,8 +6,8 @@ import net.eagle0.eagle.model.state.quest.QuestT object NotificationT { sealed trait Llm object Llm { - case object Empty extends Llm - case class Id(id: String) extends Llm + case object Empty extends Llm + case class Id(id: String) extends Llm case class Message(message: String) extends Llm } } diff --git a/src/main/scala/net/eagle0/eagle/model/action_result/changed_province/concrete/ChangedProvinceC.scala b/src/main/scala/net/eagle0/eagle/model/action_result/changed_province/concrete/ChangedProvinceC.scala index 0e1048a711..b822897313 100644 --- a/src/main/scala/net/eagle0/eagle/model/action_result/changed_province/concrete/ChangedProvinceC.scala +++ b/src/main/scala/net/eagle0/eagle/model/action_result/changed_province/concrete/ChangedProvinceC.scala @@ -1,12 +1,6 @@ package net.eagle0.eagle.model.action_result.changed_province.concrete -import net.eagle0.eagle.{ - BattalionId, - FactionId, - HeroId, - MovingSuppliesId, - ProvinceId -} +import net.eagle0.eagle.{BattalionId, FactionId, HeroId, MovingSuppliesId, ProvinceId} import net.eagle0.eagle.model.action_result.changed_province.ChangedProvinceT import net.eagle0.eagle.model.state.{ Army, @@ -18,17 +12,12 @@ import net.eagle0.eagle.model.state.{ MovingArmy, MovingSupplies } -import net.eagle0.eagle.model.state.province.{ - DeferredChangeT, - IncomingEndTurnAction, - ProvinceEvent, - ProvinceOrderType -} +import net.eagle0.eagle.model.state.province.{DeferredChangeT, IncomingEndTurnAction, ProvinceEvent, ProvinceOrderType} import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroT sealed trait NewLockedImprovementType object NewLockedImprovementType { - case object None extends NewLockedImprovementType + case object None extends NewLockedImprovementType case class New(value: ImprovementType) extends NewLockedImprovementType } @@ -125,11 +114,10 @@ case class ChangedProvinceC( def withRemovedUnaffiliatedHeroIds( heroIds: Vector[HeroId] - ): ChangedProvinceC = { + ): ChangedProvinceC = copy( removedUnaffiliatedHeroIds = removedUnaffiliatedHeroIds ++ heroIds ) - } def withChangedUnaffiliatedHeroes( heroes: Vector[UnaffiliatedHeroT] diff --git a/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ActionResultC.scala b/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ActionResultC.scala index 862d2a238c..b949fc291a 100644 --- a/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ActionResultC.scala +++ b/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ActionResultC.scala @@ -45,8 +45,7 @@ case class ActionResultC( destroyedBattalionIds: Vector[BattalionId] = Vector.empty, removedHeroIds: Vector[HeroId] = Vector.empty, removedFactionIds: Vector[FactionId] = Vector.empty, - clientTextVisibilityExtensions: Vector[ClientTextVisibilityExtensionT] = - Vector.empty, + clientTextVisibilityExtensions: Vector[ClientTextVisibilityExtensionT] = Vector.empty, newGeneratedTextRequests: Vector[GeneratedTextRequestT] = Vector.empty, newNotifications: Vector[NotificationT] = Vector.empty, removedNotifications: Vector[NotificationT] = Vector.empty, @@ -79,10 +78,8 @@ case class ActionResultC( destroyedBattalionIds: Vector[BattalionId] = destroyedBattalionIds, removedHeroes: Vector[HeroId] = removedHeroIds, removedFactionIds: Vector[FactionId] = removedFactionIds, - clientTextVisibilityExtensions: Vector[ClientTextVisibilityExtensionT] = - clientTextVisibilityExtensions, - newGeneratedTextRequests: Vector[GeneratedTextRequestT] = - newGeneratedTextRequests, + clientTextVisibilityExtensions: Vector[ClientTextVisibilityExtensionT] = clientTextVisibilityExtensions, + newGeneratedTextRequests: Vector[GeneratedTextRequestT] = newGeneratedTextRequests, newNotifications: Vector[NotificationT] = newNotifications, removedNotifications: Vector[NotificationT] = removedNotifications, newVictorFactionId: Option[FactionId] = newVictorFactionId, diff --git a/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedFactionC.scala b/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedFactionC.scala index 3e6322af9e..f45ae4908e 100644 --- a/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedFactionC.scala +++ b/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedFactionC.scala @@ -9,10 +9,7 @@ import net.eagle0.eagle.model.action_result.concrete.ChangedFactionC.{ } import net.eagle0.eagle.model.action_result.ChangedFactionT import net.eagle0.eagle.model.state.diplomacy_offer.DiplomacyOffer -import net.eagle0.eagle.model.state.faction.{ - FactionRelationship, - PrestigeModifier -} +import net.eagle0.eagle.model.state.faction.{FactionRelationship, PrestigeModifier} import net.eagle0.eagle.views.province_view.ProvinceView case class TrustLevelUpdate( @@ -39,14 +36,10 @@ case class ChangedFactionC( removedFactionRelationshipFactionIds: Vector[FactionId] = Vector.empty, newIncomingDiplomacyOffers: Vector[DiplomacyOffer] = Vector.empty, removedIncomingDiplomacyOfferFactionIds: Vector[FactionId] = Vector.empty, - newOutgoingTruceOfferFactionIds: Vector[OutgoingTruceOfferFactionId] = - Vector.empty, - newOutgoingAllianceOfferFactionIds: Vector[OutgoingAllianceOfferFactionId] = - Vector.empty, - newOutgoingInvitationFactionIds: Vector[OutgoingInvitationFactionId] = - Vector.empty, - newOutgoingRansomOfferFactionIds: Vector[OutgoingRansomOfferFactionId] = - Vector.empty, + newOutgoingTruceOfferFactionIds: Vector[OutgoingTruceOfferFactionId] = Vector.empty, + newOutgoingAllianceOfferFactionIds: Vector[OutgoingAllianceOfferFactionId] = Vector.empty, + newOutgoingInvitationFactionIds: Vector[OutgoingInvitationFactionId] = Vector.empty, + newOutgoingRansomOfferFactionIds: Vector[OutgoingRansomOfferFactionId] = Vector.empty, newFocusProvinceId: Option[ProvinceId] = None, clearFocusProvinceId: Boolean = false, updatedReconnedProvinces: Vector[ProvinceView] = Vector.empty, diff --git a/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedHeroC.scala b/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedHeroC.scala index 0e060aa128..a900c8242f 100644 --- a/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedHeroC.scala +++ b/src/main/scala/net/eagle0/eagle/model/action_result/concrete/ChangedHeroC.scala @@ -5,9 +5,9 @@ import net.eagle0.eagle.model.action_result.ChangedHeroT import net.eagle0.eagle.model.state.hero.EventForHeroBackstoryT sealed trait StatChange -case class StatDelta(value: Double) extends StatChange +case class StatDelta(value: Double) extends StatChange case class StatAbsolute(value: Double) extends StatChange -case object StatNoChange extends StatChange +case object StatNoChange extends StatChange case class ChangedHeroC( heroId: HeroId, diff --git a/src/main/scala/net/eagle0/eagle/model/action_result/generated_text_request/GeneratedTextRequestT.scala b/src/main/scala/net/eagle0/eagle/model/action_result/generated_text_request/GeneratedTextRequestT.scala index 839ab51643..423e2161e2 100644 --- a/src/main/scala/net/eagle0/eagle/model/action_result/generated_text_request/GeneratedTextRequestT.scala +++ b/src/main/scala/net/eagle0/eagle/model/action_result/generated_text_request/GeneratedTextRequestT.scala @@ -27,7 +27,7 @@ case class FixedHeroName( fixedName: String ) extends GeneratedTextRequestT { override def recipientFactionIds: Vector[FactionId] = Vector.empty - override def alwaysGenerate: Boolean = true + override def alwaysGenerate: Boolean = true } case class GeneratedHeroName( @@ -36,7 +36,7 @@ case class GeneratedHeroName( gender: Gender ) extends GeneratedTextRequestT { override def recipientFactionIds: Vector[FactionId] = Vector.empty - override def alwaysGenerate: Boolean = true + override def alwaysGenerate: Boolean = true } enum LlmRequestT extends GeneratedTextRequestT: diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/ActionResultProtoConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/ActionResultProtoConverter.scala index ff78ac21d7..b54d4cf624 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/ActionResultProtoConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/ActionResultProtoConverter.scala @@ -18,11 +18,7 @@ import net.eagle0.eagle.model.action_result.{ NotificationT } import net.eagle0.eagle.model.action_result.changed_province.ChangedProvinceT -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedBattalionC, - ClientTextVisibilityExtensionC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedBattalionC, ClientTextVisibilityExtensionC} import net.eagle0.eagle.model.action_result.generated_text_request.{ FixedHeroName, GeneratedHeroName, @@ -33,10 +29,7 @@ import net.eagle0.eagle.model.action_result.types.base.ActionResultType import net.eagle0.eagle.model.proto_converters.date.DateConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.proto_converters.generated_text_request.LlmRequestConverter -import net.eagle0.eagle.model.proto_converters.hero.{ - GenderConverter, - HeroConverter -} +import net.eagle0.eagle.model.proto_converters.hero.{GenderConverter, HeroConverter} import net.eagle0.eagle.model.proto_converters.shardok_battle.ShardokBattleConverter import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.date.Date @@ -87,20 +80,16 @@ object ActionResultProtoConverter { player = actingFactionId, province = provinceId, provinceActed = provinceIdActed, - newRoundPhase = newRoundPhase.map(rp => - NewRoundPhaseProto(RoundPhaseConverter.toProto(rp)) - ), + newRoundPhase = newRoundPhase.map(rp => NewRoundPhaseProto(RoundPhaseConverter.toProto(rp))), newRoundId = newRoundId, newDate = newDate.map(DateConverter.toProto), newBattle = newBattle.map(ShardokBattleConverter.toProto), changedBattalions = changedBattalions.map { case ChangedBattalionC(to) => BattalionConverter.toProto(to) }, - changedFactions = - changedFactions.map(ChangedFactionConverter.toProto), + changedFactions = changedFactions.map(ChangedFactionConverter.toProto), changedHeroes = changedHeroes.map(ChangedHeroConverter.toProto), - changedProvinces = - changedProvinces.map(ChangedProvinceConverter.toProto), + changedProvinces = changedProvinces.map(ChangedProvinceConverter.toProto), clientTextVisibilityExtensions = clientTextVisibilityExtensions.map { case ClientTextVisibilityExtensionC( textId: String, @@ -118,9 +107,9 @@ object ActionResultProtoConverter { removedHeroes = removedHeroIds, removedFactionIds = removedFactionIds, newGeneratedTextRequests = newGeneratedTextRequests.map { - case llmRequestT: LlmRequestT => + case llmRequestT: LlmRequestT => LlmRequestConverter.toProto(llmRequestT) - case fixedHeroName: FixedHeroName => + case fixedHeroName: FixedHeroName => GeneratedTextRequest( id = fixedHeroName.requestId, eagleGameId = fixedHeroName.eagleGameId, @@ -144,28 +133,27 @@ object ActionResultProtoConverter { ) ) }, - removedNotifications = - removedNotifications.map(NotificationConverter.toProto).map(_._1), + removedNotifications = removedNotifications.map(NotificationConverter.toProto).map(_._1), newVictor = newVictorFactionId, gameEnded = gameEnded, newRandomSeed = newRandomSeed, affectedPlayers = affectedFactionIds ) - newNotifications.foldLeft(arInit) { case (ar, note: NotificationT) => - NotificationConverter.toProto(note) match { - case (noteProto, deferred) => - if deferred then { - ar.copy( - newDeferredNotification = Some(noteProto) - ) - } else { - ar.copy( - notificationsToDeliver = - ar.notificationsToDeliver :+ noteProto - ) - } - } + newNotifications.foldLeft(arInit) { + case (ar, note: NotificationT) => + NotificationConverter.toProto(note) match { + case (noteProto, deferred) => + if deferred then { + ar.copy( + newDeferredNotification = Some(noteProto) + ) + } else { + ar.copy( + notificationsToDeliver = ar.notificationsToDeliver :+ noteProto + ) + } + } } } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/ArmyConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/ArmyConverter.scala index 1f88f16ee0..def45c1892 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/ArmyConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/ArmyConverter.scala @@ -15,13 +15,7 @@ import net.eagle0.eagle.internal.army.{ } import net.eagle0.eagle.internal.army.HostileArmyGroupStatus.Empty import net.eagle0.eagle.model.proto_converters.ProtoConversionException -import net.eagle0.eagle.model.state.{ - Army, - HostileArmyGroup, - HostileArmyGroupStatus, - MovingArmy, - Supplies -} +import net.eagle0.eagle.model.state.{Army, HostileArmyGroup, HostileArmyGroupStatus, MovingArmy, Supplies} object ArmyConverter { def toProto(army: Army): ArmyProto = @@ -83,14 +77,14 @@ object ArmyConverter { def toProto( hostileArmyGroupStatus: HostileArmyGroupStatus ): HostileArmyGroupStatusProto = hostileArmyGroupStatus match { - case HostileArmyGroupStatus.AwaitingDecision => AwaitingDecisionProto() - case HostileArmyGroupStatus.AwaitingFreeForAll => AwaitingFreeForAllProto() - case HostileArmyGroupStatus.TributeDemanded(tributeAmount) => + case HostileArmyGroupStatus.AwaitingDecision => AwaitingDecisionProto() + case HostileArmyGroupStatus.AwaitingFreeForAll => AwaitingFreeForAllProto() + case HostileArmyGroupStatus.TributeDemanded(tributeAmount) => TributeDemandedProto(Some(TributeAmountConverter.toProto(tributeAmount))) - case HostileArmyGroupStatus.TributePaid(tributeAmount) => + case HostileArmyGroupStatus.TributePaid(tributeAmount) => TributePaidProto(Some(TributeAmountConverter.toProto(tributeAmount))) - case HostileArmyGroupStatus.Attacking => AttackingProto() - case HostileArmyGroupStatus.Withdrawing => WithdrawingProto() + case HostileArmyGroupStatus.Attacking => AttackingProto() + case HostileArmyGroupStatus.Withdrawing => WithdrawingProto() case HostileArmyGroupStatus.SafePassageGranted(destinationProvinceId) => SafePassageGrantedProto(destinationProvinceId) } @@ -98,21 +92,21 @@ object ArmyConverter { def fromProto( hostileArmyGroupStatusProto: HostileArmyGroupStatusProto ): HostileArmyGroupStatus = hostileArmyGroupStatusProto match { - case _: AwaitingDecisionProto => HostileArmyGroupStatus.AwaitingDecision - case _: AwaitingFreeForAllProto => HostileArmyGroupStatus.AwaitingFreeForAll - case TributeDemandedProto(tributeAmountProto, _) => + case _: AwaitingDecisionProto => HostileArmyGroupStatus.AwaitingDecision + case _: AwaitingFreeForAllProto => HostileArmyGroupStatus.AwaitingFreeForAll + case TributeDemandedProto(tributeAmountProto, _) => HostileArmyGroupStatus.TributeDemanded( TributeAmountConverter.fromProto(tributeAmountProto.get) ) - case TributePaidProto(tributeAmountProto, _) => + case TributePaidProto(tributeAmountProto, _) => HostileArmyGroupStatus.TributePaid( TributeAmountConverter.fromProto(tributeAmountProto.get) ) - case _: AttackingProto => HostileArmyGroupStatus.Attacking - case _: WithdrawingProto => HostileArmyGroupStatus.Withdrawing + case _: AttackingProto => HostileArmyGroupStatus.Attacking + case _: WithdrawingProto => HostileArmyGroupStatus.Withdrawing case SafePassageGrantedProto(destinationProvinceId, _) => HostileArmyGroupStatus.SafePassageGranted(destinationProvinceId) - case Empty => + case Empty => throw new ProtoConversionException( "hostile army group status cannot be empty" ) diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/BattleRevelationConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/BattleRevelationConverter.scala index 48f811aacd..c71760acd9 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/BattleRevelationConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/BattleRevelationConverter.scala @@ -10,9 +10,9 @@ object BattleRevelationConverter { battleRevelationType: BattleRevelationType ): BattleRevelationTypeProto = battleRevelationType match { - case BattleRevelationType.Unknown => + case BattleRevelationType.Unknown => BattleRevelationTypeProto.UNKNOWN - case BattleRevelationType.Withdrew => + case BattleRevelationType.Withdrew => BattleRevelationTypeProto.WITHDREW case BattleRevelationType.DidBattle => BattleRevelationTypeProto.DID_BATTLE @@ -22,11 +22,11 @@ object BattleRevelationConverter { battleRevelationTypeProto: BattleRevelationTypeProto ): BattleRevelationType = battleRevelationTypeProto match { - case BattleRevelationTypeProto.UNKNOWN => + case BattleRevelationTypeProto.UNKNOWN => BattleRevelationType.Unknown - case BattleRevelationTypeProto.WITHDREW => + case BattleRevelationTypeProto.WITHDREW => BattleRevelationType.Withdrew - case BattleRevelationTypeProto.DID_BATTLE => + case BattleRevelationTypeProto.DID_BATTLE => BattleRevelationType.DidBattle case BattleRevelationTypeProto.Unrecognized(unrecognizedValue) => throw new ProtoConversionException( diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/CapturedHeroConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/CapturedHeroConverter.scala index bf04134a37..1f53b3d2cf 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/CapturedHeroConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/CapturedHeroConverter.scala @@ -19,7 +19,6 @@ object CapturedHeroConverter { recruitmentAttempted = capturedHeroProto.recruitmentAttempted, previousFactionId = capturedHeroProto.previousFactionId, messageId = capturedHeroProto.messageId, - recruitmentRefusedMessageId = - capturedHeroProto.recruitmentRefusedMessageId + recruitmentRefusedMessageId = capturedHeroProto.recruitmentRefusedMessageId ) } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedFactionConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedFactionConverter.scala index e07c8c8ca3..c5823cd2e1 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedFactionConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedFactionConverter.scala @@ -8,10 +8,7 @@ import net.eagle0.eagle.internal.changed_faction.{ } import net.eagle0.eagle.internal.faction.PrestigeModifier as PrestigeModifierProto import net.eagle0.eagle.internal.faction_relationship.FactionRelationship as FactionRelationshipProto -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedFactionC, - TrustLevelUpdate -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedFactionC, TrustLevelUpdate} import net.eagle0.eagle.model.action_result.concrete.ChangedFactionC.{ OutgoingAllianceOfferFactionId, OutgoingInvitationFactionId, @@ -22,10 +19,7 @@ import net.eagle0.eagle.model.action_result.ChangedFactionT import net.eagle0.eagle.model.proto_converters.diplomacy_offer.DiplomacyOfferConverter import net.eagle0.eagle.model.proto_converters.faction.FactionConverter import net.eagle0.eagle.model.state.diplomacy_offer.DiplomacyOffer -import net.eagle0.eagle.model.state.faction.{ - FactionRelationship, - PrestigeModifier -} +import net.eagle0.eagle.model.state.faction.{FactionRelationship, PrestigeModifier} import net.eagle0.eagle.views.province_view.ProvinceView object ChangedFactionConverter { @@ -67,26 +61,16 @@ object ChangedFactionConverter { newFactionHeadId = newFactionHeadHeroId, addedLeaders = newLeaderHeroIds, removedLeaders = removedLeaderHeroIds, - addedPrestigeModifiers = - newPrestigeModifiers.map(FactionConverter.toProto), - removedPrestigeModifiers = - removedPrestigeModifiers.map(FactionConverter.toProto), - changedFactionRelationships = - changedFactionRelationships.map(FactionConverter.toProto), - removedFactionRelationshipPartners = - removedFactionRelationshipFactionIds, - addedIncomingDiplomacyOffers = - newIncomingDiplomacyOffers.map(DiplomacyOfferConverter.toProto), - removedIncomingDiplomacyOfferFactionIds = - removedIncomingDiplomacyOfferFactionIds, - addedOutgoingTruceOfferPartners = - newOutgoingTruceOfferFactionIds.map(_.fid), - addedOutgoingAllianceOfferPartners = - newOutgoingAllianceOfferFactionIds.map(_.fid), - addedOutgoingInvitationPartners = - newOutgoingInvitationFactionIds.map(_.fid), - addedOutgoingRansomOfferPartners = - newOutgoingRansomOfferFactionIds.map(_.fid), + addedPrestigeModifiers = newPrestigeModifiers.map(FactionConverter.toProto), + removedPrestigeModifiers = removedPrestigeModifiers.map(FactionConverter.toProto), + changedFactionRelationships = changedFactionRelationships.map(FactionConverter.toProto), + removedFactionRelationshipPartners = removedFactionRelationshipFactionIds, + addedIncomingDiplomacyOffers = newIncomingDiplomacyOffers.map(DiplomacyOfferConverter.toProto), + removedIncomingDiplomacyOfferFactionIds = removedIncomingDiplomacyOfferFactionIds, + addedOutgoingTruceOfferPartners = newOutgoingTruceOfferFactionIds.map(_.fid), + addedOutgoingAllianceOfferPartners = newOutgoingAllianceOfferFactionIds.map(_.fid), + addedOutgoingInvitationPartners = newOutgoingInvitationFactionIds.map(_.fid), + addedOutgoingRansomOfferPartners = newOutgoingRansomOfferFactionIds.map(_.fid), newFocusProvinceId = newFocusProvinceId, clearFocusProvinceId = clearFocusProvinceId, updatedReconnedProvinces = updatedReconnedProvinces, @@ -133,27 +117,22 @@ object ChangedFactionConverter { newFactionHeadHeroId = newFactionHeadId, newLeaderHeroIds = addedLeaders.toVector, removedLeaderHeroIds = removedLeaders.toVector, - newPrestigeModifiers = - addedPrestigeModifiers.map(FactionConverter.fromProto).toVector, - removedPrestigeModifiers = - removedPrestigeModifiers.map(FactionConverter.fromProto).toVector, + newPrestigeModifiers = addedPrestigeModifiers.map(FactionConverter.fromProto).toVector, + removedPrestigeModifiers = removedPrestigeModifiers.map(FactionConverter.fromProto).toVector, changedFactionRelationships = changedFactionRelationships .map(FactionConverter.fromProto) .toVector, - removedFactionRelationshipFactionIds = - removedFactionRelationshipPartners.toVector, + removedFactionRelationshipFactionIds = removedFactionRelationshipPartners.toVector, newIncomingDiplomacyOffers = addedIncomingDiplomacyOffers .map(DiplomacyOfferConverter.fromProto) .toVector, - removedIncomingDiplomacyOfferFactionIds = - removedIncomingDiplomacyOfferFactionIds.toVector, + removedIncomingDiplomacyOfferFactionIds = removedIncomingDiplomacyOfferFactionIds.toVector, newOutgoingTruceOfferFactionIds = addedOutgoingTruceOfferPartners .map(fid => OutgoingTruceOfferFactionId(fid)) .toVector, - newOutgoingAllianceOfferFactionIds = - addedOutgoingAllianceOfferPartners - .map(fid => OutgoingAllianceOfferFactionId(fid)) - .toVector, + newOutgoingAllianceOfferFactionIds = addedOutgoingAllianceOfferPartners + .map(fid => OutgoingAllianceOfferFactionId(fid)) + .toVector, newOutgoingInvitationFactionIds = addedOutgoingInvitationPartners .map(fid => OutgoingInvitationFactionId(fid)) .toVector, diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedHeroConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedHeroConverter.scala index 33658fbe90..539c80209c 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedHeroConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedHeroConverter.scala @@ -1,21 +1,10 @@ package net.eagle0.eagle.model.proto_converters import net.eagle0.eagle.internal.changed_hero.ChangedHero.{Loyalty, Vigor} -import net.eagle0.eagle.internal.changed_hero.ChangedHero.Loyalty.{ - LoyaltyAbsolute, - LoyaltyDelta -} -import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor.{ - VigorAbsolute, - VigorDelta -} +import net.eagle0.eagle.internal.changed_hero.ChangedHero.Loyalty.{LoyaltyAbsolute, LoyaltyDelta} +import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor.{VigorAbsolute, VigorDelta} import net.eagle0.eagle.internal.changed_hero.ChangedHero as ChangedHeroProto -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedHeroC, - StatAbsolute, - StatDelta, - StatNoChange -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatAbsolute, StatDelta, StatNoChange} import net.eagle0.eagle.model.action_result.ChangedHeroT import net.eagle0.eagle.model.proto_converters.hero.EventForHeroBackstoryConverter @@ -56,8 +45,7 @@ object ChangedHeroConverter { wisdomXpDelta = wisdomXpDelta, constitutionXpDelta = constitutionXpDelta, newBackstoryTextId = newBackstoryTextId, - newBackstoryEvents = - newEventsForHeroBackstory.map(EventForHeroBackstoryConverter.toProto), + newBackstoryEvents = newEventsForHeroBackstory.map(EventForHeroBackstoryConverter.toProto), clearBackstoryEvents = clearEventsForHeroBackstory ) } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedProvinceConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedProvinceConverter.scala index 26b8d1019a..92d6683d49 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedProvinceConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/ChangedProvinceConverter.scala @@ -1,13 +1,6 @@ package net.eagle0.eagle.model.proto_converters -import net.eagle0.eagle.{ - BattalionId, - FactionId, - HeroId, - MovingArmyId, - MovingSuppliesId, - ProvinceId -} +import net.eagle0.eagle.{BattalionId, FactionId, HeroId, MovingArmyId, MovingSuppliesId, ProvinceId} import net.eagle0.eagle.common.improvement_type.ImprovementType.NONE import net.eagle0.eagle.common.province_order_type.ProvinceOrderType as ProvinceOrderTypeProto import net.eagle0.eagle.internal.changed_province.ChangedProvince.{ @@ -24,20 +17,8 @@ import net.eagle0.eagle.model.action_result.changed_province.concrete.{ } import net.eagle0.eagle.model.action_result.changed_province.ChangedProvinceT import net.eagle0.eagle.model.proto_converters.province.ProvinceEventConverter -import net.eagle0.eagle.model.state.{ - Army, - BattleRevelation, - CapturedHero, - HostileArmyGroup, - MovingArmy, - MovingSupplies -} -import net.eagle0.eagle.model.state.province.{ - DeferredChangeT, - IncomingEndTurnAction, - ProvinceEvent, - ProvinceOrderType -} +import net.eagle0.eagle.model.state.{Army, BattleRevelation, CapturedHero, HostileArmyGroup, MovingArmy, MovingSupplies} +import net.eagle0.eagle.model.state.province.{DeferredChangeT, IncomingEndTurnAction, ProvinceEvent, ProvinceOrderType} import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroT object ChangedProvinceConverter { @@ -107,16 +88,12 @@ object ChangedProvinceConverter { newUnaffiliatedHeroes = newUnaffiliatedHeroes.map( UnaffiliatedHeroConverter.toProto ), - changedUnaffiliatedHeroes = - changedUnaffiliatedHeroes.map(UnaffiliatedHeroConverter.toProto), + changedUnaffiliatedHeroes = changedUnaffiliatedHeroes.map(UnaffiliatedHeroConverter.toProto), removedUnaffiliatedHeroIds = removedUnaffiliatedHeroIds, - addedDeferredChange = - DeferredChangeConverter.toProto(newDeferredChange), + addedDeferredChange = DeferredChangeConverter.toProto(newDeferredChange), removedDeferredChangeIndex = removedDeferredChangeIndex, - newCapturedHeroes = - newCapturedHeroes.map(CapturedHeroConverter.toProto), - recruitmentAttemptedCapturedHeroIds = - recruitmentAtteptedCapturedHeroIds, + newCapturedHeroes = newCapturedHeroes.map(CapturedHeroConverter.toProto), + recruitmentAttemptedCapturedHeroIds = recruitmentAtteptedCapturedHeroIds, removedCapturedHeroIds = removedCapturedHeroIds, clearRulingFactionId = clearRulingFactionId, newRulingFactionId = newRulingFactionId, @@ -131,8 +108,7 @@ object ChangedProvinceConverter { ), addedIncomingArmies = newIncomingArmies.map(ArmyConverter.toProto), removedIncomingArmyIds = removedIncomingArmyIds, - addedWithdrawingArmies = - newWithdrawingArmies.map(ArmyConverter.toProto), + addedWithdrawingArmies = newWithdrawingArmies.map(ArmyConverter.toProto), removedWithdrawingArmyIds = removedWithdrawingArmyIds, addedHostileArmies = newHostileArmies.map(ArmyConverter.toProto), removedHostileArmyFactionIds = removedHostileArmyFactionIds, @@ -145,8 +121,7 @@ object ChangedProvinceConverter { }, newDefendingArmy = newDefendingArmy.map(ArmyConverter.toProto), clearDefendingArmy = clearDefendingArmy, - addedIncomingShipments = - newIncomingShipments.map(SuppliesConverter.toProto), + addedIncomingShipments = newIncomingShipments.map(SuppliesConverter.toProto), removedIncomingShipmentIds = removedIncomingShipmentIds, addedIncomingEndTurnActions = newIncomingEndTurnActions.map( IncomingEndTurnActionConverter.toProto @@ -162,15 +137,14 @@ object ChangedProvinceConverter { case NewLockedImprovementType.None => NONE }) }, - newProvinceOrders = newProvinceOrders - .map { - case ProvinceOrderType.UnknownOrderType => - ProvinceOrderTypeProto.UNKNOWN_ORDERS - case ProvinceOrderType.Entrust => ProvinceOrderTypeProto.ENTRUST - case ProvinceOrderType.Develop => ProvinceOrderTypeProto.DEVELOP - case ProvinceOrderType.Expand => ProvinceOrderTypeProto.EXPAND - case ProvinceOrderType.Mobilize => ProvinceOrderTypeProto.MOBILIZE - } + newProvinceOrders = newProvinceOrders.map { + case ProvinceOrderType.UnknownOrderType => + ProvinceOrderTypeProto.UNKNOWN_ORDERS + case ProvinceOrderType.Entrust => ProvinceOrderTypeProto.ENTRUST + case ProvinceOrderType.Develop => ProvinceOrderTypeProto.DEVELOP + case ProvinceOrderType.Expand => ProvinceOrderTypeProto.EXPAND + case ProvinceOrderType.Mobilize => ProvinceOrderTypeProto.MOBILIZE + } .map(pot => ProvinceOrdersOption(pot)), addedBattleRevelations = newBattleRevelations.map( BattleRevelationConverter.toProto diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/DeferredChangeConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/DeferredChangeConverter.scala index 39f1f01912..f76b329360 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/DeferredChangeConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/DeferredChangeConverter.scala @@ -34,16 +34,16 @@ object DeferredChangeConverter { responsibleFaction = responsibleFaction, durationMonths = durationMonths ) - case DeferredChange.BlizzardEnded(responsibleFaction) => + case DeferredChange.BlizzardEnded(responsibleFaction) => BlizzardEnded(responsibleFaction) - case DeferredChange.EpidemicStarted(responsibleFaction) => + case DeferredChange.EpidemicStarted(responsibleFaction) => EpidemicStarted(responsibleFaction) - case DeferredChange.DroughtStarted(responsibleFaction, durationMonths) => + case DeferredChange.DroughtStarted(responsibleFaction, durationMonths) => DroughtStarted( responsibleFaction = responsibleFaction, durationMonths = durationMonths ) - case DeferredChange.DroughtEnded(responsibleFaction) => + case DeferredChange.DroughtEnded(responsibleFaction) => DroughtEnded(responsibleFaction) case DeferredChange.PrisonerMoved(heroId, fromProvinceId, toProvinceId) => PrisonerMoved( diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/ImprovementTypeConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/ImprovementTypeConverter.scala index 469778757b..52993bf68b 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/ImprovementTypeConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/ImprovementTypeConverter.scala @@ -22,10 +22,10 @@ object ImprovementTypeConverter { improvementTypeProto: ImprovementTypeProto ): Option[ImprovementType] = improvementTypeProto match { - case ImprovementTypeProto.AGRICULTURE => Some(ImprovementType.Agriculture) - case ImprovementTypeProto.DEVASTATION => Some(ImprovementType.Devastation) - case ImprovementTypeProto.ECONOMY => Some(ImprovementType.Economy) - case ImprovementTypeProto.INFRASTRUCTURE => + case ImprovementTypeProto.AGRICULTURE => Some(ImprovementType.Agriculture) + case ImprovementTypeProto.DEVASTATION => Some(ImprovementType.Devastation) + case ImprovementTypeProto.ECONOMY => Some(ImprovementType.Economy) + case ImprovementTypeProto.INFRASTRUCTURE => Some(ImprovementType.Infrastructure) case ImprovementTypeProto.NONE => None case ImprovementTypeProto.UNKNOWN => None diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/IncomingEndTurnActionConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/IncomingEndTurnActionConverter.scala index bb7f3611eb..9c7149fe0c 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/IncomingEndTurnActionConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/IncomingEndTurnActionConverter.scala @@ -4,10 +4,7 @@ import net.eagle0.eagle.internal.province.IncomingEndTurnAction.Action.Empty import net.eagle0.eagle.internal.province.IncomingEndTurnAction.IncomingRecon as IncomingReconProto import net.eagle0.eagle.internal.province.IncomingEndTurnAction as IncomingEndTurnActionProto import net.eagle0.eagle.model.proto_converters.ProtoConversionException -import net.eagle0.eagle.model.state.province.{ - IncomingEndTurnAction, - IncomingRecon -} +import net.eagle0.eagle.model.state.province.{IncomingEndTurnAction, IncomingRecon} object IncomingEndTurnActionConverter { def toProto( diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/NotificationConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/NotificationConverter.scala index 107c4590de..05a3fb71f9 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/NotificationConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/NotificationConverter.scala @@ -181,7 +181,7 @@ object NotificationConverter { returnedHeroId = returnedHeroId, returningFactionId = returningFactionId ) - case NotificationDetails.Divined => DivinedDetails() + case NotificationDetails.Divined => DivinedDetails() case NotificationDetails.HeroDeparture( departingHeroId, fromFactionId, @@ -228,12 +228,12 @@ object NotificationConverter { provinceId = provinceId, apprehendedHeroId = apprehendedHeroId ) - case NotificationDetails.OutlawSpotted(outlawHeroId, provinceId) => + case NotificationDetails.OutlawSpotted(outlawHeroId, provinceId) => OutlawSpottedDetails( outlawHeroId = outlawHeroId, provinceId = provinceId ) - case NotificationDetails.QuestFailed(heroId, provinceId, failedQuest) => + case NotificationDetails.QuestFailed(heroId, provinceId, failedQuest) => QuestFailedDetails( heroId = heroId, provinceId = provinceId, @@ -249,7 +249,7 @@ object NotificationConverter { provinceId = provinceId, fulfilledQuest = Some(QuestConverter.toProto(fulfilledQuest)) ) - case NotificationDetails.ShatteredArmy(factionId, provinceId, reason) => + case NotificationDetails.ShatteredArmy(factionId, provinceId, reason) => ShatteredArmyDetails( factionId = factionId, provinceId = provinceId, @@ -773,15 +773,15 @@ object NotificationConverter { factionId = factionId, provinceId = provinceId, reason = reason match { - case ShatteredArmyDetails.Reason.SHATTERED_ARMY_REASON_BLIZZARD => + case ShatteredArmyDetails.Reason.SHATTERED_ARMY_REASON_BLIZZARD => NotificationDetails.ShatteredArmy.Reason.Blizzard - case ShatteredArmyDetails.Reason.SHATTERED_ARMY_REASON_WITHDRAW => + case ShatteredArmyDetails.Reason.SHATTERED_ARMY_REASON_WITHDRAW => NotificationDetails.ShatteredArmy.Reason.Withdrew case ShatteredArmyDetails.Reason.SHATTERED_ARMY_REASON_UNKNOWN_UNSPECIFIED => throw new ProtoConversionException( s"Unspecified ShatteredArmyDetails reason" ) - case ShatteredArmyDetails.Reason.Unrecognized(unrecognizedValue) => + case ShatteredArmyDetails.Reason.Unrecognized(unrecognizedValue) => throw new ProtoConversionException( s"Unrecognized ShatteredArmyDetails reason: $unrecognizedValue" ) diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/ProtoConversionException.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/ProtoConversionException.scala index 3d6c711653..3c796e2fd7 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/ProtoConversionException.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/ProtoConversionException.scala @@ -2,5 +2,4 @@ package net.eagle0.eagle.model.proto_converters import net.eagle0.eagle.library.EagleInternalException -class ProtoConversionException(message: String) - extends EagleInternalException(message) +class ProtoConversionException(message: String) extends EagleInternalException(message) diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/QuestConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/QuestConverter.scala index aa5f2f4972..ae81fb0668 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/QuestConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/QuestConverter.scala @@ -60,13 +60,13 @@ object QuestConverter { } questC match { - case q: AlmsAcrossRealmQuest => + case q: AlmsAcrossRealmQuest => QuestProto( details = AlmsAcrossRealmQuestProto(q.totalFood), componentCount = q.componentCount, componentsFulfilled = q.componentsFulfilled ) - case q: AlmsToProvinceQuest => + case q: AlmsToProvinceQuest => QuestProto( details = AlmsToProvinceQuestProto( provinceId = q.provinceId, @@ -75,25 +75,25 @@ object QuestConverter { componentCount = q.componentCount, componentsFulfilled = q.componentsFulfilled ) - case q: DefeatFactionQuest => + case q: DefeatFactionQuest => QuestProto(details = DefeatFactionQuestProto(q.targetFactionId)) - case q: DismissSpecificVassalQuest => + case q: DismissSpecificVassalQuest => QuestProto(details = DismissSpecificVassalQuestProto(q.targetHeroId)) - case q: ExecutePrisonerQuest => + case q: ExecutePrisonerQuest => QuestProto( details = ExecutePrisonerQuestProto( prisonerHeroId = q.prisonerHeroId, provinceId = q.prisonerProvinceId ) ) - case q: ExilePrisonerQuest => + case q: ExilePrisonerQuest => QuestProto( details = ExilePrisonerQuestProto( prisonerHeroId = q.prisonerHeroId, provinceId = q.prisonerProvinceId ) ) - case q: ReleasePrisonerQuest => + case q: ReleasePrisonerQuest => QuestProto( details = ReleasePrisonerQuestProto( prisonerHeroId = q.prisonerHeroId, @@ -106,7 +106,7 @@ object QuestConverter { componentCount = q.componentCount, componentsFulfilled = q.componentsFulfilled ) - case q: GiveToHeroesInProvinceQuest => + case q: GiveToHeroesInProvinceQuest => QuestProto( details = GiveToHeroesInProvinceQuestProto( provinceId = q.provinceId, @@ -115,30 +115,30 @@ object QuestConverter { componentCount = q.componentCount, componentsFulfilled = q.componentsFulfilled ) - case q: GrandArmyQuest => + case q: GrandArmyQuest => QuestProto(details = GrandArmyQuestProto(q.totalTroopCount)) - case q: ImproveAgricultureQuest => + case q: ImproveAgricultureQuest => QuestProto( details = ImproveAgricultureQuestProto( provinceId = q.provinceId, desiredValue = q.desiredValue ) ) - case q: ImproveEconomyQuest => + case q: ImproveEconomyQuest => QuestProto( details = ImproveEconomyQuestProto( provinceId = q.provinceId, desiredValue = q.desiredValue ) ) - case q: ImproveInfrastructureQuest => + case q: ImproveInfrastructureQuest => QuestProto( details = ImproveInfrastructureQuestProto( provinceId = q.provinceId, desiredValue = q.desiredValue ) ) - case q: ReturnPrisonerQuest => + case q: ReturnPrisonerQuest => QuestProto( details = ReturnPrisonerQuestProto( prisonerHeroId = q.prisonerHeroId, @@ -146,34 +146,33 @@ object QuestConverter { toFactionId = q.toFactionId ) ) - case q: SpecificExpansionQuest => + case q: SpecificExpansionQuest => QuestProto(details = SpecificExpansionQuestProto(q.provinceId)) - case q: TruceCountQuest => + case q: TruceCountQuest => QuestProto(details = TruceCountQuestProto(q.truceCount)) - case q: TruceWithFactionQuest => + case q: TruceWithFactionQuest => QuestProto(details = TruceWithFactionQuestProto(q.targetFactionId)) - case q: UpgradeBattalionQuest => + case q: UpgradeBattalionQuest => QuestProto( details = UpgradeBattalionQuestProto( provinceId = q.provinceId, - battalionTypeId = - BattalionTypeIdProto.fromValue(q.battalionTypeId.value), + battalionTypeId = BattalionTypeIdProto.fromValue(q.battalionTypeId.value), minimumArmament = q.minimumArmament, minimumTraining = q.minimumTraining ) ) - case q: WealthQuest => + case q: WealthQuest => QuestProto(details = WealthQuestProto(q.gold, q.food)) - case _ => + case _ => throw new IllegalArgumentException(s"Unknown quest type: $questC") } } def fromProto(questProto: QuestProto): QuestC = questProto.details match { - case AllianceQuestProto(_ /* unknownFieldSet */ ) => + case AllianceQuestProto(_ /* unknownFieldSet */ ) => AllianceQuest - case AlmsAcrossRealmQuestProto(totalFood, _ /* unknownFieldSet */ ) => + case AlmsAcrossRealmQuestProto(totalFood, _ /* unknownFieldSet */ ) => AlmsAcrossRealmQuest( componentCount = questProto.componentCount, componentsFulfilled = questProto.componentsFulfilled, @@ -235,7 +234,7 @@ object QuestConverter { provinceId = provinceId, totalGold = totalGold ) - case GrandArmyQuestProto(totalTroopCount, _ /* unknownFieldSet */ ) => + case GrandArmyQuestProto(totalTroopCount, _ /* unknownFieldSet */ ) => GrandArmyQuest(totalTroopCount) case ImproveAgricultureQuestProto( provinceId, @@ -262,9 +261,9 @@ object QuestConverter { _ /* unknownFieldSet */ ) => ReturnPrisonerQuest(prisonerHeroId, provinceId, toFactionId) - case SpecificExpansionQuestProto(provinceId, _ /* unknownFieldSet */ ) => + case SpecificExpansionQuestProto(provinceId, _ /* unknownFieldSet */ ) => SpecificExpansionQuest(provinceId) - case TruceCountQuestProto(truceCount, _ /* unknownFieldSet */ ) => + case TruceCountQuestProto(truceCount, _ /* unknownFieldSet */ ) => TruceCountQuest(truceCount) case TruceWithFactionQuestProto( targetFactionId, @@ -284,9 +283,9 @@ object QuestConverter { minimumArmament, minimumTraining ) - case WealthQuestProto(gold, food, _ /* unknownFieldSet */ ) => + case WealthQuestProto(gold, food, _ /* unknownFieldSet */ ) => WealthQuest(gold, food) - case QuestDetailsProto.Empty => + case QuestDetailsProto.Empty => throw new IllegalArgumentException("Empty quest details") } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/RoundPhaseConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/RoundPhaseConverter.scala index 697e7ee1fa..e728069d5e 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/RoundPhaseConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/RoundPhaseConverter.scala @@ -6,72 +6,72 @@ import net.eagle0.eagle.model.state.RoundPhase object RoundPhaseConverter { def toProto(roundPhase: RoundPhase): RoundPhaseProto = roundPhase match { - case RoundPhase.NewRound => RoundPhaseProto.NEW_ROUND - case RoundPhase.PrisonerExchange => RoundPhaseProto.PRISONER_EXCHANGE - case RoundPhase.ProvinceEvents => RoundPhaseProto.PROVINCE_EVENTS - case RoundPhase.ForcedTurnBack => RoundPhaseProto.FORCED_TURN_BACK - case RoundPhase.ProvinceMoveResolution => + case RoundPhase.NewRound => RoundPhaseProto.NEW_ROUND + case RoundPhase.PrisonerExchange => RoundPhaseProto.PRISONER_EXCHANGE + case RoundPhase.ProvinceEvents => RoundPhaseProto.PROVINCE_EVENTS + case RoundPhase.ForcedTurnBack => RoundPhaseProto.FORCED_TURN_BACK + case RoundPhase.ProvinceMoveResolution => RoundPhaseProto.PROVINCE_MOVE_RESOLUTION - case RoundPhase.HandleRiot => RoundPhaseProto.HANDLE_RIOT - case RoundPhase.HeroDepartures => RoundPhaseProto.HERO_DEPARTURES - case RoundPhase.PleaseRecruitMe => RoundPhaseProto.PLEASE_RECRUIT_ME - case RoundPhase.UnaffiliatedHeroActions => + case RoundPhase.HandleRiot => RoundPhaseProto.HANDLE_RIOT + case RoundPhase.HeroDepartures => RoundPhaseProto.HERO_DEPARTURES + case RoundPhase.PleaseRecruitMe => RoundPhaseProto.PLEASE_RECRUIT_ME + case RoundPhase.UnaffiliatedHeroActions => RoundPhaseProto.UNAFFILIATED_HERO_ACTIONS - case RoundPhase.VassalCommands => RoundPhaseProto.VASSAL_COMMANDS - case RoundPhase.PlayerCommands => RoundPhaseProto.PLAYER_COMMANDS - case RoundPhase.HostileArmySetup => RoundPhaseProto.HOSTILE_ARMY_SETUP - case RoundPhase.FreeForAllDecision => RoundPhaseProto.FREE_FOR_ALL_DECISION - case RoundPhase.FreeForAllBattleRequest => + case RoundPhase.VassalCommands => RoundPhaseProto.VASSAL_COMMANDS + case RoundPhase.PlayerCommands => RoundPhaseProto.PLAYER_COMMANDS + case RoundPhase.HostileArmySetup => RoundPhaseProto.HOSTILE_ARMY_SETUP + case RoundPhase.FreeForAllDecision => RoundPhaseProto.FREE_FOR_ALL_DECISION + case RoundPhase.FreeForAllBattleRequest => RoundPhaseProto.FREE_FOR_ALL_BATTLE_REQUEST case RoundPhase.FreeForAllBattleResolution => RoundPhaseProto.FREE_FOR_ALL_BATTLE_RESOLUTION - case RoundPhase.UncontestedConquest => RoundPhaseProto.UNCONTESTED_CONQUEST - case RoundPhase.AttackDecision => RoundPhaseProto.ATTACK_DECISION - case RoundPhase.DefenseDecision => RoundPhaseProto.DEFENSE_DECISION - case RoundPhase.TruceTurnBack => RoundPhaseProto.TRUCE_TURN_BACK - case RoundPhase.BattleRequest => RoundPhaseProto.BATTLE_REQUEST - case RoundPhase.FoodConsumption => RoundPhaseProto.FOOD_CONSUMPTION - case RoundPhase.BattleResolution => RoundPhaseProto.BATTLE_RESOLUTION - case RoundPhase.BattleAftermath => RoundPhaseProto.BATTLE_AFTERMATH - case RoundPhase.DiplomacyResolution => RoundPhaseProto.DIPLOMACY_RESOLUTION - case RoundPhase.ReconResolution => RoundPhaseProto.RECON_RESOLUTION + case RoundPhase.UncontestedConquest => RoundPhaseProto.UNCONTESTED_CONQUEST + case RoundPhase.AttackDecision => RoundPhaseProto.ATTACK_DECISION + case RoundPhase.DefenseDecision => RoundPhaseProto.DEFENSE_DECISION + case RoundPhase.TruceTurnBack => RoundPhaseProto.TRUCE_TURN_BACK + case RoundPhase.BattleRequest => RoundPhaseProto.BATTLE_REQUEST + case RoundPhase.FoodConsumption => RoundPhaseProto.FOOD_CONSUMPTION + case RoundPhase.BattleResolution => RoundPhaseProto.BATTLE_RESOLUTION + case RoundPhase.BattleAftermath => RoundPhaseProto.BATTLE_AFTERMATH + case RoundPhase.DiplomacyResolution => RoundPhaseProto.DIPLOMACY_RESOLUTION + case RoundPhase.ReconResolution => RoundPhaseProto.RECON_RESOLUTION } def fromProto(roundPhaseProto: RoundPhaseProto): RoundPhase = roundPhaseProto match { - case RoundPhaseProto.NEW_ROUND => RoundPhase.NewRound - case RoundPhaseProto.PRISONER_EXCHANGE => RoundPhase.PrisonerExchange - case RoundPhaseProto.PROVINCE_EVENTS => RoundPhase.ProvinceEvents - case RoundPhaseProto.FORCED_TURN_BACK => RoundPhase.ForcedTurnBack - case RoundPhaseProto.PROVINCE_MOVE_RESOLUTION => + case RoundPhaseProto.NEW_ROUND => RoundPhase.NewRound + case RoundPhaseProto.PRISONER_EXCHANGE => RoundPhase.PrisonerExchange + case RoundPhaseProto.PROVINCE_EVENTS => RoundPhase.ProvinceEvents + case RoundPhaseProto.FORCED_TURN_BACK => RoundPhase.ForcedTurnBack + case RoundPhaseProto.PROVINCE_MOVE_RESOLUTION => RoundPhase.ProvinceMoveResolution - case RoundPhaseProto.HANDLE_RIOT => RoundPhase.HandleRiot - case RoundPhaseProto.HERO_DEPARTURES => RoundPhase.HeroDepartures - case RoundPhaseProto.PLEASE_RECRUIT_ME => RoundPhase.PleaseRecruitMe - case RoundPhaseProto.UNAFFILIATED_HERO_ACTIONS => + case RoundPhaseProto.HANDLE_RIOT => RoundPhase.HandleRiot + case RoundPhaseProto.HERO_DEPARTURES => RoundPhase.HeroDepartures + case RoundPhaseProto.PLEASE_RECRUIT_ME => RoundPhase.PleaseRecruitMe + case RoundPhaseProto.UNAFFILIATED_HERO_ACTIONS => RoundPhase.UnaffiliatedHeroActions - case RoundPhaseProto.VASSAL_COMMANDS => RoundPhase.VassalCommands - case RoundPhaseProto.PLAYER_COMMANDS => RoundPhase.PlayerCommands - case RoundPhaseProto.HOSTILE_ARMY_SETUP => RoundPhase.HostileArmySetup - case RoundPhaseProto.FREE_FOR_ALL_DECISION => + case RoundPhaseProto.VASSAL_COMMANDS => RoundPhase.VassalCommands + case RoundPhaseProto.PLAYER_COMMANDS => RoundPhase.PlayerCommands + case RoundPhaseProto.HOSTILE_ARMY_SETUP => RoundPhase.HostileArmySetup + case RoundPhaseProto.FREE_FOR_ALL_DECISION => RoundPhase.FreeForAllDecision - case RoundPhaseProto.FREE_FOR_ALL_BATTLE_REQUEST => + case RoundPhaseProto.FREE_FOR_ALL_BATTLE_REQUEST => RoundPhase.FreeForAllBattleRequest - case RoundPhaseProto.FREE_FOR_ALL_BATTLE_RESOLUTION => + case RoundPhaseProto.FREE_FOR_ALL_BATTLE_RESOLUTION => RoundPhase.FreeForAllBattleResolution - case RoundPhaseProto.UNCONTESTED_CONQUEST => + case RoundPhaseProto.UNCONTESTED_CONQUEST => RoundPhase.UncontestedConquest - case RoundPhaseProto.ATTACK_DECISION => RoundPhase.AttackDecision - case RoundPhaseProto.DEFENSE_DECISION => RoundPhase.DefenseDecision - case RoundPhaseProto.TRUCE_TURN_BACK => RoundPhase.TruceTurnBack - case RoundPhaseProto.BATTLE_REQUEST => RoundPhase.BattleRequest - case RoundPhaseProto.FOOD_CONSUMPTION => RoundPhase.FoodConsumption - case RoundPhaseProto.BATTLE_RESOLUTION => RoundPhase.BattleResolution - case RoundPhaseProto.BATTLE_AFTERMATH => RoundPhase.BattleAftermath - case RoundPhaseProto.DIPLOMACY_RESOLUTION => + case RoundPhaseProto.ATTACK_DECISION => RoundPhase.AttackDecision + case RoundPhaseProto.DEFENSE_DECISION => RoundPhase.DefenseDecision + case RoundPhaseProto.TRUCE_TURN_BACK => RoundPhase.TruceTurnBack + case RoundPhaseProto.BATTLE_REQUEST => RoundPhase.BattleRequest + case RoundPhaseProto.FOOD_CONSUMPTION => RoundPhase.FoodConsumption + case RoundPhaseProto.BATTLE_RESOLUTION => RoundPhase.BattleResolution + case RoundPhaseProto.BATTLE_AFTERMATH => RoundPhase.BattleAftermath + case RoundPhaseProto.DIPLOMACY_RESOLUTION => RoundPhase.DiplomacyResolution - case RoundPhaseProto.RECON_RESOLUTION => RoundPhase.ReconResolution - case RoundPhaseProto.UNKNOWN_PHASE => + case RoundPhaseProto.RECON_RESOLUTION => RoundPhase.ReconResolution + case RoundPhaseProto.UNKNOWN_PHASE => throw new ProtoConversionException( "UNKNOWN_PHASE is not a valid RoundPhase" ) diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/SuppliesConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/SuppliesConverter.scala index aa09d9d99d..0f1c887113 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/SuppliesConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/SuppliesConverter.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.model.proto_converters -import net.eagle0.eagle.internal.supplies.{ - MovingSupplies as MovingSuppliesProto, - Supplies as SuppliesProto -} +import net.eagle0.eagle.internal.supplies.{MovingSupplies as MovingSuppliesProto, Supplies as SuppliesProto} import net.eagle0.eagle.model.state.{MovingSupplies, Supplies} object SuppliesConverter { diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/UnaffiliatedHeroConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/UnaffiliatedHeroConverter.scala index 968faa8c3b..dc10de4ec2 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/UnaffiliatedHeroConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/UnaffiliatedHeroConverter.scala @@ -16,58 +16,53 @@ import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.{ import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType as UnaffiliatedHeroTypeProto import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero as UnaffiliatedHeroProto import net.eagle0.eagle.model.proto_converters.date.DateConverter -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC object UnaffiliatedHeroConverter { - private val unaffiliatedHeroTypeMap - : Map[UnaffiliatedHeroTypeProto, UnaffiliatedHeroType] = + private val unaffiliatedHeroTypeMap: Map[UnaffiliatedHeroTypeProto, UnaffiliatedHeroType] = Map( - UNAFFILIATED_HERO_UNKNOWN -> UnaffiliatedHeroType.Unknown, - UNAFFILIATED_HERO_PRISONER -> UnaffiliatedHeroType.Prisoner, - UNAFFILIATED_HERO_TRAVELER -> UnaffiliatedHeroType.Traveler, - UNAFFILIATED_HERO_RESIDENT -> UnaffiliatedHeroType.Resident, - UNAFFILIATED_HERO_OUTLAW -> UnaffiliatedHeroType.Outlaw, - UNAFFILIATED_HERO_MOVING_PRISONER -> UnaffiliatedHeroType.MovingPrisoner, + UNAFFILIATED_HERO_UNKNOWN -> UnaffiliatedHeroType.Unknown, + UNAFFILIATED_HERO_PRISONER -> UnaffiliatedHeroType.Prisoner, + UNAFFILIATED_HERO_TRAVELER -> UnaffiliatedHeroType.Traveler, + UNAFFILIATED_HERO_RESIDENT -> UnaffiliatedHeroType.Resident, + UNAFFILIATED_HERO_OUTLAW -> UnaffiliatedHeroType.Outlaw, + UNAFFILIATED_HERO_MOVING_PRISONER -> UnaffiliatedHeroType.MovingPrisoner, UNAFFILIATED_HERO_RETURNING_PRISONER -> UnaffiliatedHeroType.ReturningPrisoner ) private def recruitmentInfoFromProto( recruitmentInfoProto: RecruitmentInfoProto ): RecruitmentInfo = recruitmentInfoProto.status match { - case RecruitmentStatusProto.RECRUITMENT_STATUS_UNKNOWN => + case RecruitmentStatusProto.RECRUITMENT_STATUS_UNKNOWN => RecruitmentInfo.Unknown - case RecruitmentStatusProto.RECRUITMENT_STATUS_WOULD_JOIN => + case RecruitmentStatusProto.RECRUITMENT_STATUS_WOULD_JOIN => RecruitmentInfo.WouldJoin - case RecruitmentStatusProto.RECRUITMENT_STATUS_PRISONER => + case RecruitmentStatusProto.RECRUITMENT_STATUS_PRISONER => RecruitmentInfo.Prisoner - case RecruitmentStatusProto.RECRUITMENT_STATUS_TRAVELER => + case RecruitmentStatusProto.RECRUITMENT_STATUS_TRAVELER => RecruitmentInfo.Traveler - case RecruitmentStatusProto.RECRUITMENT_STATUS_OUTLAW => + case RecruitmentStatusProto.RECRUITMENT_STATUS_OUTLAW => RecruitmentInfo.Outlaw - case RecruitmentStatusProto.RECRUITMENT_STATUS_LOW_PRESTIGE => + case RecruitmentStatusProto.RECRUITMENT_STATUS_LOW_PRESTIGE => RecruitmentInfo.LowPrestige - case RecruitmentStatusProto.RECRUITMENT_STATUS_SWORN => + case RecruitmentStatusProto.RECRUITMENT_STATUS_SWORN => RecruitmentInfo.Sworn case RecruitmentStatusProto.RECRUITMENT_STATUS_NO_RULER_IN_PROVINCE => RecruitmentInfo.NoRulerInProvince - case RecruitmentStatusProto.RECRUITMENT_STATUS_NO_QUEST_AVAILABLE => + case RecruitmentStatusProto.RECRUITMENT_STATUS_NO_QUEST_AVAILABLE => RecruitmentInfo.NoQuestAvailable - case RecruitmentStatusProto.RECRUITMENT_STATUS_NOT_DIVINED => + case RecruitmentStatusProto.RECRUITMENT_STATUS_NOT_DIVINED => RecruitmentInfo.NotDivined - case RecruitmentStatusProto.RECRUITMENT_STATUS_HAS_QUEST => + case RecruitmentStatusProto.RECRUITMENT_STATUS_HAS_QUEST => RecruitmentInfo.HasQuest( QuestConverter.fromProto(recruitmentInfoProto.quest.get) ) - case RecruitmentStatusProto.RECRUITMENT_STATUS_EXILE => + case RecruitmentStatusProto.RECRUITMENT_STATUS_EXILE => RecruitmentInfo.Exile - case RecruitmentStatusProto.RECRUITMENT_STATUS_MOVING_PRISONER => + case RecruitmentStatusProto.RECRUITMENT_STATUS_MOVING_PRISONER => RecruitmentInfo.MovingPrisoner - case RecruitmentStatusProto.Unrecognized(unrecognizedValue) => + case RecruitmentStatusProto.Unrecognized(unrecognizedValue) => throw new ProtoConversionException( s"Unrecognized recruitment status: $unrecognizedValue" ) @@ -76,31 +71,31 @@ object UnaffiliatedHeroConverter { def recruitmentInfoToProto( recruitmentInfo: RecruitmentInfo ): RecruitmentInfoProto = recruitmentInfo match { - case RecruitmentInfo.Unknown => + case RecruitmentInfo.Unknown => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_UNKNOWN ) - case RecruitmentInfo.WouldJoin => + case RecruitmentInfo.WouldJoin => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_WOULD_JOIN ) - case RecruitmentInfo.Prisoner => + case RecruitmentInfo.Prisoner => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_PRISONER ) - case RecruitmentInfo.Traveler => + case RecruitmentInfo.Traveler => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_TRAVELER ) - case RecruitmentInfo.Outlaw => + case RecruitmentInfo.Outlaw => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_OUTLAW ) - case RecruitmentInfo.LowPrestige => + case RecruitmentInfo.LowPrestige => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_LOW_PRESTIGE ) - case RecruitmentInfo.Sworn => + case RecruitmentInfo.Sworn => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_SWORN ) @@ -108,24 +103,24 @@ object UnaffiliatedHeroConverter { RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_NO_RULER_IN_PROVINCE ) - case RecruitmentInfo.NoQuestAvailable => + case RecruitmentInfo.NoQuestAvailable => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_NO_QUEST_AVAILABLE ) - case RecruitmentInfo.NotDivined => + case RecruitmentInfo.NotDivined => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_NOT_DIVINED ) - case RecruitmentInfo.HasQuest(quest) => + case RecruitmentInfo.HasQuest(quest) => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_HAS_QUEST, quest = Some(QuestConverter.toProto(quest)) ) - case RecruitmentInfo.Exile => + case RecruitmentInfo.Exile => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_EXILE ) - case RecruitmentInfo.MovingPrisoner => + case RecruitmentInfo.MovingPrisoner => RecruitmentInfoProto( status = RecruitmentStatusProto.RECRUITMENT_STATUS_MOVING_PRISONER ) @@ -141,18 +136,16 @@ object UnaffiliatedHeroConverter { lastFactionId = uhProto.lastFaction, recruitmentInfo = recruitmentInfoFromProto(uhProto.recruitmentInfo.get), divinedTextId = uhProto.divinedTextId, - pleaseRecruitMeRejectionDate = - uhProto.pleaseRecruitMeRejectionDate.map { date => - DateConverter.fromProto(Some(date)) - }, + pleaseRecruitMeRejectionDate = uhProto.pleaseRecruitMeRejectionDate.map { date => + DateConverter.fromProto(Some(date)) + }, pleaseRecruitMeTextId = uhProto.pleaseRecruitMeTextId ) - def toProto(uh: UnaffiliatedHeroT): UnaffiliatedHeroProto = { + def toProto(uh: UnaffiliatedHeroT): UnaffiliatedHeroProto = UnaffiliatedHeroProto( heroId = uh.heroId, - `type` = - unaffiliatedHeroTypeMap.find(_._2 == uh.unaffiliatedHeroType).get._1, + `type` = unaffiliatedHeroTypeMap.find(_._2 == uh.unaffiliatedHeroType).get._1, roundsInType = uh.roundsInType, recruitmentAttempted = uh.recruitmentAttempted, factionBiases = uh.factionBiases, @@ -164,5 +157,4 @@ object UnaffiliatedHeroConverter { }, pleaseRecruitMeTextId = uh.pleaseRecruitMeTextId ) - } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/chronicle_entry/ChronicleEntryConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/chronicle_entry/ChronicleEntryConverter.scala index 9c6caacfc8..fb7fd5a538 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/chronicle_entry/ChronicleEntryConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/chronicle_entry/ChronicleEntryConverter.scala @@ -7,17 +7,15 @@ import net.eagle0.eagle.model.state.chronicle_entry.ChronicleEntry object ChronicleEntryConverter { - def toProto(chronicleEntry: ChronicleEntry): ChronicleEntryProto = { + def toProto(chronicleEntry: ChronicleEntry): ChronicleEntryProto = ChronicleEntryProto( generatedTextId = chronicleEntry.generatedTextId, date = Some(DateConverter.toProto(chronicleEntry.date)) ) - } - def fromProto(chronicleEntryProto: ChronicleEntryProto): ChronicleEntry = { + def fromProto(chronicleEntryProto: ChronicleEntryProto): ChronicleEntry = ChronicleEntry( generatedTextId = chronicleEntryProto.generatedTextId, date = DateConverter.fromProto(chronicleEntryProto.date) ) - } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/date/DateConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/date/DateConverter.scala index 81a2df8d1b..2950f5f06d 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/date/DateConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/date/DateConverter.scala @@ -4,17 +4,15 @@ import net.eagle0.eagle.common.date.Date as DateProto import net.eagle0.eagle.model.state.date.Date object DateConverter { - def toProto(date: Date): DateProto = { + def toProto(date: Date): DateProto = DateProto( year = date.year, month = date.month.value ) - } - def fromProto(dateProto: Option[DateProto]): Date = { + def fromProto(dateProto: Option[DateProto]): Date = Date( year = dateProto.get.year, month = Date.Month.fromInt(dateProto.get.month) ) - } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/DiplomacyOfferConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/DiplomacyOfferConverter.scala index f411fa4b3e..c4b278cc4e 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/DiplomacyOfferConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/DiplomacyOfferConverter.scala @@ -39,7 +39,7 @@ object DiplomacyOfferConverter { status = StatusConverter.toProto(offer.status), offerTextId = offer.offerTextId, offerDetails = offer match { - case to: TruceOffer => + case to: TruceOffer => TruceOfferDetails(Some(DateConverter.toProto(to.endDate))) case _: AllianceOffer => AllianceOfferDetails() case _: BreakAlliance => BreakAllianceDetails() @@ -96,39 +96,35 @@ object DiplomacyOfferConverter { originatingFactionId = diplomacyOfferProto.originatingFactionId, targetFactionId = diplomacyOfferProto.targetFactionId, messengerHeroId = diplomacyOfferProto.messengerHeroId, - messengerOriginProvinceId = - diplomacyOfferProto.messengerOriginProvinceId, + messengerOriginProvinceId = diplomacyOfferProto.messengerOriginProvinceId, status = StatusConverter.fromProto(diplomacyOfferProto.status), offerTextId = diplomacyOfferProto.offerTextId, endDate = DateConverter.fromProto(endDate) ) - case AllianceOfferDetails(_) => + case AllianceOfferDetails(_) => AllianceOffer( originatingFactionId = diplomacyOfferProto.originatingFactionId, targetFactionId = diplomacyOfferProto.targetFactionId, messengerHeroId = diplomacyOfferProto.messengerHeroId, - messengerOriginProvinceId = - diplomacyOfferProto.messengerOriginProvinceId, + messengerOriginProvinceId = diplomacyOfferProto.messengerOriginProvinceId, status = StatusConverter.fromProto(diplomacyOfferProto.status), offerTextId = diplomacyOfferProto.offerTextId ) - case BreakAllianceDetails(_) => + case BreakAllianceDetails(_) => BreakAlliance( originatingFactionId = diplomacyOfferProto.originatingFactionId, targetFactionId = diplomacyOfferProto.targetFactionId, messengerHeroId = diplomacyOfferProto.messengerHeroId, - messengerOriginProvinceId = - diplomacyOfferProto.messengerOriginProvinceId, + messengerOriginProvinceId = diplomacyOfferProto.messengerOriginProvinceId, status = StatusConverter.fromProto(diplomacyOfferProto.status), offerTextId = diplomacyOfferProto.offerTextId ) - case InvitationDetails(_) => + case InvitationDetails(_) => Invitation( originatingFactionId = diplomacyOfferProto.originatingFactionId, targetFactionId = diplomacyOfferProto.targetFactionId, messengerHeroId = diplomacyOfferProto.messengerHeroId, - messengerOriginProvinceId = - diplomacyOfferProto.messengerOriginProvinceId, + messengerOriginProvinceId = diplomacyOfferProto.messengerOriginProvinceId, status = StatusConverter.fromProto(diplomacyOfferProto.status), offerTextId = diplomacyOfferProto.offerTextId ) @@ -143,8 +139,7 @@ object DiplomacyOfferConverter { originatingFactionId = diplomacyOfferProto.originatingFactionId, targetFactionId = diplomacyOfferProto.targetFactionId, messengerHeroId = diplomacyOfferProto.messengerHeroId, - messengerOriginProvinceId = - diplomacyOfferProto.messengerOriginProvinceId, + messengerOriginProvinceId = diplomacyOfferProto.messengerOriginProvinceId, status = StatusConverter.fromProto(diplomacyOfferProto.status), offerTextId = diplomacyOfferProto.offerTextId, prisonerToBeRansomed = fromProto(prisonerToBeRansomed.get), @@ -152,7 +147,7 @@ object DiplomacyOfferConverter { hostagesOffered = hostagesOffered.map(fromProto).toVector, goldOffered = goldOffered ) - case Empty => + case Empty => throw new ProtoConversionException(s"Empty offer details") } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/status/StatusConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/status/StatusConverter.scala index bbe19efb01..9a8ebec6ff 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/status/StatusConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_offer/status/StatusConverter.scala @@ -32,13 +32,13 @@ object StatusConverter { def fromProto(statusProto: DiplomacyOfferStatusProto): Status = statusProto match { - case DIPLOMACY_OFFER_STATUS_UNRESOLVED => Unresolved - case DIPLOMACY_OFFER_STATUS_ACCEPTED => Accepted - case DIPLOMACY_OFFER_STATUS_REJECTED => Rejected - case DIPLOMACY_OFFER_STATUS_IMPRISONED => Imprisoned - case DIPLOMACY_OFFER_STATUS_INVALIDATED => + case DIPLOMACY_OFFER_STATUS_UNRESOLVED => Unresolved + case DIPLOMACY_OFFER_STATUS_ACCEPTED => Accepted + case DIPLOMACY_OFFER_STATUS_REJECTED => Rejected + case DIPLOMACY_OFFER_STATUS_IMPRISONED => Imprisoned + case DIPLOMACY_OFFER_STATUS_INVALIDATED => Invalidated - case DIPLOMACY_OFFER_STATUS_UNKNOWN => + case DIPLOMACY_OFFER_STATUS_UNKNOWN => throw new ProtoConversionException("Unknown diplomacy offer status") case DiplomacyOfferStatusProto.Unrecognized(unrecognizedValue) => throw new ProtoConversionException( diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_option/DiplomacyOptionConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_option/DiplomacyOptionConverter.scala index 930117deec..fb5fe92cd3 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_option/DiplomacyOptionConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/diplomacy_option/DiplomacyOptionConverter.scala @@ -15,7 +15,7 @@ import net.eagle0.eagle.model.state.diplomacy_option.DiplomacyOption import net.eagle0.eagle.FactionId object DiplomacyOptionConverter { - def fromProto(proto: DiplomacyOptionProto): DiplomacyOption = { + def fromProto(proto: DiplomacyOptionProto): DiplomacyOption = proto match { case truceProto: TruceOptionProto => DiplomacyOption.TruceOption( @@ -65,9 +65,8 @@ object DiplomacyOptionConverter { "DiplomacyOption proto has empty sealed value" ) } - } - def toProto(diplomacyOption: DiplomacyOption): DiplomacyOptionProto = { + def toProto(diplomacyOption: DiplomacyOption): DiplomacyOptionProto = diplomacyOption match { case DiplomacyOption.TruceOption(targetFactionId, goldCost) => TruceOptionProto( @@ -92,12 +91,9 @@ object DiplomacyOptionConverter { targetFactionId = targetFactionId, ransomOffer = Some( RansomOfferDetailsProto( - prisonerToBeRansomed = - Some(DiplomacyOfferConverter.toProto(prisonerToBeRansomed)), - prisonersOffered = - prisonersOffered.map(DiplomacyOfferConverter.toProto), - hostagesOffered = - hostagesOffered.map(DiplomacyOfferConverter.toProto), + prisonerToBeRansomed = Some(DiplomacyOfferConverter.toProto(prisonerToBeRansomed)), + prisonersOffered = prisonersOffered.map(DiplomacyOfferConverter.toProto), + hostagesOffered = hostagesOffered.map(DiplomacyOfferConverter.toProto), goldOffered = goldOffered ) ) @@ -115,5 +111,4 @@ object DiplomacyOptionConverter { goldCost = goldCost ) } - } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/faction/FactionConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/faction/FactionConverter.scala index 865fc7ca1d..644264e1d1 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/faction/FactionConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/faction/FactionConverter.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.model.proto_converters.faction import net.eagle0.eagle.{FactionId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.common.diplomacy_offer.DiplomacyOffer as DiplomacyOfferProto -import net.eagle0.eagle.internal.faction.{ - Faction as FactionProto, - PrestigeModifier as PrestigeModifierProto -} +import net.eagle0.eagle.internal.faction.{Faction as FactionProto, PrestigeModifier as PrestigeModifierProto} import net.eagle0.eagle.internal.faction.Faction.OutgoingOfferRound as OutgoingOfferRoundProto import net.eagle0.eagle.internal.faction_relationship.FactionRelationship as FactionRelationshipProto import net.eagle0.eagle.model.proto_converters.date.DateConverter @@ -13,11 +10,7 @@ import net.eagle0.eagle.model.proto_converters.diplomacy_offer.DiplomacyOfferCon import net.eagle0.eagle.model.proto_converters.ProtoConversionException import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.diplomacy_offer.DiplomacyOffer -import net.eagle0.eagle.model.state.faction.{ - FactionRelationship, - FactionT, - PrestigeModifier -} +import net.eagle0.eagle.model.state.faction.{FactionRelationship, FactionT, PrestigeModifier} import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionT.OutgoingOfferRound import net.eagle0.eagle.views.province_view.ProvinceView @@ -48,19 +41,14 @@ object FactionConverter { leaders = leaderIds, prestigeModifiers = prestigeModifiers.map(toProto), factionRelationships = factionRelationships.map(toProto), - incomingDiplomacyOffers = - incomingDiplomacyOffers.map(DiplomacyOfferConverter.toProto), + incomingDiplomacyOffers = incomingDiplomacyOffers.map(DiplomacyOfferConverter.toProto), focusProvinceId = focusProvinceId, reconnedProvinces = reconnedProvinces, lastActedProvinceIdThisRound = lastActedProvinceIdThisRound, - lastOutgoingTruceOfferRounds = - lastOutgoingTruceOfferRounds.map(toProto), - lastOutgoingAllianceOfferRounds = - lastOutgoingAllianceOfferRounds.map(toProto), - lastOutgoingInvitationRounds = - lastOutgoingInvitationRounds.map(toProto), - lastOutgoingRansomOfferRounds = - lastOutgoingRansomOfferRounds.map(toProto), + lastOutgoingTruceOfferRounds = lastOutgoingTruceOfferRounds.map(toProto), + lastOutgoingAllianceOfferRounds = lastOutgoingAllianceOfferRounds.map(toProto), + lastOutgoingInvitationRounds = lastOutgoingInvitationRounds.map(toProto), + lastOutgoingRansomOfferRounds = lastOutgoingRansomOfferRounds.map(toProto), earliestRoundForInvitation = earliestRoundForInvitation ) @@ -71,10 +59,10 @@ object FactionConverter { def toProto(prestigeModifier: PrestigeModifier): PrestigeModifierProto = PrestigeModifierProto( `type` = prestigeModifier.prestigeModifierType match { - case PrestigeModifier.Type.Unknown => PrestigeModifierProto.Type.UNKNOWN + case PrestigeModifier.Type.Unknown => PrestigeModifierProto.Type.UNKNOWN case PrestigeModifier.Type.SuppressedBeasts => PrestigeModifierProto.Type.SUPPRESSED_BEASTS - case PrestigeModifier.Type.Festival => + case PrestigeModifier.Type.Festival => PrestigeModifierProto.Type.FESTIVAL }, value = prestigeModifier.value @@ -94,9 +82,9 @@ object FactionConverter { relationshipLevel = relationshipLevel match { case FactionRelationship.RelationshipLevel.Unknown => FactionRelationshipProto.RelationshipLevel.UNKNOWN - case FactionRelationship.RelationshipLevel.Ally => + case FactionRelationship.RelationshipLevel.Ally => FactionRelationshipProto.RelationshipLevel.ALLY - case FactionRelationship.RelationshipLevel.Truce => + case FactionRelationship.RelationshipLevel.Truce => FactionRelationshipProto.RelationshipLevel.TRUCE case FactionRelationship.RelationshipLevel.Hostile => FactionRelationshipProto.RelationshipLevel.HOSTILE @@ -151,14 +139,10 @@ object FactionConverter { focusProvinceId = focusProvinceId, reconnedProvinces = reconnedProvinces.toVector, lastActedProvinceIdThisRound = lastActedProvinceIdThisRound, - lastOutgoingTruceOfferRounds = - lastOutgoingTruceOfferRounds.map(fromProto).toVector, - lastOutgoingAllianceOfferRounds = - lastOutgoingAllianceOfferRounds.map(fromProto).toVector, - lastOutgoingInvitationRounds = - lastOutgoingInvitationRounds.map(fromProto).toVector, - lastOutgoingRansomOfferRounds = - lastOutgoingRansomOfferRounds.map(fromProto).toVector, + lastOutgoingTruceOfferRounds = lastOutgoingTruceOfferRounds.map(fromProto).toVector, + lastOutgoingAllianceOfferRounds = lastOutgoingAllianceOfferRounds.map(fromProto).toVector, + lastOutgoingInvitationRounds = lastOutgoingInvitationRounds.map(fromProto).toVector, + lastOutgoingRansomOfferRounds = lastOutgoingRansomOfferRounds.map(fromProto).toVector, earliestRoundForInvitation = earliestRoundForInvitation ) } @@ -176,13 +160,13 @@ object FactionConverter { FactionRelationship( targetFactionId = targetFactionId, relationshipLevel = relationshipLevel match { - case FactionRelationshipProto.RelationshipLevel.UNKNOWN => + case FactionRelationshipProto.RelationshipLevel.UNKNOWN => FactionRelationship.RelationshipLevel.Unknown - case FactionRelationshipProto.RelationshipLevel.ALLY => + case FactionRelationshipProto.RelationshipLevel.ALLY => FactionRelationship.RelationshipLevel.Ally - case FactionRelationshipProto.RelationshipLevel.TRUCE => + case FactionRelationshipProto.RelationshipLevel.TRUCE => FactionRelationship.RelationshipLevel.Truce - case FactionRelationshipProto.RelationshipLevel.HOSTILE => + case FactionRelationshipProto.RelationshipLevel.HOSTILE => FactionRelationship.RelationshipLevel.Hostile case FactionRelationshipProto.RelationshipLevel.Unrecognized(value) => throw new ProtoConversionException( @@ -199,10 +183,10 @@ object FactionConverter { ): PrestigeModifier = PrestigeModifier( prestigeModifierType = prestigeModifierProto.`type` match { - case PrestigeModifierProto.Type.UNKNOWN => PrestigeModifier.Type.Unknown - case PrestigeModifierProto.Type.SUPPRESSED_BEASTS => + case PrestigeModifierProto.Type.UNKNOWN => PrestigeModifier.Type.Unknown + case PrestigeModifierProto.Type.SUPPRESSED_BEASTS => PrestigeModifier.Type.SuppressedBeasts - case PrestigeModifierProto.Type.FESTIVAL => + case PrestigeModifierProto.Type.FESTIVAL => PrestigeModifier.Type.Festival case PrestigeModifierProto.Type.Unrecognized(value) => throw new IllegalArgumentException( diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/game_state/GameStateConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/game_state/GameStateConverter.scala index a3ed721547..a33a822f34 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/game_state/GameStateConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/game_state/GameStateConverter.scala @@ -1,13 +1,6 @@ package net.eagle0.eagle.model.proto_converters.game_state -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.common.action_result_notification_details.Notification as NotificationProto import net.eagle0.eagle.common.battalion_type.BattalionType as BattalionTypeProto import net.eagle0.eagle.common.date.Date as DateProto @@ -81,20 +74,15 @@ object GameStateConverter { actionResultCount = actionResultCount, provinces = provinces.view.mapValues(ProvinceConverter.toProto).toMap, heroes = heroes.view.mapValues(HeroConverter.toProto).toMap, - battalions = - battalions.view.mapValues(BattalionConverter.toProto).toMap, - destroyedBattalions = - destroyedBattalions.view.mapValues(BattalionConverter.toProto).toMap, + battalions = battalions.view.mapValues(BattalionConverter.toProto).toMap, + destroyedBattalions = destroyedBattalions.view.mapValues(BattalionConverter.toProto).toMap, factions = factions.view.mapValues(FactionConverter.toProto).toMap, factionCommandCounts = factionCommandCounts, killedHeroes = killedHeroes.view.mapValues(HeroConverter.toProto).toMap, - destroyedFactions = - destroyedFactions.view.mapValues(FactionConverter.toProto).toMap, - outstandingBattles = - outstandingBattles.map(ShardokBattleConverter.toProto), + destroyedFactions = destroyedFactions.view.mapValues(FactionConverter.toProto).toMap, + outstandingBattles = outstandingBattles.map(ShardokBattleConverter.toProto), battleCounter = battleCounter, - deferredNotifications = - deferredNotifications.map(NotificationConverter.toProto).map(_._1), + deferredNotifications = deferredNotifications.map(NotificationConverter.toProto).map(_._1), runStatus = RunStatusConverter.toProto(runStatus), victor = victor, battalionTypes = battalionTypes.map(BattalionTypeConverter.toProto), @@ -134,39 +122,31 @@ object GameStateConverter { currentRoundId = currentRoundId, currentPhase = RoundPhaseConverter.fromProto(currentPhase), currentDate = - if currentDate.isDefined then - Some(DateConverter.fromProto(currentDate)) + if currentDate.isDefined then Some(DateConverter.fromProto(currentDate)) else None, actionResultCount = actionResultCount, - provinces = - provinces.view.mapValues(ProvinceConverter.fromProto).to(Map), + provinces = provinces.view.mapValues(ProvinceConverter.fromProto).to(Map), heroes = heroes.view.mapValues(HeroConverter.fromProto).to(Map), - battalions = - battalions.view.mapValues(BattalionConverter.fromProto).to(Map), + battalions = battalions.view.mapValues(BattalionConverter.fromProto).to(Map), destroyedBattalions = destroyedBattalions.view .mapValues(BattalionConverter.fromProto) .to(Map), - factions = - factions.view.mapValues(FactionConverter.fromProto).to(Map), + factions = factions.view.mapValues(FactionConverter.fromProto).to(Map), factionCommandCounts = factionCommandCounts, - killedHeroes = - killedHeroes.view.mapValues(HeroConverter.fromProto).to(Map), + killedHeroes = killedHeroes.view.mapValues(HeroConverter.fromProto).to(Map), destroyedFactions = destroyedFactions.view .mapValues(FactionConverter.fromProto) .to(Map), - outstandingBattles = - outstandingBattles.map(ShardokBattleConverter.fromProto).toVector, + outstandingBattles = outstandingBattles.map(ShardokBattleConverter.fromProto).toVector, battleCounter = battleCounter, deferredNotifications = deferredNotifications .map(NotificationConverter.fromProto(_, true)) .toVector, runStatus = RunStatusConverter.fromProto(runStatus), victor = victor, - battalionTypes = - battalionTypes.map(BattalionTypeConverter.fromProto).toVector, + battalionTypes = battalionTypes.map(BattalionTypeConverter.fromProto).toVector, randomSeed = randomSeed, - chronicleEntries = - chronicleEntries.map(ChronicleEntryConverter.fromProto).toVector + chronicleEntries = chronicleEntries.map(ChronicleEntryConverter.fromProto).toVector ) } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/EventForHeroBackstoryConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/EventForHeroBackstoryConverter.scala index 080b6832ac..2db20cb6f5 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/EventForHeroBackstoryConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/EventForHeroBackstoryConverter.scala @@ -40,10 +40,7 @@ import net.eagle0.eagle.internal.event_for_hero_backstory.FoughtInBattleBackstor UNIT_STATUS_UNKNOWN } import net.eagle0.eagle.internal.event_for_hero_backstory.FoughtInBattleBackstoryEvent.UnitStatus as UnitStatusProto -import net.eagle0.eagle.model.proto_converters.{ - ProtoConversionException, - QuestConverter -} +import net.eagle0.eagle.model.proto_converters.{ProtoConversionException, QuestConverter} import net.eagle0.eagle.model.proto_converters.date.DateConverter import net.eagle0.eagle.model.proto_converters.diplomacy_offer.status.StatusConverter import net.eagle0.eagle.model.proto_converters.view.battalion.BattalionViewConverter @@ -669,15 +666,15 @@ object EventForHeroBackstoryConverter { def fromProto( statusProto: UnitStatusProto - ): UnitStatus = { + ): UnitStatus = statusProto match { - case UNIT_STATUS_NORMAL => UnitStatus.Normal - case UNIT_STATUS_CAPTURED => UnitStatus.Captured - case UNIT_STATUS_FLED => UnitStatus.Fled - case UNIT_STATUS_RETREATED => UnitStatus.Retreated - case UNIT_STATUS_NEVER_ENTERED => UnitStatus.NeverEntered - case UNIT_STATUS_OUTLAWED => UnitStatus.Outlawed - case UNIT_STATUS_UNKNOWN => + case UNIT_STATUS_NORMAL => UnitStatus.Normal + case UNIT_STATUS_CAPTURED => UnitStatus.Captured + case UNIT_STATUS_FLED => UnitStatus.Fled + case UNIT_STATUS_RETREATED => UnitStatus.Retreated + case UNIT_STATUS_NEVER_ENTERED => UnitStatus.NeverEntered + case UNIT_STATUS_OUTLAWED => UnitStatus.Outlawed + case UNIT_STATUS_UNKNOWN => throw new ProtoConversionException( s"Unknown UnitStatusProto" ) @@ -686,5 +683,4 @@ object EventForHeroBackstoryConverter { s"Unrecognized UnitStatusProto: $unrecognizedValue" ) } - } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/HeroConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/HeroConverter.scala index de78b9f0ec..3d9b0bc034 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/HeroConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/HeroConverter.scala @@ -4,12 +4,7 @@ import net.eagle0.eagle.{FactionId, HeroId, RoundId} import net.eagle0.eagle.common.hero_backstory_version.BackstoryVersion as BackstoryVersionProto import net.eagle0.eagle.internal.hero.Hero as HeroProto import net.eagle0.eagle.model.proto_converters.date.DateConverter -import net.eagle0.eagle.model.state.hero.{ - EventForHeroBackstoryT, - Gender, - HeroT, - Profession -} +import net.eagle0.eagle.model.state.hero.{EventForHeroBackstoryT, Gender, HeroT, Profession} import net.eagle0.eagle.model.state.hero.backstory_version.BackstoryVersion import net.eagle0.eagle.model.state.hero.concrete.HeroC @@ -68,12 +63,11 @@ object HeroConverter { loyalty = loyalty, imagePath = imagePath, personalityWords = personalityWords, - backstoryVersions = - backstoryVersions.map { case BackstoryVersion(textId, date) => + backstoryVersions = backstoryVersions.map { + case BackstoryVersion(textId, date) => BackstoryVersionProto(textId, Some(DateConverter.toProto(date))) - }, - newBackstoryEvents = - backstoryEvents.map(EventForHeroBackstoryConverter.toProto) + }, + newBackstoryEvents = backstoryEvents.map(EventForHeroBackstoryConverter.toProto) ) } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/ProfessionConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/ProfessionConverter.scala index 140ccfadaf..86fd5c8c33 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/ProfessionConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/hero/ProfessionConverter.scala @@ -21,14 +21,14 @@ object ProfessionConverter { throw new ProtoConversionException( s"Unknown profession proto: $professionProto" ) - case ProfessionProto.NO_PROFESSION => Profession.NoProfession - case ProfessionProto.MAGE => Profession.Mage - case ProfessionProto.NECROMANCER => Profession.Necromancer - case ProfessionProto.ENGINEER => Profession.Engineer - case ProfessionProto.PALADIN => Profession.Paladin - case ProfessionProto.RANGER => Profession.Ranger - case ProfessionProto.CHAMPION => Profession.Champion - case ProfessionProto.Unrecognized(_) => + case ProfessionProto.NO_PROFESSION => Profession.NoProfession + case ProfessionProto.MAGE => Profession.Mage + case ProfessionProto.NECROMANCER => Profession.Necromancer + case ProfessionProto.ENGINEER => Profession.Engineer + case ProfessionProto.PALADIN => Profession.Paladin + case ProfessionProto.RANGER => Profession.Ranger + case ProfessionProto.CHAMPION => Profession.Champion + case ProfessionProto.Unrecognized(_) => throw new ProtoConversionException( s"Unrecognized profession proto: $professionProto" ) diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/llm_request/chronicle_event/ChronicleEventConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/llm_request/chronicle_event/ChronicleEventConverter.scala index c4de48c360..7c346c1d6f 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/llm_request/chronicle_event/ChronicleEventConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/llm_request/chronicle_event/ChronicleEventConverter.scala @@ -603,7 +603,7 @@ object ChronicleEventConverter { ShatteredArmyChronicleEvent.Blizzard case ShatteredArmyEventProto.Reason.SHATTERED_ARMY_EVENT_REASON_WITHDRAW => ShatteredArmyChronicleEvent.Withdraw - case _ => + case _ => throw new ProtoConversionException( s"Unknown ShatteredArmyEventProto.Reason: $reason" ) diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceConverter.scala index 0f586eb1c4..13e758003f 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceConverter.scala @@ -105,15 +105,15 @@ object ProvinceConverter { ProvinceProto( id = id, name = name, - neighbors = neighbors.map { case Neighbor(provinceId, distance) => - NeighborProto(provinceId, distance) + neighbors = neighbors.map { + case Neighbor(provinceId, distance) => + NeighborProto(provinceId, distance) }, rulingFactionId = rulingFactionId, rulingHeroId = rulingHeroId, rulingFactionHeroIds = rulingFactionHeroIds, battalionIds = battalionIds, - specialBattalionTypes = - specialBattalionTypeIds.map(BattalionTypeIdConverter.toProto), + specialBattalionTypes = specialBattalionTypeIds.map(BattalionTypeIdConverter.toProto), gold = gold, food = food, priceIndex = priceIndex, @@ -126,8 +126,7 @@ object ProvinceConverter { agricultureDevastation = agricultureDevastation, infrastructureDevastation = infrastructureDevastation, support = support, - unaffiliatedHeroes = - unaffiliatedHeroes.map(UnaffiliatedHeroConverter.toProto), + unaffiliatedHeroes = unaffiliatedHeroes.map(UnaffiliatedHeroConverter.toProto), capturedHeroes = capturedHeroes.map(CapturedHeroConverter.toProto), activeEvents = activeEvents.map(ProvinceEventConverter.toProto), lastBeastsDate = lastBeastsDate.map(DateConverter.toProto), @@ -135,24 +134,21 @@ object ProvinceConverter { lastCommand = lastCommand match { case Some(sc: SelectedCommand) => sc - case Some(x) => + case Some(x) => throw new ProtoConversionException( s"Unknown lastCommand type: ${x.getClass}" ) - case None => SelectedCommand.Empty + case None => SelectedCommand.Empty }, incomingArmies = incomingArmies.map(ArmyConverter.toProto), hostileArmies = hostileArmies.map(ArmyConverter.toProto), defendingArmy = defendingArmy.map(ArmyConverter.toProto), incomingShipments = incomingShipments.map(SuppliesConverter.toProto), - incomingEndTurnActions = - incomingEndTurnActions.map(IncomingEndTurnActionConverter.toProto), + incomingEndTurnActions = incomingEndTurnActions.map(IncomingEndTurnActionConverter.toProto), provinceOrders = ProvinceOrderTypeConverter.toProto(provinceOrders), deferredChanges = deferredChanges.map(DeferredChangeConverter.toProto), - lockedImprovementType = - ImprovementTypeConverter.toProto(lockedImprovementType), - battleRevelations = - battleRevelations.map(BattleRevelationConverter.toProto), + lockedImprovementType = ImprovementTypeConverter.toProto(lockedImprovementType), + battleRevelations = battleRevelations.map(BattleRevelationConverter.toProto), hexMapName = hexMapName, castleCount = castleCount, heroCap = heroCap @@ -227,32 +223,23 @@ object ProvinceConverter { agricultureDevastation = agricultureDevastation, infrastructureDevastation = infrastructureDevastation, support = support, - unaffiliatedHeroes = - unaffiliatedHeroes.map(UnaffiliatedHeroConverter.fromProto).toVector, - capturedHeroes = - capturedHeroes.map(CapturedHeroConverter.fromProto).toVector, - activeEvents = - activeEvents.map(ProvinceEventConverter.fromProto).toVector, - lastBeastsDate = - lastBeastsDate.map(date => DateConverter.fromProto(Some(date))), - lastRiotDate = - lastRiotDate.map(date => DateConverter.fromProto(Some(date))), + unaffiliatedHeroes = unaffiliatedHeroes.map(UnaffiliatedHeroConverter.fromProto).toVector, + capturedHeroes = capturedHeroes.map(CapturedHeroConverter.fromProto).toVector, + activeEvents = activeEvents.map(ProvinceEventConverter.fromProto).toVector, + lastBeastsDate = lastBeastsDate.map(date => DateConverter.fromProto(Some(date))), + lastRiotDate = lastRiotDate.map(date => DateConverter.fromProto(Some(date))), lastCommand = Some(lastCommand), incomingArmies = incomingArmies.map(ArmyConverter.fromProto).toVector, hostileArmies = hostileArmies.map(ArmyConverter.fromProto).toVector, defendingArmy = defendingArmy.map(ArmyConverter.fromProto), - incomingShipments = - incomingShipments.map(SuppliesConverter.fromProto).toVector, + incomingShipments = incomingShipments.map(SuppliesConverter.fromProto).toVector, incomingEndTurnActions = incomingEndTurnActions .map(IncomingEndTurnActionConverter.fromProto) .toVector, provinceOrders = ProvinceOrderTypeConverter.fromProto(provinceOrders), - deferredChanges = - deferredChanges.map(DeferredChangeConverter.fromProto).toVector, - lockedImprovementType = - ImprovementTypeConverter.fromProto(lockedImprovementType), - battleRevelations = - battleRevelations.map(BattleRevelationConverter.fromProto).toVector, + deferredChanges = deferredChanges.map(DeferredChangeConverter.fromProto).toVector, + lockedImprovementType = ImprovementTypeConverter.fromProto(lockedImprovementType), + battleRevelations = battleRevelations.map(BattleRevelationConverter.fromProto).toVector, hexMapName = hexMapName, castleCount = castleCount, heroCap = heroCap diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceEventConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceEventConverter.scala index 167503722d..3a19199036 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceEventConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceEventConverter.scala @@ -33,28 +33,28 @@ object ProvinceEventConverter { endDate = Some(DateConverter.toProto(endDate)), beastInfo = Some(BeastInfoConverter.toProto(beastInfo)) ) - case ImminentRiotEvent() => ImminentRiotEventProto() - case BlizzardEvent(startDate, endDate) => + case ImminentRiotEvent() => ImminentRiotEventProto() + case BlizzardEvent(startDate, endDate) => BlizzardEventProto( startDate = Some(DateConverter.toProto(startDate)), endDate = Some(DateConverter.toProto(endDate)) ) - case FestivalEvent(startDate, endDate) => + case FestivalEvent(startDate, endDate) => FestivalEventProto( startDate = Some(DateConverter.toProto(startDate)), endDate = Some(DateConverter.toProto(endDate)) ) - case FloodEvent(startDate, endDate) => + case FloodEvent(startDate, endDate) => FloodEventProto( startDate = Some(DateConverter.toProto(startDate)), endDate = Some(DateConverter.toProto(endDate)) ) - case DroughtEvent(startDate, endDate) => + case DroughtEvent(startDate, endDate) => DroughtEventProto( startDate = Some(DateConverter.toProto(startDate)), endDate = Some(DateConverter.toProto(endDate)) ) - case EpidemicEvent(startDate) => + case EpidemicEvent(startDate) => EpidemicEventProto(startDate = Some(DateConverter.toProto(startDate))) } @@ -67,30 +67,30 @@ object ProvinceEventConverter { endDate = DateConverter.fromProto(endDate), beastInfo = BeastInfoConverter.fromProto(beastInfo.get) ) - case ImminentRiotEventProto(_) => ImminentRiotEvent() - case BlizzardEventProto(startDate, endDate, _) => + case ImminentRiotEventProto(_) => ImminentRiotEvent() + case BlizzardEventProto(startDate, endDate, _) => BlizzardEvent( startDate = DateConverter.fromProto(startDate), endDate = DateConverter.fromProto(endDate) ) - case FestivalEventProto(startDate, endDate, _) => + case FestivalEventProto(startDate, endDate, _) => FestivalEvent( startDate = DateConverter.fromProto(startDate), endDate = DateConverter.fromProto(endDate) ) - case FloodEventProto(startDate, endDate, _) => + case FloodEventProto(startDate, endDate, _) => FloodEvent( startDate = DateConverter.fromProto(startDate), endDate = DateConverter.fromProto(endDate) ) - case DroughtEventProto(startDate, endDate, _) => + case DroughtEventProto(startDate, endDate, _) => DroughtEvent( startDate = DateConverter.fromProto(startDate), endDate = DateConverter.fromProto(endDate) ) - case EpidemicEventProto(startDate, _) => + case EpidemicEventProto(startDate, _) => EpidemicEvent(startDate = DateConverter.fromProto(startDate)) - case _ => + case _ => throw new IllegalArgumentException("Unknown province event type") } } diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceOrderTypeConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceOrderTypeConverter.scala index bf3edfc60f..69156f074d 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceOrderTypeConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/province/ProvinceOrderTypeConverter.scala @@ -3,13 +3,7 @@ package net.eagle0.eagle.model.proto_converters.province import net.eagle0.eagle.common.province_order_type.ProvinceOrderType as ProvinceOrderTypeProto import net.eagle0.eagle.model.proto_converters.ProtoConversionException import net.eagle0.eagle.model.state.province.ProvinceOrderType -import net.eagle0.eagle.model.state.province.ProvinceOrderType.{ - Develop, - Entrust, - Expand, - Mobilize, - UnknownOrderType -} +import net.eagle0.eagle.model.state.province.ProvinceOrderType.{Develop, Entrust, Expand, Mobilize, UnknownOrderType} object ProvinceOrderTypeConverter { def toProto( @@ -26,11 +20,11 @@ object ProvinceOrderTypeConverter { provinceOrderTypeProto: ProvinceOrderTypeProto ): ProvinceOrderType = provinceOrderTypeProto match { - case ProvinceOrderTypeProto.UNKNOWN_ORDERS => UnknownOrderType - case ProvinceOrderTypeProto.ENTRUST => Entrust - case ProvinceOrderTypeProto.DEVELOP => Develop - case ProvinceOrderTypeProto.EXPAND => Expand - case ProvinceOrderTypeProto.MOBILIZE => Mobilize + case ProvinceOrderTypeProto.UNKNOWN_ORDERS => UnknownOrderType + case ProvinceOrderTypeProto.ENTRUST => Entrust + case ProvinceOrderTypeProto.DEVELOP => Develop + case ProvinceOrderTypeProto.EXPAND => Expand + case ProvinceOrderTypeProto.MOBILIZE => Mobilize case ProvinceOrderTypeProto.Unrecognized(unrecognizedValue) => throw new ProtoConversionException( s"Unrecognized province order type: $unrecognizedValue" diff --git a/src/main/scala/net/eagle0/eagle/model/proto_converters/shardok_battle/ShardokBattleConverter.scala b/src/main/scala/net/eagle0/eagle/model/proto_converters/shardok_battle/ShardokBattleConverter.scala index 0b68b49f18..23b39889bc 100644 --- a/src/main/scala/net/eagle0/eagle/model/proto_converters/shardok_battle/ShardokBattleConverter.scala +++ b/src/main/scala/net/eagle0/eagle/model/proto_converters/shardok_battle/ShardokBattleConverter.scala @@ -7,16 +7,8 @@ import net.eagle0.eagle.internal.shardok_battle.{ ShardokBattle as ShardokBattleProto, ShardokPlayer as ShardokPlayerProto } -import net.eagle0.eagle.model.proto_converters.{ - ArmyConverter, - ProtoConversionException -} -import net.eagle0.eagle.model.state.shardok_battle.{ - BattleType, - ShardokBattle, - ShardokPlayer, - VictoryCondition -} +import net.eagle0.eagle.model.proto_converters.{ArmyConverter, ProtoConversionException} +import net.eagle0.eagle.model.state.shardok_battle.{BattleType, ShardokBattle, ShardokPlayer, VictoryCondition} object ShardokBattleConverter { @@ -105,73 +97,69 @@ object ShardokBattleConverter { ) } - private def toProto(battleType: BattleType): ShardokBattleProto.BattleType = { + private def toProto(battleType: BattleType): ShardokBattleProto.BattleType = battleType match { - case BattleType.Unknown => + case BattleType.Unknown => ShardokBattleProto.BattleType.BATTLE_TYPE_UNKNOWN case BattleType.AssaultProvince => ShardokBattleProto.BattleType.BATTLE_TYPE_ASSAULT_PROVINCE - case BattleType.FreeForAll => + case BattleType.FreeForAll => ShardokBattleProto.BattleType.BATTLE_TYPE_FREE_FOR_ALL - case BattleType.Sally => ShardokBattleProto.BattleType.BATTLE_TYPE_SALLY + case BattleType.Sally => ShardokBattleProto.BattleType.BATTLE_TYPE_SALLY } - } private def fromProto( battleTypeProto: ShardokBattleProto.BattleType - ): BattleType = { + ): BattleType = battleTypeProto match { - case ShardokBattleProto.BattleType.BATTLE_TYPE_UNKNOWN => + case ShardokBattleProto.BattleType.BATTLE_TYPE_UNKNOWN => BattleType.Unknown case ShardokBattleProto.BattleType.BATTLE_TYPE_ASSAULT_PROVINCE => BattleType.AssaultProvince - case ShardokBattleProto.BattleType.BATTLE_TYPE_FREE_FOR_ALL => + case ShardokBattleProto.BattleType.BATTLE_TYPE_FREE_FOR_ALL => BattleType.FreeForAll - case ShardokBattleProto.BattleType.BATTLE_TYPE_SALLY => BattleType.Sally - case ShardokBattleProto.BattleType.Unrecognized(value) => + case ShardokBattleProto.BattleType.BATTLE_TYPE_SALLY => BattleType.Sally + case ShardokBattleProto.BattleType.Unrecognized(value) => throw new ProtoConversionException(s"Unknown BattleType value: $value") } - } private def toProto( victoryCondition: VictoryCondition - ): VictoryConditionProto = { + ): VictoryConditionProto = victoryCondition match { - case VictoryCondition.Unknown => + case VictoryCondition.Unknown => VictoryConditionProto.UNKNOWN_VICTORY_CONDITION - case VictoryCondition.HoldsCriticalTiles => + case VictoryCondition.HoldsCriticalTiles => VictoryConditionProto.VICTORY_CONDITION_HOLDS_CRITICAL_TILES - case VictoryCondition.WinAfterMaxRounds => + case VictoryCondition.WinAfterMaxRounds => VictoryConditionProto.VICTORY_CONDITION_WIN_AFTER_MAX_ROUNDS - case VictoryCondition.LastPlayerStanding => + case VictoryCondition.LastPlayerStanding => VictoryConditionProto.VICTORY_CONDITION_LAST_PLAYER_STANDING - case VictoryCondition.MostTroopsStanding => + case VictoryCondition.MostTroopsStanding => VictoryConditionProto.VICTORY_CONDITION_MOST_TROOPS_STANDING case VictoryCondition.LastAllianceStanding => VictoryConditionProto.VICTORY_CONDITION_LAST_ALLIANCE_STANDING } - } private def fromProto( victoryConditionProto: VictoryConditionProto - ): VictoryCondition = { + ): VictoryCondition = victoryConditionProto match { - case VictoryConditionProto.UNKNOWN_VICTORY_CONDITION => + case VictoryConditionProto.UNKNOWN_VICTORY_CONDITION => VictoryCondition.Unknown - case VictoryConditionProto.VICTORY_CONDITION_HOLDS_CRITICAL_TILES => + case VictoryConditionProto.VICTORY_CONDITION_HOLDS_CRITICAL_TILES => VictoryCondition.HoldsCriticalTiles - case VictoryConditionProto.VICTORY_CONDITION_WIN_AFTER_MAX_ROUNDS => + case VictoryConditionProto.VICTORY_CONDITION_WIN_AFTER_MAX_ROUNDS => VictoryCondition.WinAfterMaxRounds - case VictoryConditionProto.VICTORY_CONDITION_LAST_PLAYER_STANDING => + case VictoryConditionProto.VICTORY_CONDITION_LAST_PLAYER_STANDING => VictoryCondition.LastPlayerStanding - case VictoryConditionProto.VICTORY_CONDITION_MOST_TROOPS_STANDING => + case VictoryConditionProto.VICTORY_CONDITION_MOST_TROOPS_STANDING => VictoryCondition.MostTroopsStanding case VictoryConditionProto.VICTORY_CONDITION_LAST_ALLIANCE_STANDING => VictoryCondition.LastAllianceStanding - case VictoryConditionProto.Unrecognized(value) => + case VictoryConditionProto.Unrecognized(value) => throw new ProtoConversionException( s"Unknown VictoryCondition value: $value" ) } - } } diff --git a/src/main/scala/net/eagle0/eagle/model/state/Army.scala b/src/main/scala/net/eagle0/eagle/model/state/Army.scala index 19bd0561ae..c2d18b54ca 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/Army.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/Army.scala @@ -27,14 +27,11 @@ case class HostileArmyGroup( sealed trait HostileArmyGroupStatus object HostileArmyGroupStatus { - case object AwaitingDecision extends HostileArmyGroupStatus - case object AwaitingFreeForAll extends HostileArmyGroupStatus - case class TributeDemanded(tributeAmount: TributeAmount) - extends HostileArmyGroupStatus - case class TributePaid(tributeAmount: TributeAmount) - extends HostileArmyGroupStatus - case object Attacking extends HostileArmyGroupStatus - case object Withdrawing extends HostileArmyGroupStatus - case class SafePassageGranted(destinationProvinceId: ProvinceId) - extends HostileArmyGroupStatus + case object AwaitingDecision extends HostileArmyGroupStatus + case object AwaitingFreeForAll extends HostileArmyGroupStatus + case class TributeDemanded(tributeAmount: TributeAmount) extends HostileArmyGroupStatus + case class TributePaid(tributeAmount: TributeAmount) extends HostileArmyGroupStatus + case object Attacking extends HostileArmyGroupStatus + case object Withdrawing extends HostileArmyGroupStatus + case class SafePassageGranted(destinationProvinceId: ProvinceId) extends HostileArmyGroupStatus } diff --git a/src/main/scala/net/eagle0/eagle/model/state/BattalionTypeId.scala b/src/main/scala/net/eagle0/eagle/model/state/BattalionTypeId.scala index 766705555b..79f0d4dfca 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/BattalionTypeId.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/BattalionTypeId.scala @@ -4,10 +4,10 @@ sealed abstract class BattalionTypeId(val value: Int) object BattalionTypeId { case object LightInfantry extends BattalionTypeId(0) case object HeavyInfantry extends BattalionTypeId(1) - case object LightCavalry extends BattalionTypeId(2) - case object HeavyCavalry extends BattalionTypeId(3) - case object Longbowmen extends BattalionTypeId(4) - case object Undead extends BattalionTypeId(5) + case object LightCavalry extends BattalionTypeId(2) + case object HeavyCavalry extends BattalionTypeId(3) + case object Longbowmen extends BattalionTypeId(4) + case object Undead extends BattalionTypeId(5) def fromInt(value: Int): BattalionTypeId = value match { case 0 => LightInfantry diff --git a/src/main/scala/net/eagle0/eagle/model/state/BattleRevelation.scala b/src/main/scala/net/eagle0/eagle/model/state/BattleRevelation.scala index 99adc2bad8..832089f609 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/BattleRevelation.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/BattleRevelation.scala @@ -4,8 +4,8 @@ import net.eagle0.eagle.{FactionId, ProvinceId} sealed trait BattleRevelationType object BattleRevelationType { - case object Unknown extends BattleRevelationType - case object Withdrew extends BattleRevelationType + case object Unknown extends BattleRevelationType + case object Withdrew extends BattleRevelationType case object DidBattle extends BattleRevelationType } diff --git a/src/main/scala/net/eagle0/eagle/model/state/RoundPhase.scala b/src/main/scala/net/eagle0/eagle/model/state/RoundPhase.scala index adfcbc12f4..af3adf1945 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/RoundPhase.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/RoundPhase.scala @@ -1,30 +1,30 @@ package net.eagle0.eagle.model.state sealed trait RoundPhase { def value: Int } -object RoundPhase { - case object NewRound extends RoundPhase { val value = 1 } - case object PrisonerExchange extends RoundPhase { val value = 2 } - case object ProvinceEvents extends RoundPhase { val value = 3 } - case object ForcedTurnBack extends RoundPhase { val value = 4 } - case object ProvinceMoveResolution extends RoundPhase { val value = 5 } - case object HandleRiot extends RoundPhase { val value = 6 } - case object HeroDepartures extends RoundPhase { val value = 7 } - case object PleaseRecruitMe extends RoundPhase { val value = 8 } - case object UnaffiliatedHeroActions extends RoundPhase { val value = 9 } - case object VassalCommands extends RoundPhase { val value = 10 } - case object PlayerCommands extends RoundPhase { val value = 11 } - case object HostileArmySetup extends RoundPhase { val value = 12 } - case object FreeForAllDecision extends RoundPhase { val value = 13 } - case object FreeForAllBattleRequest extends RoundPhase { val value = 14 } +object RoundPhase { + case object NewRound extends RoundPhase { val value = 1 } + case object PrisonerExchange extends RoundPhase { val value = 2 } + case object ProvinceEvents extends RoundPhase { val value = 3 } + case object ForcedTurnBack extends RoundPhase { val value = 4 } + case object ProvinceMoveResolution extends RoundPhase { val value = 5 } + case object HandleRiot extends RoundPhase { val value = 6 } + case object HeroDepartures extends RoundPhase { val value = 7 } + case object PleaseRecruitMe extends RoundPhase { val value = 8 } + case object UnaffiliatedHeroActions extends RoundPhase { val value = 9 } + case object VassalCommands extends RoundPhase { val value = 10 } + case object PlayerCommands extends RoundPhase { val value = 11 } + case object HostileArmySetup extends RoundPhase { val value = 12 } + case object FreeForAllDecision extends RoundPhase { val value = 13 } + case object FreeForAllBattleRequest extends RoundPhase { val value = 14 } case object FreeForAllBattleResolution extends RoundPhase { val value = 15 } - case object UncontestedConquest extends RoundPhase { val value = 16 } - case object AttackDecision extends RoundPhase { val value = 17 } - case object DefenseDecision extends RoundPhase { val value = 18 } - case object TruceTurnBack extends RoundPhase { val value = 19 } - case object BattleRequest extends RoundPhase { val value = 20 } - case object FoodConsumption extends RoundPhase { val value = 21 } - case object BattleResolution extends RoundPhase { val value = 22 } - case object BattleAftermath extends RoundPhase { val value = 23 } - case object DiplomacyResolution extends RoundPhase { val value = 24 } - case object ReconResolution extends RoundPhase { val value = 26 } + case object UncontestedConquest extends RoundPhase { val value = 16 } + case object AttackDecision extends RoundPhase { val value = 17 } + case object DefenseDecision extends RoundPhase { val value = 18 } + case object TruceTurnBack extends RoundPhase { val value = 19 } + case object BattleRequest extends RoundPhase { val value = 20 } + case object FoodConsumption extends RoundPhase { val value = 21 } + case object BattleResolution extends RoundPhase { val value = 22 } + case object BattleAftermath extends RoundPhase { val value = 23 } + case object DiplomacyResolution extends RoundPhase { val value = 24 } + case object ReconResolution extends RoundPhase { val value = 26 } } diff --git a/src/main/scala/net/eagle0/eagle/model/state/battalion/concrete/BattalionC.scala b/src/main/scala/net/eagle0/eagle/model/state/battalion/concrete/BattalionC.scala index 4b43f02cdd..b26dc362e3 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/battalion/concrete/BattalionC.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/battalion/concrete/BattalionC.scala @@ -12,7 +12,7 @@ object BattalionC { training: Double = 0.0, armament: Double = 0.0, name: String = "" - ): BattalionC = { + ): BattalionC = new BattalionC( id = id, typeId = typeId, @@ -21,7 +21,6 @@ object BattalionC { armament = armament, name = name ) - } } case class BattalionC( @@ -36,7 +35,7 @@ case class BattalionC( size: Int = size, training: Double = training, armament: Double = armament - ): BattalionT = { + ): BattalionT = BattalionC( id = this.id, typeId = this.typeId, @@ -45,5 +44,4 @@ case class BattalionC( armament = armament, name = this.name ) - } } diff --git a/src/main/scala/net/eagle0/eagle/model/state/date/Date.scala b/src/main/scala/net/eagle0/eagle/model/state/date/Date.scala index 5c74682fea..3379850d81 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/date/Date.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/date/Date.scala @@ -4,19 +4,19 @@ import scala.math.Ordered.orderingToOrdered object Date { abstract class Month(val value: Int) {} - object Month { - case object January extends Month(1) - case object February extends Month(2) - case object March extends Month(3) - case object April extends Month(4) - case object May extends Month(5) - case object June extends Month(6) - case object July extends Month(7) - case object August extends Month(8) + object Month { + case object January extends Month(1) + case object February extends Month(2) + case object March extends Month(3) + case object April extends Month(4) + case object May extends Month(5) + case object June extends Month(6) + case object July extends Month(7) + case object August extends Month(8) case object September extends Month(9) - case object October extends Month(10) - case object November extends Month(11) - case object December extends Month(12) + case object October extends Month(10) + case object November extends Month(11) + case object December extends Month(12) def fromInt(value: Int): Month = value match { case 1 => January @@ -36,8 +36,7 @@ object Date { } } - implicit def ordering: Ordering[Date] = (x: Date, y: Date) => - (x.year, x.month.value).compare((y.year, y.month.value)) + implicit def ordering: Ordering[Date] = (x: Date, y: Date) => (x.year, x.month.value).compare((y.year, y.month.value)) implicit class _Date(value: Date) extends Ordered[Date] { def ==(rhs: Date): Boolean = diff --git a/src/main/scala/net/eagle0/eagle/model/state/faction/FactionRelationship.scala b/src/main/scala/net/eagle0/eagle/model/state/faction/FactionRelationship.scala index 2e32f978af..647c71834d 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/faction/FactionRelationship.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/faction/FactionRelationship.scala @@ -8,8 +8,8 @@ object FactionRelationship { sealed trait RelationshipLevel object RelationshipLevel { case object Unknown extends RelationshipLevel - case object Ally extends RelationshipLevel - case object Truce extends RelationshipLevel + case object Ally extends RelationshipLevel + case object Truce extends RelationshipLevel case object Hostile extends RelationshipLevel } } diff --git a/src/main/scala/net/eagle0/eagle/model/state/faction/FactionT.scala b/src/main/scala/net/eagle0/eagle/model/state/faction/FactionT.scala index 476f705892..70effd728b 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/faction/FactionT.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/faction/FactionT.scala @@ -24,8 +24,7 @@ trait FactionT { def focusProvinceId: Option[ProvinceId] - def reconnedProvinces - : Vector[ProvinceView] // FIXME: this is just using the proto for now + def reconnedProvinces: Vector[ProvinceView] // FIXME: this is just using the proto for now def lastActedProvinceIdThisRound: ProvinceId diff --git a/src/main/scala/net/eagle0/eagle/model/state/faction/PrestigeModifier.scala b/src/main/scala/net/eagle0/eagle/model/state/faction/PrestigeModifier.scala index 07eb5c4d80..8a688917bf 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/faction/PrestigeModifier.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/faction/PrestigeModifier.scala @@ -3,9 +3,9 @@ package net.eagle0.eagle.model.state.faction object PrestigeModifier { sealed trait Type object Type { - case object Unknown extends Type + case object Unknown extends Type case object SuppressedBeasts extends Type - case object Festival extends Type + case object Festival extends Type } } diff --git a/src/main/scala/net/eagle0/eagle/model/state/faction/concrete/FactionC.scala b/src/main/scala/net/eagle0/eagle/model/state/faction/concrete/FactionC.scala index 91217fc488..3db97fdc68 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/faction/concrete/FactionC.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/faction/concrete/FactionC.scala @@ -2,11 +2,7 @@ package net.eagle0.eagle.model.state.faction.concrete import net.eagle0.eagle.{FactionId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.model.state.diplomacy_offer.DiplomacyOffer -import net.eagle0.eagle.model.state.faction.{ - FactionRelationship, - FactionT, - PrestigeModifier -} +import net.eagle0.eagle.model.state.faction.{FactionRelationship, FactionT, PrestigeModifier} import net.eagle0.eagle.model.state.faction.FactionT.OutgoingOfferRound import net.eagle0.eagle.views.province_view.ProvinceView diff --git a/src/main/scala/net/eagle0/eagle/model/state/game_state/GameState.scala b/src/main/scala/net/eagle0/eagle/model/state/game_state/GameState.scala index 3d36bc5ab1..e8650b14d0 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/game_state/GameState.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/game_state/GameState.scala @@ -1,13 +1,6 @@ package net.eagle0.eagle.model.state.game_state -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.model.action_result.NotificationT import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.chronicle_entry.ChronicleEntry diff --git a/src/main/scala/net/eagle0/eagle/model/state/hero/Gender.scala b/src/main/scala/net/eagle0/eagle/model/state/hero/Gender.scala index d2a7fd660f..9a6aed452b 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/hero/Gender.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/hero/Gender.scala @@ -3,6 +3,6 @@ package net.eagle0.eagle.model.state.hero sealed abstract class Gender(val name: String) object Gender { case object Female extends Gender("Female") - case object Male extends Gender("Male") - case object Other extends Gender("Other") + case object Male extends Gender("Male") + case object Other extends Gender("Other") } diff --git a/src/main/scala/net/eagle0/eagle/model/state/hero/Profession.scala b/src/main/scala/net/eagle0/eagle/model/state/hero/Profession.scala index bde6da7338..c092e51d06 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/hero/Profession.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/hero/Profession.scala @@ -2,11 +2,11 @@ package net.eagle0.eagle.model.state.hero sealed abstract class Profession(val name: String) object Profession { - case object Mage extends Profession("Mage") - case object Necromancer extends Profession("Necromancer") - case object Engineer extends Profession("Engineer") - case object Paladin extends Profession("Paladin") - case object Ranger extends Profession("Ranger") - case object Champion extends Profession("Champion") + case object Mage extends Profession("Mage") + case object Necromancer extends Profession("Necromancer") + case object Engineer extends Profession("Engineer") + case object Paladin extends Profession("Paladin") + case object Ranger extends Profession("Ranger") + case object Champion extends Profession("Champion") case object NoProfession extends Profession("NoProfession") } diff --git a/src/main/scala/net/eagle0/eagle/model/state/hero/concrete/HeroC.scala b/src/main/scala/net/eagle0/eagle/model/state/hero/concrete/HeroC.scala index 48f1f79e91..0b08d6886c 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/hero/concrete/HeroC.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/hero/concrete/HeroC.scala @@ -1,12 +1,7 @@ package net.eagle0.eagle.model.state.hero.concrete import net.eagle0.eagle.{FactionId, HeroId, RoundId} -import net.eagle0.eagle.model.state.hero.{ - EventForHeroBackstoryT, - Gender, - HeroT, - Profession -} +import net.eagle0.eagle.model.state.hero.{EventForHeroBackstoryT, Gender, HeroT, Profession} import net.eagle0.eagle.model.state.hero.backstory_version.BackstoryVersion case class HeroC( diff --git a/src/main/scala/net/eagle0/eagle/model/state/province/DeferredChangeT.scala b/src/main/scala/net/eagle0/eagle/model/state/province/DeferredChangeT.scala index 66cafb1f31..46b1474181 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/province/DeferredChangeT.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/province/DeferredChangeT.scala @@ -4,17 +4,13 @@ import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} sealed trait DeferredChangeT object DeferredChange { - case class BlizzardStarted(responsibleFaction: FactionId, durationMonths: Int) - extends DeferredChangeT + case class BlizzardStarted(responsibleFaction: FactionId, durationMonths: Int) extends DeferredChangeT - case class BlizzardEnded(responsibleFaction: FactionId) - extends DeferredChangeT + case class BlizzardEnded(responsibleFaction: FactionId) extends DeferredChangeT - case class EpidemicStarted(responsibleFaction: FactionId) - extends DeferredChangeT + case class EpidemicStarted(responsibleFaction: FactionId) extends DeferredChangeT - case class DroughtStarted(responsibleFaction: FactionId, durationMonths: Int) - extends DeferredChangeT + case class DroughtStarted(responsibleFaction: FactionId, durationMonths: Int) extends DeferredChangeT case class DroughtEnded(responsibleFaction: FactionId) extends DeferredChangeT diff --git a/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceEvent.scala b/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceEvent.scala index 8ac1872cef..87035dc5b6 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceEvent.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceEvent.scala @@ -12,6 +12,6 @@ case class BeastsEvent( case class ImminentRiotEvent() extends ProvinceEvent case class BlizzardEvent(startDate: Date, endDate: Date) extends ProvinceEvent case class FestivalEvent(startDate: Date, endDate: Date) extends ProvinceEvent -case class FloodEvent(startDate: Date, endDate: Date) extends ProvinceEvent -case class DroughtEvent(startDate: Date, endDate: Date) extends ProvinceEvent -case class EpidemicEvent(startDate: Date) extends ProvinceEvent +case class FloodEvent(startDate: Date, endDate: Date) extends ProvinceEvent +case class DroughtEvent(startDate: Date, endDate: Date) extends ProvinceEvent +case class EpidemicEvent(startDate: Date) extends ProvinceEvent diff --git a/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceT.scala b/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceT.scala index facf4721ef..4c6668d40b 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceT.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/province/ProvinceT.scala @@ -93,8 +93,7 @@ trait ProvinceT { rulingHeroId: Option[HeroId] = rulingHeroId, rulingFactionHeroIds: Vector[HeroId] = rulingFactionHeroIds, battalionIds: Vector[BattalionId] = battalionIds, - specialBattalionTypeIds: Vector[BattalionTypeId] = - specialBattalionTypeIds, + specialBattalionTypeIds: Vector[BattalionTypeId] = specialBattalionTypeIds, gold: Int = gold, food: Int = food, priceIndex: Double = priceIndex, @@ -116,8 +115,7 @@ trait ProvinceT { hostileArmies: Vector[HostileArmyGroup] = hostileArmies, defendingArmy: Option[Army] = defendingArmy, incomingShipments: Vector[MovingSupplies] = incomingShipments, - incomingEndTurnActions: Vector[IncomingEndTurnAction] = - incomingEndTurnActions, + incomingEndTurnActions: Vector[IncomingEndTurnAction] = incomingEndTurnActions, provinceOrders: ProvinceOrderType = provinceOrders, deferredChanges: Vector[DeferredChangeT] = deferredChanges, lockedImprovementType: Option[ImprovementType] = lockedImprovementType, @@ -129,20 +127,20 @@ trait ProvinceT { def withRulingFactionId(rulingFactionId: FactionId): ProvinceT = updateWith(rulingFactionId = Some(rulingFactionId)) - def clearRulingFactionId: ProvinceT = updateWith(rulingFactionId = None) + def clearRulingFactionId: ProvinceT = updateWith(rulingFactionId = None) def withBattalionIds(battalionIds: Vector[BattalionId]): ProvinceT = updateWith(battalionIds = this.battalionIds ++ battalionIds) - def clearBattalionIds: ProvinceT = updateWith(battalionIds = Vector.empty) - def clearIncomingArmies: ProvinceT = updateWith(incomingArmies = Vector.empty) - def clearHostileArmies: ProvinceT = updateWith(hostileArmies = Vector.empty) + def clearBattalionIds: ProvinceT = updateWith(battalionIds = Vector.empty) + def clearIncomingArmies: ProvinceT = updateWith(incomingArmies = Vector.empty) + def clearHostileArmies: ProvinceT = updateWith(hostileArmies = Vector.empty) def withRulerIsTraveling(rulerIsTraveling: Boolean): ProvinceT = updateWith(rulerIsTraveling = rulerIsTraveling) - def withEconomy(economy: Double): ProvinceT = + def withEconomy(economy: Double): ProvinceT = updateWith(economy = economy) - def withAgriculture(agriculture: Double): ProvinceT = updateWith( + def withAgriculture(agriculture: Double): ProvinceT = updateWith( agriculture = agriculture ) def withInfrastructure(infrastructure: Double): ProvinceT = diff --git a/src/main/scala/net/eagle0/eagle/model/state/province/concrete/ProvinceC.scala b/src/main/scala/net/eagle0/eagle/model/state/province/concrete/ProvinceC.scala index 51350ece9d..f95fd4789a 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/province/concrete/ProvinceC.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/province/concrete/ProvinceC.scala @@ -73,8 +73,7 @@ case class ProvinceC( rulingHeroId: Option[HeroId] = rulingHeroId, rulingFactionHeroIds: Vector[HeroId] = rulingFactionHeroIds, battalionIds: Vector[BattalionId] = battalionIds, - specialBattalionTypeIds: Vector[BattalionTypeId] = - specialBattalionTypeIds, + specialBattalionTypeIds: Vector[BattalionTypeId] = specialBattalionTypeIds, gold: Int = gold, food: Int = food, priceIndex: Double = priceIndex, @@ -96,8 +95,7 @@ case class ProvinceC( hostileArmies: Vector[HostileArmyGroup] = hostileArmies, defendingArmy: Option[Army] = defendingArmy, incomingShipments: Vector[MovingSupplies] = incomingShipments, - incomingEndTurnActions: Vector[IncomingEndTurnAction] = - incomingEndTurnActions, + incomingEndTurnActions: Vector[IncomingEndTurnAction] = incomingEndTurnActions, provinceOrders: ProvinceOrderType = provinceOrders, deferredChanges: Vector[DeferredChangeT] = deferredChanges, lockedImprovementType: Option[ImprovementType] = lockedImprovementType, diff --git a/src/main/scala/net/eagle0/eagle/model/state/quest/concrete/QuestC.scala b/src/main/scala/net/eagle0/eagle/model/state/quest/concrete/QuestC.scala index 95ae33d1d5..f3a93a7e94 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/quest/concrete/QuestC.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/quest/concrete/QuestC.scala @@ -16,7 +16,7 @@ object QuestC { sealed trait QuestC extends QuestT sealed abstract class ComponentQuest extends QuestC { - def componentCount: Int = 1 + def componentCount: Int = 1 def componentsFulfilled: Int = 0 def withComponentsFulfilled(componentsFulfilled: Int): QuestC = @@ -79,11 +79,9 @@ case class GiveToHeroesInProvinceQuest( case class GrandArmyQuest(totalTroopCount: Int) extends QuestC -case class ImproveAgricultureQuest(provinceId: ProvinceId, desiredValue: Double) - extends QuestC +case class ImproveAgricultureQuest(provinceId: ProvinceId, desiredValue: Double) extends QuestC -case class ImproveEconomyQuest(provinceId: ProvinceId, desiredValue: Double) - extends QuestC +case class ImproveEconomyQuest(provinceId: ProvinceId, desiredValue: Double) extends QuestC case class ImproveInfrastructureQuest( provinceId: ProvinceId, diff --git a/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/UnaffiliatedHeroT.scala b/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/UnaffiliatedHeroT.scala index 725dd17e7d..073efc599f 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/UnaffiliatedHeroT.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/UnaffiliatedHeroT.scala @@ -6,30 +6,30 @@ import net.eagle0.eagle.model.state.quest.QuestT sealed trait UnaffiliatedHeroType object UnaffiliatedHeroType { - case object Unknown extends UnaffiliatedHeroType - case object Prisoner extends UnaffiliatedHeroType - case object Traveler extends UnaffiliatedHeroType - case object Resident extends UnaffiliatedHeroType - case object Outlaw extends UnaffiliatedHeroType - case object MovingPrisoner extends UnaffiliatedHeroType + case object Unknown extends UnaffiliatedHeroType + case object Prisoner extends UnaffiliatedHeroType + case object Traveler extends UnaffiliatedHeroType + case object Resident extends UnaffiliatedHeroType + case object Outlaw extends UnaffiliatedHeroType + case object MovingPrisoner extends UnaffiliatedHeroType case object ReturningPrisoner extends UnaffiliatedHeroType } sealed trait RecruitmentInfo object RecruitmentInfo { - case object Unknown extends RecruitmentInfo - case object WouldJoin extends RecruitmentInfo - case object Prisoner extends RecruitmentInfo - case object Traveler extends RecruitmentInfo - case object Outlaw extends RecruitmentInfo - case object LowPrestige extends RecruitmentInfo - case object Sworn extends RecruitmentInfo - case object NoRulerInProvince extends RecruitmentInfo - case object NoQuestAvailable extends RecruitmentInfo - case object NotDivined extends RecruitmentInfo + case object Unknown extends RecruitmentInfo + case object WouldJoin extends RecruitmentInfo + case object Prisoner extends RecruitmentInfo + case object Traveler extends RecruitmentInfo + case object Outlaw extends RecruitmentInfo + case object LowPrestige extends RecruitmentInfo + case object Sworn extends RecruitmentInfo + case object NoRulerInProvince extends RecruitmentInfo + case object NoQuestAvailable extends RecruitmentInfo + case object NotDivined extends RecruitmentInfo case class HasQuest(quest: QuestT) extends RecruitmentInfo - case object Exile extends RecruitmentInfo - case object MovingPrisoner extends RecruitmentInfo + case object Exile extends RecruitmentInfo + case object MovingPrisoner extends RecruitmentInfo } trait UnaffiliatedHeroT { diff --git a/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/concrete/UnaffiliatedHeroC.scala b/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/concrete/UnaffiliatedHeroC.scala index 3677fc92bd..e65b2309bb 100644 --- a/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/concrete/UnaffiliatedHeroC.scala +++ b/src/main/scala/net/eagle0/eagle/model/state/unaffiliated_hero/concrete/UnaffiliatedHeroC.scala @@ -2,11 +2,7 @@ package net.eagle0.eagle.model.state.unaffiliated_hero.concrete import net.eagle0.eagle.{FactionId, HeroId} import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT, UnaffiliatedHeroType} case class UnaffiliatedHeroC( heroId: HeroId, diff --git a/src/main/scala/net/eagle0/eagle/package.scala b/src/main/scala/net/eagle0/eagle/package.scala index cfedd1b353..107f055c8f 100644 --- a/src/main/scala/net/eagle0/eagle/package.scala +++ b/src/main/scala/net/eagle0/eagle/package.scala @@ -1,14 +1,14 @@ package net.eagle0 package object eagle { - type GameId = Long - type ShardokGameId = String - type ProvinceId = Int - type FactionId = Int - type RoundId = Int - type HeroId = Int - type BattalionId = Int - type MovingArmyId = Int + type GameId = Long + type ShardokGameId = String + type ProvinceId = Int + type FactionId = Int + type RoundId = Int + type HeroId = Int + type BattalionId = Int + type MovingArmyId = Int type MovingSuppliesId = Int type ClientTextId = String diff --git a/src/main/scala/net/eagle0/eagle/service/CustomBattleManager.scala b/src/main/scala/net/eagle0/eagle/service/CustomBattleManager.scala index 97a1b9f237..0dee81bed9 100644 --- a/src/main/scala/net/eagle0/eagle/service/CustomBattleManager.scala +++ b/src/main/scala/net/eagle0/eagle/service/CustomBattleManager.scala @@ -4,11 +4,7 @@ import net.eagle0.common.game_setup_info.NewGameRequest import net.eagle0.common.shardok_internal_interface.OnePlayerUpdateResponse import net.eagle0.common.shardok_internal_interface.ShardokInternalInterfaceGrpc.ShardokInternalInterfaceStub import net.eagle0.eagle.{FactionId, GameId, ShardokGameId} -import net.eagle0.eagle.api.eagle.{ - GameUpdate, - ShardokActionResultResponse, - UpdateStreamResponse -} +import net.eagle0.eagle.api.eagle.{GameUpdate, ShardokActionResultResponse, UpdateStreamResponse} import net.eagle0.eagle.api.eagle.ShardokActionResultResponse.SingleShardokGameResultResponse import net.eagle0.eagle.api.eagle.ShardokPlacementCommands.ShardokPlacementCommand import net.eagle0.eagle.api.eagle.UpdateStreamRequest.StreamGameRequest.ShardokViewStatus @@ -42,33 +38,31 @@ case class CustomBattleGameController( knownShardokResultCount: Int, responseObserver: SyncResponseObserver ): CustomBattleGameController = { - shardokResults.playerViews.find(_.factionId != -1).foreach { - existingState => - if knownShardokResultCount < existingState.resultViews.size then - responseObserver.onNext( - UpdateStreamResponse( - responseDetails = UpdateStreamResponse.ResponseDetails.GameUpdate( - GameUpdate( - gameId = gameId, - startingState = None, - gameUpdateDetails = - GameUpdate.GameUpdateDetails.ShardokActionResultResponse( - ShardokActionResultResponse( - shardokGameResponses = Vector( - SingleShardokGameResultResponse( - shardokGameId = shardokResults.shardokGameId, - actionResultViews = existingState.resultViews - .drop(knownShardokResultCount), - newResultViewCount = existingState.resultViews.size, - availableCommands = existingState.availableCommands - ) - ) + shardokResults.playerViews.find(_.factionId != -1).foreach { existingState => + if knownShardokResultCount < existingState.resultViews.size then + responseObserver.onNext( + UpdateStreamResponse( + responseDetails = UpdateStreamResponse.ResponseDetails.GameUpdate( + GameUpdate( + gameId = gameId, + startingState = None, + gameUpdateDetails = GameUpdate.GameUpdateDetails.ShardokActionResultResponse( + ShardokActionResultResponse( + shardokGameResponses = Vector( + SingleShardokGameResultResponse( + shardokGameId = shardokResults.shardokGameId, + actionResultViews = existingState.resultViews + .drop(knownShardokResultCount), + newResultViewCount = existingState.resultViews.size, + availableCommands = existingState.availableCommands ) ) + ) ) ) ) ) + ) } CustomBattleGameController( @@ -95,23 +89,21 @@ case class CustomBattleGameController( GameUpdate( gameId = gameId, startingState = None, - gameUpdateDetails = - GameUpdate.GameUpdateDetails.ShardokActionResultResponse( - ShardokActionResultResponse( - shardokGameResponses = Vector( - SingleShardokGameResultResponse( - shardokGameId = shardokResults.shardokGameId, - actionResultViews = newViews, - newResultViewCount = shardokResults.playerViews - .find(_.factionId != -1) - .map(_.resultViews.size) - .getOrElse(0) + newViews.size, - availableCommands = - availableCommands.find(_._1 != -1).get._2 - ) + gameUpdateDetails = GameUpdate.GameUpdateDetails.ShardokActionResultResponse( + ShardokActionResultResponse( + shardokGameResponses = Vector( + SingleShardokGameResultResponse( + shardokGameId = shardokResults.shardokGameId, + actionResultViews = newViews, + newResultViewCount = shardokResults.playerViews + .find(_.factionId != -1) + .map(_.resultViews.size) + .getOrElse(0) + newViews.size, + availableCommands = availableCommands.find(_._1 != -1).get._2 ) ) ) + ) ) ) ) @@ -128,8 +120,7 @@ case class CustomBattleGameController( newPlayerResults = newPlayerResults, newAvailableCommands = availableCommands ), - currentGameState = - com.google.protobuf.ByteString.copyFrom(currentGameState) + currentGameState = com.google.protobuf.ByteString.copyFrom(currentGameState) ), responseObserver = responseObserver ) @@ -212,7 +203,7 @@ class CustomBattleManager( ), newGameRequest = newGameRequest.update( _.eagleGameId := eagleGameId, - _.gameId := shardokGameId + _.gameId := shardokGameId ) ) @@ -299,18 +290,17 @@ class CustomBattleManager( ) => val prevController = gameControllerInfos(battle.shardokGameId) - gameControllerInfos = - gameControllerInfos + (battle.shardokGameId -> prevController - .withNewResults( - newResults = results, - newPlayerResults = updates.map { opur => - opur.eagleFactionId -> opur.actionResultViews.toVector - }, - currentGameState = currentGameStateBytes, - availableCommands = updates.map { opur => - opur.eagleFactionId -> opur.availableCommands - } - )) + gameControllerInfos = gameControllerInfos + (battle.shardokGameId -> prevController + .withNewResults( + newResults = results, + newPlayerResults = updates.map { opur => + opur.eagleFactionId -> opur.actionResultViews.toVector + }, + currentGameState = currentGameStateBytes, + availableCommands = updates.map { opur => + opur.eagleFactionId -> opur.availableCommands + } + )) PostResults( gameState = null, diff --git a/src/main/scala/net/eagle0/eagle/service/EagleServiceImpl.scala b/src/main/scala/net/eagle0/eagle/service/EagleServiceImpl.scala index 5511e561ba..dff4155ec5 100644 --- a/src/main/scala/net/eagle0/eagle/service/EagleServiceImpl.scala +++ b/src/main/scala/net/eagle0/eagle/service/EagleServiceImpl.scala @@ -56,8 +56,7 @@ class EagleServiceImpl( ): Future[CreateGameResponse] = lockAndUpdateGamesWith(un => gamesManager.createGameForUser( - expandedGameParameters = - GameParametersUtils.defaultExpandedGameParameters, + expandedGameParameters = GameParametersUtils.defaultExpandedGameParameters, userName = un, desiredLeaderTextId = request.desiredLeaderTextId, maxHumanPlayers = request.humanPlayerCount, @@ -170,7 +169,7 @@ class EagleServiceImpl( ) extends StreamObserver[UpdateStreamRequest] { override def onNext(value: UpdateStreamRequest): Unit = try { value.requestDetails match { - case UpdateStreamRequest.RequestDetails.Empty => + case UpdateStreamRequest.RequestDetails.Empty => throw new EagleClientException("Must include a request") case UpdateStreamRequest.RequestDetails.StreamGameRequest( streamGameRequest @@ -178,7 +177,7 @@ class EagleServiceImpl( streamOneUpdate(streamGameRequest, responseObserver) case UpdateStreamRequest.RequestDetails.HeartbeatRequest(value) => handleHeartbeat(value.clientTimestamp, responseObserver) - case UpdateStreamRequest.RequestDetails.EnterLobbyRequest(_) => + case UpdateStreamRequest.RequestDetails.EnterLobbyRequest(_) => lockAndDoWithUserName { userName => lobbyUsers = lobbyUsers + (userName -> responseObserver) lockedSendLobbyUpdate(userName) @@ -220,10 +219,9 @@ class EagleServiceImpl( joinGame(request).map { joinGameResponse => responseObserver.onNext( UpdateStreamResponse( - responseDetails = - UpdateStreamResponse.ResponseDetails.JoinGameResponse( - joinGameResponse - ) + responseDetails = UpdateStreamResponse.ResponseDetails.JoinGameResponse( + joinGameResponse + ) ) ) } @@ -235,10 +233,9 @@ class EagleServiceImpl( createGame(request).map { createGameResponse => responseObserver.onNext( UpdateStreamResponse( - responseDetails = - UpdateStreamResponse.ResponseDetails.CreateGameResponse( - createGameResponse - ) + responseDetails = UpdateStreamResponse.ResponseDetails.CreateGameResponse( + createGameResponse + ) ) ) } @@ -250,10 +247,9 @@ class EagleServiceImpl( createCustomBattle(request).map { createCustomBattleResponse => responseObserver.onNext( UpdateStreamResponse( - responseDetails = - UpdateStreamResponse.ResponseDetails.CustomBattleResponse( - createCustomBattleResponse - ) + responseDetails = UpdateStreamResponse.ResponseDetails.CustomBattleResponse( + createCustomBattleResponse + ) ) ) } @@ -262,8 +258,8 @@ class EagleServiceImpl( case UpdateStreamRequest.RequestDetails.HexMapsRequest(request) => val responseInfos = gamesManager.hexMaps.flatMap { case (mapName, hexMap) => - val bytes = hexMap.toByteArray - val hash = bytes.splitAt(bytes.length / 2) match { + val bytes = hexMap.toByteArray + val hash = bytes.splitAt(bytes.length / 2) match { case (a, b) => MurmurHash3.arrayHash(a).toLong << 31 | MurmurHash3.arrayHash(b).toLong @@ -297,10 +293,9 @@ class EagleServiceImpl( postCommand(request).map { postCommandResponse => responseObserver.onNext( UpdateStreamResponse( - responseDetails = - UpdateStreamResponse.ResponseDetails.PostCommandResponse( - postCommandResponse - ) + responseDetails = UpdateStreamResponse.ResponseDetails.PostCommandResponse( + postCommandResponse + ) ) ) } @@ -329,14 +324,14 @@ class EagleServiceImpl( } override def onError(t: Throwable): Unit = t match { - case ce: EagleClientException => + case ce: EagleClientException => responseObserver.onError(ce) case sre: StatusRuntimeException => SimpleTimedLogger.printLogger.logLine( s"Caught StatusRuntimeError $sre for ${responseObserver.userName}, it's probably fine" ) responseObserver.onError(sre) - case e: Exception => + case e: Exception => SimpleTimedLogger.printLogger.logLine( s"Caught error $e for ${responseObserver.userName}" ) @@ -369,12 +364,11 @@ class EagleServiceImpl( ) val _ = responseObserver.onNext( UpdateStreamResponse( - responseDetails = - UpdateStreamResponse.ResponseDetails.HeartbeatResponse( - HeartbeatResponse( - serverTimestamp = System.currentTimeMillis() - ) + responseDetails = UpdateStreamResponse.ResponseDetails.HeartbeatResponse( + HeartbeatResponse( + serverTimestamp = System.currentTimeMillis() ) + ) ) ) } @@ -386,7 +380,7 @@ class EagleServiceImpl( responseObserver: SyncResponseObserver ): Unit = { lockAndDoWithUserName { userName => - try { + try if gamesManager.gameControllerInfos.values.exists( _.controller.gameId == request.gameId ) @@ -405,15 +399,15 @@ class EagleServiceImpl( knownShardokResultCounts = request.shardokViewStatuses.toVector, responseObserver = responseObserver ) - } catch { - case ce: EagleClientException => + catch { + case ce: EagleClientException => responseObserver.onError(ce) case sre: StatusRuntimeException => SimpleTimedLogger.printLogger.logLine( s"Caught StatusRuntimeError $sre for ${responseObserver.userName}, it's probably fine" ) responseObserver.onError(sre) - case e: Exception => + case e: Exception => SimpleTimedLogger.printLogger.logLine(s"Caught error $e") e.printStackTrace() responseObserver.onError(e) @@ -424,42 +418,40 @@ class EagleServiceImpl( } private def lockedSendLobbyUpdate(userName: String): Unit = - try { + try lobbyUsers .get(userName) .foreach( _.onNext( UpdateStreamResponse( - responseDetails = - UpdateStreamResponse.ResponseDetails.LobbyResponse( - LobbyResponse( - runningGames = gamesManager - .gamesFor(userName) - .map(gamePlayerInfos => - GameInfo( - gameId = gamePlayerInfos.gameId, - factionId = gamePlayerInfos.factionId, - leader = Some(gamePlayerInfos.leader) - ) - ), - availableGames = gamesManager.availableGamesFor(userName), - waitingGames = gamesManager.waitingGamesFor(userName), - newGameOptions = Some( - NewGameOptions( - maxSupportedPlayers = MaxSupportedPlayers.intValue, - availableLeaders = gamesManager - .allLeaders( - expandedGameParameters = - GameParametersUtils.defaultExpandedGameParameters - ) + responseDetails = UpdateStreamResponse.ResponseDetails.LobbyResponse( + LobbyResponse( + runningGames = gamesManager + .gamesFor(userName) + .map(gamePlayerInfos => + GameInfo( + gameId = gamePlayerInfos.gameId, + factionId = gamePlayerInfos.factionId, + leader = Some(gamePlayerInfos.leader) ) + ), + availableGames = gamesManager.availableGamesFor(userName), + waitingGames = gamesManager.waitingGamesFor(userName), + newGameOptions = Some( + NewGameOptions( + maxSupportedPlayers = MaxSupportedPlayers.intValue, + availableLeaders = gamesManager + .allLeaders( + expandedGameParameters = GameParametersUtils.defaultExpandedGameParameters + ) ) ) ) + ) ) ) ) - } catch { + catch { case t: Throwable => SimpleTimedLogger.printLogger.logLine( s"Caught exception in lockedSendLobbyUpdate: $t" @@ -482,7 +474,6 @@ object EagleServiceImpl { gamesManager: GamesManager, customBattleManager: CustomBattleManager, functionalRandom: FunctionalRandom - ): EagleServiceImpl = { + ): EagleServiceImpl = new EagleServiceImpl(gamesManager, customBattleManager, functionalRandom) - } } diff --git a/src/main/scala/net/eagle0/eagle/service/ExceptionInterceptor.scala b/src/main/scala/net/eagle0/eagle/service/ExceptionInterceptor.scala index 2985f0107d..32b3cc11f6 100644 --- a/src/main/scala/net/eagle0/eagle/service/ExceptionInterceptor.scala +++ b/src/main/scala/net/eagle0/eagle/service/ExceptionInterceptor.scala @@ -14,9 +14,9 @@ class ExceptionInterceptor extends ServerInterceptor { } val listener = - try { + try next.startCall(call, headers) - } catch { + catch { case e: Throwable => println(s"Caught exception $e") throw e @@ -34,9 +34,9 @@ private class ExceptionHandlingServerCallListener[ReqT]( // Helper method to reduce code duplication private def wrapWithExceptionHandling(action: => Unit): Unit = - try { + try action - } catch { + catch { case e: Throwable => handleThrowable(e) throw e diff --git a/src/main/scala/net/eagle0/eagle/service/GamesManager.scala b/src/main/scala/net/eagle0/eagle/service/GamesManager.scala index 8be44aff27..c302d155ff 100644 --- a/src/main/scala/net/eagle0/eagle/service/GamesManager.scala +++ b/src/main/scala/net/eagle0/eagle/service/GamesManager.scala @@ -8,16 +8,9 @@ import net.eagle0.eagle.{FactionId, GameId, ProvinceId, ShardokGameId} import net.eagle0.eagle.api.eagle.* import net.eagle0.eagle.api.eagle.JoinGameResult.INVALID_OPTIONS_RESULT import net.eagle0.eagle.api.eagle.ShardokPlacementCommands.ShardokPlacementCommand -import net.eagle0.eagle.api.eagle.UpdateStreamRequest.StreamGameRequest.{ - ShardokViewStatus, - StreamingTextStatus -} +import net.eagle0.eagle.api.eagle.UpdateStreamRequest.StreamGameRequest.{ShardokViewStatus, StreamingTextStatus} import net.eagle0.eagle.api.selected_command.SelectedCommand -import net.eagle0.eagle.client_text.{ - ClientTextStoreImpl, - PregeneratedClientTextStore, - UnrequestedClientText -} +import net.eagle0.eagle.client_text.{ClientTextStoreImpl, PregeneratedClientTextStore, UnrequestedClientText} import net.eagle0.eagle.common.battalion_type.BattalionType import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.game_state.GameState @@ -27,20 +20,13 @@ import net.eagle0.eagle.internal.llm_response.LLMResponse import net.eagle0.eagle.internal.running_games.{RunningGame, RunningGames} import net.eagle0.eagle.internal.shardok_battle.ShardokBattle import net.eagle0.eagle.library.* -import net.eagle0.eagle.library.settings.loaders.{ - BattalionTypeLoader, - SettingsLoader -} +import net.eagle0.eagle.library.settings.loaders.{BattalionTypeLoader, SettingsLoader} import net.eagle0.eagle.library.settings.MaxSupportedPlayers import net.eagle0.eagle.library.util.hero_generator.hero_with_name.HeroWithName import net.eagle0.eagle.library.util.hero_generator.HeroGenerator import net.eagle0.eagle.library.util.EagleRequire import net.eagle0.eagle.service.controller.* -import net.eagle0.eagle.service.new_game_creation.{ - ExpandedGameParameters, - GameParametersUtils, - NewGameCreation -} +import net.eagle0.eagle.service.new_game_creation.{ExpandedGameParameters, GameParametersUtils, NewGameCreation} import net.eagle0.eagle.service.persistence.Persister import net.eagle0.eagle.shardok_interface.{ BattleResolution, @@ -72,7 +58,7 @@ case class GameAwaitingPlayers( ) { private def claimedNameTextIds: Vector[String] = existingHumanPlayers.map(_.leaderNameTextId) - def availableNameTextIds: Vector[String] = + def availableNameTextIds: Vector[String] = greatPeople .map(_.nameTextId) .filterNot(claimedNameTextIds.contains) @@ -128,27 +114,24 @@ object GamesManager { val runningGames = persister .retrieveAsStream(key) .toOption - .flatMap(inputStream => - ProtoParser.parse[RunningGames](inputStream)(using RunningGames) - ) + .flatMap(inputStream => ProtoParser.parse[RunningGames](inputStream)(using RunningGames)) .map(_.runningGames) .getOrElse(Vector.empty) val controllers = runningGames .filter(_.ongoing) - .flatMap(rg => - gameController(rg, gamePersisterCreation.persisterForGame(rg.gameId)) - ) + .flatMap(rg => gameController(rg, gamePersisterCreation.persisterForGame(rg.gameId))) .map(gc => gc.gameId -> gc) .toMap new GamesManager( shardokInternalInterface = shardokInternalInterface, - gameControllerInfos = controllers.map { case (gameId, c) => - ( - gameId, - ControllerInfo(controller = c, isAiGame = false, maxPlayers = 2) - ) + gameControllerInfos = controllers.map { + case (gameId, c) => + ( + gameId, + ControllerInfo(controller = c, isAiGame = false, maxPlayers = 2) + ) }, gamesAwaitingPlayers = Vector.empty, randomGenerator = randomGenerator, @@ -190,9 +173,7 @@ object GamesManager { .toVector val pregenHeroes = - pregeneratedHeroes.filterNot(heroWithName => - existingNames.contains(heroWithName.name) - ) + pregeneratedHeroes.filterNot(heroWithName => existingNames.contains(heroWithName.name)) HeroGenerator( pregeneratedHeroes = pregenHeroes, @@ -280,7 +261,7 @@ class GamesManager( gameControllerInfos = gameControllerInfos.zipWithIndex.map { case ((gameId, c), idx) => - val withIncomplete = + val withIncomplete = unrequestedTextHandler.clientTextStoreWithHandledIncompleteTexts( clientTextStore = c.controller.clientTextStore, gameHistory = c.controller.engine.history, @@ -397,22 +378,23 @@ class GamesManager( } def gamesFor(name: String): Vector[GamePlayerInfo] = this.synchronized { - gameControllerInfos.flatMap { case (gameId, c) => - c.controller.userNameToFactionId - .get(name) - .map(fid => - GamePlayerInfo( - gameId, - Some(fid), - availableLeader( - c.controller.engine.currentState.heroes( - c.controller.engine.currentState - .factions(fid) - .factionHeadId + gameControllerInfos.flatMap { + case (gameId, c) => + c.controller.userNameToFactionId + .get(name) + .map(fid => + GamePlayerInfo( + gameId, + Some(fid), + availableLeader( + c.controller.engine.currentState.heroes( + c.controller.engine.currentState + .factions(fid) + .factionHeadId + ) ) ) ) - ) }.toVector } @@ -479,12 +461,13 @@ class GamesManager( private def save(): Unit = this.synchronized { val rg = RunningGames( - runningGames = gameControllerInfos.map { case (gameId, gc) => - RunningGame( - gameId = gameId, - userToPid = gc.controller.userNameToFactionId, - ongoing = true - ) + runningGames = gameControllerInfos.map { + case (gameId, gc) => + RunningGame( + gameId = gameId, + userToPid = gc.controller.userNameToFactionId, + ongoing = true + ) }.toVector ) @@ -587,8 +570,7 @@ class GamesManager( PlacementCommand(unitId = pc.unitId, row = pc.row, column = pc.column) }, token = shardokToken, - eagleFactionId = - gameControllerInfos(eagleGameId).controller.userNameToFactionId(name) + eagleFactionId = gameControllerInfos(eagleGameId).controller.userNameToFactionId(name) ) } @@ -647,15 +629,14 @@ class GamesManager( gameControllerInfos.contains(gameId), s"No game found with ID ${gameId.toHexString}" ) - gameControllerInfos(gameId).controller = - gameControllerInfos(gameId).controller - .streamUpdates( - userName = name, - knownResultCount = knownResultCount, - knownShardokResultCounts = knownShardokResultCounts, - responseObserver = responseObserver, - streamingTextStatuses = streamingTextStatuses - ) + gameControllerInfos(gameId).controller = gameControllerInfos(gameId).controller + .streamUpdates( + userName = name, + knownResultCount = knownResultCount, + knownShardokResultCounts = knownShardokResultCounts, + responseObserver = responseObserver, + streamingTextStatuses = streamingTextStatuses + ) } def stopStreaming( @@ -663,9 +644,8 @@ class GamesManager( gameId: GameId ): Unit = this.synchronized { - gameControllerInfos(gameId).controller = - gameControllerInfos(gameId).controller - .stopStreaming(userName = name) + gameControllerInfos(gameId).controller = gameControllerInfos(gameId).controller + .stopStreaming(userName = name) } def joinGame( @@ -689,8 +669,7 @@ class GamesManager( expandedGameParameters = gap.expandedGameParameters, gameId = newGap.gameId, humanPlayers = newGap.existingHumanPlayers, - aiPlayerCount = - newGap.totalPlayerCount - newGap.existingHumanPlayers.size, + aiPlayerCount = newGap.totalPlayerCount - newGap.existingHumanPlayers.size, persister = persister ) } else @@ -712,7 +691,7 @@ class GamesManager( result = JoinGameResult.NO_SUCH_LEADER_JOIN_GAME_RESULT, gameId = gameId ) - case None => + case None => JoinGameResponse( JoinGameResult.GAME_FULL_JOIN_GAME_RESULT, gameId = gameId @@ -765,13 +744,12 @@ class GamesManager( persister: Persister ): GameControllerWithPostResults = { val humanPlayerCount = humanPlayers.size - val initialEar = gameCreation + val initialEar = gameCreation .createGame( expandedGameParameters = expandedGameParameters, gameId = gameId, persister = gamePersisterCreation.persisterForGame(gameId), - humanPlayerFactionLeaderNameTextIds = - humanPlayers.map(_.leaderNameTextId), + humanPlayerFactionLeaderNameTextIds = humanPlayers.map(_.leaderNameTextId), playerCount = humanPlayerCount + aiPlayerCount, allBattalionTypes = GamesManager.battalionTypes ) diff --git a/src/main/scala/net/eagle0/eagle/service/InMemoryHistory.scala b/src/main/scala/net/eagle0/eagle/service/InMemoryHistory.scala index c972eff2e4..2c4883fc4e 100644 --- a/src/main/scala/net/eagle0/eagle/service/InMemoryHistory.scala +++ b/src/main/scala/net/eagle0/eagle/service/InMemoryHistory.scala @@ -28,8 +28,7 @@ object InMemoryHistory { ) } -final case class InMemoryHistory(history: Vector[ActionWithResultingState]) - extends GameHistory { +final case class InMemoryHistory(history: Vector[ActionWithResultingState]) extends GameHistory { override def all: Vector[ActionWithResultingState] = history diff --git a/src/main/scala/net/eagle0/eagle/service/LlmResolver.scala b/src/main/scala/net/eagle0/eagle/service/LlmResolver.scala index 832ce85e20..57edd2c399 100644 --- a/src/main/scala/net/eagle0/eagle/service/LlmResolver.scala +++ b/src/main/scala/net/eagle0/eagle/service/LlmResolver.scala @@ -86,11 +86,10 @@ import net.eagle0.eagle.library.actions.llm_prompt_generators.{ import net.eagle0.eagle.library.EagleInternalException sealed trait LlmResolverResult -case class LlmResolverDependencyNotSatisfied(notSatisfiedTextId: String) - extends LlmResolverResult -case object LlmResolverTooManyRequestsInFlight extends LlmResolverResult -case object LlmResolverBypassed extends LlmResolverResult -case class LlmResolverRequested(future: Future[?]) extends LlmResolverResult +case class LlmResolverDependencyNotSatisfied(notSatisfiedTextId: String) extends LlmResolverResult +case object LlmResolverTooManyRequestsInFlight extends LlmResolverResult +case object LlmResolverBypassed extends LlmResolverResult +case class LlmResolverRequested(future: Future[?]) extends LlmResolverResult object LlmResolver { case class LlmRequestWithGameState( @@ -108,12 +107,12 @@ class LlmResolver(updateReceiver: LlmUpdateQueuingProxy, gptModelName: String) { private def newChatGptServiceImpl = new OpenAIChatCompletionsServiceImpl( defaultModelName = gptModelName ) - private def newClaudeServiceImpl = new ClaudeServiceImpl( + private def newClaudeServiceImpl = new ClaudeServiceImpl( defaultModelName = "claude-sonnet-4-20250514" ) private val chatGptCount = 2 - private val claudeCount = 0 + private val claudeCount = 0 lazy private val llmCallers = ((1 to claudeCount).map { _ => new ExternalTextGenerationCaller( @@ -137,7 +136,7 @@ class LlmResolver(updateReceiver: LlmUpdateQueuingProxy, gptModelName: String) { functionalRandom: FunctionalRandom ): RandomState[ Vector[(GeneratedTextRequest, TextGenerationResult, Option[String])] - ] = { + ] = functionalRandom.nextMap(llmRequests) { case ( LlmRequestWithGameState(llmRequest, gameState, partialCompletion), @@ -149,37 +148,37 @@ class LlmResolver(updateReceiver: LlmUpdateQueuingProxy, gptModelName: String) { (llmRequest, prompt, partialCompletion) } } - } def sortedLlmRequestsWithPrompts( prompts: Vector[ (GeneratedTextRequest, TextGenerationResult, Option[String]) ] ): Vector[(GeneratedTextRequest, TextGenerationResult, Option[String])] = - prompts.sortBy { case (llmRequest, maybePrompt, partialCompletion) => - maybePrompt match { - case TextGenerationSuccess(_ /* result */ ) - if prompts - .map(_._2) - .contains(TextGenerationDependencyWaiting(llmRequest.id)) => - 1 - case TextGenerationSuccess(_ /* result */ ) => 5 - case TextGenerationDependencyWaiting(_ /* notSatisfiedTextId */ ) => - 10 - case TextGenerationDependencyInProgress( - _ /* inProgressTextId */, - _ /* partialText */ - ) => - 100 - case TextGenerationDependencyUnknown(unknownTextId) => - throw new EagleInternalException( - s"Unknown dependency: $unknownTextId" - ) - case _ => - throw new EagleInternalException( - s"Unexpected dependency state for ${llmRequest.id}" - ) - } + prompts.sortBy { + case (llmRequest, maybePrompt, partialCompletion) => + maybePrompt match { + case TextGenerationSuccess(_ /* result */ ) + if prompts + .map(_._2) + .contains(TextGenerationDependencyWaiting(llmRequest.id)) => + 1 + case TextGenerationSuccess(_ /* result */ ) => 5 + case TextGenerationDependencyWaiting(_ /* notSatisfiedTextId */ ) => + 10 + case TextGenerationDependencyInProgress( + _ /* inProgressTextId */, + _ /* partialText */ + ) => + 100 + case TextGenerationDependencyUnknown(unknownTextId) => + throw new EagleInternalException( + s"Unknown dependency: $unknownTextId" + ) + case _ => + throw new EagleInternalException( + s"Unexpected dependency state for ${llmRequest.id}" + ) + } } def resolveLlmRequests( @@ -232,12 +231,13 @@ class LlmResolver(updateReceiver: LlmUpdateQueuingProxy, gptModelName: String) { completed = streamingResults.completed ) ) - .recover { case ex => - // Handle failure by moving request back to unrequested state for retry - updateReceiver.receiveStreamingLlmFailure( - llmRequest = llmRequest - ) - throw ex // Re-throw to maintain error semantics + .recover { + case ex => + // Handle failure by moving request back to unrequested state for retry + updateReceiver.receiveStreamingLlmFailure( + llmRequest = llmRequest + ) + throw ex // Re-throw to maintain error semantics } } } @@ -268,21 +268,21 @@ class LlmResolver(updateReceiver: LlmUpdateQueuingProxy, gptModelName: String) { ): RandomState[LLMPromptGenerator] = { functionalRandom.nextInt.map { randomInt => details match { - case fixedHeroName: FixedHeroNameMessage => + case fixedHeroName: FixedHeroNameMessage => throw new EagleInternalException( "FixedHeroNameMessage should not be used in LLM requests" ) - case generatedHeroName: GeneratedHeroNameMessage => + case generatedHeroName: GeneratedHeroNameMessage => throw new EagleInternalException( "GeneratedHeroNameMessage should not be used in LLM requests" ) - case plea: HandleCapturedHeroPlea => + case plea: HandleCapturedHeroPlea => HandleCapturedHeroPleaPromptGenerator( plea = plea, gameState = gameState, clientTextStore = clientTextStore ) - case truceOfferMessage: TruceOfferMessage => + case truceOfferMessage: TruceOfferMessage => TruceOfferMessagePromptGenerator( truceOfferMessage = truceOfferMessage, gameState = gameState, @@ -294,7 +294,7 @@ class LlmResolver(updateReceiver: LlmUpdateQueuingProxy, gptModelName: String) { gameState = gameState, clientTextStore = clientTextStore ) - case allianceOfferMessage: AllianceOfferMessage => + case allianceOfferMessage: AllianceOfferMessage => AllianceOfferMessagePromptGenerator( allianceOfferMessage = allianceOfferMessage, gameState = gameState, @@ -330,109 +330,109 @@ class LlmResolver(updateReceiver: LlmUpdateQueuingProxy, gptModelName: String) { randomInt = randomInt ) - case invitationMessage: InvitationMessage => + case invitationMessage: InvitationMessage => InvitationMessagePromptGenerator( invitationMessage = invitationMessage, gameState = gameState, clientTextStore = clientTextStore ) - case invitationResolutionMessage: InvitationResolutionMessage => + case invitationResolutionMessage: InvitationResolutionMessage => InvitationResolutionMessagePromptGenerator( invitationResolutionMessage = invitationResolutionMessage, gameState = gameState, clientTextStore = clientTextStore ) - case ransomOfferMessage: RansomOfferMessage => + case ransomOfferMessage: RansomOfferMessage => RansomOfferMessagePromptGenerator( ransomOfferMessage = ransomOfferMessage, gameState = gameState, clientTextStore = clientTextStore ) - case ransomResolutionMessage: RansomResolutionMessage => + case ransomResolutionMessage: RansomResolutionMessage => RansomResolutionMessagePromptGenerator( ransomResolutionMessage = ransomResolutionMessage, gameState = gameState, clientTextStore = clientTextStore ) - case capturedHeroExecutedMessage: CapturedHeroExecutedMessage => + case capturedHeroExecutedMessage: CapturedHeroExecutedMessage => CapturedHeroExecutedPromptGenerator( executedMessage = capturedHeroExecutedMessage, gameState = gameState, clientTextStore = clientTextStore ) - case capturedHeroExiledMessage: CapturedHeroExiledMessage => + case capturedHeroExiledMessage: CapturedHeroExiledMessage => CapturedHeroExiledPromptGenerator( exiledMessage = capturedHeroExiledMessage, gameState = gameState, clientTextStore = clientTextStore ) - case capturedHeroImprisonedMessage: CapturedHeroImprisonedMessage => + case capturedHeroImprisonedMessage: CapturedHeroImprisonedMessage => CapturedHeroImprisonedPromptGenerator( imprisonedMessage = capturedHeroImprisonedMessage, gameState = gameState, clientTextStore = clientTextStore ) - case pleaseRecruitMeMessage: PleaseRecruitMeMessage => + case pleaseRecruitMeMessage: PleaseRecruitMeMessage => PleaseRecruitMePromptGenerator( pleaseRecruitMeMessage = pleaseRecruitMeMessage, gameState = gameState, clientTextStore = clientTextStore ) - case questFailedMessage: QuestFailedMessage => + case questFailedMessage: QuestFailedMessage => QuestFailedPromptGenerator( questFailedMessage = questFailedMessage, gameState = gameState, clientTextStore = clientTextStore ) - case questFulfilledMessage: QuestFulfilledMessage => + case questFulfilledMessage: QuestFulfilledMessage => QuestFulfilledPromptGenerator( questFulfilledMessage = questFulfilledMessage, gameState = gameState, clientTextStore = clientTextStore ) - case recruitmentRefusedMessage: RecruitmentRefusedMessage => + case recruitmentRefusedMessage: RecruitmentRefusedMessage => RecruitmentRefusedPromptGenerator( recruitmentRefusedMessage = recruitmentRefusedMessage, gameState = gameState, clientTextStore = clientTextStore ) - case swearBrotherhoodMessage: SwearBrotherhoodMessage => + case swearBrotherhoodMessage: SwearBrotherhoodMessage => SwearBrotherhoodPromptGenerator( swearBrotherhoodMessage = swearBrotherhoodMessage, gameState = gameState, clientTextStore = clientTextStore ) - case divineMessage: DivineMessage => + case divineMessage: DivineMessage => DivineMessagePromptGenerator( divineMessage = divineMessage, gameState = gameState, clientTextStore = clientTextStore ) - case exileVassalMessage: ExileVassalMessage => + case exileVassalMessage: ExileVassalMessage => ExileVassalPromptGenerator( exileVassalMessage = exileVassalMessage, gameState = gameState, clientTextStore = clientTextStore ) - case backgroundUpdateRequest: HeroBackstoryUpdateRequest => + case backgroundUpdateRequest: HeroBackstoryUpdateRequest => HeroBackstoryUpdatePromptGenerator( backstoryUpdateRequest = backgroundUpdateRequest, gameState = gameState, clientTextStore = clientTextStore ) - case initialBackstoryRequest: HeroInitialBackstoryRequest => + case initialBackstoryRequest: HeroInitialBackstoryRequest => HeroInitialBackstoryPromptGenerator( initialBackstoryRequest = initialBackstoryRequest, gameState = gameState, clientTextStore = clientTextStore ) - case heroDepartureMessage: HeroDepartureMessage => + case heroDepartureMessage: HeroDepartureMessage => HeroDeparturePromptGenerator( heroDepartureMessage = heroDepartureMessage, gameState = gameState, clientTextStore = clientTextStore ) - case suppressBeastsFailedMessage: SuppressBeastsFailedMessage => + case suppressBeastsFailedMessage: SuppressBeastsFailedMessage => SuppressBeastsFailedPromptGenerator( suppressBeastsFailedMessage = suppressBeastsFailedMessage, gameState = gameState, diff --git a/src/main/scala/net/eagle0/eagle/service/LlmUpdateQueuingProxy.scala b/src/main/scala/net/eagle0/eagle/service/LlmUpdateQueuingProxy.scala index 49f9995d08..b9919eb347 100644 --- a/src/main/scala/net/eagle0/eagle/service/LlmUpdateQueuingProxy.scala +++ b/src/main/scala/net/eagle0/eagle/service/LlmUpdateQueuingProxy.scala @@ -15,7 +15,7 @@ class LlmUpdateQueuingProxy(destination: LlmUpdateReceiver) { llmRequest: GeneratedTextRequest ) extends QueuedLlmUpdate - private val queue = new scala.collection.mutable.Queue[QueuedLlmUpdate] + private val queue = new scala.collection.mutable.Queue[QueuedLlmUpdate] private val consumerThread = new Thread(new Consumer()) consumerThread.start() @@ -40,9 +40,7 @@ class LlmUpdateQueuingProxy(destination: LlmUpdateReceiver) { private class Consumer extends Runnable { override def run(): Unit = while true do { val updates = queue.synchronized { - while queue.isEmpty do { - queue.wait() - } + while queue.isEmpty do queue.wait() queue .dequeueAll(_ => true) } @@ -60,12 +58,13 @@ class LlmUpdateQueuingProxy(destination: LlmUpdateReceiver) { // Then handle responses grouped by streamId responses .groupBy(_.streamId) - .foreach { case (streamId, messages) => - destination.receiveStreamingLlmResponses( - streamId, - messages.map(_.llmResponse), - messages.last.completed - ) + .foreach { + case (streamId, messages) => + destination.receiveStreamingLlmResponses( + streamId, + messages.map(_.llmResponse), + messages.last.completed + ) } } } diff --git a/src/main/scala/net/eagle0/eagle/service/LocalGamePersisterCreation.scala b/src/main/scala/net/eagle0/eagle/service/LocalGamePersisterCreation.scala index f4ea40c2b9..de7c3ab312 100644 --- a/src/main/scala/net/eagle0/eagle/service/LocalGamePersisterCreation.scala +++ b/src/main/scala/net/eagle0/eagle/service/LocalGamePersisterCreation.scala @@ -16,7 +16,7 @@ object LocalGamePersisterCreation extends GamePersisterCreation { private def localFilePersister(gameId: GameId) = LocalFilePersister( SaveDirectory.saveDirectoryForGame(gameId) ) - private def s3Persister(gameId: GameId) = + private def s3Persister(gameId: GameId) = S3Persister(S3Utils.mainBucketName, S3Utils.makeS3Prefix(gameId)) def persisterForGame(gameId: GameId): Persister = diff --git a/src/main/scala/net/eagle0/eagle/service/PersistedHistory.scala b/src/main/scala/net/eagle0/eagle/service/PersistedHistory.scala index ed338dd878..040aa4153c 100644 --- a/src/main/scala/net/eagle0/eagle/service/PersistedHistory.scala +++ b/src/main/scala/net/eagle0/eagle/service/PersistedHistory.scala @@ -24,7 +24,7 @@ import net.eagle0.shardok.storage.action_result.ActionResult as ShardokActionRes object PersistedHistory { private val resultsPerSaveFile = 200 - private val applier = new ActionResultProtoApplierImpl( + private val applier = new ActionResultProtoApplierImpl( validator = RuntimeValidator ) @@ -90,8 +90,8 @@ object PersistedHistory { ): Option[PersistedHistory] = { val allKeys = persister.existingKeys - val key = s"directory${persistence.eagleIndexExtension}" - val stream = persister.retrieveAsStream(key) + val key = s"directory${persistence.eagleIndexExtension}" + val stream = persister.retrieveAsStream(key) val directoryProto = ProtoParser .parse[PartialGameIndex](stream.get)(using PartialGameIndex) .get @@ -112,7 +112,7 @@ object PersistedHistory { .sortBy(_.dropRight(4).toInt) .lastOption - val shardokKeys = allKeys.filter(_.endsWith(persistence.shardokExtension)) + val shardokKeys = allKeys.filter(_.endsWith(persistence.shardokExtension)) val shardokGames = shardokKeys .map(persister.retrieveAsStream) @@ -125,9 +125,7 @@ object PersistedHistory { lastKey .map(persister.retrieveAsStream) .flatMap(_.toOption) - .flatMap(inputStream => - ProtoParser.parseZipped[PartialGame](inputStream)(using PartialGame) - ) + .flatMap(inputStream => ProtoParser.parseZipped[PartialGame](inputStream)(using PartialGame)) .map { pg => internalRequire( pg.getStartingState.actionResultCount == pg.startingIndex, @@ -267,8 +265,7 @@ final case class PersistedHistory( } override def since(startCount: Int): Vector[ActionWithResultingState] = - if startCount >= persistedCount then - recentHistory.drop(startCount - persistedCount) + if startCount >= persistedCount then recentHistory.drop(startCount - persistedCount) else { val initialIndex = (startCount / resultsPerSaveFile) * resultsPerSaveFile @@ -292,9 +289,7 @@ final case class PersistedHistory( .dropWhile(_.endingDate < date) val pgs = validEntries - .flatMap(entry => - PartialGameUtils.partialGame(persister, entry.startingIndex) - ) + .flatMap(entry => PartialGameUtils.partialGame(persister, entry.startingIndex)) val results = pgs.flatMap(_.results) val history = PersistedHistory.formAwrs( @@ -390,13 +385,12 @@ final case class PersistedHistory( throw new EagleInternalException( s"Requested state after $count, but only have $persistedCount persisted and ${recentHistory.length} recent" ) - else if count > persistedCount then - recentHistory(count - 1 - persistedCount).gameState + else if count > persistedCount then recentHistory(count - 1 - persistedCount).gameState else { val initialIndex = ((count - 1) / resultsPerSaveFile) * resultsPerSaveFile - val pgs = PartialGameUtils + val pgs = PartialGameUtils .partialGames(persister, initialIndex, persistedCount) - val vec = + val vec = PersistedHistory.formAwrs( pgs.head.startingState.get, pgs.flatMap(_.results) @@ -422,7 +416,7 @@ final case class PersistedHistory( private def viewsForPlayer( shardokGameId: ShardokGameId, factionId: FactionId - ): Option[ShardokResults.OnePlayerViews] = { + ): Option[ShardokResults.OnePlayerViews] = shardokHistory .find(_.shardokGameId == shardokGameId) .flatMap(sr => @@ -430,7 +424,6 @@ final case class PersistedHistory( .find(_.factionId == factionId) .orElse(sr.playerViews.find(_.factionId == -1)) ) - } override def shardokPlayerCount( shardokGameId: ShardokGameId, @@ -529,8 +522,7 @@ final case class PersistedHistory( newPlayerResults = newPlayerResults, newAvailableCommands = availableCommands ).toVector, - currentGameState = - com.google.protobuf.ByteString.copyFrom(currentGameState) + currentGameState = com.google.protobuf.ByteString.copyFrom(currentGameState) ) } .getOrElse( @@ -543,8 +535,7 @@ final case class PersistedHistory( newAvailableCommands = availableCommands ), eagleRoundId = eagleRoundId, - currentGameState = - com.google.protobuf.ByteString.copyFrom(currentGameState) + currentGameState = com.google.protobuf.ByteString.copyFrom(currentGameState) ) ) diff --git a/src/main/scala/net/eagle0/eagle/service/ServerSetupHelpers.scala b/src/main/scala/net/eagle0/eagle/service/ServerSetupHelpers.scala index 024137bcf2..626e0099e7 100644 --- a/src/main/scala/net/eagle0/eagle/service/ServerSetupHelpers.scala +++ b/src/main/scala/net/eagle0/eagle/service/ServerSetupHelpers.scala @@ -11,13 +11,7 @@ import io.grpc.{Channel, ManagedChannelBuilder} import net.eagle0.common.shardok_internal_interface.ShardokInternalInterfaceGrpc import net.eagle0.common.shardok_internal_interface.ShardokInternalInterfaceGrpc.ShardokInternalInterfaceStub import net.eagle0.eagle.service.new_game_creation.FixedNewGameCreation -import net.eagle0.eagle.service.persistence.{ - CompoundPersister, - LocalFilePersister, - S3Persister, - S3Utils, - SaveDirectory -} +import net.eagle0.eagle.service.persistence.{CompoundPersister, LocalFilePersister, S3Persister, S3Utils, SaveDirectory} import net.eagle0.eagle.shardok_interface.ShardokInterfaceGrpcClient import net.eagle0.shardok.common.hex_map.HexMap @@ -36,9 +30,9 @@ object ServerSetupHelpers { shardokInterfaceAddress: String, gptModelName: String ): GamesManager = { - implicit val ec = scala.concurrent.ExecutionContext.global + implicit val ec = scala.concurrent.ExecutionContext.global val shardokInternalInterface = newShardokInterface(shardokInterfaceAddress) - val shardokClient = + val shardokClient = new ShardokInterfaceGrpcClient(shardokInternalInterface, null) val hexMaps: Map[String, HexMap] = Await @@ -47,16 +41,14 @@ object ServerSetupHelpers { .getHexMapNames() .flatMap { names => Future.sequence( - names - .map { name => - name -> shardokClient.getHexMap(name) - } - .toMap - .map { case (name, hexMapF) => + names.map { name => + name -> shardokClient.getHexMap(name) + }.toMap.map { + case (name, hexMapF) => hexMapF.map { hexMap => name -> hexMap } - } + } ) } .map(_.toMap), @@ -67,9 +59,9 @@ object ServerSetupHelpers { .get val localPersister = LocalFilePersister(SaveDirectory.saveDirectory) - val s3Persister = + val s3Persister = S3Persister(S3Utils.mainBucketName, S3Utils.runningGamesKeyPrefix) - val _ = s3Persister + val _ = s3Persister GamesManager( shardokInternalInterface = shardokInternalInterface, diff --git a/src/main/scala/net/eagle0/eagle/service/UnrequestedTextHandler.scala b/src/main/scala/net/eagle0/eagle/service/UnrequestedTextHandler.scala index 4935b7998b..47197aa8a8 100644 --- a/src/main/scala/net/eagle0/eagle/service/UnrequestedTextHandler.scala +++ b/src/main/scala/net/eagle0/eagle/service/UnrequestedTextHandler.scala @@ -49,43 +49,40 @@ class UnrequestedTextHandler(llmResolver: LlmResolver) { .clientTextStore } - val (llmRequests, generatedNameRequests) = generationRequests.partition { - ut => - ut.llmRequest.details match { - case _: GeneratedHeroNameMessage => false - case _ => true - } + val (llmRequests, generatedNameRequests) = generationRequests.partition { ut => + ut.llmRequest.details match { + case _: GeneratedHeroNameMessage => false + case _ => true + } } val ctsWithRequestedNames = HeroNameFetcher .names( - genderStrings = generatedNameRequests - .map { ut => - ut.llmRequest.details.asInstanceOf[GeneratedHeroNameMessage].gender - } - .toVector - .map { - case Gender.GENDER_UNKNOWN => "other" - case Gender.GENDER_FEMALE => "female" - case Gender.GENDER_MALE => "male" - case Gender.GENDER_OTHER => "other" - case Gender.Unrecognized(_) => "other" - }, + genderStrings = generatedNameRequests.map { ut => + ut.llmRequest.details.asInstanceOf[GeneratedHeroNameMessage].gender + }.toVector.map { + case Gender.GENDER_UNKNOWN => "other" + case Gender.GENDER_FEMALE => "female" + case Gender.GENDER_MALE => "male" + case Gender.GENDER_OTHER => "other" + case Gender.Unrecognized(_) => "other" + }, excludingNames = ctsWithResolvedFixedHeroNames.completeTexts.values .map(_.text) .toVector ) .get .zip(generatedNameRequests) - .foldLeft(ctsWithResolvedFixedHeroNames) { case (acc, (name, request)) => - acc - .withMarkedRequested(request.id) - .withAppendedText( - id = request.id, - newText = name, - complete = true - ) - .clientTextStore + .foldLeft(ctsWithResolvedFixedHeroNames) { + case (acc, (name, request)) => + acc + .withMarkedRequested(request.id) + .withAppendedText( + id = request.id, + newText = name, + complete = true + ) + .clientTextStore } val llmRequestsWithGameStates = @@ -110,29 +107,30 @@ class UnrequestedTextHandler(llmResolver: LlmResolver) { ctsWithRequestedNames, Vector.empty[StuckUnrequested] ) - ) { case (acc, (llmRequest, llmResolverResult)) => - llmResolverResult match { - case LlmResolverRequested(_) => - Accumulator( - clientTextStore = acc.clientTextStore - .withMarkedRequested(llmRequest.id), - acc.stuckEntries - ) - case LlmResolverBypassed => - Accumulator( - clientTextStore = acc.clientTextStore.withBypassed(llmRequest.id), - acc.stuckEntries - ) - case LlmResolverTooManyRequestsInFlight => - acc - case LlmResolverDependencyNotSatisfied(unsatisfiedTextId) => - acc.copy(stuckEntries = - acc.stuckEntries :+ StuckUnrequested( - llmRequest, - unsatisfiedTextId + ) { + case (acc, (llmRequest, llmResolverResult)) => + llmResolverResult match { + case LlmResolverRequested(_) => + Accumulator( + clientTextStore = acc.clientTextStore + .withMarkedRequested(llmRequest.id), + acc.stuckEntries ) - ) - } + case LlmResolverBypassed => + Accumulator( + clientTextStore = acc.clientTextStore.withBypassed(llmRequest.id), + acc.stuckEntries + ) + case LlmResolverTooManyRequestsInFlight => + acc + case LlmResolverDependencyNotSatisfied(unsatisfiedTextId) => + acc.copy(stuckEntries = + acc.stuckEntries :+ StuckUnrequested( + llmRequest, + unsatisfiedTextId + ) + ) + } } // If every unrequested text is waiting on another unrequested text, we have a circular dependency diff --git a/src/main/scala/net/eagle0/eagle/service/controller/GameController.scala b/src/main/scala/net/eagle0/eagle/service/controller/GameController.scala index d8b65b7768..dea8d80f86 100644 --- a/src/main/scala/net/eagle0/eagle/service/controller/GameController.scala +++ b/src/main/scala/net/eagle0/eagle/service/controller/GameController.scala @@ -10,35 +10,17 @@ import net.eagle0.common.{RandomState, SeededRandom, SimpleTimedLogger} import net.eagle0.eagle.{FactionId, GameId, ProvinceId} import net.eagle0.eagle.ai.AIClient import net.eagle0.eagle.api.eagle.ShardokActionResultResponse.SingleShardokGameResultResponse -import net.eagle0.eagle.api.eagle.UpdateStreamRequest.StreamGameRequest.{ - ShardokViewStatus, - StreamingTextStatus -} +import net.eagle0.eagle.api.eagle.UpdateStreamRequest.StreamGameRequest.{ShardokViewStatus, StreamingTextStatus} import net.eagle0.eagle.api.selected_command.SelectedCommand -import net.eagle0.eagle.client_text.{ - ClientText, - ClientTextStore, - ClientTextStoreWithUpdate -} +import net.eagle0.eagle.client_text.{ClientText, ClientTextStore, ClientTextStoreWithUpdate} import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.action_result.ActionResult.ClientTextVisibilityExtension import net.eagle0.eagle.internal.generated_text_request.GeneratedTextRequest import net.eagle0.eagle.internal.llm_response.LLMResponse -import net.eagle0.eagle.library.{ - EagleInternalException, - Engine, - EngineAndResults -} +import net.eagle0.eagle.library.{EagleInternalException, Engine, EngineAndResults} import net.eagle0.eagle.library.util.CommandSelection -import net.eagle0.eagle.library.util.EagleRequire.{ - clientRequire, - internalRequire -} -import net.eagle0.eagle.service.{ - LlmRequestAfterHistoryCount, - PostResults, - SyncResponseObserver -} +import net.eagle0.eagle.library.util.EagleRequire.{clientRequire, internalRequire} +import net.eagle0.eagle.service.{LlmRequestAfterHistoryCount, PostResults, SyncResponseObserver} import net.eagle0.eagle.shardok_interface.{BattleResolution, BattleUpdate} case class GameControllerWithPostResults( @@ -63,17 +45,18 @@ object GameController { if commands.isEmpty then newAcc else { - val next = commands.foldLeft(newAcc) { case (gcwpr, (fid, cmd)) => - val tmp = gcwpr.gameController.withPostedCommand( - factionId = fid, - selectedProvinceId = cmd.actingProvinceId, - command = cmd.selected, - save = false - ) - GameControllerWithPostResults( - gameController = tmp.gameController, - postResults = gcwpr.postResults.append(tmp.postResults) - ) + val next = commands.foldLeft(newAcc) { + case (gcwpr, (fid, cmd)) => + val tmp = gcwpr.gameController.withPostedCommand( + factionId = fid, + selectedProvinceId = cmd.actingProvinceId, + command = cmd.selected, + save = false + ) + GameControllerWithPostResults( + gameController = tmp.gameController, + postResults = gcwpr.postResults.append(tmp.postResults) + ) } go(next) @@ -91,26 +74,22 @@ object GameController { completed: Boolean ): Vector[HumanPlayerClientConnectionState] = humanClients - .partition(client => - accessibleTo.isEmpty || accessibleTo.contains(client.factionId) - ) match { + .partition(client => accessibleTo.isEmpty || accessibleTo.contains(client.factionId)) match { case (clientsToUpdate, clientsToIgnore) => - clientsToUpdate - .flatMap { client => - try { - Some(client.update(clientText = updatedText)) - } catch { - case x: StatusRuntimeException - if x.getStatus.getCode == Status.Code.CANCELLED => - None + clientsToUpdate.flatMap { client => + try + Some(client.update(clientText = updatedText)) + catch { + case x: StatusRuntimeException if x.getStatus.getCode == Status.Code.CANCELLED => + None - case x: StatusRuntimeException => - SimpleTimedLogger.printLogger.logLine( - s"fid ${client.factionId}: Caught exception $x" - ) - Some(client) - } - } ++ clientsToIgnore + case x: StatusRuntimeException => + SimpleTimedLogger.printLogger.logLine( + s"fid ${client.factionId}: Caught exception $x" + ) + Some(client) + } + } ++ clientsToIgnore } private def humanClientsAfterPostingResults( @@ -126,7 +105,7 @@ object GameController { clientTextStore.completeTexts.get(ext.textId) } - val updates = engine.filteredHistoryWithUnfilteredCount( + val updates = engine.filteredHistoryWithUnfilteredCount( client.factionId, client.unfilteredKnownHistoryCount ) @@ -141,12 +120,12 @@ object GameController { .find(_.shardokGameId == shardokGameId) .map(_.filteredResultCount) .getOrElse(0) - val arvs = engine.history.shardokPlayerResultsSince( + val arvs = engine.history.shardokPlayerResultsSince( shardokGameId = shardokGameId, factionId = client.factionId, startingCount = startingCount ) - val acs = engine.history.shardokPlayerAvailableCommands( + val acs = engine.history.shardokPlayerAvailableCommands( shardokGameId = shardokGameId, factionId = client.factionId ) @@ -158,17 +137,16 @@ object GameController { ) } - try { + try Some { val availableCommands = engine.getAvailablePlayerCommands(client.factionId) - val note = + val note = s"fid ${client.factionId}: Updating client with ${updates.filteredResults.length} new results, " + s"${shardokUpdates.length} new Shardok results, " - val note2 = availableCommands - .map { acs => - s"available commands with token ${acs.token}" - } + val note2 = availableCommands.map { acs => + s"available commands with token ${acs.token}" + } .getOrElse("no available commands") SimpleTimedLogger .fileLogger(gameId = engine.gameId, fileName = "timings") @@ -176,20 +154,19 @@ object GameController { clientTextUpdates.foldLeft( client .update( - availableCommands = - engine.getAvailablePlayerCommands(client.factionId), + availableCommands = engine.getAvailablePlayerCommands(client.factionId), filteredResults = updates.filteredResults, unfilteredCountAfter = updates.unfilteredCountAfter, knownShardokResults = shardokUpdates.toVector ) - ) { case (client, clientTextUpdate) => - client.update(clientText = clientTextUpdate) + ) { + case (client, clientTextUpdate) => + client.update(clientText = clientTextUpdate) } } } - } catch { - case x: StatusRuntimeException - if x.getStatus.getCode == Status.Code.CANCELLED => + catch { + case x: StatusRuntimeException if x.getStatus.getCode == Status.Code.CANCELLED => None case x: StatusRuntimeException => @@ -198,6 +175,7 @@ object GameController { ) None } + end try } def advancedFrom( @@ -215,8 +193,9 @@ object GameController { aiClients = Vector(), clientTextStore = clientTextStore ) - ) { case (c, aiPid) => - c.withNewAiClientWithFid(aiPid) + ) { + case (c, aiPid) => + c.withNewAiClientWithFid(aiPid) } .withHandledEngineAndResults(engine.updated) } @@ -248,7 +227,7 @@ final case class GameController( // FIXME: this isn't actually atomic, but at least we'll fail violently private def copyWithAtomicSave: GameController = try { - val newCts = clientTextStore.saved + val newCts = clientTextStore.saved val newEngine = engine.saveNow copy( @@ -282,8 +261,9 @@ final case class GameController( this.withAiClient(AIClient(gameId = gameId, factionId = fid)) def withNewAiClientsWithFids(fids: Vector[FactionId]): GameController = - fids.foldLeft(this) { case (gc, fid) => - gc.withAiClient(AIClient(gameId = gameId, factionId = fid)) + fids.foldLeft(this) { + case (gc, fid) => + gc.withAiClient(AIClient(gameId = gameId, factionId = fid)) } def postBattleResolution( @@ -306,7 +286,7 @@ final case class GameController( streamId: String, llmResponse: LLMResponse, completed: Boolean - ): GameController = { + ): GameController = this.clientTextStore .withAppendedText( id = llmResponse.llmRequest.get.id, @@ -326,24 +306,24 @@ final case class GameController( ) .copyWithLlmSave } - } def postStreamingLlmUpdates( streamId: String, llmResponses: Vector[LLMResponse], completed: Boolean ): GameControllerWithPostResults = { - val requestId = llmResponses.head.llmRequest.get.id + val requestId = llmResponses.head.llmRequest.get.id internalRequire( llmResponses.forall(_.llmRequest.get.id == requestId), "All LLM responses must have the same ID" ) val controllerWithHandledStreams = llmResponses match { case h :+ t => - h.foldLeft(this) { case (innerC, llmResponse) => - innerC.postOneLlmResponse(streamId, llmResponse, completed = false) + h.foldLeft(this) { + case (innerC, llmResponse) => + innerC.postOneLlmResponse(streamId, llmResponse, completed = false) }.postOneLlmResponse(streamId, t, completed) - case _ => throw new EagleInternalException("llmResponses is empty") + case _ => throw new EagleInternalException("llmResponses is empty") } GameControllerWithPostResults( @@ -405,19 +385,16 @@ final case class GameController( ): Vector[ LlmRequestAfterHistoryCount ] = - results.zipWithIndex - .map { case (result, index) => (result, index + startingCount + 1) } - .flatMap { case (result, historyCount) => - result.newGeneratedTextRequests - .filter { req => - req.alwaysGenerate || - req.recipientFactionIds.isEmpty || - req.recipientFactionIds.exists(!aiClientFactionIds.contains(_)) - } - .map { req => - LlmRequestAfterHistoryCount(req, historyCount) - } - } + results.zipWithIndex.map { case (result, index) => (result, index + startingCount + 1) }.flatMap { + case (result, historyCount) => + result.newGeneratedTextRequests.filter { req => + req.alwaysGenerate || + req.recipientFactionIds.isEmpty || + req.recipientFactionIds.exists(!aiClientFactionIds.contains(_)) + }.map { req => + LlmRequestAfterHistoryCount(req, historyCount) + } + } private def foldInLlmRequests( clientTextStore: ClientTextStore, @@ -430,9 +407,7 @@ final case class GameController( accessibleTo = if llmRequestAfterHistoryCount.llmRequest.recipientFactionIds.isEmpty then engine.factionIds - else - llmRequestAfterHistoryCount.llmRequest.recipientFactionIds.toVector - , + else llmRequestAfterHistoryCount.llmRequest.recipientFactionIds.toVector, llmRequest = llmRequestAfterHistoryCount.llmRequest, requestedAfterHistoryCount = llmRequestAfterHistoryCount.historyCount ) @@ -442,11 +417,12 @@ final case class GameController( clientTextStore: ClientTextStore, visibilityExtensions: Vector[ClientTextVisibilityExtension] ): ClientTextStore = - visibilityExtensions.foldLeft(clientTextStore) { case (cts, ext) => - cts.withExtendedVisibility( - id = ext.textId, - addedFactionIds = ext.recipientFactionIds.toVector - ) + visibilityExtensions.foldLeft(clientTextStore) { + case (cts, ext) => + cts.withExtendedVisibility( + id = ext.textId, + addedFactionIds = ext.recipientFactionIds.toVector + ) } private def withHandledEngineAndResults( @@ -463,8 +439,9 @@ final case class GameController( GameControllerWithPostResults( gameController = GameController( engine = engineAndResults.engine, - userNameToFactionId = userNameToFactionId.filter { case (_, fid) => - engineAndResults.engine.factionIds.contains(fid) + userNameToFactionId = userNameToFactionId.filter { + case (_, fid) => + engineAndResults.engine.factionIds.contains(fid) }, humanClients = GameController.humanClientsAfterPostingResults( humanClients = humanClients, @@ -530,8 +507,9 @@ final case class GameController( new PrintWriter(new FileOutputStream(new File(path), true)) } ) - ) { case (client, clientText) => - client.update(clientText = clientText) + ) { + case (client, clientText) => + client.update(clientText = clientText) } ) } @@ -541,9 +519,7 @@ final case class GameController( GameController( engine = this.engine, userNameToFactionId = this.userNameToFactionId, - humanClients = this.humanClients.filterNot(hc => - userNameToFactionId.get(userName).contains(hc.factionId) - ), + humanClients = this.humanClients.filterNot(hc => userNameToFactionId.get(userName).contains(hc.factionId)), aiClients = this.aiClients, clientTextStore = this.clientTextStore ) @@ -582,8 +558,7 @@ final case class GameController( ) } - private def aiClientCommands - : (GameController, Vector[(FactionId, CommandSelection)]) = + private def aiClientCommands: (GameController, Vector[(FactionId, CommandSelection)]) = aiClients .map(client => client.newValue.chooseCommand(engine, client.nextRandom)) .map(clientWithCommandRS => diff --git a/src/main/scala/net/eagle0/eagle/service/controller/HumanPlayerClientConnectionState.scala b/src/main/scala/net/eagle0/eagle/service/controller/HumanPlayerClientConnectionState.scala index 7c00b2e2c4..6353b5b932 100644 --- a/src/main/scala/net/eagle0/eagle/service/controller/HumanPlayerClientConnectionState.scala +++ b/src/main/scala/net/eagle0/eagle/service/controller/HumanPlayerClientConnectionState.scala @@ -7,18 +7,10 @@ import scala.annotation.tailrec import net.eagle0.eagle.{FactionId, GameId, ShardokGameId} import net.eagle0.eagle.api.command.AvailableCommands -import net.eagle0.eagle.api.eagle.{ - ActionResultResponse, - GameUpdate, - ShardokActionResultResponse, - UpdateStreamResponse -} +import net.eagle0.eagle.api.eagle.{ActionResultResponse, GameUpdate, ShardokActionResultResponse, UpdateStreamResponse} import net.eagle0.eagle.api.eagle.GameUpdate.GameUpdateDetails import net.eagle0.eagle.api.eagle.ShardokActionResultResponse.SingleShardokGameResultResponse -import net.eagle0.eagle.api.eagle.UpdateStreamRequest.StreamGameRequest.{ - ShardokViewStatus, - StreamingTextStatus -} +import net.eagle0.eagle.api.eagle.UpdateStreamRequest.StreamGameRequest.{ShardokViewStatus, StreamingTextStatus} import net.eagle0.eagle.api.streaming_text_response.StreamingTextResponse import net.eagle0.eagle.client_text.ClientText import net.eagle0.eagle.library.{ActionResultFilter, GameHistory} @@ -73,7 +65,7 @@ object HumanPlayerClientConnectionState { client: HumanPlayerClientConnectionState, llmId: String, text: String - ): String = { + ): String = client.streamingTextStatuses .find(_.llmIdentifier == llmId) .map { @@ -98,7 +90,6 @@ object HumanPlayerClientConnectionState { case _ => "" } .getOrElse(text) - } } case class HumanPlayerClientConnectionState( @@ -111,7 +102,7 @@ case class HumanPlayerClientConnectionState( logWriter: PrintWriter ) { private val maxResultsPerMessage = 1024 - private val maxInitialResults = 100 + private val maxInitialResults = 100 def update( clientText: ClientText @@ -123,7 +114,7 @@ case class HumanPlayerClientConnectionState( ) match { case "" if !clientText.complete => this - case diff => + case diff => this.update( StreamingTextResponse( llmIdentifier = clientText.id, @@ -159,8 +150,7 @@ case class HumanPlayerClientConnectionState( GameUpdate( gameId = eagleGameId, startingState = None, - gameUpdateDetails = - GameUpdateDetails.StreamingTextResponse(streamingLlmResult) + gameUpdateDetails = GameUpdateDetails.StreamingTextResponse(streamingLlmResult) ) ) ) @@ -245,7 +235,7 @@ case class HumanPlayerClientConnectionState( // The client might be reconnecting during a battle that has since ended val shardokGameIdsToCheck = activeShardokGameIds ++ knownShardokResultCounts.map(_.shardokGameId) - val sfr = shardokGameIdsToCheck.map { sgid => + val sfr = shardokGameIdsToCheck.map { sgid => val previousCount = knownShardokResultCounts .find(_.shardokGameId == sgid) .map(_.filteredResultCount) @@ -398,7 +388,7 @@ case class HumanPlayerClientConnectionState( end if } - try { + try // eagle results go( client = this, @@ -407,7 +397,7 @@ case class HumanPlayerClientConnectionState( unfilteredCountAfter = unfilteredCountAfter, availableCommands = availableCommands ) - } catch { + catch { case e: Exception => println(e) this @@ -444,7 +434,8 @@ case class HumanPlayerClientConnectionState( private def enqueueShardokResults( filteredShardokResults: Vector[SingleShardokGameResultResponse] ): HumanPlayerClientConnectionState = - filteredShardokResults.foldLeft(this) { case (nextClient, resp) => - nextClient.enqueueShardokResult(resp) + filteredShardokResults.foldLeft(this) { + case (nextClient, resp) => + nextClient.enqueueShardokResult(resp) } } diff --git a/src/main/scala/net/eagle0/eagle/service/new_game_creation/GameParametersUtils.scala b/src/main/scala/net/eagle0/eagle/service/new_game_creation/GameParametersUtils.scala index 4ff789296c..10ba51b710 100644 --- a/src/main/scala/net/eagle0/eagle/service/new_game_creation/GameParametersUtils.scala +++ b/src/main/scala/net/eagle0/eagle/service/new_game_creation/GameParametersUtils.scala @@ -4,10 +4,7 @@ import scala.io.Source import scala.util.{Try, Using} import net.eagle0.eagle.{BattalionId, FactionId, HeroId} -import net.eagle0.eagle.internal.game_parameters.{ - GameParameters, - ProvinceOverrides -} +import net.eagle0.eagle.internal.game_parameters.{GameParameters, ProvinceOverrides} import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.util.{MapGenerator, PriceIndexUtils} @@ -33,17 +30,17 @@ object GameParametersUtils { private val defaultResourceLocation: String = "/net/eagle0/eagle/game_parameters.json" - private val fixedHeroFilePath: String = "/net/eagle0/eagle/heroes.tsv" + private val fixedHeroFilePath: String = "/net/eagle0/eagle/heroes.tsv" private val generatedHeroFilePath: String = "/net/eagle0/eagle/generated_heroes.tsv" // These will just crash on launch if we can't read the files - private val fixedHeroes = FixedHeroes.parse(fixedHeroFilePath).get - private val pregeneratedHeroes = + private val fixedHeroes = FixedHeroes.parse(fixedHeroFilePath).get + private val pregeneratedHeroes = FixedHeroes.parse(generatedHeroFilePath).get val greatPeople: Vector[GreatPersonWithBackstory] = fixedHeroes.greatPeople - val fixedOthers: Vector[LoadedHero] = fixedHeroes.others - val pregeneratedOthers: Vector[LoadedHero] = pregeneratedHeroes.others + val fixedOthers: Vector[LoadedHero] = fixedHeroes.others + val pregeneratedOthers: Vector[LoadedHero] = pregeneratedHeroes.others val allPregeneratedHeroes: Vector[HeroWithName] = (greatPeople.map( _.greatPerson.hero @@ -55,7 +52,7 @@ object GameParametersUtils { ) ++ fixedOthers ++ pregeneratedOthers) .map(LoadedHeroConversion.toHeroProto) - val fixedHeroesNameMap: Map[String, String] = + val fixedHeroesNameMap: Map[String, String] = heroNamesMap(fixedHeroes) val pregeneratedHeroesNameMap: Map[String, String] = heroNamesMap(pregeneratedHeroes) @@ -65,7 +62,7 @@ object GameParametersUtils { throw new EagleInternalException("Hero names hash collision") } - val fixedHeroBackstories: Map[String, String] = + val fixedHeroBackstories: Map[String, String] = FixedHeroes.parseBackstories(fixedHeroFilePath).get val pregeneratedHeroBackstories: Map[String, String] = FixedHeroes .parseBackstories(generatedHeroFilePath) @@ -75,7 +72,7 @@ object GameParametersUtils { expandedGameParametersFrom(defaultResourceLocation).get private def heroNamesMap(fixedHeroes: FixedHeroes): Map[String, String] = { - val heroes = fixedHeroes.greatPeople.map( + val heroes = fixedHeroes.greatPeople.map( _.greatPerson.hero ) ++ fixedHeroes.others val namesMap = heroes.map { hero => @@ -108,7 +105,7 @@ object GameParametersUtils { resourceName: String ): Try[ExpandedGameParameters] = readGameParameters(resourceName).map { parameters => - val allSetFactionHeadNames = parameters.setFactions.map(_.factionHeadName) + val allSetFactionHeadNames = parameters.setFactions.map(_.factionHeadName) val allSetFactionBrotherNames = parameters.setFactions.flatMap(_.swornBrotherNames) @@ -126,9 +123,7 @@ object GameParametersUtils { ) val setFactionBrothers = - fixedOthers.filter(heroWithBackstory => - allSetFactionBrotherNames.contains(heroWithBackstory.name) - ) + fixedOthers.filter(heroWithBackstory => allSetFactionBrotherNames.contains(heroWithBackstory.name)) ExpandedGameParameters( gameParameters = parameters, @@ -147,10 +142,10 @@ object GameParametersUtils { battalionIds: Vector[BattalionId] ): Province = province.update( - _.economy := provinceOverrides.economy, - _.agriculture := provinceOverrides.agriculture, - _.infrastructure := provinceOverrides.infrastructure, - _.priceIndex := PriceIndexUtils.steadyState( + _.economy := provinceOverrides.economy, + _.agriculture := provinceOverrides.agriculture, + _.infrastructure := provinceOverrides.infrastructure, + _.priceIndex := PriceIndexUtils.steadyState( provinceOverrides.economy, provinceOverrides.agriculture, provinceOverrides.infrastructure, @@ -159,16 +154,16 @@ object GameParametersUtils { 0 ), _.specialBattalionTypes := provinceOverrides.specialBattalionTypes, - _.support := provinceOverrides.support, - _.rulingFactionId := factionId, - _.rulingFactionHeroIds := provinceOverrides.rulingPlayerHeroNames + _.support := provinceOverrides.support, + _.rulingFactionId := factionId, + _.rulingFactionHeroIds := provinceOverrides.rulingPlayerHeroNames .map(nameToHeroId) ++ extraHeroIds, - _.rulingHeroId := (provinceOverrides.rulingPlayerHeroNames + _.rulingHeroId := (provinceOverrides.rulingPlayerHeroNames .map(nameToHeroId) ++ extraHeroIds).head, - _.provinceOrders := provinceOverrides.orders, - _.battalionIds := battalionIds, - _.gold := provinceOverrides.gold, - _.food := provinceOverrides.food + _.provinceOrders := provinceOverrides.orders, + _.battalionIds := battalionIds, + _.gold := provinceOverrides.gold, + _.food := provinceOverrides.food ) def provincesWithoutPlayers( @@ -180,10 +175,10 @@ object GameParametersUtils { ) .map(p => p.update( - _.economy := gameParameters.getGenericProvinceOverrides.economy, - _.agriculture := gameParameters.getGenericProvinceOverrides.agriculture, - _.infrastructure := gameParameters.getGenericProvinceOverrides.infrastructure, - _.priceIndex := PriceIndexUtils.steadyState( + _.economy := gameParameters.getGenericProvinceOverrides.economy, + _.agriculture := gameParameters.getGenericProvinceOverrides.agriculture, + _.infrastructure := gameParameters.getGenericProvinceOverrides.infrastructure, + _.priceIndex := PriceIndexUtils.steadyState( gameParameters.getGenericProvinceOverrides.economy, gameParameters.getGenericProvinceOverrides.agriculture, gameParameters.getGenericProvinceOverrides.infrastructure, diff --git a/src/main/scala/net/eagle0/eagle/service/new_game_creation/LoadedHeroConversion.scala b/src/main/scala/net/eagle0/eagle/service/new_game_creation/LoadedHeroConversion.scala index 5274d6197f..5f89ecac13 100644 --- a/src/main/scala/net/eagle0/eagle/service/new_game_creation/LoadedHeroConversion.scala +++ b/src/main/scala/net/eagle0/eagle/service/new_game_creation/LoadedHeroConversion.scala @@ -5,10 +5,7 @@ import net.eagle0.eagle.common.hero_backstory_version.BackstoryVersion as Backst import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.library.util.hero_generator.hero_with_name.HeroWithName import net.eagle0.eagle.model.proto_converters.date.DateConverter -import net.eagle0.eagle.model.proto_converters.hero.{ - GenderConverter, - ProfessionConverter -} +import net.eagle0.eagle.model.proto_converters.hero.{GenderConverter, ProfessionConverter} import net.eagle0.eagle.model.state.hero.{Gender, Profession} import net.eagle0.eagle.model.state.hero.backstory_version.BackstoryVersion import net.eagle0.eagle.model.state.hero.concrete.HeroC diff --git a/src/main/scala/net/eagle0/eagle/service/new_game_creation/NewGameCreation.scala b/src/main/scala/net/eagle0/eagle/service/new_game_creation/NewGameCreation.scala index 0ff1e1bf5d..ca4f719614 100644 --- a/src/main/scala/net/eagle0/eagle/service/new_game_creation/NewGameCreation.scala +++ b/src/main/scala/net/eagle0/eagle/service/new_game_creation/NewGameCreation.scala @@ -22,11 +22,7 @@ import net.eagle0.eagle.internal.chronicle_entry.ChronicleEntry import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.HOSTILE -import net.eagle0.eagle.internal.game_parameters.{ - GameParameters, - ProvinceOverrides, - SetFaction -} +import net.eagle0.eagle.internal.game_parameters.{GameParameters, ProvinceOverrides, SetFaction} import net.eagle0.eagle.internal.game_parameters.SetFaction.StartingTrust import net.eagle0.eagle.internal.generated_text_request.{ FixedHeroNameMessage, @@ -36,12 +32,7 @@ import net.eagle0.eagle.internal.generated_text_request.{ } import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.{ - EagleInternalException, - EngineAndResults, - EngineAndResultsImpl, - EngineImpl -} +import net.eagle0.eagle.library.{EagleInternalException, EngineAndResults, EngineAndResultsImpl, EngineImpl} import net.eagle0.eagle.library.actions.name_generation_request.NameGenerationRequestCreator import net.eagle0.eagle.library.util.hero_generator.hero_generation_response.HeroGenerationResponse import net.eagle0.eagle.library.util.hero_generator.image_paths.ImagePaths @@ -53,10 +44,7 @@ import net.eagle0.eagle.model.action_result.generated_text_request.{ GeneratedTextRequestT } import net.eagle0.eagle.model.proto_converters.date.DateConverter -import net.eagle0.eagle.model.proto_converters.hero.{ - GenderConverter, - HeroConverter -} +import net.eagle0.eagle.model.proto_converters.hero.{GenderConverter, HeroConverter} import net.eagle0.eagle.service.persistence.Persister import net.eagle0.eagle.service.PersistedHistory import net.eagle0.util.hero_generation.LoadedHero @@ -71,7 +59,7 @@ object NewGameCreation { ) val initialChronicleGeneratedTextId: String = "initial_chronicle_entry" - val initialChronicleText: String = + val initialChronicleText: String = s"""A Civil War |===== |""".stripMargin ++ @@ -102,7 +90,7 @@ object FixedNewGameCreation extends NewGameCreation { GameParametersUtils.fixedOthers ++ GameParametersUtils.pregeneratedOthers - private def initialBackstories: Map[String, String] = { + private def initialBackstories: Map[String, String] = ( GameParametersUtils.greatPeople.map { gpwb => gpwb.backstoryTextId -> gpwb.backstory @@ -114,7 +102,6 @@ object FixedNewGameCreation extends NewGameCreation { hwb.backstoryTextId -> hwb.backstory } ).toMap - } private def randomProvinceIdSet( provinces: Vector[Province], @@ -128,32 +115,30 @@ object FixedNewGameCreation extends NewGameCreation { ): RandomState[Vector[ProvinceId]] = if remainingCount == 0 then acc else { - acc.continue { case (accPids, fr) => - val availableProvinces = remainingAvailable - .filter(_.rulingFactionId.isEmpty) - .filterNot { p => - p.neighbors - .map(_.provinceId) - .map(pid => provinces.find(_.id == pid).get) - .exists(p => - p.rulingFactionId.isDefined || acc.newValue.contains(p.id) - ) - } - .toList + acc.continue { + case (accPids, fr) => + val availableProvinces = remainingAvailable + .filter(_.rulingFactionId.isEmpty) + .filterNot { p => + p.neighbors + .map(_.provinceId) + .map(pid => provinces.find(_.id == pid).get) + .exists(p => p.rulingFactionId.isDefined || acc.newValue.contains(p.id)) + } + .toList - if availableProvinces.isEmpty then - go(RandomState(Vector(), acc.nextRandom), provinces, factionCount) - else { - val selectedProvince = - fr.nextRandomElement(availableProvinces) - go( - selectedProvince.map { p => accPids :+ p.id }, - remainingAvailable.filterNot( - _.id == selectedProvince.newValue.id - ), - remainingCount - 1 - ) - } + if availableProvinces.isEmpty then go(RandomState(Vector(), acc.nextRandom), provinces, factionCount) + else { + val selectedProvince = + fr.nextRandomElement(availableProvinces) + go( + selectedProvince.map(p => accPids :+ p.id), + remainingAvailable.filterNot( + _.id == selectedProvince.newValue.id + ), + remainingCount - 1 + ) + } } } @@ -188,45 +173,46 @@ object FixedNewGameCreation extends NewGameCreation { count: Int, playerCount: Int ): RandomState[(ActionResult, Vector[HeroId])] = - value.continue { case (ar, fr) => - val hids: Vector[HeroId] = - (value.newValue.nextHeroId until value.newValue.nextHeroId + count).toVector + value.continue { + case (ar, fr) => + val hids: Vector[HeroId] = + (value.newValue.nextHeroId until value.newValue.nextHeroId + count).toVector - RandomHeroGenerator - .createHeroesWithNoProfession( - hids = hids, - functionalRandom = fr, - remainingImagePathsByProfession = - (p, g) => ImagePaths.imagePathsByProfession((p, g)), - date = StartDate.startDate - ) - .map { - _.map { case HeroGenerationResponse(hero, nameInfo) => + RandomHeroGenerator + .createHeroesWithNoProfession( + hids = hids, + functionalRandom = fr, + remainingImagePathsByProfession = (p, g) => ImagePaths.imagePathsByProfession((p, g)), + date = StartDate.startDate + ) + .map { + _.map { + case HeroGenerationResponse(hero, nameInfo) => + ( + hero.copy( + factionId = Some(fid), + loyalty = 75, + roundIdJoined = Some(0) + ), + NameGenerationRequestCreator.nameGenerationRequest( + heroId = hero.id, + gameId = gameId, + nameInfo = nameInfo + ) + ) + } + } + .map { newHeroes => ( - hero.copy( - factionId = Some(fid), - loyalty = 75, - roundIdJoined = Some(0) - ), - NameGenerationRequestCreator.nameGenerationRequest( - heroId = hero.id, - gameId = gameId, - nameInfo = nameInfo - ) + ar.withHeroes(newHeroes.map(_._1).map(HeroConverter.toProto)) + .withGeneratedTextRequests( + newHeroes + .flatMap(_._2) + .map(convertNameRequest(_, playerCount)) + ), + newHeroes.map(_._1.id) ) } - } - .map { newHeroes => - ( - ar.withHeroes(newHeroes.map(_._1).map(HeroConverter.toProto)) - .withGeneratedTextRequests( - newHeroes - .flatMap(_._2) - .map(convertNameRequest(_, playerCount)) - ), - newHeroes.map(_._1.id) - ) - } } def withSetFactionProvinces( @@ -261,22 +247,23 @@ object FixedNewGameCreation extends NewGameCreation { playerCount = playerCount, gameId = gameId ) - .map { case (ar, randomHids) => - ar.withBattalions(provinceOverrides.battalions.map { b => - b.withName(battalionName.getOrElse(b.name)) - }) match { - case (ar, bids) => - ar.withProvince( - GameParametersUtils.provinceWithOverride( - province = province, - provinceOverrides = provinceOverrides, - factionId = factionId, - nameToHeroId = value.newValue.nameToHeroId, - extraHeroIds = extraHeroIds ++ randomHids, - battalionIds = bids.toVector + .map { + case (ar, randomHids) => + ar.withBattalions(provinceOverrides.battalions.map { b => + b.withName(battalionName.getOrElse(b.name)) + }) match { + case (ar, bids) => + ar.withProvince( + GameParametersUtils.provinceWithOverride( + province = province, + provinceOverrides = provinceOverrides, + factionId = factionId, + nameToHeroId = value.newValue.nameToHeroId, + extraHeroIds = extraHeroIds ++ randomHids, + battalionIds = bids.toVector + ) ) - ) - } + } } def withSetFactionProvince( @@ -325,15 +312,16 @@ object FixedNewGameCreation extends NewGameCreation { .name ) .zip(provinceIds) - .foldLeft(value) { case (innerArRS, (name, pid)) => - innerArRS - .withHumanPlayerFaction( - expandedGameParameters = expandedGameParameters, - headName = name, - provinceId = pid, - playerCount = playerCount, - gameId = gameId - ) + .foldLeft(value) { + case (innerArRS, (name, pid)) => + innerArRS + .withHumanPlayerFaction( + expandedGameParameters = expandedGameParameters, + headName = name, + provinceId = pid, + playerCount = playerCount, + gameId = gameId + ) } def withFactionHead( @@ -350,28 +338,27 @@ object FixedNewGameCreation extends NewGameCreation { .get val gpWithFid = gp.copy( - greatPerson = - gp.greatPerson.copy(hero = gp.greatPerson.hero.withFactionId(fid)) + greatPerson = gp.greatPerson.copy(hero = gp.greatPerson.hero.withFactionId(fid)) ) value .map(_.withLoadedHero(gpWithFid.greatPerson.hero.withFactionId(fid))) - .map { case (ar, hid) => - ( - ar.withFaction( - NewGameCreation.singleHeroFaction( - gpWithFid.greatPerson - .copy(hero = gpWithFid.greatPerson.hero.withId(hid)) - ) - ), - hid - ) + .map { + case (ar, hid) => + ( + ar.withFaction( + NewGameCreation.singleHeroFaction( + gpWithFid.greatPerson + .copy(hero = gpWithFid.greatPerson.hero.withId(hid)) + ) + ), + hid + ) } match { case RandomState((ar, hid), nr) => RandomState(ar, nr).withProvinceOverrides( province = value.newValue.provinceMap(provinceId), - provinceOverrides = - expandedGameParameters.gameParameters.getOccupiedProvinceOverrides, + provinceOverrides = expandedGameParameters.gameParameters.getOccupiedProvinceOverrides, extraHeroIds = Vector(hid), factionId = fid, battalionName = Some(s"$headName's Loyalists"), @@ -392,9 +379,7 @@ object FixedNewGameCreation extends NewGameCreation { .filterNot(h => value.newValue.newFactions .flatMap(_.leaders) - .map(leaderId => - value.newValue.newHeroes.find(_.id == leaderId).get.nameTextId - ) + .map(leaderId => value.newValue.newHeroes.find(_.id == leaderId).get.nameTextId) .contains(h.nameTextId) ) ) @@ -406,16 +391,18 @@ object FixedNewGameCreation extends NewGameCreation { playerCount: Int, gameId: GameId ): RandomState[ActionResult] = - value.continue { case (ar, fr) => - headName(expandedGameParameters, fr).continue { case (name, fr) => - RandomState(ar, fr).withFactionHead( - expandedGameParameters = expandedGameParameters, - headName = name, - provinceId = provinceId, - playerCount = playerCount, - gameId = gameId - ) - } + value.continue { + case (ar, fr) => + headName(expandedGameParameters, fr).continue { + case (name, fr) => + RandomState(ar, fr).withFactionHead( + expandedGameParameters = expandedGameParameters, + headName = name, + provinceId = provinceId, + playerCount = playerCount, + gameId = gameId + ) + } } @tailrec @@ -447,7 +434,7 @@ object FixedNewGameCreation extends NewGameCreation { playerCount: Int, gameId: GameId ): RandomState[ActionResult] = { - val fid = value.newValue.nextFactionId + val fid = value.newValue.nextFactionId val factionHeadGp = expandedGameParameters.setFactionHeads .find(_.greatPerson.hero.name == sf.factionHeadName) .getOrElse( @@ -544,14 +531,15 @@ object FixedNewGameCreation extends NewGameCreation { accRS: RandomState[Vector[HeroGenerationResponse]], heroId: HeroId ): RandomState[Vector[HeroGenerationResponse]] = - accRS.continue { case (acc, fr) => - generator - .getHero( - random = fr, - hid = heroId, - date = StartDate.startDate - ) - .map { acc :+ _ } + accRS.continue { + case (acc, fr) => + generator + .getHero( + random = fr, + hid = heroId, + date = StartDate.startDate + ) + .map(acc :+ _) } private def randomHeroes( @@ -580,7 +568,7 @@ object FixedNewGameCreation extends NewGameCreation { ), recipientFactionIds = (1 to playerCount).toVector ) - case GeneratedHeroName(requestId, eagleGameId, gender) => + case GeneratedHeroName(requestId, eagleGameId, gender) => GeneratedTextRequest( id = requestId, eagleGameId = eagleGameId, @@ -588,7 +576,7 @@ object FixedNewGameCreation extends NewGameCreation { gender = GenderConverter.toProto(gender) ) ) - case _ => + case _ => throw new EagleInternalException( "Only FixedHeroName is supported in NewGameCreation" ) @@ -616,12 +604,13 @@ object FixedNewGameCreation extends NewGameCreation { gameId = gameId ) - val splitPids = setFactionsResult.continue { case (sfr, nextRandom) => - randomProvinceIdSet( - sfr.newProvinces.toVector, - playerCount, - nextRandom - ).map(_.splitAt(humanPlayerFactionLeaderNameTextIds.size)) + val splitPids = setFactionsResult.continue { + case (sfr, nextRandom) => + randomProvinceIdSet( + sfr.newProvinces.toVector, + playerCount, + nextRandom + ).map(_.splitAt(humanPlayerFactionLeaderNameTextIds.size)) } val allFactionsResult = splitPids.continue { @@ -636,8 +625,7 @@ object FixedNewGameCreation extends NewGameCreation { ) .withOtherAiFactions( expandedGameParameters = expandedGameParameters, - factionCount = - playerCount - humanPlayerFactionLeaderNameTextIds.size, + factionCount = playerCount - humanPlayerFactionLeaderNameTextIds.size, provinceIds = aiProvinceIds, playerCount = playerCount, gameId = gameId @@ -662,13 +650,12 @@ object FixedNewGameCreation extends NewGameCreation { val fixedHeroesARwithGenerator = withFixedHeroesAR.continue { case (ar, fr) => HeroGenerator( - pregeneratedHeroes = - pregeneratedHeroes.map(LoadedHeroConversion.toHeroWithName), + pregeneratedHeroes = pregeneratedHeroes.map(LoadedHeroConversion.toHeroWithName), excludingNames = Vector(), functionalRandom = fr ).map((ar, _)) } - val withRandomHeroesAR = fixedHeroesARwithGenerator.continue { + val withRandomHeroesAR = fixedHeroesARwithGenerator.continue { case ((ar, generator), fr) => randomHeroes( generator = generator, @@ -676,25 +663,26 @@ object FixedNewGameCreation extends NewGameCreation { nextHeroId = ar.nextHeroId, count = randomHeroCount ).map { newHeroes => - newHeroes.map { case HeroGenerationResponse(hero, nameInfo) => - ( - hero, - NameGenerationRequestCreator.nameGenerationRequest( - heroId = hero.id, - gameId = gameId, - nameInfo = nameInfo + newHeroes.map { + case HeroGenerationResponse(hero, nameInfo) => + ( + hero, + NameGenerationRequestCreator.nameGenerationRequest( + heroId = hero.id, + gameId = gameId, + nameInfo = nameInfo + ) ) - ) } }.map(newHeroes => ar.withHeroes(newHeroes.map(_._1).map(HeroConverter.toProto)) .withGeneratedTextRequests( - newHeroes.flatMap(_._2).map { convertNameRequest(_, playerCount) } + newHeroes.flatMap(_._2).map(convertNameRequest(_, playerCount)) ) ) } - def randomUH(randInt: Int, heroId: HeroId): UnaffiliatedHero = { + def randomUH(randInt: Int, heroId: HeroId): UnaffiliatedHero = if randInt % 3 == 0 then UnaffiliatedHero( heroId = heroId, @@ -707,31 +695,30 @@ object FixedNewGameCreation extends NewGameCreation { UnaffiliatedHero( heroId = heroId, `type` = UNAFFILIATED_HERO_TRAVELER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ) - } val provincesWithExtraHeroesState = withRandomHeroesAR.newValue.newHeroes .filter(_.factionId.isEmpty) - .foldLeft(withRandomHeroesAR) { case (RandomState(innerAR, r), h) => - val pState = - r.nextInt(atLeast = 1, lessThan = innerAR.newProvinces.size + 1) - val pState2 = pState.nextRandom.nextInt - val pid = pState.newValue - val p = innerAR.provinceMap(pid) - RandomState( - innerAR.withProvince( - p.update( - _.unaffiliatedHeroes := p.unaffiliatedHeroes :+ randomUH( - pState2.newValue, - h.id + .foldLeft(withRandomHeroesAR) { + case (RandomState(innerAR, r), h) => + val pState = + r.nextInt(atLeast = 1, lessThan = innerAR.newProvinces.size + 1) + val pState2 = pState.nextRandom.nextInt + val pid = pState.newValue + val p = innerAR.provinceMap(pid) + RandomState( + innerAR.withProvince( + p.update( + _.unaffiliatedHeroes := p.unaffiliatedHeroes :+ randomUH( + pState2.newValue, + h.id + ) ) - ) - ), - pState2.nextRandom - ) + ), + pState2.nextRandom + ) } val withBattalionTypesResult = @@ -745,9 +732,7 @@ object FixedNewGameCreation extends NewGameCreation { withBattalionTypesResult .withGeneratedTextRequests( withBattalionTypesResult.newHeroes - .filterNot(nh => - handledKeys.contains(nh.backstoryVersions.last.textId) - ) + .filterNot(nh => handledKeys.contains(nh.backstoryVersions.last.textId)) .map { heroWithoutPersonality => GeneratedTextRequest( id = heroWithoutPersonality.backstoryVersions.last.textId, diff --git a/src/main/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtils.scala b/src/main/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtils.scala index 8ce49e06a9..a164038d86 100644 --- a/src/main/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtils.scala +++ b/src/main/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtils.scala @@ -7,11 +7,7 @@ import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.generated_text_request.GeneratedTextRequest import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.util.hero_generation.LoadedHero object StartGameActionResultUtils { @@ -37,9 +33,7 @@ object StartGameActionResultUtils { def withProvinces(ps: Iterable[Province]): ActionResult = value.update( - _.newProvinces := (provinceMap ++ ps.map(p => - p.id -> p - )).values.toVector + _.newProvinces := (provinceMap ++ ps.map(p => p.id -> p)).values.toVector ) def withHero(h: Hero): (ActionResult, HeroId) = { @@ -105,15 +99,15 @@ object StartGameActionResultUtils { def withBattalions( bs: Iterable[Battalion] ): (ActionResult, Seq[BattalionId]) = - bs.foldLeft((value, Seq[BattalionId]())) { case ((ar, bids), batt) => - ar.withBattalion(batt) match { - case (innerAR, bid) => (innerAR, bids :+ bid) - } + bs.foldLeft((value, Seq[BattalionId]())) { + case ((ar, bids), batt) => + ar.withBattalion(batt) match { + case (innerAR, bid) => (innerAR, bids :+ bid) + } } def withFaction(f: Faction): ActionResult = { - if f.factionHeadId < 1 || f.leaders.exists(_ < 1) then - throw new IllegalStateException("bad hid") + if f.factionHeadId < 1 || f.leaders.exists(_ < 1) then throw new IllegalStateException("bad hid") value.update( _.newFactions := (factionMap + (f.id -> f)).values.toVector ) diff --git a/src/main/scala/net/eagle0/eagle/service/persistence/CompoundPersister.scala b/src/main/scala/net/eagle0/eagle/service/persistence/CompoundPersister.scala index c2bee0b494..7cd2ae8c46 100644 --- a/src/main/scala/net/eagle0/eagle/service/persistence/CompoundPersister.scala +++ b/src/main/scala/net/eagle0/eagle/service/persistence/CompoundPersister.scala @@ -8,30 +8,28 @@ import scala.util.{Failure, Success, Try} // Manages persistence to multiple locations. The order of the persister seq is important for retrieval; it will // always go down the list and return the first item that succeeds. For saves, it always attempts all. case class CompoundPersister(persisters: Vector[Persister]) extends Persister { - override def save(key: String, bytes: Array[Byte]): Boolean = { + override def save(key: String, bytes: Array[Byte]): Boolean = persisters.forall { persister => persister.save(key, bytes) } - } override def retrieveAsStream(key: String): Try[InputStream] = { @tailrec - def go(remaining: Vector[Persister]): Try[InputStream] = { + def go(remaining: Vector[Persister]): Try[InputStream] = remaining match { case h +: t => h.retrieveAsStream(key) match { case Success(a) => Try(a) case Failure(_) => go(t) } - case _ => Failure(new FileNotFoundException()) + case _ => Failure(new FileNotFoundException()) } - } go(persisters) } - def retrieveAsBytes(key: String): Try[Array[Byte]] = + def retrieveAsBytes(key: String): Try[Array[Byte]] = retrieveAsStream(key).map(_.readAllBytes()) - def retrieveAs[T](key: String, f: InputStream => T): Try[T] = + def retrieveAs[T](key: String, f: InputStream => T): Try[T] = retrieveAsStream(key).map(f) override def existingKeys: Vector[String] = diff --git a/src/main/scala/net/eagle0/eagle/service/persistence/LocalFilePersister.scala b/src/main/scala/net/eagle0/eagle/service/persistence/LocalFilePersister.scala index 1892abe72b..520788ef1e 100644 --- a/src/main/scala/net/eagle0/eagle/service/persistence/LocalFilePersister.scala +++ b/src/main/scala/net/eagle0/eagle/service/persistence/LocalFilePersister.scala @@ -29,7 +29,7 @@ class LocalFilePersister(directoryPath: String) extends Persister { override def save(key: String, bytes: Array[Byte]): Boolean = save(key, new ByteArrayInputStream(bytes)) - def save(key: String, stream: InputStream): Boolean = { + def save(key: String, stream: InputStream): Boolean = Using( new BufferedOutputStream( new FileOutputStream(fullPath(key)) @@ -37,7 +37,6 @@ class LocalFilePersister(directoryPath: String) extends Persister { ) { os => stream.transferTo(os) }.map(_ => true).getOrElse(false) - } def delete(key: String): Boolean = { val f = new File(fullPath(key)) @@ -46,14 +45,12 @@ class LocalFilePersister(directoryPath: String) extends Persister { override def retrieveAsStream(key: String): Try[InputStream] = { val fileRef = new File(fullPath(key)) - if fileRef.exists && fileRef.isFile then - Try(new BufferedInputStream(new FileInputStream(fileRef))) + if fileRef.exists && fileRef.isFile then Try(new BufferedInputStream(new FileInputStream(fileRef))) else Failure(new FileNotFoundException(fileRef.getPath)) } - override def existingKeys: Vector[String] = { + override def existingKeys: Vector[String] = new File(directoryPath).listFiles .map(_.getAbsolutePath.substring(directoryPath.length + 1)) .toVector - } } diff --git a/src/main/scala/net/eagle0/eagle/service/persistence/PartialGameUtils.scala b/src/main/scala/net/eagle0/eagle/service/persistence/PartialGameUtils.scala index 08442b0b9a..36384533d5 100644 --- a/src/main/scala/net/eagle0/eagle/service/persistence/PartialGameUtils.scala +++ b/src/main/scala/net/eagle0/eagle/service/persistence/PartialGameUtils.scala @@ -13,9 +13,7 @@ object PartialGameUtils { persister .retrieveAsStream(s"$startingIndex$eagleExtension") .toOption - .flatMap(inputStream => - ProtoParser.parseZipped(inputStream)(using PartialGame) - ) + .flatMap(inputStream => ProtoParser.parseZipped(inputStream)(using PartialGame)) def partialGames( persister: Persister, diff --git a/src/main/scala/net/eagle0/eagle/service/persistence/S3Persister.scala b/src/main/scala/net/eagle0/eagle/service/persistence/S3Persister.scala index 485c622940..41a0bff1fc 100644 --- a/src/main/scala/net/eagle0/eagle/service/persistence/S3Persister.scala +++ b/src/main/scala/net/eagle0/eagle/service/persistence/S3Persister.scala @@ -4,8 +4,7 @@ import java.io.InputStream import scala.util.Try -case class S3Persister(bucketName: String, keyPrefix: String) - extends Persister { +case class S3Persister(bucketName: String, keyPrefix: String) extends Persister { private def fullKey(key: String): String = keyPrefix + key override def save(key: String, bytes: Array[Byte]): Boolean = diff --git a/src/main/scala/net/eagle0/eagle/service/persistence/S3Utils.scala b/src/main/scala/net/eagle0/eagle/service/persistence/S3Utils.scala index 0bb6b5d445..c0d034a0ee 100644 --- a/src/main/scala/net/eagle0/eagle/service/persistence/S3Utils.scala +++ b/src/main/scala/net/eagle0/eagle/service/persistence/S3Utils.scala @@ -13,11 +13,7 @@ import net.eagle0.eagle.GameId import software.amazon.awssdk.core.async.AsyncRequestBody import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.s3.{S3AsyncClient, S3Client} -import software.amazon.awssdk.services.s3.model.{ - GetObjectRequest, - ListObjectsV2Request, - PutObjectRequest -} +import software.amazon.awssdk.services.s3.model.{GetObjectRequest, ListObjectsV2Request, PutObjectRequest} import software.amazon.awssdk.transfer.s3.model.UploadRequest import software.amazon.awssdk.transfer.s3.S3TransferManager @@ -55,7 +51,7 @@ object S3Utils { def retrieveAsStream(key: String): Try[InputStream] = retrieveAsStream(mainBucketName, key) - def retrieveAsStream(bucketName: String, key: String): Try[InputStream] = { + def retrieveAsStream(bucketName: String, key: String): Try[InputStream] = if key == null || key.isEmpty then { Failure(new IllegalArgumentException("key cannot be empty")) } else { @@ -65,7 +61,6 @@ object S3Utils { GetObjectRequest.builder().bucket(bucketName).key(key).build() Try(s3.getObject(getObjectRequest)) } - } def list(bucketName: String, prefix: String): Vector[String] = { val s3: S3Client = syncClient() @@ -97,9 +92,9 @@ object S3Utils { ) } - def upload(key: String, inputStream: InputStream): Boolean = { + def upload(key: String, inputStream: InputStream): Boolean = try { - val body = AsyncRequestBody.fromInputStream( + val body = AsyncRequestBody.fromInputStream( inputStream, inputStream.available().toLong, executor @@ -125,7 +120,6 @@ object S3Utils { System.err.println(e.toString) false } - } def upload(key: String, bytes: Array[Byte]): Boolean = upload(key, new ByteArrayInputStream(bytes)) diff --git a/src/main/scala/net/eagle0/eagle/service/persistence/credentials/S3Credentials.scala b/src/main/scala/net/eagle0/eagle/service/persistence/credentials/S3Credentials.scala index bcaa57381a..3211c1a805 100644 --- a/src/main/scala/net/eagle0/eagle/service/persistence/credentials/S3Credentials.scala +++ b/src/main/scala/net/eagle0/eagle/service/persistence/credentials/S3Credentials.scala @@ -5,11 +5,7 @@ import java.io.File import scala.io.Source import scala.util.{Try, Using} -import software.amazon.awssdk.auth.credentials.{ - AwsBasicCredentials, - AwsCredentialsProvider, - StaticCredentialsProvider -} +import software.amazon.awssdk.auth.credentials.{AwsBasicCredentials, AwsCredentialsProvider, StaticCredentialsProvider} object S3Credentials { private def makeS3cfgMap(): Try[Map[String, String]] = { @@ -38,7 +34,7 @@ object S3Credentials { private val s3cfgMap = makeS3cfgMap().get - private val credentials = AwsBasicCredentials.create( + private val credentials = AwsBasicCredentials.create( s3cfgMap("access_key"), s3cfgMap("secret_key") ) diff --git a/src/main/scala/net/eagle0/eagle/service/persistence/package.scala b/src/main/scala/net/eagle0/eagle/service/persistence/package.scala index 62a30d584e..428d867cb5 100644 --- a/src/main/scala/net/eagle0/eagle/service/persistence/package.scala +++ b/src/main/scala/net/eagle0/eagle/service/persistence/package.scala @@ -2,6 +2,6 @@ package net.eagle0.eagle.service package object persistence { val eagleIndexExtension = ".e0i" - val eagleExtension = ".e0a" - val shardokExtension = ".e0s" + val eagleExtension = ".e0a" + val shardokExtension = ".e0s" } diff --git a/src/main/scala/net/eagle0/eagle/shardok_interface/CommonConverters.scala b/src/main/scala/net/eagle0/eagle/shardok_interface/CommonConverters.scala index cae243b6fc..d98f701de8 100644 --- a/src/main/scala/net/eagle0/eagle/shardok_interface/CommonConverters.scala +++ b/src/main/scala/net/eagle0/eagle/shardok_interface/CommonConverters.scala @@ -18,8 +18,7 @@ object CommonConverters { eagleHeroId = eagleUnit.hero.id, nameTextId = eagleUnit.hero.nameTextId, isVip = isVip, - profession = - CommonProfession.fromValue(eagleUnit.hero.profession.value), + profession = CommonProfession.fromValue(eagleUnit.hero.profession.value), strength = eagleUnit.hero.strength, strengthXp = eagleUnit.hero.strengthXp, agility = eagleUnit.hero.agility, @@ -40,8 +39,7 @@ object CommonConverters { battalion = Some( CommonBattalion( eagleBattalionId = eagleUnit.battalion.id, - `type` = - CommonBattalionTypeId.fromValue(eagleUnit.battalion.`type`.value), + `type` = CommonBattalionTypeId.fromValue(eagleUnit.battalion.`type`.value), size = eagleUnit.battalion.size, training = eagleUnit.battalion.training, armament = eagleUnit.battalion.armament diff --git a/src/main/scala/net/eagle0/eagle/shardok_interface/ShardokInterfaceGrpcClient.scala b/src/main/scala/net/eagle0/eagle/shardok_interface/ShardokInterfaceGrpcClient.scala index ef1c24014e..25f9cd2320 100644 --- a/src/main/scala/net/eagle0/eagle/shardok_interface/ShardokInterfaceGrpcClient.scala +++ b/src/main/scala/net/eagle0/eagle/shardok_interface/ShardokInterfaceGrpcClient.scala @@ -42,11 +42,11 @@ class ShardokInterfaceGrpcClient( mutable .Map[ShardokGameId, (ShardokBattle, NewGameRequest)]() - def connect(): Unit = { - pendingBattles.foreach { case (_, (battle, newGameRequest)) => - resolveNewGameRequest(battle, newGameRequest) + def connect(): Unit = + pendingBattles.foreach { + case (_, (battle, newGameRequest)) => + resolveNewGameRequest(battle, newGameRequest) } - } private def waitingForHumanPlayer(battle: ShardokBattle): Boolean = resolutionReceiver.hasHumanPlayerCommands( @@ -62,7 +62,7 @@ class ShardokInterfaceGrpcClient( maybeBattle match { case Some((battle, _)) => update.specific match { - case Specific.GameOverResponse(gameOverResponse) => + case Specific.GameOverResponse(gameOverResponse) => val _ = pendingBattles.synchronized { pendingBattles.remove(update.gameId) } @@ -73,9 +73,9 @@ class ShardokInterfaceGrpcClient( ResolvedShardokPlayer( eagleFid = ui.eagleFactionId, endGameCondition = ui.endGameCondition.get, - units = ui.units.map(ru => { + units = ui.units.map { ru => val commonUnit = ru.unit.get - val eagleUnit = fromCommon(commonUnit) + val eagleUnit = fromCommon(commonUnit) ResolvedEagleUnit( HeroConverter.fromProto(eagleUnit.hero), if commonUnit.battalion.get.eagleBattalionId == EagleUnit.defaultBattalionId @@ -87,7 +87,7 @@ class ShardokInterfaceGrpcClient( , convertUnitStatus(ru.status) ) - }) + } ) ) ) @@ -99,8 +99,7 @@ class ShardokInterfaceGrpcClient( results = gameUpdateResponse.updateResponses.toVector, updates = gameUpdateResponse.filteredUpdateResponses.toVector, newUnfilteredCount = gameUpdateResponse.totalActionResultCount, - currentGameStateBytes = - gameUpdateResponse.currentGameState.toByteArray + currentGameStateBytes = gameUpdateResponse.currentGameState.toByteArray ) ) // Only do the gameStatusRunner if there are no available commands. If there are available commands, just wait @@ -111,7 +110,7 @@ class ShardokInterfaceGrpcClient( shardokGameId = battle.shardokGameId, newGameRequest = None ) - case Specific.Empty => + case Specific.Empty => // FIXME: maybe a delay if !waitingForHumanPlayer(battle) then gameStatusRunner( @@ -120,7 +119,7 @@ class ShardokInterfaceGrpcClient( newGameRequest = None ) } - case None => + case None => println(s"No pending battle found for ${update.gameId}") } } @@ -131,8 +130,7 @@ class ShardokInterfaceGrpcClient( playerToUserMap: Map[FactionId, String] ): PlayerSetupInfo = PlayerSetupInfo( - `type` = - if playerToUserMap.contains(shardokPlayer.eagleFid) then HUMAN else AI, + `type` = if playerToUserMap.contains(shardokPlayer.eagleFid) then HUMAN else AI, eagleFactionId = shardokPlayer.eagleFid, userName = playerToUserMap.getOrElse(shardokPlayer.eagleFid, ""), units = toCommon( @@ -246,8 +244,7 @@ class ShardokInterfaceGrpcClient( PostCommandRequest( gameId = shardokGameId, playerId = shardokPlayerId, - token = - resolutionReceiver.knownResultCount(eagleGameId, shardokGameId), + token = resolutionReceiver.knownResultCount(eagleGameId, shardokGameId), index = index, roll = roll, eagleFactionId = eagleFactionId, @@ -269,7 +266,7 @@ class ShardokInterfaceGrpcClient( .onComplete { case Success(gameStatusResponse) => handleBattleResponse(gameStatusResponse) - case Failure(e) => + case Failure(e) => print("failed to post a command\n") throw e } @@ -296,8 +293,7 @@ class ShardokInterfaceGrpcClient( gameId = shardokGameId, playerId = shardokPlayerId, placementCommands = placementCommands.toVector, - token = - resolutionReceiver.knownResultCount(eagleGameId, shardokGameId), + token = resolutionReceiver.knownResultCount(eagleGameId, shardokGameId), eagleFactionId = eagleFactionId, gameSetupInfo = Some( GameSetupInfo( @@ -317,7 +313,7 @@ class ShardokInterfaceGrpcClient( .onComplete { case Success(gameStatusResponse) => handleBattleResponse(gameStatusResponse) - case Failure(e) => + case Failure(e) => print("failed to post a placement command") throw e } @@ -364,8 +360,7 @@ class ShardokInterfaceGrpcClient( id = commonUnit.hero.get.eagleHeroId, factionId = Some(commonUnit.eaglePlayerId), nameTextId = commonUnit.hero.get.nameTextId, - profession = - EagleProfession.fromValue(commonUnit.hero.get.profession.value), + profession = EagleProfession.fromValue(commonUnit.hero.get.profession.value), strength = commonUnit.hero.get.strength, strengthXp = commonUnit.hero.get.strengthXp, agility = commonUnit.hero.get.agility, @@ -385,8 +380,7 @@ class ShardokInterfaceGrpcClient( ), battalion = EagleBattalion( id = commonUnit.battalion.get.eagleBattalionId, - `type` = - EagleBattalionTypeId.fromValue(commonUnit.battalion.get.`type`.value), + `type` = EagleBattalionTypeId.fromValue(commonUnit.battalion.get.`type`.value), size = commonUnit.battalion.get.size, training = commonUnit.battalion.get.training, armament = commonUnit.battalion.get.armament @@ -397,18 +391,18 @@ class ShardokInterfaceGrpcClient( protoStatus: net.eagle0.common.common_unit.UnitStatus ): UnitStatus = protoStatus match { - case net.eagle0.common.common_unit.UnitStatus.NORMAL_UNIT => + case net.eagle0.common.common_unit.UnitStatus.NORMAL_UNIT => UnitStatus.Normal - case net.eagle0.common.common_unit.UnitStatus.CAPTURED_UNIT => + case net.eagle0.common.common_unit.UnitStatus.CAPTURED_UNIT => UnitStatus.Captured - case net.eagle0.common.common_unit.UnitStatus.FLED_UNIT => UnitStatus.Fled - case net.eagle0.common.common_unit.UnitStatus.RETREATED_UNIT => + case net.eagle0.common.common_unit.UnitStatus.FLED_UNIT => UnitStatus.Fled + case net.eagle0.common.common_unit.UnitStatus.RETREATED_UNIT => UnitStatus.Retreated case net.eagle0.common.common_unit.UnitStatus.NEVER_ENTERED_UNIT => UnitStatus.NeverEntered - case net.eagle0.common.common_unit.UnitStatus.OUTLAWED_UNIT => + case net.eagle0.common.common_unit.UnitStatus.OUTLAWED_UNIT => UnitStatus.Outlawed - case other => + case other => throw new IllegalArgumentException(s"Unrecognized UnitStatus: $other") } } diff --git a/src/main/scala/net/eagle0/util/HeadshotImageListGenerator.scala b/src/main/scala/net/eagle0/util/HeadshotImageListGenerator.scala index dc35cccf1d..4161e829ac 100644 --- a/src/main/scala/net/eagle0/util/HeadshotImageListGenerator.scala +++ b/src/main/scala/net/eagle0/util/HeadshotImageListGenerator.scala @@ -25,14 +25,14 @@ object HeadshotImageListGenerator { val keys = S3Utils.list(bucketName, s"$profString/").filter(_.endsWith(".png")) - (profString -> keys) + profString -> keys }.toMap def toTsv(pathsMap: Map[String, Vector[String]]): String = - pathsMap - .map { case (profString, paths) => + pathsMap.map { + case (profString, paths) => s"### $profString\n" ++ paths.mkString("\n") - } + } .mkString("\n") def main(args: Array[String]): Unit = { @@ -42,7 +42,7 @@ object HeadshotImageListGenerator { val outputFile = new File(outputPath) new File(Paths.get(outputPath).getParent.toAbsolutePath.toString).mkdirs() - val os = new FileOutputStream(outputFile) + val os = new FileOutputStream(outputFile) os.write(tsv.getBytes(StandardCharsets.UTF_8)) } } diff --git a/src/main/scala/net/eagle0/util/HeroLibraryGenerator.scala b/src/main/scala/net/eagle0/util/HeroLibraryGenerator.scala index fc1f768b94..ae3c164a73 100644 --- a/src/main/scala/net/eagle0/util/HeroLibraryGenerator.scala +++ b/src/main/scala/net/eagle0/util/HeroLibraryGenerator.scala @@ -14,17 +14,10 @@ import net.eagle0.common.llm_integration.{ StreamingTextResults } import net.eagle0.common.SeededRandom -import net.eagle0.eagle.library.actions.llm_prompt_generators.GeneratorUtilities.{ - academyName, - conjunction -} +import net.eagle0.eagle.library.actions.llm_prompt_generators.GeneratorUtilities.{academyName, conjunction} import net.eagle0.eagle.library.util.hero_generator.hero_generation_response.HeroGenerationResponse import net.eagle0.eagle.library.util.hero_generator.hero_with_name.HeroWithName -import net.eagle0.eagle.library.util.hero_generator.name_info.{ - FixedName, - NameRequest, - NoNameRequest -} +import net.eagle0.eagle.library.util.hero_generator.name_info.{FixedName, NameRequest, NoNameRequest} import net.eagle0.eagle.library.util.hero_generator.random_hero_generator.RandomHeroGenerator import net.eagle0.eagle.model.state.hero.{Gender, Profession} import net.eagle0.eagle.model.state.hero.concrete.HeroC @@ -32,10 +25,10 @@ import net.eagle0.eagle.service.new_game_creation.{FixedHeroes, StartDate} import net.eagle0.util.hero_generation.LoadedHero object HeroLibraryGenerator { - private val random = new Random() - private val heroFilePath: String = "/net/eagle0/eagle/heroes.tsv" + private val random = new Random() + private val heroFilePath: String = "/net/eagle0/eagle/heroes.tsv" private val generatedHeroesFilePath = "/net/eagle0/eagle/generated_heroes.tsv" - val heroCount = 10 + val heroCount = 10 private val openAICaller = new OpenAIChatCompletionsServiceImpl( timeoutSeconds = 90, @@ -106,8 +99,8 @@ object HeroLibraryGenerator { private def heroWithName( heroGenerationResponse: HeroGenerationResponse ): HeroWithName = heroGenerationResponse.nameInfo match { - case NoNameRequest => ??? - case FixedName(nameId, name) => + case NoNameRequest => ??? + case FixedName(nameId, name) => HeroWithName(heroGenerationResponse.hero, name) case NameRequest(nameId, gender) => ??? } @@ -117,11 +110,11 @@ object HeroLibraryGenerator { case HeroWithName(hero, name) => s"(${genderString(hero.pronounGender)}) (${professionString( hero.profession - )}) (${personalityString(hero)}) ${name}" + )}) (${personalityString(hero)}) $name" } def main(args: Array[String]): Unit = { - val heroes = FixedHeroes.parse(heroFilePath).get + val heroes = FixedHeroes.parse(heroFilePath).get val randomHeroes = FixedHeroes.parse(generatedHeroesFilePath).get val usedHeroes = @@ -136,14 +129,14 @@ object HeroLibraryGenerator { println( "name\tstrength\tagility\tconstitution\tcharisma\twisdom\tsum\tintegrity\tambition\tgregariousness\tbravery\tvigor\tprofession\tgreat person\timage_path\tgender\tbackstory\tpersonality" ) - randomHeroes.others.foreach { hero => println(heroTsvString(hero)) } + randomHeroes.others.foreach(hero => println(heroTsvString(hero))) - val factionHeadNames = conjunction( + val factionHeadNames = conjunction( heroes.greatPeople.map(_.greatPerson.hero.name) ).get val factionDescriptions = s"Possible leaders of the factions are: $factionHeadNames." - val promptString = + val promptString = s"""This is a fantasy setting with a medieval technology level. Multiple factions are engaged in a civil war for |control of the kingdom after a mysterious stranger from afar, a powerful mage called The Eagle, invaded the realm. |King Bregos Fyar's right-hand man, Ikhaan Tarn, betrayed the King to join with The Eagle. @@ -171,8 +164,7 @@ object HeroLibraryGenerator { .createHeroes( hids = (1 to heroCount).toVector, functionalRandom = SeededRandom(seed = new Random().nextLong()), - remainingImagePathsByProfession = - (_, _) => (1 to heroCount).map(_.toString).toSet, + remainingImagePathsByProfession = (_, _) => (1 to heroCount).map(_.toString).toSet, date = StartDate.startDate ) .newValue @@ -185,7 +177,7 @@ object HeroLibraryGenerator { serviceImpl = claudeCaller ) - var allText = "" + var allText = "" val consumer: Consumer[StreamingTextResults] = { case StreamingTextResults(streamId, textValue, completed) => if completed then { @@ -242,7 +234,7 @@ object HeroLibraryGenerator { Await.ready(future, Duration.Inf).value match { case Some(Success(value)) => println(value) - case _ => throw new IllegalStateException("Failure!") + case _ => throw new IllegalStateException("Failure!") } } } diff --git a/src/main/scala/net/eagle0/util/HexMapJsonUtils.scala b/src/main/scala/net/eagle0/util/HexMapJsonUtils.scala index b437b48f5b..46e339e47c 100644 --- a/src/main/scala/net/eagle0/util/HexMapJsonUtils.scala +++ b/src/main/scala/net/eagle0/util/HexMapJsonUtils.scala @@ -1,20 +1,11 @@ package net.eagle0.util -import java.io.{ - BufferedReader, - FileOutputStream, - InputStream, - InputStreamReader -} +import java.io.{BufferedReader, FileOutputStream, InputStream, InputStreamReader} import java.nio.charset.StandardCharsets import java.util.stream.Collectors import net.eagle0.shardok.common.coords.Coords -import net.eagle0.shardok.common.hex_map.{ - HexMap, - MonthlyWeather, - StartingPositionList -} +import net.eagle0.shardok.common.hex_map.{HexMap, MonthlyWeather, StartingPositionList} import net.eagle0.shardok.common.terrain.Terrain import net.eagle0.shardok.common.tile_modifier.TileModifier import net.eagle0.shardok.common.tile_modifier.TileModifier.SingleModifier @@ -32,9 +23,8 @@ object HexMapJsonUtils { outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8)) } - private def getInt(obj: JObject, key: String): Int = { + private def getInt(obj: JObject, key: String): Int = (obj \ key).extractOrElse[Int](0) - } private def startingPositions(obj: JObject): StartingPositionList = StartingPositionList(positions = @@ -89,12 +79,10 @@ object HexMapJsonUtils { .asInstanceOf[JObject] ) ), - attackerStartingPositions = - (obj \ "attackerStartingPositions").extract[List[JObject]].map { v => - startingPositions(v) - }, - monthlyWeather = - (obj \ "monthlyWeather").extractOrElse(List[JObject]()).map(weather) + attackerStartingPositions = (obj \ "attackerStartingPositions").extract[List[JObject]].map { v => + startingPositions(v) + }, + monthlyWeather = (obj \ "monthlyWeather").extractOrElse(List[JObject]()).map(weather) ) def fromJsonStream(stream: InputStream): HexMap = { diff --git a/src/main/scala/net/eagle0/util/HexMapModificationJob.scala b/src/main/scala/net/eagle0/util/HexMapModificationJob.scala index fdf9068adf..3d8d31d7d5 100644 --- a/src/main/scala/net/eagle0/util/HexMapModificationJob.scala +++ b/src/main/scala/net/eagle0/util/HexMapModificationJob.scala @@ -11,7 +11,7 @@ object HexMapModificationJob { HexMapModifier.modifyMaps(directory, fixClouds) } - def fixClouds(map: HexMap): HexMap = { + def fixClouds(map: HexMap): HexMap = map.update( _.monthlyWeather.modify(ws => ws.map { mw => @@ -21,5 +21,4 @@ object HexMapModificationJob { } ) ) - } } diff --git a/src/main/scala/net/eagle0/util/HexMapModifier.scala b/src/main/scala/net/eagle0/util/HexMapModifier.scala index 25063ef238..936d96c69b 100644 --- a/src/main/scala/net/eagle0/util/HexMapModifier.scala +++ b/src/main/scala/net/eagle0/util/HexMapModifier.scala @@ -10,35 +10,31 @@ object HexMapModifier { outputDir.mkdirs() directory.listFiles.filter(_.getName.endsWith(".e0mj")).foreach { file => - val original = loadMap(file) + val original = loadMap(file) val transformed = transform(original) - val outputFile = new File( + val outputFile = new File( outputDir.getAbsolutePath + "/" + file.getName ) - val os = new FileOutputStream(outputFile) + val os = new FileOutputStream(outputFile) - try { + try HexMapJsonUtils.saveJson(transformed, os) - } finally { + finally os.close() - } } } - def modifyMap(f: File, transform: HexMap => HexMap): Unit = { + def modifyMap(f: File, transform: HexMap => HexMap): Unit = transform(loadMap(f)).writeTo(new FileOutputStream(f)) - } def loadMap(f: File): HexMap = { val is = new FileInputStream(f) - try { + try if f.getAbsolutePath.endsWith(".e0m") then HexMap.parseFrom(is) - else if f.getAbsolutePath.endsWith(".e0mj") then - HexMapJsonUtils.fromJsonStream(is) + else if f.getAbsolutePath.endsWith(".e0mj") then HexMapJsonUtils.fromJsonStream(is) else ??? - } finally { + finally is.close() - } } } diff --git a/src/main/scala/net/eagle0/util/NameListChecker.scala b/src/main/scala/net/eagle0/util/NameListChecker.scala index e7322164b7..cc8db99d22 100644 --- a/src/main/scala/net/eagle0/util/NameListChecker.scala +++ b/src/main/scala/net/eagle0/util/NameListChecker.scala @@ -6,20 +6,21 @@ object NameListChecker { def main(args: Array[String]): Unit = { val maps = TsvUtils.loadColumnMaps(args(0)).get - maps.foreach { case (key, words) => - words - .groupBy(identity) - .filter { case (str, words) => words.length > 1 } - .foreach { case (str, words) => - System.err.println(s"Found duplicate in column $key: $str") - } + maps.foreach { + case (key, words) => + words + .groupBy(identity) + .filter { case (str, words) => words.length > 1 } + .foreach { + case (str, words) => + System.err.println(s"Found duplicate in column $key: $str") + } } - val distinct = maps - .map { case (key, words) => + val distinct = maps.map { + case (key, words) => key +: words.distinct.sorted - } - .toVector + }.toVector .sortBy(_.length) .reverse diff --git a/src/main/scala/net/eagle0/util/NameListJSONMaker.scala b/src/main/scala/net/eagle0/util/NameListJSONMaker.scala index 4ffbd16e31..c45bfc7af6 100644 --- a/src/main/scala/net/eagle0/util/NameListJSONMaker.scala +++ b/src/main/scala/net/eagle0/util/NameListJSONMaker.scala @@ -8,16 +8,18 @@ object NameListJSONMaker { def main(args: Array[String]): Unit = { val maps = TsvUtils.loadColumnMaps(args(0)).get - maps.foreach { case (key, words) => - words - .groupBy(identity) - .filter { case (_, words) => words.length > 1 } - .foreach { case (str, _) => - System.err.println(s"Found duplicate in column $key: $str") - } + maps.foreach { + case (key, words) => + words + .groupBy(identity) + .filter { case (_, words) => words.length > 1 } + .foreach { + case (str, _) => + System.err.println(s"Found duplicate in column $key: $str") + } } - val distinct = maps.view.mapValues { _.distinct.sorted }.toMap + val distinct = maps.view.mapValues(_.distinct.sorted).toMap val jsonLists = new Json(DefaultFormats).writePretty(distinct) diff --git a/src/main/scala/net/eagle0/util/SettingUpdater.scala b/src/main/scala/net/eagle0/util/SettingUpdater.scala index 3ad5a5f22c..463ff0c5fb 100644 --- a/src/main/scala/net/eagle0/util/SettingUpdater.scala +++ b/src/main/scala/net/eagle0/util/SettingUpdater.scala @@ -7,21 +7,17 @@ import scala.concurrent.Await import scala.language.existentials import io.grpc.ManagedChannelBuilder -import net.eagle0.eagle.api.eagle.{ - AddSettingsKeyValue, - AddSettingsRequest, - EagleGrpc -} +import net.eagle0.eagle.api.eagle.{AddSettingsKeyValue, AddSettingsRequest, EagleGrpc} object SettingUpdater { val address = "192.168.123.34" - val port = 30011 + val port = 30011 def main(args: Array[String]): Unit = { val address = args(0) - val port = args(1).toInt - val key = args(2) - val value = args(3) + val port = args(1).toInt + val key = args(2) + val value = args(3) println(s"We'll set $key -> $value") diff --git a/src/main/scala/net/eagle0/util/hero_generation/LoadedHero.scala b/src/main/scala/net/eagle0/util/hero_generation/LoadedHero.scala index 0df919167a..3b7bf9ec05 100644 --- a/src/main/scala/net/eagle0/util/hero_generation/LoadedHero.scala +++ b/src/main/scala/net/eagle0/util/hero_generation/LoadedHero.scala @@ -30,9 +30,9 @@ case class LoadedHero( pronounGender: Gender = Gender.Other, personalityWords: Vector[String] = Vector.empty ) { - def withId(newId: HeroId): LoadedHero = copy(id = newId) + def withId(newId: HeroId): LoadedHero = copy(id = newId) def withFactionId(newFactionId: FactionId): LoadedHero = copy(factionId = Some(newFactionId)) - def nameTextId: ClientTextId = LoadedHero.nameTextId(name) - def backstoryTextId: ClientTextId = s"${name}_backstory 0" + def nameTextId: ClientTextId = LoadedHero.nameTextId(name) + def backstoryTextId: ClientTextId = s"${name}_backstory 0" } diff --git a/src/test/resources/net/eagle0/shardok/maps/MapValidationTest.scala b/src/test/resources/net/eagle0/shardok/maps/MapValidationTest.scala index c6ab26f527..4d08dc90c2 100644 --- a/src/test/resources/net/eagle0/shardok/maps/MapValidationTest.scala +++ b/src/test/resources/net/eagle0/shardok/maps/MapValidationTest.scala @@ -9,15 +9,11 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class MapValidationTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class MapValidationTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { import net.eagle0.util.HexMapUtils.hexMap - override def beforeEach(): Unit = { + override def beforeEach(): Unit = HeroCapPerCastle.setIntValue(3) - } private def checkNeighbor( provinceName: String, @@ -26,7 +22,7 @@ class MapValidationTest allProvinces: Map[ProvinceId, Province] ): Boolean = { val neighborProvince = allProvinces(neighbor.provinceId) - val neighborName = neighborProvince.name + val neighborName = neighborProvince.name if map.attackerStartingPositions.size <= neighbor.startingPositionIndex then { @@ -41,8 +37,8 @@ class MapValidationTest .size < 10 then { println( - s"""Province ${provinceName} has neighbor $neighborName listed in starting position index ${neighbor.startingPositionIndex}. - |But ${provinceName} only has ${map + s"""Province $provinceName has neighbor $neighborName listed in starting position index ${neighbor.startingPositionIndex}. + |But $provinceName only has ${map .attackerStartingPositions(neighbor.startingPositionIndex) .positions .size} attacker starting positions defined there. @@ -94,17 +90,17 @@ class MapValidationTest true } - private def checkWeather(province: Province, map: HexMap): Boolean = { - map.monthlyWeather.zipWithIndex.forall { case (mw, idx) => - if checkMonthlyWeather(mw) then true - else { - println( - s"Invalid weather for month index $idx in ${province.name}" - ) - false - } + private def checkWeather(province: Province, map: HexMap): Boolean = + map.monthlyWeather.zipWithIndex.forall { + case (mw, idx) => + if checkMonthlyWeather(mw) then true + else { + println( + s"Invalid weather for month index $idx in ${province.name}" + ) + false + } } - } private def checkProvince( province: Province, @@ -125,14 +121,13 @@ class MapValidationTest } "map files" should "return no errors" in { - val provinces = { + val provinces = IDable.mapifyProvinces( MapGenerator .loadMap( tsvUrl = getClass.getResource("/net/eagle0/eagle/province_map.tsv") )* ) - } provinces.values.foreach { province => checkProvince(province, provinces) shouldBe true diff --git a/src/test/scala/net/eagle0/common/FunctionalRandomTest.scala b/src/test/scala/net/eagle0/common/FunctionalRandomTest.scala index 631143e590..626bdaa29d 100644 --- a/src/test/scala/net/eagle0/common/FunctionalRandomTest.scala +++ b/src/test/scala/net/eagle0/common/FunctionalRandomTest.scala @@ -10,13 +10,13 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { behavior of "FunctionalRandomTest" "nextPositiveInt" should "return positive numbers" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val results = for (_ <- 0 to 10000) yield rs.nextPositiveInt.newValue results.forall(_ > 0) shouldBe true } "nextInt" should "always be within the range given with exclusive upper bound" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val results = for (_ <- 0 to 1000) yield rs.nextInt(atLeast = 5, lessThan = 10).newValue results.forall(_ >= 5) shouldBe true @@ -24,21 +24,21 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } it should "hit the lower bound" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val results = for (_ <- 0 to 1000) yield rs.nextInt(atLeast = 5, lessThan = 10).newValue results should contain(5) } it should "hit the upper bound - 1" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val results = for (_ <- 0 to 1000) yield rs.nextInt(atLeast = 5, lessThan = 10).newValue results should contain(9) } "nextIntInclusive" should "always be within the range" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val results = for (_ <- 0 to 1000) yield rs.nextIntInclusive(atLeast = 5, upTo = 10).newValue @@ -47,7 +47,7 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } it should "hit the lower bound" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val results = for (_ <- 0 to 1000) yield rs.nextIntInclusive(atLeast = 5, upTo = 10).newValue @@ -55,7 +55,7 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } it should "hit the upper bound" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val results = for (_ <- 0 to 1000) yield rs.nextIntInclusive(atLeast = 5, upTo = 10).newValue @@ -63,19 +63,20 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } "nextShuffled" should "return the same elements" in { - val rs = new JankyRandom(new Random) + val rs = new JankyRandom(new Random) val vec = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val results = rs.nextShuffled(vec).newValue - results should contain theSameElementsAs (vec) + results should contain theSameElementsAs vec } "nextFlatMap" should "fold in the random numbers" in { - val rs = IntSequenceRandom(Vector(2, 1, 3)) + val rs = IntSequenceRandom(Vector(2, 1, 3)) val vec = Vector(1, 6, 10, 10, 1, 3, 5) - val results = rs.nextFlatMap(vec) { case (i, fr) => - fr.nextInt(0, 10).map(x => Vector.fill(x)(i)) + val results = rs.nextFlatMap(vec) { + case (i, fr) => + fr.nextInt(0, 10).map(x => Vector.fill(x)(i)) } results shouldBe RandomState( @@ -85,11 +86,12 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } "nextMap" should "fold in the random numbers" in { - val rs = IntSequenceRandom(Vector(6, 1, 3)) + val rs = IntSequenceRandom(Vector(6, 1, 3)) val vec = Vector(1, 1, 10, 10, 1, 1, 5) - val results = rs.nextMap(vec) { case (i, fr) => - fr.nextInt(0, 10).map(x => x + i) + val results = rs.nextMap(vec) { + case (i, fr) => + fr.nextInt(0, 10).map(x => x + i) } results shouldBe RandomState( @@ -99,11 +101,12 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } "nextCollect" should "return the values that match the PartialFunction" in { - val rs = IntSequenceRandom(Vector(1, 2, 3)) + val rs = IntSequenceRandom(Vector(1, 2, 3)) val vec = Vector(10, "hello", 30, "bye", 0.3, 20, 50) - val collected = rs.nextCollect(vec) { case x: Int => - _.nextInt.map(_ + x) + val collected = rs.nextCollect(vec) { + case x: Int => + _.nextInt.map(_ + x) } // 10, 30, 20, 50 match, add 1, 2, 3, 1 to those @@ -114,11 +117,12 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } "nextCollectFirst" should "return the first value that matches the PartialFunction" in { - val rs = IntSequenceRandom(Vector(1, 2, 3)) + val rs = IntSequenceRandom(Vector(1, 2, 3)) val vec = Vector(10, "hello", 30, "bye", 0.3, 20, 50) - val collected = rs.nextCollectFirst(vec) { case x: Int => - _.nextInt.map(_ + x) + val collected = rs.nextCollectFirst(vec) { + case x: Int => + _.nextInt.map(_ + x) } // 10, 30, 20, 50 match, take the first one and add 1 @@ -129,13 +133,14 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } "nextFlatCollect" should "return the values that match the PartialFunction and return Some" in { - val rs = IntSequenceRandom(Vector(1, 2, 3)) + val rs = IntSequenceRandom(Vector(1, 2, 3)) val vec = Vector(10, 15, 30, 22, 25, 20, 50) - val collected = rs.nextFlatCollect(vec) { case x => - fr => - if x % 10 == 0 then fr.nextInt.map(ni => Some(ni + x)) - else RandomState(None, fr) + val collected = rs.nextFlatCollect(vec) { + case x => + fr => + if x % 10 == 0 then fr.nextInt.map(ni => Some(ni + x)) + else RandomState(None, fr) } // 10, 30, 20, 50 match, add 1, 2, 3, 1 to those @@ -146,13 +151,14 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } "nextFlatCollectFirst" should "return the first value that matches the PartialFunction and returns Some" in { - val rs = IntSequenceRandom(Vector(1, 2, 3)) + val rs = IntSequenceRandom(Vector(1, 2, 3)) val vec = Vector(10, 15, 30, 22, 25, 20, 50) - val collected = rs.nextFlatCollectFirst(vec) { case x => - fr => - if x % 10 == 5 then fr.nextInt.map(ni => Some(ni + x)) - else RandomState(None, fr) + val collected = rs.nextFlatCollectFirst(vec) { + case x => + fr => + if x % 10 == 5 then fr.nextInt.map(ni => Some(ni + x)) + else RandomState(None, fr) } // 15, 25 match, take the first one and add 1 @@ -163,14 +169,15 @@ class FunctionalRandomTest extends AnyFlatSpec with Matchers { } it should "advance the functionalrandom if the partial function returns None" in { - val rs = IntSequenceRandom(Vector(1, 2, 3)) + val rs = IntSequenceRandom(Vector(1, 2, 3)) val vec = Vector(10, 15, "sheep", 17, 22, 25, 20, 50) - val collected = rs.nextFlatCollectFirst(vec) { case x: Int => - fr => - fr.nextInt.map { ni => - Option.when((ni + x) % 10 == 0) { x } - } + val collected = rs.nextFlatCollectFirst(vec) { + case x: Int => + fr => + fr.nextInt.map { ni => + Option.when((ni + x) % 10 == 0)(x) + } } // 17 matches and loops all the way diff --git a/src/test/scala/net/eagle0/common/FunctionalRandomTestClasses.scala b/src/test/scala/net/eagle0/common/FunctionalRandomTestClasses.scala index a301e6efc8..6acf02dd3d 100644 --- a/src/test/scala/net/eagle0/common/FunctionalRandomTestClasses.scala +++ b/src/test/scala/net/eagle0/common/FunctionalRandomTestClasses.scala @@ -19,8 +19,7 @@ case class StaticRandom(doubleValue: Double) extends FunctionalRandom { ) } -case class DoubleSequenceRandom(doubles: Vector[Double]) - extends FunctionalRandom { +case class DoubleSequenceRandom(doubles: Vector[Double]) extends FunctionalRandom { override def seed: Long = 0 override def nextInt: RandomState[Int] = diff --git a/src/test/scala/net/eagle0/common/ProtoMatchers.scala b/src/test/scala/net/eagle0/common/ProtoMatchers.scala index 5e5318efe1..fb03a23b96 100644 --- a/src/test/scala/net/eagle0/common/ProtoMatchers.scala +++ b/src/test/scala/net/eagle0/common/ProtoMatchers.scala @@ -13,7 +13,7 @@ trait ProtoMatchers { indentLevel: Int = 0 ): String = (received, expected) match { - case (recPM: PMessage, expPM: PMessage) => + case (recPM: PMessage, expPM: PMessage) => differingFields(recPM, expPM, indentLevel).mkString("\n") case (recPR: PRepeated, expPR: PRepeated) => if recPR.value.size != expPR.value.size then @@ -24,8 +24,8 @@ trait ProtoMatchers { entry <- recPR.value.zip(expPR.value).zipWithIndex } yield { val index = entry._2 - val rec = entry._1._1 - val exp = entry._1._2 + val rec = entry._1._1 + val exp = entry._1._2 if rec == exp then "" else indented( @@ -36,9 +36,9 @@ trait ProtoMatchers { s"Differing entries in repeated field:\n${indexedDiffs.mkString("")}" } - case (PEmpty, expected) => s"No entry for expected $expected" - case (received, PEmpty) => s"Expected no entry but got $received" - case (rec, exp) => + case (PEmpty, expected) => s"No entry for expected $expected" + case (received, PEmpty) => s"Expected no entry but got $received" + case (rec, exp) => s"Expected\n${indented(exp.toString, indentLevel + 1)}\n${indented("but got", indentLevel)}\n${indented(rec.toString, indentLevel + 1)}" } @@ -47,14 +47,13 @@ trait ProtoMatchers { expected: PMessage, indentLevel: Int = 0 ): Iterable[String] = - received.value - .map { case (fd, v) => + received.value.map { + case (fd, v) => (fd, v, expected.value(fd)) - } - .filterNot { case (_, rec, exp) => rec == exp } - .map { case (fd, rec, exp) => + }.filterNot { case (_, rec, exp) => rec == exp }.map { + case (fd, rec, exp) => s"In field ${fd.fullName}, found difference \n${indented(fieldDifferenceMessage(rec, exp, indentLevel + 1), indentLevel + 1)}" - } + } def differingFields[U <: GeneratedMessage]( received: U, @@ -62,8 +61,7 @@ trait ProtoMatchers { ): Iterable[String] = differingFields(received.toPMessage, expected.toPMessage) - class ProtobufEqualsMatcher[P <: GeneratedMessage](expectedMessage: P) - extends Matcher[P] { + class ProtobufEqualsMatcher[P <: GeneratedMessage](expectedMessage: P) extends Matcher[P] { def apply(left: P): MatchResult = { val df = differingFields(left, expectedMessage) MatchResult( @@ -91,8 +89,9 @@ trait ProtoMatchers { val results = received .zip(expectedMessages) .zipWithIndex - .flatMap { case ((rec, exp), index) => - differingFields(rec, exp).map(s => s"Position $index: $s") + .flatMap { + case ((rec, exp), index) => + differingFields(rec, exp).map(s => s"Position $index: $s") } MatchResult( results.isEmpty, diff --git a/src/test/scala/net/eagle0/common/name_generation/StringConstructionParserTest.scala b/src/test/scala/net/eagle0/common/name_generation/StringConstructionParserTest.scala index 0614169d82..176a588c32 100644 --- a/src/test/scala/net/eagle0/common/name_generation/StringConstructionParserTest.scala +++ b/src/test/scala/net/eagle0/common/name_generation/StringConstructionParserTest.scala @@ -5,7 +5,7 @@ import org.scalatest.matchers.should.Matchers class StringConstructionParserTest extends AnyFlatSpec with Matchers { - private val names = Vector("Joe", "Lisa") + private val names = Vector("Joe", "Lisa") private val parser = new StringConstructionParser( Map("titles" -> Vector.empty, "names" -> names), Map("titles" -> Vector.empty, "names" -> names) diff --git a/src/test/scala/net/eagle0/common/name_generation/StringConstructionTokenTest.scala b/src/test/scala/net/eagle0/common/name_generation/StringConstructionTokenTest.scala index 28f8932f6f..116e271105 100644 --- a/src/test/scala/net/eagle0/common/name_generation/StringConstructionTokenTest.scala +++ b/src/test/scala/net/eagle0/common/name_generation/StringConstructionTokenTest.scala @@ -5,10 +5,7 @@ import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class StringConstructionTokenTest - extends AnyFlatSpec - with Matchers - with MockFactory { +class StringConstructionTokenTest extends AnyFlatSpec with Matchers with MockFactory { private val mockRandom = mock[FunctionalRandom] "LiteralToken" should "return the literal" in { @@ -25,9 +22,8 @@ class StringConstructionTokenTest (() => mockRandom.nextInt).expects().never() - val ex = the[MissingLiteralKeyException] thrownBy { + val ex = the[MissingLiteralKeyException] thrownBy token.nextString(mockRandom, Map()) - } ex.getMessage shouldBe "Missing literal key KEY" } @@ -47,7 +43,7 @@ class StringConstructionTokenTest val token2 = LiteralToken("Second") val token3 = LiteralToken("Third") - val token = SequenceToken(Vector(token1, token2, token3)) + val token = SequenceToken(Vector(token1, token2, token3)) val result = token.nextString(mockRandom, Map()) result.newValue shouldBe "FirstSecondThird" @@ -71,7 +67,7 @@ class StringConstructionTokenTest val lowRandom = mock[FunctionalRandom] (() => lowRandom.nextDouble).expects().returns(RandomState(0.1, mockRandom)) - val result = optionalToken.nextString(lowRandom, Map()) + val result = optionalToken.nextString(lowRandom, Map()) result.newValue shouldBe "optional" result.nextRandom shouldBe mockRandom } @@ -84,7 +80,7 @@ class StringConstructionTokenTest (() => highRandom.nextDouble) .expects() .returns(RandomState(0.4, mockRandom)) - val result = optionalToken.nextString(highRandom, Map()) + val result = optionalToken.nextString(highRandom, Map()) result.newValue shouldBe "" result.nextRandom shouldBe mockRandom } @@ -100,7 +96,7 @@ class StringConstructionTokenTest val lowRandom = mock[FunctionalRandom] (() => lowRandom.nextDouble).expects().returns(RandomState(0.1, mockRandom)) - val result = oneofToken.nextString(lowRandom, Map()) + val result = oneofToken.nextString(lowRandom, Map()) result.newValue shouldBe "first" result.nextRandom shouldBe mockRandom } @@ -118,7 +114,7 @@ class StringConstructionTokenTest (() => mediumRandom.nextDouble) .expects() .returns(RandomState(0.25, mockRandom)) - val result = oneofToken.nextString(mediumRandom, Map()) + val result = oneofToken.nextString(mediumRandom, Map()) result.newValue shouldBe "second" result.nextRandom shouldBe mockRandom } @@ -136,7 +132,7 @@ class StringConstructionTokenTest (() => highRandom.nextDouble) .expects() .returns(RandomState(0.51, mockRandom)) - val result = oneofToken.nextString(highRandom, Map()) + val result = oneofToken.nextString(highRandom, Map()) result.newValue shouldBe "third" result.nextRandom shouldBe mockRandom } diff --git a/src/test/scala/net/eagle0/common/sse/SseEventReaderTest.scala b/src/test/scala/net/eagle0/common/sse/SseEventReaderTest.scala index 728b955fe9..ee27b93d96 100644 --- a/src/test/scala/net/eagle0/common/sse/SseEventReaderTest.scala +++ b/src/test/scala/net/eagle0/common/sse/SseEventReaderTest.scala @@ -36,7 +36,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { data = "", carryover = "data: h" ) - val text = "ello" + val text = "ello" SseEventReader .readOneEvent(Some(previous), text) shouldBe SseEventReader @@ -91,7 +91,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "append new text item to existing data" in { - val newText = "data: , world\n\n" + val newText = "data: , world\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map.empty, @@ -110,7 +110,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "append to the end of any carried over text" in { - val newText = "a: world\ndata: !!!\n\n" + val newText = "a: world\ndata: !!!\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map.empty, @@ -129,7 +129,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "append metadata for Id or Retry" in { - val newText = "ld\nretry: 1234\n\n" + val newText = "ld\nretry: 1234\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map("id" -> "123"), @@ -148,7 +148,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "handle colon-less metadata items" in { - val newText = "ld\nretry\n\n" + val newText = "ld\nretry\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map("id" -> "123"), @@ -167,7 +167,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "ignore items with a key not in the set values" in { - val newText = "ld\nsomeKey: huzzah\n\n" + val newText = "ld\nsomeKey: huzzah\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map("id" -> "123"), @@ -186,7 +186,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "ignore colon-less metadata items with a key not in the set values" in { - val newText = "ld\nsomeKey\n\n" + val newText = "ld\nsomeKey\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map("id" -> "123"), @@ -205,7 +205,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "set the event type" in { - val newText = "ld\nevent: start\n\n" + val newText = "ld\nevent: start\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map("id" -> "123"), @@ -224,7 +224,7 @@ class SseEventReaderTest extends AnyFlatSpec with Matchers { } it should "ignore a line that starts with a colon" in { - val newText = "ld\n: ignore me\n\n" + val newText = "ld\n: ignore me\n\n" val carriedOver = IncompleteEvent( eventType = "message", metadata = Map("id" -> "123"), diff --git a/src/test/scala/net/eagle0/eagle/ai/AIClientUtilsTest.scala b/src/test/scala/net/eagle0/eagle/ai/AIClientUtilsTest.scala index 6c847ae517..c8662de182 100644 --- a/src/test/scala/net/eagle0/eagle/ai/AIClientUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/AIClientUtilsTest.scala @@ -6,7 +6,7 @@ import org.scalatest.matchers.should.Matchers class AIClientUtilsTest extends AnyFlatSpec with Matchers { "desiredCountForMarchTowardFocus" should "leave two heroes behind if no leaders are involved" in { - val originProvince = Province( + val originProvince = Province( id = 19, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(3, 4, 5) @@ -16,7 +16,7 @@ class AIClientUtilsTest extends AnyFlatSpec with Matchers { rulingFactionId = Some(4), rulingFactionHeroIds = Vector(6, 7, 8) ) - val factionLeaders = Vector(1, 11) + val factionLeaders = Vector(1, 11) AIClientUtils.desiredCountForMarchTowardFocus( originProvince = originProvince, @@ -28,7 +28,7 @@ class AIClientUtilsTest extends AnyFlatSpec with Matchers { } it should "leave two heroes behind if we can still take the leader if there isn't one at the destination" in { - val originProvince = Province( + val originProvince = Province( id = 19, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(3, 4, 5) @@ -38,7 +38,7 @@ class AIClientUtilsTest extends AnyFlatSpec with Matchers { rulingFactionId = Some(4), rulingFactionHeroIds = Vector(6, 7, 8) ) - val factionLeaders = Vector(3, 11) + val factionLeaders = Vector(3, 11) AIClientUtils.desiredCountForMarchTowardFocus( originProvince = originProvince, @@ -50,7 +50,7 @@ class AIClientUtilsTest extends AnyFlatSpec with Matchers { } it should "leave only one hero behind in order to move the faction leader" in { - val originProvince = Province( + val originProvince = Province( id = 19, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(3, 4) @@ -60,7 +60,7 @@ class AIClientUtilsTest extends AnyFlatSpec with Matchers { rulingFactionId = Some(4), rulingFactionHeroIds = Vector(6, 7, 8) ) - val factionLeaders = Vector(3, 11) + val factionLeaders = Vector(3, 11) AIClientUtils.desiredCountForMarchTowardFocus( originProvince = originProvince, diff --git a/src/test/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRankerTest.scala b/src/test/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRankerTest.scala index 7b964b72d5..d563b450c5 100644 --- a/src/test/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRankerTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/FactionLeaderProvinceRankerTest.scala @@ -8,10 +8,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class FactionLeaderProvinceRankerTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class FactionLeaderProvinceRankerTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { "rankedProvinceIds" should "order by hostile, then hostile + neutral" in { val gameState: GameState = GameState( @@ -25,8 +22,7 @@ class FactionLeaderProvinceRankerTest Province( id = 41, rulingFactionId = Some(4), - neighbors = - Vector(Neighbor(provinceId = 71), Neighbor(provinceId = 42)) + neighbors = Vector(Neighbor(provinceId = 71), Neighbor(provinceId = 42)) ), // Two hostile and one neutral neighbor Province( @@ -230,9 +226,7 @@ class FactionLeaderProvinceRankerTest it should "return None if no province is better than the one we're in" in { val gsWithCurrentProvinceIsTie = bestSettlementGameState.update( - _.provinces(40).neighbors :++= Vector(71, 72).map(pid => - Neighbor(provinceId = pid) - ) + _.provinces(40).neighbors :++= Vector(71, 72).map(pid => Neighbor(provinceId = pid)) ) FactionLeaderProvinceRanker.bestSettlementPidForFactionLeader( diff --git a/src/test/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelectorTest.scala index 32910e685b..35fa87b841 100644 --- a/src/test/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/FixLeaderAloneCommandSelectorTest.scala @@ -21,12 +21,9 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class FixLeaderAloneCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class FixLeaderAloneCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val factionId: FactionId = 7 + private val factionId: FactionId = 7 private val factionLeaderHeroId: HeroId = 77 private val factionLeaderProvinceId: ProvinceId = 17 diff --git a/src/test/scala/net/eagle0/eagle/ai/InvitationCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/ai/InvitationCommandSelectorTest.scala index b4403fe056..45c514a19a 100644 --- a/src/test/scala/net/eagle0/eagle/ai/InvitationCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/InvitationCommandSelectorTest.scala @@ -1,14 +1,8 @@ package net.eagle0.eagle.ai import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.api.available_command.{ - AvailableCommand, - DiplomacyAvailableCommand -} -import net.eagle0.eagle.api.command.util.diplomacy_option.{ - InvitationOption, - TruceOption -} +import net.eagle0.eagle.api.available_command.{AvailableCommand, DiplomacyAvailableCommand} +import net.eagle0.eagle.api.command.util.diplomacy_option.{InvitationOption, TruceOption} import net.eagle0.eagle.api.selected_command.DiplomacySelectedCommand import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction.Faction.OutgoingOfferRound @@ -31,12 +25,9 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class InvitationCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class InvitationCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val actingFactionId: FactionId = 7 + private val actingFactionId: FactionId = 7 private val actingProvinceId: ProvinceId = 14 private val targetFactionId: FactionId = 8 @@ -70,7 +61,7 @@ class InvitationCommandSelectorTest ) ) - private val invitationOption = + private val invitationOption = InvitationOption(targetFactionId = targetFactionId, goldCost = 1000) private val diplomacyAvailableCommand = DiplomacyAvailableCommand( options = Vector( diff --git a/src/test/scala/net/eagle0/eagle/ai/MidGameAIClientTest.scala b/src/test/scala/net/eagle0/eagle/ai/MidGameAIClientTest.scala index fabaa32b68..d508e1a85b 100644 --- a/src/test/scala/net/eagle0/eagle/ai/MidGameAIClientTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/MidGameAIClientTest.scala @@ -8,11 +8,7 @@ import net.eagle0.eagle.api.available_command.{ MarchCommandFromOneProvince, ReconAvailableCommand } -import net.eagle0.eagle.api.selected_command.{ - ImproveSelectedCommand, - MarchSelectedCommand, - ReconSelectedCommand -} +import net.eagle0.eagle.api.selected_command.{ImproveSelectedCommand, MarchSelectedCommand, ReconSelectedCommand} import net.eagle0.eagle.common.battalion_type.{BattalionType, BattalionTypeId} import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.improvement_type.ImprovementType @@ -25,27 +21,16 @@ import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.Relati import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.{Neighbor, Province} -import net.eagle0.eagle.library.settings.{ - GoldPerHeroHeldBack, - MonthsReconConsideredRecent -} +import net.eagle0.eagle.library.settings.{GoldPerHeroHeldBack, MonthsReconConsideredRecent} import net.eagle0.eagle.library.util.IDable -import net.eagle0.eagle.library.util.IDable.{ - mapifyBattalions, - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyBattalions, mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.views.province_view.ProvinceView import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class MidGameAIClientTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class MidGameAIClientTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { GoldPerHeroHeldBack.setDoubleValue(100) @@ -54,8 +39,8 @@ class MidGameAIClientTest behavior of "AIClientTest" - val factionId = 22 - val leaderId = 58 + val factionId = 22 + val leaderId = 58 val hubProvinceId = 4 private val faction = @@ -170,7 +155,7 @@ class MidGameAIClientTest originProvince, destinationProvinceId, marchingUnits, - _ /* uknownFieldSet */ + _ /* uknownFieldSet */ ) => destinationProvinceId shouldBe 1 originProvince shouldBe 3 @@ -322,8 +307,7 @@ class MidGameAIClientTest Province(id = 19, rulingFactionId = Some(factionId)), Province(id = 23, rulingFactionId = Some(999)) ), - heroes = - mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) + heroes = mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) ) val acs = Vector( @@ -364,8 +348,7 @@ class MidGameAIClientTest neighbors = Vector(Neighbor(provinceId = 19)) ) ), - heroes = - mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) + heroes = mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) ) val acs = Vector( @@ -403,8 +386,7 @@ class MidGameAIClientTest Province( id = 19, rulingFactionId = Some(factionId), - neighbors = - Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) + neighbors = Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) ), Province( id = 23, @@ -412,8 +394,7 @@ class MidGameAIClientTest neighbors = Vector(Neighbor(provinceId = 19)) ) ), - heroes = - mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) + heroes = mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) ) val acs = Vector( @@ -465,8 +446,7 @@ class MidGameAIClientTest Province( id = 19, rulingFactionId = Some(factionId), - neighbors = - Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) + neighbors = Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) ), Province( id = 23, @@ -474,8 +454,7 @@ class MidGameAIClientTest neighbors = Vector(Neighbor(provinceId = 19)) ) ), - heroes = - mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) + heroes = mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) ) val acs = Vector( @@ -527,8 +506,7 @@ class MidGameAIClientTest Province( id = 19, rulingFactionId = Some(factionId), - neighbors = - Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) + neighbors = Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) ), Province( id = 23, @@ -536,8 +514,7 @@ class MidGameAIClientTest neighbors = Vector(Neighbor(provinceId = 19)) ) ), - heroes = - mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) + heroes = mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) ) val acs = Vector( @@ -592,8 +569,7 @@ class MidGameAIClientTest Province( id = 19, rulingFactionId = Some(factionId), - neighbors = - Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) + neighbors = Vector(Neighbor(provinceId = 23), Neighbor(provinceId = 7)) ), Province( id = 23, @@ -601,8 +577,7 @@ class MidGameAIClientTest neighbors = Vector(Neighbor(provinceId = 19)) ) ), - heroes = - mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) + heroes = mapifyHeroes(Hero(id = 9, profession = Profession.RANGER, vigor = 90)) ) val acs = Vector( @@ -732,8 +707,8 @@ class MidGameAIClientTest val gameState = improveForTroopsGS.update( _.provinces(17) := improveForTroopsProvince.update( _.battalionIds := Vector(3, 9), - _.agriculture := 60, - _.economy := 60 + _.agriculture := 60, + _.economy := 60 ), _.battalions :++= mapifyBattalions( Battalion(id = 9, `type` = BattalionTypeId.LONGBOWMEN) @@ -799,8 +774,8 @@ class MidGameAIClientTest val gameState = improveForTroopsGS.update( _.provinces(17) := improveForTroopsProvince.update( _.battalionIds := Vector(3, 9), - _.agriculture := 55, - _.economy := 57 + _.agriculture := 55, + _.economy := 57 ), _.battalions :++= mapifyBattalions( Battalion(id = 9, `type` = BattalionTypeId.LONGBOWMEN) @@ -840,8 +815,8 @@ class MidGameAIClientTest val gameState = improveForTroopsGS.update( _.provinces(17) := improveForTroopsProvince.update( _.battalionIds := Vector(3, 9), - _.agriculture := 55, - _.economy := 50 + _.agriculture := 55, + _.economy := 50 ), _.battalions :++= mapifyBattalions( Battalion(id = 9, `type` = BattalionTypeId.LONGBOWMEN) @@ -894,9 +869,7 @@ class MidGameAIClientTest ) ), heroes = mapifyHeroes( - Vector(5, 10, 15, 20, 25, 30, 40, 50).map(hid => - Hero(id = hid, factionId = Some(21), vigor = 80) - )* + Vector(5, 10, 15, 20, 25, 30, 40, 50).map(hid => Hero(id = hid, factionId = Some(21), vigor = 80))* ) ) diff --git a/src/test/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooserTest.scala index f65c8292ff..a6093eb26b 100644 --- a/src/test/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/MoveLeaderToBetterProvinceCommandChooserTest.scala @@ -18,13 +18,10 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class MoveLeaderToBetterProvinceCommandChooserTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class MoveLeaderToBetterProvinceCommandChooserTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val factionId: FactionId = 22 - private val leaderId: HeroId = 58 + private val factionId: FactionId = 22 + private val leaderId: HeroId = 58 private val hubProvinceId: ProvinceId = 4 private val faction: Faction = @@ -74,15 +71,13 @@ class MoveLeaderToBetterProvinceCommandChooserTest heroCap = 20 ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = GoldPerHeroHeldBack.setDoubleValue(100) - } "maybeMoveLeaderToFocusCommand" should "move the leader toward the focus province if possible" in { val gs = GameState( factions = Map(factionId -> faction), - provinces = - IDable.mapifyProvinces(provinceA, provinceB, provinceC, provinceD), + provinces = IDable.mapifyProvinces(provinceA, provinceB, provinceC, provinceD), heroes = heroesInLeaderProvince.map(h => h.id -> h).toMap ) @@ -136,7 +131,7 @@ class MoveLeaderToBetterProvinceCommandChooserTest originProvince, destinationProvinceId, marchingUnits, - _ /* uknownFieldSet */ + _ /* uknownFieldSet */ ) => destinationProvinceId shouldBe 2 originProvince shouldBe 1 @@ -210,7 +205,7 @@ class MoveLeaderToBetterProvinceCommandChooserTest originProvince, destinationProvinceId, marchingUnits, - _ /* uknownFieldSet */ + _ /* uknownFieldSet */ ) => destinationProvinceId shouldBe 4 originProvince shouldBe 2 diff --git a/src/test/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelectorTest.scala index 26964a3a89..99f62cded3 100644 --- a/src/test/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/ResolveDiplomacyCommandSelectorTest.scala @@ -16,10 +16,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class ResolveDiplomacyCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ResolveDiplomacyCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { PrestigePerSupportedProvince.setDoubleValue(15) @@ -29,11 +26,10 @@ class ResolveDiplomacyCommandSelectorTest } "invitationAcceptanceChance" should "be zero if the factions have the same prestige" in { - val originFid = 17 + val originFid = 17 val invitedFid = 7 - val gs = GameState( - factions = - mapifyFactions(Faction(id = originFid), Faction(id = invitedFid)) + val gs = GameState( + factions = mapifyFactions(Faction(id = originFid), Faction(id = invitedFid)) ) ResolveDiplomacyCommandSelector.invitationAcceptanceChance( originFid, @@ -43,9 +39,9 @@ class ResolveDiplomacyCommandSelectorTest } it should "be equal to the difference in prestige minus the min diff" in { - val originFid = 17 + val originFid = 17 val invitedFid = 7 - val gs = GameState( + val gs = GameState( factions = mapifyFactions( Faction( id = originFid, @@ -65,11 +61,10 @@ class ResolveDiplomacyCommandSelectorTest } "truceAcceptanceChance" should "be the floor of the base chance if the factions have the same prestige" in { - val originFid = 17 + val originFid = 17 val invitedFid = 7 - val gs = GameState( - factions = - mapifyFactions(Faction(id = originFid), Faction(id = invitedFid)) + val gs = GameState( + factions = mapifyFactions(Faction(id = originFid), Faction(id = invitedFid)) ) AiTruceAcceptanceBaseChance.setDoubleValue(81.3) @@ -81,9 +76,9 @@ class ResolveDiplomacyCommandSelectorTest } it should "go down if the offering faction has lower prestige" in { - val originFid = 17 + val originFid = 17 val invitedFid = 7 - val gs = GameState( + val gs = GameState( factions = mapifyFactions( Faction( id = originFid, @@ -103,9 +98,9 @@ class ResolveDiplomacyCommandSelectorTest } it should "change based on trust" in { - val originFid = 17 + val originFid = 17 val invitedFid = 7 - val gs = GameState( + val gs = GameState( factions = mapifyFactions( Faction(id = originFid), Faction( @@ -126,7 +121,7 @@ class ResolveDiplomacyCommandSelectorTest "allianceOfferAcceptanceChance" should "be the floor of the base chance if the factions have the same prestige" in { val originFid = 17 val targetFid = 7 - val gs = GameState( + val gs = GameState( provinces = mapifyProvinces( Province(id = 1, rulingFactionId = Some(originFid)), Province( @@ -140,8 +135,7 @@ class ResolveDiplomacyCommandSelectorTest neighbors = Vector(Neighbor(provinceId = 2)) ) ), - factions = - mapifyFactions(Faction(id = originFid), Faction(id = targetFid)) + factions = mapifyFactions(Faction(id = originFid), Faction(id = targetFid)) ) AiAllianceAcceptanceBaseChance.setDoubleValue(49.1) @@ -155,8 +149,8 @@ class ResolveDiplomacyCommandSelectorTest it should "return 0 if the target faction already has an alliance" in { val originFid = 17 val targetFid = 7 - val thirdFid = 99 - val gs = GameState( + val thirdFid = 99 + val gs = GameState( provinces = mapifyProvinces( Province(id = 1, rulingFactionId = Some(originFid)), Province( @@ -195,7 +189,7 @@ class ResolveDiplomacyCommandSelectorTest it should "return 0 if our only neighbor belongs the enemy" in { val originFid = 17 val targetFid = 7 - val gs = GameState( + val gs = GameState( provinces = mapifyProvinces( Province(id = 1, rulingFactionId = Some(originFid)), Province( @@ -226,7 +220,7 @@ class ResolveDiplomacyCommandSelectorTest it should "go down if the offering faction has lower prestige" in { val originFid = 17 val targetFid = 7 - val gs = GameState( + val gs = GameState( provinces = mapifyProvinces( Province(id = 1, rulingFactionId = Some(originFid)), Province( @@ -261,7 +255,7 @@ class ResolveDiplomacyCommandSelectorTest it should "change based on trust" in { val originFid = 17 val targetFid = 7 - val gs = GameState( + val gs = GameState( provinces = mapifyProvinces( Province(id = 1, rulingFactionId = Some(originFid)), Province( diff --git a/src/test/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooserTest.scala index 632e6674d4..4a20db1224 100644 --- a/src/test/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/ai/SeekMoreLeadersCommandChooserTest.scala @@ -32,25 +32,17 @@ import net.eagle0.eagle.library.settings.{ MinimumLoyaltyForSwearBrotherhood } import net.eagle0.eagle.library.util.CommandSelection -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class SeekMoreLeadersCommandChooserTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class SeekMoreLeadersCommandChooserTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val swearBrotherhoodAC = SwearBrotherhoodAvailableCommand( actingProvinceId = 17, - availableHeroes = - Vector(9, 12, 13).map(hid => HeroAndBackstory(heroId = hid)) + availableHeroes = Vector(9, 12, 13).map(hid => HeroAndBackstory(heroId = hid)) ) private val heroGiftAC = HeroGiftAvailableCommand( @@ -80,8 +72,7 @@ class SeekMoreLeadersCommandChooserTest Province(id = 20, rulingFactionId = Some(4)), Province(id = 909, rulingFactionId = Some(4)) ), - factions = - mapifyFactions(Faction(id = 4, leaders = Vector(1), factionHeadId = 1)), + factions = mapifyFactions(Faction(id = 4, leaders = Vector(1), factionHeadId = 1)), heroes = mapifyHeroes( Hero(id = 1, charisma = 90, constitution = 90, factionId = Some(4)), Hero(id = 9, charisma = 70, constitution = 70, factionId = Some(4)), @@ -224,9 +215,9 @@ class SeekMoreLeadersCommandChooserTest it should "do nothing if no available hero meets the minimums" in { val crappyHeroesGS = swearBrotherhoodGameState.update( - _.heroes(12).charisma := 64, + _.heroes(12).charisma := 64, _.heroes(9).constitution := 63, - _.heroes(13).charisma := 60 + _.heroes(13).charisma := 60 ) SeekMoreLeadersCommandChooser @@ -266,20 +257,17 @@ class SeekMoreLeadersCommandChooserTest id = 17, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(1, 9, 13), - neighbors = - Vector(Neighbor(provinceId = 20, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 20, startingPositionIndex = 0)) ), Province( id = 20, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(12, 15, 16), - neighbors = - Vector(Neighbor(provinceId = 17, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 17, startingPositionIndex = 0)) ), Province(id = 909, rulingFactionId = Some(4)) ), - factions = - mapifyFactions(Faction(id = 4, leaders = Vector(1), factionHeadId = 1)), + factions = mapifyFactions(Faction(id = 4, leaders = Vector(1), factionHeadId = 1)), heroes = mapifyHeroes( Hero(id = 1, charisma = 90, constitution = 90, factionId = Some(4)), Hero(id = 9, charisma = 70, constitution = 35, factionId = Some(4)), @@ -337,8 +325,7 @@ class SeekMoreLeadersCommandChooserTest food = 0, originProvince = 20, destinationProvinceId = 17, - marchingUnits = - Vector(CombatUnit(factionId = 4, heroId = 12, battalionId = None)) + marchingUnits = Vector(CombatUnit(factionId = 4, heroId = 12, battalionId = None)) ), reason = "Moving a good hero toward the faction leader" ) diff --git a/src/test/scala/net/eagle0/eagle/client_text/ClientTextStoreImplTest.scala b/src/test/scala/net/eagle0/eagle/client_text/ClientTextStoreImplTest.scala index 4856c65b36..d09fc6e53a 100644 --- a/src/test/scala/net/eagle0/eagle/client_text/ClientTextStoreImplTest.scala +++ b/src/test/scala/net/eagle0/eagle/client_text/ClientTextStoreImplTest.scala @@ -7,11 +7,8 @@ import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class ClientTextStoreImplTest - extends AnyFlatSpec - with MockFactory - with Matchers { - private val mockPersister = mock[Persister] +class ClientTextStoreImplTest extends AnyFlatSpec with MockFactory with Matchers { + private val mockPersister = mock[Persister] private val pregeneratedClientTextStore = PregeneratedClientTextStore( Map( "pregeneratedId1" -> "pregeneratedText1", @@ -19,7 +16,7 @@ class ClientTextStoreImplTest ) ) - private val basicStore = + private val basicStore = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, @@ -75,14 +72,13 @@ class ClientTextStoreImplTest } it should "throw if the id is pregenerated" in { - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy basicStore.withAddedTextRequest( id = "pregeneratedId1", accessibleTo = Vector(), requestedAfterHistoryCount = requestedAfterHistoryCount, llmRequest = genericLlmRequest ) - } ex.getMessage shouldBe "requirement failed: Text with id pregeneratedId1 is pregenerated" } @@ -377,7 +373,7 @@ class ClientTextStoreImplTest } "withMarkedRequested" should "move unrequested to incomplete" in { - val store = + val store = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, @@ -410,7 +406,7 @@ class ClientTextStoreImplTest } "withAppendedText" should "append text and keep incomplete if not complete" in { - val store = + val store = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, @@ -458,15 +454,14 @@ class ClientTextStoreImplTest accessibleToIsSaved = false ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy store.withAppendedText("pregeneratedId1", "new text", complete = false) - } ex.getMessage shouldBe "requirement failed: Text with id pregeneratedId1 is pregenerated" } "withAppendedText" should "append text and move to completed if marked complete" in { - val store = + val store = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, @@ -520,15 +515,14 @@ class ClientTextStoreImplTest accessibleToIsSaved = false ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy store.withAppendedText("this_id", "new text", complete = false) - } ex.getMessage shouldBe "requirement failed: Text with id this_id is already complete" } it should "return the updated aggregated text" in { - val store = + val store = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, @@ -578,15 +572,14 @@ class ClientTextStoreImplTest accessibleToIsSaved = false ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy store.withAppendedText("differentId", "new text", complete = true) - } ex.getMessage shouldBe "Text with id differentId not found" } "withExtendedVisibility" should "add the factions if there was no entry previously" in { - val store = + val store = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, @@ -605,7 +598,7 @@ class ClientTextStoreImplTest } it should "do nothing if the factions are already present" in { - val store = + val store = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, @@ -624,7 +617,7 @@ class ClientTextStoreImplTest } it should "add a faction if not already present" in { - val store = + val store = ClientTextStoreImpl( pregenerated = pregeneratedClientTextStore, persister = mockPersister, diff --git a/src/test/scala/net/eagle0/eagle/library/ActionResultFilterTest.scala b/src/test/scala/net/eagle0/eagle/library/ActionResultFilterTest.scala index 281655da98..581c70cc33 100644 --- a/src/test/scala/net/eagle0/eagle/library/ActionResultFilterTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/ActionResultFilterTest.scala @@ -4,7 +4,4 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class ActionResultFilterTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach {} +class ActionResultFilterTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach {} diff --git a/src/test/scala/net/eagle0/eagle/library/EngineImplTest.scala b/src/test/scala/net/eagle0/eagle/library/EngineImplTest.scala index 5e4ea523bb..275ac50840 100644 --- a/src/test/scala/net/eagle0/eagle/library/EngineImplTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/EngineImplTest.scala @@ -11,19 +11,15 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach //noinspection RedundantDefaultArgument -class EngineImplTest - extends AnyFlatSpec - with BeforeAndAfterEach - with MockFactory - with Matchers { +class EngineImplTest extends AnyFlatSpec with BeforeAndAfterEach with MockFactory with Matchers { private val startingHistory = Vector( ActionResult( newRoundId = Some(1), newDate = Some(Date(year = 1501, month = 6)) ) ) - private val gameId = 0xabcd123f - private val heroGenerator = mock[HeroGenerator] + private val gameId = 0xabcd123f + private val heroGenerator = mock[HeroGenerator] override def beforeEach(): Unit = {} @@ -47,13 +43,12 @@ class EngineImplTest engine.getAvailablePlayerCommands(0) val selectedCommand = ReturnSelectedCommand() - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy engine.postCommand( factionId = 0, selectedProvinceId = 5, selectedCommand = selectedCommand ) - } ex.getMessage shouldBe "requirement failed: Attempted to post a command for faction 0, but there are none" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImplTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImplTest.scala index 7b67e4c07f..54d1f07e61 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImplTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/applier/ActionResultProtoApplierImplTest.scala @@ -22,25 +22,16 @@ import net.eagle0.eagle.common.hero_backstory_version.BackstoryVersion import net.eagle0.eagle.common.profession.Profession import net.eagle0.eagle.common.province_event.{BeastsEvent, ImminentRiotEvent} import net.eagle0.eagle.common.province_order_type.ProvinceOrderType -import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{ - DEVELOP, - MOBILIZE -} +import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{DEVELOP, MOBILIZE} import net.eagle0.eagle.common.round_phase.{NewRoundPhase, RoundPhase} import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.army.Army import net.eagle0.eagle.internal.battalion.Battalion -import net.eagle0.eagle.internal.changed_faction.{ - ChangedFaction, - TrustLevelUpdate -} +import net.eagle0.eagle.internal.changed_faction.{ChangedFaction, TrustLevelUpdate} import net.eagle0.eagle.internal.changed_hero.ChangedHero import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor.VigorDelta import net.eagle0.eagle.internal.changed_province.ChangedProvince -import net.eagle0.eagle.internal.changed_province.ChangedProvince.{ - ProvinceEventsReplacement, - ProvinceOrdersOption -} +import net.eagle0.eagle.internal.changed_province.ChangedProvince.{ProvinceEventsReplacement, ProvinceOrdersOption} import net.eagle0.eagle.internal.deferred_change.BlizzardStarted import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction.Faction.OutgoingOfferRound @@ -50,25 +41,15 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.shardok_battle.ShardokBattle -import net.eagle0.eagle.library.{ - EagleInternalException, - EagleValidationException -} -import net.eagle0.eagle.library.settings.{ - ExtraXpForStatBumpOver100, - VigorToConstitutionXpMultiplier, - XpForStatBump -} +import net.eagle0.eagle.library.{EagleInternalException, EagleValidationException} +import net.eagle0.eagle.library.settings.{ExtraXpForStatBumpOver100, VigorToConstitutionXpMultiplier, XpForStatBump} import net.eagle0.eagle.library.util.validations.RuntimeValidator import net.eagle0.eagle.library.util.IDable.mapifyFactions import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class ActionResultProtoApplierImplTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ActionResultProtoApplierImplTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { import net.eagle0.common.ProtoMatchers.* override def beforeEach(): Unit = { @@ -143,9 +124,7 @@ class ActionResultProtoApplierImplTest currentPhase = RoundPhase.PLAYER_COMMANDS ) - val actionResult = ActionResult(newRoundPhase = - Some(NewRoundPhase(RoundPhase.UNAFFILIATED_HERO_ACTIONS)) - ) + val actionResult = ActionResult(newRoundPhase = Some(NewRoundPhase(RoundPhase.UNAFFILIATED_HERO_ACTIONS))) val newGameState = actionResultProtoApplier.applyActionResult( @@ -196,7 +175,7 @@ class ActionResultProtoApplierImplTest ) val changedBattalion = Battalion(id = 5, size = 800, training = 60) - val actionResult = + val actionResult = ActionResult(changedBattalions = Vector(changedBattalion)) val newGameState = @@ -233,7 +212,7 @@ class ActionResultProtoApplierImplTest val changedBattalion = Battalion(id = 5, size = 0, training = 60, `type` = LIGHT_INFANTRY) - val actionResult = + val actionResult = ActionResult(changedBattalions = Vector(changedBattalion)) val newGameState = @@ -248,7 +227,7 @@ class ActionResultProtoApplierImplTest "A result with a new battalion" should "include both battalions" in { val originalBattalion = Battalion(id = 5, size = 1000, training = 50) - val startingState = + val startingState = GameState( randomSeed = 1L, currentDate = Some(Date(year = 1501, month = 6)), @@ -268,7 +247,7 @@ class ActionResultProtoApplierImplTest newGameState.gameState.battalions shouldBe Map( originalBattalion.id + 1 -> newBattalion.withId(originalBattalion.id + 1), - originalBattalion.id -> originalBattalion + originalBattalion.id -> originalBattalion ) newGameState.gameState.provinces(13).battalionIds shouldBe Vector(5, 6) } @@ -290,7 +269,7 @@ class ActionResultProtoApplierImplTest heroes = Map(originalHero.id -> originalHero) ) - val changedHero = ChangedHero(id = originalHero.id, vigor = VigorDelta(-10)) + val changedHero = ChangedHero(id = originalHero.id, vigor = VigorDelta(-10)) val actionResult = ActionResult(changedHeroes = Vector(changedHero)) val newGameState = @@ -322,15 +301,14 @@ class ActionResultProtoApplierImplTest heroes = Map(originalHero.id -> originalHero) ) - val newHero = originalHero.copy(vigor = 60) + val newHero = originalHero.copy(vigor = 60) val actionResult = ActionResult(newHeroes = Vector(newHero)) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"requirement failed: Got a new hero update $newHero for existing hero $originalHero" } @@ -369,7 +347,7 @@ class ActionResultProtoApplierImplTest ) newGameState.gameState.heroes shouldBe Map( - changedHero.id -> changedHero, + changedHero.id -> changedHero, originalHero.id -> originalHero ) } @@ -424,12 +402,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(newHeroes = newHeroes) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: Invalid id for hero ${newHeroes.head.toString}" } @@ -445,12 +422,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(newHeroes = newHeroes) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: Invalid player id for hero ${newHeroes.head.toString}" } @@ -465,12 +441,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(changedBattalions = changedBattalions) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: Invalid id for battalion ${changedBattalions.head.toString}" } @@ -485,12 +460,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(newProvinces = changedProvinces) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: Invalid id for province ${changedProvinces.head}" } @@ -512,12 +486,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(newProvinces = changedProvinces) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: Invalid hero id in province ${changedProvinces.head}" } @@ -533,12 +506,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(newProvinces = changedProvinces) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: Invalid battalion id in province ${changedProvinces.head}" } @@ -560,12 +532,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(newProvinces = changedProvinces) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: The ruling player and ruling hero state do not match in province ${changedProvinces.head.toString}" } @@ -583,12 +554,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(newProvinces = changedProvinces) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: The ruling hero is not in the heroes list in province ${changedProvinces.head.toString}" } @@ -657,8 +627,7 @@ class ActionResultProtoApplierImplTest val startingState = GameState( randomSeed = 1L, currentDate = Some(Date(year = 1501, month = 6)), - heroes = - Vector(6, 7, 8).map(h => h -> Hero(id = h, factionId = Some(5))).toMap, + heroes = Vector(6, 7, 8).map(h => h -> Hero(id = h, factionId = Some(5))).toMap, battalions = Vector(9, 10).map(b => b -> Battalion(id = b)).toMap, provinces = Map( 7 -> Province( @@ -728,12 +697,11 @@ class ActionResultProtoApplierImplTest val actionResult = ActionResult(provinceActed = Some(0)) - val ex = the[EagleValidationException] thrownBy { + val ex = the[EagleValidationException] thrownBy actionResultProtoApplier.applyActionResult( startingState, actionResult ) - } ex.getMessage shouldBe s"validation failed: Invalid acted province id in action result ${actionResult.toString}" } @@ -741,14 +709,14 @@ class ActionResultProtoApplierImplTest "A result with a new faction" should "add the faction to the map" in { val existingFaction = Faction(id = 1, factionHeadId = 3, name = "Joe's Faction") - val startingState = + val startingState = GameState( randomSeed = 1L, currentDate = Some(Date(year = 1501, month = 6)), factions = Map(existingFaction.id -> existingFaction) ) - val newFaction = Faction(id = 2, factionHeadId = 7, name = "Jane's Faction") + val newFaction = Faction(id = 2, factionHeadId = 7, name = "Jane's Faction") val actionResult = ActionResult(newFactions = Vector(newFaction)) val awrs = @@ -758,7 +726,7 @@ class ActionResultProtoApplierImplTest ) awrs.gameState.factions shouldBe Map( existingFaction.id -> existingFaction, - newFaction.id -> newFaction + newFaction.id -> newFaction ) } @@ -767,7 +735,7 @@ class ActionResultProtoApplierImplTest Faction(id = 1, factionHeadId = 3, name = "Joe's Faction") val existingFaction2 = Faction(id = 3, factionHeadId = 7, name = "Jane's Faction") - val startingState = GameState( + val startingState = GameState( randomSeed = 1L, currentDate = Some(Date(year = 1501, month = 6)), factions = Map( @@ -777,7 +745,7 @@ class ActionResultProtoApplierImplTest ) val changedFaction = ChangedFaction(id = 1, newFactionHeadId = Some(87)) - val actionResult = ActionResult(changedFactions = Vector(changedFaction)) + val actionResult = ActionResult(changedFactions = Vector(changedFaction)) val awrs = actionResultProtoApplier.applyActionResult( @@ -786,7 +754,7 @@ class ActionResultProtoApplierImplTest ) awrs.gameState.factions shouldBe Map( existingFaction2.id -> existingFaction2, - changedFaction.id -> existingFaction1.withFactionHeadId(87) + changedFaction.id -> existingFaction1.withFactionHeadId(87) ) } @@ -809,8 +777,7 @@ class ActionResultProtoApplierImplTest Vector( ChangedFaction( id = 7, - trustLevelUpdates = - Vector(TrustLevelUpdate(targetFactionId = 1, delta = 25)) + trustLevelUpdates = Vector(TrustLevelUpdate(targetFactionId = 1, delta = 25)) ) ) ) @@ -846,8 +813,7 @@ class ActionResultProtoApplierImplTest Vector( ChangedFaction( id = 7, - trustLevelUpdates = - Vector(TrustLevelUpdate(targetFactionId = 5, delta = -10)) + trustLevelUpdates = Vector(TrustLevelUpdate(targetFactionId = 5, delta = -10)) ) ) ) @@ -876,8 +842,7 @@ class ActionResultProtoApplierImplTest Faction(id = 1), Faction( id = 7, - factionRelationships = - Vector(FactionRelationship(targetFactionId = 1, trustValue = 94)) + factionRelationships = Vector(FactionRelationship(targetFactionId = 1, trustValue = 94)) ) ) ) @@ -886,8 +851,7 @@ class ActionResultProtoApplierImplTest Vector( ChangedFaction( id = 7, - trustLevelUpdates = - Vector(TrustLevelUpdate(targetFactionId = 1, delta = 25)) + trustLevelUpdates = Vector(TrustLevelUpdate(targetFactionId = 1, delta = 25)) ) ) ) @@ -928,8 +892,8 @@ class ActionResultProtoApplierImplTest currentDate = Some(Date(year = 1501, month = 6)), battalions = Map( 10 -> Battalion(id = 10), - 5 -> Battalion(id = 5), - 7 -> Battalion(id = 7) + 5 -> Battalion(id = 5), + 7 -> Battalion(id = 7) ) ) @@ -998,19 +962,19 @@ class ActionResultProtoApplierImplTest currentDate = Some(Date(year = 1501, month = 6)), provinces = Map(7 -> province), heroes = Map( - 4 -> Hero( + 4 -> Hero( id = 4, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 4 ), - 5 -> Hero( + 5 -> Hero( id = 5, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 5 ), - 9 -> Hero( + 9 -> Hero( id = 9, factionId = Some(3), profession = Profession.MAGE, @@ -1022,7 +986,7 @@ class ActionResultProtoApplierImplTest profession = Profession.NO_PROFESSION, wisdom = 11 ), - 8 -> Hero( + 8 -> Hero( id = 8, factionId = None, profession = Profession.NO_PROFESSION, @@ -1071,19 +1035,19 @@ class ActionResultProtoApplierImplTest currentDate = Some(Date(year = 1501, month = 6)), provinces = Map(7 -> province), heroes = Map( - 4 -> Hero( + 4 -> Hero( id = 4, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 4 ), - 5 -> Hero( + 5 -> Hero( id = 5, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 5 ), - 9 -> Hero( + 9 -> Hero( id = 9, factionId = Some(3), profession = Profession.MAGE, @@ -1095,7 +1059,7 @@ class ActionResultProtoApplierImplTest profession = Profession.NO_PROFESSION, wisdom = 11 ), - 8 -> Hero( + 8 -> Hero( id = 8, factionId = None, profession = Profession.NO_PROFESSION, @@ -1111,8 +1075,7 @@ class ActionResultProtoApplierImplTest Vector( ChangedProvince( id = 7, - newProvinceEvents = - Some(ProvinceEventsReplacement(newEvents = Vector.empty)) + newProvinceEvents = Some(ProvinceEventsReplacement(newEvents = Vector.empty)) ) ) ) @@ -1141,19 +1104,19 @@ class ActionResultProtoApplierImplTest currentDate = Some(Date(month = 7, year = 225)), provinces = Map(7 -> province), heroes = Map( - 4 -> Hero( + 4 -> Hero( id = 4, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 4 ), - 5 -> Hero( + 5 -> Hero( id = 5, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 5 ), - 9 -> Hero( + 9 -> Hero( id = 9, factionId = Some(3), profession = Profession.MAGE, @@ -1165,7 +1128,7 @@ class ActionResultProtoApplierImplTest profession = Profession.NO_PROFESSION, wisdom = 11 ), - 8 -> Hero( + 8 -> Hero( id = 8, factionId = None, profession = Profession.NO_PROFESSION, @@ -1216,19 +1179,19 @@ class ActionResultProtoApplierImplTest currentDate = Some(Date(month = 7, year = 225)), provinces = Map(7 -> province), heroes = Map( - 4 -> Hero( + 4 -> Hero( id = 4, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 4 ), - 5 -> Hero( + 5 -> Hero( id = 5, factionId = Some(3), profession = Profession.NO_PROFESSION, wisdom = 5 ), - 9 -> Hero( + 9 -> Hero( id = 9, factionId = Some(3), profession = Profession.MAGE, @@ -1240,7 +1203,7 @@ class ActionResultProtoApplierImplTest profession = Profession.NO_PROFESSION, wisdom = 11 ), - 8 -> Hero( + 8 -> Hero( id = 8, factionId = None, profession = Profession.NO_PROFESSION, @@ -1322,8 +1285,7 @@ class ActionResultProtoApplierImplTest Faction(id = 3), Faction( id = 4, - lastOutgoingTruceOfferRounds = - Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) + lastOutgoingTruceOfferRounds = Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) ) ), currentRoundId = 19 @@ -1407,8 +1369,7 @@ class ActionResultProtoApplierImplTest Faction(id = 3), Faction( id = 4, - lastOutgoingInvitationRounds = - Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) + lastOutgoingInvitationRounds = Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) ) ), currentRoundId = 19 @@ -1495,8 +1456,7 @@ class ActionResultProtoApplierImplTest Faction(id = 3), Faction( id = 4, - lastOutgoingRansomOfferRounds = - Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) + lastOutgoingRansomOfferRounds = Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) ) ), currentRoundId = 19 @@ -1582,8 +1542,7 @@ class ActionResultProtoApplierImplTest Faction(id = 3), Faction( id = 4, - lastOutgoingAllianceOfferRounds = - Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) + lastOutgoingAllianceOfferRounds = Vector(OutgoingOfferRound(toFactionId = 3, roundId = 3)) ) ), currentRoundId = 19 @@ -1632,7 +1591,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.strength shouldBe 54 @@ -1652,7 +1611,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.agility shouldBe 54 @@ -1672,7 +1631,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.wisdom shouldBe 54 @@ -1692,7 +1651,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.charisma shouldBe 54 @@ -1712,7 +1671,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.constitution shouldBe 54 @@ -1732,7 +1691,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.charisma shouldBe 100 @@ -1752,7 +1711,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.charisma shouldBe 102 @@ -1772,7 +1731,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.charisma shouldBe 102 @@ -1792,7 +1751,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.constitution shouldBe 63 @@ -1812,7 +1771,7 @@ class ActionResultProtoApplierImplTest heroes = Map(hero.id -> hero) ) - val after = gs.applyChangedHero(changedHero, Date(6, 1)) + val after = gs.applyChangedHero(changedHero, Date(6, 1)) val afterHero = after.heroes(19) afterHero.constitution shouldBe 64 diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactoryTest.scala index bd8c5ff0e5..19edd79ffb 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAlmsCommandFactoryTest.scala @@ -11,23 +11,20 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableAlmsCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableAlmsCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { MaxAlmsFood.setIntValue(1000) MinVigorForAlms.setDoubleValue(20) } - private val factionId = 7 + private val factionId = 7 private val factionHeadId = 12 private val leaderProvinceId = 9 - private val factionLeader = + private val factionLeader = Hero(id = factionHeadId, factionId = Some(factionId), vigor = 50) - private val leaderProvince = Province( + private val leaderProvince = Province( id = 9, rulingFactionId = Some(factionId), rulingHeroId = Some(factionHeadId), @@ -68,7 +65,7 @@ class AvailableAlmsCommandFactoryTest private val extraProvinceGameState = gameState .update( - _.provinces(extraProvince.id) := extraProvince, + _.provinces(extraProvince.id) := extraProvince, _.heroes(extraProvinceVassal1.id) := extraProvinceVassal1 ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactoryTest.scala index 46927bf878..fd1ed58012 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableApprehendOutlawCommandFactoryTest.scala @@ -26,10 +26,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableApprehendOutlawCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableApprehendOutlawCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { MinVigorForApprehendOutlaw.setDoubleValue(50) @@ -48,8 +45,7 @@ class AvailableApprehendOutlawCommandFactoryTest heroId = 19, `type` = UNAFFILIATED_HERO_OUTLAW, lastFaction = Some(3), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) private val outlaw2 = @@ -57,26 +53,24 @@ class AvailableApprehendOutlawCommandFactoryTest heroId = 20, `type` = UNAFFILIATED_HERO_OUTLAW, lastFaction = Some(4), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) private val resident = UnaffiliatedHero( heroId = 21, `type` = UNAFFILIATED_HERO_RESIDENT, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_NOT_DIVINED)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_NOT_DIVINED)) ) - private val outlaw1Hero = Hero(id = outlaw1.heroId) - private val outlaw2Hero = Hero(id = outlaw2.heroId) + private val outlaw1Hero = Hero(id = outlaw1.heroId) + private val outlaw2Hero = Hero(id = outlaw2.heroId) private val residentHero = Hero(id = resident.heroId) private val uhHeroes = Vector(outlaw1Hero, outlaw2Hero, residentHero) private val notTiredHero = Hero(id = 1, factionId = Some(fid), vigor = 80) - private val tiredHero = Hero(id = 2, factionId = Some(fid), vigor = 10) + private val tiredHero = Hero(id = 2, factionId = Some(fid), vigor = 10) private val residentHeroes = Vector(notTiredHero, tiredHero) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactoryTest.scala index d45513d07d..ec20246f04 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableArmTroopsCommandFactoryTest.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.ArmamentCost import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - LIGHT_INFANTRY, - LONGBOWMEN -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{LIGHT_INFANTRY, LONGBOWMEN} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province @@ -14,10 +11,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableArmTroopsCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableArmTroopsCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val rulingFactionId = 5 private val lowArmamentBattalion = @@ -37,7 +31,7 @@ class AvailableArmTroopsCommandFactoryTest ) private val lightInfantryBaseCost = 0.01 - private val longbowmenBaseCost = 0.03 + private val longbowmenBaseCost = 0.03 private val battalionTypes = Vector( BattalionType( @@ -71,8 +65,9 @@ class AvailableArmTroopsCommandFactoryTest val command = AvailableArmTroopsCommandFactory.availableCommand( gameState = startingState .update( - _.battalions.modify(_.map { case (bid, batt) => - (bid, batt.withSize(0)) + _.battalions.modify(_.map { + case (bid, batt) => + (bid, batt.withSize(0)) }) ), factionId = rulingFactionId, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactoryTest.scala index c418f9d68c..5daa0d8ced 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableAttackDecisionCommandFactoryTest.scala @@ -12,13 +12,7 @@ import net.eagle0.eagle.api.command.util.attack_decision_type.{ import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.tribute_amount.TributeAmount -import net.eagle0.eagle.internal.army.{ - Army, - Attacking, - AwaitingDecision, - HostileArmyGroup, - MovingArmy -} +import net.eagle0.eagle.internal.army.{Army, Attacking, AwaitingDecision, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship @@ -36,12 +30,9 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableAttackDecisionCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val attackerFid: FactionId = 3 - private val defenderFid: FactionId = 4 +class AvailableAttackDecisionCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val attackerFid: FactionId = 3 + private val defenderFid: FactionId = 4 private val currentRoundId: RoundId = 27 private val incomingArmy: HostileArmyGroup = HostileArmyGroup( @@ -317,7 +308,7 @@ class AvailableAttackDecisionCommandFactoryTest ) ) ), - _.battalions(372) := Battalion(size = 120), + _.battalions(372) := Battalion(size = 120), _.factions(attackerFid).factionRelationships :+= FactionRelationship( targetFactionId = anotherAttackerFid, @@ -372,14 +363,13 @@ class AvailableAttackDecisionCommandFactoryTest _.battalions(372) := Battalion(size = 120) ) - val exception = the[EagleInternalException] thrownBy { + val exception = the[EagleInternalException] thrownBy AvailableAttackDecisionCommandFactory .availableCommand( gameState = gameStateWithAnotherIncomingArmy, factionId = attackerFid, provinceId = defenderProvince.id ) - } exception.getMessage shouldBe s"requirement failed: Incoming armies in attack decision phase are not mutually allied in province ${defenderProvince.id}" } @@ -471,7 +461,7 @@ class AvailableAttackDecisionCommandFactoryTest Neighbor(provinceId = 18), Neighbor(provinceId = 818) ), - _.provinces :+= 18 -> Province( + _.provinces :+= 18 -> Province( id = 18, rulingFactionId = Some(attackerFid), rulingHeroId = Some(30), @@ -479,7 +469,7 @@ class AvailableAttackDecisionCommandFactoryTest hostileArmies = Vector.empty, neighbors = Vector(Neighbor(provinceId = defenderProvince.id)) ), - _.provinces :+= 818 -> Province( + _.provinces :+= 818 -> Province( id = 818, rulingFactionId = None, hostileArmies = Vector.empty, @@ -517,7 +507,7 @@ class AvailableAttackDecisionCommandFactoryTest Neighbor(provinceId = 18), Neighbor(provinceId = 818) ), - _.provinces :+= 18 -> Province( + _.provinces :+= 18 -> Province( id = 18, rulingFactionId = Some(defenderFid), rulingHeroId = Some(30), @@ -525,7 +515,7 @@ class AvailableAttackDecisionCommandFactoryTest hostileArmies = Vector.empty, neighbors = Vector(Neighbor(provinceId = defenderProvince.id)) ), - _.provinces :+= 818 -> Province( + _.provinces :+= 818 -> Province( id = 818, rulingFactionId = None, hostileArmies = Vector.empty, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactoryTest.scala index 485ccbb566..ded9de71d7 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableCommandsFactoryTest.scala @@ -2,62 +2,40 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.* import net.eagle0.eagle.api.command.OneProvinceAvailableCommands -import net.eagle0.eagle.api.selected_command.{ - ImproveSelectedCommand, - MarchSelectedCommand, - TrainSelectedCommand -} +import net.eagle0.eagle.api.selected_command.{ImproveSelectedCommand, MarchSelectedCommand, TrainSelectedCommand} import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.improvement_type.ImprovementType.AGRICULTURE import net.eagle0.eagle.common.province_event.ImminentRiotEvent -import net.eagle0.eagle.common.round_phase.RoundPhase.{ - DEFENSE_DECISION, - HANDLE_RIOT, - PLAYER_COMMANDS -} -import net.eagle0.eagle.internal.army.{ - Army, - AwaitingDecision, - HostileArmyGroup, - MovingArmy -} +import net.eagle0.eagle.common.round_phase.RoundPhase.{DEFENSE_DECISION, HANDLE_RIOT, PLAYER_COMMANDS} +import net.eagle0.eagle.internal.army.{Army, AwaitingDecision, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.TRUCE import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - FeastGoldCostPerHero, - MinVigorForImprove, - RiotMaxFood, - RiotMaxGold -} +import net.eagle0.eagle.library.settings.{FeastGoldCostPerHero, MinVigorForImprove, RiotMaxFood, RiotMaxGold} import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyProvinces} import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableCommandsFactoryTest - extends AnyFlatSpec - with Matchers - with MockFactory - with BeforeAndAfterEach { - private val mockTraveling1 = mock[AvailableCommandsFactoryForType] - private val mockTraveling2 = mock[AvailableCommandsFactoryForType] +class AvailableCommandsFactoryTest extends AnyFlatSpec with Matchers with MockFactory with BeforeAndAfterEach { + private val mockTraveling1 = mock[AvailableCommandsFactoryForType] + private val mockTraveling2 = mock[AvailableCommandsFactoryForType] private val mockFreeForAllDecisionTier = mock[AvailableCommandsFactoryForType] - private val mockAttackDecisionTier = mock[AvailableCommandsFactoryForType] - private val mockDefenseTier = mock[AvailableCommandsFactoryForType] - private val mockCommandsTier1 = mock[AvailableCommandsFactoryForType] - private val mockCommandsTier2 = mock[AvailableCommandsFactoryForType] + private val mockAttackDecisionTier = mock[AvailableCommandsFactoryForType] + private val mockDefenseTier = mock[AvailableCommandsFactoryForType] + private val mockCommandsTier1 = mock[AvailableCommandsFactoryForType] + private val mockCommandsTier2 = mock[AvailableCommandsFactoryForType] - private val factionId = 6 - private val provinceId = 8 - private val factionHeadId = 14 - private val firstSwordBrotherId = 97 + private val factionId = 6 + private val provinceId = 8 + private val factionHeadId = 14 + private val firstSwordBrotherId = 97 private val secondSwornBrotherId = 15 - private val vassalId = 16 - private val gameState = GameState( + private val vassalId = 16 + private val gameState = GameState( currentRoundId = 13, currentPhase = PLAYER_COMMANDS, provinces = Map( @@ -111,12 +89,12 @@ class AvailableCommandsFactoryTest } "AvailableCommandsFactory.suggestedProvinceId" should "return a province that last acted this round" in { - val provinceRuledByFirstSwornBrother = Province( + val provinceRuledByFirstSwornBrother = Province( id = 23, rulingFactionId = Some(factionId), rulingHeroId = Some(firstSwordBrotherId) ) - val provinceRuledByFactionHead = Province( + val provinceRuledByFactionHead = Province( id = 9, rulingFactionId = Some(factionId), rulingHeroId = Some(factionHeadId) @@ -151,7 +129,7 @@ class AvailableCommandsFactoryTest factionId, Map( 23 -> OneProvinceAvailableCommands(provinceId = 23), - 9 -> OneProvinceAvailableCommands(provinceId = 9), + 9 -> OneProvinceAvailableCommands(provinceId = 9), 11 -> OneProvinceAvailableCommands(provinceId = 11) ), gs @@ -159,12 +137,12 @@ class AvailableCommandsFactoryTest } it should "return a province that is under attack if no province has acted" in { - val provinceRuledByFirstSwornBrother = Province( + val provinceRuledByFirstSwornBrother = Province( id = 23, rulingFactionId = Some(factionId), rulingHeroId = Some(firstSwordBrotherId) ) - val provinceRuledByFactionHead = Province( + val provinceRuledByFactionHead = Province( id = 9, rulingFactionId = Some(factionId), rulingHeroId = Some(factionHeadId) @@ -198,7 +176,7 @@ class AvailableCommandsFactoryTest factionId, Map( 23 -> OneProvinceAvailableCommands(provinceId = 23), - 9 -> OneProvinceAvailableCommands(provinceId = 9), + 9 -> OneProvinceAvailableCommands(provinceId = 9), 11 -> OneProvinceAvailableCommands(provinceId = 11) ), gs @@ -206,12 +184,12 @@ class AvailableCommandsFactoryTest } it should "return the province led by the most senior faction leader" in { - val provinceRuledByFirstSwornBrother = Province( + val provinceRuledByFirstSwornBrother = Province( id = 23, rulingFactionId = Some(factionId), rulingHeroId = Some(firstSwordBrotherId) ) - val provinceRuledByFactionHead = Province( + val provinceRuledByFactionHead = Province( id = 9, rulingFactionId = Some(factionId), rulingHeroId = Some(factionHeadId) @@ -242,7 +220,7 @@ class AvailableCommandsFactoryTest factionId, Map( 23 -> OneProvinceAvailableCommands(provinceId = 23), - 9 -> OneProvinceAvailableCommands(provinceId = 9), + 9 -> OneProvinceAvailableCommands(provinceId = 9), 11 -> OneProvinceAvailableCommands(provinceId = 11) ), gs @@ -250,12 +228,12 @@ class AvailableCommandsFactoryTest } it should "not count a province as under attack if the army arrives later" in { - val provinceRuledByFirstSwornBrother = Province( + val provinceRuledByFirstSwornBrother = Province( id = 23, rulingFactionId = Some(factionId), rulingHeroId = Some(firstSwordBrotherId) ) - val provinceRuledByFactionHead = Province( + val provinceRuledByFactionHead = Province( id = 9, rulingFactionId = Some(factionId), rulingHeroId = Some(factionHeadId) @@ -289,7 +267,7 @@ class AvailableCommandsFactoryTest factionId, Map( 23 -> OneProvinceAvailableCommands(provinceId = 23), - 9 -> OneProvinceAvailableCommands(provinceId = 9), + 9 -> OneProvinceAvailableCommands(provinceId = 9), 11 -> OneProvinceAvailableCommands(provinceId = 11) ), gs @@ -398,7 +376,7 @@ class AvailableCommandsFactoryTest suggestedCommandIndex = 0, commands = Vector(restCommand, goToWarCommand) ), - 12 -> OneProvinceAvailableCommands( + 12 -> OneProvinceAvailableCommands( provinceId = 12, suggestedCommandIndex = 0, commands = Vector(secondProvinceRestCommand) @@ -409,8 +387,9 @@ class AvailableCommandsFactoryTest it should "return only the traveling commands if the province is in travel state" in { val provinceTravelGameState = gameState .withProvinces( - gameState.provinces.map { case (k, v) => - k -> v.withRulerIsTraveling(true) + gameState.provinces.map { + case (k, v) => + k -> v.withRulerIsTraveling(true) } ) @@ -553,8 +532,7 @@ class AvailableCommandsFactoryTest army = Some( Army( factionId = hostileFactionId, - units = - Vector(CombatUnit(factionId = hostileFactionId, heroId = 51)) + units = Vector(CombatUnit(factionId = hostileFactionId, heroId = 51)) ) ) ) @@ -565,7 +543,7 @@ class AvailableCommandsFactoryTest gameState.provinces(provinceId).withHostileArmies(Vector(hostileArmy)) val gsWithIA = gameState.update( - _.provinces(provinceId) := provinceWithIA, + _.provinces(provinceId) := provinceWithIA, _.factions(hostileFactionId) := Faction(id = hostileFactionId) ) @@ -602,8 +580,7 @@ class AvailableCommandsFactoryTest army = Some( Army( factionId = alliedFactionId, - units = - Vector(CombatUnit(factionId = alliedFactionId, heroId = 51)) + units = Vector(CombatUnit(factionId = alliedFactionId, heroId = 51)) ) ) ) @@ -614,7 +591,7 @@ class AvailableCommandsFactoryTest gameState.provinces(provinceId).withHostileArmies(Vector(alliedArmy)) val gsWithIA = gameState.update( - _.provinces(provinceId) := provinceWithIA, + _.provinces(provinceId) := provinceWithIA, _.factions(alliedFactionId) := Faction( id = alliedFactionId, factionRelationships = Vector( @@ -668,11 +645,10 @@ class AvailableCommandsFactoryTest gameState.provinces(provinceId).withIncomingArmies(Vector(alliedArmy)) val gsWithIA = gameState.update( - _.provinces(provinceId) := provinceWithIA, + _.provinces(provinceId) := provinceWithIA, _.factions(alliedFactionId) := Faction( id = alliedFactionId, - factionRelationships = - Vector(FactionRelationship(targetFactionId = factionId)) + factionRelationships = Vector(FactionRelationship(targetFactionId = factionId)) ), _.factions(factionId).factionRelationships :+= FactionRelationship( targetFactionId = alliedFactionId, @@ -693,7 +669,7 @@ class AvailableCommandsFactoryTest "handle riot command phase" should "return commands for a faction leader province with an imminent riot" in { val gsWithRiot = gameState.update( _.provinces(provinceId).activeEvents := Vector(ImminentRiotEvent()), - _.currentPhase := HANDLE_RIOT + _.currentPhase := HANDLE_RIOT ) val cmds = factory.availablePlayerCommands(gsWithRiot, factionId) @@ -710,7 +686,7 @@ class AvailableCommandsFactoryTest val gsWithRiotWithoutFactionLeader = gameState.update( _.provinces(provinceId).rulingHeroId := 273, _.provinces(provinceId).activeEvents := Vector(ImminentRiotEvent()), - _.currentPhase := HANDLE_RIOT + _.currentPhase := HANDLE_RIOT ) val cmds = diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactoryTest.scala index 45291872c6..fe91f66760 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableControlWeatherCommandsFactoryTest.scala @@ -20,28 +20,24 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableControlWeatherCommandsFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableControlWeatherCommandsFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val minVigor: Int = 60 - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForControlWeather.setDoubleValue(minVigor) - } - private val actingPid: ProvinceId = 19 - private val actingFid: FactionId = 7 + private val actingPid: ProvinceId = 19 + private val actingFid: FactionId = 7 private val neighborPids: Vector[ProvinceId] = Vector(3, 7, 28) - private val mage1: Hero = + private val mage1: Hero = Hero(id = 29, profession = Profession.MAGE, vigor = 90) - private val mage2: Hero = + private val mage2: Hero = Hero(id = 98, profession = Profession.MAGE, vigor = 90) private val tiredMage: Hero = Hero(id = 12, profession = Profession.MAGE, vigor = 40) - private val notMage: Hero = Hero(id = 3, vigor = 90) + private val notMage: Hero = Hero(id = 3, vigor = 90) private val actingProvince = Province( id = actingPid, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactoryTest.scala index 7d86920611..5ecdd26a0c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDeclineQuestCommandsFactoryTest.scala @@ -13,21 +13,15 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.views.hero_view.HeroView import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.Inside.inside -class AvailableDeclineQuestCommandsFactoryTest - extends AnyFlatSpec - with Matchers { +class AvailableDeclineQuestCommandsFactoryTest extends AnyFlatSpec with Matchers { private val actingFactionId = 3 - private val provinceId = 7 + private val provinceId = 7 private val gameState = GameState( gameId = 0xdead, @@ -75,7 +69,7 @@ class AvailableDeclineQuestCommandsFactoryTest "availableCommand" should "return None when the province is not ruled by the faction leader" in { val gsWithoutLeaderInCharge = gameState.update( - _.provinces(provinceId).rulingHeroId := 11, + _.provinces(provinceId).rulingHeroId := 11, _.provinces(provinceId).rulingFactionHeroIds := Vector(11) ) @@ -147,9 +141,10 @@ class AvailableDeclineQuestCommandsFactoryTest actingProvinceId should equal(provinceId) declinableHeroes should have size 1 - inside(declinableHeroes.head.hero.get) { case hv: HeroView => - hv.id should equal(100) - hv.factionId should equal(None) + inside(declinableHeroes.head.hero.get) { + case hv: HeroView => + hv.id should equal(100) + hv.factionId should equal(None) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactoryTest.scala index 805a3ffe81..959153563d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDefendCommandsFactoryTest.scala @@ -2,36 +2,21 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.{FactionId, RoundId} import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_INFANTRY, - LIGHT_CAVALRY, - LIGHT_INFANTRY -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_INFANTRY, LIGHT_CAVALRY, LIGHT_INFANTRY} import net.eagle0.eagle.common.combat_unit.CombatUnit -import net.eagle0.eagle.internal.army.{ - Army, - Attacking, - HostileArmyGroup, - MovingArmy -} +import net.eagle0.eagle.internal.army.{Army, Attacking, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.{Neighbor, Province} -import net.eagle0.eagle.library.settings.{ - MaxCombatUnitCountPerSide, - MinVigorForDefend -} +import net.eagle0.eagle.library.settings.{MaxCombatUnitCountPerSide, MinVigorForDefend} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach //noinspection RedundantDefaultArgument -class AvailableDefendCommandsFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableDefendCommandsFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { val actingFactionId = 2 private val battalionTypes = Vector( @@ -52,7 +37,7 @@ class AvailableDefendCommandsFactoryTest ) ) - private val sufficientVigorHeroes = Vector( + private val sufficientVigorHeroes = Vector( Hero(id = 9, vigor = 50, factionId = Some(actingFactionId)), Hero(id = 10, vigor = 60, factionId = Some(actingFactionId)) ) @@ -61,7 +46,7 @@ class AvailableDefendCommandsFactoryTest Hero(id = 4, vigor = 35, factionId = Some(actingFactionId)) ) - private val validBattalions = Vector( + private val validBattalions = Vector( Battalion(id = 11, size = 3) ) private val invalidBattalions = Vector( @@ -71,12 +56,11 @@ class AvailableDefendCommandsFactoryTest private val defendingProvince = Province( id = 7, rulingFactionId = Some(actingFactionId), - rulingFactionHeroIds = - (sufficientVigorHeroes ++ insufficientVigorHeroes).map(_.id), + rulingFactionHeroIds = (sufficientVigorHeroes ++ insufficientVigorHeroes).map(_.id), battalionIds = (validBattalions ++ invalidBattalions).map(_.id) ) - private val attackingFid: FactionId = 8 + private val attackingFid: FactionId = 8 private def movingArmyWithArrivalRound(arrivalRound: RoundId) = MovingArmy( originProvince = 6, destinationProvince = 7, @@ -108,7 +92,7 @@ class AvailableDefendCommandsFactoryTest private val currentRoundId = 22 - private val movingArmy = movingArmyWithArrivalRound(currentRoundId) + private val movingArmy = movingArmyWithArrivalRound(currentRoundId) private val attackingArmy = HostileArmyGroup( status = Attacking(), factionId = attackingFid, @@ -118,8 +102,7 @@ class AvailableDefendCommandsFactoryTest private val gameStateWithoutProvince = GameState( currentRoundId = currentRoundId, heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), - battalions = - BattalionMap(validBattalions ++ invalidBattalions ++ hostileBattalions), + battalions = BattalionMap(validBattalions ++ invalidBattalions ++ hostileBattalions), factions = Map(actingFactionId -> Faction(id = actingFactionId)), battalionTypes = battalionTypes ) @@ -136,7 +119,7 @@ class AvailableDefendCommandsFactoryTest 7 -> defendingProvince.clearHostileArmies ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -153,7 +136,7 @@ class AvailableDefendCommandsFactoryTest .withIncomingArmies(Vector(movingArmy.withArrivalRound(24))) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -169,7 +152,7 @@ class AvailableDefendCommandsFactoryTest 7 -> defendingProvince.withHostileArmies(Vector(attackingArmy)) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -185,7 +168,7 @@ class AvailableDefendCommandsFactoryTest 7 -> defendingProvince.withHostileArmies(Vector(attackingArmy)) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -202,7 +185,7 @@ class AvailableDefendCommandsFactoryTest 7 -> defendingProvince.withHostileArmies(Vector(attackingArmy)) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -218,7 +201,7 @@ class AvailableDefendCommandsFactoryTest 7 -> defendingProvince.withHostileArmies(Vector(attackingArmy)) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -240,7 +223,7 @@ class AvailableDefendCommandsFactoryTest .withRulingFactionHeroIds(insufficientVigorHeroes.map(_.id)) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -255,7 +238,7 @@ class AvailableDefendCommandsFactoryTest Map( 7 -> defendingProvince.update( _.hostileArmies := Vector(attackingArmy), - _.neighbors := Vector(4, 6, 8, 9) + _.neighbors := Vector(4, 6, 8, 9) .map(pid => Neighbor(provinceId = pid)) ), 6 -> Province( @@ -270,7 +253,7 @@ class AvailableDefendCommandsFactoryTest ) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -280,7 +263,7 @@ class AvailableDefendCommandsFactoryTest 9, // own province 8, // empty province 4, // attacker - 6 // attacker + 6 // attacker ) } @@ -290,7 +273,7 @@ class AvailableDefendCommandsFactoryTest Map( 7 -> defendingProvince.update( _.hostileArmies := Vector(attackingArmy), - _.neighbors := Vector(4, 6, 8, 9) + _.neighbors := Vector(4, 6, 8, 9) .map(pid => Neighbor(provinceId = pid)) ), 6 -> Province( @@ -305,7 +288,7 @@ class AvailableDefendCommandsFactoryTest ) ) ) - val command = AvailableDefendCommandsFactory.availableCommand( + val command = AvailableDefendCommandsFactory.availableCommand( gameState, actingFactionId, 7 @@ -321,7 +304,7 @@ class AvailableDefendCommandsFactoryTest 7 -> defendingProvince.withHostileArmies(Vector(attackingArmy)) ) ) - val command = AvailableDefendCommandsFactory + val command = AvailableDefendCommandsFactory .availableCommand( gameState, actingFactionId, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactoryTest.scala index 7d901fa6e9..58ae872afb 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDiplomacyCommandsFactoryTest.scala @@ -38,21 +38,14 @@ import net.eagle0.eagle.library.settings.{ PrestigePerSupportedProvince, TruceGoldCost } -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableDiplomacyCommandsFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableDiplomacyCommandsFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val actingFid = 3 + private val actingFid = 3 private val actingProvinceId = 7 private val gameState = GameState( @@ -211,7 +204,7 @@ class AvailableDiplomacyCommandsFactoryTest diploCmd.options.foreach { case TruceOption(targetFactionId, _, _ /* uknownFieldSet */ ) => targetFactionId should not be 5 - case _ => + case _ => } } @@ -342,7 +335,7 @@ class AvailableDiplomacyCommandsFactoryTest it should "not include an invite option before the inviting faction's earliest possible round" in { val gameStateWithInvitationRestriction = gameState.update( _.factions(actingFid).earliestRoundForInvitation := 35, - _.currentRoundId := 34 + _.currentRoundId := 34 ) AvailableDiplomacyCommandsFactory @@ -364,7 +357,7 @@ class AvailableDiplomacyCommandsFactoryTest it should "include an invite option on the inviting faction's earliest possible round" in { val gameStateWithInvitationRestriction = gameState.update( _.factions(actingFid).earliestRoundForInvitation := 35, - _.currentRoundId := 35 + _.currentRoundId := 35 ) val diploCmd = AvailableDiplomacyCommandsFactory @@ -402,7 +395,7 @@ class AvailableDiplomacyCommandsFactoryTest dipOpt match { case InvitationOption(targetFactionId, _, _ /* uknownFieldSet */ ) => targetFactionId == 4 - case _ => false + case _ => false } ) shouldBe false } @@ -426,8 +419,7 @@ class AvailableDiplomacyCommandsFactoryTest it should "not include an invite command if you don't have more provinces" in { val diploCmd = AvailableDiplomacyCommandsFactory .availableCommand( - gameState = - gameState.update(_.provinces(8).optionalRulingFactionId := None), + gameState = gameState.update(_.provinces(8).optionalRulingFactionId := None), factionId = actingFid, provinceId = actingProvinceId ) @@ -442,8 +434,7 @@ class AvailableDiplomacyCommandsFactoryTest it should "not include an invite command if there is no clear path from the inviter to the invitee" in { val diploCmd = AvailableDiplomacyCommandsFactory .availableCommand( - gameState = - gameState.update(_.provinces(20).optionalRulingFactionId := Some(80)), + gameState = gameState.update(_.provinces(20).optionalRulingFactionId := Some(80)), factionId = actingFid, provinceId = actingProvinceId ) @@ -476,14 +467,14 @@ class AvailableDiplomacyCommandsFactoryTest val diploCmd = AvailableDiplomacyCommandsFactory .availableCommand( gameState = gameState.update( - _.provinces(20).optionalRulingFactionId := Some(4), + _.provinces(20).optionalRulingFactionId := Some(4), _.factions(actingFid).factionRelationships := Vector( FactionRelationship( targetFactionId = 4, relationshipLevel = ALLY ) ), - _.factions(4).factionRelationships := Vector( + _.factions(4).factionRelationships := Vector( FactionRelationship( targetFactionId = actingFid, relationshipLevel = ALLY @@ -545,8 +536,8 @@ class AvailableDiplomacyCommandsFactoryTest it should "return nothing if there are no available heroes with sufficient vigor" in { val cmd = AvailableDiplomacyCommandsFactory.availableCommand( gameState = gameState.update( - _.heroes(8).vigor := 20, - _.heroes(9).vigor := 30, + _.heroes(8).vigor := 20, + _.heroes(9).vigor := 30, _.heroes(10).vigor := 40, _.heroes(11).vigor := 50 ), @@ -560,7 +551,7 @@ class AvailableDiplomacyCommandsFactoryTest it should "return nothing if there is exactly one ruling faction hero" in { val cmd = AvailableDiplomacyCommandsFactory.availableCommand( gameState = gameState.update( - _.heroes(9).vigor := 90, + _.heroes(9).vigor := 90, _.provinces(actingProvinceId).rulingFactionHeroIds := Vector(9) ), factionId = actingFid, @@ -595,8 +586,8 @@ class AvailableDiplomacyCommandsFactoryTest it should "recommend the hero with the highest vigor" in { val gsWithVigor = gameState.update( - _.heroes(8).vigor := 75, - _.heroes(9).vigor := 85, + _.heroes(8).vigor := 75, + _.heroes(9).vigor := 85, _.heroes(10).vigor := 90, _.heroes(11).vigor := 85 ) @@ -615,8 +606,8 @@ class AvailableDiplomacyCommandsFactoryTest it should "not recommend the faction head if there is another option" in { val gsWithVigor = gameState.update( - _.heroes(8).vigor := 87, - _.heroes(9).vigor := 90, + _.heroes(8).vigor := 87, + _.heroes(9).vigor := 90, _.heroes(10).vigor := 75, _.heroes(11).vigor := 85 ) @@ -635,8 +626,8 @@ class AvailableDiplomacyCommandsFactoryTest it should "recommend the faction head if there is no other option" in { val gsWithVigor = gameState.update( - _.heroes(8).vigor := 33, - _.heroes(9).vigor := 85, + _.heroes(8).vigor := 33, + _.heroes(9).vigor := 85, _.heroes(10).vigor := 44, _.heroes(11).vigor := 22 ) @@ -660,14 +651,14 @@ class AvailableDiplomacyCommandsFactoryTest 9, 10 ), // no 11, a faction leader - _.provinces(7).unaffiliatedHeroes := Vector( + _.provinces(7).unaffiliatedHeroes := Vector( UnaffiliatedHero( heroId = 83, `type` = UNAFFILIATED_HERO_PRISONER, lastFaction = Some(19) ) ), - _.provinces(50).unaffiliatedHeroes := Vector( + _.provinces(50).unaffiliatedHeroes := Vector( UnaffiliatedHero( heroId = 11, `type` = UNAFFILIATED_HERO_PRISONER, @@ -724,10 +715,10 @@ class AvailableDiplomacyCommandsFactoryTest 9, 10 ), // no 11, a faction leader - _.provinces(7).unaffiliatedHeroes := Vector( + _.provinces(7).unaffiliatedHeroes := Vector( UnaffiliatedHero(heroId = 83, `type` = UNAFFILIATED_HERO_RESIDENT) ), - _.provinces(50).unaffiliatedHeroes := Vector( + _.provinces(50).unaffiliatedHeroes := Vector( UnaffiliatedHero( heroId = 11, `type` = UNAFFILIATED_HERO_PRISONER, @@ -756,14 +747,14 @@ class AvailableDiplomacyCommandsFactoryTest 10, 11 ), // no 8, not a faction leader - _.provinces(7).unaffiliatedHeroes := Vector( + _.provinces(7).unaffiliatedHeroes := Vector( UnaffiliatedHero( heroId = 83, `type` = UNAFFILIATED_HERO_PRISONER, lastFaction = Some(19) ) ), - _.provinces(50).unaffiliatedHeroes := Vector( + _.provinces(50).unaffiliatedHeroes := Vector( UnaffiliatedHero( heroId = 8, `type` = UNAFFILIATED_HERO_PRISONER, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDivineCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDivineCommandsFactoryTest.scala index 4afd77a814..33f0a61fcc 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDivineCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableDivineCommandsFactoryTest.scala @@ -15,26 +15,15 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.settings.{ - GoldCostForDivine, - MinimumAgilityForArchery, - MinimumAgilityForStartFire -} -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.settings.{GoldCostForDivine, MinimumAgilityForArchery, MinimumAgilityForStartFire} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.views.hero_view.{HeroSortKey, HeroView} import net.eagle0.eagle.views.stat_with_condition.StatWithCondition import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableDivineCommandsFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableDivineCommandsFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { GoldCostForDivine.setIntValue(100) @@ -42,7 +31,7 @@ class AvailableDivineCommandsFactoryTest MinimumAgilityForStartFire.setDoubleValue(70) } - private val actingFid: FactionId = 9 + private val actingFid: FactionId = 9 private val actingPid: ProvinceId = 27 private val gameState: GameState = GameState( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactoryTest.scala index 37e349ce80..14026728fb 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableExileVassalCommandFactoryTest.scala @@ -32,8 +32,7 @@ class AvailableExileVassalCommandFactoryTest extends AnyFlatSpec with Matchers { "availableCommand" should "include non-leader vassals" in { val cmd = AvailableExileVassalCommandFactory .availableCommand( - gameState = - gameState(vassalFids = Vector(5, 19), leaderFids = Vector(6, 12)), + gameState = gameState(vassalFids = Vector(5, 19), leaderFids = Vector(6, 12)), factionId = fid, provinceId = pid ) @@ -45,8 +44,7 @@ class AvailableExileVassalCommandFactoryTest extends AnyFlatSpec with Matchers { it should "not return a command if only leaders are present" in { AvailableExileVassalCommandFactory .availableCommand( - gameState = - gameState(vassalFids = Vector(), leaderFids = Vector(6, 12)), + gameState = gameState(vassalFids = Vector(), leaderFids = Vector(6, 12)), factionId = fid, provinceId = pid ) shouldBe empty @@ -55,8 +53,7 @@ class AvailableExileVassalCommandFactoryTest extends AnyFlatSpec with Matchers { it should "not return a command if no leader is present" in { AvailableExileVassalCommandFactory .availableCommand( - gameState = - gameState(vassalFids = Vector(5, 19), leaderFids = Vector()), + gameState = gameState(vassalFids = Vector(5, 19), leaderFids = Vector()), factionId = fid, provinceId = pid ) shouldBe empty diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFeastCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFeastCommandFactoryTest.scala index 4100c3b471..669fdbb557 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFeastCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFeastCommandFactoryTest.scala @@ -8,14 +8,10 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableFeastCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableFeastCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - override def beforeEach(): Unit = { + override def beforeEach(): Unit = FeastGoldCostPerHero.setIntValue(20) - } behavior of "AvailableFeastCommandFactoryTest" diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactoryTest.scala index 6b720f1a53..fff78c2115 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableFreeForAllDecisionCommandFactoryTest.scala @@ -5,22 +5,11 @@ import net.eagle0.common.ProtoMatchers import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.api.available_command.FreeForAllDecisionAvailableCommand import net.eagle0.eagle.api.command.util.army_stats.ArmyStats -import net.eagle0.eagle.api.command.util.attack_decision_type.{ - AdvanceDecision, - WithdrawDecision -} +import net.eagle0.eagle.api.command.util.attack_decision_type.{AdvanceDecision, WithdrawDecision} import net.eagle0.eagle.api.command.util.expanded_combat_unit.ExpandedCombatUnit import net.eagle0.eagle.common.combat_unit.CombatUnit -import net.eagle0.eagle.common.round_phase.RoundPhase.{ - FREE_FOR_ALL_DECISION, - PLAYER_COMMANDS -} -import net.eagle0.eagle.internal.army.{ - Army, - AwaitingDecision, - HostileArmyGroup, - MovingArmy -} +import net.eagle0.eagle.common.round_phase.RoundPhase.{FREE_FOR_ALL_DECISION, PLAYER_COMMANDS} +import net.eagle0.eagle.internal.army.{Army, AwaitingDecision, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship @@ -46,11 +35,11 @@ class AvailableFreeForAllDecisionCommandFactoryTest with ProtoMatchers with BeforeAndAfterEach { val actingFid: FactionId = 4 - val otherFid: FactionId = 6 + val otherFid: FactionId = 6 private val actingFactionHero: Hero = Hero(id = 9, factionId = Some(actingFid), vigor = 90, loyalty = 60) - private val otherFactionHero: Hero = + private val otherFactionHero: Hero = Hero(id = 11, factionId = Some(otherFid), vigor = 70, loyalty = 90) val pid: ProvinceId = 17 @@ -111,7 +100,7 @@ class AvailableFreeForAllDecisionCommandFactoryTest ), factions = Map( actingFid -> Faction(id = actingFid), - otherFid -> Faction(id = otherFid) + otherFid -> Faction(id = otherFid) ), heroes = Map(9 -> actingFactionHero, 11 -> otherFactionHero), battalions = Map( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactoryTest.scala index 3b69c78f7e..120f7c4fb7 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleCapturedHeroCommandFactoryTest.scala @@ -22,10 +22,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableHandleCapturedHeroCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableHandleCapturedHeroCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { behavior of "AvailableHandleCapturedHeroCommandFactoryTest" @@ -227,7 +224,7 @@ class AvailableHandleCapturedHeroCommandFactoryTest it should "not allow return for a sworn brother if they do not have any provinces" in { val gameStateWithFactionLeader = gameStateWithOne.update( - _.factions := Map( + _.factions := Map( capturedHeroesFaction -> Faction( id = capturedHeroesFaction, factionHeadId = 25, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactoryTest.scala index e4554e4960..6a28089811 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotCrackDownCommandFactoryTest.scala @@ -13,17 +13,14 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableHandleRiotCrackDownCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { - private val fid: FactionId = 17 - private val pid: ProvinceId = 21 - private val date = Date(year = 305, month = 4) +class AvailableHandleRiotCrackDownCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { + private val fid: FactionId = 17 + private val pid: ProvinceId = 21 + private val date = Date(year = 305, month = 4) private val rulingFactionHeroIds = Vector(10, 20, 30) - private val battalionIds = Vector(19, 20, 21) - private val goldAvailable = 150 - private val foodAvailable = 120 + private val battalionIds = Vector(19, 20, 21) + private val goldAvailable = 150 + private val foodAvailable = 120 private val gameState = GameState( provinces = Map( @@ -42,9 +39,8 @@ class AvailableHandleRiotCrackDownCommandFactoryTest .toMap ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForCrackDown.setDoubleValue(50) - } "availableCommands" should "return a command if there is an imminent riot" in { AvailableHandleRiotCrackDownCommandFactory diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactoryTest.scala index ad7ed32100..5df6b861f7 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotDoNothingCommandFactoryTest.scala @@ -12,17 +12,14 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableHandleRiotDoNothingCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { - private val fid: FactionId = 17 - private val pid: ProvinceId = 21 - private val date = Date(year = 305, month = 4) +class AvailableHandleRiotDoNothingCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { + private val fid: FactionId = 17 + private val pid: ProvinceId = 21 + private val date = Date(year = 305, month = 4) private val rulingFactionHeroIds = Vector(10, 20, 30) - private val battalionIds = Vector(19, 20, 21) - private val goldAvailable = 150 - private val foodAvailable = 120 + private val battalionIds = Vector(19, 20, 21) + private val goldAvailable = 150 + private val foodAvailable = 120 private val gameState = GameState( provinces = Map( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactoryTest.scala index 818b14709a..61fa576556 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHandleRiotGiveCommandFactoryTest.scala @@ -13,17 +13,14 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableHandleRiotGiveCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { - private val fid: FactionId = 17 - private val pid: ProvinceId = 21 - private val date = Date(year = 305, month = 4) +class AvailableHandleRiotGiveCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { + private val fid: FactionId = 17 + private val pid: ProvinceId = 21 + private val date = Date(year = 305, month = 4) private val rulingFactionHeroIds = Vector(10, 20, 30) - private val battalionIds = Vector(19, 20, 21) - private val goldAvailable = 150 - private val foodAvailable = 120 + private val battalionIds = Vector(19, 20, 21) + private val goldAvailable = 150 + private val foodAvailable = 120 private val gameState = GameState( provinces = Map( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactoryTest.scala index edef91878d..a739697d80 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableHeroGiftCommandFactoryTest.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.availability -import net.eagle0.eagle.api.available_command.{ - EligibleGift, - HeroGiftAvailableCommand -} +import net.eagle0.eagle.api.available_command.{EligibleGift, HeroGiftAvailableCommand} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -13,31 +10,27 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableHeroGiftCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableHeroGiftCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { import net.eagle0.common.ProtoMatchers.* - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MaxGiftGold.setIntValue(100) - } - private val factionId = 7 - private val factionHeadId = 12 + private val factionId = 7 + private val factionHeadId = 12 private val factionLeaders = Vector(12, 15, 18) private val leaderProvinceId = 9 - private val factionLeader = + private val factionLeader = Hero(id = factionHeadId, factionId = Some(factionId)) - private val leaderVassal1 = + private val leaderVassal1 = Hero(id = 25, factionId = Some(factionId), loyalty = 50) - private val leaderVassal2 = + private val leaderVassal2 = Hero(id = 30, factionId = Some(factionId), loyalty = 100) - private val leaderVassal3 = + private val leaderVassal3 = Hero(id = 35, factionId = Some(factionId), loyalty = 90) - private val leaderProvince = Province( + private val leaderProvince = Province( id = 9, rulingFactionId = Some(factionId), rulingHeroId = Some(factionHeadId), @@ -59,7 +52,7 @@ class AvailableHeroGiftCommandFactoryTest ) ), heroes = Map( - factionHeadId -> factionLeader, + factionHeadId -> factionLeader, leaderVassal1.id -> leaderVassal1, leaderVassal2.id -> leaderVassal2, leaderVassal3.id -> leaderVassal3 @@ -69,11 +62,11 @@ class AvailableHeroGiftCommandFactoryTest ) ) - private val brother1 = Hero( + private val brother1 = Hero( id = 15, factionId = Some(factionId) ) - private val brother2 = Hero( + private val brother2 = Hero( id = 18, factionId = Some(factionId) ) @@ -92,17 +85,16 @@ class AvailableHeroGiftCommandFactoryTest id = 15, rulingHeroId = Some(15), rulingFactionId = Some(factionId), - rulingFactionHeroIds = - Vector(brother1, brother2, extraProvinceVassal1, extraProvinceVassal2) - .map(_.id), + rulingFactionHeroIds = Vector(brother1, brother2, extraProvinceVassal1, extraProvinceVassal2) + .map(_.id), gold = 500 ) private val extraProvinceGameState = gameState .update( - _.provinces(extraProvince.id) := extraProvince, - _.heroes(brother1.id) := brother1, - _.heroes(brother2.id) := brother2, + _.provinces(extraProvince.id) := extraProvince, + _.heroes(brother1.id) := brother1, + _.heroes(brother2.id) := brother2, _.heroes(extraProvinceVassal1.id) := extraProvinceVassal1, _.heroes(extraProvinceVassal2.id) := extraProvinceVassal2 ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactoryTest.scala index 926962a89c..d145f2d848 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableImproveCommandsFactoryTest.scala @@ -1,11 +1,6 @@ package net.eagle0.eagle.library.actions.availability -import net.eagle0.eagle.common.improvement_type.ImprovementType.{ - AGRICULTURE, - DEVASTATION, - ECONOMY, - INFRASTRUCTURE -} +import net.eagle0.eagle.common.improvement_type.ImprovementType.{AGRICULTURE, DEVASTATION, ECONOMY, INFRASTRUCTURE} import net.eagle0.eagle.common.profession.Profession.ENGINEER import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -16,10 +11,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableImproveCommandsFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableImproveCommandsFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val rulingFactionId = 9 private val restedHeroes = Vector( @@ -71,18 +63,16 @@ class AvailableImproveCommandsFactoryTest private val gameState = GameState(provinces = Map(province.id -> province), heroes = heroesMap) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForImprove.setDoubleValue(46.0) - } "availableCommands" should "throw if the province does not belong to the player" in { - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy AvailableImproveCommandsFactory.availableCommand( gameState = gameState, factionId = 10, provinceId = province.id ) - } ex.getMessage shouldBe "requirement failed: Player 10 does not rule province 3" } @@ -156,8 +146,8 @@ class AvailableImproveCommandsFactoryTest it should "include only one type if the others are at 100" in { val mostlyDevelopedProvince = province.update( - _.agriculture := 100, - _.economy := 50, + _.agriculture := 100, + _.economy := 50, _.infrastructure := 100 ) @@ -175,8 +165,8 @@ class AvailableImproveCommandsFactoryTest it should "return nothing if the province is fully developed" in { val fullyDevelopedProvince = province.update( - _.agriculture := 100, - _.economy := 100, + _.agriculture := 100, + _.economy := 100, _.infrastructure := 100 ) @@ -250,8 +240,8 @@ class AvailableImproveCommandsFactoryTest it should "not include DEVASTATION option if there is no devastation" in { val provinceWithoutDevastation = province.update( - _.economyDevastation := 0, - _.agricultureDevastation := 0, + _.economyDevastation := 0, + _.agricultureDevastation := 0, _.infrastructureDevastation := 0 ) @@ -264,7 +254,7 @@ class AvailableImproveCommandsFactoryTest provinceId = province.id ) - command.get.availableTypes should not contain (DEVASTATION) + command.get.availableTypes should not contain DEVASTATION } it should "recommend the least tired hero" in { diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactoryTest.scala index dd332daa3c..1109a297e0 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableIssueOrdersCommandFactoryTest.scala @@ -1,12 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.command.util.province_orders.ProvinceOrders -import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{ - DEVELOP, - ENTRUST, - EXPAND, - MOBILIZE -} +import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{DEVELOP, ENTRUST, EXPAND, MOBILIZE} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province @@ -14,16 +9,16 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class AvailableIssueOrdersCommandFactoryTest extends AnyFlatSpec with Matchers { - private val factionId = 5 - private val hostilePlayerId = 3 - private val factionHeadId = 43 - private val anotherLeaderId = 98 - private val anotherHeroId = 23 + private val factionId = 5 + private val hostilePlayerId = 3 + private val factionHeadId = 43 + private val anotherLeaderId = 98 + private val anotherHeroId = 23 private val anotherProvinceHeroId1 = 1 private val anotherProvinceHeroId2 = 2 - private val hostileHeroId = 9 + private val hostileHeroId = 9 - private val faction: Faction = + private val faction: Faction = Faction( id = factionId, name = "blah", @@ -80,11 +75,11 @@ class AvailableIssueOrdersCommandFactoryTest extends AnyFlatSpec with Matchers { factions = Map(factionId -> faction), provinces = Map( factionHeadProvince.id -> factionHeadProvince, - leaderProvince.id -> leaderProvince, - owned1.id -> owned1, - owned2.id -> owned2, - unowned.id -> unowned, - hostile.id -> hostile + leaderProvince.id -> leaderProvince, + owned1.id -> owned1, + owned2.id -> owned2, + unowned.id -> unowned, + hostile.id -> hostile ) ) @@ -92,7 +87,7 @@ class AvailableIssueOrdersCommandFactoryTest extends AnyFlatSpec with Matchers { val availableCommand = AvailableIssueOrdersCommandFactory .availableCommand( gameState = gameState.update( - _.provinces(factionHeadProvince.id).rulingHeroId := anotherHeroId, + _.provinces(factionHeadProvince.id).rulingHeroId := anotherHeroId, _.provinces(factionHeadProvince.id).rulingFactionHeroIds := Vector( anotherHeroId ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonerCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonerCommandsFactoryTest.scala index 9d7d4e242f..d25a03bc37 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonerCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableManagePrisonerCommandsFactoryTest.scala @@ -23,10 +23,7 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.{Neighbor, Province} import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.settings.{ - MinimumAgilityForArchery, - MinimumAgilityForStartFire -} +import net.eagle0.eagle.library.settings.{MinimumAgilityForArchery, MinimumAgilityForStartFire} import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyProvinces} import net.eagle0.eagle.views.hero_view.{HeroSortKey, HeroView} import net.eagle0.eagle.views.stat_with_condition.StatWithCondition @@ -34,24 +31,21 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableManagePrisonerCommandsFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableManagePrisonerCommandsFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { MinimumAgilityForArchery.setDoubleValue(70) MinimumAgilityForStartFire.setDoubleValue(70) } - private val actingFactionId: FactionId = 17 + private val actingFactionId: FactionId = 17 private val actingProvinceId: ProvinceId = 5 private val enemyFactionLeaderHid: HeroId = 19 private val neighbor1ProvinceId: ProvinceId = 21 private val neighbor2ProvinceId: ProvinceId = 31 - private val enemyProvinceId: ProvinceId = 51 + private val enemyProvinceId: ProvinceId = 51 private val enemyFactionId: FactionId = 99 @@ -70,20 +64,17 @@ class AvailableManagePrisonerCommandsFactoryTest UnaffiliatedHero( heroId = 17, `type` = UNAFFILIATED_HERO_PRISONER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ), UnaffiliatedHero( heroId = 18, `type` = UNAFFILIATED_HERO_TRAVELER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ), UnaffiliatedHero( heroId = enemyFactionLeaderHid, `type` = UNAFFILIATED_HERO_PRISONER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ), rulerIsTraveling = true, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactoryTest.scala index 93ed0ebc4b..b7b6d9e473 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableMarchCommandFactoryTest.scala @@ -1,33 +1,22 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_INFANTRY, - LIGHT_INFANTRY -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_INFANTRY, LIGHT_INFANTRY} import net.eagle0.eagle.common.province_event.BlizzardEvent import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.{Neighbor, Province} -import net.eagle0.eagle.library.settings.{ - MaxCombatUnitCountPerSide, - MaxFoodTribute, - MaxGoldTribute, - MinVigorForMarch -} +import net.eagle0.eagle.library.settings.{MaxCombatUnitCountPerSide, MaxFoodTribute, MaxGoldTribute, MinVigorForMarch} import net.eagle0.eagle.library.util.ShardokMapInfo import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableMarchCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableMarchCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val actingPlayerId = 5 - private val sufficientVigorHeroes = Vector( + private val sufficientVigorHeroes = Vector( Hero(id = 9, vigor = 50, factionId = Some(actingPlayerId)), Hero(id = 10, vigor = 60, factionId = Some(actingPlayerId)) ) @@ -70,24 +59,21 @@ class AvailableMarchCommandFactoryTest "availableCommand" should "include neighbor provinces ruled by other players as available destinations" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = Some(6), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -111,24 +97,21 @@ class AvailableMarchCommandFactoryTest it should "include provinces ruled by same player" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = Some(6), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -151,24 +134,21 @@ class AvailableMarchCommandFactoryTest it should "include provinces ruled by no one" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -191,25 +171,22 @@ class AvailableMarchCommandFactoryTest it should "not include a destination province with a blizzard" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), activeEvents = Vector(BlizzardEvent()), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -230,24 +207,21 @@ class AvailableMarchCommandFactoryTest it should "include heroes with sufficient vigor" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -268,24 +242,21 @@ class AvailableMarchCommandFactoryTest it should "exclude heroes with insufficient vigor" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -306,24 +277,21 @@ class AvailableMarchCommandFactoryTest it should "include battalions with size > 0" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -345,27 +313,24 @@ class AvailableMarchCommandFactoryTest it should "return nothing if there are no heroes with enough vigor" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince.copy( + 7 -> actingProvince.copy( rulingFactionHeroIds = actingProvince.rulingFactionHeroIds .filterNot(id => sufficientVigorHeroes.map(_.id).contains(id)) ), - 4 -> Province( + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(insufficientVigorHeroes ++ sufficientVigorHeroes), @@ -384,26 +349,23 @@ class AvailableMarchCommandFactoryTest it should "return nothing if the province has a blizzard" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince.withActiveEvents( + 7 -> actingProvince.withActiveEvents( Vector(BlizzardEvent()) ), - 4 -> Province( + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -423,24 +385,21 @@ class AvailableMarchCommandFactoryTest it should "include available gold in the province" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince, - 4 -> Province( + 7 -> actingProvince, + 4 -> Province( id = 4, rulingFactionId = Some(5), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 0)) ), - 8 -> Province( + 8 -> Province( id = 8, rulingFactionId = Some(6), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 1)) ), 12 -> Province( id = 12, rulingFactionId = Some(9), - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 2)) ) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), @@ -462,7 +421,7 @@ class AvailableMarchCommandFactoryTest provinceId: Int, backReferencePositionIndex: Int, rulingFactionId: Option[Int] = None - ): Province = { + ): Province = Province( id = provinceId, neighbors = Vector( @@ -473,12 +432,11 @@ class AvailableMarchCommandFactoryTest ), rulingFactionId = rulingFactionId ) - } "availableCommand" should "set requiresRiverCrossing correctly based on map info" in { // We need to use real province IDs that exist in the ShardokMapInfo // Let's use province 1 as the acting province and 37 as destination - val actingProvinceId = 1 + val actingProvinceId = 1 val destinationProvinceId = 37 val testActingProvince = Province( @@ -503,7 +461,7 @@ class AvailableMarchCommandFactoryTest val gameState = GameState( provinces = Map( - actingProvinceId -> testActingProvince, + actingProvinceId -> testActingProvince, destinationProvinceId -> testDestinationProvince ), heroes = HeroMap(sufficientVigorHeroes), @@ -524,7 +482,7 @@ class AvailableMarchCommandFactoryTest destinationProvince should be(defined) // Calculate expected river crossing requirement based on map info - val mapInfo = ShardokMapInfo.shardokMapInfos(destinationProvinceId) + val mapInfo = ShardokMapInfo.shardokMapInfos(destinationProvinceId) val expectedRequiresRiverCrossing = mapInfo.waterCrossingRequirementsByPosition(0) >= 10 @@ -533,7 +491,7 @@ class AvailableMarchCommandFactoryTest it should "set requiresRiverCrossing based on map info regardless of specific values" in { // Use the same province combinations as the first river crossing test for consistency - val actingProvinceId = 1 + val actingProvinceId = 1 val destinationProvinceId = 37 val testActingProvince = Province( @@ -558,7 +516,7 @@ class AvailableMarchCommandFactoryTest val gameState = GameState( provinces = Map( - actingProvinceId -> testActingProvince, + actingProvinceId -> testActingProvince, destinationProvinceId -> testDestinationProvince ), heroes = HeroMap(sufficientVigorHeroes), @@ -579,7 +537,7 @@ class AvailableMarchCommandFactoryTest destinationProvince should be(defined) // Calculate expected river crossing requirement - val mapInfo = ShardokMapInfo.shardokMapInfos(destinationProvinceId) + val mapInfo = ShardokMapInfo.shardokMapInfos(destinationProvinceId) val expectedRequiresRiverCrossing = mapInfo.waterCrossingRequirementsByPosition(0) >= 10 @@ -588,7 +546,7 @@ class AvailableMarchCommandFactoryTest it should "correctly handle multiple destination provinces" in { // Use a simpler test that just verifies the feature works with one province - val actingProvinceId = 1 + val actingProvinceId = 1 val destinationProvinceId = 37 val testActingProvince = Province( @@ -613,7 +571,7 @@ class AvailableMarchCommandFactoryTest val gameState = GameState( provinces = Map( - actingProvinceId -> testActingProvince, + actingProvinceId -> testActingProvince, destinationProvinceId -> testDestinationProvince ), heroes = HeroMap(sufficientVigorHeroes), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactoryTest.scala index cb9e3ee8e4..7b730feff7 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableOrganizeTroopsCommandsFactoryTest.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.api.available_command.TroopCost import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_CAVALRY, - LIGHT_INFANTRY -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_CAVALRY, LIGHT_INFANTRY} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -15,10 +12,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableOrganizeTroopsCommandsFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableOrganizeTroopsCommandsFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val actingPlayerId = 5 private val heroes = Vector( @@ -57,16 +51,15 @@ class AvailableOrganizeTroopsCommandsFactoryTest ) ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForMarch.setDoubleValue(45.0) - } "availableCommand" should "include all battalions, below cap or not, if stats are high enough" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince.withEconomy(70).withAgriculture(70), - 4 -> Province(id = 4, rulingFactionId = Some(5)), - 8 -> Province(id = 8, rulingFactionId = Some(6)), + 7 -> actingProvince.withEconomy(70).withAgriculture(70), + 4 -> Province(id = 4, rulingFactionId = Some(5)), + 8 -> Province(id = 8, rulingFactionId = Some(6)), 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(heroes), @@ -84,9 +77,9 @@ class AvailableOrganizeTroopsCommandsFactoryTest "availableCommand" should "not include command if there is not enough gold in province for one troop" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince.withGold(1), - 4 -> Province(id = 4, rulingFactionId = Some(5)), - 8 -> Province(id = 8, rulingFactionId = Some(6)), + 7 -> actingProvince.withGold(1), + 4 -> Province(id = 4, rulingFactionId = Some(5)), + 8 -> Province(id = 8, rulingFactionId = Some(6)), 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(heroes), @@ -102,12 +95,12 @@ class AvailableOrganizeTroopsCommandsFactoryTest it should "include base costs when priceIndex is 1.0" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince + 7 -> actingProvince .withEconomy(70) .withAgriculture(70) .withPriceIndex(1.0), - 4 -> Province(id = 4, rulingFactionId = Some(5)), - 8 -> Province(id = 8, rulingFactionId = Some(6)), + 4 -> Province(id = 4, rulingFactionId = Some(5)), + 8 -> Province(id = 8, rulingFactionId = Some(6)), 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(heroes), @@ -127,12 +120,12 @@ class AvailableOrganizeTroopsCommandsFactoryTest it should "adjust base costs by priceIndex" in { val gameState = GameState( provinces = Map( - 7 -> actingProvince + 7 -> actingProvince .withEconomy(70) .withAgriculture(70) .withPriceIndex(0.9), - 4 -> Province(id = 4, rulingFactionId = Some(5)), - 8 -> Province(id = 8, rulingFactionId = Some(6)), + 4 -> Province(id = 4, rulingFactionId = Some(5)), + 8 -> Province(id = 8, rulingFactionId = Some(6)), 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(heroes), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactoryTest.scala index 88b054be69..f042f8c755 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailablePleaseRecruitMeCommandFactoryTest.scala @@ -31,10 +31,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailablePleaseRecruitMeCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailablePleaseRecruitMeCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val actingFactionId = 5 private val heroes = Vector( @@ -45,8 +42,7 @@ class AvailablePleaseRecruitMeCommandFactoryTest private val unaffiliatedHero = UnaffiliatedHero( heroId = 10, `type` = UNAFFILIATED_HERO_RESIDENT, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_NOT_DIVINED)), + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_NOT_DIVINED)), factionBiases = Map( actingFactionId -> 500 ), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReconCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReconCommandFactoryTest.scala index 6d6e31eaea..181e75fa09 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReconCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReconCommandFactoryTest.scala @@ -2,11 +2,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.common.ProtoMatchers.equalProto import net.eagle0.eagle.api.available_command.ReconAvailableCommand -import net.eagle0.eagle.common.profession.Profession.{ - NECROMANCER, - PALADIN, - RANGER -} +import net.eagle0.eagle.common.profession.Profession.{NECROMANCER, PALADIN, RANGER} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -18,13 +14,10 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableReconCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableReconCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { val actingFactionId: FactionId = 3 - val otherFactionId: FactionId = 4 + val otherFactionId: FactionId = 4 private val actingProvince = Province( id = 15, @@ -39,10 +32,10 @@ class AvailableReconCommandFactoryTest private val gameState = GameState( factions = Map( actingFactionId -> Faction(id = actingFactionId, factionHeadId = 3), - otherFactionId -> Faction(id = otherFactionId) + otherFactionId -> Faction(id = otherFactionId) ), provinces = Map( - actingProvince.id -> actingProvince, + actingProvince.id -> actingProvince, unownedProvince.id -> unownedProvince, hostileProvince.id -> hostileProvince ), @@ -53,9 +46,8 @@ class AvailableReconCommandFactoryTest ) ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForRecon.setDoubleValue(50) - } "available command" should "return None if there is no ranger in the province" in { val cmd = AvailableReconCommandFactory.availableCommand( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactoryTest.scala index e0c1c0ae03..91f49f525f 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableRecruitHeroesCommandFactoryTest.scala @@ -34,17 +34,14 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableRecruitHeroesCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableRecruitHeroesCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val provinceId = 19 - val factionId = 3 + val factionId = 3 - private val leader = + private val leader = Hero(id = 9, nameTextId = "hn_9", factionId = Some(factionId)) - private val recruitableHero = + private val recruitableHero = Hero(id = 11, nameTextId = "hn_11", factionId = None) private val anotherRecruitableHero = Hero(id = 21, nameTextId = "hn_21", factionId = None) @@ -59,8 +56,7 @@ class AvailableRecruitHeroesCommandFactoryTest heroId = recruitableHero.id, `type` = UNAFFILIATED_HERO_RESIDENT, factionBiases = Map(factionId -> 200.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_WOULD_JOIN)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_WOULD_JOIN)) ) ), rulerIsTraveling = true @@ -68,8 +64,8 @@ class AvailableRecruitHeroesCommandFactoryTest val gameState = GameState( heroes = Map( - leader.id -> leader, - recruitableHero.id -> recruitableHero, + leader.id -> leader, + recruitableHero.id -> recruitableHero, anotherRecruitableHero.id -> anotherRecruitableHero ), provinces = Map(province.id -> province), @@ -150,15 +146,13 @@ class AvailableRecruitHeroesCommandFactoryTest heroId = recruitableHero.id, `type` = UNAFFILIATED_HERO_TRAVELER, factionBiases = Map(factionId -> 200.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_WOULD_JOIN)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_WOULD_JOIN)) ), UnaffiliatedHero( heroId = anotherRecruitableHero.id, `type` = UNAFFILIATED_HERO_RESIDENT, factionBiases = Map(factionId -> 200.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_WOULD_JOIN)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_WOULD_JOIN)) ) ) ) @@ -199,7 +193,7 @@ class AvailableRecruitHeroesCommandFactoryTest val gameStateWithFactionLeader = gameState.update( _.factions(8).update( _.factionHeadId := recruitableHero.id, - _.leaders := Vector(recruitableHero.id) + _.leaders := Vector(recruitableHero.id) ) ) @@ -214,7 +208,7 @@ class AvailableRecruitHeroesCommandFactoryTest val gameStateWithFactionLeader = gameState.update( _.factions(8).update( _.factionHeadId := 156, - _.leaders := Vector(156, recruitableHero.id) + _.leaders := Vector(156, recruitableHero.id) ) ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactoryTest.scala index bab2d0b490..c1e9859270 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveAllianceOfferCommandFactoryTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.common.diplomacy_offer.{ - AllianceOfferDetails, - DiplomacyOffer -} +import net.eagle0.eagle.common.diplomacy_offer.{AllianceOfferDetails, DiplomacyOffer} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_ACCEPTED, @@ -20,12 +17,9 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableResolveAllianceOfferCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val actingFid = 19 - private val firstOfferingFid = 22 +class AvailableResolveAllianceOfferCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val actingFid = 19 + private val firstOfferingFid = 22 private val secondOfferingFid = 6 private val gameState = GameState( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactoryTest.scala index c7b9efaa53..b860030b52 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveBreakAllianceCommandFactoryTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.common.diplomacy_offer.{ - BreakAllianceDetails, - DiplomacyOffer -} +import net.eagle0.eagle.common.diplomacy_offer.{BreakAllianceDetails, DiplomacyOffer} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_ACCEPTED, @@ -20,12 +17,9 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableResolveBreakAllianceCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val actingFid = 19 - private val firstOfferingFid = 22 +class AvailableResolveBreakAllianceCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val actingFid = 19 + private val firstOfferingFid = 22 private val secondOfferingFid = 6 private val gameState = GameState( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactoryTest.scala index 5e756f94a0..0135d20a4a 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveInvitationCommandFactoryTest.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.availability -import net.eagle0.eagle.common.diplomacy_offer.{ - DiplomacyOffer, - InvitationDetails -} +import net.eagle0.eagle.common.diplomacy_offer.{DiplomacyOffer, InvitationDetails} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_ACCEPTED, DIPLOMACY_OFFER_STATUS_IMPRISONED, @@ -17,11 +14,9 @@ import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class AvailableResolveInvitationCommandFactoryTest - extends AnyFlatSpec - with Matchers { - private val actingFid = 19 - private val firstInvitingFid = 22 +class AvailableResolveInvitationCommandFactoryTest extends AnyFlatSpec with Matchers { + private val actingFid = 19 + private val firstInvitingFid = 22 private val secondInvitingFid = 6 private val gameState = GameState( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactoryTest.scala index da0cfb53db..62af31cd61 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveRansomOfferCommandFactoryTest.scala @@ -31,11 +31,9 @@ import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class AvailableResolveRansomOfferCommandFactoryTest - extends AnyFlatSpec - with Matchers { - private val actingFid = 19 - private val firstOfferingFid = 22 +class AvailableResolveRansomOfferCommandFactoryTest extends AnyFlatSpec with Matchers { + private val actingFid = 19 + private val firstOfferingFid = 22 private val secondOfferingFid = 6 private val firstOffer = DiplomacyOffer( @@ -49,10 +47,8 @@ class AvailableResolveRansomOfferCommandFactoryTest provinceIdForPrisoner = 1 ) ), - prisonersOffered = - Vector(PrisonerOfferedInExchange(heroId = 105, provinceIdWithHero = 2)), - hostagesOffered = - Vector(HostageOfferedInExchange(heroId = 101, provinceIdWithHero = 2)), + prisonersOffered = Vector(PrisonerOfferedInExchange(heroId = 105, provinceIdWithHero = 2)), + hostagesOffered = Vector(HostageOfferedInExchange(heroId = 101, provinceIdWithHero = 2)), goldOffered = 150 ), status = DIPLOMACY_OFFER_STATUS_UNRESOLVED @@ -77,8 +73,7 @@ class AvailableResolveRansomOfferCommandFactoryTest UnaffiliatedHero( heroId = 86, `type` = UNAFFILIATED_HERO_PRISONER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ) ), @@ -91,8 +86,7 @@ class AvailableResolveRansomOfferCommandFactoryTest UnaffiliatedHero( heroId = 105, `type` = UNAFFILIATED_HERO_PRISONER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ) ), @@ -142,8 +136,7 @@ class AvailableResolveRansomOfferCommandFactoryTest UnaffiliatedHero( heroId = 105, `type` = UNAFFILIATED_HERO_TRAVELER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ) ) ), @@ -167,8 +160,7 @@ class AvailableResolveRansomOfferCommandFactoryTest UnaffiliatedHero( heroId = 86, `type` = UNAFFILIATED_HERO_TRAVELER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ) ) ), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactoryTest.scala index 36184aeb01..c3036f699c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTributeCommandsFactoryTest.scala @@ -4,12 +4,7 @@ import net.eagle0.eagle.api.available_command.TributeAndFaction import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.tribute_amount.TributeAmount -import net.eagle0.eagle.internal.army.{ - Army, - HostileArmyGroup, - MovingArmy, - TributeDemanded -} +import net.eagle0.eagle.internal.army.{Army, HostileArmyGroup, MovingArmy, TributeDemanded} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship @@ -21,11 +16,9 @@ import net.eagle0.eagle.RoundId import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class AvailableResolveTributeCommandsFactoryTest - extends AnyFlatSpec - with Matchers { - val actingFactionId = 3 - val actingProvinceId = 17 +class AvailableResolveTributeCommandsFactoryTest extends AnyFlatSpec with Matchers { + val actingFactionId = 3 + val actingProvinceId = 17 val currentRound: RoundId = 222 private val actingProvince = Province( @@ -94,8 +87,7 @@ class AvailableResolveTributeCommandsFactoryTest gameState = gameState.update( _.provinces(actingProvinceId).hostileArmies := Vector( HostileArmyGroup( - status = - TributeDemanded(Some(TributeAmount(gold = 123, food = 456))), + status = TributeDemanded(Some(TributeAmount(gold = 123, food = 456))), factionId = hostileFaction1.id, armies = Vector( MovingArmy( @@ -116,8 +108,7 @@ class AvailableResolveTributeCommandsFactoryTest ) ), HostileArmyGroup( - status = - TributeDemanded(Some(TributeAmount(gold = 333, food = 999))), + status = TributeDemanded(Some(TributeAmount(gold = 333, food = 999))), factionId = hostileFaction2.id, armies = Vector( MovingArmy( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactoryTest.scala index 797fe81eb7..517ee59667 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableResolveTruceOfferCommandFactoryTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.common.diplomacy_offer.{ - DiplomacyOffer, - TruceOfferDetails -} +import net.eagle0.eagle.common.diplomacy_offer.{DiplomacyOffer, TruceOfferDetails} import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus import net.eagle0.eagle.common.diplomacy_offer_status.DiplomacyOfferStatus.{ DIPLOMACY_OFFER_STATUS_ACCEPTED, @@ -21,12 +18,9 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableResolveTruceOfferCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val actingFid = 19 - private val firstOfferingFid = 22 +class AvailableResolveTruceOfferCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val actingFid = 19 + private val firstOfferingFid = 22 private val secondOfferingFid = 6 private val gameState = GameState( @@ -42,8 +36,7 @@ class AvailableResolveTruceOfferCommandFactoryTest messengerOriginProvinceId = 19, status = DiplomacyOfferStatus.DIPLOMACY_OFFER_STATUS_UNRESOLVED, offerTextId = "truce offer", - offerDetails = - TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) + offerDetails = TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) ), DiplomacyOffer( originatingFactionId = secondOfferingFid, @@ -52,8 +45,7 @@ class AvailableResolveTruceOfferCommandFactoryTest messengerOriginProvinceId = 20, status = DiplomacyOfferStatus.DIPLOMACY_OFFER_STATUS_UNRESOLVED, offerTextId = "truce offer 2", - offerDetails = - TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) + offerDetails = TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) ) ) ), @@ -66,9 +58,8 @@ class AvailableResolveTruceOfferCommandFactoryTest ) ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = TruceMonths.setIntValue(12) - } "availableCommand" should "return a command with the available truce offers" in { val cmd = AvailableResolveTruceOfferCommandFactory @@ -88,8 +79,7 @@ class AvailableResolveTruceOfferCommandFactoryTest DIPLOMACY_OFFER_STATUS_IMPRISONED ), offerTextId = "truce offer 2", - offerDetails = - TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) + offerDetails = TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) ), DiplomacyOffer( originatingFactionId = firstOfferingFid, @@ -103,8 +93,7 @@ class AvailableResolveTruceOfferCommandFactoryTest DIPLOMACY_OFFER_STATUS_IMPRISONED ), offerTextId = "truce offer", - offerDetails = - TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) + offerDetails = TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) ) ) } @@ -133,8 +122,7 @@ class AvailableResolveTruceOfferCommandFactoryTest DIPLOMACY_OFFER_STATUS_IMPRISONED ), offerTextId = "truce offer 2", - offerDetails = - TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) + offerDetails = TruceOfferDetails(endDate = Some(Date(year = 353, month = 2))) ) ) } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReturnCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReturnCommandsFactoryTest.scala index ba30f8fc89..92c01c139d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReturnCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableReturnCommandsFactoryTest.scala @@ -26,13 +26,12 @@ class AvailableReturnCommandsFactoryTest extends AnyFlatSpec with Matchers { .withHeroes(Map(rulingHero.id -> rulingHero)) "availableCommands" should "throw if the given player does not rule the province" in { - val ex = the[IllegalArgumentException] thrownBy { + val ex = the[IllegalArgumentException] thrownBy AvailableReturnCommandsFactory.availableCommand( gameState = gameState, factionId = 2, provinceId = province.id ) - } ex.getMessage shouldBe "requirement failed: Player 2 does not rule province 24" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactoryTest.scala index 54963134a4..985a3cd5ae 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSendSuppliesCommandFactoryTest.scala @@ -11,10 +11,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableSendSuppliesCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableSendSuppliesCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val actingFactionId = 5 private val sufficientVigorHeroes = Vector( @@ -28,7 +25,7 @@ class AvailableSendSuppliesCommandFactoryTest ) private val actingProvinceId: ProvinceId = 7 - private val neighborPids = Vector(4, 8, 12) + private val neighborPids = Vector(4, 8, 12) private val masterProvince: Province = Province( id = actingProvinceId, @@ -42,16 +39,13 @@ class AvailableSendSuppliesCommandFactoryTest private val gameState: GameState = GameState( provinces = mapifyProvinces( - masterProvince +: neighborPids.map(pid => - Province(id = pid, rulingFactionId = Some(actingFactionId)) - ): _* + masterProvince +: neighborPids.map(pid => Province(id = pid, rulingFactionId = Some(actingFactionId))): _* ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes) ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForSendSupplies.setDoubleValue(45) - } "availableCommands" should "return nothing if there are no heroes with sufficient vigor" in { val insufficientVigorGS = gameState.update( @@ -69,9 +63,7 @@ class AvailableSendSuppliesCommandFactoryTest "availableCommands" should "return nothing if the faction only owns one province" in { val onlyOneProvinceGS = gameState.update( _.provinces := mapifyProvinces( - masterProvince +: neighborPids.map(pid => - Province(id = pid, rulingFactionId = None) - ): _* + masterProvince +: neighborPids.map(pid => Province(id = pid, rulingFactionId = None)): _* ) ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactoryTest.scala index 396b3f36a5..04ed6d402f 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableStartEpidemicCommandFactoryTest.scala @@ -14,28 +14,24 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableStartEpidemicCommandFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableStartEpidemicCommandFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { val minVigor: Int = 50 - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForStartEpidemic.setDoubleValue(minVigor) - } - val actingPid: ProvinceId = 19 - val actingFid: FactionId = 7 + val actingPid: ProvinceId = 19 + val actingFid: FactionId = 7 val neighborPids: Vector[ProvinceId] = Vector(3, 7, 28) - private val necromancer1: Hero = + private val necromancer1: Hero = Hero(id = 29, profession = Profession.NECROMANCER, vigor = 90) - private val necromancer2: Hero = + private val necromancer2: Hero = Hero(id = 98, profession = Profession.NECROMANCER, vigor = 90) private val tiredNecromancer: Hero = Hero(id = 12, profession = Profession.NECROMANCER, vigor = 40) - private val notNecromancer: Hero = Hero(id = 3, vigor = 90) + private val notNecromancer: Hero = Hero(id = 3, vigor = 90) private val actingProvince = Province( id = actingPid, @@ -119,15 +115,13 @@ class AvailableStartEpidemicCommandFactoryTest .get cmd.options should equalProtos( - (actingPid +: actingProvince.neighbors.map(_.provinceId)).map(pid => - StartEpidemicOptions(targetProvinceId = pid) - ) + (actingPid +: actingProvince.neighbors.map(_.provinceId)).map(pid => StartEpidemicOptions(targetProvinceId = pid)) ) } it should "not include own province with an epidemic" in { val gsWithBlizzard = gsWithNecromancers.update( - _.provinces(7).activeEvents := Vector(EpidemicEvent()), + _.provinces(7).activeEvents := Vector(EpidemicEvent()), _.provinces(7).rulingFactionId := actingFid ) @@ -145,7 +139,7 @@ class AvailableStartEpidemicCommandFactoryTest it should "include unowned province with an epidemic" in { val gsWithBlizzard = gsWithNecromancers.update( - _.provinces(7).activeEvents := Vector(EpidemicEvent()), + _.provinces(7).activeEvents := Vector(EpidemicEvent()), _.provinces(7).optionalRulingFactionId := None ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactoryTest.scala index 33076515c6..74b68e764d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableSwearBrotherhoodCommandFactoryTest.scala @@ -7,18 +7,12 @@ import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - MaximumFactionLeaders, - MinimumLoyaltyForSwearBrotherhood -} +import net.eagle0.eagle.library.settings.{MaximumFactionLeaders, MinimumLoyaltyForSwearBrotherhood} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableSwearBrotherhoodCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableSwearBrotherhoodCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { MinimumLoyaltyForSwearBrotherhood.setDoubleValue(96) MaximumFactionLeaders.setIntValue(5) @@ -45,7 +39,7 @@ class AvailableSwearBrotherhoodCommandFactoryTest ) ), heroes = Map( - 5 -> Hero( + 5 -> Hero( id = 5, factionId = Some(12), loyalty = 99, @@ -56,10 +50,10 @@ class AvailableSwearBrotherhoodCommandFactoryTest ) ) ), - 6 -> Hero(id = 6, factionId = Some(12), loyalty = 99), - 7 -> Hero(id = 7, factionId = Some(12), loyalty = 50), - 8 -> Hero(id = 8, factionId = Some(12), loyalty = 99), - 9 -> Hero(id = 9, factionId = Some(12), loyalty = 99), + 6 -> Hero(id = 6, factionId = Some(12), loyalty = 99), + 7 -> Hero(id = 7, factionId = Some(12), loyalty = 50), + 8 -> Hero(id = 8, factionId = Some(12), loyalty = 99), + 9 -> Hero(id = 9, factionId = Some(12), loyalty = 99), 10 -> Hero(id = 10, factionId = Some(12), loyalty = 99), 11 -> Hero(id = 11, factionId = Some(12), loyalty = 99), 12 -> Hero(id = 12, factionId = Some(12), loyalty = 99) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTradeCommandFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTradeCommandFactoryTest.scala index 6fbc3eeb3a..1b1d2e024d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTradeCommandFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTradeCommandFactoryTest.scala @@ -8,10 +8,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableTradeCommandFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableTradeCommandFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val province = Province( id = 89, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactoryTest.scala index 4bbc46065c..233509657b 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTrainCommandsFactoryTest.scala @@ -2,11 +2,7 @@ package net.eagle0.eagle.library.actions.availability import net.eagle0.common.ProtoMatchers.equalProto import net.eagle0.eagle.api.available_command.TrainAvailableCommand -import net.eagle0.eagle.common.profession.Profession.{ - CHAMPION, - NO_PROFESSION, - PALADIN -} +import net.eagle0.eagle.common.profession.Profession.{CHAMPION, NO_PROFESSION, PALADIN} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -17,10 +13,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableTrainCommandsFactoryTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AvailableTrainCommandsFactoryTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val actingFactionId = 5 private val sufficientVigorHeroes = Vector( @@ -58,9 +51,8 @@ class AvailableTrainCommandsFactoryTest battalionIds = Vector(trainableBattalion.id, untrainableBattalion.id) ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForTrain.setDoubleValue(45.0) - } "availableCommands" should "return nothing if there are no heroes with sufficient vigor" in { val actingProvince = masterProvince.copy( @@ -69,12 +61,11 @@ class AvailableTrainCommandsFactoryTest val gameState = GameState( provinces = Map( - 7 -> actingProvince, + 7 -> actingProvince, 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), - battalions = - BattalionMap(Vector(untrainableBattalion, trainableBattalion)) + battalions = BattalionMap(Vector(untrainableBattalion, trainableBattalion)) ) val availableCommands = AvailableTrainCommandsFactory.availableCommand( @@ -90,12 +81,11 @@ class AvailableTrainCommandsFactoryTest val gameState = GameState( provinces = Map( - 7 -> actingProvince, + 7 -> actingProvince, 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), - battalions = - BattalionMap(Vector(untrainableBattalion, trainableBattalion)) + battalions = BattalionMap(Vector(untrainableBattalion, trainableBattalion)) ) val availableCommands = AvailableTrainCommandsFactory.availableCommand( @@ -119,12 +109,11 @@ class AvailableTrainCommandsFactoryTest val gameState = GameState( provinces = Map( - 7 -> actingProvince, + 7 -> actingProvince, 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), - battalions = - BattalionMap(Vector(untrainableBattalion, trainableBattalion)) + battalions = BattalionMap(Vector(untrainableBattalion, trainableBattalion)) ) val availableCommands = AvailableTrainCommandsFactory.availableCommand( @@ -141,12 +130,11 @@ class AvailableTrainCommandsFactoryTest val gameState = GameState( provinces = Map( - 7 -> actingProvince, + 7 -> actingProvince, 12 -> Province(id = 12, rulingFactionId = Some(9)) ), heroes = HeroMap(sufficientVigorHeroes ++ insufficientVigorHeroes), - battalions = - BattalionMap(Vector(untrainableBattalion, trainableBattalion)) + battalions = BattalionMap(Vector(untrainableBattalion, trainableBattalion)) ) val availableCommands = AvailableTrainCommandsFactory.availableCommand( @@ -193,8 +181,7 @@ class AvailableTrainCommandsFactoryTest 7 -> actingProvince ), heroes = heroes, - battalions = - BattalionMap(Vector(untrainableBattalion, trainableBattalion)) + battalions = BattalionMap(Vector(untrainableBattalion, trainableBattalion)) ) val availableCommand = AvailableTrainCommandsFactory diff --git a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTravelCommandsFactoryTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTravelCommandsFactoryTest.scala index f8e21a35fe..2a0bebbffa 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTravelCommandsFactoryTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/availability/AvailableTravelCommandsFactoryTest.scala @@ -9,10 +9,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AvailableTravelCommandsFactoryTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AvailableTravelCommandsFactoryTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val rulingHeroId = Hero() .withNameTextId("hn_17") @@ -30,9 +27,8 @@ class AvailableTravelCommandsFactoryTest .withProvinces(Map(province.id -> province)) .withHeroes(Map(rulingHeroId.id -> rulingHeroId)) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinVigorForTravel.setDoubleValue(42.0) - } it should "return nothing if the ruling hero has low vigor" in { val gameStateWithLowVigorHero = gameState @@ -93,13 +89,12 @@ class AvailableTravelCommandsFactoryTest } it should "throw if the given player does not rule the province" in { - val ex = the[IllegalArgumentException] thrownBy { + val ex = the[IllegalArgumentException] thrownBy AvailableTravelCommandsFactory.availableCommand( gameState = gameState, factionId = 2, provinceId = province.id ) - } ex.getMessage shouldBe "requirement failed: Player 2 does not rule province 24" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesActionTest.scala index adba9d41d8..7aaab3a56c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFactionChangesActionTest.scala @@ -17,7 +17,7 @@ class CheckForFactionChangesActionTest extends AnyFlatSpec with Matchers { private val gameId: GameId = 0xcafeface - private val fid = 5 + private val fid = 5 private val factionWithLeaders = FactionC( id = fid, @@ -25,7 +25,7 @@ class CheckForFactionChangesActionTest extends AnyFlatSpec with Matchers { factionHeadId = 13, leaderIds = Vector(13, 12, 11) ) - private val anotherFaction = + private val anotherFaction = FactionC( id = 22, name = "anotherFaction", @@ -117,9 +117,10 @@ class CheckForFactionChangesActionTest extends AnyFlatSpec with Matchers { killedHeroIds = factionWithLeaders.leaderIds ).randomResults(staticFr).newValue - inside(results.head) { case ar: ActionResultT => - ar.actionResultType shouldBe FactionDestroyedResultType - ar.removedFactionIds shouldBe Vector(fid) + inside(results.head) { + case ar: ActionResultT => + ar.actionResultType shouldBe FactionDestroyedResultType + ar.removedFactionIds shouldBe Vector(fid) } } // diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsActionTest.scala index 6a1606b4ce..57b1b58d7c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFailedQuestsActionTest.scala @@ -15,35 +15,32 @@ import net.eagle0.eagle.model.state.quest.concrete.{ TruceWithFactionQuest } import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Prisoner -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Prisoner} import net.eagle0.eagle.GameId import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class CheckForFailedQuestsActionTest extends AnyFlatSpec with Matchers { - private val actingFid = 23 - private val province = ProvinceC(id = 3, rulingFactionId = Some(actingFid)) - private val provinces = Vector(province) + private val actingFid = 23 + private val province = ProvinceC(id = 3, rulingFactionId = Some(actingFid)) + private val provinces = Vector(province) private val gameId: GameId = 0xfeedface - private val date: Date = Date(year = 2024, month = Date.Month.July) - private val roundId = 123 - private val actingFaction = FactionC( + private val date: Date = Date(year = 2024, month = Date.Month.July) + private val roundId = 123 + private val actingFaction = FactionC( id = actingFid, name = "Great Faction", factionHeadId = 3, leaderIds = Vector(3) ) private val enemyFactionId = 898 - private val enemyFaction = FactionC( + private val enemyFaction = FactionC( id = enemyFactionId, name = "Enemy Faction", factionHeadId = 899, leaderIds = Vector(899) ) - private val factions = Vector(actingFaction, enemyFaction) + private val factions = Vector(actingFaction, enemyFaction) behavior of "defeatFactionQuest" private val defeatFactionQuest = DefeatFactionQuest(targetFactionId = 7) @@ -217,7 +214,7 @@ class CheckForFailedQuestsActionTest extends AnyFlatSpec with Matchers { } behavior of "dismiss specific vassal quest" - private val targetHid = 87 + private val targetHid = 87 private val dismissVassalQuest = DismissSpecificVassalQuest(targetHeroId = targetHid) @@ -258,8 +255,8 @@ class CheckForFailedQuestsActionTest extends AnyFlatSpec with Matchers { } behavior of "return prisoner quest" - private val prisonerHid = 87 - private val prisonerProvinceId = 333 + private val prisonerHid = 87 + private val prisonerProvinceId = 333 private val returnPrisonerQuest = ReturnPrisonerQuest( prisonerHeroId = prisonerHid, prisonerProvinceId = prisonerProvinceId, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsActionTest.scala index 57796293bb..07226cc09c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/CheckForFulfilledQuestsActionTest.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.ProtoMatchers import net.eagle0.eagle.{GameId, RoundId} -import net.eagle0.eagle.common.battalion_type.{ - BattalionType, - BattalionTypeId as BattalionTypeIdProto -} +import net.eagle0.eagle.common.battalion_type.{BattalionType, BattalionTypeId as BattalionTypeIdProto} import net.eagle0.eagle.library.settings.{ MinSupportForTaxes, PortionOfCapacityForUpgradeBattalionQuest, @@ -32,24 +29,16 @@ import net.eagle0.eagle.model.state.quest.concrete.{ WealthQuest } import net.eagle0.eagle.model.state.BattalionTypeId -import net.eagle0.eagle.model.state.BattalionTypeId.{ - HeavyCavalry, - LightInfantry, - Longbowmen -} +import net.eagle0.eagle.model.state.BattalionTypeId.{HeavyCavalry, LightInfantry, Longbowmen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class CheckForFulfilledQuestsActionTest - extends AnyFlatSpec - with Matchers - with ProtoMatchers - with BeforeAndAfterEach { - private val fid = 9 +class CheckForFulfilledQuestsActionTest extends AnyFlatSpec with Matchers with ProtoMatchers with BeforeAndAfterEach { + private val fid = 9 private val otherFid = 7 private val province = ProvinceC(id = 21, rulingFactionId = Some(fid)) - private val faction = FactionC( + private val faction = FactionC( id = fid, name = s"Faction $fid", factionHeadId = 9, @@ -60,11 +49,11 @@ class CheckForFulfilledQuestsActionTest BattalionType(typeId = BattalionTypeIdProto.LONGBOWMEN, capacity = 800) ) - private val gameId: GameId = 0xfacecafe - private val date: Date = Date(year = 2024, month = Date.Month.August) + private val gameId: GameId = 0xfacecafe + private val date: Date = Date(year = 2024, month = Date.Month.August) private val roundId: RoundId = 71 - private val provinces = Vector(province) - private val factions = Vector(faction) + private val provinces = Vector(province) + private val factions = Vector(faction) private val questRecruitmentBonus: Double = 93.5 @@ -272,8 +261,7 @@ class CheckForFulfilledQuestsActionTest gameId = gameId, currentDate = date, currentRoundId = roundId, - provinces = - provinces :+ ProvinceC(id = 13, rulingFactionId = Some(otherFid)), + provinces = provinces :+ ProvinceC(id = 13, rulingFactionId = Some(otherFid)), factions = factions, battalions = Vector(), getHero = _ => None, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseActionTest.scala index 4f97d36a02..633a73e5f2 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndAttackDecisionPhaseActionTest.scala @@ -23,16 +23,9 @@ import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.TruceWithFactionQuest -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Resident, - Traveler -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Resident, Traveler} import net.eagle0.eagle.model.state.HostileArmyGroupStatus.Attacking import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -41,9 +34,9 @@ import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class EndAttackDecisionPhaseActionTest extends AnyFlatSpec with Matchers { - private val gameId: GameId = 0xfeedface + private val gameId: GameId = 0xfeedface private val currentRoundId: RoundId = 921 - private val currentDate = Date(year = 221, month = Date.Month.April) + private val currentDate = Date(year = 221, month = Date.Month.April) private val provincesWithWithdrawingArmy: Vector[ProvinceT] = Vector( ProvinceC( @@ -164,16 +157,17 @@ class EndAttackDecisionPhaseActionTest extends AnyFlatSpec with Matchers { forExactly(1, results) { result => result.actionResultType shouldBe QuestFailedResultType - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes should have size 1 - inside(cp.changedUnaffiliatedHeroes.head) { - case uh: UnaffiliatedHeroT => - uh.heroId shouldBe 3 - uh.unaffiliatedHeroType shouldBe Traveler - uh.recruitmentAttempted shouldBe false - uh.recruitmentInfo shouldBe RecruitmentInfo.Traveler - uh.factionBiases shouldBe Map(9 -> -50) - } + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes should have size 1 + inside(cp.changedUnaffiliatedHeroes.head) { + case uh: UnaffiliatedHeroT => + uh.heroId shouldBe 3 + uh.unaffiliatedHeroType shouldBe Traveler + uh.recruitmentAttempted shouldBe false + uh.recruitmentInfo shouldBe RecruitmentInfo.Traveler + uh.factionBiases shouldBe Map(9 -> -50) + } } } } @@ -203,22 +197,25 @@ class EndAttackDecisionPhaseActionTest extends AnyFlatSpec with Matchers { ) .results(1) - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newUnaffiliatedHeroes should have size 2 - inside(cp.newUnaffiliatedHeroes.head) { case uh: UnaffiliatedHeroT => - uh.heroId shouldBe 3 - uh.lastFactionId shouldBe Some(9) - uh.unaffiliatedHeroType shouldBe Outlaw - uh.recruitmentAttempted shouldBe false - uh.recruitmentInfo shouldBe RecruitmentInfo.Outlaw - } - inside(cp.newUnaffiliatedHeroes.last) { case uh: UnaffiliatedHeroT => - uh.heroId shouldBe 5 - uh.lastFactionId shouldBe Some(9) - uh.unaffiliatedHeroType shouldBe Outlaw - uh.recruitmentAttempted shouldBe false - uh.recruitmentInfo shouldBe RecruitmentInfo.Outlaw - } + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newUnaffiliatedHeroes should have size 2 + inside(cp.newUnaffiliatedHeroes.head) { + case uh: UnaffiliatedHeroT => + uh.heroId shouldBe 3 + uh.lastFactionId shouldBe Some(9) + uh.unaffiliatedHeroType shouldBe Outlaw + uh.recruitmentAttempted shouldBe false + uh.recruitmentInfo shouldBe RecruitmentInfo.Outlaw + } + inside(cp.newUnaffiliatedHeroes.last) { + case uh: UnaffiliatedHeroT => + uh.heroId shouldBe 5 + uh.lastFactionId shouldBe Some(9) + uh.unaffiliatedHeroType shouldBe Outlaw + uh.recruitmentAttempted shouldBe false + uh.recruitmentInfo shouldBe RecruitmentInfo.Outlaw + } } } @@ -231,8 +228,9 @@ class EndAttackDecisionPhaseActionTest extends AnyFlatSpec with Matchers { provinces = provincesWithWithdrawingArmy ).results.head - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.removedHostileArmyFactionIds shouldBe Vector(9) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.removedHostileArmyFactionIds shouldBe Vector(9) } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseActionTest.scala index 0ce0241026..f2e07eb08f 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndBattleAftermathPhaseActionTest.scala @@ -26,33 +26,18 @@ import net.eagle0.eagle.library.settings.{ TruceMonthsFromReturningLeader } import net.eagle0.eagle.library.util.validations.TestingNoopValidator -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.library.EagleInternalException -import net.eagle0.eagle.model.action_result.{ - ActionResultT, - NotificationDetails, - NotificationT -} +import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedFactionC, - ChangedHeroC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedFactionC, ChangedHeroC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.{ CapturedHeroExecutedMessage, CapturedHeroExiledMessage, CapturedHeroImprisonedMessage } -import net.eagle0.eagle.model.action_result.types.{ - CapturedHeroResolvedResultType, - EndAftermathPhaseResultType -} +import net.eagle0.eagle.model.action_result.types.{CapturedHeroResolvedResultType, EndAftermathPhaseResultType} import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.faction.FactionRelationship import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.Truce @@ -63,10 +48,7 @@ import net.eagle0.eagle.model.state.hero.{ } import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Prisoner -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Prisoner} import net.eagle0.eagle.model.state.RoundPhase import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -75,10 +57,7 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class EndBattleAftermathPhaseActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class EndBattleAftermathPhaseActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { FactionBiasFromImprisonment.setDoubleValue(-100) FactionBiasFromExile.setDoubleValue(-500) @@ -105,9 +84,10 @@ class EndBattleAftermathPhaseActionTest .randomResults(staticFr) .newValue - inside(results.head) { case ar: ActionResultT => - ar.actionResultType shouldBe EndAftermathPhaseResultType - ar.newRoundPhase should contain(RoundPhase.DiplomacyResolution) + inside(results.head) { + case ar: ActionResultT => + ar.actionResultType shouldBe EndAftermathPhaseResultType + ar.newRoundPhase should contain(RoundPhase.DiplomacyResolution) } } @@ -174,10 +154,9 @@ class EndBattleAftermathPhaseActionTest ) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy EndBattleAftermathPhaseAction(gameState, actionResultApplier) .randomResults(staticFr) - } ex.getMessage shouldBe "requirement failed: There is still a defending army in province 7" } @@ -192,24 +171,22 @@ class EndBattleAftermathPhaseActionTest HostileArmyGroup( factionId = 17, armies = Vector(), - status = - TributeDemanded(Some(TributeAmount(gold = 17, food = 11))) + status = TributeDemanded(Some(TributeAmount(gold = 17, food = 11))) ) ) ) ) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy EndBattleAftermathPhaseAction(gameState, actionResultApplier) .randomResults(staticFr) - } ex.getMessage shouldBe "requirement failed: There is still a hostile army with status TributeDemanded(Some(TributeAmount(17,11,UnknownFieldSet(Map()))),UnknownFieldSet(Map())) for faction 17 in province 7" } it should "remove an executed hero" in { val executedHero = Hero(id = 18, factionId = Some(7), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( currentDate = Some(DateProto(month = 6, year = 322)), gameId = 0xcafe, currentRoundId = 717, @@ -237,15 +214,16 @@ class EndBattleAftermathPhaseActionTest .randomResults(staticFr) .newValue - inside(results.head) { case ar: ActionResultT => - ar.actionResultType shouldBe CapturedHeroResolvedResultType - ar.removedHeroIds shouldBe Vector(18) + inside(results.head) { + case ar: ActionResultT => + ar.actionResultType shouldBe CapturedHeroResolvedResultType + ar.removedHeroIds shouldBe Vector(18) } } it should "have the captured hero resolved, hero backstories updated, and end aftermath phase result types" in { val executedHero = Hero(id = 18, factionId = Some(7), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( currentDate = Some(DateProto(month = 6, year = 322)), gameId = 0xcafe, currentRoundId = 717, @@ -279,7 +257,7 @@ class EndBattleAftermathPhaseActionTest it should "include notification for a captured hero executed" in { val executedHero = Hero(id = 18, factionId = Some(7), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( currentDate = Some(DateProto(month = 6, year = 322)), gameId = 0xcafe, currentRoundId = 717, @@ -304,37 +282,38 @@ class EndBattleAftermathPhaseActionTest .randomResults(staticFr) .newValue - inside(results.head) { case result: ActionResultT => - result.newNotifications shouldBe Vector( - NotificationC( - details = NotificationDetails.CapturedHeroExecuted( - capturedFromFactionId = 6, - provinceId = 7, - executedHeroId = 18, - executingFactionId = 3 - ), - llm = NotificationT.Llm.Id("execution 717 18"), - deferred = true + inside(results.head) { + case result: ActionResultT => + result.newNotifications shouldBe Vector( + NotificationC( + details = NotificationDetails.CapturedHeroExecuted( + capturedFromFactionId = 6, + provinceId = 7, + executedHeroId = 18, + executingFactionId = 3 + ), + llm = NotificationT.Llm.Id("execution 717 18"), + deferred = true + ) + ) + result.newGeneratedTextRequests.loneElement shouldBe CapturedHeroExecutedMessage( + requestId = "execution 717 18", + eagleGameId = 0xcafe, + recipientFactionIds = Vector.empty, + alwaysGenerate = false, + capturedHeroId = executedHero.id, + capturedHeroFactionId = 6, + actingHeroId = 71, + actingFactionId = 3, + provinceId = 7 ) - ) - result.newGeneratedTextRequests.loneElement shouldBe CapturedHeroExecutedMessage( - requestId = "execution 717 18", - eagleGameId = 0xcafe, - recipientFactionIds = Vector.empty, - alwaysGenerate = false, - capturedHeroId = executedHero.id, - capturedHeroFactionId = 6, - actingHeroId = 71, - actingFactionId = 3, - provinceId = 7 - ) } } it should "imprison an imprisoned hero" in { val imprisonedHero = Hero(id = 18, factionId = Some(6), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentDate = Some(DateProto(month = 6, year = 322)), currentRoundId = 717, @@ -368,28 +347,30 @@ class EndBattleAftermathPhaseActionTest .actionResults .newValue - inside(results.loneElement) { case result: ActionResultT => - result.actionResultType shouldBe CapturedHeroResolvedResultType - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 7 - cp.removedDeferredChangeIndex shouldBe Some(0) - cp.removedCapturedHeroIds shouldBe Vector(18) - inside(cp.newUnaffiliatedHeroes.loneElement) { - case uh: UnaffiliatedHeroC => - uh.heroId shouldBe 18 - uh.unaffiliatedHeroType shouldBe Prisoner - uh.factionBiases shouldBe Map(3 -> -100.0) - uh.lastFactionId shouldBe Some(6) - uh.recruitmentInfo shouldBe RecruitmentInfo.Prisoner + inside(results.loneElement) { + case result: ActionResultT => + result.actionResultType shouldBe CapturedHeroResolvedResultType + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 7 + cp.removedDeferredChangeIndex shouldBe Some(0) + cp.removedCapturedHeroIds shouldBe Vector(18) + inside(cp.newUnaffiliatedHeroes.loneElement) { + case uh: UnaffiliatedHeroC => + uh.heroId shouldBe 18 + uh.unaffiliatedHeroType shouldBe Prisoner + uh.factionBiases shouldBe Map(3 -> -100.0) + uh.lastFactionId shouldBe Some(6) + uh.recruitmentInfo shouldBe RecruitmentInfo.Prisoner + } } - } } } it should "include a notification for a captured hero imprisoned" in { val imprisonedHero = Hero(id = 18, factionId = Some(6), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -423,42 +404,43 @@ class EndBattleAftermathPhaseActionTest .actionResults .newValue - inside(results.loneElement) { case result: ActionResultT => - forExactly(1, result.newNotifications) { - case NotificationC( - details: NotificationDetails, - _ /* targetFactionIds */, - _ /* affectedProvinceIds */, - _ /* affectedHeroIds */, - llm: NotificationT.Llm, - deferred: Boolean - ) => - deferred shouldBe true - llm shouldBe NotificationT.Llm.Id("imprison 717 18") - inside(details) { - case capturedHeroImprisonedDetails: NotificationDetails.CapturedHeroImprisoned => - capturedHeroImprisonedDetails shouldBe - NotificationDetails.CapturedHeroImprisoned( - capturedFromFactionId = 6, - provinceId = 7, - imprisonedHeroId = 18, - imprisoningFactionId = 3 - ) - } - } - result.newGeneratedTextRequests should contain( - CapturedHeroImprisonedMessage( - requestId = "imprison 717 18", - eagleGameId = 0xcafe, - recipientFactionIds = Vector.empty, - alwaysGenerate = false, - capturedHeroId = 18, - capturedHeroFactionId = 6, - actingHeroId = 71, - actingFactionId = 3, - provinceId = 7 + inside(results.loneElement) { + case result: ActionResultT => + forExactly(1, result.newNotifications) { + case NotificationC( + details: NotificationDetails, + _ /* targetFactionIds */, + _ /* affectedProvinceIds */, + _ /* affectedHeroIds */, + llm: NotificationT.Llm, + deferred: Boolean + ) => + deferred shouldBe true + llm shouldBe NotificationT.Llm.Id("imprison 717 18") + inside(details) { + case capturedHeroImprisonedDetails: NotificationDetails.CapturedHeroImprisoned => + capturedHeroImprisonedDetails shouldBe + NotificationDetails.CapturedHeroImprisoned( + capturedFromFactionId = 6, + provinceId = 7, + imprisonedHeroId = 18, + imprisoningFactionId = 3 + ) + } + } + result.newGeneratedTextRequests should contain( + CapturedHeroImprisonedMessage( + requestId = "imprison 717 18", + eagleGameId = 0xcafe, + recipientFactionIds = Vector.empty, + alwaysGenerate = false, + capturedHeroId = 18, + capturedHeroFactionId = 6, + actingHeroId = 71, + actingFactionId = 3, + provinceId = 7 + ) ) - ) } } @@ -467,10 +449,9 @@ class EndBattleAftermathPhaseActionTest id = 18, factionId = Some(6), nameTextId = "hn_18", - backstoryVersions = - Vector(BackstoryVersion(textId = "backstory-18-717-1")) + backstoryVersions = Vector(BackstoryVersion(textId = "backstory-18-717-1")) ) - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -504,22 +485,24 @@ class EndBattleAftermathPhaseActionTest .actionResults .newValue - inside(results.loneElement) { case result: ActionResultT => - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe 18 - ch.newEventsForHeroBackstory.loneElement shouldBe CapturedHeroImprisonedBackstoryEvent( - date = Date(month = Date.Month.June, year = 322), - provinceId = 7, - capturingFactionId = 3, - capturingHeroId = 71 - ) - } + inside(results.loneElement) { + case result: ActionResultT => + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe 18 + ch.newEventsForHeroBackstory.loneElement shouldBe CapturedHeroImprisonedBackstoryEvent( + date = Date(month = Date.Month.June, year = 322), + provinceId = 7, + capturingFactionId = 3, + capturingHeroId = 71 + ) + } } } it should "exile an exiled hero" in { val exiledHero = Hero(id = 18, factionId = Some(6), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -553,29 +536,31 @@ class EndBattleAftermathPhaseActionTest .actionResults .newValue - inside(results.loneElement) { case result: ActionResultT => - result.actionResultType shouldBe CapturedHeroResolvedResultType + inside(results.loneElement) { + case result: ActionResultT => + result.actionResultType shouldBe CapturedHeroResolvedResultType - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 7 - cp.removedDeferredChangeIndex shouldBe Some(0) - cp.removedCapturedHeroIds shouldBe Vector(18) - cp.newUnaffiliatedHeroes.loneElement shouldBe ( - UnaffiliatedHeroC( - heroId = 18, - unaffiliatedHeroType = Outlaw, - factionBiases = Map(3 -> -500.0, 6 -> -200.0), - lastFactionId = Some(6), - recruitmentInfo = RecruitmentInfo.Outlaw - ) - ) - } + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 7 + cp.removedDeferredChangeIndex shouldBe Some(0) + cp.removedCapturedHeroIds shouldBe Vector(18) + cp.newUnaffiliatedHeroes.loneElement shouldBe ( + UnaffiliatedHeroC( + heroId = 18, + unaffiliatedHeroType = Outlaw, + factionBiases = Map(3 -> -500.0, 6 -> -200.0), + lastFactionId = Some(6), + recruitmentInfo = RecruitmentInfo.Outlaw + ) + ) + } } } it should "include a notification for a captured hero exiled" in { val exiledHero = Hero(id = 18, factionId = Some(6), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -609,31 +594,32 @@ class EndBattleAftermathPhaseActionTest .actionResults .newValue - inside(results.loneElement) { case result: ActionResultT => - forExactly(1, result.newNotifications) { - case notification: NotificationC => - notification.details shouldBe NotificationDetails.CapturedHeroExiled( - capturedFromFactionId = 6, - provinceId = 7, - exiledHeroId = 18, - exilingFactionId = 3 - ) - notification.llm shouldBe NotificationT.Llm.Id("exile 717 18") - } + inside(results.loneElement) { + case result: ActionResultT => + forExactly(1, result.newNotifications) { + case notification: NotificationC => + notification.details shouldBe NotificationDetails.CapturedHeroExiled( + capturedFromFactionId = 6, + provinceId = 7, + exiledHeroId = 18, + exilingFactionId = 3 + ) + notification.llm shouldBe NotificationT.Llm.Id("exile 717 18") + } - result.newGeneratedTextRequests should contain( - CapturedHeroExiledMessage( - requestId = "exile 717 18", - eagleGameId = 0xcafe, - recipientFactionIds = Vector.empty, - alwaysGenerate = false, - capturedHeroId = 18, - capturedHeroFactionId = 6, - actingHeroId = 71, - actingFactionId = 3, - provinceId = 7 + result.newGeneratedTextRequests should contain( + CapturedHeroExiledMessage( + requestId = "exile 717 18", + eagleGameId = 0xcafe, + recipientFactionIds = Vector.empty, + alwaysGenerate = false, + capturedHeroId = 18, + capturedHeroFactionId = 6, + actingHeroId = 71, + actingFactionId = 3, + provinceId = 7 + ) ) - ) } } @@ -642,10 +628,9 @@ class EndBattleAftermathPhaseActionTest id = 18, factionId = Some(6), nameTextId = "hn_18", - backstoryVersions = - Vector(BackstoryVersion(textId = "backstory-18-717-1")) + backstoryVersions = Vector(BackstoryVersion(textId = "backstory-18-717-1")) ) - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -679,22 +664,24 @@ class EndBattleAftermathPhaseActionTest .actionResults .newValue - inside(results.loneElement) { case result: ActionResultT => - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe 18 - ch.newEventsForHeroBackstory.loneElement shouldBe CapturedHeroExiledBackstoryEvent( - date = Date(month = Date.Month.June, year = 322), - provinceId = 7, - capturingFactionId = 3, - capturingHeroId = 71 - ) - } + inside(results.loneElement) { + case result: ActionResultT => + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe 18 + ch.newEventsForHeroBackstory.loneElement shouldBe CapturedHeroExiledBackstoryEvent( + date = Date(month = Date.Month.June, year = 322), + provinceId = 7, + capturingFactionId = 3, + capturingHeroId = 71 + ) + } } } it should "return a returned hero" in { val returnedHero = Hero(id = 18, factionId = Some(6), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -726,33 +713,33 @@ class EndBattleAftermathPhaseActionTest inside( EndBattleAftermathPhaseAction .deferredChangeAR( - deferredChange = - EndBattleAftermathPhaseAction.allDeferredChanges(gameState).head, + deferredChange = EndBattleAftermathPhaseAction.allDeferredChanges(gameState).head, gameState = gameState, functionalRandom = SeededRandom(0xfeed) ) .newValue - ) { case result: ActionResultT => - result.actionResultType shouldBe CapturedHeroResolvedResultType - result.changedProvinces should have size 2 - result.changedProvinces.head shouldBe ChangedProvinceC( - provinceId = 7, - removedDeferredChangeIndex = Some(0), - removedCapturedHeroIds = Vector(18) - ) - result.changedProvinces.last shouldBe ChangedProvinceC( - provinceId = 19, - newRulingFactionHeroIds = Vector(18) - ) - result.newNotifications.loneElement shouldBe NotificationC( - details = NotificationDetails.CapturedHeroReturned( - capturedFromFactionId = 6, + ) { + case result: ActionResultT => + result.actionResultType shouldBe CapturedHeroResolvedResultType + result.changedProvinces should have size 2 + result.changedProvinces.head shouldBe ChangedProvinceC( provinceId = 7, - returnedHeroId = 18, - returningFactionId = 3 - ), - deferred = true - ) + removedDeferredChangeIndex = Some(0), + removedCapturedHeroIds = Vector(18) + ) + result.changedProvinces.last shouldBe ChangedProvinceC( + provinceId = 19, + newRulingFactionHeroIds = Vector(18) + ) + result.newNotifications.loneElement shouldBe NotificationC( + details = NotificationDetails.CapturedHeroReturned( + capturedFromFactionId = 6, + provinceId = 7, + returnedHeroId = 18, + returningFactionId = 3 + ), + deferred = true + ) } } @@ -762,10 +749,9 @@ class EndBattleAftermathPhaseActionTest id = 18, factionId = Some(6), nameTextId = "hn_18", - backstoryVersions = - Vector(BackstoryVersion(textId = "backstory-18-717-1")) + backstoryVersions = Vector(BackstoryVersion(textId = "backstory-18-717-1")) ) - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -797,28 +783,29 @@ class EndBattleAftermathPhaseActionTest inside( EndBattleAftermathPhaseAction .deferredChangeAR( - deferredChange = - EndBattleAftermathPhaseAction.allDeferredChanges(gameState).head, + deferredChange = EndBattleAftermathPhaseAction.allDeferredChanges(gameState).head, gameState = gameState, functionalRandom = SeededRandom(0xfeed) ) .newValue - ) { case result: ActionResultT => - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe 18 - ch.newEventsForHeroBackstory.loneElement shouldBe CapturedHeroReturnedBackstoryEvent( - date = Date(month = Date.Month.June, year = 322), - provinceId = 7, - capturingFactionId = 3, - capturingHeroId = 71 - ) - } + ) { + case result: ActionResultT => + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe 18 + ch.newEventsForHeroBackstory.loneElement shouldBe CapturedHeroReturnedBackstoryEvent( + date = Date(month = Date.Month.June, year = 322), + provinceId = 7, + capturingFactionId = 3, + capturingHeroId = 71 + ) + } } } it should "add a truce for a returned hero" in { val returnedHero = Hero(id = 18, factionId = Some(6), nameTextId = "hn_18") - val gameState = GameState( + val gameState = GameState( gameId = 0xcafe, currentRoundId = 717, currentDate = Some(DateProto(month = 6, year = 322)), @@ -847,36 +834,36 @@ class EndBattleAftermathPhaseActionTest inside( EndBattleAftermathPhaseAction .deferredChangeAR( - deferredChange = - EndBattleAftermathPhaseAction.allDeferredChanges(gameState).head, + deferredChange = EndBattleAftermathPhaseAction.allDeferredChanges(gameState).head, gameState = gameState, functionalRandom = SeededRandom(0xface) ) .newValue - ) { case result: ActionResultT => - result.actionResultType shouldBe CapturedHeroResolvedResultType + ) { + case result: ActionResultT => + result.actionResultType shouldBe CapturedHeroResolvedResultType - // result.changedFactions should have size 2 - result.changedFactions.head shouldBe ChangedFactionC( - factionId = 3, - changedFactionRelationships = Vector( - FactionRelationship( - targetFactionId = 6, - relationshipLevel = Truce, - resetDate = Some(Date(month = Date.Month.June, year = 323)) + // result.changedFactions should have size 2 + result.changedFactions.head shouldBe ChangedFactionC( + factionId = 3, + changedFactionRelationships = Vector( + FactionRelationship( + targetFactionId = 6, + relationshipLevel = Truce, + resetDate = Some(Date(month = Date.Month.June, year = 323)) + ) ) ) - ) - result.changedFactions.last shouldBe ChangedFactionC( - factionId = 6, - changedFactionRelationships = Vector( - FactionRelationship( - targetFactionId = 3, - relationshipLevel = Truce, - resetDate = Some(Date(month = Date.Month.June, year = 323)) + result.changedFactions.last shouldBe ChangedFactionC( + factionId = 6, + changedFactionRelationships = Vector( + FactionRelationship( + targetFactionId = 3, + relationshipLevel = Truce, + resetDate = Some(Date(month = Date.Month.June, year = 323)) + ) ) ) - ) } } @@ -898,10 +885,9 @@ class EndBattleAftermathPhaseActionTest factions = mapifyFactions(Faction(id = 3)) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy EndBattleAftermathPhaseAction(gameState, actionResultApplier) .randomResults(staticFr) - } ex.getMessage shouldBe "Event should not be present in EndBattleAftermathPhaseAction" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseActionTest.scala index 3dfb4e83de..b5951fa91a 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDefenseDecisionPhaseActionTest.scala @@ -4,12 +4,7 @@ import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.common.action_result_type.ActionResultType.END_DEFENSE_DECISION_PHASE import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.internal.army.{ - Army, - HostileArmyGroup, - MovingArmy, - TributePaid -} +import net.eagle0.eagle.internal.army.{Army, HostileArmyGroup, MovingArmy, TributePaid} import net.eagle0.eagle.internal.changed_province.ChangedProvince import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState @@ -26,9 +21,9 @@ class EndDefenseDecisionPhaseActionTest extends AnyFlatSpec with Matchers { ) private val defendingProvinceId: ProvinceId = 1 - private val defenderFid: FactionId = 3 - private val attacker1Fid: FactionId = 7 - private val attacker2Fid: FactionId = 8 + private val defenderFid: FactionId = 3 + private val attacker1Fid: FactionId = 7 + private val attacker2Fid: FactionId = 8 private val tributeArmy1: HostileArmyGroup = HostileArmyGroup( status = TributePaid(), @@ -94,9 +89,9 @@ class EndDefenseDecisionPhaseActionTest extends AnyFlatSpec with Matchers { randomSeed = 1L, provinces = Map( defendingProvinceId -> defendingProvince, - 7 -> Province(id = 7), - 27 -> Province(id = 27), - 8 -> Province(id = 8) + 7 -> Province(id = 7), + 27 -> Province(id = 27), + 8 -> Province(id = 8) ), factions = Map( defenderFid -> Faction(id = defenderFid, leaders = Vector(19)) @@ -107,7 +102,7 @@ class EndDefenseDecisionPhaseActionTest extends AnyFlatSpec with Matchers { val results = EndDefenseDecisionPhaseAction( gameState ).execute(actionResultProtoApplier) - val lastAr = results.last.actionResult + val lastAr = results.last.actionResult lastAr.`type` shouldBe END_DEFENSE_DECISION_PHASE } @@ -122,8 +117,7 @@ class EndDefenseDecisionPhaseActionTest extends AnyFlatSpec with Matchers { allCps should contain( ChangedProvince( id = defendingProvinceId, - removedHostileArmyFactionIds = - Vector(tributeArmy1.factionId, tributeArmy2.factionId) + removedHostileArmyFactionIds = Vector(tributeArmy1.factionId, tributeArmy2.factionId) ) ) } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseActionTest.scala index a5e236deb9..09e78d4c9c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndDiplomacyResolutionPhaseActionTest.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.SeededRandom import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.actions.applier.{ - ActionResultProtoApplierImpl, - ActionResultTApplierImpl -} +import net.eagle0.eagle.library.actions.applier.{ActionResultProtoApplierImpl, ActionResultTApplierImpl} import net.eagle0.eagle.library.util.validations.TestingNoopValidator import net.eagle0.eagle.model.action_result.types.EndDiplomacyResolutionPhaseResultType import net.eagle0.eagle.model.state.RoundPhase @@ -14,12 +11,9 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class EndDiplomacyResolutionPhaseActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class EndDiplomacyResolutionPhaseActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val offeringFactionId = 7 - val actingFactionId = 4 + val actingFactionId = 4 val actionResultProtoApplier = new ActionResultProtoApplierImpl( validator = TestingNoopValidator @@ -27,7 +21,7 @@ class EndDiplomacyResolutionPhaseActionTest private val gameState: GameState = GameState() - private val applier = new ActionResultTApplierImpl(actionResultProtoApplier) + private val applier = new ActionResultTApplierImpl(actionResultProtoApplier) private val functionalRandom = SeededRandom(282) override def beforeEach(): Unit = {} diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseActionTest.scala index 45f8039671..6ac0409e5c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndHandleRiotsPhaseActionTest.scala @@ -5,10 +5,7 @@ import net.eagle0.eagle.api.available_command.HandleRiotDoNothingAvailableComman import net.eagle0.eagle.api.command.OneProvinceAvailableCommands import net.eagle0.eagle.api.selected_command.HandleRiotDoNothingSelectedCommand import net.eagle0.eagle.common.action_result_type.ActionResultType -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - RIOT_AVERSION_FAILED, - RIOT_AVERTED -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{RIOT_AVERSION_FAILED, RIOT_AVERTED} import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.province_event.ImminentRiotEvent import net.eagle0.eagle.common.round_phase.{NewRoundPhase, RoundPhase} @@ -37,16 +34,12 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class EndHandleRiotsPhaseActionTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers - with MockFactory { +class EndHandleRiotsPhaseActionTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers with MockFactory { private val actionResultProtoApplier = new ActionResultProtoApplierImpl( validator = TestingNoopValidator ) - private val commandFactory = mock[CommandFactory] + private val commandFactory = mock[CommandFactory] val fid = 19 val hid = 25 @@ -57,7 +50,7 @@ class EndHandleRiotsPhaseActionTest rulingFactionId = Some(fid), rulingHeroId = Some(hid) ) - private val province = ProvinceConverter.fromProto(provinceProto) + private val province = ProvinceConverter.fromProto(provinceProto) private val gameState: GameState = GameState( currentDate = Some(Date(year = 1501, month = 6)), @@ -66,8 +59,7 @@ class EndHandleRiotsPhaseActionTest provinces = Map( pid -> provinceProto ), - factions = - Map(fid -> Faction(id = fid, factionHeadId = 99, leaders = Vector(99))) + factions = Map(fid -> Faction(id = fid, factionHeadId = 99, leaders = Vector(99))) ) override def beforeEach(): Unit = { @@ -124,7 +116,7 @@ class EndHandleRiotsPhaseActionTest commandsForProvince.get, commandFactory ).results(actionResultProtoApplier) - val result = results.head + val result = results.head result.province shouldBe Some(pid) result.player shouldBe Some(fid) result.changedProvinces should have size 1 diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseActionTest.scala index 50581dafa0..9ce8258258 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/EndPlayerCommandsPhaseActionTest.scala @@ -4,10 +4,7 @@ import net.eagle0.common.SeededRandom import net.eagle0.eagle.common.date.Date as DateProto import net.eagle0.eagle.common.gender.Gender.GENDER_OTHER import net.eagle0.eagle.common.profession.Profession.NO_PROFESSION -import net.eagle0.eagle.common.province_event.{ - BlizzardEvent as BlizzardEventProto, - DroughtEvent as DroughtEventProto -} +import net.eagle0.eagle.common.province_event.{BlizzardEvent as BlizzardEventProto, DroughtEvent as DroughtEventProto} import net.eagle0.eagle.common.province_order_type.ProvinceOrderType import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo as RecruitmentInfoProto import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.{ @@ -24,23 +21,12 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.{Neighbor, Province} import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.actions.applier.{ - ActionResultProtoApplierImpl, - ActionResultTApplierImpl -} +import net.eagle0.eagle.library.actions.applier.{ActionResultProtoApplierImpl, ActionResultTApplierImpl} import net.eagle0.eagle.library.settings.PrisonerEscapeChance import net.eagle0.eagle.library.util.validations.TestingNoopValidator -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC} import net.eagle0.eagle.model.action_result.types.{ EndPlayerCommandsPhaseResultType, EpidemicTookEffectResultType, @@ -49,19 +35,9 @@ import net.eagle0.eagle.model.action_result.types.{ WeatherTookEffectResultType } import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.province.{ - BlizzardEvent, - DroughtEvent, - EpidemicEvent -} -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Prisoner -} +import net.eagle0.eagle.model.state.province.{BlizzardEvent, DroughtEvent, EpidemicEvent} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Prisoner} import net.eagle0.eagle.model.state.RoundPhase import net.eagle0.eagle.FactionId import org.scalatest.flatspec.AnyFlatSpec @@ -70,10 +46,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class EndPlayerCommandsPhaseActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class EndPlayerCommandsPhaseActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { super.beforeEach() PrisonerEscapeChance.setDoubleValue(0.05) @@ -83,7 +56,7 @@ class EndPlayerCommandsPhaseActionTest new ActionResultProtoApplierImpl(TestingNoopValidator) ) - private val rulingFactionId = 5 + private val rulingFactionId = 5 private val enemyFactionId: FactionId = 15 private val heroes = Vector( @@ -197,7 +170,7 @@ class EndPlayerCommandsPhaseActionTest it should "clear focus province if the abandoning faction had this province set" in { val gameStateWithNoHeroesInProvince = gameState.update( - _.provinces := mapifyProvinces( + _.provinces := mapifyProvinces( Province( id = 3, rulingHeroId = Some(7), @@ -280,19 +253,20 @@ class EndPlayerCommandsPhaseActionTest val deferredEvent = results.head - inside(deferredEvent) { case actionResult: ActionResultC => - actionResult.actionResultType shouldBe WeatherTookEffectResultType - actionResult.provinceId shouldBe Some(3) - inside(actionResult.changedProvinces.loneElement) { - case cp: ChangedProvinceC => - cp.provinceId shouldBe 3 - inside(cp.newProvinceEvents.get.loneElement) { - case pe: BlizzardEvent => - pe.startDate shouldBe Date(year = 1507, month = Date.Month.April) - pe.endDate shouldBe Date(year = 1507, month = Date.Month.July) - } - cp.removedDeferredChangeIndex shouldBe Some(0) - } + inside(deferredEvent) { + case actionResult: ActionResultC => + actionResult.actionResultType shouldBe WeatherTookEffectResultType + actionResult.provinceId shouldBe Some(3) + inside(actionResult.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 3 + inside(cp.newProvinceEvents.get.loneElement) { + case pe: BlizzardEvent => + pe.startDate shouldBe Date(year = 1507, month = Date.Month.April) + pe.endDate shouldBe Date(year = 1507, month = Date.Month.July) + } + cp.removedDeferredChangeIndex shouldBe Some(0) + } } } @@ -313,15 +287,16 @@ class EndPlayerCommandsPhaseActionTest actionResultApplier ).results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - deferredEvent.actionResultType shouldBe WeatherTookEffectResultType - deferredEvent.provinceId shouldBe Some(3) - inside(deferredEvent.changedProvinces.loneElement) { - case cp: ChangedProvinceC => - cp.provinceId shouldBe 3 - cp.newProvinceEvents shouldBe Some(Vector()) - cp.removedDeferredChangeIndex shouldBe Some(0) - } + inside(results.head) { + case deferredEvent: ActionResultC => + deferredEvent.actionResultType shouldBe WeatherTookEffectResultType + deferredEvent.provinceId shouldBe Some(3) + inside(deferredEvent.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 3 + cp.newProvinceEvents shouldBe Some(Vector()) + cp.removedDeferredChangeIndex shouldBe Some(0) + } } } @@ -337,18 +312,19 @@ class EndPlayerCommandsPhaseActionTest actionResultApplier ).results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - deferredEvent.actionResultType shouldBe EpidemicTookEffectResultType - deferredEvent.provinceId shouldBe Some(3) - inside(deferredEvent.changedProvinces.loneElement) { - case cp: ChangedProvinceC => - cp.provinceId shouldBe 3 - inside(cp.newProvinceEvents.get.loneElement) { - case pe: EpidemicEvent => - pe.startDate shouldBe Date(year = 1507, month = Date.Month.April) - } - cp.removedDeferredChangeIndex shouldBe Some(0) - } + inside(results.head) { + case deferredEvent: ActionResultC => + deferredEvent.actionResultType shouldBe EpidemicTookEffectResultType + deferredEvent.provinceId shouldBe Some(3) + inside(deferredEvent.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 3 + inside(cp.newProvinceEvents.get.loneElement) { + case pe: EpidemicEvent => + pe.startDate shouldBe Date(year = 1507, month = Date.Month.April) + } + cp.removedDeferredChangeIndex shouldBe Some(0) + } } } @@ -364,19 +340,20 @@ class EndPlayerCommandsPhaseActionTest actionResultApplier ).results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - deferredEvent.actionResultType shouldBe WeatherTookEffectResultType - deferredEvent.provinceId shouldBe Some(3) - inside(deferredEvent.changedProvinces.loneElement) { - case cp: ChangedProvinceC => - cp.provinceId shouldBe 3 - inside(cp.newProvinceEvents.get.loneElement) { - case de: DroughtEvent => - de.startDate shouldBe Date(year = 1507, month = Date.Month.April) - de.endDate shouldBe Date(year = 1507, month = Date.Month.July) - } - cp.removedDeferredChangeIndex shouldBe Some(0) - } + inside(results.head) { + case deferredEvent: ActionResultC => + deferredEvent.actionResultType shouldBe WeatherTookEffectResultType + deferredEvent.provinceId shouldBe Some(3) + inside(deferredEvent.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 3 + inside(cp.newProvinceEvents.get.loneElement) { + case de: DroughtEvent => + de.startDate shouldBe Date(year = 1507, month = Date.Month.April) + de.endDate shouldBe Date(year = 1507, month = Date.Month.July) + } + cp.removedDeferredChangeIndex shouldBe Some(0) + } } } @@ -397,15 +374,16 @@ class EndPlayerCommandsPhaseActionTest actionResultApplier ).results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - deferredEvent.actionResultType shouldBe WeatherTookEffectResultType - deferredEvent.provinceId shouldBe Some(3) - inside(deferredEvent.changedProvinces.loneElement) { - case cp: ChangedProvinceC => - cp.provinceId shouldBe 3 - cp.newProvinceEvents shouldBe Some(Vector()) - cp.removedDeferredChangeIndex shouldBe Some(0) - } + inside(results.head) { + case deferredEvent: ActionResultC => + deferredEvent.actionResultType shouldBe WeatherTookEffectResultType + deferredEvent.provinceId shouldBe Some(3) + inside(deferredEvent.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 3 + cp.newProvinceEvents shouldBe Some(Vector()) + cp.removedDeferredChangeIndex shouldBe Some(0) + } } } @@ -432,11 +410,13 @@ class EndPlayerCommandsPhaseActionTest ) .results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - inside(deferredEvent.changedProvinces.head) { case cp: ChangedProvinceC => - cp.removedUnaffiliatedHeroIds shouldBe Vector(57) - cp.removedDeferredChangeIndex shouldBe Some(0) - } + inside(results.head) { + case deferredEvent: ActionResultC => + inside(deferredEvent.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.removedUnaffiliatedHeroIds shouldBe Vector(57) + cp.removedDeferredChangeIndex shouldBe Some(0) + } } } @@ -464,18 +444,20 @@ class EndPlayerCommandsPhaseActionTest ) .results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - deferredEvent.actionResultType shouldBe PrisonerMoveTookEffectResultType - inside(deferredEvent.changedProvinces.last) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 4 - inside(cp.newUnaffiliatedHeroes.loneElement) { - case uh: UnaffiliatedHeroT => - uh.heroId shouldBe 57 - uh.unaffiliatedHeroType shouldBe Prisoner - uh.recruitmentInfo shouldBe RecruitmentInfo.Prisoner - uh.roundsInType shouldBe 6 + inside(results.head) { + case deferredEvent: ActionResultC => + deferredEvent.actionResultType shouldBe PrisonerMoveTookEffectResultType + inside(deferredEvent.changedProvinces.last) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 4 + inside(cp.newUnaffiliatedHeroes.loneElement) { + case uh: UnaffiliatedHeroT => + uh.heroId shouldBe 57 + uh.unaffiliatedHeroType shouldBe Prisoner + uh.recruitmentInfo shouldBe RecruitmentInfo.Prisoner + uh.roundsInType shouldBe 6 + } } - } } } @@ -504,30 +486,31 @@ class EndPlayerCommandsPhaseActionTest ) .results(SeededRandom(1)) - inside(results.head) { case deferredEvent: ActionResultC => - deferredEvent.actionResultType shouldBe PrisonerEscapedResultType - inside(deferredEvent.changedProvinces.last) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 4 - inside(cp.newUnaffiliatedHeroes.loneElement) { - case uh: UnaffiliatedHeroT => - uh.heroId shouldBe 57 - uh.unaffiliatedHeroType shouldBe Outlaw - uh.recruitmentInfo shouldBe RecruitmentInfo.Outlaw - uh.roundsInType shouldBe 0 + inside(results.head) { + case deferredEvent: ActionResultC => + deferredEvent.actionResultType shouldBe PrisonerEscapedResultType + inside(deferredEvent.changedProvinces.last) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 4 + inside(cp.newUnaffiliatedHeroes.loneElement) { + case uh: UnaffiliatedHeroT => + uh.heroId shouldBe 57 + uh.unaffiliatedHeroType shouldBe Outlaw + uh.recruitmentInfo shouldBe RecruitmentInfo.Outlaw + uh.roundsInType shouldBe 0 + } } - } } } it should "remove a prisoner if the province has a prisoner returned deferred event" in { val gameStateWithMovingPrisoner = gameState.update( _.provinces(4).rulingFactionId := enemyFactionId, - _.heroes(16).factionId := enemyFactionId, + _.heroes(16).factionId := enemyFactionId, _.provinces(3).unaffiliatedHeroes :+= UnaffiliatedHero( heroId = 57, `type` = UNAFFILIATED_HERO_RETURNING_PRISONER, - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ), _.provinces(3).deferredChanges :+= PrisonerReturned( heroId = 57, @@ -545,24 +528,25 @@ class EndPlayerCommandsPhaseActionTest ) .results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - inside(deferredEvent.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 3 - cp.removedUnaffiliatedHeroIds shouldBe Vector(57) - cp.removedDeferredChangeIndex shouldBe Some(0) - } + inside(results.head) { + case deferredEvent: ActionResultC => + inside(deferredEvent.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 3 + cp.removedUnaffiliatedHeroIds shouldBe Vector(57) + cp.removedDeferredChangeIndex shouldBe Some(0) + } } } it should "add the prisoner to the to province if there is a prisoner returned event" in { val gameStateWithMovingPrisoner = gameState.update( _.provinces(4).rulingFactionId := enemyFactionId, - _.heroes(16).factionId := enemyFactionId, + _.heroes(16).factionId := enemyFactionId, _.provinces(3).unaffiliatedHeroes :+= UnaffiliatedHero( heroId = 57, `type` = UNAFFILIATED_HERO_RETURNING_PRISONER, - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ), _.provinces(3).deferredChanges :+= PrisonerReturned( heroId = 57, @@ -580,15 +564,18 @@ class EndPlayerCommandsPhaseActionTest ) .results(seededRandom) - inside(results.head) { case deferredEvent: ActionResultC => - inside(deferredEvent.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe 57 - ch.newFactionId shouldBe Some(enemyFactionId) - } - inside(deferredEvent.changedProvinces.last) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 4 - cp.newRulingFactionHeroIds shouldBe Vector(57) - } + inside(results.head) { + case deferredEvent: ActionResultC => + inside(deferredEvent.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe 57 + ch.newFactionId shouldBe Some(enemyFactionId) + } + inside(deferredEvent.changedProvinces.last) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 4 + cp.newRulingFactionHeroIds shouldBe Vector(57) + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/FriendlyMoveActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/FriendlyMoveActionTest.scala index 45f8b53dd4..477caa457c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/FriendlyMoveActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/FriendlyMoveActionTest.scala @@ -17,9 +17,9 @@ class FriendlyMoveActionTest extends AnyFlatSpec with Matchers { Hero(id = 2, factionId = Some(movingFactionId)) ) - private val originProvinceId = 14 + private val originProvinceId = 14 private val destinationProvinceId = 13 - private val currentRoundId = 27 + private val currentRoundId = 27 private val movingArmy = MovingArmy( id = 22, @@ -114,8 +114,9 @@ class FriendlyMoveActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.removedIncomingArmyIds shouldBe Vector(movingArmy.id) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.removedIncomingArmyIds shouldBe Vector(movingArmy.id) } } @@ -127,8 +128,9 @@ class FriendlyMoveActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newRulingFactionHeroIds shouldBe movingArmy.army.units.map(_.heroId) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newRulingFactionHeroIds shouldBe movingArmy.army.units.map(_.heroId) } } @@ -140,8 +142,9 @@ class FriendlyMoveActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newBattalionIds shouldBe movingArmy.army.units.flatMap(_.battalionId) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newBattalionIds shouldBe movingArmy.army.units.flatMap(_.battalionId) } } @@ -153,10 +156,11 @@ class FriendlyMoveActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.goldDelta should contain( - (movingArmy.supplies.gold * (1.0 - movingArmy.suppliesLoss)).floor.toInt - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.goldDelta should contain( + (movingArmy.supplies.gold * (1.0 - movingArmy.suppliesLoss)).floor.toInt + ) } } @@ -168,10 +172,11 @@ class FriendlyMoveActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.foodDelta should contain( - (movingArmy.supplies.food * (1.0 - movingArmy.suppliesLoss)).floor.toInt - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.foodDelta should contain( + (movingArmy.supplies.food * (1.0 - movingArmy.suppliesLoss)).floor.toInt + ) } } @@ -183,8 +188,9 @@ class FriendlyMoveActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newRulingFactionId shouldBe empty + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newRulingFactionId shouldBe empty } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundActionTest.scala index f3896461e3..c06b748e71 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewRoundActionTest.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.impl.action -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - NEW_ROUND_ACTION, - NEW_YEAR_ACTION -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{NEW_ROUND_ACTION, NEW_YEAR_ACTION} import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.DEVELOP import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo @@ -14,29 +11,16 @@ import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.{ UNAFFILIATED_HERO_PRISONER, UNAFFILIATED_HERO_TRAVELER } -import net.eagle0.eagle.internal.army.{ - HostileArmyGroup, - MovingArmy, - Withdrawing -} -import net.eagle0.eagle.internal.changed_faction.{ - ChangedFaction, - TrustLevelUpdate -} +import net.eagle0.eagle.internal.army.{HostileArmyGroup, MovingArmy, Withdrawing} +import net.eagle0.eagle.internal.changed_faction.{ChangedFaction, TrustLevelUpdate} import net.eagle0.eagle.internal.changed_hero.ChangedHero -import net.eagle0.eagle.internal.changed_hero.ChangedHero.Loyalty.{ - LoyaltyAbsolute, - LoyaltyDelta -} +import net.eagle0.eagle.internal.changed_hero.ChangedHero.Loyalty.{LoyaltyAbsolute, LoyaltyDelta} import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor.VigorDelta import net.eagle0.eagle.internal.changed_province.ChangedProvince import net.eagle0.eagle.internal.chronicle_entry.ChronicleEntry import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship -import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.{ - HOSTILE, - TRUCE -} +import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.{HOSTILE, TRUCE} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province @@ -92,8 +76,8 @@ class NewRoundActionTest currentPhase = RoundPhase.NEW_ROUND, currentDate = Some(Date(year = 252, month = 7)), heroes = Map( - 3 -> Hero(id = 3), - 4 -> Hero(id = 4), + 3 -> Hero(id = 3), + 4 -> Hero(id = 4), 17 -> Hero(id = 17), 18 -> Hero(id = 18) ) @@ -138,12 +122,13 @@ class NewRoundActionTest val results = NewRoundAction(gsWithDevastation, mockHistory).resultsOfExecute() - inside(results.head.changedProvinces.head) { case cp: ChangedProvince => - cp.id shouldBe 7 - cp.setHasActed shouldBe Some(false) - cp.economyDevastationDelta shouldBe Some(-2.0) - cp.agricultureDevastationDelta shouldBe Some(-2.0) - cp.infrastructureDevastationDelta shouldBe Some(-2.0) + inside(results.head.changedProvinces.head) { + case cp: ChangedProvince => + cp.id shouldBe 7 + cp.setHasActed shouldBe Some(false) + cp.economyDevastationDelta shouldBe Some(-2.0) + cp.agricultureDevastationDelta shouldBe Some(-2.0) + cp.infrastructureDevastationDelta shouldBe Some(-2.0) } } @@ -162,12 +147,13 @@ class NewRoundActionTest val results = NewRoundAction(gsWithDevastation, mockHistory).resultsOfExecute() - inside(results.head.changedProvinces.head) { case cp: ChangedProvince => - cp.id shouldBe 7 - cp.setHasActed shouldBe Some(false) - cp.economyDevastationDelta shouldBe Some(-0.3) - cp.agricultureDevastationDelta shouldBe Some(-1.9) - cp.infrastructureDevastationDelta shouldBe None + inside(results.head.changedProvinces.head) { + case cp: ChangedProvince => + cp.id shouldBe 7 + cp.setHasActed shouldBe Some(false) + cp.economyDevastationDelta shouldBe Some(-0.3) + cp.agricultureDevastationDelta shouldBe Some(-1.9) + cp.infrastructureDevastationDelta shouldBe None } } @@ -197,7 +183,7 @@ class NewRoundActionTest it should "advance the year if month was 12" in { val endOfYearGameState = midyearGameState.withCurrentDate(Date(year = 252, month = 12)) - val results = + val results = NewRoundAction(endOfYearGameState, mockHistory).resultsOfExecute() results.find(_.`type` == NEW_ROUND_ACTION).get.newDate shouldBe Some( @@ -208,7 +194,7 @@ class NewRoundActionTest it should "also return a NewYearAction if month was 12" in { val endOfYearGameState = midyearGameState.withCurrentDate(Date(year = 252, month = 12)) - val results = + val results = NewRoundAction(endOfYearGameState, mockHistory).resultsOfExecute() results.head.`type` shouldBe NEW_YEAR_ACTION @@ -283,7 +269,7 @@ class NewRoundActionTest loyalty = 1, roundIdJoined = Some(2) ) - ) ++ ((3 to 10).toVector) + ) ++ (3 to 10).toVector .map(hid => hid -> Hero( id = hid, @@ -292,7 +278,7 @@ class NewRoundActionTest roundIdJoined = Some(2) ) ) - ++ ((11 to 12).toVector) + ++ (11 to 12).toVector .map(hid => hid -> Hero( id = hid, @@ -308,7 +294,7 @@ class NewRoundActionTest id = 7, rulingFactionId = Some(10), rulingHeroId = Some(2), - rulingFactionHeroIds = (((1 to 12).toVector)).toVector, + rulingFactionHeroIds = (1 to 12).toVector.toVector, provinceOrders = DEVELOP, gold = 2, castleCount = 2, @@ -322,9 +308,7 @@ class NewRoundActionTest results.head.changedHeroes should contain theSameElementsAs (Vector( ChangedHero(id = 1, loyalty = LoyaltyDelta(-2)), ChangedHero(id = 2, loyalty = LoyaltyAbsolute(0)) - ) ++ ((3 to 12).toVector).map(hid => - ChangedHero(id = hid, loyalty = LoyaltyDelta(-2)) - )) + ) ++ (3 to 12).toVector.map(hid => ChangedHero(id = hid, loyalty = LoyaltyDelta(-2)))) } it should "not lower loyalty if we're not over the cap after dropping recent heroes" in { @@ -344,7 +328,7 @@ class NewRoundActionTest loyalty = 1, roundIdJoined = Some(2) ) - ) ++ ((3 to 10).toVector) + ) ++ (3 to 10).toVector .map(hid => hid -> Hero( id = hid, @@ -353,7 +337,7 @@ class NewRoundActionTest roundIdJoined = Some(2) ) ) - ++ ((11 to 12).toVector) + ++ (11 to 12).toVector .map(hid => hid -> Hero( id = hid, @@ -400,7 +384,7 @@ class NewRoundActionTest loyalty = 1, roundIdJoined = Some(2) ) - ) ++ ((3 to 11).toVector) + ) ++ (3 to 11).toVector .map(hid => hid -> Hero( id = hid, @@ -409,7 +393,7 @@ class NewRoundActionTest roundIdJoined = Some(2) ) ) - ++ ((12 to 12).toVector) + ++ (12 to 12).toVector .map(hid => hid -> Hero( id = hid, @@ -425,7 +409,7 @@ class NewRoundActionTest id = 7, rulingFactionId = Some(10), rulingHeroId = Some(2), - rulingFactionHeroIds = ((1 to 12).toVector), + rulingFactionHeroIds = (1 to 12).toVector, provinceOrders = DEVELOP, gold = 2, castleCount = 2, @@ -436,7 +420,7 @@ class NewRoundActionTest val results = NewRoundAction(gameState, mockHistory).resultsOfExecute() - results.head.changedHeroes should contain theSameElementsAs ((1 to 12).toVector) + results.head.changedHeroes should contain theSameElementsAs (1 to 12).toVector .map(hid => ChangedHero(id = hid, loyalty = LoyaltyDelta(-1))) } @@ -486,29 +470,27 @@ class NewRoundActionTest it should "increment the rounds in type of unaffiliated heroes" in { val gameState = midyearGameState.update( - _.heroes := Map( - 3 -> Hero(id = 3), - 4 -> Hero(id = 4), + _.heroes := Map( + 3 -> Hero(id = 3), + 4 -> Hero(id = 4), 17 -> Hero(id = 17) ), _.provinces := Map( - 7 -> Province( + 7 -> Province( id = 7, unaffiliatedHeroes = Vector( UnaffiliatedHero( heroId = 3, `type` = UNAFFILIATED_HERO_TRAVELER, roundsInType = 3, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ), UnaffiliatedHero( heroId = 4, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 0, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ) ), @@ -519,8 +501,7 @@ class NewRoundActionTest heroId = 17, `type` = UNAFFILIATED_HERO_OUTLAW, roundsInType = 23, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) ) ) @@ -540,15 +521,13 @@ class NewRoundActionTest heroId = 3, `type` = UNAFFILIATED_HERO_TRAVELER, roundsInType = 4, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ), UnaffiliatedHero( heroId = 4, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 1, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ) } @@ -561,8 +540,7 @@ class NewRoundActionTest heroId = 17, `type` = UNAFFILIATED_HERO_OUTLAW, roundsInType = 24, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) ) } @@ -572,7 +550,7 @@ class NewRoundActionTest val gameState = midyearGameState.update( _.provinces := Map( - 7 -> Province( + 7 -> Province( id = 7, unaffiliatedHeroes = Vector( UnaffiliatedHero( @@ -580,16 +558,14 @@ class NewRoundActionTest `type` = UNAFFILIATED_HERO_TRAVELER, roundsInType = 3, factionBiases = Map(3 -> -20), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ), UnaffiliatedHero( heroId = 4, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 0, factionBiases = Map(5 -> 200), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ) ), @@ -601,16 +577,14 @@ class NewRoundActionTest `type` = UNAFFILIATED_HERO_OUTLAW, roundsInType = 23, factionBiases = Map(3 -> -50.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ), UnaffiliatedHero( heroId = 18, `type` = UNAFFILIATED_HERO_OUTLAW, roundsInType = 25, factionBiases = Map(3 -> -5), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) ) ) @@ -622,58 +596,56 @@ class NewRoundActionTest mockHistory ).resultsOfExecute().head.changedProvinces - inside(cps.head) { case cp: ChangedProvince => - cp.id shouldBe 7 - cp.setHasActed shouldBe Some(false) - cp.changedUnaffiliatedHeroes should contain theSameElementsAs Vector( - UnaffiliatedHero( - heroId = 3, - `type` = UNAFFILIATED_HERO_TRAVELER, - roundsInType = 4, - factionBiases = Map(3 -> -10.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) - ), - UnaffiliatedHero( - heroId = 4, - `type` = UNAFFILIATED_HERO_PRISONER, - roundsInType = 1, - factionBiases = Map(5 -> 180), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + inside(cps.head) { + case cp: ChangedProvince => + cp.id shouldBe 7 + cp.setHasActed shouldBe Some(false) + cp.changedUnaffiliatedHeroes should contain theSameElementsAs Vector( + UnaffiliatedHero( + heroId = 3, + `type` = UNAFFILIATED_HERO_TRAVELER, + roundsInType = 4, + factionBiases = Map(3 -> -10.0), + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + ), + UnaffiliatedHero( + heroId = 4, + `type` = UNAFFILIATED_HERO_PRISONER, + roundsInType = 1, + factionBiases = Map(5 -> 180), + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + ) ) - ) } - inside(cps.last) { case cp: ChangedProvince => - cp.id shouldBe 12 - cp.setHasActed shouldBe Some(false) - cp.changedUnaffiliatedHeroes should contain theSameElementsAs Vector( - UnaffiliatedHero( - heroId = 17, - `type` = UNAFFILIATED_HERO_OUTLAW, - roundsInType = 24, - factionBiases = Map(3 -> -40.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) - ), - UnaffiliatedHero( - heroId = 18, - `type` = UNAFFILIATED_HERO_OUTLAW, - roundsInType = 26, - factionBiases = Map(3 -> 0.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + inside(cps.last) { + case cp: ChangedProvince => + cp.id shouldBe 12 + cp.setHasActed shouldBe Some(false) + cp.changedUnaffiliatedHeroes should contain theSameElementsAs Vector( + UnaffiliatedHero( + heroId = 17, + `type` = UNAFFILIATED_HERO_OUTLAW, + roundsInType = 24, + factionBiases = Map(3 -> -40.0), + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + ), + UnaffiliatedHero( + heroId = 18, + `type` = UNAFFILIATED_HERO_OUTLAW, + roundsInType = 26, + factionBiases = Map(3 -> 0.0), + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + ) ) - ) } } it should "remove expired truces" in { - val currentDate = Date(year = 252, month = 5) + val currentDate = Date(year = 252, month = 5) val gsWithTruces = midyearGameState.update( _.currentDate := currentDate, - _.factions := Map( + _.factions := Map( 3 -> Faction( id = 3, factionRelationships = Vector( @@ -836,11 +808,10 @@ class NewRoundActionTest )) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy NewRoundAction(gameStateWithOldArmy, mockHistory).execute( actionResultProtoApplier ) - } ex.getMessage shouldBe "requirement failed: Province 9 has an army that should have already arrived" } @@ -858,11 +829,10 @@ class NewRoundActionTest )) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy NewRoundAction(gameStateWithHostileArmy, mockHistory).execute( actionResultProtoApplier ) - } ex.getMessage shouldBe "requirement failed: Province 9 has hostile armies at the round start" } @@ -870,7 +840,7 @@ class NewRoundActionTest it should "include a chronicle notification if in November" in { val gameState = midyearGameState.withCurrentDate(Date(year = 252, month = 10)) - val results = NewRoundAction(gameState, mockHistory).resultsOfExecute() + val results = NewRoundAction(gameState, mockHistory).resultsOfExecute() val relevantAction = results.find(_.`type` == NEW_ROUND_ACTION).get relevantAction.newChronicleEntry should contain( @@ -884,7 +854,7 @@ class NewRoundActionTest it should "include a chronicle LLM request if in November" in { val gameState = midyearGameState.withCurrentDate(Date(year = 252, month = 10)) - val results = NewRoundAction(gameState, mockHistory).resultsOfExecute() + val results = NewRoundAction(gameState, mockHistory).resultsOfExecute() val relevantAction = results.find(_.`type` == NEW_ROUND_ACTION).get relevantAction.newGeneratedTextRequests should have size 1 diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewYearActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewYearActionTest.scala index 803a6405e9..ec0426394a 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewYearActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/NewYearActionTest.scala @@ -20,10 +20,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class NewYearActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class NewYearActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val lowSupportProvince = Province( id = 17, rulingFactionId = Some(1), @@ -47,20 +44,20 @@ class NewYearActionTest ) private val provincesMap = Map( - lowSupportProvince.id -> lowSupportProvince, + lowSupportProvince.id -> lowSupportProvince, highSupportProvince.id -> highSupportProvince ) - private val factionLeader = Hero( + private val factionLeader = Hero( id = 7, loyalty = 100, integrity = 70, gregariousness = 70, bravery = 70 ) - private val swornBrother = + private val swornBrother = Hero(id = 9, factionId = Some(1), loyalty = 100, roundIdJoined = Some(9)) - private val provinceLeader = + private val provinceLeader = Hero(id = 11, factionId = Some(1), loyalty = 70, roundIdJoined = Some(5)) private val highDiscordHero = Hero( id = 13, @@ -71,7 +68,7 @@ class NewYearActionTest bravery = 15, roundIdJoined = Some(12) ) - private val lowDiscordHero = Hero( + private val lowDiscordHero = Hero( id = 15, factionId = Some(1), loyalty = 55, @@ -156,9 +153,7 @@ class NewYearActionTest it should "degrade the economy in all provinces" in { val result = NewYearAction(startingGameState).immediateExecute - val oldAndNew = provincesMap.values.map(p => - (p, result.changedProvinces.find(_.id == p.id).get) - ) + val oldAndNew = provincesMap.values.map(p => (p, result.changedProvinces.find(_.id == p.id).get)) for (oldProv, newProv) <- oldAndNew do { newProv.economyDelta shouldBe empty @@ -169,9 +164,7 @@ class NewYearActionTest it should "degrade the agriculture in all provinces" in { val result = NewYearAction(startingGameState).immediateExecute - val oldAndNew = provincesMap.values.map(p => - (p, result.changedProvinces.find(_.id == p.id).get) - ) + val oldAndNew = provincesMap.values.map(p => (p, result.changedProvinces.find(_.id == p.id).get)) for (oldProv, newProv) <- oldAndNew do { newProv.agricultureDelta shouldBe empty @@ -184,9 +177,7 @@ class NewYearActionTest it should "degrade the infrastructure in all provinces" in { val result = NewYearAction(startingGameState).immediateExecute - val oldAndNew = provincesMap.values.map(p => - (p, result.changedProvinces.find(_.id == p.id).get) - ) + val oldAndNew = provincesMap.values.map(p => (p, result.changedProvinces.find(_.id == p.id).get)) for (oldProv, newProv) <- oldAndNew do { newProv.infrastructureDelta shouldBe empty @@ -199,13 +190,9 @@ class NewYearActionTest it should "degrade the support in all provinces" in { val result = NewYearAction(startingGameState).immediateExecute - val oldAndNew = provincesMap.values.map(p => - (p, result.changedProvinces.find(_.id == p.id).get) - ) + val oldAndNew = provincesMap.values.map(p => (p, result.changedProvinces.find(_.id == p.id).get)) - for (oldProv, newProv) <- oldAndNew do { - newProv.supportDelta should contain(-0.15 * oldProv.support) - } + for (oldProv, newProv) <- oldAndNew do newProv.supportDelta should contain(-0.15 * oldProv.support) } it should "degrade the armament of all battalions" in { @@ -214,9 +201,7 @@ class NewYearActionTest val oldAndNew = battalions.map(b => (b, result.changedBattalions.find(_.id == b.id).get)) - for (oldB, newB) <- oldAndNew do { - newB.armament shouldBe (0.85 * oldB.armament) - } + for (oldB, newB) <- oldAndNew do newB.armament shouldBe (0.85 * oldB.armament) } it should "degrade the training of all battalions" in { @@ -225,16 +210,14 @@ class NewYearActionTest val oldAndNew = battalions.map(b => (b, result.changedBattalions.find(_.id == b.id).get)) - for (oldB, newB) <- oldAndNew do { - newB.training shouldBe (0.85 * oldB.training) - } + for (oldB, newB) <- oldAndNew do newB.training shouldBe (0.85 * oldB.training) } it should "modify the loyalty of a non-leader hero" in { val modState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := highDiscordHero.id, + _.rulingHeroId := highDiscordHero.id, _.rulingFactionHeroIds := Vector(highDiscordHero.id) ) ) @@ -249,7 +232,7 @@ class NewYearActionTest val modState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := highDiscordHero.id, + _.rulingHeroId := highDiscordHero.id, _.rulingFactionHeroIds := Vector(highDiscordHero.id) ) ), @@ -265,7 +248,7 @@ class NewYearActionTest val modState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := factionLeader.id, + _.rulingHeroId := factionLeader.id, _.rulingFactionHeroIds := Vector(factionLeader.id, swornBrother.id) ) ) @@ -279,7 +262,7 @@ class NewYearActionTest val highAmbitionGameState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := lowDiscordHero.id, + _.rulingHeroId := lowDiscordHero.id, _.rulingFactionHeroIds := Vector( lowDiscordHero.id, highDiscordHero.id @@ -295,11 +278,11 @@ class NewYearActionTest val highAmbitionResult = NewYearAction(highAmbitionGameState).immediateExecute - val lowAmbitionResult = NewYearAction(lowAmbitionGameState).immediateExecute + val lowAmbitionResult = NewYearAction(lowAmbitionGameState).immediateExecute val highAmbitionHeroAfter = highAmbitionResult.changedHeroes.find(_.id == highDiscordHero.id).get - val lowAmbitionHeroAfter = + val lowAmbitionHeroAfter = lowAmbitionResult.changedHeroes.find(_.id == lowDiscordHero.id).get highAmbitionHeroAfter.loyalty.loyaltyDelta.get should be < lowAmbitionHeroAfter.loyalty.loyaltyDelta.get @@ -309,7 +292,7 @@ class NewYearActionTest val highAmbitionGameState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := highDiscordHero.id, + _.rulingHeroId := highDiscordHero.id, _.rulingFactionHeroIds := Vector( lowDiscordHero.id, highDiscordHero.id @@ -325,11 +308,11 @@ class NewYearActionTest val highAmbitionResult = NewYearAction(highAmbitionGameState).immediateExecute - val lowAmbitionResult = NewYearAction(lowAmbitionGameState).immediateExecute + val lowAmbitionResult = NewYearAction(lowAmbitionGameState).immediateExecute val highAmbitionHeroAfter = highAmbitionResult.changedHeroes.find(_.id == highDiscordHero.id).get - val lowAmbitionHeroAfter = + val lowAmbitionHeroAfter = lowAmbitionResult.changedHeroes.find(_.id == highDiscordHero.id).get highAmbitionHeroAfter.loyalty.loyaltyDelta shouldBe lowAmbitionHeroAfter.loyalty.loyaltyDelta @@ -339,7 +322,7 @@ class NewYearActionTest val modGameState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := swornBrother.id, + _.rulingHeroId := swornBrother.id, _.rulingFactionHeroIds := Vector( swornBrother.id, lowDiscordHero.id, @@ -355,7 +338,7 @@ class NewYearActionTest val highDiscordHeroAfter = result.changedHeroes.find(_.id == highDiscordHero.id).get - val lowDiscordHeroAfter = + val lowDiscordHeroAfter = result.changedHeroes.find(_.id == lowDiscordHero.id).get highDiscordHeroAfter.loyalty.loyaltyDelta.get should be < lowDiscordHeroAfter.loyalty.loyaltyDelta.get @@ -363,17 +346,17 @@ class NewYearActionTest it should "not increase a loyalty beyond 100" in { val noDiscordHero = lowDiscordHero.update( - _.ambition := 0, - _.integrity := factionLeader.integrity, + _.ambition := 0, + _.integrity := factionLeader.integrity, _.gregariousness := factionLeader.gregariousness, - _.bravery := factionLeader.bravery, - _.loyalty := 99 + _.bravery := factionLeader.bravery, + _.loyalty := 99 ) val modGameState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := noDiscordHero.id, + _.rulingHeroId := noDiscordHero.id, _.rulingFactionHeroIds := Vector( noDiscordHero.id ) @@ -395,7 +378,7 @@ class NewYearActionTest val modGameState = startingGameState.update( _.provinces(lowSupportProvince.id).modify( _.update( - _.rulingHeroId := swornBrother.id, + _.rulingHeroId := swornBrother.id, _.rulingFactionHeroIds := Vector( swornBrother.id, highDiscordHero.id @@ -403,7 +386,7 @@ class NewYearActionTest ) ), _.heroes(highDiscordHero.id).ambition := 100, - _.heroes(highDiscordHero.id).loyalty := 3 + _.heroes(highDiscordHero.id).loyalty := 3 ) val result = diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseActionTest.scala index 2592d4b21c..e0002e3132 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformFoodConsumptionPhaseActionTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_CAVALRY, - LIGHT_INFANTRY -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_CAVALRY, LIGHT_INFANTRY} import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.round_phase.RoundPhase @@ -20,10 +17,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PerformFoodConsumptionPhaseActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class PerformFoodConsumptionPhaseActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val battalionTypes = Vector( @@ -46,8 +40,8 @@ class PerformFoodConsumptionPhaseActionTest currentPhase = RoundPhase.NEW_ROUND, currentDate = Some(Date(year = 252, month = 7)), heroes = Map( - 3 -> Hero(id = 3), - 4 -> Hero(id = 4), + 3 -> Hero(id = 3), + 4 -> Hero(id = 4), 17 -> Hero(id = 17), 18 -> Hero(id = 18) ), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackActionTest.scala index d179b9060d..d407eed30c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformForcedTurnBackActionTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.ProtoMatchers.equalProto -import net.eagle0.eagle.common.action_result_notification_details.{ - Notification, - ShatteredArmyDetails -} +import net.eagle0.eagle.common.action_result_notification_details.{Notification, ShatteredArmyDetails} import net.eagle0.eagle.common.action_result_notification_details.ShatteredArmyDetails.Reason.SHATTERED_ARMY_REASON_BLIZZARD import net.eagle0.eagle.common.action_result_type.ActionResultType.{ ARMY_SHATTERED, @@ -36,22 +33,18 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PerformForcedTurnBackActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class PerformForcedTurnBackActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val actionResultProtoApplier = new ActionResultProtoApplierImpl( validator = RuntimeValidator ) private val destinationPid: ProvinceId = 17 - private val fleePid: ProvinceId = 28 + private val fleePid: ProvinceId = 28 private val currentDate = Some(Date(year = 123, month = 4)) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = WinterSuppliesLoss.setDoubleValue(0.25) - } private val provinceWithBlizzard = Province( id = destinationPid, @@ -74,19 +67,17 @@ class PerformForcedTurnBackActionTest private val gsWithBlizzard = GameState( currentRoundId = 27, currentDate = currentDate, - provinces = - Map(destinationPid -> provinceWithBlizzard, fleePid -> fleeProvince) + provinces = Map(destinationPid -> provinceWithBlizzard, fleePid -> fleeProvince) ) private val gsWithoutBlizzard = GameState( currentRoundId = 27, currentDate = Some(Date(year = 123, month = 4)), - provinces = - Map(destinationPid -> provinceWithoutBlizzard, fleePid -> fleeProvince) + provinces = Map(destinationPid -> provinceWithoutBlizzard, fleePid -> fleeProvince) ) "results" should "include an end phase result" in { - val gs = gsWithoutBlizzard + val gs = gsWithoutBlizzard val results = PerformForcedTurnBackAction(gs = gs).results(actionResultProtoApplier) @@ -100,7 +91,7 @@ class PerformForcedTurnBackActionTest } it should "include a weather forced turn back event for an incoming army into a province with a blizzard" in { - val gs = gsWithBlizzard.update( + val gs = gsWithBlizzard.update( _.provinces(destinationPid).incomingArmies := Vector( MovingArmy( id = 99, @@ -159,7 +150,7 @@ class PerformForcedTurnBackActionTest } it should "include a shattered army event if there is no flee province" in { - val gs = gsWithBlizzard.update( + val gs = gsWithBlizzard.update( _.provinces(destinationPid).incomingArmies := Vector( MovingArmy( id = 99, @@ -201,8 +192,7 @@ class PerformForcedTurnBackActionTest heroId = 5, `type` = UNAFFILIATED_HERO_OUTLAW, lastFaction = Some(54), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) ) ) @@ -223,7 +213,7 @@ class PerformForcedTurnBackActionTest } it should "not include a weather forced turn back event if no blizzard" in { - val gs = gsWithoutBlizzard.update( + val gs = gsWithoutBlizzard.update( _.provinces(destinationPid).incomingArmies := Vector( MovingArmy( id = 99, @@ -248,7 +238,7 @@ class PerformForcedTurnBackActionTest } it should "generate a send back supplies event if sending supplies into a blizzard" in { - val gs = gsWithBlizzard.update( + val gs = gsWithBlizzard.update( _.provinces(destinationPid).incomingShipments := Vector( MovingSupplies( id = 12, @@ -297,7 +287,7 @@ class PerformForcedTurnBackActionTest } it should "lose the supplies if there's nowhere to flee" in { - val gs = gsWithBlizzard.update( + val gs = gsWithBlizzard.update( _.provinces(destinationPid).incomingShipments := Vector( MovingSupplies( id = 12, @@ -332,7 +322,7 @@ class PerformForcedTurnBackActionTest } it should "not generate a turn back event if there's no blizzard" in { - val gs = gsWithoutBlizzard.update( + val gs = gsWithoutBlizzard.update( _.provinces(destinationPid).incomingShipments := Vector( MovingSupplies( id = 12, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesActionTest.scala index add1d66ab8..666ec758c7 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHeroDeparturesActionTest.scala @@ -2,10 +2,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.ProtoMatchers.equalProto import net.eagle0.common.StaticRandom -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_HERO_DEPARTURE_PHASE, - HEROES_DEPARTED -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_HERO_DEPARTURE_PHASE, HEROES_DEPARTED} import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.hero_backstory_version.BackstoryVersion import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo @@ -13,50 +10,41 @@ import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.RECRUITMENT_ST import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFFILIATED_HERO_TRAVELER import net.eagle0.eagle.internal.changed_hero.ChangedHero import net.eagle0.eagle.internal.changed_province.ChangedProvince -import net.eagle0.eagle.internal.event_for_hero_backstory.{ - EventForHeroBackstory, - HeroDepartedBackstoryEvent -} +import net.eagle0.eagle.internal.event_for_hero_backstory.{EventForHeroBackstory, HeroDepartedBackstoryEvent} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplierImpl -import net.eagle0.eagle.library.settings.{ - FactionBiasFromDeparture, - LoyaltyThreshold -} +import net.eagle0.eagle.library.settings.{FactionBiasFromDeparture, LoyaltyThreshold} import net.eagle0.eagle.library.util.validations.RuntimeValidator import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PerformHeroDeparturesActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class PerformHeroDeparturesActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val actionResultProtoApplier = new ActionResultProtoApplierImpl( validator = RuntimeValidator ) private val factionId = 5 - private val faction = Faction(id = factionId) + private val faction = Faction(id = factionId) - private val hero1 = Hero( + private val hero1 = Hero( id = 7, factionId = Some(factionId), loyalty = 20, backstoryVersions = Vector(BackstoryVersion(textId = "backstory-7")) ) - private val hero2 = Hero( + private val hero2 = Hero( id = 9, factionId = Some(factionId), loyalty = 50, backstoryVersions = Vector(BackstoryVersion(textId = "backstory-9")) ) - private val province = + private val province = Province( id = 17, rulingFactionId = Some(factionId), @@ -125,7 +113,7 @@ class PerformHeroDeparturesActionTest } "immediateExecute" should "set the basics" in { - val action = PerformHeroDeparturesAction(gameState, StaticRandom(0.05)) + val action = PerformHeroDeparturesAction(gameState, StaticRandom(0.05)) val results = action.results(actionResultProtoApplier) results.head.`type` shouldBe HEROES_DEPARTED @@ -154,8 +142,7 @@ class PerformHeroDeparturesActionTest `type` = UNAFFILIATED_HERO_TRAVELER, recruitmentAttempted = true, factionBiases = Map(factionId -> -100.0), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ) ) } @@ -243,8 +230,7 @@ class PerformHeroDeparturesActionTest `type` = UNAFFILIATED_HERO_TRAVELER, factionBiases = Map(factionId -> -100.0), recruitmentAttempted = true, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ) ) ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupActionTest.scala index d6b0a1e29f..29241ac011 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformHostileArmySetupActionTest.scala @@ -5,12 +5,7 @@ import net.eagle0.eagle.{FactionId, RoundId} import net.eagle0.eagle.common.action_result_type.ActionResultType.SET_UP_HOSTILE_ARMIES import net.eagle0.eagle.common.round_phase.NewRoundPhase import net.eagle0.eagle.common.round_phase.RoundPhase.FREE_FOR_ALL_DECISION -import net.eagle0.eagle.internal.army.{ - Army, - AwaitingDecision, - HostileArmyGroup, - MovingArmy -} +import net.eagle0.eagle.internal.army.{Army, AwaitingDecision, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.changed_province.ChangedProvince import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.{Neighbor, Province} @@ -19,15 +14,12 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PerformHostileArmySetupActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class PerformHostileArmySetupActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val currentRoundId: RoundId = 524 + private val currentRoundId: RoundId = 524 private val rulingFactionId: FactionId = 12 - private val anotherFactionId = 3 - private val neighborProvinceId = 19 + private val anotherFactionId = 3 + private val neighborProvinceId = 19 private val province: Province = Province( id = 98, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsActionTest.scala index a7482f5f63..028306becb 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceEventsActionTest.scala @@ -61,10 +61,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PerformProvinceEventsActionTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class PerformProvinceEventsActionTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { BlizzardEventChance.setDoubleValue(0.1) @@ -215,11 +212,10 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), - provinceEventRolls = - noEventsRoll.copy(beastsRoll = 0.01, beastTypeRoll = 0.01) + provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.01, beastTypeRoll = 0.01) ) .get @@ -250,7 +246,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.01) @@ -267,14 +263,13 @@ class PerformProvinceEventsActionTest 7 -> Province( id = 7, rulingFactionId = Some(fid), - activeEvents = - Vector(FestivalEvent(endDate = Some(Date(year = 1502, month = 11)))) + activeEvents = Vector(FestivalEvent(endDate = Some(Date(year = 1502, month = 11)))) ) ) ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.01) @@ -351,7 +346,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.5) @@ -385,7 +380,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.5) @@ -419,7 +414,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.5) @@ -453,7 +448,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.5) @@ -586,8 +581,7 @@ class PerformProvinceEventsActionTest val cp = PerformProvinceEventsAction(imminentRiotGS) .changedProvince( province = imminentRiotGS.provinces(7), - provinceEventRolls = - noEventsRoll.copy(beastsRoll = 0.01, riotRoll = 0.01) + provinceEventRolls = noEventsRoll.copy(beastsRoll = 0.01, riotRoll = 0.01) ) .get @@ -717,7 +711,7 @@ class PerformProvinceEventsActionTest it should "not add a blizzard if it is not winter" in { val summerGS = blizzardGS.withCurrentDate(Date(year = 1502, month = 6)) - val cp = PerformProvinceEventsAction(summerGS) + val cp = PerformProvinceEventsAction(summerGS) .changedProvince( province = summerGS.provinces(7), provinceEventRolls = noEventsRoll.copy(blizzardRoll = 0.01) @@ -732,7 +726,7 @@ class PerformProvinceEventsActionTest BlizzardEvent(endDate = Some(Date(year = 1502, month = 11))) ) ) - val cp = PerformProvinceEventsAction(alreadyBlizzardGS) + val cp = PerformProvinceEventsAction(alreadyBlizzardGS) .changedProvince( province = alreadyBlizzardGS.provinces(7), provinceEventRolls = noEventsRoll.copy(blizzardRoll = 0.01) @@ -879,7 +873,7 @@ class PerformProvinceEventsActionTest endDate = Some(Date(year = 1502, month = 11)) ) ) - val cp = PerformProvinceEventsAction( + val cp = PerformProvinceEventsAction( festivalGS.update(_.provinces(7) := province) ).changedProvince( province = province, @@ -897,7 +891,7 @@ class PerformProvinceEventsActionTest endDate = Some(Date(year = 1502, month = 11)) ) ) - val cp = PerformProvinceEventsAction( + val cp = PerformProvinceEventsAction( festivalGS.update(_.provinces(7) := province) ).changedProvince( province = province, @@ -926,7 +920,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll @@ -995,7 +989,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll @@ -1028,7 +1022,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll @@ -1061,7 +1055,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll @@ -1093,7 +1087,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll @@ -1125,7 +1119,7 @@ class PerformProvinceEventsActionTest ) val action = PerformProvinceEventsAction(gameState) - val cp = action + val cp = action .changedProvince( province = gameState.provinces(7), provinceEventRolls = noEventsRoll.copy(epidemicStartRoll = 0.005) @@ -1134,8 +1128,7 @@ class PerformProvinceEventsActionTest cp.newProvinceEvents.get should equalProto( ProvinceEventsReplacement( - newEvents = - Vector(EpidemicEvent(startDate = Some(Date(year = 1501, month = 7)))) + newEvents = Vector(EpidemicEvent(startDate = Some(Date(year = 1501, month = 7)))) ) ) } @@ -1271,13 +1264,11 @@ class PerformProvinceEventsActionTest id = 7, economy = 51.0, infrastructure = 40.0, - neighbors = - Vector(Neighbor(provinceId = 8, startingPositionIndex = 3)) + neighbors = Vector(Neighbor(provinceId = 8, startingPositionIndex = 3)) ), 8 -> Province( id = 8, - neighbors = - Vector(Neighbor(provinceId = 7, startingPositionIndex = 9)), + neighbors = Vector(Neighbor(provinceId = 7, startingPositionIndex = 9)), activeEvents = Vector(EpidemicEvent()) ) ) @@ -1291,8 +1282,7 @@ class PerformProvinceEventsActionTest .get .getNewProvinceEvents should equalProto( ProvinceEventsReplacement( - newEvents = - Vector(EpidemicEvent(startDate = Some(Date(year = 1501, month = 7)))) + newEvents = Vector(EpidemicEvent(startDate = Some(Date(year = 1501, month = 7)))) ) ) } @@ -1439,7 +1429,7 @@ class PerformProvinceEventsActionTest it should "not add a drought if it is not the season" in { val springGS = droughtGS.withCurrentDate(Date(year = 1502, month = 3)) - val cp = PerformProvinceEventsAction(springGS) + val cp = PerformProvinceEventsAction(springGS) .changedProvince( province = springGS.provinces(7), provinceEventRolls = noEventsRoll.copy(droughtRoll = 0.01) @@ -1454,7 +1444,7 @@ class PerformProvinceEventsActionTest DroughtEvent(endDate = Some(Date(year = 1502, month = 11))) ) ) - val cp = PerformProvinceEventsAction(alreadyDroughtGS) + val cp = PerformProvinceEventsAction(alreadyDroughtGS) .changedProvince( province = alreadyDroughtGS.provinces(7), provinceEventRolls = noEventsRoll.copy(droughtRoll = 0.01) @@ -1469,7 +1459,7 @@ class PerformProvinceEventsActionTest FloodEvent(endDate = Some(Date(year = 1502, month = 11))) ) ) - val cp = PerformProvinceEventsAction(alreadyFloodGS) + val cp = PerformProvinceEventsAction(alreadyFloodGS) .changedProvince( province = alreadyFloodGS.provinces(7), provinceEventRolls = noEventsRoll.copy(droughtRoll = 0.01) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionActionTest.scala index cd36c33a10..06e9c783c2 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformProvinceMoveResolutionActionTest.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.impl.action -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_PROVINCE_EVENTS_PHASE, - FRIENDLY_MOVE -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_PROVINCE_EVENTS_PHASE, FRIENDLY_MOVE} import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.gender.Gender.GENDER_OTHER @@ -23,11 +20,9 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.Inspectors.{forAll, forExactly} -class PerformProvinceMoveResolutionActionTest - extends AnyFlatSpec - with Matchers { +class PerformProvinceMoveResolutionActionTest extends AnyFlatSpec with Matchers { - private val movingPlayer = 3 + private val movingPlayer = 3 private val currentRoundId = 27 private val movingArmy = MovingArmy( @@ -90,13 +85,13 @@ class PerformProvinceMoveResolutionActionTest factionHeadId = 2, leaders = Vector(2) ), - 125 -> Faction(id = 125, factionHeadId = 126, leaders = Vector(126)) + 125 -> Faction(id = 125, factionHeadId = 126, leaders = Vector(126)) ), currentRoundId = currentRoundId, currentPhase = PROVINCE_MOVE_RESOLUTION, provinces = Map( province1.id -> province1, - 300 -> Province( + 300 -> Province( id = 300, rulingFactionId = Some(125), rulingHeroId = Some(126), @@ -104,9 +99,9 @@ class PerformProvinceMoveResolutionActionTest ) ), heroes = Map( - 1 -> minimalHero(1), - 2 -> minimalHero(2), - 4 -> minimalHero(4), + 1 -> minimalHero(1), + 2 -> minimalHero(2), + 4 -> minimalHero(4), 126 -> Hero( id = 126, factionId = Some(125), @@ -123,10 +118,10 @@ class PerformProvinceMoveResolutionActionTest val startingStateWithNoMovingArmies = startingState.update( _.provinces(province1.id) := province1.clearIncomingArmies ) - val action = PerformProvinceMoveResolutionAction( + val action = PerformProvinceMoveResolutionAction( startingState = startingStateWithNoMovingArmies ) - val results = action.resultsOfExecute() + val results = action.resultsOfExecute() results.head.`type` shouldBe END_PROVINCE_EVENTS_PHASE } @@ -163,7 +158,7 @@ class PerformProvinceMoveResolutionActionTest val moveResults = results.filter(_.`type` == FRIENDLY_MOVE) moveResults should have size 2 - forAll(moveResults) { _.province should contain(p.id) } + forAll(moveResults)(_.province should contain(p.id)) moveResults.last.changedProvinces.head.addedRulingPlayerHeroIds should contain theSameElementsAs Vector( 4 @@ -181,8 +176,8 @@ class PerformProvinceMoveResolutionActionTest rulingFactionHeroIds = Vector(6), incomingArmies = Vector( secondMovingArmy.update( - _.army.factionId := 99, - _.originProvince := 5, + _.army.factionId := 99, + _.originProvince := 5, _.destinationProvince := 4 ) ), @@ -190,8 +185,8 @@ class PerformProvinceMoveResolutionActionTest ) val gs = startingState.update( - _.heroes(6) := minimalHero(6).withFactionId(99), - _.heroes(4) := minimalHero(4).withFactionId(99), + _.heroes(6) := minimalHero(6).withFactionId(99), + _.heroes(4) := minimalHero(4).withFactionId(99), _.provinces(province2.id) := province2 ) @@ -203,7 +198,7 @@ class PerformProvinceMoveResolutionActionTest val moveResults = results.filter(_.`type` == FRIENDLY_MOVE) moveResults should have size 2 - forAll(moveResults) { _.`type` shouldBe FRIENDLY_MOVE } + forAll(moveResults)(_.`type` shouldBe FRIENDLY_MOVE) forExactly(1, moveResults) { result => result.province should contain(province1.id) result.changedProvinces.map(_.id) shouldBe Vector(province1.id) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionActionTest.scala index 8ad020fe2a..08c6818392 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformReconResolutionActionTest.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.actions.impl.action import scala.util.Random import net.eagle0.common.SeededRandom -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_RECON_RESOLUTION_PHASE, - RECON_SUCCEEDED -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_RECON_RESOLUTION_PHASE, RECON_SUCCEEDED} import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.hero_backstory_version.BackstoryVersion import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.ENTRUST @@ -22,25 +19,19 @@ import net.eagle0.eagle.internal.province.{IncomingEndTurnAction, Province} import net.eagle0.eagle.internal.province.IncomingEndTurnAction.IncomingRecon import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplierImpl -import net.eagle0.eagle.library.settings.{ - BaseResourceLimit, - PerDevelopmentResourceLimit -} +import net.eagle0.eagle.library.settings.{BaseResourceLimit, PerDevelopmentResourceLimit} import net.eagle0.eagle.library.util.validations.TestingNoopValidator import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PerformReconResolutionActionTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class PerformReconResolutionActionTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val actionResultProtoApplier = new ActionResultProtoApplierImpl( validator = TestingNoopValidator ) - private val actingFaction = 7 + private val actingFaction = 7 private val incomingRecon: IncomingEndTurnAction = IncomingEndTurnAction( fromFactionId = 7, fromProvinceId = 9, @@ -48,21 +39,21 @@ class PerformReconResolutionActionTest IncomingRecon(heroId = 19) ) ) - private val currentDate: Date = Date(year = 7238, month = 4) + private val currentDate: Date = Date(year = 7238, month = 4) private val gameState = GameState( factions = Map( actingFaction -> Faction(id = actingFaction) ), provinces = Map( - 3 -> Province( + 3 -> Province( id = 3, rulingFactionId = Some(2), rulingFactionHeroIds = Vector(100, 101, 102), incomingEndTurnActions = Vector(incomingRecon), provinceOrders = ENTRUST ), - 9 -> Province( + 9 -> Province( id = 9, rulingFactionId = Some(7), provinceOrders = ENTRUST @@ -75,7 +66,7 @@ class PerformReconResolutionActionTest 15 -> Province(id = 15) ), heroes = Map( - 19 -> Hero(id = 19, factionId = Some(7)), + 19 -> Hero(id = 19, factionId = Some(7)), 100 -> Hero( id = 100, factionId = Some(2), @@ -95,7 +86,7 @@ class PerformReconResolutionActionTest currentDate = Some(currentDate) ) - private val random = new Random() + private val random = new Random() private var functionalRandom = SeededRandom(0) override def beforeEach(): Unit = { @@ -165,7 +156,7 @@ class PerformReconResolutionActionTest it should "just make the hero unaffiliated otherwise" in { val gsWithLostProvinces = gameState.update( - _.provinces(9).rulingFactionId := 2, + _.provinces(9).rulingFactionId := 2, _.provinces(10).rulingFactionId := 3 ) @@ -255,15 +246,14 @@ class PerformReconResolutionActionTest IncomingEndTurnAction( fromFactionId = 3, fromProvinceId = 3, - action = - IncomingEndTurnAction.Action.Recon(IncomingRecon(heroId = 25)) + action = IncomingEndTurnAction.Action.Recon(IncomingRecon(heroId = 25)) ) ) ), - _.heroes(23) := Hero(id = 23, factionId = Some(2)), - _.heroes(25) := Hero(id = 25, factionId = Some(3)), - _.factions(3) := Faction(id = 3), - _.factions(2) := Faction(id = 2) + _.heroes(23) := Hero(id = 23, factionId = Some(2)), + _.heroes(25) := Hero(id = 25, factionId = Some(3)), + _.factions(3) := Faction(id = 3), + _.factions(2) := Faction(id = 2) ) val allResults = PerformReconResolutionAction( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesActionTest.scala index 1defe42ae8..6bf8bd2e13 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUnaffiliatedHeroesActionTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.ProtoMatchers.equalProto -import net.eagle0.eagle.common.action_result_notification_details.{ - Notification, - OutlawSpottedDetails -} +import net.eagle0.eagle.common.action_result_notification_details.{Notification, OutlawSpottedDetails} import net.eagle0.eagle.common.action_result_notification_details.Notification.TargetFaction import net.eagle0.eagle.common.action_result_type.ActionResultType.{ END_UNAFFILIATED_HERO_ACTIONS_PHASE, @@ -60,19 +57,12 @@ import net.eagle0.eagle.library.settings.{ VigorToConstitutionXpMultiplier, XpForStatBump } -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PerformUnaffiliatedHeroesActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class PerformUnaffiliatedHeroesActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { RestVigorGain.setDoubleValue(17.2) MinVigorForFreeHeroMove.setDoubleValue(60) @@ -97,8 +87,8 @@ class PerformUnaffiliatedHeroesActionTest "movableNeighbors" should "include exactly neighbors without a blizzard" in { val gs = GameState( provinces = Map( - 3 -> Province(id = 3), - 6 -> Province( + 3 -> Province(id = 3), + 6 -> Province( id = 6, neighbors = Vector( Neighbor(provinceId = 3, startingPositionIndex = 0), @@ -106,11 +96,11 @@ class PerformUnaffiliatedHeroesActionTest Neighbor(provinceId = 12, startingPositionIndex = 2) ) ), - 7 -> Province( + 7 -> Province( id = 7, activeEvents = Vector(BlizzardEvent()) ), - 9 -> Province(id = 9), // not a neighbor + 9 -> Province(id = 9), // not a neighbor 12 -> Province(id = 12) ) ) @@ -139,8 +129,7 @@ class PerformUnaffiliatedHeroesActionTest UnaffiliatedHero( `type` = UNAFFILIATED_HERO_TRAVELER, heroId = 19, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ) ) ) @@ -184,8 +173,7 @@ class PerformUnaffiliatedHeroesActionTest heroId = 17, `type` = UNAFFILIATED_HERO_OUTLAW, lastFaction = Some(6), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) ) ) @@ -234,8 +222,7 @@ class PerformUnaffiliatedHeroesActionTest heroId = 17, `type` = UNAFFILIATED_HERO_OUTLAW, lastFaction = Some(6), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ) ) ) @@ -289,8 +276,7 @@ class PerformUnaffiliatedHeroesActionTest heroId = 17, `type` = UNAFFILIATED_HERO_PRISONER, lastFaction = Some(6), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ), provinceOrders = ENTRUST @@ -316,8 +302,7 @@ class PerformUnaffiliatedHeroesActionTest factionId = Some(23) ) ), - factions = - mapifyFactions(Faction(id = 23, factionHeadId = 9), Faction(id = 6)) + factions = mapifyFactions(Faction(id = 23, factionHeadId = 9), Faction(id = 6)) ) val results = PerformUnaffiliatedHeroesAction( @@ -343,8 +328,7 @@ class PerformUnaffiliatedHeroesActionTest heroId = 17, `type` = UNAFFILIATED_HERO_PRISONER, lastFaction = Some(6), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ) ) @@ -404,8 +388,7 @@ class PerformUnaffiliatedHeroesActionTest heroId = 17, `type` = UNAFFILIATED_HERO_PRISONER, lastFaction = Some(6), - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ) ) @@ -430,8 +413,7 @@ class PerformUnaffiliatedHeroesActionTest factionId = Some(23) ) ), - factions = - mapifyFactions(Faction(id = 23), Faction(id = 6, leaders = Vector(17))) + factions = mapifyFactions(Faction(id = 23), Faction(id = 6, leaders = Vector(17))) ) val results = PerformUnaffiliatedHeroesAction( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestActionTest.scala index 0f0f584474..ed101d77a2 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformUncontestedConquestActionTest.scala @@ -37,7 +37,7 @@ class PerformUncontestedConquestActionTest extends AnyFlatSpec with Matchers { private val attackerId = 1 private val heroes: Map[Int, HeroC] = Map( - 92 -> HeroC( + 92 -> HeroC( id = 92, factionId = Some(attackerId), nameTextId = "hn_92", @@ -249,10 +249,11 @@ class PerformUncontestedConquestActionTest extends AnyFlatSpec with Matchers { battalions = battalions ).results - inside(results.head.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId.shouldBe(5) - cp.goldDelta.shouldBe(Some(200)) - cp.foodDelta.shouldBe(Some(300)) + inside(results.head.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId.shouldBe(5) + cp.goldDelta.shouldBe(Some(200)) + cp.foodDelta.shouldBe(Some(300)) } } @@ -411,7 +412,7 @@ class PerformUncontestedConquestActionTest extends AnyFlatSpec with Matchers { ) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy PerformUncontestedConquestAction( gameId = 12345L, currentRoundId = 9, @@ -421,7 +422,6 @@ class PerformUncontestedConquestActionTest extends AnyFlatSpec with Matchers { heroes = heroes, battalions = battalions ).results - } ex.getMessage.shouldBe( "requirement failed: Attacking armies Vector(1, 2) are not mutually allied" @@ -440,7 +440,7 @@ class PerformUncontestedConquestActionTest extends AnyFlatSpec with Matchers { val provinces = Map( 17 -> ProvinceC(id = 17, rulingFactionId = Some(1)), 27 -> ProvinceC(id = 27, rulingFactionId = Some(2)), - 5 -> ProvinceC( + 5 -> ProvinceC( id = 5, rulingFactionId = None, rulingHeroId = None, @@ -529,47 +529,53 @@ class PerformUncontestedConquestActionTest extends AnyFlatSpec with Matchers { ) ) ) - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId.shouldBe(17) - inside(cp.newIncomingArmies.loneElement) { case ma: MovingArmy => - ma.id.shouldBe(17) - ma.originProvinceId.shouldBe(5) - ma.arrivalRound.shouldBe(10) - ma.supplies.shouldBe(Supplies(300, 200)) - ma.startingPositionIndex.shouldBe(None) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId.shouldBe(17) + inside(cp.newIncomingArmies.loneElement) { + case ma: MovingArmy => + ma.id.shouldBe(17) + ma.originProvinceId.shouldBe(5) + ma.arrivalRound.shouldBe(10) + ma.supplies.shouldBe(Supplies(300, 200)) + ma.startingPositionIndex.shouldBe(None) - inside(ma.army) { case army: Army => - army.factionId.shouldBe(1) - army.units.loneElement.shouldBe( - CombatUnit( - heroId = 92, - battalionId = Some(34), - factionId = 1 - ) - ) + inside(ma.army) { + case army: Army => + army.factionId.shouldBe(1) + army.units.loneElement.shouldBe( + CombatUnit( + heroId = 92, + battalionId = Some(34), + factionId = 1 + ) + ) + } } - } } - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId.shouldBe(27) - inside(cp.newIncomingArmies.loneElement) { case ma: MovingArmy => - ma.id.shouldBe(717) - ma.originProvinceId.shouldBe(5) - ma.arrivalRound.shouldBe(10) - ma.supplies.shouldBe(Supplies(500, 400)) - ma.startingPositionIndex.shouldBe(None) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId.shouldBe(27) + inside(cp.newIncomingArmies.loneElement) { + case ma: MovingArmy => + ma.id.shouldBe(717) + ma.originProvinceId.shouldBe(5) + ma.arrivalRound.shouldBe(10) + ma.supplies.shouldBe(Supplies(500, 400)) + ma.startingPositionIndex.shouldBe(None) - inside(ma.army) { case army: Army => - army.factionId.shouldBe(2) - army.units.loneElement.shouldBe( - CombatUnit( - heroId = 102, - battalionId = Some(99), - factionId = 2 - ) - ) + inside(ma.army) { + case army: Army => + army.factionId.shouldBe(2) + army.units.loneElement.shouldBe( + CombatUnit( + heroId = 102, + battalionId = Some(99), + factionId = 2 + ) + ) + } } - } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseActionTest.scala index c7b2a282ef..60b5ddc8ef 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PerformVassalCommandsPhaseActionTest.scala @@ -6,23 +6,12 @@ import net.eagle0.common.SeededRandom import net.eagle0.eagle.api.available_command.* import net.eagle0.eagle.api.command.util.battalion_with_food_cost.BattalionWithFoodCost import net.eagle0.eagle.api.command.OneProvinceAvailableCommands -import net.eagle0.eagle.api.selected_command.{ - HeroGiftSelectedCommand, - RestSelectedCommand, - SendSuppliesSelectedCommand -} +import net.eagle0.eagle.api.selected_command.{HeroGiftSelectedCommand, RestSelectedCommand, SendSuppliesSelectedCommand} import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_CAVALRY, - HEAVY_INFANTRY, - LIGHT_INFANTRY -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_CAVALRY, HEAVY_INFANTRY, LIGHT_INFANTRY} import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.improvement_type.ImprovementType.* -import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{ - DEVELOP, - EXPAND -} +import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{DEVELOP, EXPAND} import net.eagle0.eagle.internal.army.{Army, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction @@ -55,11 +44,7 @@ import net.eagle0.eagle.library.settings.{ import net.eagle0.eagle.library.util.command_choice_helpers.CommandChoiceHelpers import net.eagle0.eagle.library.util.command_choice_helpers.SelectedCommandMatcher.* import net.eagle0.eagle.library.util.CommandSelection -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.model.state.game_state.GameState import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec @@ -67,11 +52,7 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class PerformVassalCommandsPhaseActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach - with MockFactory { +class PerformVassalCommandsPhaseActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach with MockFactory { import net.eagle0.common.ProtoMatchers.* @@ -81,14 +62,14 @@ class PerformVassalCommandsPhaseActionTest private val actingFactionId = 19 - private val fullyRestedHero1 = + private val fullyRestedHero1 = Hero( factionId = Some(actingFactionId), id = 1, vigor = 90, constitution = 90 ) - private val fullyRestedHero2 = + private val fullyRestedHero2 = Hero( factionId = Some(actingFactionId), id = 2, @@ -102,14 +83,14 @@ class PerformVassalCommandsPhaseActionTest vigor = 75, constitution = 80 ) - private val veryTiredHero1 = + private val veryTiredHero1 = Hero( factionId = Some(actingFactionId), id = 4, vigor = 50, constitution = 70 ) - private val veryTiredHero2 = + private val veryTiredHero2 = Hero( factionId = Some(actingFactionId), id = 5, @@ -124,7 +105,7 @@ class PerformVassalCommandsPhaseActionTest vigor = 50, constitution = 50 ) - private val hostileHero = + private val hostileHero = Hero( factionId = Some(actingFactionId + 1), id = 7, @@ -135,7 +116,7 @@ class PerformVassalCommandsPhaseActionTest private val unownedProvince1 = Province(id = 27, heroCap = 15) private val unownedProvince2 = Province(id = 31, heroCap = 15) private val unownedProvince3 = Province(id = 39, heroCap = 15) - private val ownedProvince = + private val ownedProvince = Province( id = 41, rulingFactionId = Some(actingFactionId), @@ -143,7 +124,7 @@ class PerformVassalCommandsPhaseActionTest rulingFactionHeroIds = Vector(6), heroCap = 15 ) - private val hostileProvince = + private val hostileProvince = Province( id = 43, rulingFactionId = Some(actingFactionId + 1), @@ -151,7 +132,7 @@ class PerformVassalCommandsPhaseActionTest rulingFactionHeroIds = Vector(7), heroCap = 15 ) - private val enRouteProvince = Province( + private val enRouteProvince = Province( id = 45, incomingArmies = Vector( MovingArmy( @@ -175,7 +156,7 @@ class PerformVassalCommandsPhaseActionTest id = 7, rulingFactionId = Some(actingFactionId), rulingHeroId = Some(1), - rulingFactionHeroIds = ((1 to 5).toVector), + rulingFactionHeroIds = (1 to 5).toVector, infrastructure = 20, economy = 50, agriculture = 40, @@ -228,7 +209,7 @@ class PerformVassalCommandsPhaseActionTest factions = mapifyFactions(Faction(id = 19)) ) - val leader: Hero = Hero(id = 99, factionId = Some(actingFactionId)) + val leader: Hero = Hero(id = 99, factionId = Some(actingFactionId)) val faction: Faction = Faction( id = actingFactionId, @@ -350,7 +331,7 @@ class PerformVassalCommandsPhaseActionTest "loyaltyManagementCommand" should "return a feast command if there are several heroes low on loyalty" in { val developingProvince = actingProvince.withProvinceOrders(DEVELOP) - val developingGS = + val developingGS = gameState.update(_.provinces(developingProvince.id) := developingProvince) val selection = PerformVassalCommandsPhaseAction( @@ -384,14 +365,14 @@ class PerformVassalCommandsPhaseActionTest it should "return a gift command if there is only one hero with low loyalty" in { val developingProvince = actingProvince.withProvinceOrders(DEVELOP) - val developingGS = + val developingGS = gameState.update( _.provinces(developingProvince.id) := developingProvince, - _.heroes(1).loyalty := 70, - _.heroes(2).loyalty := 25, - _.heroes(3).loyalty := 70, - _.heroes(4).loyalty := 70, - _.heroes(5).loyalty := 70 + _.heroes(1).loyalty := 70, + _.heroes(2).loyalty := 25, + _.heroes(3).loyalty := 70, + _.heroes(4).loyalty := 70, + _.heroes(5).loyalty := 70 ) val selection = PerformVassalCommandsPhaseAction( @@ -436,14 +417,14 @@ class PerformVassalCommandsPhaseActionTest it should "return a neither if everybody has sufficient loyalty" in { val developingProvince = actingProvince.withProvinceOrders(DEVELOP) - val developingGS = + val developingGS = gameState.update( _.provinces(developingProvince.id) := developingProvince, - _.heroes(1).loyalty := 60, - _.heroes(2).loyalty := 51, - _.heroes(3).loyalty := 70, - _.heroes(4).loyalty := 70, - _.heroes(5).loyalty := 70 + _.heroes(1).loyalty := 60, + _.heroes(2).loyalty := 51, + _.heroes(3).loyalty := 70, + _.heroes(4).loyalty := 70, + _.heroes(5).loyalty := 70 ) val selection = PerformVassalCommandsPhaseAction( @@ -496,7 +477,7 @@ class PerformVassalCommandsPhaseActionTest "choose on a Developing province" should "return a successful Improve" in { val developingProvince = actingProvince.withProvinceOrders(DEVELOP) - val developingGS = + val developingGS = gameState.update(_.provinces(developingProvince.id) := developingProvince) val selection = PerformVassalCommandsPhaseAction( @@ -517,7 +498,7 @@ class PerformVassalCommandsPhaseActionTest "choose on a Developing province with no improvement available" should "return an successful Rest" in { val developingProvince = actingProvince.withProvinceOrders(DEVELOP) - val developingGS = + val developingGS = gameState.update(_.provinces(developingProvince.id) := developingProvince) val selection = PerformVassalCommandsPhaseAction( @@ -538,7 +519,7 @@ class PerformVassalCommandsPhaseActionTest "choose on an Expanding province" should "return a successful March" in { val marchingProvince = actingProvince.withProvinceOrders(EXPAND) - val marchingGS = marchGameState.update( + val marchingGS = marchGameState.update( _.provinces(marchingProvince.id) := marchingProvince ) @@ -561,14 +542,15 @@ class PerformVassalCommandsPhaseActionTest commandFactory = commandFactory ).chooseCommand(actingProvince.id, functionalRandom).newValue.get - inside(selection.available) { case mac: MarchAvailableCommand => - mac should equalProto(marchCommand) + inside(selection.available) { + case mac: MarchAvailableCommand => + mac should equalProto(marchCommand) } } "choose on an Expanding province with no available targets" should "improve" in { val marchingProvince = actingProvince.withProvinceOrders(EXPAND) - val marchingGS = marchGameState.update( + val marchingGS = marchGameState.update( _.provinces(marchingProvince.id) := marchingProvince ) @@ -655,16 +637,16 @@ class PerformVassalCommandsPhaseActionTest supplies.isEmpty shouldBe true } - private val leaderProvince = Province( + private val leaderProvince = Province( id = 154, rulingFactionId = Some(actingFactionId), rulingHeroId = Some(leader.id), rulingFactionHeroIds = Vector(leader.id) ) private val leaderGameState = marchGameState.update( - _.factions(actingFactionId) := faction, + _.factions(actingFactionId) := faction, _.provinces(leaderProvince.id) := leaderProvince, - _.heroes(leader.id) := leader + _.heroes(leader.id) := leader ) private val availableSendSuppliesCommand: SendSuppliesAvailableCommand = @@ -686,7 +668,7 @@ class PerformVassalCommandsPhaseActionTest } it should "return nothing if there is no path through friendly territory" in { - val intermediateProvince = Province(id = 200).clearRulingFactionId + val intermediateProvince = Province(id = 200).clearRulingFactionId .withNeighbors( Vector(actingProvince.id, leaderProvince.id) .map(pid => Neighbor(provinceId = pid)) @@ -697,16 +679,16 @@ class PerformVassalCommandsPhaseActionTest val leaderProvinceWithIntermediateNeighbor = leaderProvince.update( _.neighbors :+= Neighbor(provinceId = intermediateProvince.id) ) - val gs = leaderGameState.update( + val gs = leaderGameState.update( _.provinces(intermediateProvince.id) := intermediateProvince, _.provinces( actingProvinceWithIntermediateNeighbor.id - ) := actingProvinceWithIntermediateNeighbor, + ) := actingProvinceWithIntermediateNeighbor, _.provinces( leaderProvinceWithIntermediateNeighbor.id - ) := leaderProvinceWithIntermediateNeighbor + ) := leaderProvinceWithIntermediateNeighbor ) - val ac = availableSendSuppliesCommand.update( + val ac = availableSendSuppliesCommand.update( _.availableDestinationProvinceIds :+= intermediateProvince.id ) @@ -718,7 +700,7 @@ class PerformVassalCommandsPhaseActionTest } it should "return the leader's province if it is a neighbor" in { - val intermediateProvince = + val intermediateProvince = Province( id = 200, rulingFactionId = Some(actingFactionId), @@ -735,16 +717,16 @@ class PerformVassalCommandsPhaseActionTest _.neighbors :+= Neighbor(provinceId = intermediateProvince.id), _.neighbors :+= Neighbor(provinceId = actingProvince.id) ) - val gs = leaderGameState.update( + val gs = leaderGameState.update( _.provinces(intermediateProvince.id) := intermediateProvince, _.provinces( actingProvinceWithIntermediateNeighbor.id - ) := actingProvinceWithIntermediateNeighbor, + ) := actingProvinceWithIntermediateNeighbor, _.provinces( leaderProvinceWithIntermediateNeighbor.id - ) := leaderProvinceWithIntermediateNeighbor + ) := leaderProvinceWithIntermediateNeighbor ) - val ac = availableSendSuppliesCommand.update( + val ac = availableSendSuppliesCommand.update( _.availableDestinationProvinceIds :+= intermediateProvince.id, _.availableDestinationProvinceIds :+= leaderProvince.id ) @@ -759,10 +741,10 @@ class PerformVassalCommandsPhaseActionTest } it should "return the a sworn brother's province if it is a neighbor" in { - val swornBrother = Hero(id = 867, factionId = Some(faction.id)) + val swornBrother = Hero(id = 867, factionId = Some(faction.id)) val factionWithBrother = faction.withLeaders(Vector(leader.id, 867)) - val activeProvince = Province( + val activeProvince = Province( id = 15, neighbors = Vector(Neighbor(provinceId = 16), Neighbor(provinceId = 17)), rulingFactionId = Some(faction.id) @@ -778,7 +760,7 @@ class PerformVassalCommandsPhaseActionTest rulingFactionId = Some(faction.id), rulingFactionHeroIds = Vector(swornBrother.id) ) - val leaderProvince = Province( + val leaderProvince = Province( id = 18, neighbors = Vector(Neighbor(provinceId = 16)), rulingFactionId = Some(faction.id), @@ -787,16 +769,16 @@ class PerformVassalCommandsPhaseActionTest val gs = leaderGameState.update( _.heroes(swornBrother.id) := swornBrother, - _.provinces := Vector( + _.provinces := Vector( activeProvince, intermediateProvince, swornBrotherProvince, leaderProvince ).map(p => p.id -> p).toMap, - _.factions := Map(factionWithBrother.id -> factionWithBrother) + _.factions := Map(factionWithBrother.id -> factionWithBrother) ) val ac = availableSendSuppliesCommand.update( - _.actingProvinceId := 15, + _.actingProvinceId := 15, _.availableDestinationProvinceIds := Vector(16, 17) ) @@ -810,10 +792,10 @@ class PerformVassalCommandsPhaseActionTest } it should "return not return an owned neighbor over the faction leader if it isn't a sword brother" in { - val swornBrother = Hero(id = 867, factionId = Some(faction.id)) + val swornBrother = Hero(id = 867, factionId = Some(faction.id)) val factionWithBrother = faction.withLeaders(Vector(leader.id)) - val activeProvince = Province( + val activeProvince = Province( id = 15, neighbors = Vector(Neighbor(provinceId = 16), Neighbor(provinceId = 17)), rulingFactionId = Some(faction.id) @@ -829,7 +811,7 @@ class PerformVassalCommandsPhaseActionTest rulingFactionId = Some(faction.id), rulingFactionHeroIds = Vector(swornBrother.id) ) - val leaderProvince = Province( + val leaderProvince = Province( id = 18, neighbors = Vector(Neighbor(provinceId = 16)), rulingFactionId = Some(faction.id), @@ -838,16 +820,16 @@ class PerformVassalCommandsPhaseActionTest val gs = leaderGameState.update( _.heroes(swornBrother.id) := swornBrother, - _.provinces := Vector( + _.provinces := Vector( activeProvince, intermediateProvince, swornBrotherProvince, leaderProvince ).map(p => p.id -> p).toMap, - _.factions := Map(factionWithBrother.id -> factionWithBrother) + _.factions := Map(factionWithBrother.id -> factionWithBrother) ) val ac = availableSendSuppliesCommand.update( - _.actingProvinceId := 15, + _.actingProvinceId := 15, _.availableDestinationProvinceIds := Vector(16, 17) ) @@ -861,7 +843,7 @@ class PerformVassalCommandsPhaseActionTest } it should "get closer to the leader if there is a path" in { - val intermediateProvince = + val intermediateProvince = Province( id = 200, rulingFactionId = Some(actingFactionId), @@ -876,16 +858,16 @@ class PerformVassalCommandsPhaseActionTest val leaderProvinceWithIntermediateNeighbor = leaderProvince.update( _.neighbors :+= Neighbor(provinceId = intermediateProvince.id) ) - val gs = leaderGameState.update( + val gs = leaderGameState.update( _.provinces(intermediateProvince.id) := intermediateProvince, _.provinces( actingProvinceWithIntermediateNeighbor.id - ) := actingProvinceWithIntermediateNeighbor, + ) := actingProvinceWithIntermediateNeighbor, _.provinces( leaderProvinceWithIntermediateNeighbor.id - ) := leaderProvinceWithIntermediateNeighbor + ) := leaderProvinceWithIntermediateNeighbor ) - val ac = availableSendSuppliesCommand.update( + val ac = availableSendSuppliesCommand.update( _.availableDestinationProvinceIds :+= intermediateProvince.id ) @@ -899,7 +881,7 @@ class PerformVassalCommandsPhaseActionTest } "chosenSendSuppliesCommand" should "return a command when appropriate" in { - val intermediateProvince = + val intermediateProvince = Province( id = 200, rulingFactionId = Some(actingFactionId), @@ -915,16 +897,16 @@ class PerformVassalCommandsPhaseActionTest val leaderProvinceWithIntermediateNeighbor = leaderProvince.update( _.neighbors :+= Neighbor(provinceId = intermediateProvince.id) ) - val gs = leaderGameState.update( + val gs = leaderGameState.update( _.provinces(intermediateProvince.id) := intermediateProvince, _.provinces( actingProvinceWithIntermediateNeighbor.id - ) := actingProvinceWithIntermediateNeighbor, + ) := actingProvinceWithIntermediateNeighbor, _.provinces( leaderProvinceWithIntermediateNeighbor.id - ) := leaderProvinceWithIntermediateNeighbor + ) := leaderProvinceWithIntermediateNeighbor ) - val ac = availableSendSuppliesCommand.update( + val ac = availableSendSuppliesCommand.update( _.availableDestinationProvinceIds :+= intermediateProvince.id ) @@ -944,7 +926,7 @@ class PerformVassalCommandsPhaseActionTest } it should "return nothing if the supplies are empty" in { - val intermediateProvince = + val intermediateProvince = Province( id = 200, rulingFactionId = Some(actingFactionId), @@ -956,22 +938,22 @@ class PerformVassalCommandsPhaseActionTest val actingProvinceWithIntermediateNeighbor = actingProvince.update( _.neighbors :+= Neighbor(provinceId = intermediateProvince.id), _.battalionIds := Vector(), - _.gold := 0, - _.food := 0 + _.gold := 0, + _.food := 0 ) val leaderProvinceWithIntermediateNeighbor = leaderProvince.update( _.neighbors :+= Neighbor(provinceId = intermediateProvince.id) ) - val gs = leaderGameState.update( + val gs = leaderGameState.update( _.provinces(intermediateProvince.id) := intermediateProvince, _.provinces( actingProvinceWithIntermediateNeighbor.id - ) := actingProvinceWithIntermediateNeighbor, + ) := actingProvinceWithIntermediateNeighbor, _.provinces( leaderProvinceWithIntermediateNeighbor.id - ) := leaderProvinceWithIntermediateNeighbor + ) := leaderProvinceWithIntermediateNeighbor ) - val ac = availableSendSuppliesCommand.update( + val ac = availableSendSuppliesCommand.update( _.availableDestinationProvinceIds :+= intermediateProvince.id ) @@ -983,7 +965,7 @@ class PerformVassalCommandsPhaseActionTest } it should "return nothing if there is no path to the leader" in { - val intermediateProvince = Province(id = 200).clearRulingFactionId + val intermediateProvince = Province(id = 200).clearRulingFactionId .withNeighbors( Vector( Neighbor(provinceId = actingProvince.id), @@ -997,16 +979,16 @@ class PerformVassalCommandsPhaseActionTest val leaderProvinceWithIntermediateNeighbor = leaderProvince.update( _.neighbors :+= Neighbor(provinceId = intermediateProvince.id) ) - val gs = leaderGameState.update( + val gs = leaderGameState.update( _.provinces(intermediateProvince.id) := intermediateProvince, _.provinces( actingProvinceWithIntermediateNeighbor.id - ) := actingProvinceWithIntermediateNeighbor, + ) := actingProvinceWithIntermediateNeighbor, _.provinces( leaderProvinceWithIntermediateNeighbor.id - ) := leaderProvinceWithIntermediateNeighbor + ) := leaderProvinceWithIntermediateNeighbor ) - val ac = availableSendSuppliesCommand.update( + val ac = availableSendSuppliesCommand.update( _.availableDestinationProvinceIds :+= intermediateProvince.id ) CommandChoiceHelpers.maybeChosenSendSuppliesCommand( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeActionTest.scala index 9248d0fdf0..3ea4c0f31c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/PrisonerExchangeActionTest.scala @@ -1,14 +1,8 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.ProtoMatchers -import net.eagle0.eagle.common.action_result_notification_details.{ - Notification, - PrisonerExchangeDetails -} -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_PRISONER_EXCHANGE_PHASE, - PRISONERS_EXCHANGED -} +import net.eagle0.eagle.common.action_result_notification_details.{Notification, PrisonerExchangeDetails} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_PRISONER_EXCHANGE_PHASE, PRISONERS_EXCHANGED} import net.eagle0.eagle.common.round_phase.{NewRoundPhase, RoundPhase} import net.eagle0.eagle.common.round_phase.RoundPhase.PROVINCE_EVENTS import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFFILIATED_HERO_PRISONER @@ -20,19 +14,13 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.actions.applier.ActionResultProtoApplierImpl -import net.eagle0.eagle.library.actions.impl.action.PrisonerExchangeAction.{ - ExchangeMatch, - ExchangeableHeroInfo -} +import net.eagle0.eagle.library.actions.impl.action.PrisonerExchangeAction.{ExchangeMatch, ExchangeableHeroInfo} import net.eagle0.eagle.library.util.validations.RuntimeValidator import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class PrisonerExchangeActionTest - extends AnyFlatSpec - with Matchers - with ProtoMatchers { +class PrisonerExchangeActionTest extends AnyFlatSpec with Matchers with ProtoMatchers { private val actionResultProtoApplier = new ActionResultProtoApplierImpl( validator = RuntimeValidator ) @@ -314,7 +302,7 @@ class PrisonerExchangeActionTest ) ) - val results = PrisonerExchangeAction(gs).results(actionResultProtoApplier) + val results = PrisonerExchangeAction(gs).results(actionResultProtoApplier) val headResult = results.head headResult.`type` shouldBe PRISONERS_EXCHANGED @@ -360,7 +348,7 @@ class PrisonerExchangeActionTest ) ) - val results = PrisonerExchangeAction(gs).results(actionResultProtoApplier) + val results = PrisonerExchangeAction(gs).results(actionResultProtoApplier) val headResult = results.head headResult.`type` shouldBe PRISONERS_EXCHANGED @@ -398,7 +386,7 @@ class PrisonerExchangeActionTest ) ) - val results = PrisonerExchangeAction(gs).results(actionResultProtoApplier) + val results = PrisonerExchangeAction(gs).results(actionResultProtoApplier) val headResult = results.head headResult.`type` shouldBe PRISONERS_EXCHANGED @@ -420,7 +408,7 @@ class PrisonerExchangeActionTest val gs = basicGameState.update( _.factions :+= 2 -> Faction(id = 2, leaders = Vector(13)), _.factions :+= 1 -> Faction(id = 1, leaders = Vector(2)), - _.provinces := mapifyProvinces( + _.provinces := mapifyProvinces( Province( id = 37, rulingFactionId = Some(3), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredActionTest.scala index d39919d7f5..527e45f375 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceConqueredActionTest.scala @@ -10,11 +10,7 @@ import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.{ RECRUITMENT_STATUS_HAS_QUEST, RECRUITMENT_STATUS_PRISONER } -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - Quest as QuestProto, - TruceCountQuest, - WealthQuest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{Quest as QuestProto, TruceCountQuest, WealthQuest} import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.{ UNAFFILIATED_HERO_PRISONER, UNAFFILIATED_HERO_RESIDENT @@ -43,12 +39,7 @@ import net.eagle0.eagle.library.settings.{ RecruitmentPrestigeFactor } import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedFactionC, - ChangedHeroC, - NotificationC, - StatAbsolute -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedFactionC, ChangedHeroC, NotificationC, StatAbsolute} import net.eagle0.eagle.model.action_result.types.ProvinceConqueredResultType import net.eagle0.eagle.model.action_result.NotificationDetails import net.eagle0.eagle.model.proto_converters.date.DateConverter @@ -60,10 +51,7 @@ import net.eagle0.eagle.model.proto_converters.BattalionConverter import net.eagle0.eagle.model.proto_converters.UnaffiliatedHeroConverter import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Invalidated, - Unresolved -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Invalidated, Unresolved} import net.eagle0.eagle.model.state.diplomacy_offer.RansomOffer import net.eagle0.eagle.model.state.diplomacy_offer.RansomOfferDetails.PrisonerToBeRansomed import net.eagle0.eagle.model.state.hero.concrete.HeroC @@ -84,7 +72,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { province: Province = conqueredProvince, conquerors: Vector[ResolvedEagleUnit] = notFledAttackers, defenders: Vector[ResolvedEagleUnit] = Vector.empty - ): ProvinceConqueredAction = { + ): ProvinceConqueredAction = ProvinceConqueredAction( gameId = gameState.gameId, currentRoundId = gameState.currentRoundId, @@ -94,24 +82,20 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { notFledDefenders = defenders, destroyedBattalions = Vector.empty, defendingFactionId = province.rulingFactionId, - factions = - gameState.factions.view.mapValues(FactionConverter.fromProto).toMap, + factions = gameState.factions.view.mapValues(FactionConverter.fromProto).toMap, heroes = gameState.heroes.view.mapValues(HeroConverter.fromProto).toMap, - battalions = - gameState.battalions.view.mapValues(BattalionConverter.fromProto).toMap, - provinces = - gameState.provinces.view.mapValues(ProvinceConverter.fromProto).toMap + battalions = gameState.battalions.view.mapValues(BattalionConverter.fromProto).toMap, + provinces = gameState.provinces.view.mapValues(ProvinceConverter.fromProto).toMap ) - } - val attackingFactionId = 8 - private val attackingHero1 = + val attackingFactionId = 8 + private val attackingHero1 = Hero( id = 23, factionId = Some(attackingFactionId), profession = Profession.CHAMPION, pronounGender = Gender.GENDER_MALE ) - private val attackingHero2 = + private val attackingHero2 = Hero( id = 24, factionId = Some(attackingFactionId), @@ -163,7 +147,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) private val defendingFactionId = 3 - private val defendingHero = + private val defendingHero = Hero( id = 55, factionId = Some(defendingFactionId), @@ -220,7 +204,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { factionHeadId = defendingHero.id, leaders = Vector(defendingHero.id) ), - neutralFactionId -> Faction( + neutralFactionId -> Faction( id = neutralFactionId ) ) @@ -293,7 +277,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { } it should "invalidate any incoming ransom offers to the province" in { - val firstDO = RansomOffer( + val firstDO = RansomOffer( originatingFactionId = 99, targetFactionId = defendingFactionId, messengerHeroId = 18, @@ -323,7 +307,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { goldOffered = 100, offerTextId = "" ) - val otherDO = RansomOffer( + val otherDO = RansomOffer( originatingFactionId = 97, targetFactionId = defendingFactionId, messengerHeroId = 16, @@ -378,16 +362,14 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(attackingFactionId), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ), UnaffiliatedHeroProto( heroId = 94, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(attackingFactionId), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ) ) ) @@ -396,7 +378,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { _.factions(attackingFactionId).leaders :+= 97, _.provinces( conqueredProvince.id - ) := conqueredProvinceWithImprisonedHeroesFromAttacker, + ) := conqueredProvinceWithImprisonedHeroesFromAttacker, _.heroes(97) := Hero( id = 97, factionId = None, @@ -423,9 +405,10 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { changedProvince.newRulingFactionHeroIds should contain allOf (94, 97) } - forExactly(1, result.changedHeroes) { case changedHero: ChangedHeroC => - changedHero.heroId shouldBe 94 - changedHero.loyaltyChange shouldBe StatAbsolute(90) + forExactly(1, result.changedHeroes) { + case changedHero: ChangedHeroC => + changedHero.heroId shouldBe 94 + changedHero.loyaltyChange shouldBe StatAbsolute(90) } } @@ -486,13 +469,13 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { val startingStateWithImprisonedHeroes = startingState.update( _.provinces(conqueredProvince.id) := conqueredProvinceWithQuests, - _.heroes(97) := Hero( + _.heroes(97) := Hero( id = 97, factionId = None, profession = Profession.CHAMPION, pronounGender = Gender.GENDER_MALE ), - _.heroes(94) := Hero( + _.heroes(94) := Hero( id = 94, factionId = None, profession = Profession.CHAMPION, @@ -579,7 +562,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { val result = createProvinceConqueredAction( gameState = startingState.update( _.factions(defendingFactionId).focusProvinceId := 12, - _.provinces(12) := Province( + _.provinces(12) := Province( id = 12, rulingFactionId = Some(defendingFactionId) ) @@ -601,26 +584,28 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { province = conqueredProvince.update(_.optionalRulingFactionId := None) ).immediateExecute - forExactly(1, result.newNotifications) { case notification: NotificationC => - notification.deferred shouldBe true - notification.details shouldBe NotificationDetails.ProvinceExpansion( - provinceId = conqueredProvince.id, - expandingFactionId = attackingFactionId - ) + forExactly(1, result.newNotifications) { + case notification: NotificationC => + notification.deferred shouldBe true + notification.details shouldBe NotificationDetails.ProvinceExpansion( + provinceId = conqueredProvince.id, + expandingFactionId = attackingFactionId + ) } } it should "include a ProvinceConquered notification if the province was occupied" in { val result = createProvinceConqueredAction().immediateExecute - forExactly(1, result.newNotifications) { case notification: NotificationC => - notification.deferred shouldBe true - notification.details shouldBe NotificationDetails.ProvinceConquered( - provinceId = conqueredProvince.id, - conqueringFactionId = attackingFactionId, - otherAttackingFactionIds = Vector(), - defendingFactionId = defendingFactionId - ) + forExactly(1, result.newNotifications) { + case notification: NotificationC => + notification.deferred shouldBe true + notification.details shouldBe NotificationDetails.ProvinceConquered( + provinceId = conqueredProvince.id, + conqueringFactionId = attackingFactionId, + otherAttackingFactionIds = Vector(), + defendingFactionId = defendingFactionId + ) } } @@ -632,23 +617,21 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(attackingFactionId), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ), UnaffiliatedHeroProto( heroId = 94, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(attackingFactionId), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ) ) ) val startingStateWithPrisoners = startingState.update( _.provinces(conqueredProvince.id) := conqueredProvinceWithPrisoners, - _.heroes(97) := Hero( + _.heroes(97) := Hero( id = 97, factionId = None, profession = Profession.CHAMPION, @@ -660,7 +643,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) ) ), - _.heroes(94) := Hero( + _.heroes(94) := Hero( id = 94, factionId = None, profession = Profession.CHAMPION, @@ -695,23 +678,21 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(attackingFactionId), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ), UnaffiliatedHeroProto( heroId = 94, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(attackingFactionId), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ) ) ) val startingStateWithPrisoners = startingState.update( _.provinces(conqueredProvince.id) := conqueredProvinceWithPrisoners, - _.heroes(97) := Hero( + _.heroes(97) := Hero( id = 97, factionId = None, profession = Profession.CHAMPION, @@ -723,7 +704,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) ) ), - _.heroes(94) := Hero( + _.heroes(94) := Hero( id = 94, factionId = None, profession = Profession.CHAMPION, @@ -743,30 +724,32 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { defenders = notFledDefenders ).immediateExecute - forExactly(1, result.changedHeroes) { case changedHero: ChangedHeroC => - changedHero.heroId shouldBe 97 - changedHero.newFactionId shouldBe Some(attackingFactionId) - changedHero.loyaltyChange shouldBe StatAbsolute(90) - changedHero.newEventsForHeroBackstory shouldBe Vector( - ReleasedByProvinceCaptureBackstoryEvent( - date = Date(year = 2024, month = Date.Month.July), - capturingFactionId = attackingFactionId, - releasedInProvinceId = conqueredProvince.id + forExactly(1, result.changedHeroes) { + case changedHero: ChangedHeroC => + changedHero.heroId shouldBe 97 + changedHero.newFactionId shouldBe Some(attackingFactionId) + changedHero.loyaltyChange shouldBe StatAbsolute(90) + changedHero.newEventsForHeroBackstory shouldBe Vector( + ReleasedByProvinceCaptureBackstoryEvent( + date = Date(year = 2024, month = Date.Month.July), + capturingFactionId = attackingFactionId, + releasedInProvinceId = conqueredProvince.id + ) ) - ) } - forExactly(1, result.changedHeroes) { case changedHero: ChangedHeroC => - changedHero.heroId shouldBe 94 - changedHero.newFactionId shouldBe Some(attackingFactionId) - changedHero.loyaltyChange shouldBe StatAbsolute(90) - changedHero.newEventsForHeroBackstory shouldBe Vector( - ReleasedByProvinceCaptureBackstoryEvent( - date = Date(year = 2024, month = Date.Month.July), - capturingFactionId = attackingFactionId, - releasedInProvinceId = conqueredProvince.id + forExactly(1, result.changedHeroes) { + case changedHero: ChangedHeroC => + changedHero.heroId shouldBe 94 + changedHero.newFactionId shouldBe Some(attackingFactionId) + changedHero.loyaltyChange shouldBe StatAbsolute(90) + changedHero.newEventsForHeroBackstory shouldBe Vector( + ReleasedByProvinceCaptureBackstoryEvent( + date = Date(year = 2024, month = Date.Month.July), + capturingFactionId = attackingFactionId, + releasedInProvinceId = conqueredProvince.id + ) ) - ) } } @@ -781,16 +764,14 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(alliedFid), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ), UnaffiliatedHeroProto( heroId = 94, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(alliedFid), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ) ), _.neighbors :++= Vector( @@ -805,7 +786,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { relationshipLevel = FactionRelationship.RelationshipLevel.ALLY ) ), - _.factions(alliedFid) := Faction( + _.factions(alliedFid) := Faction( id = alliedFid, factionHeadId = 97, leaders = Vector(97), @@ -816,8 +797,8 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) ) ), - _.provinces(conqueredProvince.id) := conqueredProvinceWithPrisoners, - _.heroes(97) := Hero( + _.provinces(conqueredProvince.id) := conqueredProvinceWithPrisoners, + _.heroes(97) := Hero( id = 97, factionId = None, profession = Profession.CHAMPION, @@ -829,7 +810,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) ) ), - _.heroes(94) := Hero( + _.heroes(94) := Hero( id = 94, factionId = None, profession = Profession.CHAMPION, @@ -841,7 +822,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) ) ), - _.provinces(alliedPid) := Province( + _.provinces(alliedPid) := Province( id = alliedPid, rulingFactionId = Some(alliedFid), neighbors = Vector( @@ -879,16 +860,14 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(alliedFid), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ), UnaffiliatedHeroProto( heroId = 94, `type` = UNAFFILIATED_HERO_PRISONER, roundsInType = 10, lastFaction = Some(alliedFid), - recruitmentInfo = - Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfoProto(status = RECRUITMENT_STATUS_PRISONER)) ) ) ) @@ -900,7 +879,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { relationshipLevel = FactionRelationship.RelationshipLevel.ALLY ) ), - _.factions(alliedFid) := Faction( + _.factions(alliedFid) := Faction( id = alliedFid, factionHeadId = 97, leaders = Vector(97), @@ -911,8 +890,8 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) ) ), - _.provinces(conqueredProvince.id) := conqueredProvinceWithPrisoners, - _.heroes(97) := Hero( + _.provinces(conqueredProvince.id) := conqueredProvinceWithPrisoners, + _.heroes(97) := Hero( id = 97, factionId = None, profession = Profession.CHAMPION, @@ -924,7 +903,7 @@ class ProvinceConqueredActionTest extends AnyFlatSpec with Matchers { ) ) ), - _.heroes(94) := Hero( + _.heroes(94) := Hero( id = 94, factionId = None, profession = Profession.CHAMPION, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldActionTest.scala index 19ebeb519d..ef92952ae6 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ProvinceHeldActionTest.scala @@ -129,8 +129,7 @@ class ProvinceHeldActionTest extends AnyFlatSpec with Matchers { attackerProvince.id -> attackerProvince ), heroes = (defenderHeroes ++ attackerHeroes).map(h => h.id -> h).toMap, - battalions = - (defenderBattalions ++ attackerBattalions).map(b => b.id -> b).toMap, + battalions = (defenderBattalions ++ attackerBattalions).map(b => b.id -> b).toMap, factions = mapifyFactions( Faction(id = defenderFid, factionHeadId = 37) ) @@ -204,13 +203,14 @@ class ProvinceHeldActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute - forExactly(1, result.newNotifications) { case note: NotificationC => - note.deferred shouldBe true - note.details shouldBe NotificationDetails.ProvinceHeld( - provinceId = defenderProvince.id, - attackingFactionIds = Vector(attackerFid), - defendingFactionId = defenderFid - ) + forExactly(1, result.newNotifications) { + case note: NotificationC => + note.deferred shouldBe true + note.details shouldBe NotificationDetails.ProvinceHeld( + provinceId = defenderProvince.id, + attackingFactionIds = Vector(attackerFid), + defendingFactionId = defenderFid + ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesActionTest.scala index bf4ef55e4e..a0f2c8f71d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/RequestBattlesActionTest.scala @@ -12,14 +12,8 @@ import net.eagle0.eagle.model.state.hero.Gender.{Female, Male} import net.eagle0.eagle.model.state.hero.Profession.NoProfession import net.eagle0.eagle.model.state.province.{Neighbor, ProvinceOrderType} import net.eagle0.eagle.model.state.province.concrete.ProvinceC -import net.eagle0.eagle.model.state.shardok_battle.{ - BattleType, - VictoryCondition -} -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - Attacking, - AwaitingDecision -} +import net.eagle0.eagle.model.state.shardok_battle.{BattleType, VictoryCondition} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{Attacking, AwaitingDecision} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.Inside.inside @@ -127,8 +121,7 @@ class RequestBattlesActionTest extends AnyFlatSpec with Matchers { id = 5, rulingFactionId = Some(defenderId), rulingHeroId = Some(22), - neighbors = - Vector(Neighbor(provinceId = 17, startingPositionIndex = 4)), + neighbors = Vector(Neighbor(provinceId = 17, startingPositionIndex = 4)), provinceOrders = ProvinceOrderType.Entrust, rulingFactionHeroIds = Vector(22), defendingArmy = Some(defendingArmy), @@ -288,7 +281,7 @@ class RequestBattlesActionTest extends AnyFlatSpec with Matchers { 2 -> createFaction(2, 22) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RequestBattlesAction( gameId = 0x123, currentRoundId = 9, @@ -300,7 +293,6 @@ class RequestBattlesActionTest extends AnyFlatSpec with Matchers { factions = factions, battalionTypes = battalionTypes ).results - } ex.getMessage shouldBe "requirement failed: all armies must be attacking in the battle request phase" } @@ -394,8 +386,7 @@ class RequestBattlesActionTest extends AnyFlatSpec with Matchers { id = 5, rulingFactionId = Some(defenderId), rulingHeroId = Some(22), - neighbors = - Vector(Neighbor(provinceId = 17, startingPositionIndex = 4)), + neighbors = Vector(Neighbor(provinceId = 17, startingPositionIndex = 4)), provinceOrders = ProvinceOrderType.Entrust, rulingFactionHeroIds = Vector(22), defendingArmy = Some(defendingArmy), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleActionTest.scala index 74244cbfc6..7797b55cd3 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/ResolveBattleActionTest.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.impl.action -import net.eagle0.common.victory_condition.{ - DrawType, - EndGameCondition, - VictoryCondition -} +import net.eagle0.common.victory_condition.{DrawType, EndGameCondition, VictoryCondition} import net.eagle0.common.ProtoMatchers import net.eagle0.eagle.common.action_result_type.ActionResultType.{ BATTLE_ENDED, @@ -20,15 +16,9 @@ import net.eagle0.eagle.common.gender.Gender import net.eagle0.eagle.common.hero_backstory_version.BackstoryVersion import net.eagle0.eagle.common.profession.Profession import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.ENTRUST -import net.eagle0.eagle.common.recruitment_info.{ - RecruitmentInfo, - RecruitmentStatus -} +import net.eagle0.eagle.common.recruitment_info.{RecruitmentInfo, RecruitmentStatus} import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.RECRUITMENT_STATUS_WOULD_JOIN -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - DefeatFactionQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{DefeatFactionQuest, Quest} import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFFILIATED_HERO_OUTLAW import net.eagle0.eagle.internal.army.{Army, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion @@ -37,10 +27,7 @@ import net.eagle0.eagle.internal.battle_revelation.BattleRevelation.RevelationTy import net.eagle0.eagle.internal.changed_hero.ChangedHero import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor.VigorAbsolute import net.eagle0.eagle.internal.changed_province.ChangedProvince -import net.eagle0.eagle.internal.event_for_hero_backstory.{ - EventForHeroBackstory, - FoughtInBattleBackstoryEvent -} +import net.eagle0.eagle.internal.event_for_hero_backstory.{EventForHeroBackstory, FoughtInBattleBackstoryEvent} import net.eagle0.eagle.internal.event_for_hero_backstory.FoughtInBattleBackstoryEvent.UnitStatus.UNIT_STATUS_NORMAL import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship @@ -51,10 +38,7 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.shardok_battle.{ShardokBattle, ShardokPlayer} import net.eagle0.eagle.internal.shardok_battle.ShardokBattle.BattleType import net.eagle0.eagle.internal.supplies.Supplies -import net.eagle0.eagle.internal.unaffiliated_hero.{ - CapturedHero, - UnaffiliatedHero -} +import net.eagle0.eagle.internal.unaffiliated_hero.{CapturedHero, UnaffiliatedHero} import net.eagle0.eagle.library.actions.impl.WaitingAction import net.eagle0.eagle.library.settings.{ BattleAgricultureDevastationDelta, @@ -66,12 +50,7 @@ import net.eagle0.eagle.library.util.IDable.mapifyFactions import net.eagle0.eagle.model.proto_converters.hero.HeroConverter import net.eagle0.eagle.model.proto_converters.BattalionConverter import net.eagle0.eagle.model.state.unit_status.UnitStatus -import net.eagle0.eagle.shardok_interface.{ - BattleResolution, - EagleUnit, - ResolvedEagleUnit, - ResolvedShardokPlayer -} +import net.eagle0.eagle.shardok_interface.{BattleResolution, EagleUnit, ResolvedEagleUnit, ResolvedShardokPlayer} import net.eagle0.eagle.views.battalion_view.BattalionView import net.eagle0.eagle.FactionId import org.scalamock.scalatest.MockFactory @@ -88,10 +67,10 @@ class ResolveBattleActionTest with Matchers with ProtoMatchers with BeforeAndAfterEach { - private val attackerFid = 14 - private val defenderFid = 91 - private val allyFid = 3 - private val attackerProvinceId = 21 + private val attackerFid = 14 + private val defenderFid = 91 + private val allyFid = 3 + private val attackerProvinceId = 21 private val attackerOriginProvince = Province( id = attackerProvinceId, rulingFactionId = Some(attackerFid), @@ -102,15 +81,15 @@ class ResolveBattleActionTest food = 2100, provinceOrders = ENTRUST ) - private val allyProvinceId = 37 - private val allyOriginProvince = Province( + private val allyProvinceId = 37 + private val allyOriginProvince = Province( id = allyProvinceId, rulingFactionId = Some(allyFid), rulingFactionHeroIds = Vector(999), battalionIds = Vector.empty, provinceOrders = ENTRUST ) - private val defenderProvinceId = 23 + private val defenderProvinceId = 23 private val defendingArmy = Army( factionId = defenderFid, @@ -323,31 +302,32 @@ class ResolveBattleActionTest private val resolvedExpandedUnits = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + UnitStatus.Normal + ) } - private val resolvedExpandedUnitsWithAllies = battleHeroesWithAllies - .map { case h => + private val resolvedExpandedUnitsWithAllies = battleHeroesWithAllies.map { + case h => ResolvedEagleUnit( HeroConverter.fromProto(h), Some(BattalionConverter.fromProto(EagleUnit.defaultBattalion)), UnitStatus.Normal ) - } + } - private val resolvedExpandedUnitsWithCapturedAlly = battleHeroes - .map { case h => + private val resolvedExpandedUnitsWithCapturedAlly = battleHeroes.map { + case h => ResolvedEagleUnit( HeroConverter.fromProto(h), Some(BattalionConverter.fromProto(EagleUnit.defaultBattalion)), UnitStatus.Normal ) - } :+ + } :+ ResolvedEagleUnit( HeroConverter.fromProto(alliedHero), Some(BattalionConverter.fromProto(EagleUnit.defaultBattalion)), @@ -360,12 +340,13 @@ class ResolveBattleActionTest ): Vector[ResolvedShardokPlayer] = units .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition(resolution(fid)) - ) + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition(resolution(fid)) + ) } .toVector @@ -376,7 +357,7 @@ class ResolveBattleActionTest .Victory(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), defenderFid -> EndGameCondition.Condition .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), - allyFid -> EndGameCondition.Condition.AllyVictory( + allyFid -> EndGameCondition.Condition.AllyVictory( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) ) @@ -389,7 +370,7 @@ class ResolveBattleActionTest .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), defenderFid -> EndGameCondition.Condition .Victory(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), - allyFid -> EndGameCondition.Condition.Loss( + allyFid -> EndGameCondition.Condition.Loss( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) ) @@ -402,7 +383,7 @@ class ResolveBattleActionTest .Victory(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), defenderFid -> EndGameCondition.Condition .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), - allyFid -> EndGameCondition.Condition.AllyVictory( + allyFid -> EndGameCondition.Condition.AllyVictory( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) ) @@ -416,7 +397,7 @@ class ResolveBattleActionTest .Victory(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), defenderFid -> EndGameCondition.Condition .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), - allyFid -> EndGameCondition.Condition.AllyVictory( + allyFid -> EndGameCondition.Condition.AllyVictory( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) ) @@ -465,9 +446,9 @@ class ResolveBattleActionTest outstandingBattles = Vector(shardokBattle), provinces = Map( attackerProvinceId -> attackerOriginProvince, - allyProvinceId -> allyOriginProvince, + allyProvinceId -> allyOriginProvince, defenderProvinceId -> defenderProvince, - 39 -> defenderFleeProvince + 39 -> defenderFleeProvince ), battalionTypes = Vector( BattalionType(typeId = BattalionTypeId.LIGHT_INFANTRY, capacity = 1000) @@ -475,7 +456,7 @@ class ResolveBattleActionTest ) private val startingGameStateWithAllies = startingGameState.update( - _.heroes := (battleHeroesWithAllies ++ otherHeroes) + _.heroes := (battleHeroesWithAllies ++ otherHeroes) .map(h => h.id -> h) .toMap, _.factions(attackerFid).factionRelationships :+= FactionRelationship( @@ -483,7 +464,7 @@ class ResolveBattleActionTest relationshipLevel = TRUCE, resetDate = Some(Date(year = 9999, month = 1)) ), - _.factions(allyFid) := Faction( + _.factions(allyFid) := Faction( id = allyFid, factionRelationships = Vector( FactionRelationship( @@ -541,10 +522,8 @@ class ResolveBattleActionTest training = Some(batt.training) ) ), - isVictorious = - if bh.factionId.contains(attackerFid) then true else false, - isAttacker = - if bh.factionId.contains(attackerFid) then true else false, + isVictorious = if bh.factionId.contains(attackerFid) then true else false, + isAttacker = if bh.factionId.contains(attackerFid) then true else false, enemyFactionIds = Vector( if bh.factionId.contains(defenderFid) then attackerFid else defenderFid @@ -652,7 +631,7 @@ class ResolveBattleActionTest .Victory(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), defenderFid -> EndGameCondition.Condition .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), - allyFid -> EndGameCondition.Condition.AllyVictory( + allyFid -> EndGameCondition.Condition.AllyVictory( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) ) @@ -661,8 +640,8 @@ class ResolveBattleActionTest val action = ResolveBattleAction( startingGameState.update( _.outstandingBattles.head := battleWithExtraHero, - _.heroes(99) := outlawedHero, - _.battalions(99) := Battalion( + _.heroes(99) := outlawedHero, + _.battalions(99) := Battalion( id = 99, `type` = LIGHT_INFANTRY, size = 105 @@ -691,9 +670,7 @@ class ResolveBattleActionTest recruitmentAttempted = false, lastFaction = Some(attackerFid), recruitmentInfo = Some( - RecruitmentInfo(status = - RecruitmentStatus.RECRUITMENT_STATUS_OUTLAW - ) + RecruitmentInfo(status = RecruitmentStatus.RECRUITMENT_STATUS_OUTLAW) ) ) ) @@ -736,7 +713,7 @@ class ResolveBattleActionTest .Victory(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), defenderFid -> EndGameCondition.Condition .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING), - allyFid -> EndGameCondition.Condition.AllyVictory( + allyFid -> EndGameCondition.Condition.AllyVictory( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) ) @@ -745,8 +722,8 @@ class ResolveBattleActionTest val action = ResolveBattleAction( startingGameState.update( _.outstandingBattles.head := battleWithExtraHero, - _.heroes(99) := outlawedHero, - _.battalions(99) := Battalion( + _.heroes(99) := outlawedHero, + _.battalions(99) := Battalion( id = 99, `type` = LIGHT_INFANTRY, size = 105 @@ -800,10 +777,8 @@ class ResolveBattleActionTest training = Some(batt.training) ) ), - isVictorious = - if bh.factionId.contains(attackerFid) then true else false, - isAttacker = - if bh.factionId.contains(attackerFid) then true else false, + isVictorious = if bh.factionId.contains(attackerFid) then true else false, + isAttacker = if bh.factionId.contains(attackerFid) then true else false, enemyFactionIds = Vector( if bh.factionId.contains(defenderFid) then attackerFid else defenderFid @@ -829,7 +804,7 @@ class ResolveBattleActionTest val results = action.resultsOfExecute() val battleEndedResult = results.find(x => x.`type` == BATTLE_ENDED).get - val allyOriginCp = + val allyOriginCp = battleEndedResult.changedProvinces.find(_.id == allyProvinceId).get allyOriginCp.addedIncomingArmies should have size 1 @@ -865,7 +840,7 @@ class ResolveBattleActionTest val results = action.resultsOfExecute() val battleEndedResult = results.find(x => x.`type` == BATTLE_ENDED).get - val allyOriginCp = + val allyOriginCp = battleEndedResult.changedProvinces.find(_.id == allyProvinceId).get allyOriginCp.addedIncomingArmies should have size 1 @@ -924,7 +899,7 @@ class ResolveBattleActionTest val results = action.resultsOfExecute() val battleEndedResult = results.find(x => x.`type` == BATTLE_ENDED).get - val newOutlawsCp = + val newOutlawsCp = battleEndedResult.changedProvinces.find(_.id == defenderProvinceId).get newOutlawsCp.newUnaffiliatedHeroes should have size 1 @@ -943,34 +918,36 @@ class ResolveBattleActionTest it should "add captured defenders to the conquered province" in { val resolvedExpandedUnitsWithCapturedDefender = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - if h.id == 7 then UnitStatus.Captured - else UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + if h.id == 7 then UnitStatus.Captured + else UnitStatus.Normal + ) } val resolvedPlayersWithCapturedDefender = resolvedExpandedUnitsWithCapturedDefender .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - if fid == attackerFid then - EndGameCondition.Condition.Victory( - VictoryCondition.VICTORY_CONDITION_HOLDS_CRITICAL_TILES - ) - else - EndGameCondition.Condition - .Loss( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + if fid == attackerFid then + EndGameCondition.Condition.Victory( + VictoryCondition.VICTORY_CONDITION_HOLDS_CRITICAL_TILES ) + else + EndGameCondition.Condition + .Loss( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + ) ) - ) } .toVector @@ -1005,34 +982,36 @@ class ResolveBattleActionTest it should "add defenders that did not enter battle to as captured heroes" in { val resolvedExpandedUnitsWithNeverEnteredDefender = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - if h.id == 7 then UnitStatus.NeverEntered - else UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + if h.id == 7 then UnitStatus.NeverEntered + else UnitStatus.Normal + ) } val resolvedPlayersWithNeverEnteredDefender = resolvedExpandedUnitsWithNeverEnteredDefender .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - if fid == attackerFid then - EndGameCondition.Condition.Victory( - VictoryCondition.VICTORY_CONDITION_HOLDS_CRITICAL_TILES - ) - else - EndGameCondition.Condition - .Loss( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + if fid == attackerFid then + EndGameCondition.Condition.Victory( + VictoryCondition.VICTORY_CONDITION_HOLDS_CRITICAL_TILES ) + else + EndGameCondition.Condition + .Loss( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + ) ) - ) } .toVector @@ -1166,31 +1145,33 @@ class ResolveBattleActionTest it should "send fled defenders as an incoming army to the defender flee province" in { val resolvedExpandedUnitsWithFledDefender = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - if h.id == 7 then UnitStatus.Fled - else UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + if h.id == 7 then UnitStatus.Fled + else UnitStatus.Normal + ) } val resolvedPlayersWithFledDefender = resolvedExpandedUnitsWithFledDefender .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - if fid == defenderFid then - EndGameCondition.Condition.Victory( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING - ) - else - EndGameCondition.Condition - .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING) + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + if fid == defenderFid then + EndGameCondition.Condition.Victory( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + else + EndGameCondition.Condition + .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING) + ) ) - ) } .toVector @@ -1241,31 +1222,33 @@ class ResolveBattleActionTest it should "send fled attackers as an incoming army to the attacker flee province" in { val resolvedExpandedUnitsWithFledAttacker = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - if h.id == 1 then UnitStatus.Fled - else UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + if h.id == 1 then UnitStatus.Fled + else UnitStatus.Normal + ) } val resolvedPlayersWithFledAttacker = resolvedExpandedUnitsWithFledAttacker .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - if fid == defenderFid then - EndGameCondition.Condition.Victory( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING - ) - else - EndGameCondition.Condition - .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING) + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + if fid == defenderFid then + EndGameCondition.Condition.Victory( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + else + EndGameCondition.Condition + .Loss(VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING) + ) ) - ) } .toVector @@ -1316,34 +1299,36 @@ class ResolveBattleActionTest it should "add captured attackers to the captured heroes in the defender province" in { val resolvedExpandedUnitsWithCapturedAttacker = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - if h.id == 1 then UnitStatus.Captured - else UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + if h.id == 1 then UnitStatus.Captured + else UnitStatus.Normal + ) } val resolvedPlayersWithCapturedAttacker = resolvedExpandedUnitsWithCapturedAttacker .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - if fid == defenderFid then - EndGameCondition.Condition.Victory( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING - ) - else - EndGameCondition.Condition - .Loss( + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + if fid == defenderFid then + EndGameCondition.Condition.Victory( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) + else + EndGameCondition.Condition + .Loss( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + ) ) - ) } .toVector @@ -1378,34 +1363,36 @@ class ResolveBattleActionTest it should "add attackers left on the map to the captured heroes in the defender province" in { val resolvedExpandedUnitsWithCapturedAttacker = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - if h.id == 1 then UnitStatus.Captured - else UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + if h.id == 1 then UnitStatus.Captured + else UnitStatus.Normal + ) } val resolvedPlayersWithCapturedAttacker = resolvedExpandedUnitsWithCapturedAttacker .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - if fid == defenderFid then - EndGameCondition.Condition.Victory( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING - ) - else - EndGameCondition.Condition - .Loss( + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + if fid == defenderFid then + EndGameCondition.Condition.Victory( VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING ) + else + EndGameCondition.Condition + .Loss( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + ) ) - ) } .toVector @@ -1496,32 +1483,34 @@ class ResolveBattleActionTest val resolvedDrawUnits = (battleHeroes.filter(_.getFactionId == attackerFid) ++ attacker2Heroes) .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + UnitStatus.Normal + ) } val resolvedPlayersWithDraw = resolvedDrawUnits .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - EndGameCondition.Condition.Draw( - DrawType.DRAW_AFTER_MAX_ROUNDS + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + EndGameCondition.Condition.Draw( + DrawType.DRAW_AFTER_MAX_ROUNDS + ) ) ) - ) } .toVector - val action = ResolveBattleAction( + val action = ResolveBattleAction( startingGameState.update( _.outstandingBattles := Vector(freeForAll), - _.provinces(111) := Province(id = 111), + _.provinces(111) := Province(id = 111), _.heroes :++= attacker2Heroes.map(h => h.id -> h) ), Vector( @@ -1752,7 +1741,7 @@ class ResolveBattleActionTest // COMPREHENSIVE TEST FOR WITHDRAWN UNITS FUNCTIONALITY (PROTOBUF VERSION) it should "create incoming armies in destination provinces for withdrawn units with explicit flee provinces" in { val fleeProvinceId = 99 - val fleeProvince = Province( + val fleeProvince = Province( id = fleeProvinceId, rulingFactionId = None, provinceOrders = ENTRUST @@ -1781,8 +1770,7 @@ class ResolveBattleActionTest battalionId = Some(88) ) ), - fleeProvinceId = - Some(fleeProvinceId) // Important: explicit flee destination + fleeProvinceId = Some(fleeProvinceId) // Important: explicit flee destination ) ), supplies = Some(Supplies(gold = 500, food = 700)) @@ -1815,38 +1803,40 @@ class ResolveBattleActionTest // Create a scenario where attackers flee val resolvedExpandedUnitsWithFledAttackers = battleHeroes .zip(battalions) - .map { case (h, b) => - ResolvedEagleUnit( - HeroConverter.fromProto(h), - Some(BattalionConverter.fromProto(b)), - if h.factionId.contains(attackerFid) then UnitStatus.Fled - else UnitStatus.Normal - ) + .map { + case (h, b) => + ResolvedEagleUnit( + HeroConverter.fromProto(h), + Some(BattalionConverter.fromProto(b)), + if h.factionId.contains(attackerFid) then UnitStatus.Fled + else UnitStatus.Normal + ) } val resolvedPlayersWithFledAttackers = resolvedExpandedUnitsWithFledAttackers .groupBy(_.hero.factionId.get) - .map { case (fid, units) => - ResolvedShardokPlayer( - eagleFid = fid, - units = units, - endGameCondition = EndGameCondition( - if fid == defenderFid then - EndGameCondition.Condition.Victory( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING - ) - else - EndGameCondition.Condition.Loss( - VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING - ) + .map { + case (fid, units) => + ResolvedShardokPlayer( + eagleFid = fid, + units = units, + endGameCondition = EndGameCondition( + if fid == defenderFid then + EndGameCondition.Condition.Victory( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + else + EndGameCondition.Condition.Loss( + VictoryCondition.VICTORY_CONDITION_LAST_PLAYER_STANDING + ) + ) ) - ) } .toVector val gameStateWithFleeProvince = startingGameState.update( - _.outstandingBattles.head := battleWithFleeProvince, + _.outstandingBattles.head := battleWithFleeProvince, _.provinces(fleeProvinceId) := fleeProvince ) @@ -1860,7 +1850,7 @@ class ResolveBattleActionTest ) ) - val results = action.resultsOfExecute() + val results = action.resultsOfExecute() val battleEndedResult = results.find(x => x.`type` == BATTLE_ENDED) battleEndedResult should not be empty diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedActionTest.scala index bbd5495d09..40bafef71a 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/SafePassageArmiesProceedActionTest.scala @@ -3,28 +3,20 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.eagle.{FactionId, ProvinceId, RoundId} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.types.ArmySafePassageProceededResultType -import net.eagle0.eagle.model.state.{ - Army, - HostileArmyGroup, - MovingArmy, - Supplies -} +import net.eagle0.eagle.model.state.{Army, HostileArmyGroup, MovingArmy, Supplies} import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ProvinceT -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - Attacking, - SafePassageGranted -} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{Attacking, SafePassageGranted} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.Inside.inside class SafePassageArmiesProceedActionTest extends AnyFlatSpec with Matchers { - private val proceedingFactionId: FactionId = 31 - private val currentRoundId: RoundId = 8721 + private val proceedingFactionId: FactionId = 31 + private val currentRoundId: RoundId = 8721 private val proceedingThroughProvinceId: ProvinceId = 11 - private val destinationProvinceId: ProvinceId = 98 + private val destinationProvinceId: ProvinceId = 98 private val hostileArmyGroup: HostileArmyGroup = HostileArmyGroup( factionId = proceedingFactionId, @@ -78,9 +70,10 @@ class SafePassageArmiesProceedActionTest extends AnyFlatSpec with Matchers { results.head.actionResultType shouldBe ArmySafePassageProceededResultType val cps = results.head.changedProvinces cps should have size 2 - inside(cps.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe proceedingThroughProvinceId - cp.removedHostileArmyFactionIds should contain only proceedingFactionId + inside(cps.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe proceedingThroughProvinceId + cp.removedHostileArmyFactionIds should contain only proceedingFactionId } } @@ -91,38 +84,39 @@ class SafePassageArmiesProceedActionTest extends AnyFlatSpec with Matchers { results.head.actionResultType shouldBe ArmySafePassageProceededResultType val cps = results.head.changedProvinces cps should have size 2 - inside(cps(1)) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.newIncomingArmies should contain theSameElementsAs Vector( - MovingArmy( - army = Army( - fleeProvinceId = None, - factionId = proceedingFactionId, - units = Vector.empty + inside(cps(1)) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.newIncomingArmies should contain theSameElementsAs Vector( + MovingArmy( + army = Army( + fleeProvinceId = None, + factionId = proceedingFactionId, + units = Vector.empty + ), + arrivalRound = currentRoundId + 1, + destinationProvinceId = destinationProvinceId, + originProvinceId = proceedingThroughProvinceId, + supplies = Supplies(0, 0), + suppliesLoss = 0, + id = 121, + startingPositionIndex = Some(5) ), - arrivalRound = currentRoundId + 1, - destinationProvinceId = destinationProvinceId, - originProvinceId = proceedingThroughProvinceId, - supplies = Supplies(0, 0), - suppliesLoss = 0, - id = 121, - startingPositionIndex = Some(5) - ), - MovingArmy( - army = Army( - fleeProvinceId = None, - factionId = proceedingFactionId, - units = Vector.empty - ), - arrivalRound = currentRoundId + 1, - destinationProvinceId = destinationProvinceId, - originProvinceId = proceedingThroughProvinceId, - supplies = Supplies(0, 0), - suppliesLoss = 0, - id = 122, - startingPositionIndex = Some(6) + MovingArmy( + army = Army( + fleeProvinceId = None, + factionId = proceedingFactionId, + units = Vector.empty + ), + arrivalRound = currentRoundId + 1, + destinationProvinceId = destinationProvinceId, + originProvinceId = proceedingThroughProvinceId, + supplies = Supplies(0, 0), + suppliesLoss = 0, + id = 122, + startingPositionIndex = Some(6) + ) ) - ) } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseActionTest.scala index b4d5a90535..f8fb4dd9e6 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/TruceTurnBackPhaseActionTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.ProtoMatchers.equalProto -import net.eagle0.eagle.common.action_result_type.ActionResultType.{ - END_TRUCE_TURN_BACK_PHASE, - WITHDRAWAL_FOR_TRUCE -} +import net.eagle0.eagle.common.action_result_type.ActionResultType.{END_TRUCE_TURN_BACK_PHASE, WITHDRAWAL_FOR_TRUCE} import net.eagle0.eagle.common.round_phase.{NewRoundPhase, RoundPhase} import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.army.* @@ -32,7 +29,7 @@ class TruceTurnBackPhaseActionTest extends AnyFlatSpec with Matchers { private val defendingFid: FactionId = 23 private val destinationPid = 17 - private val fleePid = 98 + private val fleePid = 98 private val fleeProvince = Province(id = fleePid, rulingFactionId = Some(attackingFid)) @@ -68,8 +65,7 @@ class TruceTurnBackPhaseActionTest extends AnyFlatSpec with Matchers { ) private val gameState = GameState( - currentDate = - Some(net.eagle0.eagle.common.date.Date(year = 400, month = 3)), + currentDate = Some(net.eagle0.eagle.common.date.Date(year = 400, month = 3)), currentRoundId = 155, currentPhase = RoundPhase.TRUCE_TURN_BACK, provinces = mapifyProvinces(destinationProvince, fleeProvince), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedActionTest.scala index 3e7e75b9ab..ae20641e27 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroAppearedActionTest.scala @@ -2,19 +2,13 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.eagle.{FactionId, GameId} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.generated_text_request.{ - FixedHeroName, - LlmRequestT -} +import net.eagle0.eagle.model.action_result.generated_text_request.{FixedHeroName, LlmRequestT} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.HeroInitialBackstoryRequest import net.eagle0.eagle.model.action_result.types.HeroAppearsResultType import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.hero.backstory_version.BackstoryVersion import net.eagle0.eagle.model.state.hero.concrete.HeroC -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -23,10 +17,10 @@ import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class UnaffiliatedHeroAppearedActionTest extends AnyFlatSpec with Matchers { private val provinceId = 17 - private val heroId = 23 + private val heroId = 23 private val currentRoundId = 37 - private val currentDate = Date(year = 273, month = Date.Month.July) + private val currentDate = Date(year = 273, month = Date.Month.July) private val newHero = HeroC( id = heroId, @@ -96,10 +90,11 @@ class UnaffiliatedHeroAppearedActionTest extends AnyFlatSpec with Matchers { val result = action.immediateExecute result.changedProvinces should have size 1 - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newUnaffiliatedHeroes should contain theSameElementsAs Vector( - expectedNewUnaffiliatedHero - ) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newUnaffiliatedHeroes should contain theSameElementsAs Vector( + expectedNewUnaffiliatedHero + ) } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedActionTest.scala index 83355f05d6..249767f004 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroMovedActionTest.scala @@ -3,10 +3,7 @@ package library.actions.impl.action import net.eagle0.common.ProtoMatchers.equalProto import net.eagle0.common.SeededRandom -import net.eagle0.eagle.common.action_result_notification_details.{ - Notification, - OutlawSpottedDetails -} +import net.eagle0.eagle.common.action_result_notification_details.{Notification, OutlawSpottedDetails} import net.eagle0.eagle.common.action_result_notification_details.Notification.TargetFaction import net.eagle0.eagle.common.action_result_type.ActionResultType.HERO_MOVED import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo @@ -23,29 +20,22 @@ import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.settings.FreeHeroMoveVigorCost -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class UnaffiliatedHeroMovedActionTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val outlawUH = +class UnaffiliatedHeroMovedActionTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val outlawUH = UnaffiliatedHero(heroId = 9, `type` = UNAFFILIATED_HERO_OUTLAW) private val travelerUH = UnaffiliatedHero(heroId = 19, `type` = UNAFFILIATED_HERO_TRAVELER) private val fromPid = 22 - private val toPid = 33 + private val toPid = 33 private val fromFid = 7 - private val toFid = 9 - private val gs = GameState( + private val toFid = 9 + private val gs = GameState( heroes = mapifyHeroes( Hero(id = 9), Hero(id = 19) @@ -60,9 +50,8 @@ class UnaffiliatedHeroMovedActionTest ) ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = FreeHeroMoveVigorCost.setDoubleValue(12) - } "immediateExecute" should "include a notification if it's an outlaw" in { val result = UnaffiliatedHeroMovedAction( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroesChangedActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroesChangedActionTest.scala index aa213ac8ff..76e97c4c88 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroesChangedActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/UnaffiliatedHeroesChangedActionTest.scala @@ -17,10 +17,10 @@ import org.scalatest.matchers.should.Matchers class UnaffiliatedHeroesChangedActionTest extends AnyFlatSpec with Matchers { private val heroId1: HeroId = 7 - private val hero1: Hero = Hero(id = heroId1) + private val hero1: Hero = Hero(id = heroId1) private val heroId2: HeroId = 19 - private val hero2: Hero = Hero(id = heroId2) + private val hero2: Hero = Hero(id = heroId2) private val provinceId: ProvinceId = 9 @@ -68,7 +68,7 @@ class UnaffiliatedHeroesChangedActionTest extends AnyFlatSpec with Matchers { val result = heroChangedAction.immediateExecute result.changedProvinces should have size 1 - val cp = result.changedProvinces.head + val cp = result.changedProvinces.head cp.changedUnaffiliatedHeroes shouldBe Vector( UnaffiliatedHero(heroId = heroId1, `type` = UNAFFILIATED_HERO_RESIDENT) @@ -86,10 +86,10 @@ class UnaffiliatedHeroesChangedActionTest extends AnyFlatSpec with Matchers { val result = heroChangedAction.immediateExecute result.changedProvinces should have size 1 - val cp = result.changedProvinces.head + val cp = result.changedProvinces.head - cp.removedUnaffiliatedHeroIds should not contain (heroId2) - cp.newUnaffiliatedHeroes.map(_.heroId) should not contain (heroId2) + cp.removedUnaffiliatedHeroIds should not contain heroId2 + cp.newUnaffiliatedHeroes.map(_.heroId) should not contain heroId2 } it should "change two included hero's types" in { @@ -104,7 +104,7 @@ class UnaffiliatedHeroesChangedActionTest extends AnyFlatSpec with Matchers { val result = heroChangedAction.immediateExecute result.changedProvinces should have size 1 - val cp = result.changedProvinces.head + val cp = result.changedProvinces.head cp.changedUnaffiliatedHeroes should contain theSameElementsAs Vector( UnaffiliatedHero(heroId = heroId1, `type` = UNAFFILIATED_HERO_RESIDENT), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WithdrawnArmiesReturnHomeActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WithdrawnArmiesReturnHomeActionTest.scala index 8dcc5cc0b8..ba916d61f1 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WithdrawnArmiesReturnHomeActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WithdrawnArmiesReturnHomeActionTest.scala @@ -3,17 +3,8 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.common.ProtoMatchers import net.eagle0.eagle.{FactionId, ProvinceId, RoundId} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.types.{ - ArmyShatteredResultType, - WithdrawnArmyReturnsResultType -} -import net.eagle0.eagle.model.state.{ - Army, - HostileArmyGroup, - HostileArmyGroupStatus, - MovingArmy, - Supplies -} +import net.eagle0.eagle.model.action_result.types.{ArmyShatteredResultType, WithdrawnArmyReturnsResultType} +import net.eagle0.eagle.model.state.{Army, HostileArmyGroup, HostileArmyGroupStatus, MovingArmy, Supplies} import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.HostileArmyGroupStatus.Attacking @@ -21,13 +12,10 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.Inside.inside -class WithdrawnArmiesReturnHomeActionTest - extends AnyFlatSpec - with Matchers - with ProtoMatchers { +class WithdrawnArmiesReturnHomeActionTest extends AnyFlatSpec with Matchers with ProtoMatchers { - private val withdrawingFactionId: FactionId = 31 - private val currentRoundId: RoundId = 8721 + private val withdrawingFactionId: FactionId = 31 + private val currentRoundId: RoundId = 8721 private val withdrawingFromProvinceId: ProvinceId = 11 private val hostileArmyGroup: HostileArmyGroup = HostileArmyGroup( @@ -79,9 +67,10 @@ class WithdrawnArmiesReturnHomeActionTest results.head.actionResultType shouldBe WithdrawnArmyReturnsResultType results.head.changedProvinces should have size 3 - inside(results.head.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe withdrawingFromProvinceId - cp.removedHostileArmyFactionIds shouldBe Vector(withdrawingFactionId) + inside(results.head.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe withdrawingFromProvinceId + cp.removedHostileArmyFactionIds shouldBe Vector(withdrawingFactionId) } } @@ -211,7 +200,7 @@ class WithdrawnArmiesReturnHomeActionTest "an army set to Attacking" should "do nothing" in { val hostileArmyGroupWithAttackingArmy: HostileArmyGroup = hostileArmyGroup.copy(status = Attacking) - val provinces: Vector[ProvinceT] = Vector( + val provinces: Vector[ProvinceT] = Vector( ProvinceC( id = withdrawingFromProvinceId, hostileArmies = Vector(hostileArmyGroupWithAttackingArmy) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllActionTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllActionTest.scala index ea1ddb1bdd..a5e88b2417 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllActionTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/WonFreeForAllActionTest.scala @@ -3,14 +3,7 @@ package net.eagle0.eagle.library.actions.impl.action import net.eagle0.eagle.{FactionId, ProvinceId, RoundId} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.types.WonFreeForAllResultType -import net.eagle0.eagle.model.state.{ - Army, - BattalionTypeId, - CombatUnit, - HostileArmyGroup, - MovingArmy, - Supplies -} +import net.eagle0.eagle.model.state.{Army, BattalionTypeId, CombatUnit, HostileArmyGroup, MovingArmy, Supplies} import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.province.concrete.ProvinceC @@ -24,8 +17,8 @@ import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class WonFreeForAllActionTest extends AnyFlatSpec with Matchers { - private val winningFid: FactionId = 37 - private val roundId: RoundId = 88 + private val winningFid: FactionId = 37 + private val roundId: RoundId = 88 private val provinceId: ProvinceId = 19 private val winningArmy = MovingArmy( @@ -82,7 +75,7 @@ class WonFreeForAllActionTest extends AnyFlatSpec with Matchers { ) ) - private val winningUnits = Vector( + private val winningUnits = Vector( ResolvedEagleUnit( hero = HeroC( id = 11, @@ -116,8 +109,9 @@ class WonFreeForAllActionTest extends AnyFlatSpec with Matchers { result.actionResultType shouldBe WonFreeForAllResultType result.provinceId should contain(provinceId) - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe provinceId + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe provinceId } } @@ -140,8 +134,9 @@ class WonFreeForAllActionTest extends AnyFlatSpec with Matchers { winningArmyGroups ).immediateExecute - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.newHostileArmies.loneElement.armies.loneElement shouldBe winningArmy + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.newHostileArmies.loneElement.armies.loneElement shouldBe winningArmy } } @@ -166,27 +161,28 @@ class WonFreeForAllActionTest extends AnyFlatSpec with Matchers { winningArmyGroups ).immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newHostileArmies.loneElement.armies.loneElement shouldBe MovingArmy( - id = 0, - destinationProvinceId = provinceId, - originProvinceId = 1, - army = Army( - factionId = winningFid, - units = Vector( - CombatUnit( - heroId = 12, - battalionId = Some(34), - factionId = winningFid - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newHostileArmies.loneElement.armies.loneElement shouldBe MovingArmy( + id = 0, + destinationProvinceId = provinceId, + originProvinceId = 1, + army = Army( + factionId = winningFid, + units = Vector( + CombatUnit( + heroId = 12, + battalionId = Some(34), + factionId = winningFid + ) + ), + fleeProvinceId = None ), - fleeProvinceId = None - ), - arrivalRound = roundId, - supplies = Supplies(0, 0), - suppliesLoss = 0.0, - startingPositionIndex = None - ) + arrivalRound = roundId, + supplies = Supplies(0, 0), + suppliesLoss = 0.0, + startingPositionIndex = None + ) } } @@ -274,15 +270,16 @@ class WonFreeForAllActionTest extends AnyFlatSpec with Matchers { winningArmyGroups = multipleWinningArmyGroups ).immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newHostileArmies should have size 2 - cp.newHostileArmies.flatMap( - _.armies - ) should contain theSameElementsAs Seq( - winningArmy, - sameFidWinningArmy, - differentFidWinningArmy - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newHostileArmies should have size 2 + cp.newHostileArmies.flatMap( + _.armies + ) should contain theSameElementsAs Seq( + winningArmy, + sameFidWinningArmy, + differentFidWinningArmy + ) } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpersTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpersTest.scala index 7187d8b217..db24718af8 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpersTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/AllianceResolutionHelpersTest.scala @@ -28,28 +28,17 @@ import net.eagle0.eagle.model.action_result.types.{ HeroesReturnedByAllyResultType } import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected, - Unresolved -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected, Unresolved} import net.eagle0.eagle.model.state.diplomacy_offer.AllianceOffer import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionRelationship import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.Ally -import net.eagle0.eagle.model.state.hero.{ - AllianceAmbassadorBackstoryEvent, - ReleasedByAllianceBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{AllianceAmbassadorBackstoryEvent, ReleasedByAllianceBackstoryEvent} import net.eagle0.eagle.model.state.hero.backstory_version.BackstoryVersion import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ProvinceOrderType.Entrust -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.Prisoner import org.scalatest.flatspec.AnyFlatSpec @@ -59,14 +48,11 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.{forEvery, forExactly} import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class AllianceResolutionHelpersTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AllianceResolutionHelpersTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val offeringFactionId = 7 - private val actingFactionId = 4 + private val actingFactionId = 4 - private val offeringFactionProvinceId = 15 + private val offeringFactionProvinceId = 15 private val acceptingFactionProvinceId = 23 private val acceptingFactionRulingHeroId = 28 @@ -210,9 +196,10 @@ class AllianceResolutionHelpersTest .newValue inside(results.loneElement) { result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId } } } @@ -239,13 +226,14 @@ class AllianceResolutionHelpersTest .newValue inside(results.loneElement) { result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.changedFactionRelationships.loneElement shouldBe FactionRelationship( - targetFactionId = offeringFactionId, - relationshipLevel = Ally, - resetDate = None - ) + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.changedFactionRelationships.loneElement shouldBe FactionRelationship( + targetFactionId = offeringFactionId, + relationshipLevel = Ally, + resetDate = None + ) } } } @@ -294,7 +282,7 @@ class AllianceResolutionHelpersTest ) ) ) - val results = AllianceResolutionHelpers + val results = AllianceResolutionHelpers .acceptedAllianceResult( allianceOffer = allianceOffer, currentDate = currentDate, @@ -305,15 +293,17 @@ class AllianceResolutionHelpersTest ) .newValue - inside(results.loneElement) { case result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe offeringFactionId - cf.changedFactionRelationships.loneElement shouldBe FactionRelationship( - targetFactionId = actingFactionId, - relationshipLevel = Ally, - resetDate = None - ) - } + inside(results.loneElement) { + case result => + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe offeringFactionId + cf.changedFactionRelationships.loneElement shouldBe FactionRelationship( + targetFactionId = actingFactionId, + relationshipLevel = Ally, + resetDate = None + ) + } } } @@ -326,7 +316,7 @@ class AllianceResolutionHelpersTest ) ) ) - val results = AllianceResolutionHelpers + val results = AllianceResolutionHelpers .acceptedAllianceResult( allianceOffer = allianceOffer, currentDate = currentDate, @@ -337,13 +327,14 @@ class AllianceResolutionHelpersTest ) .newValue - inside(results.loneElement) { case result => - result.clientTextVisibilityExtensions should contain( - ClientTextVisibilityExtensionC( - textId = "backstory_28", - recipientFactionIds = Vector(offeringFactionId) + inside(results.loneElement) { + case result => + result.clientTextVisibilityExtensions should contain( + ClientTextVisibilityExtensionC( + textId = "backstory_28", + recipientFactionIds = Vector(offeringFactionId) + ) ) - ) } } @@ -356,7 +347,7 @@ class AllianceResolutionHelpersTest ) ) ) - val results = AllianceResolutionHelpers + val results = AllianceResolutionHelpers .acceptedAllianceResult( allianceOffer = allianceOffer, currentDate = currentDate, @@ -367,11 +358,13 @@ class AllianceResolutionHelpersTest ) .newValue - inside(results.loneElement) { case result => - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe offeringFactionProvinceId - cp.newRulingFactionHeroIds.loneElement shouldBe 111 - } + inside(results.loneElement) { + case result => + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe offeringFactionProvinceId + cp.newRulingFactionHeroIds.loneElement shouldBe 111 + } } } @@ -535,32 +528,33 @@ class AllianceResolutionHelpersTest results.size shouldBe 2 - inside(results.last) { case result: ActionResultC => - result.actionResultType shouldBe HeroesReturnedByAllyResultType - result.actingFactionId shouldBe Some(offeringFactionId) - result.changedHeroes.loneElement shouldBe - ChangedHeroC( - heroId = 523, - newFactionId = Some(actingFactionId), - newEventsForHeroBackstory = Vector( - ReleasedByAllianceBackstoryEvent( - date = currentDate, - releasingFactionId = offeringFactionId, - releasedFromProvinceId = offeringFactionProvinceId + inside(results.last) { + case result: ActionResultC => + result.actionResultType shouldBe HeroesReturnedByAllyResultType + result.actingFactionId shouldBe Some(offeringFactionId) + result.changedHeroes.loneElement shouldBe + ChangedHeroC( + heroId = 523, + newFactionId = Some(actingFactionId), + newEventsForHeroBackstory = Vector( + ReleasedByAllianceBackstoryEvent( + date = currentDate, + releasingFactionId = offeringFactionId, + releasedFromProvinceId = offeringFactionProvinceId + ) ) ) - ) - result.changedProvinces shouldBe Vector( - ChangedProvinceC( - provinceId = offeringFactionProvinceId, - removedUnaffiliatedHeroIds = Vector(523) - ), - ChangedProvinceC( - provinceId = acceptingFactionProvinceId, - newRulingFactionHeroIds = Vector(523) + result.changedProvinces shouldBe Vector( + ChangedProvinceC( + provinceId = offeringFactionProvinceId, + removedUnaffiliatedHeroIds = Vector(523) + ), + ChangedProvinceC( + provinceId = acceptingFactionProvinceId, + newRulingFactionHeroIds = Vector(523) + ) ) - ) } } @@ -576,7 +570,7 @@ class AllianceResolutionHelpersTest .actionResultType shouldBe AllianceRejectedResultType } - it should "remove the incoming alliance offer" in { + it should "remove the incoming alliance offer" in inside( AllianceResolutionHelpers .rejectedAllianceResult( @@ -586,36 +580,16 @@ class AllianceResolutionHelpersTest functionalRandom = functionalRandom ) .newValue - ) { case result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId - } - } - } - - it should "not create a alliance for the acting faction" in { - inside( - AllianceResolutionHelpers - .rejectedAllianceResult( - allianceOffer = allianceOffer, - currentDate = currentDate, - provinces = provinces, - functionalRandom = functionalRandom - ) - .newValue - ) { case result => - forEvery( - result.changedFactions.filter { case cf: ChangedFactionC => - cf.factionId == actingFactionId + ) { + case result => + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId } - ) { case cf: ChangedFactionC => - cf.changedFactionRelationships shouldBe empty - } } - } - it should "return the ambassador to their originating province" in { + it should "not create a alliance for the acting faction" in inside( AllianceResolutionHelpers .rejectedAllianceResult( @@ -625,15 +599,20 @@ class AllianceResolutionHelpersTest functionalRandom = functionalRandom ) .newValue - ) { case result => - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe offeringFactionProvinceId - cp.newRulingFactionHeroIds.loneElement shouldBe 111 - } + ) { + case result => + forEvery( + result.changedFactions.filter { + case cf: ChangedFactionC => + cf.factionId == actingFactionId + } + ) { + case cf: ChangedFactionC => + cf.changedFactionRelationships shouldBe empty + } } - } - it should "give the ambassador a new backstory text id" in { + it should "return the ambassador to their originating province" in inside( AllianceResolutionHelpers .rejectedAllianceResult( @@ -643,19 +622,39 @@ class AllianceResolutionHelpersTest functionalRandom = functionalRandom ) .newValue - ) { case result => - forExactly(1, result.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe 111 - ch.newEventsForHeroBackstory.loneElement shouldBe - AllianceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = 7, - toFactionId = 4, - outcome = Rejected - ) - } + ) { + case result => + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe offeringFactionProvinceId + cp.newRulingFactionHeroIds.loneElement shouldBe 111 + } + } + + it should "give the ambassador a new backstory text id" in + inside( + AllianceResolutionHelpers + .rejectedAllianceResult( + allianceOffer = allianceOffer, + currentDate = currentDate, + provinces = provinces, + functionalRandom = functionalRandom + ) + .newValue + ) { + case result => + forExactly(1, result.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe 111 + ch.newEventsForHeroBackstory.loneElement shouldBe + AllianceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = 7, + toFactionId = 4, + outcome = Rejected + ) + } } - } "imprisonedAmbassadorResults" should "return a result of type AMBASSADOR_IMPRISONED" in { val factionsWithAmbassadorImprisoned = Vector( @@ -699,9 +698,10 @@ class AllianceResolutionHelpersTest factionsWithAmbassadorImprisoned ) ) { result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId } } } @@ -725,9 +725,10 @@ class AllianceResolutionHelpersTest factionsWithAmbassadorImprisoned ) ) { result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.changedFactionRelationships shouldBe empty + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.changedFactionRelationships shouldBe empty } } } @@ -751,9 +752,10 @@ class AllianceResolutionHelpersTest factionsWithAmbassadorImprisoned ) ) { result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe offeringFactionId - cf.changedFactionRelationships shouldBe empty + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe offeringFactionId + cf.changedFactionRelationships shouldBe empty } } } @@ -777,16 +779,17 @@ class AllianceResolutionHelpersTest factionsWithAmbassadorImprisoned ) ) { result => - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe acceptingFactionProvinceId - inside(cp.newUnaffiliatedHeroes.loneElement) { - case uh: UnaffiliatedHeroT => - uh.heroId shouldBe 111 - uh.unaffiliatedHeroType shouldBe Prisoner - uh.lastFactionId shouldBe Some(offeringFactionId) - uh.recruitmentInfo shouldBe RecruitmentInfo.Prisoner - uh.factionBiases shouldBe Map(actingFactionId -> -100) - } + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe acceptingFactionProvinceId + inside(cp.newUnaffiliatedHeroes.loneElement) { + case uh: UnaffiliatedHeroT => + uh.heroId shouldBe 111 + uh.unaffiliatedHeroType shouldBe Prisoner + uh.lastFactionId shouldBe Some(offeringFactionId) + uh.recruitmentInfo shouldBe RecruitmentInfo.Prisoner + uh.factionBiases shouldBe Map(actingFactionId -> -100) + } } } } @@ -810,15 +813,16 @@ class AllianceResolutionHelpersTest factionsWithAmbassadorImprisoned ) ) { result => - forExactly(1, result.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe 111 - ch.newEventsForHeroBackstory.loneElement shouldBe - AllianceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = 7, - toFactionId = 4, - outcome = Imprisoned - ) + forExactly(1, result.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe 111 + ch.newEventsForHeroBackstory.loneElement shouldBe + AllianceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = 7, + toFactionId = 4, + outcome = Imprisoned + ) } } } @@ -842,8 +846,9 @@ class AllianceResolutionHelpersTest factionsWithAmbassadorImprisoned ) ) { result => - forEvery(result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId should not be offeringFactionProvinceId + forEvery(result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId should not be offeringFactionProvinceId } } } @@ -867,12 +872,13 @@ class AllianceResolutionHelpersTest factionsWithAmbassadorImprisoned ) ) { result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe offeringFactionId - cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( - targetFactionId = actingFactionId, - delta = -40 - ) + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe offeringFactionId + cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( + targetFactionId = actingFactionId, + delta = -40 + ) } } } @@ -902,12 +908,13 @@ class AllianceResolutionHelpersTest factions = factionsWithAmbassadorImprisoned ) ) { result => - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.factionId shouldBe 57 - cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( - targetFactionId = actingFactionId, - delta = -20 - ) + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.factionId shouldBe 57 + cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( + targetFactionId = actingFactionId, + delta = -20 + ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpersTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpersTest.scala index 777f86b5d6..3c66b676a5 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpersTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/BreakAllianceResolutionHelpersTest.scala @@ -14,28 +14,14 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.EagleInternalException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedFactionC, - ChangedHeroC, - TrustLevelUpdate -} -import net.eagle0.eagle.model.action_result.types.{ - AmbassadorImprisonedResultType, - BreakAllianceAcceptedResultType -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedFactionC, ChangedHeroC, TrustLevelUpdate} +import net.eagle0.eagle.model.action_result.types.{AmbassadorImprisonedResultType, BreakAllianceAcceptedResultType} import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Unresolved -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Unresolved} import net.eagle0.eagle.model.state.diplomacy_offer.BreakAlliance import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionRelationship -import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{ - Hostile, - Truce -} +import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{Hostile, Truce} import net.eagle0.eagle.model.state.hero.BreakAllianceAmbassadorBackstoryEvent import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ProvinceOrderType.Entrust @@ -49,12 +35,9 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.{forAll, forExactly} import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class BreakAllianceResolutionHelpersTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class BreakAllianceResolutionHelpersTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { val breakingFactionId = 7 - val actingFactionId = 4 + val actingFactionId = 4 private val breakAllianceOffer: BreakAlliance = BreakAlliance( originatingFactionId = breakingFactionId, @@ -127,7 +110,7 @@ class BreakAllianceResolutionHelpersTest .actionResultType shouldBe BreakAllianceAcceptedResultType } - it should "remove the incoming break alliance offer" in { + it should "remove the incoming break alliance offer" in inside( BreakAllianceResolutionHelpers .acceptedResult( @@ -145,9 +128,8 @@ class BreakAllianceResolutionHelpersTest changedFaction.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe breakingFactionId } } - } - it should "create an truce with the appropriate end date for the acting faction" in { + it should "create an truce with the appropriate end date for the acting faction" in inside( BreakAllianceResolutionHelpers .acceptedResult( @@ -162,18 +144,16 @@ class BreakAllianceResolutionHelpersTest forExactly(1, result.changedFactions) { case changedFaction: ChangedFactionC => changedFaction.factionId shouldBe actingFactionId - changedFaction.changedFactionRelationships.loneElement shouldBe { + changedFaction.changedFactionRelationships.loneElement shouldBe FactionRelationship( targetFactionId = breakingFactionId, relationshipLevel = Truce, resetDate = Some(Date(year = 557, month = Date.Month.July)) ) - } } } - } - it should "create a truce with the appropriate end date for the originating faction" in { + it should "create a truce with the appropriate end date for the originating faction" in inside( BreakAllianceResolutionHelpers .acceptedResult( @@ -188,18 +168,16 @@ class BreakAllianceResolutionHelpersTest forExactly(1, result.changedFactions) { case changedFaction: ChangedFactionC => changedFaction.factionId shouldBe breakingFactionId - changedFaction.changedFactionRelationships.loneElement shouldBe { + changedFaction.changedFactionRelationships.loneElement shouldBe FactionRelationship( targetFactionId = actingFactionId, relationshipLevel = Truce, resetDate = Some(Date(year = 557, month = Date.Month.July)) ) - } } } - } - it should "return the ambassador to their originating province" in { + it should "return the ambassador to their originating province" in inside( BreakAllianceResolutionHelpers .acceptedResult( @@ -217,9 +195,8 @@ class BreakAllianceResolutionHelpersTest changedProvince.newRulingFactionHeroIds.loneElement shouldBe 111 } } - } - it should "give the ambassador a new backstory text id" in { + it should "give the ambassador a new backstory text id" in inside( BreakAllianceResolutionHelpers .acceptedResult( @@ -231,26 +208,25 @@ class BreakAllianceResolutionHelpersTest ) .newValue ) { result => - forExactly(1, result.changedHeroes) { case hero: ChangedHeroC => - hero.heroId shouldBe 111 - hero.newEventsForHeroBackstory.loneElement shouldBe BreakAllianceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = 7, - toFactionId = 4, - outcome = Accepted - ) + forExactly(1, result.changedHeroes) { + case hero: ChangedHeroC => + hero.heroId shouldBe 111 + hero.newEventsForHeroBackstory.loneElement shouldBe BreakAllianceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = 7, + toFactionId = 4, + outcome = Accepted + ) } } - } "rejectedBreakAllianceResult" should "throw an exception" in { - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy BreakAllianceResolutionHelpers .rejectedResult( breakAllianceOffer = breakAllianceOffer, functionalRandom = functionalRandom ) - } ex.getMessage shouldBe "Cannot reject breaking an alliance" } @@ -266,7 +242,7 @@ class BreakAllianceResolutionHelpersTest .actionResultType shouldBe AmbassadorImprisonedResultType } - it should "remove the incoming break alliance offer" in { + it should "remove the incoming break alliance offer" in forExactly( 1, BreakAllianceResolutionHelpers @@ -277,13 +253,13 @@ class BreakAllianceResolutionHelpersTest factions = factions ) .changedFactions - ) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe breakingFactionId + ) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe breakingFactionId } - } - it should "not create a truce for the acting faction" in { + it should "not create a truce for the acting faction" in forExactly( 1, BreakAllianceResolutionHelpers @@ -294,19 +270,18 @@ class BreakAllianceResolutionHelpersTest factions = factions ) .changedFactions - ) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.changedFactionRelationships.loneElement shouldBe { - FactionRelationship( - targetFactionId = breakingFactionId, - relationshipLevel = Hostile, - resetDate = None - ) - } + ) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.changedFactionRelationships.loneElement shouldBe + FactionRelationship( + targetFactionId = breakingFactionId, + relationshipLevel = Hostile, + resetDate = None + ) } - } - it should "not create a alliance for the originating faction" in { + it should "not create a alliance for the originating faction" in forExactly( 1, BreakAllianceResolutionHelpers @@ -317,18 +292,18 @@ class BreakAllianceResolutionHelpersTest factions = factions ) .changedFactions - ) { case cf: ChangedFactionC => - cf.factionId shouldBe breakingFactionId - cf.changedFactionRelationships.loneElement shouldBe - FactionRelationship( - targetFactionId = actingFactionId, - relationshipLevel = Hostile, - resetDate = None - ) + ) { + case cf: ChangedFactionC => + cf.factionId shouldBe breakingFactionId + cf.changedFactionRelationships.loneElement shouldBe + FactionRelationship( + targetFactionId = actingFactionId, + relationshipLevel = Hostile, + resetDate = None + ) } - } - it should "imprison the ambassador" in { + it should "imprison the ambassador" in forExactly( 1, BreakAllianceResolutionHelpers @@ -339,19 +314,19 @@ class BreakAllianceResolutionHelpersTest factions = factions ) .changedProvinces - ) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 23 - cp.newUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 111, - unaffiliatedHeroType = Prisoner, - lastFactionId = Some(breakingFactionId), - recruitmentInfo = RecruitmentInfo.Prisoner, - factionBiases = Map(actingFactionId -> -100) - ) + ) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 23 + cp.newUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 111, + unaffiliatedHeroType = Prisoner, + lastFactionId = Some(breakingFactionId), + recruitmentInfo = RecruitmentInfo.Prisoner, + factionBiases = Map(actingFactionId -> -100) + ) } - } - it should "not change the ambassador's origin province" in { + it should "not change the ambassador's origin province" in forAll( BreakAllianceResolutionHelpers .imprisonedAmbassadorResult( @@ -361,10 +336,9 @@ class BreakAllianceResolutionHelpersTest factions = factions ) .changedProvinces - ) { cp => cp.provinceId should not be 15 } - } + )(cp => cp.provinceId should not be 15) - it should "give the ambassador a new backstory text id" in { + it should "give the ambassador a new backstory text id" in forExactly( 1, BreakAllianceResolutionHelpers @@ -375,18 +349,18 @@ class BreakAllianceResolutionHelpersTest factions = factions ) .changedHeroes - ) { case hero: ChangedHeroC => - hero.heroId shouldBe 111 - hero.newEventsForHeroBackstory.loneElement shouldBe BreakAllianceAmbassadorBackstoryEvent( - date = currentDate, - fromFactionId = 7, - toFactionId = 4, - outcome = Imprisoned - ) + ) { + case hero: ChangedHeroC => + hero.heroId shouldBe 111 + hero.newEventsForHeroBackstory.loneElement shouldBe BreakAllianceAmbassadorBackstoryEvent( + date = currentDate, + fromFactionId = 7, + toFactionId = 4, + outcome = Imprisoned + ) } - } - it should "decrease trust in the offering faction" in { + it should "decrease trust in the offering faction" in forExactly( 1, BreakAllianceResolutionHelpers @@ -397,15 +371,15 @@ class BreakAllianceResolutionHelpersTest factions = factions ) .changedFactions - ) { case cf: ChangedFactionC => - cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( - targetFactionId = actingFactionId, - delta = -40 - ) + ) { + case cf: ChangedFactionC => + cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( + targetFactionId = actingFactionId, + delta = -40 + ) } - } - it should "decrease trust less in other factions" in { + it should "decrease trust less in other factions" in forExactly( 1, BreakAllianceResolutionHelpers @@ -421,12 +395,12 @@ class BreakAllianceResolutionHelpersTest ) ) .changedFactions - ) { case cf: ChangedFactionC => - cf.factionId shouldBe 57 - cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( - targetFactionId = actingFactionId, - delta = -20 - ) + ) { + case cf: ChangedFactionC => + cf.factionId shouldBe 57 + cf.trustLevelUpdates.loneElement shouldBe TrustLevelUpdate( + targetFactionId = actingFactionId, + delta = -20 + ) } - } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpersTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpersTest.scala index d64872e554..047e21472b 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpersTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/InvitationResolutionHelpersTest.scala @@ -11,26 +11,12 @@ import net.eagle0.eagle.library.settings.{ StartingLoyalty } import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedHeroC, - StatAbsolute -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatAbsolute} import net.eagle0.eagle.model.action_result.types.InvitationAcceptedResultType -import net.eagle0.eagle.model.state.{ - Army, - BattalionTypeId, - CombatUnit, - MovingArmy, - Supplies -} +import net.eagle0.eagle.model.state.{Army, BattalionTypeId, CombatUnit, MovingArmy, Supplies} import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected, - Unresolved -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected, Unresolved} import net.eagle0.eagle.model.state.diplomacy_offer.Invitation import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.hero.JoinedByInvitationBackstoryEvent @@ -45,12 +31,9 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inspectors.forExactly -class InvitationResolutionHelpersTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class InvitationResolutionHelpersTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - private val random = new Random() + private val random = new Random() private var functionalRandom = SeededRandom(0) override def beforeEach(): Unit = { @@ -62,8 +45,8 @@ class InvitationResolutionHelpersTest functionalRandom = SeededRandom(random.nextLong()) } - private val actingFactionId: FactionId = 4 - private val firstInvitingFid: FactionId = 3 + private val actingFactionId: FactionId = 4 + private val firstInvitingFid: FactionId = 3 private val secondInvitingFid: FactionId = 8 private val actingFidProvince = ProvinceC( @@ -242,10 +225,11 @@ class InvitationResolutionHelpersTest .newValue .head - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe secondInvitingFidProvince.id - cp.newRulingFactionHeroIds should contain(99) - cp.newBattalionIds should contain(500) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe secondInvitingFidProvince.id + cp.newRulingFactionHeroIds should contain(99) + cp.newBattalionIds should contain(500) } } @@ -646,7 +630,7 @@ class InvitationResolutionHelpersTest // } "battalionOutcomes" should "bring all battalions when battalion count is less than or equal to hero count" in { - val provinces = Vector( + val provinces = Vector( ProvinceC( id = 1, rulingFactionHeroIds = Vector(10, 11, 12), // 3 heroes @@ -669,7 +653,7 @@ class InvitationResolutionHelpersTest } it should "bring all battalions when battalion count equals hero count" in { - val provinces = Vector( + val provinces = Vector( ProvinceC( id = 1, rulingFactionHeroIds = Vector(10, 11), // 2 heroes @@ -692,12 +676,11 @@ class InvitationResolutionHelpersTest } it should "bring only the strongest battalions when battalion count exceeds hero count" in { - val provinces = Vector( + val provinces = Vector( ProvinceC( id = 1, rulingFactionHeroIds = Vector(10, 11), // 2 heroes - battalionIds = - Vector(100, 101, 102, 103) // 4 battalions - more than heroes + battalionIds = Vector(100, 101, 102, 103) // 4 battalions - more than heroes ) ) val battalions = Vector( @@ -744,10 +727,10 @@ class InvitationResolutionHelpersTest } it should "handle multiple provinces correctly" in { - val provinces = Vector( + val provinces = Vector( ProvinceC( id = 1, - rulingFactionHeroIds = Vector(10), // 1 hero + rulingFactionHeroIds = Vector(10), // 1 hero battalionIds = Vector(100, 101, 102) // 3 battalions ), ProvinceC( @@ -818,14 +801,14 @@ class InvitationResolutionHelpersTest startingPositionIndex = Some(1) ) ) - val provinces = Vector( + val provinces = Vector( ProvinceC( id = 1, rulingFactionHeroIds = Vector(10), // 1 hero battalionIds = Vector(100, 101) // 2 battalions ) ) - val battalions = Vector( + val battalions = Vector( BattalionC( id = 100, typeId = BattalionTypeId.LightInfantry, diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpersTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpersTest.scala index 1188f4340c..560c2d6949 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpersTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/RansomResolutionHelpersTest.scala @@ -8,33 +8,17 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - TrustLevelUpdate -} -import net.eagle0.eagle.model.action_result.types.{ - RansomAcceptedResultType, - RansomRejectedResultType -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, TrustLevelUpdate} +import net.eagle0.eagle.model.action_result.types.{RansomAcceptedResultType, RansomRejectedResultType} import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Invalidated, - Rejected -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Invalidated, Rejected} import net.eagle0.eagle.model.state.diplomacy_offer.RansomOffer import net.eagle0.eagle.model.state.diplomacy_offer.RansomOfferDetails.{ HostageOfferedInExchange, PrisonerOfferedInExchange, PrisonerToBeRansomed } -import net.eagle0.eagle.model.state.hero.{ - ExchangedInRansomBackstoryEvent, - RansomedBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{ExchangedInRansomBackstoryEvent, RansomedBackstoryEvent} import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.quest.concrete.{ ExecutePrisonerQuest, @@ -44,23 +28,16 @@ import net.eagle0.eagle.model.state.quest.concrete.{ } import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Prisoner, - Resident, - Traveler -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Prisoner, Resident, Traveler} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class RansomResolutionHelpersTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class RansomResolutionHelpersTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val questFailedRecruitmentPenalty = -50 - private val questRecruitmentBonus = 250 + private val questRecruitmentBonus = 250 override def beforeEach(): Unit = { TrustDeltaFromRejectingRansom.setIntValue(-25) @@ -69,16 +46,16 @@ class RansomResolutionHelpersTest QuestRecruitmentBonus.setDoubleValue(questRecruitmentBonus) } - private val offeringFactionId = 17 + private val offeringFactionId = 17 private val offeringProvinceId = 55 - private val messengerHeroId = 989 + private val messengerHeroId = 989 private val imprisoningFactionId = 15 private val prisonerToBeRansomedHeroId = 2 private val destinationProvinceId = 3 - private val destinationProvince = ProvinceC( + private val destinationProvince = ProvinceC( id = destinationProvinceId, rulingFactionId = Some(imprisoningFactionId) ) @@ -92,8 +69,8 @@ class RansomResolutionHelpersTest previousBackstoryTextIdLookup = _ => "backstory_text" ) - private val prisoner1HeroId = 151 - private val prisoner2HeroId = 152 + private val prisoner1HeroId = 151 + private val prisoner2HeroId = 152 private val acceptedRansomOffer: RansomOffer = RansomOffer( originatingFactionId = offeringFactionId, targetFactionId = imprisoningFactionId, @@ -187,17 +164,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results.loneElement.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe 101 - ch.newEventsForHeroBackstory shouldBe Vector( - ExchangedInRansomBackstoryEvent( - date = currentDate, - ransomPaidByFactionId = offeringFactionId, - ransomPaidToFactionId = imprisoningFactionId, - ransomedHeroId = 2, - imprisonedInProvinceId = destinationProvinceId + forExactly(1, results.loneElement.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe 101 + ch.newEventsForHeroBackstory shouldBe Vector( + ExchangedInRansomBackstoryEvent( + date = currentDate, + ransomPaidByFactionId = offeringFactionId, + ransomPaidToFactionId = imprisoningFactionId, + ransomedHeroId = 2, + imprisonedInProvinceId = destinationProvinceId + ) ) - ) } } @@ -256,30 +234,32 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results.loneElement.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe 151 - ch.newEventsForHeroBackstory shouldBe Vector( - ExchangedInRansomBackstoryEvent( - date = currentDate, - ransomPaidByFactionId = offeringFactionId, - ransomPaidToFactionId = imprisoningFactionId, - ransomedHeroId = 2, - imprisonedInProvinceId = destinationProvinceId + forExactly(1, results.loneElement.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe 151 + ch.newEventsForHeroBackstory shouldBe Vector( + ExchangedInRansomBackstoryEvent( + date = currentDate, + ransomPaidByFactionId = offeringFactionId, + ransomPaidToFactionId = imprisoningFactionId, + ransomedHeroId = 2, + imprisonedInProvinceId = destinationProvinceId + ) ) - ) } - forExactly(1, results.loneElement.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe 152 - ch.newEventsForHeroBackstory shouldBe Vector( - ExchangedInRansomBackstoryEvent( - date = currentDate, - ransomPaidByFactionId = offeringFactionId, - ransomPaidToFactionId = imprisoningFactionId, - ransomedHeroId = 2, - imprisonedInProvinceId = destinationProvinceId + forExactly(1, results.loneElement.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe 152 + ch.newEventsForHeroBackstory shouldBe Vector( + ExchangedInRansomBackstoryEvent( + date = currentDate, + ransomPaidByFactionId = offeringFactionId, + ransomPaidToFactionId = imprisoningFactionId, + ransomedHeroId = 2, + imprisonedInProvinceId = destinationProvinceId + ) ) - ) } } @@ -323,9 +303,10 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results.loneElement.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe prisonerToBeRansomedHeroId - ch.newFactionId shouldBe Some(offeringFactionId) + forExactly(1, results.loneElement.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe prisonerToBeRansomedHeroId + ch.newFactionId shouldBe Some(offeringFactionId) } } @@ -337,18 +318,19 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results.loneElement.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe prisonerToBeRansomedHeroId - ch.newEventsForHeroBackstory shouldBe Vector( - RansomedBackstoryEvent( - date = currentDate, - ransomPaidByFactionId = offeringFactionId, - ransomPaidToFactionId = imprisoningFactionId, - imprisonedInProvinceId = destinationProvinceId, - goldPaid = 500, - heroIdsExchanged = Vector(151, 152, 101) + forExactly(1, results.loneElement.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe prisonerToBeRansomedHeroId + ch.newEventsForHeroBackstory shouldBe Vector( + RansomedBackstoryEvent( + date = currentDate, + ransomPaidByFactionId = offeringFactionId, + ransomPaidToFactionId = imprisoningFactionId, + imprisonedInProvinceId = destinationProvinceId, + goldPaid = 500, + heroIdsExchanged = Vector(151, 152, 101) + ) ) - ) } } @@ -360,9 +342,10 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results.loneElement.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe 101 - ch.clearFactionId shouldBe true + forExactly(1, results.loneElement.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe 101 + ch.clearFactionId shouldBe true } } @@ -370,8 +353,9 @@ class RansomResolutionHelpersTest val result = RansomResolutionHelpers.rejectedRansomResult(rejectedDiploOffer) - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId } } @@ -443,17 +427,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = - Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -480,17 +465,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = - Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -517,17 +503,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = - Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -555,16 +542,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.WouldJoin, - factionBiases = Map(imprisoningFactionId -> questRecruitmentBonus) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.WouldJoin, + factionBiases = Map(imprisoningFactionId -> questRecruitmentBonus) + ) + } } } @@ -591,17 +580,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = - Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -628,17 +618,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = - Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -665,17 +656,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = - Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -703,17 +695,18 @@ class RansomResolutionHelpersTest questFulfillmentChecker = questFulfillmentChecker ) - forExactly(1, results) { case ar: ActionResultC => - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe destinationProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 9991, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = - Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) - ) - } + forExactly(1, results) { + case ar: ActionResultC => + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe destinationProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 9991, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(imprisoningFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -730,8 +723,9 @@ class RansomResolutionHelpersTest offer = rejectedDiploOffer ) - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId } } @@ -740,9 +734,10 @@ class RansomResolutionHelpersTest offer = rejectedDiploOffer ) - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.trustLevelUpdates.loneElement shouldBe - TrustLevelUpdate(targetFactionId = imprisoningFactionId, delta = -25) + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.trustLevelUpdates.loneElement shouldBe + TrustLevelUpdate(targetFactionId = imprisoningFactionId, delta = -25) } } @@ -767,8 +762,9 @@ class RansomResolutionHelpersTest offer = invalidatedDiploOffer ) - forExactly(1, result.changedFactions) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId + forExactly(1, result.changedFactions) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds.loneElement shouldBe offeringFactionId } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpersTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpersTest.scala index 436fc2f326..2ab53cbf1c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpersTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/action/diplomacy_helpers/TruceResolutionHelpersTest.scala @@ -14,11 +14,7 @@ import net.eagle0.eagle.library.settings.{ TrustDeltaForImprisoningOwnHero } import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedFactionC, - ChangedHeroC, - TrustLevelUpdate -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedFactionC, ChangedHeroC, TrustLevelUpdate} import net.eagle0.eagle.model.action_result.types.{ AmbassadorImprisonedResultType, TruceAcceptedResultType, @@ -26,12 +22,7 @@ import net.eagle0.eagle.model.action_result.types.{ } import net.eagle0.eagle.model.action_result.ActionResultT import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected, - Unresolved -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected, Unresolved} import net.eagle0.eagle.model.state.diplomacy_offer.TruceOffer import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionRelationship @@ -43,11 +34,7 @@ import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.quest.concrete.TruceWithFactionQuest import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Prisoner, - Resident, - Traveler -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Prisoner, Resident, Traveler} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach @@ -55,12 +42,9 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.{forAll, forExactly} import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class TruceResolutionHelpersTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class TruceResolutionHelpersTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { val offeringFactionId = 7 - val actingFactionId = 4 + val actingFactionId = 4 private val endDate = Date(year = 300, month = Date.Month.April) @@ -75,8 +59,8 @@ class TruceResolutionHelpersTest ) private val currentRoundId = 133 - private val currentDate = Date(year = 300, month = Date.Month.March) - private val gameId = 0xcafe + private val currentDate = Date(year = 300, month = Date.Month.March) + private val gameId = 0xcafe private val actingFaction: FactionC = FactionC( id = actingFactionId, @@ -102,7 +86,7 @@ class TruceResolutionHelpersTest rulingFactionHeroIds = Vector(22), provinceOrders = Entrust ) - private val actingFactionProvince = ProvinceC( + private val actingFactionProvince = ProvinceC( id = 23, rulingFactionId = Some(actingFactionId), rulingHeroId = Some(15), @@ -141,7 +125,7 @@ class TruceResolutionHelpersTest .actionResultType shouldBe TruceAcceptedResultType } - it should "remove the incoming truce offer" in { + it should "remove the incoming truce offer" in forExactly( 1, TruceResolutionHelpers @@ -154,15 +138,15 @@ class TruceResolutionHelpersTest ) .newValue .changedFactions - ) { case changedFaction: ChangedFactionC => - changedFaction.factionId shouldBe actingFactionId - changedFaction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - offeringFactionId - ) + ) { + case changedFaction: ChangedFactionC => + changedFaction.factionId shouldBe actingFactionId + changedFaction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + offeringFactionId + ) } - } - it should "create a truce with the appropriate end date for the acting faction" in { + it should "create a truce with the appropriate end date for the acting faction" in forExactly( 1, TruceResolutionHelpers @@ -175,19 +159,19 @@ class TruceResolutionHelpersTest ) .newValue .changedFactions - ) { case cf: ChangedFactionC => - cf.factionId shouldBe actingFactionId - cf.changedFactionRelationships shouldBe Vector( - FactionRelationship( - targetFactionId = offeringFactionId, - relationshipLevel = Truce, - resetDate = Some(endDate) + ) { + case cf: ChangedFactionC => + cf.factionId shouldBe actingFactionId + cf.changedFactionRelationships shouldBe Vector( + FactionRelationship( + targetFactionId = offeringFactionId, + relationshipLevel = Truce, + resetDate = Some(endDate) + ) ) - ) } - } - it should "create a truce with the appropriate end date for the originating faction" in { + it should "create a truce with the appropriate end date for the originating faction" in inside( TruceResolutionHelpers .acceptedTruceResult( @@ -201,18 +185,18 @@ class TruceResolutionHelpersTest .changedFactions .find(_.factionId == offeringFactionId) .get - ) { case changedFaction: ChangedFactionC => - changedFaction.changedFactionRelationships shouldBe Vector( - FactionRelationship( - targetFactionId = actingFactionId, - relationshipLevel = Truce, - resetDate = Some(endDate) + ) { + case changedFaction: ChangedFactionC => + changedFaction.changedFactionRelationships shouldBe Vector( + FactionRelationship( + targetFactionId = actingFactionId, + relationshipLevel = Truce, + resetDate = Some(endDate) + ) ) - ) } - } - it should "return the ambassador to their originating province" in { + it should "return the ambassador to their originating province" in forExactly( 1, TruceResolutionHelpers @@ -225,11 +209,11 @@ class TruceResolutionHelpersTest ) .newValue .changedProvinces - ) { case changedProvince: ChangedProvinceC => - changedProvince.provinceId shouldBe 15 - changedProvince.newRulingFactionHeroIds shouldBe Vector(111) + ) { + case changedProvince: ChangedProvinceC => + changedProvince.provinceId shouldBe 15 + changedProvince.newRulingFactionHeroIds shouldBe Vector(111) } - } it should "give the ambassador a new backstory text id" in { val changedHeroes = TruceResolutionHelpers @@ -243,20 +227,21 @@ class TruceResolutionHelpersTest .newValue .changedHeroes - inside(changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe 111 - inside(ch.newEventsForHeroBackstory.loneElement) { - case TruceAmbassadorBackstoryEvent( - date, - fromFactionId, - toFactionId, - outcome - ) => - date shouldBe currentDate - fromFactionId shouldBe 7 - toFactionId shouldBe 4 - outcome shouldBe Accepted - } + inside(changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe 111 + inside(ch.newEventsForHeroBackstory.loneElement) { + case TruceAmbassadorBackstoryEvent( + date, + fromFactionId, + toFactionId, + outcome + ) => + date shouldBe currentDate + fromFactionId shouldBe 7 + toFactionId shouldBe 4 + outcome shouldBe Accepted + } } } @@ -274,7 +259,7 @@ class TruceResolutionHelpersTest .actionResultType shouldBe TruceRejectedResultType } - it should "remove the incoming truce offer" in { + it should "remove the incoming truce offer" in forExactly( 1, TruceResolutionHelpers @@ -288,15 +273,15 @@ class TruceResolutionHelpersTest .newValue .head .changedFactions - ) { case changedFaction: ChangedFactionC => - changedFaction.factionId shouldBe actingFactionId - changedFaction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - offeringFactionId - ) + ) { + case changedFaction: ChangedFactionC => + changedFaction.factionId shouldBe actingFactionId + changedFaction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + offeringFactionId + ) } - } - it should "not create a truce for the acting faction" in { + it should "not create a truce for the acting faction" in forAll( TruceResolutionHelpers .rejectedTruceResults( @@ -310,12 +295,12 @@ class TruceResolutionHelpersTest .head .changedFactions .filter(_.factionId == actingFactionId) - ) { case changedFaction: ChangedFactionC => - changedFaction.changedFactionRelationships shouldBe empty + ) { + case changedFaction: ChangedFactionC => + changedFaction.changedFactionRelationships shouldBe empty } - } - it should "return the ambassador to their originating province" in { + it should "return the ambassador to their originating province" in forExactly( 1, TruceResolutionHelpers @@ -329,13 +314,13 @@ class TruceResolutionHelpersTest .newValue .head .changedProvinces - ) { case changedProvince: ChangedProvinceC => - changedProvince.provinceId shouldBe 15 - changedProvince.newRulingFactionHeroIds shouldBe Vector(111) + ) { + case changedProvince: ChangedProvinceC => + changedProvince.provinceId shouldBe 15 + changedProvince.newRulingFactionHeroIds shouldBe Vector(111) } - } - it should "give the ambassador a new backstory text id" in { + it should "give the ambassador a new backstory text id" in inside( TruceResolutionHelpers .rejectedTruceResults( @@ -349,22 +334,22 @@ class TruceResolutionHelpersTest .head .changedHeroes .loneElement - ) { case changedHero: ChangedHeroC => - changedHero.heroId shouldBe 111 - inside(changedHero.newEventsForHeroBackstory.loneElement) { - case TruceAmbassadorBackstoryEvent( - date, - fromFactionId, - toFactionId, - outcome - ) => - date shouldBe currentDate - fromFactionId shouldBe 7 - toFactionId shouldBe 4 - outcome shouldBe Rejected - } + ) { + case changedHero: ChangedHeroC => + changedHero.heroId shouldBe 111 + inside(changedHero.newEventsForHeroBackstory.loneElement) { + case TruceAmbassadorBackstoryEvent( + date, + fromFactionId, + toFactionId, + outcome + ) => + date shouldBe currentDate + fromFactionId shouldBe 7 + toFactionId shouldBe 4 + outcome shouldBe Rejected + } } - } it should "remove any quests for the offerer" in { val provinces = Vector( @@ -395,14 +380,15 @@ class TruceResolutionHelpersTest .newValue .head .changedProvinces - ) { case provinceWithQuest: ChangedProvinceC => - provinceWithQuest.provinceId shouldBe 15 - provinceWithQuest.changedUnaffiliatedHeroes should have size 1 - provinceWithQuest.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 151, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.NotDivined - ) + ) { + case provinceWithQuest: ChangedProvinceC => + provinceWithQuest.provinceId shouldBe 15 + provinceWithQuest.changedUnaffiliatedHeroes should have size 1 + provinceWithQuest.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 151, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.NotDivined + ) } } @@ -435,14 +421,15 @@ class TruceResolutionHelpersTest ) .newValue(1) .changedProvinces - ) { case provinceWithQuest: ChangedProvinceC => - provinceWithQuest.provinceId shouldBe 23 - provinceWithQuest.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 151, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -50) - ) + ) { + case provinceWithQuest: ChangedProvinceC => + provinceWithQuest.provinceId shouldBe 23 + provinceWithQuest.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 151, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -50) + ) } } @@ -459,7 +446,7 @@ class TruceResolutionHelpersTest .actionResultType shouldBe AmbassadorImprisonedResultType } - it should "remove the incoming truce offer" in { + it should "remove the incoming truce offer" in forExactly( 1, TruceResolutionHelpers @@ -472,15 +459,15 @@ class TruceResolutionHelpersTest ) .head .changedFactions - ) { case changedFaction: ChangedFactionC => - changedFaction.factionId shouldBe actingFactionId - changedFaction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - offeringFactionId - ) + ) { + case changedFaction: ChangedFactionC => + changedFaction.factionId shouldBe actingFactionId + changedFaction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + offeringFactionId + ) } - } - it should "not create a truce for the acting faction" in { + it should "not create a truce for the acting faction" in forAll( TruceResolutionHelpers .imprisonedAmbassadorResults( @@ -493,12 +480,12 @@ class TruceResolutionHelpersTest .head .changedFactions .filter(_.factionId == actingFactionId) - ) { case changedFaction: ChangedFactionC => - changedFaction.changedFactionRelationships shouldBe empty + ) { + case changedFaction: ChangedFactionC => + changedFaction.changedFactionRelationships shouldBe empty } - } - it should "not create a truce for the originating faction" in { + it should "not create a truce for the originating faction" in forAll( TruceResolutionHelpers .imprisonedAmbassadorResults( @@ -511,12 +498,12 @@ class TruceResolutionHelpersTest .head .changedFactions .filter(_.factionId == offeringFactionId) - ) { case changedFaction: ChangedFactionC => - changedFaction.changedFactionRelationships shouldBe empty + ) { + case changedFaction: ChangedFactionC => + changedFaction.changedFactionRelationships shouldBe empty } - } - it should "imprison the ambassador" in { + it should "imprison the ambassador" in forExactly( 1, TruceResolutionHelpers @@ -529,20 +516,20 @@ class TruceResolutionHelpersTest ) .head .changedProvinces - ) { case changedProvince: ChangedProvinceC => - changedProvince.provinceId shouldBe 23 - changedProvince.newUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 111, - unaffiliatedHeroType = Prisoner, - recruitmentAttempted = false, - lastFactionId = Some(offeringFactionId), - recruitmentInfo = RecruitmentInfo.Prisoner, - factionBiases = Map(actingFactionId -> -100) - ) + ) { + case changedProvince: ChangedProvinceC => + changedProvince.provinceId shouldBe 23 + changedProvince.newUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 111, + unaffiliatedHeroType = Prisoner, + recruitmentAttempted = false, + lastFactionId = Some(offeringFactionId), + recruitmentInfo = RecruitmentInfo.Prisoner, + factionBiases = Map(actingFactionId -> -100) + ) } - } - it should "give the ambassador a new backstory text id" in { + it should "give the ambassador a new backstory text id" in inside( TruceResolutionHelpers .imprisonedAmbassadorResults( @@ -555,22 +542,22 @@ class TruceResolutionHelpersTest .head .changedHeroes .loneElement - ) { case changedHero: ChangedHeroC => - changedHero.heroId shouldBe 111 - inside(changedHero.newEventsForHeroBackstory.loneElement) { - case TruceAmbassadorBackstoryEvent( - date, - fromFactionId, - toFactionId, - outcome - ) => - date shouldBe currentDate - fromFactionId shouldBe 7 - toFactionId shouldBe 4 - outcome shouldBe Imprisoned - } + ) { + case changedHero: ChangedHeroC => + changedHero.heroId shouldBe 111 + inside(changedHero.newEventsForHeroBackstory.loneElement) { + case TruceAmbassadorBackstoryEvent( + date, + fromFactionId, + toFactionId, + outcome + ) => + date shouldBe currentDate + fromFactionId shouldBe 7 + toFactionId shouldBe 4 + outcome shouldBe Imprisoned + } } - } it should "not change the ambassador's origin province" in { TruceResolutionHelpers @@ -600,12 +587,13 @@ class TruceResolutionHelpersTest results.head.changedFactions .filter(_.factionId == offeringFactionId) .loneElement - ) { case changedFaction: ChangedFactionC => - inside(changedFaction.trustLevelUpdates.loneElement) { - case trustLevelUpdate: TrustLevelUpdate => - trustLevelUpdate.targetFactionId shouldBe actingFactionId - trustLevelUpdate.delta shouldBe -40 - } + ) { + case changedFaction: ChangedFactionC => + inside(changedFaction.trustLevelUpdates.loneElement) { + case trustLevelUpdate: TrustLevelUpdate => + trustLevelUpdate.targetFactionId shouldBe actingFactionId + trustLevelUpdate.delta shouldBe -40 + } } } @@ -630,12 +618,13 @@ class TruceResolutionHelpersTest results.head.changedFactions .filter(_.factionId == 57) .loneElement - ) { case changedFaction: ChangedFactionC => - inside(changedFaction.trustLevelUpdates.loneElement) { - case trustLevelUpdate: TrustLevelUpdate => - trustLevelUpdate.targetFactionId shouldBe actingFactionId - trustLevelUpdate.delta shouldBe -20 - } + ) { + case changedFaction: ChangedFactionC => + inside(changedFaction.trustLevelUpdates.loneElement) { + case trustLevelUpdate: TrustLevelUpdate => + trustLevelUpdate.targetFactionId shouldBe actingFactionId + trustLevelUpdate.delta shouldBe -20 + } } } @@ -670,13 +659,14 @@ class TruceResolutionHelpersTest inside( results.head.changedProvinces.filter(_.provinceId == 15).loneElement - ) { case cp: ChangedProvinceC => - inside(cp.changedUnaffiliatedHeroes.loneElement) { - case uh: UnaffiliatedHeroC => - uh.heroId shouldBe 151 - uh.unaffiliatedHeroType shouldBe Resident - uh.recruitmentInfo shouldBe RecruitmentInfo.NotDivined - } + ) { + case cp: ChangedProvinceC => + inside(cp.changedUnaffiliatedHeroes.loneElement) { + case uh: UnaffiliatedHeroC => + uh.heroId shouldBe 151 + uh.unaffiliatedHeroType shouldBe Resident + uh.recruitmentInfo shouldBe RecruitmentInfo.NotDivined + } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommandTest.scala index d3afa87f7c..6b33f0e360 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AlmsCommandTest.scala @@ -18,15 +18,8 @@ import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.hero.Profession.{NoProfession, Paladin} import net.eagle0.eagle.model.state.province.{ProvinceOrderType, ProvinceT} import net.eagle0.eagle.model.state.province.concrete.ProvinceC -import net.eagle0.eagle.model.state.quest.concrete.{ - AlmsAcrossRealmQuest, - AlmsToProvinceQuest, - ImproveAgricultureQuest -} -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.quest.concrete.{AlmsAcrossRealmQuest, AlmsToProvinceQuest, ImproveAgricultureQuest} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.FactionId import org.scalatest.flatspec.AnyFlatSpec @@ -35,13 +28,9 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class AlmsCommandTest - extends AnyFlatSpec - with Matchers - with ProtoMatchers - with BeforeAndAfterEach { +class AlmsCommandTest extends AnyFlatSpec with Matchers with ProtoMatchers with BeforeAndAfterEach { - private val actionVigorCost = 15 + private val actionVigorCost = 15 override def beforeEach(): Unit = { MaxAlmsFood.setIntValue(1000) AlmsMaxCharismaXp.setIntValue(10) @@ -52,8 +41,8 @@ class AlmsCommandTest XpForStatBump.setIntValue(100) } - val fid: FactionId = 9 - private val actingProvince = ProvinceC( + val fid: FactionId = 9 + private val actingProvince = ProvinceC( id = 5, rulingFactionId = Some(fid), rulingHeroId = Some(12), @@ -90,18 +79,18 @@ class AlmsCommandTest ) ) ) - private val actingHero = + private val actingHero = HeroC(id = 13, factionId = Some(fid), profession = NoProfession) private val factionProvinces: Vector[ProvinceT] = Vector(actingProvince, anotherOwnedProvince) - private val availableHeroIds = Vector(12, 13) - private val foodAvailable = 2600 + private val availableHeroIds = Vector(12, 13) + private val foodAvailable = 2600 private val selectedFoodAmount = 1111 "make" should "throw if amount is negative" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy AlmsCommand.make( actingFactionId = fid, availableHeroIds = availableHeroIds, @@ -111,13 +100,12 @@ class AlmsCommandTest actingHero = actingHero, factionProvinces = factionProvinces ) - } ex.getMessage shouldBe "requirement failed: Gift amount must be > 0 (was -5)" } it should "throw if amount is greater than available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy AlmsCommand.make( actingFactionId = fid, availableHeroIds = availableHeroIds, @@ -127,7 +115,6 @@ class AlmsCommandTest actingHero = actingHero, factionProvinces = factionProvinces ) - } ex.getMessage shouldBe "requirement failed: Tried to give 2800 food but only 2600 available" } @@ -135,7 +122,7 @@ class AlmsCommandTest it should "throw if leader is not among available heroes" in { val badHero = HeroC(id = 14, factionId = Some(fid)) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy AlmsCommand.make( actingFactionId = fid, availableHeroIds = availableHeroIds, @@ -145,7 +132,6 @@ class AlmsCommandTest actingHero = badHero, factionProvinces = factionProvinces ) - } ex.getMessage shouldBe "requirement failed: Must select hero from Vector(12, 13) but chose 14" } @@ -234,9 +220,10 @@ class AlmsCommandTest .changedHeroes .head - inside(ch) { case ch: ChangedHeroC => - ch.heroId shouldBe 13 - ch.vigorChange shouldBe StatDelta(-actionVigorCost) + inside(ch) { + case ch: ChangedHeroC => + ch.heroId shouldBe 13 + ch.vigorChange shouldBe StatDelta(-actionVigorCost) } } @@ -255,14 +242,15 @@ class AlmsCommandTest .changedHeroes .head - inside(ch) { case ch: ChangedHeroC => - ch.heroId shouldBe 13 - ch.charismaXpDelta shouldBe Some(6) + inside(ch) { + case ch: ChangedHeroC => + ch.heroId shouldBe 13 + ch.charismaXpDelta shouldBe Some(6) } } it should "update the quest for anyone in the province with an AlmsToProvince quest" in { - val uh = actingProvince.unaffiliatedHeroes.head + val uh = actingProvince.unaffiliatedHeroes.head val provinceWithAlmsToProvinceQuest = actingProvince.copy( unaffiliatedHeroes = uh.withQuest( @@ -309,7 +297,7 @@ class AlmsCommandTest } it should "update the quest for anyone in the province with an AlmsAcrossRealm quest" in { - val uh = actingProvince.unaffiliatedHeroes.head + val uh = actingProvince.unaffiliatedHeroes.head val provinceWithAlmsAcrossRealmQuest = actingProvince.copy( unaffiliatedHeroes = uh.withQuest( @@ -329,8 +317,7 @@ class AlmsCommandTest selectedFoodAmount = selectedFoodAmount, actingProvince = provinceWithAlmsAcrossRealmQuest, actingHero = actingHero, - factionProvinces = - Vector(anotherOwnedProvince, provinceWithAlmsAcrossRealmQuest) + factionProvinces = Vector(anotherOwnedProvince, provinceWithAlmsAcrossRealmQuest) ) .immediateExecute .changedProvinces @@ -355,7 +342,7 @@ class AlmsCommandTest } it should "not update the quest for someone with an AlmsToProvince quest in another province" in { - val uh = anotherOwnedProvince.unaffiliatedHeroes.head + val uh = anotherOwnedProvince.unaffiliatedHeroes.head val anotherProvinceWithAlmsToProvinceQuest = anotherOwnedProvince.copy( unaffiliatedHeroes = uh.withQuest( @@ -376,8 +363,7 @@ class AlmsCommandTest selectedFoodAmount = selectedFoodAmount, actingProvince = actingProvince, actingHero = actingHero, - factionProvinces = - Vector(anotherProvinceWithAlmsToProvinceQuest, actingProvince) + factionProvinces = Vector(anotherProvinceWithAlmsToProvinceQuest, actingProvince) ) .immediateExecute .changedProvinces @@ -388,7 +374,7 @@ class AlmsCommandTest } it should "update the quest for someone with an AlmsAcrossRealm quest in another province" in { - val uh = anotherOwnedProvince.unaffiliatedHeroes.head + val uh = anotherOwnedProvince.unaffiliatedHeroes.head val anotherOwnedProvinceWithAlmsAcrossRealmQuest = anotherOwnedProvince.copy( unaffiliatedHeroes = uh.withQuest( @@ -408,8 +394,7 @@ class AlmsCommandTest selectedFoodAmount = selectedFoodAmount, actingProvince = actingProvince, actingHero = actingHero, - factionProvinces = - Vector(anotherOwnedProvinceWithAlmsAcrossRealmQuest, actingProvince) + factionProvinces = Vector(anotherOwnedProvinceWithAlmsAcrossRealmQuest, actingProvince) ) .immediateExecute .changedProvinces diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommandTest.scala index 15cfbdefb8..8c9fe7993b 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ApprehendOutlawCommandTest.scala @@ -1,20 +1,14 @@ package net.eagle0.eagle package library.actions.impl.command -import net.eagle0.eagle.library.settings.{ - ApprehendOutlawVigorCost, - FactionBiasFromImprisonment -} +import net.eagle0.eagle.library.settings.{ApprehendOutlawVigorCost, FactionBiasFromImprisonment} import net.eagle0.eagle.library.EagleClientException import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.OutlawApprehendedResultType import net.eagle0.eagle.model.state.province.concrete.ProvinceC -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -23,10 +17,7 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ApprehendOutlawCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ApprehendOutlawCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { ApprehendOutlawVigorCost.setDoubleValue(25) @@ -59,13 +50,13 @@ class ApprehendOutlawCommandTest ) private val availableHeroIds = Vector(3, 4, 5) - private val outlawHeroIds = Vector(10, 20) + private val outlawHeroIds = Vector(10, 20) private val heroIdToApprehend = 20 - private val actingHeroId = 3 + private val actingHeroId = 3 "make" should "throw if the selected actor was not in available" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy ApprehendOutlawCommand.make( actingFactionId = fid, availableHeroIds = availableHeroIds, @@ -74,12 +65,11 @@ class ApprehendOutlawCommandTest heroIdToApprehend = heroIdToApprehend, actingProvince = actingProvince ) - } ex.getMessage shouldBe "requirement failed: Selected hid 6 was not among Vector(3, 4, 5)" } it should "throw if the selected target was not among the outlaws" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy ApprehendOutlawCommand.make( actingFactionId = fid, availableHeroIds = availableHeroIds, @@ -88,7 +78,6 @@ class ApprehendOutlawCommandTest heroIdToApprehend = 30, actingProvince = actingProvince ) - } ex.getMessage shouldBe "requirement failed: Selected target hid 30 was not among Vector(10, 20)" } @@ -122,8 +111,9 @@ class ApprehendOutlawCommandTest ) .immediateExecute - inside(result.changedHeroes.head) { case ch: ChangedHeroC => - ch.vigorChange shouldBe StatDelta(-25) + inside(result.changedHeroes.head) { + case ch: ChangedHeroC => + ch.vigorChange shouldBe StatDelta(-25) } } @@ -139,8 +129,9 @@ class ApprehendOutlawCommandTest ) .immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.removedUnaffiliatedHeroIds shouldBe Vector(20) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.removedUnaffiliatedHeroIds shouldBe Vector(20) } } @@ -156,17 +147,18 @@ class ApprehendOutlawCommandTest ) .immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newUnaffiliatedHeroes.loneElement shouldBe - UnaffiliatedHeroC( - heroId = 20, - unaffiliatedHeroType = UnaffiliatedHeroType.Prisoner, - roundsInType = 0, - recruitmentAttempted = false, - factionBiases = Map(fid -> -100), - lastFactionId = Some(20), - recruitmentInfo = RecruitmentInfo.Prisoner - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newUnaffiliatedHeroes.loneElement shouldBe + UnaffiliatedHeroC( + heroId = 20, + unaffiliatedHeroType = UnaffiliatedHeroType.Prisoner, + roundsInType = 0, + recruitmentAttempted = false, + factionBiases = Map(fid -> -100), + lastFactionId = Some(20), + recruitmentInfo = RecruitmentInfo.Prisoner + ) } } @@ -183,10 +175,11 @@ class ApprehendOutlawCommandTest .immediateExecute forExactly(1, result.newNotifications) { (note: NotificationT) => - inside(note.details) { case oad: NotificationDetails.OutlawApprehended => - oad.factionId shouldBe fid - oad.provinceId shouldBe pid - oad.apprehendedHeroId shouldBe 20 + inside(note.details) { + case oad: NotificationDetails.OutlawApprehended => + oad.factionId shouldBe fid + oad.provinceId shouldBe pid + oad.apprehendedHeroId shouldBe 20 } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommandTest.scala index 9b747f2514..e4b7fe11d3 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ArmTroopsCommandTest.scala @@ -1,9 +1,6 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.library.actions.impl.command.ArmTroopsCommand.{ - ArmamentCost, - ArmedBattalion -} +import net.eagle0.eagle.library.actions.impl.command.ArmTroopsCommand.{ArmamentCost, ArmedBattalion} import net.eagle0.eagle.library.settings.PriceIndexShiftPerGold import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC @@ -13,27 +10,19 @@ import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.BattalionType import net.eagle0.eagle.model.state.BattalionTypeId -import net.eagle0.eagle.model.state.BattalionTypeId.{ - HeavyCavalry, - LightInfantry, - Longbowmen -} +import net.eagle0.eagle.model.state.BattalionTypeId.{HeavyCavalry, LightInfantry, Longbowmen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ArmTroopsCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val factionId = 4 +class ArmTroopsCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val factionId = 4 private val provinceId = 98 - override def beforeEach(): Unit = { + override def beforeEach(): Unit = PriceIndexShiftPerGold.setDoubleValue(0.0001) - } private val battalions = Vector( BattalionC(typeId = HeavyCavalry, size = 352, id = 23, armament = 0), @@ -115,7 +104,7 @@ class ArmTroopsCommandTest "a malformed make" should "throw if the selected battalions are not in the available battalions" in { val badBattalions = Vector(ArmedBattalion(id = 7, newArmament = 99)) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ArmTroopsCommand.make( actingFactionId = factionId, availableBattalionIds = availableBattalions, @@ -125,14 +114,13 @@ class ArmTroopsCommandTest battalionTypes = battalionTypes, armamentCosts = armamentCosts ) - } ex.getMessage shouldBe s"requirement failed: Selected battalions Vector(7) is not a subset of Vector(23, 99, 221)" } it should "throw if the province is not in travel state" in { val notTravelingProvince = province.withRulerIsTraveling(false) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ArmTroopsCommand.make( actingFactionId = factionId, availableBattalionIds = availableBattalions, @@ -142,7 +130,6 @@ class ArmTroopsCommandTest battalionTypes = battalionTypes, armamentCosts = armamentCosts ) - } ex.getMessage shouldBe s"requirement failed: Province $provinceId is not in travel state" } @@ -153,7 +140,7 @@ class ArmTroopsCommandTest ArmedBattalion(id = 23, newArmament = 99) ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ArmTroopsCommand.make( actingFactionId = factionId, availableBattalionIds = availableBattalions, @@ -163,7 +150,6 @@ class ArmTroopsCommandTest battalionTypes = battalionTypes, armamentCosts = armamentCosts ) - } ex.getMessage shouldBe s"requirement failed: Duplicate battalionIds in selected command" } @@ -198,8 +184,9 @@ class ArmTroopsCommandTest val result = command.immediateExecute - result.changedBattalions.collect { case ChangedBattalionC(to) => - to + result.changedBattalions.collect { + case ChangedBattalionC(to) => + to } should contain theSameElementsAs Seq( battalions.head.withArmament(100), battalions(1).withArmament(21), @@ -230,16 +217,17 @@ class ArmTroopsCommandTest val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(-expectedCost) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(-expectedCost) } } it should "spend gold based on the passed-in costs" in { val expectedCost = ( - 352 * (100 - 0) * 0.0234 + // heavy cavalry + 352 * (100 - 0) * 0.0234 + // heavy cavalry 220 * (21 - 20) * 0.0108 + // light infantry - 800 * (99 - 93) * 0.0151 // longbowmen + 800 * (99 - 93) * 0.0151 // longbowmen ).ceil.toInt val command = ArmTroopsCommand.make( @@ -267,8 +255,9 @@ class ArmTroopsCommandTest val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(-expectedCost) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(-expectedCost) } } @@ -295,8 +284,9 @@ class ArmTroopsCommandTest val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newPriceIndex shouldBe Some(1.0 + expectedCost * 0.0001) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newPriceIndex shouldBe Some(1.0 + expectedCost * 0.0001) } } @@ -327,8 +317,9 @@ class ArmTroopsCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.setRulerIsTraveling shouldBe empty + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.setRulerIsTraveling shouldBe empty } } @@ -343,9 +334,8 @@ class ArmTroopsCommandTest armamentCosts = armamentCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe s"requirement failed: Needs 1909 gold but there is only 500" } @@ -366,9 +356,8 @@ class ArmTroopsCommandTest armamentCosts = armamentCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: New armament must be higher" } @@ -377,16 +366,14 @@ class ArmTroopsCommandTest actingFactionId = factionId, availableBattalionIds = availableBattalions, armedBattalions = armedBattalionsForUpgradeAll, - actingProvince = - province.withInfrastructure(45).withInfrastructureDevastation(12), + actingProvince = province.withInfrastructure(45).withInfrastructureDevastation(12), existingBattalions = battalions, battalionTypes = battalionTypes, armamentCosts = armamentCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: Cannot raise beyond effective infrastructure of 33.0" } @@ -407,9 +394,8 @@ class ArmTroopsCommandTest armamentCosts = armamentCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: New armament must be higher" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommandTest.scala index 0df01e6910..fb8ab8c6f2 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/AttackDecisionCommandTest.scala @@ -13,22 +13,14 @@ import net.eagle0.eagle.library.settings.{ MinimumWisdomForStartFire } import net.eagle0.eagle.library.EagleClientException -import net.eagle0.eagle.model.action_result.changed_province.concrete.{ - ChangedProvinceC, - HostileArmyStatusChange -} +import net.eagle0.eagle.model.action_result.changed_province.concrete.{ChangedProvinceC, HostileArmyStatusChange} import net.eagle0.eagle.model.action_result.types.{ ArmyAdvancedResultType, ArmySafePassageGrantedResultType, ArmyWithdrewResultType, TributeDemandedResultType } -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - Attacking, - SafePassageGranted, - TributeDemanded, - Withdrawing -} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{Attacking, SafePassageGranted, TributeDemanded, Withdrawing} import net.eagle0.eagle.model.state.TributeAmount import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -36,12 +28,9 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class AttackDecisionCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val attackerFid: FactionId = 19 - private val defenderFid: FactionId = 25 +class AttackDecisionCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val attackerFid: FactionId = 19 + private val defenderFid: FactionId = 25 private val defenderPid: ProvinceId = 101 private val tributeAmount = TributeAmount(gold = 100, food = 200) @@ -78,7 +67,7 @@ class AttackDecisionCommandTest } it should "throw if the selected decision is not in the available list" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy AttackDecisionCommand .make( actingProvinceId = defenderPid, @@ -87,7 +76,6 @@ class AttackDecisionCommandTest selectedDecision = Advance, defendingFactionId = defenderFid ) - } ex.getMessage shouldBe "requirement failed: Selected decision Advance was not among Vector(DemandTribute(TributeAmount(100,200)))" } @@ -105,7 +93,7 @@ class AttackDecisionCommandTest result.actionResultType shouldBe ArmyAdvancedResultType } - it should "add an attacking army" in { + it should "add an attacking army" in inside( AttackDecisionCommand .make( @@ -118,13 +106,14 @@ class AttackDecisionCommandTest .immediateExecute .changedProvinces .loneElement - ) { case cp: ChangedProvinceC => - inside(cp.hostileArmyStatusChanges.loneElement) { case td => - td.factionId shouldBe attackerFid - td.newStatus shouldBe Attacking - } + ) { + case cp: ChangedProvinceC => + inside(cp.hostileArmyStatusChanges.loneElement) { + case td => + td.factionId shouldBe attackerFid + td.newStatus shouldBe Attacking + } } - } "demand tribute decision" should "set the result type to TRIBUTE_DEMANDED" in { val result = AttackDecisionCommand @@ -141,37 +130,33 @@ class AttackDecisionCommandTest } it should "throw if the tribute food exceeds available" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy AttackDecisionCommand .make( actingProvinceId = defenderPid, actingFactionId = attackerFid, availableDecisions = availableAttackDecisions, - selectedDecision = - DemandTribute(TributeAmount(gold = 0, food = 3000)), + selectedDecision = DemandTribute(TributeAmount(gold = 0, food = 3000)), defendingFactionId = defenderFid ) - } ex.getMessage shouldBe "requirement failed: Demanded food amount 3000 exceeds maximum 1000" } it should "throw if the tribute gold exceeds available" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy AttackDecisionCommand .make( actingProvinceId = defenderPid, actingFactionId = attackerFid, availableDecisions = availableAttackDecisions, - selectedDecision = - DemandTribute(TributeAmount(gold = 2500, food = 0)), + selectedDecision = DemandTribute(TributeAmount(gold = 2500, food = 0)), defendingFactionId = defenderFid ) - } ex.getMessage shouldBe "requirement failed: Demanded gold amount 2500 exceeds maximum 2000" } it should "throw if demanded gold is negative" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy AttackDecisionCommand .make( actingProvinceId = defenderPid, @@ -180,12 +165,11 @@ class AttackDecisionCommandTest selectedDecision = DemandTribute(TributeAmount(gold = -15, food = 0)), defendingFactionId = defenderFid ) - } ex.getMessage shouldBe "requirement failed: Tried to demand negative gold" } it should "throw if demanded food is negative" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy AttackDecisionCommand .make( actingProvinceId = defenderPid, @@ -194,12 +178,11 @@ class AttackDecisionCommandTest selectedDecision = DemandTribute(TributeAmount(gold = 0, food = -15)), defendingFactionId = defenderFid ) - } ex.getMessage shouldBe "requirement failed: Tried to demand negative food" } it should "throw if demanded food and gold are both zero" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy AttackDecisionCommand .make( actingProvinceId = defenderPid, @@ -208,12 +191,11 @@ class AttackDecisionCommandTest selectedDecision = DemandTribute(TributeAmount(gold = 0, food = 0)), defendingFactionId = defenderFid ) - } ex.getMessage shouldBe "requirement failed: Demanded gold and food cannot both be zero" } - it should "add a tribute demander" in { + it should "add a tribute demander" in inside( AttackDecisionCommand .make( @@ -226,16 +208,16 @@ class AttackDecisionCommandTest .immediateExecute .changedProvinces .head - ) { case cp: ChangedProvinceC => - inside(cp.hostileArmyStatusChanges.loneElement) { - case hasc: HostileArmyStatusChange => - hasc.factionId shouldBe attackerFid - hasc.newStatus shouldBe TributeDemanded( - TributeAmount(gold = 100, food = 200) - ) - } + ) { + case cp: ChangedProvinceC => + inside(cp.hostileArmyStatusChanges.loneElement) { + case hasc: HostileArmyStatusChange => + hasc.factionId shouldBe attackerFid + hasc.newStatus shouldBe TributeDemanded( + TributeAmount(gold = 100, food = 200) + ) + } } - } "withdraw decision" should "have result type ARMY_WITHDREW" in { val result = AttackDecisionCommand @@ -251,7 +233,7 @@ class AttackDecisionCommandTest result.actionResultType shouldBe ArmyWithdrewResultType } - it should "change the status to withdrawn" in { + it should "change the status to withdrawn" in inside( AttackDecisionCommand .make( @@ -264,15 +246,15 @@ class AttackDecisionCommandTest .immediateExecute .changedProvinces .head - ) { case cp: ChangedProvinceC => - inside(cp.hostileArmyStatusChanges.loneElement) { - case hasc: HostileArmyStatusChange => - hasc.factionId shouldBe attackerFid - hasc.newStatus shouldBe Withdrawing - } + ) { + case cp: ChangedProvinceC => + inside(cp.hostileArmyStatusChanges.loneElement) { + case hasc: HostileArmyStatusChange => + hasc.factionId shouldBe attackerFid + hasc.newStatus shouldBe Withdrawing + } } - } "safe passage decision" should "have result type ARMY_SAFE_PASSAGE_GRANTED" in { val result = AttackDecisionCommand @@ -288,7 +270,7 @@ class AttackDecisionCommandTest result.actionResultType shouldBe ArmySafePassageGrantedResultType } - it should "change the status to safe passage granted" in { + it should "change the status to safe passage granted" in inside( AttackDecisionCommand .make( @@ -301,14 +283,12 @@ class AttackDecisionCommandTest .immediateExecute .changedProvinces .head - ) { case cp: ChangedProvinceC => - inside(cp.hostileArmyStatusChanges.loneElement) { - case hasc: HostileArmyStatusChange => - hasc.factionId shouldBe attackerFid - hasc.newStatus shouldBe SafePassageGranted(destinationProvinceId = - 102 - ) - } + ) { + case cp: ChangedProvinceC => + inside(cp.hostileArmyStatusChanges.loneElement) { + case hasc: HostileArmyStatusChange => + hasc.factionId shouldBe attackerFid + hasc.newStatus shouldBe SafePassageGranted(destinationProvinceId = 102) + } } - } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommandTest.scala index 445bc185a0..7b248f1adf 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ControlWeatherCommandTest.scala @@ -30,16 +30,13 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ControlWeatherCommandTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class ControlWeatherCommandTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { behavior of "ControlWeatherCommandTest" private val wisdomXpDelta: Int = 25 - private val vigorDelta: Int = -40 - private val durationMonths = 5 + private val vigorDelta: Int = -40 + private val durationMonths = 5 override def beforeEach(): Unit = { ControlWeatherVigorDelta.setDoubleValue(vigorDelta) @@ -48,10 +45,10 @@ class ControlWeatherCommandTest ControlWeatherDroughtDurationMonths.setIntValue(durationMonths) } - private val actingPid = 17 - private val actingFid = 2 + private val actingPid = 17 + private val actingFid = 2 private val availableHids = Vector(10, 20, 30) - private val options = Vector( + private val options = Vector( ControlWeatherOption( targetedProvinceId = 17, controlWeatherTypes = Vector( @@ -75,11 +72,11 @@ class ControlWeatherCommandTest ) ) - private val actingHid: HeroId = 10 + private val actingHid: HeroId = 10 private val targetedPid: ProvinceId = 19 "make" should "throw if the hero was not among options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ControlWeatherCommand.make( actingFactionId = actingFid, actingHeroId = 11, @@ -89,12 +86,11 @@ class ControlWeatherCommandTest controlWeatherType = StartBlizzard, options = options ) - } ex.getMessage shouldBe "requirement failed: Must select hero from Vector(10, 20, 30) but chose 11" } it should "throw if the target province was not among options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ControlWeatherCommand.make( actingFactionId = actingFid, actingHeroId = actingHid, @@ -104,12 +100,11 @@ class ControlWeatherCommandTest controlWeatherType = StartBlizzard, options = options ) - } ex.getMessage shouldBe "requirement failed: Selected pid 6 was not among Vector(17, 4, 19)" } it should "throw if the selected type was not among options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ControlWeatherCommand.make( actingFactionId = actingFid, actingHeroId = actingHid, @@ -119,7 +114,6 @@ class ControlWeatherCommandTest controlWeatherType = EndBlizzard, options = options ) - } ex.getMessage shouldBe "requirement failed: EndBlizzard was not an option for pid 19" } @@ -155,9 +149,10 @@ class ControlWeatherCommandTest ) .immediateExecute - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe actingHid - ch.wisdomXpDelta shouldBe Some(wisdomXpDelta) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe actingHid + ch.wisdomXpDelta shouldBe Some(wisdomXpDelta) } } @@ -174,9 +169,10 @@ class ControlWeatherCommandTest ) .immediateExecute - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe actingHid - ch.vigorChange shouldBe StatDelta(vigorDelta) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe actingHid + ch.vigorChange shouldBe StatDelta(vigorDelta) } } @@ -209,11 +205,12 @@ class ControlWeatherCommandTest ) .immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 4 - cp.newDeferredChange shouldBe Some( - BlizzardEnded(responsibleFaction = actingFid) - ) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 4 + cp.newDeferredChange shouldBe Some( + BlizzardEnded(responsibleFaction = actingFid) + ) } } @@ -230,14 +227,15 @@ class ControlWeatherCommandTest ) .immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe targetedPid - cp.newDeferredChange shouldBe Some( - BlizzardStarted( - responsibleFaction = actingFid, - durationMonths = durationMonths + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe targetedPid + cp.newDeferredChange shouldBe Some( + BlizzardStarted( + responsibleFaction = actingFid, + durationMonths = durationMonths + ) ) - ) } } @@ -254,11 +252,12 @@ class ControlWeatherCommandTest ) .immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.newDeferredChange shouldBe Some( - DroughtEnded(responsibleFaction = actingFid) - ) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.newDeferredChange shouldBe Some( + DroughtEnded(responsibleFaction = actingFid) + ) } } @@ -275,14 +274,15 @@ class ControlWeatherCommandTest ) .immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 4 - cp.newDeferredChange shouldBe Some( - DroughtStarted( - responsibleFaction = actingFid, - durationMonths = durationMonths + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 4 + cp.newDeferredChange shouldBe Some( + DroughtStarted( + responsibleFaction = actingFid, + durationMonths = durationMonths + ) ) - ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DeclineQuestCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DeclineQuestCommandTest.scala index e7ffd036a2..6c70cd4c62 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DeclineQuestCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DeclineQuestCommandTest.scala @@ -18,11 +18,7 @@ import net.eagle0.eagle.model.state.hero.QuestFailedBackstoryEvent import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.quest.concrete.ImproveAgricultureQuest import net.eagle0.eagle.model.state.quest.QuestT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.views.hero_view.HeroView import org.scalatest.flatspec.AnyFlatSpec @@ -33,15 +29,14 @@ import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class DeclineQuestCommandTest extends AnyFlatSpec { - private val actingFid = 13 - private val provinceId = 7 - private val currentDate = Date(year = 2024, month = Date.Month.June) - private val currentRoundId = 42 - private val previousBackstoryTextIdLookup: HeroId => String = hid => - s"backstory-$hid" + private val actingFid = 13 + private val provinceId = 7 + private val currentDate = Date(year = 2024, month = Date.Month.June) + private val currentRoundId = 42 + private val previousBackstoryTextIdLookup: HeroId => String = hid => s"backstory-$hid" "make" should "throw an exception if the selected hero is not an option" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy DeclineQuestCommand.make( actingFactionId = actingFid, province = ProvinceC(id = provinceId), @@ -52,14 +47,13 @@ class DeclineQuestCommandTest extends AnyFlatSpec { declinableHeroes = Vector(27), previousBackstoryTextIdLookup = previousBackstoryTextIdLookup ) - } ex.getMessage shouldBe "requirement failed: Selected hero 8 was not an option" } behavior of "immediateExecute" - private val questDetailsProto = ImproveAgricultureQuestProto( + private val questDetailsProto = ImproveAgricultureQuestProto( provinceId = provinceId, desiredValue = 72 ) @@ -68,20 +62,20 @@ class DeclineQuestCommandTest extends AnyFlatSpec { componentsFulfilled = 0, details = questDetailsProto ) - private val quest = ImproveAgricultureQuest( + private val quest = ImproveAgricultureQuest( provinceId = provinceId, desiredValue = 72 ) - private val uh: UnaffiliatedHeroT = UnaffiliatedHeroC( + private val uh: UnaffiliatedHeroT = UnaffiliatedHeroC( unaffiliatedHeroType = UnaffiliatedHeroType.Resident, heroId = 8, recruitmentInfo = RecruitmentInfo.HasQuest(quest) ) - private val euh = ExpandedUnaffiliatedHero( + private val euh = ExpandedUnaffiliatedHero( hero = Some(HeroView(id = 8)), quest = Some(questProto) ) - private val province = ProvinceC( + private val province = ProvinceC( id = provinceId, unaffiliatedHeroes = Vector(uh), rulingFactionId = Some(actingFid) @@ -98,7 +92,7 @@ class DeclineQuestCommandTest extends AnyFlatSpec { declinableHeroes = Vector(8), previousBackstoryTextIdLookup = previousBackstoryTextIdLookup ) - val result = command.immediateExecute + val result = command.immediateExecute result.actionResultType shouldBe QuestDeclinedResultType } @@ -136,7 +130,7 @@ class DeclineQuestCommandTest extends AnyFlatSpec { declinableHeroes = Vector(8), previousBackstoryTextIdLookup = previousBackstoryTextIdLookup ) - val result = command.immediateExecute + val result = command.immediateExecute forExactly(1, result.newNotifications) { (note: NotificationT) => note.targetFactionIds shouldBe Vector(actingFid) @@ -166,7 +160,7 @@ class DeclineQuestCommandTest extends AnyFlatSpec { declinableHeroes = Vector(8), previousBackstoryTextIdLookup = previousBackstoryTextIdLookup ) - val result = command.immediateExecute + val result = command.immediateExecute forExactly(1, result.newGeneratedTextRequests) { case QuestFailedMessage( @@ -200,7 +194,7 @@ class DeclineQuestCommandTest extends AnyFlatSpec { declinableHeroes = Vector(8), previousBackstoryTextIdLookup = previousBackstoryTextIdLookup ) - val result = command.immediateExecute + val result = command.immediateExecute forExactly(1, result.changedHeroes) { case ch: ChangedHeroC if ch.heroId == 8 => diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DefendCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DefendCommandTest.scala index 8c220a4a0f..aee49d5dde 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DefendCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DefendCommandTest.scala @@ -7,13 +7,7 @@ import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedPro import net.eagle0.eagle.model.action_result.concrete.ActionResultC import net.eagle0.eagle.model.action_result.types.DefendResultType import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.{ - Army, - CombatUnit, - HostileArmyGroup, - MovingArmy, - Supplies -} +import net.eagle0.eagle.model.state.{Army, CombatUnit, HostileArmyGroup, MovingArmy, Supplies} import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.HostileArmyGroupStatus.Attacking import org.scalatest.flatspec.AnyFlatSpec @@ -22,10 +16,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.OptionValues.* -class DefendCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class DefendCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val fleeProvinceId = 19 @@ -67,12 +58,11 @@ class DefendCommandTest private val defendingProvince = ProvinceC(id = 7, hostileArmies = Vector(attackers)) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MaxCombatUnitCountPerSide.setIntValue(10) - } "make" should "throw if a flee province is selected when none were available" in { - val exception = the[EagleCommandException] thrownBy { + val exception = the[EagleCommandException] thrownBy DefendCommand.make( actingFactionId = 1, defendingUnits = Vector(), @@ -80,14 +70,13 @@ class DefendCommandTest availableFleeProvinceIds = Vector(), actingProvince = defendingProvince ) - } exception.getMessage should be( "requirement failed: Flee province 19 was selected, but none were available" ) } it should "throw if flee provinces are available and none is selected" in { - val exception = the[EagleCommandException] thrownBy { + val exception = the[EagleCommandException] thrownBy DefendCommand.make( actingFactionId = 1, defendingUnits = Vector(), @@ -95,14 +84,13 @@ class DefendCommandTest availableFleeProvinceIds = Vector(5, 6), actingProvince = defendingProvince ) - } exception.getMessage should be( "requirement failed: Flee provinces Vector(5, 6) are available, but none was selected" ) } it should "throw if the selected flee province is not among the available ones" in { - val exception = the[EagleCommandException] thrownBy { + val exception = the[EagleCommandException] thrownBy DefendCommand.make( actingFactionId = 1, defendingUnits = Vector(), @@ -110,7 +98,6 @@ class DefendCommandTest availableFleeProvinceIds = Vector(5, 6), actingProvince = defendingProvince ) - } exception.getMessage should be( "requirement failed: Selected flee province 19 is not in available Vector(5, 6)" ) @@ -128,9 +115,8 @@ class DefendCommandTest actingProvince = defendingProvinceWithoutHostileArmies ) - val exception = the[EagleCommandException] thrownBy { + val exception = the[EagleCommandException] thrownBy command.immediateExecute - } exception.getMessage should be( "requirement failed: There are no attacking armies to defend against in province 7" ) @@ -160,22 +146,24 @@ class DefendCommandTest ) val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actingFactionId should contain(4) - ar.actionResultType shouldBe DefendResultType - ar.provinceId should contain(7) - ar.provinceIdActed should contain(7) + inside(result) { + case ar: ActionResultC => + ar.actingFactionId should contain(4) + ar.actionResultType shouldBe DefendResultType + ar.provinceId should contain(7) + ar.provinceIdActed should contain(7) - ar.changedProvinces should have size 1 - inside(ar.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 7 + ar.changedProvinces should have size 1 + inside(ar.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 7 - cp.newDefendingArmy shouldBe defined - val defendingArmy = cp.newDefendingArmy.value - defendingArmy.factionId shouldBe 4 - defendingArmy.units shouldBe defenders - defendingArmy.fleeProvinceId shouldBe Some(fleeProvinceId) - } + cp.newDefendingArmy shouldBe defined + val defendingArmy = cp.newDefendingArmy.value + defendingArmy.factionId shouldBe 4 + defendingArmy.units shouldBe defenders + defendingArmy.fleeProvinceId shouldBe Some(fleeProvinceId) + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommandTest.scala index c4a1d62518..fc81396446 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DiplomacyCommandTest.scala @@ -1,18 +1,9 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.library.{EagleClientException, EagleCommandException} -import net.eagle0.eagle.library.settings.{ - ActionVigorCost, - TruceMonths, - VigorToConstitutionXpMultiplier, - XpForStatBump -} +import net.eagle0.eagle.library.settings.{ActionVigorCost, TruceMonths, VigorToConstitutionXpMultiplier, XpForStatBump} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedFactionC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedFactionC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.concrete.ChangedFactionC.{ OutgoingRansomOfferFactionId, OutgoingTruceOfferFactionId @@ -26,13 +17,7 @@ import net.eagle0.eagle.model.action_result.types.{ } import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.date.Date.Month -import net.eagle0.eagle.model.state.diplomacy_offer.{ - AllianceOffer, - BreakAlliance, - Invitation, - RansomOffer, - TruceOffer -} +import net.eagle0.eagle.model.state.diplomacy_offer.{AllianceOffer, BreakAlliance, Invitation, RansomOffer, TruceOffer} import net.eagle0.eagle.model.state.diplomacy_offer.status.Unresolved import net.eagle0.eagle.model.state.diplomacy_offer.RansomOfferDetails.{ HostageOfferedInExchange, @@ -47,10 +32,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class DiplomacyCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class DiplomacyCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { ActionVigorCost.setIntValue(20) @@ -59,16 +41,16 @@ class DiplomacyCommandTest XpForStatBump.setIntValue(100) } - private val actingFid = 3 + private val actingFid = 3 private val actingProvince = ProvinceC( id = 19, rulingFactionId = Some(actingFid), gold = 1000 ) - private val currentDate = Date(year = 2001, month = Month.May) + private val currentDate = Date(year = 2001, month = Month.May) private val currentRoundId = 57 - private val gameId = 0xcafefeed + private val gameId = 0xcafefeed "commandType" should "be DIPLOMACY_COMMAND" in {} @@ -76,10 +58,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.TruceOption(targetFactionId = 4, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.TruceOption(targetFactionId = 4, goldCost = 0) - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 5, // Not in available heroes @@ -91,7 +73,6 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage shouldBe "requirement failed: Sent hero 5 was not in available options Vector(4, 6)" } @@ -99,12 +80,12 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.TruceOption(targetFactionId = 4, goldCost = 0)) - val selectedOption = DiplomacyOption.TruceOption( + val selectedOption = DiplomacyOption.TruceOption( targetFactionId = 5, goldCost = 0 ) // Different target - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, @@ -116,7 +97,6 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage should include("Selected option") ex.getMessage should include("was not in available options") } @@ -125,10 +105,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.TruceOption(targetFactionId = 4, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.TruceOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -148,10 +128,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.TruceOption(targetFactionId = 4, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.TruceOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -164,9 +144,10 @@ class DiplomacyCommandTest ) val result = cmd.immediateExecute - inside(result.changedHeroes.head) { case hero: ChangedHeroC => - hero.heroId shouldBe 4 - hero.vigorChange shouldBe StatDelta(-20) + inside(result.changedHeroes.head) { + case hero: ChangedHeroC => + hero.heroId shouldBe 4 + hero.vigorChange shouldBe StatDelta(-20) } } @@ -174,10 +155,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.TruceOption(targetFactionId = 5, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.TruceOption(targetFactionId = 5, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -209,10 +190,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.TruceOption(targetFactionId = 5, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.TruceOption(targetFactionId = 5, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -238,10 +219,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.InvitationOption(targetFactionId = 4, goldCost = 0) ) - val selectedOption = + val selectedOption = DiplomacyOption.InvitationOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -262,10 +243,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.InvitationOption(targetFactionId = 4, goldCost = 0) ) - val selectedOption = + val selectedOption = DiplomacyOption.InvitationOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -278,9 +259,10 @@ class DiplomacyCommandTest ) val result = cmd.immediateExecute - inside(result.changedHeroes.head) { case hero: ChangedHeroC => - hero.heroId shouldBe 4 - hero.vigorChange shouldBe StatDelta(-20) + inside(result.changedHeroes.head) { + case hero: ChangedHeroC => + hero.heroId shouldBe 4 + hero.vigorChange shouldBe StatDelta(-20) } } @@ -289,10 +271,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.InvitationOption(targetFactionId = 4, goldCost = 150) ) - val selectedOption = + val selectedOption = DiplomacyOption.InvitationOption(targetFactionId = 4, goldCost = 150) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -305,10 +287,11 @@ class DiplomacyCommandTest ) val result = cmd.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.removedRulingFactionHeroIds shouldBe Vector(4) - cp.goldDelta shouldBe Some(-150) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.removedRulingFactionHeroIds shouldBe Vector(4) + cp.goldDelta shouldBe Some(-150) } } @@ -317,10 +300,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.InvitationOption(targetFactionId = 5, goldCost = 0) ) - val selectedOption = + val selectedOption = DiplomacyOption.InvitationOption(targetFactionId = 5, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -351,10 +334,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.AllianceOption(targetFactionId = 4, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.AllianceOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -374,10 +357,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.AllianceOption(targetFactionId = 4, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.AllianceOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -390,9 +373,10 @@ class DiplomacyCommandTest ) val result = cmd.immediateExecute - inside(result.changedHeroes.head) { case hero: ChangedHeroC => - hero.heroId shouldBe 4 - hero.vigorChange shouldBe StatDelta(-20) + inside(result.changedHeroes.head) { + case hero: ChangedHeroC => + hero.heroId shouldBe 4 + hero.vigorChange shouldBe StatDelta(-20) } } @@ -401,10 +385,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.AllianceOption(targetFactionId = 4, goldCost = 150) ) - val selectedOption = + val selectedOption = DiplomacyOption.AllianceOption(targetFactionId = 4, goldCost = 150) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -417,10 +401,11 @@ class DiplomacyCommandTest ) val result = cmd.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.removedRulingFactionHeroIds shouldBe Vector(4) - cp.goldDelta shouldBe Some(-150) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.removedRulingFactionHeroIds shouldBe Vector(4) + cp.goldDelta shouldBe Some(-150) } } @@ -428,10 +413,10 @@ class DiplomacyCommandTest val availableHeroIds = Vector(4, 6) val availableOptions = Vector(DiplomacyOption.AllianceOption(targetFactionId = 5, goldCost = 0)) - val selectedOption = + val selectedOption = DiplomacyOption.AllianceOption(targetFactionId = 5, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -463,10 +448,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.BreakAllianceOption(targetFactionId = 4, goldCost = 0) ) - val selectedOption = + val selectedOption = DiplomacyOption.BreakAllianceOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -487,10 +472,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.BreakAllianceOption(targetFactionId = 4, goldCost = 0) ) - val selectedOption = + val selectedOption = DiplomacyOption.BreakAllianceOption(targetFactionId = 4, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -503,9 +488,10 @@ class DiplomacyCommandTest ) val result = cmd.immediateExecute - inside(result.changedHeroes.head) { case hero: ChangedHeroC => - hero.heroId shouldBe 4 - hero.vigorChange shouldBe StatDelta(-20) + inside(result.changedHeroes.head) { + case hero: ChangedHeroC => + hero.heroId shouldBe 4 + hero.vigorChange shouldBe StatDelta(-20) } } @@ -514,10 +500,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.BreakAllianceOption(targetFactionId = 4, goldCost = 150) ) - val selectedOption = + val selectedOption = DiplomacyOption.BreakAllianceOption(targetFactionId = 4, goldCost = 150) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -530,10 +516,11 @@ class DiplomacyCommandTest ) val result = cmd.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.removedRulingFactionHeroIds shouldBe Vector(4) - cp.goldDelta shouldBe Some(-150) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.removedRulingFactionHeroIds shouldBe Vector(4) + cp.goldDelta shouldBe Some(-150) } } @@ -542,10 +529,10 @@ class DiplomacyCommandTest val availableOptions = Vector( DiplomacyOption.BreakAllianceOption(targetFactionId = 5, goldCost = 0) ) - val selectedOption = + val selectedOption = DiplomacyOption.BreakAllianceOption(targetFactionId = 5, goldCost = 0) - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -573,12 +560,12 @@ class DiplomacyCommandTest } "RansomOfferCommand execute" should "have type RANSOM_STARTED" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -587,9 +574,9 @@ class DiplomacyCommandTest goldOffered = 100 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -606,12 +593,12 @@ class DiplomacyCommandTest } it should "not tire the actor (ransom commands don't use generic diplomacy result)" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -620,9 +607,9 @@ class DiplomacyCommandTest goldOffered = 100 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -640,12 +627,12 @@ class DiplomacyCommandTest } it should "not change provinces directly (ransom commands don't use generic diplomacy result)" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -654,9 +641,9 @@ class DiplomacyCommandTest goldOffered = 200 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -674,25 +661,25 @@ class DiplomacyCommandTest } it should "add the incoming ransom offer to the target faction" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val prisonersOffered = Vector( + val prisonersOffered = Vector( PrisonerOfferedInExchange( heroId = 15, factionIdForPrisoner = 3, provinceIdWithHero = 19 ) ) - val hostagesOffered = Vector( + val hostagesOffered = Vector( HostageOfferedInExchange( heroId = 20, provinceIdWithHero = 19 ) ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -701,9 +688,9 @@ class DiplomacyCommandTest goldOffered = 300 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val cmd = DiplomacyCommand.make( + val cmd = DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, availableHeroIds = availableHeroIds, @@ -719,38 +706,40 @@ class DiplomacyCommandTest // Check target faction receives the ransom offer val targetFactionChanges = result.changedFactions.find(_.factionId == 5) targetFactionChanges shouldBe defined - inside(targetFactionChanges.get) { case cf: ChangedFactionC => - inside(cf.newIncomingDiplomacyOffers.loneElement) { - case offer: RansomOffer => - offer.originatingFactionId shouldBe 3 - offer.targetFactionId shouldBe 5 - offer.messengerHeroId shouldBe 4 - offer.messengerOriginProvinceId shouldBe 19 - offer.status shouldBe Unresolved - offer.offerTextId shouldBe "round 57 ransom offer / province 19 / faction 3 / targetFaction 5" - offer.prisonerToBeRansomed shouldBe prisonerToBeRansomed - offer.prisonersOffered shouldBe prisonersOffered - offer.hostagesOffered shouldBe hostagesOffered - offer.goldOffered shouldBe 300 - } + inside(targetFactionChanges.get) { + case cf: ChangedFactionC => + inside(cf.newIncomingDiplomacyOffers.loneElement) { + case offer: RansomOffer => + offer.originatingFactionId shouldBe 3 + offer.targetFactionId shouldBe 5 + offer.messengerHeroId shouldBe 4 + offer.messengerOriginProvinceId shouldBe 19 + offer.status shouldBe Unresolved + offer.offerTextId shouldBe "round 57 ransom offer / province 19 / faction 3 / targetFaction 5" + offer.prisonerToBeRansomed shouldBe prisonerToBeRansomed + offer.prisonersOffered shouldBe prisonersOffered + offer.hostagesOffered shouldBe hostagesOffered + offer.goldOffered shouldBe 300 + } } // Check originating faction tracks the outgoing ransom offer val originatingFactionChanges = result.changedFactions.find(_.factionId == 3) originatingFactionChanges shouldBe defined - inside(originatingFactionChanges.get) { case cf: ChangedFactionC => - cf.newOutgoingRansomOfferFactionIds.loneElement.fid shouldBe 5 + inside(originatingFactionChanges.get) { + case cf: ChangedFactionC => + cf.newOutgoingRansomOfferFactionIds.loneElement.fid shouldBe 5 } } it should "validate ransom offer requirements" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 0, // Invalid hero ID provinceIdForPrisoner = 25 ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -759,9 +748,9 @@ class DiplomacyCommandTest goldOffered = 100 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, @@ -773,17 +762,16 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage should include("Invalid prisoner hero ID: 0") } it should "validate prisoner province ID" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 0 // Invalid province ID ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -792,9 +780,9 @@ class DiplomacyCommandTest goldOffered = 100 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, @@ -806,24 +794,23 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage should include("Invalid prisoner province ID: 0") } it should "validate offered prisoners have valid IDs" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val prisonersOffered = Vector( + val prisonersOffered = Vector( PrisonerOfferedInExchange( heroId = 0, // Invalid hero ID factionIdForPrisoner = 3, provinceIdWithHero = 19 ) ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -832,9 +819,9 @@ class DiplomacyCommandTest goldOffered = 100 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, @@ -846,23 +833,22 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage should include("Invalid offered prisoner hero ID: 0") } it should "validate offered hostages have valid IDs" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val hostagesOffered = Vector( + val hostagesOffered = Vector( HostageOfferedInExchange( heroId = 0, // Invalid hero ID provinceIdWithHero = 19 ) ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -871,9 +857,9 @@ class DiplomacyCommandTest goldOffered = 100 ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, @@ -885,19 +871,18 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage should include("Invalid offered hostage hero ID: 0") } it should "validate sufficient gold for ransom offer" in { - val limitedGoldProvince = + val limitedGoldProvince = actingProvince.copy(gold = 50) // Less than what we're offering - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -906,9 +891,9 @@ class DiplomacyCommandTest goldOffered = 100 // More than available ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, @@ -920,17 +905,16 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage should include("Not enough gold to offer 100 (have 50)") } it should "require at least one form of payment (gold, prisoners, or hostages)" in { - val availableHeroIds = Vector(4, 6) + val availableHeroIds = Vector(4, 6) val prisonerToBeRansomed = PrisonerToBeRansomed( prisonerHeroId = 10, provinceIdForPrisoner = 25 ) - val availableOptions = Vector( + val availableOptions = Vector( DiplomacyOption.RansomOfferOption( targetFactionId = 5, prisonerToBeRansomed = prisonerToBeRansomed, @@ -939,9 +923,9 @@ class DiplomacyCommandTest goldOffered = 0 // No payment offered ) ) - val selectedOption = availableOptions.head + val selectedOption = availableOptions.head - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy DiplomacyCommand.make( actingFactionId = actingFid, sentHeroId = 4, @@ -953,7 +937,6 @@ class DiplomacyCommandTest currentRoundId = currentRoundId, currentDate = currentDate ) - } ex.getMessage should include("Must select gold, hostages, or prisoners") } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommandTest.scala index 93295ee70f..73dd6372d2 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/DivineCommandTest.scala @@ -41,10 +41,7 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class DivineCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class DivineCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { GoldCostForDivine.setIntValue(100) @@ -67,7 +64,7 @@ class DivineCommandTest PriceIndexShiftPerGold.setDoubleValue(0.0001) } - private val gameId = 0xfeedface + private val gameId = 0xfeedface private val currentRoundId = 387 private val actingFactionId: FactionId = 17 @@ -105,7 +102,7 @@ class DivineCommandTest private val functionalRandom = SeededRandom(0xcafe) "make" should "throw if a heroId is duplicated" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy DivineCommand.make( actingFactionId = actingFactionId, actingProvinceId = provinceId, @@ -117,12 +114,11 @@ class DivineCommandTest factions = factions, battalions = Vector() ) - } ex.getMessage shouldBe "requirement failed: Duplicate heroIds found in Vector(12, 13, 12)" } it should "throw if there is not enough gold" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy DivineCommand.make( actingFactionId = actingFactionId, actingProvinceId = provinceId, @@ -134,12 +130,11 @@ class DivineCommandTest factions = factions, battalions = Vector() ) - } ex.getMessage shouldBe "requirement failed: Insufficient gold to divine 2 heroes" } it should "throw if a selected hero was not in the available list" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy DivineCommand.make( actingFactionId = actingFactionId, actingProvinceId = provinceId, @@ -151,7 +146,6 @@ class DivineCommandTest factions = factions, battalions = Vector() ) - } ex.getMessage shouldBe "requirement failed: Selected heroes Vector(12, 14) was not a subset of Vector(12, 13, 15)" } @@ -201,17 +195,15 @@ class DivineCommandTest currentRoundId = currentRoundId, allProvinces = Vector( province.copy( - unaffiliatedHeroes = - province.unaffiliatedHeroes.filterNot(_.heroId == 13) + unaffiliatedHeroes = province.unaffiliatedHeroes.filterNot(_.heroId == 13) ) ), factions = factions, battalions = Vector() ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy command.immediateExecute(functionalRandom = functionalRandom) - } ex.getMessage shouldBe "requirement failed: No unaffiliated hero with id 13 was present in province 93" } @@ -232,21 +224,22 @@ class DivineCommandTest .immediateExecute(functionalRandom = functionalRandom) .newValue - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - val changedUHs = cp.changedUnaffiliatedHeroes - changedUHs should have size 2 - forExactly(1, changedUHs) { uh => - uh.heroId shouldBe 12 - uh.recruitmentInfo should matchPattern { - case RecruitmentInfo.HasQuest(_) => + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + val changedUHs = cp.changedUnaffiliatedHeroes + changedUHs should have size 2 + forExactly(1, changedUHs) { uh => + uh.heroId shouldBe 12 + uh.recruitmentInfo should matchPattern { + case RecruitmentInfo.HasQuest(_) => + } } - } - forExactly(1, changedUHs) { uh => - uh.heroId shouldBe 15 - uh.recruitmentInfo should matchPattern { - case RecruitmentInfo.HasQuest(_) => + forExactly(1, changedUHs) { uh => + uh.heroId shouldBe 15 + uh.recruitmentInfo should matchPattern { + case RecruitmentInfo.HasQuest(_) => + } } - } } } @@ -266,8 +259,9 @@ class DivineCommandTest .immediateExecute(functionalRandom = functionalRandom) .newValue - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(-200) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(-200) } } @@ -287,8 +281,9 @@ class DivineCommandTest .immediateExecute(functionalRandom = functionalRandom) .newValue - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(-180) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(-180) } } @@ -308,8 +303,9 @@ class DivineCommandTest .immediateExecute(functionalRandom = functionalRandom) .newValue - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newPriceIndex shouldBe Some(1.02) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newPriceIndex shouldBe Some(1.02) } // 200 gold spent } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommandTest.scala index a5e94e6f74..0dbfa509e4 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ExileVassalCommandTest.scala @@ -4,10 +4,7 @@ package library.actions.impl.command import net.eagle0.eagle.library.settings.ExiledHeroFactionBias import net.eagle0.eagle.library.EagleClientException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedHeroC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.ExileVassalMessage import net.eagle0.eagle.model.action_result.types.VassalExiledResultType @@ -19,10 +16,7 @@ import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.hero.ExiledBackstoryEvent import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.quest.concrete.DismissSpecificVassalQuest -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -30,18 +24,14 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ExileVassalCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - override def beforeEach(): Unit = { +class ExileVassalCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + override def beforeEach(): Unit = ExiledHeroFactionBias.setDoubleValue(-500) - } - private val fid: FactionId = 12 - private val exiledHid: HeroId = 9 + private val fid: FactionId = 12 + private val exiledHid: HeroId = 9 private val notExiledHid: HeroId = 99 - private val pid: ProvinceId = 22 - private val currentDate = Date(2021, Date.Month.January) + private val pid: ProvinceId = 22 + private val currentDate = Date(2021, Date.Month.January) private val exiledHero = HeroC( id = exiledHid, @@ -86,14 +76,14 @@ class ExileVassalCommandTest ) private val currentRoundId: RoundId = 4 - private val gameId: GameId = 0xcafebabe + private val gameId: GameId = 0xcafebabe private val exilableHeroIds: Vector[HeroId] = Vector(exiledHid, notExiledHid) "commandType" should "be EXILE_VASSAL_COMMAND" in {} "make" should "throw if the selected hero was not in the available list" in { - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy ExileVassalCommand .make( actingFactionId = fid, @@ -104,7 +94,6 @@ class ExileVassalCommandTest currentDate = currentDate, actingProvince = province ) - } ex.getMessage shouldBe "requirement failed: Selected hid 19 was not among Vector(9, 99)" } @@ -141,9 +130,10 @@ class ExileVassalCommandTest ) .immediateExecute - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe exiledHid - ch.clearFactionId shouldBe true + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe exiledHid + ch.clearFactionId shouldBe true } } @@ -160,13 +150,14 @@ class ExileVassalCommandTest ) .immediateExecute - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe exiledHid - ch.newEventsForHeroBackstory.loneElement shouldBe ExiledBackstoryEvent( - date = Date(year = 2021, month = Date.Month.January), - exiledByFactionId = fid, - exiledFromProvinceId = pid - ) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe exiledHid + ch.newEventsForHeroBackstory.loneElement shouldBe ExiledBackstoryEvent( + date = Date(year = 2021, month = Date.Month.January), + exiledByFactionId = fid, + exiledFromProvinceId = pid + ) } } @@ -183,8 +174,9 @@ class ExileVassalCommandTest ) .immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.removedRulingFactionHeroIds shouldBe Vector(exiledHid) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.removedRulingFactionHeroIds shouldBe Vector(exiledHid) } } @@ -201,14 +193,15 @@ class ExileVassalCommandTest ) .immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newUnaffiliatedHeroes.loneElement shouldBe - UnaffiliatedHeroC( - heroId = exiledHid, - unaffiliatedHeroType = UnaffiliatedHeroType.Traveler, - recruitmentInfo = RecruitmentInfo.Exile, - factionBiases = Map(fid -> -500) - ) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newUnaffiliatedHeroes.loneElement shouldBe + UnaffiliatedHeroC( + heroId = exiledHid, + unaffiliatedHeroType = UnaffiliatedHeroType.Traveler, + recruitmentInfo = RecruitmentInfo.Exile, + factionBiases = Map(fid -> -500) + ) } } @@ -234,10 +227,11 @@ class ExileVassalCommandTest llm, deferred ) => - inside(details) { case ved: NotificationDetails.VassalExiled => - ved.exilingFactionId shouldBe fid - ved.provinceId shouldBe pid - ved.exiledHeroId shouldBe exiledHid + inside(details) { + case ved: NotificationDetails.VassalExiled => + ved.exilingFactionId shouldBe fid + ved.provinceId shouldBe pid + ved.exiledHeroId shouldBe exiledHid } targetFactions shouldBe empty affectedProvinceIds shouldBe Vector(pid) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommandTest.scala index e383133104..28ab60fbf0 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FeastCommandTest.scala @@ -1,17 +1,9 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.common.action_result_type.ActionResultType.FEAST -import net.eagle0.eagle.library.settings.{ - LoyaltyGainFromFeast, - PriceIndexShiftPerGold, - VigorGainFromFeast -} +import net.eagle0.eagle.library.settings.{LoyaltyGainFromFeast, PriceIndexShiftPerGold, VigorGainFromFeast} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedHeroC, - StatDelta, - StatNoChange -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatDelta, StatNoChange} import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.province.concrete.ProvinceC import org.scalatest.flatspec.AnyFlatSpec @@ -20,16 +12,13 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.Inspectors.forExactly -class FeastCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class FeastCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { LoyaltyGainFromFeast.setDoubleValue(12) VigorGainFromFeast.setDoubleValue(10) PriceIndexShiftPerGold.setDoubleValue(0.0001) } - val actingFactionId = 3 + val actingFactionId = 3 private val province = ProvinceC( id = 12, @@ -77,8 +66,7 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 44 ) @@ -95,16 +83,16 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 44 ) .immediateExecute - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe province.id - cp.goldDelta shouldBe Some(-44) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe province.id + cp.goldDelta shouldBe Some(-44) } } @@ -113,16 +101,16 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 100 ) .immediateExecute - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe province.id - cp.newPriceIndex shouldBe Some(1.01) // 1.0 + 0.0001 * 100 + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe province.id + cp.newPriceIndex shouldBe Some(1.01) // 1.0 + 0.0001 * 100 } } @@ -131,8 +119,7 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 44 ) @@ -153,8 +140,7 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 44 ) @@ -171,8 +157,7 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 44 ) @@ -193,8 +178,7 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 44 ) @@ -211,8 +195,7 @@ class FeastCommandTest .make( actingFactionId = actingFactionId, province = province, - rulingFactionHeroes = - Vector(normalHero, fullVigorHero, fullLoyaltyHero), + rulingFactionHeroes = Vector(normalHero, fullVigorHero, fullLoyaltyHero), factionLeaderIds = Vector(7), goldCost = 44 ) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommandTest.scala index f3a5ca73c2..58fd4dd2d6 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/FreeForAllDecisionCommandTest.scala @@ -1,42 +1,29 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.library.actions.impl.command.FreeForAllDecisionCommand.{ - Advance, - FreeForAllDecision, - Withdraw -} +import net.eagle0.eagle.library.actions.impl.command.FreeForAllDecisionCommand.{Advance, FreeForAllDecision, Withdraw} import net.eagle0.eagle.library.EagleCommandException -import net.eagle0.eagle.model.action_result.changed_province.concrete.{ - ChangedProvinceC, - HostileArmyStatusChange -} +import net.eagle0.eagle.model.action_result.changed_province.concrete.{ChangedProvinceC, HostileArmyStatusChange} import net.eagle0.eagle.model.action_result.concrete.ActionResultC import net.eagle0.eagle.model.action_result.types.{ ArmyAdvancedToFreeForAllResultType, ArmyWithdrewFromFreeForAllResultType } import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - AwaitingFreeForAll, - Withdrawing -} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{AwaitingFreeForAll, Withdrawing} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.Inside -class FreeForAllDecisionCommandTest - extends AnyFlatSpec - with Matchers - with Inside { +class FreeForAllDecisionCommandTest extends AnyFlatSpec with Matchers with Inside { val actingFactionId: FactionId = 18 - val pid: ProvinceId = 23 - val originPid: ProvinceId = 22 + val pid: ProvinceId = 23 + val originPid: ProvinceId = 22 private val availableDecisions: Vector[FreeForAllDecision] = Vector(Advance, Withdraw) - private val attackDecision: FreeForAllDecision = Advance - private val withdrawDecision: FreeForAllDecision = Withdraw + private val attackDecision: FreeForAllDecision = Advance + private val withdrawDecision: FreeForAllDecision = Withdraw "execute ATTACK_DECISION" should "set the armies to FreeForAll army group" in { val result = FreeForAllDecisionCommand @@ -48,21 +35,22 @@ class FreeForAllDecisionCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe ArmyAdvancedToFreeForAllResultType - ar.actingFactionId shouldBe Some(actingFactionId) - ar.provinceId shouldBe Some(pid) - ar.changedProvinces shouldBe Vector( - ChangedProvinceC( - provinceId = pid, - hostileArmyStatusChanges = Vector( - HostileArmyStatusChange( - factionId = actingFactionId, - newStatus = AwaitingFreeForAll + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe ArmyAdvancedToFreeForAllResultType + ar.actingFactionId shouldBe Some(actingFactionId) + ar.provinceId shouldBe Some(pid) + ar.changedProvinces shouldBe Vector( + ChangedProvinceC( + provinceId = pid, + hostileArmyStatusChanges = Vector( + HostileArmyStatusChange( + factionId = actingFactionId, + newStatus = AwaitingFreeForAll + ) ) ) ) - ) } } @@ -76,35 +64,35 @@ class FreeForAllDecisionCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe ArmyWithdrewFromFreeForAllResultType - ar.actingFactionId shouldBe Some(actingFactionId) - ar.provinceId shouldBe Some(pid) - ar.changedProvinces shouldBe Vector( - ChangedProvinceC( - provinceId = pid, - hostileArmyStatusChanges = Vector( - HostileArmyStatusChange( - factionId = actingFactionId, - newStatus = Withdrawing + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe ArmyWithdrewFromFreeForAllResultType + ar.actingFactionId shouldBe Some(actingFactionId) + ar.provinceId shouldBe Some(pid) + ar.changedProvinces shouldBe Vector( + ChangedProvinceC( + provinceId = pid, + hostileArmyStatusChanges = Vector( + HostileArmyStatusChange( + factionId = actingFactionId, + newStatus = Withdrawing + ) ) ) ) - ) } } "make" should "throw if the selected decision is not in the available list" in { val limitedAvailableDecisions = Vector(Advance) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy FreeForAllDecisionCommand.make( actingFactionId = actingFactionId, provinceId = pid, selectedDecision = withdrawDecision, availableDecisions = limitedAvailableDecisions ) - } ex.getMessage shouldBe "requirement failed: Selected Withdraw was not in Vector(Advance)" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommandTest.scala index bc57015e5c..6b802f4387 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleCapturedHeroesCommandTest.scala @@ -37,14 +37,11 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class HandleCapturedHeroesCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class HandleCapturedHeroesCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val gameId: GameId = 0xcafeface - val actingFactionId = 2 - val capturedHeroFactionId = 12 + val actingFactionId = 2 + val capturedHeroFactionId = 12 private val actingProvince: ProvinceT = ProvinceC( id = 19, @@ -61,12 +58,12 @@ class HandleCapturedHeroesCommandTest private val allProvinces = Vector(actingProvince, capturedHeroProvince) - private val currentDate = Date(year = 343, month = Date.Month.April) + private val currentDate = Date(year = 343, month = Date.Month.April) private val currentRoundId = 268 private val capturedHero = HeroC(id = 6, factionId = Some(capturedHeroFactionId)) - private val actingHero = HeroC(id = 29, factionId = Some(actingFactionId)) + private val actingHero = HeroC(id = 29, factionId = Some(actingFactionId)) private val actingFaction = FactionC( name = "Acting Faction", @@ -129,15 +126,17 @@ class HandleCapturedHeroesCommandTest result.actionResultType shouldBe CapturedHeroExecutedResultType result.provinceId shouldBe Some(19) - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.removedCapturedHeroIds shouldBe Vector(6) - inside(cp.newDeferredChange.get) { case ch: CapturedHeroExecuted => - ch.heroId shouldBe 6 - ch.provinceId shouldBe 19 - ch.executingFactionId shouldBe actingFactionId - ch.prisonerFactionId shouldBe capturedHeroFactionId - } + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.removedCapturedHeroIds shouldBe Vector(6) + inside(cp.newDeferredChange.get) { + case ch: CapturedHeroExecuted => + ch.heroId shouldBe 6 + ch.provinceId shouldBe 19 + ch.executingFactionId shouldBe actingFactionId + ch.prisonerFactionId shouldBe capturedHeroFactionId + } } } @@ -161,15 +160,17 @@ class HandleCapturedHeroesCommandTest result.actionResultType shouldBe CapturedHeroImprisonedResultType result.provinceId shouldBe Some(19) - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.removedCapturedHeroIds shouldBe Vector(6) - inside(cp.newDeferredChange.get) { case ch: CapturedHeroImprisoned => - ch.heroId shouldBe 6 - ch.provinceId shouldBe 19 - ch.imprisoningFactionId shouldBe actingFactionId - ch.prisonerFactionId shouldBe capturedHeroFactionId - } + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.removedCapturedHeroIds shouldBe Vector(6) + inside(cp.newDeferredChange.get) { + case ch: CapturedHeroImprisoned => + ch.heroId shouldBe 6 + ch.provinceId shouldBe 19 + ch.imprisoningFactionId shouldBe actingFactionId + ch.prisonerFactionId shouldBe capturedHeroFactionId + } } } @@ -193,15 +194,17 @@ class HandleCapturedHeroesCommandTest result.actionResultType shouldBe CapturedHeroExiledResultType result.provinceId shouldBe Some(19) - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.removedCapturedHeroIds shouldBe Vector(6) - inside(cp.newDeferredChange.get) { case ch: CapturedHeroExiled => - ch.heroId shouldBe 6 - ch.provinceId shouldBe 19 - ch.exilingFactionId shouldBe actingFactionId - ch.prisonerFactionId shouldBe capturedHeroFactionId - } + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.removedCapturedHeroIds shouldBe Vector(6) + inside(cp.newDeferredChange.get) { + case ch: CapturedHeroExiled => + ch.heroId shouldBe 6 + ch.provinceId shouldBe 19 + ch.exilingFactionId shouldBe actingFactionId + ch.prisonerFactionId shouldBe capturedHeroFactionId + } } } @@ -230,16 +233,18 @@ class HandleCapturedHeroesCommandTest result.actionResultType shouldBe CapturedHeroReturnedResultType result.provinceId shouldBe Some(19) - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.provinceId shouldBe 19 - cp.removedCapturedHeroIds shouldBe Vector(6) - inside(cp.newDeferredChange.get) { case ch: CapturedHeroReturned => - ch.heroId shouldBe 6 - ch.fromProvinceId shouldBe 19 - ch.fromFactionId shouldBe actingFactionId - ch.toProvinceId shouldBe 36 - ch.toFactionId shouldBe capturedHeroFactionId - } + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe 19 + cp.removedCapturedHeroIds shouldBe Vector(6) + inside(cp.newDeferredChange.get) { + case ch: CapturedHeroReturned => + ch.heroId shouldBe 6 + ch.fromProvinceId shouldBe 19 + ch.fromFactionId shouldBe actingFactionId + ch.toProvinceId shouldBe 36 + ch.toFactionId shouldBe capturedHeroFactionId + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommandTest.scala index 2d9c68affa..588308468b 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotCrackDownCommandTest.scala @@ -14,14 +14,8 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedBattalionC, - ChangedHeroC -} -import net.eagle0.eagle.model.action_result.types.{ - RiotAversionFailedResultType, - RiotSuppressedResultType -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedBattalionC, ChangedHeroC} +import net.eagle0.eagle.model.action_result.types.{RiotAversionFailedResultType, RiotSuppressedResultType} import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.hero.Profession @@ -34,10 +28,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class HandleRiotCrackDownCommandTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class HandleRiotCrackDownCommandTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { RiotSupportDelta.setDoubleValue(-30) @@ -52,11 +43,11 @@ class HandleRiotCrackDownCommandTest } private val actingFactionId: FactionId = 27 - private val pid: ProvinceId = 19 - private val heroIds = Vector(9, 1, 3) - private val weakBid = 22 - private val strongBid = 33 - private val battalionIds = Vector(strongBid, weakBid) + private val pid: ProvinceId = 19 + private val heroIds = Vector(9, 1, 3) + private val weakBid = 22 + private val strongBid = 33 + private val battalionIds = Vector(strongBid, weakBid) private val actingProvince = ProvinceC( id = pid, @@ -65,7 +56,7 @@ class HandleRiotCrackDownCommandTest rulingHeroId = Some(heroIds.head), activeEvents = Vector(ImminentRiotEvent()) ) - private val heroes = heroIds + private val heroes = heroIds .map(hid => HeroC( id = hid, @@ -84,7 +75,7 @@ class HandleRiotCrackDownCommandTest armament = 50.0, training = 50.0 ) - private val weakBattalion = + private val weakBattalion = BattalionC( id = weakBid, size = 100, @@ -94,7 +85,7 @@ class HandleRiotCrackDownCommandTest ) it should "throw if a heroId is not available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy HandleRiotCrackDownCommand.make( actingFactionId = actingFactionId, actingProvince = actingProvince, @@ -104,12 +95,11 @@ class HandleRiotCrackDownCommandTest availableHeroIds = heroIds, availableBattalionIds = battalionIds ) - } ex.getMessage shouldBe s"requirement failed: tried to send hero 15 but $heroIds were available" } it should "throw if a battalionId is not available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy HandleRiotCrackDownCommand.make( actingFactionId = actingFactionId, actingProvince = actingProvince, @@ -125,7 +115,6 @@ class HandleRiotCrackDownCommandTest availableHeroIds = heroIds, availableBattalionIds = battalionIds ) - } ex.getMessage shouldBe s"requirement failed: tried to send battalion 11 but $battalionIds were available" } @@ -171,8 +160,9 @@ class HandleRiotCrackDownCommandTest result.actionResultType shouldBe RiotAversionFailedResultType result.removedHeroIds shouldBe Vector(heroIds.head) - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.setHasActed should contain(true) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.setHasActed should contain(true) } } @@ -197,9 +187,10 @@ class HandleRiotCrackDownCommandTest ) .immediateExecuteWithRoll(1.0) - val lowRollAftermathBattalions = - lowRollAftermath.changedBattalions.collect { case cb: ChangedBattalionC => - cb + val lowRollAftermathBattalions = + lowRollAftermath.changedBattalions.collect { + case cb: ChangedBattalionC => + cb } val highRollAftermathBattalions = highRollAftermath.changedBattalions.collect { @@ -209,7 +200,7 @@ class HandleRiotCrackDownCommandTest lowRollAftermathBattalions should have size 1 highRollAftermathBattalions should have size 1 - val lowRollBatt = lowRollAftermathBattalions.head.to + val lowRollBatt = lowRollAftermathBattalions.head.to val highRollBatt = highRollAftermathBattalions.head.to lowRollBatt.size should be > highRollBatt.size @@ -236,7 +227,7 @@ class HandleRiotCrackDownCommandTest ) .immediateExecuteWithRoll(1.0) - val lowCharismaAftermathBattalions = + val lowCharismaAftermathBattalions = lowCharismaAftermath.changedBattalions.collect { case cb: ChangedBattalionC => cb @@ -250,7 +241,7 @@ class HandleRiotCrackDownCommandTest lowCharismaAftermathBattalions should have size 1 highCharismaAftermathBattalions should have size 1 - val lowCharismaBatt = lowCharismaAftermathBattalions.head.to + val lowCharismaBatt = lowCharismaAftermathBattalions.head.to val highCharismaBatt = highCharismaAftermathBattalions.head.to highCharismaBatt.size should be > lowCharismaBatt.size @@ -267,10 +258,11 @@ class HandleRiotCrackDownCommandTest ) .immediateExecuteWithRoll(1.0) - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe heroIds.head - ch.strengthXpDelta shouldBe Some(75) - ch.agilityXpDelta shouldBe Some(25) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe heroIds.head + ch.strengthXpDelta shouldBe Some(75) + ch.agilityXpDelta shouldBe Some(25) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotDoNothingCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotDoNothingCommandTest.scala index 72c5fd29d6..eb8150811a 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotDoNothingCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotDoNothingCommandTest.scala @@ -16,10 +16,7 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inspectors.forExactly -class HandleRiotDoNothingCommandTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class HandleRiotDoNothingCommandTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { RiotSupportDelta.setDoubleValue(-30) @@ -27,9 +24,9 @@ class HandleRiotDoNothingCommandTest RiotInfrastructureDevastationDelta.setDoubleValue(30) } - private val fid: FactionId = 27 + private val fid: FactionId = 27 private val pid: ProvinceId = 19 - private val heroIds = Vector(9, 1, 3) + private val heroIds = Vector(9, 1, 3) private val province = ProvinceC( id = pid, @@ -48,9 +45,10 @@ class HandleRiotDoNothingCommandTest ) .immediateExecute - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.setHasActed should contain(true) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.setHasActed should contain(true) } result.actionResultType shouldBe RiotAversionFailedResultType } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommandTest.scala index 81adaccd20..153e56914e 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotGiveCommandTest.scala @@ -15,10 +15,7 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.types.{ - RiotAversionFailedResultType, - RiotAvertedResultType -} +import net.eagle0.eagle.model.action_result.types.{RiotAversionFailedResultType, RiotAvertedResultType} import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ImminentRiotEvent @@ -28,10 +25,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.Inspectors.forExactly -class HandleRiotGiveCommandTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class HandleRiotGiveCommandTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { RiotMaxFood.setIntValue(1000) @@ -42,11 +36,11 @@ class HandleRiotGiveCommandTest RiotInfrastructureDevastationDelta.setDoubleValue(30) } - private val fid: FactionId = 27 + private val fid: FactionId = 27 private val pid: ProvinceId = 19 - private val foodAvailable = 900 - private val goldAvailable = 1200 - private val heroIds = Vector(9, 1, 3) + private val foodAvailable = 900 + private val goldAvailable = 1200 + private val heroIds = Vector(9, 1, 3) private val province = ProvinceC( id = pid, @@ -60,7 +54,7 @@ class HandleRiotGiveCommandTest .map(hid => HeroC(id = hid, factionId = Some(fid), charisma = 80)) "make" should "throw if more food than available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy HandleRiotGiveCommand.make( actingFactionId = fid, province = province, @@ -70,12 +64,11 @@ class HandleRiotGiveCommandTest foodAvailable = foodAvailable, goldAvailable = goldAvailable ) - } ex.getMessage shouldBe "requirement failed: tried to give 1501 food but only 900 available" } it should "throw if more gold than available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy HandleRiotGiveCommand.make( actingFactionId = fid, province = province, @@ -85,7 +78,6 @@ class HandleRiotGiveCommandTest foodAvailable = foodAvailable, goldAvailable = goldAvailable ) - } ex.getMessage shouldBe "requirement failed: tried to give 2702 gold but only 1200 available" } @@ -109,9 +101,10 @@ class HandleRiotGiveCommandTest foodAmount = 100 ).immediateExecuteWithRoll(roll = 0.1) - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.foodDelta should contain(-100) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.foodDelta should contain(-100) } } @@ -134,9 +127,10 @@ class HandleRiotGiveCommandTest foodAmount = 100 ).immediateExecuteWithRoll(roll = 0.35) - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.foodDelta should contain(-100) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.foodDelta should contain(-100) } } @@ -159,9 +153,10 @@ class HandleRiotGiveCommandTest goldAmount = 50 ).immediateExecuteWithRoll(roll = 0.1) - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.goldDelta should contain(-50) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.goldDelta should contain(-50) } } @@ -174,8 +169,9 @@ class HandleRiotGiveCommandTest ).immediateExecuteWithRoll(roll = 0.35) result.actionResultType shouldBe RiotAversionFailedResultType - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.setHasActed should contain(true) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.setHasActed should contain(true) } } @@ -187,9 +183,10 @@ class HandleRiotGiveCommandTest goldAmount = 50 ).immediateExecuteWithRoll(roll = 0.35) - forExactly(1, result.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.goldDelta should contain(-50) + forExactly(1, result.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.goldDelta should contain(-50) } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtilsTest.scala index cbdd7b9136..070ad9b475 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HandleRiotUtilsTest.scala @@ -15,11 +15,8 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inspectors.forExactly -class HandleRiotUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val fid: FactionId = 27 +class HandleRiotUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val fid: FactionId = 27 private val pid: ProvinceId = 19 private val province = ProvinceC( @@ -41,11 +38,12 @@ class HandleRiotUtilsTest province = province ) - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.supportDelta should contain(-30) - cp.economyDevastationDelta should contain(40) - cp.infrastructureDevastationDelta should contain(35) + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.supportDelta should contain(-30) + cp.economyDevastationDelta should contain(40) + cp.infrastructureDevastationDelta should contain(35) } } @@ -56,11 +54,12 @@ class HandleRiotUtilsTest province = province ) - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.newProvinceEvents should contain( - Vector() - ) + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.newProvinceEvents should contain( + Vector() + ) } } @@ -72,11 +71,12 @@ class HandleRiotUtilsTest avoidType = RiotAvertedResultType ) - forExactly(1, ar.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe pid - cp.newProvinceEvents should contain( - Vector() - ) + forExactly(1, ar.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe pid + cp.newProvinceEvents should contain( + Vector() + ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommandTest.scala index 04b54558f1..bd510b43d6 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/HeroGiftCommandTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.library.actions.impl.command.HeroGiftCommand.EligibleGift -import net.eagle0.eagle.library.settings.{ - LoyaltyIncreasePerGold, - PriceIndexShiftPerGold -} +import net.eagle0.eagle.library.settings.{LoyaltyIncreasePerGold, PriceIndexShiftPerGold} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatDelta} @@ -17,10 +14,7 @@ import net.eagle0.eagle.model.state.quest.concrete.{ GiveToHeroesInProvinceQuest, ImproveAgricultureQuest } -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -28,19 +22,16 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inspectors.{forAll, forExactly} import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class HeroGiftCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class HeroGiftCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { LoyaltyIncreasePerGold.setDoubleValue(0.25) PriceIndexShiftPerGold.setDoubleValue(0.0001) } - private val provinceId = 21 + private val provinceId = 21 private val anotherOwnedProvinceId = 27 - private val factionId = 7 + private val factionId = 7 private val recipient = HeroC( id = 12, @@ -113,7 +104,7 @@ class HeroGiftCommandTest private val goldGiven = 80 "make" should "fail if recipient is not among available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy HeroGiftCommand.make( actingFactionId = factionId, actingProvince = recipientProvince, @@ -123,12 +114,11 @@ class HeroGiftCommandTest eligibleGifts = eligibleGifts, factionProvinces = factionProvinces ) - } ex.getMessage shouldBe "requirement failed: Recipient 5 was not among Vector(12, 19, 202)" } it should "fail if amount is zero" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy HeroGiftCommand.make( actingFactionId = factionId, goldGiven = 0, @@ -138,12 +128,11 @@ class HeroGiftCommandTest recipientHero = recipient, factionProvinces = factionProvinces ) - } ex.getMessage shouldBe "requirement failed: 0 not a valid amount, 100 available" } it should "fail if amount is greater than available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy HeroGiftCommand.make( actingFactionId = factionId, goldGiven = 75, @@ -153,7 +142,6 @@ class HeroGiftCommandTest recipientHero = HeroC(id = 19), factionProvinces = factionProvinces ) - } ex.getMessage shouldBe "requirement failed: 75 not a valid amount, 50 available" } @@ -191,9 +179,10 @@ class HeroGiftCommandTest val res = cmd.immediateExecute // starts at 25, 80 gold * 0.25 increase - forExactly(1, res.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe recipient.id - ch.loyaltyChange shouldBe StatDelta(20.0) + forExactly(1, res.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe recipient.id + ch.loyaltyChange shouldBe StatDelta(20.0) } } @@ -214,9 +203,10 @@ class HeroGiftCommandTest val res = cmd.immediateExecute // starts at 25, 80 gold * 0.25 increase, but divided by 1.25 - forExactly(1, res.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe recipient.id - ch.loyaltyChange shouldBe StatDelta(16.0) + forExactly(1, res.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe recipient.id + ch.loyaltyChange shouldBe StatDelta(16.0) } } @@ -256,9 +246,10 @@ class HeroGiftCommandTest val res = cmd.immediateExecute - forExactly(1, res.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe provinceId - cp.goldDelta shouldBe Some(-80) + forExactly(1, res.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe provinceId + cp.goldDelta shouldBe Some(-80) } } @@ -275,7 +266,7 @@ class HeroGiftCommandTest totalGold = 500 ) ) +: t - case _ => ??? + case _ => ??? } ) @@ -287,28 +278,28 @@ class HeroGiftCommandTest actingProvince = provinceWithGiveToHeroesQuest, recipientProvince = provinceWithGiveToHeroesQuest, recipientHero = recipient, - factionProvinces = - Vector(provinceWithGiveToHeroesQuest, anotherOwnedProvince) + factionProvinces = Vector(provinceWithGiveToHeroesQuest, anotherOwnedProvince) ) .immediateExecute .changedProvinces - forExactly(1, cps) { case cp: ChangedProvinceC => - cp.provinceId shouldBe provinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe - UnaffiliatedHeroC( - heroId = 101, - unaffiliatedHeroType = UnaffiliatedHeroType.Resident, - recruitmentAttempted = false, - recruitmentInfo = RecruitmentInfo.HasQuest( - GiveToHeroesInProvinceQuest( - componentCount = 500, - componentsFulfilled = 180, - totalGold = 500, - provinceId = provinceId + forExactly(1, cps) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe provinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe + UnaffiliatedHeroC( + heroId = 101, + unaffiliatedHeroType = UnaffiliatedHeroType.Resident, + recruitmentAttempted = false, + recruitmentInfo = RecruitmentInfo.HasQuest( + GiveToHeroesInProvinceQuest( + componentCount = 500, + componentsFulfilled = 180, + totalGold = 500, + provinceId = provinceId + ) ) ) - ) } } @@ -324,7 +315,7 @@ class HeroGiftCommandTest totalGold = 1250 ) ) +: t - case _ => ??? + case _ => ??? } ) @@ -336,27 +327,27 @@ class HeroGiftCommandTest actingProvince = provinceWithGiveToHeroesQuest, recipientProvince = provinceWithGiveToHeroesQuest, recipientHero = recipient, - factionProvinces = - Vector(provinceWithGiveToHeroesQuest, anotherOwnedProvince) + factionProvinces = Vector(provinceWithGiveToHeroesQuest, anotherOwnedProvince) ) .immediateExecute .changedProvinces - forExactly(1, cps) { case cp: ChangedProvinceC => - cp.provinceId shouldBe provinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe - UnaffiliatedHeroC( - heroId = 101, - unaffiliatedHeroType = UnaffiliatedHeroType.Resident, - recruitmentAttempted = false, - recruitmentInfo = RecruitmentInfo.HasQuest( - GiveToHeroesAcrossRealmQuest( - componentCount = 1250, - componentsFulfilled = 180, - totalGold = 1250 + forExactly(1, cps) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe provinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe + UnaffiliatedHeroC( + heroId = 101, + unaffiliatedHeroType = UnaffiliatedHeroType.Resident, + recruitmentAttempted = false, + recruitmentInfo = RecruitmentInfo.HasQuest( + GiveToHeroesAcrossRealmQuest( + componentCount = 1250, + componentsFulfilled = 180, + totalGold = 1250 + ) ) ) - ) } } @@ -373,7 +364,7 @@ class HeroGiftCommandTest totalGold = 500 ) ) +: t - case _ => ??? + case _ => ??? } ) @@ -385,8 +376,7 @@ class HeroGiftCommandTest actingProvince = recipientProvince, recipientProvince = recipientProvince, recipientHero = recipient, - factionProvinces = - Vector(recipientProvince, anotherProvinceWithGiveToHeroesQuest) + factionProvinces = Vector(recipientProvince, anotherProvinceWithGiveToHeroesQuest) ) .immediateExecute .changedProvinces @@ -409,7 +399,7 @@ class HeroGiftCommandTest totalGold = 500 ) ) +: t - case _ => ??? + case _ => ??? } ) @@ -421,28 +411,28 @@ class HeroGiftCommandTest actingProvince = recipientProvince, recipientProvince = anotherOwnedProvinceWithGiveToHeroesQuest, recipientHero = recipient, - factionProvinces = - Vector(recipientProvince, anotherOwnedProvinceWithGiveToHeroesQuest) + factionProvinces = Vector(recipientProvince, anotherOwnedProvinceWithGiveToHeroesQuest) ) .immediateExecute .changedProvinces - forExactly(1, cps) { case cp: ChangedProvinceC => - cp.provinceId shouldBe anotherOwnedProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe - UnaffiliatedHeroC( - heroId = 102, - unaffiliatedHeroType = UnaffiliatedHeroType.Resident, - recruitmentAttempted = false, - recruitmentInfo = RecruitmentInfo.HasQuest( - GiveToHeroesInProvinceQuest( - componentCount = 500, - componentsFulfilled = 145, - provinceId = anotherOwnedProvinceId, - totalGold = 500 + forExactly(1, cps) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe anotherOwnedProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe + UnaffiliatedHeroC( + heroId = 102, + unaffiliatedHeroType = UnaffiliatedHeroType.Resident, + recruitmentAttempted = false, + recruitmentInfo = RecruitmentInfo.HasQuest( + GiveToHeroesInProvinceQuest( + componentCount = 500, + componentsFulfilled = 145, + provinceId = anotherOwnedProvinceId, + totalGold = 500 + ) ) ) - ) } } @@ -458,7 +448,7 @@ class HeroGiftCommandTest totalGold = 1250 ) ) +: t - case _ => ??? + case _ => ??? } ) @@ -478,21 +468,22 @@ class HeroGiftCommandTest .immediateExecute .changedProvinces - forExactly(1, cps) { case cp: ChangedProvinceC => - cp.provinceId shouldBe anotherOwnedProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe - UnaffiliatedHeroC( - heroId = 102, - unaffiliatedHeroType = UnaffiliatedHeroType.Resident, - recruitmentAttempted = false, - recruitmentInfo = RecruitmentInfo.HasQuest( - GiveToHeroesAcrossRealmQuest( - componentCount = 1250, - componentsFulfilled = 180, - totalGold = 1250 + forExactly(1, cps) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe anotherOwnedProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe + UnaffiliatedHeroC( + heroId = 102, + unaffiliatedHeroType = UnaffiliatedHeroType.Resident, + recruitmentAttempted = false, + recruitmentInfo = RecruitmentInfo.HasQuest( + GiveToHeroesAcrossRealmQuest( + componentCount = 1250, + componentsFulfilled = 180, + totalGold = 1250 + ) ) ) - ) } } @@ -509,9 +500,10 @@ class HeroGiftCommandTest val res = cmd.immediateExecute - forExactly(1, res.changedProvinces) { case cp: ChangedProvinceC => - cp.provinceId shouldBe provinceId - cp.newPriceIndex shouldBe Some(1.008) + forExactly(1, res.changedProvinces) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe provinceId + cp.newPriceIndex shouldBe Some(1.008) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommandTest.scala index 9a5f171c61..e4165ef1b3 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ImproveCommandTest.scala @@ -9,10 +9,7 @@ import net.eagle0.eagle.library.settings.{ ImprovementXpPerStat } import net.eagle0.eagle.library.EagleCommandException -import net.eagle0.eagle.model.action_result.changed_province.concrete.{ - ChangedProvinceC, - NewLockedImprovementType -} +import net.eagle0.eagle.model.action_result.changed_province.concrete.{ChangedProvinceC, NewLockedImprovementType} import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.ImproveResultType import net.eagle0.eagle.model.state.hero.{HeroT, Profession} @@ -24,10 +21,7 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class ImproveCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ImproveCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val actingFactionId = 19 @@ -66,11 +60,11 @@ class ImproveCommandTest ImprovementType.Devastation ) - private val improvementPerStat = 0.08 - private val improvementReductionMax = 0.25 - private val improvementSupportGain = 0.75 + private val improvementPerStat = 0.08 + private val improvementReductionMax = 0.25 + private val improvementSupportGain = 0.75 private val engineerImprovementBonus = 1.8 - private val xpPerStat = 5 + private val xpPerStat = 5 override def beforeEach(): Unit = { ImprovementPerStat.setDoubleValue(improvementPerStat) @@ -148,8 +142,9 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedHeroes.head) { case ch: ChangedHeroC => - ch.vigorChange shouldBe StatDelta(-15.0) + inside(result.changedHeroes.head) { + case ch: ChangedHeroC => + ch.vigorChange shouldBe StatDelta(-15.0) } } @@ -166,9 +161,10 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedHeroes.head) { case ch: ChangedHeroC => - ch.strengthXpDelta shouldBe Some(xpPerStat) - ch.agilityXpDelta shouldBe Some(xpPerStat) + inside(result.changedHeroes.head) { + case ch: ChangedHeroC => + ch.strengthXpDelta shouldBe Some(xpPerStat) + ch.agilityXpDelta shouldBe Some(xpPerStat) } } @@ -237,12 +233,13 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.economyDevastationDelta shouldBe Some(-expectedImprovementFromZero) - cp.agricultureDevastationDelta shouldBe Some(-expectedImprovementFromZero) - cp.infrastructureDevastationDelta shouldBe Some( - -expectedImprovementFromZero - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.economyDevastationDelta shouldBe Some(-expectedImprovementFromZero) + cp.agricultureDevastationDelta shouldBe Some(-expectedImprovementFromZero) + cp.infrastructureDevastationDelta shouldBe Some( + -expectedImprovementFromZero + ) } } @@ -260,10 +257,11 @@ class ImproveCommandTest val betterExpectedImprovement = 7.12 // improvementPerStat * (85 + 93) / 2.0 val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.economyDevastationDelta shouldBe Some( - -betterExpectedImprovement - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.economyDevastationDelta shouldBe Some( + -betterExpectedImprovement + ) } } @@ -281,12 +279,13 @@ class ImproveCommandTest val expectedImprovement = expectedImprovementFromZero + engineerImprovementBonus - val result = cmd.immediateExecute + val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.infrastructureDevastationDelta shouldBe Some( - -expectedImprovement - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.infrastructureDevastationDelta shouldBe Some( + -expectedImprovement + ) } } @@ -303,10 +302,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.supportDelta shouldBe Some( - improvementSupportGain * expectedImprovementFromZero - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.supportDelta shouldBe Some( + improvementSupportGain * expectedImprovementFromZero + ) } } @@ -323,10 +323,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.economyDelta shouldBe Some( - expectedImprovementFromZero - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.economyDelta shouldBe Some( + expectedImprovementFromZero + ) } } @@ -346,10 +347,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.economyDelta shouldBe Some( - reducedExpectedImprovement - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.economyDelta shouldBe Some( + reducedExpectedImprovement + ) } } @@ -368,10 +370,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.economyDelta shouldBe Some( - betterExpectedImprovement - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.economyDelta shouldBe Some( + betterExpectedImprovement + ) } } @@ -389,12 +392,13 @@ class ImproveCommandTest val expectedImprovement = expectedImprovementFromZero + engineerImprovementBonus - val result = cmd.immediateExecute + val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.economyDelta shouldBe Some( - expectedImprovement - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.economyDelta shouldBe Some( + expectedImprovement + ) } } @@ -411,10 +415,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.supportDelta shouldBe Some( - improvementSupportGain * expectedImprovementFromZero - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.supportDelta shouldBe Some( + improvementSupportGain * expectedImprovementFromZero + ) } } @@ -431,10 +436,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.agricultureDelta shouldBe Some( - expectedImprovementFromZero - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.agricultureDelta shouldBe Some( + expectedImprovementFromZero + ) } } @@ -451,10 +457,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.infrastructureDelta shouldBe Some( - expectedImprovementFromZero - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.infrastructureDelta shouldBe Some( + expectedImprovementFromZero + ) } } @@ -471,10 +478,11 @@ class ImproveCommandTest val result = cmd.immediateExecute - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newLockedImprovementType shouldBe Some( - NewLockedImprovementType.New(ImprovementType.Infrastructure) - ) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newLockedImprovementType shouldBe Some( + NewLockedImprovementType.New(ImprovementType.Infrastructure) + ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommandTest.scala index 31e66f0537..8e8196c8d9 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/IssueOrdersCommandTest.scala @@ -7,18 +7,15 @@ import net.eagle0.eagle.model.action_result.concrete.ChangedFactionC import net.eagle0.eagle.model.action_result.types.OrdersIssuedResultType import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.province.ProvinceOrderType -import net.eagle0.eagle.model.state.province.ProvinceOrderType.{ - Expand, - Mobilize -} +import net.eagle0.eagle.model.state.province.ProvinceOrderType.{Expand, Mobilize} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class IssueOrdersCommandTest extends AnyFlatSpec with Matchers { private val actingFactionId = 7 - private val actingProvince = 5 - private val factionLeader = 19 - private val anotherLeader = 20 + private val actingProvince = 5 + private val factionLeader = 19 + private val anotherLeader = 20 private val actingFaction: FactionC = FactionC( id = actingFactionId, @@ -74,7 +71,7 @@ class IssueOrdersCommandTest extends AnyFlatSpec with Matchers { } "make with a duplicated ID" should "throw with duplicate id message" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy IssueOrdersCommand.make( actingFaction = actingFaction, actingProvinceId = actingProvince, @@ -86,13 +83,12 @@ class IssueOrdersCommandTest extends AnyFlatSpec with Matchers { ), newFocusProvinceId = Some(5) ) - } ex.getMessage shouldBe "requirement failed: Duplicate province ID found in orders Vector(ProvinceOrders(5,Mobilize), ProvinceOrders(9,Expand), ProvinceOrders(5,Develop))" } "make with an unowned province ID" should "throw with unowned id message" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy IssueOrdersCommand.make( actingFaction = actingFaction, actingProvinceId = actingProvince, @@ -104,7 +100,6 @@ class IssueOrdersCommandTest extends AnyFlatSpec with Matchers { ), newFocusProvinceId = Some(5) ) - } ex.getMessage shouldBe "requirement failed: Found a province that does not belong to player 7 in Vector(ProvinceOrders(5,Mobilize), ProvinceOrders(9,Expand), ProvinceOrders(1,Develop))" diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtilsTest.scala index 91baa19eaa..74e33433e4 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/LegacyHandleRiotUtilsTest.scala @@ -14,11 +14,8 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class LegacyHandleRiotUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val fid: FactionId = 27 +class LegacyHandleRiotUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val fid: FactionId = 27 private val pid: ProvinceId = 19 private val province = ProvinceC( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommandTest.scala index 6c7bd21ccd..aa8061a285 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ManagePrisonersCommandTest.scala @@ -1,14 +1,8 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, ProvinceId} -import net.eagle0.eagle.library.actions.impl.command.ManagePrisonersCommand.{ - PrisonerManagementOption, - PrisonerToManage -} -import net.eagle0.eagle.library.settings.{ - QuestFailedRecruitmentPenalty, - QuestRecruitmentBonus -} +import net.eagle0.eagle.library.actions.impl.command.ManagePrisonersCommand.{PrisonerManagementOption, PrisonerToManage} +import net.eagle0.eagle.library.settings.{QuestFailedRecruitmentPenalty, QuestRecruitmentBonus} import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC @@ -25,10 +19,7 @@ import net.eagle0.eagle.model.action_result.types.{ import net.eagle0.eagle.model.action_result.NotificationDetails import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.province.concrete.ProvinceC -import net.eagle0.eagle.model.state.province.DeferredChange.{ - PrisonerMoved, - PrisonerReturned -} +import net.eagle0.eagle.model.state.province.DeferredChange.{PrisonerMoved, PrisonerReturned} import net.eagle0.eagle.model.state.province.Neighbor import net.eagle0.eagle.model.state.quest.concrete.{ ExecutePrisonerQuest, @@ -53,20 +44,17 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ManagePrisonersCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ManagePrisonersCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val actingFactionId = 7 - private val actingProvinceId = 15 + private val actingFactionId = 7 + private val actingProvinceId = 15 private val neighboringProvinceId = 17 - private val enemyFactionId: FactionId = 98 + private val enemyFactionId: FactionId = 98 private val enemyProvinceId: ProvinceId = 25 private val questRecruitmentBonus = 237.2 - private val questFailedPenalty = 122 + private val questFailedPenalty = 122 private val questFulfillmentChecker = new QuestFulfillmentChecker( gameId = 0xcafeface, @@ -116,8 +104,8 @@ class ManagePrisonersCommandTest private val heroIdDesiringExecute = 983 private val heroIdDesiringRelease = 984 - private val heroIdDesiringExile = 985 - private val heroIdDesiringReturn = 986 + private val heroIdDesiringExile = 985 + private val heroIdDesiringReturn = 986 private val provincesWithQuests = allProvinces :+ ProvinceC( id = 982, @@ -212,7 +200,7 @@ class ManagePrisonersCommandTest recruitmentInfo = RecruitmentInfo.Prisoner, lastFactionId = Some(9) ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ManagePrisonersCommand.make( actingFactionId = actingFactionId, actingProvinceId = actingProvinceId, @@ -222,12 +210,11 @@ class ManagePrisonersCommandTest allProvinces = allProvinces, questFulfillmentChecker = questFulfillmentChecker ) - } ex.getMessage shouldBe "requirement failed: Selected prisoner hero id 105 was not among available prisoners Vector(97, 103)" } it should "throw if the selected option was not in the available list" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ManagePrisonersCommand.make( actingFactionId = actingFactionId, actingProvinceId = actingProvinceId, @@ -237,7 +224,6 @@ class ManagePrisonersCommandTest allProvinces = allProvinces, questFulfillmentChecker = questFulfillmentChecker ) - } ex.getMessage shouldBe "requirement failed: Selected management type Release was not among available options Vector(Execute, Return(98), Move(17))" } @@ -314,20 +300,21 @@ class ManagePrisonersCommandTest .results .loneElement - inside(ar.newNotifications.loneElement) { case note: NotificationC => - note.deferred shouldBe true - inside(note.details) { - case NotificationDetails.PrisonerExecuted( - lastFactionId, - provinceId, - executedHeroId, - executingFactionId - ) => - provinceId shouldBe provinceId - executedHeroId shouldBe 103 - executingFactionId shouldBe actingFactionId - lastFactionId shouldBe Some(9) - } + inside(ar.newNotifications.loneElement) { + case note: NotificationC => + note.deferred shouldBe true + inside(note.details) { + case NotificationDetails.PrisonerExecuted( + lastFactionId, + provinceId, + executedHeroId, + executingFactionId + ) => + provinceId shouldBe provinceId + executedHeroId shouldBe 103 + executingFactionId shouldBe actingFactionId + lastFactionId shouldBe Some(9) + } } } @@ -346,13 +333,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringRelease, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringRelease, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -372,13 +360,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExile, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExile, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -398,13 +387,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringReturn, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringReturn, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -424,13 +414,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFulfilledResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExecute, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.WouldJoin, - factionBiases = Map(actingFactionId -> questRecruitmentBonus) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExecute, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.WouldJoin, + factionBiases = Map(actingFactionId -> questRecruitmentBonus) + ) } } } @@ -442,8 +433,7 @@ class ManagePrisonersCommandTest actingProvinceId = actingProvinceId, availablePrisoners = availablePrisoners, prisonerUnaffiliatedHero = secondUH103, - chosenOption = - PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), + chosenOption = PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), allProvinces = allProvinces, questFulfillmentChecker = questFulfillmentChecker ) @@ -462,23 +452,23 @@ class ManagePrisonersCommandTest actingProvinceId = actingProvinceId, availablePrisoners = availablePrisoners, prisonerUnaffiliatedHero = secondUH103, - chosenOption = - PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), + chosenOption = PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), allProvinces = allProvinces, questFulfillmentChecker = questFulfillmentChecker ) .results .loneElement - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe actingProvinceId - cp.newDeferredChange shouldBe Some( - PrisonerMoved( - heroId = 103, - fromProvinceId = actingProvinceId, - toProvinceId = neighboringProvinceId + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe actingProvinceId + cp.newDeferredChange shouldBe Some( + PrisonerMoved( + heroId = 103, + fromProvinceId = actingProvinceId, + toProvinceId = neighboringProvinceId + ) ) - ) } } @@ -489,22 +479,22 @@ class ManagePrisonersCommandTest actingProvinceId = actingProvinceId, availablePrisoners = availablePrisoners, prisonerUnaffiliatedHero = secondUH103, - chosenOption = - PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), + chosenOption = PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), allProvinces = allProvinces, questFulfillmentChecker = questFulfillmentChecker ) .results .loneElement - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe actingProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 103, - unaffiliatedHeroType = MovingPrisoner, - recruitmentInfo = RecruitmentInfo.Prisoner, - lastFactionId = Some(9) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe actingProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 103, + unaffiliatedHeroType = MovingPrisoner, + recruitmentInfo = RecruitmentInfo.Prisoner, + lastFactionId = Some(9) + ) } } @@ -515,8 +505,7 @@ class ManagePrisonersCommandTest actingProvinceId = actingProvinceId, availablePrisoners = availablePrisoners, prisonerUnaffiliatedHero = secondUH103, - chosenOption = - PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), + chosenOption = PrisonerManagementOption.Move(toProvinceId = neighboringProvinceId), allProvinces = provincesWithQuests, questFulfillmentChecker = questFulfillmentChecker ) @@ -524,13 +513,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExecute, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExecute, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -552,13 +542,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringRelease, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringRelease, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -580,13 +571,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExile, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExile, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -608,13 +600,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringReturn, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringReturn, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -652,14 +645,15 @@ class ManagePrisonersCommandTest .results .loneElement - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe actingProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 103, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - lastFactionId = Some(9) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe actingProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 103, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + lastFactionId = Some(9) + ) } } @@ -678,13 +672,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFulfilledResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringRelease, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.WouldJoin, - factionBiases = Map(actingFactionId -> questRecruitmentBonus) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringRelease, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.WouldJoin, + factionBiases = Map(actingFactionId -> questRecruitmentBonus) + ) } } } @@ -704,13 +699,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExecute, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExecute, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -730,13 +726,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExile, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExile, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -756,13 +753,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringReturn, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringReturn, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -800,14 +798,15 @@ class ManagePrisonersCommandTest .results .loneElement - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.provinceId shouldBe actingProvinceId - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 103, - unaffiliatedHeroType = Outlaw, - recruitmentInfo = RecruitmentInfo.Outlaw, - lastFactionId = Some(9) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe actingProvinceId + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 103, + unaffiliatedHeroType = Outlaw, + recruitmentInfo = RecruitmentInfo.Outlaw, + lastFactionId = Some(9) + ) } } @@ -826,13 +825,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExecute, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExecute, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -852,13 +852,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringRelease, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringRelease, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -878,13 +879,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringReturn, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringReturn, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -904,13 +906,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFulfilledResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExile, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.WouldJoin, - factionBiases = Map(actingFactionId -> questRecruitmentBonus) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExile, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.WouldJoin, + factionBiases = Map(actingFactionId -> questRecruitmentBonus) + ) } } } @@ -948,16 +951,17 @@ class ManagePrisonersCommandTest .results .loneElement - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newDeferredChange shouldBe Some( - PrisonerReturned( - heroId = 97, - fromProvinceId = actingProvinceId, - fromFactionId = actingFactionId, - toProvinceId = enemyProvinceId, - toFactionId = enemyFactionId + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newDeferredChange shouldBe Some( + PrisonerReturned( + heroId = 97, + fromProvinceId = actingProvinceId, + fromFactionId = actingFactionId, + toProvinceId = enemyProvinceId, + toFactionId = enemyFactionId + ) ) - ) } } @@ -975,13 +979,14 @@ class ManagePrisonersCommandTest .results .loneElement - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 97, - unaffiliatedHeroType = ReturningPrisoner, - recruitmentInfo = RecruitmentInfo.Prisoner, - lastFactionId = Some(enemyFactionId) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 97, + unaffiliatedHeroType = ReturningPrisoner, + recruitmentInfo = RecruitmentInfo.Prisoner, + lastFactionId = Some(enemyFactionId) + ) } } @@ -1000,13 +1005,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 981, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 981, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -1018,8 +1024,7 @@ class ManagePrisonersCommandTest actingProvinceId = actingProvinceId, availablePrisoners = availablePrisoners, prisonerUnaffiliatedHero = secondUH103, - chosenOption = - PrisonerManagementOption.Return(toFactionId = enemyFactionId), + chosenOption = PrisonerManagementOption.Return(toFactionId = enemyFactionId), allProvinces = provincesWithQuests, questFulfillmentChecker = questFulfillmentChecker ) @@ -1027,13 +1032,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringRelease, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringRelease, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -1045,8 +1051,7 @@ class ManagePrisonersCommandTest actingProvinceId = actingProvinceId, availablePrisoners = availablePrisoners, prisonerUnaffiliatedHero = secondUH103, - chosenOption = - PrisonerManagementOption.Return(toFactionId = enemyFactionId), + chosenOption = PrisonerManagementOption.Return(toFactionId = enemyFactionId), allProvinces = provincesWithQuests, questFulfillmentChecker = questFulfillmentChecker ) @@ -1054,13 +1059,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringExile, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedPenalty) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringExile, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedPenalty) + ) } } } @@ -1072,8 +1078,7 @@ class ManagePrisonersCommandTest actingProvinceId = actingProvinceId, availablePrisoners = availablePrisoners, prisonerUnaffiliatedHero = secondUH103, - chosenOption = - PrisonerManagementOption.Return(toFactionId = enemyFactionId), + chosenOption = PrisonerManagementOption.Return(toFactionId = enemyFactionId), allProvinces = provincesWithQuests, questFulfillmentChecker = questFulfillmentChecker ) @@ -1081,13 +1086,14 @@ class ManagePrisonersCommandTest forExactly(1, results) { ar => ar.actionResultType shouldBe QuestFulfilledResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = heroIdDesiringReturn, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.WouldJoin, - factionBiases = Map(actingFactionId -> questRecruitmentBonus) - ) + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = heroIdDesiringReturn, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.WouldJoin, + factionBiases = Map(actingFactionId -> questRecruitmentBonus) + ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommandTest.scala index 79671355d1..8f4eb8f3eb 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/MarchCommandTest.scala @@ -1,47 +1,29 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.{ - BattalionId, - FactionId, - GameId, - HeroId, - ProvinceId, - RoundId -} -import net.eagle0.eagle.library.settings.{ - ActionVigorCost, - MarchWisdomXp, - TurnsToResolveConquest -} +import net.eagle0.eagle.{BattalionId, FactionId, GameId, HeroId, ProvinceId, RoundId} +import net.eagle0.eagle.library.settings.{ActionVigorCost, MarchWisdomXp, TurnsToResolveConquest} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.MarchActionResultType import net.eagle0.eagle.model.state.CombatUnit import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class MarchCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class MarchCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { // Test data for new protoless API - private val actingFactionId: FactionId = 5 - private val originProvinceId: ProvinceId = 7 + private val actingFactionId: FactionId = 5 + private val originProvinceId: ProvinceId = 7 private val destinationProvinceId: ProvinceId = 3 - private val availableDestinationProvinceIds = Vector[ProvinceId](3, 4, 5) - private val availableHeroIds = Vector[HeroId](1, 27) - private val availableBattalionIds = Vector[BattalionId](98, 99) - private val goldAvailable = 3500 - private val foodAvailable = 4000 - private val currentRoundId: RoundId = 3 - private val gameId: GameId = 0xcafe + private val availableDestinationProvinceIds = Vector[ProvinceId](3, 4, 5) + private val availableHeroIds = Vector[HeroId](1, 27) + private val availableBattalionIds = Vector[BattalionId](98, 99) + private val goldAvailable = 3500 + private val foodAvailable = 4000 + private val currentRoundId: RoundId = 3 + private val gameId: GameId = 0xcafe private val gold = 3212 private val food = 3535 @@ -58,7 +40,7 @@ class MarchCommandTest } "make" should "throw if destination province is not available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy MarchCommand.make( actingFactionId = actingFactionId, originProvinceId = originProvinceId, @@ -74,13 +56,12 @@ class MarchCommandTest currentRoundId = currentRoundId, gameId = gameId ) - } ex.getMessage should include("Destination province 99 is not in") } it should "throw if gold exceeds available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy MarchCommand.make( actingFactionId = actingFactionId, originProvinceId = originProvinceId, @@ -96,13 +77,12 @@ class MarchCommandTest currentRoundId = currentRoundId, gameId = gameId ) - } ex.getMessage should include("Specified 4000 gold but only 3500 available") } it should "throw if no marching units provided" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy MarchCommand.make( actingFactionId = actingFactionId, originProvinceId = originProvinceId, @@ -118,7 +98,6 @@ class MarchCommandTest currentRoundId = currentRoundId, gameId = gameId ) - } ex.getMessage should include( "Must supply at least one acting unit for MarchCommand" @@ -244,7 +223,7 @@ class MarchCommandTest .find(_.provinceId == destinationProvinceId) .get .asInstanceOf[ChangedProvinceC] - val incomingArmy = destinationProvinceChange.newIncomingArmies.head + val incomingArmy = destinationProvinceChange.newIncomingArmies.head incomingArmy.army.factionId.shouldBe(actingFactionId) incomingArmy.army.units.shouldBe(marchingUnits) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommandTest.scala index 0c8a3107e5..1344487f1d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/OrganizeTroopsCommandTest.scala @@ -16,12 +16,7 @@ import net.eagle0.eagle.model.state.battalion.BattalionT import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.BattalionType import net.eagle0.eagle.model.state.BattalionTypeId -import net.eagle0.eagle.model.state.BattalionTypeId.{ - HeavyCavalry, - HeavyInfantry, - LightInfantry, - Longbowmen -} +import net.eagle0.eagle.model.state.BattalionTypeId.{HeavyCavalry, HeavyInfantry, LightInfantry, Longbowmen} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.Inside.inside @@ -124,9 +119,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { newBattalions = Vector(), troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom).newValue - } ex.getMessage shouldBe "requirement failed: Attempting to change battalions that are not in province 7" } @@ -149,17 +143,15 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: LightInfantry was not among constructible battalion types Vector(Longbowmen)" } it should "not throw if a changed battalion without any new troops has a non-supported type" in { val command = OrganizeTroopsCommand.make( actingFactionId = actingFactionId, - province = - province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), + province = province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), existingBattalions = existingBattalions, constructibleBattalionTypeIds = Vector(Longbowmen), allBattalionTypes = battalionTypes, @@ -180,9 +172,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - noException should be thrownBy { + noException should be thrownBy command.immediateExecute(functionalRandom) - } } it should "throw if a new battalion has a non-supported type" in { @@ -203,9 +194,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: LightInfantry was not among constructible battalion types Vector(Longbowmen)" } @@ -228,9 +218,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Trying to take an existing battalion over its capacity" } @@ -252,9 +241,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Trying to make a new battalion over its capacity" } @@ -276,9 +264,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Changes cost 1150 but only 3 is available" } @@ -315,9 +302,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Moving 80 troops from a battalion that only has 30" } @@ -354,9 +340,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Moving troops from battalion 23, which does not exist" } @@ -393,9 +378,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Can't change LightInfantry troops into HeavyCavalry" } @@ -434,8 +418,9 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue - result.changedBattalions.collect { case cb: ChangedBattalionC => - cb.to + result.changedBattalions.collect { + case cb: ChangedBattalionC => + cb.to } should contain( battalion1.withSize(10) ) @@ -444,8 +429,7 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { it should "add the troops to the merged-to battalion with the stats averaged" in { val command = OrganizeTroopsCommand.make( actingFactionId = actingFactionId, - province = - province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), + province = province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), existingBattalions = existingBattalions, constructibleBattalionTypeIds = battalionTypes.map(_.typeId), allBattalionTypes = battalionTypes, @@ -468,8 +452,9 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue - result.changedBattalions.collect { case cb: ChangedBattalionC => - cb.to + result.changedBattalions.collect { + case cb: ChangedBattalionC => + cb.to } should contain(battalion1.withSize(130)) val changedBattalion3 = result.changedBattalions.collectFirst { case cb: ChangedBattalionC if cb.to.id == battalion3.id => cb @@ -483,8 +468,7 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { it should "throw if a ChangedBattalion id is duplicated" in { val command = OrganizeTroopsCommand.make( actingFactionId = actingFactionId, - province = - province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), + province = province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), existingBattalions = existingBattalions, constructibleBattalionTypeIds = battalionTypes.map(_.typeId), allBattalionTypes = battalionTypes, @@ -511,9 +495,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe s"requirement failed: Changed battalion id appears multiple times" } @@ -541,17 +524,15 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe s"requirement failed: Changed battalion id ${battalion1.id} cannot merge from itself" } it should "throw if a ChangedBattalion has a merged-from id appear twice" in { val command = OrganizeTroopsCommand.make( actingFactionId = actingFactionId, - province = - province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), + province = province.copy(battalionIds = Vector(battalion1.id, battalion3.id)), existingBattalions = existingBattalions, constructibleBattalionTypeIds = battalionTypes.map(_.typeId), allBattalionTypes = battalionTypes, @@ -576,9 +557,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe s"requirement failed: Merged-from id appears multiple times for battalion ${battalion3.id}" } @@ -601,9 +581,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Trying to take an existing battalion over its capacity" } @@ -630,9 +609,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Trying to make a new battalion over its capacity" } @@ -682,10 +660,11 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue result.changedBattalions should have size 1 - inside(result.changedBattalions.head) { case cb: ChangedBattalionC => - cb.to.size shouldBe 600 - cb.to.id shouldBe battalion1.id - cb.to.typeId shouldBe battalion1.typeId + inside(result.changedBattalions.head) { + case cb: ChangedBattalionC => + cb.to.size shouldBe 600 + cb.to.id shouldBe battalion1.id + cb.to.typeId shouldBe battalion1.typeId } } @@ -711,10 +690,11 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue result.changedBattalions should have size 1 - inside(result.changedBattalions.head) { case cb: ChangedBattalionC => - cb.to.training shouldBe 12.5 // 150 / 600 * 50.0 - cb.to.id shouldBe battalion1.id - cb.to.typeId shouldBe battalion1.typeId + inside(result.changedBattalions.head) { + case cb: ChangedBattalionC => + cb.to.training shouldBe 12.5 // 150 / 600 * 50.0 + cb.to.id shouldBe battalion1.id + cb.to.typeId shouldBe battalion1.typeId } } @@ -740,10 +720,11 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue result.changedBattalions should have size 1 - inside(result.changedBattalions.head) { case cb: ChangedBattalionC => - cb.to.armament shouldBe 20.0 // 150 / 600 * 80.0 - cb.to.id shouldBe battalion1.id - cb.to.typeId shouldBe battalion1.typeId + inside(result.changedBattalions.head) { + case cb: ChangedBattalionC => + cb.to.armament shouldBe 20.0 // 150 / 600 * 80.0 + cb.to.id shouldBe battalion1.id + cb.to.typeId shouldBe battalion1.typeId } } @@ -769,8 +750,9 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue result.changedProvinces should have size 1 - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.goldDelta should contain(-450.0 * 1.2) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.goldDelta should contain(-450.0 * 1.2) } } @@ -799,8 +781,9 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { result.changedProvinces should have size 1 - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.newPriceIndex shouldBe Some(1.054) // 1.0 + 0.0001 * 450.0 * 1.2 + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.newPriceIndex shouldBe Some(1.054) // 1.0 + 0.0001 * 450.0 * 1.2 } } @@ -851,8 +834,9 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue result.changedProvinces should have size 1 - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - cp.goldDelta should contain(-(324 * 1.2).ceil) + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + cp.goldDelta should contain(-(324 * 1.2).ceil) } } @@ -906,12 +890,13 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute(functionalRandom).newValue result.changedBattalions should have size 1 - inside(result.changedBattalions.head) { case cb: ChangedBattalionC => - cb.to.id shouldBe battalion1.id - cb.to.typeId shouldBe battalion1.typeId - cb.to.size shouldBe (battalion1.size - 53) - cb.to.training shouldBe battalion1.training - cb.to.armament shouldBe battalion1.armament + inside(result.changedBattalions.head) { + case cb: ChangedBattalionC => + cb.to.id shouldBe battalion1.id + cb.to.typeId shouldBe battalion1.typeId + cb.to.size shouldBe (battalion1.size - 53) + cb.to.training shouldBe battalion1.training + cb.to.armament shouldBe battalion1.armament } } @@ -934,9 +919,8 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { troopCosts = troopCosts ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute(functionalRandom) - } ex.getMessage shouldBe "requirement failed: Trying to take a battalion below 0 size" } @@ -1021,7 +1005,7 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { } "make" should "throw if there are no new battalions or changed battalions" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy OrganizeTroopsCommand.make( actingFactionId = actingFactionId, province = province, @@ -1032,7 +1016,6 @@ class OrganizeTroopsCommandTest extends AnyFlatSpec with Matchers { newBattalions = Vector(), troopCosts = troopCosts ) - } ex.getMessage shouldBe "requirement failed: Must specify either a new battalion or a changed battalion" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommandTest.scala index ef11e629d5..cb1b235815 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/PleaseRecruitMeCommandTest.scala @@ -1,22 +1,12 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{GameId, RoundId} -import net.eagle0.eagle.library.settings.{ - QuestFailedRecruitmentPenalty, - QuestRecruitmentBonus, - StartingLoyalty -} +import net.eagle0.eagle.library.settings.{QuestFailedRecruitmentPenalty, QuestRecruitmentBonus, StartingLoyalty} import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC -} -import net.eagle0.eagle.model.action_result.types.{ - QuestFailedResultType, - QuestFulfilledResultType -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC} +import net.eagle0.eagle.model.action_result.types.{QuestFailedResultType, QuestFulfilledResultType} import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.hero.PleaseRecruitMeBackstoryEvent import net.eagle0.eagle.model.state.province.concrete.ProvinceC @@ -27,28 +17,19 @@ import net.eagle0.eagle.model.state.quest.concrete.{ ReleasePrisonerQuest, ReturnPrisonerQuest } -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Resident, - Traveler -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Resident, Traveler} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class PleaseRecruitMeCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class PleaseRecruitMeCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val questFailedRecruitmentPenalty = -50 - private val questRecruitmentBonus = 250 + private val questRecruitmentBonus = 250 override def beforeEach(): Unit = { StartingLoyalty.setDoubleValue(70) @@ -56,7 +37,7 @@ class PleaseRecruitMeCommandTest QuestRecruitmentBonus.setDoubleValue(questRecruitmentBonus) } - private val actingFactionId = 13 + private val actingFactionId = 13 private val actingProvinceId = 9 private val questFulfillmentChecker = new QuestFulfillmentChecker( @@ -66,7 +47,7 @@ class PleaseRecruitMeCommandTest previousBackstoryTextIdLookup = _ => "backstoryUpdate" ) - private val province = ProvinceC( + private val province = ProvinceC( id = actingProvinceId, rulingFactionId = Some(actingFactionId), unaffiliatedHeroes = Vector( @@ -85,13 +66,13 @@ class PleaseRecruitMeCommandTest ) private val pleaseRecruitableHeroIds = Vector(18, 14) - private val currentDate = Date(month = Date.Month.April, year = 98) + private val currentDate = Date(month = Date.Month.April, year = 98) private val currentRoundId: RoundId = 897 - private val gameId: GameId = 0xfeedface + private val gameId: GameId = 0xfeedface private val previousBackstoryTextId = "backstoryUpdate-14-897-1" "make" should "throw if the selected UH is not among available" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy PleaseRecruitMeCommand.make( actingFactionId = actingFactionId, pleaseRecruitableHeroIds = pleaseRecruitableHeroIds, @@ -105,7 +86,6 @@ class PleaseRecruitMeCommandTest previousBackstoryTextId = previousBackstoryTextId, questFulfillmentChecker = questFulfillmentChecker ) - } ex.getMessage shouldBe "requirement failed: Selected hero 21 was not among available Vector(18, 14)" } @@ -314,16 +294,18 @@ class PleaseRecruitMeCommandTest ) .results - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFailedResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -375,16 +357,18 @@ class PleaseRecruitMeCommandTest ) .results - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFailedResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -436,16 +420,18 @@ class PleaseRecruitMeCommandTest ) .results - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFulfilledResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.WouldJoin, - factionBiases = Map(actingFactionId -> questRecruitmentBonus) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFulfilledResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.WouldJoin, + factionBiases = Map(actingFactionId -> questRecruitmentBonus) + ) + } } } @@ -499,16 +485,18 @@ class PleaseRecruitMeCommandTest ) .results - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFailedResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) + ) + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RansomCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RansomCommandTest.scala index 2de6b10ba5..8ef0c0140c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RansomCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RansomCommandTest.scala @@ -22,13 +22,10 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class RansomCommandTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class RansomCommandTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - val actingProvinceId: ProvinceId = 17 - val actingFactionId: FactionId = 4 + val actingProvinceId: ProvinceId = 17 + val actingFactionId: FactionId = 4 val availableCommand: RansomAvailableCommand = RansomAvailableCommand( actingProvinceId = actingProvinceId, prisonersToBeRansomed = Vector( @@ -130,14 +127,13 @@ class RansomCommandTest "make" should "throw if no hero to ransom is selected" in { val sc = selectedCommand.clearPrisonerToBeRansomed - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy RansomCommand.make( actingFactionId = actingFactionId, gameState = gameState, availableCommand = availableCommand, selectedCommand = sc ) - } ex.getMessage shouldBe "requirement failed: Must select a prisoner to ransom" } @@ -150,14 +146,13 @@ class RansomCommandTest ) ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy RansomCommand.make( actingFactionId = actingFactionId, gameState = gameState, availableCommand = availableCommand, selectedCommand = sc ) - } ex.getMessage shouldBe "requirement failed: Selected prisoner to ransom PrisonerToBeRansomed(94,17) is not among available Vector(PrisonerToBeRansomed(93,13), PrisonerToBeRansomed(95,15), PrisonerToBeRansomed(97,17))" } @@ -178,14 +173,13 @@ class RansomCommandTest ) ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy RansomCommand.make( actingFactionId = actingFactionId, gameState = gameState, availableCommand = availableCommand, selectedCommand = sc ) - } ex.getMessage shouldBe "requirement failed: Offered prisoners Vector(20, 17) are not all among available Vector(19, 17)" } @@ -204,14 +198,13 @@ class RansomCommandTest ) ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy RansomCommand.make( actingFactionId = actingFactionId, gameState = gameState, availableCommand = availableCommand, selectedCommand = sc ) - } ex.getMessage shouldBe "requirement failed: Offered hostages Vector(4, 2) are not all among available Vector(4)" } @@ -219,14 +212,13 @@ class RansomCommandTest it should "throw if the gold selected is more than available" in { val sc = selectedCommand.withGoldOffered(6163) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy RansomCommand.make( actingFactionId = actingFactionId, gameState = gameState, availableCommand = availableCommand, selectedCommand = sc ) - } ex.getMessage shouldBe "requirement failed: Tried to send 6163 gold but only 6162 available" } @@ -234,14 +226,13 @@ class RansomCommandTest it should "throw if the gold selected is negative" in { val sc = selectedCommand.withGoldOffered(-51) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy RansomCommand.make( actingFactionId = actingFactionId, gameState = gameState, availableCommand = availableCommand, selectedCommand = sc ) - } ex.getMessage shouldBe "requirement failed: Can't send negative gold" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommandTest.scala index 58a872b501..4c19283ae6 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReconCommandTest.scala @@ -1,35 +1,21 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.library.settings.{ - ReconAgilityXp, - ReconVigorCost, - ReconWisdomXp -} +import net.eagle0.eagle.library.settings.{ReconAgilityXp, ReconVigorCost, ReconWisdomXp} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.ReconStartedResultType import net.eagle0.eagle.model.action_result.ActionResultT -import net.eagle0.eagle.model.state.province.{ - IncomingEndTurnAction, - IncomingRecon -} +import net.eagle0.eagle.model.state.province.{IncomingEndTurnAction, IncomingRecon} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class ReconCommandTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class ReconCommandTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - private val actingProvinceId = 5 - private val availableHeroIds = Vector(1, 2, 3) + private val actingProvinceId = 5 + private val availableHeroIds = Vector(1, 2, 3) private val availableTargetProvinces = Vector(9, 10, 11) override def beforeEach(): Unit = { @@ -39,7 +25,7 @@ class ReconCommandTest } "make" should "throw if the acting hero is not in the available list" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ReconCommand.make( actingFactionId = 7, actingProvinceId = actingProvinceId, @@ -48,13 +34,12 @@ class ReconCommandTest availableHeroIds = availableHeroIds, availableTargetProvinces = availableTargetProvinces ) - } ex.getMessage shouldBe s"requirement failed: Acting hero 8 is not among available Vector(1, 2, 3)" } it should "throw if the destination province is not in the available list" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ReconCommand.make( actingFactionId = 7, actingProvinceId = actingProvinceId, @@ -63,7 +48,6 @@ class ReconCommandTest availableHeroIds = availableHeroIds, availableTargetProvinces = availableTargetProvinces ) - } ex.getMessage shouldBe s"requirement failed: Destination province 13 is not among available Vector(9, 10, 11)" } @@ -81,34 +65,35 @@ class ReconCommandTest ) .immediateExecute - inside(results) { case ar: ActionResultC => - ar.actionResultType shouldBe ReconStartedResultType - ar.actingFactionId shouldBe Some(7) - ar.provinceId shouldBe Some(5) - ar.changedHeroes shouldBe Vector( - ChangedHeroC( - heroId = 3, - vigorChange = StatDelta(-30), - agilityXpDelta = Some(20), - wisdomXpDelta = Some(10) + inside(results) { + case ar: ActionResultC => + ar.actionResultType shouldBe ReconStartedResultType + ar.actingFactionId shouldBe Some(7) + ar.provinceId shouldBe Some(5) + ar.changedHeroes shouldBe Vector( + ChangedHeroC( + heroId = 3, + vigorChange = StatDelta(-30), + agilityXpDelta = Some(20), + wisdomXpDelta = Some(10) + ) ) - ) - ar.changedProvinces shouldBe Vector( - ChangedProvinceC( - provinceId = 5, - removedRulingFactionHeroIds = Vector(3) - ), - ChangedProvinceC( - provinceId = 11, - newIncomingEndTurnActions = Vector( - IncomingEndTurnAction( - fromFactionId = 7, - fromProvinceId = 5, - details = IncomingRecon(heroId = 3) + ar.changedProvinces shouldBe Vector( + ChangedProvinceC( + provinceId = 5, + removedRulingFactionHeroIds = Vector(3) + ), + ChangedProvinceC( + provinceId = 11, + newIncomingEndTurnActions = Vector( + IncomingEndTurnAction( + fromFactionId = 7, + fromProvinceId = 5, + details = IncomingRecon(heroId = 3) + ) ) ) ) - ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommandTest.scala index d8debcb4e6..07fa5a9a4e 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RecruitHeroesCommandTest.scala @@ -1,18 +1,10 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.library.settings.{ - QuestFailedRecruitmentPenalty, - QuestRecruitmentBonus, - StartingLoyalty -} +import net.eagle0.eagle.library.settings.{QuestFailedRecruitmentPenalty, QuestRecruitmentBonus, StartingLoyalty} import net.eagle0.eagle.library.util.quest_fulfillment.QuestFulfillmentChecker import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatAbsolute -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatAbsolute} import net.eagle0.eagle.model.action_result.types.{ QuestFailedResultType, QuestFulfilledResultType, @@ -29,28 +21,22 @@ import net.eagle0.eagle.model.state.quest.concrete.{ } import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.RecruitmentInfo -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Resident, - Traveler -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Resident, Traveler} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class RecruitHeroesCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class RecruitHeroesCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val currentDate = Date(year = 2025, month = Date.Month.February) private val actingProvinceId = 8 - private val actingFactionId = 4 + private val actingFactionId = 4 private val rulingHeroId = 7 - private val hero1Id = 17 - private val hero2Id = 28 + private val hero1Id = 17 + private val hero2Id = 28 private val availableHeroIds = Vector(hero1Id, hero2Id) @@ -82,9 +68,9 @@ class RecruitHeroesCommandTest private val validSelectedHeroIds = Vector(hero2Id) - private val startingLoyalty = 80.0 + private val startingLoyalty = 80.0 private val questFailedRecruitmentPenalty = 50 - private val questRecruitmentBonus = 200 + private val questRecruitmentBonus = 200 override def beforeEach(): Unit = { StartingLoyalty.setDoubleValue(startingLoyalty) @@ -93,7 +79,7 @@ class RecruitHeroesCommandTest } "make" should "throw if the selected hero ID is not among the options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy RecruitHeroesCommand.make( actingFactionId = actingFactionId, currentDate = currentDate, @@ -103,7 +89,6 @@ class RecruitHeroesCommandTest allProvinces = Vector(province), questFulfillmentChecker = questFulfillmentChecker ) - } ex.getMessage shouldBe "requirement failed: Selected heroes Vector(9) was not a subset of Vector(17, 28)" } @@ -141,8 +126,9 @@ class RecruitHeroesCommandTest .results .loneElement - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.newFactionId shouldBe Some(actingFactionId) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.newFactionId shouldBe Some(actingFactionId) } } @@ -160,8 +146,9 @@ class RecruitHeroesCommandTest .results .loneElement - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.loyaltyChange shouldBe StatAbsolute(startingLoyalty) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.loyaltyChange shouldBe StatAbsolute(startingLoyalty) } } @@ -179,14 +166,15 @@ class RecruitHeroesCommandTest .results .loneElement - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - inside(ch.newEventsForHeroBackstory.loneElement) { - case e: RecruitedBackstoryEvent => - e.date shouldBe currentDate - e.recruitedByFactionId shouldBe actingFactionId - e.recruitedByHeroId shouldBe rulingHeroId - e.recruitedInProvinceId shouldBe actingProvinceId - } + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + inside(ch.newEventsForHeroBackstory.loneElement) { + case e: RecruitedBackstoryEvent => + e.date shouldBe currentDate + e.recruitedByFactionId shouldBe actingFactionId + e.recruitedByHeroId shouldBe rulingHeroId + e.recruitedInProvinceId shouldBe actingProvinceId + } } } @@ -204,8 +192,9 @@ class RecruitHeroesCommandTest .results .loneElement - inside(result.changedProvinces.loneElement) { case ch: ChangedProvinceC => - ch.newRulingFactionHeroIds shouldBe Vector(hero2Id) + inside(result.changedProvinces.loneElement) { + case ch: ChangedProvinceC => + ch.newRulingFactionHeroIds shouldBe Vector(hero2Id) } } @@ -223,8 +212,9 @@ class RecruitHeroesCommandTest .results .loneElement - inside(result.changedProvinces.loneElement) { case ch: ChangedProvinceC => - ch.removedUnaffiliatedHeroIds shouldBe Vector(hero2Id) + inside(result.changedProvinces.loneElement) { + case ch: ChangedProvinceC => + ch.removedUnaffiliatedHeroIds shouldBe Vector(hero2Id) } } @@ -242,8 +232,9 @@ class RecruitHeroesCommandTest .results .loneElement - inside(result.changedProvinces.loneElement) { case ch: ChangedProvinceC => - ch.setHasActed shouldBe empty + inside(result.changedProvinces.loneElement) { + case ch: ChangedProvinceC => + ch.setHasActed shouldBe empty } } @@ -291,16 +282,18 @@ class RecruitHeroesCommandTest .results results should have size 2 - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFailedResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -348,16 +341,18 @@ class RecruitHeroesCommandTest .results results should have size 2 - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFailedResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) + ) + } } } @@ -405,16 +400,18 @@ class RecruitHeroesCommandTest .results results should have size 2 - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFulfilledResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Resident, - recruitmentInfo = RecruitmentInfo.WouldJoin, - factionBiases = Map(actingFactionId -> questRecruitmentBonus) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFulfilledResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Resident, + recruitmentInfo = RecruitmentInfo.WouldJoin, + factionBiases = Map(actingFactionId -> questRecruitmentBonus) + ) + } } } @@ -464,16 +461,18 @@ class RecruitHeroesCommandTest .results results should have size 2 - inside(results.last) { case ar: ActionResultC => - ar.actionResultType shouldBe QuestFailedResultType - inside(ar.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( - heroId = 983, - unaffiliatedHeroType = Traveler, - recruitmentInfo = RecruitmentInfo.Traveler, - factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) - ) - } + inside(results.last) { + case ar: ActionResultC => + ar.actionResultType shouldBe QuestFailedResultType + inside(ar.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.changedUnaffiliatedHeroes.loneElement shouldBe UnaffiliatedHeroC( + heroId = 983, + unaffiliatedHeroType = Traveler, + recruitmentInfo = RecruitmentInfo.Traveler, + factionBiases = Map(actingFactionId -> -questFailedRecruitmentPenalty) + ) + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommandTest.scala index e4186a8251..7209fc4c92 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveAllianceOfferCommandTest.scala @@ -3,11 +3,7 @@ import net.eagle0.eagle.{FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.concrete.ChangedFactionC import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected} import net.eagle0.eagle.model.state.diplomacy_offer.AllianceOffer import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -15,13 +11,13 @@ import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { - private val actingFactionId: FactionId = 4 - private val originatingFactionId: FactionId = 8 - private val messengerHeroId: HeroId = 29 + private val actingFactionId: FactionId = 4 + private val originatingFactionId: FactionId = 8 + private val messengerHeroId: HeroId = 29 private val messengerOriginProvinceId: ProvinceId = 2 - private val gameId: GameId = 0xfeed - private val currentRoundId: RoundId = 873 - private val allianceOffer = AllianceOffer( + private val gameId: GameId = 0xfeed + private val currentRoundId: RoundId = 873 + private val allianceOffer = AllianceOffer( originatingFactionId = originatingFactionId, targetFactionId = actingFactionId, messengerHeroId = messengerHeroId, @@ -43,7 +39,7 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { } it should "throw if the selected resolution was not available in the alliance offer" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveAllianceOfferCommand.make( actingFactionId = actingFactionId, allianceOffer = allianceOffer, @@ -52,7 +48,6 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Selected alliance resolution Accepted was not among options Vector(Rejected, Imprisoned)" } @@ -65,7 +60,7 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute result.actionResultType shouldBe OfferResolvedResultType } @@ -78,15 +73,16 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute val changedFaction = result.changedFactions.head changedFaction.factionId shouldBe actingFactionId - inside(changedFaction) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - cf.newIncomingDiplomacyOffers.head.status shouldBe Accepted + inside(changedFaction) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + cf.newIncomingDiplomacyOffers.head.status shouldBe Accepted } } @@ -99,7 +95,7 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute result.actionResultType shouldBe OfferResolvedResultType } @@ -112,15 +108,16 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute val changedFaction = result.changedFactions.head changedFaction.factionId shouldBe actingFactionId - inside(changedFaction) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - cf.newIncomingDiplomacyOffers.head.status shouldBe Rejected + inside(changedFaction) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + cf.newIncomingDiplomacyOffers.head.status shouldBe Rejected } } @@ -133,7 +130,7 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute result.actionResultType shouldBe OfferResolvedResultType } @@ -146,15 +143,16 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute val changedFaction = result.changedFactions.head changedFaction.factionId shouldBe actingFactionId - inside(changedFaction) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - cf.newIncomingDiplomacyOffers.head.status shouldBe Imprisoned + inside(changedFaction) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + cf.newIncomingDiplomacyOffers.head.status shouldBe Imprisoned } } @@ -167,7 +165,7 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val acceptedResult = acceptedCommand.immediateExecute + val acceptedResult = acceptedCommand.immediateExecute acceptedResult.newNotifications.loneElement.affectedHeroIds should contain( messengerHeroId @@ -181,7 +179,7 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val rejectedResult = rejectedCommand.immediateExecute + val rejectedResult = rejectedCommand.immediateExecute rejectedResult.newNotifications.loneElement.affectedHeroIds should contain( messengerHeroId @@ -197,7 +195,7 @@ class ResolveAllianceOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute val llmRequest = result.newGeneratedTextRequests.loneElement llmRequest.requestId shouldBe s"$currentRoundId resolve alliance offer $messengerHeroId" diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommandTest.scala index 5609e13005..ee5e83a462 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveBreakAllianceCommandTest.scala @@ -1,18 +1,11 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.library.{EagleClientException, EagleCommandException} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.BreakAllianceResolutionMessage import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType import net.eagle0.eagle.model.action_result.NotificationDetails -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected} import net.eagle0.eagle.model.state.diplomacy_offer.BreakAlliance import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -20,14 +13,11 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ResolveBreakAllianceCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ResolveBreakAllianceCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val actingFactionId = 4 - val gameId = 0xfeed - val currentRoundId = 873 + val gameId = 0xfeed + val currentRoundId = 873 private val firstBreakAllianceOffer = BreakAlliance( originatingFactionId = 8, @@ -39,7 +29,7 @@ class ResolveBreakAllianceCommandTest ) private val availableOriginatingFactionIds = Vector(3, 8) - private val availableResolutions = Vector(Accepted, Rejected, Imprisoned) + private val availableResolutions = Vector(Accepted, Rejected, Imprisoned) "execute with resolution ACCEPT" should "return a result of type OFFER_RESOLVED" in { val result = ResolveBreakAllianceCommand @@ -68,17 +58,19 @@ class ResolveBreakAllianceCommandTest ) .immediateExecute - inside(ar) { case result: ActionResultC => - val actingFactionAfter = result.changedFactions - .find(_.factionId == actingFactionId) - .get + inside(ar) { + case result: ActionResultC => + val actingFactionAfter = result.changedFactions + .find(_.factionId == actingFactionId) + .get - inside(actingFactionAfter) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector(8) - cf.newIncomingDiplomacyOffers shouldBe Vector( - firstBreakAllianceOffer.copy(status = Accepted) - ) - } + inside(actingFactionAfter) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector(8) + cf.newIncomingDiplomacyOffers shouldBe Vector( + firstBreakAllianceOffer.copy(status = Accepted) + ) + } } } @@ -94,16 +86,17 @@ class ResolveBreakAllianceCommandTest ) .immediateExecute - inside(ar) { case result: ActionResultC => - result.newNotifications should have size 1 - val notification = result.newNotifications.head - notification.details shouldBe NotificationDetails.BreakAllianceAccepted( - offeringFactionId = 8, - targetFactionId = actingFactionId, - ambassadorHeroId = 29 - ) - notification.affectedHeroIds shouldBe Vector(29) - notification.deferred shouldBe true + inside(ar) { + case result: ActionResultC => + result.newNotifications should have size 1 + val notification = result.newNotifications.head + notification.details shouldBe NotificationDetails.BreakAllianceAccepted( + offeringFactionId = 8, + targetFactionId = actingFactionId, + ambassadorHeroId = 29 + ) + notification.affectedHeroIds shouldBe Vector(29) + notification.deferred shouldBe true } } @@ -119,23 +112,24 @@ class ResolveBreakAllianceCommandTest ) .immediateExecute - inside(ar) { case result: ActionResultC => - result.newGeneratedTextRequests should have size 1 + inside(ar) { + case result: ActionResultC => + result.newGeneratedTextRequests should have size 1 - inside(result.newGeneratedTextRequests.head) { - case llmRequest: BreakAllianceResolutionMessage => - llmRequest.requestId shouldBe s"$currentRoundId resolve break alliance 29" - llmRequest.eagleGameId shouldBe gameId - llmRequest.breakingFactionId shouldBe 8 - llmRequest.targetFactionId shouldBe actingFactionId - llmRequest.messengerHeroId shouldBe 29 - llmRequest.resolution shouldBe Accepted - } + inside(result.newGeneratedTextRequests.head) { + case llmRequest: BreakAllianceResolutionMessage => + llmRequest.requestId shouldBe s"$currentRoundId resolve break alliance 29" + llmRequest.eagleGameId shouldBe gameId + llmRequest.breakingFactionId shouldBe 8 + llmRequest.targetFactionId shouldBe actingFactionId + llmRequest.messengerHeroId shouldBe 29 + llmRequest.resolution shouldBe Accepted + } } } "execute with resolution REJECT" should "throw an exception" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveBreakAllianceCommand .make( actingFactionId = actingFactionId, @@ -146,7 +140,6 @@ class ResolveBreakAllianceCommandTest currentRoundId = currentRoundId ) .immediateExecute - } ex.getMessage shouldBe "REJECTED not valid for break alliance" } @@ -154,7 +147,7 @@ class ResolveBreakAllianceCommandTest it should "throw if the selected resolution was not an option" in { val limitedResolutions = Vector(Accepted, Rejected) // No Imprisoned - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy ResolveBreakAllianceCommand.make( actingFactionId = actingFactionId, breakAllianceOffer = firstBreakAllianceOffer, @@ -163,7 +156,6 @@ class ResolveBreakAllianceCommandTest gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Selected break alliance resolution Imprisoned was not among options Vector(Accepted, Rejected)" } @@ -195,17 +187,19 @@ class ResolveBreakAllianceCommandTest ) .immediateExecute - inside(ar) { case result: ActionResultC => - val actingFactionAfter = result.changedFactions - .find(_.factionId == actingFactionId) - .get + inside(ar) { + case result: ActionResultC => + val actingFactionAfter = result.changedFactions + .find(_.factionId == actingFactionId) + .get - inside(actingFactionAfter) { case cf: ChangedFactionC => - cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector(8) - cf.newIncomingDiplomacyOffers shouldBe Vector( - firstBreakAllianceOffer.copy(status = Imprisoned) - ) - } + inside(actingFactionAfter) { + case cf: ChangedFactionC => + cf.removedIncomingDiplomacyOfferFactionIds shouldBe Vector(8) + cf.newIncomingDiplomacyOffers shouldBe Vector( + firstBreakAllianceOffer.copy(status = Imprisoned) + ) + } } } @@ -222,16 +216,17 @@ class ResolveBreakAllianceCommandTest ) .immediateExecute - inside(ar) { case result: ActionResultC => - val notification = result.newNotifications.loneElement - notification.details shouldBe NotificationDetails - .BreakAllianceAmbassadorImprisoned( - offeringFactionId = 8, - targetFactionId = actingFactionId, - ambassadorHeroId = 29 - ) - notification.affectedHeroIds shouldBe Vector(29) - notification.deferred shouldBe true + inside(ar) { + case result: ActionResultC => + val notification = result.newNotifications.loneElement + notification.details shouldBe NotificationDetails + .BreakAllianceAmbassadorImprisoned( + offeringFactionId = 8, + targetFactionId = actingFactionId, + ambassadorHeroId = 29 + ) + notification.affectedHeroIds shouldBe Vector(29) + notification.deferred shouldBe true } } @@ -247,16 +242,17 @@ class ResolveBreakAllianceCommandTest ) .immediateExecute - inside(ar) { case result: ActionResultC => - inside(result.newGeneratedTextRequests.loneElement) { - case llmRequest: BreakAllianceResolutionMessage => - llmRequest.requestId shouldBe s"$currentRoundId resolve break alliance 29" - llmRequest.eagleGameId shouldBe gameId - llmRequest.breakingFactionId shouldBe 8 - llmRequest.targetFactionId shouldBe actingFactionId - llmRequest.messengerHeroId shouldBe 29 - llmRequest.resolution shouldBe Imprisoned - } + inside(ar) { + case result: ActionResultC => + inside(result.newGeneratedTextRequests.loneElement) { + case llmRequest: BreakAllianceResolutionMessage => + llmRequest.requestId shouldBe s"$currentRoundId resolve break alliance 29" + llmRequest.eagleGameId shouldBe gameId + llmRequest.breakingFactionId shouldBe 8 + llmRequest.targetFactionId shouldBe actingFactionId + llmRequest.messengerHeroId shouldBe 29 + llmRequest.resolution shouldBe Imprisoned + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommandTest.scala index 40ecbd3448..b899bace1f 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveInvitationCommandTest.scala @@ -1,17 +1,9 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC} import net.eagle0.eagle.model.action_result.types.InvitationResolvedResultType import net.eagle0.eagle.model.state.diplomacy_offer.{DiplomacyOffer, Invitation} -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Invalidated, - Rejected -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Invalidated, Rejected} import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionT import net.eagle0.eagle.FactionId @@ -21,10 +13,10 @@ import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class ResolveInvitationCommandTest extends AnyFlatSpec with Matchers { - private val actingFactionId = 4 + private val actingFactionId = 4 private val originatingFactionId = 8 - private val currentRoundId = 873 - private val gameId = 0xfeed + private val currentRoundId = 873 + private val gameId = 0xfeed private val invitation = Invitation( originatingFactionId = originatingFactionId, @@ -87,10 +79,10 @@ class ResolveInvitationCommandTest extends AnyFlatSpec with Matchers { ) private val allFactions: Map[Int, FactionT] = Map( - actingFactionId -> acceptingFaction, + actingFactionId -> acceptingFaction, originatingFactionId -> originatingFaction, - 15 -> secondOfferFaction, - 10 -> targetOfOutgoingFaction + 15 -> secondOfferFaction, + 10 -> targetOfOutgoingFaction ) "execute with Accepted" should "return a result of type InvitationResolvedResultType" in { @@ -103,11 +95,12 @@ class ResolveInvitationCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe InvitationResolvedResultType - ar.actingFactionId shouldBe Some(actingFactionId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe InvitationResolvedResultType + ar.actingFactionId shouldBe Some(actingFactionId) } } @@ -121,42 +114,45 @@ class ResolveInvitationCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - // Should have 2 changed factions: accepting faction + target of outgoing faction - ar.changedFactions should have length 2 + inside(result) { + case ar: ActionResultC => + // Should have 2 changed factions: accepting faction + target of outgoing faction + ar.changedFactions should have length 2 - // Find the accepting faction change - val acceptingFactionChange = - ar.changedFactions.find(_.factionId == actingFactionId).get - inside(acceptingFactionChange) { case faction: ChangedFactionC => - faction.removedIncomingDiplomacyOfferFactionIds.shouldBe( - Vector( - originatingFactionId, - 15 // Second invitation faction ID - ) - ) - faction.newIncomingDiplomacyOffers.shouldBe( - Vector[DiplomacyOffer]( - invitation.copy(status = Accepted), - secondInvitation.copy(status = Invalidated) - ) - ) - } + // Find the accepting faction change + val acceptingFactionChange = + ar.changedFactions.find(_.factionId == actingFactionId).get + inside(acceptingFactionChange) { + case faction: ChangedFactionC => + faction.removedIncomingDiplomacyOfferFactionIds.shouldBe( + Vector( + originatingFactionId, + 15 // Second invitation faction ID + ) + ) + faction.newIncomingDiplomacyOffers.shouldBe( + Vector[DiplomacyOffer]( + invitation.copy(status = Accepted), + secondInvitation.copy(status = Invalidated) + ) + ) + } - // Find the target of outgoing faction change (faction 10) - val outgoingTargetChange = ar.changedFactions.find(_.factionId == 10).get - inside(outgoingTargetChange) { case faction: ChangedFactionC => - faction.removedIncomingDiplomacyOfferFactionIds.shouldBe( - Vector(actingFactionId) - ) - faction.newIncomingDiplomacyOffers.shouldBe( - Vector[DiplomacyOffer]( - outgoingOffer.copy(status = Invalidated) - ) - ) - } + // Find the target of outgoing faction change (faction 10) + val outgoingTargetChange = ar.changedFactions.find(_.factionId == 10).get + inside(outgoingTargetChange) { + case faction: ChangedFactionC => + faction.removedIncomingDiplomacyOfferFactionIds.shouldBe( + Vector(actingFactionId) + ) + faction.newIncomingDiplomacyOffers.shouldBe( + Vector[DiplomacyOffer]( + outgoingOffer.copy(status = Invalidated) + ) + ) + } } } @@ -170,11 +166,12 @@ class ResolveInvitationCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe InvitationResolvedResultType - ar.actingFactionId shouldBe Some(actingFactionId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe InvitationResolvedResultType + ar.actingFactionId shouldBe Some(actingFactionId) } } @@ -188,20 +185,22 @@ class ResolveInvitationCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedFactions.loneElement) { case faction: ChangedFactionC => - faction.factionId shouldBe actingFactionId - faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - faction.newIncomingDiplomacyOffers.shouldBe( - Vector[DiplomacyOffer]( - invitation.copy(status = Rejected) - ) - ) - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedFactions.loneElement) { + case faction: ChangedFactionC => + faction.factionId shouldBe actingFactionId + faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + faction.newIncomingDiplomacyOffers.shouldBe( + Vector[DiplomacyOffer]( + invitation.copy(status = Rejected) + ) + ) + } } } @@ -215,19 +214,21 @@ class ResolveInvitationCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - // Should invalidate outgoing offers from accepting faction - val outgoingTargetChange = ar.changedFactions.find(_.factionId == 10) - outgoingTargetChange.shouldBe(defined) - inside(outgoingTargetChange.get) { case faction: ChangedFactionC => - faction.newIncomingDiplomacyOffers.should( - contain( - outgoingOffer.copy(status = Invalidated): DiplomacyOffer - ) - ) - } + inside(result) { + case ar: ActionResultC => + // Should invalidate outgoing offers from accepting faction + val outgoingTargetChange = ar.changedFactions.find(_.factionId == 10) + outgoingTargetChange.shouldBe(defined) + inside(outgoingTargetChange.get) { + case faction: ChangedFactionC => + faction.newIncomingDiplomacyOffers.should( + contain( + outgoingOffer.copy(status = Invalidated): DiplomacyOffer + ) + ) + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommandTest.scala index 2ac377eaef..f7fc53c731 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveRansomOfferCommandTest.scala @@ -1,15 +1,9 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.library.EagleCommandException -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC} import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType -import net.eagle0.eagle.model.state.diplomacy_offer.{ - DiplomacyOffer, - RansomOffer -} +import net.eagle0.eagle.model.state.diplomacy_offer.{DiplomacyOffer, RansomOffer} import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Rejected} import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionT @@ -20,10 +14,10 @@ import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { - private val actingFactionId = 4 + private val actingFactionId = 4 private val originatingFactionId = 8 - private val currentRoundId = 873 - private val gameId = 0xfeed + private val currentRoundId = 873 + private val gameId = 0xfeed import net.eagle0.eagle.model.state.diplomacy_offer.RansomOfferDetails.* @@ -71,7 +65,7 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { ) private val allFactions: Map[Int, FactionT] = Map( - actingFactionId -> acceptingFaction, + actingFactionId -> acceptingFaction, originatingFactionId -> originatingFaction ) @@ -85,11 +79,12 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe OfferResolvedResultType - ar.actingFactionId shouldBe Some(actingFactionId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe OfferResolvedResultType + ar.actingFactionId shouldBe Some(actingFactionId) } } @@ -103,20 +98,22 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedFactions.loneElement) { case faction: ChangedFactionC => - faction.factionId shouldBe actingFactionId - faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - faction.newIncomingDiplomacyOffers.shouldBe( - Vector[DiplomacyOffer]( - ransomOffer.copy(status = Accepted) - ) - ) - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedFactions.loneElement) { + case faction: ChangedFactionC => + faction.factionId shouldBe actingFactionId + faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + faction.newIncomingDiplomacyOffers.shouldBe( + Vector[DiplomacyOffer]( + ransomOffer.copy(status = Accepted) + ) + ) + } } } @@ -130,11 +127,12 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe OfferResolvedResultType - ar.actingFactionId shouldBe Some(actingFactionId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe OfferResolvedResultType + ar.actingFactionId shouldBe Some(actingFactionId) } } @@ -148,20 +146,22 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - val result = command.immediateExecute + val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedFactions.loneElement) { case faction: ChangedFactionC => - faction.factionId shouldBe actingFactionId - faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - faction.newIncomingDiplomacyOffers.shouldBe( - Vector[DiplomacyOffer]( - ransomOffer.copy(status = Rejected) - ) - ) - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedFactions.loneElement) { + case faction: ChangedFactionC => + faction.factionId shouldBe actingFactionId + faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + faction.newIncomingDiplomacyOffers.shouldBe( + Vector[DiplomacyOffer]( + ransomOffer.copy(status = Rejected) + ) + ) + } } } @@ -171,7 +171,7 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { originatingFactionId -> originatingFaction ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveRansomOfferCommand.make( actingFactionId = actingFactionId, originatingFactionId = originatingFactionId, @@ -181,7 +181,6 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage should include( s"Acting faction $actingFactionId not found in faction data" @@ -198,11 +197,11 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { ) val factionsWithoutRansomOffer = Map( - actingFactionId -> actingFactionWithoutRansomOffer, + actingFactionId -> actingFactionWithoutRansomOffer, originatingFactionId -> originatingFaction ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveRansomOfferCommand.make( actingFactionId = actingFactionId, originatingFactionId = originatingFactionId, @@ -212,7 +211,6 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage should include( s"Ransom offer from faction $originatingFactionId not found" @@ -220,7 +218,7 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { } it should "throw when ransom offer from different originating faction exists" in { - val differentOriginatingFactionId = 999 + val differentOriginatingFactionId = 999 val ransomOfferFromDifferentFaction = ransomOffer.copy(originatingFactionId = differentOriginatingFactionId) @@ -233,11 +231,11 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { ) val factionsWithWrongRansomOffer = Map( - actingFactionId -> actingFactionWithDifferentRansomOffer, + actingFactionId -> actingFactionWithDifferentRansomOffer, originatingFactionId -> originatingFaction ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveRansomOfferCommand.make( actingFactionId = actingFactionId, originatingFactionId = originatingFactionId, @@ -247,7 +245,6 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage should include( s"Ransom offer from faction $originatingFactionId not found" @@ -264,22 +261,20 @@ class ResolveRansomOfferCommandTest extends AnyFlatSpec with Matchers { ) val factionsWithLimitedOffer = Map( - actingFactionId -> actingFactionWithLimitedOffer, + actingFactionId -> actingFactionWithLimitedOffer, originatingFactionId -> originatingFaction ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveRansomOfferCommand.make( actingFactionId = actingFactionId, originatingFactionId = originatingFactionId, - resolution = - Rejected, // Not allowed since availableResolutions only contains Accepted + resolution = Rejected, // Not allowed since availableResolutions only contains Accepted allFactions = factionsWithLimitedOffer, availableResolutions = Vector(Accepted), gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage should include( s"Selected ransom offer resolution $Rejected was not among options Vector($Accepted)" diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommandTest.scala index a36b086d78..fae4726e5d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTributeCommandTest.scala @@ -2,28 +2,15 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, GameId, ProvinceId, RoundId} import net.eagle0.eagle.library.EagleCommandException -import net.eagle0.eagle.model.action_result.changed_province.concrete.{ - ChangedProvinceC, - HostileArmyStatusChange -} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC -} -import net.eagle0.eagle.model.action_result.types.{ - TributePaidResultType, - TributeRefusedResultType -} +import net.eagle0.eagle.model.action_result.changed_province.concrete.{ChangedProvinceC, HostileArmyStatusChange} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC} +import net.eagle0.eagle.model.action_result.types.{TributePaidResultType, TributeRefusedResultType} import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.faction.FactionRelationship import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.ProvinceT import net.eagle0.eagle.model.state.HostileArmyGroup -import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{ - Attacking, - TributeDemanded, - TributePaid -} +import net.eagle0.eagle.model.state.HostileArmyGroupStatus.{Attacking, TributeDemanded, TributePaid} import net.eagle0.eagle.model.state.TributeAmount import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -31,14 +18,14 @@ import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { - private val actingFactionId: FactionId = 12 + private val actingFactionId: FactionId = 12 private val demandingFactionId: FactionId = 7 - private val actingProvinceId: ProvinceId = 22 - private val gameId: GameId = 0xfeed - private val currentRoundId: RoundId = 873 - private val currentDate = Date(year = 1425, month = Date.Month.June) + private val actingProvinceId: ProvinceId = 22 + private val gameId: GameId = 0xfeed + private val currentRoundId: RoundId = 873 + private val currentDate = Date(year = 1425, month = Date.Month.June) - private val tributeAmount = TributeAmount(gold = 500, food = 300) + private val tributeAmount = TributeAmount(gold = 500, food = 300) private val availableDemandingFactionIds = Vector(demandingFactionId, 15, 20) "make" should "successfully create command when paying tribute with sufficient resources" in { @@ -82,7 +69,7 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { it should "throw when demanding faction ID is not in available list" in { val invalidDemandingFactionId = 999 - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveTributeCommand.make( actingFactionId = actingFactionId, demandingFactionId = invalidDemandingFactionId, @@ -97,7 +84,6 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { currentDate = currentDate, allProvinces = Vector.empty ) - } ex.getMessage should include( s"Selected demanding faction ID $invalidDemandingFactionId was not among options $availableDemandingFactionIds" @@ -105,7 +91,7 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { } it should "throw when paying tribute but insufficient gold" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveTributeCommand.make( actingFactionId = actingFactionId, demandingFactionId = demandingFactionId, @@ -120,7 +106,6 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { currentDate = currentDate, allProvinces = Vector.empty ) - } ex.getMessage should include( s"Not enough gold to pay tribute: have 400, need ${tributeAmount.gold}" @@ -128,7 +113,7 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { } it should "throw when paying tribute but insufficient food" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveTributeCommand.make( actingFactionId = actingFactionId, demandingFactionId = demandingFactionId, @@ -143,7 +128,6 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { currentDate = currentDate, allProvinces = Vector.empty ) - } ex.getMessage should include( s"Not enough food to pay tribute: have 200, need ${tributeAmount.food}" @@ -168,9 +152,10 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe TributePaidResultType - ar.actingFactionId shouldBe Some(actingFactionId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe TributePaidResultType + ar.actingFactionId shouldBe Some(actingFactionId) } } @@ -192,13 +177,14 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedProvinces.loneElement) { - case province: ChangedProvinceC => - province.provinceId shouldBe actingProvinceId - province.goldDelta shouldBe Some(-tributeAmount.gold) - province.foodDelta shouldBe Some(-tributeAmount.food) - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedProvinces.loneElement) { + case province: ChangedProvinceC => + province.provinceId shouldBe actingProvinceId + province.goldDelta shouldBe Some(-tributeAmount.gold) + province.foodDelta shouldBe Some(-tributeAmount.food) + } } } @@ -220,9 +206,10 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe TributeRefusedResultType - ar.actingFactionId shouldBe Some(actingFactionId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe TributeRefusedResultType + ar.actingFactionId shouldBe Some(actingFactionId) } } @@ -244,13 +231,14 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedProvinces.loneElement) { - case province: ChangedProvinceC => - province.provinceId shouldBe actingProvinceId - province.goldDelta shouldBe None - province.foodDelta shouldBe None - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedProvinces.loneElement) { + case province: ChangedProvinceC => + province.provinceId shouldBe actingProvinceId + province.goldDelta shouldBe None + province.foodDelta shouldBe None + } } } @@ -272,15 +260,16 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedProvinces.loneElement) { - case province: ChangedProvinceC => - inside(province.hostileArmyStatusChanges.loneElement) { - case statusChange: HostileArmyStatusChange => - statusChange.factionId shouldBe demandingFactionId - statusChange.newStatus shouldBe TributePaid(tributeAmount) - } - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedProvinces.loneElement) { + case province: ChangedProvinceC => + inside(province.hostileArmyStatusChanges.loneElement) { + case statusChange: HostileArmyStatusChange => + statusChange.factionId shouldBe demandingFactionId + statusChange.newStatus shouldBe TributePaid(tributeAmount) + } + } } } @@ -302,33 +291,33 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.changedFactions should have size 2 + inside(result) { + case ar: ActionResultC => + ar.changedFactions should have size 2 - // Check the paying faction's relationship - val payingFactionChange = ar.changedFactions.collectFirst { - case faction: ChangedFactionC if faction.factionId == actingFactionId => - faction - }.get - payingFactionChange.changedFactionRelationships should have size 1 - val payingRelationship = - payingFactionChange.changedFactionRelationships.head - payingRelationship.targetFactionId shouldBe demandingFactionId - payingRelationship.relationshipLevel shouldBe FactionRelationship.RelationshipLevel.Truce - payingRelationship.resetDate shouldBe Some(currentDate.addMonths(12)) + // Check the paying faction's relationship + val payingFactionChange = ar.changedFactions.collectFirst { + case faction: ChangedFactionC if faction.factionId == actingFactionId => + faction + }.get + payingFactionChange.changedFactionRelationships should have size 1 + val payingRelationship = + payingFactionChange.changedFactionRelationships.head + payingRelationship.targetFactionId shouldBe demandingFactionId + payingRelationship.relationshipLevel shouldBe FactionRelationship.RelationshipLevel.Truce + payingRelationship.resetDate shouldBe Some(currentDate.addMonths(12)) - // Check the demanding faction's relationship - val demandingFactionChange = ar.changedFactions.collectFirst { - case faction: ChangedFactionC - if faction.factionId == demandingFactionId => - faction - }.get - demandingFactionChange.changedFactionRelationships should have size 1 - val demandingRelationship = - demandingFactionChange.changedFactionRelationships.head - demandingRelationship.targetFactionId shouldBe actingFactionId - demandingRelationship.relationshipLevel shouldBe FactionRelationship.RelationshipLevel.Truce - demandingRelationship.resetDate shouldBe Some(currentDate.addMonths(12)) + // Check the demanding faction's relationship + val demandingFactionChange = ar.changedFactions.collectFirst { + case faction: ChangedFactionC if faction.factionId == demandingFactionId => + faction + }.get + demandingFactionChange.changedFactionRelationships should have size 1 + val demandingRelationship = + demandingFactionChange.changedFactionRelationships.head + demandingRelationship.targetFactionId shouldBe actingFactionId + demandingRelationship.relationshipLevel shouldBe FactionRelationship.RelationshipLevel.Truce + demandingRelationship.resetDate shouldBe Some(currentDate.addMonths(12)) } } @@ -350,24 +339,25 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedProvinces.loneElement) { - case province: ChangedProvinceC => - inside(province.hostileArmyStatusChanges.loneElement) { - case statusChange: HostileArmyStatusChange => - statusChange.factionId shouldBe demandingFactionId - statusChange.newStatus shouldBe Attacking - } - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedProvinces.loneElement) { + case province: ChangedProvinceC => + inside(province.hostileArmyStatusChanges.loneElement) { + case statusChange: HostileArmyStatusChange => + statusChange.factionId shouldBe demandingFactionId + statusChange.newStatus shouldBe Attacking + } + } } } it should "update hostile army status in other provinces ruled by acting faction when tribute is paid" in { // Create simple test provinces using ProvinceC - val otherProvinceId1: ProvinceId = 100 - val otherProvinceId2: ProvinceId = 200 + val otherProvinceId1: ProvinceId = 100 + val otherProvinceId2: ProvinceId = 200 val differentFactionProvinceId: ProvinceId = 300 - val otherFactionId: FactionId = 99 + val otherFactionId: FactionId = 99 // Create provinces with hostile armies from the demanding faction val mockProvince1 = ProvinceC( @@ -426,53 +416,57 @@ class ResolveTributeCommandTest extends AnyFlatSpec with Matchers { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - // Should have 3 changed provinces: the acting province + 2 other provinces with hostile armies - ar.changedProvinces should have size 3 + inside(result) { + case ar: ActionResultC => + // Should have 3 changed provinces: the acting province + 2 other provinces with hostile armies + ar.changedProvinces should have size 3 - // Find changes for the acting province (with resource deduction) - val actingProvinceChange = - ar.changedProvinces.find(_.provinceId == actingProvinceId).get - inside(actingProvinceChange) { case apc: ChangedProvinceC => - apc.goldDelta shouldBe Some(-tributeAmount.gold) - apc.foodDelta shouldBe Some(-tributeAmount.food) - apc.hostileArmyStatusChanges should have size 1 - apc.hostileArmyStatusChanges.head.factionId shouldBe demandingFactionId - apc.hostileArmyStatusChanges.head.newStatus shouldBe TributePaid( - tributeAmount - ) - } + // Find changes for the acting province (with resource deduction) + val actingProvinceChange = + ar.changedProvinces.find(_.provinceId == actingProvinceId).get + inside(actingProvinceChange) { + case apc: ChangedProvinceC => + apc.goldDelta shouldBe Some(-tributeAmount.gold) + apc.foodDelta shouldBe Some(-tributeAmount.food) + apc.hostileArmyStatusChanges should have size 1 + apc.hostileArmyStatusChanges.head.factionId shouldBe demandingFactionId + apc.hostileArmyStatusChanges.head.newStatus shouldBe TributePaid( + tributeAmount + ) + } - // Find changes for the first other province - val otherProvince1Change = - ar.changedProvinces.find(_.provinceId == otherProvinceId1).get - inside(otherProvince1Change) { case opc1: ChangedProvinceC => - opc1.goldDelta shouldBe None // No resource changes for other provinces - opc1.foodDelta shouldBe None - opc1.hostileArmyStatusChanges should have size 1 - opc1.hostileArmyStatusChanges.head.factionId shouldBe demandingFactionId - opc1.hostileArmyStatusChanges.head.newStatus shouldBe TributePaid( - TributeAmount(gold = 0, food = 0) - ) - } + // Find changes for the first other province + val otherProvince1Change = + ar.changedProvinces.find(_.provinceId == otherProvinceId1).get + inside(otherProvince1Change) { + case opc1: ChangedProvinceC => + opc1.goldDelta shouldBe None // No resource changes for other provinces + opc1.foodDelta shouldBe None + opc1.hostileArmyStatusChanges should have size 1 + opc1.hostileArmyStatusChanges.head.factionId shouldBe demandingFactionId + opc1.hostileArmyStatusChanges.head.newStatus shouldBe TributePaid( + TributeAmount(gold = 0, food = 0) + ) + } - // Find changes for the second other province - val otherProvince2Change = - ar.changedProvinces.find(_.provinceId == otherProvinceId2).get - inside(otherProvince2Change) { case opc2: ChangedProvinceC => - opc2.goldDelta shouldBe None // No resource changes for other provinces - opc2.foodDelta shouldBe None - opc2.hostileArmyStatusChanges should have size 1 - opc2.hostileArmyStatusChanges.head.factionId shouldBe demandingFactionId - opc2.hostileArmyStatusChanges.head.newStatus shouldBe TributePaid( - TributeAmount(gold = 0, food = 0) - ) - } + // Find changes for the second other province + val otherProvince2Change = + ar.changedProvinces.find(_.provinceId == otherProvinceId2).get + inside(otherProvince2Change) { + case opc2: ChangedProvinceC => + opc2.goldDelta shouldBe None // No resource changes for other provinces + opc2.foodDelta shouldBe None + opc2.hostileArmyStatusChanges should have size 1 + opc2.hostileArmyStatusChanges.head.factionId shouldBe demandingFactionId + opc2.hostileArmyStatusChanges.head.newStatus shouldBe TributePaid( + TributeAmount(gold = 0, food = 0) + ) + } - // Verify that the province ruled by a different faction is NOT in the changed provinces - ar.changedProvinces.find( - _.provinceId == differentFactionProvinceId - ) shouldBe None + // Verify that the province ruled by a different faction is NOT in the changed provinces + ar.changedProvinces.find( + _.provinceId == differentFactionProvinceId + ) shouldBe None } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommandTest.scala index 21c3e6574b..2c6857e130 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ResolveTruceOfferCommandTest.scala @@ -2,20 +2,11 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.TruceResolutionMessage import net.eagle0.eagle.model.action_result.types.OfferResolvedResultType import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.diplomacy_offer.status.{ - Accepted, - Imprisoned, - Rejected, - Unresolved -} +import net.eagle0.eagle.model.state.diplomacy_offer.status.{Accepted, Imprisoned, Rejected, Unresolved} import net.eagle0.eagle.model.state.diplomacy_offer.TruceOffer import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -23,17 +14,14 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ResolveTruceOfferCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ResolveTruceOfferCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val actingFactionId = 4 - private val originatingFactionId = 8 - private val messengerHeroId = 29 + private val actingFactionId = 4 + private val originatingFactionId = 8 + private val messengerHeroId = 29 private val messengerOriginProvinceId = 2 - private val currentRoundId = 873 - private val gameId = 0xfeed + private val currentRoundId = 873 + private val gameId = 0xfeed private val truceOffer = TruceOffer( originatingFactionId = originatingFactionId, @@ -46,10 +34,10 @@ class ResolveTruceOfferCommandTest ) private val availableOriginatingFactionIds = Vector(3, 8, 15) - private val availableResolutions = Vector(Accepted, Rejected, Imprisoned) + private val availableResolutions = Vector(Accepted, Rejected, Imprisoned) "make" should "throw if the selected originating faction is not among options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveTruceOfferCommand.make( actingFactionId = actingFactionId, originatingFactionId = 99, // not in available list @@ -62,13 +50,12 @@ class ResolveTruceOfferCommandTest gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Selected faction ID 99 was not among options Vector(3, 8, 15)" } it should "throw if the selected resolution is not among options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy ResolveTruceOfferCommand.make( actingFactionId = actingFactionId, originatingFactionId = originatingFactionId, @@ -77,12 +64,10 @@ class ResolveTruceOfferCommandTest truceOffer = truceOffer, resolution = Accepted, availableOriginatingFactionIds = availableOriginatingFactionIds, - availableResolutions = - Vector(Rejected, Imprisoned), // Accepted not available + availableResolutions = Vector(Rejected, Imprisoned), // Accepted not available gameId = gameId, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Selected truce resolution Accepted was not among options Vector(Rejected, Imprisoned)" } @@ -103,9 +88,10 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe OfferResolvedResultType - ar.actingFactionId shouldBe Some(actingFactionId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe OfferResolvedResultType + ar.actingFactionId shouldBe Some(actingFactionId) } } @@ -125,16 +111,18 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedFactions.loneElement) { case faction: ChangedFactionC => - faction.factionId shouldBe actingFactionId - faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - faction.newIncomingDiplomacyOffers shouldBe Vector( - truceOffer.copy(status = Accepted) - ) - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedFactions.loneElement) { + case faction: ChangedFactionC => + faction.factionId shouldBe actingFactionId + faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + faction.newIncomingDiplomacyOffers shouldBe Vector( + truceOffer.copy(status = Accepted) + ) + } } } @@ -154,17 +142,18 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.newNotifications.loneElement) { - case notification: NotificationC => - notification.details shouldBe NotificationDetails.TruceAccepted( - offeringFactionId = originatingFactionId, - targetFactionId = actingFactionId, - ambassadorHeroId = messengerHeroId - ) - notification.affectedHeroIds shouldBe Vector(messengerHeroId) - notification.deferred shouldBe true - } + inside(result) { + case ar: ActionResultC => + inside(ar.newNotifications.loneElement) { + case notification: NotificationC => + notification.details shouldBe NotificationDetails.TruceAccepted( + offeringFactionId = originatingFactionId, + targetFactionId = actingFactionId, + ambassadorHeroId = messengerHeroId + ) + notification.affectedHeroIds shouldBe Vector(messengerHeroId) + notification.deferred shouldBe true + } } } @@ -184,16 +173,17 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.newGeneratedTextRequests.loneElement) { - case llm: TruceResolutionMessage => - llm.requestId shouldBe s"$currentRoundId resolve truce $messengerHeroId" - llm.eagleGameId shouldBe gameId - llm.offeringFactionId shouldBe originatingFactionId - llm.targetFactionId shouldBe actingFactionId - llm.messengerHeroId shouldBe messengerHeroId - llm.resolution shouldBe Accepted - } + inside(result) { + case ar: ActionResultC => + inside(ar.newGeneratedTextRequests.loneElement) { + case llm: TruceResolutionMessage => + llm.requestId shouldBe s"$currentRoundId resolve truce $messengerHeroId" + llm.eagleGameId shouldBe gameId + llm.offeringFactionId shouldBe originatingFactionId + llm.targetFactionId shouldBe actingFactionId + llm.messengerHeroId shouldBe messengerHeroId + llm.resolution shouldBe Accepted + } } } @@ -213,16 +203,18 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedFactions.loneElement) { case faction: ChangedFactionC => - faction.factionId shouldBe actingFactionId - faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - faction.newIncomingDiplomacyOffers shouldBe Vector( - truceOffer.copy(status = Rejected) - ) - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedFactions.loneElement) { + case faction: ChangedFactionC => + faction.factionId shouldBe actingFactionId + faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + faction.newIncomingDiplomacyOffers shouldBe Vector( + truceOffer.copy(status = Rejected) + ) + } } } @@ -242,17 +234,18 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.newNotifications.loneElement) { - case notification: NotificationC => - notification.details shouldBe NotificationDetails.TruceRejected( - offeringFactionId = originatingFactionId, - targetFactionId = actingFactionId, - ambassadorHeroId = messengerHeroId - ) - notification.affectedHeroIds shouldBe Vector(messengerHeroId) - notification.deferred shouldBe true - } + inside(result) { + case ar: ActionResultC => + inside(ar.newNotifications.loneElement) { + case notification: NotificationC => + notification.details shouldBe NotificationDetails.TruceRejected( + offeringFactionId = originatingFactionId, + targetFactionId = actingFactionId, + ambassadorHeroId = messengerHeroId + ) + notification.affectedHeroIds shouldBe Vector(messengerHeroId) + notification.deferred shouldBe true + } } } @@ -272,16 +265,18 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.changedFactions.loneElement) { case faction: ChangedFactionC => - faction.factionId shouldBe actingFactionId - faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( - originatingFactionId - ) - faction.newIncomingDiplomacyOffers shouldBe Vector( - truceOffer.copy(status = Imprisoned) - ) - } + inside(result) { + case ar: ActionResultC => + inside(ar.changedFactions.loneElement) { + case faction: ChangedFactionC => + faction.factionId shouldBe actingFactionId + faction.removedIncomingDiplomacyOfferFactionIds shouldBe Vector( + originatingFactionId + ) + faction.newIncomingDiplomacyOffers shouldBe Vector( + truceOffer.copy(status = Imprisoned) + ) + } } } @@ -301,18 +296,19 @@ class ResolveTruceOfferCommandTest ) .immediateExecute - inside(result) { case ar: ActionResultC => - inside(ar.newNotifications.loneElement) { - case notification: NotificationC => - notification.details shouldBe NotificationDetails - .TruceAmbassadorImprisoned( - offeringFactionId = originatingFactionId, - targetFactionId = actingFactionId, - ambassadorHeroId = messengerHeroId - ) - notification.affectedHeroIds shouldBe Vector(messengerHeroId) - notification.deferred shouldBe true - } + inside(result) { + case ar: ActionResultC => + inside(ar.newNotifications.loneElement) { + case notification: NotificationC => + notification.details shouldBe NotificationDetails + .TruceAmbassadorImprisoned( + offeringFactionId = originatingFactionId, + targetFactionId = actingFactionId, + ambassadorHeroId = messengerHeroId + ) + notification.affectedHeroIds shouldBe Vector(messengerHeroId) + notification.deferred shouldBe true + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RestCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RestCommandTest.scala index cf4387af52..611705d7a3 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RestCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/RestCommandTest.scala @@ -2,11 +2,7 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, ProvinceId} import net.eagle0.eagle.library.settings.RestVigorGain -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.RestResultType import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.hero.HeroT @@ -14,11 +10,7 @@ import org.scalatest.{BeforeAndAfterEach, Inside} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class RestCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach - with Inside { +class RestCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach with Inside { private val rulingFactionId: FactionId = 5 private val fullyRestedHero = HeroC( @@ -44,9 +36,8 @@ class RestCommandTest private val provinceId: ProvinceId = 8 - override def beforeEach(): Unit = { + override def beforeEach(): Unit = RestVigorGain.setDoubleValue(15) - } "Execute" should "return the appropriate type and basic info" in { val command = RestCommand.make( @@ -57,11 +48,12 @@ class RestCommandTest val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe RestResultType - ar.actingFactionId shouldBe Some(5) - ar.provinceId shouldBe Some(8) - ar.provinceIdActed shouldBe Some(8) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe RestResultType + ar.actingFactionId shouldBe Some(5) + ar.provinceId shouldBe Some(8) + ar.provinceIdActed shouldBe Some(8) } } @@ -74,15 +66,16 @@ class RestCommandTest val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.changedHeroes shouldBe Vector( - ChangedHeroC(heroId = restableHero.id, vigorChange = StatDelta(15.0)) - ) + inside(result) { + case ar: ActionResultC => + ar.changedHeroes shouldBe Vector( + ChangedHeroC(heroId = restableHero.id, vigorChange = StatDelta(15.0)) + ) } } it should "cap hero vigor at constitution" in { - val almostRestedHero = restableHero.copy(vigor = 88.0) + val almostRestedHero = restableHero.copy(vigor = 88.0) val heroesWithAlmostRested = Vector(fullyRestedHero, almostRestedHero) val command = RestCommand.make( @@ -93,11 +86,12 @@ class RestCommandTest val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe RestResultType - ar.changedHeroes shouldBe Vector( - ChangedHeroC(heroId = almostRestedHero.id, vigorChange = StatDelta(2.0)) - ) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe RestResultType + ar.changedHeroes shouldBe Vector( + ChangedHeroC(heroId = almostRestedHero.id, vigorChange = StatDelta(2.0)) + ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommandTest.scala index e9d7c5edb8..2b8d5ff0bd 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/ReturnCommandTest.scala @@ -11,7 +11,7 @@ import org.scalatest.Inside class ReturnCommandTest extends AnyFlatSpec with Matchers with Inside { private val actingFactionId: FactionId = 19 - private val provinceId: ProvinceId = 7 + private val provinceId: ProvinceId = 7 "execute" should "throw if the province is not in travel state" in { val ex = the[EagleCommandException] thrownBy { @@ -36,11 +36,12 @@ class ReturnCommandTest extends AnyFlatSpec with Matchers with Inside { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.actionResultType shouldBe ReturnResultType - ar.actingFactionId shouldBe Some(actingFactionId) - ar.provinceId shouldBe Some(provinceId) - ar.provinceIdActed shouldBe Some(provinceId) + inside(result) { + case ar: ActionResultC => + ar.actionResultType shouldBe ReturnResultType + ar.actingFactionId shouldBe Some(actingFactionId) + ar.provinceId shouldBe Some(provinceId) + ar.provinceIdActed shouldBe Some(provinceId) } } @@ -53,13 +54,14 @@ class ReturnCommandTest extends AnyFlatSpec with Matchers with Inside { val result = command.immediateExecute - inside(result) { case ar: ActionResultC => - ar.changedProvinces shouldBe Vector( - ChangedProvinceC( - provinceId = provinceId, - setRulerIsTraveling = Some(false) + inside(result) { + case ar: ActionResultC => + ar.changedProvinces shouldBe Vector( + ChangedProvinceC( + provinceId = provinceId, + setRulerIsTraveling = Some(false) + ) ) - ) } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommandTest.scala index d1395ca69f..146c4fad59 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SendSuppliesCommandTest.scala @@ -16,22 +16,19 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class SendSuppliesCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class SendSuppliesCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val actingFactionId = 9 - private val actingHeroId = 15 - private val originProvinceId = 14 - private val destinationProvinceId = 25 + private val actingFactionId = 9 + private val actingHeroId = 15 + private val originProvinceId = 14 + private val destinationProvinceId = 25 private val availableDestinationProvinceIds = Vector(25, 26, 27) - private val availableHeroIds = Vector(12, 15, 18) - private val goldAvailable = 2500 - private val foodAvailable = 3500 - private val gold = 1500 - private val food = 2750 - private val currentRoundId = 0 + private val availableHeroIds = Vector(12, 15, 18) + private val goldAvailable = 2500 + private val foodAvailable = 3500 + private val gold = 1500 + private val food = 2750 + private val currentRoundId = 0 override def beforeEach(): Unit = { TurnsToResolveShipment.setIntValue(1) @@ -43,7 +40,7 @@ class SendSuppliesCommandTest } "make command" should "throw if the food amount is negative" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SendSuppliesCommand.make( actingFactionId = actingFactionId, actingHeroId = actingHeroId, @@ -57,13 +54,12 @@ class SendSuppliesCommandTest foodSent = -5, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Food amount cannot be negative" } it should "throw if the food amount is greater than available food" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SendSuppliesCommand.make( actingFactionId = actingFactionId, actingHeroId = actingHeroId, @@ -77,13 +73,12 @@ class SendSuppliesCommandTest foodSent = 3501, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Food amount 3501 greater than available 3500" } it should "throw if the gold amount is negative" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SendSuppliesCommand.make( actingFactionId = actingFactionId, actingHeroId = actingHeroId, @@ -97,13 +92,12 @@ class SendSuppliesCommandTest foodSent = food, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Gold amount cannot be negative" } it should "throw if the gold amount is greater than the available gold" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SendSuppliesCommand.make( actingFactionId = actingFactionId, actingHeroId = actingHeroId, @@ -117,13 +111,12 @@ class SendSuppliesCommandTest foodSent = food, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Gold amount 2698 greater than available 2500" } it should "throw if the actor is not among the available heroes" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SendSuppliesCommand.make( actingFactionId = actingFactionId, actingHeroId = 19, @@ -137,13 +130,12 @@ class SendSuppliesCommandTest foodSent = food, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Available heroes Vector(12, 15, 18) did not include 19" } it should "throw if the destination province is not in the available list" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SendSuppliesCommand.make( actingFactionId = actingFactionId, actingHeroId = actingHeroId, @@ -157,7 +149,6 @@ class SendSuppliesCommandTest foodSent = food, currentRoundId = currentRoundId ) - } ex.getMessage shouldBe "requirement failed: Available destination provinces Vector(25, 26, 27) did not include 4" } @@ -208,7 +199,7 @@ class SendSuppliesCommandTest destinationProvinceChange should be(defined) // Cast to concrete type to access newIncomingShipments - val concreteChange = + val concreteChange = destinationProvinceChange.get.asInstanceOf[ChangedProvinceC] val incomingShipments = concreteChange.newIncomingShipments incomingShipments.should(have).size(1) diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommandTest.scala index 332d2354d2..db39ef620a 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/StartEpidemicCommandTest.scala @@ -1,17 +1,10 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, HeroId, ProvinceId} -import net.eagle0.eagle.library.settings.{ - StartEpidemicCharismaXp, - StartEpidemicVigorDelta -} +import net.eagle0.eagle.library.settings.{StartEpidemicCharismaXp, StartEpidemicVigorDelta} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.EpidemicStartedResultType import net.eagle0.eagle.model.state.province.DeferredChange import org.scalatest.flatspec.AnyFlatSpec @@ -20,30 +13,27 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class StartEpidemicCommandTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class StartEpidemicCommandTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { behavior of "StartEpidemicCommandTest" private val charismaXpDelta: Int = 25 - private val vigorDelta: Int = -40 + private val vigorDelta: Int = -40 override def beforeEach(): Unit = { StartEpidemicVigorDelta.setDoubleValue(vigorDelta) StartEpidemicCharismaXp.setIntValue(charismaXpDelta) } - private val actingPid: ProvinceId = 17 - private val actingFid: FactionId = 2 - private val availableHeroIds = Vector[HeroId](10, 20, 30) + private val actingPid: ProvinceId = 17 + private val actingFid: FactionId = 2 + private val availableHeroIds = Vector[HeroId](10, 20, 30) private val availableTargetProvinceIds = Vector[ProvinceId](17, 4, 19) - private val actingHid: HeroId = 10 - private val targetedPid: ProvinceId = 19 + private val actingHid: HeroId = 10 + private val targetedPid: ProvinceId = 19 "make" should "throw if the hero was not among options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy StartEpidemicCommand.make( actingFactionId = actingFid, actingHeroId = 11, @@ -52,13 +42,12 @@ class StartEpidemicCommandTest availableHeroIds = availableHeroIds, availableTargetProvinceIds = availableTargetProvinceIds ) - } ex.getMessage shouldBe "requirement failed: Must select hero from Vector(10, 20, 30) but chose 11" } it should "throw if the target province was not among options" in { - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy StartEpidemicCommand.make( actingFactionId = actingFid, actingHeroId = actingHid, @@ -67,7 +56,6 @@ class StartEpidemicCommandTest availableHeroIds = availableHeroIds, availableTargetProvinceIds = availableTargetProvinceIds ) - } ex.getMessage shouldBe "requirement failed: Selected pid 6 was not among Vector(17, 4, 19)" } @@ -83,10 +71,11 @@ class StartEpidemicCommandTest availableTargetProvinceIds = availableTargetProvinceIds ) - inside(action.immediateExecute) { case ar: ActionResultC => - ar.actionResultType shouldBe EpidemicStartedResultType - ar.actingHeroId shouldBe Some(actingHid) - ar.provinceId shouldBe Some(actingPid) + inside(action.immediateExecute) { + case ar: ActionResultC => + ar.actionResultType shouldBe EpidemicStartedResultType + ar.actingHeroId shouldBe Some(actingHid) + ar.provinceId shouldBe Some(actingPid) } } @@ -101,11 +90,13 @@ class StartEpidemicCommandTest availableTargetProvinceIds = availableTargetProvinceIds ) - inside(action.immediateExecute) { case ar: ActionResultC => - inside(ar.changedHeroes.loneElement) { case hero: ChangedHeroC => - hero.heroId shouldBe actingHid - hero.charismaXpDelta shouldBe Some(charismaXpDelta) - } + inside(action.immediateExecute) { + case ar: ActionResultC => + inside(ar.changedHeroes.loneElement) { + case hero: ChangedHeroC => + hero.heroId shouldBe actingHid + hero.charismaXpDelta shouldBe Some(charismaXpDelta) + } } } @@ -120,11 +111,13 @@ class StartEpidemicCommandTest availableTargetProvinceIds = availableTargetProvinceIds ) - inside(action.immediateExecute) { case ar: ActionResultC => - inside(ar.changedHeroes.loneElement) { case hero: ChangedHeroC => - hero.heroId shouldBe actingHid - hero.vigorChange shouldBe StatDelta(vigorDelta) - } + inside(action.immediateExecute) { + case ar: ActionResultC => + inside(ar.changedHeroes.loneElement) { + case hero: ChangedHeroC => + hero.heroId shouldBe actingHid + hero.vigorChange shouldBe StatDelta(vigorDelta) + } } } @@ -139,8 +132,9 @@ class StartEpidemicCommandTest availableTargetProvinceIds = availableTargetProvinceIds ) - inside(action.immediateExecute) { case ar: ActionResultC => - ar.provinceIdActed shouldBe Some(actingPid) + inside(action.immediateExecute) { + case ar: ActionResultC => + ar.provinceIdActed shouldBe Some(actingPid) } } @@ -155,14 +149,15 @@ class StartEpidemicCommandTest availableTargetProvinceIds = availableTargetProvinceIds ) - inside(action.immediateExecute) { case ar: ActionResultC => - inside(ar.changedProvinces.loneElement) { - case province: ChangedProvinceC => - province.provinceId shouldBe targetedPid - province.newDeferredChange shouldBe Some( - DeferredChange.EpidemicStarted(responsibleFaction = actingFid) - ) - } + inside(action.immediateExecute) { + case ar: ActionResultC => + inside(ar.changedProvinces.loneElement) { + case province: ChangedProvinceC => + province.provinceId shouldBe targetedPid + province.newDeferredChange shouldBe Some( + DeferredChange.EpidemicStarted(responsibleFaction = actingFid) + ) + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommandTest.scala index a7eb740ddf..da0e2cebb2 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SuppressBeastsCommandTest.scala @@ -16,16 +16,9 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedBattalionC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedBattalionC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.concrete.ActionResultC -import net.eagle0.eagle.model.action_result.types.{ - SuppressBeastsFailedResultType, - SuppressedBeastsResultType -} +import net.eagle0.eagle.model.action_result.types.{SuppressBeastsFailedResultType, SuppressedBeastsResultType} import net.eagle0.eagle.model.action_result.NotificationDetails import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.date.Date @@ -42,17 +35,14 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class SuppressBeastsCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class SuppressBeastsCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val actingFactionId: FactionId = 5 - private val actingHeroId: HeroId = 15 - private val provinceId: ProvinceId = 7 - private val roundId = 87 - private val currentDate = Date(year = 1500, month = Date.Month.May) - private val gameId: GameId = 0xcafe + private val actingHeroId: HeroId = 15 + private val provinceId: ProvinceId = 7 + private val roundId = 87 + private val currentDate = Date(year = 1500, month = Date.Month.May) + private val gameId: GameId = 0xcafe // Test data private val pirates = BeastInfo( @@ -140,12 +130,12 @@ class SuppressBeastsCommandTest provinceOrders = ProvinceOrderType.Entrust ) - private val pirateProvince = provinceWithBeasts(pirates, 150) + private val pirateProvince = provinceWithBeasts(pirates, 150) private val crocodileProvince = provinceWithBeasts(crocodiles, 100) - private val wolvesProvince = provinceWithBeasts(wolves, 55) + private val wolvesProvince = provinceWithBeasts(wolves, 55) val strengthXp = 45 - val agilityXp = 55 + val agilityXp = 55 override def beforeEach(): Unit = { ActionVigorCost.setIntValue(20) @@ -193,7 +183,7 @@ class SuppressBeastsCommandTest "make" should "throw if the selected hero ID is not in the available list" in { val badHeroId: HeroId = 8 - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SuppressBeastsCommand.make( actingFactionId = actingFactionId, availableHeroIds = Vector(actingHeroId), @@ -205,7 +195,6 @@ class SuppressBeastsCommandTest currentDate = currentDate, currentRoundId = 87 ) - } ex.getMessage shouldBe s"requirement failed: Tried to suppress beasts with hero $badHeroId, but options were Vector($actingHeroId)" } @@ -213,7 +202,7 @@ class SuppressBeastsCommandTest it should "throw if the selected battalion ID is not in the available list" in { val otherBattalionId: BattalionId = 32 - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SuppressBeastsCommand.make( actingFactionId = actingFactionId, availableHeroIds = Vector(actingHeroId), @@ -225,7 +214,6 @@ class SuppressBeastsCommandTest currentDate = currentDate, currentRoundId = 87 ) - } ex.getMessage shouldBe s"requirement failed: Tried to suppress beasts with battalion ${actingBattalion.id}, but options were Vector(32)" } @@ -236,9 +224,10 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.heroId shouldBe actingHeroId - ch.vigorChange shouldBe StatDelta(-20.0) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.heroId shouldBe actingHeroId + ch.vigorChange shouldBe StatDelta(-20.0) } } @@ -248,9 +237,10 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.changedHeroes.head) { case ch: ChangedHeroC => - ch.strengthXpDelta should contain(strengthXp) - ch.agilityXpDelta should contain(agilityXp) + inside(result.changedHeroes.head) { + case ch: ChangedHeroC => + ch.strengthXpDelta should contain(strengthXp) + ch.agilityXpDelta should contain(agilityXp) } } @@ -260,9 +250,10 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.changedBattalions.loneElement) { case cb: ChangedBattalionC => - cb.to.id shouldBe 3 - cb.to.size should be < 500 + inside(result.changedBattalions.loneElement) { + case cb: ChangedBattalionC => + cb.to.id shouldBe 3 + cb.to.size should be < 500 } } @@ -289,8 +280,9 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newProvinceEvents.get should be(empty) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newProvinceEvents.get should be(empty) } } @@ -304,13 +296,14 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - // There are 150 pirates, which have a gold gained of 1.8, with a swing of 20%. So the count should be between 216 and 324. - val goldGained = cp.goldDelta.get - goldGained should be >= 216 - goldGained should be <= 324 + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + // There are 150 pirates, which have a gold gained of 1.8, with a swing of 20%. So the count should be between 216 and 324. + val goldGained = cp.goldDelta.get + goldGained should be >= 216 + goldGained should be <= 324 - cp.foodDelta shouldBe empty + cp.foodDelta shouldBe empty } } @@ -324,13 +317,14 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.changedProvinces.head) { case cp: ChangedProvinceC => - // There are 55 wolves, which have a food gained of 0.5, with a swing of 20%. So the count should be between 22 and 33. - val foodGained = cp.foodDelta.get - foodGained should be >= 22 - foodGained should be <= 33 + inside(result.changedProvinces.head) { + case cp: ChangedProvinceC => + // There are 55 wolves, which have a food gained of 0.5, with a swing of 20%. So the count should be between 22 and 33. + val foodGained = cp.foodDelta.get + foodGained should be >= 22 + foodGained should be <= 33 - cp.goldDelta shouldBe empty + cp.goldDelta shouldBe empty } } @@ -340,8 +334,9 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.supportDelta shouldBe Some(6.0) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.supportDelta shouldBe Some(6.0) } } @@ -349,16 +344,17 @@ class SuppressBeastsCommandTest val result = executeCommand(pirateProvince, actingHero, Some(actingBattalion)) - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - inside(ch.newEventsForHeroBackstory.loneElement) { - case evt: SuppressedBeastsBackstoryEvent => - evt.date shouldBe currentDate - evt.provinceId shouldBe provinceId - evt.beastType shouldBe "pirate" - evt.beastCount shouldBe 150 - evt.battalion.isDefined shouldBe true - evt.succeeded shouldBe true - } + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + inside(ch.newEventsForHeroBackstory.loneElement) { + case evt: SuppressedBeastsBackstoryEvent => + evt.date shouldBe currentDate + evt.provinceId shouldBe provinceId + evt.beastType shouldBe "pirate" + evt.beastCount shouldBe 150 + evt.battalion.isDefined shouldBe true + evt.succeeded shouldBe true + } } } @@ -368,10 +364,11 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType - inside(result.newNotifications.loneElement) { case notification => - notification.details shouldBe a[NotificationDetails.SuppressedBeasts] - notification.targetFactionIds should contain(actingFactionId) - notification.deferred shouldBe true + inside(result.newNotifications.loneElement) { + case notification => + notification.details shouldBe a[NotificationDetails.SuppressedBeasts] + notification.targetFactionIds should contain(actingFactionId) + notification.deferred shouldBe true } result.newGeneratedTextRequests.loneElement.eagleGameId shouldBe gameId @@ -383,10 +380,11 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressBeastsFailedResultType - inside(result.newNotifications.loneElement) { case notification => - notification.details shouldBe a[NotificationDetails.SuppressBeastsFailed] - notification.targetFactionIds shouldBe empty // all factions learn about failures - notification.deferred shouldBe true + inside(result.newNotifications.loneElement) { + case notification => + notification.details shouldBe a[NotificationDetails.SuppressBeastsFailed] + notification.targetFactionIds shouldBe empty // all factions learn about failures + notification.deferred shouldBe true } result.newGeneratedTextRequests.loneElement.eagleGameId shouldBe gameId @@ -398,17 +396,19 @@ class SuppressBeastsCommandTest result.actionResultType shouldBe SuppressedBeastsResultType result.changedBattalions should be(empty) - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - // Hero should take some vigor damage when fighting alone - inside(ch.vigorChange) { case sd: StatDelta => - sd.value should be < 0.0 - } + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + // Hero should take some vigor damage when fighting alone + inside(ch.vigorChange) { + case sd: StatDelta => + sd.value should be < 0.0 + } } } it should "handle weak hero scenarios (hero death without battalion)" in { val weakHero = actingHero.copy(strength = 10, agility = 10, vigor = 30) - val result = executeCommand(crocodileProvince, weakHero, None) + val result = executeCommand(crocodileProvince, weakHero, None) result.actionResultType shouldBe SuppressBeastsFailedResultType result.removedHeroIds should contain(weakHero.id) @@ -424,11 +424,11 @@ class SuppressBeastsCommandTest it should "work with different beast types" in { // Test that we can create commands for different beast scenarios - val pirateCommand = + val pirateCommand = createCommand(pirateProvince, actingHero, Some(actingBattalion)) val crocodileCommand = createCommand(crocodileProvince, actingHero, Some(actingBattalion)) - val wolvesCommand = + val wolvesCommand = createCommand(wolvesProvince, actingHero, Some(actingBattalion)) pirateCommand shouldBe a[ProtolessRandomSimpleAction] diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommandTest.scala index 0170f04ae8..af39cf5675 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/SwearBrotherhoodCommandTest.scala @@ -2,18 +2,10 @@ package net.eagle0.eagle.library.actions.impl.command import net.eagle0.eagle.{FactionId, GameId, HeroId, ProvinceId, RoundId} import net.eagle0.eagle.library.actions.impl.common.ProtolessSimpleAction -import net.eagle0.eagle.library.settings.{ - AcceptBrotherhoodCharismaXp, - SwearBrotherhoodCharismaXp -} +import net.eagle0.eagle.library.settings.{AcceptBrotherhoodCharismaXp, SwearBrotherhoodCharismaXp} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.{NotificationDetails, NotificationT} -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedFactionC, - ChangedHeroC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedFactionC, ChangedHeroC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.SwearBrotherhoodMessage import net.eagle0.eagle.model.action_result.types.SwearBrotherhoodResultType import net.eagle0.eagle.model.state.date.Date @@ -22,29 +14,26 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class SwearBrotherhoodCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class SwearBrotherhoodCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { SwearBrotherhoodCharismaXp.setIntValue(75) AcceptBrotherhoodCharismaXp.setIntValue(50) } // Test data for new protoless API - private val actingFactionId: FactionId = 3 + private val actingFactionId: FactionId = 3 private val actingProvinceId: ProvinceId = 17 - private val newBrotherHeroId: HeroId = 6 - private val factionHeadHeroId: HeroId = 101 - private val availableHeroIds = Vector[HeroId](5, 6, 7) - private val currentDate = Date(year = 1500, month = Date.Month.January) - private val currentRoundId: RoundId = 0 - private val gameId: GameId = 0xcafe + private val newBrotherHeroId: HeroId = 6 + private val factionHeadHeroId: HeroId = 101 + private val availableHeroIds = Vector[HeroId](5, 6, 7) + private val currentDate = Date(year = 1500, month = Date.Month.January) + private val currentRoundId: RoundId = 0 + private val gameId: GameId = 0xcafe "make" should "throw if the selected brother is not among the options" in { val invalidBrotherHeroId: HeroId = 9 - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy SwearBrotherhoodCommand.make( actingFactionId = actingFactionId, actingProvinceId = actingProvinceId, @@ -55,7 +44,6 @@ class SwearBrotherhoodCommandTest currentRoundId = currentRoundId, gameId = gameId ) - } ex.getMessage shouldBe "requirement failed: Tried to swear brotherhood with 9, but options were Vector(5, 6, 7)" } @@ -71,7 +59,7 @@ class SwearBrotherhoodCommandTest currentRoundId = currentRoundId, gameId = gameId ) - val result = action.immediateExecute + val result = action.immediateExecute result.shouldBe(a[ActionResultC]) val actionResult = result.asInstanceOf[ActionResultC] @@ -93,7 +81,7 @@ class SwearBrotherhoodCommandTest currentRoundId = currentRoundId, gameId = gameId ) - val result = action.immediateExecute + val result = action.immediateExecute result.shouldBe(a[ActionResultC]) val actionResult = result.asInstanceOf[ActionResultC] @@ -139,13 +127,13 @@ class SwearBrotherhoodCommandTest currentRoundId = currentRoundId, gameId = gameId ) - val result = action.immediateExecute + val result = action.immediateExecute result.shouldBe(a[ActionResultC]) val actionResult = result.asInstanceOf[ActionResultC] val expectedLlmId = - s"${currentRoundId} swear brotherhood ${newBrotherHeroId}" + s"$currentRoundId swear brotherhood $newBrotherHeroId" actionResult.newNotifications.shouldBe( Vector( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommandTest.scala index a9c24a0d8a..9d113c2973 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TradeCommandTest.scala @@ -1,10 +1,6 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.library.actions.impl.command.TradeCommandType.{ - BuyFood, - SellFood, - Unknown -} +import net.eagle0.eagle.library.actions.impl.command.TradeCommandType.{BuyFood, SellFood, Unknown} import net.eagle0.eagle.library.settings.{BaseFoodBuyPrice, BaseFoodSellPrice} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC @@ -16,18 +12,15 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class TradeCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class TradeCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val actingFactionId = 82 - val provinceId = 3 + val provinceId = 3 private val rulingHeroId = 7 - val startingGold = 1000 - val startingFood = 1500 - val foodBuyPrice = 0.6 + val startingGold = 1000 + val startingFood = 1500 + val foodBuyPrice = 0.6 val foodSellPrice = 0.25 private val province = ProvinceC( @@ -54,9 +47,8 @@ class TradeCommandTest amount = 2000 ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: cost of 1200 exceeds 1000 available" } @@ -69,9 +61,8 @@ class TradeCommandTest amount = 2000 ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: trying to sell 2000 food but only 1500 available" } @@ -84,9 +75,8 @@ class TradeCommandTest amount = 20 ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "Unknown trade type" } @@ -101,9 +91,8 @@ class TradeCommandTest amount = 500 ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe s"requirement failed: province $provinceId is not in travel state" } @@ -116,9 +105,8 @@ class TradeCommandTest amount = 0 ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: invalid amount 0" } @@ -131,9 +119,8 @@ class TradeCommandTest amount = -50 ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: invalid amount -50" } @@ -163,8 +150,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(-600) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(-600) } } @@ -177,8 +165,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(-900) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(-900) } } @@ -191,8 +180,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.foodDelta shouldBe Some(1000) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.foodDelta shouldBe Some(1000) } } @@ -205,8 +195,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.foodDelta shouldBe Some(1000) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.foodDelta shouldBe Some(1000) } } @@ -219,9 +210,10 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.foodDelta shouldBe Some(1000) - cp.goldDelta shouldBe Some(-600) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.foodDelta shouldBe Some(1000) + cp.goldDelta shouldBe Some(-600) } } @@ -234,8 +226,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newPriceIndex shouldBe Some(1.06) // spent 600 gold + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newPriceIndex shouldBe Some(1.06) // spent 600 gold } } @@ -248,8 +241,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(250) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(250) } } @@ -262,8 +256,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.goldDelta shouldBe Some(375) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.goldDelta shouldBe Some(375) } } @@ -276,8 +271,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.foodDelta shouldBe Some(-1000) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.foodDelta shouldBe Some(-1000) } } @@ -290,8 +286,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.foodDelta shouldBe Some(-1000) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.foodDelta shouldBe Some(-1000) } } @@ -304,9 +301,10 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.foodDelta shouldBe Some(-996) - cp.goldDelta shouldBe Some(249) + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.foodDelta shouldBe Some(-996) + cp.goldDelta shouldBe Some(249) } } @@ -319,8 +317,9 @@ class TradeCommandTest ) val result = command.immediateExecute - inside(result.changedProvinces.loneElement) { case cp: ChangedProvinceC => - cp.newPriceIndex shouldBe Some(0.975) // gained 250 gold + inside(result.changedProvinces.loneElement) { + case cp: ChangedProvinceC => + cp.newPriceIndex shouldBe Some(0.975) // gained 250 gold } } } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommandTest.scala index faa16a6120..99517c3fa0 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TrainCommandTest.scala @@ -10,11 +10,7 @@ import net.eagle0.eagle.library.settings.{ TrainStrengthXp } import net.eagle0.eagle.library.EagleCommandException -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedBattalionC, - ChangedHeroC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedBattalionC, ChangedHeroC, StatDelta} import net.eagle0.eagle.model.action_result.types.TrainResultType import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.battalion.BattalionT @@ -31,10 +27,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class TrainCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class TrainCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val fid: FactionId = 4 private val heroes: Vector[HeroT] = Vector( @@ -122,9 +115,8 @@ class TrainCommandTest battalionTypes = battalionTypes ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: Attempting to train in province 7, but there are no trainable battalions" } @@ -139,9 +131,8 @@ class TrainCommandTest battalionTypes = battalionTypes ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: Player 5 does not rule province 7" } @@ -156,9 +147,8 @@ class TrainCommandTest battalionTypes = battalionTypes ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: Attempting to train with hero 5, but they are not in province 7" } @@ -175,9 +165,8 @@ class TrainCommandTest battalionTypes = battalionTypes ) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy command.immediateExecute - } ex.getMessage shouldBe "requirement failed: Attempting to train with hero 18, but they are too tired" } @@ -205,8 +194,9 @@ class TrainCommandTest val result = command.immediateExecute result.actionResultType shouldBe TrainResultType - inside(result.changedHeroes.loneElement) { case ch: ChangedHeroC => - ch.vigorChange shouldBe StatDelta(-10.0) + inside(result.changedHeroes.loneElement) { + case ch: ChangedHeroC => + ch.vigorChange shouldBe StatDelta(-10.0) } } @@ -221,7 +211,7 @@ class TrainCommandTest rulingFactionHeroIds = Vector(18), battalionIds = Vector(5) ) - val provinceBattalions = Vector( + val provinceBattalions = Vector( BattalionC( id = 5, size = 1000, @@ -242,8 +232,9 @@ class TrainCommandTest val result = command.immediateExecute result.actionResultType shouldBe TrainResultType - inside(result.changedBattalions.loneElement) { case cb: ChangedBattalionC => - cb.to.training shouldBe (50.0 + (hero.strength + hero.charisma) / 5.0 / battalionType.trainingDifficulty + expectedBonus) + inside(result.changedBattalions.loneElement) { + case cb: ChangedBattalionC => + cb.to.training shouldBe (50.0 + (hero.strength + hero.charisma) / 5.0 / battalionType.trainingDifficulty + expectedBonus) } () } @@ -309,7 +300,7 @@ class TrainCommandTest BattalionC(id = 5, typeId = LightInfantry, size = 1000, training = 50), BattalionC(id = 6, typeId = LightInfantry, size = 1000, training = 50) ) - val province = ProvinceC( + val province = ProvinceC( id = 7, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(18), @@ -329,8 +320,9 @@ class TrainCommandTest result.actionResultType shouldBe TrainResultType result.changedBattalions should have size 2 - val cbs = result.changedBattalions.collect { case cb: ChangedBattalionC => - cb.to + val cbs = result.changedBattalions.collect { + case cb: ChangedBattalionC => + cb.to } cbs.head.training shouldBe (50.0 + 20 / Math.sqrt(2)) cbs(1).training shouldBe (50.0 + 20 / Math.sqrt(2)) @@ -350,7 +342,7 @@ class TrainCommandTest BattalionC(id = 5, typeId = LightInfantry, size = 1000, training = 99), BattalionC(id = 6, typeId = LightInfantry, size = 1000, training = 50) ) - val province = ProvinceC( + val province = ProvinceC( id = 7, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(18), @@ -369,8 +361,9 @@ class TrainCommandTest val result = command.immediateExecute result.actionResultType shouldBe TrainResultType - val cbs = result.changedBattalions.collect { case cb: ChangedBattalionC => - cb.to + val cbs = result.changedBattalions.collect { + case cb: ChangedBattalionC => + cb.to } cbs.size shouldBe 2 cbs.head.training shouldBe 100.0 @@ -390,7 +383,7 @@ class TrainCommandTest val provinceBattalions = Vector( BattalionC(id = 5, typeId = LightInfantry, size = 1000, training = 99) ) - val province = ProvinceC( + val province = ProvinceC( id = 7, rulingFactionId = Some(4), rulingFactionHeroIds = Vector(18), diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TravelCommandTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TravelCommandTest.scala index 289d394a38..c96aa7b850 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TravelCommandTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/command/TravelCommandTest.scala @@ -1,17 +1,9 @@ package net.eagle0.eagle.library.actions.impl.command -import net.eagle0.eagle.library.settings.{ - ActionVigorCost, - VigorToConstitutionXpMultiplier, - XpForStatBump -} +import net.eagle0.eagle.library.settings.{ActionVigorCost, VigorToConstitutionXpMultiplier, XpForStatBump} import net.eagle0.eagle.library.EagleCommandException import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ChangedHeroC, - ClientTextVisibilityExtensionC, - StatDelta -} +import net.eagle0.eagle.model.action_result.concrete.{ChangedHeroC, ClientTextVisibilityExtensionC, StatDelta} import net.eagle0.eagle.model.action_result.types.TravelResultType import net.eagle0.eagle.model.state.date.Date import net.eagle0.eagle.model.state.hero.backstory_version.BackstoryVersion @@ -26,10 +18,7 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class TravelCommandTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class TravelCommandTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { val actingFactionId = 19 private val date = Date(year = 5, month = Date.Month.October) @@ -45,13 +34,11 @@ class TravelCommandTest private val unaffiliatedHeroes: Vector[HeroT] = Vector( HeroC( id = 700, - backstoryVersions = - Vector(BackstoryVersion(textId = "backstory_700", date = date)) + backstoryVersions = Vector(BackstoryVersion(textId = "backstory_700", date = date)) ), HeroC( id = 701, - backstoryVersions = - Vector(BackstoryVersion(textId = "backstory_701", date = date)) + backstoryVersions = Vector(BackstoryVersion(textId = "backstory_701", date = date)) ) ) @@ -85,7 +72,7 @@ class TravelCommandTest val startingStateWithProvinceInTravelState = province.withRulerIsTraveling(true) - val ex = the[EagleCommandException] thrownBy { + val ex = the[EagleCommandException] thrownBy TravelCommand .make( province = startingStateWithProvinceInTravelState, @@ -93,7 +80,6 @@ class TravelCommandTest unaffiliatedHeroes = unaffiliatedHeroes ) .immediateExecute - } ex.getMessage shouldBe s"requirement failed: Province ${province.id} is already in travel state" } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplierTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplierTest.scala index 570f37c3a4..c7f640be56 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplierTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/common/VigorXPApplierTest.scala @@ -3,23 +3,16 @@ package net.eagle0.eagle.library.actions.impl.common import net.eagle0.common.ProtoMatchers.equalProto import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.changed_hero.ChangedHero -import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor.{ - VigorAbsolute, - VigorDelta -} +import net.eagle0.eagle.internal.changed_hero.ChangedHero.Vigor.{VigorAbsolute, VigorDelta} import net.eagle0.eagle.library.settings.VigorToConstitutionXpMultiplier import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class VigorXPApplierTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class VigorXPApplierTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - override def beforeEach(): Unit = { + override def beforeEach(): Unit = VigorToConstitutionXpMultiplier.setDoubleValue(0.2) - } "a result with changed heroes with reduced vigor" should "add charisma xp" in { val ar = ActionResult( diff --git a/src/test/scala/net/eagle0/eagle/library/actions/impl/package.scala b/src/test/scala/net/eagle0/eagle/library/actions/impl/package.scala index 9b1973c992..19f477c1f0 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/impl/package.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/impl/package.scala @@ -3,10 +3,7 @@ package net.eagle0.eagle.library.actions import net.eagle0.eagle.internal.action_result.ActionResult import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.hero.Hero -import net.eagle0.eagle.library.actions.applier.{ - ActionResultProtoApplier, - ActionResultProtoApplierImpl -} +import net.eagle0.eagle.library.actions.applier.{ActionResultProtoApplier, ActionResultProtoApplierImpl} import net.eagle0.eagle.library.actions.impl.common.Action import net.eagle0.eagle.library.util.validations.TestingNoopValidator @@ -23,8 +20,7 @@ package object impl { implicit class WaitingAction(action: Action) { def resultsOfExecute( - actionResultProtoApplier: ActionResultProtoApplier = - new ActionResultProtoApplierImpl(TestingNoopValidator) + actionResultProtoApplier: ActionResultProtoApplier = new ActionResultProtoApplierImpl(TestingNoopValidator) ): Vector[ActionResult] = action.execute(actionResultProtoApplier).map(_.actionResult) } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGeneratorTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGeneratorTest.scala index 52935e6a70..0a48979b5c 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGeneratorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/CapturedHeroMessagePromptGeneratorTest.scala @@ -10,25 +10,18 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.generated_text_request.CapturedHeroExecutedMessage import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -class CapturedHeroMessagePromptGeneratorTest - extends AnyFlatSpec - with Matchers - with MockFactory { - private val capturedHeroId: HeroId = 18 - private val capturedHeroFactionId: FactionId = 4 +class CapturedHeroMessagePromptGeneratorTest extends AnyFlatSpec with Matchers with MockFactory { + private val capturedHeroId: HeroId = 18 + private val capturedHeroFactionId: FactionId = 4 private val capturedHeroFactionHeadId: HeroId = 2 - private val actingHeroId: HeroId = 12 - private val actingFactionId: FactionId = 7 + private val actingHeroId: HeroId = 12 + private val actingFactionId: FactionId = 7 private val actingFactionHeadId: HeroId = 6 private val provinceId: ProvinceId = 54 @@ -41,8 +34,7 @@ class CapturedHeroMessagePromptGeneratorTest factionId = Some(capturedHeroFactionId), personalityWords = Vector("saucy"), pronounGender = GENDER_MALE, - backstoryVersions = - Vector(BackstoryVersion(textId = s"$capturedHeroId backstory 0")) + backstoryVersions = Vector(BackstoryVersion(textId = s"$capturedHeroId backstory 0")) ) private val gameState = GameState( @@ -54,8 +46,7 @@ class CapturedHeroMessagePromptGeneratorTest factionId = Some(actingFactionId), pronounGender = GENDER_FEMALE, personalityWords = Vector("haughty"), - backstoryVersions = - Vector(BackstoryVersion(textId = s"$actingHeroId backstory 0")) + backstoryVersions = Vector(BackstoryVersion(textId = s"$actingHeroId backstory 0")) ), Hero( id = capturedHeroFactionHeadId, @@ -74,8 +65,7 @@ class CapturedHeroMessagePromptGeneratorTest profession = RANGER, pronounGender = GENDER_MALE, personalityWords = Vector("stupid"), - backstoryVersions = - Vector(BackstoryVersion(textId = s"$actingFactionId backstory 0")) + backstoryVersions = Vector(BackstoryVersion(textId = s"$actingFactionId backstory 0")) ) ), factions = mapifyFactions( @@ -154,17 +144,17 @@ class CapturedHeroMessagePromptGeneratorTest "other practitioners of arcane magics are trained and practice, has remained neutral, though some of its members " + "take part in the war." + """ - | - |Joe the Captured has been captured in battle by his enemy, Jane the Victor. - |The battle took place in the province of Parnia. Jane the Victor has decided to execute Joe the Captured. - | - |Joe the Captured serves as a vassal under Losing Faction Head Guy in Losing Faction. He is saucy. - |Jane the Victor serves as a vassal under Winning Faction Head Guy in Winning Faction. She is haughty. - | - |Write the last words of Joe the Captured, as intended to be heard by everyone in the land. - | - |Do not include any other context beyond the in-world text of the response itself. Limit your response to 35 words or fewer. - |""".stripMargin + | + |Joe the Captured has been captured in battle by his enemy, Jane the Victor. + |The battle took place in the province of Parnia. Jane the Victor has decided to execute Joe the Captured. + | + |Joe the Captured serves as a vassal under Losing Faction Head Guy in Losing Faction. He is saucy. + |Jane the Victor serves as a vassal under Winning Faction Head Guy in Winning Faction. She is haughty. + | + |Write the last words of Joe the Captured, as intended to be heard by everyone in the land. + | + |Do not include any other context beyond the in-world text of the response itself. Limit your response to 35 words or fewer. + |""".stripMargin messagePrompt.get shouldBe expectedPrompt } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGeneratorTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGeneratorTest.scala index e10eeb5c4e..408af45140 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGeneratorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/ChronicleUpdatePromptGeneratorTest.scala @@ -4,32 +4,20 @@ import net.eagle0.eagle.client_text.{ClientTextStore, TextGenerationSuccess} import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.gender.Gender import net.eagle0.eagle.common.hero_backstory_version.BackstoryVersion -import net.eagle0.eagle.internal.event_for_chronicle.{ - EventForChronicle, - FactionDestroyedEvent, - ProvinceExpansionEvent -} +import net.eagle0.eagle.internal.event_for_chronicle.{EventForChronicle, FactionDestroyedEvent, ProvinceExpansionEvent} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.generated_text_request.ChronicleUpdateMessage import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.ChronicleWordCount -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class ChronicleUpdatePromptGeneratorTest - extends AnyFlatSpec - with BeforeAndAfterEach - with MockFactory - with Matchers { +class ChronicleUpdatePromptGeneratorTest extends AnyFlatSpec with BeforeAndAfterEach with MockFactory with Matchers { override def beforeEach(): Unit = { super.beforeEach() @@ -143,31 +131,31 @@ class ChronicleUpdatePromptGeneratorTest case TextGenerationSuccess(text) => text case _ => fail("Text generation failed") } - val expectedText = + val expectedText = s"""This is a fantasy setting with a medieval technology level. Multiple factions are engaged in a civil war for control of the kingdom. Write a 250-word chronicle of the state of the war, as told by an in-universe chronicler, who writes in the style and format of a modern journalist (but without reproducing any copyrighted material), as of October of the Year of the Realm 343. - | - |${MapDescription.mapDescription} - | - |The first block of text below is the list of previous chronicle entries, with dates. These were probably written by different chroniclers, so the information in them is relevant, but the style may differ. The second block of text lists major events that happened since that last story. The third block of text lists the major surviving factions and what provinces they control. The update should be roughly chronological for the events of the last year, but more thematic, focusing on major trends, for the previous history. Not all the events need to be included, focus on the most important developments during the time period covered. The chronicler's description should not be separated into blocks, but told in medieval terms. Do not include any other context beyond the in-world text of the response itself. Start with a title of no more than five words, then \"=====\" on a separate line, then the main text of the chronicle, like this: - |This is a title - |===== - |This is the chronicle text - |--- - |FIRST SECTION - |January 342 - |Last year's title - |===== - |Last year's text - |--- - |SECOND SECTION - |January 344 Vengeance is no more. - |April 344 The King's Loyalists expanded peacefully into Faluria. - |--- - |THIRD SECTION - |The Eagle's Faction, led by The Eagle, controls Gorania. The Eagle is a mysterious stranger from afar. - |The King's Loyalists, led by Bregos Fyar, controls Faluria. Bregos Fyar is the King of the realm. - |Vengeance, led by Bridget, controls Hakaria and Igaria. Bridget is an enigmatic mage. - |""".stripMargin + | + |${MapDescription.mapDescription} + | + |The first block of text below is the list of previous chronicle entries, with dates. These were probably written by different chroniclers, so the information in them is relevant, but the style may differ. The second block of text lists major events that happened since that last story. The third block of text lists the major surviving factions and what provinces they control. The update should be roughly chronological for the events of the last year, but more thematic, focusing on major trends, for the previous history. Not all the events need to be included, focus on the most important developments during the time period covered. The chronicler's description should not be separated into blocks, but told in medieval terms. Do not include any other context beyond the in-world text of the response itself. Start with a title of no more than five words, then \"=====\" on a separate line, then the main text of the chronicle, like this: + |This is a title + |===== + |This is the chronicle text + |--- + |FIRST SECTION + |January 342 + |Last year's title + |===== + |Last year's text + |--- + |SECOND SECTION + |January 344 Vengeance is no more. + |April 344 The King's Loyalists expanded peacefully into Faluria. + |--- + |THIRD SECTION + |The Eagle's Faction, led by The Eagle, controls Gorania. The Eagle is a mysterious stranger from afar. + |The King's Loyalists, led by Bregos Fyar, controls Faluria. Bregos Fyar is the King of the realm. + |Vengeance, led by Bridget, controls Hakaria and Igaria. Bridget is an enigmatic mage. + |""".stripMargin generatedText shouldBe expectedText } diff --git a/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilitiesTest.scala b/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilitiesTest.scala index 621861c65c..cfc15a106d 100644 --- a/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilitiesTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/actions/llm_prompt_generators/GeneratorUtilitiesTest.scala @@ -7,11 +7,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class GeneratorUtilitiesTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach - with MockFactory { +class GeneratorUtilitiesTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach with MockFactory { "conjunction with zero items" should "return None" in { GeneratorUtilities.conjunction(words = Vector.empty) shouldBe empty @@ -24,25 +20,21 @@ class GeneratorUtilitiesTest } "conjunction with two items" should "join them with and" in { - GeneratorUtilities.conjunction(words = - Vector("first", "second") - ) shouldBe Some("first and second") + GeneratorUtilities.conjunction(words = Vector("first", "second")) shouldBe Some("first and second") } "conjunction with three items" should "join them with an oxford comma" in { - GeneratorUtilities.conjunction(words = - Vector("first", "second", "third") - ) shouldBe Some("first, second, and third") + GeneratorUtilities.conjunction(words = Vector("first", "second", "third")) shouldBe Some("first, second, and third") } "conjunction with five items" should "join them with an oxford comma" in { - GeneratorUtilities.conjunction(words = - Vector("first", "second", "third", "fourth", "fifth") - ) shouldBe Some("first, second, third, fourth, and fifth") + GeneratorUtilities.conjunction(words = Vector("first", "second", "third", "fourth", "fifth")) shouldBe Some( + "first, second, third, fourth, and fifth" + ) } "basicSetup" should "not contain any newlines" in { - val gameState = GameState() + val gameState = GameState() val clientTextStore = mock[ClientTextStore] GeneratorUtilities .basicSetup( diff --git a/src/test/scala/net/eagle0/eagle/library/util/BattalionPowerTest.scala b/src/test/scala/net/eagle0/eagle/library/util/BattalionPowerTest.scala index 84d5495d6f..0a25d23bc4 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/BattalionPowerTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/BattalionPowerTest.scala @@ -12,9 +12,9 @@ class BattalionPowerTest extends AnyFlatSpec with Matchers { BattalionC(id = 1, typeId = BattalionTypeId.LightInfantry, size = 100) val heavyInfantry = BattalionC(id = 2, typeId = BattalionTypeId.HeavyInfantry, size = 100) - val heavyCavalry = + val heavyCavalry = BattalionC(id = 3, typeId = BattalionTypeId.HeavyCavalry, size = 100) - val longbowmen = + val longbowmen = BattalionC(id = 4, typeId = BattalionTypeId.Longbowmen, size = 100) BattalionPower.power( @@ -37,12 +37,12 @@ class BattalionPowerTest extends AnyFlatSpec with Matchers { val large = BattalionC(id = 2, typeId = BattalionTypeId.LightInfantry, size = 200) - BattalionPower.power(small) shouldBe 50.0 // 1.0 * 50 * 1.0 * 1.0 + BattalionPower.power(small) shouldBe 50.0 // 1.0 * 50 * 1.0 * 1.0 BattalionPower.power(large) shouldBe 200.0 // 1.0 * 200 * 1.0 * 1.0 } it should "apply armament bonuses multiplicatively" in { - val noArmament = BattalionC( + val noArmament = BattalionC( id = 1, typeId = BattalionTypeId.LightInfantry, size = 100, @@ -58,11 +58,11 @@ class BattalionPowerTest extends AnyFlatSpec with Matchers { BattalionPower.power(noArmament) shouldBe 100.0 // 1.0 * 100 * 1.0 * 1.0 BattalionPower.power( withArmament - ) shouldBe 150.0 // 1.0 * 100 * (1.0 + 0.5) * 1.0 + ) shouldBe 150.0 // 1.0 * 100 * (1.0 + 0.5) * 1.0 } it should "apply training bonuses multiplicatively" in { - val noTraining = BattalionC( + val noTraining = BattalionC( id = 1, typeId = BattalionTypeId.LightInfantry, size = 100, @@ -78,7 +78,7 @@ class BattalionPowerTest extends AnyFlatSpec with Matchers { BattalionPower.power(noTraining) shouldBe 100.0 // 1.0 * 100 * 1.0 * 1.0 BattalionPower.power( withTraining - ) shouldBe 125.0 // 1.0 * 100 * 1.0 * (1.0 + 0.25) + ) shouldBe 125.0 // 1.0 * 100 * 1.0 * (1.0 + 0.25) } it should "apply both armament and training bonuses together" in { diff --git a/src/test/scala/net/eagle0/eagle/library/util/BattalionSuitabilityTest.scala b/src/test/scala/net/eagle0/eagle/library/util/BattalionSuitabilityTest.scala index fc350fa08d..53cbadbbb0 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/BattalionSuitabilityTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/BattalionSuitabilityTest.scala @@ -7,12 +7,7 @@ import net.eagle0.eagle.api.command.util.appropriate_battalions.SuitableBattalio SUBOPTIMAL } import net.eagle0.eagle.common.battalion_type.BattalionTypeId -import net.eagle0.eagle.common.profession.Profession.{ - ENGINEER, - MAGE, - NECROMANCER, - RANGER -} +import net.eagle0.eagle.common.profession.Profession.{ENGINEER, MAGE, NECROMANCER, RANGER} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.hero.Hero import org.scalatest.flatspec.AnyFlatSpec diff --git a/src/test/scala/net/eagle0/eagle/library/util/DateProtoUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/DateProtoUtilsTest.scala index 9d60391cc5..122e72aed9 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/DateProtoUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/DateProtoUtilsTest.scala @@ -15,7 +15,7 @@ class DateProtoUtilsTest extends AnyFlatSpec with Matchers { } ">=" should "return true if it's >=" in { - val leftDate = Date(year = 1501, month = 7) + val leftDate = Date(year = 1501, month = 7) val rightDate = Date(year = 1501, month = 4) leftDate >= rightDate shouldBe true diff --git a/src/test/scala/net/eagle0/eagle/library/util/GameStateViewFilterTest.scala b/src/test/scala/net/eagle0/eagle/library/util/GameStateViewFilterTest.scala index 0a26a7d08a..a1464a244a 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/GameStateViewFilterTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/GameStateViewFilterTest.scala @@ -2,18 +2,8 @@ package net.eagle0.eagle.library.util import net.eagle0.common.hostility.Hostility import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.common.profession.Profession.{ - ENGINEER, - MAGE, - NO_PROFESSION, - PALADIN, - RANGER -} -import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{ - DEVELOP, - ENTRUST, - MOBILIZE -} +import net.eagle0.eagle.common.profession.Profession.{ENGINEER, MAGE, NO_PROFESSION, PALADIN, RANGER} +import net.eagle0.eagle.common.province_order_type.ProvinceOrderType.{DEVELOP, ENTRUST, MOBILIZE} import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.* import net.eagle0.eagle.common.round_phase.RoundPhase @@ -45,29 +35,15 @@ import net.eagle0.eagle.library.util.view_filters.GameStateViewFilter import net.eagle0.eagle.views.faction_view.FactionView import net.eagle0.eagle.views.game_state_view.GameStateView import net.eagle0.eagle.views.hero_view.{HeroSortKey, HeroView} -import net.eagle0.eagle.views.province_view.{ - FullProvinceInfo, - ProvinceView, - UnaffiliatedHeroBasics -} -import net.eagle0.eagle.views.shardok_battle_view.{ - ShardokBattlePlayerInfo, - ShardokBattleView -} +import net.eagle0.eagle.views.province_view.{FullProvinceInfo, ProvinceView, UnaffiliatedHeroBasics} +import net.eagle0.eagle.views.shardok_battle_view.{ShardokBattlePlayerInfo, ShardokBattleView} import net.eagle0.eagle.views.stat_with_condition.StatWithCondition -import net.eagle0.eagle.views.stat_with_condition.StatWithCondition.Condition.{ - HIGH, - LOW, - MEDIUM -} +import net.eagle0.eagle.views.stat_with_condition.StatWithCondition.Condition.{HIGH, LOW, MEDIUM} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class GameStateViewFilterTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class GameStateViewFilterTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { import net.eagle0.common.ProtoMatchers.* @@ -88,13 +64,13 @@ class GameStateViewFilterTest ) private val factions = Map( - 3 -> Faction( + 3 -> Faction( id = 3, factionHeadId = 8, leaders = Vector(8), name = "Jane's Faction" ), - 7 -> Faction( + 7 -> Faction( id = 7, factionHeadId = 12, leaders = Vector(12), @@ -129,8 +105,7 @@ class GameStateViewFilterTest UnaffiliatedHero( heroId = 29, `type` = UNAFFILIATED_HERO_TRAVELER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_TRAVELER)) ), UnaffiliatedHero( heroId = 11, @@ -170,8 +145,7 @@ class GameStateViewFilterTest UnaffiliatedHero( heroId = 33, `type` = UNAFFILIATED_HERO_PRISONER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ), gold = 1500, @@ -191,20 +165,17 @@ class GameStateViewFilterTest UnaffiliatedHero( heroId = 55, `type` = UNAFFILIATED_HERO_OUTLAW, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ), UnaffiliatedHero( heroId = 56, `type` = UNAFFILIATED_HERO_RESIDENT, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_LOW_PRESTIGE)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_LOW_PRESTIGE)) ), UnaffiliatedHero( heroId = 99, `type` = UNAFFILIATED_HERO_PRISONER, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_PRISONER)) ) ), gold = 200, @@ -213,32 +184,32 @@ class GameStateViewFilterTest ) ), heroes = Map( - 29 -> Hero( + 29 -> Hero( id = 29, profession = MAGE, nameTextId = "hn_29" ), - 11 -> Hero( + 11 -> Hero( id = 11, profession = NO_PROFESSION, nameTextId = "hn_11" ), - 33 -> Hero( + 33 -> Hero( id = 33, profession = ENGINEER, nameTextId = "hn_33" ), - 55 -> Hero( + 55 -> Hero( id = 55, profession = ENGINEER, nameTextId = "hn_55" ), - 56 -> Hero( + 56 -> Hero( id = 56, profession = RANGER, nameTextId = "hn_56" ), - 99 -> Hero( + 99 -> Hero( id = 99, profession = PALADIN, nameTextId = "hn_99" @@ -354,8 +325,7 @@ class GameStateViewFilterTest gold = 1500, food = 1600, provinceOrders = DEVELOP, - support = - Some(StatWithCondition(stat = 41, condition = MEDIUM)), + support = Some(StatWithCondition(stat = 41, condition = MEDIUM)), goldCap = 7100, foodCap = 9900, unaffiliatedHeroes = Vector( @@ -397,8 +367,7 @@ class GameStateViewFilterTest nameTextId = "hn_55", profession = ENGINEER, status = UNAFFILIATED_HERO_OUTLAW, - recruitmentInfo = - Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) + recruitmentInfo = Some(RecruitmentInfo(status = RECRUITMENT_STATUS_OUTLAW)) ), UnaffiliatedHeroBasics( heroId = 56, @@ -424,61 +393,55 @@ class GameStateViewFilterTest ) ), heroes = Map( - 29 -> HeroView( + 29 -> HeroView( id = 29, nameTextId = "hn_29", profession = MAGE, vigor = emptyCondition, loyalty = emptyCondition, startFireCapable = true, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 29).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 29).map(HeroSortKey(_)) ), - 11 -> HeroView( + 11 -> HeroView( id = 11, nameTextId = "hn_11", profession = NO_PROFESSION, vigor = emptyCondition, loyalty = emptyCondition, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 11).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 11).map(HeroSortKey(_)) ), - 33 -> HeroView( + 33 -> HeroView( id = 33, nameTextId = "hn_33", profession = ENGINEER, vigor = emptyCondition, loyalty = None, isFactionLeader = true, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 33).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 33).map(HeroSortKey(_)) ), - 55 -> HeroView( + 55 -> HeroView( id = 55, nameTextId = "hn_55", profession = ENGINEER, vigor = emptyCondition, loyalty = emptyCondition, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 55).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 55).map(HeroSortKey(_)) ), - 56 -> HeroView( + 56 -> HeroView( id = 56, nameTextId = "hn_56", profession = RANGER, vigor = emptyCondition, loyalty = emptyCondition, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 56).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 56).map(HeroSortKey(_)) ), - 99 -> HeroView( + 99 -> HeroView( id = 99, nameTextId = "hn_99", profession = PALADIN, vigor = emptyCondition, loyalty = emptyCondition, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 99).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 99).map(HeroSortKey(_)) ), 999 -> HeroView( id = 999, @@ -486,20 +449,19 @@ class GameStateViewFilterTest profession = PALADIN, vigor = emptyCondition, loyalty = emptyCondition, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 999).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 999).map(HeroSortKey(_)) ) ), battalionNames = Map(), factions = Map( - 3 -> FactionView( + 3 -> FactionView( id = 3, factionHeadId = 8, leaders = Vector(8), name = "Jane's Faction", prestige = 8 ), - 7 -> FactionView( + 7 -> FactionView( id = 7, factionHeadId = 12, leaders = Vector(12), @@ -559,8 +521,7 @@ class GameStateViewFilterTest gold = 1500, food = 1600, provinceOrders = DEVELOP, - support = - Some(StatWithCondition(stat = 41, condition = MEDIUM)), + support = Some(StatWithCondition(stat = 41, condition = MEDIUM)), goldCap = 7100, foodCap = 9900, unaffiliatedHeroes = Vector( @@ -586,49 +547,43 @@ class GameStateViewFilterTest ) ), heroes = Map( - 29 -> HeroView( + 29 -> HeroView( id = 29, nameTextId = "hn_29", profession = MAGE, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 29, false).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 29, false).map(HeroSortKey(_)) ), - 11 -> HeroView( + 11 -> HeroView( id = 11, nameTextId = "hn_11", profession = NO_PROFESSION, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 11, false).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 11, false).map(HeroSortKey(_)) ), - 33 -> HeroView( + 33 -> HeroView( id = 33, nameTextId = "hn_33", profession = ENGINEER, vigor = Some(StatWithCondition(0, LOW)), isFactionLeader = true, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 33, true).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 33, true).map(HeroSortKey(_)) ), - 55 -> HeroView( + 55 -> HeroView( id = 55, nameTextId = "hn_55", profession = ENGINEER, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 55, false).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 55, false).map(HeroSortKey(_)) ), - 56 -> HeroView( + 56 -> HeroView( id = 56, nameTextId = "hn_56", profession = RANGER, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 56, false).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 56, false).map(HeroSortKey(_)) ), - 99 -> HeroView( + 99 -> HeroView( id = 99, nameTextId = "hn_99", profession = PALADIN, - sortKeys = - LegacyHeroUtils.sortKeys(gameState, 99, false).map(HeroSortKey(_)) + sortKeys = LegacyHeroUtils.sortKeys(gameState, 99, false).map(HeroSortKey(_)) ), 999 -> HeroView( id = 999, @@ -641,13 +596,13 @@ class GameStateViewFilterTest ), battalionNames = Map(), factions = Map( - 3 -> FactionView( + 3 -> FactionView( id = 3, factionHeadId = 8, leaders = Vector(8), name = "Jane's Faction" ), - 7 -> FactionView( + 7 -> FactionView( id = 7, factionHeadId = 12, leaders = Vector(12), diff --git a/src/test/scala/net/eagle0/eagle/library/util/LegacyProvinceUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/LegacyProvinceUtilsTest.scala index da778f402a..b2f1f0c241 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/LegacyProvinceUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/LegacyProvinceUtilsTest.scala @@ -33,16 +33,13 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class LegacyProvinceUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val factionId: FactionId = 32 - private val factionHeadId: HeroId = 17 - private val leaderIdLow: HeroId = 3 - private val leaderIdHigh: HeroId = 5 - private val vassalIdLow: HeroId = 2 - private val vassalIdHigh: HeroId = 33 +class LegacyProvinceUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val factionId: FactionId = 32 + private val factionHeadId: HeroId = 17 + private val leaderIdLow: HeroId = 3 + private val leaderIdHigh: HeroId = 5 + private val vassalIdLow: HeroId = 2 + private val vassalIdHigh: HeroId = 33 private def heroWithWisdom(id: HeroId, wisdom: Int): Hero = Hero(id = id, factionId = Some(factionId), wisdom = wisdom) @@ -121,8 +118,7 @@ class LegacyProvinceUtilsTest it should "return the highest wisdom faction leader" in { val startingProvince = Province( rulingFactionId = Some(factionId), - rulingFactionHeroIds = - Vector(leaderIdLow, leaderIdHigh, vassalIdLow, vassalIdHigh) + rulingFactionHeroIds = Vector(leaderIdLow, leaderIdHigh, vassalIdLow, vassalIdHigh) ) LegacyProvinceUtils.provinceLeader( startingProvince, @@ -147,11 +143,11 @@ class LegacyProvinceUtilsTest "monthlyFoodSurplus" should "return 0 if there are no battalions and no support" in { val province = actingProvince.update( - _.support := 35, - _.food := 10000, + _.support := 35, + _.food := 10000, _.battalionIds := Vector() ) - val gs = gameState.update( + val gs = gameState.update( _.provinces(province.id) := province ) @@ -163,14 +159,14 @@ class LegacyProvinceUtilsTest it should "return currentFood / monthsRemaining if that is less than production amount" in { val province = actingProvince.update( - _.agriculture := 100, - _.support := 50, - _.food := 600, + _.agriculture := 100, + _.support := 50, + _.food := 600, _.battalionIds := Vector() ) - val gs = gameState.update( + val gs = gameState.update( _.provinces(province.id) := province, - _.currentDate.month := 6 // 6 months remaining + _.currentDate.month := 6 // 6 months remaining ) LegacyProvinceUtils.monthlyFoodSurplus( @@ -181,14 +177,14 @@ class LegacyProvinceUtilsTest it should "return productionAmount / 12 if that is less than the food remaining / months" in { val province = actingProvince.update( - _.agriculture := 100, // 5000 production, or 5000 / 12 == 416 per month - _.support := 50, - _.food := 12000, + _.agriculture := 100, // 5000 production, or 5000 / 12 == 416 per month + _.support := 50, + _.food := 12000, _.battalionIds := Vector() ) - val gs = gameState.update( + val gs = gameState.update( _.provinces(province.id) := province, - _.currentDate.month := 6 // 6 months remaining + _.currentDate.month := 6 // 6 months remaining ) LegacyProvinceUtils.monthlyFoodSurplus( @@ -199,26 +195,26 @@ class LegacyProvinceUtilsTest it should "reduce the surplus by the consumption of existing battalions" in { val province = actingProvince.update( - _.agriculture := 100, // 5000 production, or 5000 / 12 == 416 per month - _.support := 50, - _.food := 12000, + _.agriculture := 100, // 5000 production, or 5000 / 12 == 416 per month + _.support := 50, + _.food := 12000, _.battalionIds := Vector(1, 2) ) - val gs = gameState.update( + val gs = gameState.update( _.provinces(province.id) := province, - _.currentDate.month := 6, // 6 months remaining - _.battalions := IDable.mapifyBattalions( + _.currentDate.month := 6, // 6 months remaining + _.battalions := IDable.mapifyBattalions( Battalion(id = 1, `type` = LIGHT_INFANTRY, size = 1000), Battalion(id = 2, `type` = HEAVY_CAVALRY, size = 600).withId(2) ), - _.battalionTypes := Vector( + _.battalionTypes := Vector( BattalionType(typeId = LIGHT_INFANTRY, monthlyFoodCost = 0.65), BattalionType(typeId = HEAVY_CAVALRY, monthlyFoodCost = 1.50) ) ) val consumption = 650 + 900 - val surplus = 416 - consumption + val surplus = 416 - consumption LegacyProvinceUtils.monthlyFoodSurplus( provinceId = actingProvince.id, @@ -353,8 +349,8 @@ class LegacyProvinceUtilsTest } "provinceLeaderSeniority" should "be 5 if the faction head is in the province" in { - val fid = 4 - val province = Province( + val fid = 4 + val province = Province( id = 17, rulingFactionId = Some(fid), rulingFactionHeroIds = Vector(1, 10, 20) @@ -374,8 +370,8 @@ class LegacyProvinceUtilsTest } it should "be 4 if the faction head is en route to the province" in { - val fid = 4 - val province = Province( + val fid = 4 + val province = Province( id = 17, rulingFactionId = Some(fid), rulingFactionHeroIds = Vector(10, 20), @@ -407,8 +403,8 @@ class LegacyProvinceUtilsTest } it should "be 3 if a faction leader is in the province" in { - val fid = 4 - val province = Province( + val fid = 4 + val province = Province( id = 17, rulingFactionId = Some(fid), rulingFactionHeroIds = Vector(10, 20) @@ -428,8 +424,8 @@ class LegacyProvinceUtilsTest } it should "be 2 if a faction leader is en route to the province" in { - val fid = 4 - val province = Province( + val fid = 4 + val province = Province( id = 17, rulingFactionId = Some(fid), rulingFactionHeroIds = Vector(10), @@ -461,8 +457,8 @@ class LegacyProvinceUtilsTest } it should "be 1 if no faction leader is present or en route" in { - val fid = 4 - val province = Province( + val fid = 4 + val province = Province( id = 17, rulingFactionId = Some(fid), rulingFactionHeroIds = Vector(10) @@ -482,8 +478,8 @@ class LegacyProvinceUtilsTest } it should "be 0 if the province is unowned" in { - val fid = 4 - val province = Province( + val fid = 4 + val province = Province( id = 17 ) val gameState = GameState( diff --git a/src/test/scala/net/eagle0/eagle/library/util/PriceIndexUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/PriceIndexUtilsTest.scala index 5d4d99e469..0b1abba021 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/PriceIndexUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/PriceIndexUtilsTest.scala @@ -10,10 +10,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class PriceIndexUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class PriceIndexUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { MinimumPriceIndex.setDoubleValue(0.6) MaximumPriceIndex.setDoubleValue(1.6) diff --git a/src/test/scala/net/eagle0/eagle/library/util/ProvinceUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/ProvinceUtilsTest.scala index 68f68424e0..45faba7f48 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/ProvinceUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/ProvinceUtilsTest.scala @@ -30,16 +30,13 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class ProvinceUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { - private val factionId: FactionId = 32 - private val factionHeadId: HeroId = 17 - private val leaderIdLow: HeroId = 3 - private val leaderIdHigh: HeroId = 5 - private val vassalIdLow: HeroId = 2 - private val vassalIdHigh: HeroId = 33 +class ProvinceUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { + private val factionId: FactionId = 32 + private val factionHeadId: HeroId = 17 + private val leaderIdLow: HeroId = 3 + private val leaderIdHigh: HeroId = 5 + private val vassalIdLow: HeroId = 2 + private val vassalIdHigh: HeroId = 33 private def heroWithWisdom(id: HeroId, wisdom: Int): HeroT = HeroC( id = id, @@ -117,8 +114,7 @@ class ProvinceUtilsTest ProvinceC( id = 7, rulingFactionId = Some(factionId), - rulingFactionHeroIds = - Vector(leaderIdLow, leaderIdHigh, vassalIdLow, vassalIdHigh) + rulingFactionHeroIds = Vector(leaderIdLow, leaderIdHigh, vassalIdLow, vassalIdHigh) ) ProvinceUtils.provinceLeader( startingProvince = startingProvince, diff --git a/src/test/scala/net/eagle0/eagle/library/util/ReturningHeroesTest.scala b/src/test/scala/net/eagle0/eagle/library/util/ReturningHeroesTest.scala index f9868d2ce3..698cd8ab36 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/ReturningHeroesTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/ReturningHeroesTest.scala @@ -20,33 +20,30 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class ReturningHeroesTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class ReturningHeroesTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - private val factionId = 7 - private val hids = Vector(3, 4, 5) + private val factionId = 7 + private val hids = Vector(3, 4, 5) private val currentRoundId: RoundId = 27 - private val originProvince = ProvinceC( + private val originProvince = ProvinceC( id = 12, rulingFactionId = Some(factionId), rulingHeroId = Some(6), rulingFactionHeroIds = Vector(6) ) - private val other1 = ProvinceC( + private val other1 = ProvinceC( id = 13, rulingFactionId = Some(factionId), rulingHeroId = Some(7), rulingFactionHeroIds = Vector(7) ) - private val other2 = ProvinceC( + private val other2 = ProvinceC( id = 14, rulingFactionId = Some(factionId), rulingHeroId = Some(8), rulingFactionHeroIds = Vector(8) ) - private val movingArmy = MovingArmy( + private val movingArmy = MovingArmy( id = 72, originProvinceId = 12, destinationProvinceId = 15, @@ -71,19 +68,16 @@ class ReturningHeroesTest incomingArmies = Vector(movingArmy) ) - private val heroes: Vector[HeroT] = Vector(3, 4, 5, 6, 7, 8).map(hid => - HeroC(id = hid, factionId = Some(factionId)) - ) + private val heroes: Vector[HeroT] = Vector(3, 4, 5, 6, 7, 8).map(hid => HeroC(id = hid, factionId = Some(factionId))) private val provinces: Vector[ProvinceT] = Vector(originProvince, other1, other2, hostile) - private val random = new Random() + private val random = new Random() private var functionalRandom = SeededRandom(0) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = functionalRandom = SeededRandom(random.nextLong()) - } "heroesReturningToFaction" should "return the heroes to the origin province if it's available" in { val result = ReturningHeroes @@ -97,9 +91,10 @@ class ReturningHeroesTest .newValue result.changedHeroes shouldBe empty - inside(result.changedProvince) { case cp: ChangedProvinceC => - cp.provinceId shouldBe originProvince.id - cp.newRulingFactionHeroIds shouldBe hids + inside(result.changedProvince) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe originProvince.id + cp.newRulingFactionHeroIds shouldBe hids } } @@ -109,16 +104,16 @@ class ReturningHeroesTest hids = hids, factionId = factionId, originProvince = originProvince.clearRulingFactionId, - provinces = - Vector(originProvince.clearRulingFactionId, other1, other2, hostile), + provinces = Vector(originProvince.clearRulingFactionId, other1, other2, hostile), functionalRandom = functionalRandom ) .newValue result.changedHeroes shouldBe empty - inside(result.changedProvince) { case cp: ChangedProvinceC => - cp.provinceId should (be(other1.id) or be(other2.id)) - cp.newRulingFactionHeroIds shouldBe hids + inside(result.changedProvince) { + case cp: ChangedProvinceC => + cp.provinceId should (be(other1.id) or be(other2.id)) + cp.newRulingFactionHeroIds shouldBe hids } } @@ -141,16 +136,18 @@ class ReturningHeroesTest .newValue result.changedHeroes shouldBe empty - inside(result.changedProvince) { case cp: ChangedProvinceC => - cp.provinceId shouldBe hostile.id - cp.removedIncomingArmyIds shouldBe Vector(movingArmy.id) - inside(cp.newIncomingArmies.loneElement) { case ma: MovingArmy => - ma.army.units.map( - _.heroId - ) should contain theSameElementsAs hids ++ movingArmy.army.units.map( - _.heroId - ) - } + inside(result.changedProvince) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe hostile.id + cp.removedIncomingArmyIds shouldBe Vector(movingArmy.id) + inside(cp.newIncomingArmies.loneElement) { + case ma: MovingArmy => + ma.army.units.map( + _.heroId + ) should contain theSameElementsAs hids ++ movingArmy.army.units.map( + _.heroId + ) + } } } @@ -172,19 +169,18 @@ class ReturningHeroesTest ) .newValue - result.changedHeroes shouldBe hids.map(hid => - ChangedHeroC(heroId = hid, clearFactionId = true) - ) - inside(result.changedProvince) { case cp: ChangedProvinceC => - cp.provinceId shouldBe originProvince.id - cp.newUnaffiliatedHeroes shouldBe hids.map(hid => - UnaffiliatedHeroC( - heroId = hid, - unaffiliatedHeroType = Outlaw, - recruitmentAttempted = false, - recruitmentInfo = RecruitmentInfo.Outlaw + result.changedHeroes shouldBe hids.map(hid => ChangedHeroC(heroId = hid, clearFactionId = true)) + inside(result.changedProvince) { + case cp: ChangedProvinceC => + cp.provinceId shouldBe originProvince.id + cp.newUnaffiliatedHeroes shouldBe hids.map(hid => + UnaffiliatedHeroC( + heroId = hid, + unaffiliatedHeroType = Outlaw, + recruitmentAttempted = false, + recruitmentInfo = RecruitmentInfo.Outlaw + ) ) - ) } } } diff --git a/src/test/scala/net/eagle0/eagle/library/util/ShardokMapInfoTest.scala b/src/test/scala/net/eagle0/eagle/library/util/ShardokMapInfoTest.scala index b85f6ff61f..a8f1736998 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/ShardokMapInfoTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/ShardokMapInfoTest.scala @@ -5,14 +5,10 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class ShardokMapInfoTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class ShardokMapInfoTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - override def beforeEach(): Unit = { + override def beforeEach(): Unit = HeroCapPerCastle.setIntValue(3) - } "mapInfos" should "have Shumal's info in position 1" in { val mapInfos = ShardokMapInfo.shardokMapInfos @@ -28,8 +24,7 @@ class ShardokMapInfoTest mapInfos(37) shouldBe ExpandedShardokMapInfo( provinceId = 37, castleCount = 4, - waterCrossingRequirementsByPosition = - Map(0 -> 0, 1 -> 0, 3 -> 0, 4 -> 0, 5 -> 0, 6 -> 0, 7 -> 0) + waterCrossingRequirementsByPosition = Map(0 -> 0, 1 -> 0, 3 -> 0, 4 -> 0, 5 -> 0, 6 -> 0, 7 -> 0) ) } @@ -38,8 +33,7 @@ class ShardokMapInfoTest mapInfos(19) shouldBe ExpandedShardokMapInfo( provinceId = 19, castleCount = 3, - waterCrossingRequirementsByPosition = - Map(0 -> 10, 1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0, 5 -> 0, 6 -> 0, 7 -> 4) + waterCrossingRequirementsByPosition = Map(0 -> 10, 1 -> 0, 2 -> 0, 3 -> 0, 4 -> 0, 5 -> 0, 6 -> 0, 7 -> 4) ) } diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelectorTest.scala index eaaea8b474..aa11666a60 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AllianceOfferCommandSelectorTest.scala @@ -6,10 +6,7 @@ import net.eagle0.eagle.api.available_command.{ RestAvailableCommand, TravelAvailableCommand } -import net.eagle0.eagle.api.command.util.diplomacy_option.{ - AllianceOption, - InvitationOption -} +import net.eagle0.eagle.api.command.util.diplomacy_option.{AllianceOption, InvitationOption} import net.eagle0.eagle.api.selected_command.DiplomacySelectedCommand import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState @@ -20,10 +17,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AllianceOfferCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AllianceOfferCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val actingFactionId = 5 @@ -117,9 +111,9 @@ class AllianceOfferCommandSelectorTest AllianceOfferCommandSelector.chosenAllianceWithFactionCommand( actingFactionId = actingFactionId, gameState = gameState.update( - _.heroes(1).vigor := 100, - _.heroes(2).vigor := 80, - _.heroes(3).vigor := 100, + _.heroes(1).vigor := 100, + _.heroes(2).vigor := 80, + _.heroes(3).vigor := 100, _.factions(actingFactionId).leaders := Vector(1, 3) ), availableCommands = availableCommands, diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelectorTest.scala index c7132e8deb..581d06abcc 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AlmsCommandSelectorTest.scala @@ -10,25 +10,14 @@ import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - AlmsPaladinSupportMultiplier, - AlmsSupportIncreasePerFood, - MinSupportForTaxes -} +import net.eagle0.eagle.library.settings.{AlmsPaladinSupportMultiplier, AlmsSupportIncreasePerFood, MinSupportForTaxes} import net.eagle0.eagle.library.util.{BattalionTypesTestData, CommandSelection} -import net.eagle0.eagle.library.util.IDable.{ - mapifyBattalions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyBattalions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AlmsCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AlmsCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val battalionTypes = BattalionTypesTestData.battalionTypes diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooserTest.scala index faf9e2d032..d67bb2de7e 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackCommandChooserTest.scala @@ -31,19 +31,12 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.util.{BattalionTypesTestData, CommandSelection} import net.eagle0.eagle.library.util.DateProtoUtils._Date -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AttackCommandChooserTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AttackCommandChooserTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val battalionTypes = BattalionTypesTestData.battalionTypes @@ -95,10 +88,10 @@ class AttackCommandChooserTest ) ) - private val actingFactionId = 33 + private val actingFactionId = 33 private val destinationFactionId = 12 - private val originProvinceId = 10 + private val originProvinceId = 10 private val destinationProvinceId = 6 private val gameState = GameState( @@ -220,7 +213,7 @@ class AttackCommandChooserTest resetDate = gameState.currentDate.map(_.addMonths(1)) ) ), - _.factions(actingFactionId).factionRelationships := Vector( + _.factions(actingFactionId).factionRelationships := Vector( FactionRelationship( targetFactionId = destinationFactionId, relationshipLevel = TRUCE, @@ -247,7 +240,7 @@ class AttackCommandChooserTest resetDate = gameState.currentDate ) ), - _.factions(actingFactionId).factionRelationships := Vector( + _.factions(actingFactionId).factionRelationships := Vector( FactionRelationship( targetFactionId = destinationFactionId, relationshipLevel = TRUCE, diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooserTest.scala index e7e0c5cea5..29e5f45b24 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AttackDecisionCommandChooserTest.scala @@ -4,20 +4,12 @@ import net.eagle0.common.hostility.Hostility import net.eagle0.common.SeededRandom import net.eagle0.eagle.api.available_command.* import net.eagle0.eagle.api.command.util.army_stats.ArmyStats -import net.eagle0.eagle.api.command.util.attack_decision_type.{ - AdvanceDecision, - WithdrawDecision -} +import net.eagle0.eagle.api.command.util.attack_decision_type.{AdvanceDecision, WithdrawDecision} import net.eagle0.eagle.api.selected_command.AttackDecisionSelectedCommand import net.eagle0.eagle.common.battalion_type.BattalionTypeId.LIGHT_INFANTRY import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.internal.army.{ - Army, - AwaitingDecision, - HostileArmyGroup, - MovingArmy -} +import net.eagle0.eagle.internal.army.{Army, AwaitingDecision, HostileArmyGroup, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState @@ -25,25 +17,16 @@ import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.library.settings.MinimumPercentageOfEnemyToAttack import net.eagle0.eagle.library.util.BattalionTypesTestData -import net.eagle0.eagle.library.util.IDable.{ - mapifyBattalions, - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyBattalions, mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class AttackDecisionCommandChooserTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class AttackDecisionCommandChooserTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinimumPercentageOfEnemyToAttack.setDoubleValue(0.6) - } private val battalionTypes = BattalionTypesTestData.battalionTypes @@ -74,13 +57,11 @@ class AttackDecisionCommandChooserTest // Create armies with these battalions val army1 = Army( factionId = 1, - units = - Vector(CombatUnit(factionId = 1, heroId = 1, battalionId = Some(101))) + units = Vector(CombatUnit(factionId = 1, heroId = 1, battalionId = Some(101))) ) val army2 = Army( factionId = 1, - units = - Vector(CombatUnit(factionId = 1, heroId = 2, battalionId = Some(102))) + units = Vector(CombatUnit(factionId = 1, heroId = 2, battalionId = Some(102))) ) // Create moving armies @@ -105,12 +86,11 @@ class AttackDecisionCommandChooserTest ) // Create enemy HostileArmyGroup - val enemyArmy = Army( + val enemyArmy = Army( factionId = 2, - units = - Vector(CombatUnit(factionId = 2, heroId = 3, battalionId = Some(103))) + units = Vector(CombatUnit(factionId = 2, heroId = 3, battalionId = Some(103))) ) - val enemyMovingArmy = MovingArmy( + val enemyMovingArmy = MovingArmy( army = Some(enemyArmy), arrivalRound = 0, destinationProvince = 10, @@ -202,13 +182,11 @@ class AttackDecisionCommandChooserTest // Create armies val friendlyArmy = Army( factionId = 1, - units = - Vector(CombatUnit(factionId = 1, heroId = 1, battalionId = Some(201))) + units = Vector(CombatUnit(factionId = 1, heroId = 1, battalionId = Some(201))) ) - val enemyArmy = Army( + val enemyArmy = Army( factionId = 2, - units = - Vector(CombatUnit(factionId = 2, heroId = 2, battalionId = Some(202))) + units = Vector(CombatUnit(factionId = 2, heroId = 2, battalionId = Some(202))) ) // Create moving armies @@ -218,7 +196,7 @@ class AttackDecisionCommandChooserTest destinationProvince = 20, originProvince = 15 ) - val enemyMovingArmy = MovingArmy( + val enemyMovingArmy = MovingArmy( army = Some(enemyArmy), arrivalRound = 0, destinationProvince = 20, @@ -231,7 +209,7 @@ class AttackDecisionCommandChooserTest armies = Vector(friendlyMovingArmy), status = AwaitingDecision() ) - val enemyHostileArmyGroup = HostileArmyGroup( + val enemyHostileArmyGroup = HostileArmyGroup( factionId = 2, armies = Vector(enemyMovingArmy), status = AwaitingDecision() @@ -296,21 +274,21 @@ class AttackDecisionCommandChooserTest } it should "correctly sum multiple armies instead of using just one" in { - val battalion1 = Battalion( + val battalion1 = Battalion( id = 301, size = 600, `type` = LIGHT_INFANTRY, armament = 50.0, training = 50.0 ) - val battalion2 = Battalion( + val battalion2 = Battalion( id = 302, size = 600, `type` = LIGHT_INFANTRY, armament = 50.0, training = 50.0 ) - val battalion3 = Battalion( + val battalion3 = Battalion( id = 303, size = 600, `type` = LIGHT_INFANTRY, @@ -326,25 +304,25 @@ class AttackDecisionCommandChooserTest ) // Three small armies that together are strong enough - val army1 = Army(factionId = 1, units = Vector(CombatUnit(1, 1, Some(301)))) - val army2 = Army(factionId = 1, units = Vector(CombatUnit(1, 2, Some(302)))) - val army3 = Army(factionId = 1, units = Vector(CombatUnit(1, 3, Some(303)))) + val army1 = Army(factionId = 1, units = Vector(CombatUnit(1, 1, Some(301)))) + val army2 = Army(factionId = 1, units = Vector(CombatUnit(1, 2, Some(302)))) + val army3 = Army(factionId = 1, units = Vector(CombatUnit(1, 3, Some(303)))) val enemyArmy = Army(factionId = 2, units = Vector(CombatUnit(2, 4, Some(304)))) - val movingArmy1 = MovingArmy( + val movingArmy1 = MovingArmy( army = Some(army1), arrivalRound = 0, destinationProvince = 30, originProvince = 25 ) - val movingArmy2 = MovingArmy( + val movingArmy2 = MovingArmy( army = Some(army2), arrivalRound = 0, destinationProvince = 30, originProvince = 25 ) - val movingArmy3 = MovingArmy( + val movingArmy3 = MovingArmy( army = Some(army3), arrivalRound = 0, destinationProvince = 30, @@ -363,7 +341,7 @@ class AttackDecisionCommandChooserTest armies = Vector(movingArmy1, movingArmy2, movingArmy3), status = AwaitingDecision() ) - val enemyHostileArmyGroup = HostileArmyGroup( + val enemyHostileArmyGroup = HostileArmyGroup( factionId = 2, armies = Vector(enemyMovingArmy), status = AwaitingDecision() @@ -378,8 +356,7 @@ class AttackDecisionCommandChooserTest currentDate = Some(Date(year = 501, month = 1)), battalionTypes = battalionTypes, provinces = mapifyProvinces(province), - battalions = - mapifyBattalions(battalion1, battalion2, battalion3, enemyBattalion), + battalions = mapifyBattalions(battalion1, battalion2, battalion3, enemyBattalion), heroes = mapifyHeroes( Hero(id = 1, factionId = Some(1)), Hero(id = 2, factionId = Some(1)), @@ -427,21 +404,21 @@ class AttackDecisionCommandChooserTest it should "withdraw when summed armies are still insufficient against a strong enemy" in { // Test case: Multiple small armies that even when summed are not enough - val smallBattalion1 = Battalion( + val smallBattalion1 = Battalion( id = 401, size = 200, `type` = LIGHT_INFANTRY, armament = 50.0, training = 50.0 ) - val smallBattalion2 = Battalion( + val smallBattalion2 = Battalion( id = 402, size = 200, `type` = LIGHT_INFANTRY, armament = 50.0, training = 50.0 ) - val smallBattalion3 = Battalion( + val smallBattalion3 = Battalion( id = 403, size = 200, `type` = LIGHT_INFANTRY, @@ -457,25 +434,25 @@ class AttackDecisionCommandChooserTest ) // Three very small armies - val army1 = Army(factionId = 1, units = Vector(CombatUnit(1, 1, Some(401)))) - val army2 = Army(factionId = 1, units = Vector(CombatUnit(1, 2, Some(402)))) - val army3 = Army(factionId = 1, units = Vector(CombatUnit(1, 3, Some(403)))) + val army1 = Army(factionId = 1, units = Vector(CombatUnit(1, 1, Some(401)))) + val army2 = Army(factionId = 1, units = Vector(CombatUnit(1, 2, Some(402)))) + val army3 = Army(factionId = 1, units = Vector(CombatUnit(1, 3, Some(403)))) val strongEnemyArmy = Army(factionId = 2, units = Vector(CombatUnit(2, 4, Some(404)))) - val movingArmy1 = MovingArmy( + val movingArmy1 = MovingArmy( army = Some(army1), arrivalRound = 0, destinationProvince = 40, originProvince = 35 ) - val movingArmy2 = MovingArmy( + val movingArmy2 = MovingArmy( army = Some(army2), arrivalRound = 0, destinationProvince = 40, originProvince = 35 ) - val movingArmy3 = MovingArmy( + val movingArmy3 = MovingArmy( army = Some(army3), arrivalRound = 0, destinationProvince = 40, @@ -494,7 +471,7 @@ class AttackDecisionCommandChooserTest armies = Vector(movingArmy1, movingArmy2, movingArmy3), status = AwaitingDecision() ) - val enemyHostileArmyGroup = HostileArmyGroup( + val enemyHostileArmyGroup = HostileArmyGroup( factionId = 2, armies = Vector(strongEnemyMovingArmy), status = AwaitingDecision() @@ -533,7 +510,7 @@ class AttackDecisionCommandChooserTest armies = Vector( ArmyStats( factionId = 1, - troopCount = 600, // Total from all three small armies + troopCount = 600, // Total from all three small armies hostility = Hostility.SELF_HOSTILITY ), ArmyStats( diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandMatcher.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandMatcher.scala index 33a9c05d48..77a02abab8 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandMatcher.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandMatcher.scala @@ -9,8 +9,7 @@ object AvailableCommandMatcher { def equalAvailableCommand(expectedProto: AvailableCommand) = new AvailableCommandEqualsMatcher(expectedProto) - class AvailableCommandEqualsMatcher(expectedMessage: AvailableCommand) - extends Matcher[AvailableCommand] { + class AvailableCommandEqualsMatcher(expectedMessage: AvailableCommand) extends Matcher[AvailableCommand] { def apply(left: AvailableCommand): MatchResult = { val df = differingFields(left.asMessage, expectedMessage.asMessage) MatchResult( diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelectorTest.scala index 05780b1c76..084043f547 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/AvailableCommandSelectorTest.scala @@ -6,10 +6,7 @@ import net.eagle0.eagle.api.available_command.{ RestAvailableCommand, TravelAvailableCommand } -import net.eagle0.eagle.api.selected_command.{ - RestSelectedCommand, - TravelSelectedCommand -} +import net.eagle0.eagle.api.selected_command.{RestSelectedCommand, TravelSelectedCommand} import net.eagle0.eagle.library.util.CommandSelection import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers @@ -48,15 +45,14 @@ class AvailableCommandSelectorTest extends AnyFlatSpec with Matchers { MarchAvailableCommand() ) - AvailableCommandSelector.selectionForType[TravelAvailableCommand](acs)( - tac => - CommandSelection( - 5, - 17, - tac, - TravelSelectedCommand(), - reason = "dummy reason" - ) + AvailableCommandSelector.selectionForType[TravelAvailableCommand](acs)(tac => + CommandSelection( + 5, + 17, + tac, + TravelSelectedCommand(), + reason = "dummy reason" + ) ) shouldBe empty } @@ -66,15 +62,14 @@ class AvailableCommandSelectorTest extends AnyFlatSpec with Matchers { MarchAvailableCommand() ) - AvailableCommandSelector.selectionForType(acs) { - (tac: TravelAvailableCommand) => - CommandSelection( - 5, - 17, - tac, - TravelSelectedCommand(), - reason = "dummy reason" - ) + AvailableCommandSelector.selectionForType(acs) { (tac: TravelAvailableCommand) => + CommandSelection( + 5, + 17, + tac, + TravelSelectedCommand(), + reason = "dummy reason" + ) } shouldBe empty } @@ -111,15 +106,14 @@ class AvailableCommandSelectorTest extends AnyFlatSpec with Matchers { RestAvailableCommand(actingProvinceId = 17) ) - AvailableCommandSelector.selectionForType(acs) { - (rac: RestAvailableCommand) => - CommandSelection( - 5, - rac.actingProvinceId, - rac, - RestSelectedCommand(), - reason = "dummy reason" - ) + AvailableCommandSelector.selectionForType(acs) { (rac: RestAvailableCommand) => + CommandSelection( + 5, + rac.actingProvinceId, + rac, + RestSelectedCommand(), + reason = "dummy reason" + ) } shouldBe Some( CommandSelection( 5, @@ -137,17 +131,16 @@ class AvailableCommandSelectorTest extends AnyFlatSpec with Matchers { MarchAvailableCommand() ) - AvailableCommandSelector.flatSelectionForType[TravelAvailableCommand](acs)( - tac => - Some( - CommandSelection( - 5, - 17, - tac, - TravelSelectedCommand(), - reason = "dummy reason" - ) + AvailableCommandSelector.flatSelectionForType[TravelAvailableCommand](acs)(tac => + Some( + CommandSelection( + 5, + 17, + tac, + TravelSelectedCommand(), + reason = "dummy reason" ) + ) ) shouldBe empty } @@ -158,17 +151,16 @@ class AvailableCommandSelectorTest extends AnyFlatSpec with Matchers { RestAvailableCommand(actingProvinceId = 17) ) - AvailableCommandSelector.flatSelectionForType[RestAvailableCommand](acs)( - rac => - Some( - CommandSelection( - 5, - rac.actingProvinceId, - rac, - RestSelectedCommand(), - reason = "dummy reason" - ) + AvailableCommandSelector.flatSelectionForType[RestAvailableCommand](acs)(rac => + Some( + CommandSelection( + 5, + rac.actingProvinceId, + rac, + RestSelectedCommand(), + reason = "dummy reason" ) + ) ) shouldBe Some( CommandSelection( 5, @@ -187,17 +179,16 @@ class AvailableCommandSelectorTest extends AnyFlatSpec with Matchers { RestAvailableCommand(actingProvinceId = 17) ) - AvailableCommandSelector.flatSelectionForType[RestAvailableCommand](acs)( - rac => - Option.when(rac.actingProvinceId == 17) { - CommandSelection( - 5, - rac.actingProvinceId, - rac, - RestSelectedCommand(), - reason = "dummy reason" - ) - } + AvailableCommandSelector.flatSelectionForType[RestAvailableCommand](acs)(rac => + Option.when(rac.actingProvinceId == 17) { + CommandSelection( + 5, + rac.actingProvinceId, + rac, + RestSelectedCommand(), + reason = "dummy reason" + ) + } ) shouldBe Some( CommandSelection( 5, @@ -216,17 +207,16 @@ class AvailableCommandSelectorTest extends AnyFlatSpec with Matchers { RestAvailableCommand(actingProvinceId = 17) ) - AvailableCommandSelector.flatSelectionForType[RestAvailableCommand](acs)( - rac => - Option.when(rac.actingProvinceId == 19) { - CommandSelection( - 5, - rac.actingProvinceId, - rac, - RestSelectedCommand(), - reason = "dummy reason" - ) - } + AvailableCommandSelector.flatSelectionForType[RestAvailableCommand](acs)(rac => + Option.when(rac.actingProvinceId == 19) { + CommandSelection( + 5, + rac.actingProvinceId, + rac, + RestSelectedCommand(), + reason = "dummy reason" + ) + } ) shouldBe None } } diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelectorTest.scala index ef1b3b9779..07e9ad7ded 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CombatUnitSelectorTest.scala @@ -2,11 +2,7 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.eagle.common.battalion_type.BattalionTypeId import net.eagle0.eagle.common.combat_unit.CombatUnit -import net.eagle0.eagle.common.profession.Profession.{ - ENGINEER, - MAGE, - NO_PROFESSION -} +import net.eagle0.eagle.common.profession.Profession.{ENGINEER, MAGE, NO_PROFESSION} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.library.util.BattalionTypesTestData @@ -14,10 +10,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class CombatUnitSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class CombatUnitSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val battalionTypes = BattalionTypesTestData.battalionTypes diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpersTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpersTest.scala index e942ebc5e7..0ca41ec147 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpersTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/CommandChoiceHelpersTest.scala @@ -17,17 +17,10 @@ import net.eagle0.eagle.api.selected_command.{ } import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand.NewBattalion import net.eagle0.eagle.common.battalion_type.BattalionTypeId -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_CAVALRY, - LIGHT_INFANTRY, - LONGBOWMEN -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_CAVALRY, LIGHT_INFANTRY, LONGBOWMEN} import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.common.diplomacy_offer.{ - PrisonerToBeRansomed, - RansomOfferDetails -} +import net.eagle0.eagle.common.diplomacy_offer.{PrisonerToBeRansomed, RansomOfferDetails} import net.eagle0.eagle.internal.army.{Army, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction @@ -46,24 +39,16 @@ import net.eagle0.eagle.library.settings.{ } import net.eagle0.eagle.library.util.{BattalionTypesTestData, CommandSelection} import net.eagle0.eagle.library.util.command_choice_helpers.CommandChoiceHelpers.Supplies -import net.eagle0.eagle.library.util.IDable.{ - mapifyBattalions, - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyBattalions, mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class CommandChoiceHelpersTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class CommandChoiceHelpersTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - private val battalionTypes = BattalionTypesTestData.battalionTypes - private val random = new Random() + private val battalionTypes = BattalionTypesTestData.battalionTypes + private val random = new Random() private var functionalRandom: SeededRandom = SeededRandom(0) override def beforeEach(): Unit = { @@ -83,7 +68,7 @@ class CommandChoiceHelpersTest "chosenUnderAttackCommand" should "organize troops if under attack" in { val actingFid = 3 - val gs = GameState( + val gs = GameState( currentDate = Some(Date()), provinces = Map( 7 -> Province( @@ -791,10 +776,10 @@ class CommandChoiceHelpersTest it should "send to an unowned province if other options are at cap" in { val gameStateWithNeighborsAtCap = getUnderHeroCapGameState.update( - _.provinces(3).heroCap := 4, - _.provinces(4).heroCap := 4, + _.provinces(3).heroCap := 4, + _.provinces(4).heroCap := 4, _.provinces(6).optionalRulingFactionId := None, - _.provinces(7).heroCap := 4 + _.provinces(7).heroCap := 4 ) val choice = CommandChoiceHelpers @@ -1071,8 +1056,7 @@ class CommandChoiceHelpersTest targetFactionId = 77, ransomOffer = Some( RansomOfferDetails( - prisonerToBeRansomed = - Some(PrisonerToBeRansomed(prisonerHeroId = 1)), + prisonerToBeRansomed = Some(PrisonerToBeRansomed(prisonerHeroId = 1)), goldOffered = 9999 ) ) @@ -1081,8 +1065,7 @@ class CommandChoiceHelpersTest targetFactionId = 77, ransomOffer = Some( RansomOfferDetails( - prisonerToBeRansomed = - Some(PrisonerToBeRansomed(prisonerHeroId = 19)), + prisonerToBeRansomed = Some(PrisonerToBeRansomed(prisonerHeroId = 19)), goldOffered = 9999 ) ) @@ -1095,10 +1078,12 @@ class CommandChoiceHelpersTest .newValue .get - inside(selectedCommand.selected) { case dsc: DiplomacySelectedCommand => - inside(dsc.selectedOption) { case roo: RansomOfferOption => - roo.getRansomOffer.getPrisonerToBeRansomed.prisonerHeroId shouldBe 1 - } + inside(selectedCommand.selected) { + case dsc: DiplomacySelectedCommand => + inside(dsc.selectedOption) { + case roo: RansomOfferOption => + roo.getRansomOffer.getPrisonerToBeRansomed.prisonerHeroId shouldBe 1 + } } } @@ -1127,8 +1112,7 @@ class CommandChoiceHelpersTest targetFactionId = 77, ransomOffer = Some( RansomOfferDetails( - prisonerToBeRansomed = - Some(PrisonerToBeRansomed(prisonerHeroId = 19)), + prisonerToBeRansomed = Some(PrisonerToBeRansomed(prisonerHeroId = 19)), goldOffered = 9999 ) ) @@ -1137,8 +1121,7 @@ class CommandChoiceHelpersTest targetFactionId = 77, ransomOffer = Some( RansomOfferDetails( - prisonerToBeRansomed = - Some(PrisonerToBeRansomed(prisonerHeroId = 1)), + prisonerToBeRansomed = Some(PrisonerToBeRansomed(prisonerHeroId = 1)), goldOffered = 9999 ) ) @@ -1151,10 +1134,12 @@ class CommandChoiceHelpersTest .newValue .get - inside(selectedCommand.selected) { case dsc: DiplomacySelectedCommand => - inside(dsc.selectedOption) { case roo: RansomOfferOption => - roo.getRansomOffer.getPrisonerToBeRansomed.prisonerHeroId shouldBe 1 - } + inside(selectedCommand.selected) { + case dsc: DiplomacySelectedCommand => + inside(dsc.selectedOption) { + case roo: RansomOfferOption => + roo.getRansomOffer.getPrisonerToBeRansomed.prisonerHeroId shouldBe 1 + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelectorTest.scala index 5d2efb0fdd..b13b8e7809 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ExpandCommandSelectorTest.scala @@ -13,18 +13,10 @@ import net.eagle0.eagle.api.available_command.{ import net.eagle0.eagle.api.command.util.battalion_with_food_cost.BattalionWithFoodCost import net.eagle0.eagle.api.selected_command.MarchSelectedCommand import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_CAVALRY, - HEAVY_INFANTRY, - LIGHT_INFANTRY -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_CAVALRY, HEAVY_INFANTRY, LIGHT_INFANTRY} import net.eagle0.eagle.common.combat_unit.CombatUnit import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.common.improvement_type.ImprovementType.{ - AGRICULTURE, - ECONOMY, - INFRASTRUCTURE -} +import net.eagle0.eagle.common.improvement_type.ImprovementType.{AGRICULTURE, ECONOMY, INFRASTRUCTURE} import net.eagle0.eagle.internal.army.{Army, MovingArmy} import net.eagle0.eagle.internal.battalion.Battalion import net.eagle0.eagle.internal.faction.Faction @@ -32,22 +24,15 @@ import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.{Neighbor, Province} import net.eagle0.eagle.library.util.command_choice_helpers.SelectedCommandMatcher.equalSelectedCommand -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class ExpandCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ExpandCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - "heroIdsToMarch" should "never send a faction leader by themselves" in { + "heroIdsToMarch" should "never send a faction leader by themselves" in (1 to 100).foreach { _ => val toSend = ExpandCommandSelector .heroIdsToMarch( @@ -61,7 +46,6 @@ class ExpandCommandSelectorTest toSend should not be Vector(5) } - } it should "send a faction leader by themselves if we're only sending 1 of available 1" in { val toSend = ExpandCommandSelector @@ -77,7 +61,7 @@ class ExpandCommandSelectorTest toSend shouldBe Vector(5) } - it should "never leave a faction leader by themselves" in { + it should "never leave a faction leader by themselves" in (1 to 100).foreach { _ => val toSend = ExpandCommandSelector .heroIdsToMarch( @@ -91,9 +75,8 @@ class ExpandCommandSelectorTest toSend should not contain theSameElementsAs(Vector(3, 4, 6)) } - } - it should "split the faction leaders if there's more than one" in { + it should "split the faction leaders if there's more than one" in (1 to 100).foreach { _ => val toSend = ExpandCommandSelector .heroIdsToMarch( @@ -107,10 +90,9 @@ class ExpandCommandSelectorTest toSend.intersect(Vector(5, 6)) should have size 1 } - } it should "succeed if there are two faction leaders but neither is present" in { - noException should be thrownBy { + noException should be thrownBy ExpandCommandSelector.heroIdsToMarch( availableHeroIds = Vector(3, 4, 5, 6), heroCount = 2, @@ -118,7 +100,6 @@ class ExpandCommandSelectorTest otherCountLeftBehind = 1, functionalRandom = SeededRandom(new Random().nextLong()) ) - } } "expandSelectedCommand" should "return a march command if conditions are right" in { @@ -128,16 +109,14 @@ class ExpandCommandSelectorTest provinces = mapifyProvinces( Province( id = 9, - neighbors = - Vector(Neighbor(provinceId = 10, startingPositionIndex = 1)), + neighbors = Vector(Neighbor(provinceId = 10, startingPositionIndex = 1)), rulingFactionId = Some(33), rulingFactionHeroIds = Vector(1, 2, 3), priceIndex = 1.0 ), Province( id = 10, - neighbors = - Vector(Neighbor(provinceId = 9, startingPositionIndex = 8)), + neighbors = Vector(Neighbor(provinceId = 9, startingPositionIndex = 8)), priceIndex = 1.0 ) ), @@ -197,16 +176,14 @@ class ExpandCommandSelectorTest provinces = mapifyProvinces( Province( id = 9, - neighbors = - Vector(Neighbor(provinceId = 10, startingPositionIndex = 1)), + neighbors = Vector(Neighbor(provinceId = 10, startingPositionIndex = 1)), rulingFactionId = Some(33), rulingFactionHeroIds = Vector(1, 2, 3), priceIndex = 1.0 ), Province( id = 10, - neighbors = - Vector(Neighbor(provinceId = 9, startingPositionIndex = 8)), + neighbors = Vector(Neighbor(provinceId = 9, startingPositionIndex = 8)), priceIndex = 1.0 ) ), @@ -311,14 +288,14 @@ class ExpandCommandSelectorTest private val actingFactionId = 33 - private val fullyRestedHero1 = + private val fullyRestedHero1 = Hero( factionId = Some(actingFactionId), id = 1, vigor = 90, constitution = 90 ) - private val fullyRestedHero2 = + private val fullyRestedHero2 = Hero( factionId = Some(actingFactionId), id = 2, @@ -332,14 +309,14 @@ class ExpandCommandSelectorTest vigor = 75, constitution = 80 ) - private val veryTiredHero1 = + private val veryTiredHero1 = Hero( factionId = Some(actingFactionId), id = 4, vigor = 50, constitution = 70 ) - private val veryTiredHero2 = + private val veryTiredHero2 = Hero( factionId = Some(actingFactionId), id = 5, @@ -354,7 +331,7 @@ class ExpandCommandSelectorTest vigor = 50, constitution = 50 ) - private val hostileHero = + private val hostileHero = Hero( factionId = Some(actingFactionId + 1), id = 7, @@ -422,9 +399,8 @@ class ExpandCommandSelectorTest marchGameState, actingProvince.id, actingProvince.neighbors.map(_.provinceId).toVector - ) should not contain ( + ) should not contain ownedProvince - ) } it should "not return provinces that you already have an army heading to" in { @@ -432,9 +408,8 @@ class ExpandCommandSelectorTest marchGameState, actingProvince.id, actingProvince.neighbors.map(_.provinceId).toVector - ) should not contain ( + ) should not contain enRouteProvince - ) } it should "not return hostile provinces" in { @@ -442,9 +417,8 @@ class ExpandCommandSelectorTest marchGameState, actingProvince.id, actingProvince.neighbors.map(_.provinceId).toVector - ) should not contain ( + ) should not contain hostileProvince - ) } private val improveCommand = ImproveAvailableCommand( @@ -554,7 +528,7 @@ class ExpandCommandSelectorTest gameState = marchGameState.update( _.provinces( actingProvince.id - ).rulingFactionHeroIds := ((1 to 10).toVector), + ).rulingFactionHeroIds := ((1 to 10).toVector), _.provinces(actingProvince.id).neighbors := Vector( Neighbor(provinceId = ownedProvince.id) ) @@ -563,7 +537,7 @@ class ExpandCommandSelectorTest improveCommand, restCommand, marchCommand.update( - _.oneProvinceCommands.head.availableHeroIds := Vector( + _.oneProvinceCommands.head.availableHeroIds := Vector( 1, 8, 9, @@ -602,16 +576,16 @@ class ExpandCommandSelectorTest it should "return a march command with one hero if that's close enough" in { // We're putting 3 heroes in the acting province, and there is 1 unowned neighbor. We'd prefer to send 2 heroes // ( (3/2).ceil) ), but 1 ( (3/2).floor ) will do. - val gs = marchGameState.update( + val gs = marchGameState.update( _.provinces(actingProvince.id) := actingProvince.update( _.rulingFactionHeroIds := Vector(2, 4, 6), - _.neighbors := (Vector(Neighbor(provinceId = unownedProvince1.id))), - _.battalionIds := Vector(3) + _.neighbors := (Vector(Neighbor(provinceId = unownedProvince1.id))), + _.battalionIds := Vector(3) ) ) val mAC = marchCommand.update( - _.oneProvinceCommands.head.availableHeroIds := Vector(2), - _.oneProvinceCommands.head.availableBattalions := Vector( + _.oneProvinceCommands.head.availableHeroIds := Vector(2), + _.oneProvinceCommands.head.availableBattalions := Vector( BattalionWithFoodCost(battalionId = 3, monthlyFood = 6) ), _.oneProvinceCommands.head.availableDestinationProvinces := Vector( @@ -655,18 +629,18 @@ class ExpandCommandSelectorTest it should "return a march command with hero count rounding up if possible" in { // We're putting 3 heroes in the acting province, and there is 1 unowned neighbor. We'd prefer to send 2 heroes // ( (3/2).ceil) ), and we can, so we do. - val gs = marchGameState.update( + val gs = marchGameState.update( _.provinces(actingProvince.id) := actingProvince.update( _.rulingFactionHeroIds := Vector(2, 4, 6), - _.neighbors := (Vector(Neighbor(provinceId = unownedProvince1.id))) + _.neighbors := (Vector(Neighbor(provinceId = unownedProvince1.id))) ) ) val mAC = marchCommand.update( - _.oneProvinceCommands.head.availableHeroIds := Vector( + _.oneProvinceCommands.head.availableHeroIds := Vector( 2, 4 ), - _.oneProvinceCommands.head.availableBattalions := Vector( + _.oneProvinceCommands.head.availableBattalions := Vector( BattalionWithFoodCost(battalionId = 2, monthlyFood = 5) ), _.oneProvinceCommands.head.availableDestinationProvinces := Vector( @@ -714,13 +688,13 @@ class ExpandCommandSelectorTest it should "keep hero count balanced even if lots are available" in { // We're putting 15 heroes in the acting province, and there are 3 unowned neighbors. We will send 4 heroes even // if lots are available. - val gs = marchGameState.update( + val gs = marchGameState.update( _.provinces(actingProvince.id) := actingProvince.update( _.rulingFactionHeroIds := ((1 to 15).toVector) ) ) val mAC = marchCommand.update( - _.oneProvinceCommands.head.availableHeroIds := (1 to 12).toVector, + _.oneProvinceCommands.head.availableHeroIds := (1 to 12).toVector, _.oneProvinceCommands.head.availableDestinationProvinces := actingProvince.neighbors .map(_.provinceId) .map(pid => diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FoodConsumptionUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FoodConsumptionUtilsTest.scala index d7739fb63a..efde9f8759 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FoodConsumptionUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FoodConsumptionUtilsTest.scala @@ -22,10 +22,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class FoodConsumptionUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class FoodConsumptionUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { PrestigePerSupportedProvince.setDoubleValue(15) diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelectorTest.scala index 583c458439..e04b27e5b6 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/FulfillQuestsCommandSelectorTest.scala @@ -3,16 +3,8 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.common.SeededRandom import net.eagle0.eagle.api.available_command.* import net.eagle0.eagle.api.command.util.diplomacy_option.TruceOption -import net.eagle0.eagle.api.selected_command.{ - DiplomacySelectedCommand, - ImproveSelectedCommand -} -import net.eagle0.eagle.common.improvement_type.ImprovementType.{ - AGRICULTURE, - DEVASTATION, - ECONOMY, - INFRASTRUCTURE -} +import net.eagle0.eagle.api.selected_command.{DiplomacySelectedCommand, ImproveSelectedCommand} +import net.eagle0.eagle.common.improvement_type.ImprovementType.{AGRICULTURE, DEVASTATION, ECONOMY, INFRASTRUCTURE} import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo import net.eagle0.eagle.common.recruitment_info.RecruitmentStatus.{ RECRUITMENT_STATUS_HAS_QUEST, @@ -22,33 +14,22 @@ import net.eagle0.eagle.common.unaffiliated_hero_quest.* import net.eagle0.eagle.common.unaffiliated_hero_type.UnaffiliatedHeroType.UNAFFILIATED_HERO_RESIDENT import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship -import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.{ - HOSTILE, - TRUCE -} +import net.eagle0.eagle.internal.faction_relationship.FactionRelationship.RelationshipLevel.{HOSTILE, TRUCE} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.settings.MinimumTrustToOfferTruce import net.eagle0.eagle.library.util.CommandSelection -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class FulfillQuestsCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class FulfillQuestsCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - override def beforeEach(): Unit = { + override def beforeEach(): Unit = MinimumTrustToOfferTruce.setIntValue(0) - } private val actingFactionId = 3 @@ -117,7 +98,7 @@ class FulfillQuestsCommandSelectorTest private val restCommand = RestAvailableCommand(actingProvinceId = 18) - private val truceOption = TruceOption( + private val truceOption = TruceOption( targetFactionId = 103, goldCost = 100 ) @@ -339,7 +320,7 @@ class FulfillQuestsCommandSelectorTest .unaffiliatedHeroes(1) .recruitmentInfo .quest - .details := TruceCountQuest(3), + .details := TruceCountQuest(3), _.factions(actingFactionId).factionRelationships := Vector( FactionRelationship( targetFactionId = 103, @@ -402,7 +383,7 @@ class FulfillQuestsCommandSelectorTest .unaffiliatedHeroes(1) .recruitmentInfo .quest - .details := TruceCountQuest(3), + .details := TruceCountQuest(3), _.factions(actingFactionId).factionRelationships := Vector( FactionRelationship( targetFactionId = 103, @@ -453,7 +434,7 @@ class FulfillQuestsCommandSelectorTest .unaffiliatedHeroes(1) .recruitmentInfo .quest - .details := TruceCountQuest(3), + .details := TruceCountQuest(3), _.factions(actingFactionId).factionRelationships := Vector( FactionRelationship( targetFactionId = 103, @@ -471,7 +452,7 @@ class FulfillQuestsCommandSelectorTest trustValue = 70 ) ), - _.factions(105).factionRelationships := Vector( + _.factions(105).factionRelationships := Vector( FactionRelationship( targetFactionId = actingFactionId, relationshipLevel = TRUCE, @@ -504,8 +485,7 @@ class FulfillQuestsCommandSelectorTest "a UH with an improve quest" should "return the appropriate Improve command" in { val improveCommand = ImproveAvailableCommand( - availableTypes = - Vector(ECONOMY, AGRICULTURE, INFRASTRUCTURE, DEVASTATION), + availableTypes = Vector(ECONOMY, AGRICULTURE, INFRASTRUCTURE, DEVASTATION), actingProvinceId = 16, availableHeroIds = Vector(6, 11, 12, 13), recommendedHeroId = 6 @@ -552,8 +532,7 @@ class FulfillQuestsCommandSelectorTest it should "not return a command for the wrong province" in { val improveCommand = ImproveAvailableCommand( - availableTypes = - Vector(ECONOMY, AGRICULTURE, INFRASTRUCTURE, DEVASTATION), + availableTypes = Vector(ECONOMY, AGRICULTURE, INFRASTRUCTURE, DEVASTATION), actingProvinceId = 18, availableHeroIds = Vector(6, 11, 12, 13) ) diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelectorTest.scala index fbe70bdf06..1aa6cead0c 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/ImproveCommandSelectorTest.scala @@ -1,16 +1,9 @@ package net.eagle0.eagle.library.util.command_choice_helpers -import net.eagle0.eagle.api.available_command.{ - ImproveAvailableCommand, - RestAvailableCommand -} +import net.eagle0.eagle.api.available_command.{ImproveAvailableCommand, RestAvailableCommand} import net.eagle0.eagle.api.selected_command.ImproveSelectedCommand import net.eagle0.eagle.common.date.Date -import net.eagle0.eagle.common.improvement_type.ImprovementType.{ - AGRICULTURE, - ECONOMY, - INFRASTRUCTURE -} +import net.eagle0.eagle.common.improvement_type.ImprovementType.{AGRICULTURE, ECONOMY, INFRASTRUCTURE} import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province @@ -19,10 +12,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class ImproveCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class ImproveCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { import SelectedCommandMatcher.* @@ -39,7 +29,7 @@ class ImproveCommandSelectorTest id = 7, rulingFactionId = Some(actingFactionId), rulingHeroId = Some(1), - rulingFactionHeroIds = ((1 to 5)).toVector, + rulingFactionHeroIds = (1 to 5).toVector, infrastructure = 20, economy = 50, agriculture = 40, @@ -48,14 +38,14 @@ class ImproveCommandSelectorTest support = 50 ) - private val fullyRestedHero1 = + private val fullyRestedHero1 = Hero( factionId = Some(actingFactionId), id = 1, vigor = 90, constitution = 90 ) - private val fullyRestedHero2 = + private val fullyRestedHero2 = Hero( factionId = Some(actingFactionId), id = 2, @@ -69,14 +59,14 @@ class ImproveCommandSelectorTest vigor = 75, constitution = 80 ) - private val veryTiredHero1 = + private val veryTiredHero1 = Hero( factionId = Some(actingFactionId), id = 4, vigor = 50, constitution = 70 ) - private val veryTiredHero2 = + private val veryTiredHero2 = Hero( factionId = Some(actingFactionId), id = 5, @@ -98,10 +88,10 @@ class ImproveCommandSelectorTest it should "choose Economy if that is lower than agriculture and infrastructure" in { val lowerEconomyGameState = gameState.update( - _.provinces(actingProvince.id).economy := 20, + _.provinces(actingProvince.id).economy := 20, _.provinces(actingProvince.id).infrastructure := 30 ) - val selection = ImproveCommandSelector + val selection = ImproveCommandSelector .chosenImproveCommand( actingFactionId = actingFactionId, gameState = lowerEconomyGameState, @@ -119,8 +109,7 @@ class ImproveCommandSelectorTest ImproveCommandSelector.chosenImproveCommand( actingFactionId = actingFactionId, gameState = gameState, - availableCommands = - Vector(RestAvailableCommand(actingProvinceId = actingProvince.id)) + availableCommands = Vector(RestAvailableCommand(actingProvinceId = actingProvince.id)) ) shouldBe empty } diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelectorTest.scala index 6cbbcbde80..3e2b1b89b8 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/OrganizeCommandSelectorTest.scala @@ -1,23 +1,14 @@ package net.eagle0.eagle.library.util.command_choice_helpers -import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand.{ - ChangedBattalion, - NewBattalion -} +import net.eagle0.eagle.api.selected_command.OrganizeTroopsSelectedCommand.{ChangedBattalion, NewBattalion} import net.eagle0.eagle.common.battalion_type.BattalionType -import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{ - HEAVY_CAVALRY, - LIGHT_INFANTRY -} +import net.eagle0.eagle.common.battalion_type.BattalionTypeId.{HEAVY_CAVALRY, LIGHT_INFANTRY} import net.eagle0.eagle.internal.battalion.Battalion import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class OrganizeCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class OrganizeCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { "changedBattalions" should "top up a battalion if there is sufficient gold and food" in { val battalionTypes = @@ -48,9 +39,9 @@ class OrganizeCommandSelectorTest cbResult.changedBattalions should have size 2 - val expectedRemainingGold = 9780 // 10000 - 50 * 2.0 - 40 * 3.0 + val expectedRemainingGold = 9780 // 10000 - 50 * 2.0 - 40 * 3.0 cbResult.remainingGold shouldBe expectedRemainingGold - val expectedRemainingFoodSurplus = 482 // 500 - 50 * 0.15 - 40 * 0.25 + val expectedRemainingFoodSurplus = 482 // 500 - 50 * 0.15 - 40 * 0.25 cbResult.remainingFoodSurplus shouldBe expectedRemainingFoodSurplus cbResult.changedBattalions should contain.allOf( diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpersTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpersTest.scala index 9457790ec4..0938ba06e5 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpersTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/RansomOfferHelpersTest.scala @@ -30,10 +30,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class RansomOfferHelpersTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class RansomOfferHelpersTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { RansomOfferBaseNegative.setIntValue(-5000) RansomOfferScorePerGold.setIntValue(1) @@ -55,12 +52,10 @@ class RansomOfferHelpersTest ) private val originatingFactionId: FactionId = 1 - private val targetFactionId: FactionId = 2 + private val targetFactionId: FactionId = 2 "ransomOfferScore" should "be -5000 with nothing" in { - RansomOfferHelpers.ransomOfferScore(ransomOffer = - baseRansomOffer - ) shouldBe -5000 + RansomOfferHelpers.ransomOfferScore(ransomOffer = baseRansomOffer) shouldBe -5000 } it should "go up by 1000 for a prisoner" in { @@ -91,15 +86,13 @@ class RansomOfferHelpersTest } it should "go up by 1 per gold" in { - RansomOfferHelpers.ransomOfferScore(ransomOffer = - baseRansomOffer.withGoldOffered(1234) - ) shouldBe -3766 + RansomOfferHelpers.ransomOfferScore(ransomOffer = baseRansomOffer.withGoldOffered(1234)) shouldBe -3766 } it should "be positive with 2 hostages, a prisoner, and 1 gold" in { RansomOfferHelpers.ransomOfferScore(ransomOffer = baseRansomOffer.update( - _.goldOffered := 1, + _.goldOffered := 1, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 30, @@ -122,7 +115,7 @@ class RansomOfferHelpersTest "chosenResolution" should "be ACCEPTED with 2 hostages, a prisoner, and 1 gold" in { RansomOfferHelpers.chosenResolution(ransomOffer = baseRansomOffer.update( - _.goldOffered := 1, + _.goldOffered := 1, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 30, @@ -145,7 +138,7 @@ class RansomOfferHelpersTest it should "be REJECTED with 2 hostages, a prisoner, and 0 gold" in { RansomOfferHelpers.chosenResolution(ransomOffer = baseRansomOffer.update( - _.goldOffered := 0, + _.goldOffered := 0, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 30, @@ -167,7 +160,7 @@ class RansomOfferHelpersTest "chosenOffer" should "include everything if there are no faction leaders in the available offer" in { val bigOffer = baseRansomOffer.update( - _.goldOffered := 0, + _.goldOffered := 0, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 30, @@ -205,7 +198,7 @@ class RansomOfferHelpersTest it should "not include a faction leader" in { val bigOffer = baseRansomOffer.update( - _.goldOffered := 1279, + _.goldOffered := 1279, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 2, @@ -249,7 +242,7 @@ class RansomOfferHelpersTest it should "not include more than is necessary plus a little extra" in { val bigOffer = baseRansomOffer.update( - _.goldOffered := 1279, + _.goldOffered := 1279, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 2, @@ -311,7 +304,7 @@ class RansomOfferHelpersTest it should "be empty if there is not enough trust" in { val bigOffer = baseRansomOffer.update( - _.goldOffered := 0, + _.goldOffered := 0, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 30, @@ -355,7 +348,7 @@ class RansomOfferHelpersTest it should "be empty if we recently tried a truce offer to the same faction" in { val bigOffer = baseRansomOffer.update( - _.goldOffered := 0, + _.goldOffered := 0, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 30, @@ -399,7 +392,7 @@ class RansomOfferHelpersTest it should "not be empty if the last offer is not so recent" in { val bigOffer = baseRansomOffer.update( - _.goldOffered := 0, + _.goldOffered := 0, _.hostagesOffered := Vector( HostageOfferedInExchange( heroId = 30, diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SelectedCommandMatcher.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SelectedCommandMatcher.scala index 0cc2eb813b..05e3b453dc 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SelectedCommandMatcher.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SelectedCommandMatcher.scala @@ -9,8 +9,7 @@ object SelectedCommandMatcher { def equalSelectedCommand(expectedProto: SelectedCommand) = new SelectedCommandEqualsMatcher(expectedProto) - class SelectedCommandEqualsMatcher(expectedMessage: SelectedCommand) - extends Matcher[SelectedCommand] { + class SelectedCommandEqualsMatcher(expectedMessage: SelectedCommand) extends Matcher[SelectedCommand] { def apply(left: SelectedCommand): MatchResult = { val df = differingFields(left.asMessage, expectedMessage.asMessage) MatchResult( diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooserTest.scala index 4c7fbaf91d..1d62ef0bab 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/SwornBrotherChooserTest.scala @@ -3,18 +3,12 @@ package net.eagle0.eagle.library.util.command_choice_helpers import net.eagle0.common.ProtoMatchers.equalProto import net.eagle0.eagle.common.profession.Profession import net.eagle0.eagle.internal.hero.Hero -import net.eagle0.eagle.library.settings.{ - AiMinimumCharismaForSwornBrother, - AiMinimumConstitutionForSwornBrother -} +import net.eagle0.eagle.library.settings.{AiMinimumCharismaForSwornBrother, AiMinimumConstitutionForSwornBrother} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class SwornBrotherChooserTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class SwornBrotherChooserTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { AiMinimumCharismaForSwornBrother.setDoubleValue(65) AiMinimumConstitutionForSwornBrother.setDoubleValue(65) diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelectorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelectorTest.scala index 30c89bf7e2..ccdfee4625 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelectorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/TruceOfferCommandSelectorTest.scala @@ -6,10 +6,7 @@ import net.eagle0.eagle.api.available_command.{ RestAvailableCommand, TravelAvailableCommand } -import net.eagle0.eagle.api.command.util.diplomacy_option.{ - InvitationOption, - TruceOption -} +import net.eagle0.eagle.api.command.util.diplomacy_option.{InvitationOption, TruceOption} import net.eagle0.eagle.api.selected_command.DiplomacySelectedCommand import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState @@ -20,10 +17,7 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class TruceOfferCommandSelectorTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class TruceOfferCommandSelectorTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { private val actingFactionId = 5 @@ -114,9 +108,9 @@ class TruceOfferCommandSelectorTest val selected = TruceOfferCommandSelector.chosenTruceWithFactionCommand( actingFactionId = actingFactionId, gameState = gameState.update( - _.heroes(1).vigor := 100, - _.heroes(2).vigor := 80, - _.heroes(3).vigor := 100, + _.heroes(1).vigor := 100, + _.heroes(2).vigor := 80, + _.heroes(3).vigor := 100, _.factions(actingFactionId).leaders := Vector(1, 3) ), availableCommands = availableCommands, diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooserTest.scala index ef2245f923..c821c21e3d 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AllianceQuestCommandChooserTest.scala @@ -2,15 +2,9 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selec import net.eagle0.common.SeededRandom import net.eagle0.eagle.api.available_command.DiplomacyAvailableCommand -import net.eagle0.eagle.api.command.util.diplomacy_option.{ - AllianceOption, - TruceOption -} +import net.eagle0.eagle.api.command.util.diplomacy_option.{AllianceOption, TruceOption} import net.eagle0.eagle.api.selected_command.DiplomacySelectedCommand -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - AllianceQuest, - Quest as QuestProto -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{AllianceQuest, Quest as QuestProto} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship import net.eagle0.eagle.internal.game_state.GameState @@ -24,17 +18,14 @@ import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class AllianceQuestCommandChooserTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { - private val actingFid: FactionId = 1 +class AllianceQuestCommandChooserTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { + private val actingFid: FactionId = 1 private val targetFid1: FactionId = 20 private val targetFid2: FactionId = 30 private val gameState = GameState( factions = Map( - actingFid -> Faction( + actingFid -> Faction( id = actingFid, name = "Acting Faction", factionRelationships = Vector( @@ -105,16 +96,18 @@ class AllianceQuestCommandChooserTest functionalRandom = SeededRandom(1976L) ) - inside(result.newValue.get) { case cmd: CommandSelection => - cmd.available shouldBe availableCommands.head - inside(cmd.selected) { case sc: DiplomacySelectedCommand => - sc.targetFactionId shouldBe targetFid1 - sc.selectedOption shouldBe AllianceOption( - targetFactionId = targetFid1, - goldCost = 200 - ) - sc.sentHeroId shouldBe 8 // higher vigor - } + inside(result.newValue.get) { + case cmd: CommandSelection => + cmd.available shouldBe availableCommands.head + inside(cmd.selected) { + case sc: DiplomacySelectedCommand => + sc.targetFactionId shouldBe targetFid1 + sc.selectedOption shouldBe AllianceOption( + targetFactionId = targetFid1, + goldCost = 200 + ) + sc.sentHeroId shouldBe 8 // higher vigor + } } } @@ -141,16 +134,18 @@ class AllianceQuestCommandChooserTest functionalRandom = SeededRandom(1976L) ) - inside(result.newValue.get) { case cmd: CommandSelection => - cmd.available shouldBe availableCommands.head - inside(cmd.selected) { case sc: DiplomacySelectedCommand => - sc.targetFactionId shouldBe targetFid2 - sc.selectedOption shouldBe AllianceOption( - targetFactionId = targetFid2, - goldCost = 200 - ) - sc.sentHeroId shouldBe 8 // higher vigor - } + inside(result.newValue.get) { + case cmd: CommandSelection => + cmd.available shouldBe availableCommands.head + inside(cmd.selected) { + case sc: DiplomacySelectedCommand => + sc.targetFactionId shouldBe targetFid2 + sc.selectedOption shouldBe AllianceOption( + targetFactionId = targetFid2, + goldCost = 200 + ) + sc.sentHeroId shouldBe 8 // higher vigor + } } } diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooserTest.scala index c0b51401e6..1e701b0958 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsAcrossRealmQuestCommandChooserTest.scala @@ -6,38 +6,24 @@ import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.gender.Gender.GENDER_OTHER import net.eagle0.eagle.common.profession.Profession.NO_PROFESSION import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - AlmsAcrossRealmQuest, - ImproveAgricultureQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{AlmsAcrossRealmQuest, ImproveAgricultureQuest, Quest} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.settings.{ - AlmsSupportIncreasePerFood, - MinSupportForTaxes -} +import net.eagle0.eagle.library.settings.{AlmsSupportIncreasePerFood, MinSupportForTaxes} import net.eagle0.eagle.library.util.CommandSelection -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AlmsAcrossRealmQuestCommandChooserTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AlmsAcrossRealmQuestCommandChooserTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - private val actingFactionId = 4 + private val actingFactionId = 4 private val actingProvinceId = 12 - private val ownedProvinceId = 22 + private val ownedProvinceId = 22 private val factionLeader = Hero( @@ -46,19 +32,19 @@ class AlmsAcrossRealmQuestCommandChooserTest profession = NO_PROFESSION, pronounGender = GENDER_OTHER ) - private val uh1 = Hero( + private val uh1 = Hero( id = 57, factionId = None, profession = NO_PROFESSION, pronounGender = GENDER_OTHER ) - private val uh2 = Hero( + private val uh2 = Hero( id = 67, factionId = None, profession = NO_PROFESSION, pronounGender = GENDER_OTHER ) - private val vassal = + private val vassal = Hero( id = 6, factionId = Some(actingFactionId), @@ -155,8 +141,7 @@ class AlmsAcrossRealmQuestCommandChooserTest actingFactionId = actingFactionId, actingProvinceId = actingProvinceId, available = giveAlmsCommand, - selected = - AlmsSelectedCommand(amount = 597, actingHeroId = factionLeader.id), + selected = AlmsSelectedCommand(amount = 597, actingHeroId = factionLeader.id), reason = "fulfill AlmsAcrossRealm quest" ) ) @@ -224,8 +209,7 @@ class AlmsAcrossRealmQuestCommandChooserTest UnaffiliatedHeroWithQuest( pid = ownedProvinceId, uh = unaffiliatedHeroDifferentProvince, - quest = - unaffiliatedHeroDifferentProvince.getRecruitmentInfo.getQuest + quest = unaffiliatedHeroDifferentProvince.getRecruitmentInfo.getQuest ) ) ) @@ -235,8 +219,7 @@ class AlmsAcrossRealmQuestCommandChooserTest actingFactionId = actingFactionId, actingProvinceId = actingProvinceId, available = giveAlmsCommand, - selected = - AlmsSelectedCommand(amount = 1000, actingHeroId = factionLeader.id), + selected = AlmsSelectedCommand(amount = 1000, actingHeroId = factionLeader.id), reason = "fulfill AlmsAcrossRealm quest" ) ) @@ -267,8 +250,7 @@ class AlmsAcrossRealmQuestCommandChooserTest actingFactionId = actingFactionId, actingProvinceId = actingProvinceId, available = giveAlmsCommand, - selected = - AlmsSelectedCommand(amount = 597, actingHeroId = factionLeader.id), + selected = AlmsSelectedCommand(amount = 597, actingHeroId = factionLeader.id), reason = "fulfill AlmsAcrossRealm quest" ) ) diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooserTest.scala index 45334da2b8..027631d0e0 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/AlmsToProvinceQuestCommandChooserTest.scala @@ -6,36 +6,22 @@ import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.common.gender.Gender.GENDER_OTHER import net.eagle0.eagle.common.profession.Profession.NO_PROFESSION import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - AlmsToProvinceQuest, - ImproveAgricultureQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{AlmsToProvinceQuest, ImproveAgricultureQuest, Quest} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.settings.{ - AlmsSupportIncreasePerFood, - MinSupportForTaxes -} +import net.eagle0.eagle.library.settings.{AlmsSupportIncreasePerFood, MinSupportForTaxes} import net.eagle0.eagle.library.util.CommandSelection -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class AlmsToProvinceQuestCommandChooserTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class AlmsToProvinceQuestCommandChooserTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - private val actingFactionId = 4 + private val actingFactionId = 4 private val actingProvinceId = 12 private val factionLeader = @@ -45,7 +31,7 @@ class AlmsToProvinceQuestCommandChooserTest profession = NO_PROFESSION, pronounGender = GENDER_OTHER ) - private val hero = Hero( + private val hero = Hero( id = 57, factionId = None, profession = NO_PROFESSION, @@ -123,8 +109,7 @@ class AlmsToProvinceQuestCommandChooserTest actingFactionId = actingFactionId, actingProvinceId = actingProvinceId, available = giveAlmsCommand, - selected = - AlmsSelectedCommand(amount = 597, actingHeroId = factionLeader.id), + selected = AlmsSelectedCommand(amount = 597, actingHeroId = factionLeader.id), reason = "fulfill AlmsToProvince quest" ) ) diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooserTest.scala index b1ddfeffc6..ceeedbf1d7 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/DismissSpecificVassalCommandChooserTest.scala @@ -1,25 +1,11 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selectors -import net.eagle0.eagle.api.available_command.{ - ExileVassalAvailableCommand, - ImproveAvailableCommand -} +import net.eagle0.eagle.api.available_command.{ExileVassalAvailableCommand, ImproveAvailableCommand} import net.eagle0.eagle.api.selected_command.ExileVassalSelectedCommand -import net.eagle0.eagle.common.improvement_type.ImprovementType.{ - AGRICULTURE, - ECONOMY -} -import net.eagle0.eagle.common.profession.Profession.{ - ENGINEER, - MAGE, - NO_PROFESSION -} +import net.eagle0.eagle.common.improvement_type.ImprovementType.{AGRICULTURE, ECONOMY} +import net.eagle0.eagle.common.profession.Profession.{ENGINEER, MAGE, NO_PROFESSION} import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - DismissSpecificVassalQuest, - ImproveAgricultureQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{DismissSpecificVassalQuest, ImproveAgricultureQuest, Quest} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero @@ -27,19 +13,12 @@ import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero import net.eagle0.eagle.library.settings.RequiredPowerMultiplierForDismiss import net.eagle0.eagle.library.util.CommandSelection -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class DismissSpecificVassalCommandChooserTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class DismissSpecificVassalCommandChooserTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { private val factionLeader: Hero = Hero(id = 6) private val weakVassal: Hero = Hero( @@ -93,8 +72,7 @@ class DismissSpecificVassalCommandChooserTest Province( id = 7, rulingFactionId = Some(actingFactionId), - rulingFactionHeroIds = - Vector(factionLeader.id, weakVassal.id, strongVassal.id), + rulingFactionHeroIds = Vector(factionLeader.id, weakVassal.id, strongVassal.id), unaffiliatedHeroes = Vector(unaffiliatedHero) ) ), @@ -113,9 +91,8 @@ class DismissSpecificVassalCommandChooserTest exilableHeroIds = Vector(weakVassal.id, strongVassal.id) ) - override def beforeEach(): Unit = { + override def beforeEach(): Unit = RequiredPowerMultiplierForDismiss.setDoubleValue(1.5) - } "DismissSpecificVassalCommandChooser" should "return an exile vassal command for a weak target hero" in { val selectedCommand = @@ -156,8 +133,7 @@ class DismissSpecificVassalCommandChooserTest pid = 7, uh = unaffiliatedHero, quest = Quest( - details = - ImproveAgricultureQuest(provinceId = 7, desiredValue = 32) + details = ImproveAgricultureQuest(provinceId = 7, desiredValue = 32) ) ) ) diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooserTest.scala index 3a836b9dd3..8bd4e07d84 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesAcrossRealmQuestCommandChooserTest.scala @@ -1,48 +1,34 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selectors import net.eagle0.common.ProtoMatchers.equalProto -import net.eagle0.eagle.api.available_command.{ - EligibleGift, - HeroGiftAvailableCommand -} +import net.eagle0.eagle.api.available_command.{EligibleGift, HeroGiftAvailableCommand} import net.eagle0.eagle.api.selected_command.HeroGiftSelectedCommand import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - GiveToHeroesAcrossRealmQuest, - ImproveAgricultureQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{GiveToHeroesAcrossRealmQuest, ImproveAgricultureQuest, Quest} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class GiveToHeroesAcrossRealmQuestCommandChooserTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class GiveToHeroesAcrossRealmQuestCommandChooserTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - private val actingFactionId = 4 + private val actingFactionId = 4 private val actingProvinceId = 12 - private val ownedProvinceId = 22 + private val ownedProvinceId = 22 - private val factionLeader = Hero(id = 5, factionId = Some(actingFactionId)) - private val vassal = Hero(id = 10, factionId = Some(actingFactionId)) - private val otherVassal = Hero(id = 21, factionId = Some(actingFactionId)) - private val freeHeroInProvince = Hero(id = 57, factionId = None) + private val factionLeader = Hero(id = 5, factionId = Some(actingFactionId)) + private val vassal = Hero(id = 10, factionId = Some(actingFactionId)) + private val otherVassal = Hero(id = 21, factionId = Some(actingFactionId)) + private val freeHeroInProvince = Hero(id = 57, factionId = None) private val freeHeroOtherProvince = Hero(id = 58, factionId = None) - private val unaffiliatedHeroInProvince = UnaffiliatedHero( + private val unaffiliatedHeroInProvince = UnaffiliatedHero( heroId = freeHeroInProvince.id, recruitmentInfo = Some( RecruitmentInfo( @@ -135,13 +121,15 @@ class GiveToHeroesAcrossRealmQuestCommandChooserTest selectedCommand.actingProvinceId shouldBe actingProvinceId selectedCommand.actingFactionId shouldBe actingFactionId - inside(selectedCommand.available) { case actual: HeroGiftAvailableCommand => - actual should equalProto(heroGiftAvailableCommand) + inside(selectedCommand.available) { + case actual: HeroGiftAvailableCommand => + actual should equalProto(heroGiftAvailableCommand) } - inside(selectedCommand.selected) { case actual: HeroGiftSelectedCommand => - actual should equalProto( - HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 100) - ) + inside(selectedCommand.selected) { + case actual: HeroGiftSelectedCommand => + actual should equalProto( + HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 100) + ) } selectedCommand.reason shouldBe "fulfill GiveToHeroesAcrossRealm quest" } @@ -166,13 +154,15 @@ class GiveToHeroesAcrossRealmQuestCommandChooserTest selectedCommand.actingProvinceId shouldBe actingProvinceId selectedCommand.actingFactionId shouldBe actingFactionId - inside(selectedCommand.available) { case actual: HeroGiftAvailableCommand => - actual should equalProto(heroGiftAvailableCommand) + inside(selectedCommand.available) { + case actual: HeroGiftAvailableCommand => + actual should equalProto(heroGiftAvailableCommand) } - inside(selectedCommand.selected) { case actual: HeroGiftSelectedCommand => - actual should equalProto( - HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 47) - ) + inside(selectedCommand.selected) { + case actual: HeroGiftSelectedCommand => + actual should equalProto( + HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 47) + ) } selectedCommand.reason shouldBe "fulfill GiveToHeroesAcrossRealm quest" } @@ -227,13 +217,15 @@ class GiveToHeroesAcrossRealmQuestCommandChooserTest selectedCommand.actingProvinceId shouldBe actingProvinceId selectedCommand.actingFactionId shouldBe actingFactionId - inside(selectedCommand.available) { case actual: HeroGiftAvailableCommand => - actual should equalProto(heroGiftAvailableCommand) + inside(selectedCommand.available) { + case actual: HeroGiftAvailableCommand => + actual should equalProto(heroGiftAvailableCommand) } - inside(selectedCommand.selected) { case actual: HeroGiftSelectedCommand => - actual should equalProto( - HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 100) - ) + inside(selectedCommand.selected) { + case actual: HeroGiftSelectedCommand => + actual should equalProto( + HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 100) + ) } selectedCommand.reason shouldBe "fulfill GiveToHeroesAcrossRealm quest" } diff --git a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooserTest.scala b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooserTest.scala index febfd9f79c..b7cb834f22 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooserTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/command_choice_helpers/quest_command_selectors/GiveToHeroesInProvinceQuestCommandChooserTest.scala @@ -1,43 +1,29 @@ package net.eagle0.eagle.library.util.command_choice_helpers.quest_command_selectors import net.eagle0.common.ProtoMatchers.equalProto -import net.eagle0.eagle.api.available_command.{ - EligibleGift, - HeroGiftAvailableCommand -} +import net.eagle0.eagle.api.available_command.{EligibleGift, HeroGiftAvailableCommand} import net.eagle0.eagle.api.selected_command.HeroGiftSelectedCommand import net.eagle0.eagle.common.recruitment_info.RecruitmentInfo -import net.eagle0.eagle.common.unaffiliated_hero_quest.{ - GiveToHeroesInProvinceQuest, - ImproveAgricultureQuest, - Quest -} +import net.eagle0.eagle.common.unaffiliated_hero_quest.{GiveToHeroesInProvinceQuest, ImproveAgricultureQuest, Quest} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class GiveToHeroesInProvinceQuestCommandChooserTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class GiveToHeroesInProvinceQuestCommandChooserTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { - private val actingFactionId = 4 + private val actingFactionId = 4 private val actingProvinceId = 12 private val factionLeader = Hero(id = 5, factionId = Some(actingFactionId)) - private val vassal = Hero(id = 10, factionId = Some(actingFactionId)) - private val freeHero = Hero(id = 57, factionId = None) + private val vassal = Hero(id = 10, factionId = Some(actingFactionId)) + private val freeHero = Hero(id = 57, factionId = None) private val unaffiliatedHero = UnaffiliatedHero( heroId = freeHero.id, @@ -109,13 +95,15 @@ class GiveToHeroesInProvinceQuestCommandChooserTest selectedCommand.actingProvinceId shouldBe actingProvinceId selectedCommand.actingFactionId shouldBe actingFactionId - inside(selectedCommand.available) { case actual: HeroGiftAvailableCommand => - actual should equalProto(heroGiftAvailableCommand) + inside(selectedCommand.available) { + case actual: HeroGiftAvailableCommand => + actual should equalProto(heroGiftAvailableCommand) } - inside(selectedCommand.selected) { case actual: HeroGiftSelectedCommand => - actual should equalProto( - HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 100) - ) + inside(selectedCommand.selected) { + case actual: HeroGiftSelectedCommand => + actual should equalProto( + HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 100) + ) } selectedCommand.reason shouldBe "fulfill GiveToHeroesInProvince quest" } @@ -140,13 +128,15 @@ class GiveToHeroesInProvinceQuestCommandChooserTest selectedCommand.actingProvinceId shouldBe actingProvinceId selectedCommand.actingFactionId shouldBe actingFactionId - inside(selectedCommand.available) { case actual: HeroGiftAvailableCommand => - actual should equalProto(heroGiftAvailableCommand) + inside(selectedCommand.available) { + case actual: HeroGiftAvailableCommand => + actual should equalProto(heroGiftAvailableCommand) } - inside(selectedCommand.selected) { case actual: HeroGiftSelectedCommand => - actual should equalProto( - HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 47) - ) + inside(selectedCommand.selected) { + case actual: HeroGiftSelectedCommand => + actual should equalProto( + HeroGiftSelectedCommand(recipientHeroId = vassal.id, amount = 47) + ) } selectedCommand.reason shouldBe "fulfill GiveToHeroesInProvince quest" } diff --git a/src/test/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtilsTest.scala index 41824caaf6..60f7dc0e53 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/faction_utils/LegacyFactionUtilsTest.scala @@ -4,20 +4,14 @@ import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.faction_relationship.FactionRelationship import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - MinSupportForTaxes, - PrestigePerSupportedProvince -} +import net.eagle0.eagle.library.settings.{MinSupportForTaxes, PrestigePerSupportedProvince} import net.eagle0.eagle.library.util.faction_utils.LegacyFactionUtils import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyProvinces} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class LegacyFactionUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class LegacyFactionUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { behavior of "FactionUtilsTest" diff --git a/src/test/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtilsTest.scala index 763912ddbf..1d461c1af4 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/hero/LegacyHeroUtilsTest.scala @@ -5,27 +5,23 @@ import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.views.stat_with_condition.StatWithCondition import net.eagle0.eagle.views.stat_with_condition.StatWithCondition.Condition.HIGH import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers class LegacyHeroUtilsTest extends AnyFlatSpec with Matchers { - val fid: FactionId = 8 - val factionHeadId: HeroId = 19 - val swornBrotherId: HeroId = 99 - val vassalId: HeroId = 199 - val faction: Faction = Faction( + val fid: FactionId = 8 + val factionHeadId: HeroId = 19 + val swornBrotherId: HeroId = 99 + val vassalId: HeroId = 199 + val faction: Faction = Faction( id = fid, factionHeadId = 19, leaders = Vector(factionHeadId, swornBrotherId) ) - val factionHeadProvince: Province = Province( + val factionHeadProvince: Province = Province( id = 22, rulingFactionId = Some(fid), rulingHeroId = Some(factionHeadId), @@ -37,7 +33,7 @@ class LegacyHeroUtilsTest extends AnyFlatSpec with Matchers { rulingHeroId = Some(swornBrotherId), rulingFactionHeroIds = Vector(swornBrotherId) ) - val noLeaderProvince: Province = Province( + val noLeaderProvince: Province = Province( id = 27, rulingFactionId = Some(fid), rulingHeroId = Some(vassalId), @@ -84,9 +80,8 @@ class LegacyHeroUtilsTest extends AnyFlatSpec with Matchers { gameState, fid, factionHeadProvince.id - ) should not contain ( + ) should not contain swornBrotherProvince - ) } it should "include a province that has another faction leader if it also has the faction head" in { @@ -147,8 +142,7 @@ class LegacyHeroUtilsTest extends AnyFlatSpec with Matchers { "loyaltyAsStatWithCondition" should "return None if it's a faction leader" in { val gs = GameState( - factions = - Map(2 -> Faction(id = 2, factionHeadId = 5, leaders = Vector(5, 6))), + factions = Map(2 -> Faction(id = 2, factionHeadId = 5, leaders = Vector(5, 6))), heroes = mapifyHeroes( Hero(id = 6, factionId = Some(2), loyalty = 95), Hero(id = 7, factionId = Some(2), loyalty = 95) @@ -162,8 +156,7 @@ class LegacyHeroUtilsTest extends AnyFlatSpec with Matchers { it should "return a stat with condition with the appropriate loyalty if it's not a faction leader" in { val gs = GameState( - factions = - Map(2 -> Faction(id = 2, factionHeadId = 5, leaders = Vector(5, 6))), + factions = Map(2 -> Faction(id = 2, factionHeadId = 5, leaders = Vector(5, 6))), heroes = mapifyHeroes( Hero(id = 6, factionId = Some(2), loyalty = 95), Hero(id = 7, factionId = Some(2), loyalty = 95) diff --git a/src/test/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtilsTest.scala index d8d111ffc4..b156cedeb3 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/quest_creation/QuestCreationUtilsTest.scala @@ -26,10 +26,7 @@ import net.eagle0.eagle.library.settings.{ import net.eagle0.eagle.model.state.battalion.concrete.BattalionC import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionRelationship -import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{ - Ally, - Truce -} +import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.{Ally, Truce} import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.province.Neighbor import net.eagle0.eagle.model.state.quest.concrete.{ @@ -55,10 +52,7 @@ import net.eagle0.eagle.model.state.quest.concrete.{ WealthQuest } import net.eagle0.eagle.model.state.quest.QuestT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.Prisoner import net.eagle0.eagle.model.state.BattalionTypeId.Longbowmen @@ -69,10 +63,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside import org.scalatest.Inspectors.{forAll, forAtLeast, forExactly} -class QuestCreationUtilsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class QuestCreationUtilsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { override def beforeEach(): Unit = { MinDesiredImproveAmountInQuest.setIntValue(14) MaxRequiredImproveAmountInQuest.setIntValue(29) @@ -94,8 +85,8 @@ class QuestCreationUtilsTest } private val fid: FactionId = 12 - private val destroyedFid = 13 - private val province = ProvinceC( + private val destroyedFid = 13 + private val province = ProvinceC( id = 13, rulingFactionId = Some(fid), rulingFactionHeroIds = Vector(1, 2, 3), @@ -105,13 +96,12 @@ class QuestCreationUtilsTest Neighbor(provinceId = 15, startingPositionIndex = 2) ) ) - private val immediate1 = ProvinceC( + private val immediate1 = ProvinceC( id = 14, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = province.id, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = province.id, startingPositionIndex = 1)) ) - private val immediate2 = ProvinceC( + private val immediate2 = ProvinceC( id = 15, rulingFactionId = None, neighbors = Vector( @@ -119,7 +109,7 @@ class QuestCreationUtilsTest Neighbor(provinceId = 16, startingPositionIndex = 2) ) ) - private val twoAway = ProvinceC( + private val twoAway = ProvinceC( id = 16, rulingFactionId = None, neighbors = Vector( @@ -127,22 +117,20 @@ class QuestCreationUtilsTest Neighbor(provinceId = 17, startingPositionIndex = 2) ) ) - private val threeAway = ProvinceC( + private val threeAway = ProvinceC( id = 17, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = twoAway.id, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = twoAway.id, startingPositionIndex = 1)) ) - private val fourAway = ProvinceC( + private val fourAway = ProvinceC( id = 18, rulingFactionId = None, - neighbors = - Vector(Neighbor(provinceId = threeAway.id, startingPositionIndex = 1)) + neighbors = Vector(Neighbor(provinceId = threeAway.id, startingPositionIndex = 1)) ) - private val allProvinces = + private val allProvinces = Vector(province, immediate1, immediate2, twoAway, threeAway, fourAway) - private val factions = Vector( + private val factions = Vector( FactionC( id = fid, factionHeadId = 1, @@ -166,7 +154,7 @@ class QuestCreationUtilsTest recruitmentInfo = RecruitmentInfo.Outlaw ) - "availableQuests" should "include an agriculture improvement event if it is possible to raise enough" in { + "availableQuests" should "include an agriculture improvement event if it is possible to raise enough" in forAtLeast( 1, QuestCreationUtils @@ -179,12 +167,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should matchPattern { case ImproveAgricultureQuest(_, _) => + q should matchPattern { + case ImproveAgricultureQuest(_, _) => } } - } - it should "not include an agriculture improvement event if the current value is high" in { + it should "not include an agriculture improvement event if the current value is high" in forAll( QuestCreationUtils .availableQuests( @@ -196,12 +184,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should not matchPattern { case ImproveAgricultureQuest(_, _) => + q should not matchPattern { + case ImproveAgricultureQuest(_, _) => } } - } - "availableQuests" should "include an economy improvement event if it is possible to raise enough" in { + "availableQuests" should "include an economy improvement event if it is possible to raise enough" in forAtLeast( 1, QuestCreationUtils @@ -214,12 +202,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should matchPattern { case ImproveEconomyQuest(_, _) => + q should matchPattern { + case ImproveEconomyQuest(_, _) => } } - } - it should "not include an economy improvement event if the current value is high" in { + it should "not include an economy improvement event if the current value is high" in forAll( QuestCreationUtils .availableQuests( @@ -231,12 +219,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should not matchPattern { case ImproveEconomyQuest(_, _) => + q should not matchPattern { + case ImproveEconomyQuest(_, _) => } } - } - "availableQuests" should "include an infrastructure improvement event if it is possible to raise enough" in { + "availableQuests" should "include an infrastructure improvement event if it is possible to raise enough" in forAtLeast( 1, QuestCreationUtils @@ -249,12 +237,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should matchPattern { case ImproveInfrastructureQuest(_, _) => + q should matchPattern { + case ImproveInfrastructureQuest(_, _) => } } - } - it should "not include an infrastructure improvement event if the current value is high" in { + it should "not include an infrastructure improvement event if the current value is high" in forAll( QuestCreationUtils .availableQuests( @@ -266,10 +254,10 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should not matchPattern { case ImproveInfrastructureQuest(_, _) => + q should not matchPattern { + case ImproveInfrastructureQuest(_, _) => } } - } "availableQuests" should "include specific expansion quests for an unoccupied direct neighbors" in { QuestCreationUtils @@ -286,7 +274,7 @@ class QuestCreationUtilsTest ) } - it should "not include an expansion quest for a province that is occupied" in { + it should "not include an expansion quest for a province that is occupied" in forAll( QuestCreationUtils .availableQuests( @@ -305,12 +293,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should not matchPattern { case SpecificExpansionQuest(immediate1.id) => + q should not matchPattern { + case SpecificExpansionQuest(immediate1.id) => } } - } - it should "not include a specific expansion quest for a neighbor of a neighbor" in { + it should "not include a specific expansion quest for a neighbor of a neighbor" in forAll( QuestCreationUtils .availableQuests( @@ -322,12 +310,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should not matchPattern { case SpecificExpansionQuest(twoAway.id) => + q should not matchPattern { + case SpecificExpansionQuest(twoAway.id) => } } - } - it should "not include a specific expansion quest for a province 3 away" in { + it should "not include a specific expansion quest for a province 3 away" in forAll( QuestCreationUtils .availableQuests( @@ -339,10 +327,10 @@ class QuestCreationUtilsTest ) .newValue ) { q => - q should not matchPattern { case SpecificExpansionQuest(threeAway.id) => + q should not matchPattern { + case SpecificExpansionQuest(threeAway.id) => } } - } behavior of "availableQuests for dismiss vassal" @@ -360,7 +348,7 @@ class QuestCreationUtilsTest ) } - it should "not include a dismiss quest for the faction head" in { + it should "not include a dismiss quest for the faction head" in forAll( QuestCreationUtils .availableQuests( @@ -372,12 +360,12 @@ class QuestCreationUtilsTest ) .newValue ) { - _ should not matchPattern { case DismissSpecificVassalQuest(1) => + _ should not matchPattern { + case DismissSpecificVassalQuest(1) => } } - } - it should "not include a dismiss quest for a faction leader" in { + it should "not include a dismiss quest for a faction leader" in forAll( QuestCreationUtils .availableQuests( @@ -389,14 +377,14 @@ class QuestCreationUtilsTest ) .newValue ) { - _ should not matchPattern { case DismissSpecificVassalQuest(3) => + _ should not matchPattern { + case DismissSpecificVassalQuest(3) => } } - } behavior of "availableQuests for wealth" - it should "always include a wealth quest" in { + it should "always include a wealth quest" in forAtLeast( 1, QuestCreationUtils @@ -409,12 +397,12 @@ class QuestCreationUtilsTest ) .newValue ) { q => - inside(q) { case WealthQuest(gold, food) => - food should be >= 5000 + province.food - gold should be >= 5000 + province.gold + inside(q) { + case WealthQuest(gold, food) => + food should be >= 5000 + province.food + gold should be >= 5000 + province.gold } } - } behavior of "availableQuests for upgrading a battalion" @@ -443,7 +431,7 @@ class QuestCreationUtilsTest it should "raise the minimum requirement if there's already a battalion of that type" in { val provinceWithBatt = province.withBattalionIds(Vector(1)) - val battalions = Vector( + val battalions = Vector( BattalionC( id = 1, typeId = Longbowmen, @@ -469,8 +457,9 @@ class QuestCreationUtilsTest ) .newValue - val ubqs = quests.collect { case ubq: UpgradeBattalionQuest => - ubq + val ubqs = quests.collect { + case ubq: UpgradeBattalionQuest => + ubq } if ubqs.exists(_.battalionTypeId == Longbowmen) then ubqs @@ -488,7 +477,7 @@ class QuestCreationUtilsTest it should "not include a battalion type if the existing one has a stat too high" in { val provinceWithBatt = province.withBattalionIds(Vector(1)) - val battalions = Vector( + val battalions = Vector( BattalionC( id = 1, typeId = Longbowmen, @@ -507,8 +496,9 @@ class QuestCreationUtilsTest new JankyRandom(new Random()) ) .newValue - val ubqs = quests.collect { case ubq: UpgradeBattalionQuest => - ubq + val ubqs = quests.collect { + case ubq: UpgradeBattalionQuest => + ubq } forAll(ubqs) { ubq => @@ -520,7 +510,7 @@ class QuestCreationUtilsTest it should "include a quest for an army much larger than what we have" in { val provinceWithBatts = province.withBattalionIds(Vector(1, 2, 3, 4)) - val battalions = provinceWithBatts.battalionIds.map { id => + val battalions = provinceWithBatts.battalionIds.map { id => BattalionC(id = id, size = 800, typeId = Longbowmen) } @@ -535,9 +525,10 @@ class QuestCreationUtilsTest .newValue forAtLeast(1, quests) { q => - inside(q) { case GrandArmyQuest(totalTroopCount) => - totalTroopCount should be > 3200 + 2500 - totalTroopCount should be < 3200 + 5000 + inside(q) { + case GrandArmyQuest(totalTroopCount) => + totalTroopCount should be > 3200 + 2500 + totalTroopCount should be < 3200 + 5000 } } } @@ -633,7 +624,8 @@ class QuestCreationUtilsTest .newValue forAll(quests) { q => - q should not matchPattern { case DefeatFactionQuest(71) => + q should not matchPattern { + case DefeatFactionQuest(71) => } } } @@ -665,7 +657,8 @@ class QuestCreationUtilsTest .newValue forAll(quests) { q => - q should not matchPattern { case DefeatFactionQuest(71) => + q should not matchPattern { + case DefeatFactionQuest(71) => } } @@ -710,7 +703,7 @@ class QuestCreationUtilsTest ) .newValue - quests should not contain (AllianceQuest) + quests should not contain AllianceQuest } behavior of "available quests for a truce with a faction" @@ -742,7 +735,8 @@ class QuestCreationUtilsTest .newValue forAll(quests) { q => - q should not matchPattern { case DefeatFactionQuest(71) => + q should not matchPattern { + case DefeatFactionQuest(71) => } } @@ -784,7 +778,8 @@ class QuestCreationUtilsTest .newValue forAll(quests) { q => - q should not matchPattern { case TruceWithFactionQuest(71) => + q should not matchPattern { + case TruceWithFactionQuest(71) => } } } @@ -836,8 +831,9 @@ class QuestCreationUtilsTest .newValue forAtLeast(1, quests) { q => - inside(q) { case TruceCountQuest(truceCount) => - truceCount should be >= 3 + inside(q) { + case TruceCountQuest(truceCount) => + truceCount should be >= 3 } } } @@ -907,7 +903,8 @@ class QuestCreationUtilsTest .newValue forAll(quests) { q => - q should not matchPattern { case TruceCountQuest(truceCount) => + q should not matchPattern { + case TruceCountQuest(truceCount) => } } } @@ -975,11 +972,12 @@ class QuestCreationUtilsTest .newValue forExactly(1, quests) { quest => - inside(quest) { case AlmsAcrossRealmQuest(count, fulfilled, totalFood) => - count shouldBe totalFood - fulfilled shouldBe 0 - totalFood should be >= 4245 // 3000 * sqrt(2) - totalFood should be <= 7072 // 5000 * sqrt(2) + inside(quest) { + case AlmsAcrossRealmQuest(count, fulfilled, totalFood) => + count shouldBe totalFood + fulfilled shouldBe 0 + totalFood should be >= 4245 // 3000 * sqrt(2) + totalFood should be <= 7072 // 5000 * sqrt(2) } } } @@ -1003,11 +1001,12 @@ class QuestCreationUtilsTest .newValue forExactly(1, quests) { quest => - inside(quest) { case AlmsAcrossRealmQuest(count, fulfilled, totalFood) => - count shouldBe totalFood - fulfilled shouldBe 0 - totalFood should be >= (3000 * Math.pow(5, 0.5)).ceil.toInt - totalFood should be <= (5000 * Math.pow(5, 0.5)).ceil.toInt + inside(quest) { + case AlmsAcrossRealmQuest(count, fulfilled, totalFood) => + count shouldBe totalFood + fulfilled shouldBe 0 + totalFood should be >= (3000 * Math.pow(5, 0.5)).ceil.toInt + totalFood should be <= (5000 * Math.pow(5, 0.5)).ceil.toInt } } } diff --git a/src/test/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreationTest.scala b/src/test/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreationTest.scala index 1f15c128f6..2574628eae 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreationTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/quest_creation/TruceCountQuestCreationTest.scala @@ -1,10 +1,7 @@ package net.eagle0.eagle.library.util.quest_creation import net.eagle0.common.SeededRandom -import net.eagle0.eagle.library.settings.{ - MaxDesiredTruceCountForQuest, - MinDesiredNewTruceCountForQuest -} +import net.eagle0.eagle.library.settings.{MaxDesiredTruceCountForQuest, MinDesiredNewTruceCountForQuest} import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.faction.FactionRelationship import net.eagle0.eagle.model.state.faction.FactionRelationship.RelationshipLevel.Truce @@ -96,9 +93,10 @@ class TruceCountQuestCreationTest extends AnyFlatSpec with Matchers { .newValue quests should have size 1 - inside(quests.head) { case TruceCountQuest(truceCount) => - truceCount should be >= 3 - truceCount should be <= 4 + inside(quests.head) { + case TruceCountQuest(truceCount) => + truceCount should be >= 3 + truceCount should be <= 4 } } } diff --git a/src/test/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtilsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtilsTest.scala index 0bff7dccf9..1c7ad27b74 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/quest_fulfillment/QuestFulfillmentUtilsTest.scala @@ -5,17 +5,9 @@ import net.eagle0.eagle.common.unaffiliated_hero_quest.{ ImproveEconomyQuest as ImproveEconomyQuestProto, Quest as QuestProto } -import net.eagle0.eagle.model.action_result.{ - ActionResultT, - NotificationDetails, - NotificationT -} +import net.eagle0.eagle.model.action_result.{ActionResultT, NotificationDetails, NotificationT} import net.eagle0.eagle.model.action_result.changed_province.concrete.ChangedProvinceC -import net.eagle0.eagle.model.action_result.concrete.{ - ActionResultC, - ChangedHeroC, - NotificationC -} +import net.eagle0.eagle.model.action_result.concrete.{ActionResultC, ChangedHeroC, NotificationC} import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.{ QuestFailedMessage, @@ -24,18 +16,11 @@ import net.eagle0.eagle.model.action_result.generated_text_request.LlmRequestT.{ import net.eagle0.eagle.model.action_result.types.base.ActionResultType import net.eagle0.eagle.model.action_result.types.QuestFulfilledResultType import net.eagle0.eagle.model.state.date.Date -import net.eagle0.eagle.model.state.hero.{ - QuestFailedBackstoryEvent, - QuestFulfilledBackstoryEvent -} +import net.eagle0.eagle.model.state.hero.{QuestFailedBackstoryEvent, QuestFulfilledBackstoryEvent} import net.eagle0.eagle.model.state.province.concrete.ProvinceC import net.eagle0.eagle.model.state.quest.concrete.ImproveEconomyQuest import net.eagle0.eagle.model.state.quest.QuestT -import net.eagle0.eagle.model.state.unaffiliated_hero.{ - RecruitmentInfo, - UnaffiliatedHeroT, - UnaffiliatedHeroType -} +import net.eagle0.eagle.model.state.unaffiliated_hero.{RecruitmentInfo, UnaffiliatedHeroT, UnaffiliatedHeroType} import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC import org.scalamock.scalatest.MockFactory import org.scalatest.flatspec.AnyFlatSpec @@ -44,26 +29,23 @@ import org.scalatest.Inside.inside import org.scalatest.Inspectors.forExactly import org.scalatest.LoneElement.convertToCollectionLoneElementWrapper -class QuestFulfillmentUtilsTest - extends AnyFlatSpec - with MockFactory - with Matchers { - private val arType = mock[ActionResultType] - private val actingFid = 3 - private val uhHid = 21 - private val uhPid = 42 - private val currentDate = Date(year = 2024, month = Date.Month.July) - private val currentRoundId = 19 - private val questDetailsProto = +class QuestFulfillmentUtilsTest extends AnyFlatSpec with MockFactory with Matchers { + private val arType = mock[ActionResultType] + private val actingFid = 3 + private val uhHid = 21 + private val uhPid = 42 + private val currentDate = Date(year = 2024, month = Date.Month.July) + private val currentRoundId = 19 + private val questDetailsProto = ImproveEconomyQuestProto(provinceId = uhPid, desiredValue = 57) private val questProto: QuestProto = QuestProto( componentCount = 1, componentsFulfilled = 0, details = questDetailsProto ) - private val quest = + private val quest = ImproveEconomyQuest(provinceId = uhPid, desiredValue = 57) - private val uh: UnaffiliatedHeroT = UnaffiliatedHeroC( + private val uh: UnaffiliatedHeroT = UnaffiliatedHeroC( unaffiliatedHeroType = UnaffiliatedHeroType.Traveler, heroId = uhHid, factionBiases = Map.empty, @@ -90,7 +72,7 @@ class QuestFulfillmentUtilsTest ) shouldBe empty } - it should "return a new UH if the check is true" in { + it should "return a new UH if the check is true" in inside( QuestFulfillmentUtils .maybeFulfilledQuestResult( @@ -102,22 +84,22 @@ class QuestFulfillmentUtilsTest currentRoundId = currentRoundId, previousBackstoryTextId = s"backstory-${uh.heroId}" ) - ) { case Some(ar: ActionResultT) => - ar.actionResultType shouldBe QuestFulfilledResultType - ar.provinceId shouldBe Some(province.id) - ar.actingFactionId shouldBe Some(actingFid) - ar.changedProvinces shouldBe Vector( - ChangedProvinceC( - provinceId = province.id, - changedUnaffiliatedHeroes = Vector( - QuestFulfillmentUtils.uhWithFulfilledQuest(uh, actingFid) + ) { + case Some(ar: ActionResultT) => + ar.actionResultType shouldBe QuestFulfilledResultType + ar.provinceId shouldBe Some(province.id) + ar.actingFactionId shouldBe Some(actingFid) + ar.changedProvinces shouldBe Vector( + ChangedProvinceC( + provinceId = province.id, + changedUnaffiliatedHeroes = Vector( + QuestFulfillmentUtils.uhWithFulfilledQuest(uh, actingFid) + ) ) ) - ) } - } - it should "generate a notification and new LLM request" in { + it should "generate a notification and new LLM request" in inside( QuestFulfillmentUtils .maybeFulfilledQuestResult( @@ -129,46 +111,49 @@ class QuestFulfillmentUtilsTest currentRoundId = currentRoundId, previousBackstoryTextId = s"backstory-${uh.heroId}" ) - ) { case Some(ar: ActionResultT) => - val notes = ar.newNotifications - inside(notes.loneElement) { case note: NotificationC => - note.targetFactionIds shouldBe Vector(actingFid) - inside(note.details) { case qfd: NotificationDetails.QuestFulfilled => - qfd.heroId shouldBe uh.heroId - qfd.provinceId shouldBe province.id - qfd.fulfilledQuest shouldBe quest + ) { + case Some(ar: ActionResultT) => + val notes = ar.newNotifications + inside(notes.loneElement) { + case note: NotificationC => + note.targetFactionIds shouldBe Vector(actingFid) + inside(note.details) { + case qfd: NotificationDetails.QuestFulfilled => + qfd.heroId shouldBe uh.heroId + qfd.provinceId shouldBe province.id + qfd.fulfilledQuest shouldBe quest + } + inside(note.llm) { + case NotificationT.Llm.Id(llmId) => + llmId shouldBe s"quest fulfilled ${uh.heroId} Quest($quest)" + } + note.affectedProvinceIds shouldBe Vector(province.id) + note.affectedHeroIds shouldBe Vector(uh.heroId) + note.deferred shouldBe false } - inside(note.llm) { case NotificationT.Llm.Id(llmId) => - llmId shouldBe s"quest fulfilled ${uh.heroId} Quest($quest)" - } - note.affectedProvinceIds shouldBe Vector(province.id) - note.affectedHeroIds shouldBe Vector(uh.heroId) - note.deferred shouldBe false - } - inside(ar.newGeneratedTextRequests.loneElement) { - case QuestFulfilledMessage( - requestId: String, - eagleGameId: GameId, - recipientFactionIds: Vector[FactionId], - alwaysGenerate: Boolean, - heroId: HeroId, - provinceId: ProvinceId, - factionId: FactionId, - q: QuestT - ) => - requestId shouldBe s"quest fulfilled ${uh.heroId} Quest($quest)" - eagleGameId shouldBe gameId - heroId shouldBe uh.heroId - provinceId shouldBe province.id - factionId shouldBe actingFid - q shouldBe quest - recipientFactionIds shouldBe Vector(actingFid) - } + inside(ar.newGeneratedTextRequests.loneElement) { + case QuestFulfilledMessage( + requestId: String, + eagleGameId: GameId, + recipientFactionIds: Vector[FactionId], + alwaysGenerate: Boolean, + heroId: HeroId, + provinceId: ProvinceId, + factionId: FactionId, + q: QuestT + ) => + requestId shouldBe s"quest fulfilled ${uh.heroId} Quest($quest)" + eagleGameId shouldBe gameId + heroId shouldBe uh.heroId + provinceId shouldBe province.id + factionId shouldBe actingFid + q shouldBe quest + recipientFactionIds shouldBe Vector(actingFid) + } } - } - it should "generate a new backstory event for the hero" in { + it should "generate a new backstory event for the hero" in inside( QuestFulfillmentUtils .maybeFulfilledQuestResult( @@ -180,21 +165,21 @@ class QuestFulfillmentUtilsTest currentRoundId = currentRoundId, previousBackstoryTextId = s"backstory-19" ) - ) { case Some(ar: ActionResultT) => - ar.changedHeroes.loneElement shouldBe - ChangedHeroC( - heroId = uh.heroId, - newEventsForHeroBackstory = Vector( - QuestFulfilledBackstoryEvent( - date = currentDate, - provinceId = province.id, - factionId = actingFid, - quest = quest + ) { + case Some(ar: ActionResultT) => + ar.changedHeroes.loneElement shouldBe + ChangedHeroC( + heroId = uh.heroId, + newEventsForHeroBackstory = Vector( + QuestFulfilledBackstoryEvent( + date = currentDate, + provinceId = province.id, + factionId = actingFid, + quest = quest + ) ) ) - ) } - } "questFailedNotificationRequest" should "return a LlmRequest with the basics set" in { val result = @@ -235,15 +220,16 @@ class QuestFulfillmentUtilsTest currentDate = currentDate ) - forExactly(1, result.changedHeroes) { case ch: ChangedHeroC => - ch.heroId shouldBe uhHid - ch.newEventsForHeroBackstory.loneElement shouldBe - QuestFailedBackstoryEvent( - date = Date(year = 2024, month = Date.Month.July), - provinceId = uhPid, - factionId = actingFid, - quest = quest - ) + forExactly(1, result.changedHeroes) { + case ch: ChangedHeroC => + ch.heroId shouldBe uhHid + ch.newEventsForHeroBackstory.loneElement shouldBe + QuestFailedBackstoryEvent( + date = Date(year = 2024, month = Date.Month.July), + provinceId = uhPid, + factionId = actingFid, + quest = quest + ) } } @@ -262,12 +248,14 @@ class QuestFulfillmentUtilsTest currentDate = currentDate ) - forExactly(1, result.newNotifications) { case note: NotificationT => - inside(note.details) { case qfd: NotificationDetails.QuestFailed => - qfd.heroId shouldBe uhHid - qfd.provinceId shouldBe uhPid - qfd.failedQuest shouldBe quest - } + forExactly(1, result.newNotifications) { + case note: NotificationT => + inside(note.details) { + case qfd: NotificationDetails.QuestFailed => + qfd.heroId shouldBe uhHid + qfd.provinceId shouldBe uhPid + qfd.failedQuest shouldBe quest + } } } } diff --git a/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOddsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOddsTest.scala index a0af7483bf..97add66246 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOddsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/LegacyRecruitmentOddsTest.scala @@ -28,13 +28,10 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class LegacyRecruitmentOddsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class LegacyRecruitmentOddsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - val targetHeroId = 7 - val factionId = 3 + val targetHeroId = 7 + val factionId = 3 val factionLeadingHeroId = 9 override def beforeEach(): Unit = { @@ -130,7 +127,7 @@ class LegacyRecruitmentOddsTest } "high prestige" should "increase odds" in { - val targetHero = Hero() + val targetHero = Hero() .withId(targetHeroId) .withStrength(15) .withAgility(15) @@ -167,7 +164,7 @@ class LegacyRecruitmentOddsTest } "target status" should "change odds" in { - val targetHero = Hero() + val targetHero = Hero() .withId(targetHeroId) .withStrength(15) .withAgility(15) @@ -247,7 +244,7 @@ class LegacyRecruitmentOddsTest } "faction bias" should "change odds" in { - val targetHero = Hero() + val targetHero = Hero() .withId(targetHeroId) .withStrength(15) .withAgility(15) diff --git a/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOddsTest.scala b/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOddsTest.scala index c0999c2e6a..30b8158a92 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOddsTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/recruitment_odds/RecruitmentOddsTest.scala @@ -18,23 +18,15 @@ import net.eagle0.eagle.model.state.faction.concrete.FactionC import net.eagle0.eagle.model.state.hero.concrete.HeroC import net.eagle0.eagle.model.state.hero.Profession import net.eagle0.eagle.model.state.unaffiliated_hero.concrete.UnaffiliatedHeroC -import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{ - Outlaw, - Prisoner, - Resident, - Traveler -} +import net.eagle0.eagle.model.state.unaffiliated_hero.UnaffiliatedHeroType.{Outlaw, Prisoner, Resident, Traveler} import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class RecruitmentOddsTest - extends AnyFlatSpec - with Matchers - with BeforeAndAfterEach { +class RecruitmentOddsTest extends AnyFlatSpec with Matchers with BeforeAndAfterEach { - val targetHeroId = 7 - val factionId = 3 + val targetHeroId = 7 + val factionId = 3 val factionLeadingHeroId = 9 override def beforeEach(): Unit = { @@ -142,7 +134,7 @@ class RecruitmentOddsTest } "high prestige" should "increase odds" in { - val targetHero = HeroC( + val targetHero = HeroC( id = targetHeroId, strength = 15, agility = 15, @@ -185,7 +177,7 @@ class RecruitmentOddsTest } "target status" should "change odds" in { - val targetHero = HeroC( + val targetHero = HeroC( id = targetHeroId, strength = 15, agility = 15, diff --git a/src/test/scala/net/eagle0/eagle/library/util/validations/RuntimeValidatorTest.scala b/src/test/scala/net/eagle0/eagle/library/util/validations/RuntimeValidatorTest.scala index 1f13b8109d..82afe3b94e 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/validations/RuntimeValidatorTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/validations/RuntimeValidatorTest.scala @@ -25,9 +25,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { "validate hero" should "throw if factionId is 0" in { val hero = Hero(id = 5, factionId = Some(0)) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(hero) - } ex.getMessage shouldBe s"validation failed: Invalid player id for hero ${hero.toString}" } @@ -35,9 +34,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "throw if the heroId is 0" in { val hero = Hero(id = 0, factionId = Some(7), nameTextId = "hn_0") - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(hero) - } ex.getMessage shouldBe s"validation failed: Invalid id for hero ${hero.toString}" } @@ -45,9 +43,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "throw if the nameTextId is empty" in { val hero = Hero(id = 5, factionId = Some(7), nameTextId = "") - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(hero) - } ex.getMessage shouldBe s"validation failed: Empty nameTextId for hero ${hero.toString}" } @@ -55,9 +52,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "throw if there are no backstory events" in { val hero = Hero(id = 19, factionId = Some(7), nameTextId = "hn_19") - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(hero) - } ex.getMessage shouldBe s"validation failed: Empty backstory history for hero ${hero.toString}" } @@ -70,51 +66,44 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { nameTextId = "hn_5" ) - noException should be thrownBy { + noException should be thrownBy RuntimeValidator.validate(hero) - } } "validate battalion" should "throw if the battalion id is 0" in { val battalion = Battalion(id = 0, `type` = BattalionTypeId.LIGHT_INFANTRY) - val gs = GameState( + val gs = GameState( randomSeed = 1L, - battalionTypes = - Vector(BattalionType(typeId = LIGHT_INFANTRY, capacity = 1000)) + battalionTypes = Vector(BattalionType(typeId = LIGHT_INFANTRY, capacity = 1000)) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(battalion, gs) - } ex.getMessage shouldBe s"validation failed: Invalid id for battalion ${battalion.toString}" } it should "not throw if the battalion id is valid" in { val battalion = Battalion(id = 3, `type` = BattalionTypeId.LIGHT_INFANTRY) - val gs = GameState( + val gs = GameState( randomSeed = 1L, - battalionTypes = - Vector(BattalionType(typeId = LIGHT_INFANTRY, capacity = 1000)) + battalionTypes = Vector(BattalionType(typeId = LIGHT_INFANTRY, capacity = 1000)) ) - noException should be thrownBy { + noException should be thrownBy RuntimeValidator.validate(battalion, gs) - } } it should "throw if the battalion is over capacity" in { val battalion = Battalion(id = 7, `type` = BattalionTypeId.LIGHT_INFANTRY, size = 975) - val gs = GameState( + val gs = GameState( randomSeed = 1L, - battalionTypes = - Vector(BattalionType(typeId = LIGHT_INFANTRY, capacity = 950)) + battalionTypes = Vector(BattalionType(typeId = LIGHT_INFANTRY, capacity = 950)) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(battalion, gs) - } ex.getMessage shouldBe s"validation failed: BattalionId 7 is over capacity" } @@ -122,9 +111,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { "validate province" should "throw if the province id is 0" in { val province = Province(id = 0, priceIndex = 1.0) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: Invalid id for province ${province.toString}" } @@ -132,9 +120,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "throw if the price index is 0.0" in { val province = Province(id = 17, priceIndex = 0.0, name = "Vovimaria") - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: Invalid price index 0.0 in province 17 (Vovimaria)" } @@ -142,9 +129,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "throw if the price index is negative" in { val province = Province(id = 17, priceIndex = -0.4, name = "Fluria") - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: Invalid price index -0.4 in province 17 (Fluria)" } @@ -152,9 +138,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "not throw if the province id is valid and the priceIndex is valid" in { val province = Province(id = 17, priceIndex = 1.0) - noException should be thrownBy { + noException should be thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } } it should "throw if the province contains hero id 0" in { @@ -165,9 +150,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { rulingFactionHeroIds = Vector(3, 4, 0) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: Invalid hero id in province ${province.toString}" } @@ -175,9 +159,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "throw if the province contains battalion id 0" in { val province = Province(id = 18, battalionIds = Vector(0)) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: Invalid battalion id in province ${province.toString}" } @@ -190,9 +173,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { rulingFactionHeroIds = Vector(3, 7, 3) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: Duplicate hero ids in province ${province.toString}" } @@ -204,9 +186,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { rulingFactionHeroIds = Vector(3, 7) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.VASSAL_COMMANDS) - } ex.getMessage shouldBe s"validation failed: The ruling player and ruling hero state do not match in province ${province.toString}" } @@ -220,9 +201,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { priceIndex = 1.0 ) - noException should be thrownBy { + noException should be thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } } it should "throw if there is a ruling hero but no ruling player" in { @@ -234,9 +214,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { priceIndex = 1.0 ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.VASSAL_COMMANDS) - } ex.getMessage shouldBe s"validation failed: The ruling player and ruling hero state do not match in province ${province.toString}" } @@ -263,9 +242,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { priceIndex = 1.0 ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: The ruling hero is not in the heroes list in province ${province.toString}" } @@ -273,9 +251,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { it should "throw if the support is >0 but there is no ruling faction" in { val province = Province(id = 18, rulingFactionId = None, support = 20) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } ex.getMessage shouldBe s"validation failed: There is no ruling faction but there is support in province ${province.toString}" } @@ -290,9 +267,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { priceIndex = 1.0 ) - noException should be thrownBy { + noException should be thrownBy RuntimeValidator.validate(province, RoundPhase.PLAYER_COMMANDS) - } } "validate province against gamestate" should "throw if there is a factionId mismatch" in { @@ -309,14 +285,13 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { randomSeed = 1L, provinces = Map(province.id -> province), heroes = Map( - 3 -> Hero(id = 3, factionId = Some(2)), + 3 -> Hero(id = 3, factionId = Some(2)), mismatchedHero.id -> mismatchedHero ) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(gameState) - } ex.getMessage shouldBe s"validation failed: Mismatched factionIds in ${province.toString}\n${mismatchedHero.toString}" } @@ -345,9 +320,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { ) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(gs) - } ex.getMessage shouldBe s"validation failed: Attacking faction 3 is not allied with other attackers in ${province.toString}" } @@ -386,9 +360,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { ) ) - noException should be thrownBy { + noException should be thrownBy RuntimeValidator.validate(gs) - } } it should "not throw if the factionIds in the heroes and the ruling player of the province match" in { @@ -408,20 +381,19 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { ) ) - noException should be thrownBy { + noException should be thrownBy RuntimeValidator.validate(gameState) - } } it should "throw if the same hero Id is in multiple provinces" in { def hero(id: HeroId) = Hero(id = id, factionId = Some(2)) - val p1 = + val p1 = Province( id = 10, rulingFactionId = Some(2), rulingFactionHeroIds = Vector(3, 4) ) - val p2 = + val p2 = Province( id = 5, rulingFactionId = Some(2), @@ -434,9 +406,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { provinces = Map(p1.id -> p1, p2.id -> p2) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(gameState) - } ex.getMessage shouldBe "validation failed: HeroId 4 found in multiple provinces (10, 5): List(HeroProvincePair(4,10,0), HeroProvincePair(4,5,0))" } @@ -446,14 +417,13 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { id = 99, arrivalRound = 7 ) - val province = Province( + val province = Province( id = 31, incomingArmies = Vector(incomingArmy) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validateIncomingArmies(province, 8) - } ex.getMessage shouldBe "validation failed: MovingArmy 99 was supposed to arrive in round 7, but it is round 8" } @@ -463,7 +433,7 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { id = 99, arrivalRound = 7 ) - val province = Province( + val province = Province( id = 31, incomingArmies = Vector(incomingArmy) ) @@ -480,9 +450,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { provinces = mapifyProvinces(Province(id = 21, rulingFactionId = None)) ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(gameState) - } ex.getMessage shouldBe "validation failed: Unowned focus province for faction Faction(7,0,,List(),List(),List(),List(),Some(21),List(),0,List(),List(),List(),List(),0,UnknownFieldSet(Map()))" @@ -507,9 +476,8 @@ class RuntimeValidatorTest extends AnyFlatSpec with Matchers { ) // faction 8 does not exist ) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy RuntimeValidator.validate(gameState) - } ex.getMessage shouldBe "validation failed: Invalid target faction id 8 in faction relationship FactionRelationship(8,TRUCE,Some(Date(4,2025,UnknownFieldSet(Map()))),20,UnknownFieldSet(Map()))" diff --git a/src/test/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilterTest.scala b/src/test/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilterTest.scala index 6397040d28..fa8093bf50 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilterTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/view_filters/FactionViewFilterTest.scala @@ -6,19 +6,13 @@ import net.eagle0.eagle.common.round_phase.RoundPhase.PROVINCE_EVENTS import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState import net.eagle0.eagle.internal.province.Province -import net.eagle0.eagle.library.settings.{ - MinSupportForTaxes, - PrestigePerSupportedProvince -} +import net.eagle0.eagle.library.settings.{MinSupportForTaxes, PrestigePerSupportedProvince} import net.eagle0.eagle.views.faction_view.FactionView import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class FactionViewFilterTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class FactionViewFilterTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { PrestigePerSupportedProvince.setDoubleValue(8) @@ -26,13 +20,13 @@ class FactionViewFilterTest } private val factions = Map( - 3 -> Faction( + 3 -> Faction( id = 3, factionHeadId = 8, leaders = Vector(8), name = "Jane's Faction" ), - 7 -> Faction( + 7 -> Faction( id = 7, factionHeadId = 12, leaders = Vector(12), diff --git a/src/test/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilterTest.scala b/src/test/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilterTest.scala index 9c46c42577..ced84c211f 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilterTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/view_filters/HeroViewFilterTest.scala @@ -1,28 +1,16 @@ package net.eagle0.eagle.library.util.view_filters -import net.eagle0.eagle.common.diplomacy_offer.{ - DiplomacyOffer, - TruceOfferDetails -} -import net.eagle0.eagle.common.round_phase.RoundPhase.{ - DIPLOMACY_RESOLUTION, - PLAYER_COMMANDS -} +import net.eagle0.eagle.common.diplomacy_offer.{DiplomacyOffer, TruceOfferDetails} +import net.eagle0.eagle.common.round_phase.RoundPhase.{DIPLOMACY_RESOLUTION, PLAYER_COMMANDS} import net.eagle0.eagle.internal.faction.Faction import net.eagle0.eagle.internal.game_state.GameState -import net.eagle0.eagle.library.settings.{ - MinSupportForTaxes, - PrestigePerSupportedProvince -} +import net.eagle0.eagle.library.settings.{MinSupportForTaxes, PrestigePerSupportedProvince} import net.eagle0.eagle.library.util.IDable.mapifyFactions import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class HeroViewFilterTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class HeroViewFilterTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { PrestigePerSupportedProvince.setDoubleValue(8) diff --git a/src/test/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilterTest.scala b/src/test/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilterTest.scala index 0449f2b58d..976beb62b7 100644 --- a/src/test/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilterTest.scala +++ b/src/test/scala/net/eagle0/eagle/library/util/view_filters/ProvinceViewFilterTest.scala @@ -14,32 +14,18 @@ import net.eagle0.eagle.internal.hero.Hero import net.eagle0.eagle.internal.province.Province import net.eagle0.eagle.internal.supplies.{MovingSupplies, Supplies} import net.eagle0.eagle.internal.unaffiliated_hero.UnaffiliatedHero -import net.eagle0.eagle.library.settings.{ - BaseResourceLimit, - PerDevelopmentResourceLimit -} -import net.eagle0.eagle.library.util.IDable.{ - mapifyFactions, - mapifyHeroes, - mapifyProvinces -} +import net.eagle0.eagle.library.settings.{BaseResourceLimit, PerDevelopmentResourceLimit} +import net.eagle0.eagle.library.util.IDable.{mapifyFactions, mapifyHeroes, mapifyProvinces} import net.eagle0.eagle.views.battalion_view.BattalionView import net.eagle0.eagle.views.incoming_army_view.IncomingArmyView -import net.eagle0.eagle.views.province_view.{ - FullProvinceInfo, - ProvinceView, - UnaffiliatedHeroBasics -} +import net.eagle0.eagle.views.province_view.{FullProvinceInfo, ProvinceView, UnaffiliatedHeroBasics} import net.eagle0.eagle.HeroId import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach import org.scalatest.Inside.inside -class ProvinceViewFilterTest - extends AnyFlatSpec - with BeforeAndAfterEach - with Matchers { +class ProvinceViewFilterTest extends AnyFlatSpec with BeforeAndAfterEach with Matchers { override def beforeEach(): Unit = { BaseResourceLimit.setIntValue(5000) diff --git a/src/test/scala/net/eagle0/eagle/model/state/date/DateTest.scala b/src/test/scala/net/eagle0/eagle/model/state/date/DateTest.scala index 75453ec9e0..384b125562 100644 --- a/src/test/scala/net/eagle0/eagle/model/state/date/DateTest.scala +++ b/src/test/scala/net/eagle0/eagle/model/state/date/DateTest.scala @@ -23,28 +23,28 @@ class DateTest extends AnyFlatSpec with Matchers { } ">=" should "return true if it's a later month" in { - val leftDate = Date(year = 1501, month = Date.Month.July) + val leftDate = Date(year = 1501, month = Date.Month.July) val rightDate = Date(year = 1501, month = Date.Month.April) leftDate >= rightDate shouldBe true } it should "return true if it's the same month and year" in { - val leftDate = Date(year = 1501, month = Date.Month.July) + val leftDate = Date(year = 1501, month = Date.Month.July) val rightDate = Date(year = 1501, month = Date.Month.July) leftDate >= rightDate shouldBe true } it should "return false if it's an earlier month" in { - val leftDate = Date(year = 1501, month = Date.Month.July) + val leftDate = Date(year = 1501, month = Date.Month.July) val rightDate = Date(year = 1501, month = Date.Month.August) leftDate >= rightDate shouldBe false } it should "return true if it's a later year" in { - val leftDate = Date(year = 1501, month = Date.Month.July) + val leftDate = Date(year = 1501, month = Date.Month.July) val rightDate = Date(year = 1500, month = Date.Month.August) leftDate >= rightDate shouldBe true diff --git a/src/test/scala/net/eagle0/eagle/service/GamesManagerTest.scala b/src/test/scala/net/eagle0/eagle/service/GamesManagerTest.scala index e4ddd3a571..73ae55b696 100644 --- a/src/test/scala/net/eagle0/eagle/service/GamesManagerTest.scala +++ b/src/test/scala/net/eagle0/eagle/service/GamesManagerTest.scala @@ -29,32 +29,27 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.BeforeAndAfterEach -class GamesManagerTest - extends AnyFlatSpec - with MockFactory - with Matchers - with BeforeAndAfterEach - with ProtoMatchers { +class GamesManagerTest extends AnyFlatSpec with MockFactory with Matchers with BeforeAndAfterEach with ProtoMatchers { private class TestRandom extends Random { var nextLongImpl: () => Long = Random.nextLong - def throwOnNextLong(): Unit = nextLongImpl = () => ??? + def throwOnNextLong(): Unit = nextLongImpl = () => ??? def setStaticNextLong(value: Long): Unit = nextLongImpl = () => value - def reset(): Unit = nextLongImpl = Random.nextLong + def reset(): Unit = nextLongImpl = Random.nextLong override def nextLong(): Long = nextLongImpl() } - private val mockChannel = mock[Channel] - private val mockShardokInterface = + private val mockChannel = mock[Channel] + private val mockShardokInterface = ShardokInternalInterfaceGrpc.stub(mockChannel) - private val mockRandom = new TestRandom() - private val mockGameCreation = mock[NewGameCreation] + private val mockRandom = new TestRandom() + private val mockGameCreation = mock[NewGameCreation] private val mockGamePersisterCreation = mock[GamePersisterCreation] - private val mockEngine = mock[Engine] - private val mockHistory = mock[GameHistory] - private val mockPersister = mock[Persister] + private val mockEngine = mock[Engine] + private val mockHistory = mock[GameHistory] + private val mockPersister = mock[Persister] private val greatPerson1 = GreatPersonWithBackstory( @@ -90,9 +85,8 @@ class GamesManagerTest val dir = new File("/tmp/eagle0") - override def beforeEach(): Unit = { + override def beforeEach(): Unit = mockRandom.reset() - } private val gameId = 0xcafefeed diff --git a/src/test/scala/net/eagle0/eagle/service/HumanPlayerClientConnectionStateTest.scala b/src/test/scala/net/eagle0/eagle/service/HumanPlayerClientConnectionStateTest.scala index 323dc47b1a..fb5c34b6e7 100644 --- a/src/test/scala/net/eagle0/eagle/service/HumanPlayerClientConnectionStateTest.scala +++ b/src/test/scala/net/eagle0/eagle/service/HumanPlayerClientConnectionStateTest.scala @@ -3,11 +3,7 @@ package net.eagle0.eagle.service import java.io.PrintWriter import net.eagle0.eagle.api.command.AvailableCommands -import net.eagle0.eagle.api.eagle.{ - ActionResultResponse, - GameUpdate, - UpdateStreamResponse -} +import net.eagle0.eagle.api.eagle.{ActionResultResponse, GameUpdate, UpdateStreamResponse} import net.eagle0.eagle.api.eagle.GameUpdate.GameUpdateDetails import net.eagle0.eagle.common.date.Date import net.eagle0.eagle.internal.action_result.ActionResult @@ -29,15 +25,15 @@ class HumanPlayerClientConnectionStateTest with MockFactory with BeforeAndAfterEach with OneInstancePerTest { - private val mockHistoryLarger = mock[GameHistory] - private val mockHistorySmaller = mock[GameHistory] + private val mockHistoryLarger = mock[GameHistory] + private val mockHistorySmaller = mock[GameHistory] private val mockObserver: SyncResponseObserver = mock[SyncResponseObserver] - private val mockLogWriter = new PrintWriter(System.out) - private val fid: FactionId = 3 - private val largerCount = 22 - private val smallerCount = 20 - private val newToken = 0xabcdL - private val eagleGameId = 0xfeedfaceL + private val mockLogWriter = new PrintWriter(System.out) + private val fid: FactionId = 3 + private val largerCount = 22 + private val smallerCount = 20 + private val newToken = 0xabcdL + private val eagleGameId = 0xfeedfaceL private val leaderName = "Nolen" diff --git a/src/test/scala/net/eagle0/eagle/service/LlmResolverTest.scala b/src/test/scala/net/eagle0/eagle/service/LlmResolverTest.scala index 08b23b9fe7..8b4712ceb4 100644 --- a/src/test/scala/net/eagle0/eagle/service/LlmResolverTest.scala +++ b/src/test/scala/net/eagle0/eagle/service/LlmResolverTest.scala @@ -13,11 +13,10 @@ import org.scalatest.matchers.should.Matchers.* class LlmResolverTest extends AnyFlatSpec with MockFactory { private val mockReceiver = mock[LlmUpdateQueuingProxy] - private val llmResolver = + private val llmResolver = new LlmResolver(updateReceiver = mockReceiver, gptModelName = "fakeModel") - private val unsortedRequests - : Vector[(GeneratedTextRequest, TextGenerationResult, Option[String])] = + private val unsortedRequests: Vector[(GeneratedTextRequest, TextGenerationResult, Option[String])] = Vector( ( GeneratedTextRequest(id = "firstRequest"), diff --git a/src/test/scala/net/eagle0/eagle/service/UnrequestedTextHandlerTest.scala b/src/test/scala/net/eagle0/eagle/service/UnrequestedTextHandlerTest.scala index 937e957be2..575a4343c4 100644 --- a/src/test/scala/net/eagle0/eagle/service/UnrequestedTextHandlerTest.scala +++ b/src/test/scala/net/eagle0/eagle/service/UnrequestedTextHandlerTest.scala @@ -23,16 +23,13 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers.{shouldBe, the} import org.scalatest.BeforeAndAfterEach -class UnrequestedTextHandlerTest - extends AnyFlatSpec - with BeforeAndAfterEach - with MockFactory { +class UnrequestedTextHandlerTest extends AnyFlatSpec with BeforeAndAfterEach with MockFactory { private val mockLlmResolver = mock[LlmResolver] - private val mockCts = mock[ClientTextStore] + private val mockCts = mock[ClientTextStore] private val mockCtsAfterOne = mock[ClientTextStore] private val mockCtsAfterTwo = mock[ClientTextStore] - private val mockHistory = mock[GameHistory] - private val mockFr = mock[FunctionalRandom] + private val mockHistory = mock[GameHistory] + private val mockFr = mock[FunctionalRandom] private val llmRequest1 = GeneratedTextRequest(id = "firstRequest") private val llmRequest2 = GeneratedTextRequest(id = "secondRequest") @@ -53,7 +50,7 @@ class UnrequestedTextHandlerTest .expects() .returning( Map( - "firstRequest" -> UnrequestedClientText( + "firstRequest" -> UnrequestedClientText( id = "firstRequest", requestedAfterHistoryCount = 37, llmRequest = llmRequest1 @@ -123,7 +120,7 @@ class UnrequestedTextHandlerTest .expects() .returning( Map( - "firstRequest" -> UnrequestedClientText( + "firstRequest" -> UnrequestedClientText( id = "firstRequest", requestedAfterHistoryCount = 37, llmRequest = llmRequest1 @@ -181,14 +178,13 @@ class UnrequestedTextHandlerTest .expects(38) .returning(gameState) - val ex = the[EagleInternalException] thrownBy { + val ex = the[EagleInternalException] thrownBy handler .clientTextStoreWithHandledUnrequestedTexts( clientTextStore = mockCts, gameHistory = mockHistory, randomLong = 1 ) - } ex.getMessage shouldBe "Unrequested text dependencies are stuck: firstRequest, secondRequest" } @@ -210,7 +206,7 @@ class UnrequestedTextHandlerTest requestedAfterHistoryCount = 37, llmRequest = fixedNameRequest ), - "llmRequest" -> UnrequestedClientText( + "llmRequest" -> UnrequestedClientText( id = "llmRequest", requestedAfterHistoryCount = 38, llmRequest = llmRequest @@ -286,7 +282,7 @@ class UnrequestedTextHandlerTest .expects() .returning( Map( - "maleHeroName" -> UnrequestedClientText( + "maleHeroName" -> UnrequestedClientText( id = "maleHeroName", requestedAfterHistoryCount = 37, llmRequest = maleNameRequest @@ -365,7 +361,7 @@ class UnrequestedTextHandlerTest .expects() .returning( Map( - "fixedName" -> UnrequestedClientText( + "fixedName" -> UnrequestedClientText( id = "fixedName", requestedAfterHistoryCount = 37, llmRequest = fixedNameRequest @@ -375,7 +371,7 @@ class UnrequestedTextHandlerTest requestedAfterHistoryCount = 38, llmRequest = generatedNameRequest ), - "llmText" -> UnrequestedClientText( + "llmText" -> UnrequestedClientText( id = "llmText", requestedAfterHistoryCount = 39, llmRequest = llmRequest @@ -384,7 +380,7 @@ class UnrequestedTextHandlerTest ) // Mock the chain of processing: fixed names -> generated names -> LLM requests - val mockCtsAfterFixed = mock[ClientTextStore] + val mockCtsAfterFixed = mock[ClientTextStore] val mockCtsAfterGenerated = mock[ClientTextStore] // Fixed name processing diff --git a/src/test/scala/net/eagle0/eagle/service/controller/GameControllerTest.scala b/src/test/scala/net/eagle0/eagle/service/controller/GameControllerTest.scala index b77ce55696..e0943e0ca5 100644 --- a/src/test/scala/net/eagle0/eagle/service/controller/GameControllerTest.scala +++ b/src/test/scala/net/eagle0/eagle/service/controller/GameControllerTest.scala @@ -15,15 +15,11 @@ import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers import org.scalatest.OneInstancePerTest -class GameControllerTest - extends AnyFlatSpec - with MockFactory - with Matchers - with OneInstancePerTest { - private val mockEngine = mock[Engine] - private val mockLogWriter = new PrintWriter(System.out) +class GameControllerTest extends AnyFlatSpec with MockFactory with Matchers with OneInstancePerTest { + private val mockEngine = mock[Engine] + private val mockLogWriter = new PrintWriter(System.out) private val mockClientTextStore = mock[ClientTextStore] - private val eagleGameId = 0xfeedfaceL + private val eagleGameId = 0xfeedfaceL (() => mockEngine.factionIds) .expects() @@ -106,14 +102,13 @@ class GameControllerTest .returns(42) .anyNumberOfTimes() - val ex = the[EagleClientException] thrownBy { + val ex = the[EagleClientException] thrownBy controller.postHumanCommand( userName = "joe", selectedProvinceId = 0, command = ReturnSelectedCommand(), token = 41 ) - } ex.getMessage shouldBe "requirement failed: Token mismatch for joe (expected 42, got 41)" } @@ -208,13 +203,12 @@ class GameControllerTest .returns(5) .anyNumberOfTimes() - noException should be thrownBy { + noException should be thrownBy controller.postHumanCommand( userName = "joe", selectedProvinceId = 0, command = command, token = 5 ) - } } } diff --git a/src/test/scala/net/eagle0/eagle/service/new_game_creation/FixedHeroesTest.scala b/src/test/scala/net/eagle0/eagle/service/new_game_creation/FixedHeroesTest.scala index 6d15440be1..3d687fb18a 100644 --- a/src/test/scala/net/eagle0/eagle/service/new_game_creation/FixedHeroesTest.scala +++ b/src/test/scala/net/eagle0/eagle/service/new_game_creation/FixedHeroesTest.scala @@ -8,43 +8,43 @@ import org.scalatest.matchers.should.Matchers class FixedHeroesTest extends AnyFlatSpec with Matchers { private val tsvMaps = Vector( Map( - "name" -> "The Eagle", - "strength" -> "65", - "agility" -> "75", - "constitution" -> "96", - "charisma" -> "84", - "wisdom" -> "102", - "integrity" -> "37", - "ambition" -> "100", + "name" -> "The Eagle", + "strength" -> "65", + "agility" -> "75", + "constitution" -> "96", + "charisma" -> "84", + "wisdom" -> "102", + "integrity" -> "37", + "ambition" -> "100", "gregariousness" -> "85", - "bravery" -> "61", - "vigor" -> "96", - "profession" -> "mage", - "great person" -> "TRUE", - "image_path" -> "fixed/eagle.png", - "gender" -> "male", - "personality" -> "one, two, three", - "faction_name" -> "The Eagle's Faction", - "backstory" -> "The Eagle's backstory" + "bravery" -> "61", + "vigor" -> "96", + "profession" -> "mage", + "great person" -> "TRUE", + "image_path" -> "fixed/eagle.png", + "gender" -> "male", + "personality" -> "one, two, three", + "faction_name" -> "The Eagle's Faction", + "backstory" -> "The Eagle's backstory" ), Map( - "name" -> "Bergil", - "strength" -> "30", - "agility" -> "60", - "constitution" -> "60", - "charisma" -> "20", - "wisdom" -> "25", - "integrity" -> "95", - "ambition" -> "87", + "name" -> "Bergil", + "strength" -> "30", + "agility" -> "60", + "constitution" -> "60", + "charisma" -> "20", + "wisdom" -> "25", + "integrity" -> "95", + "ambition" -> "87", "gregariousness" -> "91", - "bravery" -> "63", - "vigor" -> "60", - "profession" -> "rAnGeR", - "great person" -> "FALSE", - "image_path" -> "fixed/bergil.png", - "gender" -> "other", - "personality" -> "five, six, seven", - "backstory" -> "Bergil's backstory" + "bravery" -> "63", + "vigor" -> "60", + "profession" -> "rAnGeR", + "great person" -> "FALSE", + "image_path" -> "fixed/bergil.png", + "gender" -> "other", + "personality" -> "five, six, seven", + "backstory" -> "Bergil's backstory" ) ) diff --git a/src/test/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtilsTest.scala b/src/test/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtilsTest.scala index f08307fe2c..fe51438a15 100644 --- a/src/test/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtilsTest.scala +++ b/src/test/scala/net/eagle0/eagle/service/new_game_creation/StartGameActionResultUtilsTest.scala @@ -13,8 +13,7 @@ class StartGameActionResultUtilsTest extends AnyFlatSpec with Matchers { Hero(id = 99, nameTextId = "hn_99", factionId = Some(3)), Hero(id = 17, nameTextId = "hn_17") ), - newProvinces = - Vector(Province(id = 8, economy = 7), Province(id = 3, agriculture = 99)) + newProvinces = Vector(Province(id = 8, economy = 7), Province(id = 3, agriculture = 99)) ) import net.eagle0.eagle.service.new_game_creation.StartGameActionResultUtils._StartGameActionResult @@ -80,9 +79,10 @@ class StartGameActionResultUtilsTest extends AnyFlatSpec with Matchers { ) .newHeroes - forExactly(1, heroesAfter) { case hero => - hero.id shouldBe 100 - hero.nameTextId shouldBe "phn_3" + forExactly(1, heroesAfter) { + case hero => + hero.id shouldBe 100 + hero.nameTextId shouldBe "phn_3" } } }