Compare commits
127
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
10c4814f34 | ||
|
|
fe221a7bd9 | ||
|
|
191abf83c0 | ||
|
|
edfeae5f0f | ||
|
|
424184a51a | ||
|
|
03a321f95d | ||
|
|
e3615fa6bb | ||
|
|
32991f736d | ||
|
|
8b2748d3d4 | ||
|
|
883080e275 | ||
|
|
ce807e2564 | ||
|
|
9a2ac82373 | ||
|
|
3c35539c16 | ||
|
|
5ab08403c6 | ||
|
|
c1ce478d22 | ||
|
|
d8bf8ba922 | ||
|
|
8cdc9c9b84 | ||
|
|
df189f4408 | ||
|
|
47fa7885c5 | ||
|
|
004dbb39b4 | ||
|
|
cd94c15137 | ||
|
|
eeb965353e | ||
|
|
6dd09bd4b4 | ||
|
|
a73189a604 | ||
|
|
4341341a07 | ||
|
|
4b82f0b35c | ||
|
|
b417e117ad | ||
|
|
85e435e99d | ||
|
|
e48c13a92f | ||
|
|
4495f0c06e | ||
|
|
312711b7ed | ||
|
|
3e8c18b8d3 | ||
|
|
fb0f768f2c | ||
|
|
5fc230d89b | ||
|
|
5fd1a6c752 | ||
|
|
76a5ea273a | ||
|
|
3d0a5a4be8 | ||
|
|
23309113ec | ||
|
|
1a1bc541f5 | ||
|
|
20060a89fd | ||
|
|
24f788d1a0 | ||
|
|
813957479d | ||
|
|
cdf58c54e0 | ||
|
|
6399134380 | ||
|
|
eb49e6f8ff | ||
|
|
ef855eb2cc | ||
|
|
c970e6586d | ||
|
|
6eaa529048 | ||
|
|
fe39241a90 | ||
|
|
d936d93be8 | ||
|
|
89127c0258 | ||
|
|
57aa07453e | ||
|
|
0722f6ab5e | ||
|
|
b9c51da782 | ||
|
|
c290404e42 | ||
|
|
cc0f965cb4 | ||
|
|
64736d194e | ||
|
|
963b04e8b0 | ||
|
|
e58ffab2a2 | ||
|
|
de29e2e157 | ||
|
|
7aa1b1889c | ||
|
|
618cfe5720 | ||
|
|
a8cecf8ec2 | ||
|
|
d858c64a3c | ||
|
|
f49b1d26a5 | ||
|
|
92e5f2472d | ||
|
|
11144f1f88 | ||
|
|
34c9a9b53e | ||
|
|
84d9cf9eb4 | ||
|
|
8a4cc5df21 | ||
|
|
df0b8ccebe | ||
|
|
ac47bc58bd | ||
|
|
570ef6f005 | ||
|
|
7eecde62fa | ||
|
|
4e0e5c9cd7 | ||
|
|
18abcde0d5 | ||
|
|
6176b64c28 | ||
|
|
3bae1157b6 | ||
|
|
5a51ad5699 | ||
|
|
312d20269c | ||
|
|
178d6f042b | ||
|
|
3352b64d0f | ||
|
|
e7d86a16d5 | ||
|
|
820c25d8dc | ||
|
|
f2dcb4d4d1 | ||
|
|
de357cfe95 | ||
|
|
0f333f8c96 | ||
|
|
93e8adadac | ||
|
|
8f98626075 | ||
|
|
a321eb1362 | ||
|
|
1a17fad0a5 | ||
|
|
c74efbb372 | ||
|
|
66f79ca5d2 | ||
|
|
f42f844f17 | ||
|
|
aee98e15d7 | ||
|
|
0936dabc9e | ||
|
|
39b209caf0 | ||
|
|
07867b3aaf | ||
|
|
de1f74cb44 | ||
|
|
65c97107c6 | ||
|
|
d796eda13c | ||
|
|
2a9029470f | ||
|
|
254364bab8 | ||
|
|
0319410ade | ||
|
|
6b64f6f8ed | ||
|
|
62fcb2e987 | ||
|
|
ff3ef4e4f3 | ||
|
|
008b0e416c | ||
|
|
bf96849027 | ||
|
|
1b035e4a42 | ||
|
|
47dec60c2b | ||
|
|
c03a28be93 | ||
|
|
d1ab2b0450 | ||
|
|
95f66e4c39 | ||
|
|
fe9ae97821 | ||
|
|
98e0a676cb | ||
|
|
2bb1387bc4 | ||
|
|
af382c541e | ||
|
|
8616a094e5 | ||
|
|
4de7ebec17 | ||
|
|
d43dff35fb | ||
|
|
5b13f8bd30 | ||
|
|
e51bc6f711 | ||
|
|
1b08aa0c58 | ||
|
|
f2547fe207 | ||
|
|
cec7726731 | ||
|
|
d679a6fed8 |
@@ -243,11 +243,14 @@ $templates = new \League\Plates\Engine(__DIR__ . '/templates');
|
||||
"SELECT nation,no,name,owner_name as ownerName, owner, picture, imgsvr,
|
||||
experience, dedication,
|
||||
dex1, dex2, dex3, dex4, dex5,
|
||||
horse, weapon, book, item
|
||||
horse, weapon, book, item, aux
|
||||
FROM general WHERE %l",
|
||||
$btn == "NPC 보기" ? "npc>=2" : "npc<2"
|
||||
) as $general) {
|
||||
$generalID = $general['no'];
|
||||
foreach (['dex1', 'dex2', 'dex3', 'dex4', 'dex5'] as $dexKey) {
|
||||
$general[$dexKey] = CentennialAllStarGrowthService::recordableRawValue($general, $dexKey);
|
||||
}
|
||||
$general['bgColor'] = $nationColor[$general['nation']] ?? GameConst::$basecolor4;
|
||||
$general['fgColor'] = newColor($general['bgColor']);
|
||||
$general['nationName'] = $nationName[$general['nation']];
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace sammo;
|
||||
|
||||
use Ds\Map;
|
||||
use sammo\Enums\RankColumn;
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
chdir(dirname(__DIR__));
|
||||
require_once 'lib.php';
|
||||
require_once 'func.php';
|
||||
|
||||
final class ComparisonTracingRNG implements RNG
|
||||
{
|
||||
private int $sequence = 0;
|
||||
|
||||
/** @var array<int, array<string, mixed>> */
|
||||
public array $calls = [];
|
||||
|
||||
public function __construct(private readonly RNG $inner)
|
||||
{
|
||||
}
|
||||
|
||||
public static function getMaxInt(): int
|
||||
{
|
||||
return LiteHashDRBG::getMaxInt();
|
||||
}
|
||||
|
||||
public function nextBytes(int $bytes): string
|
||||
{
|
||||
$value = $this->inner->nextBytes($bytes);
|
||||
$this->record('nextBytes', ['bytes' => $bytes], bin2hex($value));
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function nextBits(int $bits): string
|
||||
{
|
||||
$value = $this->inner->nextBits($bits);
|
||||
$this->record('nextBits', ['bits' => $bits], bin2hex($value));
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function nextInt(?int $max = null): int
|
||||
{
|
||||
$value = $this->inner->nextInt($max);
|
||||
$this->record('nextInt', ['maxInclusive' => $max], $value);
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function nextFloat1(): float
|
||||
{
|
||||
$value = $this->inner->nextFloat1();
|
||||
$this->record('nextFloat1', [], $value);
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function record(string $operation, array $arguments, mixed $result): void
|
||||
{
|
||||
$this->calls[] = [
|
||||
'seq' => $this->sequence++,
|
||||
'operation' => $operation,
|
||||
'arguments' => $arguments,
|
||||
'result' => $result,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
function comparisonExtractRankVar(array $raw): Map
|
||||
{
|
||||
$rankVars = new Map();
|
||||
foreach ($raw as $rawKey => $rawValue) {
|
||||
$key = RankColumn::tryFrom($rawKey);
|
||||
if ($key !== null) {
|
||||
$rankVars[$key] = $rawValue;
|
||||
}
|
||||
}
|
||||
return $rankVars;
|
||||
}
|
||||
|
||||
function comparisonBuildGeneral(
|
||||
array $raw,
|
||||
array $city,
|
||||
array $nation,
|
||||
int $year,
|
||||
int $month,
|
||||
bool $defender = false,
|
||||
): General {
|
||||
$aux = [];
|
||||
if (array_key_exists('inheritBuff', $raw)) {
|
||||
$aux['inheritBuff'] = $raw['inheritBuff'];
|
||||
}
|
||||
$raw['aux'] = Json::encode($aux);
|
||||
$raw['owner'] = 0;
|
||||
return new General(
|
||||
$raw,
|
||||
comparisonExtractRankVar($raw),
|
||||
null,
|
||||
$city,
|
||||
$nation,
|
||||
$year,
|
||||
$month,
|
||||
$defender,
|
||||
);
|
||||
}
|
||||
|
||||
function comparisonRunBattle(array $fixture): array
|
||||
{
|
||||
$seed = (string)($fixture['seed'] ?? 'battle-differential');
|
||||
$year = (int)$fixture['year'];
|
||||
$month = (int)$fixture['month'];
|
||||
$startYear = (int)($fixture['startYear'] ?? 180);
|
||||
$rawAttacker = $fixture['attackerGeneral'];
|
||||
$rawAttackerCity = $fixture['attackerCity'];
|
||||
$rawAttackerNation = $fixture['attackerNation'];
|
||||
$rawDefenderCity = $fixture['defenderCity'];
|
||||
$rawDefenderNation = $fixture['defenderNation'];
|
||||
// 비교 fixture에 명시된 경우에만 ref runtime의 scenario action chain을
|
||||
// 활성화합니다. 일반 비교 fixture의 기존 동작은 그대로 유지합니다.
|
||||
$scenarioEffect = $fixture['scenarioEffect'] ?? null;
|
||||
if ($scenarioEffect === '' || $scenarioEffect === 'None') {
|
||||
$scenarioEffect = null;
|
||||
}
|
||||
if (
|
||||
$scenarioEffect !== null
|
||||
&& (!is_string($scenarioEffect) || getScenarioEffectClass($scenarioEffect) === null)
|
||||
) {
|
||||
throw new \InvalidArgumentException('scenarioEffect is invalid');
|
||||
}
|
||||
GameConst::$scenarioEffect = $scenarioEffect;
|
||||
|
||||
$tracingRng = new ComparisonTracingRNG(new LiteHashDRBG($seed));
|
||||
$warRng = new RandUtil($tracingRng);
|
||||
$attacker = new WarUnitGeneral(
|
||||
$warRng,
|
||||
comparisonBuildGeneral($rawAttacker, $rawAttackerCity, $rawAttackerNation, $year, $month),
|
||||
$rawAttackerNation,
|
||||
true,
|
||||
);
|
||||
$city = new WarUnitCity($warRng, $rawDefenderCity, $rawDefenderNation, $year, $month, $startYear);
|
||||
|
||||
$defenderList = [];
|
||||
foreach ($fixture['defenderGenerals'] as $rawDefender) {
|
||||
$defenderList[] = new WarUnitGeneral(
|
||||
$warRng,
|
||||
comparisonBuildGeneral($rawDefender, $rawDefenderCity, $rawDefenderNation, $year, $month, true),
|
||||
$rawDefenderNation,
|
||||
false,
|
||||
);
|
||||
}
|
||||
if (count($defenderList) && extractBattleOrder($city, $attacker) > 0) {
|
||||
$defenderList[] = $city;
|
||||
}
|
||||
usort(
|
||||
$defenderList,
|
||||
fn(WarUnit $lhs, WarUnit $rhs): int =>
|
||||
-(extractBattleOrder($lhs, $attacker) <=> extractBattleOrder($rhs, $attacker)),
|
||||
);
|
||||
|
||||
$iterDefender = new \ArrayIterator($defenderList);
|
||||
$iterDefender->rewind();
|
||||
$finishedDefenders = [];
|
||||
$getNextDefender = function (?WarUnit $previous, bool $requestNext) use (
|
||||
$iterDefender,
|
||||
$attacker,
|
||||
&$finishedDefenders,
|
||||
): ?WarUnit {
|
||||
if ($previous !== null) {
|
||||
$finishedDefenders[] = buildWarTraceUnitSnapshot($previous);
|
||||
}
|
||||
if (!$requestNext || !$iterDefender->valid()) {
|
||||
return null;
|
||||
}
|
||||
$next = $iterDefender->current();
|
||||
if (extractBattleOrder($next, $attacker) <= 0) {
|
||||
return null;
|
||||
}
|
||||
$iterDefender->next();
|
||||
return $next;
|
||||
};
|
||||
|
||||
$events = [];
|
||||
$conquered = processWar_NG(
|
||||
$seed,
|
||||
$attacker,
|
||||
$getNextDefender,
|
||||
$city,
|
||||
static function (array $event) use (&$events): void {
|
||||
$events[] = $event;
|
||||
},
|
||||
);
|
||||
|
||||
$attackerLogs = $attacker->getLogger()->rollback();
|
||||
$defenderLogs = [];
|
||||
foreach ($defenderList as $defenderUnit) {
|
||||
if (!($defenderUnit instanceof WarUnitGeneral)) {
|
||||
continue;
|
||||
}
|
||||
$snapshot = buildWarTraceUnitSnapshot($defenderUnit);
|
||||
$defenderLogs[(string)$snapshot['id']] = $defenderUnit->getLogger()->rollback();
|
||||
}
|
||||
$cityLogs = $city->getLogger()->rollback();
|
||||
|
||||
return [
|
||||
'engine' => 'ref',
|
||||
'seed' => $seed,
|
||||
'conquered' => $conquered,
|
||||
'attacker' => buildWarTraceUnitSnapshot($attacker),
|
||||
'city' => buildWarTraceUnitSnapshot($city),
|
||||
'finishedDefenders' => $finishedDefenders,
|
||||
'events' => $events,
|
||||
'rng' => $tracingRng->calls,
|
||||
'logs' => [
|
||||
'attacker' => $attackerLogs,
|
||||
'defenders' => $defenderLogs,
|
||||
'city' => $cityLogs,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
$fixturePath = $argv[1] ?? null;
|
||||
if ($fixturePath === null || ($fixturePath !== '-' && !is_file($fixturePath))) {
|
||||
fwrite(STDERR, "usage: php compare/battle_trace.php <fixture.json|->\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
try {
|
||||
$fixtureJson = $fixturePath === '-' ? stream_get_contents(STDIN) : file_get_contents($fixturePath);
|
||||
$fixture = json_decode((string)$fixtureJson, true, flags: JSON_THROW_ON_ERROR);
|
||||
echo json_encode(
|
||||
comparisonRunBattle($fixture),
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
|
||||
), PHP_EOL;
|
||||
} catch (\Throwable $throwable) {
|
||||
fwrite(STDERR, $throwable::class . ': ' . $throwable->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"action": "AddGlobalBetray",
|
||||
"args": [2, 1],
|
||||
"setup": {
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2, 3],
|
||||
"general": [
|
||||
{ "id": 1, "values": { "name": "배신0", "betray": 0 } },
|
||||
{ "id": 2, "values": { "name": "배신1", "betray": 1 } },
|
||||
{ "id": 3, "values": { "name": "배신2", "betray": 2 } }
|
||||
]
|
||||
},
|
||||
"environment": {
|
||||
"year": 194,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2, 3]
|
||||
},
|
||||
"compactOutput": true
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
{
|
||||
"action": "AssignGeneralSpeciality",
|
||||
"setup": {
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2, 3],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "내정대상",
|
||||
"nation": 1,
|
||||
"age": 30,
|
||||
"leadership": 40,
|
||||
"strength": 45,
|
||||
"intel": 80,
|
||||
"special": "None",
|
||||
"specage": 30,
|
||||
"special2": "che_신산",
|
||||
"specage2": 99,
|
||||
"aux": {
|
||||
"prev_types_special": ["che_경작"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "전투대상",
|
||||
"nation": 1,
|
||||
"age": 30,
|
||||
"leadership": 80,
|
||||
"strength": 75,
|
||||
"intel": 40,
|
||||
"special": "che_인덕",
|
||||
"specage": 99,
|
||||
"special2": "None",
|
||||
"specage2": 30,
|
||||
"dex1": 200,
|
||||
"dex2": 10,
|
||||
"dex3": 10,
|
||||
"dex4": 10,
|
||||
"dex5": 10,
|
||||
"aux": {
|
||||
"prev_types_special2": ["che_돌격"]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"name": "계승대상",
|
||||
"nation": 2,
|
||||
"age": 30,
|
||||
"leadership": 50,
|
||||
"strength": 50,
|
||||
"intel": 50,
|
||||
"special": "che_경작",
|
||||
"specage": 99,
|
||||
"special2": "None",
|
||||
"specage2": 30,
|
||||
"aux": {
|
||||
"inheritSpecificSpecialWar": "che_의술",
|
||||
"marker": 3
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2, 3]
|
||||
},
|
||||
"compactOutput": true
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
{
|
||||
"action": "AutoDeleteInvader",
|
||||
"compactOutput": true,
|
||||
"args": [1],
|
||||
"setup": {
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1],
|
||||
"resetDiplomacy": true,
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "ⓞ남만족",
|
||||
"capital": 69,
|
||||
"gennum": 1,
|
||||
"tech": 100,
|
||||
"level": 2,
|
||||
"type": "che_병가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "ⓞ남만대왕",
|
||||
"nation": 1,
|
||||
"city": 69,
|
||||
"officer_level": 12,
|
||||
"npc": 9
|
||||
}
|
||||
}
|
||||
],
|
||||
"event": [
|
||||
{
|
||||
"id": 990001,
|
||||
"action": [["AutoDeleteInvader", 1]]
|
||||
}
|
||||
]
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"currentEventID": 990001
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"action": "BlockScoutAction",
|
||||
"args": [true],
|
||||
"setup": {
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2],
|
||||
"nation": [
|
||||
{ "id": 1, "values": { "name": "위", "level": 2, "scout": 0 } },
|
||||
{ "id": 2, "values": { "name": "촉", "level": 2, "scout": 0 } }
|
||||
],
|
||||
"gameEnvironment": {
|
||||
"block_change_scout": false
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {
|
||||
"nationIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
{
|
||||
"action": "MonthlyBoundary",
|
||||
"compactOutput": true,
|
||||
"environment": {
|
||||
"year": 190,
|
||||
"month": 12,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"starttime": "2026-07-25 00:00:00",
|
||||
"turntime": "2026-07-25 02:00:00"
|
||||
},
|
||||
"setup": {
|
||||
"syncEnvironment": true,
|
||||
"world": {
|
||||
"hiddenSeed": "monthly-boundary-core-catalog"
|
||||
},
|
||||
"gameEnvironment": {
|
||||
"isunited": 1,
|
||||
"refreshLimit": 3,
|
||||
"block_change_scout": false
|
||||
},
|
||||
"resetCities": true,
|
||||
"deleteOtherCities": true,
|
||||
"keepCityIds": [1, 2],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "경계도시",
|
||||
"level": 1,
|
||||
"nation": 1,
|
||||
"pop": 10000,
|
||||
"pop_max": 20000,
|
||||
"agri": 1000,
|
||||
"agri_max": 2000,
|
||||
"comm": 1000,
|
||||
"comm_max": 2000,
|
||||
"secu": 1000,
|
||||
"secu_max": 2000,
|
||||
"trust": 50,
|
||||
"trade": 100,
|
||||
"def": 1000,
|
||||
"def_max": 2000,
|
||||
"wall": 1000,
|
||||
"wall_max": 2000,
|
||||
"officer_set": 1,
|
||||
"state": 31,
|
||||
"term": 1,
|
||||
"supply": 1,
|
||||
"front": 2,
|
||||
"conflict": {},
|
||||
"dead": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "중립도시",
|
||||
"level": 8,
|
||||
"nation": 0,
|
||||
"pop": 12000,
|
||||
"pop_max": 22000,
|
||||
"agri": 1200,
|
||||
"agri_max": 2200,
|
||||
"comm": 1200,
|
||||
"comm_max": 2200,
|
||||
"secu": 1200,
|
||||
"secu_max": 2200,
|
||||
"trust": 55,
|
||||
"trade": 100,
|
||||
"def": 1200,
|
||||
"def_max": 2200,
|
||||
"wall": 1200,
|
||||
"wall_max": 2200,
|
||||
"officer_set": 1,
|
||||
"state": 0,
|
||||
"term": 0,
|
||||
"supply": 0,
|
||||
"front": 0,
|
||||
"conflict": {},
|
||||
"dead": 0
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "경계군주",
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"officer_level": 12,
|
||||
"npc": 0,
|
||||
"age": 30,
|
||||
"belong": 3,
|
||||
"makelimit": 2,
|
||||
"gold": 1000,
|
||||
"rice": 1000,
|
||||
"crew": 100,
|
||||
"train": 80,
|
||||
"atmos": 70,
|
||||
"leadership": 50,
|
||||
"strength": 50,
|
||||
"intel": 50,
|
||||
"experience": 0,
|
||||
"dedication": 0,
|
||||
"dex1": 0,
|
||||
"dex2": 0,
|
||||
"dex3": 0,
|
||||
"dex4": 0,
|
||||
"dex5": 0,
|
||||
"personal": "None",
|
||||
"special": "None",
|
||||
"specage": 0,
|
||||
"special2": "None",
|
||||
"specage2": 0,
|
||||
"betray": 0,
|
||||
"bornyear": 160,
|
||||
"deadyear": 250
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "경계재야",
|
||||
"nation": 0,
|
||||
"city": 2,
|
||||
"officer_level": 0,
|
||||
"npc": 0,
|
||||
"age": 25,
|
||||
"belong": 4,
|
||||
"makelimit": 0,
|
||||
"gold": 500,
|
||||
"rice": 500,
|
||||
"crew": 50,
|
||||
"train": 60,
|
||||
"atmos": 50,
|
||||
"leadership": 40,
|
||||
"strength": 40,
|
||||
"intel": 40,
|
||||
"experience": 0,
|
||||
"dedication": 0,
|
||||
"dex1": 0,
|
||||
"dex2": 0,
|
||||
"dex3": 0,
|
||||
"dex4": 0,
|
||||
"dex5": 0,
|
||||
"personal": "None",
|
||||
"special": "None",
|
||||
"specage": 0,
|
||||
"special2": "None",
|
||||
"specage2": 0,
|
||||
"betray": 0,
|
||||
"bornyear": 165,
|
||||
"deadyear": 250
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "경계국",
|
||||
"color": "#123456",
|
||||
"capital": 1,
|
||||
"gennum": 1,
|
||||
"gold": 10000,
|
||||
"rice": 20000,
|
||||
"tech": 100,
|
||||
"power": 10,
|
||||
"level": 2,
|
||||
"type": "che_유가",
|
||||
"bill": 100,
|
||||
"rate": 20,
|
||||
"rate_tmp": 10,
|
||||
"scout": 1,
|
||||
"chief_set": 1,
|
||||
"strategic_cmd_limit": 2,
|
||||
"surlimit": 1,
|
||||
"spy": "{}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetDiplomacy": true,
|
||||
"resetEvents": true,
|
||||
"event": [
|
||||
{
|
||||
"id": 991001,
|
||||
"target": "PRE_MONTH",
|
||||
"priority": 1000,
|
||||
"condition": true,
|
||||
"action": [
|
||||
["NoticeToHistoryLog", "aggregate-pre", 6]
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 991002,
|
||||
"target": "MONTH",
|
||||
"priority": 1000,
|
||||
"condition": true,
|
||||
"action": [
|
||||
["ProcessIncome", "gold"],
|
||||
["NewYear"],
|
||||
["ResetOfficerLock"],
|
||||
["RandomizeCityTradeRate"],
|
||||
["ChangeCity", "all", {"pop": "+10", "trust": 60}],
|
||||
["NoticeToHistoryLog", "aggregate-month", 6],
|
||||
["DeleteEvent"]
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2],
|
||||
"nationIds": [1],
|
||||
"cityIds": [1, 2],
|
||||
"eventIds": [991001, 991002],
|
||||
"accessGeneralIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"action": "NewYear",
|
||||
"environment": {
|
||||
"year": 191,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"age": 30,
|
||||
"belong": 3
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 0,
|
||||
"age": 30,
|
||||
"belong": 4
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"action": "NoticeToHistoryLog",
|
||||
"args": ["<S>새해 알림</>", 6],
|
||||
"environment": {
|
||||
"year": 191,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {},
|
||||
"observe": {}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"action": "ProcessIncome",
|
||||
"args": ["gold"],
|
||||
"environment": {
|
||||
"year": 190,
|
||||
"month": 7,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"officer_level": 5,
|
||||
"npc": 0,
|
||||
"gold": 1000,
|
||||
"rice": 1000,
|
||||
"dedication": 100
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑국",
|
||||
"capital": 1,
|
||||
"gold": 10000,
|
||||
"rice": 20000,
|
||||
"level": 1,
|
||||
"rate_tmp": 20
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑성",
|
||||
"nation": 1,
|
||||
"level": 4,
|
||||
"supply": 1,
|
||||
"pop": 10000,
|
||||
"pop_max": 20000,
|
||||
"agri": 1000,
|
||||
"agri_max": 2000,
|
||||
"comm": 1000,
|
||||
"comm_max": 2000,
|
||||
"secu": 1000,
|
||||
"secu_max": 2000,
|
||||
"trust": 80,
|
||||
"def": 500,
|
||||
"def_max": 1000,
|
||||
"wall": 500,
|
||||
"wall_max": 1000
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1],
|
||||
"nationIds": [1],
|
||||
"cityIds": [1],
|
||||
"nationEnvironmentKeys": ["prev_income_gold", "prev_income_rice"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"action": "ResetOfficerLock",
|
||||
"environment": {
|
||||
"year": 191,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetNations": true,
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"officer_set": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"chief_set": 1
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"cityIds": [1],
|
||||
"nationIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"action": "CreateAdminNPC",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 12,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"action": "CreateManyNPC",
|
||||
"args": [2, 0],
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 5,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"turntime": "0193-05-01 00:00:00"
|
||||
},
|
||||
"setup": {
|
||||
"resetGenerals": true
|
||||
},
|
||||
"observe": {}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"action": "FinishNationBetting",
|
||||
"args": [1],
|
||||
"setup": {
|
||||
"clearBetting": true,
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2],
|
||||
"nation": [
|
||||
{ "id": 1, "values": { "name": "위", "gennum": 1, "power": 100, "level": 2 } },
|
||||
{ "id": 2, "values": { "name": "촉", "gennum": 1, "power": 300, "level": 0 } }
|
||||
],
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"general": [
|
||||
{ "id": 1, "values": { "name": "장수1", "nation": 1, "owner": 1, "npc": 0 } },
|
||||
{ "id": 2, "values": { "name": "장수2", "nation": 2, "owner": 2, "npc": 0 } }
|
||||
],
|
||||
"bettingInfo": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "bettingNation",
|
||||
"name": "천통국 예상",
|
||||
"finished": false,
|
||||
"selectCnt": 1,
|
||||
"isExclusive": null,
|
||||
"reqInheritancePoint": true,
|
||||
"openYearMonth": 2400,
|
||||
"closeYearMonth": 2424,
|
||||
"candidates": [
|
||||
{
|
||||
"title": "위",
|
||||
"info": "국력: 100<br>장수 수: 1<br>도시 수: 1",
|
||||
"isHtml": true,
|
||||
"aux": { "nation": 1 }
|
||||
},
|
||||
{
|
||||
"title": "촉",
|
||||
"info": "국력: 300<br>장수 수: 1<br>도시 수: 1",
|
||||
"isHtml": true,
|
||||
"aux": { "nation": 2 }
|
||||
}
|
||||
],
|
||||
"winner": null
|
||||
}
|
||||
],
|
||||
"bet": [
|
||||
{ "betting_id": 1, "general_id": 0, "user_id": null, "betting_type": "[-1]", "amount": 100 },
|
||||
{ "betting_id": 1, "general_id": 1, "user_id": 1, "betting_type": "[0]", "amount": 100 },
|
||||
{ "betting_id": 1, "general_id": 2, "user_id": 2, "betting_type": "[1]", "amount": 100 }
|
||||
],
|
||||
"inheritancePrevious": {
|
||||
"1": 900,
|
||||
"2": 900
|
||||
},
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 202,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2],
|
||||
"nationIds": [1, 2],
|
||||
"ownerIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"action": "InvaderEnding",
|
||||
"compactOutput": true,
|
||||
"setup": {
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1],
|
||||
"setAllCitiesNation": 1,
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "기준국",
|
||||
"capital": 1,
|
||||
"gennum": 1,
|
||||
"tech": 100,
|
||||
"level": 2,
|
||||
"type": "che_유가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"gameEnvironment": {
|
||||
"isunited": 1,
|
||||
"refreshLimit": 3
|
||||
},
|
||||
"event": [
|
||||
{
|
||||
"id": 990002,
|
||||
"action": [["InvaderEnding"]]
|
||||
}
|
||||
]
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"currentEventID": 990002
|
||||
},
|
||||
"observe": {}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"action": "InvaderLifecycle",
|
||||
"args": [10, 150, 100, 20],
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1],
|
||||
"resetDiplomacy": true,
|
||||
"resetEvents": true,
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "기준도시",
|
||||
"level": 3,
|
||||
"nation": 1,
|
||||
"pop": 1000,
|
||||
"pop_max": 10000,
|
||||
"agri": 2000,
|
||||
"agri_max": 20000,
|
||||
"comm": 3000,
|
||||
"comm_max": 30000,
|
||||
"secu": 4000,
|
||||
"secu_max": 40000,
|
||||
"def": 5000,
|
||||
"def_max": 50000,
|
||||
"wall": 6000,
|
||||
"wall_max": 60000
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 48,
|
||||
"values": {
|
||||
"name": "남만",
|
||||
"level": 4,
|
||||
"nation": 0,
|
||||
"pop": 1000,
|
||||
"pop_max": 10000,
|
||||
"agri": 2000,
|
||||
"agri_max": 20000,
|
||||
"comm": 3000,
|
||||
"comm_max": 30000,
|
||||
"secu": 4000,
|
||||
"secu_max": 40000,
|
||||
"def": 5000,
|
||||
"def_max": 50000,
|
||||
"wall": 6000,
|
||||
"wall_max": 60000
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "기준국",
|
||||
"capital": 1,
|
||||
"gennum": 1,
|
||||
"tech": 100,
|
||||
"level": 2,
|
||||
"type": "che_유가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "군주",
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"officer_level": 12,
|
||||
"npc": 0,
|
||||
"leadership": 50,
|
||||
"strength": 50,
|
||||
"intel": 50,
|
||||
"experience": 1000,
|
||||
"dedication": 1000,
|
||||
"dex1": 10,
|
||||
"dex2": 20,
|
||||
"dex3": 30,
|
||||
"dex4": 40,
|
||||
"dex5": 50,
|
||||
"turntime": "0200-01-01 00:05:00"
|
||||
}
|
||||
}
|
||||
],
|
||||
"gameEnvironment": {
|
||||
"isunited": 0,
|
||||
"refreshLimit": 3
|
||||
},
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"turntime": "0200-01-01 00:00:00",
|
||||
"show_img_level": 3,
|
||||
"fiction": [0]
|
||||
},
|
||||
"observe": {}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"action": "LostUniqueItem",
|
||||
"args": [0.2],
|
||||
"environment": {
|
||||
"year": 210,
|
||||
"month": 1,
|
||||
"startyear": 180
|
||||
},
|
||||
"setup": {
|
||||
"syncEnvironment": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑",
|
||||
"npc": 0,
|
||||
"horse": "che_명마_12_옥란백용구",
|
||||
"weapon": "che_무기_15_의천검",
|
||||
"book": "che_서적_01_효경전",
|
||||
"item": "che_저지_삼황내문"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을",
|
||||
"npc": 1,
|
||||
"horse": "che_명마_12_사륜거",
|
||||
"weapon": "che_무기_01_단도",
|
||||
"book": "None",
|
||||
"item": "che_부적_태현청생부"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"action": "MergeInheritPointRank",
|
||||
"environment": {
|
||||
"year": 210,
|
||||
"month": 1,
|
||||
"startyear": 180
|
||||
},
|
||||
"setup": {
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1],
|
||||
"clearInheritanceOwnerIds": [100],
|
||||
"gameEnvironment": {
|
||||
"isunited": 0
|
||||
},
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑",
|
||||
"nation": 1,
|
||||
"owner": 100,
|
||||
"npc": 0,
|
||||
"belong": 3,
|
||||
"dex1": 1000,
|
||||
"dex2": 0,
|
||||
"dex3": 0,
|
||||
"dex4": 0,
|
||||
"dex5": 0
|
||||
}
|
||||
}
|
||||
],
|
||||
"inheritancePoints": [
|
||||
{"ownerId": 100, "key": "previous", "value": 999},
|
||||
{"ownerId": 100, "key": "lived_month", "value": 2},
|
||||
{"ownerId": 100, "key": "max_domestic_critical", "value": 4},
|
||||
{"ownerId": 100, "key": "active_action", "value": 15},
|
||||
{"ownerId": 100, "key": "unifier", "value": 6},
|
||||
{"ownerId": 100, "key": "tournament", "value": 7}
|
||||
],
|
||||
"rankData": [
|
||||
{"generalId": 1, "type": "warnum", "value": 2},
|
||||
{"generalId": 1, "type": "firenum", "value": 1},
|
||||
{"generalId": 1, "type": "betwin", "value": 2},
|
||||
{"generalId": 1, "type": "betgold", "value": 4000},
|
||||
{"generalId": 1, "type": "betwingold", "value": 2000},
|
||||
{"generalId": 1, "type": "inherit_earned_dyn", "value": 999},
|
||||
{"generalId": 1, "type": "inherit_earned_act", "value": 11},
|
||||
{"generalId": 1, "type": "inherit_earned", "value": 999},
|
||||
{"generalId": 1, "type": "inherit_spent_dyn", "value": 9},
|
||||
{"generalId": 1, "type": "inherit_spent", "value": 999}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1],
|
||||
"ownerIds": [100],
|
||||
"inheritanceKeys": [
|
||||
"previous",
|
||||
"lived_month",
|
||||
"max_domestic_critical",
|
||||
"active_action",
|
||||
"unifier",
|
||||
"tournament"
|
||||
],
|
||||
"rankGeneralIds": [1],
|
||||
"rankTypes": [
|
||||
"inherit_earned",
|
||||
"inherit_earned_act",
|
||||
"inherit_earned_dyn",
|
||||
"inherit_spent",
|
||||
"inherit_spent_dyn"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"action": "NationBettingLifecycle",
|
||||
"args": [1, 100],
|
||||
"bettorGeneralIds": [1, 2],
|
||||
"bettorOwnerIds": [1, 2],
|
||||
"setup": {
|
||||
"clearBetting": true,
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "위",
|
||||
"color": "#111111",
|
||||
"capital": 1,
|
||||
"gennum": 1,
|
||||
"gold": 1000,
|
||||
"rice": 2000,
|
||||
"tech": 100,
|
||||
"power": 100,
|
||||
"level": 2,
|
||||
"type": "che_유가"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "촉",
|
||||
"color": "#222222",
|
||||
"capital": 2,
|
||||
"gennum": 1,
|
||||
"gold": 3000,
|
||||
"rice": 4000,
|
||||
"tech": 200,
|
||||
"power": 300,
|
||||
"level": 2,
|
||||
"type": "che_병가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetCities": true,
|
||||
"deleteOtherCities": true,
|
||||
"keepCityIds": [1, 2],
|
||||
"city": [
|
||||
{ "id": 1, "values": { "name": "허창", "nation": 1, "level": 3 } },
|
||||
{ "id": 2, "values": { "name": "성도", "nation": 2, "level": 3 } }
|
||||
],
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"general": [
|
||||
{ "id": 1, "values": { "name": "장수1", "nation": 1, "city": 1, "owner": 1, "npc": 0 } },
|
||||
{ "id": 2, "values": { "name": "장수2", "nation": 2, "city": 2, "owner": 2, "npc": 0 } }
|
||||
],
|
||||
"inheritancePrevious": {
|
||||
"1": 1000,
|
||||
"2": 1000
|
||||
},
|
||||
"rankData": [
|
||||
{ "generalId": 1, "type": "inherit_spent_dyn", "value": 0 },
|
||||
{ "generalId": 1, "type": "inherit_earned_act", "value": 0 },
|
||||
{ "generalId": 2, "type": "inherit_spent_dyn", "value": 0 },
|
||||
{ "generalId": 2, "type": "inherit_earned_act", "value": 0 }
|
||||
],
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"action": "NpcNationLifecycle",
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"resetNations": true,
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "점유도시",
|
||||
"level": 5,
|
||||
"nation": 1,
|
||||
"pop": 10001,
|
||||
"pop_max": 50001,
|
||||
"agri": 1001,
|
||||
"agri_max": 5001,
|
||||
"comm": 2001,
|
||||
"comm_max": 6001,
|
||||
"secu": 3001,
|
||||
"secu_max": 7001,
|
||||
"def": 4001,
|
||||
"def_max": 8001,
|
||||
"wall": 5001,
|
||||
"wall_max": 9001
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 48,
|
||||
"values": {
|
||||
"name": "건국도시",
|
||||
"level": 5,
|
||||
"nation": 0,
|
||||
"pop": 10048,
|
||||
"pop_max": 50048,
|
||||
"agri": 1048,
|
||||
"agri_max": 5048,
|
||||
"comm": 2048,
|
||||
"comm_max": 6048,
|
||||
"secu": 3048,
|
||||
"secu_max": 7048,
|
||||
"def": 4048,
|
||||
"def_max": 8048,
|
||||
"wall": 5048,
|
||||
"wall_max": 9048
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "기준국",
|
||||
"capital": 1,
|
||||
"gennum": 0,
|
||||
"tech": 120,
|
||||
"level": 2,
|
||||
"type": "che_유가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"gameEnvironment": {
|
||||
"lastNPCTroopLeaderID": 40
|
||||
},
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"turntime": "0200-01-01 00:00:00",
|
||||
"show_img_level": 3,
|
||||
"fiction": [0]
|
||||
},
|
||||
"observe": {}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"action": "OpenNationBetting",
|
||||
"args": [1, 500],
|
||||
"setup": {
|
||||
"clearBetting": true,
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "위",
|
||||
"color": "#111111",
|
||||
"capital": 1,
|
||||
"gennum": 1,
|
||||
"gold": 1000,
|
||||
"rice": 2000,
|
||||
"tech": 100,
|
||||
"power": 100,
|
||||
"level": 2,
|
||||
"type": "che_유가"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "촉",
|
||||
"color": "#222222",
|
||||
"capital": 2,
|
||||
"gennum": 1,
|
||||
"gold": 3000,
|
||||
"rice": 4000,
|
||||
"tech": 200,
|
||||
"power": 300,
|
||||
"level": 2,
|
||||
"type": "che_병가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetCities": true,
|
||||
"city": [
|
||||
{ "id": 1, "values": { "nation": 1, "level": 3 } },
|
||||
{ "id": 2, "values": { "nation": 2, "level": 3 } }
|
||||
],
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"general": [
|
||||
{ "id": 1, "values": { "name": "장수1", "nation": 1, "city": 1, "owner": 1, "npc": 0 } },
|
||||
{ "id": 2, "values": { "name": "장수2", "nation": 2, "city": 2, "owner": 2, "npc": 0 } }
|
||||
],
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2],
|
||||
"cityIds": [1, 2],
|
||||
"nationIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
{
|
||||
"action": "PostUpdateMonthly",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 2,
|
||||
"startyear": 193,
|
||||
"seedYear": 193,
|
||||
"seedMonth": 1
|
||||
},
|
||||
"setup": {
|
||||
"world": {
|
||||
"hiddenSeed": "monthly-post-diplomacy-fixture"
|
||||
},
|
||||
"syncEnvironment": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2, 3, 4],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2, 3, 4],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑장",
|
||||
"nation": 1,
|
||||
"npc": 2,
|
||||
"crew": 0,
|
||||
"gold": 0,
|
||||
"rice": 0,
|
||||
"leadership": 10,
|
||||
"strength": 10,
|
||||
"intel": 10,
|
||||
"experience": 0,
|
||||
"dedication": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을장",
|
||||
"nation": 2,
|
||||
"npc": 2,
|
||||
"crew": 0,
|
||||
"gold": 0,
|
||||
"rice": 0,
|
||||
"leadership": 10,
|
||||
"strength": 10,
|
||||
"intel": 10,
|
||||
"experience": 0,
|
||||
"dedication": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"name": "병장",
|
||||
"nation": 3,
|
||||
"npc": 2,
|
||||
"crew": 0,
|
||||
"gold": 0,
|
||||
"rice": 0,
|
||||
"leadership": 10,
|
||||
"strength": 10,
|
||||
"intel": 10,
|
||||
"experience": 0,
|
||||
"dedication": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"values": {
|
||||
"name": "정장",
|
||||
"nation": 4,
|
||||
"npc": 2,
|
||||
"crew": 0,
|
||||
"gold": 0,
|
||||
"rice": 0,
|
||||
"leadership": 10,
|
||||
"strength": 10,
|
||||
"intel": 10,
|
||||
"experience": 0,
|
||||
"dedication": 0
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑국",
|
||||
"gennum": 2,
|
||||
"level": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을국",
|
||||
"gennum": 1,
|
||||
"level": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"name": "병국",
|
||||
"gennum": 1,
|
||||
"level": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"values": {
|
||||
"name": "정국",
|
||||
"gennum": 1,
|
||||
"level": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetDiplomacy": true,
|
||||
"diplomacy": [
|
||||
{
|
||||
"fromNationId": 1,
|
||||
"toNationId": 2,
|
||||
"state": 1,
|
||||
"term": 1,
|
||||
"dead": 777
|
||||
},
|
||||
{
|
||||
"fromNationId": 2,
|
||||
"toNationId": 1,
|
||||
"state": 1,
|
||||
"term": 1,
|
||||
"dead": 888
|
||||
},
|
||||
{
|
||||
"fromNationId": 1,
|
||||
"toNationId": 3,
|
||||
"state": 0,
|
||||
"term": 5,
|
||||
"dead": 250
|
||||
},
|
||||
{
|
||||
"fromNationId": 3,
|
||||
"toNationId": 1,
|
||||
"state": 0,
|
||||
"term": 5,
|
||||
"dead": 50
|
||||
},
|
||||
{
|
||||
"fromNationId": 3,
|
||||
"toNationId": 4,
|
||||
"state": 0,
|
||||
"term": 1,
|
||||
"dead": 0
|
||||
},
|
||||
{
|
||||
"fromNationId": 4,
|
||||
"toNationId": 3,
|
||||
"state": 0,
|
||||
"term": 1,
|
||||
"dead": 0
|
||||
},
|
||||
{
|
||||
"fromNationId": 2,
|
||||
"toNationId": 4,
|
||||
"state": 7,
|
||||
"term": 1,
|
||||
"dead": 999
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2, 3, 4],
|
||||
"nationIds": [1, 2, 3, 4]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
{
|
||||
"action": "PostUpdateMonthly",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 2,
|
||||
"startyear": 193,
|
||||
"seedYear": 193,
|
||||
"seedMonth": 1
|
||||
},
|
||||
"setup": {
|
||||
"world": {
|
||||
"hiddenSeed": "monthly-post-nation-stats-fixture"
|
||||
},
|
||||
"syncEnvironment": true,
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2],
|
||||
"resetDiplomacy": true,
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"npc": 0,
|
||||
"gold": 1000,
|
||||
"rice": 2000,
|
||||
"crew": 100,
|
||||
"leadership": 50,
|
||||
"strength": 40,
|
||||
"intel": 30,
|
||||
"experience": 100,
|
||||
"dedication": 200,
|
||||
"dex1": 1000,
|
||||
"dex2": 0,
|
||||
"dex3": 0,
|
||||
"dex4": 0,
|
||||
"dex5": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 2,
|
||||
"npc": 2,
|
||||
"gold": 3000,
|
||||
"rice": 4000,
|
||||
"crew": 200,
|
||||
"leadership": 60,
|
||||
"strength": 50,
|
||||
"intel": 40,
|
||||
"experience": 300,
|
||||
"dedication": 400,
|
||||
"dex1": 2000,
|
||||
"dex2": 1000,
|
||||
"dex3": 0,
|
||||
"dex4": 0,
|
||||
"dex5": 0
|
||||
}
|
||||
}
|
||||
],
|
||||
"rankData": [
|
||||
{"generalId": 1, "type": "killcrew_person", "value": 100},
|
||||
{"generalId": 1, "type": "deathcrew_person", "value": 0},
|
||||
{"generalId": 2, "type": "killcrew_person", "value": 0},
|
||||
{"generalId": 2, "type": "deathcrew_person", "value": 100}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑국",
|
||||
"gold": 10000,
|
||||
"rice": 20000,
|
||||
"tech": 100,
|
||||
"level": 2,
|
||||
"gennum": 9,
|
||||
"power": 7
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을국",
|
||||
"gold": 2000,
|
||||
"rice": 3000,
|
||||
"tech": 50,
|
||||
"level": 1,
|
||||
"gennum": 8,
|
||||
"power": 8
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑성",
|
||||
"nation": 1,
|
||||
"level": 4,
|
||||
"supply": 1,
|
||||
"pop": 1000,
|
||||
"pop_max": 2000,
|
||||
"agri": 100,
|
||||
"agri_max": 200,
|
||||
"comm": 100,
|
||||
"comm_max": 200,
|
||||
"secu": 100,
|
||||
"secu_max": 200,
|
||||
"def": 100,
|
||||
"def_max": 200,
|
||||
"wall": 100,
|
||||
"wall_max": 200
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을성",
|
||||
"nation": 2,
|
||||
"level": 4,
|
||||
"supply": 1,
|
||||
"pop": 2000,
|
||||
"pop_max": 4000,
|
||||
"agri": 200,
|
||||
"agri_max": 400,
|
||||
"comm": 200,
|
||||
"comm_max": 400,
|
||||
"secu": 200,
|
||||
"secu_max": 400,
|
||||
"def": 200,
|
||||
"def_max": 400,
|
||||
"wall": 200,
|
||||
"wall_max": 400
|
||||
}
|
||||
}
|
||||
],
|
||||
"nationEnvironment": [
|
||||
{
|
||||
"nationId": 1,
|
||||
"key": "max_power",
|
||||
"value": {
|
||||
"maxPower": 999,
|
||||
"maxCrew": 50,
|
||||
"maxCities": ["옛도시", "옛도시2"]
|
||||
}
|
||||
},
|
||||
{"nationId": 1, "key": "available_war_setting_cnt", "value": 1}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2],
|
||||
"nationIds": [1, 2],
|
||||
"cityIds": [1, 2],
|
||||
"rankGeneralIds": [1, 2],
|
||||
"rankTypes": ["killcrew_person", "deathcrew_person"],
|
||||
"nationEnvironmentKeys": ["max_power", "available_war_setting_cnt"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
{
|
||||
"action": "PostUpdateMonthly",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 2,
|
||||
"startyear": 193,
|
||||
"seedYear": 193,
|
||||
"seedMonth": 1
|
||||
},
|
||||
"setup": {
|
||||
"world": {
|
||||
"hiddenSeed": "monthly-post-tail-2"
|
||||
},
|
||||
"syncEnvironment": true,
|
||||
"clearNeutralAuctions": true,
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2],
|
||||
"resetDiplomacy": true,
|
||||
"gameEnvironment": {
|
||||
"tournament": 0,
|
||||
"tnmt_trig": true,
|
||||
"tnmt_pattern": [0, 1, 2, 3],
|
||||
"prev_winner": null
|
||||
},
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑장",
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"officer_level": 12,
|
||||
"npc": 0,
|
||||
"gold": 5000,
|
||||
"rice": 7000,
|
||||
"crew": 100,
|
||||
"leadership": 50,
|
||||
"strength": 40,
|
||||
"intel": 30,
|
||||
"experience": 100,
|
||||
"dedication": 200
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을장",
|
||||
"nation": 2,
|
||||
"city": 2,
|
||||
"officer_level": 12,
|
||||
"npc": 0,
|
||||
"gold": 6000,
|
||||
"rice": 8000,
|
||||
"crew": 200,
|
||||
"leadership": 60,
|
||||
"strength": 50,
|
||||
"intel": 40,
|
||||
"experience": 300,
|
||||
"dedication": 400
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑국",
|
||||
"capital": 1,
|
||||
"gold": 10000,
|
||||
"rice": 20000,
|
||||
"tech": 100,
|
||||
"level": 2,
|
||||
"gennum": 1,
|
||||
"power": 7
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을국",
|
||||
"capital": 2,
|
||||
"gold": 2000,
|
||||
"rice": 3000,
|
||||
"tech": 50,
|
||||
"level": 1,
|
||||
"gennum": 1,
|
||||
"power": 8
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑성",
|
||||
"nation": 1,
|
||||
"level": 4,
|
||||
"supply": 1,
|
||||
"front": 3,
|
||||
"pop": 1000,
|
||||
"pop_max": 2000
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "을성",
|
||||
"nation": 2,
|
||||
"level": 4,
|
||||
"supply": 1,
|
||||
"front": 3,
|
||||
"pop": 2000,
|
||||
"pop_max": 4000
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2],
|
||||
"nationIds": [1, 2],
|
||||
"cityIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
{
|
||||
"action": "PostUpdateMonthly",
|
||||
"environment": {
|
||||
"year": 195,
|
||||
"month": 2,
|
||||
"startyear": 193,
|
||||
"seedYear": 195,
|
||||
"seedMonth": 1
|
||||
},
|
||||
"setup": {
|
||||
"world": {
|
||||
"hiddenSeed": "monthly-post-wander-fixture"
|
||||
},
|
||||
"syncEnvironment": true,
|
||||
"resetCities": true,
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "방랑성",
|
||||
"nation": 4,
|
||||
"level": 4,
|
||||
"front": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "존속성",
|
||||
"nation": 1,
|
||||
"level": 4,
|
||||
"front": 1
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2, 3],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "방랑주",
|
||||
"nation": 4,
|
||||
"city": 1,
|
||||
"officer_level": 12,
|
||||
"npc": 2,
|
||||
"gold": 2000,
|
||||
"rice": 3000,
|
||||
"crew": 100,
|
||||
"makelimit": 0,
|
||||
"belong": 7,
|
||||
"leadership": 50,
|
||||
"strength": 40,
|
||||
"intel": 30,
|
||||
"experience": 100,
|
||||
"dedication": 200
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "방랑객",
|
||||
"nation": 4,
|
||||
"city": 1,
|
||||
"officer_level": 1,
|
||||
"npc": 0,
|
||||
"gold": 1500,
|
||||
"rice": 4000,
|
||||
"crew": 200,
|
||||
"makelimit": 0,
|
||||
"belong": 5,
|
||||
"leadership": 60,
|
||||
"strength": 50,
|
||||
"intel": 40,
|
||||
"experience": 300,
|
||||
"dedication": 400
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"name": "존속장",
|
||||
"nation": 1,
|
||||
"city": 2,
|
||||
"officer_level": 12,
|
||||
"npc": 2,
|
||||
"gold": 500,
|
||||
"rice": 500,
|
||||
"crew": 50,
|
||||
"leadership": 50,
|
||||
"strength": 50,
|
||||
"intel": 50,
|
||||
"experience": 0,
|
||||
"dedication": 0
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 4],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "존속국",
|
||||
"gennum": 1,
|
||||
"level": 1
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"values": {
|
||||
"name": "방랑국",
|
||||
"gennum": 2,
|
||||
"level": 0
|
||||
}
|
||||
}
|
||||
],
|
||||
"resetDiplomacy": true,
|
||||
"diplomacy": [
|
||||
{
|
||||
"fromNationId": 1,
|
||||
"toNationId": 4,
|
||||
"state": 2,
|
||||
"term": 0,
|
||||
"dead": 0
|
||||
},
|
||||
{
|
||||
"fromNationId": 4,
|
||||
"toNationId": 1,
|
||||
"state": 2,
|
||||
"term": 0,
|
||||
"dead": 0
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2, 3],
|
||||
"nationIds": [1, 4],
|
||||
"cityIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"action": "PreUpdateMonthly",
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 12,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"syncEnvironment": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1, 2],
|
||||
"general": [
|
||||
{"id": 1, "values": {"makelimit": 2}},
|
||||
{"id": 2, "values": {"makelimit": 0}}
|
||||
],
|
||||
"generalAccessLog": [
|
||||
{"generalId": 1, "refreshScoreTotal": 101},
|
||||
{"generalId": 2, "refreshScoreTotal": 1}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"rate": 35,
|
||||
"rate_tmp": 10,
|
||||
"strategic_cmd_limit": 2,
|
||||
"surlimit": 1,
|
||||
"spy": "{\"1\":1,\"2\":2}"
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{"id": 1, "values": {"state": 31, "term": 1, "conflict": {"1": 10}}},
|
||||
{"id": 2, "values": {"state": 32, "term": 2, "conflict": {"1": 20}}},
|
||||
{"id": 3, "values": {"state": 33, "term": 0, "conflict": {"1": 30}}},
|
||||
{"id": 4, "values": {"state": 34, "term": 3, "conflict": {"1": 40}}},
|
||||
{"id": 5, "values": {"state": 41, "term": 1, "conflict": {"1": 50}}},
|
||||
{"id": 6, "values": {"state": 42, "term": 2, "conflict": {"1": 60}}},
|
||||
{"id": 7, "values": {"state": 43, "term": 3, "conflict": {"1": 70}}}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2],
|
||||
"nationIds": [1],
|
||||
"cityIds": [1, 2, 3, 4, 5, 6, 7],
|
||||
"accessGeneralIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
{
|
||||
"action": "ProcessIncome",
|
||||
"args": ["gold"],
|
||||
"environment": {
|
||||
"year": 190,
|
||||
"month": 7,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"officer_level": 5,
|
||||
"npc": 0,
|
||||
"gold": 1000,
|
||||
"rice": 1000,
|
||||
"dedication": 100
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑국",
|
||||
"capital": 1,
|
||||
"gold": 10000,
|
||||
"rice": 20000,
|
||||
"level": 1,
|
||||
"rate": 35,
|
||||
"rate_tmp": 10
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "갑성",
|
||||
"nation": 1,
|
||||
"level": 4,
|
||||
"supply": 1,
|
||||
"pop": 10000,
|
||||
"pop_max": 20000,
|
||||
"agri": 1000,
|
||||
"agri_max": 2000,
|
||||
"comm": 1000,
|
||||
"comm_max": 2000,
|
||||
"secu": 1000,
|
||||
"secu_max": 2000,
|
||||
"trust": 80,
|
||||
"def": 500,
|
||||
"def_max": 1000,
|
||||
"wall": 500,
|
||||
"wall_max": 1000
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1],
|
||||
"nationIds": [1],
|
||||
"cityIds": [1],
|
||||
"nationEnvironmentKeys": ["prev_income_gold", "prev_income_rice"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
{
|
||||
"action": "ProcessSemiAnnual",
|
||||
"resource": "gold",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "반기검증국",
|
||||
"gold": 100001,
|
||||
"rice": 7777,
|
||||
"rate_tmp": 20,
|
||||
"type": "che_도가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"supply": 1,
|
||||
"pop": 10000,
|
||||
"pop_max": 50000,
|
||||
"agri": 1001,
|
||||
"agri_max": 5000,
|
||||
"comm": 1001,
|
||||
"comm_max": 5000,
|
||||
"secu": 1001,
|
||||
"secu_max": 2000,
|
||||
"trust": 55,
|
||||
"def": 1001,
|
||||
"def_max": 5000,
|
||||
"wall": 1001,
|
||||
"wall_max": 5000,
|
||||
"dead": 123
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"supply": 0,
|
||||
"pop": 10000,
|
||||
"pop_max": 50000,
|
||||
"agri": 1001,
|
||||
"agri_max": 5000,
|
||||
"comm": 1001,
|
||||
"comm_max": 5000,
|
||||
"secu": 1001,
|
||||
"secu_max": 2000,
|
||||
"trust": 55,
|
||||
"def": 1001,
|
||||
"def_max": 5000,
|
||||
"wall": 1001,
|
||||
"wall_max": 5000,
|
||||
"dead": 123
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"nation": 0,
|
||||
"supply": 1,
|
||||
"pop": 10000,
|
||||
"pop_max": 50000,
|
||||
"agri": 1001,
|
||||
"agri_max": 5000,
|
||||
"comm": 1001,
|
||||
"comm_max": 5000,
|
||||
"secu": 1001,
|
||||
"secu_max": 2000,
|
||||
"trust": 55,
|
||||
"def": 1001,
|
||||
"def_max": 5000,
|
||||
"wall": 1001,
|
||||
"wall_max": 5000,
|
||||
"dead": 123
|
||||
}
|
||||
}
|
||||
],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"gold": 10001,
|
||||
"rice": 8888
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1],
|
||||
"cityIds": [1, 2, 3],
|
||||
"nationIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
{
|
||||
"action": "ProcessSemiAnnual",
|
||||
"resource": "gold",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "반기검증국",
|
||||
"gold": 100001,
|
||||
"rice": 7777,
|
||||
"rate": 50,
|
||||
"rate_tmp": 20,
|
||||
"type": "che_중립"
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"supply": 1,
|
||||
"pop": 10000,
|
||||
"pop_max": 50000,
|
||||
"agri": 1001,
|
||||
"agri_max": 5000,
|
||||
"comm": 1001,
|
||||
"comm_max": 5000,
|
||||
"secu": 1001,
|
||||
"secu_max": 2000,
|
||||
"trust": 55,
|
||||
"def": 1001,
|
||||
"def_max": 5000,
|
||||
"wall": 1001,
|
||||
"wall_max": 5000,
|
||||
"dead": 123
|
||||
}
|
||||
}
|
||||
],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"gold": 10001,
|
||||
"rice": 8888
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1],
|
||||
"cityIds": [1],
|
||||
"nationIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"action": "ProcessWarIncome",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "전쟁수입국",
|
||||
"gold": 1000,
|
||||
"level": 1,
|
||||
"type": "che_중립"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"name": "비활성국",
|
||||
"gold": 2000,
|
||||
"level": 0,
|
||||
"type": "che_중립"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"name": "법가국",
|
||||
"gold": 3000,
|
||||
"level": 1,
|
||||
"type": "che_법가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"supply": 1,
|
||||
"pop": 1000,
|
||||
"pop_max": 2000,
|
||||
"dead": 101
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"supply": 0,
|
||||
"pop": 1000,
|
||||
"pop_max": 2000,
|
||||
"dead": 999
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"nation": 2,
|
||||
"supply": 1,
|
||||
"pop": 1000,
|
||||
"pop_max": 2000,
|
||||
"dead": 1000
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"values": {
|
||||
"nation": 3,
|
||||
"supply": 1,
|
||||
"pop": 1000,
|
||||
"pop_max": 2000,
|
||||
"dead": 105
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"values": {
|
||||
"nation": 0,
|
||||
"supply": 1,
|
||||
"pop": 999,
|
||||
"pop_max": 1000,
|
||||
"dead": 10
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"cityIds": [1, 2, 3, 4, 5],
|
||||
"nationIds": [1, 2, 3]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
{
|
||||
"action": "RaiseInvader",
|
||||
"compactOutput": true,
|
||||
"args": [10, 150, 100, 20],
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"deleteOtherGenerals": true,
|
||||
"keepGeneralIds": [1],
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"level": 3,
|
||||
"nation": 1,
|
||||
"pop": 1000,
|
||||
"pop_max": 10000,
|
||||
"agri": 2000,
|
||||
"agri_max": 20000,
|
||||
"comm": 3000,
|
||||
"comm_max": 30000,
|
||||
"secu": 4000,
|
||||
"secu_max": 40000,
|
||||
"def": 5000,
|
||||
"def_max": 50000,
|
||||
"wall": 6000,
|
||||
"wall_max": 60000
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 48,
|
||||
"values": {
|
||||
"level": 4,
|
||||
"nation": 0,
|
||||
"pop": 1000,
|
||||
"pop_max": 10000,
|
||||
"agri": 2000,
|
||||
"agri_max": 20000,
|
||||
"comm": 3000,
|
||||
"comm_max": 30000,
|
||||
"secu": 4000,
|
||||
"secu_max": 40000,
|
||||
"def": 5000,
|
||||
"def_max": 50000,
|
||||
"wall": 6000,
|
||||
"wall_max": 60000
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "기준국",
|
||||
"capital": 1,
|
||||
"gennum": 1,
|
||||
"tech": 100,
|
||||
"level": 2,
|
||||
"type": "che_유가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "군주",
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"officer_level": 12,
|
||||
"npc": 0,
|
||||
"leadership": 50,
|
||||
"strength": 50,
|
||||
"intel": 50,
|
||||
"experience": 1000,
|
||||
"dedication": 1000,
|
||||
"dex1": 10,
|
||||
"dex2": 20,
|
||||
"dex3": 30,
|
||||
"dex4": 40,
|
||||
"dex5": 50,
|
||||
"turntime": "0200-01-01 00:05:00"
|
||||
}
|
||||
}
|
||||
],
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"turntime": "0200-01-01 00:00:00",
|
||||
"show_img_level": 3,
|
||||
"fiction": [0]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1],
|
||||
"cityIds": [1, 48],
|
||||
"nationIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"action": "RaiseNPCNation",
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"resetNations": true,
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "점유도시",
|
||||
"level": 5,
|
||||
"nation": 1,
|
||||
"pop": 10001,
|
||||
"pop_max": 50001,
|
||||
"agri": 1001,
|
||||
"agri_max": 5001,
|
||||
"comm": 2001,
|
||||
"comm_max": 6001,
|
||||
"secu": 3001,
|
||||
"secu_max": 7001,
|
||||
"def": 4001,
|
||||
"def_max": 8001,
|
||||
"wall": 5001,
|
||||
"wall_max": 9001
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 48,
|
||||
"values": {
|
||||
"name": "건국도시",
|
||||
"level": 5,
|
||||
"nation": 0,
|
||||
"pop": 10048,
|
||||
"pop_max": 50048,
|
||||
"agri": 1048,
|
||||
"agri_max": 5048,
|
||||
"comm": 2048,
|
||||
"comm_max": 6048,
|
||||
"secu": 3048,
|
||||
"secu_max": 7048,
|
||||
"def": 4048,
|
||||
"def_max": 8048,
|
||||
"wall": 5048,
|
||||
"wall_max": 9048
|
||||
}
|
||||
}
|
||||
],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "기준국",
|
||||
"capital": 1,
|
||||
"gennum": 1,
|
||||
"tech": 120,
|
||||
"level": 2,
|
||||
"type": "che_유가"
|
||||
}
|
||||
}
|
||||
],
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"turntime": "0200-01-01 00:00:00",
|
||||
"show_img_level": 3,
|
||||
"fiction": [0]
|
||||
},
|
||||
"observe": {
|
||||
"cityIds": [1, 48],
|
||||
"nationIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"action": "RegNeutralNPC",
|
||||
"args": [
|
||||
0,
|
||||
"등록재야",
|
||||
null,
|
||||
0,
|
||||
33,
|
||||
45,
|
||||
55,
|
||||
65,
|
||||
180,
|
||||
245,
|
||||
null,
|
||||
"무쌍",
|
||||
""
|
||||
],
|
||||
"setup": {
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"turntime": "0200-01-01 00:00:00",
|
||||
"show_img_level": 3,
|
||||
"fiction": [0]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [],
|
||||
"cityIds": [33],
|
||||
"nationIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"action": "RegNPC",
|
||||
"args": [
|
||||
0,
|
||||
"등록장수",
|
||||
null,
|
||||
0,
|
||||
33,
|
||||
60,
|
||||
50,
|
||||
40,
|
||||
7,
|
||||
186,
|
||||
240,
|
||||
null,
|
||||
"인덕",
|
||||
"등록 대사"
|
||||
],
|
||||
"setup": {
|
||||
"syncEnvironment": true
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190,
|
||||
"turnterm": 10,
|
||||
"turntime": "0200-01-01 00:00:00",
|
||||
"show_img_level": 3,
|
||||
"fiction": [0]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [],
|
||||
"cityIds": [33],
|
||||
"nationIds": [1]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"action": "UnblockScoutAction",
|
||||
"args": [false],
|
||||
"setup": {
|
||||
"resetNations": true,
|
||||
"deleteOtherNations": true,
|
||||
"keepNationIds": [1, 2],
|
||||
"nation": [
|
||||
{ "id": 1, "values": { "name": "위", "level": 2, "scout": 1 } },
|
||||
{ "id": 2, "values": { "name": "촉", "level": 2, "scout": 1 } }
|
||||
],
|
||||
"gameEnvironment": {
|
||||
"block_change_scout": true
|
||||
}
|
||||
},
|
||||
"environment": {
|
||||
"year": 200,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"observe": {
|
||||
"nationIds": [1, 2]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
{
|
||||
"action": "UpdateCitySupply",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 1,
|
||||
"startyear": 190
|
||||
},
|
||||
"setup": {
|
||||
"nation": [
|
||||
{
|
||||
"id": 99,
|
||||
"values": {
|
||||
"name": "보급검증국",
|
||||
"color": "#777777",
|
||||
"capital": 1,
|
||||
"level": 1,
|
||||
"type": "che_중립"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 98,
|
||||
"values": {
|
||||
"name": "불일치수도국",
|
||||
"color": "#888888",
|
||||
"capital": 2,
|
||||
"level": 1,
|
||||
"type": "che_중립"
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 99,
|
||||
"supply": 0,
|
||||
"front": 2,
|
||||
"pop": 1001,
|
||||
"agri": 501,
|
||||
"comm": 499,
|
||||
"secu": 99,
|
||||
"trust": 50,
|
||||
"def": 101,
|
||||
"wall": 50,
|
||||
"officer_set": 7,
|
||||
"term": 2,
|
||||
"conflict": {"98": 3}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"values": {
|
||||
"nation": 99,
|
||||
"supply": 0,
|
||||
"front": 2,
|
||||
"pop": 1001,
|
||||
"agri": 501,
|
||||
"comm": 499,
|
||||
"secu": 99,
|
||||
"trust": 50,
|
||||
"def": 101,
|
||||
"wall": 50,
|
||||
"officer_set": 7,
|
||||
"term": 2,
|
||||
"conflict": {"98": 3}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 99,
|
||||
"supply": 1,
|
||||
"front": 2,
|
||||
"pop": 1001,
|
||||
"agri": 501,
|
||||
"comm": 499,
|
||||
"secu": 99,
|
||||
"trust": 33,
|
||||
"def": 101,
|
||||
"wall": 50,
|
||||
"officer_set": 7,
|
||||
"term": 2,
|
||||
"conflict": {"98": 3}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"nation": 0,
|
||||
"supply": 0,
|
||||
"front": 0,
|
||||
"trust": 50
|
||||
}
|
||||
}
|
||||
],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 99,
|
||||
"city": 2,
|
||||
"officer_level": 4,
|
||||
"officer_city": 2,
|
||||
"crew": 101,
|
||||
"train": 51,
|
||||
"atmos": 99
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 99,
|
||||
"city": 1,
|
||||
"officer_level": 4,
|
||||
"officer_city": 2,
|
||||
"crew": 101,
|
||||
"train": 51,
|
||||
"atmos": 99
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"values": {
|
||||
"nation": 98,
|
||||
"city": 2,
|
||||
"officer_level": 3,
|
||||
"officer_city": 1,
|
||||
"crew": 101,
|
||||
"train": 51,
|
||||
"atmos": 99
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1, 2, 3],
|
||||
"cityIds": [1, 2, 3, 9],
|
||||
"nationIds": [98, 99]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"action": "UpdateNationLevel",
|
||||
"environment": {
|
||||
"year": 193,
|
||||
"month": 2,
|
||||
"startyear": 190,
|
||||
"killturn": 1000,
|
||||
"turnterm": 10
|
||||
},
|
||||
"setup": {
|
||||
"resetCities": true,
|
||||
"resetGenerals": true,
|
||||
"resetUniqueOccupancy": true,
|
||||
"syncEnvironment": true,
|
||||
"clearNationTurnIds": [1],
|
||||
"clearInheritanceOwnerIds": [990061],
|
||||
"nation": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "작위검증국",
|
||||
"color": "#777777",
|
||||
"capital": 1,
|
||||
"gold": 10000,
|
||||
"rice": 20000,
|
||||
"level": 0,
|
||||
"type": "che_중립",
|
||||
"aux": {}
|
||||
}
|
||||
}
|
||||
],
|
||||
"city": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"level": 4
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 1,
|
||||
"level": 4
|
||||
}
|
||||
}
|
||||
],
|
||||
"general": [
|
||||
{
|
||||
"id": 1,
|
||||
"values": {
|
||||
"name": "조조",
|
||||
"nation": 1,
|
||||
"city": 1,
|
||||
"officer_level": 12,
|
||||
"owner": 990061,
|
||||
"npc": 0,
|
||||
"killturn": 1000,
|
||||
"belong": 10,
|
||||
"horse": "None",
|
||||
"weapon": "None",
|
||||
"book": "None",
|
||||
"item": "None",
|
||||
"aux": {}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"values": {
|
||||
"nation": 0,
|
||||
"city": 2,
|
||||
"officer_level": 1,
|
||||
"npc": 0,
|
||||
"killturn": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"observe": {
|
||||
"generalIds": [1],
|
||||
"cityIds": [1, 2],
|
||||
"nationIds": [1],
|
||||
"ownerIds": [990061]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace sammo;
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
chdir(dirname(__DIR__));
|
||||
require_once 'lib.php';
|
||||
require_once 'func.php';
|
||||
|
||||
$input = stream_get_contents(STDIN);
|
||||
$keys = Json::decode($input);
|
||||
if (!is_array($keys)) {
|
||||
fwrite(STDERR, "Expected a JSON array of item keys.\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($keys as $key) {
|
||||
if (!is_string($key)) {
|
||||
continue;
|
||||
}
|
||||
$item = buildItemClass($key);
|
||||
$result[$key] = [
|
||||
'rawName' => $item->getRawName(),
|
||||
'name' => $item->getName(),
|
||||
'info' => $item->getInfo(),
|
||||
'cost' => $item->getCost(),
|
||||
'buyable' => $item->isBuyable(),
|
||||
'consumable' => $item->isConsumable(),
|
||||
'reqSecu' => $item->getReqSecu(),
|
||||
];
|
||||
}
|
||||
|
||||
echo Json::encode($result);
|
||||
@@ -0,0 +1,1579 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace sammo;
|
||||
|
||||
if (PHP_SAPI !== 'cli' || getenv('TURN_DIFFERENTIAL_ENABLED') !== '1') {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
chdir(dirname(__DIR__));
|
||||
$_SERVER['REMOTE_ADDR'] ??= '127.0.0.1';
|
||||
error_reporting(E_ALL & ~E_DEPRECATED);
|
||||
require_once 'lib.php';
|
||||
require_once 'func.php';
|
||||
require_once __DIR__ . '/turn_state_snapshot.php';
|
||||
|
||||
/** @param array<string, mixed> $values */
|
||||
function comparisonMonthlyPatch(string $table, int $id, array $values): void
|
||||
{
|
||||
$definitions = [
|
||||
'city' => [
|
||||
'idColumn' => 'city',
|
||||
'allowed' => [
|
||||
'name', 'level', 'nation', 'supply', 'front', 'pop', 'pop_max',
|
||||
'agri', 'agri_max', 'comm', 'comm_max', 'secu', 'secu_max',
|
||||
'trust', 'trade', 'def', 'def_max', 'wall', 'wall_max',
|
||||
'officer_set', 'state', 'region', 'term', 'conflict', 'dead',
|
||||
],
|
||||
],
|
||||
'nation' => [
|
||||
'idColumn' => 'nation',
|
||||
'allowed' => [
|
||||
'name', 'color', 'capital', 'gennum', 'gold', 'rice', 'tech',
|
||||
'power', 'level', 'type', 'bill', 'rate_tmp', 'scout', 'chief_set', 'aux',
|
||||
'rate', 'strategic_cmd_limit', 'surlimit', 'spy',
|
||||
],
|
||||
],
|
||||
'general' => [
|
||||
'idColumn' => 'no',
|
||||
'allowed' => [
|
||||
'name', 'nation', 'city', 'officer_level', 'officer_city',
|
||||
'crew', 'train', 'atmos', 'owner', 'npc', 'killturn', 'belong',
|
||||
'gold', 'rice', 'horse', 'weapon', 'book', 'item', 'aux',
|
||||
'leadership', 'strength', 'intel', 'experience', 'dedication',
|
||||
'injury',
|
||||
'dex1', 'dex2', 'dex3', 'dex4', 'dex5', 'personal', 'special',
|
||||
'specage', 'special2', 'specage2', 'betray', 'age',
|
||||
'bornyear', 'deadyear', 'turntime', 'makelimit',
|
||||
],
|
||||
],
|
||||
];
|
||||
$definition = $definitions[$table] ?? null;
|
||||
if ($definition === null) {
|
||||
throw new \InvalidArgumentException("unsupported setup table: {$table}");
|
||||
}
|
||||
$patch = [];
|
||||
foreach ($values as $key => $value) {
|
||||
if (!is_string($key) || !in_array($key, $definition['allowed'], true)) {
|
||||
throw new \InvalidArgumentException("unsupported {$table} setup field");
|
||||
}
|
||||
if (in_array($key, ['conflict', 'aux'], true) && is_array($value)) {
|
||||
$value = json_encode($value, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
|
||||
}
|
||||
$patch[$key] = $value;
|
||||
}
|
||||
if ($table === 'nation') {
|
||||
$patch += [
|
||||
'nation' => $id,
|
||||
'name' => "fixture-nation-{$id}",
|
||||
'color' => '#777777',
|
||||
'capital' => 0,
|
||||
'gold' => 0,
|
||||
'rice' => 0,
|
||||
'level' => 1,
|
||||
'type' => 'che_중립',
|
||||
'aux' => '{}',
|
||||
];
|
||||
DB::db()->insertUpdate('nation', $patch, $patch);
|
||||
} elseif ($patch !== []) {
|
||||
DB::db()->update($table, $patch, "`{$definition['idColumn']}` = %i", $id);
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $observe */
|
||||
function comparisonMonthlyDetails(array $observe, int $worldHistoryAfterId): array
|
||||
{
|
||||
$db = DB::db();
|
||||
$generals = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'no',
|
||||
'nationId' => 'nation',
|
||||
'cityId' => 'city',
|
||||
'officerLevel' => 'officer_level',
|
||||
'officerCityId' => 'officer_city',
|
||||
'crew' => 'crew',
|
||||
'train' => 'train',
|
||||
'atmos' => 'atmos',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'injury' => 'injury',
|
||||
'leadership' => 'leadership',
|
||||
'strength' => 'strength',
|
||||
'intelligence' => 'intel',
|
||||
'age' => 'age',
|
||||
'specialDomestic' => 'special',
|
||||
'specAge' => 'specage',
|
||||
'specialWar' => 'special2',
|
||||
'specAge2' => 'specage2',
|
||||
'betray' => 'betray',
|
||||
'makeLimit' => 'makelimit',
|
||||
'horse' => 'horse',
|
||||
'weapon' => 'weapon',
|
||||
'book' => 'book',
|
||||
'item' => 'item',
|
||||
'dex1' => 'dex1',
|
||||
'dex2' => 'dex2',
|
||||
'dex3' => 'dex3',
|
||||
'dex4' => 'dex4',
|
||||
'dex5' => 'dex5',
|
||||
'aux' => 'aux',
|
||||
],
|
||||
['aux'],
|
||||
),
|
||||
comparisonRowsById('general', 'no', comparisonIntegerList($observe['generalIds'] ?? [], 'generalIds')),
|
||||
);
|
||||
$cities = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'city',
|
||||
'nationId' => 'nation',
|
||||
'state' => 'state',
|
||||
'supplyState' => 'supply',
|
||||
'frontState' => 'front',
|
||||
'officerSet' => 'officer_set',
|
||||
'term' => 'term',
|
||||
'dead' => 'dead',
|
||||
'population' => 'pop',
|
||||
'populationMax' => 'pop_max',
|
||||
'agriculture' => 'agri',
|
||||
'agricultureMax' => 'agri_max',
|
||||
'commerce' => 'comm',
|
||||
'commerceMax' => 'comm_max',
|
||||
'security' => 'secu',
|
||||
'securityMax' => 'secu_max',
|
||||
'trust' => 'trust',
|
||||
'trade' => 'trade',
|
||||
'defence' => 'def',
|
||||
'defenceMax' => 'def_max',
|
||||
'wall' => 'wall',
|
||||
'wallMax' => 'wall_max',
|
||||
'conflict' => 'conflict',
|
||||
],
|
||||
['conflict'],
|
||||
),
|
||||
comparisonRowsById('city', 'city', comparisonIntegerList($observe['cityIds'] ?? [], 'cityIds')),
|
||||
);
|
||||
$nations = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'nation',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'rate' => 'rate_tmp',
|
||||
'baseRate' => 'rate',
|
||||
'power' => 'power',
|
||||
'generalCount' => 'gennum',
|
||||
'tech' => 'tech',
|
||||
'typeCode' => 'type',
|
||||
'scout' => 'scout',
|
||||
'strategicCommandLimit' => 'strategic_cmd_limit',
|
||||
'surrenderLimit' => 'surlimit',
|
||||
'spy' => 'spy',
|
||||
'chiefSet' => 'chief_set',
|
||||
],
|
||||
['spy'],
|
||||
),
|
||||
comparisonRowsById('nation', 'nation', comparisonIntegerList($observe['nationIds'] ?? [], 'nationIds')),
|
||||
);
|
||||
$worldHistory = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'id',
|
||||
'nationId' => 'nation_id',
|
||||
'year' => 'year',
|
||||
'month' => 'month',
|
||||
'text' => 'text',
|
||||
],
|
||||
),
|
||||
$db->query(
|
||||
'SELECT id, nation_id, year, month, text FROM world_history WHERE id > %i ORDER BY id',
|
||||
$worldHistoryAfterId,
|
||||
),
|
||||
);
|
||||
$inheritanceKeys = $observe['inheritanceKeys'] ?? ['unifier'];
|
||||
if (!is_array($inheritanceKeys) || array_filter($inheritanceKeys, static fn($key): bool => !is_string($key))) {
|
||||
throw new \InvalidArgumentException('inheritanceKeys must be an array of strings');
|
||||
}
|
||||
$inheritancePoints = [];
|
||||
foreach (comparisonIntegerList($observe['ownerIds'] ?? [], 'ownerIds') as $ownerId) {
|
||||
$entry = ['ownerId' => $ownerId];
|
||||
foreach ($inheritanceKeys as $key) {
|
||||
$value = $db->queryFirstField(
|
||||
'SELECT value FROM storage WHERE namespace = %s AND `key` = %s',
|
||||
"inheritance_{$ownerId}",
|
||||
$key,
|
||||
);
|
||||
$entry[$key] = $value === null ? 0 : (comparisonJsonValue($value)[0] ?? 0);
|
||||
}
|
||||
$inheritancePoints[] = $entry;
|
||||
}
|
||||
$rankGeneralIds = comparisonIntegerList($observe['rankGeneralIds'] ?? [], 'rankGeneralIds');
|
||||
$rankTypes = $observe['rankTypes'] ?? [];
|
||||
if (!is_array($rankTypes) || array_filter($rankTypes, static fn($type): bool => !is_string($type))) {
|
||||
throw new \InvalidArgumentException('rankTypes must be an array of strings');
|
||||
}
|
||||
$rankData = (!$rankGeneralIds || !$rankTypes)
|
||||
? []
|
||||
: iterator_to_array($db->query(
|
||||
'SELECT general_id AS generalId, nation_id AS nationId, `type`, `value` FROM rank_data WHERE general_id IN %li AND `type` IN %ls ORDER BY general_id, `type`',
|
||||
$rankGeneralIds,
|
||||
$rankTypes,
|
||||
));
|
||||
$generalAccessLogs = [];
|
||||
$accessGeneralIds = comparisonIntegerList($observe['accessGeneralIds'] ?? [], 'accessGeneralIds');
|
||||
if ($accessGeneralIds) {
|
||||
$generalAccessLogs = iterator_to_array($db->query(
|
||||
'SELECT general_id AS generalId, refresh_score_total AS refreshScoreTotal FROM general_access_log WHERE general_id IN %li ORDER BY general_id',
|
||||
$accessGeneralIds,
|
||||
));
|
||||
}
|
||||
$nationEnvironment = [];
|
||||
$nationEnvironmentKeys = $observe['nationEnvironmentKeys'] ?? [];
|
||||
if (
|
||||
!is_array($nationEnvironmentKeys)
|
||||
|| array_filter($nationEnvironmentKeys, static fn($key): bool => !is_string($key))
|
||||
) {
|
||||
throw new \InvalidArgumentException('nationEnvironmentKeys must be an array of strings');
|
||||
}
|
||||
foreach (comparisonIntegerList($observe['nationIds'] ?? [], 'nationIds') as $nationId) {
|
||||
$entry = ['nationId' => $nationId];
|
||||
$storage = KVStorage::getStorage($db, $nationId, 'nation_env');
|
||||
foreach ($nationEnvironmentKeys as $key) {
|
||||
$entry[$key] = $storage->getValue($key);
|
||||
}
|
||||
$nationEnvironment[] = $entry;
|
||||
}
|
||||
return [
|
||||
'generals' => $generals,
|
||||
'cities' => $cities,
|
||||
'nations' => $nations,
|
||||
'worldHistory' => $worldHistory,
|
||||
'inheritancePoints' => $inheritancePoints,
|
||||
'rankData' => $rankData,
|
||||
'generalAccessLogs' => $generalAccessLogs,
|
||||
'nationEnvironment' => $nationEnvironment,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Exercise the dynamically-created invader events against one evolving database.
|
||||
*
|
||||
* @param array<string, mixed> $request
|
||||
* @param array<string, mixed> $environment
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
function comparisonInvaderLifecycleTrace(
|
||||
array $request,
|
||||
array $environment,
|
||||
int $generalIdBeforeAction,
|
||||
int $nationIdBeforeAction,
|
||||
int $eventIdBeforeAction,
|
||||
int $worldHistoryIdBeforeAction,
|
||||
): array {
|
||||
$db = DB::db();
|
||||
$args = $request['args'] ?? [];
|
||||
if (!is_array($args) || count($args) > 4) {
|
||||
throw new \InvalidArgumentException('InvaderLifecycle args must have at most four entries');
|
||||
}
|
||||
$year = $environment['year'];
|
||||
$month = $environment['month'];
|
||||
$startYear = $environment['startyear'];
|
||||
$raiseEnvironment = [
|
||||
'year' => $year,
|
||||
'month' => $month,
|
||||
'startyear' => $startYear,
|
||||
'turnterm' => $environment['turnterm'],
|
||||
'turntime' => $environment['turntime'],
|
||||
'show_img_level' => $environment['show_img_level'] ?? 3,
|
||||
'stored_icons' => $environment['stored_icons'] ?? [],
|
||||
'icon_path' => $environment['icon_path'] ?? '.',
|
||||
'fiction' => $environment['fiction'] ?? [0],
|
||||
];
|
||||
|
||||
(new \sammo\Event\Action\RaiseInvader(...$args))->run($raiseEnvironment);
|
||||
|
||||
$invaderNationIds = array_map(
|
||||
'intval',
|
||||
$db->queryFirstColumn('SELECT nation FROM nation WHERE nation > %i ORDER BY nation', $nationIdBeforeAction),
|
||||
);
|
||||
$existingNationId = (int)$db->queryFirstField(
|
||||
'SELECT nation FROM nation WHERE nation <= %i ORDER BY nation LIMIT 1',
|
||||
$nationIdBeforeAction,
|
||||
);
|
||||
$rulerIds = array_map(
|
||||
'intval',
|
||||
$db->queryFirstColumn(
|
||||
'SELECT no FROM general WHERE nation IN %li AND officer_level = 12 ORDER BY nation',
|
||||
$invaderNationIds,
|
||||
),
|
||||
);
|
||||
if ($invaderNationIds === [] || $existingNationId <= 0 || count($rulerIds) !== count($invaderNationIds)) {
|
||||
throw new \RuntimeException('InvaderLifecycle failed to create the expected entities');
|
||||
}
|
||||
|
||||
$autoDeleteEvents = [];
|
||||
$endingEventId = 0;
|
||||
foreach ($db->query('SELECT id, action FROM event WHERE id > %i ORDER BY id', $eventIdBeforeAction) as $row) {
|
||||
$action = comparisonJsonValue($row['action']);
|
||||
$actionName = $action[0][0] ?? null;
|
||||
if ($actionName === 'AutoDeleteInvader') {
|
||||
$autoDeleteEvents[] = [
|
||||
'eventId' => (int)$row['id'],
|
||||
'nationId' => (int)($action[0][1] ?? 0),
|
||||
];
|
||||
} elseif ($actionName === 'InvaderEnding') {
|
||||
$endingEventId = (int)$row['id'];
|
||||
}
|
||||
}
|
||||
if (count($autoDeleteEvents) !== count($invaderNationIds) || $endingEventId <= 0) {
|
||||
throw new \RuntimeException('InvaderLifecycle failed to create follow-up events');
|
||||
}
|
||||
|
||||
$diplomacyRows = iterator_to_array($db->query(
|
||||
'SELECT me, you, state, term FROM diplomacy WHERE (me IN %li AND you = %i) OR (me = %i AND you IN %li) ORDER BY me, you',
|
||||
$invaderNationIds,
|
||||
$existingNationId,
|
||||
$existingNationId,
|
||||
$invaderNationIds,
|
||||
));
|
||||
$diplomacyStates = array_values(array_unique(array_map(
|
||||
static fn(array $row): string => "{$row['state']}:{$row['term']}",
|
||||
$diplomacyRows,
|
||||
)));
|
||||
sort($diplomacyStates);
|
||||
$generalCounts = array_map(
|
||||
static fn(int $nationId): int => (int)DB::db()->queryFirstField(
|
||||
'SELECT count(*) FROM general WHERE nation = %i',
|
||||
$nationId,
|
||||
),
|
||||
$invaderNationIds,
|
||||
);
|
||||
$diplomacyCounts = array_map(
|
||||
static fn(int $nationId): int => (int)DB::db()->queryFirstField(
|
||||
'SELECT count(*) FROM diplomacy WHERE (me = %i AND you = %i) OR (me = %i AND you = %i)',
|
||||
$nationId,
|
||||
$existingNationId,
|
||||
$existingNationId,
|
||||
$nationId,
|
||||
),
|
||||
$invaderNationIds,
|
||||
);
|
||||
$gameStorage = KVStorage::getStorage($db, 'game_env');
|
||||
$afterRaise = [
|
||||
'createdNationCount' => count($invaderNationIds),
|
||||
'createdGeneralCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM general WHERE no > %i',
|
||||
$generalIdBeforeAction,
|
||||
),
|
||||
'followUpEventCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM event WHERE id > %i',
|
||||
$eventIdBeforeAction,
|
||||
),
|
||||
'generalCountsPerNation' => array_values(array_unique($generalCounts)),
|
||||
'diplomacyCountsPerNation' => array_values(array_unique($diplomacyCounts)),
|
||||
'diplomacyStates' => $diplomacyStates,
|
||||
'isunited' => (int)$gameStorage->isunited,
|
||||
'blockChangeScout' => (bool)$gameStorage->block_change_scout,
|
||||
];
|
||||
|
||||
$warResults = [];
|
||||
foreach ($autoDeleteEvents as $autoDeleteEvent) {
|
||||
$warResult = (new \sammo\Event\Action\AutoDeleteInvader($autoDeleteEvent['nationId']))->run([
|
||||
'year' => $year,
|
||||
'month' => $month + 1,
|
||||
'startyear' => $startYear,
|
||||
'currentEventID' => $autoDeleteEvent['eventId'],
|
||||
]);
|
||||
$warResults[] = $warResult[1] ?? null;
|
||||
}
|
||||
$atWar = [
|
||||
'results' => array_values(array_unique($warResults)),
|
||||
'autoDeleteEventCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM event WHERE id IN %li',
|
||||
array_column($autoDeleteEvents, 'eventId'),
|
||||
),
|
||||
];
|
||||
|
||||
$db->update(
|
||||
'diplomacy',
|
||||
['state' => 2, 'term' => 0],
|
||||
'me IN %li OR you IN %li',
|
||||
$invaderNationIds,
|
||||
$invaderNationIds,
|
||||
);
|
||||
$peaceResults = [];
|
||||
foreach ($autoDeleteEvents as $autoDeleteEvent) {
|
||||
$peaceResult = (new \sammo\Event\Action\AutoDeleteInvader($autoDeleteEvent['nationId']))->run([
|
||||
'year' => $year,
|
||||
'month' => $month + 2,
|
||||
'startyear' => $startYear,
|
||||
'currentEventID' => $autoDeleteEvent['eventId'],
|
||||
]);
|
||||
$peaceResults[] = $peaceResult[1] ?? null;
|
||||
}
|
||||
$atPeace = [
|
||||
'results' => array_values(array_unique($peaceResults)),
|
||||
'autoDeleteEventCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM event WHERE id IN %li',
|
||||
array_column($autoDeleteEvents, 'eventId'),
|
||||
),
|
||||
'rulerWanderTurnCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM general_turn WHERE general_id IN %li AND action = %s',
|
||||
$rulerIds,
|
||||
'che_방랑',
|
||||
),
|
||||
'endingEventPresent' => (bool)$db->queryFirstField(
|
||||
'SELECT count(*) FROM event WHERE id = %i',
|
||||
$endingEventId,
|
||||
),
|
||||
];
|
||||
|
||||
$invaderGeneralIds = array_map('intval', $db->queryFirstColumn(
|
||||
'SELECT no FROM general WHERE nation IN %li',
|
||||
$invaderNationIds,
|
||||
));
|
||||
if ($invaderGeneralIds !== []) {
|
||||
$db->delete('general_turn', 'general_id IN %li', $invaderGeneralIds);
|
||||
$db->delete('rank_data', 'general_id IN %li', $invaderGeneralIds);
|
||||
$db->delete('troop', 'nation IN %li', $invaderNationIds);
|
||||
$db->delete('general', 'no IN %li', $invaderGeneralIds);
|
||||
}
|
||||
$db->delete('nation_turn', 'nation_id IN %li', $invaderNationIds);
|
||||
$db->delete('diplomacy', 'me IN %li OR you IN %li', $invaderNationIds, $invaderNationIds);
|
||||
$db->delete('nation', 'nation IN %li', $invaderNationIds);
|
||||
$db->update('city', ['nation' => $existingNationId], true);
|
||||
|
||||
$endingResult = (new \sammo\Event\Action\InvaderEnding())->run([
|
||||
'year' => $year,
|
||||
'month' => $month + 3,
|
||||
'startyear' => $startYear,
|
||||
'currentEventID' => $endingEventId,
|
||||
]);
|
||||
$gameStorage->resetCache();
|
||||
$afterUserWin = [
|
||||
'result' => $endingResult[1] ?? null,
|
||||
'endingEventPresent' => (bool)$db->queryFirstField(
|
||||
'SELECT count(*) FROM event WHERE id = %i',
|
||||
$endingEventId,
|
||||
),
|
||||
'isunited' => (int)$gameStorage->isunited,
|
||||
'refreshLimit' => (int)$gameStorage->refreshLimit,
|
||||
'logs' => array_values($db->queryFirstColumn(
|
||||
'SELECT text FROM world_history WHERE id > %i AND nation_id = 0 AND year = %i AND month = %i ORDER BY id',
|
||||
$worldHistoryIdBeforeAction,
|
||||
$year,
|
||||
$month + 3,
|
||||
)),
|
||||
];
|
||||
|
||||
return [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'action' => 'InvaderLifecycle',
|
||||
'phases' => [
|
||||
'afterRaise' => $afterRaise,
|
||||
'atWar' => $atWar,
|
||||
'atPeace' => $atPeace,
|
||||
'afterUserWin' => $afterUserWin,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Exercise NPC nation creation and the same-month troop leader follow-up.
|
||||
*
|
||||
* @param array<string, mixed> $environment
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
function comparisonNpcNationLifecycleTrace(
|
||||
array $environment,
|
||||
int $generalIdBeforeAction,
|
||||
int $nationIdBeforeAction,
|
||||
int $worldHistoryIdBeforeAction,
|
||||
): array {
|
||||
$db = DB::db();
|
||||
$actionEnvironment = [
|
||||
'year' => $environment['year'],
|
||||
'month' => $environment['month'],
|
||||
'startyear' => $environment['startyear'],
|
||||
'turnterm' => $environment['turnterm'],
|
||||
'turntime' => $environment['turntime'],
|
||||
'show_img_level' => $environment['show_img_level'] ?? 3,
|
||||
'stored_icons' => $environment['stored_icons'] ?? [],
|
||||
'icon_path' => $environment['icon_path'] ?? '.',
|
||||
'fiction' => $environment['fiction'] ?? [0],
|
||||
];
|
||||
$gameStorage = KVStorage::getStorage($db, 'game_env');
|
||||
$leaderCounterBefore = (int)($gameStorage->lastNPCTroopLeaderID ?? 0);
|
||||
|
||||
(new \sammo\Event\Action\RaiseNPCNation())->run($actionEnvironment);
|
||||
$createdNationIds = array_map(
|
||||
'intval',
|
||||
$db->queryFirstColumn('SELECT nation FROM nation WHERE nation > %i ORDER BY nation', $nationIdBeforeAction),
|
||||
);
|
||||
if ($createdNationIds === []) {
|
||||
throw new \RuntimeException('NpcNationLifecycle failed to create a nation');
|
||||
}
|
||||
$createdNationGeneralCounts = array_map(
|
||||
static fn(int $nationId): int => (int)DB::db()->queryFirstField(
|
||||
'SELECT count(*) FROM general WHERE nation = %i',
|
||||
$nationId,
|
||||
),
|
||||
$createdNationIds,
|
||||
);
|
||||
$afterRaise = [
|
||||
'createdNationCount' => count($createdNationIds),
|
||||
'createdGeneralCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM general WHERE no > %i',
|
||||
$generalIdBeforeAction,
|
||||
),
|
||||
'generalCountsPerCreatedNation' => array_values(array_unique($createdNationGeneralCounts)),
|
||||
'historyLogs' => array_values($db->queryFirstColumn(
|
||||
'SELECT text FROM world_history WHERE id > %i AND nation_id = 0 ORDER BY id',
|
||||
$worldHistoryIdBeforeAction,
|
||||
)),
|
||||
];
|
||||
|
||||
(new \sammo\Event\Action\ProvideNPCTroopLeader())->run($actionEnvironment);
|
||||
$leaderIds = array_map(
|
||||
'intval',
|
||||
$db->queryFirstColumn('SELECT no FROM general WHERE no > %i AND npc = 5 ORDER BY no', $generalIdBeforeAction),
|
||||
);
|
||||
if ($leaderIds === []) {
|
||||
throw new \RuntimeException('NpcNationLifecycle failed to create troop leaders');
|
||||
}
|
||||
$leaderNationCounts = array_map(
|
||||
static fn(int $nationId): int => (int)DB::db()->queryFirstField(
|
||||
'SELECT count(*) FROM general WHERE nation = %i AND npc = 5',
|
||||
$nationId,
|
||||
),
|
||||
array_map(
|
||||
'intval',
|
||||
$db->queryFirstColumn('SELECT nation FROM nation WHERE level > 0 ORDER BY nation'),
|
||||
),
|
||||
);
|
||||
$gatherTurnCounts = array_map(
|
||||
static fn(int $generalId): int => (int)DB::db()->queryFirstField(
|
||||
'SELECT count(*) FROM general_turn WHERE general_id = %i AND action = %s',
|
||||
$generalId,
|
||||
'che_집합',
|
||||
),
|
||||
$leaderIds,
|
||||
);
|
||||
$gameStorage->resetCache();
|
||||
$afterProvide = [
|
||||
'createdLeaderCount' => count($leaderIds),
|
||||
'leaderCountsPerActiveNation' => array_values(array_unique($leaderNationCounts)),
|
||||
'troopCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM troop WHERE troop_leader IN %li',
|
||||
$leaderIds,
|
||||
),
|
||||
'gatherTurnCounts' => array_values(array_unique($gatherTurnCounts)),
|
||||
'leaderCounterDelta' => (int)$gameStorage->lastNPCTroopLeaderID - $leaderCounterBefore,
|
||||
];
|
||||
|
||||
return [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'action' => 'NpcNationLifecycle',
|
||||
'phases' => [
|
||||
'afterRaise' => $afterRaise,
|
||||
'afterProvide' => $afterProvide,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Exercise nation betting from monthly open through real user bets and settlement.
|
||||
*
|
||||
* @param array<string, mixed> $request
|
||||
* @param array<string, mixed> $environment
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
function comparisonNationBettingLifecycleTrace(
|
||||
array $request,
|
||||
array $environment,
|
||||
int $eventIdBeforeAction,
|
||||
int $worldHistoryIdBeforeAction,
|
||||
): array {
|
||||
$db = DB::db();
|
||||
$args = $request['args'] ?? [];
|
||||
if (!is_array($args) || count($args) > 2) {
|
||||
throw new \InvalidArgumentException('NationBettingLifecycle args must have at most two entries');
|
||||
}
|
||||
$bettorGeneralIds = comparisonIntegerList(
|
||||
$request['bettorGeneralIds'] ?? [],
|
||||
'bettorGeneralIds',
|
||||
);
|
||||
$bettorOwnerIds = comparisonIntegerList(
|
||||
$request['bettorOwnerIds'] ?? [],
|
||||
'bettorOwnerIds',
|
||||
);
|
||||
if (count($bettorGeneralIds) !== 2 || count($bettorOwnerIds) !== 2) {
|
||||
throw new \InvalidArgumentException(
|
||||
'NationBettingLifecycle requires exactly two bettorGeneralIds and bettorOwnerIds',
|
||||
);
|
||||
}
|
||||
|
||||
$year = $environment['year'];
|
||||
$month = $environment['month'];
|
||||
$startYear = $environment['startyear'];
|
||||
(new \sammo\Event\Action\OpenNationBetting(...$args))->run([
|
||||
'year' => $year,
|
||||
'month' => $month,
|
||||
'startyear' => $startYear,
|
||||
]);
|
||||
|
||||
$gameStorage = KVStorage::getStorage($db, 'game_env');
|
||||
$gameStorage->resetCache();
|
||||
$bettingId = (int)$gameStorage->last_betting_id;
|
||||
$betting = new Betting($bettingId);
|
||||
$bettingInfo = $betting->getInfo();
|
||||
$candidateNationIds = array_map(
|
||||
static fn(\sammo\DTO\SelectItem $candidate): int => (int)($candidate->aux['nation'] ?? 0),
|
||||
$bettingInfo->candidates,
|
||||
);
|
||||
if (count($candidateNationIds) !== 2) {
|
||||
throw new \RuntimeException('NationBettingLifecycle requires exactly two candidates');
|
||||
}
|
||||
|
||||
$finishEventCount = (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM event WHERE id > %i AND action LIKE %s',
|
||||
$eventIdBeforeAction,
|
||||
"%FinishNationBetting%{$bettingId}%",
|
||||
);
|
||||
$afterOpen = [
|
||||
'bettingId' => $bettingId,
|
||||
'candidateNationIds' => $candidateNationIds,
|
||||
'systemBonus' => (int)($db->queryFirstField(
|
||||
'SELECT amount FROM ng_betting WHERE betting_id = %i AND general_id = 0',
|
||||
$bettingId,
|
||||
) ?? 0),
|
||||
'finishEventCount' => $finishEventCount,
|
||||
'historyLogs' => array_values($db->queryFirstColumn(
|
||||
'SELECT text FROM world_history WHERE id > %i AND nation_id = 0 ORDER BY id',
|
||||
$worldHistoryIdBeforeAction,
|
||||
)),
|
||||
];
|
||||
|
||||
$betting->bet($bettorGeneralIds[0], $bettorOwnerIds[0], [1], 100);
|
||||
$betting->bet($bettorGeneralIds[1], $bettorOwnerIds[1], [0], 100);
|
||||
$afterBets = [
|
||||
'bets' => array_map(
|
||||
static fn(array $row): array => [
|
||||
'generalId' => (int)$row['general_id'],
|
||||
'ownerId' => $row['user_id'] === null ? null : (int)$row['user_id'],
|
||||
'selectionKey' => $row['betting_type'],
|
||||
'amount' => (int)$row['amount'],
|
||||
],
|
||||
iterator_to_array($db->query(
|
||||
'SELECT general_id, user_id, betting_type, amount FROM ng_betting WHERE betting_id = %i ORDER BY general_id',
|
||||
$bettingId,
|
||||
)),
|
||||
),
|
||||
'inheritancePrevious' => array_map(
|
||||
static function (int $ownerId): int {
|
||||
$value = KVStorage::getStorage(DB::db(), "inheritance_{$ownerId}")->getValue('previous');
|
||||
return is_array($value) ? (int)($value[0] ?? 0) : 0;
|
||||
},
|
||||
$bettorOwnerIds,
|
||||
),
|
||||
'spentRank' => array_map(
|
||||
static fn(int $generalId): int => (int)(DB::db()->queryFirstField(
|
||||
'SELECT value FROM rank_data WHERE general_id = %i AND type = %s',
|
||||
$generalId,
|
||||
\sammo\Enums\RankColumn::inherit_point_spent_dynamic->value,
|
||||
) ?? 0),
|
||||
$bettorGeneralIds,
|
||||
),
|
||||
];
|
||||
|
||||
$db->update('nation', ['level' => 0], 'nation = %i', $candidateNationIds[1]);
|
||||
$finishResult = (new \sammo\Event\Action\FinishNationBetting($bettingId))->run([
|
||||
'year' => $year,
|
||||
'month' => $month + 1,
|
||||
'startyear' => $startYear,
|
||||
]);
|
||||
$settledInfo = (new Betting($bettingId))->getInfo();
|
||||
$afterFinish = [
|
||||
'result' => $finishResult[1] ?? null,
|
||||
'finished' => $settledInfo->finished,
|
||||
'winner' => $settledInfo->winner,
|
||||
'inheritancePrevious' => array_map(
|
||||
static function (int $ownerId): int {
|
||||
$value = KVStorage::getStorage(DB::db(), "inheritance_{$ownerId}")->getValue('previous');
|
||||
return is_array($value) ? (int)($value[0] ?? 0) : 0;
|
||||
},
|
||||
$bettorOwnerIds,
|
||||
),
|
||||
'earnedRank' => array_map(
|
||||
static fn(int $generalId): int => (int)(DB::db()->queryFirstField(
|
||||
'SELECT value FROM rank_data WHERE general_id = %i AND type = %s',
|
||||
$generalId,
|
||||
\sammo\Enums\RankColumn::inherit_point_earned_by_action->value,
|
||||
) ?? 0),
|
||||
$bettorGeneralIds,
|
||||
),
|
||||
'historyLogs' => array_values($db->queryFirstColumn(
|
||||
'SELECT text FROM world_history WHERE id > %i AND nation_id = 0 ORDER BY id',
|
||||
$worldHistoryIdBeforeAction,
|
||||
)),
|
||||
];
|
||||
|
||||
return [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'action' => 'NationBettingLifecycle',
|
||||
'phases' => [
|
||||
'afterOpen' => $afterOpen,
|
||||
'afterBets' => $afterBets,
|
||||
'afterFinish' => $afterFinish,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
function comparisonMonthlyEventTraceMain(): void
|
||||
{
|
||||
try {
|
||||
$input = stream_get_contents(STDIN);
|
||||
$request = json_decode($input === '' ? '{}' : $input, true, flags: JSON_THROW_ON_ERROR);
|
||||
if (!is_array($request)) {
|
||||
throw new \InvalidArgumentException('request must be an object');
|
||||
}
|
||||
$actionName = $request['action'] ?? null;
|
||||
$supportedActions = [
|
||||
'UpdateCitySupply',
|
||||
'UpdateNationLevel',
|
||||
'RaiseDisaster',
|
||||
'ProcessSemiAnnual',
|
||||
'ProcessWarIncome',
|
||||
'CreateAdminNPC',
|
||||
'CreateManyNPC',
|
||||
'RegNPC',
|
||||
'RegNeutralNPC',
|
||||
'RaiseNPCNation',
|
||||
'NpcNationLifecycle',
|
||||
'RaiseInvader',
|
||||
'InvaderLifecycle',
|
||||
'AutoDeleteInvader',
|
||||
'InvaderEnding',
|
||||
'ChangeCity',
|
||||
'ProvideNPCTroopLeader',
|
||||
'NationBettingLifecycle',
|
||||
'OpenNationBetting',
|
||||
'FinishNationBetting',
|
||||
'BlockScoutAction',
|
||||
'UnblockScoutAction',
|
||||
'AssignGeneralSpeciality',
|
||||
'AddGlobalBetray',
|
||||
'LostUniqueItem',
|
||||
'MergeInheritPointRank',
|
||||
'ProcessIncome',
|
||||
'NoticeToHistoryLog',
|
||||
'NewYear',
|
||||
'ResetOfficerLock',
|
||||
'PreUpdateMonthly',
|
||||
'PostUpdateMonthly',
|
||||
'MonthlyBoundary',
|
||||
];
|
||||
if (!in_array($actionName, $supportedActions, true)) {
|
||||
throw new \InvalidArgumentException('unsupported monthly action');
|
||||
}
|
||||
$setup = $request['setup'] ?? [];
|
||||
if (!is_array($setup)) {
|
||||
throw new \InvalidArgumentException('setup must be an object');
|
||||
}
|
||||
foreach (['city', 'nation', 'general'] as $table) {
|
||||
$rows = $setup[$table] ?? [];
|
||||
if (!is_array($rows)) {
|
||||
throw new \InvalidArgumentException("setup.{$table} must be an array");
|
||||
}
|
||||
foreach ($rows as $row) {
|
||||
if (!is_array($row) || !is_int($row['id'] ?? null) || !is_array($row['values'] ?? null)) {
|
||||
throw new \InvalidArgumentException("invalid setup.{$table} row");
|
||||
}
|
||||
comparisonMonthlyPatch($table, $row['id'], $row['values']);
|
||||
}
|
||||
}
|
||||
if (($setup['resetCities'] ?? false) === true) {
|
||||
DB::db()->query('UPDATE city SET nation = 0, level = 1');
|
||||
foreach ($setup['city'] ?? [] as $row) {
|
||||
comparisonMonthlyPatch('city', $row['id'], $row['values']);
|
||||
}
|
||||
}
|
||||
if (($setup['deleteOtherCities'] ?? false) === true) {
|
||||
$keepCityIds = comparisonIntegerList($setup['keepCityIds'] ?? [], 'keepCityIds');
|
||||
if ($keepCityIds === []) {
|
||||
throw new \InvalidArgumentException('deleteOtherCities requires keepCityIds');
|
||||
}
|
||||
DB::db()->query('DELETE FROM city WHERE city NOT IN %li', $keepCityIds);
|
||||
}
|
||||
if (($setup['resetGenerals'] ?? false) === true) {
|
||||
DB::db()->query(
|
||||
'UPDATE general SET nation = 0, officer_level = 1, npc = 2, killturn = 0, horse = %s, weapon = %s, book = %s, item = %s',
|
||||
'None',
|
||||
'None',
|
||||
'None',
|
||||
'None',
|
||||
);
|
||||
foreach ($setup['general'] ?? [] as $row) {
|
||||
comparisonMonthlyPatch('general', $row['id'], $row['values']);
|
||||
}
|
||||
}
|
||||
if (($setup['deleteOtherGenerals'] ?? false) === true) {
|
||||
$keepGeneralIds = comparisonIntegerList($setup['keepGeneralIds'] ?? [], 'keepGeneralIds');
|
||||
if (!$keepGeneralIds) {
|
||||
throw new \InvalidArgumentException('deleteOtherGenerals requires keepGeneralIds');
|
||||
}
|
||||
DB::db()->query('DELETE FROM general_turn WHERE general_id NOT IN %li', $keepGeneralIds);
|
||||
DB::db()->query('DELETE FROM rank_data WHERE general_id NOT IN %li', $keepGeneralIds);
|
||||
DB::db()->query('DELETE FROM general WHERE no NOT IN %li', $keepGeneralIds);
|
||||
}
|
||||
if (($setup['resetNations'] ?? false) === true) {
|
||||
DB::db()->query('UPDATE nation SET level = 0, gennum = 0, tech = 0');
|
||||
foreach ($setup['nation'] ?? [] as $row) {
|
||||
comparisonMonthlyPatch('nation', $row['id'], $row['values']);
|
||||
}
|
||||
}
|
||||
if (($setup['deleteOtherNations'] ?? false) === true) {
|
||||
$keepNationIds = comparisonIntegerList($setup['keepNationIds'] ?? [], 'keepNationIds');
|
||||
if (!$keepNationIds) {
|
||||
throw new \InvalidArgumentException('deleteOtherNations requires keepNationIds');
|
||||
}
|
||||
DB::db()->query(
|
||||
'DELETE FROM diplomacy WHERE me NOT IN %li OR you NOT IN %li',
|
||||
$keepNationIds,
|
||||
$keepNationIds,
|
||||
);
|
||||
DB::db()->query('DELETE FROM nation_turn WHERE nation_id NOT IN %li', $keepNationIds);
|
||||
DB::db()->query('DELETE FROM nation WHERE nation NOT IN %li', $keepNationIds);
|
||||
}
|
||||
if (($setup['resetUniqueOccupancy'] ?? false) === true) {
|
||||
DB::db()->delete('ng_auction', '`type` = %s AND finished = 0', 'uniqueItem');
|
||||
DB::db()->query('DELETE FROM storage WHERE namespace LIKE %s', 'ut\\_%');
|
||||
}
|
||||
if (($setup['clearNeutralAuctions'] ?? false) === true) {
|
||||
DB::db()->delete(
|
||||
'ng_auction',
|
||||
'`type` IN %ls AND host_general_id = 0',
|
||||
['buyRice', 'sellRice'],
|
||||
);
|
||||
}
|
||||
foreach (comparisonIntegerList($setup['clearNationTurnIds'] ?? [], 'clearNationTurnIds') as $nationId) {
|
||||
DB::db()->delete('nation_turn', 'nation_id = %i', $nationId);
|
||||
}
|
||||
foreach (comparisonIntegerList($setup['clearInheritanceOwnerIds'] ?? [], 'clearInheritanceOwnerIds') as $ownerId) {
|
||||
DB::db()->delete('storage', 'namespace = %s', "inheritance_{$ownerId}");
|
||||
}
|
||||
if (($setup['clearBetting'] ?? false) === true) {
|
||||
DB::db()->query('DELETE FROM ng_betting');
|
||||
DB::db()->query('DELETE FROM storage WHERE namespace = %s', 'betting');
|
||||
$gameStorage = KVStorage::getStorage(DB::db(), 'game_env');
|
||||
$gameStorage->setValue('last_betting_id', 0);
|
||||
}
|
||||
foreach ($setup['bettingInfo'] ?? [] as $rawBettingInfo) {
|
||||
if (!is_array($rawBettingInfo) || !is_int($rawBettingInfo['id'] ?? null)) {
|
||||
throw new \InvalidArgumentException('invalid setup.bettingInfo row');
|
||||
}
|
||||
KVStorage::getStorage(DB::db(), 'betting')->setValue(
|
||||
"id_{$rawBettingInfo['id']}",
|
||||
$rawBettingInfo,
|
||||
);
|
||||
}
|
||||
foreach ($setup['bet'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['betting_id'] ?? null)
|
||||
|| !is_int($row['general_id'] ?? null)
|
||||
|| !is_string($row['betting_type'] ?? null)
|
||||
|| !is_int($row['amount'] ?? null)
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid setup.bet row');
|
||||
}
|
||||
DB::db()->insert('ng_betting', [
|
||||
'betting_id' => $row['betting_id'],
|
||||
'general_id' => $row['general_id'],
|
||||
'user_id' => $row['user_id'] ?? null,
|
||||
'betting_type' => $row['betting_type'],
|
||||
'amount' => $row['amount'],
|
||||
]);
|
||||
}
|
||||
foreach ($setup['inheritancePrevious'] ?? [] as $ownerId => $value) {
|
||||
if (!is_numeric($ownerId) || !is_int($value)) {
|
||||
throw new \InvalidArgumentException('invalid setup.inheritancePrevious entry');
|
||||
}
|
||||
KVStorage::getStorage(DB::db(), "inheritance_{$ownerId}")->setValue('previous', [$value, null]);
|
||||
}
|
||||
foreach ($setup['inheritancePoints'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['ownerId'] ?? null)
|
||||
|| !is_string($row['key'] ?? null)
|
||||
|| !is_numeric($row['value'] ?? null)
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid setup.inheritancePoints row');
|
||||
}
|
||||
KVStorage::getStorage(DB::db(), "inheritance_{$row['ownerId']}")->setValue(
|
||||
$row['key'],
|
||||
[$row['value'], null],
|
||||
);
|
||||
}
|
||||
foreach ($setup['rankData'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['generalId'] ?? null)
|
||||
|| !is_string($row['type'] ?? null)
|
||||
|| !is_int($row['value'] ?? null)
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid setup.rankData row');
|
||||
}
|
||||
$nationId = (int)(DB::db()->queryFirstField(
|
||||
'SELECT nation FROM general WHERE no = %i',
|
||||
$row['generalId'],
|
||||
) ?? 0);
|
||||
DB::db()->insertUpdate('rank_data', [
|
||||
'general_id' => $row['generalId'],
|
||||
'nation_id' => $nationId,
|
||||
'type' => $row['type'],
|
||||
'value' => $row['value'],
|
||||
], [
|
||||
'nation_id' => $nationId,
|
||||
'value' => $row['value'],
|
||||
]);
|
||||
}
|
||||
foreach ($setup['generalAccessLog'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['generalId'] ?? null)
|
||||
|| !is_int($row['refreshScoreTotal'] ?? null)
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid setup.generalAccessLog row');
|
||||
}
|
||||
DB::db()->insertUpdate('general_access_log', [
|
||||
'general_id' => $row['generalId'],
|
||||
'refresh_score_total' => $row['refreshScoreTotal'],
|
||||
], [
|
||||
'refresh_score_total' => $row['refreshScoreTotal'],
|
||||
]);
|
||||
}
|
||||
foreach ($setup['nationEnvironment'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['nationId'] ?? null)
|
||||
|| !is_string($row['key'] ?? null)
|
||||
|| !array_key_exists('value', $row)
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid setup.nationEnvironment row');
|
||||
}
|
||||
KVStorage::getStorage(DB::db(), $row['nationId'], 'nation_env')->setValue(
|
||||
$row['key'],
|
||||
$row['value'],
|
||||
);
|
||||
}
|
||||
if (($setup['resetDiplomacy'] ?? false) === true) {
|
||||
DB::db()->query('DELETE FROM diplomacy');
|
||||
}
|
||||
foreach ($setup['diplomacy'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['fromNationId'] ?? null)
|
||||
|| !is_int($row['toNationId'] ?? null)
|
||||
|| !is_int($row['state'] ?? null)
|
||||
|| !is_int($row['term'] ?? null)
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid setup.diplomacy row');
|
||||
}
|
||||
$diplomacyPatch = [
|
||||
'me' => $row['fromNationId'],
|
||||
'you' => $row['toNationId'],
|
||||
'state' => $row['state'],
|
||||
'term' => $row['term'],
|
||||
'dead' => $row['dead'] ?? 0,
|
||||
];
|
||||
DB::db()->insertUpdate('diplomacy', $diplomacyPatch, $diplomacyPatch);
|
||||
}
|
||||
if (($setup['resetEvents'] ?? false) === true) {
|
||||
DB::db()->query('DELETE FROM event');
|
||||
}
|
||||
foreach ($setup['event'] ?? [] as $row) {
|
||||
if (!is_array($row) || !is_int($row['id'] ?? null) || !is_array($row['action'] ?? null)) {
|
||||
throw new \InvalidArgumentException('invalid setup.event row');
|
||||
}
|
||||
$eventPatch = [
|
||||
'id' => $row['id'],
|
||||
'target' => $row['target'] ?? 'month',
|
||||
'priority' => $row['priority'] ?? 1000,
|
||||
'condition' => Json::encode($row['condition'] ?? true),
|
||||
'action' => Json::encode($row['action']),
|
||||
];
|
||||
DB::db()->insertUpdate('event', $eventPatch, $eventPatch);
|
||||
}
|
||||
$gameEnvironmentPatch = $setup['gameEnvironment'] ?? [];
|
||||
if (!is_array($gameEnvironmentPatch)) {
|
||||
throw new \InvalidArgumentException('setup.gameEnvironment must be an object');
|
||||
}
|
||||
$gameStorage = KVStorage::getStorage(DB::db(), 'game_env');
|
||||
$worldPatch = $setup['world'] ?? [];
|
||||
if (!is_array($worldPatch)) {
|
||||
throw new \InvalidArgumentException('setup.world must be an object');
|
||||
}
|
||||
if (array_key_exists('hiddenSeed', $worldPatch)) {
|
||||
if (!is_string($worldPatch['hiddenSeed']) || $worldPatch['hiddenSeed'] === '') {
|
||||
throw new \InvalidArgumentException('setup.world.hiddenSeed must be a non-empty string');
|
||||
}
|
||||
UniqueConst::$hiddenSeed = $worldPatch['hiddenSeed'];
|
||||
}
|
||||
foreach ([
|
||||
'isunited',
|
||||
'refreshLimit',
|
||||
'block_change_scout',
|
||||
'lastNPCTroopLeaderID',
|
||||
'tournament',
|
||||
'tnmt_trig',
|
||||
'tnmt_pattern',
|
||||
'prev_winner',
|
||||
] as $key) {
|
||||
if (array_key_exists($key, $gameEnvironmentPatch)) {
|
||||
$gameStorage->setValue($key, $gameEnvironmentPatch[$key]);
|
||||
}
|
||||
}
|
||||
if (($setup['setAllCitiesNation'] ?? null) !== null) {
|
||||
if (!is_int($setup['setAllCitiesNation'])) {
|
||||
throw new \InvalidArgumentException('setup.setAllCitiesNation must be an integer');
|
||||
}
|
||||
DB::db()->update('city', ['nation' => $setup['setAllCitiesNation']], true);
|
||||
}
|
||||
|
||||
$db = DB::db();
|
||||
$generalIdBeforeAction =
|
||||
(int)($db->queryFirstField('SELECT COALESCE(MAX(no), 0) FROM general') ?? 0);
|
||||
$nationIdBeforeAction =
|
||||
(int)($db->queryFirstField('SELECT COALESCE(MAX(nation), 0) FROM nation') ?? 0);
|
||||
$eventIdBeforeAction =
|
||||
(int)($db->queryFirstField('SELECT COALESCE(MAX(id), 0) FROM event') ?? 0);
|
||||
$auctionIdBeforeAction =
|
||||
(int)($db->queryFirstField('SELECT COALESCE(MAX(id), 0) FROM ng_auction') ?? 0);
|
||||
$snapshotRequest = ['observe' => $request['observe'] ?? []];
|
||||
$snapshotRequest['observe']['logAfterId'] =
|
||||
(int)($db->queryFirstField('SELECT COALESCE(MAX(id), 0) FROM general_record') ?? 0);
|
||||
$worldHistoryAfterId =
|
||||
(int)($db->queryFirstField('SELECT COALESCE(MAX(id), 0) FROM world_history') ?? 0);
|
||||
$before = comparisonTurnStateSnapshot($snapshotRequest);
|
||||
$beforeDetails = comparisonMonthlyDetails($snapshotRequest['observe'], $worldHistoryAfterId);
|
||||
|
||||
$environment = $request['environment'] ?? [];
|
||||
if (!is_array($environment)) {
|
||||
throw new \InvalidArgumentException('environment must be an object');
|
||||
}
|
||||
$year = $environment['year'] ?? null;
|
||||
$month = $environment['month'] ?? null;
|
||||
$startYear = $environment['startyear'] ?? null;
|
||||
if (!is_int($year) || !is_int($month) || !is_int($startYear)) {
|
||||
throw new \InvalidArgumentException('environment year, month, and startyear must be integers');
|
||||
}
|
||||
if (($setup['syncEnvironment'] ?? false) === true) {
|
||||
$gameStorage = KVStorage::getStorage(DB::db(), 'game_env');
|
||||
$environmentValues = [
|
||||
'year' => $year,
|
||||
'month' => $month,
|
||||
'startyear' => $startYear,
|
||||
'killturn' => $environment['killturn'] ?? $gameStorage->killturn,
|
||||
'turnterm' => $environment['turnterm'] ?? $gameStorage->turnterm,
|
||||
];
|
||||
if (isset($environment['starttime'])) {
|
||||
if (!is_string($environment['starttime']) || $environment['starttime'] === '') {
|
||||
throw new \InvalidArgumentException('environment.starttime must be a non-empty string');
|
||||
}
|
||||
$environmentValues['starttime'] = $environment['starttime'];
|
||||
}
|
||||
foreach ($environmentValues as $key => $value) {
|
||||
$gameStorage->setValue($key, $value);
|
||||
}
|
||||
if ($actionName === 'MonthlyBoundary') {
|
||||
$before = comparisonTurnStateSnapshot($snapshotRequest);
|
||||
$beforeDetails = comparisonMonthlyDetails($snapshotRequest['observe'], $worldHistoryAfterId);
|
||||
}
|
||||
}
|
||||
|
||||
if ($actionName === 'InvaderLifecycle') {
|
||||
foreach (['turnterm', 'turntime'] as $requiredEnvironmentKey) {
|
||||
if (!array_key_exists($requiredEnvironmentKey, $environment)) {
|
||||
throw new \InvalidArgumentException(
|
||||
"InvaderLifecycle requires environment.{$requiredEnvironmentKey}",
|
||||
);
|
||||
}
|
||||
}
|
||||
echo json_encode(
|
||||
comparisonInvaderLifecycleTrace(
|
||||
$request,
|
||||
$environment,
|
||||
$generalIdBeforeAction,
|
||||
$nationIdBeforeAction,
|
||||
$eventIdBeforeAction,
|
||||
$worldHistoryAfterId,
|
||||
),
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
|
||||
), PHP_EOL;
|
||||
return;
|
||||
}
|
||||
if ($actionName === 'NpcNationLifecycle') {
|
||||
foreach (['turnterm', 'turntime'] as $requiredEnvironmentKey) {
|
||||
if (!array_key_exists($requiredEnvironmentKey, $environment)) {
|
||||
throw new \InvalidArgumentException(
|
||||
"NpcNationLifecycle requires environment.{$requiredEnvironmentKey}",
|
||||
);
|
||||
}
|
||||
}
|
||||
echo json_encode(
|
||||
comparisonNpcNationLifecycleTrace(
|
||||
$environment,
|
||||
$generalIdBeforeAction,
|
||||
$nationIdBeforeAction,
|
||||
$worldHistoryAfterId,
|
||||
),
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
|
||||
), PHP_EOL;
|
||||
return;
|
||||
}
|
||||
if ($actionName === 'NationBettingLifecycle') {
|
||||
echo json_encode(
|
||||
comparisonNationBettingLifecycleTrace(
|
||||
$request,
|
||||
$environment,
|
||||
$eventIdBeforeAction,
|
||||
$worldHistoryAfterId,
|
||||
),
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
|
||||
), PHP_EOL;
|
||||
return;
|
||||
}
|
||||
|
||||
$actionClass = "\\sammo\\Event\\Action\\{$actionName}";
|
||||
if (in_array($actionName, ['PreUpdateMonthly', 'PostUpdateMonthly', 'MonthlyBoundary'], true)) {
|
||||
$action = null;
|
||||
} elseif ($actionName === 'ProcessSemiAnnual') {
|
||||
$resource = $request['resource'] ?? null;
|
||||
if (!is_string($resource)) {
|
||||
throw new \InvalidArgumentException('ProcessSemiAnnual requires resource');
|
||||
}
|
||||
$action = new $actionClass($resource);
|
||||
} elseif (in_array($actionName, ['CreateManyNPC', 'RegNPC', 'RegNeutralNPC', 'RaiseInvader', 'AutoDeleteInvader', 'ChangeCity', 'OpenNationBetting', 'FinishNationBetting', 'BlockScoutAction', 'UnblockScoutAction', 'AddGlobalBetray', 'LostUniqueItem', 'ProcessIncome', 'NoticeToHistoryLog'], true)) {
|
||||
$args = $request['args'] ?? [];
|
||||
if (!is_array($args)) {
|
||||
throw new \InvalidArgumentException("{$actionName} args must be an array");
|
||||
}
|
||||
if ($actionName === 'CreateManyNPC' && count($args) > 2) {
|
||||
throw new \InvalidArgumentException('CreateManyNPC args must have at most two entries');
|
||||
}
|
||||
if ($actionName === 'RaiseInvader' && count($args) > 4) {
|
||||
throw new \InvalidArgumentException('RaiseInvader args must have at most four entries');
|
||||
}
|
||||
if ($actionName === 'ChangeCity' && count($args) !== 2) {
|
||||
throw new \InvalidArgumentException('ChangeCity args must have exactly two entries');
|
||||
}
|
||||
if ($actionName === 'OpenNationBetting' && count($args) > 2) {
|
||||
throw new \InvalidArgumentException('OpenNationBetting args must have at most two entries');
|
||||
}
|
||||
if ($actionName === 'FinishNationBetting' && count($args) !== 1) {
|
||||
throw new \InvalidArgumentException('FinishNationBetting args must have exactly one entry');
|
||||
}
|
||||
if (in_array($actionName, ['BlockScoutAction', 'UnblockScoutAction'], true) && count($args) > 1) {
|
||||
throw new \InvalidArgumentException("{$actionName} args must have at most one entry");
|
||||
}
|
||||
if ($actionName === 'AddGlobalBetray' && count($args) > 2) {
|
||||
throw new \InvalidArgumentException('AddGlobalBetray args must have at most two entries');
|
||||
}
|
||||
if ($actionName === 'LostUniqueItem' && count($args) > 1) {
|
||||
throw new \InvalidArgumentException('LostUniqueItem args must have at most one entry');
|
||||
}
|
||||
if ($actionName === 'ProcessIncome' && count($args) !== 1) {
|
||||
throw new \InvalidArgumentException('ProcessIncome args must have exactly one entry');
|
||||
}
|
||||
if ($actionName === 'NoticeToHistoryLog' && (count($args) < 1 || count($args) > 2)) {
|
||||
throw new \InvalidArgumentException('NoticeToHistoryLog args must have one or two entries');
|
||||
}
|
||||
$action = new $actionClass(...$args);
|
||||
} else {
|
||||
$action = new $actionClass();
|
||||
}
|
||||
$actionEnvironment = [
|
||||
'year' => $year,
|
||||
'month' => $month,
|
||||
'startyear' => $startYear,
|
||||
];
|
||||
if (isset($environment['currentEventID'])) {
|
||||
if (!is_int($environment['currentEventID'])) {
|
||||
throw new \InvalidArgumentException('currentEventID must be an integer');
|
||||
}
|
||||
$actionEnvironment['currentEventID'] = $environment['currentEventID'];
|
||||
}
|
||||
if ($actionName === 'UpdateNationLevel') {
|
||||
$killturn = $environment['killturn'] ?? null;
|
||||
$turnterm = $environment['turnterm'] ?? null;
|
||||
if (!is_int($killturn) || !is_int($turnterm) || $turnterm <= 0) {
|
||||
throw new \InvalidArgumentException('UpdateNationLevel requires integer killturn and positive turnterm');
|
||||
}
|
||||
$actionEnvironment['killturn'] = $killturn;
|
||||
$actionEnvironment['turnterm'] = $turnterm;
|
||||
}
|
||||
if (in_array($actionName, ['CreateManyNPC', 'RegNPC', 'RegNeutralNPC', 'RaiseNPCNation', 'RaiseInvader', 'ProvideNPCTroopLeader'], true)) {
|
||||
$turnterm = $environment['turnterm'] ?? null;
|
||||
$turntime = $environment['turntime'] ?? null;
|
||||
$showImgLevel = $environment['show_img_level'] ?? 3;
|
||||
$fiction = $environment['fiction'] ?? [0];
|
||||
if (
|
||||
!is_int($turnterm)
|
||||
|| $turnterm <= 0
|
||||
|| !is_string($turntime)
|
||||
|| !is_int($showImgLevel)
|
||||
|| !is_array($fiction)
|
||||
) {
|
||||
throw new \InvalidArgumentException(
|
||||
"{$actionName} requires positive turnterm, string turntime, integer show_img_level, and array fiction",
|
||||
);
|
||||
}
|
||||
$actionEnvironment += [
|
||||
'turnterm' => $turnterm,
|
||||
'turntime' => $turntime,
|
||||
'show_img_level' => $showImgLevel,
|
||||
'stored_icons' => $environment['stored_icons'] ?? [],
|
||||
'icon_path' => $environment['icon_path'] ?? '.',
|
||||
'fiction' => $fiction,
|
||||
];
|
||||
}
|
||||
if ($actionName === 'PreUpdateMonthly') {
|
||||
if (!preUpdateMonthly()) {
|
||||
throw new \RuntimeException('preUpdateMonthly failed');
|
||||
}
|
||||
} elseif ($actionName === 'PostUpdateMonthly') {
|
||||
$seedYear = $environment['seedYear'] ?? null;
|
||||
$seedMonth = $environment['seedMonth'] ?? null;
|
||||
if (!is_int($seedYear) || !is_int($seedMonth)) {
|
||||
throw new \InvalidArgumentException('PostUpdateMonthly requires seedYear and seedMonth');
|
||||
}
|
||||
postUpdateMonthly(new RandUtil(new LiteHashDRBG(Util::simpleSerialize(
|
||||
UniqueConst::$hiddenSeed,
|
||||
'monthly',
|
||||
$seedYear,
|
||||
$seedMonth,
|
||||
))));
|
||||
} elseif ($actionName === 'MonthlyBoundary') {
|
||||
$turntime = $environment['turntime'] ?? null;
|
||||
if (!is_string($turntime) || $turntime === '') {
|
||||
throw new \InvalidArgumentException('MonthlyBoundary requires turntime');
|
||||
}
|
||||
$gameStorage = KVStorage::getStorage($db, 'game_env');
|
||||
$seedYear = (int)$gameStorage->year;
|
||||
$seedMonth = (int)$gameStorage->month;
|
||||
TurnExecutionHelper::runEventHandler($db, $gameStorage, Enums\EventTarget::PreMonth);
|
||||
if (!preUpdateMonthly()) {
|
||||
throw new \RuntimeException('preUpdateMonthly failed');
|
||||
}
|
||||
turnDate($turntime);
|
||||
$gameStorage->resetCache();
|
||||
if ((int)$gameStorage->month === 1) {
|
||||
checkStatistic();
|
||||
}
|
||||
TurnExecutionHelper::runEventHandler($db, $gameStorage, Enums\EventTarget::Month);
|
||||
postUpdateMonthly(new RandUtil(new LiteHashDRBG(Util::simpleSerialize(
|
||||
UniqueConst::$hiddenSeed,
|
||||
'monthly',
|
||||
$seedYear,
|
||||
$seedMonth,
|
||||
))));
|
||||
} else {
|
||||
$action->run($actionEnvironment);
|
||||
}
|
||||
unset($action);
|
||||
gc_collect_cycles();
|
||||
|
||||
$after = comparisonTurnStateSnapshot($snapshotRequest);
|
||||
$afterDetails = comparisonMonthlyDetails($snapshotRequest['observe'], $worldHistoryAfterId);
|
||||
$createdGenerals = [];
|
||||
if (in_array($actionName, ['CreateManyNPC', 'RegNPC', 'RegNeutralNPC', 'RaiseNPCNation', 'RaiseInvader', 'ProvideNPCTroopLeader'], true)) {
|
||||
foreach ($db->query('SELECT * FROM general WHERE no > %i ORDER BY no', $generalIdBeforeAction) as $row) {
|
||||
$generalId = (int)$row['no'];
|
||||
$turnRows = $db->query(
|
||||
'SELECT turn_idx, action, arg FROM general_turn WHERE general_id = %i ORDER BY turn_idx',
|
||||
$generalId,
|
||||
);
|
||||
$createdGenerals[] = comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'no',
|
||||
'name' => 'name',
|
||||
'nationId' => 'nation',
|
||||
'cityId' => 'city',
|
||||
'leadership' => 'leadership',
|
||||
'strength' => 'strength',
|
||||
'intelligence' => 'intel',
|
||||
'experience' => 'experience',
|
||||
'dedication' => 'dedication',
|
||||
'officerLevel' => 'officer_level',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'crew' => 'crew',
|
||||
'crewTypeId' => 'crewtype',
|
||||
'train' => 'train',
|
||||
'atmos' => 'atmos',
|
||||
'turnTime' => 'turntime',
|
||||
'killturn' => 'killturn',
|
||||
'age' => 'age',
|
||||
'npcState' => 'npc',
|
||||
'npcOriginalState' => 'npc_org',
|
||||
'affinity' => 'affinity',
|
||||
'personality' => 'personal',
|
||||
'specialDomestic' => 'special',
|
||||
'specialWar' => 'special2',
|
||||
'specAge' => 'specage',
|
||||
'specAge2' => 'specage2',
|
||||
'bornYear' => 'bornyear',
|
||||
'deadYear' => 'deadyear',
|
||||
'picture' => 'picture',
|
||||
'dex1' => 'dex1',
|
||||
'dex2' => 'dex2',
|
||||
'dex3' => 'dex3',
|
||||
'dex4' => 'dex4',
|
||||
'dex5' => 'dex5',
|
||||
],
|
||||
) + [
|
||||
'turnCount' => count($turnRows),
|
||||
'turnActions' => array_values(array_unique(array_column($turnRows, 'action'))),
|
||||
'rankCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM rank_data WHERE general_id = %i',
|
||||
$generalId,
|
||||
),
|
||||
'nonZeroRankCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM rank_data WHERE general_id = %i AND value != 0',
|
||||
$generalId,
|
||||
),
|
||||
'troop' => $db->queryFirstRow(
|
||||
'SELECT troop_leader AS id, nation AS nationId, name FROM troop WHERE troop_leader = %i',
|
||||
$generalId,
|
||||
) ?: null,
|
||||
];
|
||||
}
|
||||
}
|
||||
$createdNations = [];
|
||||
if (in_array($actionName, ['RaiseNPCNation', 'RaiseInvader'], true)) {
|
||||
foreach ($db->query('SELECT * FROM nation WHERE nation > %i ORDER BY nation', $nationIdBeforeAction) as $row) {
|
||||
$nationId = (int)$row['nation'];
|
||||
$createdNations[] = comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'nation',
|
||||
'name' => 'name',
|
||||
'color' => 'color',
|
||||
'capitalCityId' => 'capital',
|
||||
'generalCount' => 'gennum',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'tech' => 'tech',
|
||||
'level' => 'level',
|
||||
'typeCode' => 'type',
|
||||
'bill' => 'bill',
|
||||
'rate' => 'rate',
|
||||
'scout' => 'scout',
|
||||
'war' => 'war',
|
||||
'strategicCommandLimit' => 'strategic_cmd_limit',
|
||||
'surrenderLimit' => 'surlimit',
|
||||
'aux' => 'aux',
|
||||
],
|
||||
['aux'],
|
||||
) + [
|
||||
'nationTurnCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM nation_turn WHERE nation_id = %i',
|
||||
$nationId,
|
||||
),
|
||||
'diplomacyCount' => (int)$db->queryFirstField(
|
||||
'SELECT count(*) FROM diplomacy WHERE me = %i OR you = %i',
|
||||
$nationId,
|
||||
$nationId,
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
$response = [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'action' => $actionName,
|
||||
'before' => $before,
|
||||
'beforeDetails' => $beforeDetails,
|
||||
'after' => $after,
|
||||
'afterDetails' => $afterDetails,
|
||||
];
|
||||
if (in_array($actionName, ['CreateManyNPC', 'RegNPC', 'RegNeutralNPC'], true)) {
|
||||
$response['createdGenerals'] = $createdGenerals;
|
||||
}
|
||||
if (in_array($actionName, ['RaiseNPCNation', 'RaiseInvader'], true)) {
|
||||
$response['createdGenerals'] = $createdGenerals;
|
||||
$response['createdNations'] = $createdNations;
|
||||
}
|
||||
if ($actionName === 'ProvideNPCTroopLeader') {
|
||||
$response['createdGenerals'] = $createdGenerals;
|
||||
$response['gameEnvironment'] = KVStorage::getStorage(DB::db(), 'game_env')->getValues([
|
||||
'lastNPCTroopLeaderID',
|
||||
]);
|
||||
}
|
||||
if ($actionName === 'PreUpdateMonthly') {
|
||||
$response['gameEnvironment'] = KVStorage::getStorage(DB::db(), 'game_env')->getValues([
|
||||
'develcost',
|
||||
]);
|
||||
}
|
||||
if ($actionName === 'PostUpdateMonthly') {
|
||||
$response['gameEnvironment'] = KVStorage::getStorage(DB::db(), 'game_env')->getValues([
|
||||
'tournament',
|
||||
'tnmt_trig',
|
||||
'tnmt_pattern',
|
||||
'tnmt_type',
|
||||
'tnmt_auto',
|
||||
'phase',
|
||||
]);
|
||||
$response['createdNeutralAuctions'] = array_map(
|
||||
static fn(array $row): array => [
|
||||
'id' => (int)$row['id'],
|
||||
'type' => $row['type'],
|
||||
'target' => $row['target'],
|
||||
'detail' => Json::decode($row['detail']),
|
||||
],
|
||||
iterator_to_array(
|
||||
$db->query(
|
||||
'SELECT id, `type`, target, detail FROM ng_auction WHERE id > %i AND host_general_id = 0 ORDER BY id',
|
||||
$auctionIdBeforeAction,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (in_array($actionName, ['OpenNationBetting', 'FinishNationBetting'], true)) {
|
||||
$bettingStorage = KVStorage::getStorage(DB::db(), 'betting');
|
||||
$response['betting'] = $bettingStorage->getAll();
|
||||
$response['bets'] = iterator_to_array(
|
||||
$db->query(
|
||||
'SELECT betting_id AS bettingId, general_id AS generalId, user_id AS userId, betting_type AS selectionKey, amount FROM ng_betting ORDER BY id',
|
||||
),
|
||||
);
|
||||
$response['createdEvents'] = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'id',
|
||||
'targetCode' => 'target',
|
||||
'priority' => 'priority',
|
||||
'condition' => 'condition',
|
||||
'action' => 'action',
|
||||
],
|
||||
['condition', 'action'],
|
||||
),
|
||||
iterator_to_array(
|
||||
$db->query(
|
||||
'SELECT id, target, priority, `condition`, action FROM event WHERE id > %i ORDER BY id',
|
||||
$eventIdBeforeAction,
|
||||
),
|
||||
),
|
||||
);
|
||||
$response['gameEnvironment'] = KVStorage::getStorage(DB::db(), 'game_env')->getValues([
|
||||
'last_betting_id',
|
||||
]);
|
||||
$response['inheritancePrevious'] = [];
|
||||
foreach (comparisonIntegerList($request['observe']['ownerIds'] ?? [], 'ownerIds') as $ownerId) {
|
||||
$value = KVStorage::getStorage(DB::db(), "inheritance_{$ownerId}")->getValue('previous');
|
||||
$response['inheritancePrevious'][(string)$ownerId] = is_array($value) ? ($value[0] ?? 0) : 0;
|
||||
}
|
||||
}
|
||||
if (in_array($actionName, ['BlockScoutAction', 'UnblockScoutAction'], true)) {
|
||||
$response['gameEnvironment'] = KVStorage::getStorage(DB::db(), 'game_env')->getValues([
|
||||
'block_change_scout',
|
||||
]);
|
||||
}
|
||||
if ($actionName === 'RaiseInvader') {
|
||||
$response['createdEvents'] = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'id',
|
||||
'targetCode' => 'target',
|
||||
'priority' => 'priority',
|
||||
'condition' => 'condition',
|
||||
'action' => 'action',
|
||||
],
|
||||
['condition', 'action'],
|
||||
),
|
||||
iterator_to_array(
|
||||
$db->query(
|
||||
'SELECT id, target, priority, `condition`, action FROM event WHERE id > %i ORDER BY id',
|
||||
$eventIdBeforeAction,
|
||||
),
|
||||
),
|
||||
);
|
||||
$response['createdDiplomacy'] = iterator_to_array(
|
||||
$db->query(
|
||||
'SELECT me AS fromNationId, you AS toNationId, state, term FROM diplomacy WHERE me > %i OR you > %i ORDER BY me, you',
|
||||
$nationIdBeforeAction,
|
||||
$nationIdBeforeAction,
|
||||
),
|
||||
);
|
||||
$gameStorage = KVStorage::getStorage(DB::db(), 'game_env');
|
||||
$response['gameEnvironment'] = $gameStorage->getValues([
|
||||
'isunited',
|
||||
'turnterm',
|
||||
'block_change_scout',
|
||||
'refreshLimit',
|
||||
]);
|
||||
}
|
||||
if (in_array($actionName, ['AutoDeleteInvader', 'InvaderEnding'], true)) {
|
||||
$gameStorage = KVStorage::getStorage(DB::db(), 'game_env');
|
||||
$response['gameEnvironment'] = $gameStorage->getValues([
|
||||
'isunited',
|
||||
'turnterm',
|
||||
'block_change_scout',
|
||||
'refreshLimit',
|
||||
]);
|
||||
}
|
||||
if (($request['compactOutput'] ?? false) === true) {
|
||||
$observedGeneralTurns = [];
|
||||
foreach (comparisonIntegerList($request['observe']['generalIds'] ?? [], 'generalIds') as $generalId) {
|
||||
$observedGeneralTurns[(string)$generalId] = iterator_to_array(
|
||||
$db->query(
|
||||
'SELECT turn_idx AS turnIndex, action, arg FROM general_turn WHERE general_id = %i ORDER BY turn_idx',
|
||||
$generalId,
|
||||
),
|
||||
);
|
||||
}
|
||||
$response = [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'action' => $actionName,
|
||||
'afterDetails' => $afterDetails,
|
||||
'createdGeneralCount' => count($createdGenerals),
|
||||
'firstCreatedGenerals' => array_slice($createdGenerals, 0, 3),
|
||||
'createdNations' => $response['createdNations'] ?? [],
|
||||
'createdEvents' => $response['createdEvents'] ?? [],
|
||||
'createdDiplomacy' => $response['createdDiplomacy'] ?? [],
|
||||
'gameEnvironment' => $response['gameEnvironment'] ?? [],
|
||||
'logs' => $after['logs'],
|
||||
'observedGeneralTurns' => $observedGeneralTurns,
|
||||
'remainingEventIds' => array_map(
|
||||
'intval',
|
||||
$db->queryFirstColumn('SELECT id FROM event ORDER BY id'),
|
||||
),
|
||||
];
|
||||
}
|
||||
echo json_encode(
|
||||
$response,
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
|
||||
), PHP_EOL;
|
||||
} catch (\Throwable $throwable) {
|
||||
fwrite(STDERR, $throwable::class . ': ' . $throwable->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
comparisonMonthlyEventTraceMain();
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace sammo;
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
chdir(dirname(__DIR__));
|
||||
require_once 'lib.php';
|
||||
require_once 'func.php';
|
||||
|
||||
$groups = [
|
||||
'nation' => ['ActionNationType', 'ActionNationType'],
|
||||
'domestic' => ['ActionSpecialDomestic', 'ActionSpecialDomestic'],
|
||||
'war' => ['ActionSpecialWar', 'ActionSpecialWar'],
|
||||
'personality' => ['ActionPersonality', 'ActionPersonality'],
|
||||
];
|
||||
|
||||
$result = [];
|
||||
foreach ($groups as $kind => [$directory, $namespace]) {
|
||||
foreach (glob(__DIR__ . "/../sammo/{$directory}/*.php") ?: [] as $path) {
|
||||
$key = basename($path, '.php');
|
||||
if ($key === 'None' || str_starts_with($key, 'che_event_') || $key === 'che_거상') {
|
||||
continue;
|
||||
}
|
||||
$className = "\\sammo\\{$namespace}\\{$key}";
|
||||
$trait = new $className();
|
||||
$result[$kind][$key] = [
|
||||
'name' => $trait->getName(),
|
||||
'info' => $trait->getInfo(),
|
||||
];
|
||||
}
|
||||
ksort($result[$kind]);
|
||||
}
|
||||
|
||||
echo Json::encode($result);
|
||||
@@ -0,0 +1,804 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace sammo;
|
||||
|
||||
use sammo\Enums\RankColumn;
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
chdir(dirname(__DIR__));
|
||||
$_SERVER['REMOTE_ADDR'] ??= '127.0.0.1';
|
||||
error_reporting(E_ALL & ~E_DEPRECATED);
|
||||
require_once 'lib.php';
|
||||
require_once 'func.php';
|
||||
require_once __DIR__ . '/turn_state_snapshot.php';
|
||||
|
||||
final class TurnComparisonTracingRNG implements RNG
|
||||
{
|
||||
private int $sequence = 0;
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $calls = [];
|
||||
|
||||
public function __construct(private readonly RNG $inner)
|
||||
{
|
||||
}
|
||||
|
||||
public static function getMaxInt(): int
|
||||
{
|
||||
return LiteHashDRBG::getMaxInt();
|
||||
}
|
||||
|
||||
public function nextBytes(int $bytes): string
|
||||
{
|
||||
$value = $this->inner->nextBytes($bytes);
|
||||
$this->record('nextBytes', ['bytes' => $bytes], bin2hex($value));
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function nextBits(int $bits): string
|
||||
{
|
||||
$value = $this->inner->nextBits($bits);
|
||||
$this->record('nextBits', ['bits' => $bits], bin2hex($value));
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function nextInt(?int $max = null): int
|
||||
{
|
||||
$value = $this->inner->nextInt($max);
|
||||
$this->record('nextInt', ['maxInclusive' => $max], $value);
|
||||
return $value;
|
||||
}
|
||||
|
||||
public function nextFloat1(): float
|
||||
{
|
||||
$value = $this->inner->nextFloat1();
|
||||
$this->record('nextFloat1', [], $value);
|
||||
return $value;
|
||||
}
|
||||
|
||||
private function record(string $operation, array $arguments, mixed $result): void
|
||||
{
|
||||
$this->calls[] = [
|
||||
'seq' => $this->sequence++,
|
||||
'operation' => $operation,
|
||||
'arguments' => $arguments === [] ? (object)[] : $arguments,
|
||||
'result' => $result,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
function comparisonMappedPatch(array $row, array $mapping): array
|
||||
{
|
||||
$patch = [];
|
||||
foreach ($mapping as $canonical => $legacy) {
|
||||
if (array_key_exists($canonical, $row)) {
|
||||
$patch[$legacy] = $row[$canonical];
|
||||
}
|
||||
}
|
||||
return $patch;
|
||||
}
|
||||
|
||||
function comparisonApplyTurnFixtureSetup(mixed $setup): void
|
||||
{
|
||||
if ($setup === null) {
|
||||
return;
|
||||
}
|
||||
if (!is_array($setup)) {
|
||||
throw new \InvalidArgumentException('setup must be an object');
|
||||
}
|
||||
$db = DB::db();
|
||||
$world = $setup['world'] ?? null;
|
||||
if ($world !== null) {
|
||||
if (!is_array($world)) {
|
||||
throw new \InvalidArgumentException('setup.world must be an object');
|
||||
}
|
||||
$game = KVStorage::getStorage($db, 'game_env');
|
||||
foreach (['year', 'month', 'startyear', 'init_year', 'init_month'] as $key) {
|
||||
$fixtureKey = match ($key) {
|
||||
'startyear' => 'startYear',
|
||||
'init_year' => 'initYear',
|
||||
'init_month' => 'initMonth',
|
||||
default => $key,
|
||||
};
|
||||
if (!array_key_exists($fixtureKey, $world)) {
|
||||
continue;
|
||||
}
|
||||
$value = $world[$fixtureKey];
|
||||
if (
|
||||
!is_int($value)
|
||||
|| $value < 1
|
||||
|| (in_array($key, ['month', 'init_month'], true) && $value > 12)
|
||||
) {
|
||||
throw new \InvalidArgumentException("setup.world.{$fixtureKey} is invalid");
|
||||
}
|
||||
$game->setValue($key, $value);
|
||||
}
|
||||
$game->resetCache();
|
||||
if (array_key_exists('hiddenSeed', $world)) {
|
||||
$hiddenSeed = $world['hiddenSeed'];
|
||||
if (!is_string($hiddenSeed) || $hiddenSeed === '' || strlen($hiddenSeed) > 256) {
|
||||
throw new \InvalidArgumentException('setup.world.hiddenSeed is invalid');
|
||||
}
|
||||
UniqueConst::$hiddenSeed = $hiddenSeed;
|
||||
}
|
||||
// 비교 fixture는 전역 상태에 의존하지 않도록 effect 기본값을 null로 고정하고,
|
||||
// 명시된 경우에만 해당 effect를 활성화합니다.
|
||||
GameConst::$scenarioEffect = null;
|
||||
if (array_key_exists('scenarioEffect', $world)) {
|
||||
$scenarioEffect = $world['scenarioEffect'];
|
||||
if ($scenarioEffect === '' || $scenarioEffect === 'None') {
|
||||
$scenarioEffect = null;
|
||||
}
|
||||
if ($scenarioEffect !== null) {
|
||||
if (!is_string($scenarioEffect) || getScenarioEffectClass($scenarioEffect) === null) {
|
||||
throw new \InvalidArgumentException('setup.world.scenarioEffect is invalid');
|
||||
}
|
||||
}
|
||||
GameConst::$scenarioEffect = $scenarioEffect;
|
||||
}
|
||||
if (array_key_exists('staticEventHandlers', $world)) {
|
||||
$handlersByEvent = $world['staticEventHandlers'];
|
||||
if (!is_array($handlersByEvent)) {
|
||||
throw new \InvalidArgumentException('setup.world.staticEventHandlers must be an object');
|
||||
}
|
||||
foreach ($handlersByEvent as $eventType => $handlers) {
|
||||
if (!is_string($eventType) || $eventType === '' || !is_array($handlers)) {
|
||||
throw new \InvalidArgumentException('setup.world.staticEventHandlers is invalid');
|
||||
}
|
||||
foreach ($handlers as $handler) {
|
||||
if (!is_string($handler) || $handler === '') {
|
||||
throw new \InvalidArgumentException('setup.world.staticEventHandlers is invalid');
|
||||
}
|
||||
}
|
||||
}
|
||||
GameConst::$staticEventHandlers = $handlersByEvent;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (['nations', 'cities', 'generals', 'troops', 'diplomacy'] as $collection) {
|
||||
if (isset($setup[$collection]) && !is_array($setup[$collection])) {
|
||||
throw new \InvalidArgumentException("setup.{$collection} must be an array");
|
||||
}
|
||||
}
|
||||
$generalCooldowns = comparisonGeneralCooldownSelectors(
|
||||
$setup['generalCooldowns'] ?? [],
|
||||
'setup.generalCooldowns',
|
||||
);
|
||||
if ($generalCooldowns !== []) {
|
||||
$nextExecuteStorage = KVStorage::getStorage($db, 'next_execute');
|
||||
foreach ($setup['generalCooldowns'] as $entry) {
|
||||
$nextAvailableTurn = $entry['nextAvailableTurn'] ?? null;
|
||||
if (!is_int($nextAvailableTurn) || $nextAvailableTurn < 0) {
|
||||
throw new \InvalidArgumentException(
|
||||
'setup.generalCooldowns entries require a non-negative nextAvailableTurn',
|
||||
);
|
||||
}
|
||||
$key = "next_execute_{$entry['generalId']}_{$entry['actionName']}";
|
||||
$nextExecuteStorage->setValue($key, $nextAvailableTurn);
|
||||
}
|
||||
$nextExecuteStorage->resetCache();
|
||||
}
|
||||
if (isset($setup['randomFoundingCandidateCityIds'])) {
|
||||
$candidateCityIds = comparisonIntegerList(
|
||||
$setup['randomFoundingCandidateCityIds'],
|
||||
'randomFoundingCandidateCityIds',
|
||||
);
|
||||
$db->update('city', ['level' => 4], '1 = 1');
|
||||
if ($candidateCityIds !== []) {
|
||||
$db->update('city', ['level' => 5], 'city IN %li', $candidateCityIds);
|
||||
}
|
||||
}
|
||||
|
||||
if (($setup['isolateWorld'] ?? false) === true) {
|
||||
$generalIds = array_values(array_map(
|
||||
static fn(array $row): int => (int)$row['id'],
|
||||
$setup['generals'] ?? [],
|
||||
));
|
||||
$nationIds = array_values(array_map(
|
||||
static fn(array $row): int => (int)$row['id'],
|
||||
$setup['nations'] ?? [],
|
||||
));
|
||||
if ($generalIds === [] || $nationIds === []) {
|
||||
throw new \InvalidArgumentException('isolateWorld requires generals and nations');
|
||||
}
|
||||
$generalTemplate = $db->queryFirstRow(
|
||||
'SELECT * FROM general WHERE no IN %li ORDER BY no LIMIT 1',
|
||||
$generalIds,
|
||||
);
|
||||
if ($generalTemplate === null) {
|
||||
throw new \InvalidArgumentException('isolateWorld requires at least one existing fixture general');
|
||||
}
|
||||
$generalTemplateId = (int)$generalTemplate['no'];
|
||||
$rankDataTemplate = $db->query(
|
||||
'SELECT `type`, `value` FROM rank_data WHERE general_id = %i',
|
||||
$generalTemplateId,
|
||||
);
|
||||
$db->delete('general_turn', 'general_id NOT IN %li', $generalIds);
|
||||
$db->delete('rank_data', 'general_id NOT IN %li', $generalIds);
|
||||
$db->delete('nation_turn', 'nation_id NOT IN %li', $nationIds);
|
||||
$db->delete('troop', '1 = 1');
|
||||
$db->delete('diplomacy', '1 = 1');
|
||||
$db->delete('general', 'no NOT IN %li', $generalIds);
|
||||
foreach ($generalIds as $generalId) {
|
||||
if ($db->queryFirstField('SELECT no FROM general WHERE no = %i', $generalId) !== null) {
|
||||
continue;
|
||||
}
|
||||
$newGeneral = $generalTemplate;
|
||||
$newGeneral['no'] = $generalId;
|
||||
$newGeneral['owner'] = 0;
|
||||
$newGeneral['name'] = "fixture-general-{$generalId}";
|
||||
$db->insert('general', $newGeneral);
|
||||
}
|
||||
foreach ($generalIds as $generalId) {
|
||||
foreach ($rankDataTemplate as $rankRow) {
|
||||
$rankData = [
|
||||
'general_id' => $generalId,
|
||||
'type' => $rankRow['type'],
|
||||
'value' => $rankRow['value'],
|
||||
];
|
||||
$db->insertUpdate('rank_data', $rankData, $rankData);
|
||||
}
|
||||
}
|
||||
$db->delete('nation', 'nation NOT IN %li', $nationIds);
|
||||
$db->update('city', [
|
||||
'nation' => 0,
|
||||
'supply' => 0,
|
||||
'front' => 0,
|
||||
'state' => 0,
|
||||
'term' => 0,
|
||||
'conflict' => '{}',
|
||||
'officer_set' => 0,
|
||||
], '1 = 1');
|
||||
}
|
||||
|
||||
foreach ($setup['nations'] ?? [] as $row) {
|
||||
if (!is_array($row) || !is_int($row['id'] ?? null) || $row['id'] < 1) {
|
||||
throw new \InvalidArgumentException('setup.nations requires positive integer ids');
|
||||
}
|
||||
$data = comparisonMappedPatch($row, [
|
||||
'id' => 'nation',
|
||||
'name' => 'name',
|
||||
'color' => 'color',
|
||||
'capitalCityId' => 'capital',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'tech' => 'tech',
|
||||
'level' => 'level',
|
||||
'typeCode' => 'type',
|
||||
'war' => 'war',
|
||||
'diplomacyLimit' => 'surlimit',
|
||||
'generalCount' => 'gennum',
|
||||
'power' => 'power',
|
||||
'capitalRevision' => 'capset',
|
||||
'strategicCommandLimit' => 'strategic_cmd_limit',
|
||||
]);
|
||||
if (isset($row['meta'])) {
|
||||
$data['aux'] = Json::encode($row['meta']);
|
||||
}
|
||||
$data += [
|
||||
'name' => "fixture-nation-{$row['id']}",
|
||||
'color' => '#777777',
|
||||
'capital' => 0,
|
||||
'gold' => 0,
|
||||
'rice' => 0,
|
||||
'level' => 1,
|
||||
'type' => 'che_중립',
|
||||
'aux' => '{}',
|
||||
];
|
||||
$db->insertUpdate('nation', $data, $data);
|
||||
$nationStor = KVStorage::getStorage($db, $row['id'], 'nation_env');
|
||||
if (($setup['isolateWorld'] ?? false) === true) {
|
||||
$nationStor->deleteValue('recv_assist');
|
||||
$nationStor->deleteValue('resp_assist');
|
||||
}
|
||||
if (array_key_exists('nationEnv', $row)) {
|
||||
if (!is_array($row['nationEnv'])) {
|
||||
throw new \InvalidArgumentException('setup.nations.nationEnv must be an object');
|
||||
}
|
||||
foreach ($row['nationEnv'] as $key => $value) {
|
||||
if (!is_string($key) || $key === '') {
|
||||
throw new \InvalidArgumentException('setup.nations.nationEnv keys must be non-empty strings');
|
||||
}
|
||||
$nationStor->setValue($key, $value);
|
||||
}
|
||||
$nationStor->resetCache();
|
||||
}
|
||||
if (array_key_exists('turnLastByOfficerLevel', $row)) {
|
||||
$turnLastByOfficerLevel = $row['turnLastByOfficerLevel'];
|
||||
if (!is_array($turnLastByOfficerLevel)) {
|
||||
throw new \InvalidArgumentException('setup.nations.turnLastByOfficerLevel must be an object');
|
||||
}
|
||||
foreach ($turnLastByOfficerLevel as $officerLevel => $lastTurn) {
|
||||
$officerLevel = filter_var($officerLevel, FILTER_VALIDATE_INT);
|
||||
if (
|
||||
$officerLevel === false
|
||||
|| $officerLevel < 5
|
||||
|| $officerLevel > 12
|
||||
|| !is_array($lastTurn)
|
||||
) {
|
||||
throw new \InvalidArgumentException(
|
||||
'setup.nations.turnLastByOfficerLevel requires officer levels 5 through 12'
|
||||
);
|
||||
}
|
||||
$nationStor->setValue("turn_last_{$officerLevel}", $lastTurn);
|
||||
}
|
||||
$nationStor->resetCache();
|
||||
}
|
||||
}
|
||||
if (($setup['isolateWorld'] ?? false) === true && ($setup['nations'] ?? []) !== []) {
|
||||
$maxNationId = max(array_map(
|
||||
static fn(array $row): int => (int)$row['id'],
|
||||
$setup['nations'],
|
||||
));
|
||||
$db->query('ALTER TABLE nation AUTO_INCREMENT = %i', $maxNationId + 1);
|
||||
}
|
||||
|
||||
foreach ($setup['cities'] ?? [] as $row) {
|
||||
if (!is_array($row) || !is_int($row['id'] ?? null) || $row['id'] < 1) {
|
||||
throw new \InvalidArgumentException('setup.cities requires positive integer ids');
|
||||
}
|
||||
$patch = comparisonMappedPatch($row, [
|
||||
'nationId' => 'nation',
|
||||
'level' => 'level',
|
||||
'population' => 'pop',
|
||||
'populationMax' => 'pop_max',
|
||||
'agriculture' => 'agri',
|
||||
'agricultureMax' => 'agri_max',
|
||||
'commerce' => 'comm',
|
||||
'commerceMax' => 'comm_max',
|
||||
'security' => 'secu',
|
||||
'securityMax' => 'secu_max',
|
||||
'supplyState' => 'supply',
|
||||
'frontState' => 'front',
|
||||
'defence' => 'def',
|
||||
'defenceMax' => 'def_max',
|
||||
'wall' => 'wall',
|
||||
'wallMax' => 'wall_max',
|
||||
'state' => 'state',
|
||||
'term' => 'term',
|
||||
'trust' => 'trust',
|
||||
'trade' => 'trade',
|
||||
'officerSet' => 'officer_set',
|
||||
]);
|
||||
if (array_key_exists('conflictEntries', $row)) {
|
||||
if (!is_array($row['conflictEntries'])) {
|
||||
throw new \InvalidArgumentException('setup.cities.conflictEntries must be an array');
|
||||
}
|
||||
$orderedConflict = [];
|
||||
foreach ($row['conflictEntries'] as $entry) {
|
||||
if (
|
||||
!is_array($entry)
|
||||
|| count($entry) !== 2
|
||||
|| !is_int($entry[0] ?? null)
|
||||
|| $entry[0] < 1
|
||||
|| !is_numeric($entry[1] ?? null)
|
||||
) {
|
||||
throw new \InvalidArgumentException(
|
||||
'setup.cities.conflictEntries requires [positive nation id, numeric value] pairs'
|
||||
);
|
||||
}
|
||||
$orderedConflict[$entry[0]] = $entry[1];
|
||||
}
|
||||
$patch['conflict'] = Json::encode($orderedConflict);
|
||||
} elseif (array_key_exists('conflict', $row)) {
|
||||
if (!is_array($row['conflict'])) {
|
||||
throw new \InvalidArgumentException('setup.cities.conflict must be an object');
|
||||
}
|
||||
$patch['conflict'] = Json::encode($row['conflict']);
|
||||
}
|
||||
if ($patch !== []) {
|
||||
$db->update('city', $patch, 'city = %i', $row['id']);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($setup['generals'] ?? [] as $row) {
|
||||
if (!is_array($row) || !is_int($row['id'] ?? null) || $row['id'] < 1) {
|
||||
throw new \InvalidArgumentException('setup.generals requires positive integer ids');
|
||||
}
|
||||
$patch = comparisonMappedPatch($row, [
|
||||
'name' => 'name',
|
||||
'nationId' => 'nation',
|
||||
'cityId' => 'city',
|
||||
'troopId' => 'troop',
|
||||
'leadership' => 'leadership',
|
||||
'strength' => 'strength',
|
||||
'intelligence' => 'intel',
|
||||
'leadershipExp' => 'leadership_exp',
|
||||
'strengthExp' => 'strength_exp',
|
||||
'intelExp' => 'intel_exp',
|
||||
'experience' => 'experience',
|
||||
'dedication' => 'dedication',
|
||||
'expLevel' => 'explevel',
|
||||
'officerLevel' => 'officer_level',
|
||||
'officerCityId' => 'officer_city',
|
||||
'belong' => 'belong',
|
||||
'permission' => 'permission',
|
||||
'betray' => 'betray',
|
||||
'makeLimit' => 'makelimit',
|
||||
'injury' => 'injury',
|
||||
'age' => 'age',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'crew' => 'crew',
|
||||
'crewTypeId' => 'crewtype',
|
||||
'train' => 'train',
|
||||
'atmos' => 'atmos',
|
||||
'dex1' => 'dex1',
|
||||
'dex2' => 'dex2',
|
||||
'dex3' => 'dex3',
|
||||
'dex4' => 'dex4',
|
||||
'dex5' => 'dex5',
|
||||
'specAge' => 'specage',
|
||||
'specAge2' => 'specage2',
|
||||
'killTurn' => 'killturn',
|
||||
'npcState' => 'npc',
|
||||
'blockState' => 'block',
|
||||
'specialDomestic' => 'special',
|
||||
'specialWar' => 'special2',
|
||||
'personality' => 'personal',
|
||||
'itemHorse' => 'horse',
|
||||
'itemWeapon' => 'weapon',
|
||||
'itemBook' => 'book',
|
||||
'itemExtra' => 'item',
|
||||
]);
|
||||
if (isset($row['meta'])) {
|
||||
$patch['aux'] = Json::encode($row['meta']);
|
||||
}
|
||||
if (array_key_exists('penalty', $row)) {
|
||||
if (!is_array($row['penalty'])) {
|
||||
throw new \InvalidArgumentException('setup.generals.penalty must be an object');
|
||||
}
|
||||
$patch['penalty'] = Json::encode($row['penalty']);
|
||||
}
|
||||
if (isset($row['lastTurn']) && is_array($row['lastTurn'])) {
|
||||
$patch['last_turn'] = Json::encode($row['lastTurn']);
|
||||
}
|
||||
if ($patch !== []) {
|
||||
$db->update('general', $patch, 'no = %i', $row['id']);
|
||||
}
|
||||
if (array_key_exists('nationId', $row)) {
|
||||
$db->update('rank_data', [
|
||||
'nation_id' => $row['nationId'],
|
||||
], 'general_id = %i', $row['id']);
|
||||
}
|
||||
}
|
||||
foreach ($setup['rankData'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['generalId'] ?? null)
|
||||
|| !is_string($row['type'] ?? null)
|
||||
|| RankColumn::tryFrom($row['type']) === null
|
||||
|| !is_int($row['value'] ?? null)
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid setup.rankData row');
|
||||
}
|
||||
$nationId = (int)($db->queryFirstField(
|
||||
'SELECT nation FROM general WHERE no = %i',
|
||||
$row['generalId'],
|
||||
) ?? 0);
|
||||
$db->insertUpdate('rank_data', [
|
||||
'general_id' => $row['generalId'],
|
||||
'nation_id' => $nationId,
|
||||
'type' => $row['type'],
|
||||
'value' => $row['value'],
|
||||
], [
|
||||
'nation_id' => $nationId,
|
||||
'value' => $row['value'],
|
||||
]);
|
||||
}
|
||||
if (($setup['isolateWorld'] ?? false) === true && ($setup['generals'] ?? []) !== []) {
|
||||
$maxGeneralId = max(array_map(
|
||||
static fn(array $row): int => (int)$row['id'],
|
||||
$setup['generals'],
|
||||
));
|
||||
$db->query('ALTER TABLE general AUTO_INCREMENT = %i', $maxGeneralId + 1);
|
||||
}
|
||||
|
||||
foreach ($setup['troops'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row)
|
||||
|| !is_int($row['id'] ?? null)
|
||||
|| !is_int($row['nationId'] ?? null)
|
||||
|| !is_string($row['name'] ?? null)
|
||||
|| $row['id'] < 1
|
||||
|| $row['nationId'] < 1
|
||||
|| $row['name'] === ''
|
||||
) {
|
||||
throw new \InvalidArgumentException('setup.troops requires positive id/nationId and non-empty name');
|
||||
}
|
||||
$data = [
|
||||
'troop_leader' => $row['id'],
|
||||
'nation' => $row['nationId'],
|
||||
'name' => $row['name'],
|
||||
];
|
||||
$db->insertUpdate('troop', $data, $data);
|
||||
}
|
||||
|
||||
foreach ($setup['diplomacy'] ?? [] as $row) {
|
||||
if (
|
||||
!is_array($row) ||
|
||||
!is_int($row['fromNationId'] ?? null) ||
|
||||
!is_int($row['toNationId'] ?? null) ||
|
||||
$row['fromNationId'] < 1 ||
|
||||
$row['toNationId'] < 1
|
||||
) {
|
||||
throw new \InvalidArgumentException('setup.diplomacy requires positive integer nation ids');
|
||||
}
|
||||
$data = comparisonMappedPatch($row, [
|
||||
'fromNationId' => 'me',
|
||||
'toNationId' => 'you',
|
||||
'state' => 'state',
|
||||
'term' => 'term',
|
||||
'dead' => 'dead',
|
||||
]);
|
||||
$data += ['state' => 3, 'term' => 0, 'dead' => 0];
|
||||
$db->insertUpdate('diplomacy', $data, $data);
|
||||
}
|
||||
}
|
||||
|
||||
function comparisonRunTurnCommand(array $request): array
|
||||
{
|
||||
if (getenv('TURN_DIFFERENTIAL_ENABLED') !== '1') {
|
||||
throw new \RuntimeException('TURN_DIFFERENTIAL_ENABLED=1 is required');
|
||||
}
|
||||
$kind = $request['kind'] ?? null;
|
||||
if (!in_array($kind, ['general', 'nation', 'instantNation', 'troopJoinStaticEvent'], true)) {
|
||||
throw new \InvalidArgumentException(
|
||||
'kind must be general, nation, instantNation, or troopJoinStaticEvent',
|
||||
);
|
||||
}
|
||||
$actorGeneralId = $request['actorGeneralId'] ?? null;
|
||||
$action = $request['action'] ?? null;
|
||||
$args = $request['args'] ?? null;
|
||||
$includeLifecycle = $request['includeLifecycle'] ?? false;
|
||||
if (!is_int($actorGeneralId) || $actorGeneralId < 1) {
|
||||
throw new \InvalidArgumentException('actorGeneralId must be a positive integer');
|
||||
}
|
||||
if (!is_string($action) || $action === '') {
|
||||
throw new \InvalidArgumentException('action must be a non-empty string');
|
||||
}
|
||||
if (!is_bool($includeLifecycle)) {
|
||||
throw new \InvalidArgumentException('includeLifecycle must be a boolean');
|
||||
}
|
||||
if ($includeLifecycle && $kind !== 'general') {
|
||||
throw new \InvalidArgumentException('includeLifecycle currently supports general commands only');
|
||||
}
|
||||
|
||||
comparisonApplyTurnFixtureSetup($request['setup'] ?? null);
|
||||
if ($includeLifecycle) {
|
||||
DB::db()->insertUpdate('general_turn', [
|
||||
'general_id' => $actorGeneralId,
|
||||
'turn_idx' => 0,
|
||||
'action' => $action,
|
||||
'arg' => Json::encode($args),
|
||||
'brief' => $action,
|
||||
], [
|
||||
'action' => $action,
|
||||
'arg' => Json::encode($args),
|
||||
'brief' => $action,
|
||||
]);
|
||||
}
|
||||
$snapshotRequest = ['observe' => $request['observe'] ?? []];
|
||||
$before = comparisonTurnStateSnapshot($snapshotRequest);
|
||||
$db = DB::db();
|
||||
$gameStorage = KVStorage::getStorage($db, 'game_env');
|
||||
$gameStorage->resetCache();
|
||||
$environment = $gameStorage->getAll();
|
||||
if ($kind === 'troopJoinStaticEvent') {
|
||||
if ($action !== \sammo\API\Troop\JoinTroop::class) {
|
||||
throw new \InvalidArgumentException('troopJoinStaticEvent requires the JoinTroop API action');
|
||||
}
|
||||
$troopId = is_array($args) ? ($args['troopID'] ?? null) : null;
|
||||
if (!is_int($troopId) || $troopId < 1) {
|
||||
throw new \InvalidArgumentException('troopJoinStaticEvent requires a positive integer troopID');
|
||||
}
|
||||
$general = GeneralLite::createObjFromDB(
|
||||
$actorGeneralId,
|
||||
['troop'],
|
||||
Enums\GeneralLiteQueryMode::Lite,
|
||||
);
|
||||
if ($general === null) {
|
||||
throw new \RuntimeException('장수 정보를 불러올 수 없습니다.');
|
||||
}
|
||||
if ($general->getVar('troop') != 0) {
|
||||
throw new \RuntimeException('이미 부대에 소속되어 있습니다.');
|
||||
}
|
||||
$nationId = $general->getNationID();
|
||||
if ($nationId == 0) {
|
||||
throw new \RuntimeException('국가에 소속되어 있지 않습니다.');
|
||||
}
|
||||
$troopExists = $db->queryFirstField(
|
||||
'SELECT `troop_leader` FROM `troop` WHERE `troop_leader` = %i AND `nation` = %i',
|
||||
$troopId,
|
||||
$nationId,
|
||||
);
|
||||
if (!$troopExists) {
|
||||
throw new \RuntimeException('부대가 올바르지 않습니다.');
|
||||
}
|
||||
|
||||
GameConst::$staticEventHandlers = [
|
||||
\sammo\API\Troop\JoinTroop::class => ['event_부대탑승즉시이동'],
|
||||
];
|
||||
$general->setVar('troop', $troopId);
|
||||
StaticEventHandler::handleEvent($general, null, \sammo\API\Troop\JoinTroop::class, [], $args);
|
||||
$general->applyDB($db);
|
||||
$after = comparisonTurnStateSnapshot($snapshotRequest);
|
||||
|
||||
return [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'execution' => [
|
||||
'kind' => $kind,
|
||||
'actorGeneralId' => $actorGeneralId,
|
||||
'action' => $action,
|
||||
'args' => $args,
|
||||
'seedDomain' => 'none',
|
||||
'outcome' => ['completed' => true],
|
||||
],
|
||||
'before' => $before,
|
||||
'after' => $after,
|
||||
'rng' => [],
|
||||
];
|
||||
}
|
||||
$general = General::createObjFromDB($actorGeneralId);
|
||||
if ($kind === 'instantNation') {
|
||||
$command = buildNationCommandClass($action, $general, $environment, new LastTurn(), $args);
|
||||
if (!$command->hasFullConditionMet()) {
|
||||
throw new \RuntimeException($command->getFailString());
|
||||
}
|
||||
$completed = $command->run(NoRNG::rngInstance());
|
||||
$command->setNextAvailable();
|
||||
$general->getLogger()->flush();
|
||||
$after = comparisonTurnStateSnapshot($snapshotRequest);
|
||||
|
||||
return [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'execution' => [
|
||||
'kind' => $kind,
|
||||
'actorGeneralId' => $actorGeneralId,
|
||||
'action' => $action,
|
||||
'args' => $args,
|
||||
'seedDomain' => 'none',
|
||||
'outcome' => [
|
||||
'lastTurn' => (object)[],
|
||||
'commandName' => $command->getName(),
|
||||
'completed' => $completed,
|
||||
],
|
||||
],
|
||||
'before' => $before,
|
||||
'after' => $after,
|
||||
'rng' => [],
|
||||
];
|
||||
}
|
||||
$turn = new TurnExecutionHelper($general);
|
||||
$general->increaseInheritancePoint(Enums\InheritanceKey::lived_month, 1);
|
||||
$preprocessRng = new RandUtil(new LiteHashDRBG(Util::simpleSerialize(
|
||||
UniqueConst::$hiddenSeed,
|
||||
'preprocess',
|
||||
(int)$environment['year'],
|
||||
(int)$environment['month'],
|
||||
$actorGeneralId,
|
||||
)));
|
||||
$turn->preprocessCommand($preprocessRng, $environment);
|
||||
$seedDomain = $kind === 'general' ? 'generalCommand' : 'nationCommand';
|
||||
$seed = Util::simpleSerialize(
|
||||
UniqueConst::$hiddenSeed,
|
||||
$seedDomain,
|
||||
(int)$environment['year'],
|
||||
(int)$environment['month'],
|
||||
$actorGeneralId,
|
||||
$action,
|
||||
);
|
||||
$tracingRng = new TurnComparisonTracingRNG(new LiteHashDRBG($seed));
|
||||
$rng = new RandUtil($tracingRng);
|
||||
if ($kind === 'general' && $action === 'che_견문') {
|
||||
\sammo\TextDecoration\SightseeingMessage::setComparisonRng($rng);
|
||||
}
|
||||
|
||||
if ($kind === 'general') {
|
||||
$previousLastTurn = $general->getLastTurn();
|
||||
$previousLastTurnRaw = $previousLastTurn->toRaw();
|
||||
$command = buildGeneralCommandClass($action, $general, $environment, $args);
|
||||
$commandFullConditionMet = $command->hasFullConditionMet();
|
||||
$resultTurn = $turn->processCommand($rng, $command, false);
|
||||
} else {
|
||||
$nationStor = KVStorage::getStorage($db, $general->getNationID(), 'nation_env');
|
||||
$lastNationTurnKey = "turn_last_{$general->getVar('officer_level')}";
|
||||
$previousLastTurn = LastTurn::fromRaw($nationStor->getValue($lastNationTurnKey));
|
||||
$previousLastTurnRaw = $previousLastTurn->toRaw();
|
||||
$command = buildNationCommandClass($action, $general, $environment, $previousLastTurn, $args);
|
||||
$commandFullConditionMet = $command->hasFullConditionMet();
|
||||
$resultTurn = $turn->processNationCommand($rng, $command);
|
||||
$nationStor->setValue($lastNationTurnKey, $resultTurn->toRaw());
|
||||
}
|
||||
|
||||
if ($includeLifecycle) {
|
||||
pullGeneralCommand($general->getID());
|
||||
$general->increaseVarWithLimit(
|
||||
'myset',
|
||||
GameConst::$incDefSettingChange,
|
||||
null,
|
||||
GameConst::$maxDefSettingChange,
|
||||
);
|
||||
$turn->updateTurnTime();
|
||||
}
|
||||
$general->getLogger()->flush();
|
||||
$turn->applyDB();
|
||||
unset($turn);
|
||||
$after = comparisonTurnStateSnapshot($snapshotRequest);
|
||||
$resultTurnRaw = $resultTurn->toRaw();
|
||||
$resultTerm = (int)($resultTurnRaw['term'] ?? 0);
|
||||
$preReqTurn = $command->getPreReqTurn();
|
||||
$acceptScoutCompleted = (
|
||||
$action === 'che_등용수락'
|
||||
&& is_array($args)
|
||||
&& is_int($args['destNationID'] ?? null)
|
||||
&& $general->getNationID() === $args['destNationID']
|
||||
);
|
||||
$foundNationCompleted = (
|
||||
in_array($action, ['che_건국', 'cr_건국', 'che_무작위건국'], true)
|
||||
&& is_array($args)
|
||||
&& is_string($args['nationName'] ?? null)
|
||||
&& DB::db()->queryFirstField(
|
||||
'SELECT name FROM nation WHERE nation = %i',
|
||||
$general->getNationID(),
|
||||
) === $args['nationName']
|
||||
);
|
||||
$completedByState = (
|
||||
$action === 'che_접경귀환'
|
||||
&& $tracingRng->calls !== []
|
||||
) || $acceptScoutCompleted || $foundNationCompleted || (($resultTurnRaw['command'] ?? null) === $command->getName()
|
||||
&& (
|
||||
($preReqTurn === 0 && $resultTerm === 0)
|
||||
|| (
|
||||
$preReqTurn > 0
|
||||
&& ($previousLastTurnRaw['command'] ?? null) === $command->getName()
|
||||
&& ($previousLastTurnRaw['arg'] ?? null) === $command->getArg()
|
||||
&& (int)($previousLastTurnRaw['term'] ?? 0) === $preReqTurn
|
||||
)
|
||||
));
|
||||
$completed = $commandFullConditionMet && $completedByState;
|
||||
|
||||
return [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'execution' => [
|
||||
'kind' => $kind,
|
||||
'actorGeneralId' => $actorGeneralId,
|
||||
'action' => $action,
|
||||
'args' => $args,
|
||||
'seedDomain' => $seedDomain,
|
||||
'outcome' => [
|
||||
'lastTurn' => $resultTurnRaw,
|
||||
'commandName' => $command->getName(),
|
||||
'completed' => $completed,
|
||||
],
|
||||
],
|
||||
'before' => $before,
|
||||
'after' => $after,
|
||||
'rng' => $tracingRng->calls,
|
||||
];
|
||||
}
|
||||
|
||||
try {
|
||||
$input = stream_get_contents(STDIN);
|
||||
$request = json_decode($input === '' ? '{}' : $input, true, flags: JSON_THROW_ON_ERROR);
|
||||
if (!is_array($request)) {
|
||||
throw new \InvalidArgumentException('request must be an object');
|
||||
}
|
||||
echo json_encode(
|
||||
comparisonRunTurnCommand($request),
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
|
||||
), PHP_EOL;
|
||||
} catch (\Throwable $throwable) {
|
||||
fwrite(STDERR, $throwable::class . ': ' . $throwable->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
@@ -0,0 +1,643 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace sammo;
|
||||
|
||||
use sammo\Enums\RankColumn;
|
||||
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
http_response_code(404);
|
||||
exit;
|
||||
}
|
||||
|
||||
chdir(dirname(__DIR__));
|
||||
require_once 'lib.php';
|
||||
require_once 'func.php';
|
||||
|
||||
/** @return list<int> */
|
||||
function comparisonIntegerList(mixed $value, string $label): array
|
||||
{
|
||||
if ($value === null) {
|
||||
return [];
|
||||
}
|
||||
if (!is_array($value)) {
|
||||
throw new \InvalidArgumentException("{$label} must be an array");
|
||||
}
|
||||
$result = [];
|
||||
foreach ($value as $entry) {
|
||||
if (!is_int($entry) || $entry < 0) {
|
||||
throw new \InvalidArgumentException("{$label} entries must be non-negative integers");
|
||||
}
|
||||
$result[$entry] = $entry;
|
||||
}
|
||||
ksort($result, SORT_NUMERIC);
|
||||
return array_values($result);
|
||||
}
|
||||
|
||||
function comparisonJsonValue(mixed $value): mixed
|
||||
{
|
||||
if (!is_string($value) || $value === '') {
|
||||
return $value;
|
||||
}
|
||||
try {
|
||||
return json_decode($value, true, flags: JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException) {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
|
||||
function comparisonOptionalCode(mixed $value): ?string
|
||||
{
|
||||
if (!is_string($value) || $value === '' || $value === 'None') {
|
||||
return null;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @return list<array{generalId: int, actionName: string}> */
|
||||
function comparisonGeneralCooldownSelectors(mixed $value, string $label): array
|
||||
{
|
||||
if ($value === null) {
|
||||
return [];
|
||||
}
|
||||
if (!is_array($value)) {
|
||||
throw new \InvalidArgumentException("{$label} must be an array");
|
||||
}
|
||||
$result = [];
|
||||
foreach ($value as $entry) {
|
||||
if (!is_array($entry)) {
|
||||
throw new \InvalidArgumentException("{$label} entries must be objects");
|
||||
}
|
||||
$generalId = $entry['generalId'] ?? null;
|
||||
$actionName = $entry['actionName'] ?? null;
|
||||
if (!is_int($generalId) || $generalId < 1 || !is_string($actionName) || $actionName === '') {
|
||||
throw new \InvalidArgumentException(
|
||||
"{$label} entries require a positive generalId and non-empty actionName",
|
||||
);
|
||||
}
|
||||
$result["{$generalId}:{$actionName}"] = [
|
||||
'generalId' => $generalId,
|
||||
'actionName' => $actionName,
|
||||
];
|
||||
}
|
||||
ksort($result, SORT_STRING);
|
||||
return array_values($result);
|
||||
}
|
||||
|
||||
/** @return list<array{nationId: int, actionName: string}> */
|
||||
function comparisonNationCooldownSelectors(mixed $value, string $label): array
|
||||
{
|
||||
if ($value === null) {
|
||||
return [];
|
||||
}
|
||||
if (!is_array($value)) {
|
||||
throw new \InvalidArgumentException("{$label} must be an array");
|
||||
}
|
||||
$result = [];
|
||||
foreach ($value as $entry) {
|
||||
if (!is_array($entry)) {
|
||||
throw new \InvalidArgumentException("{$label} entries must be objects");
|
||||
}
|
||||
$nationId = $entry['nationId'] ?? null;
|
||||
$actionName = $entry['actionName'] ?? null;
|
||||
if (!is_int($nationId) || $nationId < 1 || !is_string($actionName) || $actionName === '') {
|
||||
throw new \InvalidArgumentException(
|
||||
"{$label} entries require a positive nationId and non-empty actionName",
|
||||
);
|
||||
}
|
||||
$result["{$nationId}:{$actionName}"] = [
|
||||
'nationId' => $nationId,
|
||||
'actionName' => $actionName,
|
||||
];
|
||||
}
|
||||
ksort($result, SORT_STRING);
|
||||
return array_values($result);
|
||||
}
|
||||
|
||||
/** @return list<array{fromNationId: int, toNationId: int}> */
|
||||
function comparisonDiplomacyPairSelectors(mixed $value, string $label): array
|
||||
{
|
||||
if ($value === null) {
|
||||
return [];
|
||||
}
|
||||
if (!is_array($value)) {
|
||||
throw new \InvalidArgumentException("{$label} must be an array");
|
||||
}
|
||||
$result = [];
|
||||
foreach ($value as $entry) {
|
||||
if (!is_array($entry)) {
|
||||
throw new \InvalidArgumentException("{$label} entries must be objects");
|
||||
}
|
||||
$fromNationId = $entry['fromNationId'] ?? null;
|
||||
$toNationId = $entry['toNationId'] ?? null;
|
||||
if (!is_int($fromNationId) || $fromNationId < 1 || !is_int($toNationId) || $toNationId < 1) {
|
||||
throw new \InvalidArgumentException(
|
||||
"{$label} entries require positive fromNationId and toNationId",
|
||||
);
|
||||
}
|
||||
$result["{$fromNationId}:{$toNationId}"] = [
|
||||
'fromNationId' => $fromNationId,
|
||||
'toNationId' => $toNationId,
|
||||
];
|
||||
}
|
||||
ksort($result, SORT_STRING);
|
||||
return array_values($result);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed> $row */
|
||||
function comparisonPickRow(array $row, array $mapping, array $jsonKeys = []): array
|
||||
{
|
||||
$result = [];
|
||||
foreach ($mapping as $canonical => $legacy) {
|
||||
if (!array_key_exists($legacy, $row)) {
|
||||
continue;
|
||||
}
|
||||
$value = $row[$legacy];
|
||||
if (in_array($legacy, $jsonKeys, true)) {
|
||||
$value = comparisonJsonValue($value);
|
||||
}
|
||||
$result[$canonical] = $value;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @param list<int> $ids */
|
||||
function comparisonRowsById(string $table, string $idColumn, array $ids): array
|
||||
{
|
||||
$db = DB::db();
|
||||
$rows = [];
|
||||
foreach ($ids as $id) {
|
||||
$row = $db->queryFirstRow(
|
||||
"SELECT * FROM `{$table}` WHERE `{$idColumn}` = %i",
|
||||
$id,
|
||||
);
|
||||
if ($row !== null) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
}
|
||||
return $rows;
|
||||
}
|
||||
|
||||
function comparisonTurnStateSnapshot(array $request): array
|
||||
{
|
||||
$observe = $request['observe'] ?? [];
|
||||
if (!is_array($observe)) {
|
||||
throw new \InvalidArgumentException('observe must be an object');
|
||||
}
|
||||
$generalIds = comparisonIntegerList($observe['generalIds'] ?? [], 'generalIds');
|
||||
$cityIds = comparisonIntegerList($observe['cityIds'] ?? [], 'cityIds');
|
||||
$nationIds = comparisonIntegerList($observe['nationIds'] ?? [], 'nationIds');
|
||||
$logAfterId = $observe['logAfterId'] ?? 0;
|
||||
$messageAfterId = $observe['messageAfterId'] ?? 0;
|
||||
$includeNationHistoryLogs = $observe['includeNationHistoryLogs'] ?? false;
|
||||
$includeGlobalHistoryLogs = $observe['includeGlobalHistoryLogs'] ?? false;
|
||||
$generalCooldownSelectors = comparisonGeneralCooldownSelectors(
|
||||
$observe['generalCooldowns'] ?? [],
|
||||
'generalCooldowns',
|
||||
);
|
||||
$nationCooldownSelectors = comparisonNationCooldownSelectors(
|
||||
$observe['nationCooldowns'] ?? [],
|
||||
'nationCooldowns',
|
||||
);
|
||||
$diplomacyPairSelectors = comparisonDiplomacyPairSelectors(
|
||||
$observe['diplomacyPairs'] ?? [],
|
||||
'diplomacyPairs',
|
||||
);
|
||||
if (
|
||||
!is_int($logAfterId)
|
||||
|| $logAfterId < 0
|
||||
|| !is_int($messageAfterId)
|
||||
|| $messageAfterId < 0
|
||||
) {
|
||||
throw new \InvalidArgumentException('logAfterId and messageAfterId must be non-negative integers');
|
||||
}
|
||||
if (!is_bool($includeNationHistoryLogs)) {
|
||||
throw new \InvalidArgumentException('includeNationHistoryLogs must be a boolean');
|
||||
}
|
||||
if (!is_bool($includeGlobalHistoryLogs)) {
|
||||
throw new \InvalidArgumentException('includeGlobalHistoryLogs must be a boolean');
|
||||
}
|
||||
|
||||
$db = DB::db();
|
||||
$game = KVStorage::getStorage($db, 'game_env');
|
||||
$game->resetCache();
|
||||
$worldValues = $game->getValues([
|
||||
'year',
|
||||
'month',
|
||||
'turnterm',
|
||||
'turntime',
|
||||
'isunited',
|
||||
'scenario',
|
||||
'init_year',
|
||||
'init_month',
|
||||
'develcost',
|
||||
'killturn',
|
||||
]);
|
||||
$nextExecuteStorage = KVStorage::getStorage($db, 'next_execute');
|
||||
$nextExecuteStorage->resetCache();
|
||||
$generalCooldowns = array_map(
|
||||
static function (array $selector) use ($nextExecuteStorage): array {
|
||||
$key = "next_execute_{$selector['generalId']}_{$selector['actionName']}";
|
||||
$value = $nextExecuteStorage->getValue($key);
|
||||
return [
|
||||
...$selector,
|
||||
'nextAvailableTurn' => is_int($value) ? $value : null,
|
||||
];
|
||||
},
|
||||
$generalCooldownSelectors,
|
||||
);
|
||||
$nationCooldowns = array_map(
|
||||
static function (array $selector) use ($db): array {
|
||||
$nationStorage = KVStorage::getStorage($db, $selector['nationId'], 'nation_env');
|
||||
$nationStorage->resetCache();
|
||||
$value = $nationStorage->getValue("next_execute_{$selector['actionName']}");
|
||||
return [
|
||||
...$selector,
|
||||
'nextAvailableTurn' => is_int($value) ? $value : null,
|
||||
];
|
||||
},
|
||||
$nationCooldownSelectors,
|
||||
);
|
||||
|
||||
$generals = array_map(
|
||||
static function (array $row): array {
|
||||
$result = comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'no',
|
||||
'name' => 'name',
|
||||
'nationId' => 'nation',
|
||||
'cityId' => 'city',
|
||||
'troopId' => 'troop',
|
||||
'leadership' => 'leadership',
|
||||
'strength' => 'strength',
|
||||
'intelligence' => 'intel',
|
||||
'experience' => 'experience',
|
||||
'dedication' => 'dedication',
|
||||
'expLevel' => 'explevel',
|
||||
'officerLevel' => 'officer_level',
|
||||
'officerCityId' => 'officer_city',
|
||||
'belong' => 'belong',
|
||||
'permission' => 'permission',
|
||||
'betray' => 'betray',
|
||||
'makeLimit' => 'makelimit',
|
||||
'injury' => 'injury',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'crew' => 'crew',
|
||||
'crewTypeId' => 'crewtype',
|
||||
'train' => 'train',
|
||||
'atmos' => 'atmos',
|
||||
'age' => 'age',
|
||||
'npcState' => 'npc',
|
||||
'turnTime' => 'turntime',
|
||||
'recentWarTime' => 'recent_war',
|
||||
'lastTurn' => 'last_turn',
|
||||
'meta' => 'aux',
|
||||
'penalty' => 'penalty',
|
||||
'leadershipExp' => 'leadership_exp',
|
||||
'strengthExp' => 'strength_exp',
|
||||
'intelExp' => 'intel_exp',
|
||||
'dex1' => 'dex1',
|
||||
'dex2' => 'dex2',
|
||||
'dex3' => 'dex3',
|
||||
'dex4' => 'dex4',
|
||||
'dex5' => 'dex5',
|
||||
'specAge' => 'specage',
|
||||
'specAge2' => 'specage2',
|
||||
'killTurn' => 'killturn',
|
||||
'mySet' => 'myset',
|
||||
'specialDomestic' => 'special',
|
||||
'specialWar' => 'special2',
|
||||
'personality' => 'personal',
|
||||
'itemHorse' => 'horse',
|
||||
'itemWeapon' => 'weapon',
|
||||
'itemBook' => 'book',
|
||||
'itemExtra' => 'item',
|
||||
],
|
||||
['last_turn', 'aux', 'penalty'],
|
||||
);
|
||||
foreach ([
|
||||
'specialDomestic',
|
||||
'specialWar',
|
||||
'personality',
|
||||
'itemHorse',
|
||||
'itemWeapon',
|
||||
'itemBook',
|
||||
'itemExtra',
|
||||
] as $key) {
|
||||
$result[$key] = comparisonOptionalCode($result[$key] ?? null);
|
||||
}
|
||||
$result['maxBelong'] = (int)($result['meta']['max_belong'] ?? 0);
|
||||
$ownerId = (int)($row['owner'] ?? 0);
|
||||
$activeActionPoints = 0;
|
||||
if ($ownerId > 0) {
|
||||
$inheritanceStorage = KVStorage::getStorage(DB::db(), "inheritance_{$ownerId}");
|
||||
$inheritanceStorage->resetCache();
|
||||
$stored = $inheritanceStorage->getValue('active_action');
|
||||
if (is_array($stored) && (is_int($stored[0] ?? null) || is_float($stored[0] ?? null))) {
|
||||
$activeActionPoints = $stored[0];
|
||||
}
|
||||
}
|
||||
$result['hasOwner'] = $ownerId > 0;
|
||||
$result['inheritActiveActionPoints'] = $activeActionPoints;
|
||||
return $result;
|
||||
},
|
||||
comparisonRowsById('general', 'no', $generalIds),
|
||||
);
|
||||
$rankTypes = array_map(
|
||||
static fn(RankColumn $column): string => $column->value,
|
||||
RankColumn::cases(),
|
||||
);
|
||||
$rankData = $generalIds === []
|
||||
? []
|
||||
: iterator_to_array($db->query(
|
||||
'SELECT general_id AS generalId, nation_id AS nationId, `type`, `value`'
|
||||
. ' FROM rank_data WHERE general_id IN %li AND `type` IN %ls'
|
||||
. ' ORDER BY general_id, `type`',
|
||||
$generalIds,
|
||||
$rankTypes,
|
||||
));
|
||||
|
||||
$cities = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'city',
|
||||
'name' => 'name',
|
||||
'nationId' => 'nation',
|
||||
'level' => 'level',
|
||||
'population' => 'pop',
|
||||
'populationMax' => 'pop_max',
|
||||
'agriculture' => 'agri',
|
||||
'agricultureMax' => 'agri_max',
|
||||
'commerce' => 'comm',
|
||||
'commerceMax' => 'comm_max',
|
||||
'security' => 'secu',
|
||||
'securityMax' => 'secu_max',
|
||||
'supplyState' => 'supply',
|
||||
'frontState' => 'front',
|
||||
'defence' => 'def',
|
||||
'defenceMax' => 'def_max',
|
||||
'wall' => 'wall',
|
||||
'wallMax' => 'wall_max',
|
||||
'state' => 'state',
|
||||
'term' => 'term',
|
||||
'trust' => 'trust',
|
||||
'trade' => 'trade',
|
||||
'conflict' => 'conflict',
|
||||
'officerSet' => 'officer_set',
|
||||
],
|
||||
['conflict'],
|
||||
),
|
||||
comparisonRowsById('city', 'city', $cityIds),
|
||||
);
|
||||
|
||||
$nations = array_map(
|
||||
static function (array $row) use ($db): array {
|
||||
$projected = comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'nation',
|
||||
'name' => 'name',
|
||||
'color' => 'color',
|
||||
'capitalCityId' => 'capital',
|
||||
'gold' => 'gold',
|
||||
'rice' => 'rice',
|
||||
'tech' => 'tech',
|
||||
'level' => 'level',
|
||||
'typeCode' => 'type',
|
||||
'generalCount' => 'gennum',
|
||||
'power' => 'power',
|
||||
'war' => 'war',
|
||||
'diplomacyLimit' => 'surlimit',
|
||||
'capitalRevision' => 'capset',
|
||||
'strategicCommandLimit' => 'strategic_cmd_limit',
|
||||
'meta' => 'aux',
|
||||
],
|
||||
['aux'],
|
||||
);
|
||||
$nationStor = KVStorage::getStorage($db, (int)$row['nation'], 'nation_env');
|
||||
$receivedAssist = $nationStor->getValue('recv_assist');
|
||||
if (is_array($receivedAssist) && $receivedAssist !== []) {
|
||||
$projected['meta']['recv_assist'] = $receivedAssist;
|
||||
}
|
||||
$respondedAssist = $nationStor->getValue('resp_assist');
|
||||
if (is_array($respondedAssist) && $respondedAssist !== []) {
|
||||
$projected['meta']['resp_assist'] = $respondedAssist;
|
||||
}
|
||||
return $projected;
|
||||
},
|
||||
comparisonRowsById('nation', 'nation', $nationIds),
|
||||
);
|
||||
|
||||
$diplomacyPairs = [];
|
||||
foreach ($nationIds as $fromNationId) {
|
||||
foreach ($nationIds as $toNationId) {
|
||||
if ($fromNationId === $toNationId) {
|
||||
continue;
|
||||
}
|
||||
$diplomacyPairs["{$fromNationId}:{$toNationId}"] = [
|
||||
'fromNationId' => $fromNationId,
|
||||
'toNationId' => $toNationId,
|
||||
];
|
||||
}
|
||||
}
|
||||
foreach ($diplomacyPairSelectors as $pair) {
|
||||
$diplomacyPairs["{$pair['fromNationId']}:{$pair['toNationId']}"] = $pair;
|
||||
}
|
||||
ksort($diplomacyPairs, SORT_STRING);
|
||||
|
||||
$diplomacy = [];
|
||||
foreach ($diplomacyPairs as $pair) {
|
||||
$row = $db->queryFirstRow(
|
||||
'SELECT me, you, state, term, dead FROM diplomacy WHERE me = %i AND you = %i',
|
||||
$pair['fromNationId'],
|
||||
$pair['toNationId'],
|
||||
);
|
||||
if ($row !== null) {
|
||||
$diplomacy[] = comparisonPickRow($row, [
|
||||
'fromNationId' => 'me',
|
||||
'toNationId' => 'you',
|
||||
'state' => 'state',
|
||||
'term' => 'term',
|
||||
'dead' => 'dead',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
$generalTurns = [];
|
||||
foreach ($generalIds as $generalId) {
|
||||
foreach ($db->query(
|
||||
'SELECT general_id, turn_idx, action, arg FROM general_turn WHERE general_id = %i ORDER BY turn_idx',
|
||||
$generalId,
|
||||
) as $row) {
|
||||
$generalTurns[] = comparisonPickRow(
|
||||
$row,
|
||||
['generalId' => 'general_id', 'turnIndex' => 'turn_idx', 'action' => 'action', 'args' => 'arg'],
|
||||
['arg'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$nationTurns = [];
|
||||
foreach ($nationIds as $nationId) {
|
||||
foreach ($db->query(
|
||||
'SELECT nation_id, officer_level, turn_idx, action, arg FROM nation_turn WHERE nation_id = %i ORDER BY officer_level, turn_idx',
|
||||
$nationId,
|
||||
) as $row) {
|
||||
$nationTurns[] = comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'nationId' => 'nation_id',
|
||||
'officerLevel' => 'officer_level',
|
||||
'turnIndex' => 'turn_idx',
|
||||
'action' => 'action',
|
||||
'args' => 'arg',
|
||||
],
|
||||
['arg'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$logs = [];
|
||||
if ($generalIds !== []) {
|
||||
foreach ($db->query(
|
||||
'SELECT id, general_id, log_type, year, month, text FROM general_record WHERE id > %i ORDER BY id',
|
||||
$logAfterId,
|
||||
) as $row) {
|
||||
if ((int)$row['general_id'] !== 0 && !in_array((int)$row['general_id'], $generalIds, true)) {
|
||||
continue;
|
||||
}
|
||||
$generalId = (int)$row['general_id'];
|
||||
$category = (string)$row['log_type'];
|
||||
if ($category === 'battle') {
|
||||
$category = 'battle_detail';
|
||||
} elseif ($generalId === 0) {
|
||||
$category = 'summary';
|
||||
}
|
||||
$logs[] = comparisonPickRow($row, [
|
||||
'id' => 'id',
|
||||
'generalId' => 'general_id',
|
||||
'year' => 'year',
|
||||
'month' => 'month',
|
||||
'text' => 'text',
|
||||
]) + [
|
||||
'scope' => $generalId === 0 ? 'system' : 'general',
|
||||
'category' => $category,
|
||||
'nationId' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
if ($includeNationHistoryLogs && $nationIds !== []) {
|
||||
foreach ($db->query(
|
||||
'SELECT id, nation_id, year, month, text FROM world_history WHERE nation_id IN %li ORDER BY id',
|
||||
$nationIds,
|
||||
) as $row) {
|
||||
$logs[] = comparisonPickRow($row, [
|
||||
'id' => 'id',
|
||||
'nationId' => 'nation_id',
|
||||
'year' => 'year',
|
||||
'month' => 'month',
|
||||
'text' => 'text',
|
||||
]) + [
|
||||
'scope' => 'nation',
|
||||
'category' => 'history',
|
||||
'generalId' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
if ($includeGlobalHistoryLogs) {
|
||||
foreach ($db->query(
|
||||
'SELECT id, nation_id, year, month, text FROM world_history WHERE nation_id = 0 ORDER BY id',
|
||||
) as $row) {
|
||||
$logs[] = comparisonPickRow($row, [
|
||||
'id' => 'id',
|
||||
'nationId' => 'nation_id',
|
||||
'year' => 'year',
|
||||
'month' => 'month',
|
||||
'text' => 'text',
|
||||
]) + [
|
||||
'scope' => 'system',
|
||||
'category' => 'history',
|
||||
'generalId' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$messages = array_map(
|
||||
static fn(array $row): array => comparisonPickRow(
|
||||
$row,
|
||||
[
|
||||
'id' => 'id',
|
||||
'mailbox' => 'mailbox',
|
||||
'type' => 'type',
|
||||
'sourceId' => 'src',
|
||||
'destinationId' => 'dest',
|
||||
'createdAt' => 'time',
|
||||
'payload' => 'message',
|
||||
],
|
||||
['message'],
|
||||
),
|
||||
$db->query(
|
||||
'SELECT id, mailbox, type, src, dest, time, message FROM message WHERE id > %i ORDER BY id',
|
||||
$messageAfterId,
|
||||
),
|
||||
);
|
||||
|
||||
return [
|
||||
'schemaVersion' => 1,
|
||||
'engine' => 'ref',
|
||||
'world' => [
|
||||
'year' => (int)$worldValues['year'],
|
||||
'month' => (int)$worldValues['month'],
|
||||
'tickMinutes' => (int)$worldValues['turnterm'],
|
||||
'turnTime' => (string)$worldValues['turntime'],
|
||||
'isUnited' => (int)$worldValues['isunited'],
|
||||
'scenarioId' => (int)$worldValues['scenario'],
|
||||
'initYear' => (int)$worldValues['init_year'],
|
||||
'initMonth' => (int)$worldValues['init_month'],
|
||||
'develCost' => (int)$worldValues['develcost'],
|
||||
'killTurn' => (int)$worldValues['killturn'],
|
||||
'generalCooldowns' => $generalCooldowns,
|
||||
'nationCooldowns' => $nationCooldowns,
|
||||
],
|
||||
'generals' => $generals,
|
||||
'rankData' => $rankData,
|
||||
'cities' => $cities,
|
||||
'nations' => $nations,
|
||||
'diplomacy' => $diplomacy,
|
||||
'generalTurns' => $generalTurns,
|
||||
'nationTurns' => $nationTurns,
|
||||
'logs' => $logs,
|
||||
'messages' => $messages,
|
||||
'watermarks' => [
|
||||
'logId' => (int)($db->queryFirstField('SELECT COALESCE(MAX(id), 0) FROM general_record') ?? 0),
|
||||
'historyLogId' => (int)($db->queryFirstField('SELECT COALESCE(MAX(id), 0) FROM world_history') ?? 0),
|
||||
'messageId' => (int)($db->queryFirstField('SELECT COALESCE(MAX(id), 0) FROM message') ?? 0),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
function comparisonTurnStateSnapshotMain(): void
|
||||
{
|
||||
try {
|
||||
$input = stream_get_contents(STDIN);
|
||||
$request = json_decode($input === '' ? '{}' : $input, true, flags: JSON_THROW_ON_ERROR);
|
||||
if (!is_array($request)) {
|
||||
throw new \InvalidArgumentException('request must be an object');
|
||||
}
|
||||
echo json_encode(
|
||||
comparisonTurnStateSnapshot($request),
|
||||
JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
|
||||
), PHP_EOL;
|
||||
} catch (\Throwable $throwable) {
|
||||
fwrite(STDERR, $throwable::class . ': ' . $throwable->getMessage() . PHP_EOL);
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (realpath((string)($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
|
||||
comparisonTurnStateSnapshotMain();
|
||||
}
|
||||
@@ -51,6 +51,22 @@
|
||||
display: none;
|
||||
}
|
||||
|
||||
.picture_choice {
|
||||
margin: 8px auto;
|
||||
}
|
||||
|
||||
.picture_choice label,
|
||||
.event_picture label {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin: 4px 8px;
|
||||
}
|
||||
|
||||
.picture_choice img {
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.custom_picture {
|
||||
display: none;
|
||||
}
|
||||
|
||||
+4
-1
@@ -1047,7 +1047,7 @@ function increaseRefresh($type = "", $cnt = 1)
|
||||
|
||||
$logDB = FileDB::db($logPath, $serverPath . '/../f_install/sql/api_log.sql');
|
||||
|
||||
$ip = $_SERVER['REMOTE_ADDR'] ?? 'local';
|
||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'local';
|
||||
$date = date('Y-m-d H:i:s');
|
||||
|
||||
$logDB->insert('api_log', [
|
||||
@@ -1403,6 +1403,9 @@ function CheckHall($no)
|
||||
|
||||
if ($valueType === 'natural') {
|
||||
$value = $generalObj->getVar($typeName);
|
||||
if (in_array($typeName, ['dex1', 'dex2', 'dex3', 'dex4', 'dex5'], true)) {
|
||||
$value = CentennialAllStarGrowthService::recordableValue($generalObj, $typeName);
|
||||
}
|
||||
} else if ($valueType === 'rank') {
|
||||
$value = $generalObj->getRankVar(RankColumn::from($typeName));
|
||||
} else if ($valueType === 'calc') {
|
||||
|
||||
@@ -10,7 +10,23 @@ function sortTokens(&$tokens){
|
||||
});
|
||||
}
|
||||
|
||||
function putInfoText(&$info){
|
||||
function putInfoText(&$info, ?array $currentTargetEnv){
|
||||
if (($info['event100Growth'] ?? false) === true) {
|
||||
if ($currentTargetEnv === null) {
|
||||
$displayStats = CentennialAllStarGrowthService::calculateUserInitialStats($info);
|
||||
$info['selectionStatLabel'] = '시작 능력치';
|
||||
} else {
|
||||
$displayStats = CentennialAllStarGrowthService::calculateUserCurrentTargetStats(
|
||||
$info,
|
||||
$currentTargetEnv
|
||||
);
|
||||
$info['selectionStatLabel'] = '현재 변경 기준 능력치';
|
||||
}
|
||||
$info['selectionLeadership'] = $displayStats['leadership'];
|
||||
$info['selectionStrength'] = $displayStats['strength'];
|
||||
$info['selectionIntel'] = $displayStats['intel'];
|
||||
}
|
||||
|
||||
if(key_exists('specialDomestic', $info)){
|
||||
$class = buildGeneralSpecialDomesticClass($info['specialDomestic']);
|
||||
$info['specialDomesticName'] = $class->getName();
|
||||
@@ -34,7 +50,8 @@ $now = $oNow->format('Y-m-d H:i:s');
|
||||
$db = DB::db();
|
||||
$gameStor = KVStorage::getStorage($db, 'game_env');
|
||||
|
||||
$npcmode = $gameStor->getValue('npcmode');
|
||||
$eventEnv = $gameStor->getValues(['npcmode', 'startyear', 'year', 'month']);
|
||||
$npcmode = $eventEnv['npcmode'];
|
||||
if($npcmode!=2){
|
||||
Json::die([
|
||||
'result'=>false,
|
||||
@@ -43,6 +60,7 @@ if($npcmode!=2){
|
||||
}
|
||||
|
||||
$rawGeneral = $db->queryFirstRow('SELECT no, aux FROM general WHERE `owner` = %i', $userID);
|
||||
$currentTargetEnv = $rawGeneral ? $eventEnv : null;
|
||||
if($rawGeneral){
|
||||
$generalAux = Json::decode($rawGeneral['aux']);
|
||||
if(key_exists('next_change', $generalAux)&& $generalAux['next_change'] > $now){
|
||||
@@ -62,7 +80,7 @@ if($tokens){
|
||||
foreach($tokens as $token){
|
||||
$valid_until = $token['reserved_until'];
|
||||
$info = Json::decode($token['info']);
|
||||
putInfoText($info);
|
||||
putInfoText($info, $currentTargetEnv);
|
||||
$info['uniqueName'] = $token['unique_name'];
|
||||
$pick[] = $info;
|
||||
}
|
||||
@@ -83,7 +101,7 @@ $valid_until = null;
|
||||
foreach(pickGeneralFromPool($db, $rng, $userID, 14) as $pickObj){
|
||||
$valid_until = $pickObj->getValidUntil();
|
||||
$info = $pickObj->getInfo();
|
||||
putInfoText($info);
|
||||
putInfoText($info, $currentTargetEnv);
|
||||
$pick[] = $info;
|
||||
}
|
||||
sortTokens($pick);//좀 무식하지만..
|
||||
|
||||
@@ -8,10 +8,20 @@ WebUtil::requireAJAX();
|
||||
|
||||
$pick = Util::getPost('pick');
|
||||
$leadership = Util::getPost('leadership', 'int', GameConst::$defaultStatMin);
|
||||
$strength = Util::getPost('leadership', 'int', GameConst::$defaultStatMin);
|
||||
$intel = Util::getPost('leadership', 'int', GameConst::$defaultStatMin);
|
||||
$isCentennialAllStar = CentennialAllStarGrowthService::isActive();
|
||||
$strength = Util::getPost(
|
||||
$isCentennialAllStar ? 'strength' : 'leadership',
|
||||
'int',
|
||||
GameConst::$defaultStatMin
|
||||
);
|
||||
$intel = Util::getPost(
|
||||
$isCentennialAllStar ? 'intel' : 'leadership',
|
||||
'int',
|
||||
GameConst::$defaultStatMin
|
||||
);
|
||||
$personal = Util::getPost('personal', 'string', null);
|
||||
$use_own_picture = Util::getPost('use_own_picture', 'bool', false);
|
||||
$pictureSource = Util::getPost('picture_source', 'string', 'selected');
|
||||
|
||||
|
||||
if(!$pick){
|
||||
@@ -60,13 +70,36 @@ if(!$selectInfo){
|
||||
}
|
||||
$selectInfo = Json::decode($selectInfo);
|
||||
|
||||
$ownerInfo = RootDB::db()->queryFirstRow('SELECT `name`,`picture`,`imgsvr` FROM member WHERE `NO`=%i',$userID);
|
||||
$ownerInfo = RootDB::db()->queryFirstRow(
|
||||
'SELECT `name`,`picture`,`imgsvr`,`grade` FROM member WHERE `NO`=%i',
|
||||
$userID
|
||||
);
|
||||
if(!$ownerInfo){
|
||||
Json::die([
|
||||
'result'=>false,
|
||||
'reason'=>'멤버 정보를 가져오지 못했습니다.'
|
||||
]);
|
||||
}
|
||||
if ($isCentennialAllStar) {
|
||||
if (!in_array($pictureSource, ['selected', 'own'], true)) {
|
||||
Json::die([
|
||||
'result' => false,
|
||||
'reason' => '올바르지 않은 전콘 선택입니다.',
|
||||
]);
|
||||
}
|
||||
if ($pictureSource === 'own') {
|
||||
$canUseOwnPicture = in_array('picture', GameConst::$generalPoolAllowOption, true)
|
||||
&& $env['show_img_level'] >= 1
|
||||
&& $ownerInfo['grade'] >= 1
|
||||
&& $ownerInfo['picture'] !== '';
|
||||
if (!$canUseOwnPicture) {
|
||||
Json::die([
|
||||
'result' => false,
|
||||
'reason' => '사용할 수 있는 내 전콘이 없습니다.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$gencount = $db->queryFirstField('SELECT count(`no`) FROM general WHERE npc<2');
|
||||
@@ -80,12 +113,25 @@ if ($gencount >= $maxgeneral) {
|
||||
|
||||
$poolClass = getGeneralPoolClass(GameConst::$targetGeneralPool);
|
||||
/** @var AbsGeneralPool */
|
||||
$pickedGeneral = new $poolClass($db, $selectInfo, $now);
|
||||
if ($isCentennialAllStar) {
|
||||
$rng = new RandUtil(new LiteHashDRBG(Util::simpleSerialize(
|
||||
UniqueConst::$hiddenSeed,
|
||||
'selectPickedGeneral',
|
||||
$userID,
|
||||
$pick
|
||||
)));
|
||||
$pickedGeneral = new $poolClass($db, $rng, $selectInfo, $now);
|
||||
} else {
|
||||
$pickedGeneral = new $poolClass($db, $selectInfo, $now);
|
||||
}
|
||||
|
||||
$builder = $pickedGeneral->getGeneralBuilder();
|
||||
if ($isCentennialAllStar) {
|
||||
CentennialAllStarGrowthService::prepareInitialUser($builder, $selectInfo);
|
||||
}
|
||||
|
||||
foreach(GameConst::$generalPoolAllowOption as $allowOption){
|
||||
if($allowOption == 'stat'){
|
||||
if($allowOption == 'stat' && !$isCentennialAllStar){
|
||||
$leadership = Util::valueFit($leadership, GameConst::$defaultStatMin, GameConst::$defaultStatMax);
|
||||
$strength = Util::valueFit($strength, GameConst::$defaultStatMin, GameConst::$defaultStatMax);
|
||||
$intel = Util::valueFit($intel, GameConst::$defaultStatMin, GameConst::$defaultStatMax);
|
||||
@@ -98,14 +144,23 @@ foreach(GameConst::$generalPoolAllowOption as $allowOption){
|
||||
}
|
||||
$builder->setStat($leadership, $strength, $intel);
|
||||
}
|
||||
else if($allowOption == 'picture' && $use_own_picture){
|
||||
else if(
|
||||
$allowOption == 'picture'
|
||||
&& (
|
||||
(!$isCentennialAllStar && $use_own_picture)
|
||||
|| ($isCentennialAllStar && $pictureSource === 'own')
|
||||
)
|
||||
){
|
||||
$builder->setPicture($ownerInfo['imgsvr'], $ownerInfo['picture']);
|
||||
}
|
||||
else if($allowOption == 'ego'){
|
||||
if(!$personal || $personal == 'Random'){
|
||||
$personal = Util::choiceRandom(GameConst::$availablePersonality);
|
||||
}
|
||||
if(!array_search($personal, GameConst::$availablePersonality)){
|
||||
$invalidPersonal = $isCentennialAllStar
|
||||
? !in_array($personal, GameConst::$availablePersonality, true)
|
||||
: !array_search($personal, GameConst::$availablePersonality);
|
||||
if($invalidPersonal){
|
||||
Json::die([
|
||||
'result'=>false,
|
||||
'reason'=>'올바르지 않은 성격입니다.'
|
||||
@@ -123,6 +178,23 @@ $builder->setKillturn(5);
|
||||
$builder->setNPCType(0);
|
||||
$builder->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $env['turnterm']));
|
||||
$builder->fillRemainSpecAsZero($env);
|
||||
if ($isCentennialAllStar) {
|
||||
$candidateCities = $db->queryFirstColumn(
|
||||
'SELECT city FROM city WHERE level >= 5 AND level <= 6 AND nation = 0'
|
||||
);
|
||||
if (!$candidateCities) {
|
||||
$candidateCities = $db->queryFirstColumn(
|
||||
'SELECT city FROM city WHERE level >= 5 AND level <= 6'
|
||||
);
|
||||
}
|
||||
if (!$candidateCities) {
|
||||
Json::die([
|
||||
'result' => false,
|
||||
'reason' => '장수를 생성할 소·중성이 없습니다.',
|
||||
]);
|
||||
}
|
||||
$builder->setCityID($rng->choice($candidateCities));
|
||||
}
|
||||
$builder->build($env);
|
||||
$generalID = $builder->getGeneralID();
|
||||
if(!$generalID){
|
||||
|
||||
@@ -7,6 +7,7 @@ include "func.php";
|
||||
WebUtil::requireAJAX();
|
||||
|
||||
$pick = Util::getPost('pick');
|
||||
$pictureSource = Util::getPost('picture_source', 'string', 'selected');
|
||||
|
||||
if(!$pick){
|
||||
Json::die([
|
||||
@@ -35,10 +36,20 @@ if(!$generalID){
|
||||
list(
|
||||
$year,
|
||||
$month,
|
||||
$startYear,
|
||||
$maxgeneral,
|
||||
$npcmode,
|
||||
$turnterm
|
||||
) = $gameStor->getValuesAsArray(['year', 'month', 'maxgeneral', 'npcmode', 'turnterm']);
|
||||
$turnterm,
|
||||
$showImgLevel
|
||||
) = $gameStor->getValuesAsArray([
|
||||
'year',
|
||||
'month',
|
||||
'startyear',
|
||||
'maxgeneral',
|
||||
'npcmode',
|
||||
'turnterm',
|
||||
'show_img_level',
|
||||
]);
|
||||
|
||||
if($npcmode!=2){
|
||||
Json::die([
|
||||
@@ -55,7 +66,10 @@ if(!$info){
|
||||
]);
|
||||
}
|
||||
|
||||
$ownerInfo = RootDB::db()->queryFirstRow('SELECT `name`,`picture`,`imgsvr` FROM member WHERE `NO`=%i',$userID);
|
||||
$ownerInfo = RootDB::db()->queryFirstRow(
|
||||
'SELECT `name`,`picture`,`imgsvr`,`grade` FROM member WHERE `NO`=%i',
|
||||
$userID
|
||||
);
|
||||
if(!$ownerInfo){
|
||||
Json::die([
|
||||
'result'=>false,
|
||||
@@ -64,6 +78,27 @@ if(!$ownerInfo){
|
||||
}
|
||||
|
||||
$info = Json::decode($info);
|
||||
$isCentennialAllStar = CentennialAllStarGrowthService::isActive();
|
||||
if ($isCentennialAllStar) {
|
||||
if (!in_array($pictureSource, ['current', 'own', 'selected'], true)) {
|
||||
Json::die([
|
||||
'result' => false,
|
||||
'reason' => '올바르지 않은 전콘 선택입니다.',
|
||||
]);
|
||||
}
|
||||
if ($pictureSource === 'own') {
|
||||
$canUseOwnPicture = in_array('picture', GameConst::$generalPoolAllowOption, true)
|
||||
&& $showImgLevel >= 1
|
||||
&& $ownerInfo['grade'] >= 1
|
||||
&& $ownerInfo['picture'] !== '';
|
||||
if (!$canUseOwnPicture) {
|
||||
Json::die([
|
||||
'result' => false,
|
||||
'reason' => '사용할 수 있는 내 전콘이 없습니다.',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$generalObj = General::createObjFromDB($generalID);
|
||||
@@ -101,34 +136,51 @@ $db->update('select_pool',[
|
||||
'reserved_until'=>null,
|
||||
], '(owner=%i or reserved_until < %s) AND general_id is NULL', $userID, $now);
|
||||
|
||||
if(key_exists('leadership', $info)){
|
||||
$generalObj->updateVar('leadership', $info['leadership']);
|
||||
$generalObj->updateVar('strength', $info['strength']);
|
||||
$generalObj->updateVar('intel', $info['intel']);
|
||||
if ($isCentennialAllStar) {
|
||||
CentennialAllStarGrowthService::prepareLegacyUserReselection($generalObj);
|
||||
CentennialAllStarGrowthService::applyTarget($generalObj, $info, [
|
||||
'startyear' => $startYear,
|
||||
'year' => $year,
|
||||
'month' => $month,
|
||||
]);
|
||||
} else {
|
||||
if(key_exists('leadership', $info)){
|
||||
$generalObj->updateVar('leadership', $info['leadership']);
|
||||
$generalObj->updateVar('strength', $info['strength']);
|
||||
$generalObj->updateVar('intel', $info['intel']);
|
||||
}
|
||||
if(key_exists('dex', $info)){
|
||||
$generalObj->updateVar('dex1', $info['dex'][0]);
|
||||
$generalObj->updateVar('dex2', $info['dex'][1]);
|
||||
$generalObj->updateVar('dex3', $info['dex'][2]);
|
||||
$generalObj->updateVar('dex4', $info['dex'][3]);
|
||||
$generalObj->updateVar('dex5', $info['dex'][4]);
|
||||
}
|
||||
if(key_exists('ego', $info)){
|
||||
$generalObj->updateVar('personal', $info['ego']);
|
||||
}
|
||||
if(key_exists('specialDomestic', $info)){
|
||||
$generalObj->updateVar('special', $info['specialDomestic']);
|
||||
}
|
||||
if(key_exists('specialWar', $info)){
|
||||
$generalObj->updateVar('special2', $info['specialWar']);
|
||||
}
|
||||
}
|
||||
if(key_exists('picture', $info)){
|
||||
if ($isCentennialAllStar) {
|
||||
if ($pictureSource === 'own') {
|
||||
$generalObj->updateVar('imgsvr', $ownerInfo['imgsvr']);
|
||||
$generalObj->updateVar('picture', $ownerInfo['picture']);
|
||||
} elseif ($pictureSource === 'selected' && key_exists('picture', $info)) {
|
||||
$generalObj->updateVar('imgsvr', $info['imgsvr']);
|
||||
$generalObj->updateVar('picture', $info['picture']);
|
||||
}
|
||||
} elseif(key_exists('picture', $info)){
|
||||
$generalObj->updateVar('imgsvr', $info['imgsvr']);
|
||||
$generalObj->updateVar('picture', $info['picture']);
|
||||
}
|
||||
if(key_exists('generalName', $info)){
|
||||
$generalObj->updateVar('name', $info['generalName']);
|
||||
}
|
||||
if(key_exists('dex', $info)){
|
||||
$generalObj->updateVar('dex1', $info['dex'][0]);
|
||||
$generalObj->updateVar('dex2', $info['dex'][1]);
|
||||
$generalObj->updateVar('dex3', $info['dex'][2]);
|
||||
$generalObj->updateVar('dex4', $info['dex'][3]);
|
||||
$generalObj->updateVar('dex5', $info['dex'][4]);
|
||||
}
|
||||
if(key_exists('ego', $info)){
|
||||
$generalObj->updateVar('personal', $info['ego']);
|
||||
}
|
||||
if(key_exists('specialDomestic', $info)){
|
||||
$generalObj->updateVar('special', $info['specialDomestic']);
|
||||
}
|
||||
if(key_exists('specialWar', $info)){
|
||||
$generalObj->updateVar('special2', $info['specialWar']);
|
||||
}
|
||||
$generalObj->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $turnterm));
|
||||
|
||||
$userNick = $ownerInfo['name'];
|
||||
|
||||
@@ -230,6 +230,7 @@ function processWar_NG(
|
||||
WarUnitGeneral $attacker,
|
||||
callable $getNextDefender,
|
||||
WarUnitCity $city,
|
||||
?callable $trace = null,
|
||||
): bool {
|
||||
$templates = new \League\Plates\Engine(__DIR__ . '/templates');
|
||||
|
||||
@@ -245,6 +246,26 @@ function processWar_NG(
|
||||
/** @var WarUnit */
|
||||
$defender = ($getNextDefender)(null, true);
|
||||
$conquerCity = false;
|
||||
$traceSeq = 0;
|
||||
$emitTrace = function (string $event, ?WarUnit $currentDefender, array $details = []) use (
|
||||
$trace,
|
||||
&$traceSeq,
|
||||
$attacker,
|
||||
$city
|
||||
): void {
|
||||
if ($trace === null) {
|
||||
return;
|
||||
}
|
||||
$trace([
|
||||
'seq' => $traceSeq++,
|
||||
'event' => $event,
|
||||
'attacker' => buildWarTraceUnitSnapshot($attacker),
|
||||
'defender' => $currentDefender === null ? null : buildWarTraceUnitSnapshot($currentDefender),
|
||||
'city' => buildWarTraceUnitSnapshot($city),
|
||||
'details' => $details,
|
||||
]);
|
||||
};
|
||||
$emitTrace('battle_start', $defender, ['seed' => $warSeed]);
|
||||
|
||||
$josaRo = JosaUtil::pick($city->getName(), '로');
|
||||
$josaYi = JosaUtil::pick($attacker->getName(), '이');
|
||||
@@ -277,6 +298,7 @@ function processWar_NG(
|
||||
$logger->pushGlobalHistoryLog("<M><b>【패퇴】</b></><D><b>{$defender->getNationVar('name')}</b></>{$josaYi} 병량 부족으로 <G><b>{$defender->getName()}</b></>{$josaUl} 뺏기고 말았습니다.");
|
||||
|
||||
$conquerCity = true;
|
||||
$emitTrace('supply_retreat', $defender);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -332,18 +354,34 @@ function processWar_NG(
|
||||
$initCaller->merge($defender->getGeneral()->getBattleInitSkillTriggerList($defender));
|
||||
|
||||
$initCaller->fire($attacker->rng, [], [$attacker, $defender]);
|
||||
$emitTrace('opponent_initialized', $defender);
|
||||
}
|
||||
|
||||
$attacker->beginPhase();
|
||||
$defender->beginPhase();
|
||||
if ($trace !== null) {
|
||||
$emitTrace('phase_power', $defender, [
|
||||
'attackerAttack' => $attacker->getComputedAttack(),
|
||||
'attackerDefence' => $attacker->getComputedDefence(),
|
||||
'attackerTrain' => $attacker->getComputedTrain(),
|
||||
'attackerAtmos' => $attacker->getComputedAtmos(),
|
||||
'defenderAttack' => $defender->getComputedAttack(),
|
||||
'defenderDefence' => $defender->getComputedDefence(),
|
||||
'defenderTrain' => $defender->getComputedTrain(),
|
||||
'defenderAtmos' => $defender->getComputedAtmos(),
|
||||
]);
|
||||
}
|
||||
|
||||
$battleCaller = $attacker->getGeneral()->getBattlePhaseSkillTriggerList($attacker);
|
||||
$battleCaller->merge($defender->getGeneral()->getBattlePhaseSkillTriggerList($defender));
|
||||
|
||||
$battleCaller->fire($attacker->rng, [], [$attacker, $defender]);
|
||||
$emitTrace('phase_triggered', $defender);
|
||||
|
||||
$deadDefender = $attacker->calcDamage();
|
||||
$deadAttacker = $defender->calcDamage();
|
||||
$rawDeadAttacker = $deadAttacker;
|
||||
$rawDeadDefender = $deadDefender;
|
||||
|
||||
$attackerHP = $attacker->getHP();
|
||||
$defenderHP = $defender->getHP();
|
||||
@@ -371,6 +409,14 @@ function processWar_NG(
|
||||
|
||||
$attacker->increaseKilled($deadDefender);
|
||||
$defender->increaseKilled($deadAttacker);
|
||||
$emitTrace('phase_damage', $defender, [
|
||||
'rawDeadAttacker' => $rawDeadAttacker,
|
||||
'rawDeadDefender' => $rawDeadDefender,
|
||||
'deadAttacker' => $deadAttacker,
|
||||
'deadDefender' => $deadDefender,
|
||||
'attackerHpBefore' => $attackerHP,
|
||||
'defenderHpBefore' => $defenderHP,
|
||||
]);
|
||||
|
||||
if($defender->getPhase() < 0){
|
||||
$phaseNickname = '先';
|
||||
@@ -394,8 +440,10 @@ function processWar_NG(
|
||||
|
||||
$attacker->addPhase();
|
||||
$defender->addPhase();
|
||||
$emitTrace('phase_end', $defender);
|
||||
|
||||
if (!$attacker->continueWar($noRice)) {
|
||||
$emitTrace('attacker_stopped', $defender, ['noRice' => (bool)$noRice]);
|
||||
$logWritten = true;
|
||||
|
||||
$attacker->logBattleResult();
|
||||
@@ -420,6 +468,7 @@ function processWar_NG(
|
||||
}
|
||||
|
||||
if (!$defender->continueWar($noRice)) {
|
||||
$emitTrace('defender_stopped', $defender, ['noRice' => (bool)$noRice]);
|
||||
$logWritten = true;
|
||||
|
||||
$attacker->logBattleResult();
|
||||
@@ -462,6 +511,7 @@ function processWar_NG(
|
||||
|
||||
$defender->finishBattle();
|
||||
$defender = ($getNextDefender)($defender, true);
|
||||
$emitTrace('opponent_switched', $defender);
|
||||
|
||||
if ($defender !== null && !($defender instanceof WarUnitGeneral)) {
|
||||
throw new \RuntimeException('다음 수비자를 받아오는데 실패');
|
||||
@@ -497,10 +547,60 @@ function processWar_NG(
|
||||
}
|
||||
|
||||
($getNextDefender)($defender, false);
|
||||
$emitTrace('battle_end', $defender, ['conquered' => $conquerCity]);
|
||||
|
||||
return $conquerCity;
|
||||
}
|
||||
|
||||
function buildWarTraceUnitSnapshot(WarUnit $unit): array
|
||||
{
|
||||
$snapshot = [
|
||||
'kind' => $unit instanceof WarUnitGeneral ? 'general' : 'city',
|
||||
'id' => $unit instanceof WarUnitGeneral
|
||||
? $unit->getGeneral()->getID()
|
||||
: $unit->getVar('city'),
|
||||
'name' => $unit->getName(),
|
||||
'isAttacker' => $unit->isAttacker(),
|
||||
'crewTypeId' => $unit->getCrewType()->id,
|
||||
'phase' => $unit->getPhase(),
|
||||
'realPhase' => $unit->getRealPhase(),
|
||||
'maxPhase' => $unit->getMaxPhase(),
|
||||
'hp' => $unit->getHP(),
|
||||
'rawWarPower' => $unit->getRawWarPower(),
|
||||
'warPower' => $unit->getWarPower(),
|
||||
'warPowerMultiplier' => $unit->getWarPowerMultiply(),
|
||||
'killed' => $unit->getKilled(),
|
||||
'dead' => $unit->getDead(),
|
||||
'activatedSkills' => $unit->getActivatedSkillLog(),
|
||||
];
|
||||
|
||||
if ($unit instanceof WarUnitGeneral) {
|
||||
$general = $unit->getGeneral();
|
||||
$snapshot['general'] = [
|
||||
'crew' => $general->getVar('crew'),
|
||||
'rice' => $general->getVar('rice'),
|
||||
'train' => $general->getVar('train'),
|
||||
'atmos' => $general->getVar('atmos'),
|
||||
'injury' => $general->getVar('injury'),
|
||||
'experience' => $general->getVar('experience'),
|
||||
'dedication' => $general->getVar('dedication'),
|
||||
'dex1' => $general->getVar('dex1'),
|
||||
'dex2' => $general->getVar('dex2'),
|
||||
'dex3' => $general->getVar('dex3'),
|
||||
'dex4' => $general->getVar('dex4'),
|
||||
'dex5' => $general->getVar('dex5'),
|
||||
];
|
||||
} else {
|
||||
$snapshot['cityState'] = [
|
||||
'defence' => $unit->getVar('def'),
|
||||
'wall' => $unit->getVar('wall'),
|
||||
'population' => $unit->getVar('pop'),
|
||||
];
|
||||
}
|
||||
|
||||
return $snapshot;
|
||||
}
|
||||
|
||||
function DeleteConflict($nation)
|
||||
{
|
||||
$db = DB::db();
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace sammo\API\InheritAction;
|
||||
|
||||
use sammo\Session;
|
||||
use DateTimeInterface;
|
||||
use sammo\CentennialAllStarGrowthService;
|
||||
use sammo\DB;
|
||||
use sammo\Enums\APIRecoveryType;
|
||||
use sammo\Enums\RankColumn;
|
||||
@@ -98,6 +99,10 @@ class ResetStat extends \sammo\BaseAPI
|
||||
return 'NPC는 능력치 초기화를 할 수 없습니다.';
|
||||
}
|
||||
|
||||
if (!CentennialAllStarGrowthService::isStatResetAllowed()) {
|
||||
return '100기 올스타 장수는 능력치 초기화를 사용할 수 없습니다.';
|
||||
}
|
||||
|
||||
|
||||
$db = DB::db();
|
||||
$gameStor = KVStorage::getStorage($db, 'game_env');
|
||||
|
||||
@@ -8,6 +8,11 @@ use sammo\Util;
|
||||
|
||||
abstract class AbsFromUserPool extends AbsGeneralPool{
|
||||
|
||||
protected static function getCandidateWeight(array $info, int $owner): int|float
|
||||
{
|
||||
return array_sum($info['dex'] ?? []);
|
||||
}
|
||||
|
||||
public function occupyGeneralName(): bool
|
||||
{
|
||||
$generalID = $this->getGeneralBuilder()->getGeneralID();
|
||||
@@ -36,8 +41,7 @@ abstract class AbsFromUserPool extends AbsGeneralPool{
|
||||
$pool = [];
|
||||
foreach($db->query('SELECT id, unique_name, info FROM select_pool WHERE reserved_until IS NULL AND general_id IS NULL', $pickCnt) as $cand){
|
||||
$cand['info'] = Json::decode($cand['info']);
|
||||
$dexTotal = array_sum($cand['info']['dex']);
|
||||
$pool[] = [$cand, $dexTotal];
|
||||
$pool[] = [$cand, static::getCandidateWeight($cand['info'], $owner)];
|
||||
}
|
||||
|
||||
if(count($pool) < $pickCnt){
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
<?php
|
||||
|
||||
namespace sammo;
|
||||
|
||||
use sammo\Scenario\GeneralBuilder;
|
||||
|
||||
final class CentennialAllStarGrowthService
|
||||
{
|
||||
public const POOL_CLASS = 'SPoolUnderU100';
|
||||
public const AUX_KEY = 'event100_allstar';
|
||||
public const TRAIT_UNLOCK_PROGRESS = 0.4;
|
||||
public const NPC_PROGRESS_MULTIPLIER = 0.9;
|
||||
|
||||
private const STAT_KEYS = ['leadership', 'strength', 'intel'];
|
||||
private const DEX_KEYS = ['dex1', 'dex2', 'dex3', 'dex4', 'dex5'];
|
||||
|
||||
public static function isActive(): bool
|
||||
{
|
||||
return GameConst::$targetGeneralPool === self::POOL_CLASS;
|
||||
}
|
||||
|
||||
public static function isStatResetAllowed(): bool
|
||||
{
|
||||
return !self::isActive();
|
||||
}
|
||||
|
||||
public static function initialAux(array $targetInfo, ?array $userInitialStats = null): array
|
||||
{
|
||||
$granted = array_fill_keys(array_merge(self::STAT_KEYS, self::DEX_KEYS), 0);
|
||||
if ($userInitialStats !== null) {
|
||||
foreach (self::STAT_KEYS as $key) {
|
||||
$initial = (int) ($userInitialStats[$key] ?? GameConst::$defaultStatMin);
|
||||
$granted[$key] = max(0, $initial - min($initial, GameConst::$defaultStatMin));
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'targetId' => (string) ($targetInfo['uniqueName'] ?? ''),
|
||||
'granted' => $granted,
|
||||
'dexConsumed' => array_fill_keys(self::DEX_KEYS, 0),
|
||||
'dexFloor' => array_fill_keys(self::DEX_KEYS, 0),
|
||||
'progressMonth' => -1,
|
||||
'milestone' => 0,
|
||||
'naturalSpecialDomestic' => null,
|
||||
'eventSpecialDomestic' => null,
|
||||
'userInitialStats' => $userInitialStats,
|
||||
'dexTargetRatio' => 1.0,
|
||||
];
|
||||
}
|
||||
|
||||
public static function attachInitialTarget(GeneralBuilder $builder, array $targetInfo): void
|
||||
{
|
||||
$builder->setAuxVar(self::AUX_KEY, self::initialAux($targetInfo));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an ordinary-user stat total while preserving the selected
|
||||
* candidate's relative strengths as closely as integer stats allow.
|
||||
*
|
||||
* @return array{leadership:int,strength:int,intel:int}
|
||||
*/
|
||||
public static function calculateUserInitialStats(array $targetInfo): array
|
||||
{
|
||||
$targets = [];
|
||||
$bases = [];
|
||||
foreach (self::STAT_KEYS as $key) {
|
||||
$target = min(
|
||||
GameConst::$defaultStatMax,
|
||||
max(0, (int) ($targetInfo[$key] ?? 0))
|
||||
);
|
||||
$targets[$key] = $target;
|
||||
$bases[$key] = min($target, GameConst::$defaultStatMin);
|
||||
}
|
||||
|
||||
$targetTotal = array_sum($targets);
|
||||
$desiredTotal = min(GameConst::$defaultStatTotal, $targetTotal);
|
||||
$baseTotal = array_sum($bases);
|
||||
$capacityTotal = $targetTotal - $baseTotal;
|
||||
if ($capacityTotal <= 0 || $desiredTotal <= $baseTotal) {
|
||||
return $bases;
|
||||
}
|
||||
|
||||
$ratio = ($desiredTotal - $baseTotal) / $capacityTotal;
|
||||
$result = [];
|
||||
$fractions = [];
|
||||
foreach (self::STAT_KEYS as $idx => $key) {
|
||||
$raw = $bases[$key] + ($targets[$key] - $bases[$key]) * $ratio;
|
||||
$result[$key] = (int) floor($raw);
|
||||
$fractions[] = [
|
||||
'key' => $key,
|
||||
'fraction' => $raw - $result[$key],
|
||||
'order' => $idx,
|
||||
];
|
||||
}
|
||||
|
||||
usort($fractions, static function (array $lhs, array $rhs): int {
|
||||
$fractionOrder = $rhs['fraction'] <=> $lhs['fraction'];
|
||||
return $fractionOrder !== 0 ? $fractionOrder : $lhs['order'] <=> $rhs['order'];
|
||||
});
|
||||
$remainder = $desiredTotal - array_sum($result);
|
||||
foreach ($fractions as $fraction) {
|
||||
if ($remainder <= 0) {
|
||||
break;
|
||||
}
|
||||
$key = $fraction['key'];
|
||||
if ($result[$key] >= $targets[$key]) {
|
||||
continue;
|
||||
}
|
||||
$result[$key]++;
|
||||
$remainder--;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the event stat baseline that a newly selected target receives at
|
||||
* the supplied game date. Organic growth can still leave the actual stat
|
||||
* above this baseline.
|
||||
*
|
||||
* @return array{leadership:int,strength:int,intel:int}
|
||||
*/
|
||||
public static function calculateUserCurrentTargetStats(
|
||||
array $targetInfo,
|
||||
array $env
|
||||
): array {
|
||||
$initialStats = self::calculateUserInitialStats($targetInfo);
|
||||
$progress = self::calculateProgress(
|
||||
(int) $env['startyear'],
|
||||
(int) $env['year'],
|
||||
(int) $env['month']
|
||||
);
|
||||
$result = [];
|
||||
foreach (self::STAT_KEYS as $key) {
|
||||
$target = min(
|
||||
GameConst::$maxLevel,
|
||||
max(0, (int) ($targetInfo[$key] ?? 0))
|
||||
);
|
||||
$result[$key] = max(
|
||||
$initialStats[$key],
|
||||
CentennialAllStarGrowth::statFloor(
|
||||
$target,
|
||||
GameConst::$defaultStatMin,
|
||||
$progress
|
||||
)
|
||||
);
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
public static function prepareInitialUser(
|
||||
GeneralBuilder $builder,
|
||||
array $targetInfo
|
||||
): void {
|
||||
$initialStats = self::calculateUserInitialStats($targetInfo);
|
||||
$builder->setStat(
|
||||
$initialStats['leadership'],
|
||||
$initialStats['strength'],
|
||||
$initialStats['intel']
|
||||
);
|
||||
$builder->setAuxVar(
|
||||
self::AUX_KEY,
|
||||
self::initialAux($targetInfo, $initialStats)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Old 100th-season characters did not distinguish their form-entered
|
||||
* initial stats from organic growth. Before their first reselection, treat
|
||||
* the ordinary creation range as the replaceable initial allocation.
|
||||
*/
|
||||
public static function prepareLegacyUserReselection(General $general): void
|
||||
{
|
||||
$aux = $general->getAuxVar(self::AUX_KEY);
|
||||
if (!is_array($aux) || is_array($aux['userInitialStats'] ?? null)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$granted = is_array($aux['granted'] ?? null)
|
||||
? $aux['granted']
|
||||
: array_fill_keys(array_merge(self::STAT_KEYS, self::DEX_KEYS), 0);
|
||||
$legacyInitialStats = [];
|
||||
foreach (self::STAT_KEYS as $key) {
|
||||
$current = (int) $general->getVar($key);
|
||||
$granted[$key] = self::calculateLegacyUserGrant(
|
||||
$current,
|
||||
(int) ($granted[$key] ?? 0)
|
||||
);
|
||||
$beforeEventGrant = max(
|
||||
0,
|
||||
$current - max(0, (int) ($aux['granted'][$key] ?? 0))
|
||||
);
|
||||
$legacyInitialStats[$key] = min(
|
||||
$beforeEventGrant,
|
||||
GameConst::$defaultStatMax
|
||||
);
|
||||
}
|
||||
$aux['granted'] = $granted;
|
||||
$aux['userInitialStats'] = $legacyInitialStats;
|
||||
$general->setAuxVar(self::AUX_KEY, $aux);
|
||||
}
|
||||
|
||||
public static function calculateLegacyUserGrant(int $current, int $eventGrant): int
|
||||
{
|
||||
$eventGrant = max(0, $eventGrant);
|
||||
$beforeEventGrant = max(0, $current - $eventGrant);
|
||||
$replaceableInitialGrant = max(
|
||||
0,
|
||||
min($beforeEventGrant, GameConst::$defaultStatMax)
|
||||
- min($beforeEventGrant, GameConst::$defaultStatMin)
|
||||
);
|
||||
return $eventGrant + $replaceableInitialGrant;
|
||||
}
|
||||
|
||||
public static function calculateProgress(
|
||||
int $startYear,
|
||||
int $year,
|
||||
int $month,
|
||||
float $progressMultiplier = 1.0
|
||||
): float {
|
||||
if ($progressMultiplier < 0 || $progressMultiplier > 1) {
|
||||
throw new \InvalidArgumentException('progress multiplier must be between 0 and 1');
|
||||
}
|
||||
return min(
|
||||
1,
|
||||
CentennialAllStarGrowth::progress($startYear, $year, $month)
|
||||
* $progressMultiplier
|
||||
);
|
||||
}
|
||||
|
||||
public static function calculateDexTargetFloor(
|
||||
int $target,
|
||||
array $env,
|
||||
float $targetRatio = 1.0
|
||||
): int {
|
||||
if ($targetRatio < 0 || $targetRatio > 1) {
|
||||
throw new \InvalidArgumentException('dex target ratio must be between 0 and 1');
|
||||
}
|
||||
$target = min(GameConst::$dexLimit, max(0, $target));
|
||||
$scaledTarget = (int) floor($target * $targetRatio);
|
||||
$progress = self::calculateProgress(
|
||||
(int) $env['startyear'],
|
||||
(int) $env['year'],
|
||||
(int) $env['month']
|
||||
);
|
||||
return CentennialAllStarGrowth::dexFloor($scaledTarget, $progress);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutates the General object but leaves persistence to the caller.
|
||||
*
|
||||
* @return array{progress:float,milestone:int,previousMilestone:int,targetChanged:bool,changed:bool}
|
||||
*/
|
||||
public static function applyTarget(
|
||||
General $general,
|
||||
array $targetInfo,
|
||||
array $env,
|
||||
float $progressMultiplier = 1.0,
|
||||
float $dexTargetRatio = 1.0
|
||||
): array
|
||||
{
|
||||
$startYear = (int) $env['startyear'];
|
||||
$year = (int) $env['year'];
|
||||
$month = (int) $env['month'];
|
||||
$progress = self::calculateProgress(
|
||||
$startYear,
|
||||
$year,
|
||||
$month,
|
||||
$progressMultiplier
|
||||
);
|
||||
$progressMonth = (int) floor(
|
||||
max(0, ($year - $startYear) * 12 + $month - 1)
|
||||
* $progressMultiplier
|
||||
);
|
||||
$targetId = (string) ($targetInfo['uniqueName'] ?? '');
|
||||
|
||||
$aux = $general->getAuxVar(self::AUX_KEY);
|
||||
if (!is_array($aux)) {
|
||||
$aux = self::initialAux($targetInfo);
|
||||
}
|
||||
$granted = is_array($aux['granted'] ?? null)
|
||||
? $aux['granted']
|
||||
: array_fill_keys(array_merge(self::STAT_KEYS, self::DEX_KEYS), 0);
|
||||
$targetChanged = ($aux['targetId'] ?? '') !== $targetId;
|
||||
$dexConsumed = is_array($aux['dexConsumed'] ?? null)
|
||||
? $aux['dexConsumed']
|
||||
: array_fill_keys(self::DEX_KEYS, 0);
|
||||
if ($targetChanged) {
|
||||
$dexConsumed = array_fill_keys(self::DEX_KEYS, 0);
|
||||
}
|
||||
$dexFloor = is_array($aux['dexFloor'] ?? null)
|
||||
? $aux['dexFloor']
|
||||
: array_fill_keys(self::DEX_KEYS, 0);
|
||||
$isUserTarget = is_array($aux['userInitialStats'] ?? null);
|
||||
$nextUserInitialStats = $targetChanged && $isUserTarget
|
||||
? self::calculateUserInitialStats($targetInfo)
|
||||
: ($aux['userInitialStats'] ?? null);
|
||||
$previousDexTargetRatio = is_numeric($aux['dexTargetRatio'] ?? null)
|
||||
? (float) $aux['dexTargetRatio']
|
||||
: 1.0;
|
||||
$dexTargetRatioChanged = $previousDexTargetRatio !== $dexTargetRatio;
|
||||
$userCurrentTargetStats = $isUserTarget
|
||||
? self::calculateUserCurrentTargetStats($targetInfo, $env)
|
||||
: null;
|
||||
$changed = $dexTargetRatioChanged;
|
||||
|
||||
foreach (self::STAT_KEYS as $key) {
|
||||
if (!array_key_exists($key, $targetInfo)) {
|
||||
continue;
|
||||
}
|
||||
$target = min(GameConst::$maxLevel, max(0, (int) $targetInfo[$key]));
|
||||
$floor = CentennialAllStarGrowth::statFloor(
|
||||
$target,
|
||||
GameConst::$defaultStatMin,
|
||||
$progress
|
||||
);
|
||||
if ($userCurrentTargetStats !== null) {
|
||||
$floor = $userCurrentTargetStats[$key];
|
||||
}
|
||||
$current = (int) $general->getVar($key);
|
||||
if ($targetChanged) {
|
||||
$result = CentennialAllStarGrowth::replaceTarget(
|
||||
$current,
|
||||
(int) ($granted[$key] ?? 0),
|
||||
$floor
|
||||
);
|
||||
} else {
|
||||
$result = CentennialAllStarGrowth::advance(
|
||||
$current,
|
||||
(int) ($granted[$key] ?? 0),
|
||||
$floor
|
||||
);
|
||||
}
|
||||
if ($result['value'] !== $current) {
|
||||
$general->updateVar($key, $result['value']);
|
||||
$changed = true;
|
||||
}
|
||||
$granted[$key] = $result['granted'];
|
||||
}
|
||||
|
||||
$targetDex = $targetInfo['dex'] ?? [];
|
||||
foreach (self::DEX_KEYS as $idx => $key) {
|
||||
if (!array_key_exists($idx, $targetDex)) {
|
||||
continue;
|
||||
}
|
||||
$floor = max(
|
||||
0,
|
||||
self::calculateDexTargetFloor(
|
||||
(int) $targetDex[$idx],
|
||||
$env,
|
||||
$dexTargetRatio
|
||||
) - max(0, (int) ($dexConsumed[$key] ?? 0))
|
||||
);
|
||||
$dexFloor[$key] = $floor;
|
||||
$current = (int) $general->getVar($key);
|
||||
if ($targetChanged || $dexTargetRatioChanged) {
|
||||
$result = CentennialAllStarGrowth::replaceTarget(
|
||||
$current,
|
||||
(int) ($granted[$key] ?? 0),
|
||||
$floor
|
||||
);
|
||||
} else {
|
||||
$result = CentennialAllStarGrowth::advance(
|
||||
$current,
|
||||
(int) ($granted[$key] ?? 0),
|
||||
$floor
|
||||
);
|
||||
}
|
||||
if ($result['value'] !== $current) {
|
||||
$general->updateVar($key, $result['value']);
|
||||
$changed = true;
|
||||
}
|
||||
$granted[$key] = $result['granted'];
|
||||
}
|
||||
|
||||
$oldEventSpecial = $aux['eventSpecialDomestic'] ?? null;
|
||||
if ($targetChanged && $oldEventSpecial !== null
|
||||
&& $general->getVar('special') === $oldEventSpecial
|
||||
) {
|
||||
$general->updateVar(
|
||||
'special',
|
||||
$aux['naturalSpecialDomestic'] ?? GameConst::$defaultSpecialDomestic
|
||||
);
|
||||
$changed = true;
|
||||
$aux['eventSpecialDomestic'] = null;
|
||||
}
|
||||
|
||||
$targetSpecial = $targetInfo['specialDomestic'] ?? null;
|
||||
if ($progress >= self::TRAIT_UNLOCK_PROGRESS && is_string($targetSpecial) && $targetSpecial !== '') {
|
||||
if (($aux['naturalSpecialDomestic'] ?? null) === null) {
|
||||
$aux['naturalSpecialDomestic'] = $general->getVar('special');
|
||||
}
|
||||
if ($general->getVar('special') !== $targetSpecial) {
|
||||
$general->updateVar('special', $targetSpecial);
|
||||
$changed = true;
|
||||
}
|
||||
$aux['eventSpecialDomestic'] = $targetSpecial;
|
||||
}
|
||||
|
||||
$previousMilestone = (int) ($aux['milestone'] ?? 0);
|
||||
$milestone = min(5, (int) floor($progress * 5 + 0.0000001));
|
||||
$aux['targetId'] = $targetId;
|
||||
$aux['granted'] = $granted;
|
||||
$aux['dexConsumed'] = $dexConsumed;
|
||||
$aux['dexFloor'] = $dexFloor;
|
||||
$aux['progressMonth'] = max((int) ($aux['progressMonth'] ?? -1), $progressMonth);
|
||||
$aux['milestone'] = max($previousMilestone, $milestone);
|
||||
$aux['userInitialStats'] = $nextUserInitialStats;
|
||||
$aux['dexTargetRatio'] = $dexTargetRatio;
|
||||
$general->setAuxVar(self::AUX_KEY, $aux);
|
||||
|
||||
return [
|
||||
'progress' => $progress,
|
||||
'milestone' => $milestone,
|
||||
'previousMilestone' => $previousMilestone,
|
||||
'targetChanged' => $targetChanged,
|
||||
'changed' => $changed || $targetChanged || $milestone > $previousMilestone,
|
||||
];
|
||||
}
|
||||
|
||||
public static function progressMultiplierFor(General $general): float
|
||||
{
|
||||
return self::progressMultiplierForNPCType($general->getNPCType());
|
||||
}
|
||||
|
||||
public static function progressMultiplierForNPCType(int $npcType): float
|
||||
{
|
||||
return in_array($npcType, [3, 4], true)
|
||||
? self::NPC_PROGRESS_MULTIPLIER
|
||||
: 1.0;
|
||||
}
|
||||
|
||||
public static function dexTargetRatioForNPCType(int $npcType): float
|
||||
{
|
||||
return in_array($npcType, [3, 4], true)
|
||||
? GameConst::$centennialNpcDexTargetRatio
|
||||
: 1.0;
|
||||
}
|
||||
|
||||
public static function applyCurrentTargetToBuiltNPC(
|
||||
\MeekroDB $db,
|
||||
GeneralBuilder $builder,
|
||||
array $targetInfo,
|
||||
array $env
|
||||
): ?array {
|
||||
if (!self::isActive()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$general = General::createObjFromDB($builder->getGeneralID());
|
||||
if (!in_array($general->getNPCType(), [3, 4], true)) {
|
||||
return null;
|
||||
}
|
||||
$result = self::applyTarget(
|
||||
$general,
|
||||
$targetInfo,
|
||||
$env,
|
||||
self::NPC_PROGRESS_MULTIPLIER,
|
||||
GameConst::$centennialNpcDexTargetRatio
|
||||
);
|
||||
$general->applyDB($db);
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the event-backed part of a dex conversion with the converted
|
||||
* value and consumes any guaranteed floor crossed by the source value.
|
||||
* This keeps the monthly floor from refilling points already converted.
|
||||
*/
|
||||
public static function reconcileDexConversion(
|
||||
General $general,
|
||||
string $sourceKey,
|
||||
string $destinationKey,
|
||||
int $sourceBefore,
|
||||
int $sourceAfter,
|
||||
int $destinationBefore,
|
||||
int $destinationAfter,
|
||||
float $convertCoeff
|
||||
): void {
|
||||
if (!in_array($sourceKey, self::DEX_KEYS, true)
|
||||
|| !in_array($destinationKey, self::DEX_KEYS, true)
|
||||
|| $sourceKey === $destinationKey
|
||||
) {
|
||||
throw new \InvalidArgumentException('invalid dex conversion keys');
|
||||
}
|
||||
if ($convertCoeff < 0 || $convertCoeff > 1) {
|
||||
throw new \InvalidArgumentException('dex conversion coefficient must be between 0 and 1');
|
||||
}
|
||||
|
||||
$sourceDecrease = max(0, $sourceBefore - $sourceAfter);
|
||||
$destinationIncrease = max(0, $destinationAfter - $destinationBefore);
|
||||
if ($sourceDecrease === 0 && $destinationIncrease === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$aux = $general->getAuxVar(self::AUX_KEY);
|
||||
if (!is_array($aux)) {
|
||||
return;
|
||||
}
|
||||
$granted = is_array($aux['granted'] ?? null)
|
||||
? $aux['granted']
|
||||
: array_fill_keys(array_merge(self::STAT_KEYS, self::DEX_KEYS), 0);
|
||||
$dexConsumed = is_array($aux['dexConsumed'] ?? null)
|
||||
? $aux['dexConsumed']
|
||||
: array_fill_keys(self::DEX_KEYS, 0);
|
||||
$dexFloor = is_array($aux['dexFloor'] ?? null)
|
||||
? $aux['dexFloor']
|
||||
: [];
|
||||
|
||||
$sourceGrantedBefore = min(
|
||||
max(0, $sourceBefore),
|
||||
max(0, (int) ($granted[$sourceKey] ?? 0))
|
||||
);
|
||||
/*
|
||||
* A dex value can contain both organic and event-backed points. Split
|
||||
* the actual command deltas by their share of the source total instead
|
||||
* of consuming either bucket first. This keeps the combined ownership
|
||||
* stable when conversion and target reselection are interleaved.
|
||||
*/
|
||||
$eventGrantRemoved = $sourceBefore > 0
|
||||
? intdiv($sourceDecrease * $sourceGrantedBefore, $sourceBefore)
|
||||
: 0;
|
||||
$sourceGrantedAfter = max(0, $sourceGrantedBefore - $eventGrantRemoved);
|
||||
|
||||
$destinationGrantedBefore = min(
|
||||
max(0, $destinationBefore),
|
||||
max(0, (int) ($granted[$destinationKey] ?? 0))
|
||||
);
|
||||
$eventGrantTransferred = $sourceBefore > 0
|
||||
? intdiv($destinationIncrease * $sourceGrantedBefore, $sourceBefore)
|
||||
: 0;
|
||||
$eventGrantTransferred = min(
|
||||
$destinationIncrease,
|
||||
$eventGrantRemoved,
|
||||
$eventGrantTransferred
|
||||
);
|
||||
$granted[$sourceKey] = $sourceGrantedAfter;
|
||||
$granted[$destinationKey] = min(
|
||||
max(0, $destinationAfter),
|
||||
$destinationGrantedBefore + $eventGrantTransferred
|
||||
);
|
||||
|
||||
$sourceFloor = max(
|
||||
0,
|
||||
(int) ($dexFloor[$sourceKey] ?? $sourceBefore)
|
||||
);
|
||||
$gapBefore = max(0, $sourceFloor - $sourceBefore);
|
||||
$gapAfter = max(0, $sourceFloor - $sourceAfter);
|
||||
$dexConsumed[$sourceKey] = max(
|
||||
0,
|
||||
(int) ($dexConsumed[$sourceKey] ?? 0)
|
||||
+ max(0, $gapAfter - $gapBefore)
|
||||
);
|
||||
|
||||
$aux['granted'] = $granted;
|
||||
$aux['dexConsumed'] = $dexConsumed;
|
||||
$general->setAuxVar(self::AUX_KEY, $aux);
|
||||
}
|
||||
|
||||
public static function recordableValue(General $general, string $key): int
|
||||
{
|
||||
$aux = $general->getAuxVar(self::AUX_KEY);
|
||||
$granted = is_array($aux) && is_array($aux['granted'] ?? null)
|
||||
? (int) ($aux['granted'][$key] ?? 0)
|
||||
: 0;
|
||||
return CentennialAllStarGrowth::recordableValue((int) $general->getVar($key), $granted);
|
||||
}
|
||||
|
||||
public static function recordableRawValue(array $general, string $key): int
|
||||
{
|
||||
$aux = Json::decode($general['aux'] ?? '{}');
|
||||
$eventAux = is_array($aux[self::AUX_KEY] ?? null) ? $aux[self::AUX_KEY] : [];
|
||||
$granted = is_array($eventAux['granted'] ?? null)
|
||||
? (int) ($eventAux['granted'][$key] ?? 0)
|
||||
: 0;
|
||||
return CentennialAllStarGrowth::recordableValue((int) ($general[$key] ?? 0), $granted);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ use function \sammo\tryUniqueItemLottery;
|
||||
|
||||
use \sammo\Constraint\ConstraintHelper;
|
||||
use sammo\StaticEventHandler;
|
||||
use sammo\CentennialAllStarGrowthService;
|
||||
|
||||
class che_숙련전환 extends Command\GeneralCommand
|
||||
{
|
||||
@@ -157,6 +158,7 @@ class che_숙련전환 extends Command\GeneralCommand
|
||||
$logger = $general->getLogger();
|
||||
|
||||
$srcDex = $general->getVar('dex' . $this->srcArmType);
|
||||
$destDex = $general->getVar('dex' . $this->destArmType);
|
||||
$cutDex = Util::toInt($srcDex * static::$decreaseCoeff);
|
||||
$cutDexText = number_format($cutDex);
|
||||
$addDex = Util::toInt($cutDex * static::$convertCoeff);
|
||||
@@ -164,6 +166,19 @@ class che_숙련전환 extends Command\GeneralCommand
|
||||
|
||||
$general->increaseVar('dex' . $this->srcArmType, -$cutDex);
|
||||
$general->increaseVar('dex' . $this->destArmType, $addDex);
|
||||
// 100기 이벤트 지급분을 목적 숙련으로 옮기고 소비한 성장 하한은 다시 채우지 않는다.
|
||||
if (CentennialAllStarGrowthService::isActive()) {
|
||||
CentennialAllStarGrowthService::reconcileDexConversion(
|
||||
$general,
|
||||
'dex' . $this->srcArmType,
|
||||
'dex' . $this->destArmType,
|
||||
$srcDex,
|
||||
$general->getVar('dex' . $this->srcArmType),
|
||||
$destDex,
|
||||
$general->getVar('dex' . $this->destArmType),
|
||||
static::$convertCoeff
|
||||
);
|
||||
}
|
||||
|
||||
$josaUl = JosaUtil::pick($cutDex, '을');
|
||||
$josaRo = JosaUtil::pick($addDex, '로');
|
||||
|
||||
@@ -7,6 +7,7 @@ use \sammo\Util;
|
||||
use \sammo\JosaUtil;
|
||||
use \sammo\General;
|
||||
use \sammo\ActionLogger;
|
||||
use \sammo\CentennialAllStarGrowthService;
|
||||
use \sammo\GameConst;
|
||||
use \sammo\LastTurn;
|
||||
use \sammo\GameUnitConst;
|
||||
@@ -190,6 +191,12 @@ class che_인재탐색 extends Command\GeneralCommand
|
||||
$newNPC->fillRemainSpecAsRandom($pickTypeList, $avgGen, $env);
|
||||
|
||||
$newNPC->build($this->env);
|
||||
CentennialAllStarGrowthService::applyCurrentTargetToBuiltNPC(
|
||||
$db,
|
||||
$newNPC,
|
||||
$pickedNPC->getInfo(),
|
||||
$this->env
|
||||
);
|
||||
$pickedNPC->occupyGeneralName();
|
||||
$npcName = $newNPC->getGeneralName();
|
||||
$josaRa = JosaUtil::pick($npcName, '라');
|
||||
|
||||
@@ -7,6 +7,7 @@ use \sammo\Util;
|
||||
use \sammo\JosaUtil;
|
||||
use \sammo\General;
|
||||
use \sammo\ActionLogger;
|
||||
use \sammo\CentennialAllStarGrowthService;
|
||||
use \sammo\GameConst;
|
||||
use \sammo\LastTurn;
|
||||
use \sammo\GameUnitConst;
|
||||
@@ -160,6 +161,12 @@ class che_의병모집 extends Command\NationCommand
|
||||
$newNPC->fillRemainSpecAsRandom($pickTypeList, $avgGen, $env);
|
||||
|
||||
$newNPC->build($this->env);
|
||||
CentennialAllStarGrowthService::applyCurrentTargetToBuiltNPC(
|
||||
$db,
|
||||
$newNPC,
|
||||
$pickedNPC->getInfo(),
|
||||
$this->env
|
||||
);
|
||||
$pickedNPC->occupyGeneralName();
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace sammo\Event\Action;
|
||||
|
||||
use sammo\ActionLogger;
|
||||
use sammo\CentennialAllStarGrowthService;
|
||||
use sammo\DB;
|
||||
use sammo\General;
|
||||
use sammo\Json;
|
||||
|
||||
class AdvanceCentennialAllStar extends \sammo\Event\Action
|
||||
{
|
||||
public function run(array $env)
|
||||
{
|
||||
if (!CentennialAllStarGrowthService::isActive()) {
|
||||
return [__CLASS__, 0];
|
||||
}
|
||||
|
||||
$db = DB::db();
|
||||
$updated = 0;
|
||||
foreach ($db->query(
|
||||
'SELECT general.no, select_pool.info
|
||||
FROM general
|
||||
JOIN select_pool ON select_pool.general_id = general.no'
|
||||
) as $row) {
|
||||
$general = General::createObjFromDB((int) $row['no']);
|
||||
$targetInfo = Json::decode($row['info']);
|
||||
$result = CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$targetInfo,
|
||||
$env,
|
||||
CentennialAllStarGrowthService::progressMultiplierFor($general),
|
||||
CentennialAllStarGrowthService::dexTargetRatioForNPCType(
|
||||
$general->getNPCType()
|
||||
)
|
||||
);
|
||||
|
||||
if ($result['milestone'] > $result['previousMilestone']) {
|
||||
$percent = $result['milestone'] * 20;
|
||||
$general->getLogger()->pushGeneralActionLog(
|
||||
"<L>올스타 동조율</>이 <C>{$percent}%</>에 도달했습니다!",
|
||||
ActionLogger::PLAIN
|
||||
);
|
||||
$general->getLogger()->pushGeneralHistoryLog(
|
||||
"<L>올스타 동조율 {$percent}% 달성</>"
|
||||
);
|
||||
}
|
||||
if ($general->applyDB($db)) {
|
||||
$updated++;
|
||||
}
|
||||
}
|
||||
|
||||
return [__CLASS__, $updated];
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ namespace sammo\Event\Action;
|
||||
use \sammo\GameConst;
|
||||
use \sammo\Util;
|
||||
use \sammo\DB;
|
||||
use sammo\CentennialAllStarGrowthService;
|
||||
use sammo\LiteHashDRBG;
|
||||
use sammo\RandUtil;
|
||||
use sammo\UniqueConst;
|
||||
@@ -35,7 +36,8 @@ class CreateManyNPC extends \sammo\Event\Action
|
||||
)));
|
||||
|
||||
$result = [];
|
||||
foreach (pickGeneralFromPool(DB::db(), $rng, 0, $cnt) as $pickedNPC) {
|
||||
$db = DB::db();
|
||||
foreach (pickGeneralFromPool($db, $rng, 0, $cnt) as $pickedNPC) {
|
||||
$age = $rng->nextRangeInt(20, 25);
|
||||
$birthYear = $env['year'] - $age;
|
||||
$deathYear = $env['year'] + $rng->nextRangeInt(10, 50);
|
||||
@@ -50,6 +52,12 @@ class CreateManyNPC extends \sammo\Event\Action
|
||||
}
|
||||
$newNPC->fillRemainSpecAsZero($env);
|
||||
$newNPC->build($env);
|
||||
CentennialAllStarGrowthService::applyCurrentTargetToBuiltNPC(
|
||||
$db,
|
||||
$newNPC,
|
||||
$pickedNPC->getInfo(),
|
||||
$env
|
||||
);
|
||||
$pickedNPC->occupyGeneralName();
|
||||
$result[] = [
|
||||
$newNPC->getGeneralName(), $newNPC->getGeneralID()
|
||||
|
||||
@@ -184,6 +184,10 @@ class GameConstBase
|
||||
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 내정 특기 */
|
||||
public static $optionalSpecialDomestic = [
|
||||
'None',
|
||||
'che_event_귀병', 'che_event_신산', 'che_event_환술', 'che_event_집중', 'che_event_신중',
|
||||
'che_event_반계', 'che_event_보병', 'che_event_궁병', 'che_event_기병', 'che_event_공성',
|
||||
'che_event_돌격', 'che_event_무쌍', 'che_event_견고', 'che_event_위압', 'che_event_저격',
|
||||
'che_event_필살', 'che_event_징병', 'che_event_의술', 'che_event_격노', 'che_event_척사',
|
||||
];
|
||||
|
||||
/** @var string 기본 전투 특기 */
|
||||
@@ -416,6 +420,8 @@ class GameConstBase
|
||||
public static $retirementYear = 80;
|
||||
|
||||
public static $targetGeneralPool = 'RandomNameGeneral';
|
||||
/** @var float 100기 올스타 NPC의 원본 목표 대비 최종 숙련 비율 */
|
||||
public static $centennialNpcDexTargetRatio = 0.4;
|
||||
public static $generalPoolAllowOption = ['stat', 'ego', 'picture'];
|
||||
|
||||
public static $randGenFirstName = [
|
||||
|
||||
@@ -3134,7 +3134,7 @@ class GeneralAI
|
||||
$rawCity = $db->queryFirstRow('SELECT * FROM city WHERE city = %i', $this->general->getCityID());
|
||||
$this->general->setRawCity($rawCity);
|
||||
}
|
||||
if (!in_array($this->general->getRawCity()['level'], [5, 6])) {
|
||||
if (in_array($this->general->getRawCity()['level'], [5, 6])) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace sammo\GeneralPool;
|
||||
|
||||
use sammo\AbsFromUserPool;
|
||||
use sammo\CentennialAllStarGrowthService;
|
||||
use sammo\Json;
|
||||
use sammo\RandUtil;
|
||||
|
||||
class SPoolUnderU100 extends AbsFromUserPool
|
||||
{
|
||||
private const MIN_DEX_WEIGHT = 100000;
|
||||
private const STAT_BONUS_MIN_TOTAL = 160;
|
||||
private const STAT_BONUS_MAX_TOTAL = 190;
|
||||
private const STAT_BONUS_MAX_MULTIPLIER = 1.5;
|
||||
|
||||
public function __construct(\MeekroDB $db, RandUtil $rng, array $info, string $validUntil)
|
||||
{
|
||||
$targetInfo = $info;
|
||||
$initialInfo = $info;
|
||||
foreach ([
|
||||
'leadership',
|
||||
'strength',
|
||||
'intel',
|
||||
'experience',
|
||||
'dedication',
|
||||
'dex',
|
||||
'specialDomestic',
|
||||
'specialWar',
|
||||
] as $targetKey) {
|
||||
unset($initialInfo[$targetKey]);
|
||||
}
|
||||
|
||||
parent::__construct($db, $rng, $initialInfo, $validUntil);
|
||||
$this->info = $targetInfo;
|
||||
CentennialAllStarGrowthService::attachInitialTarget($this->builder, $targetInfo);
|
||||
}
|
||||
|
||||
public static function getPoolName(): string
|
||||
{
|
||||
return '100기 올스타 클래식';
|
||||
}
|
||||
|
||||
protected static function getCandidateWeight(array $info, int $owner): int|float
|
||||
{
|
||||
$dexWeight = max(
|
||||
self::MIN_DEX_WEIGHT,
|
||||
array_sum($info['dex'] ?? [])
|
||||
);
|
||||
if ($owner <= 0) {
|
||||
return $dexWeight;
|
||||
}
|
||||
|
||||
$statTotal = array_sum([
|
||||
(int) ($info['leadership'] ?? 0),
|
||||
(int) ($info['strength'] ?? 0),
|
||||
(int) ($info['intel'] ?? 0),
|
||||
]);
|
||||
$normalizedStat = min(1, max(
|
||||
0,
|
||||
($statTotal - self::STAT_BONUS_MIN_TOTAL)
|
||||
/ (self::STAT_BONUS_MAX_TOTAL - self::STAT_BONUS_MIN_TOTAL)
|
||||
));
|
||||
$statMultiplier = 1
|
||||
+ (self::STAT_BONUS_MAX_MULTIPLIER - 1) * $normalizedStat;
|
||||
|
||||
return $dexWeight * $statMultiplier;
|
||||
}
|
||||
|
||||
public static function initPool(\MeekroDB $db)
|
||||
{
|
||||
$jsonData = Json::decode(file_get_contents(__DIR__ . '/Pool/UnderS100.json'));
|
||||
$columns = $jsonData['columns'];
|
||||
$sqlValues = [];
|
||||
foreach ($jsonData['data'] as $idx => $rawItem) {
|
||||
if (count($rawItem) !== count($columns)) {
|
||||
throw new \RuntimeException(($rawItem[0] ?? (string) $idx) . ' Error');
|
||||
}
|
||||
$item = array_combine($columns, $rawItem);
|
||||
$uniqueName = sprintf('A100%04d', $idx + 1);
|
||||
$item['uniqueName'] = $uniqueName;
|
||||
$item['event100Growth'] = true;
|
||||
$sqlValues[] = [
|
||||
'unique_name' => $uniqueName,
|
||||
'info' => Json::encode($item),
|
||||
];
|
||||
}
|
||||
$db->insert('select_pool', $sqlValues);
|
||||
}
|
||||
}
|
||||
@@ -345,7 +345,7 @@ class InheritancePointManager
|
||||
'general_id'=>$general->getID(),
|
||||
'year'=>$year,
|
||||
'month'=>$month,
|
||||
'value'=>$inheritStor->getAll(true)
|
||||
'value'=>Json::encode($inheritStor->getAll(true))
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,15 @@ class SightseeingMessage{
|
||||
const HeavyWounded = 0x2000;
|
||||
|
||||
static protected $messages = null;
|
||||
static protected ?\sammo\RandUtil $comparisonRng = null;
|
||||
|
||||
public static function setComparisonRng(?\sammo\RandUtil $rng): void
|
||||
{
|
||||
if ($rng !== null && getenv('TURN_DIFFERENTIAL_ENABLED') !== '1') {
|
||||
throw new \RuntimeException('comparison RNG is test-only');
|
||||
}
|
||||
static::$comparisonRng = $rng;
|
||||
}
|
||||
|
||||
protected static function getMessageList():array{
|
||||
/* [[속성, [
|
||||
@@ -104,8 +113,13 @@ class SightseeingMessage{
|
||||
}
|
||||
|
||||
public function pickAction():array{
|
||||
[$type, $texts] = Util::choiceRandomUsingWeightPair(static::$messages??[]);
|
||||
$text = Util::choiceRandom($texts);
|
||||
if (static::$comparisonRng !== null) {
|
||||
[$type, $texts] = static::$comparisonRng->choiceUsingWeightPair(static::$messages ?? []);
|
||||
$text = static::$comparisonRng->choice($texts);
|
||||
} else {
|
||||
[$type, $texts] = Util::choiceRandomUsingWeightPair(static::$messages??[]);
|
||||
$text = Util::choiceRandom($texts);
|
||||
}
|
||||
|
||||
return [$type, $text];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
{
|
||||
"title":"【공백지】 요양 ",
|
||||
"startYear":180,
|
||||
"map":{
|
||||
"mapName":"miniche"
|
||||
},
|
||||
"history":[
|
||||
"<C>●</>180년 1월:<L><b>【이벤트】</b></>쉬었다 가는 깃수입니다."
|
||||
],
|
||||
"const": {
|
||||
"joinRuinedNPCProp":0,
|
||||
"npcBanMessageProb":0.005,
|
||||
"defaultMaxGeneral": 800,
|
||||
"allItems":{
|
||||
"horse":{
|
||||
"che_명마_01_노기":0, "che_명마_02_조랑":0, "che_명마_03_노새":0,
|
||||
"che_명마_04_나귀":0, "che_명마_05_갈색마":0, "che_명마_06_흑색마":0,
|
||||
|
||||
"che_명마_07_백마" : 2, "che_명마_07_기주마" : 2, "che_명마_07_오환마" : 2, "che_명마_07_백상" : 2,
|
||||
"che_명마_08_양주마" : 2, "che_명마_08_흉노마" : 2, "che_명마_09_과하마" : 2, "che_명마_09_의남백마" : 2,
|
||||
"che_명마_10_대완마" : 2, "che_명마_10_옥추마" : 2, "che_명마_11_서량마" : 2, "che_명마_11_화종마" : 2,
|
||||
"che_명마_12_사륜거" : 2, "che_명마_12_옥란백용구": 2, "che_명마_13_절영" : 2, "che_명마_13_적로" : 2,
|
||||
"che_명마_14_적란마" : 2, "che_명마_14_조황비전" : 2, "che_명마_15_한혈마" : 2, "che_명마_15_적토마" : 2
|
||||
},
|
||||
"weapon":{
|
||||
"che_무기_01_단도":0, "che_무기_02_단궁":0, "che_무기_03_단극":0,
|
||||
"che_무기_04_목검":0, "che_무기_05_죽창":0, "che_무기_06_소부":0,
|
||||
|
||||
"che_무기_07_동추":2, "che_무기_07_철편":2, "che_무기_07_철쇄":2, "che_무기_07_맥궁":2,
|
||||
"che_무기_08_유성추":2, "che_무기_08_철질여골":2, "che_무기_09_쌍철극":2, "che_무기_09_동호비궁":2,
|
||||
"che_무기_10_삼첨도":2, "che_무기_10_대부":2, "che_무기_11_고정도":2, "che_무기_11_이광궁":2,
|
||||
"che_무기_12_철척사모":2, "che_무기_12_칠성검":2, "che_무기_13_사모":2, "che_무기_13_양유기궁":2,
|
||||
"che_무기_14_언월도":2, "che_무기_14_방천화극":2, "che_무기_15_청홍검":2, "che_무기_15_의천검":2
|
||||
},
|
||||
"book":{
|
||||
"che_서적_01_효경전":0, "che_서적_02_회남자":0, "che_서적_03_변도론":0,
|
||||
"che_서적_04_건상역주":0, "che_서적_05_여씨춘추":0, "che_서적_06_사민월령":0,
|
||||
|
||||
"che_서적_07_위료자":2, "che_서적_07_사마법":2, "che_서적_07_한서":2, "che_서적_07_논어":2,
|
||||
"che_서적_08_전론":2, "che_서적_08_사기":2, "che_서적_09_장자":2, "che_서적_09_역경":2,
|
||||
"che_서적_10_시경":2, "che_서적_10_구국론":2, "che_서적_11_상군서":2, "che_서적_11_춘추전":2,
|
||||
"che_서적_12_산해경":2, "che_서적_12_맹덕신서":2, "che_서적_13_관자":2, "che_서적_13_병법24편":2,
|
||||
"che_서적_14_한비자":2, "che_서적_14_오자병법":2, "che_서적_15_노자":2, "che_서적_15_손자병법":2
|
||||
},
|
||||
"item":{
|
||||
"che_치료_환약":0, "che_저격_수극":0, "che_사기_탁주":0,
|
||||
"che_훈련_청주":0, "che_계략_이추":0, "che_계략_향낭":0,
|
||||
|
||||
"event_전투특기_격노":0, "event_전투특기_견고":0, "event_전투특기_공성":0, "event_전투특기_궁병":0,
|
||||
"event_전투특기_귀병":0, "event_전투특기_기병":0, "event_전투특기_돌격":0, "event_전투특기_무쌍":0,
|
||||
"event_전투특기_반계":0, "event_전투특기_보병":0, "event_전투특기_신산":0, "event_전투특기_신중":0,
|
||||
"event_전투특기_위압":0, "event_전투특기_의술":0, "event_전투특기_저격":0, "event_전투특기_집중":0,
|
||||
"event_전투특기_징병":0, "event_전투특기_척사":0, "event_전투특기_필살":0, "event_전투특기_환술":0
|
||||
}
|
||||
}
|
||||
},
|
||||
"events":[
|
||||
[
|
||||
"month", 1000,
|
||||
["or", ["Date", "==", null, 12], ["Date", "==", null, 6]],
|
||||
["CreateManyNPC", 15, 10],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"month", 1000,
|
||||
["Date", "==", 181, 1],
|
||||
["RaiseNPCNation"],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"month", 999,
|
||||
["Date", "==", 181, 1],
|
||||
["OpenNationBetting", 4, 5000],
|
||||
["OpenNationBetting", 1, 2000],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"month", 1000,
|
||||
["Date", "==", null, 1],
|
||||
["ChangeCity", "all", {
|
||||
"trade":100
|
||||
}]
|
||||
],
|
||||
[
|
||||
"month", 1000,
|
||||
["Date", "==", null, 7],
|
||||
["ChangeCity", "all", {
|
||||
"trade":100
|
||||
}]
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"title": "【공백지】 100기 올스타 클래식",
|
||||
"startYear": 180,
|
||||
"map": {
|
||||
"mapName": "miniche",
|
||||
"targetGeneralPool": "SPoolUnderU100",
|
||||
"generalPoolAllowOption": ["stat", "ego", "picture"],
|
||||
"centennialNpcDexTargetRatio": 0.4
|
||||
},
|
||||
"history": [
|
||||
"<C>●</>180년 1월:<L><b>【100기 이벤트】</b></> 역대 장수들이 평범한 능력으로 다시 모여, 지난 전성기의 힘과 서서히 동조하기 시작했다!"
|
||||
],
|
||||
"const": {
|
||||
"npcBanMessageProb":0.005,
|
||||
"defaultMaxGeneral": 800,
|
||||
"uniqueTrialCoef": 2
|
||||
},
|
||||
"events": [
|
||||
[
|
||||
"month", 8000,
|
||||
true,
|
||||
["AdvanceCentennialAllStar"]
|
||||
],
|
||||
[
|
||||
"month", 1000,
|
||||
["Date", "==", null, 12],
|
||||
["CreateManyNPC", 100, 0],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"month", 1000,
|
||||
["Date", "==", 181, 1],
|
||||
["RaiseNPCNation"],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"destroy_nation", 1000,
|
||||
["and",
|
||||
["Date", ">=", 183, 1],
|
||||
["RemainNation", "==", 1]
|
||||
],
|
||||
["BlockScoutAction"],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"month", 999,
|
||||
["Date", "==", 181, 1],
|
||||
["OpenNationBetting", 4, 5000],
|
||||
["OpenNationBetting", 1, 2000],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"month", 999,
|
||||
["and",
|
||||
["Date", ">=", 183, 1],
|
||||
["RemainNation", "<=", 8]
|
||||
],
|
||||
["OpenNationBetting", 1, 1000],
|
||||
["DeleteEvent"]
|
||||
],
|
||||
[
|
||||
"destroy_nation", 1000,
|
||||
["and",
|
||||
["Date", ">=", 183, 1],
|
||||
["RemainNation", "==", 1]
|
||||
],
|
||||
["BlockScoutAction"],
|
||||
["DeleteEvent"]
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -19,8 +19,16 @@ if ($admin['npcmode'] != 2) {
|
||||
|
||||
$member = RootDB::db()->queryFirstRow("SELECT no,name,picture,imgsvr,grade from member where no= %i", $userID);
|
||||
|
||||
$generalID = $db->queryFirstField('SELECT no FROM general WHERE owner = %i', $userID);
|
||||
$currentGeneral = $db->queryFirstRow(
|
||||
'SELECT no,picture,imgsvr FROM general WHERE owner = %i',
|
||||
$userID
|
||||
);
|
||||
$generalID = $currentGeneral['no'] ?? null;
|
||||
$gencount = $db->queryFirstField('SELECT count(`no`) FROM general WHERE npc<2');
|
||||
$isCentennialAllStar = CentennialAllStarGrowthService::isActive();
|
||||
$canUseOwnPicture = $admin['show_img_level'] >= 1
|
||||
&& $member['grade'] >= 1
|
||||
&& $member['picture'] != "";
|
||||
|
||||
$nationList = $db->query('SELECT nation,`name`,color,scout FROM nation');
|
||||
shuffle($nationList);
|
||||
@@ -54,6 +62,7 @@ foreach (getCharacterList(false) as $id => [$name, $info]) {
|
||||
|
||||
<script>
|
||||
var hasGeneralID = <?= $generalID === null ? 'false' : 'true' ?>;
|
||||
var isCentennialAllStar = <?= $isCentennialAllStar ? 'true' : 'false' ?>;
|
||||
var defaultStatTotal = <?= GameConst::$defaultStatTotal ?>;
|
||||
var defaultStatMin = <?= GameConst::$defaultStatMin ?>;
|
||||
var defaultStatMax = <?= GameConst::$defaultStatMax ?>;
|
||||
@@ -104,6 +113,27 @@ if ($gencount >= $admin['maxgeneral']) {
|
||||
<small id="valid_until">(<span id="valid_until_text"></span>까지 유효)</small><small id="outdate_token">- 만료 -</small><br>
|
||||
<form class="card_holder">
|
||||
</form>
|
||||
<?php if ($isCentennialAllStar && $generalID !== null) : ?>
|
||||
<div id="reselect_picture_plate" class="picture_choice">
|
||||
<strong>변경 후 전콘</strong>
|
||||
<label>
|
||||
<input type="radio" name="reselect_picture_source" value="selected" checked>
|
||||
새로 선택할 장수 전콘
|
||||
</label>
|
||||
<label>
|
||||
<input type="radio" name="reselect_picture_source" value="current">
|
||||
<img width="32" height="32" src="<?= GetImageURL($currentGeneral['imgsvr']) ?>/<?= $currentGeneral['picture'] ?>" border="0">
|
||||
현재 장수 전콘
|
||||
</label>
|
||||
<?php if ($canUseOwnPicture) : ?>
|
||||
<label>
|
||||
<input type="radio" name="reselect_picture_source" value="own">
|
||||
<img width="32" height="32" src="<?= GetImageURL($member['imgsvr']) ?>/<?= $member['picture'] ?>" border="0">
|
||||
내 원래 전콘
|
||||
</label>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -117,7 +147,28 @@ if ($gencount >= $admin['maxgeneral']) {
|
||||
<form id='custom_form'>
|
||||
<table class='tb_layout' style='width:100%;text-align:left;'>
|
||||
<?php
|
||||
if ($admin['show_img_level'] >= 1 && $member['grade'] >= 1 && $member['picture'] != "") {
|
||||
if ($isCentennialAllStar) {
|
||||
echo "
|
||||
<tr class='event_picture'>
|
||||
<td align=right class='bg1'>전콘 선택</td>
|
||||
<td colspan=2>
|
||||
<label><input type=radio name=picture_source value=selected checked> 선택한 장수 전콘</label>
|
||||
";
|
||||
if ($canUseOwnPicture) {
|
||||
$imageTemp = GetImageURL($member['imgsvr']);
|
||||
echo "
|
||||
<label>
|
||||
<input type=radio name=picture_source value=own>
|
||||
<img width='64' height='64' src='{$imageTemp}/{$member['picture']}' border='0'>
|
||||
내 전콘
|
||||
</label>
|
||||
";
|
||||
}
|
||||
echo "
|
||||
</td>
|
||||
</tr>
|
||||
";
|
||||
} elseif ($canUseOwnPicture) {
|
||||
$imageTemp = GetImageURL($member['imgsvr']);
|
||||
echo "
|
||||
<tr class='custom_picture'>
|
||||
@@ -144,36 +195,42 @@ if ($gencount >= $admin['maxgeneral']) {
|
||||
</select> <span id="charInfoText"></span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>통솔</td>
|
||||
<td colspan=2><input type="number" name="leadership" id="leadership" value="50"></td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>무력</td>
|
||||
<td colspan=2><input type="number" name="strength" id="strength" value="50"></td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>지력</td>
|
||||
<td colspan=2><input type="number" name="intel" id="intel" value="50"></td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>능력치 조정</td>
|
||||
<td colspan=2>
|
||||
<input type=button value=랜덤형 onclick=abilityRand()>
|
||||
<input type=button value=통솔무력형 onclick=abilityLeadpow()>
|
||||
<input type=button value=통솔지력형 onclick=abilityLeadint()>
|
||||
<input type=button value=무력지력형 onclick=abilityPowint()>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=center colspan=3>
|
||||
<font color=orange>모든 능력치는 ( <?= GameConst::$defaultStatMin ?> <= 능력치 <=<?= GameConst::$defaultStatMax ?> ) 사이로 잡으셔야 합니다.<br>
|
||||
그 외의 능력치는 가입되지 않습니다.</font>
|
||||
</td>
|
||||
</tr>
|
||||
<?php if (!$isCentennialAllStar) : ?>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>통솔</td>
|
||||
<td colspan=2><input type="number" name="leadership" id="leadership" value="50"></td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>무력</td>
|
||||
<td colspan=2><input type="number" name="strength" id="strength" value="50"></td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>지력</td>
|
||||
<td colspan=2><input type="number" name="intel" id="intel" value="50"></td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=right class='bg1'>능력치 조정</td>
|
||||
<td colspan=2>
|
||||
<input type=button value=랜덤형 onclick=abilityRand()>
|
||||
<input type=button value=통솔무력형 onclick=abilityLeadpow()>
|
||||
<input type=button value=통솔지력형 onclick=abilityLeadint()>
|
||||
<input type=button value=무력지력형 onclick=abilityPowint()>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class='custom_stat'>
|
||||
<td align=center colspan=3>
|
||||
<font color=orange>모든 능력치는 ( <?= GameConst::$defaultStatMin ?> <= 능력치 <=<?= GameConst::$defaultStatMax ?> ) 사이로 잡으셔야 합니다.<br>
|
||||
그 외의 능력치는 가입되지 않습니다.</font>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endif; ?>
|
||||
<tr>
|
||||
<td align=center colspan=3>
|
||||
<span class='custom_stat'>능력치의 총합은 <?= GameConst::$defaultStatTotal ?>입니다. 가입후 0~10의 능력치 보너스를 받게 됩니다.<br></span>
|
||||
<?php if ($isCentennialAllStar) : ?>
|
||||
선택한 장수의 최종 능력치 비율을 반영한 약화 능력치로 시작합니다.<br>
|
||||
<?php else : ?>
|
||||
<span class='custom_stat'>능력치의 총합은 <?= GameConst::$defaultStatTotal ?>입니다. 가입후 0~10의 능력치 보너스를 받게 됩니다.<br></span>
|
||||
<?php endif; ?>
|
||||
임의의 도시에서 재야로 시작하며 건국과 임관은 게임 내에서 실행합니다.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -172,7 +172,7 @@
|
||||
<BButton class="col-6 offset-6" variant="primary" @click="checkOwner"> 소유자 찾기 </BButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col col-lg-4 col-sm-6 col-12 py-2">
|
||||
<div v-if="canResetStat" class="col col-lg-4 col-sm-6 col-12 py-2">
|
||||
<div class="row px-4">
|
||||
<div class="a-right col-6 align-self-center">능력치 초기화</div>
|
||||
<div class="col-6">
|
||||
@@ -222,6 +222,17 @@
|
||||
<BButton class="col-6 offset-6" variant="primary" @click="resetStat"> 능력치 초기화</BButton>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="col col-lg-4 col-sm-6 col-12 py-2">
|
||||
<div class="row px-4">
|
||||
<div class="a-right col-6 align-self-center">능력치 초기화</div>
|
||||
<div class="col-6 align-self-center">사용 불가</div>
|
||||
</div>
|
||||
<div class="a-right">
|
||||
<small class="form-text text-muted">
|
||||
100기 올스타 장수는 장수 전환 시 능력치 성장 기록을 보존하기 위해 능력치 초기화를 사용할 수 없습니다.
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<div class="col">
|
||||
@@ -297,6 +308,7 @@ declare const staticValues: {
|
||||
}
|
||||
>;
|
||||
availableTargetGeneral: Record<number, string>;
|
||||
canResetStat: boolean;
|
||||
currentStat: {
|
||||
leadership: number;
|
||||
strength: number;
|
||||
@@ -447,6 +459,7 @@ const {
|
||||
availableSpecialWar,
|
||||
availableUnique,
|
||||
availableTargetGeneral,
|
||||
canResetStat,
|
||||
currentStat
|
||||
} = staticValues;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { AutoLoginFailed, AutoLoginNonceResponse, AutoLoginResponse, LoginFailed, LoginResponse } from "./defs/API/Login";
|
||||
import { APIPathGen } from "./util/APIPathGen";
|
||||
import { callSammoAPI, extractHttpMethod, GET, POST, type APICallT, type APITail, type InvalidResponse, type RawArgType, type ValidResponse } from "./util/callSammoAPI";
|
||||
import { callSammoAPI, extractHttpMethod, POST, type APICallT, type APITail, type InvalidResponse, type RawArgType, type ValidResponse } from "./util/callSammoAPI";
|
||||
export type { ValidResponse, InvalidResponse };
|
||||
|
||||
const apiRealPath = {
|
||||
@@ -18,7 +18,7 @@ const apiRealPath = {
|
||||
hashedToken: string,
|
||||
token_id: number,
|
||||
}, AutoLoginResponse, AutoLoginFailed>,
|
||||
ReqNonce: GET as APICallT<undefined, AutoLoginNonceResponse, AutoLoginFailed>
|
||||
ReqNonce: POST as APICallT<undefined, AutoLoginNonceResponse, AutoLoginFailed>
|
||||
},
|
||||
} as const;
|
||||
|
||||
|
||||
+47
-32
@@ -37,14 +37,16 @@ function regNextToken(tokenInfo: [number, string]) {
|
||||
function getToken(): [number, string] | undefined {
|
||||
const trialToken = localStorage.getItem(LOGIN_TOKEN_KEY);
|
||||
if (!trialToken) {
|
||||
console.log('no token');
|
||||
return;
|
||||
}
|
||||
const tokenItems = JSON.parse(trialToken) as [number, [number, string], string];
|
||||
const tokenItems = JSON.parse(trialToken) as [number, [number, string], number];
|
||||
if (tokenItems[0] != TOKEN_VERSION) {
|
||||
console.log(tokenItems);
|
||||
resetToken();
|
||||
return;
|
||||
}
|
||||
console.debug(localStorage.getItem(LOGIN_TOKEN_KEY));
|
||||
const [, token,] = tokenItems;
|
||||
return token;
|
||||
}
|
||||
@@ -62,39 +64,54 @@ async function tryAutoLogin() {
|
||||
|
||||
const [tokenID, token] = tokenInfo;
|
||||
|
||||
const result = await SammoRootAPI.Login.ReqNonce(undefined, true);
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const reqNonceStartAt = Date.now();
|
||||
const nonceResult = await SammoRootAPI.Login.ReqNonce(undefined, true);
|
||||
|
||||
if (!result) {
|
||||
//api 에러.
|
||||
return;
|
||||
}
|
||||
|
||||
if (!result.result) {
|
||||
resetToken();
|
||||
return;
|
||||
}
|
||||
|
||||
const nonce = result.loginNonce;
|
||||
|
||||
const hashedToken = sha512(token + nonce);
|
||||
const loginResult = await SammoRootAPI.Login.LoginByToken({
|
||||
'hashedToken': hashedToken,
|
||||
'token_id': tokenID,
|
||||
}, true);
|
||||
|
||||
if (!loginResult.result) {
|
||||
if (!loginResult.silent) {
|
||||
alert(loginResult.reason);
|
||||
if (!nonceResult) {
|
||||
//api 에러.
|
||||
return;
|
||||
}
|
||||
console.error(loginResult.reason);
|
||||
|
||||
if (!nonceResult.result) {
|
||||
resetToken();
|
||||
return;
|
||||
}
|
||||
|
||||
const nonce = nonceResult.loginNonce;
|
||||
console.debug(
|
||||
'try auto login with token',
|
||||
tokenID,
|
||||
`attempt:${attempt + 1}`,
|
||||
`reqNonceElapsed:${Date.now() - reqNonceStartAt}ms`
|
||||
);
|
||||
|
||||
const hashedToken = sha512(token + nonce);
|
||||
const loginResult = await SammoRootAPI.Login.LoginByToken({
|
||||
'hashedToken': hashedToken,
|
||||
'token_id': tokenID,
|
||||
}, true);
|
||||
|
||||
if (!loginResult.result) {
|
||||
if (loginResult.reason === '자동 로그인: 절차 오류' && attempt === 0) {
|
||||
console.warn('auto login failed by procedure error. retrying once.');
|
||||
await delay(150);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!loginResult.silent) {
|
||||
alert(loginResult.reason);
|
||||
}
|
||||
console.error(loginResult.reason);
|
||||
return;
|
||||
}
|
||||
|
||||
if (loginResult.nextToken) {
|
||||
regNextToken(loginResult.nextToken);
|
||||
}
|
||||
window.location.href = "./";
|
||||
return;
|
||||
}
|
||||
|
||||
if (loginResult.nextToken) {
|
||||
regNextToken(loginResult.nextToken);
|
||||
}
|
||||
window.location.href = "./";
|
||||
|
||||
}
|
||||
catch (e) {
|
||||
if (isString(e)) {
|
||||
@@ -103,8 +120,6 @@ async function tryAutoLogin() {
|
||||
console.error(e);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
function getOAuthToken(mode: string, scope_list?: string[] | string) {
|
||||
|
||||
@@ -28,6 +28,15 @@ type CardItem = {
|
||||
|
||||
personal?: string,
|
||||
personalText?: string,
|
||||
event100Growth?: boolean,
|
||||
leadership?: number,
|
||||
strength?: number,
|
||||
intel?: number,
|
||||
selectionStatLabel?: string,
|
||||
selectionLeadership?: number,
|
||||
selectionStrength?: number,
|
||||
selectionIntel?: number,
|
||||
dex?: number[],
|
||||
}
|
||||
|
||||
type GeneralPoolResponse = {
|
||||
@@ -38,6 +47,7 @@ type GeneralPoolResponse = {
|
||||
|
||||
declare const characterInfo: Record<string, { name: string, info: string }>;
|
||||
declare const hasGeneralID: number;
|
||||
declare const isCentennialAllStar: boolean;
|
||||
declare let currentGeneralInfo: CardItem | undefined;
|
||||
declare const cards: Record<string, CardItem>;
|
||||
declare const validCustomOption: string[];
|
||||
@@ -45,9 +55,14 @@ declare const validCustomOption: string[];
|
||||
const templateGeneralCard = '<div class="general_card">\
|
||||
<h4 class="bg1 with_border"><%generalName%></h4>\
|
||||
<h4><img src="<%iconPath%>" height=64 width=64></h4><p>\
|
||||
<%if(event100Growth){%><b>195년 최종 동조 목표</b><br><%}%>\
|
||||
<%if(leadership){%>\
|
||||
<%leadership%> / <%strength%> / <%intel%><br>\
|
||||
<%}%>\
|
||||
<%if(selectionStatLabel){%>\
|
||||
<b><%selectionStatLabel%></b><br>\
|
||||
<%selectionLeadership%> / <%selectionStrength%> / <%selectionIntel%><br>\
|
||||
<%}%>\
|
||||
<%if(personalText){%><%personalText%><br><%}%>\
|
||||
<%if(specialDomesticText||specialWarText){%>\
|
||||
<%specialDomesticText%> / <%specialWarText%><br>\
|
||||
@@ -102,7 +117,10 @@ async function pickGeneral(this: HTMLElement, e: JQuery.Event) {
|
||||
method: 'post',
|
||||
responseType: 'json',
|
||||
data: convertFormData({
|
||||
pick: unwrap_any<string>($btn.val())
|
||||
pick: unwrap_any<string>($btn.val()),
|
||||
picture_source: unwrap_any<string>(
|
||||
$('input[name="reselect_picture_source"]:checked').val() ?? 'selected'
|
||||
)
|
||||
})
|
||||
});
|
||||
result = response.data;
|
||||
@@ -132,18 +150,24 @@ async function buildGeneral(e: JQuery.Event) {
|
||||
|
||||
let result: InvalidResponse;
|
||||
try {
|
||||
const formData: Record<string, string|number|boolean> = {
|
||||
pick: unwrap(currentGeneralInfo).uniqueName,
|
||||
use_own_picture: $('#use_own_picture').is(':checked'),
|
||||
picture_source: unwrap_any<string>(
|
||||
$('input[name="picture_source"]:checked').val() ?? 'selected'
|
||||
),
|
||||
personal: unwrap_any<string>($('#selChar').val())
|
||||
};
|
||||
if (!isCentennialAllStar) {
|
||||
formData.leadership = parseInt(unwrap_any<string>($('#leadership').val()));
|
||||
formData.strength = parseInt(unwrap_any<string>($('#leadership').val()));
|
||||
formData.intel = parseInt(unwrap_any<string>($('#leadership').val()));
|
||||
}
|
||||
const response = await axios({
|
||||
url: 'j_select_picked_general.php',
|
||||
method: 'post',
|
||||
responseType: 'json',
|
||||
data: convertFormData({
|
||||
pick: unwrap(currentGeneralInfo).uniqueName,
|
||||
use_own_picture: $('#use_own_picture').is(':checked'),
|
||||
leadership: parseInt(unwrap_any<string>($('#leadership').val())),
|
||||
strength: parseInt(unwrap_any<string>($('#leadership').val())),
|
||||
intel: parseInt(unwrap_any<string>($('#leadership').val())),
|
||||
personal: unwrap_any<string>($('#selChar').val())
|
||||
})
|
||||
data: convertFormData(formData)
|
||||
})
|
||||
result = response.data;
|
||||
if (!result.result) {
|
||||
@@ -192,6 +216,10 @@ function printGenerals(value: GeneralPoolResponse) {
|
||||
'leadership': null,
|
||||
'strength': null,
|
||||
'intel': null,
|
||||
'selectionStatLabel': null,
|
||||
'selectionLeadership': null,
|
||||
'selectionStrength': null,
|
||||
'selectionIntel': null,
|
||||
'personalText': null,
|
||||
'specialDomesticText': null,
|
||||
'specialWarText': null,
|
||||
|
||||
@@ -105,6 +105,7 @@ $lastInheritPointLogs = $db->query('SELECT id, server_id, year, month, date, tex
|
||||
'availableUnique' => $availableUnique,
|
||||
'lastInheritPointLogs' => $lastInheritPointLogs,
|
||||
'availableTargetGeneral' => $availableTargetGeneral,
|
||||
'canResetStat' => CentennialAllStarGrowthService::isStatResetAllowed(),
|
||||
'currentStat' => [
|
||||
'leadership' => Util::clamp($me->getVar('leadership'), GameConst::$defaultStatMin, GameConst::$defaultStatMax),
|
||||
'strength' => Util::clamp($me->getVar('strength'), GameConst::$defaultStatMin, GameConst::$defaultStatMax),
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@
|
||||
"main": "js/index.js",
|
||||
"scripts": {
|
||||
"test": "npm-run-all test-php-gateway test-ts",
|
||||
"test-php-gateway": "vendor/bin/phpunit --bootstrap vendor/autoload.php tests",
|
||||
"test-php-gateway": "vendor/bin/phpunit --do-not-cache-result --bootstrap vendor/autoload.php tests",
|
||||
"test-ts": "mocha",
|
||||
"build": "webpack",
|
||||
"buildDev": "webpack --mode=development",
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Build the static 100th-season all-star pool from a tab-separated query result.
|
||||
*
|
||||
* Usage:
|
||||
* mariadb --batch --raw --skip-column-names DATABASE \
|
||||
* < src/centennial_allstar_candidates.sql \
|
||||
* | php src/build_centennial_allstar_pool.php OUTPUT.json
|
||||
*/
|
||||
|
||||
const OUTPUT_COLUMNS = [
|
||||
'generalName',
|
||||
'leadership',
|
||||
'strength',
|
||||
'intel',
|
||||
'specialDomestic',
|
||||
'dex',
|
||||
'imgsvr',
|
||||
'picture',
|
||||
'sourcePhase',
|
||||
'sourceServerId',
|
||||
'sourceGeneralNo',
|
||||
'selectionReasons',
|
||||
];
|
||||
|
||||
const EXCLUDED_EVENT_PHASES = [
|
||||
5, 10, 15, 20, 25, 30, 35, 40, 45, 50,
|
||||
55, 60, 65, 70, 75, 80, 85, 90, 95,
|
||||
];
|
||||
|
||||
const LEGACY_SPECIAL_WAR_MAP = [
|
||||
40 => 'che_event_귀병',
|
||||
41 => 'che_event_신산',
|
||||
42 => 'che_event_환술',
|
||||
43 => 'che_event_집중',
|
||||
44 => 'che_event_신중',
|
||||
45 => 'che_event_반계',
|
||||
50 => 'che_event_보병',
|
||||
51 => 'che_event_궁병',
|
||||
52 => 'che_event_기병',
|
||||
53 => 'che_event_공성',
|
||||
60 => 'che_event_돌격',
|
||||
61 => 'che_event_무쌍',
|
||||
62 => 'che_event_견고',
|
||||
63 => 'che_event_위압',
|
||||
70 => 'che_event_저격',
|
||||
71 => 'che_event_필살',
|
||||
72 => 'che_event_징병',
|
||||
73 => 'che_event_의술',
|
||||
74 => 'che_event_격노',
|
||||
75 => 'che_event_척사',
|
||||
];
|
||||
|
||||
function fail(string $message): never
|
||||
{
|
||||
fwrite(STDERR, "error: {$message}\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
function firstInt(array $data, array $keys): int
|
||||
{
|
||||
foreach ($keys as $key) {
|
||||
if (array_key_exists($key, $data) && is_numeric($data[$key])) {
|
||||
return (int) $data[$key];
|
||||
}
|
||||
}
|
||||
fail('missing numeric field: ' . implode(' or ', $keys));
|
||||
}
|
||||
|
||||
function normalizeEventSpecial(mixed $rawSpecial): ?string
|
||||
{
|
||||
if (is_numeric($rawSpecial)) {
|
||||
return LEGACY_SPECIAL_WAR_MAP[(int) $rawSpecial] ?? null;
|
||||
}
|
||||
if (
|
||||
!is_string($rawSpecial)
|
||||
|| $rawSpecial === ''
|
||||
|| $rawSpecial === '0'
|
||||
|| strcasecmp($rawSpecial, 'none') === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (str_starts_with($rawSpecial, 'che_event_')) {
|
||||
return $rawSpecial;
|
||||
}
|
||||
if (str_starts_with($rawSpecial, 'che_')) {
|
||||
return 'che_event_' . substr($rawSpecial, strlen('che_'));
|
||||
}
|
||||
fail("unknown historical war special: {$rawSpecial}");
|
||||
}
|
||||
|
||||
function decodeSourceRow(string $line, int $lineNo): array
|
||||
{
|
||||
$fields = explode("\t", rtrim($line, "\r\n"), 6);
|
||||
if (count($fields) !== 6) {
|
||||
fail("line {$lineNo}: expected 6 tab-separated fields, got " . count($fields));
|
||||
}
|
||||
|
||||
[$phase, $serverId, $generalNo, $name, $rawData, $rawReasons] = $fields;
|
||||
$data = json_decode($rawData, true, 512, JSON_THROW_ON_ERROR);
|
||||
if (!is_array($data)) {
|
||||
fail("line {$lineNo}: general data is not an object");
|
||||
}
|
||||
|
||||
$phaseNo = (int) $phase;
|
||||
$sourceGeneralNo = (int) $generalNo;
|
||||
if ($phaseNo < 1 || $phaseNo > 99 || $sourceGeneralNo <= 2) {
|
||||
fail("line {$lineNo}: invalid phase/general number");
|
||||
}
|
||||
|
||||
$sourceName = trim($name);
|
||||
if ($sourceName === '') {
|
||||
fail("line {$lineNo}: empty general name");
|
||||
}
|
||||
$generalName = sprintf('%d·%s', $phaseNo, $sourceName);
|
||||
if (mb_strlen($generalName) > 32) {
|
||||
fail("line {$lineNo}: generated name exceeds 32 characters: {$generalName}");
|
||||
}
|
||||
|
||||
$dex = [
|
||||
firstInt($data, ['dex1', 'dex0']),
|
||||
firstInt($data, ['dex2', 'dex10']),
|
||||
firstInt($data, ['dex3', 'dex20']),
|
||||
firstInt($data, ['dex4', 'dex30']),
|
||||
firstInt($data, ['dex5', 'dex40']),
|
||||
];
|
||||
foreach ($dex as $value) {
|
||||
if ($value < 0) {
|
||||
fail("line {$lineNo}: negative dex value");
|
||||
}
|
||||
}
|
||||
|
||||
$reasons = $rawReasons === '' ? [] : explode(',', $rawReasons);
|
||||
sort($reasons, SORT_STRING);
|
||||
|
||||
return [
|
||||
$generalName,
|
||||
firstInt($data, ['leadership', 'leader']),
|
||||
firstInt($data, ['strength', 'power']),
|
||||
firstInt($data, ['intel']),
|
||||
normalizeEventSpecial($data['special2'] ?? null),
|
||||
$dex,
|
||||
firstInt($data, ['imgsvr']),
|
||||
is_string($data['picture'] ?? null) && $data['picture'] !== ''
|
||||
? $data['picture']
|
||||
: 'default.jpg',
|
||||
$phaseNo,
|
||||
$serverId,
|
||||
$sourceGeneralNo,
|
||||
$reasons,
|
||||
];
|
||||
}
|
||||
|
||||
if ($argc !== 2) {
|
||||
fail('usage: php build_centennial_allstar_pool.php OUTPUT.json');
|
||||
}
|
||||
|
||||
$outputPath = $argv[1];
|
||||
$rows = [];
|
||||
$seenSources = [];
|
||||
$nameIndexes = [];
|
||||
$phaseCounts = [];
|
||||
$chiefCounts = [];
|
||||
$reasonCounts = [];
|
||||
$lineNo = 0;
|
||||
|
||||
while (($line = fgets(STDIN)) !== false) {
|
||||
$lineNo++;
|
||||
if (trim($line) === '') {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
$row = decodeSourceRow($line, $lineNo);
|
||||
} catch (JsonException $e) {
|
||||
fail("line {$lineNo}: invalid JSON: {$e->getMessage()}");
|
||||
}
|
||||
|
||||
$sourceKey = "{$row[8]}:{$row[10]}";
|
||||
if (isset($seenSources[$sourceKey])) {
|
||||
fail("line {$lineNo}: duplicate source general {$sourceKey}");
|
||||
}
|
||||
$seenSources[$sourceKey] = true;
|
||||
$nameIndexes[$row[0]][] = count($rows);
|
||||
$phaseCounts[$row[8]] = ($phaseCounts[$row[8]] ?? 0) + 1;
|
||||
foreach ($row[11] as $reason) {
|
||||
$reasonGroup = str_starts_with($reason, 'chief:') ? 'chief' : 'hall';
|
||||
$reasonCounts[$reasonGroup] = ($reasonCounts[$reasonGroup] ?? 0) + 1;
|
||||
if ($reasonGroup === 'chief') {
|
||||
$chiefCounts[$row[8]] = ($chiefCounts[$row[8]] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
if ($rows === []) {
|
||||
fail('no input rows');
|
||||
}
|
||||
foreach ($nameIndexes as $generalName => $indexes) {
|
||||
if (count($indexes) === 1) {
|
||||
continue;
|
||||
}
|
||||
foreach ($indexes as $index) {
|
||||
$rows[$index][0] .= "#{$rows[$index][10]}";
|
||||
if (mb_strlen($rows[$index][0]) > 32) {
|
||||
fail("disambiguated name exceeds 32 characters: {$rows[$index][0]}");
|
||||
}
|
||||
}
|
||||
}
|
||||
ksort($phaseCounts, SORT_NUMERIC);
|
||||
$expectedPhases = array_values(array_diff(range(1, 99), EXCLUDED_EVENT_PHASES));
|
||||
if (array_keys($phaseCounts) !== $expectedPhases) {
|
||||
fail('input does not cover every non-event phase from 1 through 99');
|
||||
}
|
||||
foreach ($expectedPhases as $phase) {
|
||||
if (($chiefCounts[$phase] ?? 0) !== 8) {
|
||||
fail("phase {$phase}: expected 8 unification chiefs including the ruler");
|
||||
}
|
||||
}
|
||||
|
||||
$payload = [
|
||||
'excludedEventPhases' => EXCLUDED_EVENT_PHASES,
|
||||
'columns' => OUTPUT_COLUMNS,
|
||||
'data' => $rows,
|
||||
];
|
||||
$encoded = json_encode(
|
||||
$payload,
|
||||
JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR
|
||||
) . "\n";
|
||||
|
||||
$outputDir = dirname($outputPath);
|
||||
if (!is_dir($outputDir)) {
|
||||
fail("output directory does not exist: {$outputDir}");
|
||||
}
|
||||
$tempPath = tempnam($outputDir, basename($outputPath) . '.tmp.');
|
||||
if ($tempPath === false) {
|
||||
fail("could not create temporary output in {$outputDir}");
|
||||
}
|
||||
if (file_put_contents($tempPath, $encoded) === false || !rename($tempPath, $outputPath)) {
|
||||
@unlink($tempPath);
|
||||
fail("could not write output: {$outputPath}");
|
||||
}
|
||||
|
||||
fwrite(
|
||||
STDERR,
|
||||
sprintf(
|
||||
"wrote %d candidates across phases %d-%d (%d hall reasons, %d chief reasons)\n",
|
||||
count($rows),
|
||||
min(array_keys($phaseCounts)),
|
||||
max(array_keys($phaseCounts)),
|
||||
$reasonCounts['hall'] ?? 0,
|
||||
$reasonCounts['chief'] ?? 0,
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,131 @@
|
||||
WITH
|
||||
phases AS (
|
||||
SELECT
|
||||
e.no AS phase_no,
|
||||
e.server_id,
|
||||
g.winner_nation,
|
||||
e.l12name,
|
||||
e.l12pic,
|
||||
e.l11name,
|
||||
e.l11pic,
|
||||
e.l10name,
|
||||
e.l10pic,
|
||||
e.l9name,
|
||||
e.l9pic,
|
||||
e.l8name,
|
||||
e.l8pic,
|
||||
e.l7name,
|
||||
e.l7pic,
|
||||
e.l6name,
|
||||
e.l6pic,
|
||||
e.l5name,
|
||||
e.l5pic
|
||||
FROM emperior e
|
||||
LEFT JOIN ng_games g ON g.server_id = e.server_id
|
||||
WHERE e.no BETWEEN 1 AND 99
|
||||
AND MOD(e.no, 5) <> 0
|
||||
),
|
||||
hall_eligible AS (
|
||||
SELECT
|
||||
p.phase_no,
|
||||
h.server_id,
|
||||
h.general_no,
|
||||
h.type,
|
||||
h.value,
|
||||
h.id
|
||||
FROM phases p
|
||||
JOIN hall h ON h.server_id = p.server_id
|
||||
JOIN ng_old_generals og
|
||||
ON og.server_id = h.server_id
|
||||
AND og.general_no = h.general_no
|
||||
WHERE h.general_no > 2
|
||||
AND CAST(COALESCE(JSON_VALUE(og.data, '$.npc'), 0) AS SIGNED) = 0
|
||||
),
|
||||
hall_ranked AS (
|
||||
SELECT
|
||||
phase_no,
|
||||
server_id,
|
||||
general_no,
|
||||
type,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY server_id, type
|
||||
ORDER BY value DESC, id ASC
|
||||
) AS hall_rank
|
||||
FROM hall_eligible
|
||||
),
|
||||
selection_reasons AS (
|
||||
SELECT
|
||||
phase_no,
|
||||
server_id,
|
||||
general_no,
|
||||
CONCAT('hall:', type) AS reason
|
||||
FROM hall_ranked
|
||||
WHERE hall_rank <= 10
|
||||
),
|
||||
chief_slots AS (
|
||||
SELECT phase_no, server_id, winner_nation, 12 AS officer_level, l12name AS name, l12pic AS picture FROM phases
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, winner_nation, 11, l11name, l11pic FROM phases
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, winner_nation, 10, l10name, l10pic FROM phases
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, winner_nation, 9, l9name, l9pic FROM phases
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, winner_nation, 8, l8name, l8pic FROM phases
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, winner_nation, 7, l7name, l7pic FROM phases
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, winner_nation, 6, l6name, l6pic FROM phases
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, winner_nation, 5, l5name, l5pic FROM phases
|
||||
),
|
||||
chief_reasons AS (
|
||||
SELECT
|
||||
c.phase_no,
|
||||
c.server_id,
|
||||
og.general_no,
|
||||
CONCAT('chief:', c.officer_level) AS reason
|
||||
FROM chief_slots c
|
||||
JOIN ng_old_generals og
|
||||
ON og.server_id = c.server_id
|
||||
AND og.name = c.name
|
||||
AND SUBSTRING_INDEX(
|
||||
COALESCE(JSON_VALUE(og.data, '$.picture'), ''),
|
||||
'?=',
|
||||
1
|
||||
) = SUBSTRING_INDEX(COALESCE(c.picture, ''), '?=', 1)
|
||||
AND (
|
||||
CAST(COALESCE(JSON_VALUE(og.data, '$.officer_level'), -1) AS SIGNED) = c.officer_level
|
||||
OR (
|
||||
JSON_VALUE(og.data, '$.officer_level') IS NULL
|
||||
AND (
|
||||
c.winner_nation IS NULL
|
||||
OR CAST(JSON_VALUE(og.data, '$.nation') AS SIGNED) = c.winner_nation
|
||||
)
|
||||
)
|
||||
)
|
||||
WHERE og.general_no > 2
|
||||
),
|
||||
all_reasons AS (
|
||||
SELECT phase_no, server_id, general_no, reason FROM selection_reasons
|
||||
UNION ALL
|
||||
SELECT phase_no, server_id, general_no, reason FROM chief_reasons
|
||||
)
|
||||
SELECT
|
||||
r.phase_no,
|
||||
r.server_id,
|
||||
r.general_no,
|
||||
og.name,
|
||||
og.data,
|
||||
GROUP_CONCAT(DISTINCT r.reason ORDER BY r.reason SEPARATOR ',') AS reasons
|
||||
FROM all_reasons r
|
||||
JOIN ng_old_generals og
|
||||
ON og.server_id = r.server_id
|
||||
AND og.general_no = r.general_no
|
||||
GROUP BY
|
||||
r.phase_no,
|
||||
r.server_id,
|
||||
r.general_no,
|
||||
og.name,
|
||||
og.data
|
||||
ORDER BY r.phase_no, r.general_no;
|
||||
+72
-7
@@ -36,6 +36,57 @@ type ProcResult = {
|
||||
lastExecuted?: string;
|
||||
};
|
||||
|
||||
class CookieJar {
|
||||
#cookies = new Map<string, string>();
|
||||
|
||||
getCookieHeader(): string | undefined {
|
||||
if (this.#cookies.size === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return [...this.#cookies.entries()].map(([key, value]) => `${key}=${value}`).join("; ");
|
||||
}
|
||||
|
||||
ingestSetCookie(setCookieHeaders: string[]): void {
|
||||
for (const setCookie of setCookieHeaders) {
|
||||
const cookiePart = setCookie.split(";", 1)[0]?.trim();
|
||||
if (!cookiePart) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const eqPos = cookiePart.indexOf("=");
|
||||
if (eqPos <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = cookiePart.slice(0, eqPos).trim();
|
||||
const value = cookiePart.slice(eqPos + 1).trim();
|
||||
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (value === "") {
|
||||
this.#cookies.delete(key);
|
||||
continue;
|
||||
}
|
||||
this.#cookies.set(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getSetCookieHeaders(headers: Headers): string[] {
|
||||
const headerObj = headers as unknown as { getSetCookie?: () => string[] };
|
||||
if (typeof headerObj.getSetCookie === "function") {
|
||||
return headerObj.getSetCookie();
|
||||
}
|
||||
|
||||
const fallback = headers.get("set-cookie");
|
||||
if (!fallback) {
|
||||
return [];
|
||||
}
|
||||
return [fallback];
|
||||
}
|
||||
|
||||
function nowStr() {
|
||||
const d = new Date();
|
||||
const pad = (n: number) => n.toString().padStart(2, "0");
|
||||
@@ -131,13 +182,19 @@ async function scanOnce(): Promise<ServerEntry[]> {
|
||||
}
|
||||
|
||||
// ============ 공개 접근 체크 ============
|
||||
async function isPublicReachable(signal?: AbortSignal): Promise<boolean> {
|
||||
async function isPublicReachable(signal?: AbortSignal, cookieJar?: CookieJar): Promise<boolean> {
|
||||
if (!REQUIRE_PUBLIC) return true;
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), Math.min(5_000, FETCH_TIMEOUT_MS));
|
||||
const composite = anySignal([ctrl.signal, signal].filter(Boolean) as AbortSignal[]);
|
||||
try {
|
||||
const res = await fetch(webBase, { method: "GET", signal: composite });
|
||||
const cookieHeader = cookieJar?.getCookieHeader();
|
||||
const res = await fetch(webBase, {
|
||||
method: "GET",
|
||||
signal: composite,
|
||||
headers: cookieHeader ? { cookie: cookieHeader } : undefined,
|
||||
});
|
||||
cookieJar?.ingestSetCookie(getSetCookieHeaders(res.headers));
|
||||
if (!res.ok) { log(`[PUBLIC] 응답 ${res.status} → 비공개로 간주`); return false; }
|
||||
return true;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -150,14 +207,20 @@ async function isPublicReachable(signal?: AbortSignal): Promise<boolean> {
|
||||
}
|
||||
|
||||
// ============ HTTP ============
|
||||
async function httpGetJson<T extends Json>(url: string, outerSignal?: AbortSignal): Promise<T | null> {
|
||||
async function httpGetJson<T extends Json>(url: string, outerSignal?: AbortSignal, cookieJar?: CookieJar): Promise<T | null> {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
|
||||
const signal = anySignal([ctrl.signal, outerSignal].filter(Boolean) as AbortSignal[]);
|
||||
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
const res = await fetch(url, { signal, cache: "no-store" });
|
||||
const cookieHeader = cookieJar?.getCookieHeader();
|
||||
const res = await fetch(url, {
|
||||
signal,
|
||||
cache: "no-store",
|
||||
headers: cookieHeader ? { cookie: cookieHeader } : undefined,
|
||||
});
|
||||
cookieJar?.ingestSetCookie(getSetCookieHeaders(res.headers));
|
||||
const dt = Math.round(performance.now() - t0);
|
||||
if (!res.ok) { log("HTTPError:", res.status, url); return null; }
|
||||
try {
|
||||
@@ -195,6 +258,7 @@ class ServerRunner {
|
||||
#stopCtrl = new AbortController();
|
||||
#stopped = false;
|
||||
#lastAutoResetAt = 0;
|
||||
#cookieJar = new CookieJar();
|
||||
|
||||
constructor(entry: ServerEntry) {
|
||||
this.#entry = entry;
|
||||
@@ -222,7 +286,7 @@ class ServerRunner {
|
||||
while (!this.#stopCtrl.signal.aborted) {
|
||||
try {
|
||||
// 공개 접근 체크
|
||||
const pub = await isPublicReachable(this.#stopCtrl.signal);
|
||||
const pub = await isPublicReachable(this.#stopCtrl.signal, publicCookieJar);
|
||||
if (!pub) { await delay(15_000, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ }); continue; }
|
||||
|
||||
const hidden = await this.#entry.isHidden();
|
||||
@@ -236,7 +300,7 @@ class ServerRunner {
|
||||
if (this.#stopCtrl.signal.aborted) break;
|
||||
}
|
||||
log(`[${this.name()}] 닫힘 - (정렬) autoreset 호출 @ mm:00${AUTO_RESET_JITTER_MS ? `+${AUTO_RESET_JITTER_MS}ms` : ""}`);
|
||||
await httpGetJson<Json>(this.#entry.autoresetUrl, this.#stopCtrl.signal);
|
||||
await httpGetJson<Json>(this.#entry.autoresetUrl, this.#stopCtrl.signal, this.#cookieJar);
|
||||
// 같은 분에 중복 호출 방지: 0초 직후 잠깐 쉬고 다음 루프는 자연스럽게 다음 분으로 정렬됨
|
||||
await delay(200, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
|
||||
continue;
|
||||
@@ -244,7 +308,7 @@ class ServerRunner {
|
||||
|
||||
|
||||
// 열림: proc
|
||||
const data = await httpGetJson<ProcResult>(this.#entry.procUrl, this.#stopCtrl.signal);
|
||||
const data = await httpGetJson<ProcResult>(this.#entry.procUrl, this.#stopCtrl.signal, this.#cookieJar);
|
||||
if (!data) {
|
||||
await delay(IF_LOCKED_WAIT_MS, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
|
||||
continue;
|
||||
@@ -348,6 +412,7 @@ class DaemonManager {
|
||||
|
||||
// ============ 메인 ============
|
||||
const manager = new DaemonManager();
|
||||
const publicCookieJar = new CookieJar();
|
||||
|
||||
async function main() {
|
||||
// 신호 처리: SIGINT/SIGTERM → graceful shutdown
|
||||
|
||||
@@ -13,6 +13,8 @@ use sammo\TimeUtil;
|
||||
use sammo\Util;
|
||||
use sammo\Validator;
|
||||
|
||||
use function sammo\logError;
|
||||
|
||||
class LoginByToken extends LoginByID
|
||||
{
|
||||
static array $sensitiveArgs = ['hashedToken'];
|
||||
|
||||
@@ -73,7 +73,7 @@ class APIHelper
|
||||
$logPath = "{$rootPath}/d_log/{$realYearMonth}_api_log.db";
|
||||
}
|
||||
$logDB = FileDB::db($logPath, __DIR__ . '/../../f_install/sql/api_log.sql');
|
||||
$ip = $_SERVER['REMOTE_ADDR'] ?? 'local';
|
||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'local';
|
||||
$date = date('Y-m-d H:i:s');
|
||||
|
||||
//NOTE: array_merge([], {})의 상황이 가능함.
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace sammo;
|
||||
|
||||
final class CentennialAllStarGrowth
|
||||
{
|
||||
public const DEFAULT_GROWTH_YEARS = 15;
|
||||
|
||||
public static function progress(
|
||||
int $startYear,
|
||||
int $year,
|
||||
int $month,
|
||||
int $growthYears = self::DEFAULT_GROWTH_YEARS
|
||||
): float {
|
||||
if ($growthYears <= 0) {
|
||||
throw new \InvalidArgumentException('growthYears must be positive');
|
||||
}
|
||||
if ($month < 1 || $month > 12) {
|
||||
throw new \InvalidArgumentException('month must be between 1 and 12');
|
||||
}
|
||||
|
||||
$elapsedMonths = max(0, ($year - $startYear) * 12 + $month - 1);
|
||||
return min(1.0, $elapsedMonths / ($growthYears * 12));
|
||||
}
|
||||
|
||||
public static function statFloor(int $target, int $minimum, float $progress): int
|
||||
{
|
||||
$progress = self::clampProgress($progress);
|
||||
if ($target <= $minimum) {
|
||||
return $target;
|
||||
}
|
||||
return min($target, (int) floor($minimum + ($target - $minimum) * $progress));
|
||||
}
|
||||
|
||||
public static function dexFloor(int $target, float $progress): int
|
||||
{
|
||||
$progress = self::clampProgress($progress);
|
||||
return min($target, (int) floor($target * $progress * $progress));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{value:int, granted:int, delta:int}
|
||||
*/
|
||||
public static function advance(int $current, int $granted, int $floor): array
|
||||
{
|
||||
$delta = max(0, $floor - $current);
|
||||
return [
|
||||
'value' => $current + $delta,
|
||||
'granted' => max(0, $granted) + $delta,
|
||||
'delta' => $delta,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{value:int, granted:int, organic:int}
|
||||
*/
|
||||
public static function replaceTarget(int $current, int $oldGranted, int $newFloor): array
|
||||
{
|
||||
$organic = max(0, $current - max(0, $oldGranted));
|
||||
$value = max($organic, $newFloor);
|
||||
return [
|
||||
'value' => $value,
|
||||
'granted' => $value - $organic,
|
||||
'organic' => $organic,
|
||||
];
|
||||
}
|
||||
|
||||
public static function recordableValue(int $current, int $granted): int
|
||||
{
|
||||
return max(0, $current - max(0, $granted));
|
||||
}
|
||||
|
||||
private static function clampProgress(float $progress): float
|
||||
{
|
||||
return max(0.0, min(1.0, $progress));
|
||||
}
|
||||
}
|
||||
+1
-19
@@ -947,31 +947,13 @@ class Util
|
||||
return $flattened;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the IP address of the client.
|
||||
*
|
||||
* @param boolean $trust_proxy_headers Whether or not to trust the
|
||||
* proxy headers HTTP_CLIENT_IP
|
||||
* and HTTP_X_FORWARDED_FOR. ONLY
|
||||
* use if your server is behind a
|
||||
* proxy that sets these values
|
||||
* @return string
|
||||
*/
|
||||
public static function get_client_ip($trust_proxy_headers = false)
|
||||
{
|
||||
if (!$trust_proxy_headers) {
|
||||
return $_SERVER['REMOTE_ADDR'];
|
||||
}
|
||||
|
||||
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
|
||||
$ip = $_SERVER['HTTP_CLIENT_IP'];
|
||||
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
|
||||
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
|
||||
} else {
|
||||
$ip = $_SERVER['REMOTE_ADDR'];
|
||||
}
|
||||
|
||||
return $ip;
|
||||
return $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'local';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,874 @@
|
||||
<?php
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use sammo\CentennialAllStarGrowth;
|
||||
use sammo\CentennialAllStarGrowthService;
|
||||
use sammo\General;
|
||||
use sammo\GameConst;
|
||||
|
||||
$loader = require __DIR__ . '/../vendor/autoload.php';
|
||||
$loader->addPsr4('sammo\\', __DIR__ . '/../hwe/sammo', true);
|
||||
|
||||
require_once __DIR__ . '/../hwe/sammo/ActionLogger.php';
|
||||
require_once __DIR__ . '/../hwe/sammo/GameConstBase.php';
|
||||
require_once __DIR__ . '/../hwe/d_setting/GameConst.php';
|
||||
require_once __DIR__ . '/../hwe/sammo/CentennialAllStarGrowthService.php';
|
||||
|
||||
final class CentennialAllStarGrowthTest extends TestCase
|
||||
{
|
||||
public function testProgressMilestones(): void
|
||||
{
|
||||
self::assertSame(0.0, CentennialAllStarGrowth::progress(180, 180, 1));
|
||||
self::assertEqualsWithDelta(0.2, CentennialAllStarGrowth::progress(180, 183, 1), 0.000001);
|
||||
self::assertEqualsWithDelta(0.4, CentennialAllStarGrowth::progress(180, 186, 1), 0.000001);
|
||||
self::assertSame(1.0, CentennialAllStarGrowth::progress(180, 195, 1));
|
||||
self::assertSame(1.0, CentennialAllStarGrowth::progress(180, 210, 1));
|
||||
}
|
||||
|
||||
public function testStatResetIsDisabledOnlyForCentennialAllStarPool(): void
|
||||
{
|
||||
$previousPool = GameConst::$targetGeneralPool;
|
||||
try {
|
||||
GameConst::$targetGeneralPool = CentennialAllStarGrowthService::POOL_CLASS;
|
||||
self::assertFalse(CentennialAllStarGrowthService::isStatResetAllowed());
|
||||
|
||||
GameConst::$targetGeneralPool = 'RandomNameGeneral';
|
||||
self::assertTrue(CentennialAllStarGrowthService::isStatResetAllowed());
|
||||
} finally {
|
||||
GameConst::$targetGeneralPool = $previousPool;
|
||||
}
|
||||
}
|
||||
|
||||
public function testMAndGGeneralsAdvanceAtNinetyPercentProgress(): void
|
||||
{
|
||||
self::assertSame(
|
||||
CentennialAllStarGrowthService::NPC_PROGRESS_MULTIPLIER,
|
||||
CentennialAllStarGrowthService::progressMultiplierForNPCType(3)
|
||||
);
|
||||
self::assertSame(
|
||||
CentennialAllStarGrowthService::NPC_PROGRESS_MULTIPLIER,
|
||||
CentennialAllStarGrowthService::progressMultiplierForNPCType(4)
|
||||
);
|
||||
self::assertSame(1.0, CentennialAllStarGrowthService::progressMultiplierForNPCType(2));
|
||||
self::assertEqualsWithDelta(
|
||||
0.36,
|
||||
CentennialAllStarGrowthService::calculateProgress(180, 186, 1, 0.9),
|
||||
0.000001
|
||||
);
|
||||
self::assertEqualsWithDelta(
|
||||
0.9,
|
||||
CentennialAllStarGrowthService::calculateProgress(180, 195, 1, 0.9),
|
||||
0.000001
|
||||
);
|
||||
self::assertEqualsWithDelta(
|
||||
0.9,
|
||||
CentennialAllStarGrowthService::calculateProgress(180, 210, 1, 0.9),
|
||||
0.000001
|
||||
);
|
||||
self::assertSame(
|
||||
91,
|
||||
CentennialAllStarGrowth::statFloor(100, 15, 0.9)
|
||||
);
|
||||
self::assertSame(
|
||||
0.4,
|
||||
CentennialAllStarGrowthService::dexTargetRatioForNPCType(3)
|
||||
);
|
||||
self::assertSame(
|
||||
0.4,
|
||||
CentennialAllStarGrowthService::dexTargetRatioForNPCType(4)
|
||||
);
|
||||
self::assertSame(
|
||||
1.0,
|
||||
CentennialAllStarGrowthService::dexTargetRatioForNPCType(2)
|
||||
);
|
||||
}
|
||||
|
||||
public function testProgressMultiplierMustStayWithinUnitInterval(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
CentennialAllStarGrowthService::calculateProgress(180, 195, 1, 1.01);
|
||||
}
|
||||
|
||||
public function testLowStatGrowsWhileHigherStatStays(): void
|
||||
{
|
||||
$floor = CentennialAllStarGrowth::statFloor(90, 15, 0.6);
|
||||
self::assertSame(60, $floor);
|
||||
self::assertSame(
|
||||
['value' => 70, 'granted' => 0, 'delta' => 0],
|
||||
CentennialAllStarGrowth::advance(70, 0, $floor)
|
||||
);
|
||||
self::assertSame(
|
||||
['value' => 60, 'granted' => 10, 'delta' => 10],
|
||||
CentennialAllStarGrowth::advance(50, 0, $floor)
|
||||
);
|
||||
}
|
||||
|
||||
public function testUserInitialStatsPreserveCandidateShapeAtOrdinaryTotal(): void
|
||||
{
|
||||
$initial = CentennialAllStarGrowthService::calculateUserInitialStats([
|
||||
'leadership' => 80,
|
||||
'strength' => 70,
|
||||
'intel' => 50,
|
||||
]);
|
||||
|
||||
self::assertSame([
|
||||
'leadership' => 65,
|
||||
'strength' => 58,
|
||||
'intel' => 42,
|
||||
], $initial);
|
||||
self::assertSame(165, array_sum($initial));
|
||||
self::assertLessThanOrEqual(80, $initial['leadership']);
|
||||
self::assertLessThanOrEqual(70, $initial['strength']);
|
||||
self::assertLessThanOrEqual(50, $initial['intel']);
|
||||
}
|
||||
|
||||
public function testUserInitialStatsDoNotRaiseCandidateBelowOrdinaryTotal(): void
|
||||
{
|
||||
self::assertSame([
|
||||
'leadership' => 60,
|
||||
'strength' => 45,
|
||||
'intel' => 30,
|
||||
], CentennialAllStarGrowthService::calculateUserInitialStats([
|
||||
'leadership' => 60,
|
||||
'strength' => 45,
|
||||
'intel' => 30,
|
||||
]));
|
||||
}
|
||||
|
||||
public function testCurrentReselectionBaselineUsesCurrentYearProgress(): void
|
||||
{
|
||||
$target = [
|
||||
'leadership' => 100,
|
||||
'strength' => 15,
|
||||
'intel' => 100,
|
||||
];
|
||||
|
||||
self::assertSame([
|
||||
'leadership' => 75,
|
||||
'strength' => 15,
|
||||
'intel' => 75,
|
||||
], CentennialAllStarGrowthService::calculateUserCurrentTargetStats(
|
||||
$target,
|
||||
['startyear' => 180, 'year' => 180, 'month' => 1]
|
||||
));
|
||||
self::assertSame([
|
||||
'leadership' => 83,
|
||||
'strength' => 15,
|
||||
'intel' => 83,
|
||||
], CentennialAllStarGrowthService::calculateUserCurrentTargetStats(
|
||||
$target,
|
||||
['startyear' => 180, 'year' => 192, 'month' => 1]
|
||||
));
|
||||
self::assertSame([
|
||||
'leadership' => 100,
|
||||
'strength' => 15,
|
||||
'intel' => 100,
|
||||
], CentennialAllStarGrowthService::calculateUserCurrentTargetStats(
|
||||
$target,
|
||||
['startyear' => 180, 'year' => 195, 'month' => 1]
|
||||
));
|
||||
}
|
||||
|
||||
public function testInitialUserGrantMakesInitialAllocationReplaceable(): void
|
||||
{
|
||||
$initial = CentennialAllStarGrowthService::calculateUserInitialStats([
|
||||
'uniqueName' => 'A1000001',
|
||||
'leadership' => 80,
|
||||
'strength' => 70,
|
||||
'intel' => 50,
|
||||
]);
|
||||
$aux = CentennialAllStarGrowthService::initialAux([
|
||||
'uniqueName' => 'A1000001',
|
||||
], $initial);
|
||||
|
||||
self::assertSame('A1000001', $aux['targetId']);
|
||||
self::assertSame($initial, $aux['userInitialStats']);
|
||||
self::assertSame(1.0, $aux['dexTargetRatio']);
|
||||
self::assertSame(50, $aux['granted']['leadership']);
|
||||
self::assertSame(43, $aux['granted']['strength']);
|
||||
self::assertSame(27, $aux['granted']['intel']);
|
||||
}
|
||||
|
||||
public function testLegacyInitialGrantKeepsOnlyGrowthBeyondCreationRange(): void
|
||||
{
|
||||
self::assertSame(
|
||||
35,
|
||||
CentennialAllStarGrowthService::calculateLegacyUserGrant(50, 0)
|
||||
);
|
||||
self::assertSame(
|
||||
75,
|
||||
CentennialAllStarGrowthService::calculateLegacyUserGrant(90, 40)
|
||||
);
|
||||
self::assertSame(
|
||||
105,
|
||||
CentennialAllStarGrowthService::calculateLegacyUserGrant(140, 40)
|
||||
);
|
||||
self::assertSame(
|
||||
35,
|
||||
140 - CentennialAllStarGrowthService::calculateLegacyUserGrant(140, 40)
|
||||
);
|
||||
}
|
||||
|
||||
public function testReselectDropsOldGrantAndKeepsOrganicGrowth(): void
|
||||
{
|
||||
self::assertSame(
|
||||
['value' => 82, 'granted' => 7, 'organic' => 75],
|
||||
CentennialAllStarGrowth::replaceTarget(86, 11, 82)
|
||||
);
|
||||
self::assertSame(
|
||||
['value' => 90, 'granted' => 0, 'organic' => 90],
|
||||
CentennialAllStarGrowth::replaceTarget(101, 11, 82)
|
||||
);
|
||||
}
|
||||
|
||||
public function testRepeatedAdvanceIsIdempotent(): void
|
||||
{
|
||||
$first = CentennialAllStarGrowth::advance(50, 0, 60);
|
||||
$second = CentennialAllStarGrowth::advance($first['value'], $first['granted'], 60);
|
||||
self::assertSame(60, $second['value']);
|
||||
self::assertSame(10, $second['granted']);
|
||||
self::assertSame(0, $second['delta']);
|
||||
self::assertSame(50, CentennialAllStarGrowth::recordableValue(60, 10));
|
||||
}
|
||||
|
||||
public function testDexUsesSlowEarlyCurve(): void
|
||||
{
|
||||
self::assertSame(0, CentennialAllStarGrowth::dexFloor(900000, 0));
|
||||
self::assertSame(36000, CentennialAllStarGrowth::dexFloor(900000, 0.2));
|
||||
self::assertSame(144000, CentennialAllStarGrowth::dexFloor(900000, 0.4));
|
||||
self::assertSame(900000, CentennialAllStarGrowth::dexFloor(900000, 1));
|
||||
}
|
||||
|
||||
public function testNpcDexStopsAtFortyPercentOfHistoricalTarget(): void
|
||||
{
|
||||
$target = 900000;
|
||||
$ratio = GameConst::$centennialNpcDexTargetRatio;
|
||||
|
||||
self::assertSame(0.4, $ratio);
|
||||
self::assertSame(
|
||||
57600,
|
||||
CentennialAllStarGrowthService::calculateDexTargetFloor(
|
||||
$target,
|
||||
['startyear' => 180, 'year' => 186, 'month' => 1],
|
||||
$ratio
|
||||
)
|
||||
);
|
||||
self::assertSame(
|
||||
360000,
|
||||
CentennialAllStarGrowthService::calculateDexTargetFloor(
|
||||
$target,
|
||||
['startyear' => 180, 'year' => 195, 'month' => 1],
|
||||
$ratio
|
||||
)
|
||||
);
|
||||
self::assertSame(
|
||||
360000,
|
||||
CentennialAllStarGrowthService::calculateDexTargetFloor(
|
||||
$target,
|
||||
['startyear' => 180, 'year' => 210, 'month' => 1],
|
||||
$ratio
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function testScenarioConfigKeepsNpcDexTargetRatioAtFortyPercent(): void
|
||||
{
|
||||
$scenario = json_decode(
|
||||
file_get_contents(__DIR__ . '/../hwe/scenario/scenario_915.json'),
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR
|
||||
);
|
||||
|
||||
self::assertSame(
|
||||
GameConst::$centennialNpcDexTargetRatio,
|
||||
$scenario['map']['centennialNpcDexTargetRatio']
|
||||
);
|
||||
}
|
||||
|
||||
public function testNpcDexRatioChangeRemovesOnlyOldEventGrant(): void
|
||||
{
|
||||
self::assertSame(
|
||||
['value' => 360000, 'granted' => 360000, 'organic' => 0],
|
||||
CentennialAllStarGrowth::replaceTarget(810000, 810000, 360000)
|
||||
);
|
||||
self::assertSame(
|
||||
['value' => 360000, 'granted' => 310000, 'organic' => 50000],
|
||||
CentennialAllStarGrowth::replaceTarget(860000, 810000, 360000)
|
||||
);
|
||||
self::assertSame(
|
||||
['value' => 400000, 'granted' => 0, 'organic' => 400000],
|
||||
CentennialAllStarGrowth::replaceTarget(1210000, 810000, 360000)
|
||||
);
|
||||
}
|
||||
|
||||
public function testExistingNpcDexGrantIsRebasedWithoutChangingFinalStats(): void
|
||||
{
|
||||
$vars = [
|
||||
'leadership' => 91,
|
||||
'strength' => 91,
|
||||
'intel' => 91,
|
||||
'dex1' => 810000,
|
||||
'dex2' => 810000,
|
||||
'dex3' => 810000,
|
||||
'dex4' => 810000,
|
||||
'dex5' => 810000,
|
||||
'special' => 'None',
|
||||
];
|
||||
$aux = [
|
||||
'targetId' => 'A1000001',
|
||||
'granted' => [
|
||||
'leadership' => 76,
|
||||
'strength' => 76,
|
||||
'intel' => 76,
|
||||
'dex1' => 810000,
|
||||
'dex2' => 810000,
|
||||
'dex3' => 810000,
|
||||
'dex4' => 810000,
|
||||
'dex5' => 810000,
|
||||
],
|
||||
'progressMonth' => 162,
|
||||
'milestone' => 4,
|
||||
'naturalSpecialDomestic' => null,
|
||||
'eventSpecialDomestic' => null,
|
||||
'userInitialStats' => null,
|
||||
];
|
||||
$general = $this->getMockBuilder(General::class)
|
||||
->disableOriginalConstructor()
|
||||
->onlyMethods(['getAuxVar', 'setAuxVar', 'getVar', 'updateVar'])
|
||||
->getMock();
|
||||
$general->method('getAuxVar')->willReturnCallback(
|
||||
static fn(string $key) => $key === CentennialAllStarGrowthService::AUX_KEY
|
||||
? $aux
|
||||
: null
|
||||
);
|
||||
$general->method('getVar')->willReturnCallback(
|
||||
static fn(string $key) => $vars[$key] ?? null
|
||||
);
|
||||
$general->method('updateVar')->willReturnCallback(
|
||||
static function (string $key, $value) use (&$vars): void {
|
||||
$vars[$key] = $value;
|
||||
}
|
||||
);
|
||||
$general->method('setAuxVar')->willReturnCallback(
|
||||
static function (string $key, $value) use (&$aux): void {
|
||||
if ($key === CentennialAllStarGrowthService::AUX_KEY) {
|
||||
$aux = $value;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
$result = CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
[
|
||||
'uniqueName' => 'A1000001',
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex' => [900000, 900000, 900000, 900000, 900000],
|
||||
],
|
||||
['startyear' => 180, 'year' => 195, 'month' => 1],
|
||||
CentennialAllStarGrowthService::NPC_PROGRESS_MULTIPLIER,
|
||||
GameConst::$centennialNpcDexTargetRatio
|
||||
);
|
||||
|
||||
self::assertTrue($result['changed']);
|
||||
self::assertSame(91, $vars['leadership']);
|
||||
self::assertSame(91, $vars['strength']);
|
||||
self::assertSame(91, $vars['intel']);
|
||||
foreach (['dex1', 'dex2', 'dex3', 'dex4', 'dex5'] as $key) {
|
||||
self::assertSame(360000, $vars[$key]);
|
||||
self::assertSame(360000, $aux['granted'][$key]);
|
||||
}
|
||||
self::assertSame(0.4, $aux['dexTargetRatio']);
|
||||
}
|
||||
|
||||
public function testDexConversionConsumesEventFloorWithoutMonthlyRefill(): void
|
||||
{
|
||||
$vars = [
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex1' => 216000,
|
||||
'dex2' => 489600,
|
||||
'dex3' => 360000,
|
||||
'dex4' => 360000,
|
||||
'dex5' => 360000,
|
||||
'special' => 'None',
|
||||
];
|
||||
$aux = [
|
||||
'targetId' => 'A1000001',
|
||||
'granted' => [
|
||||
'leadership' => 85,
|
||||
'strength' => 85,
|
||||
'intel' => 85,
|
||||
'dex1' => 360000,
|
||||
'dex2' => 360000,
|
||||
'dex3' => 360000,
|
||||
'dex4' => 360000,
|
||||
'dex5' => 360000,
|
||||
],
|
||||
'dexConsumed' => [
|
||||
'dex1' => 0,
|
||||
'dex2' => 0,
|
||||
'dex3' => 0,
|
||||
'dex4' => 0,
|
||||
'dex5' => 0,
|
||||
],
|
||||
'progressMonth' => 180,
|
||||
'milestone' => 5,
|
||||
'naturalSpecialDomestic' => null,
|
||||
'eventSpecialDomestic' => null,
|
||||
'userInitialStats' => [],
|
||||
'dexTargetRatio' => 1.0,
|
||||
];
|
||||
$general = $this->createStateGeneralMock($vars, $aux);
|
||||
|
||||
CentennialAllStarGrowthService::reconcileDexConversion(
|
||||
$general,
|
||||
'dex1',
|
||||
'dex2',
|
||||
360000,
|
||||
216000,
|
||||
360000,
|
||||
489600,
|
||||
0.9
|
||||
);
|
||||
|
||||
self::assertSame(216000, $aux['granted']['dex1']);
|
||||
self::assertSame(489600, $aux['granted']['dex2']);
|
||||
self::assertSame(144000, $aux['dexConsumed']['dex1']);
|
||||
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
[
|
||||
'uniqueName' => 'A1000001',
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex' => [360000, 360000, 360000, 360000, 360000],
|
||||
],
|
||||
['startyear' => 180, 'year' => 195, 'month' => 1]
|
||||
);
|
||||
|
||||
self::assertSame(216000, $vars['dex1']);
|
||||
self::assertSame(489600, $vars['dex2']);
|
||||
self::assertSame(216000, $aux['dexFloor']['dex1']);
|
||||
self::assertSame(0, CentennialAllStarGrowthService::recordableValue($general, 'dex1'));
|
||||
self::assertSame(0, CentennialAllStarGrowthService::recordableValue($general, 'dex2'));
|
||||
|
||||
$vars['dex1'] = 129600;
|
||||
$vars['dex2'] = 567360;
|
||||
CentennialAllStarGrowthService::reconcileDexConversion(
|
||||
$general,
|
||||
'dex1',
|
||||
'dex2',
|
||||
216000,
|
||||
129600,
|
||||
489600,
|
||||
567360,
|
||||
0.9
|
||||
);
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
[
|
||||
'uniqueName' => 'A1000001',
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex' => [360000, 360000, 360000, 360000, 360000],
|
||||
],
|
||||
['startyear' => 180, 'year' => 195, 'month' => 1]
|
||||
);
|
||||
|
||||
self::assertSame(129600, $vars['dex1']);
|
||||
self::assertSame(567360, $vars['dex2']);
|
||||
self::assertSame(230400, $aux['dexConsumed']['dex1']);
|
||||
self::assertSame(129600, $aux['dexFloor']['dex1']);
|
||||
self::assertSame(0, CentennialAllStarGrowthService::recordableValue($general, 'dex1'));
|
||||
self::assertSame(0, CentennialAllStarGrowthService::recordableValue($general, 'dex2'));
|
||||
}
|
||||
|
||||
public function testNaturalDexConversionDoesNotBecomeEventGrant(): void
|
||||
{
|
||||
$vars = [
|
||||
'dex1' => 216000,
|
||||
'dex2' => 129600,
|
||||
];
|
||||
$aux = [
|
||||
'targetId' => 'A1000001',
|
||||
'granted' => [
|
||||
'dex1' => 0,
|
||||
'dex2' => 0,
|
||||
],
|
||||
'dexConsumed' => [
|
||||
'dex1' => 0,
|
||||
'dex2' => 0,
|
||||
],
|
||||
'dexFloor' => [
|
||||
'dex1' => 360000,
|
||||
'dex2' => 0,
|
||||
],
|
||||
];
|
||||
$general = $this->createStateGeneralMock($vars, $aux);
|
||||
|
||||
CentennialAllStarGrowthService::reconcileDexConversion(
|
||||
$general,
|
||||
'dex1',
|
||||
'dex2',
|
||||
360000,
|
||||
216000,
|
||||
0,
|
||||
129600,
|
||||
0.9
|
||||
);
|
||||
|
||||
self::assertSame(0, $aux['granted']['dex1']);
|
||||
self::assertSame(0, $aux['granted']['dex2']);
|
||||
self::assertSame(144000, $aux['dexConsumed']['dex1']);
|
||||
self::assertSame(216000, CentennialAllStarGrowthService::recordableValue($general, 'dex1'));
|
||||
self::assertSame(129600, CentennialAllStarGrowthService::recordableValue($general, 'dex2'));
|
||||
}
|
||||
|
||||
public function testMixedDexConversionSplitsEventAndNaturalPointsByTotalShare(): void
|
||||
{
|
||||
$vars = [
|
||||
'dex1' => 360000,
|
||||
'dex2' => 600000,
|
||||
];
|
||||
$aux = [
|
||||
'targetId' => 'archer',
|
||||
'granted' => [
|
||||
'dex1' => 0,
|
||||
'dex2' => 900000,
|
||||
],
|
||||
'dexConsumed' => [
|
||||
'dex1' => 0,
|
||||
'dex2' => 0,
|
||||
],
|
||||
'dexFloor' => [
|
||||
'dex1' => 0,
|
||||
'dex2' => 900000,
|
||||
],
|
||||
];
|
||||
$general = $this->createStateGeneralMock($vars, $aux);
|
||||
|
||||
CentennialAllStarGrowthService::reconcileDexConversion(
|
||||
$general,
|
||||
'dex2',
|
||||
'dex1',
|
||||
1000000,
|
||||
600000,
|
||||
0,
|
||||
360000,
|
||||
0.9
|
||||
);
|
||||
|
||||
self::assertSame(540000, $aux['granted']['dex2']);
|
||||
self::assertSame(324000, $aux['granted']['dex1']);
|
||||
self::assertSame(60_000, CentennialAllStarGrowthService::recordableValue($general, 'dex2'));
|
||||
self::assertSame(36_000, CentennialAllStarGrowthService::recordableValue($general, 'dex1'));
|
||||
self::assertSame(864000, $aux['granted']['dex1'] + $aux['granted']['dex2']);
|
||||
self::assertSame(
|
||||
96000,
|
||||
CentennialAllStarGrowthService::recordableValue($general, 'dex1')
|
||||
+ CentennialAllStarGrowthService::recordableValue($general, 'dex2')
|
||||
);
|
||||
}
|
||||
|
||||
public function testArcherCavalryGhostConversionChainKeepsOnlyCurrentTargetBudget(): void
|
||||
{
|
||||
$vars = $this->emptyGeneralVars();
|
||||
$aux = CentennialAllStarGrowthService::initialAux(
|
||||
$this->singleDexTarget('archer', 1),
|
||||
[]
|
||||
);
|
||||
$general = $this->createStateGeneralMock($vars, $aux);
|
||||
$env = ['startyear' => 180, 'year' => 195, 'month' => 1];
|
||||
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$this->singleDexTarget('archer', 1),
|
||||
$env
|
||||
);
|
||||
$this->convertDex($general, $vars, 'dex2', 'dex1');
|
||||
self::assertSame([324000, 540000, 0, 0, 0], $this->dexValues($vars));
|
||||
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$this->singleDexTarget('cavalry', 2),
|
||||
$env
|
||||
);
|
||||
self::assertSame([0, 0, 900000, 0, 0], $this->dexValues($vars));
|
||||
$this->convertDex($general, $vars, 'dex3', 'dex1');
|
||||
self::assertSame([324000, 0, 540000, 0, 0], $this->dexValues($vars));
|
||||
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$this->singleDexTarget('ghost', 3),
|
||||
$env
|
||||
);
|
||||
self::assertSame([0, 0, 0, 900000, 0], $this->dexValues($vars));
|
||||
$this->convertDex($general, $vars, 'dex4', 'dex1');
|
||||
|
||||
self::assertSame([324000, 0, 0, 540000, 0], $this->dexValues($vars));
|
||||
self::assertSame(864000, array_sum($this->dexValues($vars)));
|
||||
foreach (['dex1', 'dex2', 'dex3', 'dex4', 'dex5'] as $key) {
|
||||
self::assertSame(0, CentennialAllStarGrowthService::recordableValue($general, $key));
|
||||
}
|
||||
}
|
||||
|
||||
public function testSelectingInfantryAfterConversionReplacesOldEventBudget(): void
|
||||
{
|
||||
$vars = $this->emptyGeneralVars();
|
||||
$aux = CentennialAllStarGrowthService::initialAux(
|
||||
$this->singleDexTarget('archer', 1),
|
||||
[]
|
||||
);
|
||||
$general = $this->createStateGeneralMock($vars, $aux);
|
||||
$env = ['startyear' => 180, 'year' => 195, 'month' => 1];
|
||||
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$this->singleDexTarget('archer', 1),
|
||||
$env
|
||||
);
|
||||
$this->convertDex($general, $vars, 'dex2', 'dex1');
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$this->singleDexTarget('infantry', 0),
|
||||
$env
|
||||
);
|
||||
|
||||
self::assertSame([900000, 0, 0, 0, 0], $this->dexValues($vars));
|
||||
self::assertSame(900000, array_sum($aux['granted']));
|
||||
self::assertSame(0, CentennialAllStarGrowthService::recordableValue($general, 'dex1'));
|
||||
}
|
||||
|
||||
public function testMixedConversionThenReselectionPreservesOnlyPostLossNaturalTotal(): void
|
||||
{
|
||||
$vars = $this->emptyGeneralVars();
|
||||
$aux = CentennialAllStarGrowthService::initialAux(
|
||||
$this->singleDexTarget('archer', 1),
|
||||
[]
|
||||
);
|
||||
$general = $this->createStateGeneralMock($vars, $aux);
|
||||
$env = ['startyear' => 180, 'year' => 195, 'month' => 1];
|
||||
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$this->singleDexTarget('archer', 1),
|
||||
$env
|
||||
);
|
||||
$vars['dex2'] += 100000;
|
||||
$this->convertDex($general, $vars, 'dex2', 'dex1');
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
$this->singleDexTarget('infantry', 0),
|
||||
$env
|
||||
);
|
||||
|
||||
self::assertSame([900000, 60000, 0, 0, 0], $this->dexValues($vars));
|
||||
self::assertSame(864000, $aux['granted']['dex1']);
|
||||
self::assertSame(0, $aux['granted']['dex2']);
|
||||
self::assertSame(96000, array_sum($this->recordableDexValues($general)));
|
||||
self::assertSame(960000, array_sum($this->dexValues($vars)));
|
||||
}
|
||||
|
||||
public function testReselectionResetsConsumedDexFloorAndTransferredGrant(): void
|
||||
{
|
||||
$vars = [
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex1' => 216000,
|
||||
'dex2' => 489600,
|
||||
'dex3' => 360000,
|
||||
'dex4' => 360000,
|
||||
'dex5' => 360000,
|
||||
'special' => 'None',
|
||||
];
|
||||
$aux = [
|
||||
'targetId' => 'A1000001',
|
||||
'granted' => [
|
||||
'leadership' => 85,
|
||||
'strength' => 85,
|
||||
'intel' => 85,
|
||||
'dex1' => 216000,
|
||||
'dex2' => 489600,
|
||||
'dex3' => 360000,
|
||||
'dex4' => 360000,
|
||||
'dex5' => 360000,
|
||||
],
|
||||
'dexConsumed' => [
|
||||
'dex1' => 144000,
|
||||
'dex2' => 0,
|
||||
'dex3' => 0,
|
||||
'dex4' => 0,
|
||||
'dex5' => 0,
|
||||
],
|
||||
'dexFloor' => [
|
||||
'dex1' => 216000,
|
||||
'dex2' => 360000,
|
||||
'dex3' => 360000,
|
||||
'dex4' => 360000,
|
||||
'dex5' => 360000,
|
||||
],
|
||||
'progressMonth' => 180,
|
||||
'milestone' => 5,
|
||||
'naturalSpecialDomestic' => null,
|
||||
'eventSpecialDomestic' => null,
|
||||
'userInitialStats' => [],
|
||||
'dexTargetRatio' => 1.0,
|
||||
];
|
||||
$general = $this->createStateGeneralMock($vars, $aux);
|
||||
|
||||
CentennialAllStarGrowthService::applyTarget(
|
||||
$general,
|
||||
[
|
||||
'uniqueName' => 'A1000002',
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex' => [400000, 400000, 400000, 400000, 400000],
|
||||
],
|
||||
['startyear' => 180, 'year' => 195, 'month' => 1]
|
||||
);
|
||||
|
||||
self::assertSame(400000, $vars['dex1']);
|
||||
self::assertSame(400000, $vars['dex2']);
|
||||
self::assertSame(0, $aux['dexConsumed']['dex1']);
|
||||
self::assertSame(400000, $aux['dexFloor']['dex1']);
|
||||
self::assertSame(400000, $aux['granted']['dex1']);
|
||||
self::assertSame(400000, $aux['granted']['dex2']);
|
||||
}
|
||||
|
||||
public function testUserDexStillReachesFullHistoricalTarget(): void
|
||||
{
|
||||
self::assertSame(
|
||||
900000,
|
||||
CentennialAllStarGrowthService::calculateDexTargetFloor(
|
||||
900000,
|
||||
['startyear' => 180, 'year' => 195, 'month' => 1]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public function testUntrackedGeneralKeepsFullHallValue(): void
|
||||
{
|
||||
self::assertSame(
|
||||
123456,
|
||||
CentennialAllStarGrowthService::recordableRawValue(
|
||||
['dex1' => 123456, 'aux' => '{}'],
|
||||
'dex1'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
private function createStateGeneralMock(array &$vars, array &$aux): General
|
||||
{
|
||||
$general = $this->getMockBuilder(General::class)
|
||||
->disableOriginalConstructor()
|
||||
->onlyMethods(['getAuxVar', 'setAuxVar', 'getVar', 'updateVar'])
|
||||
->getMock();
|
||||
$general->method('getAuxVar')->willReturnCallback(
|
||||
static function (string $key) use (&$aux) {
|
||||
return $key === CentennialAllStarGrowthService::AUX_KEY
|
||||
? $aux
|
||||
: null;
|
||||
}
|
||||
);
|
||||
$general->method('getVar')->willReturnCallback(
|
||||
static function (string $key) use (&$vars) {
|
||||
return $vars[$key] ?? null;
|
||||
}
|
||||
);
|
||||
$general->method('updateVar')->willReturnCallback(
|
||||
static function (string $key, $value) use (&$vars): void {
|
||||
$vars[$key] = $value;
|
||||
}
|
||||
);
|
||||
$general->method('setAuxVar')->willReturnCallback(
|
||||
static function (string $key, $value) use (&$aux): void {
|
||||
if ($key === CentennialAllStarGrowthService::AUX_KEY) {
|
||||
$aux = $value;
|
||||
}
|
||||
}
|
||||
);
|
||||
return $general;
|
||||
}
|
||||
|
||||
private function emptyGeneralVars(): array
|
||||
{
|
||||
return [
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex1' => 0,
|
||||
'dex2' => 0,
|
||||
'dex3' => 0,
|
||||
'dex4' => 0,
|
||||
'dex5' => 0,
|
||||
'special' => 'None',
|
||||
];
|
||||
}
|
||||
|
||||
private function singleDexTarget(string $id, int $dexIndex): array
|
||||
{
|
||||
$dex = [0, 0, 0, 0, 0];
|
||||
$dex[$dexIndex] = 900000;
|
||||
return [
|
||||
'uniqueName' => $id,
|
||||
'leadership' => 100,
|
||||
'strength' => 100,
|
||||
'intel' => 100,
|
||||
'dex' => $dex,
|
||||
];
|
||||
}
|
||||
|
||||
private function convertDex(
|
||||
General $general,
|
||||
array &$vars,
|
||||
string $sourceKey,
|
||||
string $destinationKey
|
||||
): void {
|
||||
$sourceBefore = $vars[$sourceKey];
|
||||
$destinationBefore = $vars[$destinationKey];
|
||||
$cut = (int) ($sourceBefore * 0.4);
|
||||
$add = (int) ($cut * 0.9);
|
||||
$vars[$sourceKey] -= $cut;
|
||||
$vars[$destinationKey] += $add;
|
||||
CentennialAllStarGrowthService::reconcileDexConversion(
|
||||
$general,
|
||||
$sourceKey,
|
||||
$destinationKey,
|
||||
$sourceBefore,
|
||||
$vars[$sourceKey],
|
||||
$destinationBefore,
|
||||
$vars[$destinationKey],
|
||||
0.9
|
||||
);
|
||||
}
|
||||
|
||||
private function dexValues(array $vars): array
|
||||
{
|
||||
return [
|
||||
$vars['dex1'],
|
||||
$vars['dex2'],
|
||||
$vars['dex3'],
|
||||
$vars['dex4'],
|
||||
$vars['dex5'],
|
||||
];
|
||||
}
|
||||
|
||||
private function recordableDexValues(General $general): array
|
||||
{
|
||||
return array_map(
|
||||
static fn(string $key): int => CentennialAllStarGrowthService::recordableValue(
|
||||
$general,
|
||||
$key
|
||||
),
|
||||
['dex1', 'dex2', 'dex3', 'dex4', 'dex5']
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use sammo\GameConst;
|
||||
use sammo\GeneralPool\SPoolUnderU100;
|
||||
|
||||
require_once __DIR__ . '/../hwe/sammo/AbsGeneralPool.php';
|
||||
require_once __DIR__ . '/../hwe/sammo/AbsFromUserPool.php';
|
||||
require_once __DIR__ . '/../hwe/sammo/GeneralPool/SPoolUnderU100.php';
|
||||
require_once __DIR__ . '/../hwe/sammo/ActionLogger.php';
|
||||
require_once __DIR__ . '/../hwe/sammo/GameConstBase.php';
|
||||
require_once __DIR__ . '/../hwe/d_setting/GameConst.php';
|
||||
|
||||
final class CentennialAllStarPoolTest extends TestCase
|
||||
{
|
||||
private const POOL_PATH = __DIR__ . '/../hwe/sammo/GeneralPool/Pool/UnderS100.json';
|
||||
|
||||
public function testPoolCoversEveryCompletedNonEventPhase(): void
|
||||
{
|
||||
$pool = json_decode(
|
||||
file_get_contents(self::POOL_PATH),
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR
|
||||
);
|
||||
self::assertSame(
|
||||
[
|
||||
'generalName',
|
||||
'leadership',
|
||||
'strength',
|
||||
'intel',
|
||||
'specialDomestic',
|
||||
'dex',
|
||||
'imgsvr',
|
||||
'picture',
|
||||
'sourcePhase',
|
||||
'sourceServerId',
|
||||
'sourceGeneralNo',
|
||||
'selectionReasons',
|
||||
],
|
||||
$pool['columns']
|
||||
);
|
||||
self::assertCount(4682, $pool['data']);
|
||||
self::assertSame(
|
||||
[
|
||||
5, 10, 15, 20, 25, 30, 35, 40, 45, 50,
|
||||
55, 60, 65, 70, 75, 80, 85, 90, 95,
|
||||
],
|
||||
$pool['excludedEventPhases']
|
||||
);
|
||||
|
||||
$column = array_flip($pool['columns']);
|
||||
$phases = [];
|
||||
$chiefCounts = [];
|
||||
$sourceKeys = [];
|
||||
$generalNames = [];
|
||||
foreach ($pool['data'] as $row) {
|
||||
self::assertCount(count($pool['columns']), $row);
|
||||
|
||||
$phase = $row[$column['sourcePhase']];
|
||||
$sourceKey = "{$phase}:{$row[$column['sourceGeneralNo']]}";
|
||||
self::assertArrayNotHasKey($sourceKey, $sourceKeys);
|
||||
$sourceKeys[$sourceKey] = true;
|
||||
$phases[$phase] = true;
|
||||
|
||||
$generalName = $row[$column['generalName']];
|
||||
self::assertArrayNotHasKey($generalName, $generalNames);
|
||||
$generalNames[$generalName] = true;
|
||||
self::assertMatchesRegularExpression('/^(\d{1,2})·.+$/u', $generalName);
|
||||
self::assertSame(
|
||||
1,
|
||||
preg_match('/^(\d{1,2})·/u', $generalName, $nameMatch)
|
||||
);
|
||||
self::assertSame($phase, (int) $nameMatch[1]);
|
||||
self::assertLessThanOrEqual(32, mb_strlen($generalName));
|
||||
|
||||
self::assertCount(5, $row[$column['dex']]);
|
||||
self::assertNotEmpty($row[$column['selectionReasons']]);
|
||||
foreach ($row[$column['selectionReasons']] as $reason) {
|
||||
self::assertMatchesRegularExpression(
|
||||
'/^(hall:[a-z0-9_]+|chief:(?:5|6|7|8|9|10|11|12))$/',
|
||||
$reason
|
||||
);
|
||||
if (str_starts_with($reason, 'chief:')) {
|
||||
$chiefCounts[$phase] = ($chiefCounts[$phase] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($phases, SORT_NUMERIC);
|
||||
$expectedPhases = array_values(array_diff(
|
||||
range(1, 99),
|
||||
$pool['excludedEventPhases']
|
||||
));
|
||||
self::assertSame($expectedPhases, array_keys($phases));
|
||||
foreach ($expectedPhases as $phase) {
|
||||
self::assertSame(
|
||||
8,
|
||||
$chiefCounts[$phase] ?? 0,
|
||||
"phase {$phase} must include the ruler and seven chiefs"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function testCentennialSelectionWeightFavorsUserStatsAndKeepsZeroDexEligible(): void
|
||||
{
|
||||
$method = new ReflectionMethod(SPoolUnderU100::class, 'getCandidateWeight');
|
||||
$method->setAccessible(true);
|
||||
$low = [
|
||||
'leadership' => 80,
|
||||
'strength' => 70,
|
||||
'intel' => 10,
|
||||
'dex' => [0, 0, 0, 0, 0],
|
||||
];
|
||||
$high = [
|
||||
'leadership' => 95,
|
||||
'strength' => 85,
|
||||
'intel' => 10,
|
||||
'dex' => [0, 0, 0, 0, 0],
|
||||
];
|
||||
|
||||
self::assertSame(100000, $method->invoke(null, $low, 0));
|
||||
self::assertSame(100000.0, $method->invoke(null, $low, 1));
|
||||
self::assertSame(150000.0, $method->invoke(null, $high, 1));
|
||||
self::assertSame(100000, $method->invoke(null, $high, 0));
|
||||
}
|
||||
|
||||
public function testEveryHistoricalEventSpecialHasAnImplementation(): void
|
||||
{
|
||||
$pool = json_decode(
|
||||
file_get_contents(self::POOL_PATH),
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR
|
||||
);
|
||||
$column = array_flip($pool['columns']);
|
||||
|
||||
foreach ($pool['data'] as $row) {
|
||||
$special = $row[$column['specialDomestic']];
|
||||
if ($special === null) {
|
||||
continue;
|
||||
}
|
||||
self::assertFileExists(
|
||||
__DIR__ . "/../hwe/sammo/ActionSpecialDomestic/{$special}.php"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function testEveryHistoricalEventSpecialIsExposedToTheFrontend(): void
|
||||
{
|
||||
$pool = json_decode(
|
||||
file_get_contents(self::POOL_PATH),
|
||||
true,
|
||||
512,
|
||||
JSON_THROW_ON_ERROR
|
||||
);
|
||||
$column = array_flip($pool['columns']);
|
||||
$registeredSpecials = array_flip(array_merge(
|
||||
GameConst::$availableSpecialDomestic,
|
||||
GameConst::$optionalSpecialDomestic
|
||||
));
|
||||
|
||||
foreach ($pool['data'] as $row) {
|
||||
$special = $row[$column['specialDomestic']];
|
||||
if ($special === null || $special === '') {
|
||||
continue;
|
||||
}
|
||||
self::assertArrayHasKey(
|
||||
$special,
|
||||
$registeredSpecials,
|
||||
"{$special} must be included in GetConst iActionInfo.specialDomestic"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import fs from 'node:fs';
|
||||
import {createHash} from 'node:crypto';
|
||||
import {chromium} from 'playwright';
|
||||
|
||||
const baseURL = process.env.REF_BROWSER_URL;
|
||||
const screenshotPath = process.env.REF_SCREENSHOT_PATH;
|
||||
const resultPath = process.env.REF_RESULT_PATH;
|
||||
const username = process.env.REF_USER_ID ?? 's100user01';
|
||||
const password = fs.readFileSync('/run/secrets/test_user_password', 'utf8').trim();
|
||||
const expectedReason = '100기 올스타 장수는 능력치 초기화를 사용할 수 없습니다.';
|
||||
const expectedWarning = '100기 올스타 장수는 장수 전환 시 능력치 성장 기록을 보존하기 위해 능력치 초기화를 사용할 수 없습니다.';
|
||||
|
||||
if (!baseURL || !screenshotPath || !resultPath) {
|
||||
throw new Error('REF_BROWSER_URL, REF_SCREENSHOT_PATH, and REF_RESULT_PATH are required');
|
||||
}
|
||||
|
||||
const browser = await chromium.launch({headless: true});
|
||||
const context = await browser.newContext({
|
||||
viewport: {width: 1280, height: 960},
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
const browserMessages = [];
|
||||
const attachPageListeners = targetPage => {
|
||||
targetPage.on('console', message => {
|
||||
browserMessages.push({type: message.type(), text: message.text()});
|
||||
});
|
||||
targetPage.on('pageerror', error => {
|
||||
browserMessages.push({type: 'pageerror', text: error.message});
|
||||
});
|
||||
};
|
||||
let page = await context.newPage();
|
||||
attachPageListeners(page);
|
||||
|
||||
await page.goto(baseURL, {waitUntil: 'domcontentloaded', timeout: 60_000});
|
||||
const salt = await page.locator('#global_salt').inputValue();
|
||||
const passwordHash = createHash('sha512')
|
||||
.update(salt + password + salt)
|
||||
.digest('hex');
|
||||
const loginResponse = await page.request.post(
|
||||
new URL('api.php?path=Login/LoginByID', baseURL).href,
|
||||
{data: {username, password: passwordHash}},
|
||||
);
|
||||
const loginResult = await loginResponse.json();
|
||||
if (!loginResponse.ok() || loginResult.result !== true) {
|
||||
throw new Error(`login failed: ${String(loginResult.reason ?? loginResponse.status())}`);
|
||||
}
|
||||
|
||||
const gameLoginResponse = await page.request.get(
|
||||
new URL('hwe/api.php?path=Global/GetConst', baseURL).href,
|
||||
);
|
||||
const gameLoginResult = await gameLoginResponse.json();
|
||||
if (!gameLoginResponse.ok() || gameLoginResult.result !== true) {
|
||||
throw new Error(`game login failed: ${JSON.stringify(gameLoginResult)}`);
|
||||
}
|
||||
|
||||
await page.close();
|
||||
browserMessages.length = 0;
|
||||
page = await context.newPage();
|
||||
attachPageListeners(page);
|
||||
await page.goto(
|
||||
new URL('hwe/v_inheritPoint.php', baseURL).href,
|
||||
{waitUntil: 'networkidle', timeout: 60_000},
|
||||
);
|
||||
const bodyText = await page.locator('body').innerText();
|
||||
if (bodyText.includes('#0 /var/www/html/')) {
|
||||
throw new Error('PHP stack trace was rendered in the inheritance page');
|
||||
}
|
||||
if (!bodyText.includes(expectedWarning)) {
|
||||
await page.screenshot({path: screenshotPath, fullPage: true});
|
||||
fs.writeFileSync(
|
||||
resultPath,
|
||||
`${JSON.stringify({
|
||||
username,
|
||||
url: page.url(),
|
||||
bodyText: bodyText.slice(0, 4000),
|
||||
browserMessages,
|
||||
}, null, 2)}\n`,
|
||||
{mode: 0o600},
|
||||
);
|
||||
throw new Error('S100 stat-reset restriction was not rendered');
|
||||
}
|
||||
if (await page.getByRole('button', {name: '능력치 초기화'}).count() !== 0) {
|
||||
throw new Error('S100 stat-reset button must not be rendered');
|
||||
}
|
||||
|
||||
const warning = page.getByText(expectedWarning, {exact: true});
|
||||
await warning.waitFor({state: 'visible', timeout: 60_000});
|
||||
const warningGeometry = await warning.evaluate(element => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
rect: {
|
||||
x: rect.x,
|
||||
y: rect.y,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
},
|
||||
style: {
|
||||
color: style.color,
|
||||
fontFamily: style.fontFamily,
|
||||
fontSize: style.fontSize,
|
||||
lineHeight: style.lineHeight,
|
||||
},
|
||||
};
|
||||
});
|
||||
const beforeState = await page.evaluate(() => ({
|
||||
currentStat: staticValues.currentStat,
|
||||
previousPoint: staticValues.items.previous,
|
||||
}));
|
||||
|
||||
const resetResponse = await page.request.put(
|
||||
new URL('hwe/api.php?path=InheritAction/ResetStat', baseURL).href,
|
||||
{
|
||||
data: {
|
||||
leadership: 55,
|
||||
strength: 55,
|
||||
intel: 55,
|
||||
},
|
||||
},
|
||||
);
|
||||
const resetResult = await resetResponse.json();
|
||||
if (!resetResponse.ok()
|
||||
|| resetResult.result !== false
|
||||
|| resetResult.reason !== expectedReason
|
||||
) {
|
||||
throw new Error(`unexpected ResetStat response: ${JSON.stringify(resetResult)}`);
|
||||
}
|
||||
|
||||
await page.reload({waitUntil: 'networkidle', timeout: 60_000});
|
||||
const afterState = await page.evaluate(() => ({
|
||||
currentStat: staticValues.currentStat,
|
||||
previousPoint: staticValues.items.previous,
|
||||
}));
|
||||
if (JSON.stringify(afterState) !== JSON.stringify(beforeState)) {
|
||||
throw new Error(`ResetStat rejection changed state: ${JSON.stringify({beforeState, afterState})}`);
|
||||
}
|
||||
|
||||
await page.screenshot({path: screenshotPath, fullPage: true});
|
||||
fs.writeFileSync(
|
||||
resultPath,
|
||||
`${JSON.stringify({
|
||||
username,
|
||||
url: page.url(),
|
||||
viewport: {width: 1280, height: 960, deviceScaleFactor: 1},
|
||||
warningGeometry,
|
||||
resetResult,
|
||||
beforeState,
|
||||
afterState,
|
||||
browserMessages,
|
||||
}, null, 2)}\n`,
|
||||
{mode: 0o600},
|
||||
);
|
||||
|
||||
await browser.close();
|
||||
console.log(`S100 inheritance stat-reset guard verified: ${screenshotPath}`);
|
||||
Reference in New Issue
Block a user