전략 사용 방식 변경

This commit is contained in:
2020-07-13 21:54:32 +09:00
parent a427ddff83
commit 6306dae92d
24 changed files with 4024 additions and 3910 deletions
+1 -1
View File
@@ -232,7 +232,7 @@ function checkCommandArg(?array $arg):?string{
} }
$defaultCheck = [ $defaultCheck = [
/*'string'=>[ /*'string'=>[
'nationName', 'optionText', 'itemType', 'nationType' 'nationName', 'optionText', 'itemType', 'nationType', 'commandType',
],*/ ],*/
'integer'=>[ 'integer'=>[
'crewType', 'destGeneralID', 'destCityID', 'destNationID', 'crewType', 'destGeneralID', 'destCityID', 'destNationID',
+1139 -1138
View File
@@ -1,1138 +1,1139 @@
<?php <?php
namespace sammo; namespace sammo;
use Monolog\Logger; use Monolog\Logger;
/** /**
* 게임 룰에 해당하는 함수 모음 * 게임 룰에 해당하는 함수 모음
*/ */
function getNationLevelList(): array function getNationLevelList(): array
{ {
$table = [ $table = [
0 => ['방랑군', 2, 0], 0 => ['방랑군', 2, 0],
1 => ['호족', 2, 1], 1 => ['호족', 2, 1],
2 => ['군벌', 4, 2], 2 => ['군벌', 4, 2],
3 => ['주자사', 4, 5], 3 => ['주자사', 4, 5],
4 => ['주목', 6, 8], 4 => ['주목', 6, 8],
5 => ['공', 6, 11], 5 => ['공', 6, 11],
6 => ['왕', 8, 16], 6 => ['왕', 8, 16],
7 => ['황제', 8, 21], 7 => ['황제', 8, 21],
]; ];
return $table; return $table;
} }
function getCityLevelList(): array function getCityLevelList(): array
{ {
return [ return [
1 => '수', 1 => '수',
2 => '진', 2 => '진',
3 => '관', 3 => '관',
4 => '이', 4 => '이',
5 => '소', 5 => '소',
6 => '중', 6 => '중',
7 => '대', 7 => '대',
8 => '특' 8 => '특'
]; ];
} }
//한국가의 전체 전방 설정 //한국가의 전체 전방 설정
function SetNationFront($nationNo) function SetNationFront($nationNo)
{ {
if (!$nationNo) { if (!$nationNo) {
return; return;
} }
// 도시소유 국가와 선포,교전중인 국가 // 도시소유 국가와 선포,교전중인 국가
$adj3 = []; $adj3 = [];
$adj2 = []; $adj2 = [];
$adj1 = []; $adj1 = [];
$db = DB::db(); $db = DB::db();
foreach ($db->queryFirstColumn( foreach ($db->queryFirstColumn(
'SELECT city FROM city JOIN diplomacy ON diplomacy.you = city.nation WHERE diplomacy.state = 0 AND me = %i', 'SELECT city FROM city JOIN diplomacy ON diplomacy.you = city.nation WHERE diplomacy.state = 0 AND me = %i',
$nationNo $nationNo
) as $city) { ) as $city) {
foreach (CityConst::byID($city)->path as $adjKey => $adjVal) { foreach (CityConst::byID($city)->path as $adjKey => $adjVal) {
$adj3[$adjKey] = $adjVal; $adj3[$adjKey] = $adjVal;
} }
}; };
foreach ($db->queryFirstColumn( foreach ($db->queryFirstColumn(
'SELECT city FROM city JOIN diplomacy ON diplomacy.you = city.nation WHERE diplomacy.state = 1 AND diplomacy.term <= 5 AND me = %i', 'SELECT city FROM city JOIN diplomacy ON diplomacy.you = city.nation WHERE diplomacy.state = 1 AND diplomacy.term <= 5 AND me = %i',
$nationNo $nationNo
) as $city) { ) as $city) {
foreach (CityConst::byID($city)->path as $adjKey => $adjVal) { foreach (CityConst::byID($city)->path as $adjKey => $adjVal) {
$adj1[$adjKey] = $adjVal; $adj1[$adjKey] = $adjVal;
} }
} }
if (!$adj3 && !$adj1) { if (!$adj3 && !$adj1) {
//평시이면 공백지 //평시이면 공백지
//NOTE: if, else일 경우 NPC는 전쟁시에는 공백지로 출병하지 않는다는 뜻이 된다. //NOTE: if, else일 경우 NPC는 전쟁시에는 공백지로 출병하지 않는다는 뜻이 된다.
foreach ($db->queryFirstColumn('SELECT city from city where nation=0') as $city) { foreach ($db->queryFirstColumn('SELECT city from city where nation=0') as $city) {
foreach (CityConst::byID($city)->path as $adjKey => $adjVal) { foreach (CityConst::byID($city)->path as $adjKey => $adjVal) {
$adj2[$adjKey] = $adjVal; $adj2[$adjKey] = $adjVal;
} }
} }
} }
$db->update('city', [ $db->update('city', [
'front' => 0 'front' => 0
], 'nation=%i', $nationNo); ], 'nation=%i', $nationNo);
if ($adj1) { if ($adj1) {
$db->update('city', [ $db->update('city', [
'front' => 1, 'front' => 1,
], 'nation=%i and city in %li', $nationNo, array_keys($adj1)); ], 'nation=%i and city in %li', $nationNo, array_keys($adj1));
} }
if ($adj2) { if ($adj2) {
$db->update('city', [ $db->update('city', [
'front' => 2, 'front' => 2,
], 'nation=%i and city in %li', $nationNo, array_keys($adj2)); ], 'nation=%i and city in %li', $nationNo, array_keys($adj2));
} }
if ($adj3) { if ($adj3) {
$db->update('city', [ $db->update('city', [
'front' => 3, 'front' => 3,
], 'nation=%i and city in %li', $nationNo, array_keys($adj3)); ], 'nation=%i and city in %li', $nationNo, array_keys($adj3));
} }
} }
function checkSupply() function checkSupply()
{ {
$db = DB::db(); $db = DB::db();
$cities = []; $cities = [];
foreach ($db->query('SELECT city, nation FROM city WHERE nation != 0') as $city) { foreach ($db->query('SELECT city, nation FROM city WHERE nation != 0') as $city) {
$newCity = new \stdClass(); $newCity = new \stdClass();
$newCity->id = Util::toInt($city['city']); $newCity->id = Util::toInt($city['city']);
$newCity->nation = Util::toInt($city['nation']); $newCity->nation = Util::toInt($city['nation']);
$newCity->supply = false; $newCity->supply = false;
$cities[$newCity->id] = $newCity; $cities[$newCity->id] = $newCity;
} }
$queue = new \SplQueue(); $queue = new \SplQueue();
foreach ($db->queryAllLists('SELECT capital, nation FROM nation WHERE `level` > 0') as list($capitalID, $nationID)) { foreach ($db->queryAllLists('SELECT capital, nation FROM nation WHERE `level` > 0') as list($capitalID, $nationID)) {
if (!key_exists($capitalID, $cities)) { if (!key_exists($capitalID, $cities)) {
continue; continue;
} }
$city = $cities[$capitalID]; $city = $cities[$capitalID];
if ($nationID != $city->nation) { if ($nationID != $city->nation) {
continue; continue;
} }
$city->supply = true; $city->supply = true;
$queue->enqueue($city); $queue->enqueue($city);
} }
while (!$queue->isEmpty()) { while (!$queue->isEmpty()) {
$cityLink = $queue->dequeue(); $cityLink = $queue->dequeue();
$city = CityConst::byID($cityLink->id); $city = CityConst::byID($cityLink->id);
foreach (array_keys($city->path) as $connCityID) { foreach (array_keys($city->path) as $connCityID) {
if (!key_exists($connCityID, $cities)) { if (!key_exists($connCityID, $cities)) {
continue; continue;
} }
$connCity = $cities[$connCityID]; $connCity = $cities[$connCityID];
if ($connCity->nation != $cityLink->nation) { if ($connCity->nation != $cityLink->nation) {
continue; continue;
} }
if ($connCity->supply) { if ($connCity->supply) {
continue; continue;
} }
$connCity->supply = true; $connCity->supply = true;
$queue->enqueue($connCity); $queue->enqueue($connCity);
} }
} }
$db->update('city', [ $db->update('city', [
'supply' => 1 'supply' => 1
], 'nation=0'); ], 'nation=0');
$db->update('city', [ $db->update('city', [
'supply' => 0 'supply' => 0
], 'nation!=0'); ], 'nation!=0');
$supply = []; $supply = [];
foreach ($cities as $city) { foreach ($cities as $city) {
if ($city->supply) { if ($city->supply) {
$supply[] = $city->id; $supply[] = $city->id;
} }
} }
if ($supply) { if ($supply) {
$db->update('city', [ $db->update('city', [
'supply' => 1 'supply' => 1
], 'city IN %li', $supply); ], 'city IN %li', $supply);
} }
} }
function updateGeneralNumber(){ function updateGeneralNumber(){
$db = DB::db(); $db = DB::db();
foreach($db->queryAllLists('SELECT nation, count(*) FROM general WHERE npc != 5 GROUP BY nation') as [$nationID, $gennum]){ foreach($db->queryAllLists('SELECT nation, count(*) FROM general WHERE npc != 5 GROUP BY nation') as [$nationID, $gennum]){
if($nationID === 0){ if($nationID === 0){
continue; continue;
} }
$db->update('nation', [ $db->update('nation', [
'gennum'=>$gennum 'gennum'=>$gennum
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
} }
refreshNationStaticInfo(); refreshNationStaticInfo();
} }
function updateYearly() function updateYearly()
{ {
//통계 //통계
checkStatistic(); checkStatistic();
} }
//관직 변경 해제 //관직 변경 해제
function updateQuaterly() function updateQuaterly()
{ {
$db = DB::db(); $db = DB::db();
//천도 제한 해제, 관직 변경 제한 해제 //천도 제한 해제, 관직 변경 제한 해제
$db->update('nation', [ $db->update('nation', [
'chief_set' => 0, 'chief_set' => 0,
], true); ], true);
//관직 변경 제한 해제 //관직 변경 제한 해제
$db->update('city', [ $db->update('city', [
'officer_set' => 0, 'officer_set' => 0,
], true); ], true);
} }
// 벌점 감소와 건국제한-1 전턴제한-1 외교제한-1, 1달마다 실행, 병사 있는 장수의 군량 감소, 수입비율 조정 // 벌점 감소와 건국제한-1 전턴제한-1 외교제한-1, 1달마다 실행, 병사 있는 장수의 군량 감소, 수입비율 조정
function preUpdateMonthly() function preUpdateMonthly()
{ {
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
//연감 월결산 //연감 월결산
$result = LogHistory(); $result = LogHistory();
if ($result == false) { if ($result == false) {
return false; return false;
} }
$admin = $gameStor->getValues(['startyear', 'year', 'month']); $admin = $gameStor->getValues(['startyear', 'year', 'month']);
$logger = new ActionLogger(0, 0, $admin['year'], $admin['month']); $logger = new ActionLogger(0, 0, $admin['year'], $admin['month']);
//보급선 체크 //보급선 체크
checkSupply(); checkSupply();
//미보급도시 10% 감소 //미보급도시 10% 감소
$db->update('city', [ $db->update('city', [
'pop' => $db->sqleval('pop * 0.9'), 'pop' => $db->sqleval('pop * 0.9'),
'trust' => $db->sqleval('trust * 0.9'), 'trust' => $db->sqleval('trust * 0.9'),
'agri' => $db->sqleval('agri * 0.9'), 'agri' => $db->sqleval('agri * 0.9'),
'comm' => $db->sqleval('comm * 0.9'), 'comm' => $db->sqleval('comm * 0.9'),
'secu' => $db->sqleval('secu * 0.9'), 'secu' => $db->sqleval('secu * 0.9'),
'def' => $db->sqleval('def * 0.9'), 'def' => $db->sqleval('def * 0.9'),
'wall' => $db->sqleval('wall * 0.9'), 'wall' => $db->sqleval('wall * 0.9'),
], 'supply = 0'); ], 'supply = 0');
//미보급도시 장수 병 훈 사 5%감소 //미보급도시 장수 병 훈 사 5%감소
//NOTE: update inner join도 가능하지만, meekrodb 기준으로 깔끔하게. //NOTE: update inner join도 가능하지만, meekrodb 기준으로 깔끔하게.
$unsuppliedCities = $db->query('SELECT city, nation, trust, name FROM city WHERE supply = 0'); $unsuppliedCities = $db->query('SELECT city, nation, trust, name FROM city WHERE supply = 0');
foreach (Util::arrayGroupBy($unsuppliedCities, 'nation') as $nationID => $cityList) { foreach (Util::arrayGroupBy($unsuppliedCities, 'nation') as $nationID => $cityList) {
$cityIDList = Util::squeezeFromArray($cityList, 'city'); $cityIDList = Util::squeezeFromArray($cityList, 'city');
$db->update('general', [ $db->update('general', [
'crew' => $db->sqleval('crew*0.95'), 'crew' => $db->sqleval('crew*0.95'),
'atmos' => $db->sqleval('atmos*0.95'), 'atmos' => $db->sqleval('atmos*0.95'),
'train' => $db->sqleval('train*0.95'), 'train' => $db->sqleval('train*0.95'),
], 'city IN %li AND nation = %i', $cityIDList, $nationID); ], 'city IN %li AND nation = %i', $cityIDList, $nationID);
} }
//민심30이하 공백지 처리 //민심30이하 공백지 처리
$lostCities = []; $lostCities = [];
foreach ($unsuppliedCities as $unsuppliedCity) { foreach ($unsuppliedCities as $unsuppliedCity) {
if ($unsuppliedCity['trust'] >= 30) { if ($unsuppliedCity['trust'] >= 30) {
continue; continue;
} }
$lostCities[$unsuppliedCity['city']] = $unsuppliedCity; $lostCities[$unsuppliedCity['city']] = $unsuppliedCity;
} }
if ($lostCities) { if ($lostCities) {
foreach ($lostCities as $lostCity) { foreach ($lostCities as $lostCity) {
$josaYi = JosaUtil::pick($lostCity['name'], '이'); $josaYi = JosaUtil::pick($lostCity['name'], '이');
$logger->pushGlobalHistoryLog("<R><b>【고립】</b></><G><b>{$lostCity['name']}</b></>{$josaYi} 보급이 끊겨 <R>미지배</> 도시가 되었습니다."); $logger->pushGlobalHistoryLog("<R><b>【고립】</b></><G><b>{$lostCity['name']}</b></>{$josaYi} 보급이 끊겨 <R>미지배</> 도시가 되었습니다.");
} }
$db->update('general', [ $db->update('general', [
'officer_level' => 1, 'officer_level' => 1,
'officer_city' => 0 'officer_city' => 0
], 'officer_city IN %li', array_keys($lostCities)); ], 'officer_city IN %li', array_keys($lostCities));
$db->update('city', [ $db->update('city', [
'nation' => 0, 'nation' => 0,
'officer_set' => 0, 'officer_set' => 0,
'conflict' => '{}', 'conflict' => '{}',
'term' => 0, 'term' => 0,
'front' => 0 'front' => 0
], 'city IN %li', array_keys($lostCities)); ], 'city IN %li', array_keys($lostCities));
} }
//접률감소, 건국제한-1 //접률감소, 건국제한-1
$db->update('general', [ $db->update('general', [
'connect' => $db->sqleval('floor(connect*0.99)'), 'connect' => $db->sqleval('floor(connect*0.99)'),
'makelimit' => $db->sqleval('greatest(0, makelimit - 1)'), 'makelimit' => $db->sqleval('greatest(0, makelimit - 1)'),
], true); ], true);
//전략제한-1, 외교제한-1, 세율동기화 //전략제한-1, 외교제한-1, 세율동기화
$db->update('nation', [ $db->update('nation', [
'strategic_cmd_limit' => $db->sqleval('greatest(0, strategic_cmd_limit - 1)'), 'strategic_cmd_limit' => $db->sqleval('greatest(0, strategic_cmd_limit - 1)'),
'surlimit' => $db->sqleval('greatest(0, surlimit - 1)'), 'surlimit' => $db->sqleval('greatest(0, surlimit - 1)'),
'rate_tmp' => $db->sqleval('rate') 'rate_tmp' => $db->sqleval('rate')
], true); ], true);
//도시훈사 180년 60, 220년 87, 240년 100 //도시훈사 180년 60, 220년 87, 240년 100
$rate = Util::round(($admin['year'] - $admin['startyear']) / 1.5) + 60; $rate = Util::round(($admin['year'] - $admin['startyear']) / 1.5) + 60;
if ($rate > 100) $rate = 100; if ($rate > 100) $rate = 100;
// 20 ~ 140원 // 20 ~ 140원
$develcost = ($admin['year'] - $admin['startyear'] + 10) * 2; $develcost = ($admin['year'] - $admin['startyear'] + 10) * 2;
$gameStor->city_rate = $rate; $gameStor->city_rate = $rate;
$gameStor->develcost = $develcost; $gameStor->develcost = $develcost;
//매달 사망자 수입 결산 //매달 사망자 수입 결산
processWarIncome(); processWarIncome();
//계략, 전쟁표시 해제 //계략, 전쟁표시 해제
$db->update('city', [ $db->update('city', [
'state' => $db->sqleval(<<<EOD 'state' => $db->sqleval(<<<EOD
(CASE (CASE
WHEN state=31 THEN 0 WHEN state=31 THEN 0
WHEN state=32 THEN 31 WHEN state=32 THEN 31
WHEN state=33 THEN 0 WHEN state=33 THEN 0
WHEN state=34 THEN 33 WHEN state=34 THEN 33
WHEN state=41 THEN 0 WHEN state=41 THEN 0
WHEN state=42 THEN 41 WHEN state=42 THEN 41
WHEN state=43 THEN 42 WHEN state=43 THEN 42
ELSE state END) ELSE state END)
EOD), EOD),
'term' => $db->sqleval('greatest(0, term - 1)'), 'term' => $db->sqleval('greatest(0, term - 1)'),
'conflict' => $db->sqleval('if(term = 0,%s,conflict)', '{}'), 'conflict' => $db->sqleval('if(term = 0,%s,conflict)', '{}'),
], true); ], true);
//첩보-1 //첩보-1
foreach ($db->queryAllLists("SELECT nation, spy FROM nation WHERE spy!='' AND spy!='{}'") as [$nationNo, $rawSpy]) { foreach ($db->queryAllLists("SELECT nation, spy FROM nation WHERE spy!='' AND spy!='{}'") as [$nationNo, $rawSpy]) {
$spyInfo = Json::decode($rawSpy); $spyInfo = Json::decode($rawSpy);
foreach ($spyInfo as $cityNo => $remainMonth) { foreach ($spyInfo as $cityNo => $remainMonth) {
if ($remainMonth <= 1) { if ($remainMonth <= 1) {
unset($spyInfo[$cityNo]); unset($spyInfo[$cityNo]);
} else { } else {
$spyInfo[$cityNo] -= 1; $spyInfo[$cityNo] -= 1;
} }
} }
$db->update('nation', [ $db->update('nation', [
'spy' => Json::encode($spyInfo, Json::EMPTY_ARRAY_IS_DICT) 'spy' => Json::encode($spyInfo, Json::EMPTY_ARRAY_IS_DICT)
], 'nation=%i', $nationNo); ], 'nation=%i', $nationNo);
} }
return true; return true;
} }
// 외교 로그처리, 외교 상태 처리 // 외교 로그처리, 외교 상태 처리
function postUpdateMonthly() function postUpdateMonthly()
{ {
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getValues(['startyear', 'year', 'month', 'scenario']); $admin = $gameStor->getValues(['startyear', 'year', 'month', 'scenario']);
$globalLogger = new ActionLogger(0, 0, $admin['year'], $admin['month']); $globalLogger = new ActionLogger(0, 0, $admin['year'], $admin['month']);
//도시 수 측정 //도시 수 측정
$cityNations = []; $cityNations = [];
foreach ($db->queryAllLists('SELECT city, name, nation FROM city') as [$cityID, $cityName, $cityNation]) { foreach ($db->queryAllLists('SELECT city, name, nation FROM city') as [$cityID, $cityName, $cityNation]) {
if (!key_exists($cityNation, $cityNations)) { if (!key_exists($cityNation, $cityNations)) {
$cityNations[$cityNation] = []; $cityNations[$cityNation] = [];
} }
$cityNations[$cityNation][] = $cityName; $cityNations[$cityNation][] = $cityName;
} }
//각 국가 전월 장수수 대비 당월 장수수로 단합도 산정 //각 국가 전월 장수수 대비 당월 장수수로 단합도 산정
//각 국가 장수수를 구하고 국력 산정 //각 국가 장수수를 구하고 국력 산정
// $query = "select nation,gennum from nation where level>0"; // $query = "select nation,gennum from nation where level>0";
// 국력= // 국력=
// 자원(국가/장수의 금,쌀) // 자원(국가/장수의 금,쌀)
// 기술력 // 기술력
// 인구수*내정% // 인구수*내정%
// 장수능력 // 장수능력
// 접속률 // 접속률
// 숙련도 // 숙련도
// 명성,공헌 // 명성,공헌
$nations = Util::convertArrayToDict($db->query('SELECT $nations = Util::convertArrayToDict($db->query('SELECT
A.nation, A.nation,
A.gennum, A.gennum,
round(( round((
round(((A.gold+A.rice)+(select sum(gold+rice) from general where nation=A.nation))/100) round(((A.gold+A.rice)+(select sum(gold+rice) from general where nation=A.nation))/100)
+A.tech +A.tech
+if(A.level=0,0,( +if(A.level=0,0,(
select round( select round(
sum(pop)*sum(pop+agri+comm+secu+wall+def)/sum(pop_max+agri_max+comm_max+secu_max+wall_max+def_max)/100 sum(pop)*sum(pop+agri+comm+secu+wall+def)/sum(pop_max+agri_max+comm_max+secu_max+wall_max+def_max)/100
) from city where nation=A.nation and supply=1 ) from city where nation=A.nation and supply=1
)) ))
+(select sum(leadership+strength+intel) from general where nation=A.nation) +(select sum(leadership+strength+intel) from general where nation=A.nation)
+(select round(sum(dex1+dex2+dex3+dex4+dex5)/1000) from general where nation=A.nation) +(select round(sum(dex1+dex2+dex3+dex4+dex5)/1000) from general where nation=A.nation)
+(select round(sum(experience+dedication)/100) from general where nation=A.nation) +(select round(sum(experience+dedication)/100) from general where nation=A.nation)
+(select round(avg(connect)) from general where nation=A.nation) +(select round(avg(connect)) from general where nation=A.nation)
)/10) )/10)
as power, as power,
(select sum(crew) from general where nation=A.nation) as totalCrew (select sum(crew) from general where nation=A.nation) as totalCrew
from nation A from nation A
group by A.nation'), 'nation'); group by A.nation'), 'nation');
$maxPowerValues = KVStorage::getValuesFromInterNamespace($db, 'nation_env', 'max_power'); $maxPowerValues = KVStorage::getValuesFromInterNamespace($db, 'nation_env', 'max_power');
foreach ($nations as $nation) { foreach ($nations as $nation) {
$nationID = $nation['nation']; $nationID = $nation['nation'];
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env'); $nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$genNum[$nationID] = $nation['gennum']; $genNum[$nationID] = $nation['gennum'];
$powerValues = $maxPowerValues[$nationID]??[]; $powerValues = $maxPowerValues[$nationID]??[];
//약간의 랜덤치 부여 (95% ~ 105%) //약간의 랜덤치 부여 (95% ~ 105%)
$nation['power'] = Util::round($nation['power'] * (rand() % 101 + 950) / 1000); $nation['power'] = Util::round($nation['power'] * (rand() % 101 + 950) / 1000);
$powerValues['maxPower'] = max($powerValues['maxPower'] ?? 0, $nation['power']); $powerValues['maxPower'] = max($powerValues['maxPower'] ?? 0, $nation['power']);
$powerValues['maxCrew'] = max($powerValues['maxCrew'] ?? 0, Util::toInt($nation['totalCrew'])); $powerValues['maxCrew'] = max($powerValues['maxCrew'] ?? 0, Util::toInt($nation['totalCrew']));
if (count($cityNations[$nationID] ?? []) > count($powerValues['maxCities'] ?? [])) { if (count($cityNations[$nationID] ?? []) > count($powerValues['maxCities'] ?? [])) {
$powerValues['maxCities'] = $cityNations[$nationID]; $powerValues['maxCities'] = $cityNations[$nationID];
} }
$db->update('nation', [ $db->update('nation', [
'power' => $nation['power'] 'power' => $nation['power']
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
$nationStor->max_power = $powerValues; $nationStor->max_power = $powerValues;
} }
// 전쟁기한 세팅 // 전쟁기한 세팅
foreach($db->query('SELECT me, you, dead, term FROM diplomacy WHERE state = 0') as $dip) { foreach($db->query('SELECT me, you, dead, term FROM diplomacy WHERE state = 0') as $dip) {
$genCount = $genNum[$dip['me']]; $genCount = $genNum[$dip['me']];
// 25% 참여율일때 두당 10턴에 4000명 소모한다고 계산 // 25% 참여율일때 두당 10턴에 4000명 소모한다고 계산
// 4000 / 10 * 0.25 = 100 // 4000 / 10 * 0.25 = 100
$term = floor($dip['dead'] / 100 / $genCount); $term = floor($dip['dead'] / 100 / $genCount);
$dip['dead'] -= $term * 100 * $genCount; $dip['dead'] -= $term * 100 * $genCount;
$term = Util::valueFit($dip['term'] + $term, 0, 13); $term = Util::valueFit($dip['term'] + $term, 0, 13);
$db->update('diplomacy', [ $db->update('diplomacy', [
'term' => $term, 'term' => $term,
'dead' => $dip['dead'], 'dead' => $dip['dead'],
], 'me = %i AND you = %i', $dip['me'], $dip['you']); ], 'me = %i AND you = %i', $dip['me'], $dip['you']);
} }
//개전국 로그 //개전국 로그
foreach($db->query('SELECT me, you FROM diplomacy WHERE state = 1 AND term <= 1 AND me < you') as $dip){ foreach($db->query('SELECT me, you FROM diplomacy WHERE state = 1 AND term <= 1 AND me < you') as $dip){
$nation1 = getNationStaticInfo($dip['me']); $nation1 = getNationStaticInfo($dip['me']);
$name1 = $nation1['name']; $name1 = $nation1['name'];
$nation2 = getNationStaticInfo($dip['you']); $nation2 = getNationStaticInfo($dip['you']);
$name2 = $nation2['name']; $name2 = $nation2['name'];
$josaYi = JosaUtil::pick($name2, '이'); $josaYi = JosaUtil::pick($name2, '이');
$josaWa = JosaUtil::pick($name1, '와'); $josaWa = JosaUtil::pick($name1, '와');
$globalLogger->pushGlobalHistoryLog("<R><b>【개전】</b></><D><b>$name1</b></>{$josaWa} <D><b>$name2</b></>{$josaYi} <R>전쟁</>을 시작합니다."); $globalLogger->pushGlobalHistoryLog("<R><b>【개전】</b></><D><b>$name1</b></>{$josaWa} <D><b>$name2</b></>{$josaYi} <R>전쟁</>을 시작합니다.");
} }
//휴전국 로그 //휴전국 로그
$stopWarList = []; $stopWarList = [];
foreach($db->queryAllLists('SELECT me,you FROM diplomacy WHERE state=0 AND term <= 1 ORDER BY me desc, you desc') as [$me, $you]){ foreach($db->queryAllLists('SELECT me,you FROM diplomacy WHERE state=0 AND term <= 1 ORDER BY me desc, you desc') as [$me, $you]){
if($me < $you){ if($me < $you){
$key = "{$me}_{$you}"; $key = "{$me}_{$you}";
} }
else{ else{
$key = "{$you}_{$me}"; $key = "{$you}_{$me}";
} }
if(!key_exists($key, $stopWarList)){ if(!key_exists($key, $stopWarList)){
$stopWarList[$key] = true; $stopWarList[$key] = true;
continue; continue;
} }
//양측 기간 모두 0이 되는 상황이면 휴전 //양측 기간 모두 0이 되는 상황이면 휴전
$nation1 = getNationStaticInfo($me); $nation1 = getNationStaticInfo($me);
$name1 = $nation1['name']; $name1 = $nation1['name'];
$nation2 = getNationStaticInfo($you); $nation2 = getNationStaticInfo($you);
$name2 = $nation2['name']; $name2 = $nation2['name'];
$josaWa = JosaUtil::pick($name1, '와'); $josaWa = JosaUtil::pick($name1, '와');
$josaYi = JosaUtil::pick($name2, '이'); $josaYi = JosaUtil::pick($name2, '이');
$globalLogger->pushGlobalHistoryLog("<R><b>【휴전】</b></><D><b>$name1</b></>{$josaWa} <D><b>$name2</b></>{$josaYi} <S>휴전</>합니다."); $globalLogger->pushGlobalHistoryLog("<R><b>【휴전】</b></><D><b>$name1</b></>{$josaWa} <D><b>$name2</b></>{$josaYi} <S>휴전</>합니다.");
$db->update('diplomacy', [ $db->update('diplomacy', [
'state'=>2, 'state'=>2,
'term'=>0, 'term'=>0,
], '(me=%i AND you=%i) OR (you=%i AND me=%i)', $me, $you, $me, $you); ], '(me=%i AND you=%i) OR (you=%i AND me=%i)', $me, $you, $me, $you);
} }
$globalLogger->flush(); $globalLogger->flush();
//사상자 초기화, 외교 기한-1 //사상자 초기화, 외교 기한-1
$db->update('diplomacy', [ $db->update('diplomacy', [
'dead'=>$db->sqleval('if(state!=0, 0, dead)'), 'dead'=>$db->sqleval('if(state!=0, 0, dead)'),
'term'=>$db->sqleval('greatest(0, term-1)'), 'term'=>$db->sqleval('greatest(0, term-1)'),
], true); ], true);
//불가침 끝나면 통상으로 //불가침 끝나면 통상으로
$db->update('diplomacy', [ $db->update('diplomacy', [
'state'=>2, 'state'=>2,
], 'state = 7 AND term = 0'); ], 'state = 7 AND term = 0');
//선포 끝나면 교전으로 //선포 끝나면 교전으로
$db->update('diplomacy', [ $db->update('diplomacy', [
'state'=>0, 'state'=>0,
'term'=>6, 'term'=>6,
], 'state = 1 AND term = 0'); ], 'state = 1 AND term = 0');
//초반이후 방랑군 자동 해체 //초반이후 방랑군 자동 해체
if ($admin['year'] >= $admin['startyear'] + 2) { if ($admin['year'] >= $admin['startyear'] + 2) {
checkWander(); checkWander();
} }
// 작위 업데이트 // 작위 업데이트
updateNationState(); updateNationState();
updateGeneralNumber(); updateGeneralNumber();
refreshNationStaticInfo(); refreshNationStaticInfo();
// 천통여부 검사 // 천통여부 검사
checkEmperior(); checkEmperior();
//토너먼트 개시 //토너먼트 개시
triggerTournament(); triggerTournament();
// 시스템 거래건 등록 // 시스템 거래건 등록
registerAuction(); registerAuction();
//전방설정 //전방설정
foreach (getAllNationStaticInfo() as $nation) { foreach (getAllNationStaticInfo() as $nation) {
if ($nation['level'] <= 0) { if ($nation['level'] <= 0) {
continue; continue;
} }
SetNationFront($nation['nation']); SetNationFront($nation['nation']);
} }
} }
function checkWander() function checkWander()
{ {
$db = DB::db(); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getValues(['year', 'month']); $admin = $gameStor->getValues(['year', 'month']);
$wanderers = $db->queryFirstColumn('SELECT general.`no` FROM general LEFT JOIN nation ON general.nation = nation.nation WHERE nation.`level` = 0 AND general.`officer_level` = 12'); $wanderers = $db->queryFirstColumn('SELECT general.`no` FROM general LEFT JOIN nation ON general.nation = nation.nation WHERE nation.`level` = 0 AND general.`officer_level` = 12');
foreach (General::createGeneralObjListFromDB($wanderers) as $wanderer) { foreach (General::createGeneralObjListFromDB($wanderers) as $wanderer) {
$wanderCmd = buildGeneralCommandClass('che_해산', $wanderer, $admin); $wanderCmd = buildGeneralCommandClass('che_해산', $wanderer, $admin);
if ($wanderCmd->hasFullConditionMet()) { if ($wanderCmd->hasFullConditionMet()) {
$logger = $wanderer->getLogger(); $logger = $wanderer->getLogger();
$logger->pushGeneralActionLog('초반 제한후 방랑군은 자동 해산됩니다.', ActionLogger::PLAIN); $logger->pushGeneralActionLog('초반 제한후 방랑군은 자동 해산됩니다.', ActionLogger::PLAIN);
$wanderCmd->run(); $wanderCmd->run();
} $wanderCmd->setNextAvailable();
} }
}
if ($wanderers) {
refreshNationStaticInfo(); if ($wanderers) {
} refreshNationStaticInfo();
} }
}
function updateNationState()
{ function updateNationState()
$db = DB::db(); {
$gameStor = KVStorage::getStorage($db, 'game_env'); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$history = array();
$admin = $gameStor->getValues(['killturn', 'year', 'month', 'fiction', 'startyear', 'show_img_level', 'turnterm', 'turntime']); $history = array();
$admin = $gameStor->getValues(['killturn', 'year', 'month', 'fiction', 'startyear', 'show_img_level', 'turnterm', 'turntime']);
$assemblerCnts = [];
foreach ($db->queryAllLists('SELECT nation,count(no) FROM general WHERE npc = 5 GROUP BY nation') as [$nationID, $assemblerCnt]) { $assemblerCnts = [];
$assemblerCnts[$nationID] = $assemblerCnt; foreach ($db->queryAllLists('SELECT nation,count(no) FROM general WHERE npc = 5 GROUP BY nation') as [$nationID, $assemblerCnt]) {
}; $assemblerCnts[$nationID] = $assemblerCnt;
};
foreach ($db->query('SELECT nation,name,level,tech,aux FROM nation') as $nation) {
//TODO: level이 진관수이소중대특 체계를 벗어날 수 있음 foreach ($db->query('SELECT nation,name,level,tech,aux FROM nation') as $nation) {
$citycount = $db->queryFirstField('SELECT count(*) FROM city WHERE nation=%i AND level>=4', $nation['nation']); //TODO: level이 진관수이소중대특 체계를 벗어날 수 있음
$citycount = $db->queryFirstField('SELECT count(*) FROM city WHERE nation=%i AND level>=4', $nation['nation']);
if ($citycount == 0) {
$nationlevel = 0; // 방랑군 if ($citycount == 0) {
} elseif ($citycount == 1) { $nationlevel = 0; // 방랑군
$nationlevel = 1; // 호족 } elseif ($citycount == 1) {
} elseif ($citycount <= 4) { $nationlevel = 1; // 호족
$nationlevel = 2; // 군벌 } elseif ($citycount <= 4) {
} elseif ($citycount <= 7) { $nationlevel = 2; // 군벌
$nationlevel = 3; // 주자사 } elseif ($citycount <= 7) {
} elseif ($citycount <= 10) { $nationlevel = 3; // 주자사
$nationlevel = 4; // 주목 } elseif ($citycount <= 10) {
} elseif ($citycount <= 15) { $nationlevel = 4; // 주목
$nationlevel = 5; // 공 } elseif ($citycount <= 15) {
} elseif ($citycount <= 20) { $nationlevel = 5; // 공
$nationlevel = 6; // 왕 } elseif ($citycount <= 20) {
} else { $nationlevel = 6; // 왕
$nationlevel = 7; // 황제 } else {
} $nationlevel = 7; // 황제
}
if ($nationlevel > $nation['level']) {
$levelDiff = $nationlevel - $nation['level']; if ($nationlevel > $nation['level']) {
$oldLevel = $nation['level']; $levelDiff = $nationlevel - $nation['level'];
$nation['level'] = $nationlevel; $oldLevel = $nation['level'];
$nation['level'] = $nationlevel;
$updateVals = [
'level' => $nationlevel, $updateVals = [
'gold'=>$db->sqleval('gold + %i', $nationlevel*1000), 'level' => $nationlevel,
'rice'=>$db->sqleval('rice + %i', $nationlevel*1000), 'gold'=>$db->sqleval('gold + %i', $nationlevel*1000),
]; 'rice'=>$db->sqleval('rice + %i', $nationlevel*1000),
];
switch ($nationlevel) {
case 7: switch ($nationlevel) {
$josaUl = JosaUtil::pick(getNationLevel($nationlevel), '을'); case 7:
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>{$josaUl} 자칭하였습니다."; $josaUl = JosaUtil::pick(getNationLevel($nationlevel), '을');
pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>{$josaUl} 자칭"]); $history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>{$josaUl} 자칭하였습니다.";
$auxVal = Json::decode($nation['aux']); pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>{$josaUl} 자칭"]);
$auxVal['can_국기변경'] = 1; $auxVal = Json::decode($nation['aux']);
$auxVal['can_국변경'] = 1; $auxVal['can_국변경'] = 1;
$updateVals['aux'] = Json::encode($auxVal); $auxVal['can_국호변경'] = 1;
break; $updateVals['aux'] = Json::encode($auxVal);
case 6: break;
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 등극하였습니다."; case 6:
pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 등극"]); $history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 등극하였습니다.";
break; pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 등극"]);
case 5: break;
case 4: case 5:
case 3: case 4:
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 임명되었습니다."; case 3:
pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 임명"]); $history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 임명되었습니다.";
break; pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 임명됨"]);
case 2: break;
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 독립하여 <Y>" . getNationLevel($nationlevel) . "</>로 나섰습니다."; case 2:
pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>로 나서다"]); $history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 독립하여 <Y>" . getNationLevel($nationlevel) . "</>로 나섰습니다.";
break; pushNationHistoryLog($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>로 나서다"]);
} break;
}
$db->update('nation', $updateVals, 'nation=%i', $nation['nation']);
$db->update('nation', $updateVals, 'nation=%i', $nation['nation']);
$turnRows = [];
foreach (Util::range(getNationChiefLevel($nation['level']), 12) as $chiefLevel) { $turnRows = [];
foreach (Util::range(GameConst::$maxChiefTurn) as $turnIdx) { foreach (Util::range(getNationChiefLevel($nation['level']), 12) as $chiefLevel) {
$turnRows[] = [ foreach (Util::range(GameConst::$maxChiefTurn) as $turnIdx) {
'nation_id' => $nation['nation'], $turnRows[] = [
'officer_level' => $chiefLevel, 'nation_id' => $nation['nation'],
'turn_idx' => $turnIdx, 'officer_level' => $chiefLevel,
'action' => '휴식', 'turn_idx' => $turnIdx,
'arg' => null, 'action' => '휴식',
'brief' => '휴식' 'arg' => null,
]; 'brief' => '휴식'
} ];
} }
$db->insertIgnore('nation_turn', $turnRows); }
$db->insertIgnore('nation_turn', $turnRows);
if ($levelDiff) {
//유니크 아이템 하나 돌리자 if ($levelDiff) {
$targetKillTurn = $admin['killturn']; //유니크 아이템 하나 돌리자
$targetKillTurn -= 24 * 60 / $admin['turnterm']; $targetKillTurn = $admin['killturn'];
$nationGenIDList = $db->queryFirstColumn( $targetKillTurn -= 24 * 60 / $admin['turnterm'];
'SELECT no FROM general WHERE nation = %i AND killturn >= %i AND npc < 2', $nationGenIDList = $db->queryFirstColumn(
$nation['nation'], 'SELECT no FROM general WHERE nation = %i AND killturn >= %i AND npc < 2',
$targetKillTurn $nation['nation'],
); $targetKillTurn
$nationGenList = General::createGeneralObjListFromDB($nationGenIDList, ['belong'], 2); );
$nationGenList = General::createGeneralObjListFromDB($nationGenIDList, ['belong'], 2);
$uniqueLotteryWeightList = [];
foreach ($nationGenList as $nationGen) { $uniqueLotteryWeightList = [];
$hasUnique = false; foreach ($nationGenList as $nationGen) {
foreach ($nationGen->getItems() as $item) { $hasUnique = false;
if (!$item->isBuyable()) { foreach ($nationGen->getItems() as $item) {
$hasUnique = true; if (!$item->isBuyable()) {
break; $hasUnique = true;
} break;
} }
if ($hasUnique) { }
continue; if ($hasUnique) {
} continue;
}
$score = $nationGen->getVar('belong') + 5;
$score = $nationGen->getVar('belong') + 5;
if ($nationGen->getVar('officer_level') == 12) {
$score += 200; //NOTE: 꼬우면 군주하세요. if ($nationGen->getVar('officer_level') == 12) {
} else if ($nationGen->getVar('officer_level') == 11) { $score += 200; //NOTE: 꼬우면 군주하세요.
$score += 70; } else if ($nationGen->getVar('officer_level') == 11) {
} else if ($nationGen->getVar('officer_level') > 4) { $score += 70;
$score += 35; } else if ($nationGen->getVar('officer_level') > 4) {
} $score += 35;
$uniqueLotteryWeightList[$nationGen->getID()] = [$nationGen, $score]; }
} $uniqueLotteryWeightList[$nationGen->getID()] = [$nationGen, $score];
}
foreach (Util::range($levelDiff) as $idx) {
if (!$uniqueLotteryWeightList) { foreach (Util::range($levelDiff) as $idx) {
break; if (!$uniqueLotteryWeightList) {
} break;
}
/** @var General */
$winnerObj = Util::choiceRandomUsingWeightPair($uniqueLotteryWeightList); /** @var General */
unset($uniqueLotteryWeightList[$winnerObj->getID()]); $winnerObj = Util::choiceRandomUsingWeightPair($uniqueLotteryWeightList);
giveRandomUniqueItem($winnerObj, '작위보상'); unset($uniqueLotteryWeightList[$winnerObj->getID()]);
$winnerObj->applyDB($db); giveRandomUniqueItem($winnerObj, '작위보상');
} $winnerObj->applyDB($db);
} }
} }
}
$assemblerCnt = $assemblerCnts[$nation['nation']] ?? 0;
$maxAssemblerCnt = [ $assemblerCnt = $assemblerCnts[$nation['nation']] ?? 0;
1 => 0, $maxAssemblerCnt = [
2 => 1, 1 => 0,
3 => 3, 2 => 1,
4 => 4, 3 => 3,
5 => 6, 4 => 4,
6 => 7, 5 => 6,
7 => 9 6 => 7,
][$nationlevel] ?? 0; 7 => 9
][$nationlevel] ?? 0;
if ($assemblerCnt < $maxAssemblerCnt) {
$lastAssemblerID = $gameStor->assembler_id ?? 0; if ($assemblerCnt < $maxAssemblerCnt) {
$lastAssemblerID = $gameStor->assembler_id ?? 0;
while ($assemblerCnt < $maxAssemblerCnt) {
$lastAssemblerID += 1; while ($assemblerCnt < $maxAssemblerCnt) {
$npcObj = new Scenario\NPC( $lastAssemblerID += 1;
999, $npcObj = new Scenario\NPC(
sprintf('부대장%4d', $lastAssemblerID), 999,
null, sprintf('부대장%4d', $lastAssemblerID),
$nation['nation'], null,
null, $nation['nation'],
10, null,
10, 10,
10, 10,
1, 10,
$admin['year'] - 15, 1,
$admin['year'] + 15, $admin['year'] - 15,
'은둔', $admin['year'] + 15,
'척사' '은둔',
); '척사'
$npcObj->killturn = 70; );
$npcObj->gold = 0; $npcObj->killturn = 70;
$npcObj->rice = 0; $npcObj->gold = 0;
$npcObj->npc = 5; $npcObj->rice = 0;
$npcObj->build($admin); $npcObj->npc = 5;
$npcID = $npcObj->generalID; $npcObj->build($admin);
$npcID = $npcObj->generalID;
$db->insert('troop', [
'troop_leader' => $npcID, $db->insert('troop', [
'name' => $npcObj->realName, 'troop_leader' => $npcID,
'nation' => $nation['nation'], 'name' => $npcObj->realName,
]); 'nation' => $nation['nation'],
$db->update('general', [ ]);
'troop' => $npcID $db->update('general', [
], 'no=%i', $npcID); 'troop' => $npcID
], 'no=%i', $npcID);
$cmd = buildGeneralCommandClass('che_집합', General::createGeneralObjFromDB($npcID), $admin);
_setGeneralCommand($cmd, iterator_to_array(Util::range(GameConst::$maxTurn))); $cmd = buildGeneralCommandClass('che_집합', General::createGeneralObjFromDB($npcID), $admin);
$assemblerCnt += 1; _setGeneralCommand($cmd, iterator_to_array(Util::range(GameConst::$maxTurn)));
$gameStor->assembler_id = $lastAssemblerID; $assemblerCnt += 1;
} $gameStor->assembler_id = $lastAssemblerID;
} }
} }
pushGlobalHistoryLog($history, $admin['year'], $admin['month']); }
} pushGlobalHistoryLog($history, $admin['year'], $admin['month']);
}
function checkStatistic()
{ function checkStatistic()
$db = DB::db(); {
$gameStor = KVStorage::getStorage($db, 'game_env'); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getValues(['year', 'month']);
$admin = $gameStor->getValues(['year', 'month']);
$nationHists = [];
$specialHists = []; $nationHists = [];
$personalHists = []; $specialHists = [];
$specialHists2 = []; $personalHists = [];
$crewtypeHists = []; $specialHists2 = [];
$crewtypeHists = [];
$etc = '';
$etc = '';
$auxData = [
'generals' => [], $auxData = [
'nations' => [], 'generals' => [],
]; 'nations' => [],
];
$avgGeneral = $db->queryFirstRow(
'SELECT avg(gold) as avggold, avg(rice) as avgrice, avg(dex1+dex2+dex3+dex4) as avgdex, $avgGeneral = $db->queryFirstRow(
max(dex1+dex2+dex3+dex4) as maxdex, avg(experience+dedication) as avgexpded, max(experience+dedication) as maxexpded 'SELECT avg(gold) as avggold, avg(rice) as avgrice, avg(dex1+dex2+dex3+dex4) as avgdex,
FROM general' max(dex1+dex2+dex3+dex4) as maxdex, avg(experience+dedication) as avgexpded, max(experience+dedication) as maxexpded
); FROM general'
$auxData['generals']['avg'] = $avgGeneral; );
$auxData['generals']['avg'] = $avgGeneral;
$avgGeneral['avggold'] = Util::round($avgGeneral['avggold']);
$avgGeneral['avgrice'] = Util::round($avgGeneral['avgrice']); $avgGeneral['avggold'] = Util::round($avgGeneral['avggold']);
$avgGeneral['avgdex'] = Util::round($avgGeneral['avgdex']); $avgGeneral['avgrice'] = Util::round($avgGeneral['avgrice']);
$avgGeneral['avgexpded'] = Util::round($avgGeneral['avgexpded']); $avgGeneral['avgdex'] = Util::round($avgGeneral['avgdex']);
$etc .= "평균 금/쌀 ({$avgGeneral['avggold']}/{$avgGeneral['avgrice']}), 평균/최고 숙련({$avgGeneral['avgdex']}/{$avgGeneral['maxdex']}), 평균/최고 경험공헌({$avgGeneral['avgexpded']}/{$avgGeneral['maxexpded']}), "; $avgGeneral['avgexpded'] = Util::round($avgGeneral['avgexpded']);
$etc .= "평균 금/쌀 ({$avgGeneral['avggold']}/{$avgGeneral['avgrice']}), 평균/최고 숙련({$avgGeneral['avgdex']}/{$avgGeneral['maxdex']}), 평균/최고 경험공헌({$avgGeneral['avgexpded']}/{$avgGeneral['maxexpded']}), ";
$avgNation = $db->queryFirstRow(
'SELECT min(tech) as mintech, max(tech) as maxtech, avg(tech) as avgtech, $avgNation = $db->queryFirstRow(
min(power) as minpower, max(power) as maxpower, avg(power) as avgpower from nation where level>0' 'SELECT min(tech) as mintech, max(tech) as maxtech, avg(tech) as avgtech,
); min(power) as minpower, max(power) as maxpower, avg(power) as avgpower from nation where level>0'
$auxData['nations']['avg'] = $avgNation; );
$auxData['nations']['avg'] = $avgNation;
$avgNation['mintech'] = floor($avgNation['mintech']);
$avgNation['maxtech'] = floor($avgNation['maxtech']); $avgNation['mintech'] = floor($avgNation['mintech']);
$avgNation['avgtech'] = Util::round($avgNation['avgtech']); $avgNation['maxtech'] = floor($avgNation['maxtech']);
$avgNation['avgpower'] = Util::round($avgNation['avgpower']); $avgNation['avgtech'] = Util::round($avgNation['avgtech']);
$etc .= "최저/평균/최고 기술({$avgNation['mintech']}/{$avgNation['avgtech']}/{$avgNation['maxtech']}), "; $avgNation['avgpower'] = Util::round($avgNation['avgpower']);
$etc .= "최저/평균/최고 국력({$avgNation['minpower']}/{$avgNation['avgpower']}/{$avgNation['maxpower']}), "; $etc .= "최저/평균/최고 기술({$avgNation['mintech']}/{$avgNation['avgtech']}/{$avgNation['maxtech']}), ";
$etc .= "최저/평균/최고 국력({$avgNation['minpower']}/{$avgNation['avgpower']}/{$avgNation['maxpower']}), ";
$nationName = '';
$powerHist = ''; $nationName = '';
$powerHist = '';
$nations = Util::convertArrayToDict(
$db->query( $nations = Util::convertArrayToDict(
'SELECT nation,name,type,power,gennum,gold+rice as goldrice from nation where level>0 order by power desc', $db->query(
'nation' 'SELECT nation,name,type,power,gennum,gold+rice as goldrice from nation where level>0 order by power desc',
), 'nation'
'nation' ),
); 'nation'
$nationCount = count($nations); );
$nationCount = count($nations);
$nationGeneralInfos = Util::convertArrayToDict(
$db->query( $nationGeneralInfos = Util::convertArrayToDict(
'SELECT nation, sum(leadership+strength+intel) as abil,sum(gold+rice) as goldrice, $db->query(
sum(dex1+dex2+dex3+dex4) as dex,sum(experience+dedication) as expded 'SELECT nation, sum(leadership+strength+intel) as abil,sum(gold+rice) as goldrice,
from general GROUP BY nation' sum(dex1+dex2+dex3+dex4) as dex,sum(experience+dedication) as expded
), from general GROUP BY nation'
'nation' ),
); 'nation'
);
$nationCityInfos = Util::convertArrayToDict(
$db->query('SELECT nation, count(*) as cnt, sum(pop) as pop,sum(pop_max) as pop_max from city GROUP BY nation'), $nationCityInfos = Util::convertArrayToDict(
'nation' $db->query('SELECT nation, count(*) as cnt, sum(pop) as pop,sum(pop_max) as pop_max from city GROUP BY nation'),
); 'nation'
);
foreach ($nations as $nationNo => &$nation) {
$general = $nationGeneralInfos[$nationNo]; foreach ($nations as $nationNo => &$nation) {
$city = $nationCityInfos[$nationNo]; $general = $nationGeneralInfos[$nationNo];
$city = $nationCityInfos[$nationNo];
$nation['generalInfo'] = $general;
$nation['cityInfo'] = $city; $nation['generalInfo'] = $general;
$nation['cityInfo'] = $city;
$nationName .= $nation['name'] . '(' . getNationType($nation['type']) . '), ';
$powerHist .= "{$nation['name']}({$nation['power']}/{$nation['gennum']}/{$city['cnt']}/{$city['pop']}/{$city['pop_max']}/{$nation['goldrice']}/{$general['goldrice']}/{$general['abil']}/{$general['dex']}/{$general['expded']}), "; $nationName .= $nation['name'] . '(' . getNationType($nation['type']) . '), ';
$powerHist .= "{$nation['name']}({$nation['power']}/{$nation['gennum']}/{$city['cnt']}/{$city['pop']}/{$city['pop_max']}/{$nation['goldrice']}/{$general['goldrice']}/{$general['abil']}/{$general['dex']}/{$general['expded']}), ";
if (!isset($nationHists[$nation['type']])) {
$nationHists[$nation['type']] = 0; if (!isset($nationHists[$nation['type']])) {
} $nationHists[$nation['type']] = 0;
$nationHists[$nation['type']]++; }
} $nationHists[$nation['type']]++;
unset($nation); }
unset($nation);
$auxData['nations']['all'] = $nations;
$auxData['nations']['all'] = $nations;
$nationHist = '';
foreach (GameConst::$availableNationType as $nationType) { $nationHist = '';
if (!Util::array_get($nationHists[$nationType])) { foreach (GameConst::$availableNationType as $nationType) {
$nationHists[$nationType] = '-'; if (!Util::array_get($nationHists[$nationType])) {
} $nationHists[$nationType] = '-';
$nationHist .= getNationType($nationType) . "({$nationHists[$nationType]}), "; }
} $nationHist .= getNationType($nationType) . "({$nationHists[$nationType]}), ";
}
$generals = $db->query('SELECT `no`,npc,personal,special,special2,crewtype FROM general');
$generals = $db->query('SELECT `no`,npc,personal,special,special2,crewtype FROM general');
$genCount = 0;
$npcCount = 0; $genCount = 0;
$generalCount = count($generals); $npcCount = 0;
$generalCount = count($generals);
foreach ($generals as $general) {
if (!isset($personalHists[$general['personal']])) { foreach ($generals as $general) {
$personalHists[$general['personal']] = 0; if (!isset($personalHists[$general['personal']])) {
} $personalHists[$general['personal']] = 0;
}
if (!isset($specialHists[$general['special']])) {
$specialHists[$general['special']] = 0; if (!isset($specialHists[$general['special']])) {
} $specialHists[$general['special']] = 0;
}
if (!isset($specialHists2[$general['special2']])) {
$specialHists2[$general['special2']] = 0; if (!isset($specialHists2[$general['special2']])) {
} $specialHists2[$general['special2']] = 0;
}
if ($general['npc'] < 2) {
$genCount += 1; if ($general['npc'] < 2) {
} else { $genCount += 1;
$npcCount += 1; } else {
} $npcCount += 1;
}
$personalHists[$general['personal']]++;
$specialHists[$general['special']]++; $personalHists[$general['personal']]++;
$specialHists2[$general['special2']]++; $specialHists[$general['special']]++;
} $specialHists2[$general['special2']]++;
}
foreach ($db->queryAllLists(
'SELECT crewtype, count(crewtype) AS cnt FROM general WHERE recent_war != NULL GROUP BY crewtype' foreach ($db->queryAllLists(
) as [$crewtype, $cnt]) { 'SELECT crewtype, count(crewtype) AS cnt FROM general WHERE recent_war != NULL GROUP BY crewtype'
$crewtypeHists[$crewtype] = $cnt; ) as [$crewtype, $cnt]) {
} $crewtypeHists[$crewtype] = $cnt;
}
$auxData['generals']['hists'] = [
'personal' => $personalHists, $auxData['generals']['hists'] = [
'special' => $specialHists, 'personal' => $personalHists,
'special2' => $specialHists2, 'special' => $specialHists,
'crewtype' => $crewtypeHists, 'special2' => $specialHists2,
'userCnt' => $genCount, 'crewtype' => $crewtypeHists,
'npcCnt' => $npcCount, 'userCnt' => $genCount,
]; 'npcCnt' => $npcCount,
];
$generalCountStr = "{$generalCount}({$genCount}+{$npcCount})";
$generalCountStr = "{$generalCount}({$genCount}+{$npcCount})";
$personalHistStr = join(', ', array_map(function ($histPair) {
[$histKey, $cnt] = $histPair; $personalHistStr = join(', ', array_map(function ($histPair) {
return getGenChar($histKey) . '(' . $cnt . ')'; [$histKey, $cnt] = $histPair;
}, Util::convertDictToArray($personalHists))); return getGenChar($histKey) . '(' . $cnt . ')';
}, Util::convertDictToArray($personalHists)));
$specialHistsStr = join(', ', array_map(function ($histPair) {
[$histKey, $cnt] = $histPair; $specialHistsStr = join(', ', array_map(function ($histPair) {
return getGeneralSpecialDomesticName($histKey) . '(' . $cnt . ')'; [$histKey, $cnt] = $histPair;
}, Util::convertDictToArray($specialHists))); return getGeneralSpecialDomesticName($histKey) . '(' . $cnt . ')';
}, Util::convertDictToArray($specialHists)));
$specialHists2Str = join(', ', array_map(function ($histPair) {
[$histKey, $cnt] = $histPair; $specialHists2Str = join(', ', array_map(function ($histPair) {
return getGeneralSpecialWarName($histKey) . '(' . $cnt . ')'; [$histKey, $cnt] = $histPair;
}, Util::convertDictToArray($specialHists2))); return getGeneralSpecialWarName($histKey) . '(' . $cnt . ')';
}, Util::convertDictToArray($specialHists2)));
$specialHistsAllStr = "$specialHistsStr // $specialHists2Str";
$specialHistsAllStr = "$specialHistsStr // $specialHists2Str";
$crewtypeHistsStr = join(', ', array_map(function ($histPair) {
[$histKey, $cnt] = $histPair; $crewtypeHistsStr = join(', ', array_map(function ($histPair) {
return GameUnitConst::byID($histKey)->getShortName() . '(' . $cnt . ')'; [$histKey, $cnt] = $histPair;
}, Util::convertDictToArray($crewtypeHists))); return GameUnitConst::byID($histKey)->getShortName() . '(' . $cnt . ')';
}, Util::convertDictToArray($crewtypeHists)));
$db->insert('statistic', [
'year' => $admin['year'], $db->insert('statistic', [
'month' => $admin['month'], 'year' => $admin['year'],
'nation_count' => $nationCount, 'month' => $admin['month'],
'nation_name' => $nationName, 'nation_count' => $nationCount,
'nation_hist' => $nationHist, 'nation_name' => $nationName,
'gen_count' => $generalCountStr, 'nation_hist' => $nationHist,
'personal_hist' => $personalHistStr, 'gen_count' => $generalCountStr,
'special_hist' => $specialHistsAllStr, 'personal_hist' => $personalHistStr,
'power_hist' => $powerHist, 'special_hist' => $specialHistsAllStr,
'crewtype' => $crewtypeHistsStr, 'power_hist' => $powerHist,
'etc' => $etc, 'crewtype' => $crewtypeHistsStr,
'aux' => Json::encode($auxData) 'etc' => $etc,
]); 'aux' => Json::encode($auxData)
} ]);
}
function convForOldGeneral(array $general, int $year, int $month)
{ function convForOldGeneral(array $general, int $year, int $month)
$general['history'] = getGeneralHistoryLogAll($general['no']); {
return [ $general['history'] = getGeneralHistoryLogAll($general['no']);
'server_id' => UniqueConst::$serverID, return [
'general_no' => $general['no'], 'server_id' => UniqueConst::$serverID,
'owner' => $general['owner'], 'general_no' => $general['no'],
'name' => $general['name'], 'owner' => $general['owner'],
'last_yearmonth' => $year * 100 + $month, 'name' => $general['name'],
'turntime' => $general['turntime'], 'last_yearmonth' => $year * 100 + $month,
'data' => Json::encode($general) 'turntime' => $general['turntime'],
]; 'data' => Json::encode($general)
} ];
}
function storeOldGeneral(int $no, int $year, int $month)
{ function storeOldGeneral(int $no, int $year, int $month)
$db = DB::db(); {
$general = $db->queryFirstRow('SELECT * FROM general WHERE `no` = %i', $no); $db = DB::db();
if (!$general) { $general = $db->queryFirstRow('SELECT * FROM general WHERE `no` = %i', $no);
return; if (!$general) {
} return;
$data = convForOldGeneral($general, $year, $month); }
$db->insertUpdate( $data = convForOldGeneral($general, $year, $month);
'ng_old_generals', $db->insertUpdate(
$data, 'ng_old_generals',
$data $data,
); $data
} );
}
function storeOldGenerals(int $nation, int $year, int $month)
{ function storeOldGenerals(int $nation, int $year, int $month)
$db = DB::db(); {
foreach ($db->query('SELECT * FROM general WHERE nation = %i', $nation) as $general) { $db = DB::db();
$data = convForOldGeneral($general, $year, $month); foreach ($db->query('SELECT * FROM general WHERE nation = %i', $nation) as $general) {
$db->insertUpdate( $data = convForOldGeneral($general, $year, $month);
'ng_old_generals', $db->insertUpdate(
$data, 'ng_old_generals',
$data $data,
); $data
} );
} }
}
function checkEmperior()
{ function checkEmperior()
$db = DB::db(); {
$gameStor = KVStorage::getStorage($db, 'game_env'); $db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getValues(['year', 'month', 'isunited', 'conlimit']);
if ($admin['isunited'] != 0) { $admin = $gameStor->getValues(['year', 'month', 'isunited', 'conlimit']);
return; if ($admin['isunited'] != 0) {
} return;
}
$remainNations = $db->queryFirstColumn('SELECT nation FROM nation WHERE level > 0 LIMIT 2');
$remainNations = $db->queryFirstColumn('SELECT nation FROM nation WHERE level > 0 LIMIT 2');
if (!$remainNations || count($remainNations) != 1) {
return; if (!$remainNations || count($remainNations) != 1) {
} return;
}
$nationID = $remainNations[0];
$nationID = $remainNations[0];
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$cityCnt = $db->queryFirstField('SELECT count(city) FROM city WHERE nation=%i', $nationID);
if (!$cityCnt) { $cityCnt = $db->queryFirstField('SELECT count(city) FROM city WHERE nation=%i', $nationID);
return; if (!$cityCnt) {
} return;
}
if ($cityCnt != count(CityConst::all())) {
return; if ($cityCnt != count(CityConst::all())) {
} return;
}
checkStatistic();
checkStatistic();
$nation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $nationID);
$nationName = $nation['name']; $nation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $nationID);
$nationName = $nation['name'];
$josaYi = JosaUtil::pick($nationName, '이');
$josaYi = JosaUtil::pick($nationName, '이');
$nationLogger = new ActionLogger(0, $nationID, $admin['year'], $admin['month']);
$nationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>{$josaYi} 전토를 통일"); $nationLogger = new ActionLogger(0, $nationID, $admin['year'], $admin['month']);
$nationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>{$josaYi} 전토를 통일");
$gameStor->isunited = 2;
$gameStor->conlimit = $gameStor->conlimit * 100; $gameStor->isunited = 2;
$gameStor->conlimit = $gameStor->conlimit * 100;
foreach ($db->queryFirstColumn('SELECT no FROM general WHERE npc<2 AND age>=%i', GameConst::$minPushHallAge) as $hallGeneralNo) {
CheckHall($hallGeneralNo); foreach ($db->queryFirstColumn('SELECT no FROM general WHERE npc<2 AND age>=%i', GameConst::$minPushHallAge) as $hallGeneralNo) {
} CheckHall($hallGeneralNo);
}
[$totalPop, $totalMaxPop] = $db->queryFirstList('SELECT SUM(pop), SUM(pop_max) FROM city');
$pop = "{$totalPop} / {$totalMaxPop}"; [$totalPop, $totalMaxPop] = $db->queryFirstList('SELECT SUM(pop), SUM(pop_max) FROM city');
$poprate = round($totalPop / $totalMaxPop * 100, 2). " %"; $pop = "{$totalPop} / {$totalMaxPop}";
$poprate = round($totalPop / $totalMaxPop * 100, 2). " %";
$chiefs = Util::convertArrayToDict(
$db->query( $chiefs = Util::convertArrayToDict(
'SELECT no,name,picture,belong,officer_level FROM general WHERE nation=%i AND officer_level >= 5', $db->query(
$nationID 'SELECT no,name,picture,belong,officer_level FROM general WHERE nation=%i AND officer_level >= 5',
), $nationID
'officer_level' ),
); 'officer_level'
);
$nationGenerals = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nationID);
$nation['generals'] = $nationGenerals; $nationGenerals = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nationID);
$nation['generals'] = $nationGenerals;
$tigers = $db->query(
'SELECT value, name $tigers = $db->query(
FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no 'SELECT value, name
WHERE rank_data.nation_id = %i AND rank_data.type = "killnum" AND value > 0 ORDER BY value DESC LIMIT 5', FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no
$nationID WHERE rank_data.nation_id = %i AND rank_data.type = "killnum" AND value > 0 ORDER BY value DESC LIMIT 5',
); // 오호장군 $nationID
); // 오호장군
$tigerstr = join(', ', array_map(function ($arr) {
$number = number_format($arr['value']); $tigerstr = join(', ', array_map(function ($arr) {
return "{$arr['name']}{$number}"; $number = number_format($arr['value']);
}, $tigers)); return "{$arr['name']}{$number}";
}, $tigers));
$eagles = $db->query(
'SELECT value, name $eagles = $db->query(
FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no 'SELECT value, name
WHERE rank_data.nation_id = %i AND rank_data.type = "firenum" AND value > 0 ORDER BY value DESC LIMIT 7', FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no
$nationID WHERE rank_data.nation_id = %i AND rank_data.type = "firenum" AND value > 0 ORDER BY value DESC LIMIT 7',
); // 건안칠자 $nationID
); // 건안칠자
$eaglestr = join(', ', array_map(function ($arr) {
$number = number_format($arr['value']); $eaglestr = join(', ', array_map(function ($arr) {
return "{$arr['name']}{$number}"; $number = number_format($arr['value']);
}, $eagles)); return "{$arr['name']}{$number}";
}, $eagles));
$rawGeneralList = $db->query('SELECT no, name, npc, owner FROM general WHERE nation=%i ORDER BY dedication DESC', $nationID);
foreach ($rawGeneralList as $rawGeneral) { $rawGeneralList = $db->query('SELECT no, name, npc, owner FROM general WHERE nation=%i ORDER BY dedication DESC', $nationID);
$generalLogger = new ActionLogger($rawGeneral['no'], $nationID, $admin['year'], $admin['month']); foreach ($rawGeneralList as $rawGeneral) {
$generalLogger->pushGeneralActionLog("<D><b>{$nationName}</b></>{$josaYi} 전토를 통일하였습니다.", ActionLogger::YEAR_MONTH); $generalLogger = new ActionLogger($rawGeneral['no'], $nationID, $admin['year'], $admin['month']);
$generalLogger->flush(); $generalLogger->pushGeneralActionLog("<D><b>{$nationName}</b></>{$josaYi} 전토를 통일하였습니다.", ActionLogger::YEAR_MONTH);
} $generalLogger->flush();
}
$gen = join(', ', array_column($rawGeneral, 'name'));
$gen = join(', ', array_column($rawGeneral, 'name'));
$stat = $db->queryFirstRow('SELECT max(nation_count) as nc, max(gen_count) as gc FROM statistic');
$genCnt = $db->queryFirstField('SELECT count(*) FROM general'); $stat = $db->queryFirstRow('SELECT max(nation_count) as nc, max(gen_count) as gc FROM statistic');
$genCnt = $db->queryFirstField('SELECT count(*) FROM general');
$statNC = "1 / {$stat['nc']}";
$statGC = "{$genCnt} / {$stat['gc']}"; $statNC = "1 / {$stat['nc']}";
$statNation = $db->queryFirstRow('SELECT nation_count,nation_name,nation_hist from statistic where nation_count=%i LIMIT 1', $stat['nc']); $statGC = "{$genCnt} / {$stat['gc']}";
$statGeneral = $db->queryFirstRow('SELECT gen_count,personal_hist,special_hist,aux from statistic order by no desc LIMIT 1'); $statNation = $db->queryFirstRow('SELECT nation_count,nation_name,nation_hist from statistic where nation_count=%i LIMIT 1', $stat['nc']);
$statGeneral = $db->queryFirstRow('SELECT gen_count,personal_hist,special_hist,aux from statistic order by no desc LIMIT 1');
$nation = $nation;
$nation['generals'] = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nation['nation']); $nation = $nation;
$nation['aux'] = Json::decode($nation['aux']); $nation['generals'] = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nation['nation']);
$nation['msg'] = $nationStor->notice; $nation['aux'] = Json::decode($nation['aux']);
$nation['scout_msg'] = $nationStor->scout_msg; $nation['msg'] = $nationStor->notice;
$nation['aux'] += $nationStor->max_power; $nation['scout_msg'] = $nationStor->scout_msg;
$nation['history'] = getNationHistoryLogAll($nation['nation']); $nation['aux'] += $nationStor->max_power;
$nation['history'] = getNationHistoryLogAll($nation['nation']);
storeOldGenerals(0, $admin['year'], $admin['month']);
storeOldGenerals($nation['nation'], $admin['year'], $admin['month']); storeOldGenerals(0, $admin['year'], $admin['month']);
storeOldGenerals($nation['nation'], $admin['year'], $admin['month']);
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID, $db->insert('ng_old_nations', [
'nation' => $nation['nation'], 'server_id' => UniqueConst::$serverID,
'data' => Json::encode($nation) 'nation' => $nation['nation'],
]); 'data' => Json::encode($nation)
]);
$noNationGeneral = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=0');
$db->insert('ng_old_nations', [ $noNationGeneral = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=0');
'server_id' => UniqueConst::$serverID, $db->insert('ng_old_nations', [
'nation' => 0, 'server_id' => UniqueConst::$serverID,
'data' => Json::encode([ 'nation' => 0,
'nation' => 0, 'data' => Json::encode([
'name' => '재야', 'nation' => 0,
'generals' => $noNationGeneral 'name' => '재야',
]) 'generals' => $noNationGeneral
]); ])
]);
$nationHistory = getNationHistoryLogAll($nation['nation']);
$nationHistory = getNationHistoryLogAll($nation['nation']);
$serverCnt = $db->queryFirstField('SELECT count(*) FROM ng_games');
$serverName = UniqueConst::$serverName; $serverCnt = $db->queryFirstField('SELECT count(*) FROM ng_games');
$serverName = UniqueConst::$serverName;
$db->update('ng_games', [
'winner_nation' => $nation['nation'] $db->update('ng_games', [
], 'server_id=%s', UniqueConst::$serverID); 'winner_nation' => $nation['nation']
], 'server_id=%s', UniqueConst::$serverID);
$db->insert('emperior', [
'phase' => $serverName . $serverCnt . '기', $db->insert('emperior', [
'server_id' => UniqueConst::$serverID, 'phase' => $serverName . $serverCnt . '기',
'nation_count' => $statNC, 'server_id' => UniqueConst::$serverID,
'nation_name' => $statNation['nation_name'], 'nation_count' => $statNC,
'nation_hist' => $statNation['nation_hist'], 'nation_name' => $statNation['nation_name'],
'gen_count' => $statGC, 'nation_hist' => $statNation['nation_hist'],
'personal_hist' => $statGeneral['personal_hist'], 'gen_count' => $statGC,
'special_hist' => $statGeneral['special_hist'], 'personal_hist' => $statGeneral['personal_hist'],
'name' => $nation['name'], 'special_hist' => $statGeneral['special_hist'],
'type' => $nation['type'], 'name' => $nation['name'],
'color' => $nation['color'], 'type' => $nation['type'],
'year' => $admin['year'], 'color' => $nation['color'],
'month' => $admin['month'], 'year' => $admin['year'],
'power' => $nation['power'], 'month' => $admin['month'],
'gennum' => $nation['gennum'], 'power' => $nation['power'],
'citynum' => $cityCnt, 'gennum' => $nation['gennum'],
'pop' => $pop, 'citynum' => $cityCnt,
'poprate' => $poprate, 'pop' => $pop,
'gold' => $nation['gold'], 'poprate' => $poprate,
'rice' => $nation['rice'], 'gold' => $nation['gold'],
'l12name' => $chiefs[12]['name'], 'rice' => $nation['rice'],
'l12pic' => $chiefs[12]['picture'], 'l12name' => $chiefs[12]['name'],
'l11name' => $chiefs[11]['name'], 'l12pic' => $chiefs[12]['picture'],
'l11pic' => $chiefs[11]['picture'], 'l11name' => $chiefs[11]['name'],
'l10name' => $chiefs[10]['name'], 'l11pic' => $chiefs[11]['picture'],
'l10pic' => $chiefs[10]['picture'], 'l10name' => $chiefs[10]['name'],
'l9name' => $chiefs[9]['name'], 'l10pic' => $chiefs[10]['picture'],
'l9pic' => $chiefs[9]['picture'], 'l9name' => $chiefs[9]['name'],
'l8name' => $chiefs[8]['name'], 'l9pic' => $chiefs[9]['picture'],
'l8pic' => $chiefs[8]['picture'], 'l8name' => $chiefs[8]['name'],
'l7name' => $chiefs[7]['name'], 'l8pic' => $chiefs[8]['picture'],
'l7pic' => $chiefs[7]['picture'], 'l7name' => $chiefs[7]['name'],
'l6name' => $chiefs[6]['name'], 'l7pic' => $chiefs[7]['picture'],
'l6pic' => $chiefs[6]['picture'], 'l6name' => $chiefs[6]['name'],
'l5name' => $chiefs[5]['name'], 'l6pic' => $chiefs[6]['picture'],
'l5pic' => $chiefs[5]['picture'], 'l5name' => $chiefs[5]['name'],
'tiger' => $tigerstr, 'l5pic' => $chiefs[5]['picture'],
'eagle' => $eaglestr, 'tiger' => $tigerstr,
'gen' => $gen, 'eagle' => $eaglestr,
'history' => JSON::encode($nationHistory), 'gen' => $gen,
'aux' => $statGeneral['aux'] 'history' => JSON::encode($nationHistory),
]); 'aux' => $statGeneral['aux']
]);
$history = ["<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【통일】</b></><D><b>{$nation['name']}</b></>{$josaYi} 전토를 통일하였습니다."];
pushGlobalHistoryLog($history, $admin['year'], $admin['month']); $history = ["<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【통일】</b></><D><b>{$nation['name']}</b></>{$josaYi} 전토를 통일하였습니다."];
pushGlobalHistoryLog($history, $admin['year'], $admin['month']);
//연감 월결산
LogHistory(); //연감 월결산
} LogHistory();
}
+1 -1
View File
@@ -35,7 +35,7 @@ jQuery(function($) {
//checkCommandArg 참고 //checkCommandArg 참고
var availableArgumentList = { var availableArgumentList = {
'string': [ 'string': [
'nationName', 'optionText', 'itemType', 'nationType', 'itemCode', 'nationName', 'optionText', 'itemType', 'nationType', 'itemCode', 'commandType',
], ],
'int': [ 'int': [
'crewType', 'destGeneralID', 'destCityID', 'destNationID', 'crewType', 'destGeneralID', 'destCityID', 'destNationID',
+34 -1
View File
@@ -17,6 +17,7 @@ use \sammo\Constraint\ConstraintHelper;
abstract class BaseCommand{ abstract class BaseCommand{
static protected $actionName = 'CommandName'; static protected $actionName = 'CommandName';
static public $reqArg = false; static public $reqArg = false;
static protected $isLazyCalcReqTurn = false;
public function getCommandDetailTitle():string{ public function getCommandDetailTitle():string{
return $this->getName(); return $this->getName();
@@ -54,7 +55,6 @@ abstract class BaseCommand{
static protected $isInitStatic = true; static protected $isInitStatic = true;
protected static function initStatic(){ protected static function initStatic(){
} }
public function __construct(General $generalObj, array $env, $arg = null){ public function __construct(General $generalObj, array $env, $arg = null){
@@ -271,6 +271,29 @@ abstract class BaseCommand{
return $this->logger; return $this->logger;
} }
abstract protected function getNextExecuteKey():string;
abstract public function getNextAvailable():?int;
abstract public function setNextAvailable(?int $yearMonth=null);
protected function testPostReqTurn():?array{
if(!$this->getPostReqTurn()){
return null;
}
$nextAvailable = $this->getNextAvailable();
if($nextAvailable === null){
return null;
}
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
$remainTurn = $nextAvailable - $yearMonth - $this->getPreReqTurn();
if($remainTurn <= 0){
return null;
}
return ['testPostReqTurn', "{$remainTurn}턴 더 기다려야 합니다"];
}
public function testPermissionToReserve():?string{ public function testPermissionToReserve():?string{
if($this->cachedPermissionToReserve){ if($this->cachedPermissionToReserve){
return $this->reasonNoPermissionToReserve; return $this->reasonNoPermissionToReserve;
@@ -331,6 +354,11 @@ abstract class BaseCommand{
]; ];
[$this->reasonConstraint, $this->reasonNotMinConditionMet] = Constraint::testAll($this->minConditionConstraints??[], $constraintInput, $this->env); [$this->reasonConstraint, $this->reasonNotMinConditionMet] = Constraint::testAll($this->minConditionConstraints??[], $constraintInput, $this->env);
if($this->reasonNotMinConditionMet === null && !self::$isLazyCalcReqTurn){
[$this->reasonConstraint, $this->reasonNotMinConditionMet] = $this->testPostReqTurn();
}
$this->cachedMinConditionMet = true; $this->cachedMinConditionMet = true;
return $this->reasonNotMinConditionMet; return $this->reasonNotMinConditionMet;
@@ -364,6 +392,11 @@ abstract class BaseCommand{
]; ];
[$this->reasonConstraint, $this->reasonNotFullConditionMet] = Constraint::testAll($this->fullConditionConstraints??[], $constraintInput, $this->env); [$this->reasonConstraint, $this->reasonNotFullConditionMet] = Constraint::testAll($this->fullConditionConstraints??[], $constraintInput, $this->env);
if($this->reasonNotFullConditionMet === null){
[$this->reasonConstraint, $this->reasonNotFullConditionMet] = $this->testPostReqTurn();
}
$this->cachedFullConditionMet = true; $this->cachedFullConditionMet = true;
return $this->reasonNotFullConditionMet; return $this->reasonNotFullConditionMet;
@@ -32,24 +32,6 @@ class che_전투특기초기화 extends Command\GeneralCommand{
} }
protected function init(){ protected function init(){
$general = $this->generalObj;
$env = $this->env;
$yearMonth = Util::joinYearMonth($env['year'], $env['month']);
$auxYearMonth = $general->getAuxVar('used_'.$this->getName())??-999;
if($yearMonth < $auxYearMonth + 60 - $this->getPreReqTurn()){
$this->minConditionConstraints=[
ConstraintHelper::AlwaysFail('초기화한 지 5년이 지나야합니다')
];
$this->fullConditionConstraints=[
ConstraintHelper::AlwaysFail('초기화한 지 5년이 지나야합니다')
];
return;
}
$this->minConditionConstraints=[ $this->minConditionConstraints=[
ConstraintHelper::ReqGeneralValue(static::$specialType, static::$specialText, '!=', 'None', '특기가 없습니다.'), ConstraintHelper::ReqGeneralValue(static::$specialType, static::$specialText, '!=', 'None', '특기가 없습니다.'),
]; ];
@@ -57,7 +39,6 @@ class che_전투특기초기화 extends Command\GeneralCommand{
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::ReqGeneralValue(static::$specialType, static::$specialText, '!=', 'None', '특기가 없습니다.') ConstraintHelper::ReqGeneralValue(static::$specialType, static::$specialText, '!=', 'None', '특기가 없습니다.')
]; ];
} }
public function getCommandDetailTitle():string{ public function getCommandDetailTitle():string{
@@ -82,7 +63,7 @@ class che_전투특기초기화 extends Command\GeneralCommand{
} }
public function getPostReqTurn():int{ public function getPostReqTurn():int{
return 0; return 60;
} }
public function getTermString():string{ public function getTermString():string{
@@ -113,7 +94,6 @@ class che_전투특기초기화 extends Command\GeneralCommand{
$general->setVar(static::$specialType, 'None'); $general->setVar(static::$specialType, 'None');
$general->setVar(static::$speicalAge, $general->getVar('age') + 1); $general->setVar(static::$speicalAge, $general->getVar('age') + 1);
$general->setAuxVar('used_'.$this->getName(), $yearMonth);
$logger = $general->getLogger(); $logger = $general->getLogger();
+35 -5
View File
@@ -1,6 +1,36 @@
<?php <?php
namespace sammo\Command; namespace sammo\Command;
use \sammo\Util;
abstract class GeneralCommand extends BaseCommand{
abstract class GeneralCommand extends BaseCommand{
protected function getNextExecuteKey():string{
$turnKey = static::$actionName;
$generalID = $this->getGeneral()->getID();
$executeKey = "next_execute_{$generalID}_{$turnKey}";
return $executeKey;
}
public function getNextAvailable():?int{
if($this->isArgValid && !$this->getPostReqTurn()){
return null;
}
$db = \sammo\DB::db();
$lastExecuteStor = \sammo\KVStorage::getStorage($db, 'next_execute');
return $lastExecuteStor->getValue($this->getNextExecuteKey());
}
public function setNextAvailable(?int $yearMonth=null){
if(!$this->getPostReqTurn()){
return;
}
if($yearMonth === null){
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']) + $this->getPostReqTurn();
}
$db = \sammo\DB::db();
$lastExecuteStor = \sammo\KVStorage::getStorage($db, 'next_execute');
$lastExecuteStor->setValue($this->getNextExecuteKey(), $yearMonth);
}
}; };
+251 -251
View File
@@ -1,251 +1,251 @@
<?php <?php
namespace sammo\Command\Nation; namespace sammo\Command\Nation;
use\sammo\{ use\sammo\{
DB, DB,
Util, Util,
JosaUtil, JosaUtil,
General, General,
DummyGeneral, DummyGeneral,
ActionLogger, ActionLogger,
GameConst, GameConst,
LastTurn, LastTurn,
GameUnitConst, GameUnitConst,
Command, Command,
Message, Message,
MessageTarget MessageTarget
}; };
use function\sammo\{ use function\sammo\{
getDomesticExpLevelBonus, getDomesticExpLevelBonus,
CriticalRatioDomestic, CriticalRatioDomestic,
CriticalScoreEx, CriticalScoreEx,
getAllNationStaticInfo, getAllNationStaticInfo,
getNationStaticInfo, getNationStaticInfo,
GetImageURL GetImageURL
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
class che_급습 extends Command\NationCommand class che_급습 extends Command\NationCommand
{ {
static protected $actionName = '급습'; static protected $actionName = '급습';
static public $reqArg = true; static public $reqArg = true;
protected function argTest(): bool protected function argTest(): bool
{ {
if ($this->arg === null) { if ($this->arg === null) {
return false; return false;
} }
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음 //NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if (!key_exists('destNationID', $this->arg)) { if (!key_exists('destNationID', $this->arg)) {
return false; return false;
} }
$destNationID = $this->arg['destNationID']; $destNationID = $this->arg['destNationID'];
if (!is_int($destNationID)) { if (!is_int($destNationID)) {
return false; return false;
} }
if ($destNationID < 1) { if ($destNationID < 1) {
return false; return false;
} }
$this->arg = [ $this->arg = [
'destNationID' => $destNationID 'destNationID' => $destNationID
]; ];
return true; return true;
} }
protected function init() protected function init()
{ {
$general = $this->generalObj; $general = $this->generalObj;
$env = $this->env; $env = $this->env;
$this->setCity(); $this->setCity();
$this->setNation(['strategic_cmd_limit']); $this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [ $this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
protected function initWithArg() protected function initWithArg()
{ {
$this->setDestNation($this->arg['destNationID'], null); $this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints = [ $this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(), ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyWithTerm( ConstraintHelper::AllowDiplomacyWithTerm(
1, 1,
12, 12,
'선포 12개월 이상인 상대국에만 가능합니다.' '선포 12개월 이상인 상대국에만 가능합니다.'
), ),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
public function getCommandDetailTitle(): string public function getCommandDetailTitle(): string
{ {
$name = $this->getName(); $name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1; $reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn(); $postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)"; return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
} }
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;
} }
public function getPostReqTurn(): int public function getPostReqTurn(): int
{ {
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit); $genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 16) * 10); $nextTerm = Util::round(sqrt($genCount * 16) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm); $nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm; return $nextTerm;
} }
public function getBrief(): string public function getBrief(): string
{ {
$commandName = $this->getName(); $commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name']; $destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}"; return "{$destNationName}】에 {$commandName}";
} }
public function run(): bool public function run(): bool
{ {
if (!$this->hasFullConditionMet()) { if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도'); throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
} }
$db = DB::db(); $db = DB::db();
$env = $this->env; $env = $this->env;
$general = $this->generalObj; $general = $this->generalObj;
$generalID = $general->getID(); $generalID = $general->getID();
$generalName = $general->getName(); $generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM); $date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year']; $year = $this->env['year'];
$month = $this->env['month']; $month = $this->env['month'];
$nation = $this->nation; $nation = $this->nation;
$nationID = $nation['nation']; $nationID = $nation['nation'];
$nationName = $nation['name']; $nationName = $nation['name'];
$destNation = $this->destNation; $destNation = $this->destNation;
$destNationID = $destNation['nation']; $destNationID = $destNation['nation'];
$destNationName = $destNation['name']; $destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이'); $josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이'); $josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName(); $commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을'); $josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger(); $logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>"); $logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1)); $general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1)); $general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다."; $broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) { foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month); $nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush(); $nationGeneralLogger->flush();
} }
$josaYiCommand = JosaUtil::pick($commandName, '이'); $josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다."; $broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($destNationGeneralList as $destNationGeneralID) { foreach ($destNationGeneralList as $destNationGeneralID) {
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month); $destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush(); $destNationGeneralLogger->flush();
} }
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month); $destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동"); $destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush(); $destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$db->update('nation', [ $db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn() 'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
$db->update('diplomacy', [ $db->update('diplomacy', [
'term' => $db->sqleval('`term` - %i', 3), 'term' => $db->sqleval('`term` - %i', 3),
], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID); ], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
public function getJSFiles(): array public function getJSFiles(): array
{ {
return [ return [
'js/defaultSelectNationByMap.js' 'js/defaultSelectNationByMap.js'
]; ];
} }
public function getForm(): string public function getForm(): string
{ {
$generalObj = $this->generalObj; $generalObj = $this->generalObj;
$nationID = $generalObj->getNationID(); $nationID = $generalObj->getNationID();
$nationList = []; $nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn()); $testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach (getAllNationStaticInfo() as $destNation) { foreach (getAllNationStaticInfo() as $destNation) {
if ($destNation['nation'] == $nationID) { if ($destNation['nation'] == $nationID) {
continue; continue;
} }
$testTurn->setArg(['destNationID' => $destNation['nation']]); $testTurn->setArg(['destNationID' => $destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]); $testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]);
if ($testCommand->hasFullConditionMet()) { if ($testCommand->hasFullConditionMet()) {
$destNation['availableCommand'] = true; $destNation['availableCommand'] = true;
} else { } else {
$destNation['availableCommand'] = false; $destNation['availableCommand'] = false;
} }
$nationList[] = $destNation; $nationList[] = $destNation;
} }
ob_start(); ob_start();
?> ?>
<?= \sammo\getMapHtml() ?><br> <?= \sammo\getMapHtml() ?><br>
선택된 국가에 급습을 발동합니다.<br> 선택된 국가에 급습을 발동합니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br> 선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br> 상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 급습 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br> 배경색은 현재 급습 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'> <select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach ($nationList as $nation) : ?> <?php foreach ($nationList as $nation) : ?>
<option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option> <option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option>
<?php endforeach; ?> <?php endforeach; ?>
<input type=button id="commonSubmit" value="<?= $this->getName() ?>"> <input type=button id="commonSubmit" value="<?= $this->getName() ?>">
<?php <?php
return ob_get_clean(); return ob_get_clean();
} }
} }
@@ -124,9 +124,18 @@ class che_물자원조 extends Command\NationCommand{
} }
public function getPostReqTurn():int{ public function getPostReqTurn():int{
//NOTE: 자체 postReqTurn 사용
return 12; return 12;
} }
public function getNextAvailable():?int{
return null;
}
public function setNextAvailable(?int $yearMonth=null){
return;
}
public function getBrief():string{ public function getBrief():string{
[$goldAmount, $riceAmount] = $this->arg['amountList']; [$goldAmount, $riceAmount] = $this->arg['amountList'];
$goldAmountText = number_format($goldAmount); $goldAmountText = number_format($goldAmount);
+192 -195
View File
@@ -1,196 +1,193 @@
<?php <?php
namespace sammo\Command\Nation; namespace sammo\Command\Nation;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, DummyGeneral, General, DummyGeneral,
ActionLogger, ActionLogger,
GameConst, GameConst,
LastTurn, LastTurn,
GameUnitConst, GameUnitConst,
Command, Command,
MessageTarget, MessageTarget,
Message, Message,
CityConst CityConst
}; };
use function \sammo\{ use function \sammo\{
getDomesticExpLevelBonus, getDomesticExpLevelBonus,
CriticalRatioDomestic, CriticalRatioDomestic,
CriticalScoreEx, CriticalScoreEx,
GetImageURL, GetImageURL,
getNationStaticInfo getNationStaticInfo
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action; use sammo\Event\Action;
class che_백성동원 extends Command\NationCommand{ class che_백성동원 extends Command\NationCommand{
static protected $actionName = '백성동원'; static protected $actionName = '백성동원';
static public $reqArg = true; static public $reqArg = true;
protected function argTest():bool{ protected function argTest():bool{
if($this->arg === null){ if($this->arg === null){
return false; return false;
} }
if(!key_exists('destCityID', $this->arg)){ if(!key_exists('destCityID', $this->arg)){
return false; return false;
} }
if(CityConst::byID($this->arg['destCityID']) === null){ if(CityConst::byID($this->arg['destCityID']) === null){
return false; return false;
} }
$destCityID = $this->arg['destCityID']; $destCityID = $this->arg['destCityID'];
$this->arg = [ $this->arg = [
'destCityID'=>$destCityID, 'destCityID'=>$destCityID,
]; ];
return true; return true;
} }
protected function init(){ protected function init(){
$general = $this->generalObj; $general = $this->generalObj;
$env = $this->env; $env = $this->env;
$this->setCity(); $this->setCity();
$this->setNation(['strategic_cmd_limit']); $this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints=[ $this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand() ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn())
]; ];
} }
protected function initWithArg() protected function initWithArg()
{ {
$this->setDestCity($this->arg['destCityID']); $this->setDestCity($this->arg['destCityID']);
$this->setDestNation($this->destCity['nation']); $this->setDestNation($this->destCity['nation']);
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::AllowDiplomacyStatus($this->generalObj->getNationID(), [ ConstraintHelper::OccupiedDestCity(),
0, 1 ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn())
], '전쟁중이 아닙니다.'), ];
ConstraintHelper::OccupiedDestCity(), }
ConstraintHelper::AvailableStrategicCommand()
]; public function getCommandDetailTitle():string{
} $name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1;
public function getCommandDetailTitle():string{ $postReqTurn = $this->getPostReqTurn();
$name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1; return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
$postReqTurn = $this->getPostReqTurn(); }
return "{$name}/{$reqTurn}턴(전략$postReqTurn)"; public function getCost():array{
} return [0, 0];
}
public function getCost():array{
return [0, 0]; public function getPreReqTurn():int{
} return 0;
}
public function getPreReqTurn():int{
return 0; public function getPostReqTurn():int{
} $genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount*4)*10);
public function getPostReqTurn():int{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit); $nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
$nextTerm = Util::round(sqrt($genCount*4)*10); return $nextTerm;
}
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm; public function getBrief():string{
} $commandName = $this->getName();
$destCityName = CityConst::byID($this->arg['destCityID'])->name;
public function getBrief():string{ return "{$destCityName}】에 {$commandName}";
$commandName = $this->getName(); }
$destCityName = CityConst::byID($this->arg['destCityID'])->name;
return "{$destCityName}】에 {$commandName}"; public function run():bool{
} if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
public function run():bool{ }
if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도'); $db = DB::db();
}
$general = $this->generalObj;
$db = DB::db(); $generalID = $general->getID();
$generalName = $general->getName();
$general = $this->generalObj; $date = $general->getTurnTime($general::TURNTIME_HM);
$generalID = $general->getID();
$generalName = $general->getName(); $year = $this->env['year'];
$date = $general->getTurnTime($general::TURNTIME_HM); $month = $this->env['month'];
$year = $this->env['year']; $destCity = $this->destCity;
$month = $this->env['month']; $destCityID = $destCity['city'];
$destCityName = $destCity['name'];
$destCity = $this->destCity;
$destCityID = $destCity['city']; $nationID = $general->getNationID();
$destCityName = $destCity['name']; $nationName = $this->nation['name'];
$nationID = $general->getNationID(); $logger = $general->getLogger();
$nationName = $this->nation['name']; $logger->pushGeneralActionLog("백성동원 발동! <1>$date</>");
$logger = $general->getLogger(); $general->addExperience(5 * ($this->getPreReqTurn() + 1));
$logger->pushGeneralActionLog("백성동원 발동! <1>$date</>"); $general->addDedication(5 * ($this->getPreReqTurn() + 1));
$general->addExperience(5 * ($this->getPreReqTurn() + 1)); $josaYi = JosaUtil::pick($generalName, '이');
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다.";
$josaYi = JosaUtil::pick($generalName, '이');
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다."; foreach($targetGeneralList as $targetGeneralID){
$targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month);
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
foreach($targetGeneralList as $targetGeneralID){ $targetLogger->flush();
$targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month); }
$targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$targetLogger->flush(); $db->update('city', [
} 'def' => $db->sqleval('GREATEST(def_max * 0.8, def)'),
'wall' => $db->sqleval('GREATEST(wall_max * 0.8, wall)'),
$db->update('city', [ ], 'city=%i', $destCityID);
'def' => $db->sqleval('GREATEST(def_max * 0.8, def)'),
'wall' => $db->sqleval('GREATEST(wall_max * 0.8, wall)'), $josaYiNation = JosaUtil::pick($nationName, '이');
], 'city=%i', $destCityID);
$josaYiNation = JosaUtil::pick($nationName, '이'); $logger->pushGeneralHistoryLog('<M>백성동원</>을 발동');
$logger->pushNationalHistoryLog("<L><b>【전략】</b></><D><b>{$nationName}</b></>{$josaYiNation} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다.");
$logger->pushGeneralHistoryLog('<M>백성동원</>을 발동'); $db->update('nation', [
$logger->pushNationalHistoryLog("<L><b>【전략】</b></><D><b>{$nationName}</b></>{$josaYiNation} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다."); 'strategic_cmd_limit' => 12
], 'nation=%i', $nationID);
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn() $this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
], 'nation=%i', $nationID); $general->applyDB($db);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0)); return true;
$general->applyDB($db); }
return true; public function getJSFiles(): array
} {
return [
public function getJSFiles(): array 'js/defaultSelectCityByMap.js'
{ ];
return [ }
'js/defaultSelectCityByMap.js'
];
} public function getForm(): string
{
ob_start();
public function getForm(): string ?>
{ <?=\sammo\getMapHtml()?><br>
ob_start(); 선택된 도시에 백성을 동원해 성벽을 쌓습니다.<br>
?> 아국 도시만 가능합니다.<br>
<?=\sammo\getMapHtml()?><br> 목록을 선택하거나 도시를 클릭하세요.<br>
선택된 도시에 백성을 동원해 성벽을 쌓습니다.<br> <select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'>
아국 도시만 가능합니다.<br> <?=\sammo\optionsForCities()?><br>
목록을 선택하거나 도시를 클릭하세요.<br> </select> <input type=button id="commonSubmit" value="<?=$this->getName()?>"><br>
<select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'> <br>
<?=\sammo\optionsForCities()?><br> <?php
</select> <input type=button id="commonSubmit" value="<?=$this->getName()?>"><br> return ob_get_clean();
<br> }
<?php
return ob_get_clean();
}
} }
+3 -3
View File
@@ -60,7 +60,7 @@ class che_수몰 extends Command\NationCommand{
$this->minConditionConstraints=[ $this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
@@ -75,7 +75,7 @@ class che_수몰 extends Command\NationCommand{
ConstraintHelper::NotNeutralDestCity(), ConstraintHelper::NotNeutralDestCity(),
ConstraintHelper::NotOccupiedDestCity(), ConstraintHelper::NotOccupiedDestCity(),
ConstraintHelper::BattleGroundCity(), ConstraintHelper::BattleGroundCity(),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
@@ -179,7 +179,7 @@ class che_수몰 extends Command\NationCommand{
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>수몰</>을 발동"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>수몰</>을 발동");
$db->update('nation', [ $db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn() 'strategic_cmd_limit' => 12
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0)); $this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
+243 -243
View File
@@ -1,243 +1,243 @@
<?php <?php
namespace sammo\Command\Nation; namespace sammo\Command\Nation;
use\sammo\{ use\sammo\{
DB, DB,
Util, Util,
JosaUtil, JosaUtil,
General, General,
ActionLogger, ActionLogger,
GameConst, GameConst,
LastTurn, LastTurn,
GameUnitConst, GameUnitConst,
Command, Command,
KVStorage KVStorage
}; };
use function\sammo\{ use function\sammo\{
getDomesticExpLevelBonus, getDomesticExpLevelBonus,
CriticalRatioDomestic, CriticalRatioDomestic,
CriticalScoreEx, CriticalScoreEx,
tryUniqueItemLottery tryUniqueItemLottery
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
class che_의병모집 extends Command\NationCommand class che_의병모집 extends Command\NationCommand
{ {
static protected $actionName = '의병모집'; static protected $actionName = '의병모집';
protected function argTest(): bool protected function argTest(): bool
{ {
$this->arg = null; $this->arg = null;
return true; return true;
} }
protected function init() protected function init()
{ {
$general = $this->generalObj; $general = $this->generalObj;
$this->setNation(['strategic_cmd_limit']); $this->setNation(['strategic_cmd_limit']);
$this->setCity(); $this->setCity();
$env = $this->env; $env = $this->env;
$relYear = $env['year'] - $env['startyear']; $relYear = $env['year'] - $env['startyear'];
$this->fullConditionConstraints = [ $this->fullConditionConstraints = [
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::NotBeNeutral(), ConstraintHelper::NotBeNeutral(),
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
ConstraintHelper::NotOpeningPart($relYear), ConstraintHelper::NotOpeningPart($relYear),
]; ];
} }
public function getCommandDetailTitle(): string public function getCommandDetailTitle(): string
{ {
$name = $this->getName(); $name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1; $reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn(); $postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)"; return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
} }
public function getCost(): array public function getCost(): array
{ {
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn(): int public function getPreReqTurn(): int
{ {
return 2; return 2;
} }
public function getPostReqTurn(): int public function getPostReqTurn(): int
{ {
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit); $genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 10) * 10); $nextTerm = Util::round(sqrt($genCount * 10) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm); $nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm; return $nextTerm;
} }
public function run(): bool public function run(): bool
{ {
if (!$this->hasFullConditionMet()) { if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도'); throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
} }
$db = DB::db(); $db = DB::db();
$env = $this->env; $env = $this->env;
$general = $this->generalObj; $general = $this->generalObj;
$generalID = $general->getID(); $generalID = $general->getID();
$generalName = $general->getName(); $generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM); $date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year']; $year = $this->env['year'];
$month = $this->env['month']; $month = $this->env['month'];
$nation = $this->nation; $nation = $this->nation;
$nationID = $nation['nation']; $nationID = $nation['nation'];
$nationName = $nation['name']; $nationName = $nation['name'];
$commandName = $this->getName(); $commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을'); $josaUl = JosaUtil::pick($commandName, '을');
$genCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc < 2', $nationID); $genCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc < 2', $nationID);
$npcCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc = 3', $nationID); $npcCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc = 3', $nationID);
$npcOtherCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation!=%i AND npc = 3', $nationID); $npcOtherCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation!=%i AND npc = 3', $nationID);
$genCount = Util::valueFit($genCount, 1); $genCount = Util::valueFit($genCount, 1);
$npcCount = Util::valueFit($npcCount, 1); $npcCount = Util::valueFit($npcCount, 1);
$npcOtherCountScore = Util::round(sqrt($npcOtherCount + 1)) - 1; $npcOtherCountScore = Util::round(sqrt($npcOtherCount + 1)) - 1;
$logger = $general->getLogger(); $logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>"); $logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$josaYi = JosaUtil::pick($generalName, '이'); $josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이'); $josaYiNation = JosaUtil::pick($nationName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동하였습니다."; $broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) { foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month); $nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush(); $nationGeneralLogger->flush();
} }
$logger->pushGeneralHistoryLog("<M>{$commandName}</>{$josaUl} 발동"); $logger->pushGeneralHistoryLog("<M>{$commandName}</>{$josaUl} 발동");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동");
$general->addExperience(5 * ($this->getPreReqTurn() + 1)); $general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1)); $general->addDedication(5 * ($this->getPreReqTurn() + 1));
$gameStor = KVStorage::getStorage($db, 'game_env'); //TODO: 차라리 env가 이거여야..? $gameStor = KVStorage::getStorage($db, 'game_env'); //TODO: 차라리 env가 이거여야..?
$avgGenCnt = $db->queryFirstField('SELECT avg(gennum) FROM nation WHERE level > 0'); $avgGenCnt = $db->queryFirstField('SELECT avg(gennum) FROM nation WHERE level > 0');
$createGenCnt = 5 + Util::round($avgGenCnt / 10); $createGenCnt = 5 + Util::round($avgGenCnt / 10);
$createGenIdx = $gameStor->npccount + 1; $createGenIdx = $gameStor->npccount + 1;
$lastCreatGenIdx = $createGenIdx + $createGenCnt; $lastCreatGenIdx = $createGenIdx + $createGenCnt;
$pickTypeList = ['무' => 5, '지' => 5]; $pickTypeList = ['무' => 5, '지' => 5];
$avgGen = $db->queryFirstRow( $avgGen = $db->queryFirstRow(
'SELECT avg(dedication) as ded,avg(experience) as exp, 'SELECT avg(dedication) as ded,avg(experience) as exp,
avg(dex1+dex2+dex3+dex4) as dex_t, avg(age) as age, avg(dex5) as dex5 avg(dex1+dex2+dex3+dex4) as dex_t, avg(age) as age, avg(dex5) as dex5
from general where nation=%i', from general where nation=%i',
$nationID $nationID
); );
$dexTotal = $avgGen['dex_t']; $dexTotal = $avgGen['dex_t'];
for (; $createGenIdx <= $lastCreatGenIdx; $createGenIdx++) { for (; $createGenIdx <= $lastCreatGenIdx; $createGenIdx++) {
$pickType = Util::choiceRandomUsingWeight($pickTypeList); $pickType = Util::choiceRandomUsingWeight($pickTypeList);
$totalStat = GameConst::$defaultStatNPCMax * 2 + 10; $totalStat = GameConst::$defaultStatNPCMax * 2 + 10;
$minStat = 10; $minStat = 10;
$mainStat = GameConst::$defaultStatNPCMax - Util::randRangeInt(0, 10); $mainStat = GameConst::$defaultStatNPCMax - Util::randRangeInt(0, 10);
//TODO: defaultStatNPCTotal, defaultStatNPCMin 추가 //TODO: defaultStatNPCTotal, defaultStatNPCMin 추가
$otherStat = $minStat + Util::randRangeInt(0, 5); $otherStat = $minStat + Util::randRangeInt(0, 5);
$subStat = $totalStat - $mainStat - $otherStat; $subStat = $totalStat - $mainStat - $otherStat;
if ($subStat < $minStat) { if ($subStat < $minStat) {
$subStat = $otherStat; $subStat = $otherStat;
$otherStat = $minStat; $otherStat = $minStat;
$mainStat = $totalStat - $subStat - $otherStat; $mainStat = $totalStat - $subStat - $otherStat;
if ($mainStat) { if ($mainStat) {
throw new \LogicException('기본 스탯 설정값이 잘못되어 있음'); throw new \LogicException('기본 스탯 설정값이 잘못되어 있음');
} }
} }
if ($pickType == '무') { if ($pickType == '무') {
$leadership = $subStat; $leadership = $subStat;
$strength = $mainStat; $strength = $mainStat;
$intel = $otherStat; $intel = $otherStat;
$dexVal = Util::choiceRandom([ $dexVal = Util::choiceRandom([
[$dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8, $dexTotal / 8], [$dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8, $dexTotal / 8],
[$dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8], [$dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8],
[$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8], [$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8],
]); ]);
} else if ($pickType == '지') { } else if ($pickType == '지') {
$leadership = $subStat; $leadership = $subStat;
$strength = $otherStat; $strength = $otherStat;
$intel = $mainStat; $intel = $mainStat;
$dexVal = [$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8]; $dexVal = [$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8];
} else { } else {
$leadership = $otherStat; $leadership = $otherStat;
$strength = $subStat; $strength = $subStat;
$intel = $mainStat; $intel = $mainStat;
$dexVal = [$dexTotal / 4, $dexTotal / 4, $dexTotal / 4, $dexTotal / 4]; $dexVal = [$dexTotal / 4, $dexTotal / 4, $dexTotal / 4, $dexTotal / 4];
} }
$leadership = Util::round($leadership); $leadership = Util::round($leadership);
$strength = Util::round($strength); $strength = Util::round($strength);
$intel = Util::round($intel); $intel = Util::round($intel);
$age = $avgGen['age']; $age = $avgGen['age'];
$newNPC = new \sammo\Scenario\NPC( $newNPC = new \sammo\Scenario\NPC(
Util::randRangeInt(1, 150), Util::randRangeInt(1, 150),
"의병장{$createGenIdx}", "의병장{$createGenIdx}",
null, null,
$nationID, $nationID,
$general->getCityID(), $general->getCityID(),
$leadership, $leadership,
$strength, $strength,
$intel, $intel,
1, 1,
$env['year'] - 20, $env['year'] - 20,
$env['year'] + 6, $env['year'] + 6,
null, null,
null null
); );
$newNPC->killturn = Util::randRangeInt(64, 70); $newNPC->killturn = Util::randRangeInt(64, 70);
$newNPC->npc = 4; $newNPC->npc = 4;
$newNPC->setMoney(1000, 1000); $newNPC->setMoney(1000, 1000);
$newNPC->setExpDed($avgGen['exp'], $avgGen['ded']); $newNPC->setExpDed($avgGen['exp'], $avgGen['ded']);
$newNPC->setDex( $newNPC->setDex(
$dexVal[0], $dexVal[0],
$dexVal[1], $dexVal[1],
$dexVal[2], $dexVal[2],
$dexVal[3], $dexVal[3],
$avgGen['dex5'] $avgGen['dex5']
); );
$newNPC->build($this->env); $newNPC->build($this->env);
} }
$gameStor->npccount = $lastCreatGenIdx; $gameStor->npccount = $lastCreatGenIdx;
$db->update('nation', [ $db->update('nation', [
'gennum' => $db->sqleval('gennum + %i', $createGenCnt), 'gennum' => $db->sqleval('gennum + %i', $createGenCnt),
'strategic_cmd_limit' => $this->getPostReqTurn() 'strategic_cmd_limit' => 12
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
} }
+250 -250
View File
@@ -1,250 +1,250 @@
<?php <?php
namespace sammo\Command\Nation; namespace sammo\Command\Nation;
use\sammo\{ use\sammo\{
DB, DB,
Util, Util,
JosaUtil, JosaUtil,
General, General,
DummyGeneral, DummyGeneral,
ActionLogger, ActionLogger,
GameConst, GameConst,
LastTurn, LastTurn,
GameUnitConst, GameUnitConst,
Command, Command,
Message, Message,
MessageTarget MessageTarget
}; };
use function\sammo\{ use function\sammo\{
getDomesticExpLevelBonus, getDomesticExpLevelBonus,
CriticalRatioDomestic, CriticalRatioDomestic,
CriticalScoreEx, CriticalScoreEx,
getAllNationStaticInfo, getAllNationStaticInfo,
getNationStaticInfo, getNationStaticInfo,
GetImageURL GetImageURL
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
class che_이호경식 extends Command\NationCommand class che_이호경식 extends Command\NationCommand
{ {
static protected $actionName = '이호경식'; static protected $actionName = '이호경식';
static public $reqArg = true; static public $reqArg = true;
protected function argTest(): bool protected function argTest(): bool
{ {
if ($this->arg === null) { if ($this->arg === null) {
return false; return false;
} }
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음 //NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if (!key_exists('destNationID', $this->arg)) { if (!key_exists('destNationID', $this->arg)) {
return false; return false;
} }
$destNationID = $this->arg['destNationID']; $destNationID = $this->arg['destNationID'];
if (!is_int($destNationID)) { if (!is_int($destNationID)) {
return false; return false;
} }
if ($destNationID < 1) { if ($destNationID < 1) {
return false; return false;
} }
$this->arg = [ $this->arg = [
'destNationID' => $destNationID 'destNationID' => $destNationID
]; ];
return true; return true;
} }
protected function init() protected function init()
{ {
$general = $this->generalObj; $general = $this->generalObj;
$env = $this->env; $env = $this->env;
$this->setCity(); $this->setCity();
$this->setNation(['strategic_cmd_limit']); $this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [ $this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
protected function initWithArg() protected function initWithArg()
{ {
$this->setDestNation($this->arg['destNationID'], null); $this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints = [ $this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(), ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyBetweenStatus( ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1], [0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.' '선포, 전쟁중인 상대국에게만 가능합니다.'
), ),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
public function getCommandDetailTitle(): string public function getCommandDetailTitle(): string
{ {
$name = $this->getName(); $name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1; $reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn(); $postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)"; return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
} }
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;
} }
public function getPostReqTurn(): int public function getPostReqTurn(): int
{ {
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit); $genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 16) * 10); $nextTerm = Util::round(sqrt($genCount * 16) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm); $nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm; return $nextTerm;
} }
public function getBrief(): string public function getBrief(): string
{ {
$commandName = $this->getName(); $commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name']; $destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}"; return "{$destNationName}】에 {$commandName}";
} }
public function run(): bool public function run(): bool
{ {
if (!$this->hasFullConditionMet()) { if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도'); throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
} }
$db = DB::db(); $db = DB::db();
$env = $this->env; $env = $this->env;
$general = $this->generalObj; $general = $this->generalObj;
$generalID = $general->getID(); $generalID = $general->getID();
$generalName = $general->getName(); $generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM); $date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year']; $year = $this->env['year'];
$month = $this->env['month']; $month = $this->env['month'];
$nation = $this->nation; $nation = $this->nation;
$nationID = $nation['nation']; $nationID = $nation['nation'];
$nationName = $nation['name']; $nationName = $nation['name'];
$destNation = $this->destNation; $destNation = $this->destNation;
$destNationID = $destNation['nation']; $destNationID = $destNation['nation'];
$destNationName = $destNation['name']; $destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이'); $josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이'); $josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName(); $commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을'); $josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger(); $logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>"); $logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1)); $general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1)); $general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다."; $broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) { foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month); $nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush(); $nationGeneralLogger->flush();
} }
$josaYiCommand = JosaUtil::pick($commandName, '이'); $josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다."; $broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($destNationGeneralList as $destNationGeneralID) { foreach ($destNationGeneralList as $destNationGeneralID) {
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month); $destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush(); $destNationGeneralLogger->flush();
} }
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month); $destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동"); $destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush(); $destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$db->update('nation', [ $db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn() 'strategic_cmd_limit' => 12
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
$db->update('diplomacy', [ $db->update('diplomacy', [
'term' => $db->sqleval('IF(`state`=0, %i, `term`+ %i)', 3, 3), 'term' => $db->sqleval('IF(`state`=0, %i, `term`+ %i)', 3, 3),
'state' => 1, 'state' => 1,
], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID); ], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg)); $this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
public function getJSFiles(): array public function getJSFiles(): array
{ {
return [ return [
'js/defaultSelectNationByMap.js' 'js/defaultSelectNationByMap.js'
]; ];
} }
public function getForm(): string public function getForm(): string
{ {
$generalObj = $this->generalObj; $generalObj = $this->generalObj;
$nationID = $generalObj->getNationID(); $nationID = $generalObj->getNationID();
$nationList = []; $nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn()); $testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach (getAllNationStaticInfo() as $destNation) { foreach (getAllNationStaticInfo() as $destNation) {
if ($destNation['nation'] == $nationID) { if ($destNation['nation'] == $nationID) {
continue; continue;
} }
$testTurn->setArg(['destNationID' => $destNation['nation']]); $testTurn->setArg(['destNationID' => $destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]); $testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]);
if ($testCommand->hasFullConditionMet()) { if ($testCommand->hasFullConditionMet()) {
$destNation['availableCommand'] = true; $destNation['availableCommand'] = true;
} else { } else {
$destNation['availableCommand'] = false; $destNation['availableCommand'] = false;
} }
$nationList[] = $destNation; $nationList[] = $destNation;
} }
ob_start(); ob_start();
?> ?>
<?= \sammo\getMapHtml() ?><br> <?= \sammo\getMapHtml() ?><br>
선택된 국가에 이호경식을 발동합니다.<br> 선택된 국가에 이호경식을 발동합니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br> 선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br> 상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 이호경식 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br> 배경색은 현재 이호경식 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'> <select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach ($nationList as $nation) : ?> <?php foreach ($nationList as $nation) : ?>
<option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option> <option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option>
<?php endforeach; ?> <?php endforeach; ?>
<input type=button id="commonSubmit" value="<?= $this->getName() ?>"> <input type=button id="commonSubmit" value="<?= $this->getName() ?>">
<?php <?php
return ob_get_clean(); return ob_get_clean();
} }
} }
@@ -95,9 +95,18 @@ class che_초토화 extends Command\NationCommand{
} }
public function getPostReqTurn():int{ public function getPostReqTurn():int{
//NOTE: 자체 postReqTurn 사용
return 24; return 24;
} }
public function getNextAvailable():?int{
return null;
}
public function setNextAvailable(?int $yearMonth=null){
return;
}
public function getCommandDetailTitle():string{ public function getCommandDetailTitle():string{
$name = $this->getName(); $name = $this->getName();
+256 -238
View File
@@ -1,239 +1,257 @@
<?php <?php
namespace sammo\Command\Nation; namespace sammo\Command\Nation;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, DummyGeneral, General, DummyGeneral,
ActionLogger, ActionLogger,
GameConst, GameConst,
LastTurn, LastTurn,
GameUnitConst, GameUnitConst,
Command, Command,
Message, MessageTarget Message, MessageTarget
}; };
use function \sammo\{ use function \sammo\{
getDomesticExpLevelBonus, buildNationCommandClass,
CriticalRatioDomestic, getDomesticExpLevelBonus,
CriticalScoreEx, CriticalRatioDomestic,
getAllNationStaticInfo, CriticalScoreEx,
getNationStaticInfo, getAllNationStaticInfo,
GetImageURL getNationStaticInfo,
}; GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_피장파장 extends Command\NationCommand{
static protected $actionName = '피장파장'; class che_피장파장 extends Command\NationCommand{
static public $reqArg = true; static protected $actionName = '피장파장';
static public $delayCnt = 60; static public $reqArg = true;
static public $delayCnt = 60;
protected function argTest():bool{
if($this->arg === null){ protected function argTest():bool{
return false; if($this->arg === null){
} return false;
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음 }
if(!key_exists('destNationID', $this->arg)){ //NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
return false; if(!key_exists('destNationID', $this->arg)){
} return false;
$destNationID = $this->arg['destNationID']; }
$destNationID = $this->arg['destNationID'];
if(!is_int($destNationID)){
return false; if(!is_int($destNationID)){
} return false;
if($destNationID < 1){ }
return false; if($destNationID < 1){
} return false;
}
$this->arg = [
'destNationID'=>$destNationID $this->arg = [
]; 'destNationID'=>$destNationID
return true; ];
} return true;
}
protected function init(){
$general = $this->generalObj; protected function init(){
$general = $this->generalObj;
$env = $this->env;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']); $this->setCity();
$this->setNation();
$this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(), $this->minConditionConstraints=[
ConstraintHelper::BeChief(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::BeChief(),
]; ];
} }
protected function initWithArg() protected function initWithArg()
{ {
$this->setDestNation($this->arg['destNationID'], null); $this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(), ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyBetweenStatus( ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1], [0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.' '선포, 전쟁중인 상대국에게만 가능합니다.'
), ),
ConstraintHelper::AvailableStrategicCommand(), ];
]; }
}
public function getCommandDetailTitle():string{
public function getCommandDetailTitle():string{ $name = $this->getName();
$name = $this->getName(); $reqTurn = $this->getPreReqTurn()+1;
$reqTurn = $this->getPreReqTurn()+1; $postReqTurn = $this->getPostReqTurn();
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}";
return "{$name}/{$reqTurn}턴(전략$postReqTurn)"; }
}
public function getCost():array{
public function getCost():array{ return [0, 0];
return [0, 0]; }
}
public function getPreReqTurn():int{
public function getPreReqTurn():int{ return 1;
return 2; }
}
public function getPostReqTurn():int{
public function getPostReqTurn():int{ return 0;
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit); }
$nextTerm = Util::round(sqrt($genCount*2)*10);
public function getBrief():string{
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm); $commandName = $this->getName();
return $nextTerm; $destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
} return "{$destNationName}】에 {$commandName}";
}
public function getBrief():string{
$commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name']; public function run():bool{
return "{$destNationName}】에 {$commandName}"; if(!$this->hasFullConditionMet()){
} throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
public function run():bool{ $db = DB::db();
if(!$this->hasFullConditionMet()){ $env = $this->env;
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
} $general = $this->generalObj;
$generalID = $general->getID();
$db = DB::db(); $generalName = $general->getName();
$env = $this->env; $date = $general->getTurnTime($general::TURNTIME_HM);
$general = $this->generalObj; $year = $this->env['year'];
$generalID = $general->getID(); $month = $this->env['month'];
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM); $nation = $this->nation;
$nationID = $nation['nation'];
$year = $this->env['year']; $nationName = $nation['name'];
$month = $this->env['month'];
$destNation = $this->destNation;
$nation = $this->nation; $destNationID = $destNation['nation'];
$nationID = $nation['nation']; $destNationName = $destNation['name'];
$nationName = $nation['name'];
$josaYi = JosaUtil::pick($generalName, '이');
$destNation = $this->destNation; $josaYiNation = JosaUtil::pick($nationName, '이');
$destNationID = $destNation['nation'];
$destNationName = $destNation['name']; $commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이'); $logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을'); $general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>"); $broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$general->addExperience(5 * ($this->getPreReqTurn() + 1)); $nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
$general->addDedication(5 * ($this->getPreReqTurn() + 1)); foreach($nationGeneralList as $nationGeneralID){
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다."; $nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); }
foreach($nationGeneralList as $nationGeneralID){
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month); $josaYiCommand = JosaUtil::pick($commandName, '이');
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush(); $broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
}
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
$josaYiCommand = JosaUtil::pick($commandName, '이'); foreach($destNationGeneralList as $destNationGeneralID){
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다."; $destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush();
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); }
foreach($destNationGeneralList as $destNationGeneralID){
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month); $destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationGeneralLogger->flush(); $destNationLogger->flush();
}
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush();
$general->applyDB($db);
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
return true;
$db->update('nation', [ }
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID); public function getJSFiles(): array
$db->update('nation', [ {
'strategic_cmd_limit' => $db->sqleval('strategic_cmd_limit + %i', static::$delayCnt) return [
], 'nation = %i', $destNationID); 'js/defaultSelectNationByMap.js'
];
$general->applyDB($db); }
return true; public function getForm(): string
} {
$generalObj = $this->generalObj;
public function getJSFiles(): array $nationID = $generalObj->getNationID();
{ $nationList = [];
return [ $testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
'js/defaultSelectNationByMap.js' foreach(getAllNationStaticInfo() as $destNation){
]; if($destNation['nation'] == $nationID){
} continue;
}
public function getForm(): string
{ $testTurn->setArg(['destNationID'=>$destNation['nation']]);
$generalObj = $this->generalObj; $testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID'=>$destNation['nation']]);
$nationID = $generalObj->getNationID(); if($testCommand->hasFullConditionMet()){
$nationList = []; $destNation['availableCommand'] = true;
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn()); }
foreach(getAllNationStaticInfo() as $destNation){ else{
if($destNation['nation'] == $nationID){ $destNation['availableCommand'] = false;
continue; }
}
$nationList[] = $destNation;
$testTurn->setArg(['destNationID'=>$destNation['nation']]); }
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID'=>$destNation['nation']]);
if($testCommand->hasFullConditionMet()){ $availableCommandTypeList = [];
$destNation['availableCommand'] = true; $currYearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
} foreach(GameConst::$availableChiefCommand['전략'] as $commandType){
else{ $cmd = buildNationCommandClass($commandType, $generalObj, $this->env, new LastTurn());
$destNation['availableCommand'] = false; if($cmd->getName() == $this->getName()){
} continue;
}
$nationList[] = $destNation; $cmdName = $cmd->getName();
} $available = true;
$nextAvailable = $cmd->getNextAvailable();
ob_start();
?> if($nextAvailable !== null && $currYearMonth < $cmd->getNextAvailable() - $cmd->getPreReqTurn()){
<?=\sammo\getMapHtml()?><br> $available = false;
선택된 국가에 피장파장을 발동합니다.<br> }
선포, 전쟁중인 상대국에만 가능합니다.<br> $availableCommandTypeList[$commandType] = [$cmdName, $available];
상대 국가를 목록에서 선택하세요.<br> }
배경색은 현재 피장파장 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'> ob_start();
<?php foreach($nationList as $nation): ?> ?>
<option <?=\sammo\getMapHtml()?><br>
value='<?=$nation['nation']?>' 선택된 국가에 피장파장을 발동합니다.<br>
style='color:<?=$nation['color']?>;<?=$nation['availableCommand']?'':'background-color:red;'?>' 지정한 전략을 상대국이 <?=static::$delayCnt?>턴 동안 사용할 수 없게됩니다.<br>
>【<?=$nation['name']?> 】</option> 선포, 전쟁중인 상대국에만 가능합니다.<br>
<?php endforeach; ?> 상대 국가를 목록에서 선택하세요.<br>
<input type=button id="commonSubmit" value="<?=$this->getName()?>"> 배경색은 현재 피장파장 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<?php <select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
return ob_get_clean(); <?php foreach($nationList as $nation): ?>
} <option
value='<?=$nation['nation']?>'
style='color:<?=$nation['color']?>;<?=$nation['availableCommand']?'':'background-color:red;'?>'
>【<?=$nation['name']?> 】</option>
<?php endforeach; ?>
<select class='formInput' name="commandType" id="commandType" size='1' style='color:white;background-color:black;'>
<?php foreach($availableCommandTypeList as $commandType=>[$cmdName, $cmdAvailable]):
/** @var \sammo\Command\NationCommand $cmdObj */
?>
<option
value='<?=$commandType?>'
style='color:white;<?=$cmdAvailable?'':'background-color:red;'?>'
>【<?=$cmdName?> 】</option>
<?php endforeach; ?>
</select>
<input type=button id="commonSubmit" value="<?=$this->getName()?>">
<?php
return ob_get_clean();
}
} }
+133 -133
View File
@@ -1,134 +1,134 @@
<?php <?php
namespace sammo\Command\Nation; namespace sammo\Command\Nation;
use \sammo\{ use \sammo\{
DB, Util, JosaUtil, DB, Util, JosaUtil,
General, DummyGeneral, General, DummyGeneral,
ActionLogger, ActionLogger,
GameConst, GameConst,
LastTurn, LastTurn,
GameUnitConst, GameUnitConst,
Command, Command,
MessageTarget, MessageTarget,
Message Message
}; };
use function \sammo\{ use function \sammo\{
getDomesticExpLevelBonus, getDomesticExpLevelBonus,
CriticalRatioDomestic, CriticalRatioDomestic,
CriticalScoreEx, CriticalScoreEx,
GetImageURL GetImageURL
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action; use sammo\Event\Action;
class che_필사즉생 extends Command\NationCommand{ class che_필사즉생 extends Command\NationCommand{
static protected $actionName = '필사즉생'; static protected $actionName = '필사즉생';
protected function argTest():bool{ protected function argTest():bool{
$this->arg = []; $this->arg = [];
return true; return true;
} }
protected function init(){ protected function init(){
$general = $this->generalObj; $general = $this->generalObj;
$env = $this->env; $env = $this->env;
$this->setCity(); $this->setCity();
$this->setNation(['strategic_cmd_limit']); $this->setNation(['strategic_cmd_limit']);
$this->fullConditionConstraints=[ $this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::AllowDiplomacyStatus($this->generalObj->getNationID(), [ ConstraintHelper::AllowDiplomacyStatus($this->generalObj->getNationID(), [
0 0
], '전쟁중이 아닙니다.'), ], '전쟁중이 아닙니다.'),
ConstraintHelper::AvailableStrategicCommand() ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn())
]; ];
} }
public function getCommandDetailTitle():string{ public function getCommandDetailTitle():string{
$name = $this->getName(); $name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1; $reqTurn = $this->getPreReqTurn()+1;
$postReqTurn = $this->getPostReqTurn(); $postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)"; return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
} }
public function getCost():array{ public function getCost():array{
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn():int{ public function getPreReqTurn():int{
return 2; return 2;
} }
public function getPostReqTurn():int{ public function getPostReqTurn():int{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit); $genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount*8)*10); $nextTerm = Util::round(sqrt($genCount*8)*10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm); $nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm; return $nextTerm;
} }
public function run():bool{ public function run():bool{
if(!$this->hasFullConditionMet()){ if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도'); throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
} }
$db = DB::db(); $db = DB::db();
$general = $this->generalObj; $general = $this->generalObj;
$generalID = $general->getID(); $generalID = $general->getID();
$generalName = $general->getName(); $generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM); $date = $general->getTurnTime($general::TURNTIME_HM);
$nationID = $general->getNationID(); $nationID = $general->getNationID();
$nationName = $this->nation['name']; $nationName = $this->nation['name'];
$logger = $general->getLogger(); $logger = $general->getLogger();
$logger->pushGeneralActionLog("필사즉생 발동! <1>$date</>"); $logger->pushGeneralActionLog("필사즉생 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1)); $general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1)); $general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이'); $josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동하였습니다."; $broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach(General::createGeneralObjListFromDB($targetGeneralList, ['train', 'atmos'], 1) as $targetGeneral){ foreach(General::createGeneralObjListFromDB($targetGeneralList, ['train', 'atmos'], 1) as $targetGeneral){
$targetGeneral->getLogger()->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $targetGeneral->getLogger()->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
if($targetGeneral->getVar('train') < 100){ if($targetGeneral->getVar('train') < 100){
$targetGeneral->setVar('train', 100); $targetGeneral->setVar('train', 100);
} }
if($targetGeneral->getVar('atmos') < 100){ if($targetGeneral->getVar('atmos') < 100){
$targetGeneral->setVar('atmos', 100); $targetGeneral->setVar('atmos', 100);
} }
$targetGeneral->applyDB($db); $targetGeneral->applyDB($db);
} }
if($general->getVar('train') < 100){ if($general->getVar('train') < 100){
$general->setVar('train', 100); $general->setVar('train', 100);
} }
if($general->getVar('atmos') < 100){ if($general->getVar('atmos') < 100){
$general->setVar('atmos', 100); $general->setVar('atmos', 100);
} }
$logger->pushGeneralHistoryLog('<M>필사즉생</>을 발동'); $logger->pushGeneralHistoryLog('<M>필사즉생</>을 발동');
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동");
$db->update('nation', [ $db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn() 'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0)); $this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
} }
+239 -239
View File
@@ -1,239 +1,239 @@
<?php <?php
namespace sammo\Command\Nation; namespace sammo\Command\Nation;
use\sammo\{ use\sammo\{
DB, DB,
Util, Util,
JosaUtil, JosaUtil,
General, General,
DummyGeneral, DummyGeneral,
ActionLogger, ActionLogger,
GameConst, GameConst,
LastTurn, LastTurn,
GameUnitConst, GameUnitConst,
Command, Command,
MessageTarget, MessageTarget,
Message, Message,
CityConst CityConst
}; };
use function\sammo\{ use function\sammo\{
getDomesticExpLevelBonus, getDomesticExpLevelBonus,
CriticalRatioDomestic, CriticalRatioDomestic,
CriticalScoreEx, CriticalScoreEx,
GetImageURL, GetImageURL,
getNationStaticInfo getNationStaticInfo
}; };
use \sammo\Constraint\Constraint; use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper; use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action; use sammo\Event\Action;
class che_허보 extends Command\NationCommand class che_허보 extends Command\NationCommand
{ {
static protected $actionName = '허보'; static protected $actionName = '허보';
static public $reqArg = true; static public $reqArg = true;
protected function argTest(): bool protected function argTest(): bool
{ {
if ($this->arg === null) { if ($this->arg === null) {
return false; return false;
} }
if (!key_exists('destCityID', $this->arg)) { if (!key_exists('destCityID', $this->arg)) {
return false; return false;
} }
if (CityConst::byID($this->arg['destCityID']) === null) { if (CityConst::byID($this->arg['destCityID']) === null) {
return false; return false;
} }
$destCityID = $this->arg['destCityID']; $destCityID = $this->arg['destCityID'];
$this->arg = [ $this->arg = [
'destCityID' => $destCityID, 'destCityID' => $destCityID,
]; ];
return true; return true;
} }
protected function init() protected function init()
{ {
$general = $this->generalObj; $general = $this->generalObj;
$env = $this->env; $env = $this->env;
$this->setCity(); $this->setCity();
$this->setNation(['strategic_cmd_limit']); $this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [ $this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
protected function initWithArg() protected function initWithArg()
{ {
$this->setDestCity($this->arg['destCityID']); $this->setDestCity($this->arg['destCityID']);
$this->setDestNation($this->destCity['nation']); $this->setDestNation($this->destCity['nation']);
$this->fullConditionConstraints = [ $this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(), ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(), ConstraintHelper::BeChief(),
ConstraintHelper::NotNeutralDestCity(), ConstraintHelper::NotNeutralDestCity(),
ConstraintHelper::NotOccupiedDestCity(), ConstraintHelper::NotOccupiedDestCity(),
ConstraintHelper::AllowDiplomacyBetweenStatus( ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1], [0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.' '선포, 전쟁중인 상대국에게만 가능합니다.'
), ),
ConstraintHelper::AvailableStrategicCommand(), ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
]; ];
} }
public function getCommandDetailTitle(): string public function getCommandDetailTitle(): string
{ {
$name = $this->getName(); $name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1; $reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn(); $postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)"; return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
} }
public function getCost(): array public function getCost(): array
{ {
return [0, 0]; return [0, 0];
} }
public function getPreReqTurn(): int public function getPreReqTurn(): int
{ {
return 1; return 1;
} }
public function getPostReqTurn(): int public function getPostReqTurn(): int
{ {
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit); $genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 4) * 10); $nextTerm = Util::round(sqrt($genCount * 4) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm); $nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm; return $nextTerm;
} }
public function getBrief(): string public function getBrief(): string
{ {
$commandName = $this->getName(); $commandName = $this->getName();
$destCityName = CityConst::byID($this->arg['destCityID'])->name; $destCityName = CityConst::byID($this->arg['destCityID'])->name;
return "{$destCityName}】에 {$commandName}"; return "{$destCityName}】에 {$commandName}";
} }
public function run(): bool public function run(): bool
{ {
if (!$this->hasFullConditionMet()) { if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도'); throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
} }
$db = DB::db(); $db = DB::db();
$general = $this->generalObj; $general = $this->generalObj;
$generalID = $general->getID(); $generalID = $general->getID();
$generalName = $general->getName(); $generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM); $date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year']; $year = $this->env['year'];
$month = $this->env['month']; $month = $this->env['month'];
$destCity = $this->destCity; $destCity = $this->destCity;
$destCityID = $destCity['city']; $destCityID = $destCity['city'];
$destCityName = $destCity['name']; $destCityName = $destCity['name'];
$destNationID = $destCity['nation']; $destNationID = $destCity['nation'];
$destNationName = getNationStaticInfo($destNationID)['name']; $destNationName = getNationStaticInfo($destNationID)['name'];
$nationID = $general->getNationID(); $nationID = $general->getNationID();
$nationName = $this->nation['name']; $nationName = $this->nation['name'];
$logger = $general->getLogger(); $logger = $general->getLogger();
$logger->pushGeneralActionLog("허보 발동! <1>$date</>"); $logger->pushGeneralActionLog("허보 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1)); $general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1)); $general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이'); $josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동하였습니다."; $broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID); $targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($targetGeneralList as $targetGeneralID) { foreach ($targetGeneralList as $targetGeneralID) {
$targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month); $targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month);
$targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN); $targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$targetLogger->flush(); $targetLogger->flush();
} }
$destBroadcastMessage = "상대의 <M>허보</>에 당했다! <1>$date</>"; $destBroadcastMessage = "상대의 <M>허보</>에 당했다! <1>$date</>";
$destNationCityList = $db->queryFirstColumn('SELECT city FROM city WHERE nation = %i AND supply = 1', $destNationID); $destNationCityList = $db->queryFirstColumn('SELECT city FROM city WHERE nation = %i AND supply = 1', $destNationID);
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND city=%i', $destNationID, $destCityID); $targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND city=%i', $destNationID, $destCityID);
foreach (General::createGeneralObjListFromDB($targetGeneralList) as $targetGeneralID => $targetGeneral) { foreach (General::createGeneralObjListFromDB($targetGeneralList) as $targetGeneralID => $targetGeneral) {
$targetLogger = $targetGeneral->getLogger(); $targetLogger = $targetGeneral->getLogger();
$targetLogger->pushGeneralActionLog($destBroadcastMessage, ActionLogger::PLAIN); $targetLogger->pushGeneralActionLog($destBroadcastMessage, ActionLogger::PLAIN);
$moveCityID = Util::choiceRandom($destNationCityList); $moveCityID = Util::choiceRandom($destNationCityList);
if ($moveCityID == $destCityID) { if ($moveCityID == $destCityID) {
//현재도시면 다시 랜덤 추첨 //현재도시면 다시 랜덤 추첨
$moveCityID = Util::choiceRandom($destNationCityList); $moveCityID = Util::choiceRandom($destNationCityList);
} }
$targetGeneral->setVar('city', $moveCityID); $targetGeneral->setVar('city', $moveCityID);
$targetGeneral->applyDB($db); $targetGeneral->applyDB($db);
} }
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month); $destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog( $destNationLogger->pushNationalHistoryLog(
"<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국의 <G><b>{$destCityName}</b></>에 <M>허보</>를 발동", "<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국의 <G><b>{$destCityName}</b></>에 <M>허보</>를 발동",
ActionLogger::PLAIN ActionLogger::PLAIN
); );
$destNationLogger->flush(); $destNationLogger->flush();
$db->update('city', [ $db->update('city', [
'def' => $db->sqleval('def * 0.2'), 'def' => $db->sqleval('def * 0.2'),
'wall' => $db->sqleval('wall * 0.2'), 'wall' => $db->sqleval('wall * 0.2'),
], 'city=%i', $destCityID); ], 'city=%i', $destCityID);
$josaYiNation = JosaUtil::pick($nationName, '이'); $josaYiNation = JosaUtil::pick($nationName, '이');
$logger->pushGeneralHistoryLog("<G><b>{$destCityName}</b></>에 <M>허보</>를 발동"); $logger->pushGeneralHistoryLog("<G><b>{$destCityName}</b></>에 <M>허보</>를 발동");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동"); $logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동");
$db->update('nation', [ $db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn() 'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID); ], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0)); $this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db); $general->applyDB($db);
return true; return true;
} }
public function getJSFiles(): array public function getJSFiles(): array
{ {
return [ return [
'js/defaultSelectCityByMap.js' 'js/defaultSelectCityByMap.js'
]; ];
} }
public function getForm(): string public function getForm(): string
{ {
ob_start(); ob_start();
?> ?>
<?= \sammo\getMapHtml() ?><br> <?= \sammo\getMapHtml() ?><br>
선택된 도시에 허보를 발동합니다.<br> 선택된 도시에 허보를 발동합니다.<br>
전쟁중인 상대국 도시만 가능합니다.<br> 전쟁중인 상대국 도시만 가능합니다.<br>
목록을 선택하거나 도시를 클릭하세요.<br> 목록을 선택하거나 도시를 클릭하세요.<br>
<select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'> <select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'>
<?= \sammo\optionsForCities() ?><br> <?= \sammo\optionsForCities() ?><br>
</select> <input type=button id="commonSubmit" value="<?= $this->getName() ?>"><br> </select> <input type=button id="commonSubmit" value="<?= $this->getName() ?>"><br>
<br> <br>
<?php <?php
return ob_get_clean(); return ob_get_clean();
} }
} }
+57 -29
View File
@@ -1,30 +1,58 @@
<?php <?php
namespace sammo\Command; namespace sammo\Command;
use \sammo\General; use \sammo\General;
use \sammo\LastTurn; use sammo\KVStorage;
use \sammo\LastTurn;
abstract class NationCommand extends BaseCommand{ use \sammo\Util;
protected $lastTurn;
protected $resultTurn; abstract class NationCommand extends BaseCommand{
protected $lastTurn;
public function __construct(General $generalObj, array $env, LastTurn $lastTurn, $arg = null){ protected $resultTurn;
$this->lastTurn = $lastTurn;
$this->resultTurn = $lastTurn->duplicate(); public function __construct(General $generalObj, array $env, LastTurn $lastTurn, $arg = null){
parent::__construct($generalObj, $env, $arg); $this->lastTurn = $lastTurn;
} $this->resultTurn = $lastTurn->duplicate();
parent::__construct($generalObj, $env, $arg);
public function getLastTurn():LastTurn{ }
return $this->lastTurn;
} public function getLastTurn():LastTurn{
return $this->lastTurn;
public function setResultTurn(LastTurn $lastTurn){ }
$this->resultTurn = $lastTurn;
} public function setResultTurn(LastTurn $lastTurn){
$this->resultTurn = $lastTurn;
public function getResultTurn():LastTurn{ }
return $this->resultTurn;
} public function getResultTurn():LastTurn{
return $this->resultTurn;
}
protected function getNextExecuteKey():string{
$turnKey = static::$actionName;
$executeKey = "next_execute_{$turnKey}";
return $executeKey;
}
public function getNextAvailable():?int{
if($this->isArgValid && !$this->getPostReqTurn()){
return null;
}
$db = \sammo\DB::db();
$nationStor = \sammo\KVStorage::getStorage($db, $this->getNationID(), 'nation_env');
return $nationStor->getValue($this->getNextExecuteKey());
}
public function setNextAvailable(?int $yearMonth=null){
if(!$this->getPostReqTurn()){
return;
}
if($yearMonth === null){
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']) + $this->getPostReqTurn();
}
$db = \sammo\DB::db();
$nationStor = \sammo\KVStorage::getStorage($db, $this->getNationID(), 'nation_env');
$nationStor->setValue($this->getNextExecuteKey(), $yearMonth);
}
}; };
@@ -1,32 +1,32 @@
<?php <?php
namespace sammo\Constraint; namespace sammo\Constraint;
class AvailableStrategicCommand extends Constraint{ class AvailableStrategicCommand extends Constraint{
const REQ_VALUES = Constraint::REQ_NATION; const REQ_VALUES = Constraint::REQ_NATION | Constraint::REQ_INT_ARG;
public function checkInputValues(bool $throwExeception=true):bool{ public function checkInputValues(bool $throwExeception=true):bool{
if(!parent::checkInputValues($throwExeception) && !$throwExeception){ if(!parent::checkInputValues($throwExeception) && !$throwExeception){
return false; return false;
} }
if(!key_exists('strategic_cmd_limit', $this->nation)){ if(!key_exists('strategic_cmd_limit', $this->nation)){
if(!$throwExeception){return false; } if(!$throwExeception){return false; }
throw new \InvalidArgumentException("require strategic_cmd_limit in nation"); throw new \InvalidArgumentException("require strategic_cmd_limit in nation");
} }
return true; return true;
} }
public function test():bool{ public function test():bool{
$this->checkInputValues(); $this->checkInputValues();
$this->tested = true; $this->tested = true;
if($this->nation['strategic_cmd_limit'] == 0){ if($this->nation['strategic_cmd_limit'] <= $this->arg){
return true; return true;
} }
$this->reason = "전략기한이 남았습니다."; $this->reason = "전략기한이 남았습니다.";
return false; return false;
} }
} }
+273 -273
View File
@@ -1,274 +1,274 @@
<?php <?php
namespace sammo\Constraint; namespace sammo\Constraint;
class ConstraintHelper{ class ConstraintHelper{
static function AdhocCallback(callable $callback):array{ static function AdhocCallback(callable $callback):array{
return [__FUNCTION__, $callback]; return [__FUNCTION__, $callback];
} }
static function AllowDiplomacyStatus(int $nationID, array $allowList, string $errMsg):array{ static function AllowDiplomacyStatus(int $nationID, array $allowList, string $errMsg):array{
return [__FUNCTION__, [$nationID, $allowList, $errMsg]]; return [__FUNCTION__, [$nationID, $allowList, $errMsg]];
} }
static function AllowDiplomacyBetweenStatus(array $allowDipCodeList, string $errMsg):array{ static function AllowDiplomacyBetweenStatus(array $allowDipCodeList, string $errMsg):array{
return [__FUNCTION__, [$allowDipCodeList, $errMsg]]; return [__FUNCTION__, [$allowDipCodeList, $errMsg]];
} }
static function AllowDiplomacyWithTerm(int $allowDipCode, int $allowMinTerm, string $errMsg):array{ static function AllowDiplomacyWithTerm(int $allowDipCode, int $allowMinTerm, string $errMsg):array{
return [__FUNCTION__, [$allowDipCode, $allowMinTerm, $errMsg]]; return [__FUNCTION__, [$allowDipCode, $allowMinTerm, $errMsg]];
} }
static function AllowJoinAction():array{ static function AllowJoinAction():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function AllowJoinDestNation(int $relYear):array{ static function AllowJoinDestNation(int $relYear):array{
return [__FUNCTION__, $relYear]; return [__FUNCTION__, $relYear];
} }
static function AllowRebellion():array{ static function AllowRebellion():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function AllowWar():array{ static function AllowWar():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function AlwaysFail(string $failMessage):array{ static function AlwaysFail(string $failMessage):array{
return [__FUNCTION__, $failMessage]; return [__FUNCTION__, $failMessage];
} }
static function AvailableRecruitCrewType(int $crewTypeID):array{ static function AvailableRecruitCrewType(int $crewTypeID):array{
return [__FUNCTION__, $crewTypeID]; return [__FUNCTION__, $crewTypeID];
} }
static function AvailableStrategicCommand():array{ static function AvailableStrategicCommand(int $allowTurnCnt=0):array{
return [__FUNCTION__]; return [__FUNCTION__, $allowTurnCnt];
} }
static function BattleGroundCity():array{ static function BattleGroundCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function BeChief():array{ static function BeChief():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function BeLord():array{ static function BeLord():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function BeNeutral():array{ static function BeNeutral():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function BeOpeningPart(int $relYear):array{ static function BeOpeningPart(int $relYear):array{
return [__FUNCTION__, $relYear]; return [__FUNCTION__, $relYear];
} }
static function CheckNationNameDuplicate(string $nationName):array{ static function CheckNationNameDuplicate(string $nationName):array{
return [__FUNCTION__, $nationName]; return [__FUNCTION__, $nationName];
} }
static function ConstructableCity():array{ static function ConstructableCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function DifferentNationDestGeneral():array{ static function DifferentNationDestGeneral():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function DifferentDestNation():array{ static function DifferentDestNation():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function DisallowDiplomacyBetweenStatus(array $disallowList):array{ static function DisallowDiplomacyBetweenStatus(array $disallowList):array{
return [__FUNCTION__, $disallowList]; return [__FUNCTION__, $disallowList];
} }
static function DisallowDiplomacyStatus(int $nationID, array $disallowList):array{ static function DisallowDiplomacyStatus(int $nationID, array $disallowList):array{
return [__FUNCTION__, [$nationID, $disallowList]]; return [__FUNCTION__, [$nationID, $disallowList]];
} }
static function ExistsAllowJoinNation(int $relYear, array $excludeNationList):array{ static function ExistsAllowJoinNation(int $relYear, array $excludeNationList):array{
return [__FUNCTION__, [$relYear, $excludeNationList]]; return [__FUNCTION__, [$relYear, $excludeNationList]];
} }
static function ExistsDestGeneral():array{ static function ExistsDestGeneral():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function ExistsDestNation():array{ static function ExistsDestNation():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function FriendlyDestGeneral():array{ static function FriendlyDestGeneral():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function HasRoute():array{ static function HasRoute():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function HasRouteWithEnemy():array{ static function HasRouteWithEnemy():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function MustBeNPC():array{ static function MustBeNPC():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function MustBeTroopLeader():array{ static function MustBeTroopLeader():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NearCity(int $distance):array{ static function NearCity(int $distance):array{
return [__FUNCTION__, $distance]; return [__FUNCTION__, $distance];
} }
static function NearNation():array{ static function NearNation():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NotBeNeutral():array{ static function NotBeNeutral():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NotCapital(bool $ignoreOfficer=false):array{ static function NotCapital(bool $ignoreOfficer=false):array{
return [__FUNCTION__, $ignoreOfficer]; return [__FUNCTION__, $ignoreOfficer];
} }
static function NotChief():array{ static function NotChief():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NotLord():array{ static function NotLord():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NotNeutralDestCity():array{ static function NotNeutralDestCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NotOccupiedDestCity():array{ static function NotOccupiedDestCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NotOpeningPart(int $relYear):array{ static function NotOpeningPart(int $relYear):array{
return [__FUNCTION__, $relYear]; return [__FUNCTION__, $relYear];
} }
static function NotSameDestCity():array{ static function NotSameDestCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function NotWanderingNation():array{ static function NotWanderingNation():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function OccupiedCity(bool $allowNeutral=false):array{ static function OccupiedCity(bool $allowNeutral=false):array{
return [__FUNCTION__, $allowNeutral]; return [__FUNCTION__, $allowNeutral];
} }
static function OccupiedDestCity():array{ static function OccupiedDestCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function RemainCityCapacity($key, string $actionName):array{ static function RemainCityCapacity($key, string $actionName):array{
return [__FUNCTION__, [$key, $actionName]]; return [__FUNCTION__, [$key, $actionName]];
} }
static function RemainCityTrust(string $actionName):array{ static function RemainCityTrust(string $actionName):array{
return [__FUNCTION__, $actionName]; return [__FUNCTION__, $actionName];
} }
static function ReqCityCapacity($key, string $keyNick, $reqVal):array{ static function ReqCityCapacity($key, string $keyNick, $reqVal):array{
return [__FUNCTION__, [$key, $keyNick, $reqVal]]; return [__FUNCTION__, [$key, $keyNick, $reqVal]];
} }
static function ReqCityTrust(float $minTrust):array{ static function ReqCityTrust(float $minTrust):array{
return [__FUNCTION__, $minTrust]; return [__FUNCTION__, $minTrust];
} }
static function ReqCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{ static function ReqCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]]; return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
} }
static function ReqDestCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{ static function ReqDestCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]]; return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
} }
static function ReqCityTrader(int $npcType):array{ static function ReqCityTrader(int $npcType):array{
return [__FUNCTION__, $npcType]; return [__FUNCTION__, $npcType];
} }
static function ReqDestNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{ static function ReqDestNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]]; return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
} }
static function ReqEnvValue($key, string $comp, $reqVal, string $failMessage):array{ static function ReqEnvValue($key, string $comp, $reqVal, string $failMessage):array{
return [__FUNCTION__, [$key, $comp, $reqVal, $failMessage]]; return [__FUNCTION__, [$key, $comp, $reqVal, $failMessage]];
} }
static function ReqGeneralAtmosMargin(int $maxAtmos):array{ static function ReqGeneralAtmosMargin(int $maxAtmos):array{
return [__FUNCTION__, $maxAtmos]; return [__FUNCTION__, $maxAtmos];
} }
static function ReqGeneralCrew():array{ static function ReqGeneralCrew():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function ReqGeneralCrewMargin(int $crewTypeID):array{ static function ReqGeneralCrewMargin(int $crewTypeID):array{
return [__FUNCTION__, $crewTypeID]; return [__FUNCTION__, $crewTypeID];
} }
static function ReqGeneralGold(int $reqGold):array{ static function ReqGeneralGold(int $reqGold):array{
return [__FUNCTION__, $reqGold]; return [__FUNCTION__, $reqGold];
} }
static function ReqGeneralRice(int $reqRice):array{ static function ReqGeneralRice(int $reqRice):array{
return [__FUNCTION__, $reqRice]; return [__FUNCTION__, $reqRice];
} }
static function ReqGeneralTrainMargin(int $maxTrain):array{ static function ReqGeneralTrainMargin(int $maxTrain):array{
return [__FUNCTION__, $maxTrain]; return [__FUNCTION__, $maxTrain];
} }
static function ReqGeneralValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{ static function ReqGeneralValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]]; return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
} }
static function ReqNationGold(int $reqGold):array{ static function ReqNationGold(int $reqGold):array{
return [__FUNCTION__, $reqGold]; return [__FUNCTION__, $reqGold];
} }
static function ReqNationRice(int $reqRice):array{ static function ReqNationRice(int $reqRice):array{
return [__FUNCTION__, $reqRice]; return [__FUNCTION__, $reqRice];
} }
static function ReqNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{ static function ReqNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]]; return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
} }
static function ReqNationAuxValue($key, $defaultValue, string $comp, $reqVal, string $errMsg):array{ static function ReqNationAuxValue($key, $defaultValue, string $comp, $reqVal, string $errMsg):array{
return [__FUNCTION__, [$key, $defaultValue, $comp, $reqVal, $errMsg]]; return [__FUNCTION__, [$key, $defaultValue, $comp, $reqVal, $errMsg]];
} }
static function ReqTroopMembers():array{ static function ReqTroopMembers():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function SuppliedCity():array{ static function SuppliedCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function SuppliedDestCity():array{ static function SuppliedDestCity():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
static function WanderingNation():array{ static function WanderingNation():array{
return [__FUNCTION__]; return [__FUNCTION__];
} }
} }
+280 -277
View File
@@ -1,278 +1,281 @@
<?php <?php
namespace sammo; namespace sammo;
class DiplomaticMessage extends Message{ class DiplomaticMessage extends Message{
const ACCEPTED = 1; const ACCEPTED = 1;
const DECLINED = -1; const DECLINED = -1;
const INVALID = 0; const INVALID = 0;
const TYPE_NO_AGGRESSION = 'noAggression'; //불가침 const TYPE_NO_AGGRESSION = 'noAggression'; //불가침
const TYPE_CANCEL_NA = 'cancelNA'; //불가침 파기 const TYPE_CANCEL_NA = 'cancelNA'; //불가침 파기
const TYPE_STOP_WAR = 'stopWar'; //종전 const TYPE_STOP_WAR = 'stopWar'; //종전
protected $diplomaticType = ''; protected $diplomaticType = '';
protected $diplomacyName = ''; protected $diplomacyName = '';
protected $diplomacyDetail = ''; protected $diplomacyDetail = '';
protected $validDiplomacy = true; protected $validDiplomacy = true;
public function __construct( public function __construct(
string $msgType, string $msgType,
MessageTarget $src, MessageTarget $src,
MessageTarget $dest, MessageTarget $dest,
string $msg, string $msg,
\DateTime $date, \DateTime $date,
\DateTime $validUntil, \DateTime $validUntil,
array $msgOption array $msgOption
) )
{ {
if ($msgType !== self::MSGTYPE_DIPLOMACY){ if ($msgType !== self::MSGTYPE_DIPLOMACY){
throw new \InvalidArgumentException('DiplomaticMessage msgType'); throw new \InvalidArgumentException('DiplomaticMessage msgType');
} }
$this->diplomaticType = Util::array_get($msgOption['action']); $this->diplomaticType = Util::array_get($msgOption['action']);
switch($this->diplomaticType){ switch($this->diplomaticType){
case self::TYPE_NO_AGGRESSION: $this->diplomacyName = '불가침'; break; case self::TYPE_NO_AGGRESSION: $this->diplomacyName = '불가침'; break;
case self::TYPE_CANCEL_NA: $this->diplomacyName = '불가침 파기'; break; case self::TYPE_CANCEL_NA: $this->diplomacyName = '불가침 파기'; break;
case self::TYPE_STOP_WAR: $this->diplomacyName = '종전'; break; case self::TYPE_STOP_WAR: $this->diplomacyName = '종전'; break;
default: throw new \RuntimeException('diplomaticType이 올바르지 않음'); default: throw new \RuntimeException('diplomaticType이 올바르지 않음');
} }
parent::__construct(...func_get_args()); parent::__construct(...func_get_args());
if(Util::array_get($msgOption['used'])){ if(Util::array_get($msgOption['used'])){
$this->validDiplomacy = false; $this->validDiplomacy = false;
} }
if($this->validUntil < (new \DateTime())){ if($this->validUntil < (new \DateTime())){
$this->validDiplomacy = false; $this->validDiplomacy = false;
} }
} }
protected function checkDiplomaticMessageValidation(array $general){ protected function checkDiplomaticMessageValidation(array $general){
if(!$this->validDiplomacy){ if(!$this->validDiplomacy){
return [self::INVALID, '유효하지 않은 외교서신입니다.']; return [self::INVALID, '유효하지 않은 외교서신입니다.'];
} }
if($this->mailbox !== $this->dest->nationID + static::MAILBOX_NATIONAL){ if($this->mailbox !== $this->dest->nationID + static::MAILBOX_NATIONAL){
return [self::INVALID, '송신자가 외교서신을 처리할 수 없습니다.']; return [self::INVALID, '송신자가 외교서신을 처리할 수 없습니다.'];
} }
$permission = checkSecretPermission($general, false); $permission = checkSecretPermission($general, false);
if(!$general || $permission < 4){ if(!$general || $permission < 4){
return [self::INVALID, '해당 국가의 외교권자가 아닙니다.']; return [self::INVALID, '해당 국가의 외교권자가 아닙니다.'];
} }
return [self::ACCEPTED, '']; return [self::ACCEPTED, ''];
} }
protected function noAggression(){ protected function noAggression(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env'); $gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1); $destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_불가침수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [ $commandObj = buildNationCommandClass('che_불가침수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID, 'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID, 'destGeneralID'=>$this->src->generalID,
'year'=>$this->msgOption['year'], 'year'=>$this->msgOption['year'],
'month'=>$this->msgOption['month'] 'month'=>$this->msgOption['month']
]); ]);
$this->diplomacyDetail = $commandObj->getBrief(); $this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){ if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()]; return [self::DECLINED, $commandObj->getFailString()];
} }
$commandObj->run(); $commandObj->run();
$commandObj->setNextAvailable();
return [self::ACCEPTED, ''];
} return [self::ACCEPTED, ''];
}
protected function cancelNA(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env'); protected function cancelNA(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_불가침파기수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID, $commandObj = buildNationCommandClass('che_불가침파기수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destGeneralID'=>$this->src->generalID, 'destNationID'=>$this->src->nationID,
]); 'destGeneralID'=>$this->src->generalID,
]);
$this->diplomacyDetail = $commandObj->getBrief();
$this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()]; if(!$commandObj->hasFullConditionMet()){
} return [self::DECLINED, $commandObj->getFailString()];
}
$commandObj->run();
$commandObj->run();
return [self::ACCEPTED, '']; $commandObj->setNextAvailable();
}
return [self::ACCEPTED, ''];
protected function stopWar(){ }
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
protected function stopWar(){
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1); $gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$commandObj = buildNationCommandClass('che_종전수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [ $destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID, $commandObj = buildNationCommandClass('che_종전수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
]); 'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
$this->diplomacyDetail = $commandObj->getBrief(); ]);
if(!$commandObj->hasFullConditionMet()){ $this->diplomacyDetail = $commandObj->getBrief();
return [self::DECLINED, $commandObj->getFailString()];
} if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()];
$commandObj->run(); }
return [self::ACCEPTED, '']; $commandObj->run();
} $commandObj->setNextAvailable();
/** return [self::ACCEPTED, ''];
* @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환 }
*/
public function agreeMessage(int $receiverID, string &$reason):int{ /**
//NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등) * @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환
*/
if(!$this->id){ public function agreeMessage(int $receiverID, string &$reason):int{
throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중'); //NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등)
}
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$general = $db->queryFirstRow( [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i',
$receiverID,
$this->dest->nationID $general = $db->queryFirstRow(
); 'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i',
$receiverID,
if($general){ $this->dest->nationID
$this->dest->generalID = $receiverID; );
$this->dest->generalName = $general['name'];
} if($general){
$this->dest->generalID = $receiverID;
$this->dest->generalName = $general['name'];
list($result, $reason) = $this->checkDiplomaticMessageValidation($general); }
if($result !== self::ACCEPTED){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 실패", ActionLogger::PLAIN);
if($result === self::DECLINED){ list($result, $reason) = $this->checkDiplomaticMessageValidation($general);
$this->_declineMessage(); if($result !== self::ACCEPTED){
} (new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 실패", ActionLogger::PLAIN);
return $result; if($result === self::DECLINED){
} $this->_declineMessage();
}
switch($this->diplomaticType){ return $result;
case self::TYPE_NO_AGGRESSION: }
list($result, $reason) = $this->noAggression();
break; switch($this->diplomaticType){
case self::TYPE_CANCEL_NA: case self::TYPE_NO_AGGRESSION:
list($result, $reason) = $this->cancelNA(); list($result, $reason) = $this->noAggression();
break; break;
case self::TYPE_STOP_WAR: case self::TYPE_CANCEL_NA:
list($result, $reason) = $this->stopWar(); list($result, $reason) = $this->cancelNA();
break; break;
default: case self::TYPE_STOP_WAR:
throw new \RuntimeException('diplomaticType이 올바르지 않음'); list($result, $reason) = $this->stopWar();
} break;
default:
if($result !== self::ACCEPTED){ throw new \RuntimeException('diplomaticType이 올바르지 않음');
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog($reason, ActionLogger::PLAIN); }
if($result === self::DECLINED){
$this->_declineMessage(); if($result !== self::ACCEPTED){
} (new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog($reason, ActionLogger::PLAIN);
return $result; if($result === self::DECLINED){
} $this->_declineMessage();
}
return $result;
}
$this->dest->generalID = $receiverID;
$this->dest->generalName = $general['name'];
$this->msgOption['used'] = true;
$this->validDiplomacy = false; $this->dest->generalID = $receiverID;
$this->dest->generalName = $general['name'];
$josaYi = JosaUtil::pick($this->src->nationName, '이'); $this->msgOption['used'] = true;
$newMsg = new Message( $this->validDiplomacy = false;
self::MSGTYPE_NATIONAL,
$this->dest, $josaYi = JosaUtil::pick($this->src->nationName, '이');
$this->src, $newMsg = new Message(
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}", self::MSGTYPE_NATIONAL,
new \DateTime(), $this->dest,
new \DateTime('9999-12-31'), $this->src,
[ "【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
'delete'=>$this->id, new \DateTime(),
'silence'=>true, new \DateTime('9999-12-31'),
'deletable' => false [
] 'delete'=>$this->id,
); 'silence'=>true,
$this->invalidate(); 'deletable' => false
$newMsg->send(); ]
);
$newMsg = new Message( $this->invalidate();
self::MSGTYPE_DIPLOMACY, $newMsg->send();
$this->dest,
$this->src, $newMsg = new Message(
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}", self::MSGTYPE_DIPLOMACY,
new \DateTime(), $this->dest,
new \DateTime('9999-12-31'), $this->src,
[ "【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
'delete'=>$this->id, new \DateTime(),
'silence'=>true, new \DateTime('9999-12-31'),
'deletable' => false [
] 'delete'=>$this->id,
); 'silence'=>true,
$newMsg->send(); 'deletable' => false
]
return self::ACCEPTED; );
$newMsg->send();
}
return self::ACCEPTED;
protected function _declineMessage(){
$this->msgOption['used'] = true; }
$this->invalidate();
$this->validDiplomacy = false; protected function _declineMessage(){
$this->msgOption['used'] = true;
return self::DECLINED; $this->invalidate();
} $this->validDiplomacy = false;
public function declineMessage(int $receiverID, string &$reason):int{ return self::DECLINED;
if(!$this->id){ }
throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중');
} public function declineMessage(int $receiverID, string &$reason):int{
if(!$this->id){
$db = DB::db(); throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중');
$gameStor = KVStorage::getStorage($db, 'game_env'); }
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$db = DB::db();
$general = $db->queryFirstRow( $gameStor = KVStorage::getStorage($db, 'game_env');
'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i', [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$receiverID,
$this->dest->nationID $general = $db->queryFirstRow(
); 'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i',
list($result, $reason) = $this->checkDiplomaticMessageValidation($general); $receiverID,
$this->dest->nationID
if($result === self::INVALID){ );
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 거절 불가.", ActionLogger::PLAIN); list($result, $reason) = $this->checkDiplomaticMessageValidation($general);
return $result;
} if($result === self::INVALID){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 거절 불가.", ActionLogger::PLAIN);
$josaYi = JosaUtil::pick($this->dest->nationName, '이'); return $result;
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("<D>{$this->src->nationName}</>의 {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN); }
(new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->nationName}</>{$josaYi} {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN);
$this->_declineMessage(); $josaYi = JosaUtil::pick($this->dest->nationName, '이');
return self::DECLINED; (new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("<D>{$this->src->nationName}</>의 {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN);
} (new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->nationName}</>{$josaYi} {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN);
$this->_declineMessage();
return self::DECLINED;
}
} }
+355 -355
View File
@@ -1,355 +1,355 @@
<?php <?php
namespace sammo; namespace sammo;
class GameConstBase class GameConstBase
{ {
/** @var string 게임명 */ /** @var string 게임명 */
public static $title = "삼국지 모의전투 PHP HiDCHe"; public static $title = "삼국지 모의전투 PHP HiDCHe";
/** @var string 코드 아래에 붙는 설명 코드 */ /** @var string 코드 아래에 붙는 설명 코드 */
public static $banner = "KOEI의 이미지를 사용, 응용하였습니다 / 제작 : HideD(hided62@gmail.com) / <a href='https://sam.hided.net/wiki/hidche/credit' target='_blank' style='color:white;text-decoration: underline;'>Credit</a>"; public static $banner = "KOEI의 이미지를 사용, 응용하였습니다 / 제작 : HideD(hided62@gmail.com) / <a href='https://sam.hided.net/wiki/hidche/credit' target='_blank' style='color:white;text-decoration: underline;'>Credit</a>";
/** @var string 사용중인 지도명 */ /** @var string 사용중인 지도명 */
public static $mapName = 'che'; public static $mapName = 'che';
/** @var string 사용중인 유닛셋 */ /** @var string 사용중인 유닛셋 */
public static $unitSet = 'che'; public static $unitSet = 'che';
/** @var int 내정시 최하 민심 설정*/ /** @var int 내정시 최하 민심 설정*/
public static $develrate = 50; public static $develrate = 50;
/** @var int 능력치 상승 경험치*/ /** @var int 능력치 상승 경험치*/
public static $upgradeLimit = 30; public static $upgradeLimit = 30;
/** @var int 숙련도 제한치*/ /** @var int 숙련도 제한치*/
public static $dexLimit = 1000000; public static $dexLimit = 1000000;
/** @var int 초기 징병 사기치*/ /** @var int 초기 징병 사기치*/
public static $defaultAtmosLow = 40; public static $defaultAtmosLow = 40;
/** @var int 초기 징병 훈련치*/ /** @var int 초기 징병 훈련치*/
public static $defaultTrainLow = 40; public static $defaultTrainLow = 40;
/** @var int 초기 모병 사기치*/ /** @var int 초기 모병 사기치*/
public static $defaultAtmosHigh = 70; public static $defaultAtmosHigh = 70;
/** @var int 초기 모병 훈련치*/ /** @var int 초기 모병 훈련치*/
public static $defaultTrainHigh = 70; public static $defaultTrainHigh = 70;
/** @var int 사기진작으로 올릴 수 있는 최대 사기치*/ /** @var int 사기진작으로 올릴 수 있는 최대 사기치*/
public static $maxAtmosByCommand = 100; public static $maxAtmosByCommand = 100;
/** @var int 훈련으로 올릴 수 있는 최대 사기치*/ /** @var int 훈련으로 올릴 수 있는 최대 사기치*/
public static $maxTrainByCommand = 100; public static $maxTrainByCommand = 100;
/** @var int 전투로 올릴 수 있는 최대 사기치*/ /** @var int 전투로 올릴 수 있는 최대 사기치*/
public static $maxAtmosByWar = 150; public static $maxAtmosByWar = 150;
/** @var int 전투로 올릴 수 훈련치*/ /** @var int 전투로 올릴 수 훈련치*/
public static $maxTrainByWar = 110; public static $maxTrainByWar = 110;
/** @var int 풀징병시 훈련 1회 상승량*/ /** @var int 풀징병시 훈련 1회 상승량*/
public static $trainDelta = 30; public static $trainDelta = 30;
/** @var int 풀징병시 훈련 1회 상승량*/ /** @var int 풀징병시 훈련 1회 상승량*/
public static $atmosDelta = 30; public static $atmosDelta = 30;
/** @var float 훈련시 사기 감소율*/ /** @var float 훈련시 사기 감소율*/
public static $atmosSideEffectByTraining = 1; public static $atmosSideEffectByTraining = 1;
/** @var float 사기시 훈련 감소율*/ /** @var float 사기시 훈련 감소율*/
public static $trainSideEffectByAtmosTurn = 1; public static $trainSideEffectByAtmosTurn = 1;
/** @var float 계략 기본 성공률*/ /** @var float 계략 기본 성공률*/
public static $sabotageDefaultProb = 0.35; public static $sabotageDefaultProb = 0.35;
/** @var int 계략시 확률 가중치(수치가 클수록 변화가 적음 : (지력차/$firing + $basefiring)*/ /** @var int 계략시 확률 가중치(수치가 클수록 변화가 적음 : (지력차/$firing + $basefiring)*/
public static $sabotageProbCoefByStat = 300; public static $sabotageProbCoefByStat = 300;
/** @var int 계략시 최소 수치 감소량*/ /** @var int 계략시 최소 수치 감소량*/
public static $sabotageDamageMin = 100; public static $sabotageDamageMin = 100;
/** @var int 계략시 최대 수치 감소량*/ /** @var int 계략시 최대 수치 감소량*/
public static $sabotageDamageMax = 500; public static $sabotageDamageMax = 500;
/** @var string 기본 배경색깔 푸른색*/ /** @var string 기본 배경색깔 푸른색*/
public static $basecolor = "#000044"; public static $basecolor = "#000044";
/** @var string 기본 배경색깔 초록색*/ /** @var string 기본 배경색깔 초록색*/
public static $basecolor2 = "#225500"; public static $basecolor2 = "#225500";
/** @var string 기본 배경색깔 붉은색*/ /** @var string 기본 배경색깔 붉은색*/
public static $basecolor3 = "#660000"; public static $basecolor3 = "#660000";
/** @var string 기본 배경색깔 검붉은색*/ /** @var string 기본 배경색깔 검붉은색*/
public static $basecolor4 = "#330000"; public static $basecolor4 = "#330000";
/** @var int 페이즈당 표준 감소 병사 수*/ /** @var int 페이즈당 표준 감소 병사 수*/
public static $armperphase = 500; public static $armperphase = 500;
/** @var int 기본 국고*/ /** @var int 기본 국고*/
public static $basegold = 0; public static $basegold = 0;
/** @var int 기본 병량*/ /** @var int 기본 병량*/
public static $baserice = 2000; public static $baserice = 2000;
/** @var int 최저 국고(긴급시) */ /** @var int 최저 국고(긴급시) */
public static $minNationalGold = 0; public static $minNationalGold = 0;
/** @var int 최저 병량(긴급시) */ /** @var int 최저 병량(긴급시) */
public static $minNationalRice = 0; public static $minNationalRice = 0;
/** @var float 군량 매매시 세율*/ /** @var float 군량 매매시 세율*/
public static $exchangeFee = 0.01; public static $exchangeFee = 0.01;
/** @var float 성인 연령 */ /** @var float 성인 연령 */
public static $adultAge = 14; public static $adultAge = 14;
/** @var float 명전 등록 가능 연령 */ /** @var float 명전 등록 가능 연령 */
public static $minPushHallAge = 40; public static $minPushHallAge = 40;
/** @var int 최대 계급 */ /** @var int 최대 계급 */
public static $maxDedLevel = 30; public static $maxDedLevel = 30;
/** @var int 최대 기술 레벨 */ /** @var int 최대 기술 레벨 */
public static $maxTechLevel = 12; public static $maxTechLevel = 12;
/** @var int 최대 하야 패널티 수 */ /** @var int 최대 하야 패널티 수 */
public static $maxBetrayCnt = 9; public static $maxBetrayCnt = 9;
/** @var int 최소 인구 증가량 */ /** @var int 최소 인구 증가량 */
public static $basePopIncreaseAmount = 5000; public static $basePopIncreaseAmount = 5000;
/** @var int 증축시 인구 증가량 */ /** @var int 증축시 인구 증가량 */
public static $expandCityPopIncreaseAmount = 100000; public static $expandCityPopIncreaseAmount = 100000;
/** @var int 증축시 내정 증가량 */ /** @var int 증축시 내정 증가량 */
public static $expandCityDevelIncreaseAmount = 2000; public static $expandCityDevelIncreaseAmount = 2000;
/** @var int 증축시 성벽 증가량 */ /** @var int 증축시 성벽 증가량 */
public static $expandCityWallIncreaseAmount = 2000; public static $expandCityWallIncreaseAmount = 2000;
/** @var int 증축시 최소 비용 */ /** @var int 증축시 최소 비용 */
public static $expandCityDefaultCost = 60000; public static $expandCityDefaultCost = 60000;
/** @var int 증축시 비용 계수 */ /** @var int 증축시 비용 계수 */
public static $expandCityCostCoef = 500; public static $expandCityCostCoef = 500;
/** @var int 징병 허용 최소 인구 */ /** @var int 징병 허용 최소 인구 */
public static $minAvailableRecruitPop = 30000; public static $minAvailableRecruitPop = 30000;
/** @var int 초기 제한시 장수 제한 */ /** @var int 초기 제한시 장수 제한 */
public static $initialNationGenLimitForRandInit = 3; public static $initialNationGenLimitForRandInit = 3;
/** @var int 초기 제한시 장수 제한 */ /** @var int 초기 제한시 장수 제한 */
public static $initialNationGenLimit = 10; public static $initialNationGenLimit = 10;
/** @var int 초기 최대 장수수 */ /** @var int 초기 최대 장수수 */
public static $defaultMaxGeneral = 500; public static $defaultMaxGeneral = 500;
/** @var int 초기 최대 국가 수 */ /** @var int 초기 최대 국가 수 */
public static $defaultMaxNation = 55; public static $defaultMaxNation = 55;
/** @var int 초기 최대 천재 수 */ /** @var int 초기 최대 천재 수 */
public static $defaultMaxGenius = 5; public static $defaultMaxGenius = 5;
/** @var int 초기 시작 년도. 실제 값은 시나리오에서 정해지므로 딱히 의미는 없음. */ /** @var int 초기 시작 년도. 실제 값은 시나리오에서 정해지므로 딱히 의미는 없음. */
public static $defaultStartYear = 180; public static $defaultStartYear = 180;
/** @var float 멸망한 NPC 장수의 임관 확률 */ /** @var float 멸망한 NPC 장수의 임관 확률 */
public static $joinRuinedNPCProp = 0.1; public static $joinRuinedNPCProp = 0.1;
/** @var int 시작시 금 */ /** @var int 시작시 금 */
public static $defaultGold = 1000; public static $defaultGold = 1000;
/** @var int 시작시 쌀 */ /** @var int 시작시 쌀 */
public static $defaultRice = 1000; public static $defaultRice = 1000;
/** @var int 원조 계수 */ /** @var int 원조 계수 */
public static $coefAidAmount = 10000; public static $coefAidAmount = 10000;
/** @var int 최대 개별 자원 금액 */ /** @var int 최대 개별 자원 금액 */
public static $maxResourceActionAmount = 10000; public static $maxResourceActionAmount = 10000;
/** @var int[] 포상/몰수 가이드 금액 */ /** @var int[] 포상/몰수 가이드 금액 */
public static $resourceActionAmountGuide = [ public static $resourceActionAmountGuide = [
100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
1200, 1500, 2000, 2500, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000 1200, 1500, 2000, 2500, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000
]; ];
public static $generalMinimumGold = 0; public static $generalMinimumGold = 0;
public static $generalMinimumRice = 500; public static $generalMinimumRice = 500;
/** @var int 최대 턴 */ /** @var int 최대 턴 */
public static $maxTurn = 30; public static $maxTurn = 30;
public static $maxChiefTurn = 12; public static $maxChiefTurn = 12;
public static $statGradeLevel = 5; public static $statGradeLevel = 5;
/** @var int 초반 제한 기간 */ /** @var int 초반 제한 기간 */
public static $openingPartYear = 3; public static $openingPartYear = 3;
/** @var int 거병,임관 제한 기간 */ /** @var int 거병,임관 제한 기간 */
public static $joinActionLimit = 12; public static $joinActionLimit = 12;
/** @var array 선택 가능한 국가 성향 */ /** @var array 선택 가능한 국가 성향 */
public static $availableNationType = [ public static $availableNationType = [
'che_도적', 'che_명가', 'che_음양가', 'che_종횡가', 'che_불가', 'che_오두미도', 'che_태평도', 'che_도가', 'che_도적', 'che_명가', 'che_음양가', 'che_종횡가', 'che_불가', 'che_오두미도', 'che_태평도', 'che_도가',
'che_묵가', 'che_덕가', 'che_병가', 'che_유가', 'che_법가' 'che_묵가', 'che_덕가', 'che_병가', 'che_유가', 'che_법가'
]; ];
/** @var array 기본 국가 성향 */ /** @var array 기본 국가 성향 */
public static $neutralNationType = 'che_중립'; public static $neutralNationType = 'che_중립';
/** @var string 기본 내정 특기 */ /** @var string 기본 내정 특기 */
public static $defaultSpecialDomestic = 'None'; public static $defaultSpecialDomestic = 'None';
/** @var array 선택 가능한 장수 내정 특기 */ /** @var array 선택 가능한 장수 내정 특기 */
public static $availableSpecialDomestic = [ public static $availableSpecialDomestic = [
'che_경작', 'che_상재', 'che_발명', 'che_축성', 'che_수비', 'che_통찰', 'che_인덕', 'che_귀모', 'che_경작', 'che_상재', 'che_발명', 'che_축성', 'che_수비', 'che_통찰', 'che_인덕', 'che_귀모',
]; ];
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 내정 특기 */ /** @var array 선택할 수 없으나 게임 내에 유효한 장수 내정 특기 */
public static $optionalSpecialDomestic = [ public static $optionalSpecialDomestic = [
'None', 'None',
]; ];
/** @var string 기본 전투 특기 */ /** @var string 기본 전투 특기 */
public static $defaultSpecialWar = 'None'; public static $defaultSpecialWar = 'None';
/** @var array 선택 가능한 장수 전투 특기 */ /** @var array 선택 가능한 장수 전투 특기 */
public static $availableSpecialWar = [ public static $availableSpecialWar = [
'che_귀병', 'che_신산', 'che_환술', 'che_집중', 'che_신중', 'che_반계', 'che_귀병', 'che_신산', 'che_환술', 'che_집중', 'che_신중', 'che_반계',
'che_보병', 'che_궁병', 'che_기병', 'che_공성', 'che_보병', 'che_궁병', 'che_기병', 'che_공성',
'che_돌격', 'che_무쌍', 'che_견고', 'che_위압', 'che_돌격', 'che_무쌍', 'che_견고', 'che_위압',
'che_저격', 'che_필살', 'che_징병', 'che_의술', 'che_격노', 'che_척사', 'che_저격', 'che_필살', 'che_징병', 'che_의술', 'che_격노', 'che_척사',
]; ];
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 전투 특기 */ /** @var array 선택할 수 없으나 게임 내에 유효한 장수 전투 특기 */
public static $optionalSpecialWar = [ public static $optionalSpecialWar = [
'None', 'None',
]; ];
/** @var string 기본 성향(공용) */ /** @var string 기본 성향(공용) */
public static $neutralPersonality = 'None'; public static $neutralPersonality = 'None';
/** @var array 선택 가능한 성향 */ /** @var array 선택 가능한 성향 */
public static $availablePersonality = [ public static $availablePersonality = [
'che_안전', 'che_유지', 'che_재간', 'che_출세', 'che_할거', 'che_정복', 'che_안전', 'che_유지', 'che_재간', 'che_출세', 'che_할거', 'che_정복',
'che_패권', 'che_의협', 'che_대의', 'che_왕좌' 'che_패권', 'che_의협', 'che_대의', 'che_왕좌'
]; ];
/** @var array 존재하는 모든 성향 */ /** @var array 존재하는 모든 성향 */
public static $optionalPersonality = [ public static $optionalPersonality = [
'che_은둔', 'None' 'che_은둔', 'None'
]; ];
public static $allItems = [ public static $allItems = [
'horse' => [ 'horse' => [
'che_명마_01_노기'=>0, 'che_명마_02_조랑'=>0, 'che_명마_03_노새'=>0, 'che_명마_01_노기'=>0, 'che_명마_02_조랑'=>0, 'che_명마_03_노새'=>0,
'che_명마_04_나귀'=>0, 'che_명마_05_갈색마'=>0, 'che_명마_06_흑색마'=>0, 'che_명마_04_나귀'=>0, 'che_명마_05_갈색마'=>0, 'che_명마_06_흑색마'=>0,
'che_명마_07_백마'=>2, 'che_명마_07_기주마'=>2, 'che_명마_07_백마'=>2, 'che_명마_07_기주마'=>2,
'che_명마_08_양주마'=>2, 'che_명마_09_과하마'=>2, 'che_명마_08_양주마'=>2, 'che_명마_09_과하마'=>2,
'che_명마_10_대완마'=>2, 'che_명마_11_서량마'=>2, 'che_명마_10_대완마'=>2, 'che_명마_11_서량마'=>2,
'che_명마_12_사륜거'=>2, 'che_명마_13_절영'=>1, 'che_명마_13_적로'=>1, 'che_명마_12_사륜거'=>2, 'che_명마_13_절영'=>1, 'che_명마_13_적로'=>1,
'che_명마_14_적란마'=>1, 'che_명마_14_조황비전'=>1, 'che_명마_15_한혈마'=>1, 'che_명마_15_적토마'=>1, 'che_명마_14_적란마'=>1, 'che_명마_14_조황비전'=>1, 'che_명마_15_한혈마'=>1, 'che_명마_15_적토마'=>1,
], ],
'weapon' => [ 'weapon' => [
'che_무기_01_단도'=>0, 'che_무기_02_단궁'=>0, 'che_무기_03_단극'=>0, 'che_무기_01_단도'=>0, 'che_무기_02_단궁'=>0, 'che_무기_03_단극'=>0,
'che_무기_04_목검'=>0, 'che_무기_05_죽창'=>0, 'che_무기_06_소부'=>0, 'che_무기_04_목검'=>0, 'che_무기_05_죽창'=>0, 'che_무기_06_소부'=>0,
'che_무기_07_동추'=>1, 'che_무기_07_철편'=>1, 'che_무기_07_철쇄'=>1, 'che_무기_07_맥궁'=>1, 'che_무기_07_동추'=>1, 'che_무기_07_철편'=>1, 'che_무기_07_철쇄'=>1, 'che_무기_07_맥궁'=>1,
'che_무기_08_유성추'=>1, 'che_무기_08_철질여골'=>1, 'che_무기_09_쌍철극'=>1, 'che_무기_09_동호비궁'=>1, 'che_무기_10_삼첨도'=>1, 'che_무기_10_대부'=>1, 'che_무기_11_고정도'=>1, 'che_무기_11_이광궁'=>1, 'che_무기_12_철척사모'=>1, 'che_무기_12_칠성검'=>1, 'che_무기_13_사모'=>1, 'che_무기_13_양유기궁'=>1, 'che_무기_08_유성추'=>1, 'che_무기_08_철질여골'=>1, 'che_무기_09_쌍철극'=>1, 'che_무기_09_동호비궁'=>1, 'che_무기_10_삼첨도'=>1, 'che_무기_10_대부'=>1, 'che_무기_11_고정도'=>1, 'che_무기_11_이광궁'=>1, 'che_무기_12_철척사모'=>1, 'che_무기_12_칠성검'=>1, 'che_무기_13_사모'=>1, 'che_무기_13_양유기궁'=>1,
'che_무기_14_언월도'=>1, 'che_무기_14_방천화극'=>1, 'che_무기_15_청홍검'=>1, 'che_무기_15_의천검'=>1 'che_무기_14_언월도'=>1, 'che_무기_14_방천화극'=>1, 'che_무기_15_청홍검'=>1, 'che_무기_15_의천검'=>1
], ],
'book' => [ 'book' => [
'che_서적_01_효경전'=>0, 'che_서적_02_회남자'=>0, 'che_서적_03_변도론'=>0, 'che_서적_01_효경전'=>0, 'che_서적_02_회남자'=>0, 'che_서적_03_변도론'=>0,
'che_서적_04_건상역주'=>0, 'che_서적_05_여씨춘추'=>0, 'che_서적_06_사민월령'=>0, 'che_서적_04_건상역주'=>0, 'che_서적_05_여씨춘추'=>0, 'che_서적_06_사민월령'=>0,
'che_서적_07_위료자'=>1, 'che_서적_07_사마법'=>1, 'che_서적_07_한서'=>1, 'che_서적_07_논어'=>1, 'che_서적_07_위료자'=>1, 'che_서적_07_사마법'=>1, 'che_서적_07_한서'=>1, 'che_서적_07_논어'=>1,
'che_서적_08_전론'=>1, 'che_서적_08_사기'=>1, 'che_서적_09_장자'=>1, 'che_서적_09_역경'=>1, 'che_서적_08_전론'=>1, 'che_서적_08_사기'=>1, 'che_서적_09_장자'=>1, 'che_서적_09_역경'=>1,
'che_서적_10_시경'=>1, 'che_서적_10_구국론'=>1, 'che_서적_11_상군서'=>1, 'che_서적_11_춘추전'=>1, 'che_서적_10_시경'=>1, 'che_서적_10_구국론'=>1, 'che_서적_11_상군서'=>1, 'che_서적_11_춘추전'=>1,
'che_서적_12_산해경'=>1, 'che_서적_12_맹덕신서'=>1, 'che_서적_13_관자'=>1, 'che_서적_13_병법24편'=>1, 'che_서적_12_산해경'=>1, 'che_서적_12_맹덕신서'=>1, 'che_서적_13_관자'=>1, 'che_서적_13_병법24편'=>1,
'che_서적_14_한비자'=>1, 'che_서적_14_오자병법'=>1, 'che_서적_15_노자'=>1, 'che_서적_15_손자병법'=>1, 'che_서적_14_한비자'=>1, 'che_서적_14_오자병법'=>1, 'che_서적_15_노자'=>1, 'che_서적_15_손자병법'=>1,
], ],
'item' => [ 'item' => [
'che_치료_환약'=>0, 'che_저격_수극'=>0, 'che_사기_탁주'=>0, 'che_치료_환약'=>0, 'che_저격_수극'=>0, 'che_사기_탁주'=>0,
'che_훈련_청주'=>0, 'che_계략_이추'=>0, 'che_계략_향낭'=>0, 'che_훈련_청주'=>0, 'che_계략_이추'=>0, 'che_계략_향낭'=>0,
'che_치료_오석산'=>1, 'che_치료_무후행군'=>1, 'che_치료_도소연명'=>1, 'che_치료_오석산'=>1, 'che_치료_무후행군'=>1, 'che_치료_도소연명'=>1,
'che_치료_칠엽청점'=>1, 'che_치료_정력견혈'=>1, 'che_치료_칠엽청점'=>1, 'che_치료_정력견혈'=>1,
'che_훈련_과실주'=>1, 'che_훈련_이강주'=>1, 'che_훈련_과실주'=>1, 'che_훈련_이강주'=>1,
'che_사기_의적주'=>1, 'che_사기_두강주'=>1, 'che_사기_보령압주'=>1, 'che_사기_의적주'=>1, 'che_사기_두강주'=>1, 'che_사기_보령압주'=>1,
'che_훈련_철벽서'=>1, 'che_훈련_단결도'=>1, 'che_사기_춘화첩'=>1, 'che_사기_초선화'=>1, 'che_훈련_철벽서'=>1, 'che_훈련_단결도'=>1, 'che_사기_춘화첩'=>1, 'che_사기_초선화'=>1,
'che_계략_육도'=>1, 'che_계략_삼략'=>1, 'che_계략_육도'=>1, 'che_계략_삼략'=>1,
'che_의술_청낭서'=>1, 'che_의술_태평청령'=>1, 'che_의술_청낭서'=>1, 'che_의술_태평청령'=>1,
'che_회피_태평요술'=>1, 'che_회피_둔갑천서'=>1, 'che_회피_태평요술'=>1, 'che_회피_둔갑천서'=>1,
] ]
]; ];
/** @var array 선택 가능한 커맨드 */ /** @var array 선택 가능한 커맨드 */
public static $availableGeneralCommand = [ public static $availableGeneralCommand = [
''=>[ ''=>[
'휴식', '휴식',
'che_요양' 'che_요양'
], ],
'내정'=>[ '내정'=>[
'che_농지개간', 'che_농지개간',
'che_상업투자', 'che_상업투자',
'che_기술연구', 'che_기술연구',
'che_수비강화', 'che_수비강화',
'che_성벽보수', 'che_성벽보수',
'che_치안강화', 'che_치안강화',
'che_정착장려', 'che_정착장려',
'che_주민선정', 'che_주민선정',
'che_물자조달', 'che_물자조달',
], ],
'군사'=>[ '군사'=>[
'che_소집해제', 'che_소집해제',
'che_첩보', 'che_첩보',
'che_징병', 'che_징병',
'che_모병', 'che_모병',
'che_훈련', 'che_훈련',
'che_사기진작', 'che_사기진작',
'che_출병', 'che_출병',
], ],
'인사'=>[ '인사'=>[
'che_이동', 'che_이동',
'che_강행', 'che_강행',
'che_인재탐색', 'che_인재탐색',
'che_등용', 'che_등용',
'che_집합', 'che_집합',
'che_귀환', 'che_귀환',
'che_임관', 'che_임관',
'che_랜덤임관', 'che_랜덤임관',
'che_장수대상임관', 'che_장수대상임관',
], ],
'계략'=>[ '계략'=>[
'che_화계', 'che_화계',
'che_파괴', 'che_파괴',
'che_탈취', 'che_탈취',
'che_선동', 'che_선동',
], ],
'개인'=>[ '개인'=>[
'che_내정특기초기화', 'che_내정특기초기화',
'che_전투특기초기화', 'che_전투특기초기화',
'che_단련', 'che_단련',
'che_숙련전환', 'che_숙련전환',
'che_견문', 'che_견문',
'che_장비매매', 'che_장비매매',
'che_군량매매', 'che_군량매매',
'che_증여', 'che_증여',
'che_헌납', 'che_헌납',
'che_하야', 'che_하야',
'che_거병', 'che_거병',
'che_건국', 'che_건국',
'che_선양', 'che_선양',
'che_방랑', 'che_방랑',
'che_해산', 'che_해산',
'che_모반시도', 'che_모반시도',
] ]
]; ];
/** @var array 선택 가능한 커맨드 */ /** @var array 선택 가능한 커맨드 */
public static $availableChiefCommand = [ public static $availableChiefCommand = [
'휴식'=>[ '휴식'=>[
'휴식', '휴식',
], ],
'인사'=>[ '인사'=>[
'che_발령', 'che_발령',
'che_포상', 'che_포상',
'che_몰수', 'che_몰수',
], ],
'외교'=>[ '외교'=>[
'che_물자원조', 'che_물자원조',
'che_불가침제의', 'che_불가침제의',
'che_선전포고', 'che_선전포고',
'che_종전제의', 'che_종전제의',
'che_불가침파기제의', 'che_불가침파기제의',
], ],
'특수'=>[ '특수'=>[
'che_초토화', 'che_초토화',
'che_천도', 'che_천도',
'che_증축', 'che_증축',
'che_감축', 'che_감축',
], ],
'전략'=>[ '전략'=>[
'che_필사즉생', 'che_피장파장',
'che_백성동원', 'che_필사즉생',
'che_수몰', 'che_백성동원',
'che_허보', 'che_수몰',
'che_피장파장', 'che_허보',
'che_의병모집', 'che_의병모집',
'che_이호경식', 'che_이호경식',
'che_급습', 'che_급습',
], ],
'기타'=>[ '기타'=>[
'che_국기변경', 'che_국기변경',
'che_국호변경', 'che_국호변경',
] ]
]; ];
public static $retirementYear = 80; public static $retirementYear = 80;
public static $randGenFirstName = [ public static $randGenFirstName = [
'가', '간', '감', '강', '고', '공', '공손', '곽', '관', '괴', '교', '금', '노', '뇌', '능', '도', '동', '두', '가', '간', '감', '강', '고', '공', '공손', '곽', '관', '괴', '교', '금', '노', '뇌', '능', '도', '동', '두',
'등', '마', '맹', '문', '미', '반', '방', '부', '비', '사', '사마', '서', '설', '성', '소', '손', '송', '순', '등', '마', '맹', '문', '미', '반', '방', '부', '비', '사', '사마', '서', '설', '성', '소', '손', '송', '순',
'신', '심', '악', '안', '양', '엄', '여', '염', '오', '왕', '요', '우', '원', '위', '유', '육', '윤', '이', '신', '심', '악', '안', '양', '엄', '여', '염', '오', '왕', '요', '우', '원', '위', '유', '육', '윤', '이',
'장', '저', '전', '정', '제갈', '조', '종', '주', '진', '채', '태사', '하', '하후', '학', '한', '향', '허', '장', '저', '전', '정', '제갈', '조', '종', '주', '진', '채', '태사', '하', '하후', '학', '한', '향', '허',
'호', '화', '황', '공손', '손', '왕', '유', '장', '조' '호', '화', '황', '공손', '손', '왕', '유', '장', '조'
]; ];
public static $randGenMiddleName = ['']; public static $randGenMiddleName = [''];
public static $randGenLastName = [ public static $randGenLastName = [
'가', '간', '강', '거', '건', '검', '견', '경', '공', '광', '권', '규', '녕', '단', '대', '도', '등', '람', '가', '간', '강', '거', '건', '검', '견', '경', '공', '광', '권', '규', '녕', '단', '대', '도', '등', '람',
'량', '례', '로', '료', '모', '민', '박', '범', '보', '비', '사', '상', '색', '서', '소', '속', '송', '수', '량', '례', '로', '료', '모', '민', '박', '범', '보', '비', '사', '상', '색', '서', '소', '속', '송', '수',
'순', '습', '승', '양', '연', '영', '온', '옹', '완', '우', '웅', '월', '위', '유', '윤', '융', '이', '익', '순', '습', '승', '양', '연', '영', '온', '옹', '완', '우', '웅', '월', '위', '유', '윤', '융', '이', '익',
'임', '정', '제', '조', '주', '준', '지', '찬', '책', '충', '탁', '택', '통', '패', '평', '포', '합', '해', '임', '정', '제', '조', '주', '준', '지', '찬', '책', '충', '탁', '택', '통', '패', '평', '포', '합', '해',
'혁', '현', '화', '환', '회', '횡', '후', '훈', '휴', '흠', '흥' '혁', '현', '화', '환', '회', '횡', '후', '훈', '휴', '흠', '흥'
]; ];
} }
+3
View File
@@ -132,6 +132,9 @@ class ResetHelper{
$gameStor->resetValues(); $gameStor->resetValues();
$gameStor->next_season_idx = $seasonIdx; $gameStor->next_season_idx = $seasonIdx;
$lastExecuteStor = KVStorage::getStorage($db, 'next_execute');
$lastExecuteStor->resetValues();
return [ return [
'result'=>true, 'result'=>true,
'serverID'=>$serverID, 'serverID'=>$serverID,
+227 -226
View File
@@ -1,227 +1,228 @@
<?php <?php
namespace sammo; namespace sammo;
class ScoutMessage extends Message{ class ScoutMessage extends Message{
const ACCEPTED = 1; const ACCEPTED = 1;
const DECLINED = -1; const DECLINED = -1;
const INVALID = 0; const INVALID = 0;
protected $validScout = true; protected $validScout = true;
public function __construct( public function __construct(
string $msgType, string $msgType,
MessageTarget $src, MessageTarget $src,
MessageTarget $dest, MessageTarget $dest,
string $msg, string $msg,
\DateTime $date, \DateTime $date,
\DateTime $validUntil, \DateTime $validUntil,
array $msgOption array $msgOption
) )
{ {
if ($msgType !== self::MSGTYPE_PRIVATE){ if ($msgType !== self::MSGTYPE_PRIVATE){
throw new \InvalidArgumentException('DiplomaticMessage msgType'); throw new \InvalidArgumentException('DiplomaticMessage msgType');
} }
if(Util::array_get($msgOption['action']) !== 'scout'){ if(Util::array_get($msgOption['action']) !== 'scout'){
throw new \InvalidArgumentException('Action !== scout'); throw new \InvalidArgumentException('Action !== scout');
} }
parent::__construct(...func_get_args()); parent::__construct(...func_get_args());
if(Util::array_get($msgOption['used'])){ if(Util::array_get($msgOption['used'])){
$this->validScout = false; $this->validScout = false;
} }
if($this->validUntil <= new \DateTime()){ if($this->validUntil <= new \DateTime()){
$this->validScout = false; $this->validScout = false;
} }
} }
protected function checkScoutMessageValidation(int $receiverID){ protected function checkScoutMessageValidation(int $receiverID){
if(!$this->validScout){ if(!$this->validScout){
return [self::INVALID, '유효하지 않은 등용장입니다.']; return [self::INVALID, '유효하지 않은 등용장입니다.'];
} }
if($this->mailbox !== $this->dest->generalID){ if($this->mailbox !== $this->dest->generalID){
return [self::INVALID, '송신자가 등용장을 처리할 수 없습니다.']; return [self::INVALID, '송신자가 등용장을 처리할 수 없습니다.'];
} }
if($this->mailbox !== $receiverID){ if($this->mailbox !== $receiverID){
return [self::INVALID, '올바른 수신자가 아닙니다.']; return [self::INVALID, '올바른 수신자가 아닙니다.'];
} }
return [self::ACCEPTED, '성공']; return [self::ACCEPTED, '성공'];
} }
/** /**
* @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환 * @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환
*/ */
public function agreeMessage(int $receiverID, string &$reason):int{ public function agreeMessage(int $receiverID, string &$reason):int{
//NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등) //NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등)
if(!$this->id){ if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중'); throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중');
} }
$gameStor = KVStorage::getStorage(DB::db(), 'game_env'); $gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$general = \sammo\General::createGeneralObjFromDB($receiverID, null, 2); $general = \sammo\General::createGeneralObjFromDB($receiverID, null, 2);
$logger = $general->getLogger(); $logger = $general->getLogger();
list($result, $reason) = $this->checkScoutMessageValidation($receiverID); list($result, $reason) = $this->checkScoutMessageValidation($receiverID);
if($result !== self::ACCEPTED){ if($result !== self::ACCEPTED){
$logger->pushGeneralActionLog("{$reason} 등용 수락 불가."); $logger->pushGeneralActionLog("{$reason} 등용 수락 불가.");
if($result === self::DECLINED){ if($result === self::DECLINED){
$this->_declineMessage(); $this->_declineMessage();
} }
return $result; return $result;
} }
$commandObj = buildGeneralCommandClass('che_등용수락', $general, $gameStor->getAll(true), [ $commandObj = buildGeneralCommandClass('che_등용수락', $general, $gameStor->getAll(true), [
'destNationID'=>$this->src->nationID, 'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID, 'destGeneralID'=>$this->src->generalID,
]); ]);
if(!$commandObj->hasFullConditionMet()){ if(!$commandObj->hasFullConditionMet()){
$logger->pushGeneralActionLog($commandObj->getFailString()); $logger->pushGeneralActionLog($commandObj->getFailString());
$reason = $commandObj->getFailString(); $reason = $commandObj->getFailString();
return self::DECLINED; return self::DECLINED;
} }
$commandObj->run(); $commandObj->run();
$commandObj->setNextAvailable();
//메시지 비 활성화
$this->msgOption['used'] = true; //메시지 비 활성화
$this->invalidate(); $this->msgOption['used'] = true;
$this->validScout = false; $this->invalidate();
$this->validScout = false;
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$newMsg = new Message( $josaRo = JosaUtil::pick($this->src->nationName, '로');
self::MSGTYPE_PRIVATE, $newMsg = new Message(
$this->src, self::MSGTYPE_PRIVATE,
$this->dest, $this->src,
"{$this->src->nationName}{$josaRo} 등용 제의 수락", $this->dest,
new \DateTime(), "{$this->src->nationName}{$josaRo} 등용 제의 수락",
new \DateTime('9999-12-31'), new \DateTime(),
[ new \DateTime('9999-12-31'),
'delete'=>$this->id [
] 'delete'=>$this->id
); ]
$newMsg->send(true); );
$newMsg->send(true);
return self::ACCEPTED;
} return self::ACCEPTED;
}
protected function _declineMessage(){
$this->msgOption['used'] = true; protected function _declineMessage(){
$this->invalidate(); $this->msgOption['used'] = true;
$this->validScout = false; $this->invalidate();
$this->validScout = false;
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$newMsg = new Message( $josaRo = JosaUtil::pick($this->src->nationName, '로');
self::MSGTYPE_PRIVATE, $newMsg = new Message(
$this->src, self::MSGTYPE_PRIVATE,
$this->dest, $this->src,
"{$this->src->nationName}{$josaRo} 등용 제의 거부", $this->dest,
new \DateTime(), "{$this->src->nationName}{$josaRo} 등용 제의 거부",
new \DateTime('9999-12-31'), new \DateTime(),
[ new \DateTime('9999-12-31'),
'delete'=>$this->id [
] 'delete'=>$this->id
); ]
$newMsg->send(true); );
$newMsg->send(true);
return self::DECLINED;
} return self::DECLINED;
}
public function declineMessage(int $receiverID, string &$reason):int{
if(!$this->id){ public function declineMessage(int $receiverID, string &$reason):int{
throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중'); if(!$this->id){
} throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env'); $db = DB::db();
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); $gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
list($result, $reason) = $this->checkScoutMessageValidation($receiverID);
list($result, $reason) = $this->checkScoutMessageValidation($receiverID);
if($result === self::INVALID){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} 등용 취소 불가.", ActionLogger::PLAIN); if($result === self::INVALID){
return $result; (new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} 등용 취소 불가.", ActionLogger::PLAIN);
} return $result;
}
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$josaYi = JosaUtil::pick($this->dest->generalName, ''); $josaRo = JosaUtil::pick($this->src->nationName, '');
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$this->src->nationName}</>{$josaRo} 망명을 거부했습니다.", ActionLogger::PLAIN); $josaYi = JosaUtil::pick($this->dest->generalName, '이');
(new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->generalName}</>{$josaYi} 등용을 거부했습니다.", ActionLogger::PLAIN); (new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$this->src->nationName}</>{$josaRo} 망명을 거부했습니다.", ActionLogger::PLAIN);
$this->_declineMessage(); (new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->generalName}</>{$josaYi} 등용을 거부했습니다.", ActionLogger::PLAIN);
$this->_declineMessage();
return self::DECLINED;
} return self::DECLINED;
}
public static function buildScoutMessage(int $srcGeneralID, int $destGeneralID, &$reason = null, \DateTime $date = null):?self{
if($srcGeneralID == $destGeneralID){ public static function buildScoutMessage(int $srcGeneralID, int $destGeneralID, &$reason = null, \DateTime $date = null):?self{
if($reason !== null){ if($srcGeneralID == $destGeneralID){
$reason = '같은 장수에게 등용장을 보낼 수 없습니다'; if($reason !== null){
} $reason = '같은 장수에게 등용장을 보낼 수 없습니다';
return null; }
} return null;
}
$db = DB::db();
$srcGeneral = $db->queryFirstRow('SELECT `name`, nation FROM general WHERE `no`=%i', $srcGeneralID); $db = DB::db();
$destGeneral = $db->queryFirstRow('SELECT `name`, nation, `officer_level` FROM general WHERE `no`=%i', $destGeneralID); $srcGeneral = $db->queryFirstRow('SELECT `name`, nation FROM general WHERE `no`=%i', $srcGeneralID);
if($date === null){ $destGeneral = $db->queryFirstRow('SELECT `name`, nation, `officer_level` FROM general WHERE `no`=%i', $destGeneralID);
$date = new \DateTime(); if($date === null){
} $date = new \DateTime();
}
if($destGeneral['officer_level'] == 12){
if($reason !== null){ if($destGeneral['officer_level'] == 12){
$reason = '군주에게 등용장을 보낼 수 없습니다'; if($reason !== null){
} $reason = '군주에게 등용장을 보낼 수 없습니다';
return null; }
} return null;
}
if(!$srcGeneral['nation']){
if($reason !== null){ if(!$srcGeneral['nation']){
$reason = '재야 상태일 때에는 등용장을 보낼 수 없습니다'; if($reason !== null){
} $reason = '재야 상태일 때에는 등용장을 보낼 수 없습니다';
return null; }
} return null;
}
if($srcGeneral['nation'] === $destGeneral['nation']){
if($reason !== null){ if($srcGeneral['nation'] === $destGeneral['nation']){
$reason = '같은 소속의 장수에게 등용장을 보낼 수 없습니다'; if($reason !== null){
} $reason = '같은 소속의 장수에게 등용장을 보낼 수 없습니다';
return null; }
} return null;
}
$srcNationInfo = getNationStaticInfo($srcGeneral['nation']);
$destNationInfo = getNationStaticInfo($destGeneral['nation']); $srcNationInfo = getNationStaticInfo($srcGeneral['nation']);
$destNationInfo = getNationStaticInfo($destGeneral['nation']);
$src = new MessageTarget(
$srcGeneralID, $src = new MessageTarget(
$srcGeneral['name'], $srcGeneralID,
$srcGeneral['nation'], $srcGeneral['name'],
$srcNationInfo['name'], $srcGeneral['nation'],
$srcNationInfo['color'] $srcNationInfo['name'],
); $srcNationInfo['color']
);
$dest = new MessageTarget(
$destGeneralID, $dest = new MessageTarget(
$destGeneral['name'], $destGeneralID,
$destGeneral['nation'], $destGeneral['name'],
$destNationInfo['name'], $destGeneral['nation'],
$destNationInfo['color'] $destNationInfo['name'],
); $destNationInfo['color']
);
$josaRo = JosaUtil::pick($src->nationName, '로');
$msg = "{$src->nationName}{$josaRo} 망명 권유 서신"; $josaRo = JosaUtil::pick($src->nationName, '로');
$validUntil = new \DateTime("9999-12-31 12:59:59"); $msg = "{$src->nationName}{$josaRo} 망명 권유 서신";
$validUntil = new \DateTime("9999-12-31 12:59:59");
$msgOption = [
'action'=>'scout' $msgOption = [
]; 'action'=>'scout'
];
return new ScoutMessage(Message::MSGTYPE_PRIVATE, $src, $dest, $msg, $date, $validUntil, $msgOption);
} return new ScoutMessage(Message::MSGTYPE_PRIVATE, $src, $dest, $msg, $date, $validUntil, $msgOption);
}
} }
+2
View File
@@ -85,6 +85,7 @@ class TurnExecutionHelper
$result = $commandObj->run(); $result = $commandObj->run();
if($result){ if($result){
$commandObj->setNextAvailable();
break; break;
} }
@@ -127,6 +128,7 @@ class TurnExecutionHelper
$result = $commandObj->run(); $result = $commandObj->run();
if($result){ if($result){
$commandObj->setNextAvailable();
break; break;
} }
$alt = $commandObj->getAlternativeCommand(); $alt = $commandObj->getAlternativeCommand();