Compare commits

...
25 Commits
Author SHA1 Message Date
Hide_D f5c5b56492 dep: babel-loader + ts-loader => esbuild-loader 2021-09-18 04:31:31 +09:00
Hide_D 69c69d63e6 dep: package upgrade 2021-09-18 03:52:27 +09:00
Hide_D 3fd8b21867 misc: lint warning, 불필요 파일 정리 2021-09-18 03:49:04 +09:00
Hide_D 8660e8cd85 fix: NPC포상 설정 메시지 수정 2021-09-18 03:42:20 +09:00
Hide_D 8458f725f2 fix: 사망 시 유산 포인트 관련 환불/초기화가 없는 문제 2021-09-18 03:36:08 +09:00
Hide_D 366678c965 fix: 장수 생성창 보이기/숨기기, 턴 시간 고정 표기 수정 2021-09-18 02:49:47 +09:00
Hide_D 336b5668db fix & inheritAction: 랜덤 유니크 습득시 환불 가능하게 수정 2021-09-18 00:15:00 +09:00
Hide_D 55886269ea inheritAction: 설문조사에서는 특정 유니크 구입 기능 해제 2021-09-18 00:06:20 +09:00
Hide_D 0b3698595b fix: hash -> gitHash 2021-09-17 23:40:47 +09:00
Hide_D 05e43a39db fix: 턴 초기화, 전특 초기화 표기 방식 변경 2021-09-17 23:37:53 +09:00
Hide_D 5737ad3db2 fix: 턴 초기화, 특기 초기화 포인트 안내가 1스텝 늦음 2021-09-17 23:34:33 +09:00
Hide_D 4ac174eb9a fix: 반계시도에는 구분 코드가 동작하지 않았음 2021-09-17 23:17:13 +09:00
Hide_D 895eec10b4 fix: 비급 반계가 전특 반계와 같이 동작하지 않는 버그 수정 2021-09-17 23:07:45 +09:00
Hide_D e0d891e89a fix: 재야일 때에는 임관 년도 증가하지 않도록 2021-09-17 03:14:14 +09:00
Hide_D adf7734b85 fix: 생성하자마자 임관 1년차로 나오는 문제 수정 2021-09-17 03:12:38 +09:00
Hide_D 5362be9c21 inheritPoint: 로그 기록 2021-09-17 02:39:11 +09:00
Hide_D 847ece52f2 fix: summernote.css 2021-09-16 22:39:19 +09:00
Hide_D 851c59d22c fix: 유저전투장 긴급포상 쌀 2021-09-16 22:37:31 +09:00
Hide_D 0669534bba fix: 궁 유니크 저격 계수 2021-09-16 22:24:29 +09:00
Hide_D 05db47e62a fix: 설문조사에서 환불 불가능한 문제 수정 2021-09-16 22:06:57 +09:00
Hide_D 4a0e608d1c fix: itemTrials 삭제 후 통째로 array가 비면 array도 마저 삭제 2021-09-16 22:00:35 +09:00
Hide_D 45fe73af86 fix: eventColumn에 aux 추가 2021-09-16 21:47:32 +09:00
Hide_D 4d9fcd657f fix: vote에서 aux 2021-09-16 21:43:37 +09:00
Hide_D a057deb0fe fix: 유니크를 얻는 턴이 아니더라도 환불은 하도록 수정 2021-09-16 21:38:43 +09:00
Hide_D 4766210a7d 랜임 실패시 실행 턴. 요양 -> 인탐 2021-09-16 21:24:52 +09:00
45 changed files with 906 additions and 736 deletions
+1
View File
@@ -64,6 +64,7 @@ var storedData = <?=Json::encode([
<?=WebUtil::printJS('dist_js/vendors.js')?> <?=WebUtil::printJS('dist_js/vendors.js')?>
<?=WebUtil::printJS('dist_js/dipcenter.js')?> <?=WebUtil::printJS('dist_js/dipcenter.js')?>
<?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?> <?=WebUtil::printCSS('../e_lib/bootstrap.min.css')?>
<?=WebUtil::printCSS('../e_lib/summernote/summernote-bs4.css')?>
<?=WebUtil::printCSS('dist_css/vendors.css')?> <?=WebUtil::printCSS('dist_css/vendors.css')?>
<?=WebUtil::printCSS('../d_shared/common.css')?> <?=WebUtil::printCSS('../d_shared/common.css')?>
<?=WebUtil::printCSS('css/common.css')?> <?=WebUtil::printCSS('css/common.css')?>
+1 -1
View File
@@ -24,7 +24,7 @@ $admin = $gameStor->getValues(['develcost', 'cost', 'vote_title', 'vote', 'votec
$generalID = Session::getGeneralID(); $generalID = Session::getGeneralID();
$general = General::createGeneralObjFromDB($generalID, ['vote','horse','weapon','book','item','npc'], 2); $general = General::createGeneralObjFromDB($generalID, ['vote','horse','weapon','book','item','npc','imgsvr','picture','aux'], 2);
if($btn == "투표" && $general->getVar('vote') == 0 && $sel > 0) { if($btn == "투표" && $general->getVar('vote') == 0 && $sel > 0) {
$develcost = $admin['develcost'] * 5; $develcost = $admin['develcost'] * 5;
+44 -13
View File
@@ -1256,9 +1256,12 @@ function addAge()
//나이와 호봉 증가 //나이와 호봉 증가
$db->update('general', [ $db->update('general', [
'age' => $db->sqleval('age+1'), 'age' => $db->sqleval('age+1'),
'belong' => $db->sqleval('belong+1')
], true); ], true);
$db->update('general', [
'belong' => $db->sqleval('belong+1')
], 'nation != 0');
[$startYear, $year, $month] = $gameStor->getValuesAsArray(['startyear', 'year', 'month']); [$startYear, $year, $month] = $gameStor->getValuesAsArray(['startyear', 'year', 'month']);
if ($year >= $startYear + 3) { if ($year >= $startYear + 3) {
@@ -1286,12 +1289,11 @@ function addAge()
$generalAux = Json::decode($general['aux']); $generalAux = Json::decode($general['aux']);
$updateVars = []; $updateVars = [];
if(key_exists('inheritSpecificSpecialWar', $generalAux)){ if (key_exists('inheritSpecificSpecialWar', $generalAux)) {
$special2 = $generalAux['inheritSpecificSpecialWar']; $special2 = $generalAux['inheritSpecificSpecialWar'];
unset($generalAux['inheritSpecificSpecialWar']); unset($generalAux['inheritSpecificSpecialWar']);
$updateVars['aux'] = Json::encode($generalAux); $updateVars['aux'] = Json::encode($generalAux);
} } else {
else{
$special2 = SpecialityHelper::pickSpecialWar( $special2 = SpecialityHelper::pickSpecialWar(
$general, $general,
($generalAux['prev_types_special2']) ?? [] ($generalAux['prev_types_special2']) ?? []
@@ -1592,9 +1594,19 @@ function giveRandomUniqueItem(General $general, string $acquireType): bool
} }
if (!$availableUnique) { if (!$availableUnique) {
if ($general->getAuxVar('inheritRandomUnique')) {
$general->setAuxVar('inheritRandomUnique', null);
$general->increaseInheritancePoint('previous', GameConst::$inheritItemRandomPoint);
$userLogger = new UserLogger($general->getVar('owner'));
$userLogger->push(sprintf("얻을 유니크가 없어 %d 포인트 반환", GameConst::$inheritItemRandomPoint), "inheritPoint");
}
return false; return false;
} }
if ($general->getAuxVar('inheritRandomUnique')) {
$general->setAuxVar('inheritRandomUnique', null);
}
[$itemType, $itemCode] = Util::choiceRandomUsingWeightPair($availableUnique); [$itemType, $itemCode] = Util::choiceRandomUsingWeightPair($availableUnique);
$nationName = $general->getStaticNation()['name']; $nationName = $general->getStaticNation()['name'];
@@ -1628,22 +1640,29 @@ function rollbackInheritUniqueTrial(General $general, string $itemKey, string $r
$itemTrials = $general->getAuxVar('inheritUniqueTrial'); $itemTrials = $general->getAuxVar('inheritUniqueTrial');
LogText("선택유니크 롤백:{$ownerID}", [$itemKey, $itemTrials]); LogText("선택유니크 롤백:{$ownerID}", [$itemKey, $itemTrials]);
unset($itemTrials[$itemKey]); unset($itemTrials[$itemKey]);
if(count($itemTrials) == 0){
$itemTrials = null;
}
$general->setAuxVar('inheritUniqueTrial', $itemTrials); $general->setAuxVar('inheritUniqueTrial', $itemTrials);
$trialStor = KVStorage::getStorage($db, "ut_{$itemKey}"); $trialStor = KVStorage::getStorage($db, "ut_{$itemKey}");
$ownTrial = $trialStor->getValue("u{$ownerID}"); $ownTrial = $trialStor->getValue("u{$ownerID}");
$itemObj = buildItemClass($itemKey);
$itemName = $itemObj->getName();
if ($ownTrial) { if ($ownTrial) {
//두 값이 general, KVStorage 둘다 있고, 이중에선 KVStorage 값을 기준으로 하자 따르자 //두 값이 general, KVStorage 둘다 있고, 이중에선 KVStorage 값을 기준으로 하자 따르자
[,, $amount] = $ownTrial; [,, $amount] = $ownTrial;
$trialStor->deleteValue("u{$ownerID}"); $trialStor->deleteValue("u{$ownerID}");
$general->increaseInheritancePoint('previous', $amount); $general->increaseInheritancePoint('previous', $amount);
LogText("선택유니크 롤백포인트:{$ownerID}", $amount); LogText("선택유니크 롤백포인트:{$ownerID}", $amount);
$userLogger = new UserLogger($ownerID);
$userLogger->push("{$itemName} 입찰에 사용한 {$amount} 포인트 반환", "inheritPoint");
} }
$itemObj = buildItemClass($itemKey);
$itemName = $itemObj->getName();
//메시지 //메시지
$staticNation = $general->getStaticNation(); $staticNation = $general->getStaticNation();
@@ -1662,11 +1681,16 @@ function rollbackInheritUniqueTrial(General $general, string $itemKey, string $r
[] []
); );
$msg->send(true);
$general->applyDB($db); $general->applyDB($db);
$msg->send(true);
} }
function tryInheritUniqueItem(General $general, string $acquireType = '아이템'): bool function tryRollbackInheritUniqueItem(General $general): void
{
tryInheritUniqueItem($general, 'Rollback', true);
}
function tryInheritUniqueItem(General $general, string $acquireType = '아이템', bool $justRollback = false): bool
{ {
$ownerID = $general->getVar('owner'); $ownerID = $general->getVar('owner');
if (!$ownerID) { if (!$ownerID) {
@@ -1769,6 +1793,9 @@ function tryInheritUniqueItem(General $general, string $acquireType = '아이템
if ($ownTarget === null) { if ($ownTarget === null) {
return false; return false;
} }
if ($justRollback) {
return false;
}
LogText("선택유니크획득{$ownerID}", $ownTarget); LogText("선택유니크획득{$ownerID}", $ownTarget);
@@ -1814,7 +1841,7 @@ function tryUniqueItemLottery(General $general, string $acquireType = '아이템
} }
$inheritUnique = $general->getAuxVar('inheritUniqueTrial'); $inheritUnique = $general->getAuxVar('inheritUniqueTrial');
if ($inheritUnique && count($inheritUnique)) { if ($acquireType != '설문조사' && $inheritUnique && count($inheritUnique)) {
LogText("유니크 준비?? {$general->getID()}", $inheritUnique); LogText("유니크 준비?? {$general->getID()}", $inheritUnique);
$trialResult = tryInheritUniqueItem($general, $acquireType); $trialResult = tryInheritUniqueItem($general, $acquireType);
if ($trialResult) { if ($trialResult) {
@@ -1833,6 +1860,12 @@ function tryUniqueItemLottery(General $general, string $acquireType = '아이템
if ($trialCnt <= 0) { if ($trialCnt <= 0) {
LogText("{$general->getName()}, {$general->getID()} 모든 아이템", $trialCnt); LogText("{$general->getName()}, {$general->getID()} 모든 아이템", $trialCnt);
if ($general->getAuxVar('inheritRandomUnique')) {
$general->setAuxVar('inheritRandomUnique', null);
$general->increaseInheritancePoint('previous', GameConst::$inheritItemRandomPoint);
$userLogger = new UserLogger($general->getVar('owner'));
$userLogger->push(sprintf("유니크를 얻을 공간이 없어 %d 포인트 반환", GameConst::$inheritItemRandomPoint), "inheritPoint");
}
return false; return false;
} }
@@ -1859,13 +1892,11 @@ function tryUniqueItemLottery(General $general, string $acquireType = '아이템
$result = false; $result = false;
$prob /= sqrt(2); $prob /= sqrt(2);
$moreProb = pow(2, 1/4); $moreProb = pow(2, 1 / 4);
if($general->getAuxVar('inheritRandomUnique')){ if ($general->getAuxVar('inheritRandomUnique')) {
//포인트로 랜덤 유니크 획득 //포인트로 랜덤 유니크 획득
$prob = 1; $prob = 1;
LogText("{$general->getName()}, {$general->getID()} 유산 포인트 유니크", $prob);
$general->setAuxVar('inheritRandomUnique', null);
} }
foreach (Util::range($trialCnt) as $_idx) { foreach (Util::range($trialCnt) as $_idx) {
+10
View File
@@ -1166,13 +1166,23 @@ function resetInheritanceUser(int $userID, bool $isRebirth=false):float{
//이미 리셋되었으므로 리셋 안함 //이미 리셋되었으므로 리셋 안함
return $allPoints['previous'][0]; return $allPoints['previous'][0];
} }
$userLogger = new UserLogger($userID);
$previousPoint = ($allPoints['previous']??[0,0])[0];
foreach($allPoints as $key=>[$value,]){ foreach($allPoints as $key=>[$value,]){
if($isRebirth && key_exists($key, $rebirthDegraded)){ if($isRebirth && key_exists($key, $rebirthDegraded)){
$value *= $rebirthDegraded[$key]; $value *= $rebirthDegraded[$key];
} }
$keyText = General::INHERITANCE_KEY[$key][2];
$userLogger->push("{$keyText} 포인트 {$value} 증가", "inheritPoint");
$totalPoint += $value; $totalPoint += $value;
} }
$totalPoint = Util::toInt($totalPoint); $totalPoint = Util::toInt($totalPoint);
$userLogger->push("포인트 {$previousPoint} => {$totalPoint}", "inheritPoint");
$userLogger->flush();
$inheritStor->resetValues(); $inheritStor->resetValues();
$inheritStor->setValue('previous', [$totalPoint, null]); $inheritStor->setValue('previous', [$totalPoint, null]);
return $totalPoint; return $totalPoint;
+5 -5
View File
@@ -47,7 +47,7 @@ else{
'name', 'leadership', 'strength', 'intel', 'gold','rice', 'name', 'leadership', 'strength', 'intel', 'gold','rice',
'troop','officer_level','npc','picture','imgsvr', 'troop','officer_level','npc','picture','imgsvr',
'permission','penalty','belong', 'crewtype', 'permission','penalty','belong', 'crewtype',
'experience', 'dedication', 'betray', 'dedlevel', 'explevel', 'makelimit', 'experience', 'dedication', 'betray', 'dedlevel', 'explevel', 'makelimit', 'aux',
], 1); ], 1);
if($general instanceof DummyGeneral){ if($general instanceof DummyGeneral){
@@ -104,7 +104,7 @@ function do수뇌임명(General $general, int $targetOfficerLevel):?string{
if($general->getVar('strength') < GameConst::$chiefStatMin){ if($general->getVar('strength') < GameConst::$chiefStatMin){
return '무력이 부족합니다.'; return '무력이 부족합니다.';
} }
} }
else{ else{
if($general->getVar('intel') < GameConst::$chiefStatMin){ if($general->getVar('intel') < GameConst::$chiefStatMin){
@@ -175,7 +175,7 @@ function do추방(General $general, int $myOfficerLevel):?string{
$generalName = $general->getVar('name'); $generalName = $general->getVar('name');
$nationID = $general->getNationID(); $nationID = $general->getNationID();
//추방할사람이 외교권자이면 불가 //추방할사람이 외교권자이면 불가
$permission = checkSecretPermission($general->getRaw()); $permission = checkSecretPermission($general->getRaw());
@@ -252,7 +252,7 @@ function do추방(General $general, int $myOfficerLevel):?string{
]); ]);
$src = new MessageTarget( $src = new MessageTarget(
$generalID, $generalID,
$generalName, $generalName,
$nationID, $nationID,
$nation['name'], $nation['name'],
@@ -260,7 +260,7 @@ function do추방(General $general, int $myOfficerLevel):?string{
GetImageURL($general->getVar('imgsvr'), $general->getVar('picture')) GetImageURL($general->getVar('imgsvr'), $general->getVar('picture'))
); );
$msg = new Message( $msg = new Message(
Message::MSGTYPE_PUBLIC, Message::MSGTYPE_PUBLIC,
$src, $src,
$src, $src,
$str, $str,
+15 -2
View File
@@ -16,6 +16,7 @@ use sammo\Session;
use sammo\SpecialityHelper; use sammo\SpecialityHelper;
use sammo\StringUtil; use sammo\StringUtil;
use sammo\TimeUtil; use sammo\TimeUtil;
use sammo\UserLogger;
use sammo\Util; use sammo\Util;
use sammo\Validator; use sammo\Validator;
use sammo\WebUtil; use sammo\WebUtil;
@@ -152,11 +153,13 @@ class Join extends \sammo\BaseAPI
} }
} }
$admin = $gameStor->getValues(['scenario', 'turnterm', 'turntime', 'show_img_level', 'startyear', 'year']); $admin = $gameStor->getValues(['scenario', 'turnterm', 'turntime', 'show_img_level', 'startyear', 'year', 'month']);
$inheritTotalPoint = resetInheritanceUser($userID); $inheritTotalPoint = resetInheritanceUser($userID);
$inheritRequiredPoint = 0; $inheritRequiredPoint = 0;
$userLogger = new UserLogger($userID, $admin['year'], $admin['month'], false);
if ($inheritCity !== null) { if ($inheritCity !== null) {
$inheritRequiredPoint += GameConst::$inheritBornCityPoint; $inheritRequiredPoint += GameConst::$inheritBornCityPoint;
} }
@@ -183,6 +186,8 @@ class Join extends \sammo\BaseAPI
} }
if ($inheritSpecial) { if ($inheritSpecial) {
$speicalText = getGeneralSpecialWarName($inheritSpecial);
$userLogger->push("{$speicalText} 전투 특기를 가진 천재 생성", "inheritPoint");
$genius = true; $genius = true;
} else { } else {
// 현재 1% // 현재 1%
@@ -196,6 +201,8 @@ class Join extends \sammo\BaseAPI
} }
if ($inheritCity !== null) { if ($inheritCity !== null) {
$cityname = CityConst::byID($inheritCity)->name;
$userLogger->push("{$cityname}에 장수 생성", "inheritPoint");
$city = $inheritCity; $city = $inheritCity;
} else { } else {
// 공백지에서만 태어나게 // 공백지에서만 태어나게
@@ -207,6 +214,7 @@ class Join extends \sammo\BaseAPI
if ($inheritBonusStat) { if ($inheritBonusStat) {
[$pleadership, $pstrength, $pintel] = $inheritBonusStat; [$pleadership, $pstrength, $pintel] = $inheritBonusStat;
$userLogger->push("{$pleadership}, {$pstrength}, {$pintel} 보너스 능력치로 생성", "inheritPoint");
} else { } else {
$pleadership = 0; $pleadership = 0;
$pstrength = 0; $pstrength = 0;
@@ -276,8 +284,10 @@ class Join extends \sammo\BaseAPI
} }
if ($inheritTurntime !== null) { if ($inheritTurntime !== null) {
//FIXME: 오동작함
$inheritTurntime = $inheritTurntime % ($admin['turnterm'] * 60); $inheritTurntime = $inheritTurntime % ($admin['turnterm'] * 60);
$userLogger->push(sprintf("턴 시간 %02d:%02d 로 지정", intdiv($inheritTurntime, 60), $inheritTurntime%60), "inheritPoint");
$inheritTurntime += Util::randRangeInt(0, 999999) / 1000000; $inheritTurntime += Util::randRangeInt(0, 999999) / 1000000;
$turntime = new \DateTimeImmutable(cutTurn($admin['turntime'], $admin['turnterm'])); $turntime = new \DateTimeImmutable(cutTurn($admin['turntime'], $admin['turnterm']));
$turntime = $turntime->add(TimeUtil::secondsToDateInterval($inheritTurntime)); $turntime = $turntime->add(TimeUtil::secondsToDateInterval($inheritTurntime));
@@ -372,9 +382,12 @@ class Join extends \sammo\BaseAPI
]); ]);
$cityname = CityConst::byID($city)->name; $cityname = CityConst::byID($city)->name;
if ($inheritRequiredPoint > 0) { if ($inheritRequiredPoint > 0) {
$userLogger->push("장수 생성으로 포인트 {$inheritRequiredPoint} 소모", "inheritPoint");
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$userID}"); $inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$userID}");
$inheritStor->setValue('previous', [$inheritTotalPoint - $inheritRequiredPoint, null]); $inheritStor->setValue('previous', [$inheritTotalPoint - $inheritRequiredPoint, null]);
$userLogger->flush();
} }
$me = [ $me = [
@@ -10,6 +10,7 @@ use sammo\General;
use sammo\KVStorage; use sammo\KVStorage;
use sammo\TimeUtil; use sammo\TimeUtil;
use sammo\TriggerInheritBuff; use sammo\TriggerInheritBuff;
use sammo\UserLogger;
use sammo\Validator; use sammo\Validator;
class BuyHiddenBuff extends \sammo\BaseAPI class BuyHiddenBuff extends \sammo\BaseAPI
@@ -50,6 +51,7 @@ class BuyHiddenBuff extends \sammo\BaseAPI
if ($userID != $general->getVar('owner')) { if ($userID != $general->getVar('owner')) {
return '로그인 상태가 이상합니다. 다시 로그인해 주세요.'; return '로그인 상태가 이상합니다. 다시 로그인해 주세요.';
} }
$userLogger = new UserLogger($userID);
$inheritBuffList = $general->getAuxVar('inheritBuff') ?? []; $inheritBuffList = $general->getAuxVar('inheritBuff') ?? [];
$prevLevel = $inheritBuffList[$type] ?? 0; $prevLevel = $inheritBuffList[$type] ?? 0;
@@ -70,6 +72,11 @@ class BuyHiddenBuff extends \sammo\BaseAPI
return '충분한 유산 포인트를 가지고 있지 않습니다.'; return '충분한 유산 포인트를 가지고 있지 않습니다.';
} }
$buffTypeText = TriggerInheritBuff::BUFF_KEY_TEXT[$type];
$moreText = $prevLevel > 0 ? "추가":"";
$userLogger->push("{$reqAmount} 포인트로 {$buffTypeText} {$level} 단계 {$moreText}구입", "inheritPoint");
$userLogger->flush();
$inheritBuffList[$type] = $level; $inheritBuffList[$type] = $level;
$general->setAuxVar('inheritBuff', $inheritBuffList); $general->setAuxVar('inheritBuff', $inheritBuffList);
$inheritStor->setValue('previous', [$previousPoint - $reqAmount, null]); $inheritStor->setValue('previous', [$previousPoint - $reqAmount, null]);
@@ -9,6 +9,7 @@ use sammo\GameConst;
use sammo\General; use sammo\General;
use sammo\KVStorage; use sammo\KVStorage;
use sammo\TimeUtil; use sammo\TimeUtil;
use sammo\UserLogger;
class BuyRandomUnique extends \sammo\BaseAPI class BuyRandomUnique extends \sammo\BaseAPI
{ {
@@ -40,12 +41,17 @@ class BuyRandomUnique extends \sammo\BaseAPI
$db = DB::db(); $db = DB::db();
$inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}"); $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}");
$previousPoint = ($inheritStor->getValue('previous')??[0, 0])[0]; $previousPoint = ($inheritStor->getValue('previous')??[0, 0])[0];
if($previousPoint < GameConst::$inheritItemRandomPoint){ $reqAmount = GameConst::$inheritItemRandomPoint;
if($previousPoint < $reqAmount){
return '충분한 유산 포인트를 가지고 있지 않습니다.'; return '충분한 유산 포인트를 가지고 있지 않습니다.';
} }
$userLogger = new UserLogger($userID);
$userLogger->push("{$reqAmount} 포인트로 랜덤 유니크 구입", "inheritPoint");
$userLogger->flush();
$general->setAuxVar('inheritRandomUnique', TimeUtil::now()); $general->setAuxVar('inheritRandomUnique', TimeUtil::now());
$inheritStor->setValue('previous', [$previousPoint - GameConst::$inheritItemRandomPoint, null]); $inheritStor->setValue('previous', [$previousPoint - $reqAmount, null]);
$general->applyDB($db); $general->applyDB($db);
return null; return null;
} }
@@ -8,8 +8,11 @@ use sammo\DB;
use sammo\GameConst; use sammo\GameConst;
use sammo\General; use sammo\General;
use sammo\KVStorage; use sammo\KVStorage;
use sammo\UserLogger;
use sammo\Validator; use sammo\Validator;
use function sammo\buildItemClass;
class BuySpecificUnique extends \sammo\BaseAPI class BuySpecificUnique extends \sammo\BaseAPI
{ {
public function validateArgs(): ?string public function validateArgs(): ?string
@@ -70,6 +73,11 @@ class BuySpecificUnique extends \sammo\BaseAPI
return '충분한 유산 포인트를 가지고 있지 않습니다.'; return '충분한 유산 포인트를 가지고 있지 않습니다.';
} }
$itemObj = buildItemClass($itemKey);
$userLogger = new UserLogger($userID);
$userLogger->push("{$amount} 포인트로 유니크 {$itemObj->getName()} 구입 시도", "inheritPoint");
$userLogger->flush();
$itemTrials[$itemKey] = $amount; $itemTrials[$itemKey] = $amount;
$general->setAuxVar('inheritUniqueTrial', $itemTrials); $general->setAuxVar('inheritUniqueTrial', $itemTrials);
$inheritStor->setValue('previous', [$previousPoint - $amount, null]); $inheritStor->setValue('previous', [$previousPoint - $amount, null]);
@@ -8,6 +8,7 @@ use sammo\DB;
use sammo\GameConst; use sammo\GameConst;
use sammo\General; use sammo\General;
use sammo\KVStorage; use sammo\KVStorage;
use sammo\UserLogger;
use sammo\Validator; use sammo\Validator;
class ResetSpecialWar extends \sammo\BaseAPI class ResetSpecialWar extends \sammo\BaseAPI
@@ -55,6 +56,10 @@ class ResetSpecialWar extends \sammo\BaseAPI
return '충분한 유산 포인트를 가지고 있지 않습니다.'; return '충분한 유산 포인트를 가지고 있지 않습니다.';
} }
$userLogger = new UserLogger($userID);
$userLogger->push("{$reqPoint} 포인트로 전투 특기 초기화", "inheritPoint");
$userLogger->flush();
$oldTypeKey = 'prev_types_special2'; $oldTypeKey = 'prev_types_special2';
$oldSpecialList = $general->getAuxVar($oldTypeKey) ?? []; $oldSpecialList = $general->getAuxVar($oldTypeKey) ?? [];
$oldSpecialList[] = $currentSpecialWar; $oldSpecialList[] = $currentSpecialWar;
@@ -10,6 +10,7 @@ use sammo\GameConst;
use sammo\General; use sammo\General;
use sammo\KVStorage; use sammo\KVStorage;
use sammo\TimeUtil; use sammo\TimeUtil;
use sammo\UserLogger;
use sammo\Util; use sammo\Util;
class ResetTurnTime extends \sammo\BaseAPI class ResetTurnTime extends \sammo\BaseAPI
@@ -59,6 +60,15 @@ class ResetTurnTime extends \sammo\BaseAPI
$afterTurn = Util::randRange($turnTerm * -60 / 2, $turnTerm * 60 / 2); $afterTurn = Util::randRange($turnTerm * -60 / 2, $turnTerm * 60 / 2);
$userLogger = new UserLogger($userID);
if($afterTurn >= 0){
$userLogger->push(sprintf("{$reqPoint} 포인트로 턴 시간을 바꾼 결과 %02d:%02d 뒤로 밀림", intdiv($afterTurn, 60), $afterTurn%60), "inheritPoint");
}
else{
$userLogger->push(sprintf("{$reqPoint} 포인트로 턴 시간을 바꾼 결과 %02d:%02d 앞으로 당김", intdiv(-$afterTurn, 60), (-$afterTurn)%60), "inheritPoint");
}
$userLogger->flush();
$turnTime = $currTurnTime->add(TimeUtil::secondsToDateInterval($afterTurn)); $turnTime = $currTurnTime->add(TimeUtil::secondsToDateInterval($afterTurn));
if ($turnTime <= $serverTurnTimeObj && $serverTurnTimeObj <= $currTurnTime) { if ($turnTime <= $serverTurnTimeObj && $serverTurnTimeObj <= $currTurnTime) {
$turnTime = $turnTime->add(TimeUtil::secondsToDateInterval($turnTerm * 60)); $turnTime = $turnTime->add(TimeUtil::secondsToDateInterval($turnTerm * 60));
@@ -8,8 +8,11 @@ use sammo\DB;
use sammo\GameConst; use sammo\GameConst;
use sammo\General; use sammo\General;
use sammo\KVStorage; use sammo\KVStorage;
use sammo\UserLogger;
use sammo\Validator; use sammo\Validator;
use function sammo\buildGeneralSpecialWarClass;
class SetNextSpecialWar extends \sammo\BaseAPI class SetNextSpecialWar extends \sammo\BaseAPI
{ {
public function validateArgs(): ?string public function validateArgs(): ?string
@@ -67,6 +70,11 @@ class SetNextSpecialWar extends \sammo\BaseAPI
return '충분한 유산 포인트를 가지고 있지 않습니다.'; return '충분한 유산 포인트를 가지고 있지 않습니다.';
} }
$userLogger = new UserLogger($userID);
$specialWarObj = buildGeneralSpecialWarClass($type);
$userLogger->push("{$reqAmount} 포인트로 다음 전투 특기로 {$specialWarObj->getName()} 지정", "inheritPoint");
$userLogger->flush();
$general->setAuxVar('inheritSpecificSpecialWar', $type); $general->setAuxVar('inheritSpecificSpecialWar', $type);
$inheritStor->setValue('previous', [$previousPoint - $reqAmount, null]); $inheritStor->setValue('previous', [$previousPoint - $reqAmount, null]);
$general->applyDB($db); $general->applyDB($db);
@@ -19,7 +19,7 @@ class che_무기_09_동호비궁 extends \sammo\BaseStatItem{
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{ public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller( return new WarUnitTriggerCaller(
new che_저격시도($unit, che_저격시도::TYPE_ITEM + che_저격시도::TYPE_DEDUP_TYPE_BASE * 109, 0.15, 20, 40), new che_저격시도($unit, che_저격시도::TYPE_ITEM + che_저격시도::TYPE_DEDUP_TYPE_BASE * 109, 0.2, 20, 40),
new che_저격발동($unit, che_저격발동::TYPE_ITEM) new che_저격발동($unit, che_저격발동::TYPE_ITEM)
); );
} }
@@ -19,7 +19,7 @@ class che_무기_13_양유기궁 extends \sammo\BaseStatItem{
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{ public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller( return new WarUnitTriggerCaller(
new che_저격시도($unit, che_저격시도::TYPE_ITEM + che_저격시도::TYPE_DEDUP_TYPE_BASE * 113, 0.05, 20, 40), new che_저격시도($unit, che_저격시도::TYPE_ITEM + che_저격시도::TYPE_DEDUP_TYPE_BASE * 113, 0.1, 20, 40),
new che_저격발동($unit, che_저격발동::TYPE_ITEM) new che_저격발동($unit, che_저격발동::TYPE_ITEM)
); );
} }
@@ -38,7 +38,7 @@ class event_전투특기_반계 extends \sammo\BaseItem{
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{ public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{
return new WarUnitTriggerCaller( return new WarUnitTriggerCaller(
new che_반계시도($unit), new che_반계시도($unit, BaseWarUnitTrigger::TYPE_ITEM),
new che_반계발동($unit) new che_반계발동($unit)
); );
} }
+6 -5
View File
@@ -4,7 +4,7 @@ namespace sammo\Command\General;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, General,
CityConst, CityConst,
ActionLogger, ActionLogger,
LastTurn, LastTurn,
Command Command
@@ -13,6 +13,7 @@ use \sammo\{
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use function sammo\tryRollbackInheritUniqueItem;
class che_NPC능동 extends Command\GeneralCommand{ class che_NPC능동 extends Command\GeneralCommand{
static protected $actionName = 'NPC능동'; static protected $actionName = 'NPC능동';
@@ -46,7 +47,7 @@ class che_NPC능동 extends Command\GeneralCommand{
$general = $this->generalObj; $general = $this->generalObj;
$this->setNation(); $this->setNation();
$this->permissionConstraints=[ $this->permissionConstraints=[
ConstraintHelper::MustBeNPC() ConstraintHelper::MustBeNPC()
@@ -65,7 +66,7 @@ class che_NPC능동 extends Command\GeneralCommand{
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 0; return 0;
} }
@@ -97,11 +98,11 @@ class che_NPC능동 extends Command\GeneralCommand{
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
} }
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
} }
@@ -36,7 +36,7 @@ class che_랜덤임관 extends Command\GeneralCommand
/*if($this->arg === null){ /*if($this->arg === null){
return true; return true;
} }
$destNationIDList = $this->arg['destNationIDList']??null; $destNationIDList = $this->arg['destNationIDList']??null;
//null은 에러, []는 정상 //null은 에러, []는 정상
@@ -56,8 +56,8 @@ class che_랜덤임관 extends Command\GeneralCommand
} }
$this->arg = [ $this->arg = [
'destNationIDList' => $destNationIDList 'destNationIDList' => $destNationIDList
]; ];
return true;*/ return true;*/
} }
@@ -234,7 +234,7 @@ class che_랜덤임관 extends Command\GeneralCommand
if (!$destNation) { if (!$destNation) {
//임관 가능한 국가가 없다! //임관 가능한 국가가 없다!
$logger->pushGeneralActionLog("임관 가능한 국가가 없습니다. <1>$date</>"); $logger->pushGeneralActionLog("임관 가능한 국가가 없습니다. <1>$date</>");
$this->alternative = new che_요양($general, $this->env, null); $this->alternative = new che_인재탐색($general, $this->env, null);
return false; return false;
} }
@@ -14,6 +14,8 @@ use \sammo\{
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use function sammo\tryRollbackInheritUniqueItem;
class che_모반시도 extends Command\GeneralCommand{ class che_모반시도 extends Command\GeneralCommand{
static protected $actionName = '모반시도'; static protected $actionName = '모반시도';
@@ -29,7 +31,7 @@ class che_모반시도 extends Command\GeneralCommand{
$this->setCity(); $this->setCity();
$this->setNation(); $this->setNation();
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::NotBeNeutral(), ConstraintHelper::NotBeNeutral(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
@@ -43,7 +45,7 @@ class che_모반시도 extends Command\GeneralCommand{
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 0; return 0;
} }
@@ -72,7 +74,7 @@ class che_모반시도 extends Command\GeneralCommand{
$lordName = $lordGeneral->getName(); $lordName = $lordGeneral->getName();
$nationName = $this->nation['name']; $nationName = $this->nation['name'];
$logger = $general->getLogger(); $logger = $general->getLogger();
$lordLogger = $lordGeneral->getLogger(); $lordLogger = $lordGeneral->getLogger();
@@ -82,7 +84,7 @@ class che_모반시도 extends Command\GeneralCommand{
$lordGeneral->setVar('officer_city', 0); $lordGeneral->setVar('officer_city', 0);
$lordGeneral->multiplyVar('experience', 0.7); $lordGeneral->multiplyVar('experience', 0.7);
$josaYi = JosaUtil::pick($generalName, '이'); $josaYi = JosaUtil::pick($generalName, '이');
$logger->pushGlobalHistoryLog("<Y><b>【모반】</b></><Y>{$generalName}</>{$josaYi} <D><b>{$nationName}</b></>의 군주 자리를 찬탈했습니다."); $logger->pushGlobalHistoryLog("<Y><b>【모반】</b></><Y>{$generalName}</>{$josaYi} <D><b>{$nationName}</b></>의 군주 자리를 찬탈했습니다.");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <Y>{$lordName}</>에게서 군주자리를 찬탈"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <Y>{$lordName}</>에게서 군주자리를 찬탈");
@@ -95,11 +97,12 @@ class che_모반시도 extends Command\GeneralCommand{
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
$lordGeneral->applyDB($db); $lordGeneral->applyDB($db);
return true; return true;
} }
} }
+6 -5
View File
@@ -3,7 +3,7 @@ namespace sammo\Command\General;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, General,
ActionLogger, ActionLogger,
GameConst, GameUnitConst, GameConst, GameUnitConst,
LastTurn, LastTurn,
@@ -15,7 +15,7 @@ use \sammo\Constraint\ConstraintHelper;
use sammo\CityConst; use sammo\CityConst;
use function sammo\DeleteConflict; use function sammo\DeleteConflict;
use function sammo\refreshNationStaticInfo; use function sammo\refreshNationStaticInfo;
use function sammo\tryRollbackInheritUniqueItem;
class che_방랑 extends Command\GeneralCommand{ class che_방랑 extends Command\GeneralCommand{
static protected $actionName = '방랑'; static protected $actionName = '방랑';
@@ -34,7 +34,7 @@ class che_방랑 extends Command\GeneralCommand{
$this->setNation(); $this->setNation();
$relYear = $env['year'] - $env['startyear']; $relYear = $env['year'] - $env['startyear'];
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::BeLord(), ConstraintHelper::BeLord(),
ConstraintHelper::NotWanderingNation(), ConstraintHelper::NotWanderingNation(),
@@ -48,7 +48,7 @@ class che_방랑 extends Command\GeneralCommand{
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 0; return 0;
} }
@@ -85,7 +85,7 @@ class che_방랑 extends Command\GeneralCommand{
$logger->pushGlobalHistoryLog("<R><b>【방랑】</b></><D><b>{$generalName}</b></>{$josaUn} <R>방랑</>의 길을 떠납니다."); $logger->pushGlobalHistoryLog("<R><b>【방랑】</b></><D><b>{$generalName}</b></>{$josaUn} <R>방랑</>의 길을 떠납니다.");
$logger->pushGeneralHistoryLog("<D><b>{$nationName}</b></>{$josaUl} 버리고 방랑"); $logger->pushGeneralHistoryLog("<D><b>{$nationName}</b></>{$josaUl} 버리고 방랑");
//분쟁기록 모두 지움 //분쟁기록 모두 지움
DeleteConflict($nationID); DeleteConflict($nationID);
// 국명, 색깔 바꿈 국가 레벨 0, 성향리셋, 기술0 // 국명, 색깔 바꿈 국가 레벨 0, 성향리셋, 기술0
@@ -123,6 +123,7 @@ class che_방랑 extends Command\GeneralCommand{
refreshNationStaticInfo(); refreshNationStaticInfo();
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
+2
View File
@@ -20,6 +20,7 @@ use function\sammo\tryUniqueItemLottery;
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use function sammo\tryRollbackInheritUniqueItem;
class che_선양 extends Command\GeneralCommand class che_선양 extends Command\GeneralCommand
{ {
@@ -136,6 +137,7 @@ class che_선양 extends Command\GeneralCommand
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
$destGeneral->applyDB($db); $destGeneral->applyDB($db);
@@ -3,7 +3,7 @@ namespace sammo\Command\General;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, General,
ActionLogger, ActionLogger,
GameConst, GameUnitConst, GameConst, GameUnitConst,
LastTurn, LastTurn,
@@ -13,6 +13,8 @@ use \sammo\{
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use function sammo\tryRollbackInheritUniqueItem;
class che_소집해제 extends Command\GeneralCommand{ class che_소집해제 extends Command\GeneralCommand{
static protected $actionName = '소집해제'; static protected $actionName = '소집해제';
@@ -27,7 +29,7 @@ class che_소집해제 extends Command\GeneralCommand{
$this->setCity(); $this->setCity();
$this->setNation(); $this->setNation();
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::ReqGeneralCrew(), ConstraintHelper::ReqGeneralCrew(),
]; ];
@@ -43,7 +45,7 @@ class che_소집해제 extends Command\GeneralCommand{
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 0; return 0;
} }
@@ -70,7 +72,7 @@ class che_소집해제 extends Command\GeneralCommand{
$exp = 70; $exp = 70;
$ded = 100; $ded = 100;
$db->update('city', [ $db->update('city', [
'pop'=>$db->sqleval('pop + %i', $crew) 'pop'=>$db->sqleval('pop + %i', $crew)
], 'city=%i', $general->getCityID()); ], 'city=%i', $general->getCityID());
@@ -80,10 +82,11 @@ class che_소집해제 extends Command\GeneralCommand{
$general->addDedication($ded); $general->addDedication($ded);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
} }
+7 -6
View File
@@ -3,7 +3,7 @@ namespace sammo\Command\General;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, General,
ActionLogger, ActionLogger,
GameConst, GameUnitConst, GameConst, GameUnitConst,
LastTurn, LastTurn,
@@ -13,7 +13,7 @@ use \sammo\{
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use function sammo\tryRollbackInheritUniqueItem;
class che_요양 extends Command\GeneralCommand{ class che_요양 extends Command\GeneralCommand{
static protected $actionName = '요양'; static protected $actionName = '요양';
@@ -28,7 +28,7 @@ class che_요양 extends Command\GeneralCommand{
$general = $this->generalObj; $general = $this->generalObj;
$this->setNation(); $this->setNation();
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
]; ];
@@ -37,7 +37,7 @@ class che_요양 extends Command\GeneralCommand{
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 0; return 0;
} }
@@ -56,7 +56,7 @@ class che_요양 extends Command\GeneralCommand{
$general = $this->generalObj; $general = $this->generalObj;
$date = $general->getTurnTime($general::TURNTIME_HM); $date = $general->getTurnTime($general::TURNTIME_HM);
$crew = $general->getVar('crew'); $crew = $general->getVar('crew');
$logger = $general->getLogger(); $logger = $general->getLogger();
@@ -71,10 +71,11 @@ class che_요양 extends Command\GeneralCommand{
$general->addDedication($ded); $general->addDedication($ded);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
} }
+2
View File
@@ -15,6 +15,7 @@ use \sammo\Json;
use function \sammo\searchDistance; use function \sammo\searchDistance;
use function \sammo\printCitiesBasedOnDistance; use function \sammo\printCitiesBasedOnDistance;
use function sammo\tryRollbackInheritUniqueItem;
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
@@ -217,6 +218,7 @@ class che_첩보 extends Command\GeneralCommand
$general->increaseVar('leadership_exp', 1); $general->increaseVar('leadership_exp', 1);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
+8 -7
View File
@@ -3,7 +3,7 @@ namespace sammo\Command\General;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, General,
ActionLogger, ActionLogger,
GameConst, GameUnitConst, GameConst, GameUnitConst,
LastTurn, LastTurn,
@@ -14,7 +14,7 @@ use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use sammo\CityConst; use sammo\CityConst;
use function sammo\tryRollbackInheritUniqueItem;
class che_하야 extends Command\GeneralCommand{ class che_하야 extends Command\GeneralCommand{
static protected $actionName = '하야'; static protected $actionName = '하야';
@@ -32,7 +32,7 @@ class che_하야 extends Command\GeneralCommand{
$this->setNation(); $this->setNation();
$relYear = $env['year'] - $env['startyear']; $relYear = $env['year'] - $env['startyear'];
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::NotBeNeutral(), ConstraintHelper::NotBeNeutral(),
ConstraintHelper::NotOpeningPart($relYear), ConstraintHelper::NotOpeningPart($relYear),
@@ -43,7 +43,7 @@ class che_하야 extends Command\GeneralCommand{
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 0; return 0;
} }
@@ -67,7 +67,7 @@ class che_하야 extends Command\GeneralCommand{
$nationID = $this->nation['nation']; $nationID = $this->nation['nation'];
$nationName = $this->nation['name']; $nationName = $this->nation['name'];
$logger = $general->getLogger(); $logger = $general->getLogger();
$logger->pushGeneralActionLog("<D><b>{$nationName}</b></>에서 하야했습니다. <1>$date</>"); $logger->pushGeneralActionLog("<D><b>{$nationName}</b></>에서 하야했습니다. <1>$date</>");
@@ -101,13 +101,14 @@ class che_하야 extends Command\GeneralCommand{
$general->setVar('officer_city', 0); $general->setVar('officer_city', 0);
$general->setVar('belong', 0); $general->setVar('belong', 0);
$general->setVar('makelimit', 12); $general->setVar('makelimit', 12);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
} }
+6 -7
View File
@@ -3,7 +3,7 @@ namespace sammo\Command\General;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, General,
ActionLogger, ActionLogger,
GameConst, GameUnitConst, GameConst, GameUnitConst,
LastTurn, LastTurn,
@@ -16,13 +16,12 @@ use \sammo\Constraint\ConstraintHelper;
use sammo\CityConst; use sammo\CityConst;
use function sammo\refreshNationStaticInfo; use function sammo\refreshNationStaticInfo;
use function sammo\deleteNation; use function sammo\deleteNation;
use function sammo\tryRollbackInheritUniqueItem;
class che_해산 extends Command\GeneralCommand{ class che_해산 extends Command\GeneralCommand{
static protected $actionName = '해산'; static protected $actionName = '해산';
protected function argTest():bool{ protected function argTest():bool{
$this->arg = []; $this->arg = [];
return true; return true;
@@ -45,7 +44,7 @@ class che_해산 extends Command\GeneralCommand{
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 0; return 0;
} }
@@ -96,11 +95,11 @@ class che_해산 extends Command\GeneralCommand{
$oldGeneral->setVar('makelimit', 12); $oldGeneral->setVar('makelimit', 12);
$oldGeneral->applyDB($db); $oldGeneral->applyDB($db);
} }
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
} }
+3
View File
@@ -14,6 +14,7 @@ use \sammo\Command;
use function \sammo\searchDistance; use function \sammo\searchDistance;
use function \sammo\printCitiesBasedOnDistance; use function \sammo\printCitiesBasedOnDistance;
use function sammo\tryRollbackInheritUniqueItem;
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
@@ -294,6 +295,7 @@ class che_화계 extends Command\GeneralCommand
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return false; return false;
} }
@@ -327,6 +329,7 @@ class che_화계 extends Command\GeneralCommand
$general->increaseRankVar('firenum', 1); $general->increaseRankVar('firenum', 1);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->checkStatChange(); $general->checkStatChange();
tryRollbackInheritUniqueItem($general);
$general->applyDB($db); $general->applyDB($db);
return true; return true;
+4 -2
View File
@@ -7,9 +7,11 @@ use \sammo\JosaUtil;
use \sammo\LastTurn; use \sammo\LastTurn;
use \sammo\DB; use \sammo\DB;
use function sammo\tryRollbackInheritUniqueItem;
class 휴식 extends Command\GeneralCommand{ class 휴식 extends Command\GeneralCommand{
static protected $actionName = '휴식'; static protected $actionName = '휴식';
protected function argTest():bool{ protected function argTest():bool{
return true; return true;
} }
@@ -39,7 +41,7 @@ class 휴식 extends Command\GeneralCommand{
$logger->pushGeneralActionLog("아무것도 실행하지 않았습니다. <1>$date</>"); $logger->pushGeneralActionLog("아무것도 실행하지 않았습니다. <1>$date</>");
$this->setResultTurn(new LastTurn()); $this->setResultTurn(new LastTurn());
tryRollbackInheritUniqueItem($general);
$general->applyDB(DB::db()); $general->applyDB(DB::db());
return true; return true;
} }
+452 -344
View File
@@ -5,7 +5,8 @@ namespace sammo;
use sammo\Command\GeneralCommand; use sammo\Command\GeneralCommand;
use sammo\WarUnitTrigger as WarUnitTrigger; use sammo\WarUnitTrigger as WarUnitTrigger;
class General implements iAction{ class General implements iAction
{
use LazyVarUpdater; use LazyVarUpdater;
protected $raw = []; protected $raw = [];
@@ -42,28 +43,28 @@ class General implements iAction{
protected $resultTurn = null; protected $resultTurn = null;
const RANK_COLUMN = [ const RANK_COLUMN = [
'firenum'=>1, 'warnum'=>1, 'killnum'=>1, 'deathnum'=>1, 'killcrew'=>1, 'deathcrew'=>1, 'firenum' => 1, 'warnum' => 1, 'killnum' => 1, 'deathnum' => 1, 'killcrew' => 1, 'deathcrew' => 1,
'ttw'=>1, 'ttd'=>1, 'ttl'=>1, 'ttg'=>1, 'ttp'=>1, 'ttw' => 1, 'ttd' => 1, 'ttl' => 1, 'ttg' => 1, 'ttp' => 1,
'tlw'=>1, 'tld'=>1, 'tll'=>1, 'tlg'=>1, 'tlp'=>1, 'tlw' => 1, 'tld' => 1, 'tll' => 1, 'tlg' => 1, 'tlp' => 1,
'tsw'=>1, 'tsd'=>1, 'tsl'=>1, 'tsg'=>1, 'tsp'=>1, 'tsw' => 1, 'tsd' => 1, 'tsl' => 1, 'tsg' => 1, 'tsp' => 1,
'tiw'=>1, 'tid'=>1, 'til'=>1, 'tig'=>1, 'tip'=>1, 'tiw' => 1, 'tid' => 1, 'til' => 1, 'tig' => 1, 'tip' => 1,
'betwin'=>1, 'betgold'=>1, 'betwingold'=>1, 'betwin' => 1, 'betgold' => 1, 'betwingold' => 1,
'killcrew_person'=>1, 'deathcrew_person'=>1, 'killcrew_person' => 1, 'deathcrew_person' => 1,
'occupied'=>1, 'occupied' => 1,
]; ];
const INHERITANCE_KEY = [ const INHERITANCE_KEY = [
'previous'=>[true, 1, '기존 포인트'], 'previous' => [true, 1, '기존 포인트'],
'lived_month'=>[true, 1, '생존'], 'lived_month' => [true, 1, '생존'],
'max_belong'=>[false, 10, '최대 임관년 수'], 'max_belong' => [false, 10, '최대 임관년 수'],
'max_domestic_critical'=>[true, 1, '최대 연속 내정 성공'], 'max_domestic_critical' => [true, 1, '최대 연속 내정 성공'],
'snipe_combat'=>[true, 10, '병종 상성 우위 횟수'], 'snipe_combat' => [true, 10, '병종 상성 우위 횟수'],
'combat'=>[['rank', 'warnum'], 5, '전투 횟수'], 'combat' => [['rank', 'warnum'], 5, '전투 횟수'],
'sabotage'=>[['rank', 'firenum'], 20, '계략 성공 횟수'], 'sabotage' => [['rank', 'firenum'], 20, '계략 성공 횟수'],
'unifier'=>[true, 1, '천통 기여'], 'unifier' => [true, 1, '천통 기여'],
'dex'=>[false, 0.001, '숙련도'], 'dex' => [false, 0.001, '숙련도'],
'tournament'=>[true, 1, '토너먼트'], 'tournament' => [true, 1, '토너먼트'],
'betting'=>[false, 10, '베팅 당첨'], 'betting' => [false, 10, '베팅 당첨'],
]; ];
const TURNTIME_FULL_MS = -1; const TURNTIME_FULL_MS = -1;
@@ -75,19 +76,19 @@ class General implements iAction{
protected static $prohibitedDirectUpdateVars = [ protected static $prohibitedDirectUpdateVars = [
//Reason: iAction //Reason: iAction
'leadership'=>1, 'leadership' => 1,
'power'=>1, 'power' => 1,
'intel'=>1, 'intel' => 1,
'nation'=>2, 'nation' => 2,
'officer_level'=>1, 'officer_level' => 1,
//NOTE: officerLevelObj로 인해 국가의 '레벨'이 바뀌는 것도 조심해야 하나, 국가 레벨의 변경은 월 초/말에만 일어남. //NOTE: officerLevelObj로 인해 국가의 '레벨'이 바뀌는 것도 조심해야 하나, 국가 레벨의 변경은 월 초/말에만 일어남.
'special'=>1, 'special' => 1,
'special2'=>1, 'special2' => 1,
'personal'=>1, 'personal' => 1,
'horse'=>1, 'horse' => 1,
'weapon'=>1, 'weapon' => 1,
'book'=>1, 'book' => 1,
'item'=>1 'item' => 1
]; ];
@@ -98,10 +99,11 @@ class General implements iAction{
* @param int|null $month 게임 월 * @param int|null $month 게임 월
* @param bool $fullConstruct iAction, 및 ActionLogger 초기화 여부, false인 경우 no, name, city, nation, officer_level 정도로 초기화 가능 * @param bool $fullConstruct iAction, 및 ActionLogger 초기화 여부, false인 경우 no, name, city, nation, officer_level 정도로 초기화 가능
*/ */
public function __construct(array $raw, ?array $rawRank, ?array $city, ?array $nation, ?int $year, ?int $month, bool $fullConstruct=true){ public function __construct(array $raw, ?array $rawRank, ?array $city, ?array $nation, ?int $year, ?int $month, bool $fullConstruct = true)
{
//TODO: 밖에서 가져오도록 하면 버그 확률이 높아짐. 필요한 raw 값을 직접 구해야함. //TODO: 밖에서 가져오도록 하면 버그 확률이 높아짐. 필요한 raw 값을 직접 구해야함.
if($nation === null){ if ($nation === null) {
$nation = getNationStaticInfo($raw['nation']); $nation = getNationStaticInfo($raw['nation']);
} }
@@ -109,20 +111,20 @@ class General implements iAction{
$this->rawCity = $city; $this->rawCity = $city;
$this->resultTurn = new LastTurn(); $this->resultTurn = new LastTurn();
if(key_exists('last_turn', $this->raw)){ if (key_exists('last_turn', $this->raw)) {
$this->lastTurn = LastTurn::fromJson($this->raw['last_turn']); $this->lastTurn = LastTurn::fromJson($this->raw['last_turn']);
$this->resultTurn = $this->lastTurn->duplicate(); $this->resultTurn = $this->lastTurn->duplicate();
} }
if($year !== null && $month !== null){ if ($year !== null && $month !== null) {
$this->initLogger($year, $month); $this->initLogger($year, $month);
} }
if($rawRank){ if ($rawRank) {
$this->rankVarRead = $rawRank; $this->rankVarRead = $rawRank;
} }
if(!$fullConstruct){ if (!$fullConstruct) {
return; return;
} }
@@ -139,15 +141,16 @@ class General implements iAction{
$this->itemObjs['book'] = buildItemClass($raw['book']); $this->itemObjs['book'] = buildItemClass($raw['book']);
$this->itemObjs['item'] = buildItemClass($raw['item']); $this->itemObjs['item'] = buildItemClass($raw['item']);
if(key_exists('aux', $this->raw)){ if (key_exists('aux', $this->raw)) {
$rawInheritBuff = $this->getAuxVar('inheritBuff'); $rawInheritBuff = $this->getAuxVar('inheritBuff');
if($rawInheritBuff !== null){ if ($rawInheritBuff !== null) {
$this->inheritBuffObj = new TriggerInheritBuff($rawInheritBuff); $this->inheritBuffObj = new TriggerInheritBuff($rawInheritBuff);
} }
} }
} }
function initLogger(int $year, int $month){ function initLogger(int $year, int $month)
{
$this->logger = new ActionLogger( $this->logger = new ActionLogger(
$this->getVar('no'), $this->getVar('no'),
$this->getVar('nation'), $this->getVar('nation'),
@@ -157,17 +160,27 @@ class General implements iAction{
); );
} }
function getTurnTime(int $short=self::TURNTIME_FULL_MS){ function getTurnTime(int $short = self::TURNTIME_FULL_MS)
{
return [ return [
self::TURNTIME_FULL_MS=>function($turntime){return $turntime;}, self::TURNTIME_FULL_MS => function ($turntime) {
self::TURNTIME_FULL=>function($turntime){return substr($turntime, 0, 19);}, return $turntime;
self::TURNTIME_HMS=>function($turntime){return substr($turntime, 11, 8);}, },
self::TURNTIME_HM=>function($turntime){return substr($turntime, 11, 5);}, self::TURNTIME_FULL => function ($turntime) {
return substr($turntime, 0, 19);
},
self::TURNTIME_HMS => function ($turntime) {
return substr($turntime, 11, 8);
},
self::TURNTIME_HM => function ($turntime) {
return substr($turntime, 11, 5);
},
][$short]($this->getVar('turntime')); ][$short]($this->getVar('turntime'));
} }
function setItem(string $itemKey='item', ?string $itemCode){ function setItem(string $itemKey = 'item', ?string $itemCode)
if($itemCode === null){ {
if ($itemCode === null) {
$this->deleteItem($itemKey); $this->deleteItem($itemKey);
} }
@@ -175,50 +188,61 @@ class General implements iAction{
$this->itemObjs[$itemKey] = buildItemClass($itemCode); $this->itemObjs[$itemKey] = buildItemClass($itemCode);
} }
function deleteItem(string $itemKey='item'){ function deleteItem(string $itemKey = 'item')
{
$this->setVar($itemKey, 'None'); $this->setVar($itemKey, 'None');
$this->itemObjs[$itemKey] = new ActionItem\None(); $this->itemObjs[$itemKey] = new ActionItem\None();
} }
function getItem(string $itemKey='item'):BaseItem{ function getItem(string $itemKey = 'item'): BaseItem
{
return $this->itemObjs[$itemKey]; return $this->itemObjs[$itemKey];
} }
function getNPCType():int{ function getNPCType(): int
{
return $this->raw['npc']; return $this->raw['npc'];
} }
/** @return BaseItem[] */ /** @return BaseItem[] */
function getItems():array{ function getItems(): array
{
return $this->itemObjs; return $this->itemObjs;
} }
function getPersonality():iAction{ function getPersonality(): iAction
{
return $this->personalityObj; return $this->personalityObj;
} }
function getSpecialDomestic():iAction{ function getSpecialDomestic(): iAction
{
return $this->specialDomesticObj; return $this->specialDomesticObj;
} }
function getSpecialWar():iAction{ function getSpecialWar(): iAction
{
return $this->specialWarObj; return $this->specialWarObj;
} }
function getLastTurn():LastTurn{ function getLastTurn(): LastTurn
{
return $this->lastTurn; return $this->lastTurn;
} }
function _setResultTurn(LastTurn $resultTurn){ function _setResultTurn(LastTurn $resultTurn)
{
$this->resultTurn = $resultTurn; $this->resultTurn = $resultTurn;
} }
function getResultTurn():LastTurn{ function getResultTurn(): LastTurn
{
return $this->resultTurn; return $this->resultTurn;
} }
function clearActivatedSkill(){ function clearActivatedSkill()
foreach ($this->activatedSkill as $skillName=>$state) { {
foreach ($this->activatedSkill as $skillName => $state) {
if (!$state) { if (!$state) {
continue; continue;
} }
@@ -232,86 +256,103 @@ class General implements iAction{
$this->activatedSkill = []; $this->activatedSkill = [];
} }
function getActivatedSkillLog():array{ function getActivatedSkillLog(): array
{
return $this->logActivatedSkill; return $this->logActivatedSkill;
} }
function hasActivatedSkill(string $skillName):bool{ function hasActivatedSkill(string $skillName): bool
{
return $this->activatedSkill[$skillName] ?? false; return $this->activatedSkill[$skillName] ?? false;
} }
function activateSkill(... $skillNames){ function activateSkill(...$skillNames)
foreach($skillNames as $skillName){ {
foreach ($skillNames as $skillName) {
$this->activatedSkill[$skillName] = true; $this->activatedSkill[$skillName] = true;
} }
} }
function deactivateSkill(... $skillNames){ function deactivateSkill(...$skillNames)
foreach($skillNames as $skillName){ {
foreach ($skillNames as $skillName) {
$this->activatedSkill[$skillName] = false; $this->activatedSkill[$skillName] = false;
} }
} }
function getName():string{ function getName(): string
{
return $this->raw['name']; return $this->raw['name'];
} }
function getInfo():string{ function getInfo(): string
{
//iAction용 info로는 적절하지 않음 //iAction용 info로는 적절하지 않음
return ''; return '';
} }
function getID():int{ function getID(): int
{
return $this->raw['no']; return $this->raw['no'];
} }
function getRawCity():?array{ function getRawCity(): ?array
{
return $this->rawCity; return $this->rawCity;
} }
function setRawCity(?array $city){ function setRawCity(?array $city)
{
$this->rawCity = $city; $this->rawCity = $city;
} }
function getCityID():int{ function getCityID(): int
{
return $this->raw['city']; return $this->raw['city'];
} }
function getNationID():int{ function getNationID(): int
{
return $this->raw['nation']; return $this->raw['nation'];
} }
function getStaticNation():array{ function getStaticNation(): array
{
return getNationStaticInfo($this->raw['nation']); return getNationStaticInfo($this->raw['nation']);
} }
function getLogger():?ActionLogger{ function getLogger(): ?ActionLogger
{
return $this->logger; return $this->logger;
} }
public function getNationTypeObj():iAction{ public function getNationTypeObj(): iAction
{
return $this->nationType; return $this->nationType;
} }
public function getOfficerLevelObj():iAction{ public function getOfficerLevelObj(): iAction
{
return $this->officerLevelObj; return $this->officerLevelObj;
} }
function getCrewTypeObj():GameUnitDetail{ function getCrewTypeObj(): GameUnitDetail
{
$crewType = GameUnitConst::byID($this->getVar('crewtype')); $crewType = GameUnitConst::byID($this->getVar('crewtype'));
if($crewType === null){ if ($crewType === null) {
throw new \InvalidArgumentException('Invalid CrewType:'.$this->getVar('crewtype')); throw new \InvalidArgumentException('Invalid CrewType:' . $this->getVar('crewtype'));
} }
return $crewType; return $crewType;
} }
function calcRecentWarTurn(int $turnTerm):int{ function calcRecentWarTurn(int $turnTerm): int
{
$cacheKey = "recent_war_turn_{$turnTerm}"; $cacheKey = "recent_war_turn_{$turnTerm}";
if(key_exists($cacheKey, $this->calcCache)){ if (key_exists($cacheKey, $this->calcCache)) {
return $this->calcCache[$cacheKey]; return $this->calcCache[$cacheKey];
} }
if(!$this->getVar('recent_war')){ if (!$this->getVar('recent_war')) {
$result = 12*1000; $result = 12 * 1000;
$this->calcCache[$cacheKey] = $result; $this->calcCache[$cacheKey] = $result;
return $result; return $result;
} }
@@ -319,7 +360,7 @@ class General implements iAction{
$turnNow = new \DateTimeImmutable($this->getVar('turntime')); $turnNow = new \DateTimeImmutable($this->getVar('turntime'));
$secDiff = TimeUtil::DateIntervalToSeconds($recwar->diff($turnNow)); $secDiff = TimeUtil::DateIntervalToSeconds($recwar->diff($turnNow));
if($secDiff <= 0){ if ($secDiff <= 0) {
$this->calcCache[$cacheKey] = 0; $this->calcCache[$cacheKey] = 0;
return 0; return 0;
} }
@@ -329,13 +370,14 @@ class General implements iAction{
return $result; return $result;
} }
function getReservedTurn(int $turnIdx, array $env):GeneralCommand{ function getReservedTurn(int $turnIdx, array $env): GeneralCommand
{
$db = DB::db(); $db = DB::db();
$rawCmd = $db->queryFirstRow('SELECT * FROM general_turn WHERE general_id = %i AND turn_idx = %i', $this->getID(), $turnIdx); $rawCmd = $db->queryFirstRow('SELECT * FROM general_turn WHERE general_id = %i AND turn_idx = %i', $this->getID(), $turnIdx);
if(!$rawCmd){ if (!$rawCmd) {
return buildGeneralCommandClass(null, $this, $env); return buildGeneralCommandClass(null, $this, $env);
} }
return buildGeneralCommandClass($rawCmd['action'], $this, $env, Json::decode($rawCmd['arg']??null)); return buildGeneralCommandClass($rawCmd['action'], $this, $env, Json::decode($rawCmd['arg'] ?? null));
} }
/** /**
@@ -345,13 +387,14 @@ class General implements iAction{
* @param array $env * @param array $env
* @return GeneralCommand[] * @return GeneralCommand[]
*/ */
public function getReservedTurnList(int $turnIdxFrom, int $turnIdxTo, array $env){ public function getReservedTurnList(int $turnIdxFrom, int $turnIdxTo, array $env)
if($turnIdxFrom < 0 || $turnIdxFrom >= GameConst::$maxTurn){ {
throw new \OutOfRangeException('$turnIdxFrom 범위 초과'.$turnIdxFrom); if ($turnIdxFrom < 0 || $turnIdxFrom >= GameConst::$maxTurn) {
throw new \OutOfRangeException('$turnIdxFrom 범위 초과' . $turnIdxFrom);
} }
if($turnIdxTo <= $turnIdxFrom || GameConst::$maxTurn < $turnIdxTo){ if ($turnIdxTo <= $turnIdxFrom || GameConst::$maxTurn < $turnIdxTo) {
throw new \OutOfRangeException('$turnIdxTo 범위 초과'.$turnIdxTo); throw new \OutOfRangeException('$turnIdxTo 범위 초과' . $turnIdxTo);
} }
$db = DB::db(); $db = DB::db();
@@ -362,15 +405,15 @@ class General implements iAction{
$rawCmds = $db->queryFirstRow('SELECT * FROM general_turn WHERE general_id = %i AND %i <= turn_idx AND turn_idx < %i ORDER BY turn_idx ASC', $generalID, $turnIdxFrom, $turnIdxTo); $rawCmds = $db->queryFirstRow('SELECT * FROM general_turn WHERE general_id = %i AND %i <= turn_idx AND turn_idx < %i ORDER BY turn_idx ASC', $generalID, $turnIdxFrom, $turnIdxTo);
if(!$rawCmds){ if (!$rawCmds) {
foreach(Util::range($turnIdxFrom, $turnIdxTo) as $turnIdx){ foreach (Util::range($turnIdxFrom, $turnIdxTo) as $turnIdx) {
$result[$turnIdx] = buildGeneralCommandClass(null, $this, $env); $result[$turnIdx] = buildGeneralCommandClass(null, $this, $env);
} }
return $result; return $result;
} }
foreach($rawCmds as $turnIdx=>$rawCmd){ foreach ($rawCmds as $turnIdx => $rawCmd) {
$result[$turnIdx] = buildGeneralCommandClass($rawCmd['action'], $this, $env, Json::decode($rawCmd['arg']??null)); $result[$turnIdx] = buildGeneralCommandClass($rawCmd['action'], $this, $env, Json::decode($rawCmd['arg'] ?? null));
} }
return $result; return $result;
@@ -388,11 +431,12 @@ class General implements iAction{
* @return int|float 계산된 능력치 * @return int|float 계산된 능력치
*/ */
protected function getStatValue(string $statName, $withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true):float{ protected function getStatValue(string $statName, $withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true): float
{
$cKey = "{$statName}_{$withInjury}_{$withIActionObj}_{$withStatAdjust}"; $cKey = "{$statName}_{$withInjury}_{$withIActionObj}_{$withStatAdjust}";
if(key_exists($cKey, $this->calcCache)){ if (key_exists($cKey, $this->calcCache)) {
$statValue = $this->calcCache[$cKey]; $statValue = $this->calcCache[$cKey];
if($useFloor){ if ($useFloor) {
return Util::toInt($statValue); return Util::toInt($statValue);
} }
return $statValue; return $statValue;
@@ -400,35 +444,34 @@ class General implements iAction{
$statValue = $this->getVar($statName); $statValue = $this->getVar($statName);
if($withInjury){ if ($withInjury) {
$statValue *= (100 - $this->getVar('injury')) / 100; $statValue *= (100 - $this->getVar('injury')) / 100;
} }
if($withStatAdjust){ if ($withStatAdjust) {
if($statName === 'strength'){ if ($statName === 'strength') {
$statValue += Util::round($this->getStatValue('intel', $withInjury, $withIActionObj, false, false) / 4); $statValue += Util::round($this->getStatValue('intel', $withInjury, $withIActionObj, false, false) / 4);
} } else if ($statName === 'intel') {
else if($statName === 'intel'){
$statValue += Util::round($this->getStatValue('strength', $withInjury, $withIActionObj, false, false) / 4); $statValue += Util::round($this->getStatValue('strength', $withInjury, $withIActionObj, false, false) / 4);
} }
} }
if($withIActionObj){ if ($withIActionObj) {
foreach([ foreach ([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
$this->specialWarObj, $this->specialWarObj,
$this->personalityObj, $this->personalityObj,
$this->inheritBuffObj, $this->inheritBuffObj,
] as $actionObj){ ] as $actionObj) {
if($actionObj !== null){ if ($actionObj !== null) {
$statValue = $actionObj->onCalcStat($this, $statName, $statValue); $statValue = $actionObj->onCalcStat($this, $statName, $statValue);
} }
} }
foreach($this->itemObjs as $actionObj){ foreach ($this->itemObjs as $actionObj) {
if($actionObj !== null){ if ($actionObj !== null) {
$statValue = $actionObj->onCalcStat($this, $statName, $statValue); $statValue = $actionObj->onCalcStat($this, $statName, $statValue);
} }
} }
@@ -436,54 +479,58 @@ class General implements iAction{
$this->calcCache[$cKey] = $statValue; $this->calcCache[$cKey] = $statValue;
if($useFloor){ if ($useFloor) {
return Util::toInt($statValue); return Util::toInt($statValue);
} }
return $statValue; return $statValue;
} }
function getLeadership($withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true):float{ function getLeadership($withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true): float
{
return $this->getStatValue('leadership', $withInjury, $withIActionObj, $withStatAdjust, $useFloor); return $this->getStatValue('leadership', $withInjury, $withIActionObj, $withStatAdjust, $useFloor);
} }
function getStrength($withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true):float{ function getStrength($withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true): float
{
return $this->getStatValue('strength', $withInjury, $withIActionObj, $withStatAdjust, $useFloor); return $this->getStatValue('strength', $withInjury, $withIActionObj, $withStatAdjust, $useFloor);
} }
function getIntel($withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true):float{ function getIntel($withInjury = true, $withIActionObj = true, $withStatAdjust = true, $useFloor = true): float
{
return $this->getStatValue('intel', $withInjury, $withIActionObj, $withStatAdjust, $useFloor); return $this->getStatValue('intel', $withInjury, $withIActionObj, $withStatAdjust, $useFloor);
} }
function getDex(GameUnitDetail $crewType){ function getDex(GameUnitDetail $crewType)
{
$armType = $crewType->armType; $armType = $crewType->armType;
if($armType == GameUnitConst::T_CASTLE){ if ($armType == GameUnitConst::T_CASTLE) {
$armType = GameUnitConst::T_SIEGE; $armType = GameUnitConst::T_SIEGE;
} }
return $this->getVar("dex{$armType}"); return $this->getVar("dex{$armType}");
} }
function addDex(GameUnitDetail $crewType, float $exp, bool $affectTrainAtmos=false){ function addDex(GameUnitDetail $crewType, float $exp, bool $affectTrainAtmos = false)
{
$armType = $crewType->armType; $armType = $crewType->armType;
if($armType == GameUnitConst::T_CASTLE){ if ($armType == GameUnitConst::T_CASTLE) {
$armType = GameUnitConst::T_SIEGE; $armType = GameUnitConst::T_SIEGE;
} }
if($armType < 0){ if ($armType < 0) {
return; return;
} }
if($armType == GameUnitConst::T_WIZARD) { if ($armType == GameUnitConst::T_WIZARD) {
$exp *= 0.9; $exp *= 0.9;
} } else if ($armType == GameUnitConst::T_SIEGE) {
else if($armType == GameUnitConst::T_SIEGE) {
$exp *= 0.9; $exp *= 0.9;
} }
if($affectTrainAtmos){ if ($affectTrainAtmos) {
$exp *= ($this->getVar('train') + $this->getVar('atmos')) / 200; $exp *= ($this->getVar('train') + $this->getVar('atmos')) / 200;
} }
@@ -492,39 +539,39 @@ class General implements iAction{
$this->increaseVar($dexType, $exp); $this->increaseVar($dexType, $exp);
} }
function addExperience(float $experience, bool $affectTrigger=true){ function addExperience(float $experience, bool $affectTrigger = true)
if($affectTrigger){ {
if ($affectTrigger) {
$experience = $this->onCalcStat($this, 'experience', $experience); $experience = $this->onCalcStat($this, 'experience', $experience);
} }
$this->increaseVar('experience', $experience); $this->increaseVar('experience', $experience);
$nextExpLevel = getExpLevel($this->getVar('experience')); $nextExpLevel = getExpLevel($this->getVar('experience'));
$comp = $nextExpLevel <=> $this->getVar('explevel'); $comp = $nextExpLevel <=> $this->getVar('explevel');
if($comp === 0){ if ($comp === 0) {
return; return;
} }
$this->updateVar('explevel', $nextExpLevel); $this->updateVar('explevel', $nextExpLevel);
$josaRo = JosaUtil::pick($nextExpLevel, '로'); $josaRo = JosaUtil::pick($nextExpLevel, '로');
if($comp > 0){ if ($comp > 0) {
$this->getLogger()->pushGeneralActionLog("<C>Lv {$nextExpLevel}</>{$josaRo} <C>레벨업</>!", ActionLogger::PLAIN); $this->getLogger()->pushGeneralActionLog("<C>Lv {$nextExpLevel}</>{$josaRo} <C>레벨업</>!", ActionLogger::PLAIN);
} } else {
else{
$this->getLogger()->pushGeneralActionLog("<C>Lv {$nextExpLevel}</>{$josaRo} <R>레벨다운</>!", ActionLogger::PLAIN); $this->getLogger()->pushGeneralActionLog("<C>Lv {$nextExpLevel}</>{$josaRo} <R>레벨다운</>!", ActionLogger::PLAIN);
} }
} }
function addDedication(float $dedication, bool $affectTrigger=true){ function addDedication(float $dedication, bool $affectTrigger = true)
if($affectTrigger){ {
if ($affectTrigger) {
$dedication = $this->onCalcStat($this, 'dedication', $dedication); $dedication = $this->onCalcStat($this, 'dedication', $dedication);
} }
$this->increaseVar('dedication', $dedication); $this->increaseVar('dedication', $dedication);
$nextDedLevel = getDedLevel($this->getVar('dedication')); $nextDedLevel = getDedLevel($this->getVar('dedication'));
$comp = $nextDedLevel <=> $this->getVar('dedlevel'); $comp = $nextDedLevel <=> $this->getVar('dedlevel');
if($comp === 0){ if ($comp === 0) {
return; return;
} }
@@ -534,20 +581,19 @@ class General implements iAction{
$billText = number_format(getBillByLevel($nextDedLevel)); $billText = number_format(getBillByLevel($nextDedLevel));
$josaRoDed = JosaUtil::pick($dedLevelText, '로'); $josaRoDed = JosaUtil::pick($dedLevelText, '로');
$josaRoBill = JosaUtil::pick($billText, '로'); $josaRoBill = JosaUtil::pick($billText, '로');
if($comp > 0){ if ($comp > 0) {
$this->getLogger()->pushGeneralActionLog("<Y>{$dedLevelText}</>{$josaRoDed} <C>승급</>하여 봉록이 <C>{$billText}</>{$josaRoBill} <C>상승</>했습니다!", ActionLogger::PLAIN); $this->getLogger()->pushGeneralActionLog("<Y>{$dedLevelText}</>{$josaRoDed} <C>승급</>하여 봉록이 <C>{$billText}</>{$josaRoBill} <C>상승</>했습니다!", ActionLogger::PLAIN);
} } else {
else{
$this->getLogger()->pushGeneralActionLog("<Y>{$dedLevelText}</>{$josaRoDed} <R>강등</>되어 봉록이 <C>{$billText}</>{$josaRoBill} <R>하락</>했습니다!", ActionLogger::PLAIN); $this->getLogger()->pushGeneralActionLog("<Y>{$dedLevelText}</>{$josaRoDed} <R>강등</>되어 봉록이 <C>{$billText}</>{$josaRoBill} <R>하락</>했습니다!", ActionLogger::PLAIN);
} }
} }
function updateVar(string $key, $value){ function updateVar(string $key, $value)
if(($this->raw[$key]??null) === $value){ {
if (($this->raw[$key] ?? null) === $value) {
return; return;
} }
if(!key_exists($key, $this->updatedVar)){ if (!key_exists($key, $this->updatedVar)) {
$this->updatedVar[$key] = true; $this->updatedVar[$key] = true;
} }
$this->raw[$key] = $value; $this->raw[$key] = $value;
@@ -557,39 +603,81 @@ class General implements iAction{
/** /**
* @param \MeekroDB $db * @param \MeekroDB $db
*/ */
function kill($db, bool $sendDyingMessage=true, ?string $dyingMessage=null){ function kill($db, bool $sendDyingMessage = true, ?string $dyingMessage = null)
{
$generalID = $this->getID(); $generalID = $this->getID();
$logger = $this->getLogger(); $logger = $this->getLogger();
$generalName = $this->getName(); $generalName = $this->getName();
$this->mergeTotalInheritancePoint(); //유산포인트 관련 항목 환불
if ($this->getNPCType() < 2) {
$refundPoint = 0;
$userID = $this->getVar('owner');
$userLogger = new UserLogger($userID);
if ($this->getAuxVar('inheritRandomUnique')) {
$this->setAuxVar('inheritRandomUnique', null);
$userLogger->push(sprintf("사망으로 랜덤 유니크 구입 %d 포인트 반환", GameConst::$inheritItemRandomPoint), "inheritPoint");
$refundPoint += GameConst::$inheritItemRandomPoint;
}
$itemTrials = $this->getAuxVar('inheritUniqueTrial') ?? [];
foreach (array_keys($itemTrials) as $itemKey) {
$trialStor = KVStorage::getStorage($db, "ut_{$itemKey}");
$ownTrial = $trialStor->getValue("u{$userID}");
$itemObj = buildItemClass($itemKey);
$itemName = $itemObj->getName();
if (!$ownTrial) {
continue;
}
[,, $amount] = $ownTrial;
$trialStor->deleteValue("u{$userID}");
$userLogger->push("사망으로 {$itemName} 입찰에 사용한 {$amount} 포인트 반환", "inheritPoint");
$refundPoint += $amount;
}
if($this->getAuxVar('inheritSpecificSpecialWar')){
$this->setAuxVar('inheritSpecificSpecialWar', null);
$userLogger->push(sprintf("사망으로 전투 특기 지정 %d 포인트 반환", GameConst::$inheritSpecificSpecialPoint), "inheritPoint");
$refundPoint += GameConst::$inheritSpecificSpecialPoint;
}
if ($refundPoint > 0) {
$this->increaseInheritancePoint('previous', $refundPoint);
}
$this->mergeTotalInheritancePoint();
}
// 군주였으면 유지 이음 // 군주였으면 유지 이음
$officerLevel = $this->getVar('officer_level'); $officerLevel = $this->getVar('officer_level');
if($officerLevel == 12) { if ($officerLevel == 12) {
nextRuler($this); nextRuler($this);
$this->setVar('officer_level', 1); $this->setVar('officer_level', 1);
} }
// 부대 처리 // 부대 처리
$troopLeaderID = $this->getVar('troop'); $troopLeaderID = $this->getVar('troop');
if($troopLeaderID == $generalID){ if ($troopLeaderID == $generalID) {
//부대장일 경우 //부대장일 경우
// 모두 탈퇴 // 모두 탈퇴
$db->update('general', [ $db->update('general', [
'troop'=>0 'troop' => 0
], 'troop=%i', $troopLeaderID); ], 'troop=%i', $troopLeaderID);
// 부대 삭제 // 부대 삭제
$db->delete('troop', 'troop_leader=%i', $troopLeaderID); $db->delete('troop', 'troop_leader=%i', $troopLeaderID);
} }
if($sendDyingMessage){ if ($sendDyingMessage) {
if($dyingMessage){ if ($dyingMessage) {
$logger->pushGlobalActionLog($dyingMessage); $logger->pushGlobalActionLog($dyingMessage);
} } else {
else{
$dyingMessageObj = new TextDecoration\DyingMessage($this); $dyingMessageObj = new TextDecoration\DyingMessage($this);
$logger->pushGlobalActionLog($dyingMessageObj->getText()); $logger->pushGlobalActionLog($dyingMessageObj->getText());
} }
@@ -597,9 +685,9 @@ class General implements iAction{
} }
$db->update('select_pool', [ $db->update('select_pool', [
'general_id'=>null, 'general_id' => null,
'owner'=>null, 'owner' => null,
'reserved_until'=>null, 'reserved_until' => null,
], 'general_id=%i', $generalID); ], 'general_id=%i', $generalID);
$db->delete('general', 'no=%i', $generalID); $db->delete('general', 'no=%i', $generalID);
@@ -609,17 +697,18 @@ class General implements iAction{
$this->updatedVar = []; $this->updatedVar = [];
$db->update('nation', [ $db->update('nation', [
'gennum'=>$db->sqleval('gennum - 1') 'gennum' => $db->sqleval('gennum - 1')
], 'nation=%i', $this->getVar('nation')); ], 'nation=%i', $this->getVar('nation'));
} }
function rebirth(){ function rebirth()
{
$logger = $this->getLogger(); $logger = $this->getLogger();
$generalName = $this->getName(); $generalName = $this->getName();
$ownerID = $this->getVar('owner'); $ownerID = $this->getVar('owner');
if($ownerID){ if ($ownerID) {
$this->mergeTotalInheritancePoint(); $this->mergeTotalInheritancePoint();
resetInheritanceUser($ownerID, true); resetInheritanceUser($ownerID, true);
} }
@@ -639,7 +728,7 @@ class General implements iAction{
$this->multiplyVar('dex4', 0.5); $this->multiplyVar('dex4', 0.5);
$this->multiplyVar('dex5', 0.5); $this->multiplyVar('dex5', 0.5);
foreach(array_keys(static::RANK_COLUMN) as $rankKey){ foreach (array_keys(static::RANK_COLUMN) as $rankKey) {
$this->setRankVar($rankKey, 0); $this->setRankVar($rankKey, 0);
} }
@@ -649,23 +738,24 @@ class General implements iAction{
$logger->pushGeneralHistoryLog('나이가 들어 은퇴하고, 자손에게 관직을 물려줌'); $logger->pushGeneralHistoryLog('나이가 들어 은퇴하고, 자손에게 관직을 물려줌');
} }
function increaseRankVar(string $key, int $value){ function increaseRankVar(string $key, int $value)
if(!key_exists($key, static::RANK_COLUMN)){ {
throw new \InvalidArgumentException('올바르지 않은 인자 :'.$key); if (!key_exists($key, static::RANK_COLUMN)) {
throw new \InvalidArgumentException('올바르지 않은 인자 :' . $key);
} }
if(key_exists($key, $this->rankVarSet)){ if (key_exists($key, $this->rankVarSet)) {
$this->rankVarSet[$key] += $value; $this->rankVarSet[$key] += $value;
return; return;
} }
if(key_exists($key, $this->rankVarRead)){ if (key_exists($key, $this->rankVarRead)) {
$this->rankVarSet[$key] = $this->rankVarRead[$key] + $value; $this->rankVarSet[$key] = $this->rankVarRead[$key] + $value;
unset($this->rankVarRead[$key]); unset($this->rankVarRead[$key]);
return; return;
} }
if(key_exists($key, $this->rankVarIncrease)){ if (key_exists($key, $this->rankVarIncrease)) {
$this->rankVarIncrease[$key] += $value; $this->rankVarIncrease[$key] += $value;
return; return;
} }
@@ -673,31 +763,32 @@ class General implements iAction{
$this->rankVarIncrease[$key] = $value; $this->rankVarIncrease[$key] = $value;
} }
function setRankVar(string $key, int $value){ function setRankVar(string $key, int $value)
if(!key_exists($key, static::RANK_COLUMN)){ {
throw new \InvalidArgumentException('올바르지 않은 인자 :'.$key); if (!key_exists($key, static::RANK_COLUMN)) {
throw new \InvalidArgumentException('올바르지 않은 인자 :' . $key);
} }
if(key_exists($key, $this->rankVarRead)){ if (key_exists($key, $this->rankVarRead)) {
unset($this->rankVarRead[$key]); unset($this->rankVarRead[$key]);
} } else if (key_exists($key, $this->rankVarIncrease)) {
else if(key_exists($key, $this->rankVarIncrease)){
unset($this->rankVarIncrease[$key]); unset($this->rankVarIncrease[$key]);
} }
$this->rankVarSet[$key]=$value; $this->rankVarSet[$key] = $value;
} }
function getRankVar(string $key):int{ function getRankVar(string $key): int
if(!key_exists($key, static::RANK_COLUMN)){ {
throw new \InvalidArgumentException('올바르지 않은 인자 :'.$key); if (!key_exists($key, static::RANK_COLUMN)) {
throw new \InvalidArgumentException('올바르지 않은 인자 :' . $key);
} }
if(key_exists($key, $this->rankVarSet)){ if (key_exists($key, $this->rankVarSet)) {
return $this->rankVarSet[$key]; return $this->rankVarSet[$key];
} }
if(!key_exists($key, $this->rankVarRead)){ if (!key_exists($key, $this->rankVarRead)) {
throw new \RuntimeException('인자가 없음 : '.$key); throw new \RuntimeException('인자가 없음 : ' . $key);
} }
return $this->rankVarRead[$key]; return $this->rankVarRead[$key];
@@ -706,8 +797,9 @@ class General implements iAction{
/** /**
* @param \MeekroDB $db * @param \MeekroDB $db
*/ */
function applyDB($db):bool{ function applyDB($db): bool
if($this->lastTurn && $this->getLastTurn() != $this->getResultTurn()){ {
if ($this->lastTurn && $this->getLastTurn() != $this->getResultTurn()) {
$this->setVar('last_turn', $this->getResultTurn()->toJson()); $this->setVar('last_turn', $this->getResultTurn()->toJson());
} }
$updateVals = $this->getUpdatedValues(); $updateVals = $this->getUpdatedValues();
@@ -716,31 +808,31 @@ class General implements iAction{
$generalID = $this->getID(); $generalID = $this->getID();
$result = false; $result = false;
if($updateVals){ if ($updateVals) {
$db->update('general', $updateVals, 'no=%i', $generalID); $db->update('general', $updateVals, 'no=%i', $generalID);
$result = $result || $db->affectedRows() > 0; $result = $result || $db->affectedRows() > 0;
if(key_exists('nation', $updateVals)){ if (key_exists('nation', $updateVals)) {
$db->update('rank_data', [ $db->update('rank_data', [
'nation_id'=>$updateVals['nation'] 'nation_id' => $updateVals['nation']
], 'general_id = %i', $generalID); ], 'general_id = %i', $generalID);
$result = true; $result = true;
} }
$this->flushUpdateValues(); $this->flushUpdateValues();
} }
if($this->rankVarIncrease){ if ($this->rankVarIncrease) {
foreach($this->rankVarIncrease as $rankKey => $rankVal){ foreach ($this->rankVarIncrease as $rankKey => $rankVal) {
$db->update('rank_data', [ $db->update('rank_data', [
'value'=>$db->sqleval('value + %i', $rankVal) 'value' => $db->sqleval('value + %i', $rankVal)
], 'general_id = %i AND type = %s', $generalID, $rankKey); ], 'general_id = %i AND type = %s', $generalID, $rankKey);
} }
$result = true; $result = true;
} }
if($this->rankVarSet){ if ($this->rankVarSet) {
foreach($this->rankVarSet as $rankKey => $rankVal){ foreach ($this->rankVarSet as $rankKey => $rankVal) {
$db->update('rank_data', [ $db->update('rank_data', [
'value'=>$rankVal 'value' => $rankVal
], 'general_id = %i AND type = %s', $generalID, $rankKey); ], 'general_id = %i AND type = %s', $generalID, $rankKey);
$this->rankVarRead[$rankKey] = $rankVal; $this->rankVarRead[$rankKey] = $rankVal;
} }
@@ -754,7 +846,8 @@ class General implements iAction{
return $result; return $result;
} }
function checkStatChange():bool{ function checkStatChange(): bool
{
$logger = $this->getLogger(); $logger = $this->getLogger();
$limit = GameConst::$upgradeLimit; $limit = GameConst::$upgradeLimit;
@@ -766,16 +859,15 @@ class General implements iAction{
$result = false; $result = false;
foreach($table as [$statNickName, $statName]){ foreach ($table as [$statNickName, $statName]) {
$statExpName = $statName.'_exp'; $statExpName = $statName . '_exp';
if($this->getVar($statExpName) < 0){ if ($this->getVar($statExpName) < 0) {
$logger->pushGeneralActionLog("<R>{$statNickName}</>이 <C>1</> 떨어졌습니다!", ActionLogger::PLAIN); $logger->pushGeneralActionLog("<R>{$statNickName}</>이 <C>1</> 떨어졌습니다!", ActionLogger::PLAIN);
$this->increaseVar($statExpName, $limit); $this->increaseVar($statExpName, $limit);
$this->increaseVar($statName, -1); $this->increaseVar($statName, -1);
$result = true; $result = true;
} } else if ($this->getVar($statExpName) >= $limit) {
else if($this->getVar($statExpName) >= $limit){
$logger->pushGeneralActionLog("<S>{$statNickName}</>이 <C>1</> 올랐습니다!", ActionLogger::PLAIN); $logger->pushGeneralActionLog("<S>{$statNickName}</>이 <C>1</> 올랐습니다!", ActionLogger::PLAIN);
$this->increaseVar($statExpName, -$limit); $this->increaseVar($statExpName, -$limit);
$this->increaseVar($statName, 1); $this->increaseVar($statName, 1);
@@ -786,9 +878,10 @@ class General implements iAction{
return $result; return $result;
} }
public function getPreTurnExecuteTriggerList(General $general):?GeneralTriggerCaller{ public function getPreTurnExecuteTriggerList(General $general): ?GeneralTriggerCaller
{
$caller = new GeneralTriggerCaller(); $caller = new GeneralTriggerCaller();
foreach(array_merge([ foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -796,9 +889,9 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -807,8 +900,9 @@ class General implements iAction{
return $caller; return $caller;
} }
public function onCalcDomestic(string $turnType, string $varType, float $value, $aux=null):float{ public function onCalcDomestic(string $turnType, string $varType, float $value, $aux = null): float
foreach(array_merge([ {
foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -816,8 +910,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -826,9 +920,10 @@ class General implements iAction{
return $value; return $value;
} }
public function onCalcStat(General $general, string $statName, $value, $aux=null){ public function onCalcStat(General $general, string $statName, $value, $aux = null)
{
//xxx: $general? //xxx: $general?
foreach(array_merge([ foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -836,8 +931,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -846,9 +941,10 @@ class General implements iAction{
return $value; return $value;
} }
public function onCalcOpposeStat(General $general, string $statName, $value, $aux=null){ public function onCalcOpposeStat(General $general, string $statName, $value, $aux = null)
{
//xxx: $general? //xxx: $general?
foreach(array_merge([ foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -856,8 +952,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -866,8 +962,9 @@ class General implements iAction{
return $value; return $value;
} }
public function onCalcStrategic(string $turnType, string $varType, $value){ public function onCalcStrategic(string $turnType, string $varType, $value)
foreach(array_merge([ {
foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -875,8 +972,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -885,8 +982,9 @@ class General implements iAction{
return $value; return $value;
} }
public function onCalcNationalIncome(string $type, $amount){ public function onCalcNationalIncome(string $type, $amount)
foreach(array_merge([ {
foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -894,8 +992,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -904,11 +1002,12 @@ class General implements iAction{
return $amount; return $amount;
} }
public function getWarPowerMultiplier(WarUnit $unit):array{ public function getWarPowerMultiplier(WarUnit $unit): array
{
//xxx:$unit //xxx:$unit
$att = 1; $att = 1;
$def = 1; $def = 1;
foreach(array_merge([ foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -916,8 +1015,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -927,9 +1026,10 @@ class General implements iAction{
} }
return [$att, $def]; return [$att, $def];
} }
public function getBattleInitSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{ public function getBattleInitSkillTriggerList(WarUnit $unit): ?WarUnitTriggerCaller
{
$caller = new WarUnitTriggerCaller(); $caller = new WarUnitTriggerCaller();
foreach(array_merge([ foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -937,8 +1037,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -947,7 +1047,8 @@ class General implements iAction{
return $caller; return $caller;
} }
public function getBattlePhaseSkillTriggerList(WarUnit $unit):?WarUnitTriggerCaller{ public function getBattlePhaseSkillTriggerList(WarUnit $unit): ?WarUnitTriggerCaller
{
$caller = new WarUnitTriggerCaller( $caller = new WarUnitTriggerCaller(
new WarUnitTrigger\che_필살시도($unit), new WarUnitTrigger\che_필살시도($unit),
new WarUnitTrigger\che_필살발동($unit), new WarUnitTrigger\che_필살발동($unit),
@@ -957,7 +1058,7 @@ class General implements iAction{
new WarUnitTrigger\che_계략발동($unit), new WarUnitTrigger\che_계략발동($unit),
new WarUnitTrigger\che_계략실패($unit) new WarUnitTrigger\che_계략실패($unit)
); );
foreach(array_merge([ foreach (array_merge([
$this->nationType, $this->nationType,
$this->officerLevelObj, $this->officerLevelObj,
$this->specialDomesticObj, $this->specialDomesticObj,
@@ -965,8 +1066,8 @@ class General implements iAction{
$this->personalityObj, $this->personalityObj,
$this->getCrewTypeObj(), $this->getCrewTypeObj(),
$this->inheritBuffObj, $this->inheritBuffObj,
], $this->itemObjs) as $iObj){ ], $this->itemObjs) as $iObj) {
if(!$iObj){ if (!$iObj) {
continue; continue;
} }
/** @var iAction $iObj */ /** @var iAction $iObj */
@@ -976,12 +1077,13 @@ class General implements iAction{
return $caller; return $caller;
} }
static public function mergeQueryColumn(?array $reqColumns=null, int $constructMode=2):array{ static public function mergeQueryColumn(?array $reqColumns = null, int $constructMode = 2): array
{
$minimumColumn = ['no', 'name', 'city', 'nation', 'officer_level', 'officer_city']; $minimumColumn = ['no', 'name', 'city', 'nation', 'officer_level', 'officer_city'];
$defaultEventColumn = [ $defaultEventColumn = [
'no', 'name', 'owner', 'city', 'nation', 'officer_level', 'officer_city', 'no', 'name', 'owner', 'city', 'nation', 'officer_level', 'officer_city',
'special', 'special2', 'personal', 'special', 'special2', 'personal',
'horse', 'weapon', 'book', 'item', 'last_turn' 'horse', 'weapon', 'book', 'item', 'last_turn', 'aux',
]; ];
$fullColumn = [ $fullColumn = [
'no', 'name', 'owner', 'owner_name', 'picture', 'imgsvr', 'nation', 'city', 'troop', 'injury', 'affinity', 'no', 'name', 'owner', 'owner_name', 'picture', 'imgsvr', 'nation', 'city', 'troop', 'injury', 'affinity',
@@ -994,22 +1096,21 @@ class General implements iAction{
'specage', 'specage2', 'con', 'connect', 'aux', 'lastrefresh', 'specage', 'specage2', 'con', 'connect', 'aux', 'lastrefresh',
]; ];
if($reqColumns === null){ if ($reqColumns === null) {
return [$fullColumn, array_keys(static::RANK_COLUMN)]; return [$fullColumn, array_keys(static::RANK_COLUMN)];
} }
$rankColumn = []; $rankColumn = [];
$subColumn = []; $subColumn = [];
foreach($reqColumns as $column){ foreach ($reqColumns as $column) {
if(key_exists($column, static::RANK_COLUMN)){ if (key_exists($column, static::RANK_COLUMN)) {
$rankColumn[] = $column; $rankColumn[] = $column;
} } else {
else{
$subColumn[] = $column; $subColumn[] = $column;
} }
} }
if($constructMode > 1){ if ($constructMode > 1) {
return [array_unique(array_merge($defaultEventColumn, $subColumn)), $rankColumn]; return [array_unique(array_merge($defaultEventColumn, $subColumn)), $rankColumn];
} }
@@ -1023,31 +1124,30 @@ class General implements iAction{
* @return \sammo\General[] * @return \sammo\General[]
* @throws MustNotBeReachedException * @throws MustNotBeReachedException
*/ */
static public function createGeneralObjListFromDB(?array $generalIDList, ?array $column=null, int $constructMode=2):array{ static public function createGeneralObjListFromDB(?array $generalIDList, ?array $column = null, int $constructMode = 2): array
if($generalIDList === []){ {
if ($generalIDList === []) {
return []; return [];
} }
$db = DB::db(); $db = DB::db();
if($constructMode > 0){ if ($constructMode > 0) {
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
} } else {
else{
$year = null; $year = null;
$month = null; $month = null;
} }
[$column, $rankColumn] = static::mergeQueryColumn($column, $constructMode); [$column, $rankColumn] = static::mergeQueryColumn($column, $constructMode);
if($generalIDList === null){ if ($generalIDList === null) {
$rawGenerals = Util::convertArrayToDict( $rawGenerals = Util::convertArrayToDict(
$db->query('SELECT %l FROM general WHERE 1', Util::formatListOfBackticks($column)), $db->query('SELECT %l FROM general WHERE 1', Util::formatListOfBackticks($column)),
'no' 'no'
); );
$generalIDList = array_keys($rawGenerals); $generalIDList = array_keys($rawGenerals);
} } else {
else{
$rawGenerals = Util::convertArrayToDict( $rawGenerals = Util::convertArrayToDict(
$db->query('SELECT %l FROM general WHERE no IN %li', Util::formatListOfBackticks($column), $generalIDList), $db->query('SELECT %l FROM general WHERE no IN %li', Util::formatListOfBackticks($column), $generalIDList),
'no' 'no'
@@ -1056,14 +1156,14 @@ class General implements iAction{
$rawRanks = []; $rawRanks = [];
if($rankColumn){ if ($rankColumn) {
$rawValue = $db->queryAllLists( $rawValue = $db->queryAllLists(
'SELECT `general_id`, `type`, `value` FROM rank_data WHERE general_id IN %li AND `type` IN %ls', 'SELECT `general_id`, `type`, `value` FROM rank_data WHERE general_id IN %li AND `type` IN %ls',
$generalIDList, $generalIDList,
$rankColumn $rankColumn
); );
foreach($rawValue as [$generalID, $rankType, $rankValue]){ foreach ($rawValue as [$generalID, $rankType, $rankValue]) {
if(!key_exists($generalID, $rawRanks)){ if (!key_exists($generalID, $rawRanks)) {
$rawRanks[$generalID] = []; $rawRanks[$generalID] = [];
} }
$rawRanks[$generalID][$rankType] = $rankValue; $rawRanks[$generalID][$rankType] = $rankValue;
@@ -1071,27 +1171,27 @@ class General implements iAction{
} }
$result = []; $result = [];
foreach($generalIDList as $generalID){ foreach ($generalIDList as $generalID) {
if(!key_exists($generalID, $rawGenerals)){ if (!key_exists($generalID, $rawGenerals)) {
$result[$generalID] = new DummyGeneral($constructMode > 0); $result[$generalID] = new DummyGeneral($constructMode > 0);
continue; continue;
} }
if(key_exists($generalID, $rawRanks) && count($rawRanks[$generalID]??[]) !== count($rankColumn)){ if (key_exists($generalID, $rawRanks) && count($rawRanks[$generalID] ?? []) !== count($rankColumn)) {
throw new \RuntimeException('column의 수가 일치하지 않음 : '.$generalID); throw new \RuntimeException('column의 수가 일치하지 않음 : ' . $generalID);
} }
$result[$generalID] = new static($rawGenerals[$generalID], $rawRanks[$generalID]??null, null, null, $year, $month, $constructMode > 1); $result[$generalID] = new static($rawGenerals[$generalID], $rawRanks[$generalID] ?? null, null, null, $year, $month, $constructMode > 1);
} }
return $result; return $result;
} }
static public function createGeneralObjFromDB(int $generalID, ?array $column=null, int $constructMode=2):self{ static public function createGeneralObjFromDB(int $generalID, ?array $column = null, int $constructMode = 2): self
{
$db = DB::db(); $db = DB::db();
if($constructMode > 0){ if ($constructMode > 0) {
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
} } else {
else{
$year = null; $year = null;
$month = null; $month = null;
} }
@@ -1099,14 +1199,14 @@ class General implements iAction{
[$column, $rankColumn] = static::mergeQueryColumn($column, $constructMode); [$column, $rankColumn] = static::mergeQueryColumn($column, $constructMode);
$rawGeneral = $db->queryFirstRow('SELECT %l FROM general WHERE no = %i', Util::formatListOfBackticks($column), $generalID); $rawGeneral = $db->queryFirstRow('SELECT %l FROM general WHERE no = %i', Util::formatListOfBackticks($column), $generalID);
if(!$rawGeneral){ if (!$rawGeneral) {
return new DummyGeneral($constructMode > 0); return new DummyGeneral($constructMode > 0);
} }
$rawRankValues = []; $rawRankValues = [];
if($rankColumn){ if ($rankColumn) {
$rawValue = $db->queryAllLists('SELECT `type`, `value` FROM rank_data WHERE general_id = %i AND `type` IN %ls', $generalID, $rankColumn); $rawValue = $db->queryAllLists('SELECT `type`, `value` FROM rank_data WHERE general_id = %i AND `type` IN %ls', $generalID, $rankColumn);
foreach($rawValue as [$rankType, $rankValue]){ foreach ($rawValue as [$rankType, $rankValue]) {
$rawRankValues[$rankType] = $rankValue; $rawRankValues[$rankType] = $rankValue;
} }
} }
@@ -1123,21 +1223,22 @@ class General implements iAction{
* @param array $env * @param array $env
* @return GeneralCommand[] * @return GeneralCommand[]
*/ */
static public function getReservedTurnByGeneralList(array $generalList, int $turnIdx, array $env){ static public function getReservedTurnByGeneralList(array $generalList, int $turnIdx, array $env)
if(!$generalList){ {
if (!$generalList) {
return []; return [];
} }
$generalIDList = array_map(function(General $general){ $generalIDList = array_map(function (General $general) {
return $general->getID(); return $general->getID();
}, $generalList); }, $generalList);
$db = DB::db(); $db = DB::db();
$result = []; $result = [];
$rawCmds = Util::convertArrayToDict($db->query('SELECT * FROM general_turn WHERE general_id IN %li AND turn_idx = %i', $generalIDList, $turnIdx), 'general_id'); $rawCmds = Util::convertArrayToDict($db->query('SELECT * FROM general_turn WHERE general_id IN %li AND turn_idx = %i', $generalIDList, $turnIdx), 'general_id');
foreach($generalList as $general){ foreach ($generalList as $general) {
$generalID = $general->getID(); $generalID = $general->getID();
if(!key_exists($generalID, $rawCmds)){ if (!key_exists($generalID, $rawCmds)) {
$result[$generalID] = buildGeneralCommandClass(null, $general, $env); $result[$generalID] = buildGeneralCommandClass(null, $general, $env);
continue; continue;
} }
@@ -1154,21 +1255,22 @@ class General implements iAction{
* @param array $env * @param array $env
* @return GeneralCommand[][] * @return GeneralCommand[][]
*/ */
static public function getReservedTurnListByGeneralList(array $generalList, int $turnIdxFrom, int $turnIdxTo, array $env){ static public function getReservedTurnListByGeneralList(array $generalList, int $turnIdxFrom, int $turnIdxTo, array $env)
{
//XXX: static인데 return값이 General이 아니라고?? GeneralCommandHelper같은게 있어야하지 않을까? //XXX: static인데 return값이 General이 아니라고?? GeneralCommandHelper같은게 있어야하지 않을까?
if(!$generalList){ if (!$generalList) {
return []; return [];
} }
if($turnIdxFrom < 0 || $turnIdxFrom >= GameConst::$maxTurn){ if ($turnIdxFrom < 0 || $turnIdxFrom >= GameConst::$maxTurn) {
throw new \OutOfRangeException('$turnIdxFrom 범위 초과'.$turnIdxFrom); throw new \OutOfRangeException('$turnIdxFrom 범위 초과' . $turnIdxFrom);
} }
if($turnIdxTo <= $turnIdxFrom || GameConst::$maxTurn < $turnIdxTo){ if ($turnIdxTo <= $turnIdxFrom || GameConst::$maxTurn < $turnIdxTo) {
throw new \OutOfRangeException('$turnIdxTo 범위 초과'.$turnIdxTo); throw new \OutOfRangeException('$turnIdxTo 범위 초과' . $turnIdxTo);
} }
$generalIDList = array_map(function(General $general){ $generalIDList = array_map(function (General $general) {
return $general->getID(); return $general->getID();
}, $generalList); }, $generalList);
@@ -1176,26 +1278,26 @@ class General implements iAction{
$rawCmds = $db->queryFirstRow('SELECT * FROM general_turn WHERE general_id IN %i AND %i <= turn_idx AND turn_idx < %i ORDER BY general_id ASC, turn_idx ASC', $generalIDList, $turnIdxFrom, $turnIdxTo); $rawCmds = $db->queryFirstRow('SELECT * FROM general_turn WHERE general_id IN %i AND %i <= turn_idx AND turn_idx < %i ORDER BY general_id ASC, turn_idx ASC', $generalIDList, $turnIdxFrom, $turnIdxTo);
$orderedRawCmds = []; $orderedRawCmds = [];
foreach($rawCmds as $rawCmd){ foreach ($rawCmds as $rawCmd) {
$generalID = $rawCmd['general_id']; $generalID = $rawCmd['general_id'];
$turnIdx = $rawCmd['turn_idx']; $turnIdx = $rawCmd['turn_idx'];
if(!key_exists($generalID, $orderedRawCmds)){ if (!key_exists($generalID, $orderedRawCmds)) {
$orderedRawCmds[$generalID] = []; $orderedRawCmds[$generalID] = [];
} }
$orderedRawCmds[$generalID][$turnIdx] = $rawCmd; $orderedRawCmds[$generalID][$turnIdx] = $rawCmd;
} }
$result = []; $result = [];
foreach($generalList as $general){ foreach ($generalList as $general) {
$generalID = $general->getID(); $generalID = $general->getID();
$result[$generalID] = []; $result[$generalID] = [];
if(!key_exists($generalID, $orderedRawCmds)){ if (!key_exists($generalID, $orderedRawCmds)) {
foreach(Util::range($turnIdxFrom, $turnIdxTo) as $turnIdx){ foreach (Util::range($turnIdxFrom, $turnIdxTo) as $turnIdx) {
$result[$generalID][$turnIdx] = buildGeneralCommandClass(null, $general, $env); $result[$generalID][$turnIdx] = buildGeneralCommandClass(null, $general, $env);
} }
continue; continue;
} }
foreach($orderedRawCmds[$generalID] as $turnIdx=>$rawCmd){ foreach ($orderedRawCmds[$generalID] as $turnIdx => $rawCmd) {
$result[$generalID][$turnIdx] = buildGeneralCommandClass($rawCmd['action'], $general, $env, Json::decode($rawCmd['arg'])); $result[$generalID][$turnIdx] = buildGeneralCommandClass($rawCmd['action'], $general, $env, Json::decode($rawCmd['arg']));
} }
} }
@@ -1205,109 +1307,113 @@ class General implements iAction{
/** /**
* @return int|float * @return int|float
*/ */
public function getInheritancePoint(string $key, &$aux=null, bool $forceCalc=false){ public function getInheritancePoint(string $key, &$aux = null, bool $forceCalc = false)
$inheritType = static::INHERITANCE_KEY[$key]??null; {
if($inheritType === null){ $inheritType = static::INHERITANCE_KEY[$key] ?? null;
if ($inheritType === null) {
throw new \OutOfRangeException("{$key}는 유산 타입이 아님"); throw new \OutOfRangeException("{$key}는 유산 타입이 아님");
} }
$ownerID = $this->getVar('owner'); $ownerID = $this->getVar('owner');
if(!$ownerID){ if (!$ownerID) {
return 0; return 0;
} }
if($this->getVar('npc') != 0){ if ($this->getVar('npc') != 0) {
return 0; return 0;
} }
[$storeType, $multiplier, ] = $inheritType; [$storeType, $multiplier,] = $inheritType;
$gameStor = KVStorage::getStorage(DB::db(), 'game_env'); $gameStor = KVStorage::getStorage(DB::db(), 'game_env');
if($storeType === true || ($gameStor->isunited != 0 && !$forceCalc)){ if ($storeType === true || ($gameStor->isunited != 0 && !$forceCalc)) {
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}"); $inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}");
[$value, $aux] = $inheritStor->getValue($key); [$value, $aux] = $inheritStor->getValue($key);
return $value; return $value;
} }
if(is_array($storeType)){ if (is_array($storeType)) {
[$storSubType, $storSubKey] = $storeType; [$storSubType, $storSubKey] = $storeType;
if($storSubType === 'rank'){ if ($storSubType === 'rank') {
return $this->getRankVar($storSubKey) * $multiplier; return $this->getRankVar($storSubKey) * $multiplier;
} }
if($storSubType === 'raw'){ if ($storSubType === 'raw') {
return $this->getVar($storSubKey) * $multiplier; return $this->getVar($storSubKey) * $multiplier;
} }
if($storSubType === 'aux'){ if ($storSubType === 'aux') {
return ($this->getAuxVar($storSubKey)??0) * $multiplier; return ($this->getAuxVar($storSubKey) ?? 0) * $multiplier;
} }
throw new \InvalidArgumentException("{$storSubType}은 참조 할 수 없는 유산 세부키임"); throw new \InvalidArgumentException("{$storSubType}은 참조 할 수 없는 유산 세부키임");
} }
if($storeType !== false){ if ($storeType !== false) {
throw new \InvalidArgumentException("{$storeType}은 올바르지 않은 유산 키임"); throw new \InvalidArgumentException("{$storeType}은 올바르지 않은 유산 키임");
} }
$extractFn = function(){ return [0, null];}; $extractFn = function () {
switch($key){ return [0, null];
case 'dex': };
$extractFn = function() use ($multiplier){ switch ($key) {
$totalDex = 0; case 'dex':
foreach(array_keys(GameUnitConst::allType()) as $armType){ $extractFn = function () use ($multiplier) {
$totalDex += $this->getVar("dex{$armType}"); $totalDex = 0;
} foreach (array_keys(GameUnitConst::allType()) as $armType) {
return [$totalDex * $multiplier, null]; $totalDex += $this->getVar("dex{$armType}");
}; }
break; return [$totalDex * $multiplier, null];
case 'betting': };
$extractFn = function() use ($multiplier){ break;
$betWin = $this->getRankVar('betwin'); case 'betting':
$betWinRate = $this->getRankVar('betwingold')/max(1, $this->getRankVar('betgold')); $extractFn = function () use ($multiplier) {
$betWin = $this->getRankVar('betwin');
$betWinRate = $this->getRankVar('betwingold') / max(1, $this->getRankVar('betgold'));
return [$betWin * $multiplier * pow($betWinRate, 2), null]; return [$betWin * $multiplier * pow($betWinRate, 2), null];
}; };
break; break;
case 'max_belong': case 'max_belong':
$extractFn = function() use ($multiplier){ $extractFn = function () use ($multiplier) {
$maxBelong = max($this->getVar('belong'), $this->getAuxVar('max_belong')??0); $maxBelong = max($this->getVar('belong'), $this->getAuxVar('max_belong') ?? 0);
return [$maxBelong * $multiplier, null]; return [$maxBelong * $multiplier, null];
}; };
break; break;
default: default:
throw new \InvalidArgumentException("{$key}는 유산 추출기를 보유하고 있지 않음"); throw new \InvalidArgumentException("{$key}는 유산 추출기를 보유하고 있지 않음");
} }
[$value, $aux] = ($extractFn)(); [$value, $aux] = ($extractFn)();
return $value; return $value;
} }
public function setInheritancePoint(string $key, $value, $aux=null){ public function setInheritancePoint(string $key, $value, $aux = null)
if(!is_int($value) && !is_float($value)){ {
if (!is_int($value) && !is_float($value)) {
throw new \InvalidArgumentException("{$value}는 숫자가 아님"); throw new \InvalidArgumentException("{$value}는 숫자가 아님");
} }
$inheritType = static::INHERITANCE_KEY[$key]??null; $inheritType = static::INHERITANCE_KEY[$key] ?? null;
if($inheritType === null){ if ($inheritType === null) {
throw new \OutOfRangeException("{$key}는 유산 타입이 아님"); throw new \OutOfRangeException("{$key}는 유산 타입이 아님");
} }
[$storeType, $multiplier, ] = $inheritType; [$storeType, $multiplier,] = $inheritType;
if($storeType !== true){ if ($storeType !== true) {
throw new \InvalidArgumentException("{$key}는 직접 저장형 유산 포인트가 아님"); throw new \InvalidArgumentException("{$key}는 직접 저장형 유산 포인트가 아님");
} }
if($multiplier != 1 && $value != 0){ if ($multiplier != 1 && $value != 0) {
throw new \InvalidArgumentException("{$key}는 1:1 유산 포인트가 아님"); throw new \InvalidArgumentException("{$key}는 1:1 유산 포인트가 아님");
} }
$ownerID = $this->getVar('owner'); $ownerID = $this->getVar('owner');
if(!$ownerID){ if (!$ownerID) {
return; return;
} }
if($this->getVar('npc') != 0){ if ($this->getVar('npc') != 0) {
return; return;
} }
$gameStor = KVStorage::getStorage(DB::db(), 'game_env'); $gameStor = KVStorage::getStorage(DB::db(), 'game_env');
if($gameStor->isunited != 0){ if ($gameStor->isunited != 0) {
return; return;
} }
@@ -1315,39 +1421,40 @@ class General implements iAction{
$inheritStor->setValue($key, [$value, $aux]); $inheritStor->setValue($key, [$value, $aux]);
} }
public function increaseInheritancePoint(string $key, $value, $aux=null){ public function increaseInheritancePoint(string $key, $value, $aux = null)
if(!is_int($value) && !is_float($value)){ {
if (!is_int($value) && !is_float($value)) {
throw new \InvalidArgumentException("{$value}는 숫자가 아님"); throw new \InvalidArgumentException("{$value}는 숫자가 아님");
} }
$inheritType = static::INHERITANCE_KEY[$key]??null; $inheritType = static::INHERITANCE_KEY[$key] ?? null;
if($inheritType === null){ if ($inheritType === null) {
throw new \OutOfRangeException("{$key}는 유산 타입이 아님"); throw new \OutOfRangeException("{$key}는 유산 타입이 아님");
} }
[$storeType, $multiplier, ] = $inheritType; [$storeType, $multiplier,] = $inheritType;
if($storeType !== true){ if ($storeType !== true) {
throw new \InvalidArgumentException("{$key}는 직접 저장형 유산 포인트가 아님"); throw new \InvalidArgumentException("{$key}는 직접 저장형 유산 포인트가 아님");
} }
$ownerID = $this->getVar('owner'); $ownerID = $this->getVar('owner');
if(!$ownerID){ if (!$ownerID) {
return; return;
} }
if($this->getVar('npc') != 0){ if ($this->getVar('npc') != 0) {
return; return;
} }
$gameStor = KVStorage::getStorage(DB::db(), 'game_env'); $gameStor = KVStorage::getStorage(DB::db(), 'game_env');
if($gameStor->isunited != 0){ if ($gameStor->isunited != 0) {
return; return;
} }
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}"); $inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}");
[$oldValue, $oldAux] = $inheritStor->getValue($key)??[0, null]; [$oldValue, $oldAux] = $inheritStor->getValue($key) ?? [0, null];
if($oldAux !== $aux){ if ($oldAux !== $aux) {
$oldValue = 0; $oldValue = 0;
} }
@@ -1355,22 +1462,23 @@ class General implements iAction{
$inheritStor->setValue($key, [$newValue, $aux]); $inheritStor->setValue($key, [$newValue, $aux]);
} }
public function mergeTotalInheritancePoint(){ public function mergeTotalInheritancePoint()
{
$ownerID = $this->getVar('owner'); $ownerID = $this->getVar('owner');
if(!$ownerID){ if (!$ownerID) {
return; return;
} }
if($this->getVar('npc') != 0){ if ($this->getVar('npc') != 0) {
return; return;
} }
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}"); $inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}");
$inheritStor->cacheAll(); $inheritStor->cacheAll();
foreach(static::INHERITANCE_KEY as $key=>[$storType, ,]){ foreach (static::INHERITANCE_KEY as $key => [$storType,,]) {
$aux = null; $aux = null;
$point = $this->getInheritancePoint($key, $aux, true); $point = $this->getInheritancePoint($key, $aux, true);
if($storType === true){ if ($storType === true) {
continue; continue;
} }
$inheritStor->setValue($key, [$point, $aux]); $inheritStor->setValue($key, [$point, $aux]);
@@ -1383,4 +1491,4 @@ class General implements iAction{
$month = $gameStor->month; $month = $gameStor->month;
$oldInheritStor->setValue("{$serverID}_{$ownerID}_{$this->getID()}_{$year}_{$month}", $inheritStor->getAll(true)); $oldInheritStor->setValue("{$serverID}_{$ownerID}_{$this->getID()}_{$year}_{$month}", $inheritStor->getAll(true));
} }
} }
+1 -1
View File
@@ -681,7 +681,7 @@ class GeneralBuilder{
'turntime'=>$turntime, 'turntime'=>$turntime,
'killturn'=>$killturn, 'killturn'=>$killturn,
'age'=>$age, 'age'=>$age,
'belong'=>1, 'belong'=>0,
'personal'=>$this->ego, 'personal'=>$this->ego,
'special'=>$this->specialDomestic, 'special'=>$this->specialDomestic,
'specage'=>$this->specAge, 'specage'=>$this->specAge,
+89
View File
@@ -0,0 +1,89 @@
<?php
namespace sammo;
class UserLogger
{
protected $userID;
protected $year;
protected $month;
protected $autoFlush;
protected $log = [];
function __construct(int $userID, ?int $year = null, ?int $month = null, bool $autoFlush = true)
{
$this->userID = $userID;
if ($year === null || $month === null) {
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->cacheValues(['year', 'month']);
if ($year === null) {
$year = $gameStor->year;
}
if ($month === null) {
$month = $gameStor->month;
}
}
$this->year = $year;
$this->month = $month;
$this->autoFlush = $autoFlush;
}
public function __destruct()
{
if ($this->autoFlush) {
$this->flush();
}
}
public function rollback()
{
$backup = $this->log;
$this->log = [];
return $backup;
}
public function flush()
{
if(!$this->log){
return;
}
if(!$this->userID){
return;
}
$db = DB::db();
$date = TimeUtil::now();
$serverID = UniqueConst::$serverID;
$request = array_map(function ($textAndType) use ($date, $serverID) {
[$text, $type] = $textAndType;
return [
'user_id' => $this->userID,
'server_id' => $serverID,
'log_type' => $type,
'year' => $this->year,
'month' => $this->month,
'date' => $date,
'text' => $text
];
}, array_values($this->log));
$db->insert('user_record', $request);
$this->log = [];
}
public function push($text, string $type)
{
if (!$text) {
return;
}
if (is_array($text)) {
foreach ($text as $textItem) {
$this->log[] = [$textItem, $type];
}
return;
}
$this->log[] = [$text, $type];
}
}
@@ -14,6 +14,7 @@ class che_반계시도 extends BaseWarUnitTrigger{
public function __construct(WarUnit $unit, int $raiseType = 0, float $prob = 0.4){ public function __construct(WarUnit $unit, int $raiseType = 0, float $prob = 0.4){
$this->object = $unit; $this->object = $unit;
$this->raiseType = $raiseType;
$this->prob = $prob; $this->prob = $prob;
} }
+5 -5
View File
@@ -149,7 +149,7 @@
<div class="col col-md-1 col-3"> <div class="col col-md-1 col-3">
<label <label
><input type="checkbox" v-model="displayInherit" />{{ ><input type="checkbox" v-model="displayInherit" />{{
displayTable ? "숨기기" : "보이기" displayInherit ? "숨기기" : "보이기"
}}</label }}</label
> >
</div> </div>
@@ -305,7 +305,7 @@ import {
CTableRow, CTableRow,
CTableHeaderCell, CTableHeaderCell,
CTableDataCell, CTableDataCell,
} from "@coreui/vue/src"; } from "@coreui/vue/src/components/table";
import { getIconPath } from "./util/getIconPath"; import { getIconPath } from "./util/getIconPath";
import { isBrightColor } from "./util/isBrightColor"; import { isBrightColor } from "./util/isBrightColor";
import { import {
@@ -458,21 +458,21 @@ export default defineComponent({
}, },
inheritTurnTimeMinute(newValue: number) { inheritTurnTimeMinute(newValue: number) {
if (!this.inheritTurnTimeSet) { if (!this.inheritTurnTimeSet) {
this.args.inheritTurntime = 0; this.args.inheritTurntime = undefined;
return; return;
} }
this.args.inheritTurntime = newValue * 60 + this.inheritTurnTimeSecond; this.args.inheritTurntime = newValue * 60 + this.inheritTurnTimeSecond;
}, },
inheritTurnTimeSecond(newValue: number) { inheritTurnTimeSecond(newValue: number) {
if (!this.inheritTurnTimeSet) { if (!this.inheritTurnTimeSet) {
this.args.inheritTurntime = 0; this.args.inheritTurntime = undefined;
return; return;
} }
this.args.inheritTurntime = this.inheritTurnTimeMinute * 60 + newValue; this.args.inheritTurntime = this.inheritTurnTimeMinute * 60 + newValue;
}, },
inheritTurnTimeSet(newValue: boolean) { inheritTurnTimeSet(newValue: boolean) {
if (!newValue) { if (!newValue) {
this.args.inheritTurntime = 0; this.args.inheritTurntime = undefined;
return; return;
} }
this.args.inheritTurntime = this.args.inheritTurntime =
+1 -1
View File
@@ -50,7 +50,7 @@
<NumberInputWithInfo <NumberInputWithInfo
v-model="nationPolicy.reqHumanWarUrgentRice" v-model="nationPolicy.reqHumanWarUrgentRice"
:step="100" :step="100"
title="유저전투장 긴급포상 " title="유저전투장 긴급포상 "
>유저장긴급포상시 이보다 쌀이 적은 장수에게 포상합니다.<br />0이면 >유저장긴급포상시 이보다 쌀이 적은 장수에게 포상합니다.<br />0이면
기본 병종으로 {{ (defaultStatMax * 100).toLocaleString() }} * 6 사살 기본 병종으로 {{ (defaultStatMax * 100).toLocaleString() }} * 6 사살
가능한 쌀을 기준으로 하며, 수치는 현재 가능한 쌀을 기준으로 하며, 수치는 현재
+3 -3
View File
@@ -893,7 +893,7 @@ $(function ($) {
} }
showBattleResult(result); showBattleResult(result);
}, function (result) { }, function () {
alert('전투 개시 실패!'); alert('전투 개시 실패!');
}); });
} }
@@ -933,7 +933,7 @@ $(function ($) {
} }
reorderDefender(result.order); reorderDefender(result.order);
}, function (result) { }, function () {
alert('재정렬 실패!'); alert('재정렬 실패!');
}); });
} }
@@ -968,7 +968,7 @@ $(function ($) {
}); });
$('#importModal').on('show.bs.modal', function (e) { $('#importModal').on('show.bs.modal', function () {
if (!initGeneralList) { if (!initGeneralList) {
const $list = $('#modalSelector'); const $list = $('#modalSelector');
-1
View File
@@ -19,7 +19,6 @@
"currentCity": "currentCity.ts", "currentCity": "currentCity.ts",
"hallOfFame": "hallOfFame.ts", "hallOfFame": "hallOfFame.ts",
"history": "history.ts", "history": "history.ts",
"join": "legacy/join.ts",
"select_general_from_pool": "select_general_from_pool.ts", "select_general_from_pool": "select_general_from_pool.ts",
"extKingdoms": "extKingdoms.ts", "extKingdoms": "extKingdoms.ts",
"common": "common_deprecated.ts" "common": "common_deprecated.ts"
+2 -3
View File
@@ -1,5 +1,4 @@
import { template } from "lodash"; import { NPCChiefActions, NPCGeneralActions } from "./defs";
import { NationPolicy, NPCChiefActions, NPCGeneralActions } from "./defs";
export const NPCPriorityBtnHelpMessage: { export const NPCPriorityBtnHelpMessage: {
[v in NPCChiefActions | NPCGeneralActions]: string; [v in NPCChiefActions | NPCGeneralActions]: string;
@@ -34,7 +33,7 @@ export const NPCPriorityBtnHelpMessage: {
NPC후방발령: NPC후방발령:
"NPC전투장 중에<br>- 병력이 충분하지 않고,<br>- 도시의 인구가 제자리 징병할 수 있을 정도로 충분하지 않고,<br>- 부대에 탑승하지 않았다면,<br>인구가 충분한 후방도시로 발령합니다.", "NPC전투장 중에<br>- 병력이 충분하지 않고,<br>- 도시의 인구가 제자리 징병할 수 있을 정도로 충분하지 않고,<br>- 부대에 탑승하지 않았다면,<br>인구가 충분한 후방도시로 발령합니다.",
NPC포상: NPC포상:
"금/쌀이 부족한 유저장에게 포상합니다.<br>NPC전투장과 NPC내정장은 각각 기준을 따릅니다.<br>국고 권장량을 가급적 지킵니다.", "금/쌀이 부족한 NPC에게 포상합니다.<br>NPC전투장과 NPC내정장은 각각 기준을 따릅니다.<br>국고 권장량을 가급적 지킵니다.",
NPC전방발령: NPC전방발령:
"후방에 있는 유저장이<br>- 병력을 가지고 있으며,<br>- 곧 훈련/사기진작이 완료될 것 같으면,<br>전방으로 발령합니다.<br><br>도시 관직이 많이 임명된 도시를 선호합니다.", "후방에 있는 유저장이<br>- 병력을 가지고 있으며,<br>- 곧 훈련/사기진작이 완료될 것 같으면,<br>전방으로 발령합니다.<br><br>도시 관직이 많이 임명된 도시를 선호합니다.",
: :
+30 -6
View File
@@ -3,7 +3,12 @@
<div <div
id="container" id="container"
class="bg0 px-2" class="bg0 px-2"
style="max-width: 1000px; margin: auto; border: solid 1px #888888; overflow:hidden;" style="
max-width: 1000px;
margin: auto;
border: solid 1px #888888;
overflow: hidden;
"
> >
<div id="inheritance_list" class="row"> <div id="inheritance_list" class="row">
<template v-for="(text, key) in inheritanceViewText" :key="key"> <template v-for="(text, key) in inheritanceViewText" :key="key">
@@ -235,6 +240,20 @@
</div> </div>
</div> </div>
</div> </div>
<div class="row">
<div class="col">
<div class="bg1 a-center">유산 포인트 변경 내역(최근 30)</div>
</div>
</div>
<div class="row" v-for="(log, idx) in lastInheritPointLogs" :key="idx">
<div class="col a-right" style="max-width:20ch">
<small class="text-muted">[{{log.date}}]</small>
</div>
<div class="col a-left">
{{log.text}}
</div>
</div>
</div> </div>
</template> </template>
@@ -263,6 +282,14 @@ type InheritanceType =
type InheritanceViewType = InheritanceType | "sum" | "new"; type InheritanceViewType = InheritanceType | "sum" | "new";
declare const lastInheritPointLogs: {
server_id: string,
year: number,
month: number,
date: string,
text: string,
}[];
declare const items: Record<InheritanceType, number>; declare const items: Record<InheritanceType, number>;
const inheritanceViewText: Record< const inheritanceViewText: Record<
@@ -442,6 +469,7 @@ export default defineComponent({
availableSpecialWar, availableSpecialWar,
availableUnique, availableUnique,
specificUniqueAmount: inheritActionCost.minSpecificUnique, specificUniqueAmount: inheritActionCost.minSpecificUnique,
lastInheritPointLogs,
}; };
}, },
methods: { methods: {
@@ -617,11 +645,7 @@ export default defineComponent({
return; return;
} }
//TODO: JosaUtil //TODO: JosaUtil
if ( if (!confirm(`${amount} 포인트로 ${uniqueName}(을)를 입찰하겠습니까?`)) {
!confirm(
`${amount} 포인트로 ${uniqueName}(을)를 입찰하겠습니까?`
)
) {
return; return;
} }
-213
View File
@@ -1,213 +0,0 @@
import $ from 'jquery';
import { exportWindow } from '../util/exportWindow';
import { mb_strwidth } from '../util/mb_strwidth';
import { unwrap_any } from '../util/unwrap_any';
declare const defaultStatTotal: number;
declare const defaultStatMax: number;
declare const defaultStatMin: number;
declare const charInfoText: Record<string, string>;
$(function ($) {
const $leadership = $('#leadership');
const $strength = $('#strength');
const $intel = $('#intel');
function abilityRand(): void {
let leadership = Math.random() * 65 + 10;
let strength = Math.random() * 65 + 10;
let intel = Math.random() * 65 + 10;
const rate = leadership + strength + intel;
leadership = Math.floor(leadership / rate * defaultStatTotal);
strength = Math.floor(strength / rate * defaultStatTotal);
intel = Math.floor(intel / rate * defaultStatTotal);
while (leadership + strength + intel < defaultStatTotal) {
leadership += 1;
}
if (leadership > defaultStatMax || strength > defaultStatMax || intel > defaultStatMax || leadership < defaultStatMin || strength < defaultStatMin || intel < defaultStatMin) {
return abilityRand();
}
$leadership.val(leadership);
$strength.val(strength);
$intel.val(intel);
}
function abilityLeadpow() {
let leadership = Math.random() * 6;
let strength = Math.random() * 6;
let intel = Math.random() * 1;
const rate = leadership + strength + intel;
leadership = Math.floor(leadership / rate * defaultStatTotal);
strength = Math.floor(strength / rate * defaultStatTotal);
intel = Math.floor(intel / rate * defaultStatTotal);
while (leadership + strength + intel < defaultStatTotal) {
strength += 1;
}
if (intel < defaultStatMin) {
leadership -= defaultStatMin - intel;
intel = defaultStatMin;
}
if (leadership > defaultStatMax) {
strength += leadership - defaultStatMax;
leadership = defaultStatMax;
}
if (strength > defaultStatMax) {
leadership += strength - defaultStatMax;
strength = defaultStatMax;
}
if (leadership > defaultStatMax) {
intel += leadership - defaultStatMax;
leadership = defaultStatMax;
}
$leadership.val(leadership);
$strength.val(strength);
$intel.val(intel);
}
function abilityLeadint() {
let leadership = Math.random() * 6;
let strength = Math.random() * 1;
let intel = Math.random() * 6;
const rate = leadership + strength + intel;
leadership = Math.floor(leadership / rate * defaultStatTotal);
strength = Math.floor(strength / rate * defaultStatTotal);
intel = Math.floor(intel / rate * defaultStatTotal);
while (leadership + strength + intel < defaultStatTotal) {
intel += 1;
}
if (strength < defaultStatMin) {
leadership -= defaultStatMin - strength;
strength = defaultStatMin;
}
if (leadership > defaultStatMax) {
intel += leadership - defaultStatMax;
leadership = defaultStatMax;
}
if (intel > defaultStatMax) {
leadership += intel - defaultStatMax;
intel = defaultStatMax;
}
if (leadership > defaultStatMax) {
strength += leadership - defaultStatMax;
leadership = defaultStatMax;
}
$leadership.val(leadership);
$strength.val(strength);
$intel.val(intel);
}
function abilityPowint() {
let leadership = Math.random() * 1;
let strength = Math.random() * 6;
let intel = Math.random() * 6;
const rate = leadership + strength + intel;
leadership = Math.floor(leadership / rate * defaultStatTotal);
strength = Math.floor(strength / rate * defaultStatTotal);
intel = Math.floor(intel / rate * defaultStatTotal);
while (leadership + strength + intel < defaultStatTotal) {
intel += 1;
}
if (leadership < defaultStatMin) {
strength -= defaultStatMin - leadership;
leadership = defaultStatMin;
}
if (strength > defaultStatMax) {
intel += strength - defaultStatMax;
strength = defaultStatMax;
}
if (intel > defaultStatMax) {
strength += intel - defaultStatMax;
intel = defaultStatMax;
}
if (strength > defaultStatMax) {
leadership += strength - defaultStatMax;
strength = defaultStatMax;
}
$leadership.val(leadership);
$strength.val(strength);
$intel.val(intel);
}
exportWindow(abilityRand, 'abilityRand');
exportWindow(abilityLeadpow, 'abilityLeadpow');
exportWindow(abilityLeadint, 'abilityLeadint');
exportWindow(abilityPowint, 'abilityPowint');
const $charInfoText = $('#charInfoText');
const $selChar = $('#selChar');
$selChar.change(function () {
const $this = $(this);
const char = unwrap_any<string>($this.val());
if (char in charInfoText) {
$charInfoText.html(charInfoText[char]);
}
else {
$charInfoText.html('');
}
});
const $generalName = $('#generalName');
$generalName.on('change keyup paste', function () {
const generalName = unwrap_any<string>($generalName.val());
const len = mb_strwidth(generalName);
if (len == 0 || len > 18) {
$generalName.css('color', 'red');
}
else {
$generalName.css('color', 'white');
}
});
$('#join_form').submit(function () {
const generalName = unwrap_any<string>($generalName.val());
if (mb_strwidth(generalName) > 18) {
alert('장수 이름이 너무 깁니다!');
return false;
}
const currentStatTotal = parseInt(unwrap_any<string>($leadership.val())) + parseInt(unwrap_any<string>($strength.val())) + parseInt(unwrap_any<string>($intel.val()));
if (currentStatTotal < defaultStatTotal) {
if (!confirm(`현재 능력치 총합은 ${currentStatTotal}으로, ${defaultStatTotal}보다 낮습니다. 그래도 생성할까요?`)) {
return false;
}
}
return true;
});
const randomGenType = Math.floor(Math.random() * 7);
if (randomGenType < 3) {
abilityLeadpow();
}
else if (randomGenType < 6) {
abilityLeadint();
}
else {
abilityPowint();
}
});
+1 -1
View File
@@ -516,7 +516,7 @@ export async function reloadWorldMap(option: loadMapOption, drawTarget = '.world
//터치스크린 탭 //터치스크린 탭
if (!option.neutralView && is_touch_device()) { if (!option.neutralView && is_touch_device()) {
$objs.on('touchstart', function (e) { $objs.on('touchstart', function () {
if (window.sam_toggleSingleTap) { if (window.sam_toggleSingleTap) {
return true; return true;
} }
+4
View File
@@ -171,6 +171,7 @@ $(function ($) {
}); });
$('#set_my_setting').on('click', async function (e) { $('#set_my_setting').on('click', async function (e) {
e.preventDefault();
let result: InvalidResponse; let result: InvalidResponse;
try { try {
@@ -186,6 +187,9 @@ $(function ($) {
}) })
}); });
result = response.data; result = response.data;
if(!result.result){
throw result.reason;
}
} }
catch (e) { catch (e) {
console.log(e); console.log(e);
+1 -1
View File
@@ -203,7 +203,7 @@ function printGenerals(value: NPCToken) {
const time = Date.now() + value.pickMoreSeconds * 1000; const time = Date.now() + value.pickMoreSeconds * 1000;
$('#btn_pick_more').data('available', time).prop('disabled', true); $('#btn_pick_more').data('available', time).prop('disabled', true);
const pick = $.map(value.pick, function (value, key) { const pick = $.map(value.pick, function (value) {
return value; return value;
}); });
+11 -8
View File
@@ -17,7 +17,7 @@ $me = General::createGeneralObjFromDB($generalID);
$currentInheritBuff = []; $currentInheritBuff = [];
foreach ($me->getAuxVar('inheritBuff')??[] as $buff => $buffLevel) { foreach ($me->getAuxVar('inheritBuff') ?? [] as $buff => $buffLevel) {
if (!key_exists($buff, TriggerInheritBuff::BUFF_KEY_TEXT)) { if (!key_exists($buff, TriggerInheritBuff::BUFF_KEY_TEXT)) {
continue; continue;
} }
@@ -43,15 +43,15 @@ foreach (GameConst::$availableSpecialWar as $specialWarKey) {
} }
$availableUnique = []; $availableUnique = [];
foreach (GameConst::$allItems as $subItems){ foreach (GameConst::$allItems as $subItems) {
foreach($subItems as $itemKey=>$amount){ foreach ($subItems as $itemKey => $amount) {
if($amount == 0){ if ($amount == 0) {
continue; continue;
} }
$itemObj = buildItemClass($itemKey); $itemObj = buildItemClass($itemKey);
$availableUnique[$itemKey] = [ $availableUnique[$itemKey] = [
'title' => $itemObj->getName(), 'title' => $itemObj->getName(),
'info'=>$itemObj->getInfo(), 'info' => $itemObj->getInfo(),
]; ];
} }
} }
@@ -62,8 +62,10 @@ foreach (array_keys(General::INHERITANCE_KEY) as $key) {
$items[$key] = $me->getInheritancePoint($key) ?? 0; $items[$key] = $me->getInheritancePoint($key) ?? 0;
} }
$resetTurnTimeLevel = $me->getAuxVar('inheritResetTurnTime') ?? 0; $resetTurnTimeLevel = ($me->getAuxVar('inheritResetTurnTime') ?? -1) + 1;
$resetSpecialWarLevel = $me->getAuxVar('inheritResetSpecialWar') ?? 0; $resetSpecialWarLevel = ($me->getAuxVar('inheritResetSpecialWar') ?? -1) + 1;
$lastInheritPointLogs = $db->query('SELECT server_id, year, month, date, text FROM user_record WHERE log_type = %s AND user_id = %i ORDER BY id desc LIMIT 30', "inheritPoint", $userID);
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
@@ -91,10 +93,11 @@ $resetSpecialWarLevel = $me->getAuxVar('inheritResetSpecialWar') ?? 0;
'resetSpecialWar' => calcResetAttrPoint($resetSpecialWarLevel), 'resetSpecialWar' => calcResetAttrPoint($resetSpecialWarLevel),
'randomUnique' => GameConst::$inheritItemRandomPoint, 'randomUnique' => GameConst::$inheritItemRandomPoint,
'nextSpecial' => GameConst::$inheritSpecificSpecialPoint, 'nextSpecial' => GameConst::$inheritSpecificSpecialPoint,
'minSpecificUnique'=>GameConst::$inheritItemUniqueMinPoint, 'minSpecificUnique' => GameConst::$inheritItemUniqueMinPoint,
], ],
'availableSpecialWar' => $avilableSpecialWar, 'availableSpecialWar' => $avilableSpecialWar,
'availableUnique' => $availableUnique, 'availableUnique' => $availableUnique,
'lastInheritPointLogs' => $lastInheritPointLogs,
]) ?> ]) ?>
</head> </head>
+1 -1
View File
@@ -230,7 +230,7 @@ if ($server == $baseServerName) {
__DIR__ . '/' . $server . '/d_setting/VersionGit.php', __DIR__ . '/' . $server . '/d_setting/VersionGit.php',
[ [
'verionGit' => $version, 'verionGit' => $version,
'hash' => $hash 'hash' => $gitHash
], ],
true true
); );
+13 -15
View File
@@ -27,8 +27,8 @@
"axios": "^0.21.4", "axios": "^0.21.4",
"bootstrap": "^4.6.0", "bootstrap": "^4.6.0",
"bootstrap5": "npm:bootstrap@^5.1.1", "bootstrap5": "npm:bootstrap@^5.1.1",
"core-js": "^3.17.2", "core-js": "^3.17.3",
"date-fns": "^2.23.0", "date-fns": "^2.24.0",
"downloadjs": "^1.4.7", "downloadjs": "^1.4.7",
"jquery": "^3.6.0", "jquery": "^3.6.0",
"js-sha512": "^0.8.0", "js-sha512": "^0.8.0",
@@ -45,39 +45,37 @@
"devDependencies": { "devDependencies": {
"@babel/cli": "^7.15.4", "@babel/cli": "^7.15.4",
"@babel/core": "^7.15.5", "@babel/core": "^7.15.5",
"@babel/preset-env": "^7.15.4", "@babel/preset-env": "^7.15.6",
"@babel/preset-typescript": "^7.15.0", "@babel/preset-typescript": "^7.15.0",
"@coreui/vue": "^4.0.0-beta.2", "@coreui/vue": "^4.0.0-beta.2",
"@types/bootstrap": "^5.1.4", "@types/bootstrap": "^5.1.4",
"@types/jquery": "^3.5.6", "@types/jquery": "^3.5.6",
"@types/lodash": "^4.14.172", "@types/lodash": "^4.14.173",
"@types/node": "^16.7.13", "@types/node": "^16.9.2",
"@typescript-eslint/eslint-plugin": "^4.31.0", "@typescript-eslint/eslint-plugin": "^4.31.1",
"@typescript-eslint/parser": "^4.31.0", "@typescript-eslint/parser": "^4.31.1",
"@vue/compiler-sfc": "^3.2.10", "@vue/compiler-sfc": "^3.2.12",
"@vue/eslint-config-typescript": "^7.0.0", "@vue/eslint-config-typescript": "^7.0.0",
"babel-loader": "^8.2.2",
"babel-plugin-lodash": "^3.3.4", "babel-plugin-lodash": "^3.3.4",
"babel-preset-modern-browsers": "^15.0.2", "babel-preset-modern-browsers": "^15.0.2",
"bootstrap-vue-3": "^0.0.3", "bootstrap-vue-3": "^0.0.3",
"bootswatch": "^5.1.1", "bootswatch": "^5.1.1",
"clean-terminal-webpack-plugin": "^3.0.0", "clean-terminal-webpack-plugin": "^3.0.0",
"css-loader": "^6.2.0", "css-loader": "^6.2.0",
"css-minimizer-webpack-plugin": "^3.0.2", "esbuild-loader": "^2.15.1",
"eslint": "^7.32.0", "eslint": "^7.32.0",
"file-loader": "^6.2.0", "file-loader": "^6.2.0",
"mini-css-extract-plugin": "^2.2.2", "mini-css-extract-plugin": "^2.3.0",
"pre-commit": "^1.2.2", "pre-commit": "^1.2.2",
"sass": "^1.39.0", "sass": "^1.41.1",
"sass-loader": "^12.1.0", "sass-loader": "^12.1.0",
"style-loader": "^3.2.1", "style-loader": "^3.2.1",
"ts-loader": "^9.2.5", "typescript": "^4.4.3",
"typescript": "^4.4.2",
"url-loader": "^4.1.1", "url-loader": "^4.1.1",
"vue-eslint-parser": "^7.11.0", "vue-eslint-parser": "^7.11.0",
"vue-loader": "^16.5.0", "vue-loader": "^16.5.0",
"vue-style-loader": "^4.1.3", "vue-style-loader": "^4.1.3",
"webpack": "^5.52.0", "webpack": "^5.53.0",
"webpack-bundle-analyzer": "^4.4.2", "webpack-bundle-analyzer": "^4.4.2",
"webpack-cli": "^4.8.0" "webpack-cli": "^4.8.0"
}, },
+102 -61
View File
@@ -1,17 +1,17 @@
const path = require('path'); const path = require('path');
const { VueLoaderPlugin } = require('vue-loader'); const { VueLoaderPlugin } = require('vue-loader');
const MiniCssExtractPlugin = require('mini-css-extract-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin; const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const { resolve } = require('path'); const { resolve } = require('path');
const CleanTerminalPlugin = require('clean-terminal-webpack-plugin'); const CleanTerminalPlugin = require('clean-terminal-webpack-plugin');
const TerserPlugin = require('terser-webpack-plugin'); const { ESBuildMinifyPlugin } = require('esbuild-loader')
module.exports = (env, argv) => { module.exports = (env, argv) => {
const target = env.target ?? 'hwe'; const target = env.target ?? 'hwe';
const mode = argv.mode ?? 'production'; const mode = argv.mode ?? 'production';
const tsDir = resolve(__dirname, `${target}/ts/`); const tsDir = resolve(__dirname, `${target}/ts/`);
const build_exports = require(`${tsDir}/build_exports.json`); const build_exports = require(`${tsDir}/build_exports.json`);
//TODO: esbuild에 browserslist 사용 가능하면 적용
//서버마다 ts 파일 구성이 다를 가능성이 높기 때문에 어떤 파일이 필요한지는 ts/build_exports.json을 확인한다. //서버마다 ts 파일 구성이 다를 가능성이 높기 때문에 어떤 파일이 필요한지는 ts/build_exports.json을 확인한다.
const entryIngameVue = {}; const entryIngameVue = {};
@@ -58,14 +58,8 @@ module.exports = (env, argv) => {
}, },
}, },
minimizer: [ minimizer: [
new CssMinimizerPlugin(), new ESBuildMinifyPlugin({
new TerserPlugin({ css: true
terserOptions: {
format: {
comments: /@license/i,
},
},
extractComments: true,
}), }),
], ],
moduleIds: 'deterministic', moduleIds: 'deterministic',
@@ -74,18 +68,27 @@ module.exports = (env, argv) => {
rules: [ rules: [
//FROM `vue inspect` and some tweaks //FROM `vue inspect` and some tweaks
{ {
test: /\.(ts|tsx)$/, test: /\.ts$/,
//exclude: /(node_modules)/, //exclude: /(node_modules)/,
use: [ use: [
'babel-loader',
{ {
loader: 'ts-loader', loader: 'esbuild-loader',
options: { options: {
transpileOnly: true, loader: 'ts',
appendTsSuffixTo: [ target: 'es2019',
'\\.vue$' }
], }
happyPackMode: false ]
},
{
test: /\.tsx$/,
//exclude: /(node_modules)/,
use: [
{
loader: 'esbuild-loader',
options: {
loader: 'tsx',
target: 'es2019',
} }
} }
] ]
@@ -94,7 +97,13 @@ module.exports = (env, argv) => {
test: /\.js$/, test: /\.js$/,
exclude: /(node_modules)/, exclude: /(node_modules)/,
use: [ use: [
'babel-loader', {
loader: 'esbuild-loader',
options: {
loader: 'js',
target: 'es2019',
}
}
] ]
}, },
{ {
@@ -194,35 +203,51 @@ module.exports = (env, argv) => {
}, },
}, },
minimizer: [ minimizer: [
new CssMinimizerPlugin(), new ESBuildMinifyPlugin({
new TerserPlugin({ css: true
terserOptions: {
format: {
comments: /@license/i,
},
},
extractComments: true,
}), }),
], ],
moduleIds: 'deterministic', moduleIds: 'deterministic',
}, },
module: { module: {
rules: [{ rules: [{
test: /\.(ts|tsx)$/i, test: /\.ts$/,
exclude: /(node_modules)/, exclude: /(node_modules)/,
use: [{ use: [
loader: 'babel-loader', {
options: { loader: 'esbuild-loader',
presets: [ options: {
['@babel/preset-env', { loader: 'ts',
"useBuiltIns": "usage", target: 'es2019',
"corejs": 3, }
"modules": false
}],
'@babel/preset-typescript'
]
} }
}, 'ts-loader'] ]
},
{
test: /\.tsx$/,
exclude: /(node_modules)/,
use: [
{
loader: 'esbuild-loader',
options: {
loader: 'tsx',
target: 'es2019',
}
}
]
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
{
loader: 'esbuild-loader',
options: {
loader: 'js',
target: 'es2019',
}
}
]
}, },
{ {
test: /.(s?[ac]ss)$/, test: /.(s?[ac]ss)$/,
@@ -270,35 +295,51 @@ module.exports = (env, argv) => {
}, },
}, },
minimizer: [ minimizer: [
new CssMinimizerPlugin(), new ESBuildMinifyPlugin({
new TerserPlugin({ css: true
terserOptions: {
format: {
comments: /@license/i,
},
},
extractComments: true,
}), }),
], ],
moduleIds: 'deterministic', moduleIds: 'deterministic',
}, },
module: { module: {
rules: [{ rules: [{
test: /\.(ts|tsx)$/i, test: /\.ts$/,
exclude: /(node_modules)/, exclude: /(node_modules)/,
use: { use: [
loader: 'babel-loader', {
options: { loader: 'esbuild-loader',
presets: [ options: {
['@babel/preset-env', { loader: 'ts',
"useBuiltIns": "usage", target: 'es2019',
"corejs": 3, }
"modules": false
}],
'@babel/preset-typescript'
]
} }
} ]
},
{
test: /\.tsx$/,
exclude: /(node_modules)/,
use: [
{
loader: 'esbuild-loader',
options: {
loader: 'tsx',
target: 'es2019',
}
}
]
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: [
{
loader: 'esbuild-loader',
options: {
loader: 'js',
target: 'es2019',
}
}
]
}, { }, {
test: /.(s?[ac]ss)$/, test: /.(s?[ac]ss)$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'] use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader']