Compare commits

..
23 Commits
Author SHA1 Message Date
Hide_D 191abf83c0 test: isolate S100 inheritance browser logs 2026-07-29 08:51:51 +00:00
Hide_D edfeae5f0f fix: block S100 inheritance stat resets 2026-07-29 08:42:38 +00:00
Hide_D 424184a51a fix: define mixed S100 dex conversion ownership 2026-07-29 07:29:43 +00:00
Hide_D 03a321f95d fix: prevent S100 dex conversion refills 2026-07-29 06:36:33 +00:00
Hide_D e3615fa6bb fix: cap S100 NPC dex growth at forty percent 2026-07-29 05:20:53 +00:00
Hide_D 32991f736d fix: expose S100 event traits to frontend 2026-07-29 05:11:19 +00:00
Hide_D 8b2748d3d4 feat: 재선택 현재 능력치 기준 표시 2026-07-28 16:56:02 +00:00
Hide_D 883080e275 feat: 100기 NPC 동조 및 후보 추첨 기능 개선과 초기 능력치 계산 로직 추가 2026-07-28 16:28:13 +00:00
Hide_D ce807e2564 유니크 획득 확률 조금 더 증가 2026-07-28 16:11:24 +00:00
Hide_D 9a2ac82373 시나리오 문제점 수정 2026-07-28 16:07:21 +00:00
Hide_D 3c35539c16 CreateManyNPC 추가 2026-07-28 16:04:50 +00:00
Hide_D 5ab08403c6 feat: 100기 NPC 동조와 후보 추첨 보완 2026-07-28 16:02:14 +00:00
Hide_D c1ce478d22 feat: exclude prior event seasons from all-star pool 2026-07-28 00:43:46 +00:00
Hide_D d8bf8ba922 feat: expand 100th-season pool through phase 99 2026-07-28 00:29:25 +00:00
Hide_D 95f66e4c39 feat: add 100th-season all-star growth event 2026-07-25 10:46:23 +00:00
Hide_D 4de7ebec17 요양 깃수 추가 2026-03-04 14:16:08 +00:00
Hide_D d43dff35fb fix: 디버그 코드 복구 2026-02-18 18:54:46 +00:00
Hide_D 5b13f8bd30 ip 기록 2026-02-17 22:31:08 +09:00
Hide_D e51bc6f711 fix: 턴 데몬에 cookie jar 적용 2026-02-17 20:35:15 +09:00
Hide_D 1b08aa0c58 wip: 디버그 코드 추가 2026-02-17 19:12:28 +09:00
Hide_D f2547fe207 dbg 2026-02-17 18:32:04 +09:00
류화영 cec7726731 fix: 방랑군이 빈번하게 해산하는 문제 해결 시도 2026-01-19 22:50:11 +09:00
Hide_D d679a6fed8 fix: InheritancePointManager 버그 수정 2025-11-01 17:38:02 +00:00
78 changed files with 119839 additions and 1222 deletions
+4 -1
View File
@@ -243,11 +243,14 @@ $templates = new \League\Plates\Engine(__DIR__ . '/templates');
"SELECT nation,no,name,owner_name as ownerName, owner, picture, imgsvr, "SELECT nation,no,name,owner_name as ownerName, owner, picture, imgsvr,
experience, dedication, experience, dedication,
dex1, dex2, dex3, dex4, dex5, dex1, dex2, dex3, dex4, dex5,
horse, weapon, book, item horse, weapon, book, item, aux
FROM general WHERE %l", FROM general WHERE %l",
$btn == "NPC 보기" ? "npc>=2" : "npc<2" $btn == "NPC 보기" ? "npc>=2" : "npc<2"
) as $general) { ) as $general) {
$generalID = $general['no']; $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['bgColor'] = $nationColor[$general['nation']] ?? GameConst::$basecolor4;
$general['fgColor'] = newColor($general['bgColor']); $general['fgColor'] = newColor($general['bgColor']);
$general['nationName'] = $nationName[$general['nation']]; $general['nationName'] = $nationName[$general['nation']];
+16
View File
@@ -51,6 +51,22 @@
display: none; 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 { .custom_picture {
display: none; display: none;
} }
+7 -48
View File
@@ -923,13 +923,6 @@ function banner()
function addTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true) function addTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
{ {
if($turnterm < 0){
if($turnterm == -60){
return VarTurn60::fromDatetime(new \DateTimeImmutable(($date)))->addTurn($turn )->toDateStr($withFraction);
}
throw new \Exception("InvalidTurnTerm".$turnterm);
}
$date = new \DateTime($date); $date = new \DateTime($date);
$target = $turnterm * $turn; $target = $turnterm * $turn;
$date->add(new \DateInterval("PT{$target}M")); $date->add(new \DateInterval("PT{$target}M"));
@@ -941,13 +934,6 @@ function addTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
function subTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true) function subTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
{ {
if($turnterm < 0){
if($turnterm == -60){
return VarTurn60::fromDatetime(new \DateTimeImmutable(($date)))->addTurn($turn * -1)->toDateStr($withFraction);
}
throw new \Exception("InvalidTurnTerm".$turnterm);
}
$date = new \DateTime($date); $date = new \DateTime($date);
$target = $turnterm * $turn; $target = $turnterm * $turn;
$date->sub(new \DateInterval("PT{$target}M")); $date->sub(new \DateInterval("PT{$target}M"));
@@ -959,14 +945,6 @@ function subTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
function cutTurn($date, int $turnterm, bool $withFraction = true) function cutTurn($date, int $turnterm, bool $withFraction = true)
{ {
if($turnterm < 0){
if($turnterm == -60){
[$baseDate, ] = VarTurn60::fromDatetime(new \DateTimeImmutable(($date)))->cutTurn($withFraction);
return $baseDate;
}
throw new \Exception("InvalidTurnTerm".$turnterm);
}
$date = new \DateTime($date); $date = new \DateTime($date);
$baseDate = new \DateTime($date->format('Y-m-d')); $baseDate = new \DateTime($date->format('Y-m-d'));
@@ -985,8 +963,6 @@ function cutTurn($date, int $turnterm, bool $withFraction = true)
function cutDay($date, int $turnterm, bool $withFraction = true) function cutDay($date, int $turnterm, bool $withFraction = true)
{ {
assert($turnterm > 0);
$date = new \DateTime($date); $date = new \DateTime($date);
$baseDate = new \DateTime($date->format('Y-m-d')); $baseDate = new \DateTime($date->format('Y-m-d'));
@@ -1071,7 +1047,7 @@ function increaseRefresh($type = "", $cnt = 1)
$logDB = FileDB::db($logPath, $serverPath . '/../f_install/sql/api_log.sql'); $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'); $date = date('Y-m-d H:i:s');
$logDB->insert('api_log', [ $logDB->insert('api_log', [
@@ -1130,7 +1106,6 @@ function CheckOverhead()
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
[$turnterm, $refreshLimit] = $gameStor->getValuesAsArray(['turnterm', 'refreshLimit']); [$turnterm, $refreshLimit] = $gameStor->getValuesAsArray(['turnterm', 'refreshLimit']);
$turnterm = abs($turnterm);
$nextRefreshLimit = Util::round(pow($turnterm, 0.6) * 3) * GameConst::$refreshLimitCoef; $nextRefreshLimit = Util::round(pow($turnterm, 0.6) * 3) * GameConst::$refreshLimitCoef;
@@ -1178,7 +1153,7 @@ function timeover(): bool
list($turnterm, $turntime) = $gameStor->getValuesAsArray(['turnterm', 'turntime']); list($turnterm, $turntime) = $gameStor->getValuesAsArray(['turnterm', 'turntime']);
$diff = (new \DateTime())->getTimestamp() - (new \DateTime($turntime))->getTimestamp(); $diff = (new \DateTime())->getTimestamp() - (new \DateTime($turntime))->getTimestamp();
$t = min(abs($turnterm), 5); $t = min($turnterm, 5);
$term = $diff; $term = $diff;
if ($term >= $t || $term < 0) { if ($term >= $t || $term < 0) {
@@ -1200,12 +1175,6 @@ function checkDelay()
// 1턴이상 갱신 없었으면 서버 지연 // 1턴이상 갱신 없었으면 서버 지연
$term = $gameStor->turnterm; $term = $gameStor->turnterm;
if($term < 0){
//가변 턴에는 수행 안함!
return;
}
if ($term >= 20) { if ($term >= 20) {
$threshold = 1; $threshold = 1;
} else if ($term >= 10) { } else if ($term >= 10) {
@@ -1285,14 +1254,10 @@ function turnDate($curtime)
$admin = $gameStor->getValues(['startyear', 'starttime', 'turnterm', 'year', 'month']); $admin = $gameStor->getValues(['startyear', 'starttime', 'turnterm', 'year', 'month']);
$turn = $admin['starttime']; $turn = $admin['starttime'];
$term = $admin['turnterm'];
if($term == -60){
$num = VarTurn60::calcTurnDiff(new \DateTimeImmutable($turn), new \DateTimeImmutable($curtime));
}
else{
$curturn = cutTurn($curtime, $admin['turnterm']); $curturn = cutTurn($curtime, $admin['turnterm']);
$term = $admin['turnterm'];
$num = intdiv((strtotime($curturn) - strtotime($turn)), $term * 60); $num = intdiv((strtotime($curturn) - strtotime($turn)), $term * 60);
}
$date = $admin['startyear'] * 12; $date = $admin['startyear'] * 12;
$date += $num; $date += $num;
@@ -1438,6 +1403,9 @@ function CheckHall($no)
if ($valueType === 'natural') { if ($valueType === 'natural') {
$value = $generalObj->getVar($typeName); $value = $generalObj->getVar($typeName);
if (in_array($typeName, ['dex1', 'dex2', 'dex3', 'dex4', 'dex5'], true)) {
$value = CentennialAllStarGrowthService::recordableValue($generalObj, $typeName);
}
} else if ($valueType === 'rank') { } else if ($valueType === 'rank') {
$value = $generalObj->getRankVar(RankColumn::from($typeName)); $value = $generalObj->getRankVar(RankColumn::from($typeName));
} else if ($valueType === 'calc') { } else if ($valueType === 'calc') {
@@ -2243,10 +2211,6 @@ function getRandTurn(RandUtil $rng, $term, ?\DateTimeInterface $baseDateTime = n
throw new MustNotBeReachedException(); throw new MustNotBeReachedException();
} }
if($term == -60){
[, $term] = VarTurn60::fromDatetime($baseDateTime)->cutTurn();
}
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1); $randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수 $randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수
@@ -2262,11 +2226,6 @@ function getRandTurn2(RandUtil $rng, $term, ?\DateTimeInterface $baseDateTime =
} else { } else {
throw new MustNotBeReachedException(); throw new MustNotBeReachedException();
} }
if($term == -60){
[, $term] = VarTurn60::fromDatetime($baseDateTime)->cutTurn();
}
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1); $randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수 $randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수
+1 -6
View File
@@ -181,12 +181,7 @@ function info($type = 0)
$admin = $gameStor->getValues(['year', 'month', 'turnterm', 'maxgeneral']); $admin = $gameStor->getValues(['year', 'month', 'turnterm', 'maxgeneral']);
$turnTermText = $admin['turnterm'].'분'; $termtype = "{$admin['turnterm']}분 턴";
if($admin['turnterm'] < 0){
$turnTermText = "가변 {$admin['turnterm']}분";
}
$termtype = "{$turnTermText}분 턴";
$gencount = $db->queryFirstField('SELECT count(no) FROM general WHERE npc < 2'); $gencount = $db->queryFirstField('SELECT count(no) FROM general WHERE npc < 2');
$npccount = $db->queryFirstField('SELECT count(no) FROM general WHERE npc >= 2'); $npccount = $db->queryFirstField('SELECT count(no) FROM general WHERE npc >= 2');
+1 -3
View File
@@ -10,7 +10,6 @@ use sammo\Enums\InheritanceKey;
* @return int 토너먼트 초 단위 * @return int 토너먼트 초 단위
*/ */
function calcTournamentTerm(int $turnTerm): int{ function calcTournamentTerm(int $turnTerm): int{
$turnTerm = abs($turnTerm);
return Util::valueFit($turnTerm, 5, 120); return Util::valueFit($turnTerm, 5, 120);
} }
@@ -139,7 +138,6 @@ function processTournament()
function getTournamentTermText(int $turnTerm) function getTournamentTermText(int $turnTerm)
{ {
$turnTerm = abs($turnTerm);
$term = calcTournamentTerm($turnTerm); $term = calcTournamentTerm($turnTerm);
if ($term % 60 === 0) { if ($term % 60 === 0) {
@@ -344,7 +342,7 @@ function startBetting($type)
{ {
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month, $startyear] = $gameStor->getValuesAsArray(['year', 'month', 'startyear']); [$year, $month, $startyear, $turnterm] = $gameStor->getValuesAsArray(['year', 'month', 'startyear', 'turnterm']);
pushGlobalHistoryLog([ pushGlobalHistoryLog([
"<S>◆</>{$year}{$month}월:<B><b>【대회】</b></>우승자를 예상하는 <C>내기</>가 진행중입니다! 호사가의 참여를 기다립니다!" "<S>◆</>{$year}{$month}월:<B><b>【대회】</b></>우승자를 예상하는 <C>내기</>가 진행중입니다! 호사가의 참여를 기다립니다!"
], $year, $month); ], $year, $month);
-1
View File
@@ -54,7 +54,6 @@ if ($session->userGrade < 5 && !$allowReset) {
<label for="turnterm" class="col-sm-3 col-form-label">턴 시간(분)</label> <label for="turnterm" class="col-sm-3 col-form-label">턴 시간(분)</label>
<div class="col-sm-9"> <div class="col-sm-9">
<div id="turnterm" class="btn-group btn-group-toggle" data-bs-toggle="buttons"> <div id="turnterm" class="btn-group btn-group-toggle" data-bs-toggle="buttons">
<input type="radio" class="btn-check" name="turnterm" id="turnterm_var60" value="-60" checked><label for="turnterm_var60" class="btn btn-secondary">가변60</label>
<input type="radio" class="btn-check" name="turnterm" id="turnterm_120" value="120"><label for="turnterm_120" class="btn btn-secondary">120</label> <input type="radio" class="btn-check" name="turnterm" id="turnterm_120" value="120"><label for="turnterm_120" class="btn btn-secondary">120</label>
<input type="radio" class="btn-check" name="turnterm" id="turnterm_60" value="60" checked><label for="turnterm_60" class="btn btn-secondary">60</label> <input type="radio" class="btn-check" name="turnterm" id="turnterm_60" value="60" checked><label for="turnterm_60" class="btn btn-secondary">60</label>
<input type="radio" class="btn-check" name="turnterm" id="turnterm_30" value="30"><label for="turnterm_30" class="btn btn-secondary">30</label> <input type="radio" class="btn-check" name="turnterm" id="turnterm_30" value="30"><label for="turnterm_30" class="btn btn-secondary">30</label>
-1
View File
@@ -36,7 +36,6 @@ list(
$turnterm, $turnterm,
$npcmode $npcmode
) = $gameStor->getValuesAsArray(['maxgeneral', 'turnterm', 'npcmode']); ) = $gameStor->getValuesAsArray(['maxgeneral', 'turnterm', 'npcmode']);
$turnterm = abs($turnterm);
if($npcmode!=1){ if($npcmode!=1){
Json::die([ Json::die([
+22 -4
View File
@@ -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)){ if(key_exists('specialDomestic', $info)){
$class = buildGeneralSpecialDomesticClass($info['specialDomestic']); $class = buildGeneralSpecialDomesticClass($info['specialDomestic']);
$info['specialDomesticName'] = $class->getName(); $info['specialDomesticName'] = $class->getName();
@@ -34,7 +50,8 @@ $now = $oNow->format('Y-m-d H:i:s');
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$npcmode = $gameStor->getValue('npcmode'); $eventEnv = $gameStor->getValues(['npcmode', 'startyear', 'year', 'month']);
$npcmode = $eventEnv['npcmode'];
if($npcmode!=2){ if($npcmode!=2){
Json::die([ Json::die([
'result'=>false, 'result'=>false,
@@ -43,6 +60,7 @@ if($npcmode!=2){
} }
$rawGeneral = $db->queryFirstRow('SELECT no, aux FROM general WHERE `owner` = %i', $userID); $rawGeneral = $db->queryFirstRow('SELECT no, aux FROM general WHERE `owner` = %i', $userID);
$currentTargetEnv = $rawGeneral ? $eventEnv : null;
if($rawGeneral){ if($rawGeneral){
$generalAux = Json::decode($rawGeneral['aux']); $generalAux = Json::decode($rawGeneral['aux']);
if(key_exists('next_change', $generalAux)&& $generalAux['next_change'] > $now){ if(key_exists('next_change', $generalAux)&& $generalAux['next_change'] > $now){
@@ -62,7 +80,7 @@ if($tokens){
foreach($tokens as $token){ foreach($tokens as $token){
$valid_until = $token['reserved_until']; $valid_until = $token['reserved_until'];
$info = Json::decode($token['info']); $info = Json::decode($token['info']);
putInfoText($info); putInfoText($info, $currentTargetEnv);
$info['uniqueName'] = $token['unique_name']; $info['uniqueName'] = $token['unique_name'];
$pick[] = $info; $pick[] = $info;
} }
@@ -83,7 +101,7 @@ $valid_until = null;
foreach(pickGeneralFromPool($db, $rng, $userID, 14) as $pickObj){ foreach(pickGeneralFromPool($db, $rng, $userID, 14) as $pickObj){
$valid_until = $pickObj->getValidUntil(); $valid_until = $pickObj->getValidUntil();
$info = $pickObj->getInfo(); $info = $pickObj->getInfo();
putInfoText($info); putInfoText($info, $currentTargetEnv);
$pick[] = $info; $pick[] = $info;
} }
sortTokens($pick);//좀 무식하지만.. sortTokens($pick);//좀 무식하지만..
+80 -8
View File
@@ -8,10 +8,20 @@ WebUtil::requireAJAX();
$pick = Util::getPost('pick'); $pick = Util::getPost('pick');
$leadership = Util::getPost('leadership', 'int', GameConst::$defaultStatMin); $leadership = Util::getPost('leadership', 'int', GameConst::$defaultStatMin);
$strength = Util::getPost('leadership', 'int', GameConst::$defaultStatMin); $isCentennialAllStar = CentennialAllStarGrowthService::isActive();
$intel = Util::getPost('leadership', 'int', GameConst::$defaultStatMin); $strength = Util::getPost(
$isCentennialAllStar ? 'strength' : 'leadership',
'int',
GameConst::$defaultStatMin
);
$intel = Util::getPost(
$isCentennialAllStar ? 'intel' : 'leadership',
'int',
GameConst::$defaultStatMin
);
$personal = Util::getPost('personal', 'string', null); $personal = Util::getPost('personal', 'string', null);
$use_own_picture = Util::getPost('use_own_picture', 'bool', false); $use_own_picture = Util::getPost('use_own_picture', 'bool', false);
$pictureSource = Util::getPost('picture_source', 'string', 'selected');
if(!$pick){ if(!$pick){
@@ -60,13 +70,36 @@ if(!$selectInfo){
} }
$selectInfo = Json::decode($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){ if(!$ownerInfo){
Json::die([ Json::die([
'result'=>false, 'result'=>false,
'reason'=>'멤버 정보를 가져오지 못했습니다.' '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'); $gencount = $db->queryFirstField('SELECT count(`no`) FROM general WHERE npc<2');
@@ -80,12 +113,25 @@ if ($gencount >= $maxgeneral) {
$poolClass = getGeneralPoolClass(GameConst::$targetGeneralPool); $poolClass = getGeneralPoolClass(GameConst::$targetGeneralPool);
/** @var AbsGeneralPool */ /** @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(); $builder = $pickedGeneral->getGeneralBuilder();
if ($isCentennialAllStar) {
CentennialAllStarGrowthService::prepareInitialUser($builder, $selectInfo);
}
foreach(GameConst::$generalPoolAllowOption as $allowOption){ foreach(GameConst::$generalPoolAllowOption as $allowOption){
if($allowOption == 'stat'){ if($allowOption == 'stat' && !$isCentennialAllStar){
$leadership = Util::valueFit($leadership, GameConst::$defaultStatMin, GameConst::$defaultStatMax); $leadership = Util::valueFit($leadership, GameConst::$defaultStatMin, GameConst::$defaultStatMax);
$strength = Util::valueFit($strength, GameConst::$defaultStatMin, GameConst::$defaultStatMax); $strength = Util::valueFit($strength, GameConst::$defaultStatMin, GameConst::$defaultStatMax);
$intel = Util::valueFit($intel, 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); $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']); $builder->setPicture($ownerInfo['imgsvr'], $ownerInfo['picture']);
} }
else if($allowOption == 'ego'){ else if($allowOption == 'ego'){
if(!$personal || $personal == 'Random'){ if(!$personal || $personal == 'Random'){
$personal = Util::choiceRandom(GameConst::$availablePersonality); $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([ Json::die([
'result'=>false, 'result'=>false,
'reason'=>'올바르지 않은 성격입니다.' 'reason'=>'올바르지 않은 성격입니다.'
@@ -121,8 +176,25 @@ $builder->setOwner($userID);
$builder->setOwnerName($userNick); $builder->setOwnerName($userNick);
$builder->setKillturn(5); $builder->setKillturn(5);
$builder->setNPCType(0); $builder->setNPCType(0);
$builder->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * abs($env['turnterm']))); $builder->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $env['turnterm']));
$builder->fillRemainSpecAsZero($env); $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); $builder->build($env);
$generalID = $builder->getGeneralID(); $generalID = $builder->getGeneralID();
if(!$generalID){ if(!$generalID){
+1 -1
View File
@@ -60,7 +60,7 @@ $me->setAuxVar('use_auto_nation_turn', $use_auto_nation_turn);
$me->setVar('tnmt', $tnmt); $me->setVar('tnmt', $tnmt);
if ($me->getNPCType() == 1 && $detachNPC) { if ($me->getNPCType() == 1 && $detachNPC) {
$turnterm = abs($gameStor->turnterm); $turnterm = $gameStor->turnterm;
if ($turnterm < 10) { if ($turnterm < 10) {
$targetKillTurn = 30 / $turnterm; $targetKillTurn = 30 / $turnterm;
+71 -20
View File
@@ -7,6 +7,7 @@ include "func.php";
WebUtil::requireAJAX(); WebUtil::requireAJAX();
$pick = Util::getPost('pick'); $pick = Util::getPost('pick');
$pictureSource = Util::getPost('picture_source', 'string', 'selected');
if(!$pick){ if(!$pick){
Json::die([ Json::die([
@@ -35,11 +36,20 @@ if(!$generalID){
list( list(
$year, $year,
$month, $month,
$startYear,
$maxgeneral, $maxgeneral,
$npcmode, $npcmode,
$turnterm $turnterm,
) = $gameStor->getValuesAsArray(['year', 'month', 'maxgeneral', 'npcmode', 'turnterm']); $showImgLevel
$turnterm = abs($turnterm); ) = $gameStor->getValuesAsArray([
'year',
'month',
'startyear',
'maxgeneral',
'npcmode',
'turnterm',
'show_img_level',
]);
if($npcmode!=2){ if($npcmode!=2){
Json::die([ Json::die([
@@ -56,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){ if(!$ownerInfo){
Json::die([ Json::die([
'result'=>false, 'result'=>false,
@@ -65,6 +78,27 @@ if(!$ownerInfo){
} }
$info = Json::decode($info); $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); $generalObj = General::createObjFromDB($generalID);
@@ -102,33 +136,50 @@ $db->update('select_pool',[
'reserved_until'=>null, 'reserved_until'=>null,
], '(owner=%i or reserved_until < %s) AND general_id is NULL', $userID, $now); ], '(owner=%i or reserved_until < %s) AND general_id is NULL', $userID, $now);
if(key_exists('leadership', $info)){ 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('leadership', $info['leadership']);
$generalObj->updateVar('strength', $info['strength']); $generalObj->updateVar('strength', $info['strength']);
$generalObj->updateVar('intel', $info['intel']); $generalObj->updateVar('intel', $info['intel']);
} }
if(key_exists('picture', $info)){ if(key_exists('dex', $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('dex1', $info['dex'][0]);
$generalObj->updateVar('dex2', $info['dex'][1]); $generalObj->updateVar('dex2', $info['dex'][1]);
$generalObj->updateVar('dex3', $info['dex'][2]); $generalObj->updateVar('dex3', $info['dex'][2]);
$generalObj->updateVar('dex4', $info['dex'][3]); $generalObj->updateVar('dex4', $info['dex'][3]);
$generalObj->updateVar('dex5', $info['dex'][4]); $generalObj->updateVar('dex5', $info['dex'][4]);
} }
if(key_exists('ego', $info)){ if(key_exists('ego', $info)){
$generalObj->updateVar('personal', $info['ego']); $generalObj->updateVar('personal', $info['ego']);
} }
if(key_exists('specialDomestic', $info)){ if(key_exists('specialDomestic', $info)){
$generalObj->updateVar('special', $info['specialDomestic']); $generalObj->updateVar('special', $info['specialDomestic']);
} }
if(key_exists('specialWar', $info)){ if(key_exists('specialWar', $info)){
$generalObj->updateVar('special2', $info['specialWar']); $generalObj->updateVar('special2', $info['specialWar']);
}
}
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']);
} }
$generalObj->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $turnterm)); $generalObj->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $turnterm));
+4 -13
View File
@@ -28,7 +28,6 @@ use sammo\UniqueConst;
use sammo\UserLogger; use sammo\UserLogger;
use sammo\Util; use sammo\Util;
use sammo\Validator; use sammo\Validator;
use sammo\VarTurn60;
use sammo\WebUtil; use sammo\WebUtil;
use function sammo\addTurn; use function sammo\addTurn;
@@ -356,28 +355,20 @@ class Join extends \sammo\BaseAPI
} }
if ($inheritTurntimeZone !== null) { if ($inheritTurntimeZone !== null) {
$turnterm = abs($admin['turnterm']); $inheritTurntime = $inheritTurntimeZone * $admin['turnterm'];
$inheritTurntime = $inheritTurntimeZone * $turnterm; $inheritTurntime += $rng->nextRangeInt(0, Util::clamp($admin['turnterm'] - 1, 0));
$inheritTurntime += $rng->nextRangeInt(0, Util::clamp($turnterm - 1, 0));
$userLogger->push(sprintf("턴 시간 %02d:%02d 로 지정", intdiv($inheritTurntime, 60), $inheritTurntime % 60), "inheritPoint"); $userLogger->push(sprintf("턴 시간 %02d:%02d 로 지정", intdiv($inheritTurntime, 60), $inheritTurntime % 60), "inheritPoint");
$inheritTurntime += $rng->nextRangeInt(0, 999999) / 1000000; $inheritTurntime += $rng->nextRangeInt(0, 999999) / 1000000;
$turntime = new \DateTimeImmutable(cutTurn($admin['turntime'], $turnterm)); $turntime = new \DateTimeImmutable(cutTurn($admin['turntime'], $admin['turnterm']));
$turntime = $turntime->add(TimeUtil::secondsToDateInterval($inheritTurntime)); $turntime = $turntime->add(TimeUtil::secondsToDateInterval($inheritTurntime));
$turntime = TimeUtil::format($turntime, true); $turntime = TimeUtil::format($turntime, true);
} else { } else {
$turntime = getRandTurn($rng, abs($admin['turnterm']), new \DateTimeImmutable($admin['turntime'])); $turntime = getRandTurn($rng, $admin['turnterm'], new \DateTimeImmutable($admin['turntime']));
} }
if ($admin['turnterm'] == -60){
$baseObj = VarTurn60::fromDatetime(new \DateTimeImmutable($admin['turntime']));
$userTurnObj = VarTurn60::fromDatetime(new \DateTimeImmutable($turntime));
if($baseObj->turnIdx != $userTurnObj->turnIdx){
$turntime = $userTurnObj->addTurn(-1)->toDateStr();
}
}
$now = TimeUtil::now(true); $now = TimeUtil::now(true);
if ($now >= $turntime) { if ($now >= $turntime) {
@@ -4,6 +4,7 @@ namespace sammo\API\InheritAction;
use sammo\Session; use sammo\Session;
use DateTimeInterface; use DateTimeInterface;
use sammo\CentennialAllStarGrowthService;
use sammo\DB; use sammo\DB;
use sammo\Enums\APIRecoveryType; use sammo\Enums\APIRecoveryType;
use sammo\Enums\RankColumn; use sammo\Enums\RankColumn;
@@ -98,6 +99,10 @@ class ResetStat extends \sammo\BaseAPI
return 'NPC는 능력치 초기화를 할 수 없습니다.'; return 'NPC는 능력치 초기화를 할 수 없습니다.';
} }
if (!CentennialAllStarGrowthService::isStatResetAllowed()) {
return '100기 올스타 장수는 능력치 초기화를 사용할 수 없습니다.';
}
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
@@ -62,7 +62,7 @@ class ResetTurnTime extends \sammo\BaseAPI
} }
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
$currTurnTime = new DateTimeImmutable($general->getTurnTime()); $currTurnTime = new DateTimeImmutable($general->getTurnTime());
+7 -3
View File
@@ -8,6 +8,11 @@ use sammo\Util;
abstract class AbsFromUserPool extends AbsGeneralPool{ abstract class AbsFromUserPool extends AbsGeneralPool{
protected static function getCandidateWeight(array $info, int $owner): int|float
{
return array_sum($info['dex'] ?? []);
}
public function occupyGeneralName(): bool public function occupyGeneralName(): bool
{ {
$generalID = $this->getGeneralBuilder()->getGeneralID(); $generalID = $this->getGeneralBuilder()->getGeneralID();
@@ -36,8 +41,7 @@ abstract class AbsFromUserPool extends AbsGeneralPool{
$pool = []; $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){ 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']); $cand['info'] = Json::decode($cand['info']);
$dexTotal = array_sum($cand['info']['dex']); $pool[] = [$cand, static::getCandidateWeight($cand['info'], $owner)];
$pool[] = [$cand, $dexTotal];
} }
if(count($pool) < $pickCnt){ if(count($pool) < $pickCnt){
@@ -46,7 +50,7 @@ abstract class AbsFromUserPool extends AbsGeneralPool{
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$result = []; $result = [];
$validUntil = TimeUtil::nowAddMinutes(2 * abs($gameStor->turnterm)); $validUntil = TimeUtil::nowAddMinutes(2 * $gameStor->turnterm);
while(count($result) < $pickCnt){ while(count($result) < $pickCnt){
$cand = $rng->choiceUsingWeightPair($pool); $cand = $rng->choiceUsingWeightPair($pool);
$poolID = $cand['id']; $poolID = $cand['id'];
+4 -4
View File
@@ -164,7 +164,7 @@ abstract class Auction
if ($date === null) { if ($date === null) {
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
$date = $this->info->closeDate->add(TimeUtil::secondsToDateInterval( $date = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID) * 60 max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID) * 60
)); ));
@@ -324,7 +324,7 @@ abstract class Auction
} }
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
if ($this->info->detail->availableLatestBidCloseDate !== null) { if ($this->info->detail->availableLatestBidCloseDate !== null) {
$extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval( $extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval(
@@ -437,7 +437,7 @@ abstract class Auction
$general->increaseVar($resType->value, -$morePoint); $general->increaseVar($resType->value, -$morePoint);
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
$extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval( $extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID) * 60 max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID) * 60
)); ));
@@ -471,7 +471,7 @@ abstract class Auction
if ($highestBid->aux->tryExtendCloseDate) { if ($highestBid->aux->tryExtendCloseDate) {
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
//연장 요청이 있었다. //연장 요청이 있었다.
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval( $extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
+1 -7
View File
@@ -58,7 +58,7 @@ abstract class AuctionBasicResource extends Auction
$now = new \DateTimeImmutable(); $now = new \DateTimeImmutable();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
$closeDate = $now->add(TimeUtil::secondsToDateInterval($closeTurnCnt * $turnTerm * 60)); $closeDate = $now->add(TimeUtil::secondsToDateInterval($closeTurnCnt * $turnTerm * 60));
$openResult = static::openAuction(new AuctionInfo( $openResult = static::openAuction(new AuctionInfo(
@@ -246,13 +246,7 @@ abstract class AuctionBasicResource extends Auction
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm'); $turnTerm = $gameStor->getValue('turnterm');
if($turnTerm == -60){
$date = VarTurn60::fromDatetime(new \DateTimeImmutable())->addTurn(1)->toDateStr();
}
else{
$date = (new DateTimeImmutable())->add(TimeUtil::secondsToDateInterval($turnTerm * 60)); $date = (new DateTimeImmutable())->add(TimeUtil::secondsToDateInterval($turnTerm * 60));
}
$this->shrinkCloseDate($date); $this->shrinkCloseDate($date);
} }
+2 -3
View File
@@ -75,7 +75,6 @@ class AuctionUniqueItem extends Auction
$now = new DateTimeImmutable(); $now = new DateTimeImmutable();
[$turnTerm, $year, $month] = $gameStor->getValuesAsArray(['turnterm', 'year', 'month']); [$turnTerm, $year, $month] = $gameStor->getValuesAsArray(['turnterm', 'year', 'month']);
$turnTerm = abs($turnTerm);
$closeDate = $now->add(TimeUtil::secondsToDateInterval( $closeDate = $now->add(TimeUtil::secondsToDateInterval(
max(static::MIN_AUCTION_CLOSE_MINUTES, $turnTerm * static::COEFF_AUCTION_CLOSE_MINUTES) * 60 max(static::MIN_AUCTION_CLOSE_MINUTES, $turnTerm * static::COEFF_AUCTION_CLOSE_MINUTES) * 60
@@ -267,7 +266,7 @@ class AuctionUniqueItem extends Auction
} }
if ($availableEquipUniqueCnt <= 0) { if ($availableEquipUniqueCnt <= 0) {
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
//제한에 걸렸다면 자동 연장 //제한에 걸렸다면 자동 연장
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval( $extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_UNIQUE_CNT) * 60 max(static::MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_UNIQUE_CNT) * 60
@@ -315,7 +314,7 @@ class AuctionUniqueItem extends Auction
if (!$availableItemTypes) { if (!$availableItemTypes) {
if ($isExtendCloseDateRequired) { if ($isExtendCloseDateRequired) {
$turnTerm = abs($gameStor->getValue('turnterm')); $turnTerm = $gameStor->getValue('turnterm');
//동일 부위 제한에 걸렸다면 자동 연장 //동일 부위 제한에 걸렸다면 자동 연장
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval( $extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_LIMIT_BY_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_BY_BID) * 60 max(static::MIN_EXTENSION_MINUTES_LIMIT_BY_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_BY_BID) * 60
@@ -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\Constraint\ConstraintHelper;
use sammo\StaticEventHandler; use sammo\StaticEventHandler;
use sammo\CentennialAllStarGrowthService;
class che_숙련전환 extends Command\GeneralCommand class che_숙련전환 extends Command\GeneralCommand
{ {
@@ -157,6 +158,7 @@ class che_숙련전환 extends Command\GeneralCommand
$logger = $general->getLogger(); $logger = $general->getLogger();
$srcDex = $general->getVar('dex' . $this->srcArmType); $srcDex = $general->getVar('dex' . $this->srcArmType);
$destDex = $general->getVar('dex' . $this->destArmType);
$cutDex = Util::toInt($srcDex * static::$decreaseCoeff); $cutDex = Util::toInt($srcDex * static::$decreaseCoeff);
$cutDexText = number_format($cutDex); $cutDexText = number_format($cutDex);
$addDex = Util::toInt($cutDex * static::$convertCoeff); $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->srcArmType, -$cutDex);
$general->increaseVar('dex' . $this->destArmType, $addDex); $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, '을'); $josaUl = JosaUtil::pick($cutDex, '을');
$josaRo = JosaUtil::pick($addDex, '로'); $josaRo = JosaUtil::pick($addDex, '로');
@@ -7,6 +7,7 @@ use \sammo\Util;
use \sammo\JosaUtil; use \sammo\JosaUtil;
use \sammo\General; use \sammo\General;
use \sammo\ActionLogger; use \sammo\ActionLogger;
use \sammo\CentennialAllStarGrowthService;
use \sammo\GameConst; use \sammo\GameConst;
use \sammo\LastTurn; use \sammo\LastTurn;
use \sammo\GameUnitConst; use \sammo\GameUnitConst;
@@ -190,6 +191,12 @@ class che_인재탐색 extends Command\GeneralCommand
$newNPC->fillRemainSpecAsRandom($pickTypeList, $avgGen, $env); $newNPC->fillRemainSpecAsRandom($pickTypeList, $avgGen, $env);
$newNPC->build($this->env); $newNPC->build($this->env);
CentennialAllStarGrowthService::applyCurrentTargetToBuiltNPC(
$db,
$newNPC,
$pickedNPC->getInfo(),
$this->env
);
$pickedNPC->occupyGeneralName(); $pickedNPC->occupyGeneralName();
$npcName = $newNPC->getGeneralName(); $npcName = $newNPC->getGeneralName();
$josaRa = JosaUtil::pick($npcName, '라'); $josaRa = JosaUtil::pick($npcName, '라');
@@ -200,7 +200,7 @@ class che_불가침제의 extends Command\NationCommand
$now = new \DateTime($date); $now = new \DateTime($date);
$validUntil = new \DateTime($date); $validUntil = new \DateTime($date);
$validMinutes = max(30, abs($env['turnterm']) * 3); $validMinutes = max(30, $env['turnterm'] * 3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M")); $validUntil->add(new \DateInterval("PT{$validMinutes}M"));
$josaWa = JosaUtil::pick($nationName, '와'); $josaWa = JosaUtil::pick($nationName, '와');
@@ -149,7 +149,7 @@ class che_불가침파기제의 extends Command\NationCommand{
$now = new \DateTime($date); $now = new \DateTime($date);
$validUntil = new \DateTime($date); $validUntil = new \DateTime($date);
$validMinutes = max(30, abs($env['turnterm'])*3); $validMinutes = max(30, $env['turnterm']*3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M")); $validUntil->add(new \DateInterval("PT{$validMinutes}M"));
$msg = new DiplomaticMessage( $msg = new DiplomaticMessage(
@@ -7,6 +7,7 @@ use \sammo\Util;
use \sammo\JosaUtil; use \sammo\JosaUtil;
use \sammo\General; use \sammo\General;
use \sammo\ActionLogger; use \sammo\ActionLogger;
use \sammo\CentennialAllStarGrowthService;
use \sammo\GameConst; use \sammo\GameConst;
use \sammo\LastTurn; use \sammo\LastTurn;
use \sammo\GameUnitConst; use \sammo\GameUnitConst;
@@ -160,6 +161,12 @@ class che_의병모집 extends Command\NationCommand
$newNPC->fillRemainSpecAsRandom($pickTypeList, $avgGen, $env); $newNPC->fillRemainSpecAsRandom($pickTypeList, $avgGen, $env);
$newNPC->build($this->env); $newNPC->build($this->env);
CentennialAllStarGrowthService::applyCurrentTargetToBuiltNPC(
$db,
$newNPC,
$pickedNPC->getInfo(),
$this->env
);
$pickedNPC->occupyGeneralName(); $pickedNPC->occupyGeneralName();
} }
@@ -147,7 +147,7 @@ class che_종전제의 extends Command\NationCommand{
$now = new \DateTime($date); $now = new \DateTime($date);
$validUntil = new \DateTime($date); $validUntil = new \DateTime($date);
$validMinutes = max(30, abs($env['turnterm'])*3); $validMinutes = max(30, $env['turnterm']*3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M")); $validUntil->add(new \DateInterval("PT{$validMinutes}M"));
$msg = new DiplomaticMessage( $msg = new DiplomaticMessage(
@@ -1,204 +0,0 @@
<?php
namespace sammo\Command\Nation;
use \sammo\DB;
use \sammo\Util;
use \sammo\JosaUtil;
use \sammo\General;
use \sammo\DummyGeneral;
use \sammo\ActionLogger;
use \sammo\GameConst;
use \sammo\LastTurn;
use \sammo\GameUnitConst;
use \sammo\Command;
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Enums\GeneralQueryMode;
use sammo\StaticEventHandler;
use function sammo\pullGeneralCommand;
use function sammo\pushGeneralCommand;
class che_행동지시 extends Command\NationCommand
{
static protected $actionName = '행동 지시';
static public $reqArg = true;
protected function argTest(): bool
{
if ($this->arg === null) {
return false;
}
if (!key_exists('isPull', $this->arg)) {
return false;
}
if (!key_exists('amount', $this->arg)) {
return false;
}
if (!key_exists('destGeneralID', $this->arg)) {
return false;
}
$isPull = $this->arg['isPull'];
$amount = $this->arg['amount'];
$destGeneralID = $this->arg['destGeneralID'];
if (!is_numeric($amount)) {
return false;
}
if ($amount <= 0) {
return false;
}
if (!is_bool($isPull)) {
return false;
}
if (!is_int($destGeneralID)) {
return false;
}
if ($destGeneralID <= 0) {
return false;
}
$amount = Util::clamp($amount, 1, 5);
$this->arg = [
'isPull' => $isPull,
'amount' => $amount,
'destGeneralID' => $destGeneralID
];
return true;
}
protected function init()
{
$general = $this->generalObj;
$this->setCity();
$this->setNation();
$this->minConditionConstraints = [
ConstraintHelper::NotBeNeutral(),
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::SuppliedCity(),
];
}
protected function initWithArg()
{
$destGeneral = General::createObjFromDB($this->arg['destGeneralID']);
$this->setDestGeneral($destGeneral);
if($this->arg['destGeneralID'] == $this->getGeneral()->getID()){
$this->fullConditionConstraints=[
ConstraintHelper::AlwaysFail('본인입니다')
];
return;
}
$this->fullConditionConstraints = [
ConstraintHelper::NotBeNeutral(),
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::SuppliedCity(),
ConstraintHelper::ExistsDestGeneral(),
ConstraintHelper::FriendlyDestGeneral()
];
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 0;
}
public function getPostReqTurn(): int
{
return 0;
}
public function getBrief(): string
{
$isPull = $this->arg['isPull'];
$amount = $this->arg['amount'];
$actSpecificName = $isPull ? '당기기' : '미루기';
$destGeneral = $this->destGeneralObj;
return "{$destGeneral->getName()}{$amount}{$actSpecificName}";
}
public function run(\Sammo\RandUtil $rng): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$general = $this->generalObj;
$date = $general->getTurnTime($general::TURNTIME_HM);
$isPull = $this->arg['isPull'];
$amount = $this->arg['amount'];
$destGeneral = $this->destGeneralObj;
if($isPull){
pullGeneralCommand($destGeneral->getID(), $amount);
}
else{
pushGeneralCommand($destGeneral->getID(), $amount);
}
$logger = $general->getLogger();
$actDestText = $isPull ? '당겼습니다.' : '미루었습니다.';
$actText = $isPull ? '당기도록' : '미루도록';
$destGeneral->getLogger()->pushGeneralActionLog("<Y>{$general->getName()}</>의 지시로 <C>{$amount}</>턴을 {$actDestText}", ActionLogger::PLAIN);
$logger->pushGeneralActionLog("<Y>{$destGeneral->getName()}</>에게 <C>{$amount}</>턴을 {$actText} 지시했습니다. <1>$date</>");
$this->setResultTurn(new LastTurn(static::getName(), $this->arg));
StaticEventHandler::handleEvent($this->generalObj, $this->destGeneralObj, $this::class, $this->env, $this->arg ?? []);
$general->applyDB($db);
$destGeneral->applyDB($db);
return true;
}
public function exportJSVars(): array
{
$db = DB::db();
$nationID = $this->getNationID();
$troops = Util::convertArrayToDict($db->query('SELECT * FROM troop WHERE nation=%i', $nationID), 'troop_leader');
$destRawGenerals = Util::convertArrayToDict($db->queryAllLists('SELECT no,name,officer_level,npc,gold,rice,leadership,strength,intel,city,crew,train,atmos,troop FROM general WHERE nation = %i ORDER BY npc,binary(name)', $nationID), 0);
if($destRawGenerals){
foreach ($db->queryAllLists(
'SELECT general_id, brief FROM general_turn WHERE general_id IN %li AND turn_idx = 0',
array_keys($destRawGenerals)
) as [$generalID, $brief]) {
if (!key_exists($generalID, $destRawGenerals)) {
continue;
}
$destRawGenerals[$generalID][] = $brief;
}
}
return [
'procRes' => [
'troops' => $troops,
'generals' => array_values($destRawGenerals),
'generalsKey' => ['no', 'name', 'officerLevel', 'npc', 'gold', 'rice', 'leadership', 'strength', 'intel', 'cityID', 'crew', 'train', 'atmos', 'troopID', 'turn0Brief'],
'cities' => \sammo\JSOptionsForCities(),
'amountGuide' => [1, 2, 3, 4, 5],
'minAmount' => 1,
'maxAmount' => 5,
]
];
}
}
@@ -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];
}
}
+9 -1
View File
@@ -5,6 +5,7 @@ namespace sammo\Event\Action;
use \sammo\GameConst; use \sammo\GameConst;
use \sammo\Util; use \sammo\Util;
use \sammo\DB; use \sammo\DB;
use sammo\CentennialAllStarGrowthService;
use sammo\LiteHashDRBG; use sammo\LiteHashDRBG;
use sammo\RandUtil; use sammo\RandUtil;
use sammo\UniqueConst; use sammo\UniqueConst;
@@ -35,7 +36,8 @@ class CreateManyNPC extends \sammo\Event\Action
))); )));
$result = []; $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); $age = $rng->nextRangeInt(20, 25);
$birthYear = $env['year'] - $age; $birthYear = $env['year'] - $age;
$deathYear = $env['year'] + $rng->nextRangeInt(10, 50); $deathYear = $env['year'] + $rng->nextRangeInt(10, 50);
@@ -50,6 +52,12 @@ class CreateManyNPC extends \sammo\Event\Action
} }
$newNPC->fillRemainSpecAsZero($env); $newNPC->fillRemainSpecAsZero($env);
$newNPC->build($env); $newNPC->build($env);
CentennialAllStarGrowthService::applyCurrentTargetToBuiltNPC(
$db,
$newNPC,
$pickedNPC->getInfo(),
$env
);
$pickedNPC->occupyGeneralName(); $pickedNPC->occupyGeneralName();
$result[] = [ $result[] = [
$newNPC->getGeneralName(), $newNPC->getGeneralID() $newNPC->getGeneralName(), $newNPC->getGeneralID()
+1 -1
View File
@@ -120,7 +120,7 @@ class RaiseInvader extends \sammo\Event\Action
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->setValue('isunited', 1); $gameStor->setValue('isunited', 1);
$turnterm = abs($gameStor->turnterm); $turnterm = $gameStor->turnterm;
$generalCnt = $db->queryFirstField('SELECT count(*) FROM general'); $generalCnt = $db->queryFirstField('SELECT count(*) FROM general');
if ($npcEachCount < 0) { if ($npcEachCount < 0) {
+1 -1
View File
@@ -134,7 +134,7 @@ class UpdateNationLevel extends \sammo\Event\Action
if ($levelDiff) { if ($levelDiff) {
//유니크 아이템 하나 돌리자 //유니크 아이템 하나 돌리자
$targetKillTurn = $env['killturn']; $targetKillTurn = $env['killturn'];
$targetKillTurn -= 24 * 60 / abs($env['turnterm']); $targetKillTurn -= 24 * 60 / $env['turnterm'];
$nationGenIDList = $db->queryFirstColumn( $nationGenIDList = $db->queryFirstColumn(
'SELECT no FROM general WHERE nation = %i AND killturn >= %i AND npc < 2', 'SELECT no FROM general WHERE nation = %i AND killturn >= %i AND npc < 2',
$nation['nation'], $nation['nation'],
+6 -1
View File
@@ -184,6 +184,10 @@ class GameConstBase
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 내정 특기 */ /** @var array 선택할 수 없으나 게임 내에 유효한 장수 내정 특기 */
public static $optionalSpecialDomestic = [ public static $optionalSpecialDomestic = [
'None', '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 기본 전투 특기 */ /** @var string 기본 전투 특기 */
@@ -384,7 +388,6 @@ class GameConstBase
'che_포상', 'che_포상',
'che_몰수', 'che_몰수',
'che_부대탈퇴지시', 'che_부대탈퇴지시',
'che_행동지시',
], ],
'외교' => [ '외교' => [
'che_물자원조', 'che_물자원조',
@@ -417,6 +420,8 @@ class GameConstBase
public static $retirementYear = 80; public static $retirementYear = 80;
public static $targetGeneralPool = 'RandomNameGeneral'; public static $targetGeneralPool = 'RandomNameGeneral';
/** @var float 100기 올스타 NPC의 원본 목표 대비 최종 숙련 비율 */
public static $centennialNpcDexTargetRatio = 0.4;
public static $generalPoolAllowOption = ['stat', 'ego', 'picture']; public static $generalPoolAllowOption = ['stat', 'ego', 'picture'];
public static $randGenFirstName = [ public static $randGenFirstName = [
-7
View File
@@ -283,7 +283,6 @@ class General extends GeneralBase implements iAction
} }
$recwar = new \DateTimeImmutable($this->getVar('recent_war')); $recwar = new \DateTimeImmutable($this->getVar('recent_war'));
$turnNow = new \DateTimeImmutable($this->getVar('turntime')); $turnNow = new \DateTimeImmutable($this->getVar('turntime'));
$secDiff = TimeUtil::DateIntervalToSeconds($recwar->diff($turnNow)); $secDiff = TimeUtil::DateIntervalToSeconds($recwar->diff($turnNow));
if ($secDiff <= 0) { if ($secDiff <= 0) {
@@ -291,12 +290,6 @@ class General extends GeneralBase implements iAction
return 0; return 0;
} }
if($turnTerm == -60){
$turnDiff = VarTurn60::calcTurnDiff($recwar, $turnNow);
$this->calcCache[$cacheKey] = $turnDiff;
return $turnDiff;
}
$result = intdiv(Util::toInt($secDiff), 60 * $turnTerm); $result = intdiv(Util::toInt($secDiff), 60 * $turnTerm);
$this->calcCache[$cacheKey] = $result; $this->calcCache[$cacheKey] = $result;
return $result; return $result;
+4 -4
View File
@@ -1980,7 +1980,7 @@ class GeneralAI
$db = DB::db(); $db = DB::db();
$nationStor = KVStorage::getStorage($db, $general->getNationID(), 'nation_env'); $nationStor = KVStorage::getStorage($db, $general->getNationID(), 'nation_env');
$turnTerm = abs($this->env['turnterm']); $turnTerm = $this->env['turnterm'];
//천도를 한턴 넣었다면 계속 넣는다. //천도를 한턴 넣었다면 계속 넣는다.
if ($lastTurn->getCommand() === '천도' && $lastTurn->getArg()['destCityID'] != $this->nation['capital']) { if ($lastTurn->getCommand() === '천도' && $lastTurn->getArg()['destCityID'] != $this->nation['capital']) {
@@ -3134,7 +3134,7 @@ class GeneralAI
$rawCity = $db->queryFirstRow('SELECT * FROM city WHERE city = %i', $this->general->getCityID()); $rawCity = $db->queryFirstRow('SELECT * FROM city WHERE city = %i', $this->general->getCityID());
$this->general->setRawCity($rawCity); $this->general->setRawCity($rawCity);
} }
if (!in_array($this->general->getRawCity()['level'], [5, 6])) { if (in_array($this->general->getRawCity()['level'], [5, 6])) {
return null; return null;
} }
} }
@@ -3715,7 +3715,7 @@ class GeneralAI
$this->updateInstance(); $this->updateInstance();
//특별 메세지 있는 경우 출력 //특별 메세지 있는 경우 출력
$term = abs($this->env['turnterm']); $term = $this->env['turnterm'];
if ($general->getVar('npcmsg') && $this->rng->nextBool(GameConst::$npcMessageFreqByDay * $term / (60 * 24))) { if ($general->getVar('npcmsg') && $this->rng->nextBool(GameConst::$npcMessageFreqByDay * $term / (60 * 24))) {
$src = new MessageTarget( $src = new MessageTarget(
$general->getID(), $general->getID(),
@@ -3985,7 +3985,7 @@ class GeneralAI
$userChiefCnt = 0; $userChiefCnt = 0;
$minUserKillturn = $this->env['killturn'] - Util::toInt(240 / abs($this->env['turnterm'])); $minUserKillturn = $this->env['killturn'] - Util::toInt(240 / $this->env['turnterm']);
$minNPCKillturn = 36; $minNPCKillturn = 36;
foreach (Util::range($minChiefLevel, 12) as $chiefLevel) { foreach (Util::range($minChiefLevel, 12) as $chiefLevel) {
File diff suppressed because it is too large Load Diff
+90
View File
@@ -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);
}
}
+2 -11
View File
@@ -245,16 +245,7 @@ class ResetHelper{
true true
); );
if($turnterm == -60){ if($sync == 0) {
[$starttime, $yearPulled, $month] = VarTurn60::fromDatetime(new \DateTimeImmutable($turntime))->cutDay();
if($yearPulled){
$year = $startyear-1;
}
else{
$year = $startyear;
}
}
else if($sync == 0) {
// 현재 시간을 1월로 맞춤 // 현재 시간을 1월로 맞춤
$starttime = cutTurn($turntime, $turnterm); $starttime = cutTurn($turntime, $turnterm);
$month = 1; $month = 1;
@@ -270,7 +261,7 @@ class ResetHelper{
} }
} }
$killturn = 4800 / abs($turnterm); $killturn = 4800 / $turnterm;
if($npcmode == 1) { $killturn = intdiv($killturn, 3); } if($npcmode == 1) { $killturn = intdiv($killturn, 3); }
$develcost = ($year - $startyear + 10) * 2; $develcost = ($year - $startyear + 10) * 2;
+9 -11
View File
@@ -20,17 +20,6 @@ final class ServerTool
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getValues(['turntime', 'turnterm', 'year', 'startyear', 'month', 'isunited']); $admin = $gameStor->getValues(['turntime', 'turnterm', 'year', 'startyear', 'month', 'isunited']);
$oldunit = $admin['turnterm'] * 60;
$unit = $turnterm * 60;
if($unit == $oldunit){
return null;
}
if($oldunit < 0 || $unit < 0){
return 'variable_turnterm';
}
$reqGameLock = $admin['isunited'] != 2 && !$ignoreLock; $reqGameLock = $admin['isunited'] != 2 && !$ignoreLock;
$locked = false; $locked = false;
@@ -51,6 +40,15 @@ final class ServerTool
$locked = tryLock(); $locked = tryLock();
} }
$oldunit = $admin['turnterm'] * 60;
$unit = $turnterm * 60;
if($unit == $oldunit){
if($locked){
unlock();
}
return null;
}
$unitDiff = $unit / $oldunit; $unitDiff = $unit / $oldunit;
+1 -10
View File
@@ -219,21 +219,12 @@ class TurnExecutionHelper
$nextTurnTimeBase = $general->getAuxVar('nextTurnTimeBase'); $nextTurnTimeBase = $general->getAuxVar('nextTurnTimeBase');
if($nextTurnTimeBase !== null){ if($nextTurnTimeBase !== null){
if($gameStor->turnterm == -60){
[$turntime, $nextTurnterm] = VarTurn60::fromDatetime(new \DateTimeImmutable($turntime))->cutTurn();
$turntimeObj = new \DateTimeImmutable($turntime);
$turntimeObj = $turntimeObj->add(TimeUtil::secondsToDateInterval($nextTurnTimeBase * $nextTurnterm / 60));
$turntime = TimeUtil::format($turntimeObj, true);
$general->setAuxVar('nextTurnTimeBase', null);
}
else {
$turntime = cutTurn($turntime, $gameStor->turnterm); $turntime = cutTurn($turntime, $gameStor->turnterm);
$turntimeObj = new \DateTimeImmutable($turntime); $turntimeObj = new \DateTimeImmutable($turntime);
$turntimeObj = $turntimeObj->add(TimeUtil::secondsToDateInterval($nextTurnTimeBase)); $turntimeObj = $turntimeObj->add(TimeUtil::secondsToDateInterval($nextTurnTimeBase));
$turntime = TimeUtil::format($turntimeObj, true); $turntime = TimeUtil::format($turntimeObj, true);
$general->setAuxVar('nextTurnTimeBase', null); $general->setAuxVar('nextTurnTimeBase', null);
} }
}
$general->setVar('turntime', $turntime); $general->setVar('turntime', $turntime);
} }
@@ -364,7 +355,7 @@ class TurnExecutionHelper
if (($autorun_user['limit_minutes'] ?? false) && $general->getNPCType() < 2 && $hasReservedTurn) { if (($autorun_user['limit_minutes'] ?? false) && $general->getNPCType() < 2 && $hasReservedTurn) {
$autorun_limit = Util::joinYearMonth($year, $month); $autorun_limit = Util::joinYearMonth($year, $month);
$autorun_limit += intdiv($autorun_user['limit_minutes'], abs($turnterm)); $autorun_limit += intdiv($autorun_user['limit_minutes'], $turnterm);
$general->setAuxVar('autorun_limit', $autorun_limit); $general->setAuxVar('autorun_limit', $autorun_limit);
} }
-191
View File
@@ -1,191 +0,0 @@
<?php
namespace sammo;
class VarTurn60
{
const MonthAdjustOffset = 2;
static array $min30ToTurn = [
[0, 0, 120], //00:00 2
[0, 30, 120], //00:30
[0, 60, 120], //01:00
[0, 90, 120], //01:30
[1, 0, 120], //02:00 3
[1, 30, 120], //02:30
[1, 60, 120], //03:00
[1, 90, 120], //03:30
[2, 0, 120], //04:00 4
[2, 30, 120], //04:30
[2, 60, 120], //05:00
[2, 90, 120], //05:30
[3, 0, 60], //06:00 5
[3, 30, 60], //06:30
[4, 0, 60], //07:00 6
[4, 30, 60], //07:30
[5, 0, 60], //08:00 7
[5, 30, 60], //08:30
[6, 0, 60], //09:00 8
[6, 30, 60], //09:30
[7, 0, 60], //10:00 9
[7, 30, 60], //10:30
[8, 0, 60], //11:00 10
[8, 30, 60], //11:30
[9, 0, 60], //12:00 11
[9, 30, 60], //12:30
[10, 0, 60], //13:00 0(12)
[10, 30, 60], //13:30
[11, 0, 60], //14:00 1(13)
[11, 30, 60], //14:30
[12, 0, 60], //15:00 2(14)
[12, 30, 60], //15:30
[13, 0, 60], //16:00 3(15)
[13, 30, 60], //16:30
[14, 0, 60], //17:00 4(16)
[14, 30, 60], //17:30
[15, 0, 60], //18:00 5(17)
[15, 30, 60], //18:30
[16, 0, 30], //19:00 6(18)
[17, 0, 30], //19:30 7(19)
[18, 0, 30], //20:00 8(20)
[19, 0, 30], //20:30 9(21)
[20, 0, 30], //21:00 10(22)
[21, 0, 30], //21:30 11(23)
[22, 0, 60], //22:00 0
[22, 30, 60], //22:30
[23, 0, 60], //23:00 1
[23, 30, 60], //23:30
//[24, 0, 60], //24:00 2
];
static array $turnToHM = [
[0, 0, 120], //0
[2, 0, 120], //1
[4, 0, 120], //2
[6, 0, 60], //3
[7, 0, 60], //4
[8, 0, 60], //5
[9, 0, 60], //6
[10, 0, 60], //7
[11, 0, 60], //8
[12, 0, 60], //9
[13, 0, 60], //10
[14, 0, 60], //11
[15, 0, 60], //12
[16, 0, 60], //13
[17, 0, 60], //14
[18, 0, 60], //15
[19, 0, 30], //16
[19, 30, 30],//17
[20, 0, 30], //18
[20, 30, 30],//19
[21, 0, 30], //20
[21, 30, 30],//21
[22, 0, 60], //22
[23, 0, 60], //23
//[24, 0, 60], //24(?)
];
function __construct(
public \DateTimeImmutable $baseDay,
public int $turnIdx, //0~23
public float $secOffset, ///turnTerm에 따라 최대치가 30*60, 60*60, 120*60 가변
)
{
}
static function fromDatetime(\DateTimeInterface $date): self {
$baseDay = new \DateTimeImmutable($date->format('Y-m-d'));
$totalSec = $date->getTimestamp() - $baseDay->getTimestamp();
$min30 = intdiv($totalSec, 60 * 30);
assert($min30 < 48);
[$turnIdx, $minOffset, ] = static::$min30ToTurn[$min30];
$secOffset = $totalSec - 60 * 30 * $min30 + $minOffset * 60;
return new static($baseDay, $turnIdx, $secOffset);
}
/// $b - $a 의 턴차
static function calcTurnDiff(\DateTimeInterface $a, \DateTimeInterface $b): int{
$aObj = static::fromDatetime($a);
$bObj = static::fromDatetime($b);
$resDays = $aObj->baseDay->diff($bObj->baseDay)->days; //놀랍게도 절대값
if($aObj->baseDay > $bObj->baseDay){
$resDays *= -1;
}
$res = $resDays * 24 + $bObj->turnIdx - $aObj->turnIdx;
return $res;
}
function cutTurn($withFraction = true): array{
[$hour, $minOffset, $turnTerm] = static::$turnToHM[$this->turnIdx];
$date = $this->baseDay->add(TimeUtil::secondsToDateInterval(($hour * 60 + $minOffset) * 60));
return [TimeUtil::format($date, $withFraction), $turnTerm];
}
function toDateStr($withFraction = true): string{
[$hour, $minOffset, ] = static::$turnToHM[$this->turnIdx];
$date = $this->baseDay->add(TimeUtil::secondsToDateInterval(($hour * 60 + $minOffset) * 60 + $this->secOffset));
return TimeUtil::format($date, $withFraction);
}
function cutDay($withFraction = true): array{
//고정 시간 기준 cutDay()의 이식
//상수 테이블이 이미 13:00에 1월이 되도록 맞춰져 있음.
//다만 20:00인 경우 8월이 아니라 9월이 됨 ^^;
$newMonth = ($this->turnIdx + static::MonthAdjustOffset) % 12 + 1;
$yearPulled = $newMonth > 3;
$obj = $yearPulled ? $this->addTurn(12): $this;
[$date, ] = $obj->addTurn(-($newMonth - 1))->cutTurn($withFraction);
return [$date, $yearPulled, $newMonth];
}
function addTurn(int $moreTurn): self{
$dayDiff = intdiv($moreTurn, 24);
$moreTurn %= 24;
$nextTurnIdx = $this->turnIdx + $moreTurn;
if($nextTurnIdx < 0){
$dayDiff -= 1;
$nextTurnIdx += 24;
}
else if($nextTurnIdx >= 24){
$dayDiff += 1;
$nextTurnIdx -= 24;
}
[, , $oldTurnTerm] = static::$turnToHM[$this->turnIdx];
[, , $nextTurnTerm] = static::$turnToHM[$nextTurnIdx];
$nextSecOffset = $this->secOffset;
if($oldTurnTerm != $nextTurnTerm){
$nextSecOffset *= $nextTurnTerm;
$nextSecOffset /= $oldTurnTerm;
}
if($dayDiff == 0){
return new static($this->baseDay, $nextTurnIdx, $nextSecOffset);
}
if($dayDiff > 0){
$nextBaseDay = $this->baseDay->add(new \DateInterval("P{$dayDiff}D"));
}
else{
$dayAbsDiff = abs($dayDiff);
$nextBaseDay = $this->baseDay->sub(new \DateInterval("P{$dayAbsDiff}D"));
}
return new static($nextBaseDay, $nextTurnIdx, $nextSecOffset);
}
}
-7
View File
@@ -81,13 +81,6 @@
["RaiseNPCNation"], ["RaiseNPCNation"],
["DeleteEvent"] ["DeleteEvent"]
], ],
[
"month", 1000,
true,
["ChangeCity", "all", {
"trade":100
}]
],
[ [
"month", 999, "month", 999,
["Date", "==", 181, 1], ["Date", "==", 181, 1],
+92
View File
@@ -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
}]
]
]
}
+71
View File
@@ -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"]
]
]
}
+59 -2
View File
@@ -19,8 +19,16 @@ if ($admin['npcmode'] != 2) {
$member = RootDB::db()->queryFirstRow("SELECT no,name,picture,imgsvr,grade from member where no= %i", $userID); $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'); $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'); $nationList = $db->query('SELECT nation,`name`,color,scout FROM nation');
shuffle($nationList); shuffle($nationList);
@@ -54,6 +62,7 @@ foreach (getCharacterList(false) as $id => [$name, $info]) {
<script> <script>
var hasGeneralID = <?= $generalID === null ? 'false' : 'true' ?>; var hasGeneralID = <?= $generalID === null ? 'false' : 'true' ?>;
var isCentennialAllStar = <?= $isCentennialAllStar ? 'true' : 'false' ?>;
var defaultStatTotal = <?= GameConst::$defaultStatTotal ?>; var defaultStatTotal = <?= GameConst::$defaultStatTotal ?>;
var defaultStatMin = <?= GameConst::$defaultStatMin ?>; var defaultStatMin = <?= GameConst::$defaultStatMin ?>;
var defaultStatMax = <?= GameConst::$defaultStatMax ?>; 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> <small id="valid_until">(<span id="valid_until_text"></span>까지 유효)</small><small id="outdate_token">- 만료 -</small><br>
<form class="card_holder"> <form class="card_holder">
</form> </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>
</div> </div>
@@ -117,7 +147,28 @@ if ($gencount >= $admin['maxgeneral']) {
<form id='custom_form'> <form id='custom_form'>
<table class='tb_layout' style='width:100%;text-align:left;'> <table class='tb_layout' style='width:100%;text-align:left;'>
<?php <?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']); $imageTemp = GetImageURL($member['imgsvr']);
echo " echo "
<tr class='custom_picture'> <tr class='custom_picture'>
@@ -144,6 +195,7 @@ if ($gencount >= $admin['maxgeneral']) {
</select> <span id="charInfoText"></span> </select> <span id="charInfoText"></span>
</td> </td>
</tr> </tr>
<?php if (!$isCentennialAllStar) : ?>
<tr class='custom_stat'> <tr class='custom_stat'>
<td align=right class='bg1'>통솔</td> <td align=right class='bg1'>통솔</td>
<td colspan=2><input type="number" name="leadership" id="leadership" value="50"></td> <td colspan=2><input type="number" name="leadership" id="leadership" value="50"></td>
@@ -171,9 +223,14 @@ if ($gencount >= $admin['maxgeneral']) {
그 외의 능력치는 가입되지 않습니다.</font> 그 외의 능력치는 가입되지 않습니다.</font>
</td> </td>
</tr> </tr>
<?php endif; ?>
<tr> <tr>
<td align=center colspan=3> <td align=center colspan=3>
<?php if ($isCentennialAllStar) : ?>
선택한 장수의 최종 능력치 비율을 반영한 약화 능력치로 시작합니다.<br>
<?php else : ?>
<span class='custom_stat'>능력치의 총합은 <?= GameConst::$defaultStatTotal ?>입니다. 가입후 0~10의 능력치 보너스를 받게 됩니다.<br></span> <span class='custom_stat'>능력치의 총합은 <?= GameConst::$defaultStatTotal ?>입니다. 가입후 0~10의 능력치 보너스를 받게 됩니다.<br></span>
<?php endif; ?>
임의의 도시에서 재야로 시작하며 건국과 임관은 게임 내에서 실행합니다. 임의의 도시에서 재야로 시작하며 건국과 임관은 게임 내에서 실행합니다.
</td> </td>
</tr> </tr>
+1 -13
View File
@@ -68,7 +68,7 @@ import { formatTime } from "@/util/formatTime";
import { mb_strwidth } from "@/util/mb_strwidth"; import { mb_strwidth } from "@/util/mb_strwidth";
import { parseTime } from "@/util/parseTime"; import { parseTime } from "@/util/parseTime";
import type { StoredActionsHelper } from "@/util/StoredActionsHelper"; import type { StoredActionsHelper } from "@/util/StoredActionsHelper";
import { addMinutes } from "date-fns/addMinutes"; import addMinutes from "date-fns/esm/addMinutes/index";
import { range } from "lodash-es"; import { range } from "lodash-es";
import { inject, onMounted, ref, type PropType } from "vue"; import { inject, onMounted, ref, type PropType } from "vue";
import VueTypes from "vue-types"; import VueTypes from "vue-types";
@@ -76,7 +76,6 @@ import DragSelect from "@/components/DragSelect.vue";
import { BButton } from "bootstrap-vue-next"; import { BButton } from "bootstrap-vue-next";
import { QueryActionHelper } from "@/util/QueryActionHelper"; import { QueryActionHelper } from "@/util/QueryActionHelper";
import type { ChiefResponse } from "@/defs/API/NationCommand"; import type { ChiefResponse } from "@/defs/API/NationCommand";
import { VarTurn60 } from "@/varTurn60";
const props = defineProps({ const props = defineProps({
style: VueTypes.object.isRequired, style: VueTypes.object.isRequired,
@@ -199,21 +198,10 @@ if (!props.officer || !props.officer.turnTime) {
} }
} else { } else {
const baseTurnTime = parseTime(props.officer.turnTime); const baseTurnTime = parseTime(props.officer.turnTime);
if(props.turnTerm == -60){
const baseTurnTimeObj = VarTurn60.fromDatetime(baseTurnTime);
for (const idx of range(props.officer.turn.length)) {
turnTimes.value.push(
formatTime(baseTurnTimeObj.addTurn(idx).toDate(), "HH:mm")
);
}
}
else{
for (const idx of range(props.officer.turn.length)) { for (const idx of range(props.officer.turn.length)) {
turnTimes.value.push( turnTimes.value.push(
formatTime(addMinutes(baseTurnTime, idx * props.turnTerm), props.turnTerm >= 5 ? "HH:mm" : "mm:ss") formatTime(addMinutes(baseTurnTime, idx * props.turnTerm), props.turnTerm >= 5 ? "HH:mm" : "mm:ss")
); );
} }
}
} }
</script> </script>
+17 -3
View File
@@ -172,7 +172,7 @@
<BButton class="col-6 offset-6" variant="primary" @click="checkOwner"> 소유자 찾기 </BButton> <BButton class="col-6 offset-6" variant="primary" @click="checkOwner"> 소유자 찾기 </BButton>
</div> </div>
</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="row px-4">
<div class="a-right col-6 align-self-center">능력치 초기화</div> <div class="a-right col-6 align-self-center">능력치 초기화</div>
<div class="col-6"> <div class="col-6">
@@ -222,6 +222,17 @@
<BButton class="col-6 offset-6" variant="primary" @click="resetStat"> 능력치 초기화</BButton> <BButton class="col-6 offset-6" variant="primary" @click="resetStat"> 능력치 초기화</BButton>
</div> </div>
</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>
<div class="row"> <div class="row">
<div class="col"> <div class="col">
@@ -297,6 +308,7 @@ declare const staticValues: {
} }
>; >;
availableTargetGeneral: Record<number, string>; availableTargetGeneral: Record<number, string>;
canResetStat: boolean;
currentStat: { currentStat: {
leadership: number; leadership: number;
strength: number; strength: number;
@@ -310,13 +322,14 @@ declare const staticValues: {
import { reactive, ref, watch } from "vue"; import { reactive, ref, watch } from "vue";
import "@scss/game_bg.scss"; import "@scss/game_bg.scss";
import TopBackBar from "@/components/TopBackBar.vue"; import TopBackBar from "@/components/TopBackBar.vue";
import { sum } from "lodash-es"; import _ from "lodash-es";
import NumberInputWithInfo from "@/components/NumberInputWithInfo.vue"; import NumberInputWithInfo from "@/components/NumberInputWithInfo.vue";
import { SammoAPI } from "./SammoAPI"; import { SammoAPI } from "./SammoAPI";
import { InheritResetStat, type inheritBuffType, type InheritPointLogItem } from "./defs/API/InheritAction"; import { InheritResetStat, type inheritBuffType, type InheritPointLogItem } from "./defs/API/InheritAction";
import * as JosaUtil from "@/util/JosaUtil"; import * as JosaUtil from "@/util/JosaUtil";
import { BButton } from "bootstrap-vue-next"; import { BButton } from "bootstrap-vue-next";
import { unwrap } from "./util/unwrap"; import { unwrap } from "./util/unwrap";
import { add as dateAdd } from 'date-fns';
const inheritanceViewText: Record<InheritanceViewType, { title: string; info: string }> = { const inheritanceViewText: Record<InheritanceViewType, { title: string; info: string }> = {
sum: { sum: {
@@ -427,7 +440,7 @@ const title = "유산 관리";
const items = ref( const items = ref(
(() => { (() => {
const totalPoint = Math.floor(sum(Object.values(staticValues.items))); const totalPoint = Math.floor(_.sum(Object.values(staticValues.items)));
const previousPoint = Math.floor(staticValues.items["previous"]); const previousPoint = Math.floor(staticValues.items["previous"]);
const newPoint = Math.floor(totalPoint - previousPoint); const newPoint = Math.floor(totalPoint - previousPoint);
const result: Record<InheritanceViewType, number> = { const result: Record<InheritanceViewType, number> = {
@@ -446,6 +459,7 @@ const {
availableSpecialWar, availableSpecialWar,
availableUnique, availableUnique,
availableTargetGeneral, availableTargetGeneral,
canResetStat,
currentStat currentStat
} = staticValues; } = staticValues;
+1 -1
View File
@@ -485,7 +485,7 @@ watch(inheritCity, (newValue: undefined | number) => {
const inheritTurnTimeZone = ref<number>(); const inheritTurnTimeZone = ref<number>();
const turnTimeZoneList: string[] = (()=>{ const turnTimeZoneList: string[] = (()=>{
const result: string[] = []; const result: string[] = [];
const zoneSec = Math.abs(turnterm); // * 60 / 60 const zoneSec = turnterm; // * 60 / 60
let zoneCur = 0; let zoneCur = 0;
for(const idx of range(60)){ for(const idx of range(60)){
const zoneNext = zoneCur + zoneSec; const zoneNext = zoneCur + zoneSec;
+1 -8
View File
@@ -276,7 +276,7 @@ declare const staticValues: {
</script> </script>
<script lang="ts" setup> <script lang="ts" setup>
import { addMinutes } from "date-fns/addMinutes"; import addMinutes from "date-fns/esm/addMinutes";
import { isString, range, trim } from "lodash-es"; import { isString, range, trim } from "lodash-es";
import queryString from "query-string"; import queryString from "query-string";
import { onMounted, ref, watch } from "vue"; import { onMounted, ref, watch } from "vue";
@@ -297,7 +297,6 @@ import { QueryActionHelper } from "./util/QueryActionHelper";
import SimpleClock from "./components/SimpleClock.vue"; import SimpleClock from "./components/SimpleClock.vue";
import type { ReservedCommandResponse } from "./defs/API/Command"; import type { ReservedCommandResponse } from "./defs/API/Command";
import { unwrap } from "./util/unwrap"; import { unwrap } from "./util/unwrap";
import { VarTurn60 } from "./varTurn60";
defineExpose({ defineExpose({
updateCommandTable, updateCommandTable,
@@ -545,15 +544,9 @@ async function reloadCommandList() {
}); });
yearMonth += 1; yearMonth += 1;
if(result.turnTerm == -60){
nextTurnTime = VarTurn60.fromDatetime(nextTurnTime).addTurn(1).toDate();
}
else{
nextTurnTime = addMinutes(nextTurnTime, result.turnTerm); nextTurnTime = addMinutes(nextTurnTime, result.turnTerm);
} }
}
serverNow.value = parseTime(result.date); serverNow.value = parseTime(result.date);
} }
+2 -2
View File
@@ -1,6 +1,6 @@
import type { AutoLoginFailed, AutoLoginNonceResponse, AutoLoginResponse, LoginFailed, LoginResponse } from "./defs/API/Login"; import type { AutoLoginFailed, AutoLoginNonceResponse, AutoLoginResponse, LoginFailed, LoginResponse } from "./defs/API/Login";
import { APIPathGen } from "./util/APIPathGen"; 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 }; export type { ValidResponse, InvalidResponse };
const apiRealPath = { const apiRealPath = {
@@ -18,7 +18,7 @@ const apiRealPath = {
hashedToken: string, hashedToken: string,
token_id: number, token_id: number,
}, AutoLoginResponse, AutoLoginFailed>, }, AutoLoginResponse, AutoLoginFailed>,
ReqNonce: GET as APICallT<undefined, AutoLoginNonceResponse, AutoLoginFailed> ReqNonce: POST as APICallT<undefined, AutoLoginNonceResponse, AutoLoginFailed>
}, },
} as const; } as const;
+2 -9
View File
@@ -256,7 +256,7 @@
</template> </template>
<script lang="ts" setup> <script lang="ts" setup>
import { addMinutes } from "date-fns/addMinutes"; import addMinutes from "date-fns/esm/addMinutes";
import queryString from "query-string"; import queryString from "query-string";
import { onMounted, ref, watch, type PropType, inject, type Ref } from "vue"; import { onMounted, ref, watch, type PropType, inject, type Ref } from "vue";
import { formatTime } from "@util/formatTime"; import { formatTime } from "@util/formatTime";
@@ -282,7 +282,6 @@ import { unwrap_err } from "@/util/unwrap_err";
import type { GameConstStore } from "@/GameConstStore"; import type { GameConstStore } from "@/GameConstStore";
import { postFilterNationCommandGen } from "@/utilGame/postFilterNationCommandGen"; import { postFilterNationCommandGen } from "@/utilGame/postFilterNationCommandGen";
import { unwrap } from "@/util/unwrap"; import { unwrap } from "@/util/unwrap";
import { VarTurn60 } from "@/varTurn60";
const toasts = unwrap(useToast()); const toasts = unwrap(useToast());
@@ -537,20 +536,14 @@ function updateCommandList() {
...obj, ...obj,
year, year,
month, month,
time: formatTime(nextTurnTime, Math.abs(props.turnTerm) >= 5 ? "HH:mm" : "mm:ss"), time: formatTime(nextTurnTime, props.turnTerm >= 5 ? "HH:mm" : "mm:ss"),
tooltip: tooltip.length == 0 ? undefined : tooltip.join("\n"), tooltip: tooltip.length == 0 ? undefined : tooltip.join("\n"),
style, style,
}); });
yearMonth += 1; yearMonth += 1;
if(props.turnTerm == -60){
nextTurnTime = VarTurn60.fromDatetime(nextTurnTime).addTurn(1).toDate();
}
else{
nextTurnTime = addMinutes(nextTurnTime, props.turnTerm); nextTurnTime = addMinutes(nextTurnTime, props.turnTerm);
} }
}
reservedCommandList.value = _reservedCommandList; reservedCommandList.value = _reservedCommandList;
updated.value = true; updated.value = true;
} }
+1 -1
View File
@@ -23,7 +23,7 @@
<AutorunInfo :autorunMode="globalInfo.autorunUser" /> <AutorunInfo :autorunMode="globalInfo.autorunUser" />
</div> </div>
<div class="s-border-t col py-2 col-8 col-lg-4 subYearMonth"> <div class="s-border-t col py-2 col-8 col-lg-4 subYearMonth">
현재: {{ globalInfo.year }} {{ globalInfo.month }} ({{ globalInfo.turnterm == -60 ? '가변 60' : globalInfo.turnterm }} 서버) 현재: {{ globalInfo.year }} {{ globalInfo.month }} ({{ globalInfo.turnterm }} 서버)
</div> </div>
<div class="s-border-t col py-2 col-4 col-lg-2 subOnlineUserCnt"> <div class="s-border-t col py-2 col-4 col-lg-2 subOnlineUserCnt">
전체 접속자 : {{ (globalInfo.onlineUserCnt ?? 0).toLocaleString() }} 전체 접속자 : {{ (globalInfo.onlineUserCnt ?? 0).toLocaleString() }}
+1 -7
View File
@@ -175,9 +175,8 @@ import { clamp } from "lodash-es";
import { formatCityName } from "@/utilGame/formatCityName"; import { formatCityName } from "@/utilGame/formatCityName";
import { isValidObjKey } from "@/utilGame/isValidObjKey"; import { isValidObjKey } from "@/utilGame/isValidObjKey";
import { calcInjury } from "@/utilGame/calcInjury"; import { calcInjury } from "@/utilGame/calcInjury";
import { addMinutes } from "date-fns/addMinutes"; import { addMinutes } from "date-fns/esm";
import type { GameIActionInfo } from "@/defs/GameObj"; import type { GameIActionInfo } from "@/defs/GameObj";
import { VarTurn60 } from "@/varTurn60";
const imagePath = window.pathConfig.gameImage; const imagePath = window.pathConfig.gameImage;
const gameConstStore = unwrap(inject<Ref<GameConstStore>>("gameConstStore")); const gameConstStore = unwrap(inject<Ref<GameConstStore>>("gameConstStore"));
const props = defineProps<{ const props = defineProps<{
@@ -279,13 +278,8 @@ watch(
() => { () => {
let turnTime = parseTime(general.value.turntime); let turnTime = parseTime(general.value.turntime);
if (turnTime.getTime() < props.lastExecuted.getTime()) { if (turnTime.getTime() < props.lastExecuted.getTime()) {
if(props.turnTerm == -60){
turnTime = VarTurn60.fromDatetime(turnTime).addTurn(1).toDate();
}
else {
turnTime = addMinutes(turnTime, props.turnTerm); turnTime = addMinutes(turnTime, props.turnTerm);
} }
}
nextExecuteMinute.value = Math.floor(clamp((turnTime.getTime() - props.lastExecuted.getTime()) / 60000, 0, 999)); nextExecuteMinute.value = Math.floor(clamp((turnTime.getTime() - props.lastExecuted.getTime()) / 60000, 0, 999));
}, },
{ immediate: true } { immediate: true }
+1 -1
View File
@@ -127,7 +127,7 @@
<script setup lang="ts"> <script setup lang="ts">
import type { MsgItem, MsgTarget, MsgType } from "@/defs/API/Message"; import type { MsgItem, MsgTarget, MsgType } from "@/defs/API/Message";
import { parseTime } from "@/util/parseTime"; import { parseTime } from "@/util/parseTime";
import { addMinutes, differenceInMilliseconds } from "date-fns"; import { differenceInMilliseconds, addMinutes } from "date-fns/esm";
import { computed, onMounted, ref, toRef, watch, type ComputedRef, type Ref } from "vue"; import { computed, onMounted, ref, toRef, watch, type ComputedRef, type Ref } from "vue";
import linkifyStr from "linkify-string"; import linkifyStr from "linkify-string";
import { SammoAPI } from "@/SammoAPI"; import { SammoAPI } from "@/SammoAPI";
+1 -1
View File
@@ -93,7 +93,7 @@ $(function () {
const runAnalysis = async function () { const runAnalysis = async function () {
let realKillturn = killturn; let realKillturn = killturn;
if(autorun_user && autorun_user.limit_minutes){ if(autorun_user && autorun_user.limit_minutes){
realKillturn -= autorun_user.limit_minutes / Math.abs(turnterm); realKillturn -= autorun_user.limit_minutes / turnterm;
} }
const $content = $('#on_mover .content'); const $content = $('#on_mover .content');
try { try {
+23 -8
View File
@@ -37,14 +37,16 @@ function regNextToken(tokenInfo: [number, string]) {
function getToken(): [number, string] | undefined { function getToken(): [number, string] | undefined {
const trialToken = localStorage.getItem(LOGIN_TOKEN_KEY); const trialToken = localStorage.getItem(LOGIN_TOKEN_KEY);
if (!trialToken) { if (!trialToken) {
console.log('no token');
return; 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) { if (tokenItems[0] != TOKEN_VERSION) {
console.log(tokenItems); console.log(tokenItems);
resetToken(); resetToken();
return; return;
} }
console.debug(localStorage.getItem(LOGIN_TOKEN_KEY));
const [, token,] = tokenItems; const [, token,] = tokenItems;
return token; return token;
} }
@@ -62,19 +64,27 @@ async function tryAutoLogin() {
const [tokenID, token] = tokenInfo; 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) { if (!nonceResult) {
//api 에러. //api 에러.
return; return;
} }
if (!result.result) { if (!nonceResult.result) {
resetToken(); resetToken();
return; return;
} }
const nonce = result.loginNonce; 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 hashedToken = sha512(token + nonce);
const loginResult = await SammoRootAPI.Login.LoginByToken({ const loginResult = await SammoRootAPI.Login.LoginByToken({
@@ -83,6 +93,12 @@ async function tryAutoLogin() {
}, true); }, true);
if (!loginResult.result) { 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) { if (!loginResult.silent) {
alert(loginResult.reason); alert(loginResult.reason);
} }
@@ -94,7 +110,8 @@ async function tryAutoLogin() {
regNextToken(loginResult.nextToken); regNextToken(loginResult.nextToken);
} }
window.location.href = "./"; window.location.href = "./";
return;
}
} }
catch (e) { catch (e) {
if (isString(e)) { if (isString(e)) {
@@ -103,8 +120,6 @@ async function tryAutoLogin() {
console.error(e); console.error(e);
return; return;
} }
} }
function getOAuthToken(mode: string, scope_list?: string[] | string) { function getOAuthToken(mode: string, scope_list?: string[] | string) {
+1 -1
View File
@@ -147,7 +147,7 @@ const descriptor: NamedRules<InstallFormType> = {
turnterm: { turnterm: {
required: true, required: true,
type: "enum", type: "enum",
enum: [1, 2, 5, 10, 20, 30, 60, 120, -60], enum: [1, 2, 5, 10, 20, 30, 60, 120],
transform: parseInt, transform: parseInt,
}, },
sync: { sync: {
+3 -3
View File
@@ -6,7 +6,7 @@ import axios from 'axios';
import { convertFormData } from '@util/convertFormData'; import { convertFormData } from '@util/convertFormData';
import { isBrightColor } from "@util/isBrightColor"; import { isBrightColor } from "@util/isBrightColor";
import { unwrap } from '@util/unwrap'; import { unwrap } from '@util/unwrap';
import { isError, isString, last, trim } from 'lodash-es'; import _, { isError, isString } from 'lodash-es';
import { addMinutes } from 'date-fns'; import { addMinutes } from 'date-fns';
import { parseTime } from '@util/parseTime'; import { parseTime } from '@util/parseTime';
import { formatTime } from '@util/formatTime'; import { formatTime } from '@util/formatTime';
@@ -234,7 +234,7 @@ function redrawMsg(msgResponse: MsgResponse, addFront: boolean): MsgResponse {
if (!msgList || msgList.length == 0) { if (!msgList || msgList.length == 0) {
continue; continue;
} }
const lastMsg = unwrap(last(msgList)); const lastMsg = unwrap(_.last(msgList));
minMsgSeq[msgType] = Math.min(minMsgSeq[msgType], lastMsg.id); minMsgSeq[msgType] = Math.min(minMsgSeq[msgType], lastMsg.id);
} }
return obj; return obj;
@@ -605,7 +605,7 @@ function activateMessageForm() {
$msgSubmit.on('click', async function () { $msgSubmit.on('click', async function () {
const text = trim(unwrap_any<string>($msgInput.val())); const text = _.trim(unwrap_any<string>($msgInput.val()));
$msgInput.val('').trigger('focus'); $msgInput.val('').trigger('focus');
const targetMailbox = unwrap_any<string>($mailboxList.val()); const targetMailbox = unwrap_any<string>($mailboxList.val());
+1
View File
@@ -10,6 +10,7 @@ import { default as che_장수대상임관 } from "./che_장수대상임관.vue"
import { default as che_징병 } from "./che_징병.vue"; import { default as che_징병 } from "./che_징병.vue";
import { default as che_헌납 } from "./che_헌납.vue"; import { default as che_헌납 } from "./che_헌납.vue";
import { default as cr_건국 } from "./cr_건국.vue"; import { default as cr_건국 } from "./cr_건국.vue";
import { default as ProcessCity } from "../ProcessCity.vue"; import { default as ProcessCity } from "../ProcessCity.vue";
import { default as ProcessGeneralAmount } from "../ProcessGeneralAmount.vue"; import { default as ProcessGeneralAmount } from "../ProcessGeneralAmount.vue";
@@ -1,118 +0,0 @@
<template>
<TopBackBar v-model:searchable="searchable" :title="commandName" :type="procEntryMode" />
<div class="bg0">
<div>장수에게 턴을 당기거라 미루라고 지시합니다.</div>
<div class="row">
<div class="col-12 col-lg-5">
장수 :
<SelectGeneral
v-model="selectedGeneralID"
:cities="citiesMap"
:generals="generalList"
:textHelper="textHelpGeneral"
:searchable="searchable"
/>
</div>
<div class="col-2 col-lg-2">
:
<b-button-group>
<b-button :pressed="isPull" @click="isPull = true"> 당기기 </b-button>
<b-button :pressed="!isPull" @click="isPull = false"> 미루기 </b-button>
</b-button-group>
</div>
<div class="col-7 col-lg-3">
<SelectAmount v-model="amount" :amountGuide="amountGuide" :maxAmount="maxAmount" :minAmount="minAmount" />
</div>
<div class="col-3 col-lg-2 d-grid">
<b-button variant="primary" @click="submit">
{{ commandName }}
</b-button>
</div>
</div>
</div>
<BottomBar :title="commandName" :type="procEntryMode" />
</template>
<script lang="ts">
declare const procRes: {
distanceList: Record<number, number[]>;
cities: [number, string][];
generals: procGeneralRawItemList;
generalsKey: procGeneralKey[];
minAmount: number;
maxAmount: number;
amountGuide: number[];
};
declare const staticValues: {
commandName: string;
entryInfo: ["General" | "Nation", unknown];
};
</script>
<script setup lang="ts">
import SelectGeneral from "@/processing/SelectGeneral.vue";
import SelectAmount from "@/processing/SelectAmount.vue";
import { ref } from "vue";
import { unwrap } from "@/util/unwrap";
import type { Args } from "@/processing/args";
import TopBackBar from "@/components/TopBackBar.vue";
import BottomBar from "@/components/BottomBar.vue";
import {
convertGeneralList,
getProcSearchable,
type procGeneralItem,
type procGeneralKey,
type procGeneralRawItemList,
} from "@/processing/processingRes";
import { getNPCColor } from "@/utilGame";
const citiesMap = ref(
new Map<
number,
{
name: string;
info?: string;
}
>()
);
for (const [id, name] of procRes.cities) {
citiesMap.value.set(id, { name });
}
const generalList = convertGeneralList(procRes.generalsKey, procRes.generals);
const amount = ref(1);
const isPull = ref(true);
const selectedGeneralID = ref(generalList[0].no);
type procGeneralItemWithTurn0Brief = procGeneralItem & {
turn0Brief: string;
};
function textHelpGeneral(_gen: procGeneralItem): string {
const gen = _gen as procGeneralItemWithTurn0Brief;
const nameColor = getNPCColor(gen.npc);
const name = nameColor ? `<span style="color:${nameColor}">${gen.name}</span>` : gen.name;
return `${name} [${citiesMap.value.get(unwrap(gen.cityID))?.name}] (${gen.leadership}/${gen.strength}/${
gen.intel
}) (${gen.turn0Brief})`;
}
async function submit(e: Event) {
const event = new CustomEvent<Args>("customSubmit", {
detail: {
amount: amount.value,
isPull: isPull.value,
destGeneralID: selectedGeneralID.value,
},
});
unwrap(e.target).dispatchEvent(event);
}
const { commandName, entryInfo } = staticValues;
const searchable = getProcSearchable();
const procEntryMode: "chief" | "normal" = entryInfo[0] == "Nation" ? "chief" : "normal";
const { minAmount, maxAmount, amountGuide } = procRes;
</script>
-2
View File
@@ -3,7 +3,6 @@ import { default as che_국호변경 } from "./che_국호변경.vue";
import { default as che_물자원조 } from "./che_물자원조.vue"; import { default as che_물자원조 } from "./che_물자원조.vue";
import { default as che_불가침제의 } from "./che_불가침제의.vue"; import { default as che_불가침제의 } from "./che_불가침제의.vue";
import { default as che_피장파장 } from "./che_피장파장.vue"; import { default as che_피장파장 } from "./che_피장파장.vue";
import { default as che_행동지시 } from "./che_행동지시.vue";
import { default as cr_인구이동 } from "./cr_인구이동.vue"; import { default as cr_인구이동 } from "./cr_인구이동.vue";
@@ -34,7 +33,6 @@ export const commandMap: Record<string, typeof ProcessNation | typeof ProcessCit
che_피장파장, che_피장파장,
che_허보: ProcessCity, che_허보: ProcessCity,
cr_인구이동, cr_인구이동,
che_행동지시,
} }
/* /*
+1 -1
View File
@@ -13,7 +13,7 @@ const intArgs = [
] as const; ] as const;
const booleanArgs = [ const booleanArgs = [
'isGold', 'buyRice', 'isPull', 'isGold', 'buyRice',
] as const; ] as const;
const integerArrayArgs = [ const integerArrayArgs = [
+37 -9
View File
@@ -28,6 +28,15 @@ type CardItem = {
personal?: string, personal?: string,
personalText?: string, personalText?: string,
event100Growth?: boolean,
leadership?: number,
strength?: number,
intel?: number,
selectionStatLabel?: string,
selectionLeadership?: number,
selectionStrength?: number,
selectionIntel?: number,
dex?: number[],
} }
type GeneralPoolResponse = { type GeneralPoolResponse = {
@@ -38,6 +47,7 @@ type GeneralPoolResponse = {
declare const characterInfo: Record<string, { name: string, info: string }>; declare const characterInfo: Record<string, { name: string, info: string }>;
declare const hasGeneralID: number; declare const hasGeneralID: number;
declare const isCentennialAllStar: boolean;
declare let currentGeneralInfo: CardItem | undefined; declare let currentGeneralInfo: CardItem | undefined;
declare const cards: Record<string, CardItem>; declare const cards: Record<string, CardItem>;
declare const validCustomOption: string[]; declare const validCustomOption: string[];
@@ -45,9 +55,14 @@ declare const validCustomOption: string[];
const templateGeneralCard = '<div class="general_card">\ const templateGeneralCard = '<div class="general_card">\
<h4 class="bg1 with_border"><%generalName%></h4>\ <h4 class="bg1 with_border"><%generalName%></h4>\
<h4><img src="<%iconPath%>" height=64 width=64></h4><p>\ <h4><img src="<%iconPath%>" height=64 width=64></h4><p>\
<%if(event100Growth){%><b>195년 최종 동조 목표</b><br><%}%>\
<%if(leadership){%>\ <%if(leadership){%>\
<%leadership%> / <%strength%> / <%intel%><br>\ <%leadership%> / <%strength%> / <%intel%><br>\
<%}%>\ <%}%>\
<%if(selectionStatLabel){%>\
<b><%selectionStatLabel%></b><br>\
<%selectionLeadership%> / <%selectionStrength%> / <%selectionIntel%><br>\
<%}%>\
<%if(personalText){%><%personalText%><br><%}%>\ <%if(personalText){%><%personalText%><br><%}%>\
<%if(specialDomesticText||specialWarText){%>\ <%if(specialDomesticText||specialWarText){%>\
<%specialDomesticText%> / <%specialWarText%><br>\ <%specialDomesticText%> / <%specialWarText%><br>\
@@ -102,7 +117,10 @@ async function pickGeneral(this: HTMLElement, e: JQuery.Event) {
method: 'post', method: 'post',
responseType: 'json', responseType: 'json',
data: convertFormData({ 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; result = response.data;
@@ -132,18 +150,24 @@ async function buildGeneral(e: JQuery.Event) {
let result: InvalidResponse; let result: InvalidResponse;
try { 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({ const response = await axios({
url: 'j_select_picked_general.php', url: 'j_select_picked_general.php',
method: 'post', method: 'post',
responseType: 'json', responseType: 'json',
data: convertFormData({ data: convertFormData(formData)
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())
})
}) })
result = response.data; result = response.data;
if (!result.result) { if (!result.result) {
@@ -192,6 +216,10 @@ function printGenerals(value: GeneralPoolResponse) {
'leadership': null, 'leadership': null,
'strength': null, 'strength': null,
'intel': null, 'intel': null,
'selectionStatLabel': null,
'selectionLeadership': null,
'selectionStrength': null,
'selectionIntel': null,
'personalText': null, 'personalText': null,
'specialDomesticText': null, 'specialDomesticText': null,
'specialWarText': null, 'specialWarText': null,
+1 -7
View File
@@ -1,11 +1,5 @@
import {parseISO} from 'date-fns'; import {parseISO} from 'date-fns';
export function parseTime(dateString: string): Date{ export function parseTime(dateString: string): Date{
if(dateString === null){ return parseISO(dateString);
console.warn('why null');
console.trace();
return new Date();
}
const tmp = parseISO(dateString);
return tmp;
} }
-1
View File
@@ -1,5 +1,4 @@
import { clamp } from 'lodash-es'; import { clamp } from 'lodash-es';
export function calcTournamentTerm(turnTerm: number): number{ export function calcTournamentTerm(turnTerm: number): number{
turnTerm = Math.abs(turnTerm);
return clamp(turnTerm, 5, 120); return clamp(turnTerm, 5, 120);
} }
-252
View File
@@ -1,252 +0,0 @@
import {
addSeconds,
addDays,
differenceInCalendarDays,
} from 'date-fns';
import {
toZonedTime,
fromZonedTime,
} from 'date-fns-tz';
import { formatTime } from './util/formatTime';
import { parse as parseDF, isValid } from 'date-fns';
export const SEOUL_TZ = 'Asia/Seoul';
// 문자열이 타임존/오프셋을 포함하는지 단순 판별 (ISO 형태 위주)
const TZ_OFFSET_RE = /([zZ]|[+-]\d{2}:?\d{2})$/;
function tryParseWithFormats(s: string): Date | null {
const fmts = [
"yyyy-MM-dd'T'HH:mm:ss", // 2025-10-31T09:30:00
'yyyy-MM-dd HH:mm:ss', // 2025-10-31 09:30:00
"yyyy-MM-dd'T'HH:mm", // 2025-10-31T09:30
'yyyy-MM-dd HH:mm', // 2025-10-31 09:30
'yyyy-MM-dd', // 2025-10-31
];
for (const fmt of fmts) {
const d = parseDF(s, fmt, new Date(0));
if (isValid(d)) return d;
}
return null;
}
/** 문자열/Date/number 입력을 UTC Date로 정규화
* - 문자열에 오프셋/타임존이 없으면 Asia/Seoul 기준 “벽시계 시간”으로 간주
* - number는 epoch ms로 간주 (epoch s면 직접 *1000 해서 넘겨줘)
*/
export function toUTC(input: string | Date | number): Date {
if (input instanceof Date) {
return new Date(input.getTime()); // 이미 절대시간
}
if (typeof input === 'number') {
return new Date(input); // epoch ms
}
const s = input.trim();
// 오프셋/타임존이 명시된 ISO라면 기본 파서로 (절대시간 유지)
if (TZ_OFFSET_RE.test(s)) {
const d = new Date(s);
if (isValid(d)) return d;
}
// 오프셋이 없는 문자열 → 서울 벽시계로 파싱해서 UTC로 변환
const parsedLocal = tryParseWithFormats(s) ?? new Date(s);
if (!isValid(parsedLocal)) {
throw new Error(`Unparsable date string: "${input}"`);
}
// parsedLocal는 "그 문자열 그대로의 Y/M/D h:m:s"를 들고 있음(타임존 無)
// 이를 Asia/Seoul 로컬로 간주해 UTC로 변환
const utc = fromZonedTime(parsedLocal, SEOUL_TZ);
return utc;
}
export class VarTurn60 {
static readonly TZ = 'Asia/Seoul';
static readonly MonthAdjustOffset = 2;
// [turnIdx, minOffset, turnTermMinutes]
static readonly min30ToTurn: Array<[number, number, number]> = [
[0, 0, 120],
[0, 30, 120],
[0, 60, 120],
[0, 90, 120],
[1, 0, 120],
[1, 30, 120],
[1, 60, 120],
[1, 90, 120],
[2, 0, 120],
[2, 30, 120],
[2, 60, 120],
[2, 90, 120],
[3, 0, 60],
[3, 30, 60],
[4, 0, 60],
[4, 30, 60],
[5, 0, 60],
[5, 30, 60],
[6, 0, 60],
[6, 30, 60],
[7, 0, 60],
[7, 30, 60],
[8, 0, 60],
[8, 30, 60],
[9, 0, 60],
[9, 30, 60],
[10, 0, 60],
[10, 30, 60],
[11, 0, 60],
[11, 30, 60],
[12, 0, 60],
[12, 30, 60],
[13, 0, 60],
[13, 30, 60],
[14, 0, 60],
[14, 30, 60],
[15, 0, 60],
[15, 30, 60],
[16, 0, 30],
[17, 0, 30],
[18, 0, 30],
[19, 0, 30],
[20, 0, 30],
[21, 0, 30],
[22, 0, 60],
[22, 30, 60],
[23, 0, 60],
[23, 30, 60],
];
// [hour, minOffset, turnTermMinutes] for turnIdx 0..23
static readonly turnToHM: Array<[number, number, number]> = [
[0, 0, 120],
[2, 0, 120],
[4, 0, 120],
[6, 0, 60],
[7, 0, 60],
[8, 0, 60],
[9, 0, 60],
[10, 0, 60],
[11, 0, 60],
[12, 0, 60],
[13, 0, 60],
[14, 0, 60],
[15, 0, 60],
[16, 0, 60],
[17, 0, 60],
[18, 0, 60],
[19, 0, 30],
[19, 30, 30],
[20, 0, 30],
[20, 30, 30],
[21, 0, 30],
[21, 30, 30],
[22, 0, 60],
[23, 0, 60],
];
constructor(
public readonly baseDayUTC: Date, // UTC 기준 하루의 00:00 (Seoul 기준)
public readonly turnIdx: number, // 0..23
public readonly secOffset: number // seconds within the turn
) { }
// ----- Utilities -----
/** date → 서울 자정 (UTC 기준 Date) */
private static toSeoulMidnightUTC(dateUTC: Date): Date {
const zoned = toZonedTime(dateUTC, this.TZ);
const midnightInSeoul = new Date(
zoned.getFullYear(), zoned.getMonth(), zoned.getDate(), 0, 0, 0, 0
);
return fromZonedTime(midnightInSeoul, this.TZ);
}
private static format(dateUTC: Date, withFraction = true): string {
const zoned = toZonedTime(dateUTC, this.TZ);
return formatTime(zoned, withFraction);
}
// ----- Core Logic -----
static fromDatetime(input: string | Date | number): VarTurn60 {
const utc = toUTC(input);
const baseDayUTC = this.toSeoulMidnightUTC(utc);
const zoned = toZonedTime(utc, this.TZ);
const totalSec = zoned.getHours() * 3600 + zoned.getMinutes() * 60 + zoned.getSeconds() + zoned.getMilliseconds() / 1000;
const min30 = Math.floor(totalSec / 1800);
if (min30 < 0 || min30 >= 48) throw new RangeError('half-hour index out of range');
const [turnIdx, minOffset] = this.min30ToTurn[min30];
const secOffset = totalSec - 1800 * min30 + minOffset * 60;
return new VarTurn60(baseDayUTC, turnIdx, secOffset);
}
static calcTurnDiff(a: string | Date | number, b: string | Date | number): number {
const aObj = this.fromDatetime(a);
const bObj = this.fromDatetime(b);
const dayDiff = differenceInCalendarDays(bObj.baseDayUTC, aObj.baseDayUTC);
return dayDiff * 24 + (bObj.turnIdx - aObj.turnIdx);
}
cutTurn(withFraction = true): [string, number] {
const [hour, minOffset, turnTerm] = VarTurn60.turnToHM[this.turnIdx];
const sec = (hour * 60 + minOffset) * 60;
const date = addSeconds(this.baseDayUTC, sec);
return [VarTurn60.format(date, withFraction), turnTerm];
}
toDate(): Date {
const [hour, minOffset] = VarTurn60.turnToHM[this.turnIdx];
const sec = (hour * 60 + minOffset) * 60 + this.secOffset;
const date = toZonedTime(addSeconds(this.baseDayUTC, sec), SEOUL_TZ);
return date;
}
toDateStr(withFraction = true): string {
const [hour, minOffset] = VarTurn60.turnToHM[this.turnIdx];
const sec = (hour * 60 + minOffset) * 60 + this.secOffset;
const date = addSeconds(this.baseDayUTC, sec);
return VarTurn60.format(date, withFraction);
}
cutDay(withFraction = true): [string, boolean, number] {
const newMonth = ((this.turnIdx + VarTurn60.MonthAdjustOffset) % 12) + 1;
const moved = this.addTurn(-(newMonth - 1));
const [dateStr] = moved.cutTurn(withFraction);
const yearPulled = newMonth > 3;
return [dateStr, yearPulled, newMonth];
}
addTurn(moreTurn: number): VarTurn60 {
let dayDiff = Math.trunc(moreTurn / 24);
moreTurn %= 24;
let nextTurnIdx = this.turnIdx + moreTurn;
if (nextTurnIdx < 0) {
dayDiff -= 1;
nextTurnIdx += 24;
} else if (nextTurnIdx >= 24) {
dayDiff += 1;
nextTurnIdx -= 24;
}
const [, , oldTurnTerm] = VarTurn60.turnToHM[this.turnIdx];
const [, , nextTurnTerm] = VarTurn60.turnToHM[nextTurnIdx];
let nextSecOffset = this.secOffset;
if (oldTurnTerm !== nextTurnTerm) {
nextSecOffset = (nextSecOffset * nextTurnTerm) / oldTurnTerm;
const cap = nextTurnTerm * 60 - 1;
if (nextSecOffset < 0) nextSecOffset = 0;
if (nextSecOffset > cap) nextSecOffset = cap;
}
const nextBaseDayUTC =
dayDiff === 0 ? this.baseDayUTC : addDays(this.baseDayUTC, dayDiff);
return new VarTurn60(nextBaseDayUTC, nextTurnIdx, nextSecOffset);
}
}
+1
View File
@@ -105,6 +105,7 @@ $lastInheritPointLogs = $db->query('SELECT id, server_id, year, month, date, tex
'availableUnique' => $availableUnique, 'availableUnique' => $availableUnique,
'lastInheritPointLogs' => $lastInheritPointLogs, 'lastInheritPointLogs' => $lastInheritPointLogs,
'availableTargetGeneral' => $availableTargetGeneral, 'availableTargetGeneral' => $availableTargetGeneral,
'canResetStat' => CentennialAllStarGrowthService::isStatResetAllowed(),
'currentStat' => [ 'currentStat' => [
'leadership' => Util::clamp($me->getVar('leadership'), GameConst::$defaultStatMin, GameConst::$defaultStatMax), 'leadership' => Util::clamp($me->getVar('leadership'), GameConst::$defaultStatMin, GameConst::$defaultStatMax),
'strength' => Util::clamp($me->getVar('strength'), GameConst::$defaultStatMin, GameConst::$defaultStatMax), 'strength' => Util::clamp($me->getVar('strength'), GameConst::$defaultStatMin, GameConst::$defaultStatMax),
+12 -26
View File
@@ -52,8 +52,7 @@
"css-color-names": "^1.0.1", "css-color-names": "^1.0.1",
"css-loader": "^6.7.3", "css-loader": "^6.7.3",
"cssnano": "^5.1.15", "cssnano": "^5.1.15",
"date-fns": "^4.1.0", "date-fns": "^2.29.3",
"date-fns-tz": "^3.2.0",
"denque": "^2.1.0", "denque": "^2.1.0",
"detect-it": "^4.0.1", "detect-it": "^4.0.1",
"downloadjs": "^1.4.7", "downloadjs": "^1.4.7",
@@ -3536,22 +3535,15 @@
"peer": true "peer": true
}, },
"node_modules/date-fns": { "node_modules/date-fns": {
"version": "4.1.0", "version": "2.29.3",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.29.3.tgz",
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==", "integrity": "sha512-dDCnyH2WnnKusqvZZ6+jA1O51Ibt8ZMRNkDZdyAyK4YfbDwa/cEmuztzG5pk6hqlp9aSBPYcjOlktquahGwGeA==",
"license": "MIT", "engines": {
"funding": { "node": ">=0.11"
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
}
}, },
"node_modules/date-fns-tz": { "funding": {
"version": "3.2.0", "type": "opencollective",
"resolved": "https://registry.npmjs.org/date-fns-tz/-/date-fns-tz-3.2.0.tgz", "url": "https://opencollective.com/date-fns"
"integrity": "sha512-sg8HqoTEulcbbbVXeg84u5UnlsQa8GS5QXMqjjYIhS4abEVVKIUwe0/l/UhrZdKaL/W5eWZNlbTeEIiOXTcsBQ==",
"license": "MIT",
"peerDependencies": {
"date-fns": "^3.0.0 || ^4.0.0"
} }
}, },
"node_modules/debug": { "node_modules/debug": {
@@ -12097,15 +12089,9 @@
"peer": true "peer": true
}, },
"date-fns": { "date-fns": {
"version": "4.1.0", "version": "2.29.3",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.29.3.tgz",
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==" "integrity": "sha512-dDCnyH2WnnKusqvZZ6+jA1O51Ibt8ZMRNkDZdyAyK4YfbDwa/cEmuztzG5pk6hqlp9aSBPYcjOlktquahGwGeA=="
},
"date-fns-tz": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/date-fns-tz/-/date-fns-tz-3.2.0.tgz",
"integrity": "sha512-sg8HqoTEulcbbbVXeg84u5UnlsQa8GS5QXMqjjYIhS4abEVVKIUwe0/l/UhrZdKaL/W5eWZNlbTeEIiOXTcsBQ==",
"requires": {}
}, },
"debug": { "debug": {
"version": "4.3.4", "version": "4.3.4",
+2 -3
View File
@@ -5,7 +5,7 @@
"main": "js/index.js", "main": "js/index.js",
"scripts": { "scripts": {
"test": "npm-run-all test-php-gateway test-ts", "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", "test-ts": "mocha",
"build": "webpack", "build": "webpack",
"buildDev": "webpack --mode=development", "buildDev": "webpack --mode=development",
@@ -65,8 +65,7 @@
"css-color-names": "^1.0.1", "css-color-names": "^1.0.1",
"css-loader": "^6.7.3", "css-loader": "^6.7.3",
"cssnano": "^5.1.15", "cssnano": "^5.1.15",
"date-fns": "^4.1.0", "date-fns": "^2.29.3",
"date-fns-tz": "^3.2.0",
"denque": "^2.1.0", "denque": "^2.1.0",
"detect-it": "^4.0.1", "detect-it": "^4.0.1",
"downloadjs": "^1.4.7", "downloadjs": "^1.4.7",
+256
View File
@@ -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,
)
);
+131
View File
@@ -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
View File
@@ -36,6 +36,57 @@ type ProcResult = {
lastExecuted?: string; 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() { function nowStr() {
const d = new Date(); const d = new Date();
const pad = (n: number) => n.toString().padStart(2, "0"); 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; if (!REQUIRE_PUBLIC) return true;
const ctrl = new AbortController(); const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), Math.min(5_000, FETCH_TIMEOUT_MS)); const timer = setTimeout(() => ctrl.abort(), Math.min(5_000, FETCH_TIMEOUT_MS));
const composite = anySignal([ctrl.signal, signal].filter(Boolean) as AbortSignal[]); const composite = anySignal([ctrl.signal, signal].filter(Boolean) as AbortSignal[]);
try { 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; } if (!res.ok) { log(`[PUBLIC] 응답 ${res.status} → 비공개로 간주`); return false; }
return true; return true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -150,14 +207,20 @@ async function isPublicReachable(signal?: AbortSignal): Promise<boolean> {
} }
// ============ HTTP ============ // ============ 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 ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS); const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
const signal = anySignal([ctrl.signal, outerSignal].filter(Boolean) as AbortSignal[]); const signal = anySignal([ctrl.signal, outerSignal].filter(Boolean) as AbortSignal[]);
const t0 = performance.now(); const t0 = performance.now();
try { 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); const dt = Math.round(performance.now() - t0);
if (!res.ok) { log("HTTPError:", res.status, url); return null; } if (!res.ok) { log("HTTPError:", res.status, url); return null; }
try { try {
@@ -195,6 +258,7 @@ class ServerRunner {
#stopCtrl = new AbortController(); #stopCtrl = new AbortController();
#stopped = false; #stopped = false;
#lastAutoResetAt = 0; #lastAutoResetAt = 0;
#cookieJar = new CookieJar();
constructor(entry: ServerEntry) { constructor(entry: ServerEntry) {
this.#entry = entry; this.#entry = entry;
@@ -222,7 +286,7 @@ class ServerRunner {
while (!this.#stopCtrl.signal.aborted) { while (!this.#stopCtrl.signal.aborted) {
try { 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; } if (!pub) { await delay(15_000, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ }); continue; }
const hidden = await this.#entry.isHidden(); const hidden = await this.#entry.isHidden();
@@ -236,7 +300,7 @@ class ServerRunner {
if (this.#stopCtrl.signal.aborted) break; if (this.#stopCtrl.signal.aborted) break;
} }
log(`[${this.name()}] 닫힘 - (정렬) autoreset 호출 @ mm:00${AUTO_RESET_JITTER_MS ? `+${AUTO_RESET_JITTER_MS}ms` : ""}`); 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초 직후 잠깐 쉬고 다음 루프는 자연스럽게 다음 분으로 정렬됨 // 같은 분에 중복 호출 방지: 0초 직후 잠깐 쉬고 다음 루프는 자연스럽게 다음 분으로 정렬됨
await delay(200, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ }); await delay(200, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
continue; continue;
@@ -244,7 +308,7 @@ class ServerRunner {
// 열림: proc // 열림: 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) { if (!data) {
await delay(IF_LOCKED_WAIT_MS, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ }); await delay(IF_LOCKED_WAIT_MS, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
continue; continue;
@@ -348,6 +412,7 @@ class DaemonManager {
// ============ 메인 ============ // ============ 메인 ============
const manager = new DaemonManager(); const manager = new DaemonManager();
const publicCookieJar = new CookieJar();
async function main() { async function main() {
// 신호 처리: SIGINT/SIGTERM → graceful shutdown // 신호 처리: SIGINT/SIGTERM → graceful shutdown
+2
View File
@@ -13,6 +13,8 @@ use sammo\TimeUtil;
use sammo\Util; use sammo\Util;
use sammo\Validator; use sammo\Validator;
use function sammo\logError;
class LoginByToken extends LoginByID class LoginByToken extends LoginByID
{ {
static array $sensitiveArgs = ['hashedToken']; static array $sensitiveArgs = ['hashedToken'];
+1 -1
View File
@@ -73,7 +73,7 @@ class APIHelper
$logPath = "{$rootPath}/d_log/{$realYearMonth}_api_log.db"; $logPath = "{$rootPath}/d_log/{$realYearMonth}_api_log.db";
} }
$logDB = FileDB::db($logPath, __DIR__ . '/../../f_install/sql/api_log.sql'); $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'); $date = date('Y-m-d H:i:s');
//NOTE: array_merge([], {})의 상황이 가능함. //NOTE: array_merge([], {})의 상황이 가능함.
+77
View File
@@ -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 -1
View File
@@ -272,7 +272,7 @@ class Session
return $this; return $this;
} }
$turnterm = abs($gameStor->turnterm); $turnterm = $gameStor->turnterm;
$isUnited = $gameStor->isunited != 0; $isUnited = $gameStor->isunited != 0;
$generalID = $general['no']; $generalID = $general['no'];
+1 -19
View File
@@ -947,31 +947,13 @@ class Util
return $flattened; 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) public static function get_client_ip($trust_proxy_headers = false)
{ {
if (!$trust_proxy_headers) { if (!$trust_proxy_headers) {
return $_SERVER['REMOTE_ADDR']; return $_SERVER['REMOTE_ADDR'];
} }
if (!empty($_SERVER['HTTP_CLIENT_IP'])) { return $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? 'local';
$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;
} }
/** /**
+874
View File
@@ -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']
);
}
}
+175
View File
@@ -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}`);