Compare commits

..
Author SHA1 Message Date
Hide_D 136acadd04 fix: keep scenario war specials in war slot 2026-08-04 01:55:13 +00:00
116 changed files with 732 additions and 2415 deletions
+2 -5
View File
@@ -13,9 +13,6 @@ $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$turntime, $tnmt_time] = $gameStor->getValuesAsArray(['turntime','tnmt_time']);
$clock = GameClock::fromStorage($gameStor);
$turntimeDisplay = $clock->formatTick(Util::toInt($turntime), true);
$tnmtTimeDisplay = $tnmt_time === null ? '-' : $clock->formatTick(Util::toInt($tnmt_time), true);
$plock = $db->queryFirstField('SELECT plock FROM plock WHERE `type` ="GAME"');
?>
@@ -33,8 +30,8 @@ $plock = $db->queryFirstField('SELECT plock FROM plock WHERE `type` ="GAME"');
</head>
<body>
<form action=_119_b.php method=post>
시간조정 : <input type=text size=3 name=minute><input type=submit name=btn value='분당김'><input type=submit name=btn value='분지연'> 최종갱신 : <?=$turntimeDisplay?> (tick <?=$turntime?>)<br>
시간조정 : <input type=text size=3 name=minute2><input type=submit name=btn value='토너분당김'><input type=submit name=btn value='토너분지연'> 토너먼트 : <?=$tnmtTimeDisplay?> (tick <?=$tnmt_time?>)<br>
시간조정 : <input type=text size=3 name=minute><input type=submit name=btn value='분당김'><input type=submit name=btn value='분지연'> 최종갱신 : <?=$turntime?><br>
시간조정 : <input type=text size=3 name=minute2><input type=submit name=btn value='토너분당김'><input type=submit name=btn value='토너분지연'> 토너먼트 : <?=$tnmt_time?><br>
봉급지급 : <input type=submit name=btn value='금지급'><input type=submit name=btn value='쌀지급'><br>
락 풀 기 : <input type=submit name=btn value='락걸기'><input type=submit name=btn value='락풀기'> 현재 : <?=$plock>0?"동결중":"가동중"?><br>
</form>
+36 -9
View File
@@ -38,9 +38,21 @@ switch ($btn) {
usleep(500000);
}
$clock = GameClock::fromStorage($gameStor);
// 스케줄 전체를 벽시계에서 빼지 않고 논리 현재 tick만 앞으로 이동합니다.
$clock->advance($gameStor, $clock->ticksFromMinutes($minute));
$gameStor->cacheValues(['turntime', 'starttime', 'tnmt_time']);
$turntime = (new \DateTimeImmutable($gameStor->turntime))->sub(new \DateInterval("PT{$minute}M"));
$starttime = (new \DateTimeImmutable($gameStor->starttime))->sub(new \DateInterval("PT{$minute}M"));
$tnmt_time = (new \DateTimeImmutable($gameStor->tnmt_time))->sub(new \DateInterval("PT{$minute}M"));
$gameStor->turntime = $turntime->format('Y-m-d H:i:s.u');
$gameStor->starttime = $starttime->format('Y-m-d H:i:s');
$gameStor->tnmt_time = $tnmt_time->format('Y-m-d H:i:s');
$db->update('general', [
'turntime' => $db->sqleval('DATE_SUB(turntime, INTERVAL %i MINUTE)', $minute)
], true);
$db->update('ng_auction', [
'close_date' => $db->sqleval('DATE_SUB(close_date, INTERVAL %i MINUTE)', $minute)
], 'finished = 0');
if ($locked) {
unlock();
}
@@ -54,19 +66,34 @@ switch ($btn) {
}
usleep(500000);
}
$clock = GameClock::fromStorage($gameStor);
$clock->advance($gameStor, -$clock->ticksFromMinutes($minute));
$gameStor->cacheValues(['turntime', 'starttime', 'tnmt_time']);
$turntime = (new \DateTimeImmutable($gameStor->turntime))->add(new \DateInterval("PT{$minute}M"));
$starttime = (new \DateTimeImmutable($gameStor->starttime))->add(new \DateInterval("PT{$minute}M"));
$tnmt_time = (new \DateTimeImmutable($gameStor->tnmt_time))->add(new \DateInterval("PT{$minute}M"));
$gameStor->turntime = $turntime->format('Y-m-d H:i:s.u');
$gameStor->starttime = $starttime->format('Y-m-d H:i:s');
$gameStor->tnmt_time = $tnmt_time->format('Y-m-d H:i:s');
$db->update('general', [
'turntime' => $db->sqleval('DATE_ADD(turntime, INTERVAL %i MINUTE)', $minute)
], true);
$db->update('ng_auction', [
'close_date' => $db->sqleval('DATE_ADD(close_date, INTERVAL %i MINUTE)', $minute)
], 'finished = 0');
if ($locked) {
unlock();
}
break;
case "토너분당김":
$clock = GameClock::fromStorage($gameStor);
$gameStor->tnmt_time = Util::toInt($gameStor->tnmt_time) - $clock->ticksFromMinutes($minute2);
$tnmt_time = new \DateTime($gameStor->tnmt_time);
$tnmt_time->sub(new \DateInterval("PT{$minute2}M"));
$gameStor->tnmt_time = $tnmt_time->format('Y-m-d H:i:s');
break;
case "토너분지연":
$clock = GameClock::fromStorage($gameStor);
$gameStor->tnmt_time = Util::toInt($gameStor->tnmt_time) + $clock->ticksFromMinutes($minute2);
$tnmt_time = new \DateTimeImmutable($gameStor->tnmt_time);
$tnmt_time->add(new \DateInterval("PT{$minute2}M"));
$gameStor->tnmt_time = $tnmt_time->format('Y-m-d H:i:s');
break;
case "금지급":
processGoldIncome();
+2 -2
View File
@@ -40,7 +40,7 @@ $admin = getAdmin();
</tr>
<tr>
<td width=110 align=right>시작시간변경</td>
<td width=285><input type=text size=20 maxlength=20 style=color:white;background-color:black;text-align:right; name=starttime value='<?=substr($admin['starttime_display'], 0, 19)?>'><input type=submit name=btn value=변경1></td>
<td width=285><input type=text size=20 maxlength=20 style=color:white;background-color:black;text-align:right; name=starttime value='<?=substr($admin['starttime'], 0, 19)?>'><input type=submit name=btn value=변경1></td>
</tr>
<tr>
<td width=110 align=right>최대 장수</td>
@@ -52,7 +52,7 @@ $admin = getAdmin();
<td width=110 align=right>시작 년도</td>
<td width=285><input type=text size=3 maxlength=3 style=color:white;background-color:black;text-align:right; name=startyear value='<?=$admin['startyear']?>'><input type=submit name=btn value=변경4></td>
<td width=110 align=right>최근 갱신 시간</td>
<td width=285>&nbsp;<?=$admin['turntime_display']?> (tick <?=$admin['turntime']?>)</td>
<td width=285>&nbsp;<?=$admin['turntime']?></td>
</tr>
<tr>
<td width=110 align=right>턴시간</td>
+3 -9
View File
@@ -25,15 +25,13 @@ if (!$v->validate()) {
$msg = Util::getPost('msg');
$btn = Util::getPost('btn');
$log = Util::getPost('log');
$starttime = Util::getPost('starttime', 'string', null);
$starttime = Util::getPost('starttime', 'string', (new \DateTime())->format('Y-m-d H:i:s'));
$maxgeneral = Util::getPost('maxgeneral', 'int', GameConst::$defaultMaxGeneral);
$maxnation = Util::getPost('maxnation', 'int', GameConst::$defaultMaxNation);
$startyear = Util::getPost('startyear', 'int', GameConst::$defaultStartYear);
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$starttime ??= $clock->formatTick($clock->nowTick());
$admin = getAdmin();
@@ -45,11 +43,7 @@ switch ($btn) {
pushGlobalHistoryLog(["<R>★</><S>{$log}</>"]);
break;
case "변경1":
$gameStor->clock_base_time = TimeUtil::format(GameClock::baseTimeForProjection(
new \DateTimeImmutable($starttime),
Util::toInt($gameStor->starttime),
$clock->getTurnTermMinutes(),
), true);
$gameStor->starttime = (new \DateTime($starttime))->format('Y-m-d H:i:s');
break;
case "변경2":
$gameStor->maxgeneral = $maxgeneral;
@@ -84,4 +78,4 @@ switch ($btn) {
break;
}
header('location:_admin1.php');
header('location:_admin1.php');
+9 -9
View File
@@ -99,7 +99,7 @@ switch ($btn) {
], '`no` IN %li', $genlist);
break;
case "강제 사망":
$date = GameClock::fromStorage($gameStor)->nowTick();
$date = TimeUtil::now(true);
$db->update('general', [
'killturn' => 0,
'turntime' => $date,
@@ -113,7 +113,7 @@ switch ($btn) {
case "경험치1000":
$text = $btn . " 지급!";
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
$db->update('general', [
@@ -124,7 +124,7 @@ switch ($btn) {
case "공헌치1000":
$text = $btn . " 지급!";
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
$db->update('general', [
@@ -135,7 +135,7 @@ switch ($btn) {
case "보숙10000":
$text = "보병숙련도+10000 지급!";
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
$db->update('general', [
@@ -145,7 +145,7 @@ switch ($btn) {
case "궁숙10000":
$text = "궁병숙련도+10000 지급!";
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
$db->update('general', [
@@ -156,7 +156,7 @@ switch ($btn) {
$src = MessageTarget::buildQuick($session->generalID);
$text = "기병숙련도+10000 지급!";
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
$db->update('general', [
@@ -167,7 +167,7 @@ switch ($btn) {
$src = MessageTarget::buildQuick($session->generalID);
$text = "귀병숙련도+10000 지급!";
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
$db->update('general', [
@@ -178,7 +178,7 @@ switch ($btn) {
$src = MessageTarget::buildQuick($session->generalID);
$text = "차병숙련도+10000 지급!";
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
$db->update('general', [
@@ -198,7 +198,7 @@ switch ($btn) {
case "메세지 전달":
$text = $msg ?? '';
foreach ($genlist as $generalID) {
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, Message::gameNow(), new \DateTime('9999-12-31'), []);
$msg = new Message(MessageType::private, $src, MessageTarget::buildQuick($generalID), $text, new \DateTime(), new \DateTime('9999-12-31'), []);
$msg->send(true);
}
break;
+2 -3
View File
@@ -42,7 +42,6 @@ if ($session->userGrade < 6) {
}
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
if ($btn == '정렬하기') {
$gen = 0;
@@ -112,7 +111,7 @@ $generalObj = General::createObjFromDB($gen, null, GeneralQueryMode::FullWithAcc
대상장수 :
<select name=gen size=1>
<?php foreach ($generalBasicList as $general) : ?>
<option <?= $gen == $general['no'] ? 'selected' : '' ?> value='<?= $general['no'] ?>'><?= $general['name'] ?> (<?= substr($clock->formatTick(Util::toInt($general['turntime'])), 14, 5) ?>)</option>
<option <?= $gen == $general['no'] ? 'selected' : '' ?> value='<?= $general['no'] ?>'><?= $general['name'] ?> (<?= substr($general['turntime'], 14, 5) ?>)</option>
<?php endforeach; ?>
</select>
<input type=submit name=btn value='조회하기'>
@@ -180,4 +179,4 @@ $generalObj = General::createObjFromDB($gen, null, GeneralQueryMode::FullWithAcc
</table>
</body>
</html>
</html>
+3 -1
View File
@@ -100,6 +100,8 @@ $sel[$type] = "selected";
throw new \Exception("알 수 없는 외교 상태: {$dip['state']}");
}
$date = TimeUtil::now();
echo "
<tr>
<td align=center style=color:" . newColor($nationColor[$me]) . ";background-color:{$nationColor[$me]};>$nationName[$me]</td>
@@ -120,4 +122,4 @@ $sel[$type] = "selected";
</table>
</body>
</html>
</html>
+1 -2
View File
@@ -9,7 +9,6 @@ include "func.php";
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
increaseRefresh("갱신정보", 1);
@@ -24,7 +23,7 @@ $recentTraffic[] = [
'month' => $admin['month'],
'refresh' => $admin['refresh'],
'online' => $curonline,
'date' => $clock->formatNow()
'date' => TimeUtil::now()
];
if ($admin['maxrefresh'] == 0) {
+2 -2
View File
@@ -16,7 +16,7 @@ $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
increaseRefresh("현재도시", 1);
$lastExecute = substr(GameClock::fromStorage($gameStor)->formatTick(Util::toInt($gameStor->turntime)), 5, 14);
$lastExecute = substr($gameStor->turntime, 5, 14);
$me = $db->queryFirstRow('SELECT no,nation,officer_level,city from general where owner=%i', $userID);
$myNation = $db->queryFirstRow('SELECT nation,level,spy FROM nation WHERE nation=%i', $me['nation']) ?? [
@@ -537,4 +537,4 @@ $templates = new \League\Plates\Engine('templates');
</table>
</body>
</html>
</html>
+1 -3
View File
@@ -129,7 +129,6 @@ $templates = new \League\Plates\Engine('templates');
);
$generalTurnList = [];
$clock = GameClock::fromStorage($gameStor);
foreach ($db->queryAllLists(
'SELECT general_id, turn_idx, brief FROM general_turn WHERE general_id IN %li AND turn_idx < 5 ORDER BY general_id ASC, turn_idx ASC',
@@ -143,7 +142,6 @@ $templates = new \League\Plates\Engine('templates');
$genCntEff = 0;
foreach ($generals as &$general) {
$general['turntime'] = $clock->formatTick(Util::toInt($general['turntime']), true);
$general['cityText'] = CityConst::byID($general['city'])->name;
$general['troopText'] = $troopName[$general['troop']] ?? '-';
@@ -286,4 +284,4 @@ $templates = new \League\Plates\Engine('templates');
</table>
</body>
</html>
</html>
+8 -12
View File
@@ -19,10 +19,8 @@ $userID = Session::getUserID();
$generalID = $session->generalID;
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->cacheValues(['turntime', 'opentime', 'autorun_user', 'npcmode']);
$clock = GameClock::fromStorage($gameStor);
$nowTick = $clock->nowTick();
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->cacheValues(['turntime', 'opentime', 'autorun_user', 'npcmode']);
$me = General::createObjFromDB($generalID, null, GeneralQueryMode::FullWithAccessLog);
@@ -42,29 +40,27 @@ $lastRefresh = $db->queryFirstField(
);
$nextChange = $me->getAuxVar('next_change');
if (!is_int($nextChange)) {
if (!is_string($nextChange) || $nextChange === '') {
$nextChange = null;
}
$nextChangeDisplay = $nextChange === null ? null : $clock->formatTick($nextChange);
increaseRefresh("내정보", 1);
if ($gameStor->turntime <= $gameStor->opentime) {
$targetTime = $me->getAuxVar('prestart_delete_after');
if (!is_int($targetTime)) {
if (!is_string($targetTime) || $targetTime === '') {
$targetTime = addTurn(
$lastRefresh === null ? $nowTick : Util::toInt($lastRefresh),
$lastRefresh ?: TimeUtil::now(),
$gameStor->turnterm,
GameConst::$minTurnDieOnPrestart
);
$me->setAuxVar('prestart_delete_after', $targetTime);
$me->applyDB($db);
}
$targetTimeDisplay = $clock->formatTick($targetTime);
//서버 가오픈시 할 수 있는 행동
if ($me->getNPCType() == 0 && $me->getNationID() == 0) {
$showDieOnPrestartBtn = true;
if ($targetTime <= $nowTick) {
if ($targetTime <= TimeUtil::now()) {
$availableDieOnPrestart = true;
}
}
@@ -177,7 +173,7 @@ $changeDefence999Atmos = $me->onCalcDomestic('changeDefenceTrain', "atmos999", $
<a href="b_myPage.php?detachNPC=1"><button type="button" style=background-color:<?= GameConst::$basecolor2 ?>;color:white;width:160px;height:30px;font-size:14px;>빙의 해체 요청</button></a>-->
<?php if ($showDieOnPrestartBtn) : ?>
가오픈 기간 내 장수 삭제 (<?= $targetTimeDisplay ?> 부터)<br>
가오픈 기간 내 장수 삭제 (<?= substr($targetTime, 0, 19) ?> 부터)<br>
<button type="button" id='dieOnPrestart' style=background-color:<?= GameConst::$basecolor2 ?>;color:white;width:160px;height:30px;font-size:14px;>장수 삭제</button><br><br>
<?php endif; ?>
@@ -192,7 +188,7 @@ $changeDefence999Atmos = $me->onCalcDomestic('changeDefenceTrain', "atmos999", $
<?php endif; ?>
<?php if ($gameStor->npcmode == 2 && $me->getNPCType() == 0) : ?>
다른 장수 선택 (<?= $nextChangeDisplay ?? '지금' ?>부터)<br>
다른 장수 선택 (<?= $nextChange ? substr($nextChange, 0, 19) : '지금' ?>부터)<br>
<a href="select_general_from_pool.php" id='select_general_from_pool'><button type="button" style=background-color:<?= GameConst::$basecolor2 ?>;color:white;width:160px;height:30px;font-size:14px;>다른 장수 선택</button></a><br><br>
<?php endif; ?>
+3 -3
View File
@@ -228,10 +228,10 @@ if($btn == "자동개최설정") {
$phase = 0;
startBetting($admin['tnmt_type'], 720);
} elseif($btn == "베팅마감") {
$clock = GameClock::fromStorage($gameStor);
$dt = date("Y-m-d H:i:s", time() + 60);
$gameStor->tournament=7;
$gameStor->phase=0;
$gameStor->tnmt_time = $clock->nowTick() + $clock->ticksFromSeconds(60);
$gameStor->tnmt_time = $dt;
} elseif($btn == "16강") {
finalFight($admin['tnmt_type'], $admin['tournament'], $admin['phase'], 16);
} elseif($btn == "8강") {
@@ -248,4 +248,4 @@ if($btn == "자동개최설정") {
$gameStor->tnmt_msg = $msg;
}
header('location:b_tournament.php');
header('location:b_tournament.php');
+119 -115
View File
@@ -630,11 +630,7 @@ function generalInfo(General $generalObj)
$injury = "건강";
}
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$remaining = max(0, intdiv(
$generalObj->getTurnTick() - $clock->nowTick(),
$clock->ticksFromMinutes(1),
));
$remaining = (new \DateTimeImmutable($generalObj->getTurnTime()))->diff(new \DateTimeImmutable())->i;
if ($nation['color'] == "") {
$nation['color'] = "#000000";
@@ -925,37 +921,45 @@ function banner()
);
}
function addTurn(int $tick, int $turnterm, int $turn = 1, bool $withFraction = true): int
{
return $tick + GameClock::TICKS_PER_TURN * $turn;
}
function subTurn(int $tick, int $turnterm, int $turn = 1, bool $withFraction = true): int
{
return $tick - GameClock::TICKS_PER_TURN * $turn;
}
function cutTurn(int $tick, int $turnterm, bool $withFraction = true): int
{
$remainder = $tick % GameClock::TICKS_PER_TURN;
if ($remainder < 0) {
$remainder += GameClock::TICKS_PER_TURN;
}
return $tick - $remainder;
}
/** 시나리오 초기화 입력인 벽시계를 기존 01:00 기준 월 경계로 정렬합니다. */
function cutTurnDateTime(string $date, int $turnterm, bool $withFraction = true): string
{
$dateObj = new \DateTime($date);
$baseDate = new \DateTime($dateObj->format('Y-m-d'));
$baseDate->sub(new \DateInterval('P1D'));
$baseDate->add(new \DateInterval('PT1H'));
$diffMin = intdiv($dateObj->getTimestamp() - $baseDate->getTimestamp(), 60);
$diffMin -= $diffMin % $turnterm;
$baseDate->add(new \DateInterval("PT{$diffMin}M"));
return $baseDate->format($withFraction ? 'Y-m-d H:i:s.u' : 'Y-m-d H:i:s');
}
function addTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
{
$date = new \DateTime($date);
$target = $turnterm * $turn;
$date->add(new \DateInterval("PT{$target}M"));
if ($withFraction) {
return $date->format('Y-m-d H:i:s.u');
}
return $date->format('Y-m-d H:i:s');
}
function subTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
{
$date = new \DateTime($date);
$target = $turnterm * $turn;
$date->sub(new \DateInterval("PT{$target}M"));
if ($withFraction) {
return $date->format('Y-m-d H:i:s.u');
}
return $date->format('Y-m-d H:i:s');
}
function cutTurn($date, int $turnterm, bool $withFraction = true)
{
$date = new \DateTime($date);
$baseDate = new \DateTime($date->format('Y-m-d'));
$baseDate->sub(new \DateInterval("P1D"));
$baseDate->add(new \DateInterval("PT1H"));
$diffMin = intdiv($date->getTimeStamp() - $baseDate->getTimeStamp(), 60);
$diffMin -= $diffMin % $turnterm;
$baseDate->add(new \DateInterval("PT{$diffMin}M"));
if ($withFraction) {
return $baseDate->format('Y-m-d H:i:s.u');
}
return $baseDate->format('Y-m-d H:i:s');
}
function cutDay($date, int $turnterm, bool $withFraction = true)
{
@@ -997,9 +1001,11 @@ function increaseRefresh($type = "", $cnt = 1)
$generalID = $session->generalID;
$userGrade = $session->userGrade;
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$date = GameClock::fromStorage($gameStor)->nowTick();
$dateObj = new \DateTimeImmutable();
$date = TimeUtil::format($dateObj, false);
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$isunited = $gameStor->isunited;
$opentime = $gameStor->opentime;
@@ -1082,12 +1088,12 @@ function updateTraffic()
if(count($recentTraffic) >= 5){
array_shift($recentTraffic);
}
$recentTraffic[] = [
$recentTraffic[] = [
'year'=>$admin['year'],
'month' => $admin['month'],
'refresh' => $admin['refresh'],
'online' => $online,
'date' => GameClock::fromStorage($gameStor)->formatNow(),
'date' => TimeUtil::now(),
];
$gameStor->recentTraffic = $recentTraffic;
@@ -1139,19 +1145,18 @@ function unlock(): bool
return $db->affectedRows() > 0;
}
function timeover(): bool
function timeover(): bool
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
list($turnterm, $turntime) = $gameStor->getValuesAsArray(['turnterm', 'turntime']);
$clock = GameClock::fromStorage($gameStor);
$diff = $clock->nowTick() - Util::toInt($turntime);
list($turnterm, $turntime) = $gameStor->getValuesAsArray(['turnterm', 'turntime']);
$diff = (new \DateTime())->getTimestamp() - (new \DateTime($turntime))->getTimestamp();
$t = min($turnterm, 5);
$term = $clock->ticksFromSeconds($t);
if ($diff >= $term || $diff < 0) {
$term = $diff;
if ($term >= $t || $term < 0) {
return true;
} else {
return false;
@@ -1164,8 +1169,9 @@ function checkDelay()
$gameStor = KVStorage::getStorage($db, 'game_env');
//서버정보
$clock = GameClock::fromStorage($gameStor);
$timeMinDiff = intdiv($clock->nowTick() - Util::toInt($gameStor->turntime), $clock->ticksFromMinutes(1));
$now = new \DateTimeImmutable();
$turntime = new \DateTimeImmutable($gameStor->turntime);
$timeMinDiff = intdiv($now->getTimestamp() - $turntime->getTimestamp(), 60);
// 1턴이상 갱신 없었으면 서버 지연
$term = $gameStor->turnterm;
@@ -1179,17 +1185,20 @@ function checkDelay()
//지연 해야할 밀린 턴 횟수
$iter = intdiv($timeMinDiff, $term);
if ($iter > $threshold) {
$minute = $iter * $term;
$delayTick = $clock->ticksFromMinutes($minute);
$gameStor->turntime = Util::toInt($gameStor->turntime) + $delayTick;
$gameStor->starttime = Util::toInt($gameStor->starttime) + $delayTick;
$db->update('general', [
'turntime' => $db->sqleval('turntime + %i', $delayTick)
], true);
$db->update('ng_auction', [
'close_tick' => $db->sqleval('close_tick + %i', $delayTick)
], 'finished = 0');
$minute = $iter * $term;
$newTurntime = $turntime->add(new \DateInterval("PT{$minute}M"));
$newNextTurntime = $turntime->add(new \DateInterval("PT{$term}M"));
$gameStor->turntime = $newTurntime->format('Y-m-d H:i:s');
$gameStor->starttime = (new \DateTimeImmutable($gameStor->starttime))
->add(new \DateInterval("PT{$minute}M"))
->format('Y-m-d H:i:s');
$db->update('general', [
'turntime' => $db->sqleval('DATE_ADD(turntime, INTERVAL %i MINUTE)', $minute)
], 'turntime<=DATE_ADD(turntime, INTERVAL %i MINUTE)', $term);
$db->update('ng_auction', [
'close_date' => $db->sqleval('DATE_ADD(close_date, INTERVAL %i MINUTE)', $minute)
], 'finished = 0');
}
}
@@ -1238,15 +1247,17 @@ function updateOnline()
$gameStor->online_nation = join(', ', $onlineNation);
}
function turnDate($curtime)
function turnDate($curtime)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getValues(['startyear', 'starttime', 'turnterm', 'year', 'month']);
$turn = $admin['starttime'];
$curturn = cutTurn(Util::toInt($curtime), $admin['turnterm']);
$num = intdiv($curturn - Util::toInt($turn), GameClock::TICKS_PER_TURN);
$curturn = cutTurn($curtime, $admin['turnterm']);
$term = $admin['turnterm'];
$num = intdiv((strtotime($curturn) - strtotime($turn)), $term * 60);
$date = $admin['startyear'] * 12;
$date += $num;
@@ -1376,14 +1387,12 @@ function CheckHall($no)
return;
}
$clock = GameClock::fromStorage($gameStor);
$unitedDate = $clock->formatTick($clock->nowTick());
$unitedDate = TimeUtil::now();
$nation = $generalObj->getStaticNation();
$serverCnt = $db->queryFirstField('SELECT count(*) FROM ng_games');
[$scenarioIdx, $scenarioName, $startTick] = $gameStor->getValuesAsArray(['scenario', 'scenario_text', 'starttime']);
$startTime = $clock->formatTick(Util::toInt($startTick));
[$scenarioIdx, $scenarioName, $startTime] = $gameStor->getValuesAsArray(['scenario', 'scenario_text', 'starttime']);
$ownerName = $generalObj->getVar('owner_name');
if ($generalObj->getVar('owner')) {
@@ -1696,21 +1705,12 @@ function tryUniqueItemLottery(RandUtil $rng, General $general, string $acquireTy
return giveRandomUniqueItem($rng, $general, $acquireType);
}
function getAdmin()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getAll();
$clock = GameClock::fromStorage($gameStor);
foreach (['turntime', 'starttime', 'opentime', 'tnmt_time'] as $key) {
if (($admin[$key] ?? null) !== null) {
$admin["{$key}_display"] = $clock->formatTick(Util::toInt($admin[$key]), true);
}
}
$admin['clock_now_tick'] = $clock->nowTick();
$admin['clock_now_display'] = $clock->formatTick($admin['clock_now_tick'], true);
return $admin;
}
function getAdmin()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
return $gameStor->getAll();
}
/** @return General[] */
function deleteNation(General $lord, bool $applyDB): array
@@ -1788,13 +1788,11 @@ function deleteNation(General $lord, bool $applyDB): array
// 부대 삭제
$db->delete('troop', 'nation=%i', $nationID);
// 국가 삭제
$gameDate = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->formatNow();
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => $nationID,
'date' => $gameDate,
'data' => Json::encode($nation)
// 국가 삭제
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => $nationID,
'data' => Json::encode($nation)
]);
$db->delete('nation', 'nation=%i', $nationID);
$db->delete('nation_turn', 'nation_id=%i', $nationID);
@@ -2201,29 +2199,35 @@ function SabotageInjury(RandUtil $rng, array $cityGeneralList, string $reason):
return $injuryCount;
}
function getRandTurn(RandUtil $rng, int $term, ?int $baseTick = null): int
{
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$baseTick ??= $clock->nowTick();
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randMicrosecond = $rng->nextRangeInt(0, 999999); // 레거시 RNG 소비 6자리 유지
return $baseTick
+ $clock->ticksFromSeconds($randSecond)
+ intdiv($randMicrosecond * $clock->ticksPerSecond(), 1_000_000);
}
function getRandTurn2(RandUtil $rng, int $term, ?int $baseTick = null): int
{
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$baseTick ??= $clock->nowTick();
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randMicrosecond = $rng->nextRangeInt(0, 999999); // 레거시 RNG 소비 6자리 유지
return $baseTick
- $clock->ticksFromSeconds($randSecond)
- intdiv($randMicrosecond * $clock->ticksPerSecond(), 1_000_000);
}
function getRandTurn(RandUtil $rng, $term, ?\DateTimeInterface $baseDateTime = null)
{
if ($baseDateTime === null) {
$baseDateTime = new \DateTimeImmutable();
} else if ($baseDateTime instanceof \DateTime) {
$baseDateTime = \DateTimeImmutable::createFromMutable($baseDateTime);
} else if ($baseDateTime instanceof \DateTimeImmutable) {
//do Nothing
} else {
throw new MustNotBeReachedException();
}
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수
return TimeUtil::format($baseDateTime->add(TimeUtil::secondsToDateInterval($randSecond + $randFraction)), true);
}
function getRandTurn2(RandUtil $rng, $term, ?\DateTimeInterface $baseDateTime = null)
{
if ($baseDateTime === null) {
$baseDateTime = new \DateTimeImmutable();
} else if ($baseDateTime instanceof \DateTime) {
$baseDateTime = \DateTimeImmutable::createFromMutable($baseDateTime);
} else {
throw new MustNotBeReachedException();
}
$randSecond = $rng->nextRangeInt(0, 60 * $term - 1);
$randFraction = $rng->nextRangeInt(0, 999999) / 1000000; //6자리 소수
return $baseDateTime->sub(TimeUtil::secondsToDateInterval($randSecond + $randFraction))->format('Y-m-d H:i:s.u');
}
+3 -4
View File
@@ -62,12 +62,11 @@ function processAuction()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$nowTick = GameClock::fromStorage($gameStor)->nowTick();
$now = TimeUtil::now();
$auctionList = $db->queryAllLists(
'SELECT id, `type` FROM ng_auction WHERE `close_tick` <= %i AND finished = 0',
$nowTick
'SELECT id, `type` FROM ng_auction WHERE `close_date` <= %s AND finished = 0',
$now
);
if (!$auctionList) {
+16 -27
View File
@@ -651,24 +651,16 @@ function checkStatistic()
}
function convForOldGeneral(array $general, int $year, int $month)
{
$general['history'] = getGeneralHistoryLogAll($general['no']);
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$turnTimeDisplay = $clock->formatTick(Util::toInt($general['turntime']), true);
$general['turntime_tick'] = Util::toInt($general['turntime']);
$general['turntime'] = $turnTimeDisplay;
if ($general['recent_war'] !== null) {
$general['recent_war_tick'] = Util::toInt($general['recent_war']);
$general['recent_war'] = $clock->formatTick(Util::toInt($general['recent_war']), true);
}
return [
function convForOldGeneral(array $general, int $year, int $month)
{
$general['history'] = getGeneralHistoryLogAll($general['no']);
return [
'server_id' => UniqueConst::$serverID,
'general_no' => $general['no'],
'owner' => $general['owner'],
'name' => $general['name'],
'last_yearmonth' => $year * 100 + $month,
'turntime' => $turnTimeDisplay,
'turntime' => $general['turntime'],
'data' => Json::encode($general)
];
}
@@ -742,7 +734,7 @@ function checkEmperior()
/** @var int[] */
$auctionList = $db->queryFirstColumn(
'SELECT `id` FROM `ng_auction` WHERE `type` = %s AND `finished` = 0 ORDER BY `close_tick` ASC',
'SELECT `id` FROM `ng_auction` WHERE `type` = %s AND `finished` = 0 ORDER BY `close_date` ASC',
AuctionType::UniqueItem->value
);
foreach($auctionList as $auctionID){
@@ -838,23 +830,20 @@ function checkEmperior()
$nation['aux'] += $nationStor->max_power ?? [];
$nation['history'] = getNationHistoryLogAll($nation['nation']);
storeOldGenerals(0, $admin['year'], $admin['month']);
storeOldGenerals($nation['nation'], $admin['year'], $admin['month']);
$gameDate = GameClock::fromStorage($gameStor)->formatNow();
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => $nation['nation'],
'date' => $gameDate,
'data' => Json::encode($nation)
storeOldGenerals(0, $admin['year'], $admin['month']);
storeOldGenerals($nation['nation'], $admin['year'], $admin['month']);
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => $nation['nation'],
'data' => Json::encode($nation)
]);
$noNationGeneral = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=0');
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => 0,
'date' => $gameDate,
'data' => Json::encode([
'server_id' => UniqueConst::$serverID,
'nation' => 0,
'data' => Json::encode([
'nation' => 0,
'name' => '재야',
'generals' => $noNationGeneral
-4
View File
@@ -4,10 +4,6 @@ namespace sammo;
function printLimitMsg($turntime)
{
if (is_int($turntime) || (is_string($turntime) && ctype_digit(ltrim($turntime, '-')))) {
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$turntime = GameClock::fromStorage($gameStor)->formatTick(Util::toInt($turntime), true);
}
//FIXME: template로 이동.
?>
<!DOCTYPE html>
+2 -6
View File
@@ -61,12 +61,8 @@ function chiefTurnTable()
";
}
function templateLimitMsg(string $turntime): string
{
if (ctype_digit(ltrim($turntime, '-'))) {
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$turntime = GameClock::fromStorage($gameStor)->formatTick(Util::toInt($turntime), true);
}
function templateLimitMsg(string $turntime): string
{
return "이미 너무 많은 접속을 하셨습니다. 다음 턴에 다시 시도해주세요. (턴시간: {$turntime})";
}
+8 -11
View File
@@ -17,10 +17,10 @@ function processTournament()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$admin = $gameStor->getValues(['tournament', 'phase', 'tnmt_type', 'tnmt_auto', 'tnmt_time', 'turnterm', 'last_tournament_betting_id']);
$offset = intdiv($clock->nowTick() - Util::toInt($admin['tnmt_time']), $clock->ticksPerSecond());
$now = new \DateTime();
$offset = $now->getTimestamp() - (new \DateTime($admin['tnmt_time']))->getTimestamp();
//수동일땐 무시
if (!$admin['tnmt_auto']) {
@@ -122,10 +122,10 @@ function processTournament()
if ($tnmt == 6) {
$betTerm = Util::valueFit($unit * 60, null, 3600);
//처리 초 더한 날짜
$dt = date("Y-m-d H:i:s", strtotime($admin['tnmt_time']) + $unit * $i + $betTerm);
$gameStor->tournament = $tnmt;
$gameStor->phase = $phase;
$gameStor->tnmt_time = Util::toInt($admin['tnmt_time'])
+ $clock->ticksFromSeconds($unit * $i + $betTerm);
$gameStor->tnmt_time = $dt;
return;
}
}
@@ -133,7 +133,7 @@ function processTournament()
$second = $unit * $iter;
$gameStor->tournament = $tnmt;
$gameStor->phase = $phase;
$gameStor->tnmt_time = Util::toInt($admin['tnmt_time']) + $clock->ticksFromSeconds($second);
$gameStor->tnmt_time = (new \DateTimeImmutable($admin['tnmt_time']))->add(new \DateInterval("PT{$second}S"))->format('Y-m-d H:i:s');
}
function getTournamentTermText(int $turnTerm)
@@ -160,8 +160,7 @@ function getTournamentTime()
$gameStor = KVStorage::getStorage($db, 'game_env');
list($tnmt, $tnmt_time) = $gameStor->getValuesAsArray(['tournament', 'tnmt_time']);
$clock = GameClock::fromStorage($gameStor);
$dt = substr($clock->formatTick(Util::toInt($tnmt_time)), 11, 5);
$dt = substr($tnmt_time, 11, 5);
switch ($tnmt) {
case 1:
$tnmt = "개막시간 {$dt}";
@@ -285,11 +284,9 @@ function startTournament($type)
$admin = $gameStor->getValues(['year', 'month', 'turnterm']);
$turnTerm = $admin['turnterm'];
$unit = calcTournamentTerm($turnTerm);
$clock = GameClock::fromStorage($gameStor);
$gameStor->tnmt_auto = true;
// 기존 startTournament은 unit을 분으로 더하므로 그 계약을 유지합니다.
$gameStor->tnmt_time = $clock->nowTick() + $clock->ticksFromMinutes($unit);
$gameStor->tnmt_time = (new \DateTimeImmutable())->add(new \DateInterval("PT{$unit}M"))->format('Y-m-d H:i:s');
$gameStor->tournament = 1;
$gameStor->tnmt_type = $type;
$gameStor->last_tournament_betting_id = 0;
@@ -1174,7 +1171,7 @@ function fight($tnmt_type, $tnmt, $phs, $group, $g1, $g2, $type)
}
$damage1 *= $factor1;
$damage2 *= $factor2;
//1합 승부
if ($phase == 1) {
+2 -3
View File
@@ -7,7 +7,6 @@ include "func.php";
Session::requireLogin()->loginGame()->setReadOnly();
$mapName = GameConst::$mapName;
$frontClock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
?>
<!DOCTYPE html>
@@ -29,7 +28,7 @@ $frontClock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env')
'maxTurn' => GameConst::$maxTurn,
'maxPushTurn' => 12,
'serverNow' => $frontClock->formatTick($frontClock->nowTick()),
'serverNow' => TimeUtil::now(false),
]
], false) ?>
<?= WebUtil::printJS('../d_shared/common_path.js') ?>
@@ -43,4 +42,4 @@ $frontClock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env')
<div id="app"></div>
</body>
</html>
</html>
+12 -15
View File
@@ -25,24 +25,21 @@ if(!$reserved){
]);
}
$reservedDate = new \DateTimeImmutable($reserved['date']);
$now = GameClock::readWallTime();
$reservedDate = new \DateTime($reserved['date']);
$now = new \DateTime();
$status = 'not_yet';
list($isUnited, $unitedWallAnchor) = $gameStor->getValuesAsArray(['isunited', 'autoreset_united_wall_anchor']);
if($isUnited === null){
$isUnited = 2;
}
$lastTurn = null;
if($isUnited > 0){
if(!is_string($unitedWallAnchor) || $unitedWallAnchor === ''){
$unitedWallAnchor = TimeUtil::format($now, true);
$gameStor->autoreset_united_wall_anchor = $unitedWallAnchor;
}
$lastTurn = new \DateTimeImmutable($unitedWallAnchor);
}
list($isUnited, $lastTurn) = $gameStor->getValuesAsArray(['isunited', 'turntime']);
if($isUnited === null || $lastTurn === null){
$isUnited = 2;
$lastTurn = '2000-01-01';
}
if($lastTurn !== null){
$lastTurn = new \DateTime($lastTurn);
}
if($lastTurn === null){
//이미 리셋된 상태임
@@ -102,4 +99,4 @@ $result['affected']=1;
$prefix = DB::prefix();
ServConfig::getServerList()[$prefix]->openServer();
Json::die($result);
Json::die($result);
+2 -3
View File
@@ -10,7 +10,6 @@ $session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID();
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$isSecretBoard = Util::getPost('isSecret', 'bool', false);
$title = Util::getPost('title');
@@ -68,7 +67,7 @@ $icon = GetImageURL($me['imgsvr'], $me['picture']);
$db->insert('board', [
'nation_no'=>$me['nation'],
'is_secret'=>$isSecretBoard,
'date'=>$clock->formatNow(),
'date'=>TimeUtil::now(),
'general_no'=>$me['no'],
'author'=>$me['name'],
'author_icon'=>$icon,
@@ -80,4 +79,4 @@ Json::die([
'result'=>true,
'reason'=>'success',
'row_id'=>$db->insertId()
]);
]);
+2 -3
View File
@@ -10,7 +10,6 @@ $session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID();
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$articleNo = Util::getPost('articleNo', 'int');
$text = Util::getPost('text');
@@ -74,7 +73,7 @@ else if ($isSecretBoard && $permission < 2) {
$db->insert('comment', [
'nation_no'=>$me['nation'],
'is_secret'=>$isSecretBoard,
'date'=>$clock->formatNow(),
'date'=>TimeUtil::now(),
'document_no'=>$articleNo,
'general_no'=>$me['no'],
'author'=>$me['name'],
@@ -85,4 +84,4 @@ Json::die([
'result'=>true,
'reason'=>'success',
'row_id'=>$db->insertId()
]);
]);
+2 -2
View File
@@ -83,7 +83,7 @@ else{
}
$now = Message::gameNow();
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
if(in_array($stateOpt, ['try_destroy_src', 'try_destroy_dest'])){
@@ -138,4 +138,4 @@ Json::die([
'result'=>true,
'reason'=>'success',
'state'=>$lastState
]);
]);
+2 -2
View File
@@ -69,7 +69,7 @@ $destNation = getNationStaticInfo($letter['dest_nation_id']);
$src = new MessageTarget($me['no'], $me['name'], $destNation['nation'], $destNation['name'], $destNation['color'], $me['icon']);
$dest = new MessageTarget(0, '', $srcNation['nation'], $srcNation['name'], $srcNation['color']);
$now = Message::gameNow();
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
if($isAgree){
@@ -133,4 +133,4 @@ $msgID = $msg->send();
Json::die([
'result'=>true,
'reason'=>'success'
]);
]);
+2 -2
View File
@@ -63,7 +63,7 @@ $destNation = getNationStaticInfo($letter['dest_nation_id']);
$src = new MessageTarget($me['no'], $me['name'], $srcNation['nation'], $srcNation['name'], $srcNation['color'], $me['icon']);
$dest = new MessageTarget(0, '', $destNation['nation'], $destNation['name'], $destNation['color']);
$now = Message::gameNow();
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
$aux['reason'] = [
@@ -91,4 +91,4 @@ $msgID = $msg->send();
Json::die([
'result'=>true,
'reason'=>'success'
]);
]);
+3 -5
View File
@@ -140,8 +140,6 @@ else{
$me['icon'] = GetImageURL($me['imgsvr'], $me['picture']);
$clock = GameClock::fromStorage($gameStor);
$gameNow = $clock->nowDateTime();
$db->insert('ng_diplomacy', [
'src_nation_id'=>$srcNation['nation'],
'dest_nation_id'=>$destNation['nation'],
@@ -149,7 +147,7 @@ $db->insert('ng_diplomacy', [
'state'=>'proposed',
'text_brief'=>$textBrief,
'text_detail'=>$textDetail,
'date'=>TimeUtil::format($gameNow),
'date'=>TimeUtil::now(),
'src_signer'=>$me['no'],
'dest_signer'=>null,
'aux'=>Json::encode([
@@ -170,7 +168,7 @@ $newLetterNo = $db->insertId();
$src = new MessageTarget($me['no'], $me['name'], $srcNation['nation'], $srcNation['name'], $srcNation['color'], $me['icon']);
$dest = new MessageTarget(0, '', $destNation['nation'], $destNation['name'], $destNation['color']);
$now = \DateTime::createFromImmutable($gameNow);
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
$josaYi = JosaUtil::pick($newLetterNo, '이');
@@ -197,4 +195,4 @@ Json::die([
'result'=>true,
'reason'=>'success',
'row_id'=>$db->insertId()
]);
]);
+23 -23
View File
@@ -16,10 +16,12 @@ $session = Session::requireLogin([])->setReadOnly();
$userID = Session::getUserID();
$oNow = new \DateTimeImmutable();
$now = $oNow->format('Y-m-d H:i:s');
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$now = $clock->nowTick();
$oldGeneral = $db->queryFirstField('SELECT `no` FROM general WHERE `owner`=%i', $userID);
if($oldGeneral !== null){
@@ -42,14 +44,15 @@ if($npcmode!=1){
]);
}
$token = $db->queryFirstRow('SELECT * FROM select_npc_token WHERE `owner`=%i AND `valid_until`>=%i', $userID, $now);
$token = $db->queryFirstRow('SELECT * FROM select_npc_token WHERE `owner`=%i AND `valid_until`>=%s', $userID, $now);
$pickResult = [];
if($token && $refresh){
$pickMoreFrom = Util::toInt($token['pick_more_from']);
$pickMoreFrom = (new \DateTime($token['pick_more_from']))->getTimestamp();
$nowT = $oNow->getTimestamp();
if($now >= $pickMoreFrom){
if($nowT >= $pickMoreFrom){
$oldPickResult = Json::decode($token['pick_result']);
foreach($keepResult as $keepId){
@@ -72,16 +75,15 @@ if($token && $refresh){
}
if($token && !$refresh){
$pickMoreFrom = Util::toInt($token['pick_more_from']);
$pickMoreFrom = (new \DateTime($token['pick_more_from']))->getTimestamp();
$nowT = $oNow->getTimestamp();
Json::die([
'result'=>true,
'pick'=>Json::decode($token['pick_result']),
'pickMoreFrom'=>$clock->formatTick($pickMoreFrom),
'pickMoreSeconds'=>intdiv($pickMoreFrom - $now, $clock->ticksPerSecond()),
'validUntil'=>$clock->formatTick(Util::toInt($token['valid_until'])),
'validForSeconds'=>max(0, intdiv(Util::toInt($token['valid_until']) - $now, $clock->ticksPerSecond())),
'clockMode'=>$clock->getMode(),
'pickMoreFrom'=>$token['pick_more_from'],
'pickMoreSeconds'=>$pickMoreFrom-$nowT,
'validUntil'=>$token['valid_until']
]);
}
@@ -98,7 +100,7 @@ foreach($db->query('SELECT `no`, `name`, leadership, strength, intel, nation, im
$weight[$general['no']] = pow($allStat, 1.5);
}
foreach($db->queryFirstColumn('SELECT pick_result FROM select_npc_token WHERE `owner`!=%i AND valid_until >=%i', $userID, $now) as $reserved){
foreach($db->queryFirstColumn('SELECT pick_result FROM select_npc_token WHERE `owner`!=%i AND valid_until >=%s', $userID, $now) as $reserved){
$reserved = Json::decode($reserved);
foreach(array_keys($reserved) as $reservedNPC){
if(key_exists($reservedNPC, $weight)){
@@ -129,8 +131,8 @@ $newNonce = random_int(0, 0xfffffff);
$validSecond = max(VALID_SECOND, $turnterm*40);
$pickMoreSecond = max(PICK_MORE_SECOND, Util::round(pow($turnterm, 0.672)*8));
$validUntil = $now + $clock->ticksFromSeconds($validSecond);
$pickMoreFrom = $now + $clock->ticksFromSeconds($pickMoreSecond);
$validUntil = $oNow->add(new \DateInterval(sprintf('PT%dS', $validSecond)));
$pickMoreFrom = $oNow->add(new \DateInterval(sprintf('PT%dS', $pickMoreSecond)));
$db->delete('select_npc_token', 'valid_until < %s', $now);
@@ -138,8 +140,8 @@ $inserted = 0;
if($token){
$db->update('select_npc_token', [
'valid_until'=>$validUntil,
'pick_more_from'=>$pickMoreFrom,
'valid_until'=>$validUntil->format('Y-m-d H:i:s'),
'pick_more_from'=>$pickMoreFrom->format('Y-m-d H:i:s'),
'pick_result'=>Json::encode($pickResult),
'nonce'=>$newNonce
], 'owner = %i AND nonce = %i', $userID, $token['nonce']);
@@ -150,8 +152,8 @@ if($token){
else{
$db->insertIgnore('select_npc_token', [
'owner'=>$userID,
'valid_until'=>$validUntil,
'pick_more_from'=>$now,
'valid_until'=>$validUntil->format('Y-m-d H:i:s'),
'pick_more_from'=>'2000-01-01 01:00:00',
'pick_result'=>Json::encode($pickResult),
'nonce'=>$newNonce
]);
@@ -171,9 +173,7 @@ if($inserted === 0){
Json::die([
'result'=>true,
'pick'=>$pickResult,
'pickMoreFrom'=>$clock->formatTick(($inserted===-1)?$pickMoreFrom:$now),
'pickMoreFrom'=>($inserted===-1)?$pickMoreFrom->format('Y-m-d H:i:s'):'2000-01-01 01:00:00',
'pickMoreSeconds'=>($inserted===-1)?$pickMoreSecond:0,
'validUntil'=>$clock->formatTick($validUntil),
'validForSeconds'=>max(0, intdiv($validUntil - $now, $clock->ticksPerSecond())),
'clockMode'=>$clock->getMode(),
]);
'validUntil'=>$validUntil->format('Y-m-d H:i:s')
]);
+9 -11
View File
@@ -43,10 +43,12 @@ function putInfoText(&$info, ?array $currentTargetEnv){
$session = Session::requireLogin([])->setReadOnly();
$userID = Session::getUserID();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$now = $clock->nowTick();
$oNow = new \DateTimeImmutable();
$now = $oNow->format('Y-m-d H:i:s');
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$eventEnv = $gameStor->getValues(['npcmode', 'startyear', 'year', 'month']);
$npcmode = $eventEnv['npcmode'];
@@ -86,9 +88,7 @@ if($tokens){
Json::die([
'result'=>true,
'pick'=>$pick,
'validUntil'=>$clock->formatTick(Util::toInt($valid_until)),
'validForSeconds'=>max(0, intdiv(Util::toInt($valid_until) - $now, $clock->ticksPerSecond())),
'clockMode'=>$clock->getMode(),
'validUntil'=>$valid_until
]);
}
@@ -108,7 +108,5 @@ sortTokens($pick);//좀 무식하지만..
Json::die([
'result'=>true,
'pick'=>$pick,
'validUntil'=>$valid_until === null ? null : $clock->formatTick(Util::toInt($valid_until)),
'validForSeconds'=>$valid_until === null ? 0 : max(0, intdiv(Util::toInt($valid_until) - $now, $clock->ticksPerSecond())),
'clockMode'=>$clock->getMode(),
]);
'validUntil'=>$valid_until
]);
+2 -2
View File
@@ -211,7 +211,7 @@ try{
$show_img_level,
!!$tournament_trig,
$join_mode,
TimeUtil::format(GameClock::readWallTime(), false),
TimeUtil::now(),
$autorun_user
));
}
@@ -220,4 +220,4 @@ catch(\Exception $e){
'result'=>false,
'reason'=>$e->getMessage()
]);
}
}
+1 -1
View File
@@ -290,7 +290,7 @@ function do추방(General $general, int $myOfficerLevel): ?string
$src,
$src,
$str,
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
+3 -3
View File
@@ -24,8 +24,8 @@ $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$rootDB = RootDB::db();
$clock = GameClock::fromStorage($gameStor);
$now = $clock->nowTick();
$oNow = new \DateTimeImmutable();
$now = $oNow->format('Y-m-d H:i:s');
$member = $rootDB->queryFirstRow('SELECT `name`, `penalty` FROM member WHERE `NO`=%i', $userID);
if(!$member){
@@ -139,4 +139,4 @@ $rootDB->insert('member_log', [
Json::die([
'result'=>true,
'reason'=>'success'
]);
]);
+3 -3
View File
@@ -37,8 +37,8 @@ $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$rootDB = RootDB::db();
$clock = GameClock::fromStorage($gameStor);
$now = $clock->nowTick();
$oNow = new \DateTimeImmutable();
$now = $oNow->format('Y-m-d H:i:s');
$hasGeneralID = $db->queryFirstField('SELECT no FROM general WHERE owner = %i', $userID);
if($hasGeneralID){
@@ -176,7 +176,7 @@ $builder->setOwner($userID);
$builder->setOwnerName($userNick);
$builder->setKillturn(5);
$builder->setNPCType(0);
$builder->setAuxVar('next_change', $now + GameClock::TICKS_PER_TURN * 12);
$builder->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $env['turnterm']));
$builder->setAuxVar(
'prestart_delete_after',
addTurn($now, $env['turnterm'], GameConst::$minTurnDieOnPrestart)
+2 -5
View File
@@ -19,7 +19,6 @@ if(!class_exists('\\sammo\\DB')){
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
if(file_exists(__DIR__.'/.htaccess')){
$reserved = $db->queryFirstRow(
@@ -76,10 +75,8 @@ $admin['maxUserCnt'] = $admin['maxgeneral'];
$admin['npcMode'] = $admin['npcmode'];
$admin['turnTerm'] = $admin['turnterm'];
$admin['isUnited'] = $admin['isunited'];
$admin['isOpen'] = $clock->nowTick() >= Util::toInt($admin['opentime']);
$admin['opentime'] = $clock->formatTick(Util::toInt($admin['opentime']));
$admin['starttime'] = substr($admin['opentime'], 5, 11);
$admin['turntime'] = substr($clock->formatTick(Util::toInt($admin['turntime'])), 5, 11);
$admin['turntime'] = substr($admin['turntime'], 5, 11);
unset($admin['npcmode']);
unset($admin['maxgeneral']);
unset($admin['turnterm']);
@@ -134,4 +131,4 @@ if($general){
Json::die([
'game'=>$admin,
'me'=>$me?:null
]);
]);
+3 -6
View File
@@ -64,7 +64,6 @@ if ($permission < 3) {
function applyNationPolicy($policy, $nationID, $generalName): ?string
{
$db = DB::db();
$gameNow = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->formatNow();
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$defaultPolicy = AutorunNationPolicy::$defaultPolicy;
@@ -140,7 +139,7 @@ function applyNationPolicy($policy, $nationID, $generalName): ?string
$nationPolicyRoot['values'] = $nationPolicy;
$nationPolicyRoot['valueSetter'] = $generalName;
$nationPolicyRoot['valueSetTime'] = $gameNow;
$nationPolicyRoot['valueSetTime'] = TimeUtil::now();
$nationStor->npc_nation_policy = $nationPolicyRoot;
return null;
}
@@ -148,7 +147,6 @@ function applyNationPolicy($policy, $nationID, $generalName): ?string
function applyNationPriority($priority, $nationID, $generalName): ?string
{
$db = DB::db();
$gameNow = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->formatNow();
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$nationPolicyRoot = $nationStor->npc_nation_policy;
@@ -160,7 +158,7 @@ function applyNationPriority($priority, $nationID, $generalName): ?string
}
$nationPolicyRoot['priority'] = $priority;
$nationPolicyRoot['prioritySetter'] = $generalName;
$nationPolicyRoot['prioritySetTime'] = $gameNow;
$nationPolicyRoot['prioritySetTime'] = TimeUtil::now();
$nationStor->npc_nation_policy = $nationPolicyRoot;
return null;
}
@@ -168,7 +166,6 @@ function applyNationPriority($priority, $nationID, $generalName): ?string
function applyGeneralPriority($priority, $nationID, $generalName): ?string
{
$db = DB::db();
$gameNow = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->formatNow();
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$generalPolicyRoot = $nationStor->npc_general_policy;
@@ -209,7 +206,7 @@ function applyGeneralPriority($priority, $nationID, $generalName): ?string
$generalPolicyRoot['priority'] = $priority;
$generalPolicyRoot['prioritySetter'] = $generalName;
$generalPolicyRoot['prioritySetTime'] = $gameNow;
$generalPolicyRoot['prioritySetTime'] = TimeUtil::now();
$nationStor->npc_general_policy = $generalPolicyRoot;
return null;
}
+1 -2
View File
@@ -77,8 +77,7 @@ $month = $query['month'];
$repeatCnt = $query['repeatCnt'];
$rawAttacker = $query['attackerGeneral'];
$battleClock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$rawAttacker['turntime'] = $battleClock->formatTick($battleClock->nowTick());
$rawAttacker['turntime'] = TimeUtil::now();
$rawAttackerCity = $query['attackerCity'];
$rawAttackerNation = $query['attackerNation'];
+3 -3
View File
@@ -22,8 +22,8 @@ $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$rootDB = RootDB::db();
$clock = GameClock::fromStorage($gameStor);
$now = $clock->nowTick();
$oNow = new \DateTimeImmutable();
$now = $oNow->format('Y-m-d H:i:s');
$generalID = $db->queryFirstField('SELECT no FROM general WHERE owner = %i', $userID);
if(!$generalID){
@@ -181,7 +181,7 @@ if ($isCentennialAllStar) {
if(key_exists('generalName', $info)){
$generalObj->updateVar('name', $info['generalName']);
}
$generalObj->setAuxVar('next_change', $now + GameClock::TICKS_PER_TURN * 12);
$generalObj->setAuxVar('next_change', TimeUtil::nowAddMinutes(12 * $turnterm));
$userNick = $ownerInfo['name'];
$generalObj->setVar('owner_name', $userNick);
+2 -4
View File
@@ -11,11 +11,9 @@ $db = DB::db();
$updated = false;
$locked = false;
$lastExecuted = TurnExecutionHelper::executeAllCommand($updated, $locked);
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
Json::die([
'result' => true,
'updated' => $updated,
'locked' => $locked,
'lastExecutedTick' => $lastExecuted,
'lastExecuted' => $clock->formatTick($lastExecuted, true),
]);
'lastExecuted' => $lastExecuted,
]);
+2 -2
View File
@@ -21,7 +21,7 @@ class BidUniqueAuction extends \sammo\BaseAPI
])
->rule('int', 'amount')
->rule('int', 'auctionID')
->rule('boolean', 'extendCloseTick');
->rule('boolean', 'extendCloseDate');
if (!$v->validate()) {
return $v->errorStr();
@@ -38,7 +38,7 @@ class BidUniqueAuction extends \sammo\BaseAPI
{
$auctionID = $this->args['auctionID'];
$amount = $this->args['amount'];
$tryExtendCloseDate = $this->args['extendCloseTick'] ?? false;
$tryExtendCloseDate = $this->args['extendCloseDate'] ?? false;
$generalID = $session->generalID;
$general = General::createObjFromDB($generalID);
@@ -15,8 +15,6 @@ use sammo\General;
use sammo\Json;
use sammo\TimeUtil;
use sammo\Util;
use sammo\GameClock;
use sammo\KVStorage;
use function sammo\getAuctionLogRecent;
@@ -35,13 +33,12 @@ class GetActiveResourceAuctionList extends \sammo\BaseAPI
public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag): null | string | array | APIRecoveryType
{
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$buyRiceList = [];
$sellRiceList = [];
/** @var AuctionInfo[] */
$auctions = array_map(fn ($raw) => AuctionInfo::fromArray($raw), $db->query(
'SELECT * FROM `ng_auction` WHERE `type` IN %ls AND `finished` = 0 ORDER BY `close_tick` ASC',
'SELECT * FROM `ng_auction` WHERE `type` IN %ls AND `finished` = 0 ORDER BY `close_date` ASC',
[
AuctionType::BuyRice->value,
AuctionType::SellRice->value,
@@ -90,8 +87,8 @@ class GetActiveResourceAuctionList extends \sammo\BaseAPI
'type' => $auction->type->value,
'hostGeneralID' => $auction->hostGeneralID,
'hostName' => $auction->detail->hostName,
'openDate' => $clock->formatTick($auction->openTick),
'closeDate' => $clock->formatTick($auction->closeTick),
'openDate' => TimeUtil::format($auction->openDate, false),
'closeDate' => TimeUtil::format($auction->closeDate, false),
'amount' => $auction->detail->amount,
'startBidAmount' => $auction->detail->startBidAmount,
'finishBidAmount' => $auction->detail->finishBidAmount,
@@ -14,8 +14,6 @@ use sammo\Enums\GeneralQueryMode;
use sammo\Enums\InheritanceKey;
use sammo\InheritancePointManager;
use sammo\TimeUtil;
use sammo\GameClock;
use sammo\KVStorage;
use sammo\Validator;
use sammo\General;
@@ -44,7 +42,6 @@ class GetUniqueItemAuctionDetail extends \sammo\BaseAPI
public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag): null | string | array | APIRecoveryType
{
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$generalID = $session->generalID;
$auctionID = $this->args['auctionID'];
@@ -95,11 +92,9 @@ class GetUniqueItemAuctionDetail extends \sammo\BaseAPI
'target' => $auction->target,
'isCallerHost' => $auction->hostGeneralID === $generalID,
'hostName' => $auction->detail->hostName,
'closeDate' => $clock->formatTick($auction->closeTick),
'closeDate' => TimeUtil::format($auction->closeDate, false),
'remainCloseDateExtensionCnt' => $auction->detail->remainCloseDateExtensionCnt,
'availableLatestBidCloseDate' => $auction->detail->availableLatestBidCloseTick === null
? null
: $clock->formatTick($auction->detail->availableLatestBidCloseTick),
'availableLatestBidCloseDate' => TimeUtil::format($auction->detail->availableLatestBidCloseDate, false),
],
'bidList' => $responseBid,
'obfuscatedName' => $obfuscatedName,
@@ -12,8 +12,6 @@ use sammo\Enums\APIRecoveryType;
use sammo\Enums\AuctionType;
use sammo\TimeUtil;
use sammo\Util;
use sammo\GameClock;
use sammo\KVStorage;
class GetUniqueItemAuctionList extends \sammo\BaseAPI
{
@@ -30,13 +28,12 @@ class GetUniqueItemAuctionList extends \sammo\BaseAPI
public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag): null | string | array | APIRecoveryType
{
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$generalID = $session->generalID;
/** @var AuctionInfo[] */
$auctions = array_map(fn($raw)=>AuctionInfo::fromArray($raw), $db->query(
'SELECT * FROM `ng_auction` WHERE `type` = %s ORDER BY `close_tick` ASC',
'SELECT * FROM `ng_auction` WHERE `type` = %s ORDER BY `close_date` ASC',
AuctionType::UniqueItem->value
) ?? []);
@@ -88,11 +85,9 @@ class GetUniqueItemAuctionList extends \sammo\BaseAPI
'target' => $auction->target,
'isCallerHost' => $auction->hostGeneralID === $generalID,
'hostName' => $auction->detail->hostName,
'closeDate' => $clock->formatTick($auction->closeTick),
'closeDate' => TimeUtil::format($auction->closeDate, false),
'remainCloseDateExtensionCnt' => $auction->detail->remainCloseDateExtensionCnt,
'availableLatestBidCloseDate' => $auction->detail->availableLatestBidCloseTick === null
? null
: $clock->formatTick($auction->detail->availableLatestBidCloseTick),
'availableLatestBidCloseDate' => TimeUtil::format($auction->detail->availableLatestBidCloseDate, false),
'highestBid' => [
'generalName' => $highestBid->aux->generalName,
'amount' => $highestBid->amount,
+3 -7
View File
@@ -7,10 +7,9 @@ use DateTimeInterface;
use sammo\DB;
use sammo\Enums\APIRecoveryType;
use sammo\GameConst;
use sammo\GameClock;
use sammo\Json;
use sammo\KVStorage;
use sammo\Util;
use sammo\TimeUtil;
use function sammo\cutTurn;
@@ -32,7 +31,6 @@ class GetReservedCommand extends \sammo\BaseAPI
$commandList = [];
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$generalID = $session->generalID;
$invalidTurnList = 0;
@@ -84,13 +82,11 @@ class GetReservedCommand extends \sammo\BaseAPI
return [
'result' => true,
'turnTimeTick' => Util::toInt($turnTime),
'turnTime' => $clock->formatTick(Util::toInt($turnTime)),
'turnTime' => $turnTime,
'turnTerm' => $turnTerm,
'year' => $year,
'month' => $month,
'date' => $clock->formatTick($clock->nowTick(), true),
'clockMode' => $clock->getMode(),
'date' => TimeUtil::now(true),
'turn' => $commandList,
'autorun_limit' => $generalAux['autorun_limit'] ?? null,
];
+5 -8
View File
@@ -11,8 +11,7 @@ use sammo\Session;
use sammo\General;
use sammo\JosaUtil;
use sammo\KVStorage;
use sammo\GameClock;
use sammo\Util;
use sammo\TimeUtil;
use function sammo\addTurn;
use function sammo\increaseRefresh;
@@ -38,8 +37,6 @@ class DieOnPrestart extends \sammo\BaseAPI
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->cacheValues(['turnterm', 'opentime', 'turntime', 'year', 'month']);
$clock = GameClock::fromStorage($gameStor);
$nowTick = $clock->nowTick();
$general = $db->queryFirstRow('SELECT no,name,nation,owner_name,npc FROM general WHERE owner=%i AND npc = 0', $userID);
if (!$general) {
@@ -70,9 +67,9 @@ class DieOnPrestart extends \sammo\BaseAPI
}
$targetTime = $generalObj->getAuxVar('prestart_delete_after');
if (!is_int($targetTime)) {
if (!is_string($targetTime) || $targetTime === '') {
$targetTime = addTurn(
$lastRefresh === null ? $nowTick : Util::toInt($lastRefresh),
$lastRefresh ?: TimeUtil::now(),
$gameStor->turnterm,
GameConst::$minTurnDieOnPrestart
);
@@ -81,8 +78,8 @@ class DieOnPrestart extends \sammo\BaseAPI
}
//서버 가오픈시 할 수 있는 행동
if ($targetTime > $nowTick) {
$targetTimeShort = $clock->formatTick($targetTime);
if ($targetTime > TimeUtil::now()) {
$targetTimeShort = substr($targetTime, 0, 19);
return "아직 삭제할 수 없습니다. {$targetTimeShort} 부터 가능합니다.";
}
+8 -18
View File
@@ -14,13 +14,13 @@ use sammo\Enums\GeneralColumn;
use sammo\Enums\GeneralQueryMode;
use sammo\Enums\RankColumn;
use sammo\GameConst;
use sammo\GameClock;
use sammo\General;
use sammo\KVStorage;
use sammo\LastTurn;
use sammo\Validator;
use sammo\Session;
use sammo\TimeUtil;
use sammo\Util;
use function sammo\buildNationCommandClass;
@@ -105,7 +105,6 @@ class GetFrontInfo extends \sammo\BaseAPI
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$gameStor->cacheValues(['isunited', 'opentime', 'refresh']);
$lastHistoryID = $this->args['lastWorldHistoryID'];
@@ -159,7 +158,6 @@ class GetFrontInfo extends \sammo\BaseAPI
private function generateGlobalInfo(MeekroDB $db): array
{
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
[
$scenarioText, $extendedGeneral, $isFiction, $npcMode,
@@ -184,9 +182,8 @@ class GetFrontInfo extends \sammo\BaseAPI
$lastVote = null;
if ($lastVoteID) {
$voteStor = KVStorage::getStorage($db, 'vote');
$rawLastVote = VoteInfo::normalizeGameStorage($voteStor->getValue("vote_{$lastVoteID}"), $clock);
$lastVote = VoteInfo::fromGameStorage($rawLastVote, $clock);
if ($rawLastVote['endTick'] !== null && $rawLastVote['endTick'] < $clock->nowTick()) {
$lastVote = VoteInfo::fromArray($voteStor->getValue("vote_{$lastVoteID}"));
if ($lastVote->endDate && $lastVote->endDate < TimeUtil::now()) {
$lastVote = null;
}
}
@@ -213,8 +210,7 @@ class GetFrontInfo extends \sammo\BaseAPI
'month' => $month,
'autorunUser' => $autorunUser,
'turnterm' => $turnterm,
'lastExecutedTick' => $lastExecuted,
'lastExecuted' => $clock->formatTick(Util::toInt($lastExecuted), true),
'lastExecuted' => $lastExecuted,
'lastVoteID' => $lastVoteID,
'develCost' => $develCost,
'noticeMsg' => $noticeMsg,
@@ -228,8 +224,7 @@ class GetFrontInfo extends \sammo\BaseAPI
'isLocked' => $isLocked,
'tournamentType' => $tournamentType,
'tournamentState' => $tournamentState,
'tournamentTimeTick' => $tournamentTime,
'tournamentTime' => $tournamentTime === null ? null : $clock->formatTick(Util::toInt($tournamentTime)),
'tournamentTime' => $tournamentTime,
'genCount' => $globalGenCount,
'generalCntLimit' => $generalCntLimit,
'serverCnt' => $serverCnt,
@@ -366,7 +361,6 @@ class GetFrontInfo extends \sammo\BaseAPI
public function generateGeneralInfo(MeekroDB $db, General $general, array $rawNation): array
{
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$permission = checkSecretPermission($general->getRaw());
@@ -431,12 +425,8 @@ class GetFrontInfo extends \sammo\BaseAPI
'crew' => $general->getVar(GeneralColumn::crew), // number;
'train' => $general->getVar(GeneralColumn::train), // number;
'atmos' => $general->getVar(GeneralColumn::atmos), // number;
'turntimeTick' => $general->getTurnTick(), // number;
'turntime' => $general->getTurnTime(), // string;
'recent_war_tick' => $general->getVar(GeneralColumn::recent_war), // number|null;
'recent_war' => $general->getVar(GeneralColumn::recent_war) === null
? null
: $clock->formatTick(Util::toInt($general->getVar(GeneralColumn::recent_war)), true), // string|null;
'turntime' => $general->getVar(GeneralColumn::turntime), // string;
'recent_war' => $general->getVar(GeneralColumn::recent_war), // string;
'horse' => $general->getVar(GeneralColumn::horse), // GameObjClassKey;
'weapon' => $general->getVar(GeneralColumn::weapon), // GameObjClassKey;
'book' => $general->getVar(GeneralColumn::book), // GameObjClassKey;
@@ -554,7 +544,7 @@ class GetFrontInfo extends \sammo\BaseAPI
'result' => false,
'reason' => '접속 제한중입니다.',
'recovery' => APIRecoveryType::GameQuota,
'recovery_arg' => $general->getTurnTime(),
'recovery_arg' => $general->getVar('turntime'),
];
}
+9 -8
View File
@@ -11,7 +11,6 @@ use sammo\Enums\APIRecoveryType;
use sammo\Enums\GeneralAccessLogColumn;
use sammo\Enums\RankColumn;
use sammo\GameConst;
use sammo\GameClock;
use sammo\GameUnitConst;
use sammo\General;
use sammo\InheritancePointManager;
@@ -166,7 +165,6 @@ class Join extends \sammo\BaseAPI
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->cacheValues(['year', 'month', 'maxgeneral', 'scenario', 'show_img_level', 'block_general_create', 'turnterm', 'turntime', 'genius', 'npcmode']);
$clock = GameClock::fromStorage($gameStor);
########## 동일 정보 존재여부 확인. ##########
$block_general_create = $gameStor->getValue('block_general_create');
@@ -224,7 +222,7 @@ class Join extends \sammo\BaseAPI
$userLogger = new UserLogger($userID, $admin['year'], $admin['month'], false);
$now = $clock->nowTick();
$now = TimeUtil::now(false);
$rng = new RandUtil(new LiteHashDRBG(Util::simpleSerialize(
UniqueConst::$hiddenSeed,
'MakeGeneral',
@@ -362,14 +360,17 @@ class Join extends \sammo\BaseAPI
$userLogger->push(sprintf("턴 시간 %02d:%02d 로 지정", intdiv($inheritTurntime, 60), $inheritTurntime % 60), "inheritPoint");
$inheritTurnMicrosecond = $rng->nextRangeInt(0, 999999);
$turntime = cutTurn(Util::toInt($admin['turntime']), $admin['turnterm'])
+ $clock->ticksFromSeconds($inheritTurntime)
+ intdiv($inheritTurnMicrosecond * $clock->ticksPerSecond(), 1_000_000);
$inheritTurntime += $rng->nextRangeInt(0, 999999) / 1000000;
$turntime = new \DateTimeImmutable(cutTurn($admin['turntime'], $admin['turnterm']));
$turntime = $turntime->add(TimeUtil::secondsToDateInterval($inheritTurntime));
$turntime = TimeUtil::format($turntime, true);
} else {
$turntime = getRandTurn($rng, $admin['turnterm'], Util::toInt($admin['turntime']));
$turntime = getRandTurn($rng, $admin['turnterm'], new \DateTimeImmutable($admin['turntime']));
}
$now = TimeUtil::now(true);
if ($now >= $turntime) {
$turntime = addTurn($turntime, $admin['turnterm']);
}
+1 -5
View File
@@ -8,8 +8,6 @@ use DateTimeInterface;
use sammo\Enums\APIRecoveryType;
use sammo\TurnExecutionHelper;
use sammo\UniqueConst;
use sammo\GameClock;
use sammo\KVStorage;
class ExecuteEngine extends \sammo\BaseAPI
{
@@ -37,13 +35,11 @@ class ExecuteEngine extends \sammo\BaseAPI
$updated = false;
$locked = false;
$lastExecuted = TurnExecutionHelper::executeAllCommand($updated, $locked);
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
return [
'result' => true,
'updated' => $updated,
'locked' => $locked,
'lastExecutedTick' => $lastExecuted,
'lastExecuted' => $clock->formatTick($lastExecuted, true),
'lastExecuted' => $lastExecuted,
];
}
}
+1 -3
View File
@@ -3,7 +3,6 @@
namespace sammo\API\Global;
use sammo\DB;
use sammo\GameClock;
use sammo\Enums\APIRecoveryType;
use sammo\Json;
use sammo\KVStorage;
@@ -146,8 +145,7 @@ class GeneralList extends \sammo\BaseAPI
if (static::$withToken) {
$gameStor = KVStorage::getStorage($db, 'game_env');
$now = GameClock::fromStorage($gameStor)->nowTick();
$now = (new \DateTimeImmutable())->format('Y-m-d H:i:s');
$tokens = [];
foreach ($db->query('SELECT * FROM select_npc_token WHERE `valid_until`>=%s', $now) as $token) {
$validUntil = $token['valid_until'];
@@ -10,6 +10,7 @@ use sammo\Enums\RankColumn;
use sammo\GameConst;
use sammo\General;
use sammo\KVStorage;
use sammo\TimeUtil;
use sammo\UserLogger;
class BuyRandomUnique extends \sammo\BaseAPI
@@ -55,7 +56,7 @@ class BuyRandomUnique extends \sammo\BaseAPI
$userLogger->push("{$reqAmount} 포인트로 랜덤 유니크 구입", "inheritPoint");
$userLogger->flush();
$general->setAuxVar('inheritRandomUnique', true);
$general->setAuxVar('inheritRandomUnique', TimeUtil::now());
$inheritStor->setValue('previous', [$previousPoint - $reqAmount, null]);
$general->increaseRankVar(RankColumn::inherit_point_spent_dynamic, $reqAmount);
$general->applyDB($db);
+2 -2
View File
@@ -116,7 +116,7 @@ class CheckOwner extends \sammo\BaseAPI
$src,
$dest,
"{$destGeneralName}의 소유자는 {$destGeneralOwnerName} 입니다.",
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
@@ -142,7 +142,7 @@ class CheckOwner extends \sammo\BaseAPI
$src,
$dest,
"소유자명이 누군가에 의해 확인되었습니다.",
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
@@ -64,11 +64,13 @@ class ResetTurnTime extends \sammo\BaseAPI
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$currTurnTime = new DateTimeImmutable($general->getTurnTime());
$rng = new RandUtil(new LiteHashDRBG(Util::simpleSerialize(
UniqueConst::$hiddenSeed,
'ResetTurnTime',
$userID,
$general->getAuxVar('nextTurnTimeBase') ?? $general->getTurnTick()
$general->getAuxVar('nextTurnTimeBase') ?? $general->getTurnTime()
)));
$afterTurn = $rng->nextFloat1() * $turnTerm * 60;
+4 -4
View File
@@ -44,7 +44,7 @@ class SendMessage extends \sammo\BaseAPI
private function genPublicMessage(MessageTarget $src, string $text): Message
{
$now = Message::gameNow();
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
$msg = new Message(
@@ -62,7 +62,7 @@ class SendMessage extends \sammo\BaseAPI
private function genNationalMessage(MessageTarget $src, string $text): Message
{
$now = Message::gameNow();
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
$dest = new MessageTarget(0, '', $src->nationID, $src->nationName, $src->color);
@@ -82,7 +82,7 @@ class SendMessage extends \sammo\BaseAPI
private function genDiplomacyMessage(MessageTarget $src, int $destNationID, string $text): Message|string
{
$now = Message::gameNow();
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
$destNation = getNationStaticInfo($destNationID);
@@ -107,7 +107,7 @@ class SendMessage extends \sammo\BaseAPI
private function genPrivateMessage(MessageTarget $src, int $destGeneralID, int $permission, string $text): Message|string
{
$now = Message::gameNow();
$now = new \DateTime();
$unlimited = new \DateTime('9999-12-31');
$db = DB::db();
+2 -6
View File
@@ -8,7 +8,6 @@ use sammo\Enums\APIRecoveryType;
use sammo\Enums\GeneralLiteQueryMode;
use sammo\Enums\GeneralQueryMode;
use sammo\General;
use sammo\GameClock;
use sammo\GeneralLite;
use sammo\Session;
use sammo\Util;
@@ -265,11 +264,8 @@ class GeneralList extends \sammo\BaseAPI
'honorText' => fn ($rawGeneral) => getHonor($rawGeneral['experience']),
'dedLevelText' => fn ($rawGeneral) => getDedLevelText($rawGeneral['dedlevel']),
//'0000-00-00 11:23';
'turntime' => fn ($rawGeneral) => GameClock::fromStorage($gameStor)
->formatTick(Util::toInt($rawGeneral['turntime'])),
'recent_war' => fn ($rawGeneral) => $rawGeneral['recent_war'] === null
? null
: GameClock::fromStorage($gameStor)->formatTick(Util::toInt($rawGeneral['recent_war'])),
'turntime' => fn ($rawGeneral) => substr($rawGeneral['turntime'], 0, 19),
'recent_war' => fn ($rawGeneral) => substr($rawGeneral['recent_war'], 0, 19),
'bill' => fn ($rawGeneral) => getBillByLevel($rawGeneral['dedlevel']),
'reservedCommand' => fn ($rawGeneral) => $reservedCommand[$rawGeneral['no']] ?? null,
'autorun_limit' => fn ($rawGeneral) => ($rawGeneral['aux'] ?? [])['autorun_limit'] ?? 0,
+2 -3
View File
@@ -6,8 +6,8 @@ use sammo\Session;
use DateTimeInterface;
use sammo\DB;
use sammo\Enums\APIRecoveryType;
use sammo\GameClock;
use sammo\KVStorage;
use sammo\TimeUtil;
use sammo\Validator;
use sammo\WebUtil;
@@ -51,9 +51,8 @@ class SetNotice extends \sammo\BaseAPI
$nationID = $me['nation'];
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$gameNow = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->formatNow();
$nationStor->nationNotice = [
'date'=>$gameNow,
'date'=>TimeUtil::now(),
'msg'=>WebUtil::htmlPurify($msg),
'author'=>$me['name'],
'authorID'=>$me['no'],
@@ -8,10 +8,10 @@ use sammo\DB;
use sammo\Enums\APIRecoveryType;
use sammo\Enums\GeneralQueryMode;
use sammo\GameConst;
use sammo\GameClock;
use sammo\General;
use sammo\Json;
use sammo\KVStorage;
use sammo\TimeUtil;
use sammo\Util;
use function sammo\checkLimit;
@@ -39,7 +39,6 @@ class GetReservedCommand extends \sammo\BaseAPI
increaseRefresh("사령부", 1);
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$userID = $session->userID;
$me = $db->queryFirstRow(
@@ -52,8 +51,7 @@ class GetReservedCommand extends \sammo\BaseAPI
$nationID = $me['nation'];
$limitState = checkLimit($me['refresh_score']);
if ($limitState >= 2) {
$limitTime = GameClock::fromStorage($gameStor)->formatTick(Util::toInt($me['turntime']), true);
return "접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다. (다음 갱신 가능 시각 : {$limitTime})";
return "접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다. (다음 갱신 가능 시각 : {$me['turntime']})";
}
$permission = checkSecretPermission($me);
@@ -158,8 +156,7 @@ class GetReservedCommand extends \sammo\BaseAPI
'year' => $year,
'month' => $month,
'turnTerm' => $turnTerm,
'date' => $clock->formatTick($clock->nowTick(), true),
'clockMode' => $clock->getMode(),
'date' => TimeUtil::now(true),
'chiefList' => $nationChiefList,
'troopList' => $troopList,
'isChief' => ($me['officer_level'] > 4),
+3 -4
View File
@@ -10,9 +10,8 @@ use sammo\Enums\GeneralLiteQueryMode;
use sammo\Enums\GeneralQueryMode;
use sammo\General;
use sammo\GeneralLite;
use sammo\GameClock;
use sammo\KVStorage;
use sammo\Session;
use sammo\TimeUtil;
use sammo\Validator;
class AddComment extends \sammo\BaseAPI
@@ -48,8 +47,7 @@ class AddComment extends \sammo\BaseAPI
$generalName = $general->getName();
$nationID = $general->getNationID();
$nationName = $general->getStaticNation()['name'];
$db = DB::db();
$date = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->formatNow();
$date = TimeUtil::now();
$comment = new VoteComment(
@@ -63,6 +61,7 @@ class AddComment extends \sammo\BaseAPI
date: $date
);
$db = DB::db();
$db->insert('vote_comment', $comment->toArray());
return null;
+1 -6
View File
@@ -8,7 +8,6 @@ use sammo\DB;
use sammo\DTO\VoteComment;
use sammo\DTO\VoteInfo;
use sammo\Enums\APIRecoveryType;
use sammo\GameClock;
use sammo\Json;
use sammo\KVStorage;
use sammo\Validator;
@@ -36,16 +35,13 @@ class GetVoteDetail extends \sammo\BaseAPI
{
$voteID = $this->args['voteID'];
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$voteStor = KVStorage::getStorage($db, 'vote');
$rawVote = $voteStor->getValue("vote_{$voteID}");
if (!$rawVote) {
return '설문조사가 없습니다.';
}
$rawVote = VoteInfo::normalizeGameStorage($rawVote, $clock);
$voteInfo = VoteInfo::fromGameStorage($rawVote, $clock);
$isOpen = $rawVote['endTick'] === null || $rawVote['endTick'] >= $clock->nowTick();
$voteInfo = VoteInfo::fromArray($rawVote);
$votes = array_map(fn ($arr) => [Json::decode($arr[0]), $arr[1]], $db->queryAllLists(
@@ -74,7 +70,6 @@ class GetVoteDetail extends \sammo\BaseAPI
'comments' => $comments,
'myVote' => $myVote,
'userCnt' => $userCnt,
'isOpen' => $isOpen,
];
}
}
+3 -5
View File
@@ -6,7 +6,6 @@ use DateTimeInterface;
use sammo\DB;
use sammo\DTO\VoteInfo;
use sammo\Enums\APIRecoveryType;
use sammo\GameClock;
use sammo\KVStorage;
use sammo\Session;
@@ -26,17 +25,16 @@ class GetVoteList extends \sammo\BaseAPI
public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag): null | string | array | APIRecoveryType
{
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$voteStor = KVStorage::getStorage($db, 'vote');
$votes = [];
foreach($voteStor->getAll() as $voteKey => $rawVote){
if(preg_match('/^vote_(\d+)$/D', $voteKey, $matches) !== 1){
if(!str_starts_with($voteKey, 'vote_')){
continue;
}
$voteID = (int)$matches[1];
$votes[$voteID] = VoteInfo::fromGameStorage($rawVote, $clock);
$voteID = (int)substr($voteKey, 5);
$votes[$voteID] = VoteInfo::fromArray($rawVote);
}
return [
+15 -19
View File
@@ -9,7 +9,7 @@ use sammo\Enums\APIRecoveryType;
use sammo\KVStorage;
use sammo\RootDB;
use sammo\Session;
use sammo\GameClock;
use sammo\TimeUtil;
use sammo\Util;
use sammo\Validator;
@@ -37,7 +37,7 @@ class NewVote extends \sammo\BaseAPI
return null;
}
function closeOldVote(int $voteID, KVStorage $voteStor, GameClock $clock)
function closeOldVote(int $voteID, KVStorage $voteStor)
{
$db = DB::db();
$voteStor = KVStorage::getStorage($db, 'vote');
@@ -45,14 +45,13 @@ class NewVote extends \sammo\BaseAPI
if (!$rawLastVoteInfo) {
return;
}
$rawLastVoteInfo = VoteInfo::normalizeGameStorage($rawLastVoteInfo, $clock);
if ($rawLastVoteInfo['endTick'] !== null) {
$lastVoteInfo = VoteInfo::fromArray($rawLastVoteInfo);
if ($lastVoteInfo->endDate) {
return;
}
$rawLastVoteInfo['endTick'] = $clock->nowTick();
$rawLastVoteInfo['endDate'] = $clock->formatTick($rawLastVoteInfo['endTick']);
$voteStor->setValue("vote_{$voteID}", $rawLastVoteInfo);
$lastVoteInfo->endDate = TimeUtil::now();
$voteStor->setValue("vote_{$voteID}", $lastVoteInfo->toArray());
}
function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag): null | string | array | APIRecoveryType
@@ -72,11 +71,7 @@ class NewVote extends \sammo\BaseAPI
$multipleOptions = 0;
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$nowTick = $clock->nowTick();
$now = $clock->formatTick($nowTick);
$now = TimeUtil::now();
/** @var ?string */
$endDate = $this->args['endDate'] ?? null;
/** @var string[] */
@@ -88,9 +83,9 @@ class NewVote extends \sammo\BaseAPI
if($endDate !== null){
try{
$oNow = new \DateTimeImmutable($now);
$oEndDate = new \DateTimeImmutable($endDate);
$endTick = $clock->dateTimeToTick($oEndDate);
if($endTick < $nowTick){
if($oEndDate < $oNow){
return '종료일이 이미 지났습니다.';
}
}
@@ -101,13 +96,17 @@ class NewVote extends \sammo\BaseAPI
$userName = $session->userName;
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$lastVote = $gameStor->getValue('lastVote') ?? 0;
$voteID = $lastVote + 1;
$voteStor = KVStorage::getStorage($db, 'vote');
if (!($this->args['keepOldVote'] ?? false)) {
$this->closeOldVote($lastVote, $voteStor, $clock);
$this->closeOldVote($lastVote, $voteStor);
}
$multipleOptions = Util::valueFit($multipleOptions, 0, count($options));
@@ -123,10 +122,7 @@ class NewVote extends \sammo\BaseAPI
options: $options,
);
$voteStor->setValue("vote_{$voteID}", $voteInfo->toArray() + [
'startTick' => $nowTick,
'endTick' => $endDate === null ? null : $clock->dateTimeToTick(new \DateTimeImmutable($endDate)),
]);
$voteStor->setValue("vote_{$voteID}", $voteInfo->toArray());
$gameStor->setValue('lastVote', $voteID);
$db->update('general', [
+2 -5
View File
@@ -8,7 +8,6 @@ use sammo\DTO\VoteInfo;
use sammo\Enums\APIRecoveryType;
use sammo\Enums\GeneralQueryMode;
use sammo\General;
use sammo\GameClock;
use sammo\Json;
use sammo\KVStorage;
use sammo\LiteHashDRBG;
@@ -55,17 +54,15 @@ class Vote extends \sammo\BaseAPI
return '선택한 항목이 없습니다.';
}
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$voteStor = KVStorage::getStorage($db, 'vote');
$rawVoteInfo = $voteStor->getValue("vote_{$voteID}");
if (!$rawVoteInfo) {
return '설문조사가 없습니다.';
}
$rawVoteInfo = VoteInfo::normalizeGameStorage($rawVoteInfo, $clock);
$voteInfo = VoteInfo::fromGameStorage($rawVoteInfo, $clock);
$voteInfo = VoteInfo::fromArray($rawVoteInfo);
if ($rawVoteInfo['endTick'] !== null && $rawVoteInfo['endTick'] < $clock->nowTick()) {
if ($voteInfo->endDate && $voteInfo->endDate < new \DateTimeImmutable()) {
return '설문조사가 종료되었습니다.';
}
+5 -5
View File
@@ -30,9 +30,8 @@ abstract class AbsFromUserPool extends AbsGeneralPool{
}
static public function pickGeneralFromPool(\MeekroDB $db, RandUtil $rng, int $owner, int $pickCnt, ?string $prefix=null):array{
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$now = $clock->nowTick();
$oNow = new \DateTimeImmutable();
$now = $oNow->format('Y-m-d H:i:s');
$db->update('select_pool', [
'reserved_until'=>null,
@@ -49,8 +48,9 @@ abstract class AbsFromUserPool extends AbsGeneralPool{
throw new \RuntimeException('pool 부족');
}
$result = [];
$validUntil = $now + GameClock::TICKS_PER_TURN * 2;
$gameStor = KVStorage::getStorage($db, 'game_env');
$result = [];
$validUntil = TimeUtil::nowAddMinutes(2 * $gameStor->turnterm);
while(count($result) < $pickCnt){
$cand = $rng->choiceUsingWeightPair($pool);
$poolID = $cand['id'];
+3 -3
View File
@@ -34,7 +34,7 @@ abstract class AbsGeneralPool{
* specialWar
*/
public function __construct(\MeekroDB $db, RandUtil $rng, array $info, int $validUntil)
public function __construct(\MeekroDB $db, RandUtil $rng, array $info, string $validUntil)
{
$this->db = $db;
$this->info = $info;
@@ -92,7 +92,7 @@ abstract class AbsGeneralPool{
return $this->builder;
}
public function getValidUntil():int{
public function getValidUntil():string{
return $this->validUntil;
}
@@ -109,4 +109,4 @@ abstract class AbsGeneralPool{
abstract public static function getPoolName():string;
abstract public static function initPool(\MeekroDB $db);
}
}
+54 -55
View File
@@ -146,35 +146,40 @@ abstract class Auction
return $this->info;
}
public function shrinkCloseTick(?int $tick): ?string
public function shrinkCloseDate(?DateTimeInterface $date): ?string
{
if ($date === null) {
$date = new DateTimeImmutable();
}
$this->info->closeDate = $date;
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$this->info->closeTick = $tick ?? $clock->nowTick();
$db->update('ng_auction', $this->info->toArray('id'), 'id = %i', $this->info->id);
return null;
}
public function extendLatestBidCloseTick(?int $tick): ?string
public function extendLatestBidCloseDate(?DateTimeInterface $date): ?string
{
if ($tick === null) {
if ($date === null) {
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$turnTerm = $gameStor->getValue('turnterm');
$tick = $this->info->closeTick + $clock->ticksFromMinutes(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID)
);
$date = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID) * 60
));
}
if ($this->info->detail->availableLatestBidCloseTick !== null && $tick < $this->info->detail->availableLatestBidCloseTick) {
else{
$date = DateTimeImmutable::createFromInterface($date);
}
if ($this->info->detail->availableLatestBidCloseDate !== null && $date < $this->info->detail->availableLatestBidCloseDate) {
return '기간보다 짧습니다.';
}
$this->info->detail->availableLatestBidCloseTick = $tick;
$this->info->detail->availableLatestBidCloseDate = $date;
return null;
}
public function extendCloseTick(int $tick, bool $force = false): ?string
public function extendCloseDate(DateTimeInterface $date, bool $force = false): ?string
{
if (!$force) {
if ($this->info->detail->remainCloseDateExtensionCnt === null) {
@@ -188,11 +193,12 @@ abstract class Auction
}
}
if ($tick < $this->info->closeTick) {
if ($date < $this->info->closeDate) {
return '종료 기간보다 짧습니다.';
}
$this->info->closeTick = $tick;
$closeDate = DateTimeImmutable::createFromInterface($date);
$this->info->closeDate = $closeDate;
return null;
}
@@ -239,13 +245,12 @@ abstract class Auction
//TODO: 전역 알림이 나타나야한다. 일반 메시지보다는 중요하고, 메시지보단 약하게..
//TODO: 바로가기를 제공하는 편이 좋을 것 같다.
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$msg = new Message(
MessageType::private,
$src,
$dest,
$reason,
DateTime::createFromImmutable($clock->tickToDateTime($clock->nowTick())),
new DateTime(),
new DateTime('9999-12-31'),
[]
);
@@ -270,12 +275,7 @@ abstract class Auction
$db->update('ng_auction', $this->info->toArray('id'), 'id = %i', $this->info->id);
}
private function bidInheritPoint(
int $amount,
int $nowTick,
\DateTimeImmutable $nowDate,
bool $tryExtendCloseDate,
): ?string
private function bidInheritPoint(int $amount, \DateTimeImmutable $now, bool $tryExtendCloseDate): ?string
{
$db = DB::db();
@@ -311,7 +311,7 @@ abstract class Auction
$general->getVar('owner'),
$general->getID(),
$amount,
$nowDate,
$now,
new AuctionBidItemData(
$general->getVar('owner_name'),
$obfuscatedName,
@@ -324,16 +324,15 @@ abstract class Auction
}
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$turnTerm = $gameStor->getValue('turnterm');
if ($this->info->detail->availableLatestBidCloseTick !== null) {
$extendedCloseTick = $nowTick + $clock->ticksFromMinutes(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID)
);
if ($this->info->detail->availableLatestBidCloseDate !== null) {
$extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID) * 60
));
if ($extendedCloseTick > $this->info->closeTick && $this->info->closeTick < $this->info->detail->availableLatestBidCloseTick) {
$this->extendCloseTick(min($extendedCloseTick, $this->info->detail->availableLatestBidCloseTick), true);
if ($extendedCloseDate > $this->info->closeDate && $this->info->closeDate < $this->info->detail->availableLatestBidCloseDate) {
$this->extendCloseDate(min($extendedCloseDate, $this->info->detail->availableLatestBidCloseDate), true);
$this->applyDB();
}
}
@@ -357,16 +356,12 @@ abstract class Auction
return '경매가 이미 끝났습니다.';
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$nowTick = $clock->nowTick();
$nowDate = $clock->tickToDateTime($nowTick);
$now = new \DateTimeImmutable();
if ($auctionInfo->closeTick < $nowTick) {
if ($auctionInfo->closeDate < $now) {
return '경매가 이미 끝났습니다.';
}
if ($auctionInfo->openTick > $nowTick) {
if ($auctionInfo->openDate > $now) {
return '경매가 아직 시작되지 않았습니다.';
}
@@ -382,11 +377,13 @@ abstract class Auction
if ($auctionInfo->reqResource === ResourceType::inheritancePoint) {
return $this->bidInheritPoint($amount, $nowTick, $nowDate, $tryExtendCloseDate);
return $this->bidInheritPoint($amount, $now, $tryExtendCloseDate);
}
//reqResource는 말 그대로 '구매자가 내야하는 자원'이다.
$db = DB::db();
$highestBid = $this->getHighestBid();
if (!$auctionInfo->detail->isReverse) {
if ($highestBid !== null && $amount <= $highestBid->amount) {
@@ -424,7 +421,7 @@ abstract class Auction
$general->getVar('owner'),
$general->getID(),
$amount,
$nowDate,
$now,
new AuctionBidItemData(
$general->getVar('owner_name'),
$general->getName(),
@@ -439,13 +436,14 @@ abstract class Auction
$general->increaseVar($resType->value, -$morePoint);
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$extendedCloseTick = $nowTick + $clock->ticksFromMinutes(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID)
);
$extendedCloseDate = $now->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_PER_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_PER_BID) * 60
));
if ($extendedCloseTick > $this->info->closeTick) {
$this->extendCloseTick($extendedCloseTick, true);
if ($extendedCloseDate > $this->info->closeDate) {
$this->extendCloseDate($extendedCloseDate, true);
$this->applyDB();
}
@@ -458,10 +456,10 @@ abstract class Auction
public function tryFinish(): ?bool
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
if ($clock->nowTick() < $this->info->closeTick) return null;
$now = new DateTimeImmutable();
if ($now < $this->info->closeDate) {
return null;
}
//경매를 닫아야한다.
$highestBid = $this->getHighestBid();
@@ -471,15 +469,17 @@ abstract class Auction
}
if ($highestBid->aux->tryExtendCloseDate) {
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
//연장 요청이 있었다.
$extendedCloseTick = $this->info->closeTick + $clock->ticksFromMinutes(
max(static::MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY, $turnTerm * static::COEFF_EXTENSION_MINUTES_BY_EXTENSION_QUERY)
);
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY, $turnTerm * static::COEFF_EXTENSION_MINUTES_BY_EXTENSION_QUERY) * 60
));
if ($this->extendCloseTick($extendedCloseTick) === null) {
$this->extendLatestBidCloseTick(null);
if ($this->extendCloseDate($extendedCloseDate) === null) {
$this->extendLatestBidCloseDate(null);
$this->applyDB();
return false;
}
@@ -509,13 +509,12 @@ abstract class Auction
//TODO: 전역 알림이 나타나야한다. 일반 메시지보다는 중요하고, 메시지보단 약하게..
//TODO: 바로가기를 제공하는 편이 좋을 것 같다.
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$msg = new Message(
MessageType::private,
$src,
$dest,
$failReason,
DateTime::createFromImmutable($clock->tickToDateTime($clock->nowTick())),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
+7 -9
View File
@@ -56,11 +56,10 @@ abstract class AuctionBasicResource extends Auction
}
$now = new \DateTimeImmutable();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
$nowTick = $clock->nowTick();
$turnTerm = $gameStor->getValue('turnterm');
$closeTick = $nowTick + GameClock::TICKS_PER_TURN * $closeTurnCnt;
$closeDate = $now->add(TimeUtil::secondsToDateInterval($closeTurnCnt * $turnTerm * 60));
$openResult = static::openAuction(new AuctionInfo(
null,
@@ -69,8 +68,8 @@ abstract class AuctionBasicResource extends Auction
"$amount",
$general->getId(),
$bidderRes,
$nowTick,
$closeTick,
$now,
$closeDate,
new AuctionInfoDetail(
"{$hostResName} {$amount} 경매",
$general->getName(),
@@ -146,13 +145,12 @@ abstract class AuctionBasicResource extends Auction
//TODO: 전역 알림이 나타나야한다. 일반 메시지보다는 중요하고, 메시지보단 약하게..
//TODO: 바로가기를 제공하는 편이 좋을 것 같다.
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$msg = new Message(
MessageType::private,
$src,
$dest,
"{$this->auctionID}{$hostResName} 경매에 입찰이 없어 취소되었습니다.",
\DateTime::createFromImmutable($clock->tickToDateTime($clock->nowTick())),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
@@ -248,8 +246,8 @@ abstract class AuctionBasicResource extends Auction
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$turnTerm = $gameStor->getValue('turnterm');
$clock = GameClock::fromStorage($gameStor);
$this->shrinkCloseTick($clock->nowTick() + GameClock::TICKS_PER_TURN);
$date = (new DateTimeImmutable())->add(TimeUtil::secondsToDateInterval($turnTerm * 60));
$this->shrinkCloseDate($date);
}
return null;
+26 -27
View File
@@ -72,15 +72,16 @@ class AuctionUniqueItem extends Auction
$gameStor = KVStorage::getStorage($db, 'game_env');
$now = new DateTimeImmutable();
[$turnTerm, $year, $month] = $gameStor->getValuesAsArray(['turnterm', 'year', 'month']);
$clock = GameClock::fromStorage($gameStor);
$nowTick = $clock->nowTick();
$closeTick = $nowTick + $clock->ticksFromMinutes(
max(static::MIN_AUCTION_CLOSE_MINUTES, $turnTerm * static::COEFF_AUCTION_CLOSE_MINUTES)
);
$availableLatestBidCloseTick = $closeTick + $clock->ticksFromMinutes(
max(static::MIN_EXTENSION_MINUTES_LIMIT_BY_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_BY_BID)
);
$closeDate = $now->add(TimeUtil::secondsToDateInterval(
max(static::MIN_AUCTION_CLOSE_MINUTES, $turnTerm * static::COEFF_AUCTION_CLOSE_MINUTES) * 60
));
$availableLatestBidCloseDate = $closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_LIMIT_BY_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_BY_BID) * 60
));
$info = new AuctionInfo(
null,
@@ -89,8 +90,8 @@ class AuctionUniqueItem extends Auction
$itemKey,
$general->getID(),
ResourceType::inheritancePoint,
$nowTick,
$closeTick,
$now,
$closeDate,
new AuctionInfoDetail(
"{$item->getName()} 경매",
static::genObfuscatedName($general->getID()),
@@ -99,7 +100,7 @@ class AuctionUniqueItem extends Auction
$startAmount,
null,
1,
$availableLatestBidCloseTick,
$availableLatestBidCloseDate,
)
);
@@ -266,22 +267,21 @@ class AuctionUniqueItem extends Auction
if ($availableEquipUniqueCnt <= 0) {
$turnTerm = $gameStor->getValue('turnterm');
$clock = GameClock::fromStorage($gameStor);
//제한에 걸렸다면 자동 연장
$extendedCloseTick = $this->info->closeTick + $clock->ticksFromMinutes(
max(static::MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_UNIQUE_CNT)
);
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_BY_EXTENSION_QUERY, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_UNIQUE_CNT) * 60
));
if($bidder->getID() != $this->info->hostGeneralID){
$this->setHostAsNeutral();
}
$this->extendCloseTick($extendedCloseTick, true);
$this->extendLatestBidCloseTick(null);
$this->extendCloseDate($extendedCloseDate, true);
$this->extendLatestBidCloseDate(null);
$this->applyDB();
return '유니크 아이템 소유 제한 상태입니다. 종료 시간이 연장됩니다.';
}
$isExtendCloseTickRequired = false;
$isExtendCloseDateRequired = false;
foreach (GameConst::$allItems as $itemType => $itemList) {
//아직은 그런 경우는 없지만 동일 유니크를 여러 부위에 장착할 수 있을지도 모름
if (!key_exists($itemKey, $itemList)) {
@@ -291,13 +291,13 @@ class AuctionUniqueItem extends Auction
$ownItem = $general->getItem($itemType);
if ($ownItem->getRawClassName() == $itemKey) {
//FIXME: 이 경우에는 환불이 되던가 해야함.
$isExtendCloseTickRequired = true;
$isExtendCloseDateRequired = true;
$reasons[] = '이미 그 유니크를 가지고 있습니다.';
continue;
}
if (!$ownItem->isBuyable()) {
$isExtendCloseTickRequired = true;
$isExtendCloseDateRequired = true;
$reasons[] = '이미 다른 유니크를 가지고 있습니다.';
continue;
}
@@ -313,19 +313,18 @@ class AuctionUniqueItem extends Auction
}
if (!$availableItemTypes) {
if ($isExtendCloseTickRequired) {
if ($isExtendCloseDateRequired) {
$turnTerm = $gameStor->getValue('turnterm');
$clock = GameClock::fromStorage($gameStor);
//동일 부위 제한에 걸렸다면 자동 연장
$extendedCloseTick = $this->info->closeTick + $clock->ticksFromMinutes(
max(static::MIN_EXTENSION_MINUTES_LIMIT_BY_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_BY_BID)
);
$extendedCloseDate = $this->info->closeDate->add(TimeUtil::secondsToDateInterval(
max(static::MIN_EXTENSION_MINUTES_LIMIT_BY_BID, $turnTerm * static::COEFF_EXTENSION_MINUTES_LIMIT_BY_BID) * 60
));
if($bidder->getID() != $this->info->hostGeneralID){
$this->setHostAsNeutral();
}
$this->extendCloseTick($extendedCloseTick, true);
$this->extendLatestBidCloseTick(null);
$this->extendCloseDate($extendedCloseDate, true);
$this->extendLatestBidCloseDate(null);
$this->applyDB();
}
return join(' ', $reasons);
+1 -1
View File
@@ -193,7 +193,7 @@ class che_몰수 extends Command\NationCommand
$src,
$src,
$text,
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
+1 -1
View File
@@ -159,7 +159,7 @@ class che_발령 extends Command\NationCommand
$destGeneral->getLogger()->pushGeneralActionLog("<Y>{$generalName}</>에 의해 <G><b>{$destCityName}</b></>{$josaRo} 발령됐습니다. <1>$date</>");
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
if (cutTurn($general->getTurnTick(), $this->env['turnterm']) != cutTurn($destGeneral->getTurnTick(), $this->env['turnterm'])) {
if (cutTurn($general->getTurnTime(), $this->env['turnterm']) != cutTurn($destGeneral->getTurnTime(), $this->env['turnterm'])) {
$yearMonth += 1;
}
$destGeneral->setAuxVar('last발령', $yearMonth);
@@ -198,9 +198,8 @@ class che_불가침제의 extends Command\NationCommand
$destNation['color']
);
$clock = \sammo\GameClock::fromStorage(\sammo\KVStorage::getStorage($db, 'game_env'));
$now = \DateTime::createFromImmutable($clock->tickToDateTime($general->getTurnTick()));
$validUntil = clone $now;
$now = new \DateTime($date);
$validUntil = new \DateTime($date);
$validMinutes = max(30, $env['turnterm'] * 3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M"));
@@ -147,9 +147,8 @@ class che_불가침파기제의 extends Command\NationCommand{
$destNation['color']
);
$clock = \sammo\GameClock::fromStorage(\sammo\KVStorage::getStorage($db, 'game_env'));
$now = \DateTime::createFromImmutable($clock->tickToDateTime($general->getTurnTick()));
$validUntil = clone $now;
$now = new \DateTime($date);
$validUntil = new \DateTime($date);
$validMinutes = max(30, $env['turnterm']*3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M"));
@@ -218,4 +217,4 @@ class che_불가침파기제의 extends Command\NationCommand{
],
];
}
}
}
@@ -145,9 +145,8 @@ class che_종전제의 extends Command\NationCommand{
$destNation['color']
);
$clock = \sammo\GameClock::fromStorage(\sammo\KVStorage::getStorage($db, 'game_env'));
$now = \DateTime::createFromImmutable($clock->tickToDateTime($general->getTurnTick()));
$validUntil = clone $now;
$now = new \DateTime($date);
$validUntil = new \DateTime($date);
$validMinutes = max(30, $env['turnterm']*3);
$validUntil->add(new \DateInterval("PT{$validMinutes}M"));
@@ -204,4 +203,4 @@ class che_종전제의 extends Command\NationCommand{
],
];
}
}
}
+1 -1
View File
@@ -137,7 +137,7 @@ class che_천도 extends Command\NationCommand
$nationID = $general->getNationID();
$nationStor = \sammo\KVStorage::getStorage(DB::db(), $nationID, 'nation_env');
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTick()];
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTime()];
if ($lastTurn->getCommand() != $commandName || $lastTurn->getArg() !== $this->arg) {
$this->setResultTurn(new LastTurn(
+8 -4
View File
@@ -2,9 +2,11 @@
namespace sammo\DTO;
use LDTO\Attr\Convert;
use LDTO\Attr\JsonString;
use LDTO\Attr\NullIsUndefined;
use LDTO\Attr\RawName;
use LDTO\Converter\DateTimeConverter;
use sammo\Enums\AuctionType;
use sammo\Enums\ResourceType;
@@ -21,10 +23,12 @@ class AuctionInfo extends \LDTO\DTO
#[RawName('req_resource')]
public ResourceType $reqResource,
#[RawName('open_tick')]
public int $openTick,
#[RawName('close_tick')]
public int $closeTick,
#[RawName('open_date')]
#[Convert(DateTimeConverter::class)]
public \DateTimeImmutable $openDate,
#[RawName('close_date')]
#[Convert(DateTimeConverter::class)]
public \DateTimeImmutable $closeDate,
#[JsonString]
public AuctionInfoDetail $detail,
+4 -1
View File
@@ -2,7 +2,9 @@
namespace sammo\DTO;
use LDTO\Attr\Convert;
use LDTO\Attr\NullIsUndefined;
use LDTO\Converter\DateTimeConverter;
class AuctionInfoDetail extends \LDTO\DTO
{
@@ -19,7 +21,8 @@ class AuctionInfoDetail extends \LDTO\DTO
#[NullIsUndefined]
public ?int $remainCloseDateExtensionCnt,
#[NullIsUndefined]
public ?int $availableLatestBidCloseTick,
#[Convert(DateTimeConverter::class)]
public ?\DateTimeImmutable $availableLatestBidCloseDate,
) {
}
}
+5 -2
View File
@@ -2,8 +2,10 @@
namespace sammo\DTO;
use LDTO\Attr\Convert;
use LDTO\Attr\NullIsUndefined;
use LDTO\Attr\RawName;
use LDTO\Converter\DateTimeConverter;
class GeneralAccessLog extends \LDTO\DTO
{
@@ -18,7 +20,8 @@ class GeneralAccessLog extends \LDTO\DTO
public ?int $userID,
#[RawName('last_refresh')]
public ?int $lastRefresh,
#[Convert(DateTimeConverter::class)]
public \DateTimeImmutable $lastRefresh,
public int $refresh,
@@ -32,4 +35,4 @@ class GeneralAccessLog extends \LDTO\DTO
public int $refreshScoreTotal,
) {
}
}
}
-33
View File
@@ -2,41 +2,8 @@
namespace sammo\DTO;
use sammo\GameClock;
use sammo\Util;
class VoteInfo extends \LDTO\DTO
{
/**
* 기존 문자열만 가진 vote도 읽되, 저장 경계에서는 반드시 tick을 함께 둡니다.
*
* @return array<string,mixed>
*/
public static function normalizeGameStorage(array $raw, GameClock $clock): array
{
if (!array_key_exists('startTick', $raw)) {
$raw['startTick'] = $clock->dateTimeToTick(new \DateTimeImmutable((string)$raw['startDate']));
}
if (!array_key_exists('endTick', $raw)) {
$raw['endTick'] = ($raw['endDate'] ?? null) === null
? null
: $clock->dateTimeToTick(new \DateTimeImmutable((string)$raw['endDate']));
}
$raw['startTick'] = Util::toInt($raw['startTick']);
$raw['endTick'] = $raw['endTick'] === null ? null : Util::toInt($raw['endTick']);
$raw['startDate'] = $clock->formatTick($raw['startTick']);
$raw['endDate'] = $raw['endTick'] === null ? null : $clock->formatTick($raw['endTick']);
return $raw;
}
public static function fromGameStorage(array $raw, GameClock $clock): self
{
$raw = self::normalizeGameStorage($raw, $clock);
unset($raw['startTick'], $raw['endTick']);
return self::fromArray($raw);
}
public function __construct(
public int $id,
public string $title,
+4 -4
View File
@@ -49,7 +49,7 @@ class DiplomaticMessage extends Message{
$this->validDiplomacy = false;
}
if($this->validUntil < $this->date){
if($this->validUntil < (new \DateTime())){
$this->validDiplomacy = false;
}
}
@@ -215,7 +215,7 @@ class DiplomaticMessage extends Message{
$this->dest,
$this->src,
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id,
@@ -231,7 +231,7 @@ class DiplomaticMessage extends Message{
$this->dest,
$this->src,
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id,
@@ -281,4 +281,4 @@ class DiplomaticMessage extends Message{
return self::DECLINED;
}
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ class OpenNationBetting extends \sammo\Event\Action
}
$logger->flush();
$now = Message::gameNow();
$now = new DateTime();
$text = "새로운 {$name} 내기가 열렸습니다. 천통국 베팅란을 확인해주세요.";
$src = new MessageTarget(0, '', 0, 'System', '#000000');
+10 -7
View File
@@ -281,13 +281,16 @@ class General extends GeneralBase implements iAction
$this->calcCache[$cacheKey] = $result;
return $result;
}
$tickDiff = Util::toInt($this->getVar('turntime')) - Util::toInt($this->getVar('recent_war'));
if ($tickDiff <= 0) {
$this->calcCache[$cacheKey] = 0;
return 0;
}
$result = intdiv($tickDiff, GameClock::TICKS_PER_TURN);
$recwar = new \DateTimeImmutable($this->getVar('recent_war'));
$turnNow = new \DateTimeImmutable($this->getVar('turntime'));
$secDiff = TimeUtil::DateIntervalToSeconds($recwar->diff($turnNow));
if ($secDiff <= 0) {
$this->calcCache[$cacheKey] = 0;
return 0;
}
$result = intdiv(Util::toInt($secDiff), 60 * $turnTerm);
$this->calcCache[$cacheKey] = $result;
return $result;
}
+16 -13
View File
@@ -302,7 +302,7 @@ class GeneralAI
$this->calcWarRoute();
$troopCandidate = [];
$chiefTurn = cutTurn($this->general->getTurnTick(), $this->env['turnterm']);
$chiefTurn = cutTurn($this->general->getTurnTime(), $this->env['turnterm']);
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
foreach ($this->troopLeaders as $troopLeader) {
@@ -319,7 +319,7 @@ class GeneralAI
$last발령 = $troopLeader->getAuxVar('last발령');
if ($last발령) {
$leaderTurn = cutTurn($troopLeader->getTurnTick(), $this->env['turnterm']);
$leaderTurn = cutTurn($troopLeader->getTurnTime(), $this->env['turnterm']);
$compYearMonth = $yearMonth;
if ($chiefTurn < $leaderTurn) {
$compYearMonth += 1;
@@ -405,7 +405,7 @@ class GeneralAI
return null;
}
$chiefTurn = cutTurn($this->general->getTurnTick(), $this->env['turnterm']);
$chiefTurn = cutTurn($this->general->getTurnTime(), $this->env['turnterm']);
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
$troopCandidate = [];
@@ -428,7 +428,7 @@ class GeneralAI
$last발령 = $troopLeader->getAuxVar('last발령');
if ($last발령) {
$leaderTurn = cutTurn($troopLeader->getTurnTick(), $this->env['turnterm']);
$leaderTurn = cutTurn($troopLeader->getTurnTime(), $this->env['turnterm']);
$compYearMonth = $yearMonth;
if ($chiefTurn < $leaderTurn) {
$compYearMonth += 1;
@@ -586,8 +586,8 @@ class GeneralAI
continue;
}
$generalTurnTime = $userGeneral->getTurnTick();
$troopTurnTime = $troopLeader->getTurnTick();
$generalTurnTime = $userGeneral->getTurnTime();
$troopTurnTime = $troopLeader->getTurnTime();
if ($generalTurnTime < $troopTurnTime) { //NOTE: 어차피 수뇌 턴이 제일 빠르다
$generalCadidates[$generalID] = $userGeneral;
@@ -782,7 +782,7 @@ class GeneralAI
if (
key_exists($troopLeader->getCityID(), $this->supplyCities) &&
$this->troopLeaders[$troopID]->getTurnTick() < $lostGeneral->getTurnTick()
$this->troopLeaders[$troopID]->getTurnTime() < $lostGeneral->getTurnTime()
) {
//이미 탈출 가능한 부대를 탔다
continue;
@@ -1986,7 +1986,7 @@ class GeneralAI
if ($lastTurn->getCommand() === '천도' && $lastTurn->getArg()['destCityID'] != $this->nation['capital']) {
$cmd = buildNationCommandClass('che_천도', $this->general, $this->env, $lastTurn, $lastTurn->getArg());
if ($cmd->hasFullConditionMet()) {
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTick()];
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTime()];
$this->reqUpdateInstance = true;
return $cmd;
}
@@ -1995,9 +1995,12 @@ class GeneralAI
$lastTrial = $nationStor->last천도Trial;
if ($lastTrial) {
[$lastTrialLevel, $lastTrialTurnTime] = $lastTrial;
$timeDiffTick = abs($general->getTurnTick() - Util::toInt($lastTrialTurnTime));
if ($timeDiffTick < intdiv(GameClock::TICKS_PER_TURN, 2)
&& $lastTrialLevel !== $general->getVar('officer_level')) { //0.5Turn
$timeDiffSeconds = TimeUtil::DateIntervalToSeconds(
date_create_immutable($lastTrialTurnTime)->diff(
date_create_immutable($general->getTurnTime())
)
);
if ($timeDiffSeconds < $turnTerm * 30 && $lastTrialLevel !== $general->getVar('officer_level')) { //0.5Turn
return null;
}
}
@@ -2106,7 +2109,7 @@ class GeneralAI
}
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTick()];
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTime()];
$this->reqUpdateInstance = true;
return $cmd;
}
@@ -3727,7 +3730,7 @@ class GeneralAI
$src,
$src,
$general->getVar('npcmsg'),
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
+10 -33
View File
@@ -54,24 +54,14 @@ abstract class GeneralBase
);
}
function getTurnTime(int $short = self::TURNTIME_FULL_MS): ?string
{
if(!key_exists('turntime', $this->raw)){
return null;
}
$rawTurnTime = $this->getVar('turntime');
// 비교용 Dummy와 과거 fixture는 문자열을 잠시 허용하되 제품 DB는 tick만 사용합니다.
if (is_string($rawTurnTime) && !ctype_digit(ltrim($rawTurnTime, '-'))) {
$formattedTurnTime = $rawTurnTime;
} else {
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$formattedTurnTime = $clock->formatTick(Util::toInt($rawTurnTime), true);
}
return [
self::TURNTIME_FULL_MS => function ($turntime) {
function getTurnTime(int $short = self::TURNTIME_FULL_MS): ?string
{
if(!key_exists('turntime', $this->raw)){
return null;
}
return [
self::TURNTIME_FULL_MS => function ($turntime) {
return $turntime;
},
self::TURNTIME_FULL => function ($turntime) {
@@ -83,21 +73,8 @@ abstract class GeneralBase
self::TURNTIME_HM => function ($turntime) {
return substr($turntime, 11, 5);
},
][$short]($formattedTurnTime);
}
function getTurnTick(): ?int
{
if (!key_exists('turntime', $this->raw)) {
return null;
}
$rawTurnTime = $this->getVar('turntime');
if (is_string($rawTurnTime) && !ctype_digit(ltrim($rawTurnTime, '-'))) {
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
return $clock->dateTimeToTick(new \DateTimeImmutable($rawTurnTime));
}
return Util::toInt($rawTurnTime);
}
][$short]($this->getVar('turntime'));
}
function getNPCType(): int
{
+8 -7
View File
@@ -59,7 +59,7 @@ class RandomNameGeneral extends AbsGeneralPool{
'generalName'=>$generalName,
'imgsvr'=>0,
'picture'=>null
], PHP_INT_MAX);
], '9999-12-31 12:00:00');
}
static public function pickGeneralFromPool(MeekroDB $db, RandUtil $rng, int $owner, int $pickCnt, ?string $prefix = null): array
@@ -68,25 +68,26 @@ class RandomNameGeneral extends AbsGeneralPool{
$result = [];
$dbInsert = [];
$oNow = new \DateTimeImmutable();
for($i=0;$i<$pickCnt;$i++){
$result[] = static::pickGeneral1FromPool($db, $rng, $owner, $prefix);
}
if($owner){
$gameStor = \sammo\KVStorage::getStorage($db, 'game_env');
$clock = \sammo\GameClock::fromStorage($gameStor);
$now = $clock->nowTick();
$now = $oNow->format('Y-m-d H:i:s');
$db->delete('select_pool', [
'reserved_until'=>null,
'owner'=>null,
],'(reserved_until < %s OR reserved_until IS NULL) AND general_id IS null', $now);
$validUntil = $now + $clock->ticksFromSeconds(30);
$validUntil = $oNow->add(new \DateInterval(sprintf('PT%dS', 30)));
foreach($result as $pickedGeneral){
$dbInsert[] = [
'owner'=>$owner,
'uniqueName'=>$pickedGeneral->getUniqueName(),
'info'=>$pickedGeneral->getInfo(),
'reserved_until'=>$validUntil
'reserved_until'=>$validUntil->format(('Y-m-d H:i:s'))
];
}
$db->insert('select_pool', $dbInsert);
@@ -98,4 +99,4 @@ class RandomNameGeneral extends AbsGeneralPool{
public static function initPool(\MeekroDB $db){
//do Nothing
}
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ class SPoolUnderU100 extends AbsFromUserPool
private const STAT_BONUS_MAX_TOTAL = 190;
private const STAT_BONUS_MAX_MULTIPLIER = 1.5;
public function __construct(\MeekroDB $db, RandUtil $rng, array $info, int $validUntil)
public function __construct(\MeekroDB $db, RandUtil $rng, array $info, string $validUntil)
{
$targetInfo = $info;
$initialInfo = $info;
+18 -54
View File
@@ -26,12 +26,6 @@ class Message
) {
}
public static function gameNow(): \DateTime
{
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
return \DateTime::createFromImmutable($clock->nowDateTime());
}
public function setSentInfo(int $mailbox, int $messageID) : self
{
if(!Message::isValidMailBox($mailbox)){
@@ -84,15 +78,6 @@ class Message
}
public function toArray():array{
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$messageTick = $clock->dateTimeToTick($this->date);
$deleteUntilTick = GameClock::addTicks($messageTick, $clock->ticksFromMinutes(5));
$deleteRemainingTicks = max(0, $deleteUntilTick - $clock->nowTick());
$deleteRemainingTicks = min($deleteRemainingTicks, $clock->ticksFromSeconds(2_147_483));
$deleteRemainingMilliseconds = intdiv(
$deleteRemainingTicks * 1000,
$clock->ticksPerSecond(),
);
if($this->msgType === MessageType::public){
$src = $this->src->toArray();
$dest = null;
@@ -113,15 +98,12 @@ class Message
'dest'=>$dest,
'text'=>$this->msg,
'option'=>$this->msgOption,
'time'=>$this->date->format('Y-m-d H:i:s'),
'deleteRemainingMilliseconds'=>$deleteRemainingMilliseconds,
'clockMode'=>$clock->getMode(),
'time'=>$this->date->format('Y-m-d H:i:s')
];
}
public static function buildFromArray(array $row) : Message
{
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$dbMessage = Json::decode($row['message']);
$msgType = MessageType::from($row['type']);
@@ -134,8 +116,8 @@ class Message
$src,
$dest,
$dbMessage['text'],
\DateTime::createFromImmutable($clock->tickToDateTime(Util::toInt($row['time']))),
\DateTime::createFromImmutable($clock->tickToDateTime(Util::toInt($row['valid_until']))),
new \DateTime($row['time']),
new \DateTime($row['valid_until']),
$option
];
@@ -169,12 +151,9 @@ class Message
public static function getMessageByID(int $messageID) : ?Message
{
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$row = $db->queryFirstRow(
'SELECT * FROM `message` WHERE `id` = %i AND valid_until > %i',
$messageID,
$clock->nowTick(),
);
$now = new \DateTime();
$row = $db->queryFirstRow('SELECT * FROM `message` WHERE `id` = %i AND valid_until', $messageID);
//FIXME: $now가 들어가야 하는데 안 들어가있는데?
if (!$row) {
return null;
}
@@ -192,12 +171,12 @@ class Message
{
$db = DB::db();
$date = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->nowTick();
$date = (new \DateTime())->format('Y-m-d H:i:s');
$where = new \WhereClause('and');
$where->add('mailbox = %i', $mailbox);
$where->add('type = %s', $msgType->value);
$where->add('valid_until > %i', $date);
$where->add('valid_until > %s', $date);
if ($fromSeq > 0) {
$where->add('id >= %i', $fromSeq);
}
@@ -224,12 +203,12 @@ class Message
{
$db = DB::db();
$date = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->nowTick();
$date = (new \DateTime())->format('Y-m-d H:i:s');
$where = new \WhereClause('and');
$where->add('mailbox = %i', $mailbox);
$where->add('type = %s', $msgType->value);
$where->add('valid_until > %i', $date);
$where->add('valid_until > %s', $date);
$where->add('id < %i', $toSeq);
if ($limit > 0) {
@@ -257,8 +236,7 @@ class Message
return '시스템 외교 메시지는 삭제할 수 없습니다.';
}
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$prev5min = \DateTime::createFromImmutable($clock->tickToDateTime($clock->nowTick()));
$prev5min = new \DateTime();
$prev5min->sub(new \DateInterval('PT5M'));
if($msgObj->date < $prev5min){
@@ -287,15 +265,14 @@ class Message
}
$now = \DateTime::createFromImmutable($clock->tickToDateTime($clock->nowTick()));
$in1min = clone $now;
$in1min = new \DateTime();
$in1min->add(new \DateInterval('PT1M'));
$newMsg = new Message(
$msgObj->msgType,
$msgObj->src,
$msgObj->dest,
"req_del_msg",
$now,
new \DateTime(),
$in1min,
$msgOption
);
@@ -323,23 +300,13 @@ class Message
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$timeTick = $clock->nowTick();
if (Util::toInt($this->validUntil->format('Y')) >= 9000) {
$validUntilTick = GameClock::MAX_SAFE_TICK;
} else {
$validitySeconds = $this->validUntil->getTimestamp() - $this->date->getTimestamp();
$validUntilTick = $timeTick + $clock->ticksFromSeconds($validitySeconds);
}
$this->date = \DateTime::createFromImmutable($clock->tickToDateTime($timeTick));
$this->validUntil = \DateTime::createFromImmutable($clock->tickToDateTime($validUntilTick));
$db->insert('message', [
'mailbox' => $mailbox,
'type' => $this->msgType->value,
'src' => $src_id,
'dest' => $dest_id,
'time' => $timeTick,
'valid_until' => $validUntilTick,
'time' => $this->date->format('Y-m-d H:i:s'),
'valid_until' => $this->validUntil->format('Y-m-d H:i:s'),
'message' => Json::encode([
'src'=>($this->src)?($this->src->toArray()):[],
'dest'=>($this->dest)?($this->dest->toArray()):[],
@@ -463,7 +430,7 @@ class Message
$src,
$dest,
$msg,
self::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[]
);
@@ -497,8 +464,6 @@ class Message
}
public function invalidate(?array $newMsgOption=null, bool $hideMsg=true){
$clock = GameClock::fromStorage(KVStorage::getStorage(DB::db(), 'game_env'));
$validUntilTick = $clock->dateTimeToTick($this->validUntil);
if($newMsgOption !== null){
$this->msgOption = $newMsgOption;
}
@@ -506,8 +471,7 @@ class Message
$this->msgOption['invalid'] = true;
if($hideMsg){
$validUntilTick = GameClock::addTicks($clock->nowTick(), -1);
$this->validUntil = \DateTime::createFromImmutable($clock->tickToDateTime($validUntilTick));
$this->validUntil = new \DateTime('2000-12-31');
}
else{
if(key_exists('receiverMessageID', $this->msgOption)){
@@ -525,7 +489,7 @@ class Message
'text' => $this->msg,
'option' => $this->msgOption
]),
'valid_until'=>$validUntilTick,
'valid_until'=>$this->validUntil->format('Y-m-d H:i:s'),
], 'id=%i', $this->id);
}
+1 -1
View File
@@ -142,7 +142,7 @@ class RaiseInvaderMessage extends Message
$srcTarget = MessageTarget::buildSystemTarget();
$destTarget = MessageTarget::buildQuick($destGeneralID);
if ($date === null) {
$date = Message::gameNow();
$date = new \DateTime();
}
/**
+16 -34
View File
@@ -245,35 +245,21 @@ class ResetHelper{
true
);
$requestedTime = new \DateTimeImmutable($turntime);
if($sync == 0) {
// 현재 시간을 1월로 맞춤
$baseTime = new \DateTimeImmutable(cutTurnDateTime($turntime, $turnterm));
$month = 1;
$year = $startyear;
} else {
// 현재 시간과 동기화
[$baseTimeString, $yearPulled, $month] = cutDay($turntime, $turnterm);
$baseTime = new \DateTimeImmutable($baseTimeString);
if($sync == 0) {
// 현재 시간을 1월로 맞춤
$starttime = cutTurn($turntime, $turnterm);
$month = 1;
$year = $startyear;
} else {
// 현재 시간과 동기화
[$starttime, $yearPulled, $month] = cutDay($turntime, $turnterm);
if($yearPulled){
$year = $startyear-1;
}
else{
$year = $startyear;
}
}
$wallNow = GameClock::readWallTime();
$initialClock = new GameClock(
$baseTime,
$turnterm,
0,
GameClock::MODE_REALTIME,
$wallNow,
fn (): \DateTimeImmutable => $wallNow,
);
$requestedTick = $initialClock->dateTimeToTick($requestedTime);
$currentTick = $initialClock->dateTimeToTick($wallNow);
}
$killturn = 4800 / $turnterm;
if($npcmode == 1) { $killturn = intdiv($killturn, 3); }
@@ -297,14 +283,10 @@ class ResetHelper{
'maxnation'=>GameConst::$defaultMaxNation,
'refreshLimit'=>30000,
'develcost'=>$develcost,
'turntime'=>$requestedTick,
'starttime'=>0,
'opentime'=>$requestedTick,
'turnterm'=>$turnterm,
'clock_base_time'=>TimeUtil::format($baseTime, true),
'clock_tick'=>$currentTick,
'clock_mode'=>GameClock::MODE_REALTIME,
'clock_wall_anchor'=>TimeUtil::format($wallNow, true),
'turntime'=>$turntime,
'starttime'=>$starttime,
'opentime'=>$turntime,
'turnterm'=>$turnterm,
'killturn'=>$killturn,
'genius'=>GameConst::$defaultMaxGenius,
'show_img_level'=>$show_img_level,
@@ -326,7 +308,7 @@ class ResetHelper{
'name'=>$admin['name'],
'picture'=>$admin['picture'],
'imgsvr'=>$admin['imgsvr'],
'turntime'=>$requestedTick,
'turntime'=>$turntime,
'killturn'=>9999,
'crewtype'=>GameUnitConst::DEFAULT_CREWTYPE
]);
@@ -362,7 +344,7 @@ class ResetHelper{
$db->insert('ng_games', [
'server_id'=>$serverID,
'date'=>TimeUtil::format($requestedTime, false),
'date'=>$turntime,
'winner_nation'=>null,
'map'=>$scenarioObj->getMapTheme(),
'season'=>$seasonIdx,
@@ -386,4 +368,4 @@ class ResetHelper{
'result'=>true
];
}
}
}
+1 -1
View File
@@ -653,7 +653,7 @@ class GeneralBuilder{
$officerLevel = $nationID?1:0;
}
$turntime = \sammo\getRandTurn($this->rng, $env['turnterm'], Util::toInt($env['turntime']));
$turntime = \sammo\getRandTurn($this->rng, $env['turnterm'], new \DateTimeImmutable($env['turntime']));
if($this->killturn){
$killturn = $this->killturn;
+8 -8
View File
@@ -35,7 +35,7 @@ class ScoutMessage extends Message
$this->validScout = false;
}
if ($this->validUntil <= $this->date) {
if ($this->validUntil <= new \DateTime()) {
$this->validScout = false;
}
}
@@ -108,7 +108,7 @@ class ScoutMessage extends Message
$this->src,
$this->dest,
"{$this->src->nationName}{$josaRo} 등용 제의 수락",
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete' => $this->id
@@ -122,11 +122,11 @@ class ScoutMessage extends Message
public static function invalidateAll(int $generalID, ?int $exceptMsgID = null)
{
$db = DB::db();
$now = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'))->nowTick();
$now = TimeUtil::now();
//XXX: 뭔가 기존 쿼리가 애매하다. invalid 관련해서 다른 옵션이 가능한가?
$rawMsgList = Util::convertArrayToDict($db->query(
'SELECT * FROM `message` WHERE
`mailbox` = %i AND `type` = "private" AND `dest` = `mailbox` AND `valid_until` > %i AND
`mailbox` = %i AND `type` = "private" AND `dest` = `mailbox` AND `valid_until` > %s AND
JSON_VALUE(message, "$.option.action") = %s',
$generalID,
$now,
@@ -156,7 +156,7 @@ class ScoutMessage extends Message
$this->src,
$this->dest,
"{$this->src->nationName}{$josaRo} 등용 제의 거부",
Message::gameNow(),
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete' => $this->id
@@ -205,9 +205,9 @@ class ScoutMessage extends Message
$db = DB::db();
$srcGeneral = $db->queryFirstRow('SELECT `name`, nation FROM general WHERE `no`=%i', $srcGeneralID);
$destGeneral = $db->queryFirstRow('SELECT `name`, nation, `officer_level` FROM general WHERE `no`=%i', $destGeneralID);
if ($date === null) {
$date = Message::gameNow();
}
if ($date === null) {
$date = new \DateTime();
}
if ($destGeneral['officer_level'] == 12) {
if ($reason !== null) {
+21 -9
View File
@@ -40,22 +40,34 @@ final class ServerTool
$locked = tryLock();
}
if($turnterm == $admin['turnterm']){
$oldunit = $admin['turnterm'] * 60;
$unit = $turnterm * 60;
if($unit == $oldunit){
if($locked){
unlock();
}
return null;
}
$oldClock = GameClock::fromStorage($gameStor);
$currentTick = $oldClock->nowTick();
$currentDisplay = $oldClock->tickToDateTime($currentTick);
$oldClock->persistTick($gameStor, $currentTick);
$unitDiff = $unit / $oldunit;
$servTurnTime = new \DateTimeImmutable($admin['turntime']);
foreach ($db->query('SELECT no,turntime FROM general') as $gen) {
$genTurnTime = new \DateTimeImmutable($gen['turntime']);
$timeDiff = TimeUtil::DateIntervalToSeconds($genTurnTime->diff($servTurnTime));
$timeDiff *= $unitDiff;
$newGenTurnTime = $servTurnTime->add(TimeUtil::secondsToDateInterval($timeDiff));
$db->update('general', [
'turntime' => $newGenTurnTime->format('Y-m-d H:i:s.u')
], 'no=%i', $gen['no']);
}
$turn = ($admin['year'] - $admin['startyear']) * 12 + $admin['month'] - 1;
$starttime = $servTurnTime->sub(TimeUtil::secondsToDateInterval($turn * $unit))->format('Y-m-d H:i:s');
$starttime = cutTurn($starttime, $turnterm, false);
$gameStor->turnterm = $turnterm;
$gameStor->clock_base_time = TimeUtil::format(
GameClock::baseTimeForProjection($currentDisplay, $currentTick, $turnterm),
true,
);
$gameStor->starttime = $starttime;
pushGlobalHistoryLog(["<R>★</>턴시간이 <C>{$turnterm}분</>으로 변경됩니다."]);
if($locked){
+22 -36
View File
@@ -6,20 +6,15 @@ use sammo\Enums\EventTarget;
use sammo\Enums\InheritanceKey;
use \Symfony\Component\Lock;
class TurnExecutionHelper
{
class TurnExecutionHelper
{
/** @var General*/
protected $generalObj;
public function __construct(General $general)
public function __construct(General $general)
{
$this->generalObj = $general;
}
public static function monotonicCompletionTick(int $completedTick, int $candidateTick): int
{
return max($completedTick, $candidateTick);
}
}
public function __destruct()
{
@@ -220,13 +215,14 @@ class TurnExecutionHelper
$general->rebirth();
}
$turntime = addTurn($general->getTurnTick(), $gameStor->turnterm);
$turntime = addTurn($general->getTurnTime(), $gameStor->turnterm);
$nextTurnTimeBase = $general->getAuxVar('nextTurnTimeBase');
if($nextTurnTimeBase !== null){
$turntime = cutTurn($turntime, $gameStor->turnterm);
$clock = GameClock::fromStorage($gameStor);
$turntime += $clock->ticksFromSeconds($nextTurnTimeBase);
$turntimeObj = new \DateTimeImmutable($turntime);
$turntimeObj = $turntimeObj->add(TimeUtil::secondsToDateInterval($nextTurnTimeBase));
$turntime = TimeUtil::format($turntimeObj, true);
$general->setAuxVar('nextTurnTimeBase', null);
}
@@ -234,7 +230,7 @@ class TurnExecutionHelper
}
static public function executeGeneralCommandUntil(int $date, \DateTimeInterface $limitActionTime, int $year, int $month)
static public function executeGeneralCommandUntil(string $date, \DateTimeInterface $limitActionTime, int $year, int $month)
{
$db = DB::db();
$generalsTodo = $db->query(
@@ -248,7 +244,7 @@ class TurnExecutionHelper
$autorun_user = $gameStor->autorun_user;
foreach ($generalsTodo as $rawGeneral) {
$currActionTime = GameClock::readWallTime();
$currActionTime = new \DateTimeImmutable();
if ($currActionTime > $limitActionTime) {
return [true, $currentTurn];
}
@@ -354,7 +350,7 @@ class TurnExecutionHelper
pullNationCommand($general->getVar('nation'), $general->getVar('officer_level'));
pullGeneralCommand($general->getID());
$currentTurn = $general->getTurnTick();
$currentTurn = $general->getTurnTime();
$general->increaseVarWithLimit('myset', GameConst::$incDefSettingChange, null, GameConst::$maxDefSettingChange);
if (($autorun_user['limit_minutes'] ?? false) && $general->getNPCType() < 2 && $hasReservedTurn) {
@@ -394,14 +390,13 @@ class TurnExecutionHelper
return true;
}
static public function executeAllCommand(&$executed = false, &$locked = false): int
static public function executeAllCommand(&$executed = false, &$locked = false): string
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$clock = GameClock::fromStorage($gameStor);
if ($clock->nowTick() < $gameStor->turntime) {
if (TimeUtil::now(true) < $gameStor->turntime) {
//턴 시각 이전이면 아무것도 하지 않음
return $gameStor->turntime;
}
@@ -425,7 +420,7 @@ class TurnExecutionHelper
//접속자 수 따라서 갱신제한 변경
CheckOverhead();
$date = $clock->nowTick();
$date = TimeUtil::now(true);
// 최종 처리 월턴의 다음 월턴시간 구함
//$lastExecuted = $gameStor->turntime;
$prevTurn = cutTurn($gameStor->turntime, $gameStor->turnterm);
@@ -438,7 +433,7 @@ class TurnExecutionHelper
$maxActionTime = max($maxActionTime * 2 / 3, $maxActionTime - 10);
}
$limitActionTime = GameClock::readWallTime()->add(TimeUtil::secondsToDateInterval($maxActionTime));
$limitActionTime = (new \DateTimeImmutable())->add(TimeUtil::secondsToDateInterval($maxActionTime));
// 현재 턴 이전 월턴까지 모두처리.
//최종 처리 이후 다음 월턴이 현재 시간보다 전이라면
@@ -455,12 +450,9 @@ class TurnExecutionHelper
updateTraffic();
if ($executionOver) {
if ($currentTurn !== null) {
$executed = true;
$gameStor->turntime = self::monotonicCompletionTick(
Util::toInt($gameStor->turntime),
$currentTurn,
);
if ($currentTurn !== null) {
$executed = true;
$gameStor->turntime = $currentTurn;
}
unlock();
return $gameStor->turntime;
@@ -505,16 +497,10 @@ class TurnExecutionHelper
$gameStor->month
);
if ($currentTurn !== null) {
$executed = true;
// A general's sub-tick can be just before the monthly boundary that
// was completed above. Never move the global completion cursor back
// behind an already-applied monthly event.
$gameStor->turntime = self::monotonicCompletionTick(
Util::toInt($gameStor->turntime),
$currentTurn,
);
}
if ($currentTurn !== null) {
$executed = true;
$gameStor->turntime = $currentTurn;
}
//토너먼트 처리
processTournament();
+1 -2
View File
@@ -55,8 +55,7 @@ class UserLogger
}
$db = DB::db();
$clock = GameClock::fromStorage(KVStorage::getStorage($db, 'game_env'));
$date = $clock->formatTick($clock->nowTick());
$date = TimeUtil::now();
$serverID = UniqueConst::$serverID;
$request = array_map(function ($textAndType) use ($date, $serverID) {
[$text, $type] = $textAndType;
+5 -5
View File
@@ -57,16 +57,16 @@ class WarUnitGeneral extends WarUnit
$this->general->increaseRankVar(RankColumn::warnum, 1);
if ($this->isAttacker) {
$semiTurn = $general->getTurnTick();
$semiTurn = $general->getTurnTime();
} else if ($oppose !== null) {
$semiTurn = $oppose->getGeneral()->getTurnTick();
$semiTurn = $oppose->getGeneral()->getTurnTime();
} else {
LogText("WarUnitGeneral::setOppose", "defender인데 oppose가 null {$general->getID()}, {$general->getTurnTime()}");
$semiTurn = $general->getTurnTick();
$semiTurn = $general->getTurnTime();
}
$phase = $this->getRealPhase();
$semiTurn -= $semiTurn % 100;
$semiTurn += Util::valueFit($phase, 0, 99);
$semiTurn = substr($semiTurn, 0, strlen($semiTurn) - 2);
$semiTurn .= sprintf("%02d", Util::valueFit($phase, 0, 99));
$general->setVar('recent_war', $semiTurn);
}
+14 -14
View File
@@ -45,8 +45,8 @@ CREATE TABLE `general` (
`book` VARCHAR(20) NOT NULL DEFAULT 'None',
`horse` VARCHAR(20) NOT NULL DEFAULT 'None',
`item` VARCHAR(20) NOT NULL DEFAULT 'None',
`turntime` BIGINT NOT NULL,
`recent_war` BIGINT NULL DEFAULT NULL,
`turntime` DATETIME(6) NOT NULL,
`recent_war` DATETIME(6) NULL DEFAULT NULL,
`makelimit` INT(2) NULL DEFAULT '0',
`killturn` INT(3) NULL DEFAULT NULL,
`block` INT(1) NULL DEFAULT '0',
@@ -97,7 +97,7 @@ CREATE TABLE `general_access_log` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`general_id` INT(11) NOT NULL,
`user_id` INT(11) NULL DEFAULT NULL,
`last_refresh` BIGINT NULL DEFAULT NULL,
`last_refresh` DATETIME NULL DEFAULT NULL,
`refresh` INT(11) NOT NULL DEFAULT '0',
`refresh_total` INT(11) NOT NULL DEFAULT '0',
`refresh_score` INT(11) NOT NULL DEFAULT '0',
@@ -244,8 +244,8 @@ CREATE TABLE `message` (
`type` ENUM('private', 'national', 'public', 'diplomacy') NOT NULL,
`src` INT(11) NOT NULL,
`dest` INT(11) NOT NULL,
`time` BIGINT NOT NULL,
`valid_until` BIGINT NOT NULL,
`time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`valid_until` DATETIME NOT NULL DEFAULT '9999-12-31 23:59:59',
`message` TEXT NOT NULL COLLATE 'utf8mb4_bin',
PRIMARY KEY (`id`),
INDEX `by_mailbox` (`mailbox`, `type`, `id`),
@@ -297,7 +297,7 @@ CREATE TABLE IF NOT EXISTS `ng_old_nations` (
`server_id` CHAR(20) NOT NULL DEFAULT '0',
`nation` INT(11) NOT NULL DEFAULT '0',
`data` LONGTEXT NOT NULL DEFAULT '{}' COLLATE 'utf8mb4_bin',
`date` DATETIME NOT NULL,
`date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
INDEX `server_id` (`server_id`, `nation`),
CONSTRAINT `json` CHECK (json_valid(`data`))
@@ -395,7 +395,7 @@ CREATE TABLE `ng_diplomacy` (
`state` ENUM('proposed', 'activated', 'cancelled', 'replaced') NOT NULL DEFAULT 'proposed',
`text_brief` TEXT NOT NULL,
`text_detail` TEXT NOT NULL,
`date` DATETIME NOT NULL,
`date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`src_signer` INT(11) NOT NULL,
`dest_signer` INT(11) NULL DEFAULT NULL,
`aux` TEXT NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
@@ -536,8 +536,8 @@ CREATE TABLE IF NOT EXISTS `reserved_open` (
CREATE TABLE `select_npc_token` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`owner` INT(11) NOT NULL,
`valid_until` BIGINT NOT NULL,
`pick_more_from` BIGINT NOT NULL,
`valid_until` DATETIME NOT NULL,
`pick_more_from` DATETIME NOT NULL,
`pick_result` TEXT NOT NULL COLLATE 'utf8mb4_bin',
`nonce` INT(11) NOT NULL,
PRIMARY KEY (`id`),
@@ -553,7 +553,7 @@ CREATE TABLE `select_pool` (
`unique_name` VARCHAR(20) NOT NULL,
`owner` INT(11) NULL DEFAULT NULL,
`general_id` INT(11) NULL DEFAULT NULL,
`reserved_until` BIGINT NULL DEFAULT NULL,
`reserved_until` DATETIME NULL DEFAULT NULL,
`info` TEXT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `unique_name` (`unique_name`),
@@ -694,11 +694,11 @@ CREATE TABLE `ng_auction` (
`target` VARCHAR(50) NULL DEFAULT NULL COLLATE 'utf8mb4_bin',
`host_general_id` INT(11) NOT NULL,
`req_resource` ENUM('gold','rice','inheritPoint') NOT NULL COLLATE 'utf8mb4_bin',
`open_tick` BIGINT NOT NULL,
`close_tick` BIGINT NOT NULL,
`open_date` DATETIME NOT NULL,
`close_date` DATETIME NOT NULL,
`detail` LONGTEXT NOT NULL COLLATE 'utf8mb4_bin',
PRIMARY KEY (`id`) USING BTREE,
INDEX `by_close` (`finished`, `type`, `close_tick`) USING BTREE,
INDEX `by_close` (`finished`, `type`, `close_date`) USING BTREE,
INDEX `by_general_id` (`host_general_id`, `type`, `finished`) USING BTREE,
CONSTRAINT `detail` CHECK (json_valid(`detail`))
)
@@ -721,4 +721,4 @@ CREATE TABLE `ng_auction_bid` (
CONSTRAINT `aux` CHECK (json_valid(`aux`))
)
COLLATE='utf8mb4_general_ci'
ENGINE = Aria;
ENGINE = Aria;
-14
View File
@@ -1,14 +0,0 @@
import assert from 'assert';
import { resolveGatewayOpenState } from '../ts/gateway/resolveGatewayOpenState';
describe('resolveGatewayOpenState', () => {
it('keeps the logical server decision even when projected dates disagree with wall time', () => {
assert.strictEqual(resolveGatewayOpenState(false, '2000-01-01 00:00:00', '2026-08-04 00:00:00'), false);
assert.strictEqual(resolveGatewayOpenState(true, '2042-01-01 00:00:00', '2026-08-04 00:00:00'), true);
});
it('falls back to legacy wall time only when isOpen is absent', () => {
assert.strictEqual(resolveGatewayOpenState(undefined, '2026-08-03 00:00:00', '2026-08-04 00:00:00'), true);
assert.strictEqual(resolveGatewayOpenState(undefined, '2026-08-05 00:00:00', '2026-08-04 00:00:00'), false);
});
});
+1 -3
View File
@@ -42,7 +42,6 @@
:maxTurn="maxChiefTurn"
:maxPushTurn="Math.floor(maxChiefTurn / 2)"
:date="date"
:clockMode="clockMode"
:officer="officer"
@raiseReload="reloadTable()"
/>
@@ -140,7 +139,6 @@ const tableObj = reactive<Omit<OptionalFull<ChiefResponse>, "result">>({
month: undefined,
turnTerm: undefined,
date: undefined,
clockMode: undefined,
troopList: undefined,
chiefList: undefined,
isChief: undefined,
@@ -151,7 +149,7 @@ const tableObj = reactive<Omit<OptionalFull<ChiefResponse>, "result">>({
unitSet: undefined,
});
const { year, month, turnTerm, date, clockMode, chiefList, troopList, officerLevel, commandList } = toRefs(tableObj);
const { year, month, turnTerm, date, chiefList, troopList, officerLevel, commandList } = toRefs(tableObj);
let postFilterNationCommand = function (turnObj: TurnObj): TurnObj {
return turnObj;
+9 -1
View File
@@ -195,6 +195,7 @@ import { onMounted, reactive, ref, watch, computed } from "vue";
import type { VoteInfo, VoteDetailResult } from "@/defs/API/Vote";
import { SammoAPI } from "@/SammoAPI";
import { isString, range, sum } from "lodash-es";
import { formatTime } from "@/util/formatTime";
import { isBrightColor } from "@/util/isBrightColor";
import { formatVoteColor } from "@/utilGame/formatVoteColor";
@@ -238,7 +239,14 @@ const canVote = computed(() => {
if (currentVote.value.myVote) {
return false;
}
return currentVote.value.isOpen;
const endDate = currentVote.value.voteInfo.endDate;
if (endDate) {
const now = formatTime(new Date());
if (now > endDate) {
return false;
}
}
return true;
});
const currentVoteID = ref<number>();
+1 -3
View File
@@ -13,7 +13,7 @@
class="col alert alert-primary m-0 p-0"
style="text-align: center; display: flex; justify-content: center; align-items: center"
>
<SimpleClock :serverTime="serverNow" :running="clockRunning" />
<SimpleClock :serverTime="serverNow" />
</div>
<div class="col d-grid">
<BDropdown right text="반복">
@@ -467,7 +467,6 @@ async function pushGeneralCommand(amount: number) {
}
const serverNow = ref(new Date());
const clockRunning = ref(true);
function pushGeneralCommandSingle(e: Event) {
//NOTE: split ,
@@ -549,7 +548,6 @@ async function reloadCommandList() {
}
serverNow.value = parseTime(result.date);
clockRunning.value = result.clockMode === "realtime";
}
async function reserveCommandDirect(args: [number[], TurnObj][], reload = true): Promise<boolean> {
+1 -5
View File
@@ -27,7 +27,7 @@
<div class="row gx-1 gy-1 py-1">
<div class="col-lg-4 mx-0 mb-0 mt-1 d-grid">
<div class="alert alert-primary mb-0 center" style="padding: 0.5rem 0">
<SimpleClock :serverTime="parseTime(props.date)" :running="props.clockMode === 'realtime'" />
<SimpleClock :serverTime="parseTime(props.date)" />
</div>
</div>
@@ -289,10 +289,6 @@ const props = defineProps({
maxTurn: VueTypes.integer.isRequired,
maxPushTurn: VueTypes.integer.isRequired,
date: VueTypes.string.isRequired,
clockMode: {
type: String as PropType<"realtime" | "manual">,
required: true,
},
year: VueTypes.integer.isRequired,
month: VueTypes.integer.isRequired,
turnTerm: VueTypes.integer.isRequired,
+5 -2
View File
@@ -126,6 +126,8 @@
<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 { computed, onMounted, ref, toRef, watch, type ComputedRef, type Ref } from "vue";
import linkifyStr from "linkify-string";
import { SammoAPI } from "@/SammoAPI";
@@ -203,10 +205,11 @@ function testDeletable(msg: MsgItem): boolean {
if (msg.option.invalid) return false;
if (!(msg.option.deletable ?? true)) return false;
const timeDiff = msg.deleteRemainingMilliseconds;
const now = new Date();
const last5min = addMinutes(parseTime(msg.time), 5);
const timeDiff = differenceInMilliseconds(last5min, now);
if (timeDiff <= 0) return false;
if (msg.clockMode === "manual") return true;
deletableTimer.value = window.setTimeout(() => {
deletable.value = testDeletable(msg);
+7 -27
View File
@@ -4,7 +4,7 @@
<script lang="ts" setup>
import { addMilliseconds } from "date-fns";
import { type PropType, ref, onMounted, onUnmounted, watch } from "vue";
import { type PropType, ref, onMounted, watch } from "vue";
import { formatTime } from "@/util/formatTime";
const props = defineProps({
serverTime: {
@@ -17,39 +17,25 @@ const props = defineProps({
required: false,
default: "HH:mm:ss",
},
running: {
type: Boolean,
default: true,
},
});
const timeDiff = ref(0);
const serverNow = ref("");
watch(
() => [props.serverTime, props.running] as const,
([newValue]) => {
() => props.serverTime,
(newValue) => {
const clientNow = new Date();
timeDiff.value = newValue.getTime() - clientNow.getTime();
updateNow();
}
);
let timer: ReturnType<typeof setTimeout> | undefined;
function updateNow() {
if (timer !== undefined) {
clearTimeout(timer);
timer = undefined;
}
const serverNowObj = props.running
? addMilliseconds(new Date(), timeDiff.value)
: props.serverTime;
const serverNowObj = addMilliseconds(new Date(), timeDiff.value);
serverNow.value = formatTime(serverNowObj, props.timeFormat);
if (props.running) {
timer = setTimeout(() => {
updateNow();
}, 1000 - serverNowObj.getMilliseconds());
}
setTimeout(() => {
updateNow();
}, 1000 - serverNowObj.getMilliseconds());
}
onMounted(() => {
@@ -57,10 +43,4 @@ onMounted(() => {
timeDiff.value = props.serverTime.getTime() - clientNow.getTime();
updateNow();
});
onUnmounted(() => {
if (timer !== undefined) {
clearTimeout(timer);
}
});
</script>
-1
View File
@@ -7,7 +7,6 @@ export type ReservedCommandResponse = {
year: number;
month: number;
date: string;
clockMode: "realtime" | "manual";
turn: TurnObj[];
autorun_limit: null | number;
};
+1 -3
View File
@@ -34,8 +34,6 @@ export type MsgItem = {
delete?: number;
};
time: string;
deleteRemainingMilliseconds: number;
clockMode: "realtime" | "manual";
};
export type MsgPrintItem = MsgItem & {
@@ -79,4 +77,4 @@ export type MailboxItem = {
export type MabilboxListResponse = {
result: true,
nation: MailboxItem[]
}
}

Some files were not shown because too many files have changed in this diff Show More