Compare commits

...
30 Commits
Author SHA1 Message Date
Hide_D b4f110dbd5 fix: InheritancePointManager 버그 수정 2025-11-01 17:37:37 +00:00
Hide_D cde6d86e1b feat: 턴 당기기, 턴 미루기 사령턴 2025-11-01 16:59:50 +00:00
Hide_D 1492666d3a fix: 가변턴이고 yearPulled조건일 때 개시 턴을 180년에 맞춰야함 2025-10-30 11:40:15 +00:00
Hide_D de2ee02b3b fix: 가변턴 자동턴 설정 문제 2025-10-30 09:38:39 +00:00
Hide_D 4f65f6870b misc: 이벤트 클랙시에서 항상 상인 등장 2025-10-29 17:48:20 +00:00
Hide_D 7801e5fd81 fix: varTurn60에 밀리초 없음 2025-10-29 17:44:12 +00:00
Hide_D b7c7d6ffce feat: -60 turnterm 가변턴 2025-10-29 17:24:25 +00:00
Hide_D d5b2d4e1f2 dep: datefns 2025-10-29 16:55:42 +00:00
Hide_D d1e5c2105e fix: VarTurn60 CutDay 2025-10-29 16:25:27 +00:00
Hide_D acd73fc63e feat: addTurn, subTurn, cutTurn에서 VarTurn60 버전 호환 2025-10-29 16:01:23 +00:00
Hide_D 76ea61f751 feat: VarTurn60::cutDay() 2025-10-29 15:40:20 +00:00
Hide_D 8dc5231118 refac: turnterm이 varturn 인 경우 대응 준비 2025-10-29 15:15:05 +00:00
Hide_D 45fa74573a feat: VarTurn60 2025-10-29 15:13:57 +00:00
Hide_D 6fe156eb7c fix: composer uninstall 누락 2025-10-29 13:00:46 +00:00
Hide_D 663ddbe76a fix: inheritance_result 작성 문제 2025-10-28 20:24:25 +00:00
Hide_D 30297454f7 refac: inheritance_result로 데이터 이관 2025-10-28 20:15:05 +00:00
Hide_D bc602722bf feat: schema에 inheritance_result 추가
- storage에 의미없이 쌓이는 데이터 이관
2025-10-28 20:09:30 +00:00
Hide_D be8f147216 dep: brandonwamboldt/utilphp 제거 2025-10-28 19:56:02 +00:00
Hide_D b9495fb64a refac: 턴 데몬 전체를 async로 변경경 2025-10-07 20:05:55 +09:00
Hide_D 07b217b290 fix: 서버 오픈 핸들러를 00초에 맞추도록 변경경 2025-10-07 19:54:24 +09:00
Hide_D 42fac46062 refac: brandonwamboldt/utilphp 의존 코드 수정
- 실제 의존성 제거는 이후에에
2025-10-07 19:26:22 +09:00
Hide_D 24bc8985d0 __filename 2025-10-04 11:39:35 +00:00
Hide_D 76a2d5ff63 daemon typescript 버전 추가 2025-10-04 11:29:03 +00:00
Hide_D 148f32f78b fix: execute engine updated 2025-10-04 11:04:36 +00:00
Hide_D 62f5b6597e proc.php 일부 수정
- api.php 미사용 경로 대비
2025-10-04 10:59:56 +00:00
Hide_D 7e810b0279 LogText 끄기 2025-09-07 06:01:04 +00:00
Hide_D 2336b29b65 fix: ?? 2025-08-30 06:15:25 +00:00
Hide_D 185c0e16a0 fix: AI 일부 key 접근 문제 수정 2025-08-30 06:11:37 +00:00
Hide_D 656baeb9ee fix: 토너먼트 분노 공격 확률 오류 수정 (#263)
Reviewed-on: https://storage.hided.net/gitea/devsam/core/pulls/263
2025-08-23 10:08:13 +09:00
류화영 3e06304dc7 fix: 토너먼트 분노 공격 확률 오류 수정 2025-08-23 09:23:00 +09:00
84 changed files with 1587 additions and 198 deletions
-1
View File
@@ -12,7 +12,6 @@
}
},
"require": {
"brandonwamboldt/utilphp": "^1.1",
"sergeytsalkov/meekrodb": "^2.5",
"league/plates": "^3.5",
"vlucas/valitron": "^1.4",
Generated
+2 -52
View File
@@ -4,58 +4,8 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "deed9afdc95bc42f84784df67d295223",
"content-hash": "7edae9b6be35e66ffd0d180f5fac6679",
"packages": [
{
"name": "brandonwamboldt/utilphp",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/brandonwamboldt/utilphp.git",
"reference": "36c32efc4f0679c05163464a550f45c8d83fe683"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/brandonwamboldt/utilphp/zipball/36c32efc4f0679c05163464a550f45c8d83fe683",
"reference": "36c32efc4f0679c05163464a550f45c8d83fe683",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"satooshi/php-coveralls": "dev-master"
},
"type": "library",
"autoload": {
"psr-0": {
"utilphp\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Brandon Wamboldt",
"email": "brandon.wamboldt@gmail.com"
}
],
"description": "util.php is a collection of useful functions and snippets that you need or could use every day, designed to avoid conflicts with existing projects",
"homepage": "https://github.com/brandonwamboldt/utilphp",
"keywords": [
"collection",
"helpers",
"php",
"utility"
],
"support": {
"issues": "https://github.com/brandonwamboldt/utilphp/issues",
"source": "https://github.com/brandonwamboldt/utilphp/tree/master"
},
"time": "2015-02-02T17:56:14+00:00"
},
{
"name": "brick/math",
"version": "0.12.1",
@@ -5721,5 +5671,5 @@
"platform-overrides": {
"php": "8.3"
},
"plugin-api-version": "2.3.0"
"plugin-api-version": "2.6.0"
}
+1 -1
View File
@@ -31,7 +31,7 @@ $queryMap = [
];
if ($reqQueryType === null || !key_exists($reqQueryType, $queryMap)) {
$reqQueryType = Util::array_first_key($queryMap);
$reqQueryType = array_key_first($queryMap);
}
//로그인 검사
+48 -4
View File
@@ -923,6 +923,13 @@ function banner()
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);
$target = $turnterm * $turn;
$date->add(new \DateInterval("PT{$target}M"));
@@ -934,6 +941,13 @@ function addTurn($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);
$target = $turnterm * $turn;
$date->sub(new \DateInterval("PT{$target}M"));
@@ -945,6 +959,14 @@ function subTurn($date, int $turnterm, int $turn = 1, 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);
$baseDate = new \DateTime($date->format('Y-m-d'));
@@ -963,6 +985,8 @@ function cutTurn($date, int $turnterm, bool $withFraction = true)
function cutDay($date, int $turnterm, bool $withFraction = true)
{
assert($turnterm > 0);
$date = new \DateTime($date);
$baseDate = new \DateTime($date->format('Y-m-d'));
@@ -1106,6 +1130,7 @@ function CheckOverhead()
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$turnterm, $refreshLimit] = $gameStor->getValuesAsArray(['turnterm', 'refreshLimit']);
$turnterm = abs($turnterm);
$nextRefreshLimit = Util::round(pow($turnterm, 0.6) * 3) * GameConst::$refreshLimitCoef;
@@ -1153,7 +1178,7 @@ function timeover(): bool
list($turnterm, $turntime) = $gameStor->getValuesAsArray(['turnterm', 'turntime']);
$diff = (new \DateTime())->getTimestamp() - (new \DateTime($turntime))->getTimestamp();
$t = min($turnterm, 5);
$t = min(abs($turnterm), 5);
$term = $diff;
if ($term >= $t || $term < 0) {
@@ -1175,6 +1200,12 @@ function checkDelay()
// 1턴이상 갱신 없었으면 서버 지연
$term = $gameStor->turnterm;
if($term < 0){
//가변 턴에는 수행 안함!
return;
}
if ($term >= 20) {
$threshold = 1;
} else if ($term >= 10) {
@@ -1254,10 +1285,14 @@ function turnDate($curtime)
$admin = $gameStor->getValues(['startyear', 'starttime', 'turnterm', 'year', 'month']);
$turn = $admin['starttime'];
$curturn = cutTurn($curtime, $admin['turnterm']);
$term = $admin['turnterm'];
$num = intdiv((strtotime($curturn) - strtotime($turn)), $term * 60);
if($term == -60){
$num = VarTurn60::calcTurnDiff(new \DateTimeImmutable($turn), new \DateTimeImmutable($curtime));
}
else{
$curturn = cutTurn($curtime, $admin['turnterm']);
$num = intdiv((strtotime($curturn) - strtotime($turn)), $term * 60);
}
$date = $admin['startyear'] * 12;
$date += $num;
@@ -2208,6 +2243,10 @@ function getRandTurn(RandUtil $rng, $term, ?\DateTimeInterface $baseDateTime = n
throw new MustNotBeReachedException();
}
if($term == -60){
[, $term] = VarTurn60::fromDatetime($baseDateTime)->cutTurn();
}
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수
@@ -2223,6 +2262,11 @@ function getRandTurn2(RandUtil $rng, $term, ?\DateTimeInterface $baseDateTime =
} else {
throw new MustNotBeReachedException();
}
if($term == -60){
[, $term] = VarTurn60::fromDatetime($baseDateTime)->cutTurn();
}
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수
+1 -1
View File
@@ -559,7 +559,7 @@ function checkStatistic()
$nationHist = '';
foreach (GameConst::$availableNationType as $nationType) {
if (!Util::array_get($nationHists[$nationType])) {
if (!($nationHists[$nationType] ?? null)) {
$nationHists[$nationType] = '-';
}
$nationHist .= getNationType($nationType) . "({$nationHists[$nationType]}), ";
+8 -3
View File
@@ -138,7 +138,7 @@ function JSCitiesBasedOnDistance(int $cityNo, int $maxDistance = 1): array{
$distanceList = searchDistance($cityNo, $maxDistance, true);
$result = [];
for ($dist = 1; $dist <= $maxDistance; $dist++) {
$result[$dist] = Util::array_get($distanceList[$dist], []);
$result[$dist] = $distanceList[$dist] ?? [];
}
return $result;
}
@@ -152,7 +152,7 @@ function printCitiesBasedOnDistance(int $cityNo, int $maxDistance = 1): string
for ($dist = 1; $dist <= $maxDistance; $dist++) {
$cityList = array_map(function ($cityID) {
return CityConst::byID($cityID)->name;
}, Util::array_get($distanceList[$dist], []));
}, $distanceList[$dist] ?? []);
$cityStr = join(', ', $cityList);
@@ -181,7 +181,12 @@ function info($type = 0)
$admin = $gameStor->getValues(['year', 'month', 'turnterm', 'maxgeneral']);
$termtype = "{$admin['turnterm']}분 턴";
$turnTermText = $admin['turnterm'].'분';
if($admin['turnterm'] < 0){
$turnTermText = "가변 {$admin['turnterm']}분";
}
$termtype = "{$turnTermText}분 턴";
$gencount = $db->queryFirstField('SELECT count(no) FROM general WHERE npc < 2');
$npccount = $db->queryFirstField('SELECT count(no) FROM general WHERE npc >= 2');
+10 -4
View File
@@ -10,6 +10,7 @@ use sammo\Enums\InheritanceKey;
* @return int 토너먼트 초 단위
*/
function calcTournamentTerm(int $turnTerm): int{
$turnTerm = abs($turnTerm);
return Util::valueFit($turnTerm, 5, 120);
}
@@ -138,6 +139,7 @@ function processTournament()
function getTournamentTermText(int $turnTerm)
{
$turnTerm = abs($turnTerm);
$term = calcTournamentTerm($turnTerm);
if ($term % 60 === 0) {
@@ -342,7 +344,7 @@ function startBetting($type)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month, $startyear, $turnterm] = $gameStor->getValuesAsArray(['year', 'month', 'startyear', 'turnterm']);
[$year, $month, $startyear] = $gameStor->getValuesAsArray(['year', 'month', 'startyear']);
pushGlobalHistoryLog([
"<S>◆</>{$year}{$month}월:<B><b>【대회】</b></>우승자를 예상하는 <C>내기</>가 진행중입니다! 호사가의 참여를 기다립니다!"
], $year, $month);
@@ -1153,21 +1155,25 @@ function fight($tnmt_type, $tnmt, $phs, $group, $g1, $g2, $type)
];
//막판 분노
$factor1 = 1.0;
$factor2 = 1.0;
$ratio = rand() % 300;
if ($e1 / 5 > $energy1 && $damage1 > $damage2 && $gen1[$tp] >= $ratio) {
$damage2 *= Util::round((rand() % 301 + 200) / 100); // 200 ~ 500%
$factor2 = Util::round((rand() % 301 + 200) / 100); // 200 ~ 500%
$critical1 = 1;
$str = Util::choiceRandom($crticialSkillMap[$tnmt_type]);
$log[] = "<S>●</> <Y>{$gen1['name']}</>의 분노의 <M>{$str}</> 공격!";
}
$ratio = rand() % 300;
if ($e2 / 5 > $energy2 && $damage2 > $damage1 && $gen2[$tp] >= $ratio) {
$damage1 *= Util::round((rand() % 301 + 200) / 100); // 200 ~ 500%
$factor1 = Util::round((rand() % 301 + 200) / 100); // 200 ~ 500%
$critical2 = 1;
$str = Util::choiceRandom($crticialSkillMap[$tnmt_type]);
$log[] = "<S>●</> <Y>{$gen2['name']}</>의 분노의 <M>{$str}</> 공격!";
}
$damage1 *= $factor1;
$damage2 *= $factor2;
//1합 승부
if ($phase == 1) {
+1
View File
@@ -54,6 +54,7 @@ if ($session->userGrade < 5 && !$allowReset) {
<label for="turnterm" class="col-sm-3 col-form-label">턴 시간(분)</label>
<div class="col-sm-9">
<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_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>
+1
View File
@@ -36,6 +36,7 @@ list(
$turnterm,
$npcmode
) = $gameStor->getValuesAsArray(['maxgeneral', 'turnterm', 'npcmode']);
$turnterm = abs($turnterm);
if($npcmode!=1){
Json::die([
+1 -1
View File
@@ -144,7 +144,7 @@ function do도시임명(General $general, int $cityID, int $targetOfficerLevel):
return '올바르지 않은 도시입니다';
}
if ($general->getVar(GeneralColumn::officer_level) >= 4 && $myPenalty[PenaltyKey::NoChiefChange->value] ?? false) {
if ($general->getVar(GeneralColumn::officer_level) >= 4 && ($myPenalty[PenaltyKey::NoChiefChange->value] ?? false)) {
return '수뇌인 장수를 변경할 수 없는 상태입니다.';
}
+1 -1
View File
@@ -121,7 +121,7 @@ $builder->setOwner($userID);
$builder->setOwnerName($userNick);
$builder->setKillturn(5);
$builder->setNPCType(0);
$builder->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $env['turnterm']));
$builder->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * abs($env['turnterm'])));
$builder->fillRemainSpecAsZero($env);
$builder->build($env);
$generalID = $builder->getGeneralID();
+1 -1
View File
@@ -60,7 +60,7 @@ $me->setAuxVar('use_auto_nation_turn', $use_auto_nation_turn);
$me->setVar('tnmt', $tnmt);
if ($me->getNPCType() == 1 && $detachNPC) {
$turnterm = $gameStor->turnterm;
$turnterm = abs($gameStor->turnterm);
if ($turnterm < 10) {
$targetKillTurn = 30 / $turnterm;
+1
View File
@@ -39,6 +39,7 @@ list(
$npcmode,
$turnterm
) = $gameStor->getValuesAsArray(['year', 'month', 'maxgeneral', 'npcmode', 'turnterm']);
$turnterm = abs($turnterm);
if($npcmode!=2){
Json::die([
+3 -2
View File
@@ -51,8 +51,9 @@ function MessageBox($str)
function LogText($prefix, $variable)
{
$text = sprintf('%s : %s'."\r\n", $prefix, TVarDumper::dump($variable));
file_put_contents(ROOT.'/d_log/'.UniqueConst::$serverName.'_dbg_logs.txt', $text, FILE_APPEND);
return;
//$text = sprintf('%s : %s'."\r\n", $prefix, TVarDumper::dump($variable));
//file_put_contents(ROOT.'/d_log/'.UniqueConst::$serverName.'_dbg_logs.txt', $text, FILE_APPEND);
}
function prepareDir(string $dirPath, bool $forceCreate=true):bool{
+9 -1
View File
@@ -8,4 +8,12 @@ $session = Session::getInstance()->setReadOnly();
$db = DB::db();
TurnExecutionHelper::executeAllCommand();
$updated = false;
$locked = false;
$lastExecuted = TurnExecutionHelper::executeAllCommand($updated, $locked);
Json::die([
'result' => true,
'updated' => $updated,
'locked' => $locked,
'lastExecuted' => $lastExecuted,
]);
+1 -1
View File
@@ -526,7 +526,7 @@ function DeleteConflict($nation)
function getConquerNation($city): int
{
$conflict = Json::decode($city['conflict']);
return Util::array_first_key($conflict);
return array_key_first($conflict);
}
function ConquerCity(array $admin, General $general, array $city, array $defenderCityGeneralList)
+14 -5
View File
@@ -28,6 +28,7 @@ use sammo\UniqueConst;
use sammo\UserLogger;
use sammo\Util;
use sammo\Validator;
use sammo\VarTurn60;
use sammo\WebUtil;
use function sammo\addTurn;
@@ -99,7 +100,7 @@ class Join extends \sammo\BaseAPI
}
$gameID = UniqueConst::$serverID;
$alreadyJoined = $db->queryFirstField('SELECT count(*) FROM `storage` WHERE `namespace` = %s AND `key` LIKE %s', 'inheritance_result', "{$gameID}_{$userID}_%");
$alreadyJoined = $db->queryFirstField('SELECT COUNT(*) FROM `inheritance_result` WHERE `server_id` = %s AND `owner` = %i', $gameID, $userID);
if ($alreadyJoined) {
//이미 받았음
return 0;
@@ -355,20 +356,28 @@ class Join extends \sammo\BaseAPI
}
if ($inheritTurntimeZone !== null) {
$inheritTurntime = $inheritTurntimeZone * $admin['turnterm'];
$inheritTurntime += $rng->nextRangeInt(0, Util::clamp($admin['turnterm'] - 1, 0));
$turnterm = abs($admin['turnterm']);
$inheritTurntime = $inheritTurntimeZone * $turnterm;
$inheritTurntime += $rng->nextRangeInt(0, Util::clamp($turnterm - 1, 0));
$userLogger->push(sprintf("턴 시간 %02d:%02d 로 지정", intdiv($inheritTurntime, 60), $inheritTurntime % 60), "inheritPoint");
$inheritTurntime += $rng->nextRangeInt(0, 999999) / 1000000;
$turntime = new \DateTimeImmutable(cutTurn($admin['turntime'], $admin['turnterm']));
$turntime = new \DateTimeImmutable(cutTurn($admin['turntime'], $turnterm));
$turntime = $turntime->add(TimeUtil::secondsToDateInterval($inheritTurntime));
$turntime = TimeUtil::format($turntime, true);
} else {
$turntime = getRandTurn($rng, $admin['turnterm'], new \DateTimeImmutable($admin['turntime']));
$turntime = getRandTurn($rng, abs($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);
if ($now >= $turntime) {
@@ -62,7 +62,7 @@ class ResetTurnTime extends \sammo\BaseAPI
}
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
$currTurnTime = new DateTimeImmutable($general->getTurnTime());
+1 -1
View File
@@ -46,7 +46,7 @@ abstract class AbsFromUserPool extends AbsGeneralPool{
$gameStor = KVStorage::getStorage($db, 'game_env');
$result = [];
$validUntil = TimeUtil::nowAddMinutes(2 * $gameStor->turnterm);
$validUntil = TimeUtil::nowAddMinutes(2 * abs($gameStor->turnterm));
while(count($result) < $pickCnt){
$cand = $rng->choiceUsingWeightPair($pool);
$poolID = $cand['id'];
@@ -33,7 +33,7 @@ class event_전투특기_공성 extends \sammo\BaseItem{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_SIEGE;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -28,7 +28,7 @@ class event_전투특기_궁병 extends \sammo\BaseItem{
if($statName === 'warAvoidRatio'){
return $value + 0.2;
}
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_ARCHER;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -28,7 +28,7 @@ class event_전투특기_귀병 extends \sammo\BaseItem{
if($statName === 'warMagicSuccessProb'){
return $value + 0.2;
}
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_WIZARD;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -32,7 +32,7 @@ class event_전투특기_기병 extends \sammo\BaseItem{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_CAVALRY;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -33,7 +33,7 @@ class event_전투특기_보병 extends \sammo\BaseItem{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_FOOTMAN;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -35,7 +35,7 @@ class che_event_공성 extends \sammo\BaseSpecial{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_SIEGE;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -31,7 +31,7 @@ class che_event_궁병 extends \sammo\BaseSpecial{
if($statName === 'warAvoidRatio'){
return $value + 0.2;
}
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_ARCHER;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -30,7 +30,7 @@ class che_event_귀병 extends \sammo\BaseSpecial{
if($statName === 'warMagicSuccessProb'){
return $value + 0.2;
}
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_WIZARD;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -35,7 +35,7 @@ class che_event_기병 extends \sammo\BaseSpecial{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_CAVALRY;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
@@ -35,7 +35,7 @@ class che_event_보병 extends \sammo\BaseSpecial{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_FOOTMAN;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
+1 -1
View File
@@ -35,7 +35,7 @@ class che_공성 extends \sammo\BaseSpecial{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_SIEGE;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
+1 -1
View File
@@ -31,7 +31,7 @@ class che_궁병 extends \sammo\BaseSpecial{
if($statName === 'warAvoidRatio'){
return $value + 0.2;
}
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_ARCHER;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
+1 -1
View File
@@ -30,7 +30,7 @@ class che_귀병 extends \sammo\BaseSpecial{
if($statName === 'warMagicSuccessProb'){
return $value + 0.2;
}
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_WIZARD;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
+1 -1
View File
@@ -35,7 +35,7 @@ class che_기병 extends \sammo\BaseSpecial{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_CAVALRY;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
+1 -1
View File
@@ -35,7 +35,7 @@ class che_보병 extends \sammo\BaseSpecial{
}
public function onCalcStat(General $general, string $statName, $value, $aux=null){
if(\sammo\Util::starts_with($statName, 'dex')){
if(str_starts_with($statName, 'dex')){
$myArmType = 'dex'.GameUnitConst::T_FOOTMAN;
$opposeArmType = 'dex'.$aux['opposeType']->armType;;
if($aux['isAttacker'] && $opposeArmType === $statName){
+4 -4
View File
@@ -164,7 +164,7 @@ abstract class Auction
if ($date === null) {
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
$date = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
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');
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
if ($this->info->detail->availableLatestBidCloseDate !== null) {
$extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval(
@@ -437,7 +437,7 @@ abstract class Auction
$general->increaseVar($resType->value, -$morePoint);
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
$extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval(
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) {
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
//연장 요청이 있었다.
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
+8 -2
View File
@@ -58,7 +58,7 @@ abstract class AuctionBasicResource extends Auction
$now = new \DateTimeImmutable();
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
$closeDate = $now->add(TimeUtil::secondsToDateInterval($closeTurnCnt * $turnTerm * 60));
$openResult = static::openAuction(new AuctionInfo(
@@ -246,7 +246,13 @@ abstract class AuctionBasicResource extends Auction
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$date = (new DateTimeImmutable())->add(TimeUtil::secondsToDateInterval($turnTerm * 60));
if($turnTerm == -60){
$date = VarTurn60::fromDatetime(new \DateTimeImmutable())->addTurn(1)->toDateStr();
}
else{
$date = (new DateTimeImmutable())->add(TimeUtil::secondsToDateInterval($turnTerm * 60));
}
$this->shrinkCloseDate($date);
}
+3 -2
View File
@@ -75,6 +75,7 @@ class AuctionUniqueItem extends Auction
$now = new DateTimeImmutable();
[$turnTerm, $year, $month] = $gameStor->getValuesAsArray(['turnterm', 'year', 'month']);
$turnTerm = abs($turnTerm);
$closeDate = $now->add(TimeUtil::secondsToDateInterval(
max(static::MIN_AUCTION_CLOSE_MINUTES, $turnTerm * static::COEFF_AUCTION_CLOSE_MINUTES) * 60
@@ -266,7 +267,7 @@ class AuctionUniqueItem extends Auction
}
if ($availableEquipUniqueCnt <= 0) {
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
//제한에 걸렸다면 자동 연장
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_UNIQUE_CNT) * 60
@@ -314,7 +315,7 @@ class AuctionUniqueItem extends Auction
if (!$availableItemTypes) {
if ($isExtendCloseDateRequired) {
$turnTerm = $gameStor->getValue('turnterm');
$turnTerm = abs($gameStor->getValue('turnterm'));
//동일 부위 제한에 걸렸다면 자동 연장
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_LIMIT_BY_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_BY_BID) * 60
@@ -208,7 +208,7 @@ class che_랜덤임관 extends Command\GeneralCommand
foreach ($rawGeneralsCnt as $nation) {
$calcCnt = $nation['warpower'] + $nation['develpower'];
if ($general->getNPCType() < 2 && Util::starts_with($nation['name'], 'ⓤ')) {
if ($general->getNPCType() < 2 && str_starts_with($nation['name'], 'ⓤ')) {
$calcCnt *= 100;
}
+1 -1
View File
@@ -164,7 +164,7 @@ class che_출병 extends Command\GeneralCommand
$currDist = 999;
$minDist = Util::array_first_key($distanceList);
$minDist = array_key_first($distanceList);
do {
//1: 최단 거리 도시 중 공격 대상이 있는가 확인
//2: 최단 거리 + 1 도시 중 공격 대상이 있는가 확인
@@ -200,7 +200,7 @@ class che_불가침제의 extends Command\NationCommand
$now = new \DateTime($date);
$validUntil = new \DateTime($date);
$validMinutes = max(30, $env['turnterm'] * 3);
$validMinutes = max(30, abs($env['turnterm']) * 3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M"));
$josaWa = JosaUtil::pick($nationName, '와');
@@ -149,7 +149,7 @@ class che_불가침파기제의 extends Command\NationCommand{
$now = new \DateTime($date);
$validUntil = new \DateTime($date);
$validMinutes = max(30, $env['turnterm']*3);
$validMinutes = max(30, abs($env['turnterm'])*3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M"));
$msg = new DiplomaticMessage(
@@ -147,7 +147,7 @@ class che_종전제의 extends Command\NationCommand{
$now = new \DateTime($date);
$validUntil = new \DateTime($date);
$validMinutes = max(30, $env['turnterm']*3);
$validMinutes = max(30, abs($env['turnterm'])*3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M"));
$msg = new DiplomaticMessage(
@@ -0,0 +1,204 @@
<?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,
]
];
}
}
+1 -1
View File
@@ -127,7 +127,7 @@ class ChangeCity extends \sammo\Event\Action{
return DB::db()->sqleval('ROUND(%b * %d, 0)', $keyMax, $value/100);
}
if(Util::ends_with($key, '_max') && preg_match(self::REGEXP_MATH, $value, $matches)){
if(str_ends_with($key, '_max') && preg_match(self::REGEXP_MATH, $value, $matches)){
//key가 아예 최대치에 대한 값이면 연산은 결과값이 0보다만 높게.
$op = $matches[1];
$value = $matches[2];
+1 -1
View File
@@ -120,7 +120,7 @@ class RaiseInvader extends \sammo\Event\Action
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->setValue('isunited', 1);
$turnterm = $gameStor->turnterm;
$turnterm = abs($gameStor->turnterm);
$generalCnt = $db->queryFirstField('SELECT count(*) FROM general');
if ($npcEachCount < 0) {
+1 -1
View File
@@ -134,7 +134,7 @@ class UpdateNationLevel extends \sammo\Event\Action
if ($levelDiff) {
//유니크 아이템 하나 돌리자
$targetKillTurn = $env['killturn'];
$targetKillTurn -= 24 * 60 / $env['turnterm'];
$targetKillTurn -= 24 * 60 / abs($env['turnterm']);
$nationGenIDList = $db->queryFirstColumn(
'SELECT no FROM general WHERE nation = %i AND killturn >= %i AND npc < 2',
$nation['nation'],
+1
View File
@@ -384,6 +384,7 @@ class GameConstBase
'che_포상',
'che_몰수',
'che_부대탈퇴지시',
'che_행동지시',
],
'외교' => [
'che_물자원조',
+7
View File
@@ -283,6 +283,7 @@ class General extends GeneralBase implements iAction
}
$recwar = new \DateTimeImmutable($this->getVar('recent_war'));
$turnNow = new \DateTimeImmutable($this->getVar('turntime'));
$secDiff = TimeUtil::DateIntervalToSeconds($recwar->diff($turnNow));
if ($secDiff <= 0) {
@@ -290,6 +291,12 @@ class General extends GeneralBase implements iAction
return 0;
}
if($turnTerm == -60){
$turnDiff = VarTurn60::calcTurnDiff($recwar, $turnNow);
$this->calcCache[$cacheKey] = $turnDiff;
return $turnDiff;
}
$result = intdiv(Util::toInt($secDiff), 60 * $turnTerm);
$this->calcCache[$cacheKey] = $result;
return $result;
+12 -6
View File
@@ -1980,7 +1980,7 @@ class GeneralAI
$db = DB::db();
$nationStor = KVStorage::getStorage($db, $general->getNationID(), 'nation_env');
$turnTerm = $this->env['turnterm'];
$turnTerm = abs($this->env['turnterm']);
//천도를 한턴 넣었다면 계속 넣는다.
if ($lastTurn->getCommand() === '천도' && $lastTurn->getArg()['destCityID'] != $this->nation['capital']) {
@@ -2084,7 +2084,7 @@ class GeneralAI
}
}
$finalCityID = Util::array_first_key($cityScoreList);
$finalCityID = array_key_first($cityScoreList);
$dist = $distanceList[$capital][$finalCityID];
$targetCityID = $finalCityID;
if ($dist > 1) {
@@ -3129,8 +3129,14 @@ class GeneralAI
$db = DB::db();
$dupLord = $db->queryFirstField('SELECT COUNT(*) FROM general WHERE officer_level = 12 AND city = %i', $this->general->getCityID());
if($dupLord <= 1 && !in_array($this->general->getRawCity()['level'], [5, 6])) {
return null;
if($dupLord <= 1) {
if ($this->general->getRawCity() === null) {
$rawCity = $db->queryFirstRow('SELECT * FROM city WHERE city = %i', $this->general->getCityID());
$this->general->setRawCity($rawCity);
}
if (!in_array($this->general->getRawCity()['level'], [5, 6])) {
return null;
}
}
$general = $this->general;
@@ -3709,7 +3715,7 @@ class GeneralAI
$this->updateInstance();
//특별 메세지 있는 경우 출력
$term = $this->env['turnterm'];
$term = abs($this->env['turnterm']);
if ($general->getVar('npcmsg') && $this->rng->nextBool(GameConst::$npcMessageFreqByDay * $term / (60 * 24))) {
$src = new MessageTarget(
$general->getID(),
@@ -3979,7 +3985,7 @@ class GeneralAI
$userChiefCnt = 0;
$minUserKillturn = $this->env['killturn'] - Util::toInt(240 / $this->env['turnterm']);
$minUserKillturn = $this->env['killturn'] - Util::toInt(240 / abs($this->env['turnterm']));
$minNPCKillturn = 36;
foreach (Util::range($minChiefLevel, 12) as $chiefLevel) {
+10 -2
View File
@@ -334,11 +334,19 @@ class InheritancePointManager
$inheritStor->setValue($key, [$point, $aux]);
}
$oldInheritStor = KVStorage::getStorage(DB::db(), "inheritance_result");
$db = DB::db();
$serverID = UniqueConst::$serverID;
$year = $gameStor->year;
$month = $gameStor->month;
$oldInheritStor->setValue("{$serverID}_{$ownerID}_{$general->getID()}_{$year}_{$month}", $inheritStor->getAll(true));
$db->insert('inheritance_result', [
'server_id'=>$serverID,
'owner'=>$ownerID,
'general_id'=>$general->getID(),
'year'=>$year,
'month'=>$month,
'value'=>Json::encode($inheritStor->getAll(true))
]);
}
+11 -2
View File
@@ -245,7 +245,16 @@ class ResetHelper{
true
);
if($sync == 0) {
if($turnterm == -60){
[$starttime, $yearPulled, $month] = VarTurn60::fromDatetime(new \DateTimeImmutable($turntime))->cutDay();
if($yearPulled){
$year = $startyear-1;
}
else{
$year = $startyear;
}
}
else if($sync == 0) {
// 현재 시간을 1월로 맞춤
$starttime = cutTurn($turntime, $turnterm);
$month = 1;
@@ -261,7 +270,7 @@ class ResetHelper{
}
}
$killturn = 4800 / $turnterm;
$killturn = 4800 / abs($turnterm);
if($npcmode == 1) { $killturn = intdiv($killturn, 3); }
$develcost = ($year - $startyear + 10) * 2;
+12 -10
View File
@@ -14,12 +14,23 @@ final class ServerTool
if ((120 % $turnterm) != 0) {
return 'invalid minute';
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$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;
$locked = false;
@@ -40,15 +51,6 @@ final class ServerTool
$locked = tryLock();
}
$oldunit = $admin['turnterm'] * 60;
$unit = $turnterm * 60;
if($unit == $oldunit){
if($locked){
unlock();
}
return null;
}
$unitDiff = $unit / $oldunit;
+1 -1
View File
@@ -62,7 +62,7 @@ abstract class TriggerCaller{
return $this;
}
$lastKey = Util::array_last_key($this->triggerListByPriority);
$lastKey = array_key_last($this->triggerListByPriority);
if($lastKey < $priority){
$this->triggerListByPriority[$priority] = [$uniqueID=>$trigger];
return $this;
+16 -14
View File
@@ -219,11 +219,20 @@ class TurnExecutionHelper
$nextTurnTimeBase = $general->getAuxVar('nextTurnTimeBase');
if($nextTurnTimeBase !== null){
$turntime = cutTurn($turntime, $gameStor->turnterm);
$turntimeObj = new \DateTimeImmutable($turntime);
$turntimeObj = $turntimeObj->add(TimeUtil::secondsToDateInterval($nextTurnTimeBase));
$turntime = TimeUtil::format($turntimeObj, true);
$general->setAuxVar('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);
$turntimeObj = new \DateTimeImmutable($turntime);
$turntimeObj = $turntimeObj->add(TimeUtil::secondsToDateInterval($nextTurnTimeBase));
$turntime = TimeUtil::format($turntimeObj, true);
$general->setAuxVar('nextTurnTimeBase', null);
}
}
$general->setVar('turntime', $turntime);
@@ -355,7 +364,7 @@ class TurnExecutionHelper
if (($autorun_user['limit_minutes'] ?? false) && $general->getNPCType() < 2 && $hasReservedTurn) {
$autorun_limit = Util::joinYearMonth($year, $month);
$autorun_limit += intdiv($autorun_user['limit_minutes'], $turnterm);
$autorun_limit += intdiv($autorun_user['limit_minutes'], abs($turnterm));
$general->setAuxVar('autorun_limit', $autorun_limit);
}
@@ -422,7 +431,7 @@ class TurnExecutionHelper
$date = TimeUtil::now(true);
// 최종 처리 월턴의 다음 월턴시간 구함
$lastExecuted = $gameStor->turntime;
//$lastExecuted = $gameStor->turntime;
$prevTurn = cutTurn($gameStor->turntime, $gameStor->turnterm);
$nextTurn = addTurn($prevTurn, $gameStor->turnterm);
@@ -455,9 +464,6 @@ class TurnExecutionHelper
$gameStor->turntime = $currentTurn;
}
unlock();
if($lastExecuted !== $currentTurn){
$executed = true;
}
return $gameStor->turntime;
}
@@ -516,10 +522,6 @@ class TurnExecutionHelper
$gameStor->resetCache();
unlock();
if($lastExecuted !== $currentTurn){
$executed = true;
}
return $turntime;
}
}
+191
View File
@@ -0,0 +1,191 @@
<?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,6 +81,13 @@
["RaiseNPCNation"],
["DeleteEvent"]
],
[
"month", 1000,
true,
["ChangeCity", "all", {
"trade":100
}]
],
[
"month", 999,
["Date", "==", 181, 1],
+14
View File
@@ -583,6 +583,20 @@ CREATE TABLE IF NOT EXISTS `nation_env` (
UNIQUE INDEX `key` (`namespace`, `key`),
CONSTRAINT `json` CHECK (json_valid(`value`))
) COLLATE = 'utf8mb4_bin' ENGINE = Aria;
CREATE TABLE IF NOT EXISTS `inheritance_result` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`server_id` CHAR(20) NOT NULL COLLATE 'utf8mb4_general_ci',
`owner` INT(11) NOT NULL,
`general_id` INT(11) NOT NULL,
`year` INT(11) NOT NULL,
`month` INT(11) NOT NULL,
`value` LONGTEXT NOT NULL COLLATE 'utf8mb4_bin',
PRIMARY KEY (`id`),
INDEX `by_owner` (`server_id`, `owner`, `general_id`, `year`, `month`)
)
COLLATE='utf8mb4_general_ci'
ENGINE=Aria
;
##############################
##
+17 -5
View File
@@ -68,7 +68,7 @@ import { formatTime } from "@/util/formatTime";
import { mb_strwidth } from "@/util/mb_strwidth";
import { parseTime } from "@/util/parseTime";
import type { StoredActionsHelper } from "@/util/StoredActionsHelper";
import addMinutes from "date-fns/esm/addMinutes/index";
import { addMinutes } from "date-fns/addMinutes";
import { range } from "lodash-es";
import { inject, onMounted, ref, type PropType } from "vue";
import VueTypes from "vue-types";
@@ -76,6 +76,7 @@ import DragSelect from "@/components/DragSelect.vue";
import { BButton } from "bootstrap-vue-next";
import { QueryActionHelper } from "@/util/QueryActionHelper";
import type { ChiefResponse } from "@/defs/API/NationCommand";
import { VarTurn60 } from "@/varTurn60";
const props = defineProps({
style: VueTypes.object.isRequired,
@@ -198,10 +199,21 @@ if (!props.officer || !props.officer.turnTime) {
}
} else {
const baseTurnTime = parseTime(props.officer.turnTime);
for (const idx of range(props.officer.turn.length)) {
turnTimes.value.push(
formatTime(addMinutes(baseTurnTime, idx * props.turnTerm), props.turnTerm >= 5 ? "HH:mm" : "mm:ss")
);
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)) {
turnTimes.value.push(
formatTime(addMinutes(baseTurnTime, idx * props.turnTerm), props.turnTerm >= 5 ? "HH:mm" : "mm:ss")
);
}
}
}
</script>
+2 -3
View File
@@ -310,14 +310,13 @@ declare const staticValues: {
import { reactive, ref, watch } from "vue";
import "@scss/game_bg.scss";
import TopBackBar from "@/components/TopBackBar.vue";
import _ from "lodash-es";
import { sum } from "lodash-es";
import NumberInputWithInfo from "@/components/NumberInputWithInfo.vue";
import { SammoAPI } from "./SammoAPI";
import { InheritResetStat, type inheritBuffType, type InheritPointLogItem } from "./defs/API/InheritAction";
import * as JosaUtil from "@/util/JosaUtil";
import { BButton } from "bootstrap-vue-next";
import { unwrap } from "./util/unwrap";
import { add as dateAdd } from 'date-fns';
const inheritanceViewText: Record<InheritanceViewType, { title: string; info: string }> = {
sum: {
@@ -428,7 +427,7 @@ const title = "유산 관리";
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 newPoint = Math.floor(totalPoint - previousPoint);
const result: Record<InheritanceViewType, number> = {
+1 -1
View File
@@ -485,7 +485,7 @@ watch(inheritCity, (newValue: undefined | number) => {
const inheritTurnTimeZone = ref<number>();
const turnTimeZoneList: string[] = (()=>{
const result: string[] = [];
const zoneSec = turnterm; // * 60 / 60
const zoneSec = Math.abs(turnterm); // * 60 / 60
let zoneCur = 0;
for(const idx of range(60)){
const zoneNext = zoneCur + zoneSec;
+9 -2
View File
@@ -276,7 +276,7 @@ declare const staticValues: {
</script>
<script lang="ts" setup>
import addMinutes from "date-fns/esm/addMinutes";
import { addMinutes } from "date-fns/addMinutes";
import { isString, range, trim } from "lodash-es";
import queryString from "query-string";
import { onMounted, ref, watch } from "vue";
@@ -297,6 +297,7 @@ import { QueryActionHelper } from "./util/QueryActionHelper";
import SimpleClock from "./components/SimpleClock.vue";
import type { ReservedCommandResponse } from "./defs/API/Command";
import { unwrap } from "./util/unwrap";
import { VarTurn60 } from "./varTurn60";
defineExpose({
updateCommandTable,
@@ -544,7 +545,13 @@ async function reloadCommandList() {
});
yearMonth += 1;
nextTurnTime = addMinutes(nextTurnTime, result.turnTerm);
if(result.turnTerm == -60){
nextTurnTime = VarTurn60.fromDatetime(nextTurnTime).addTurn(1).toDate();
}
else{
nextTurnTime = addMinutes(nextTurnTime, result.turnTerm);
}
}
serverNow.value = parseTime(result.date);
+10 -3
View File
@@ -256,7 +256,7 @@
</template>
<script lang="ts" setup>
import addMinutes from "date-fns/esm/addMinutes";
import { addMinutes } from "date-fns/addMinutes";
import queryString from "query-string";
import { onMounted, ref, watch, type PropType, inject, type Ref } from "vue";
import { formatTime } from "@util/formatTime";
@@ -282,6 +282,7 @@ import { unwrap_err } from "@/util/unwrap_err";
import type { GameConstStore } from "@/GameConstStore";
import { postFilterNationCommandGen } from "@/utilGame/postFilterNationCommandGen";
import { unwrap } from "@/util/unwrap";
import { VarTurn60 } from "@/varTurn60";
const toasts = unwrap(useToast());
@@ -536,13 +537,19 @@ function updateCommandList() {
...obj,
year,
month,
time: formatTime(nextTurnTime, props.turnTerm >= 5 ? "HH:mm" : "mm:ss"),
time: formatTime(nextTurnTime, Math.abs(props.turnTerm) >= 5 ? "HH:mm" : "mm:ss"),
tooltip: tooltip.length == 0 ? undefined : tooltip.join("\n"),
style,
});
yearMonth += 1;
nextTurnTime = addMinutes(nextTurnTime, props.turnTerm);
if(props.turnTerm == -60){
nextTurnTime = VarTurn60.fromDatetime(nextTurnTime).addTurn(1).toDate();
}
else{
nextTurnTime = addMinutes(nextTurnTime, props.turnTerm);
}
}
reservedCommandList.value = _reservedCommandList;
updated.value = true;
+1 -1
View File
@@ -23,7 +23,7 @@
<AutorunInfo :autorunMode="globalInfo.autorunUser" />
</div>
<div class="s-border-t col py-2 col-8 col-lg-4 subYearMonth">
현재: {{ globalInfo.year }} {{ globalInfo.month }} ({{ globalInfo.turnterm }} 서버)
현재: {{ globalInfo.year }} {{ globalInfo.month }} ({{ globalInfo.turnterm == -60 ? '가변 60' : globalInfo.turnterm }} 서버)
</div>
<div class="s-border-t col py-2 col-4 col-lg-2 subOnlineUserCnt">
전체 접속자 : {{ (globalInfo.onlineUserCnt ?? 0).toLocaleString() }}
+8 -2
View File
@@ -175,8 +175,9 @@ import { clamp } from "lodash-es";
import { formatCityName } from "@/utilGame/formatCityName";
import { isValidObjKey } from "@/utilGame/isValidObjKey";
import { calcInjury } from "@/utilGame/calcInjury";
import { addMinutes } from "date-fns/esm";
import { addMinutes } from "date-fns/addMinutes";
import type { GameIActionInfo } from "@/defs/GameObj";
import { VarTurn60 } from "@/varTurn60";
const imagePath = window.pathConfig.gameImage;
const gameConstStore = unwrap(inject<Ref<GameConstStore>>("gameConstStore"));
const props = defineProps<{
@@ -278,7 +279,12 @@ watch(
() => {
let turnTime = parseTime(general.value.turntime);
if (turnTime.getTime() < props.lastExecuted.getTime()) {
turnTime = addMinutes(turnTime, props.turnTerm);
if(props.turnTerm == -60){
turnTime = VarTurn60.fromDatetime(turnTime).addTurn(1).toDate();
}
else {
turnTime = addMinutes(turnTime, props.turnTerm);
}
}
nextExecuteMinute.value = Math.floor(clamp((turnTime.getTime() - props.lastExecuted.getTime()) / 60000, 0, 999));
},
+1 -1
View File
@@ -127,7 +127,7 @@
<script setup lang="ts">
import type { MsgItem, MsgTarget, MsgType } from "@/defs/API/Message";
import { parseTime } from "@/util/parseTime";
import { differenceInMilliseconds, addMinutes } from "date-fns/esm";
import { addMinutes, differenceInMilliseconds } from "date-fns";
import { computed, onMounted, ref, toRef, watch, type ComputedRef, type Ref } from "vue";
import linkifyStr from "linkify-string";
import { SammoAPI } from "@/SammoAPI";
+1 -1
View File
@@ -93,7 +93,7 @@ $(function () {
const runAnalysis = async function () {
let realKillturn = killturn;
if(autorun_user && autorun_user.limit_minutes){
realKillturn -= autorun_user.limit_minutes / turnterm;
realKillturn -= autorun_user.limit_minutes / Math.abs(turnterm);
}
const $content = $('#on_mover .content');
try {
+1 -1
View File
@@ -147,7 +147,7 @@ const descriptor: NamedRules<InstallFormType> = {
turnterm: {
required: true,
type: "enum",
enum: [1, 2, 5, 10, 20, 30, 60, 120],
enum: [1, 2, 5, 10, 20, 30, 60, 120, -60],
transform: parseInt,
},
sync: {
+3 -3
View File
@@ -6,7 +6,7 @@ import axios from 'axios';
import { convertFormData } from '@util/convertFormData';
import { isBrightColor } from "@util/isBrightColor";
import { unwrap } from '@util/unwrap';
import _, { isError, isString } from 'lodash-es';
import { isError, isString, last, trim } from 'lodash-es';
import { addMinutes } from 'date-fns';
import { parseTime } from '@util/parseTime';
import { formatTime } from '@util/formatTime';
@@ -234,7 +234,7 @@ function redrawMsg(msgResponse: MsgResponse, addFront: boolean): MsgResponse {
if (!msgList || msgList.length == 0) {
continue;
}
const lastMsg = unwrap(_.last(msgList));
const lastMsg = unwrap(last(msgList));
minMsgSeq[msgType] = Math.min(minMsgSeq[msgType], lastMsg.id);
}
return obj;
@@ -605,7 +605,7 @@ function activateMessageForm() {
$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');
const targetMailbox = unwrap_any<string>($mailboxList.val());
-1
View File
@@ -10,7 +10,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 cr_건국 } from "./cr_건국.vue";
import { default as ProcessCity } from "../ProcessCity.vue";
import { default as ProcessGeneralAmount } from "../ProcessGeneralAmount.vue";
@@ -0,0 +1,118 @@
<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,6 +3,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";
@@ -33,6 +34,7 @@ export const commandMap: Record<string, typeof ProcessNation | typeof ProcessCit
che_피장파장,
che_허보: ProcessCity,
cr_인구이동,
che_행동지시,
}
/*
+1 -1
View File
@@ -13,7 +13,7 @@ const intArgs = [
] as const;
const booleanArgs = [
'isGold', 'buyRice',
'isGold', 'buyRice', 'isPull',
] as const;
const integerArrayArgs = [
+7 -1
View File
@@ -1,5 +1,11 @@
import {parseISO} from 'date-fns';
export function parseTime(dateString: string): Date{
return parseISO(dateString);
if(dateString === null){
console.warn('why null');
console.trace();
return new Date();
}
const tmp = parseISO(dateString);
return tmp;
}
+1
View File
@@ -1,4 +1,5 @@
import { clamp } from 'lodash-es';
export function calcTournamentTerm(turnTerm: number): number{
turnTerm = Math.abs(turnTerm);
return clamp(turnTerm, 5, 120);
}
+252
View File
@@ -0,0 +1,252 @@
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);
}
}
+2 -2
View File
@@ -174,7 +174,7 @@ function tryNpmInstall()
tryComposerInstall();
if (tryNpmInstall()) {
genJS(Util::array_last_key(ServConfig::getServerList()));
genJS(array_key_last(ServConfig::getServerList()));
}
$session = Session::requireLogin(null)->setReadOnly();
@@ -227,7 +227,7 @@ if (!$allowFullUpdate || !$target) {
$target = $request['target'];
}
$baseServerName = Util::array_last_key(ServConfig::getServerList());
$baseServerName = array_key_last(ServConfig::getServerList());
if (!$target && $server != $baseServerName) {
Json::die([
+4 -4
View File
@@ -109,16 +109,16 @@ if($expires < $nowDate){
$access_token = $result['access_token'];
$expires = TimeUtil::nowAddSeconds($result['expires_in']);
if(isset($result['refresh_token'])){
$refresh_token = Util::array_get($result['refresh_token']);
$refresh_token = $result['refresh_token'] ?? null;
$refresh_token_expires = TimeUtil::nowAddSeconds($result['refresh_token_expires_in']);
}
}
$signupResult = $restAPI->signup();
$kakaoID = Util::array_get($signupResult['id']);
$kakaoID = $signupResult['id'] ?? null;
if(!$kakaoID && Util::array_get($signupResult['msg'])!='already registered'){
if(!$kakaoID && ($signupResult['msg'] ?? null) !='already registered'){
Json::die([
'result'=>false,
'reason'=>'카카오 로그인 과정 중 앱 연결 절차를 실패했습니다'.Json::encode($signupResult)
@@ -126,7 +126,7 @@ if(!$kakaoID && Util::array_get($signupResult['msg'])!='already registered'){
}
$me = $restAPI->meWithEmail();
$me['code'] = Util::array_get($me['code'], 0);
$me['code'] = $me['code'] ?? 0;
$kakao_account = $me['kakao_account']??[];
if ($me['code']< 0) {
$restAPI->unlink();
+26 -12
View File
@@ -52,7 +52,8 @@
"css-color-names": "^1.0.1",
"css-loader": "^6.7.3",
"cssnano": "^5.1.15",
"date-fns": "^2.29.3",
"date-fns": "^4.1.0",
"date-fns-tz": "^3.2.0",
"denque": "^2.1.0",
"detect-it": "^4.0.1",
"downloadjs": "^1.4.7",
@@ -3535,15 +3536,22 @@
"peer": true
},
"node_modules/date-fns": {
"version": "2.29.3",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.29.3.tgz",
"integrity": "sha512-dDCnyH2WnnKusqvZZ6+jA1O51Ibt8ZMRNkDZdyAyK4YfbDwa/cEmuztzG5pk6hqlp9aSBPYcjOlktquahGwGeA==",
"engines": {
"node": ">=0.11"
},
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/date-fns"
"type": "github",
"url": "https://github.com/sponsors/kossnocorp"
}
},
"node_modules/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==",
"license": "MIT",
"peerDependencies": {
"date-fns": "^3.0.0 || ^4.0.0"
}
},
"node_modules/debug": {
@@ -12089,9 +12097,15 @@
"peer": true
},
"date-fns": {
"version": "2.29.3",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.29.3.tgz",
"integrity": "sha512-dDCnyH2WnnKusqvZZ6+jA1O51Ibt8ZMRNkDZdyAyK4YfbDwa/cEmuztzG5pk6hqlp9aSBPYcjOlktquahGwGeA=="
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg=="
},
"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": {
"version": "4.3.4",
+2 -1
View File
@@ -65,7 +65,8 @@
"css-color-names": "^1.0.1",
"css-loader": "^6.7.3",
"cssnano": "^5.1.15",
"date-fns": "^2.29.3",
"date-fns": "^4.1.0",
"date-fns-tz": "^3.2.0",
"denque": "^2.1.0",
"detect-it": "^4.0.1",
"downloadjs": "^1.4.7",
+375
View File
@@ -0,0 +1,375 @@
#!/usr/bin/env node
/* eslint-disable no-console */
import fs from "node:fs/promises";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
//const __dirname = path.dirname(__filename);
// ============ 환경설정 ============
const REQUIRE_PUBLIC = (process.env.REQUIRE_PUBLIC ?? "true").toLowerCase() === "true";
const FETCH_TIMEOUT_MS = nenv("FETCH_TIMEOUT_MS", 60_000);
const IF_LOCKED_WAIT_MS = nenv("IF_LOCKED_WAIT_MS", 10_000);
const IF_UPDATED_WAIT_MS = nenv("IF_UPDATED_WAIT_MS", 1_000);
const DEFAULT_WAIT_MS = nenv("DEFAULT_WAIT_MS", 8_000);
const BASE_SCAN_DEPTH_ONE = (process.env.BASE_SCAN_DEPTH_ONE ?? "true").toLowerCase() === "true";
const RESCAN_INTERVAL_MS = nenv("RESCAN_INTERVAL_MS", 300_000); // 5분
const SHUTDOWN_TIMEOUT_MS = nenv("SHUTDOWN_TIMEOUT_MS", 15_000);
const AUTO_RESET_JITTER_MS = nenv("AUTO_RESET_JITTER_MS", 0); // 0초 직후 지연(밀리초)
function nenv(key: string, def: number): number {
const v = process.env[key];
if (!v) return def;
const num = Number(v);
return Number.isFinite(num) ? num : def;
}
// ============ 유틸 ============
type Json = Record<string, unknown>;
type ProcResult = {
result: boolean;
updated: boolean;
locked: boolean;
lastExecuted?: string;
};
function nowStr() {
const d = new Date();
const pad = (n: number) => n.toString().padStart(2, "0");
const ms = d.getMilliseconds().toString().padStart(3, "0");
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${ms}`;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function log(...args: any[]) { console.log(nowStr(), ...args); }
async function fileExists(fp: string): Promise<boolean> {
try { await fs.access(fp, fs.constants.F_OK); return true; } catch { return false; }
}
async function readFileSafe(fp: string): Promise<string | null> {
try { return await fs.readFile(fp, "utf8"); } catch { return null; }
}
async function listDirsOnceAsync(base: string): Promise<string[]> {
const out: string[] = [];
const names = await fs.readdir(base);
for (const name of names) {
const p = path.join(base, name);
try { if ((await fs.stat(p)).isDirectory()) out.push(p); } catch { /* empty */ }
}
return out;
}
function joinUrl(base: string, suffix: string): string {
if (base.endsWith("/") && suffix.startsWith("/")) return base + suffix.slice(1);
if (!base.endsWith("/") && !suffix.startsWith("/")) return base + "/" + suffix;
return base + suffix;
}
// 분 0초 정렬 대기 시간 계산: 지금 시각에서 다음 분의 0초(+지터)까지 남은 ms
function msUntilNextMinuteZero(jitterMs = 0): number {
const now = Date.now();
const nextMinuteStart = Math.ceil(now / 60_000) * 60_000;
const target = nextMinuteStart + Math.max(0, jitterMs);
return Math.max(0, target - now);
}
// ============ 경로/루트 URL ============
const basepath = path.dirname(path.dirname(path.resolve(__filename)));
async function parseWebBaseFromCommonPath(base: string): Promise<string> {
const jsPath = path.join(base, "d_shared", "common_path.js");
const text = await readFileSafe(jsPath);
if (!text) { log("[WARN] common_path.js 읽기 실패 → fallback=http://127.0.0.1"); return "http://127.0.0.1"; }
for (const line of text.split(/\r?\n/)) {
if (line.includes("root:")) {
let v = line.slice(line.indexOf("root:") + 5).trim();
v = v.replace(/^[\s,'"`]+/, "").replace(/[\s,'"`,]+$/, "");
if (v) return v;
}
}
log("[WARN] root: 항목 없음 → fallback=http://127.0.0.1");
return "http://127.0.0.1";
}
const webBase = process.env.PUBLIC_CHECK_URL || await parseWebBaseFromCommonPath(basepath);
log("BASEPATH =", basepath);
log("WEBBASE =", webBase);
// ============ 서버 모델 ============
type ServerEntry = {
name: string; // servRelPath
abs: string; // 절대 경로
isHidden: () => Promise<boolean>; // .htaccess 존재 여부
procUrl: string;
autoresetUrl: string;
};
async function scanOnce(): Promise<ServerEntry[]> {
const dirs = await listDirsOnceAsync(basepath); // 깊이는 1단계만
const out: ServerEntry[] = [];
for (const dir of dirs) {
if (BASE_SCAN_DEPTH_ONE === false) {
// 필요하면 확장 로직 배치
}
const dbphp = path.join(dir, "d_setting", "DB.php");
if (!await fileExists(dbphp)) continue;
const name = path.relative(basepath, dir);
const isHidden = () => fileExists(path.join(dir, ".htaccess"));
out.push({
name,
abs: dir,
isHidden,
procUrl: joinUrl(webBase, `/${name}/proc.php`),
autoresetUrl:joinUrl(webBase, `/${name}/j_autoreset.php`),
});
}
return out;
}
// ============ 공개 접근 체크 ============
async function isPublicReachable(signal?: AbortSignal): Promise<boolean> {
if (!REQUIRE_PUBLIC) return true;
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), Math.min(5_000, FETCH_TIMEOUT_MS));
const composite = anySignal([ctrl.signal, signal].filter(Boolean) as AbortSignal[]);
try {
const res = await fetch(webBase, { method: "GET", signal: composite });
if (!res.ok) { log(`[PUBLIC] 응답 ${res.status} → 비공개로 간주`); return false; }
return true;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
if (e?.name !== "AbortError") log(`[PUBLIC] 체크 실패: ${e?.name || e}`);
return false;
} finally {
clearTimeout(timer);
}
}
// ============ HTTP ============
async function httpGetJson<T extends Json>(url: string, outerSignal?: AbortSignal): Promise<T | null> {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
const signal = anySignal([ctrl.signal, outerSignal].filter(Boolean) as AbortSignal[]);
const t0 = performance.now();
try {
const res = await fetch(url, { signal, cache: "no-store" });
const dt = Math.round(performance.now() - t0);
if (!res.ok) { log("HTTPError:", res.status, url); return null; }
try {
const data = (await res.json()) as T;
log(url, `${dt}ms`);
return data;
} catch {
await res.arrayBuffer().catch(() => { /* empty */ });
log("ParseError: JSON 변환 실패", url);
return null;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
if (e?.name !== "AbortError") log(e?.name || "Exception", e?.message || String(e), url);
return null;
} finally {
clearTimeout(timer);
}
}
function anySignal(signals: AbortSignal[]): AbortSignal {
if (signals.length === 1) return signals[0];
const ctrl = new AbortController();
for (const s of signals) {
if (s.aborted) { ctrl.abort(); break; }
s.addEventListener("abort", () => ctrl.abort(), { once: true });
}
return ctrl.signal;
}
// ============ 서버 러너 ============
class ServerRunner {
#entry: ServerEntry;
#task?: Promise<void>;
#stopCtrl = new AbortController();
#stopped = false;
#lastAutoResetAt = 0;
constructor(entry: ServerEntry) {
this.#entry = entry;
}
name() { return this.#entry.name; }
start() {
if (!this.#task) {
log(`[${this.name()}] 루프 시작`);
this.#task = this.#run();
}
return this.#task;
}
async stop(): Promise<void> {
if (this.#stopped) return;
this.#stopped = true;
this.#stopCtrl.abort();
try { await this.#task; } catch { /* empty */ }
log(`[${this.name()}] 루프 종료`);
}
async #run() {
while (!this.#stopCtrl.signal.aborted) {
try {
// 공개 접근 체크
const pub = await isPublicReachable(this.#stopCtrl.signal);
if (!pub) { await delay(15_000, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ }); continue; }
const hidden = await this.#entry.isHidden();
if (hidden) {
// ★ 매 분 0초에 맞춰 호출
const waitMs = msUntilNextMinuteZero(AUTO_RESET_JITTER_MS);
if (waitMs > 0) {
// 신호 안전하게 대기
await delay(waitMs, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
if (this.#stopCtrl.signal.aborted) break;
}
log(`[${this.name()}] 닫힘 - (정렬) autoreset 호출 @ mm:00${AUTO_RESET_JITTER_MS ? `+${AUTO_RESET_JITTER_MS}ms` : ""}`);
await httpGetJson<Json>(this.#entry.autoresetUrl, this.#stopCtrl.signal);
// 같은 분에 중복 호출 방지: 0초 직후 잠깐 쉬고 다음 루프는 자연스럽게 다음 분으로 정렬됨
await delay(200, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
continue;
}
// 열림: proc
const data = await httpGetJson<ProcResult>(this.#entry.procUrl, this.#stopCtrl.signal);
if (!data) {
await delay(IF_LOCKED_WAIT_MS, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
continue;
}
if (data.result === false || data.locked === true) {
log(`[${this.name()}] result=${data.result} locked=${data.locked}${IF_LOCKED_WAIT_MS}ms 대기`);
await delay(IF_LOCKED_WAIT_MS, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
continue;
}
if (data.updated === true) {
log(`[${this.name()}] updated=true → ${IF_UPDATED_WAIT_MS}ms 후 재호출 (last=${data.lastExecuted ?? "-"})`);
await delay(IF_UPDATED_WAIT_MS, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
continue;
}
await delay(DEFAULT_WAIT_MS, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
if (this.#stopCtrl.signal.aborted) break;
log(`[${this.name()}] 루프 예외:`, e?.message || String(e));
await delay(5_000, undefined, { signal: this.#stopCtrl.signal }).catch(() => { /* empty */ });
}
}
}
}
// ============ 매니저: 재스캔 & 종료 ============
class DaemonManager {
#runners = new Map<string, ServerRunner>();
#rescanCtrl = new AbortController();
async start() {
log("턴 데몬 시작");
await this.#rescanOnce(); // 초기 스캔
this.#scheduleRescan(); // 주기적 재스캔
}
async shutdown(timeoutMs = SHUTDOWN_TIMEOUT_MS) {
log("[SHUTDOWN] 신호 수신 → 종료 절차 시작");
this.#rescanCtrl.abort();
const stops: Promise<void>[] = [];
for (const r of this.#runners.values()) stops.push(r.stop());
// 타임아웃 대기
const done = Promise.allSettled(stops);
const timeout = delay(timeoutMs).then(() => { throw new Error("Shutdown timeout"); });
try { await Promise.race([done, timeout]); }
catch { log("[SHUTDOWN] 타임아웃 도달 → 강제 종료"); }
log("[SHUTDOWN] 종료 완료");
}
#scheduleRescan() {
// 반복 타이머(AbortSignal과 함께)
const loop = async () => {
while (!this.#rescanCtrl.signal.aborted) {
await delay(RESCAN_INTERVAL_MS, undefined, { signal: this.#rescanCtrl.signal }).catch(() => { /* empty */ });
if (this.#rescanCtrl.signal.aborted) break;
try { await this.#rescanOnce(); }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
catch (e: any) { log("[RESCAN] 예외:", e?.message || String(e)); }
}
};
loop().catch(() => { /* empty */ });
}
async #rescanOnce() {
const entries = await scanOnce();
log(`[RESCAN] 서버 ${entries.length}개 발견`);
// 추가/갱신/삭제 판정
const seen = new Set<string>();
for (const e of entries) {
seen.add(e.name);
if (!this.#runners.has(e.name)) {
// 신규 서버
const runner = new ServerRunner(e);
this.#runners.set(e.name, runner);
runner.start().catch(() => { /* empty */ });
log(`[RESCAN] 추가: ${e.name}`);
} else {
// 이미 러너 있음 → 경로/URL 변경 가능성 거의 없지만, 필요시 갱신 로직 여기에
}
}
// 사라진 서버 중지
for (const name of Array.from(this.#runners.keys())) {
if (!seen.has(name)) {
log(`[RESCAN] 제거: ${name}`);
const r = this.#runners.get(name);
if (!r) continue;
this.#runners.delete(name);
r.stop().catch(() => { /* empty */ });
}
}
}
}
// ============ 메인 ============
const manager = new DaemonManager();
async function main() {
// 신호 처리: SIGINT/SIGTERM → graceful shutdown
const onSignal = async (sig: NodeJS.Signals) => {
log(`[SIGNAL] ${sig} 수신`);
// 중복 호출 방지
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.off("SIGINT", onSignal as any);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.off("SIGTERM", onSignal as any);
await manager.shutdown().catch(() => { /* empty */ });
process.exit(0);
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.on("SIGINT", onSignal as any);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
process.on("SIGTERM", onSignal as any);
await manager.start();
}
main().catch((e) => {
log("치명적 예외:", e);
process.exitCode = 1;
});
+1 -1
View File
@@ -272,7 +272,7 @@ class Session
return $this;
}
$turnterm = $gameStor->turnterm;
$turnterm = abs($gameStor->turnterm);
$isUnited = $gameStor->isunited != 0;
$generalID = $general['no'];
+4 -4
View File
@@ -88,9 +88,9 @@ class Setting
$tail = new FileTail($this->versionFile);
$version = 'noVersionJson';
foreach ($tail->smart(5, 100, true) as $line) {
if (Util::starts_with($line, '//{')) {
if (str_starts_with($line, '//{')) {
$version = Json::decode(substr($line, 2));
$version = Util::array_get($version['version'], 'noVersionValue');
$version = $version['version'] ?? 'noVersionValue';
break;
}
}
@@ -106,8 +106,8 @@ class Setting
$templates = new \League\Plates\Engine(__DIR__.'/templates');
//TODO: .htaccess가 서버 오픈에도 사용될 수 있으니 별도의 방법이 필요함
$allow_ip = Util::get_client_ip(false);
if (Util::starts_with($allow_ip, '192.168.') ||
Util::starts_with($allow_ip, '10.')) {
if (str_starts_with($allow_ip, '192.168.') ||
str_starts_with($allow_ip, '10.')) {
//172.16~172.31은 코딩하기 귀찮으니까 안할거다
$allow_ip = Util::get_client_ip(true);
}
+107 -1
View File
@@ -3,7 +3,7 @@ namespace sammo;
use Iterator;
class Util extends \utilphp\util
class Util
{
/**
@@ -889,4 +889,110 @@ class Util extends \utilphp\util
}
return join('|', $result);
}
/**
* http://github.com/brandonwamboldt/utilphp/ 구버전 코드에서 이식함
* 일부 코드는 수정
* 해당 라이선스: MIT
*/
/**
* Returns the first element in an array.
* PHP 8.5부터 array_first 사용 가능
*
* @param array $array
* @return mixed
*/
public static function array_first(array $array)
{
return $array[array_key_first($array)];
}
/**
* Returns the last element in an array.
* PHP 8.5부터 array_last 사용 가능
*
* @param array $array
* @return mixed
*/
public static function array_last(array $array)
{
return $array[array_key_last($array)];
}
/**
* Flatten a multi-dimensional array into a one dimensional array.
*
* Contributed by Theodore R. Smith of PHP Experts, Inc. <http://www.phpexperts.pro/>
*
* @param array $array The array to flatten
* @param boolean $preserve_keys Whether or not to preserve array keys.
* Keys from deeply nested arrays will
* overwrite keys from shallowy nested arrays
* @return array
*/
public static function array_flatten(array $array, $preserve_keys = true)
{
$flattened = array();
array_walk_recursive($array, function($value, $key) use (&$flattened, $preserve_keys) {
if ($preserve_keys && !is_int($key)) {
$flattened[$key] = $value;
} else {
$flattened[] = $value;
}
});
return $flattened;
}
/**
* Returns the IP address of the client.
*
* @param boolean $trust_proxy_headers Whether or not to trust the
* proxy headers HTTP_CLIENT_IP
* and HTTP_X_FORWARDED_FOR. ONLY
* use if your server is behind a
* proxy that sets these values
* @return string
*/
public static function get_client_ip($trust_proxy_headers = false)
{
if (!$trust_proxy_headers) {
return $_SERVER['REMOTE_ADDR'];
}
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
/**
* Access an array index, retrieving the value stored there if it
* exists or a default if it does not. This function allows you to
* concisely access an index which may or may not exist without
* raising a warning.
*
* @deprecated PHP 7.0 이상에서는 null 병합 연산자 사용을 권장
*
* @param array $var Array value to access
* @param mixed $default Default value to return if the key is not
* present in the array
* @return mixed
*/
public static function array_get(&$var, $default = null)
{
if (isset($var)) {
return $var;
}
return $default;
}
};
+2 -1
View File
@@ -81,7 +81,8 @@
},
"include": [
"hwe/ts/**/*",
"hwe/ts/**/*.vue"
"hwe/ts/**/*.vue",
"src/*.ts",
],
"exclude": [
"**/*.test.ts"