mirror of
https://github.com/nolen777/eagle0.git
synced 2026-07-28 19:55:41 +00:00
+30
-1
@@ -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\\..*"],
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
+14
-23
@@ -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()
|
||||
}
|
||||
|
||||
+3
-5
@@ -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("")
|
||||
|
||||
+40
-45
@@ -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)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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(" ")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-11
@@ -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) =>
|
||||
|
||||
@@ -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 _ => ???
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -37,5 +37,5 @@ case class UnrequestedClientText(
|
||||
llmRequest: GeneratedTextRequest
|
||||
) extends ClientText {
|
||||
def complete: Boolean = false
|
||||
def text: String = ""
|
||||
def text: String = ""
|
||||
}
|
||||
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
package net.eagle0.eagle.library
|
||||
|
||||
class EagleValidationException(message: String)
|
||||
extends EagleInternalException(message) {}
|
||||
class EagleValidationException(message: String) extends EagleInternalException(message) {}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
|
||||
+130
-157
@@ -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,
|
||||
|
||||
+7
-7
@@ -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(
|
||||
|
||||
+3
-6
@@ -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)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+4
-8
@@ -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(
|
||||
|
||||
+3
-8
@@ -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)
|
||||
)
|
||||
)
|
||||
|
||||
+16
-21
@@ -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
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+97
-114
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-6
@@ -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)
|
||||
)
|
||||
)
|
||||
|
||||
+2
-5
@@ -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))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+12
-21
@@ -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,
|
||||
|
||||
+52
-61
@@ -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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
+1
-2
@@ -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,
|
||||
|
||||
+20
-35
@@ -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)
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-18
@@ -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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+3
-6
@@ -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
|
||||
|
||||
+1
-2
@@ -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,
|
||||
|
||||
+1
-2
@@ -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,
|
||||
|
||||
+2
-6
@@ -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 {
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-9
@@ -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(
|
||||
|
||||
+2
-5
@@ -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)
|
||||
)
|
||||
}
|
||||
|
||||
+3
-9
@@ -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 {
|
||||
|
||||
+7
-19
@@ -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(
|
||||
|
||||
+16
-22
@@ -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))
|
||||
|
||||
+8
-12
@@ -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(
|
||||
|
||||
+2
-4
@@ -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))
|
||||
|
||||
+6
-10
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
+1
-4
@@ -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,
|
||||
|
||||
+1
-4
@@ -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
|
||||
|
||||
+1
-5
@@ -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
|
||||
|
||||
+16
-22
@@ -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
|
||||
)
|
||||
|
||||
+7
-11
@@ -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
|
||||
|
||||
+1
-2
@@ -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,
|
||||
|
||||
+2
-5
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
+2
-5
@@ -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
|
||||
|
||||
+2
-6
@@ -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
|
||||
|
||||
+1
-1
@@ -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)
|
||||
|
||||
+1
-4
@@ -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(
|
||||
|
||||
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
+48
-57
@@ -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
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-10
@@ -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
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+16
-31
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
+4
-5
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+7
-6
@@ -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
|
||||
|
||||
+42
-77
@@ -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
|
||||
}
|
||||
|
||||
+4
-4
@@ -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!"
|
||||
)
|
||||
|
||||
+1
-2
@@ -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,
|
||||
|
||||
+10
-12
@@ -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
|
||||
|
||||
+71
-104
@@ -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"
|
||||
)
|
||||
|
||||
+1
-2
@@ -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))
|
||||
)
|
||||
}
|
||||
|
||||
+1
-2
@@ -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(
|
||||
|
||||
+36
-39
@@ -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(
|
||||
|
||||
+23
-44
@@ -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
|
||||
}
|
||||
|
||||
+1
-2
@@ -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,
|
||||
|
||||
+33
-38
@@ -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 =>
|
||||
|
||||
+10
-25
@@ -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,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user