nation_env 수정, $connect 일부 제거

This commit is contained in:
2020-05-06 01:53:00 +09:00
parent 562c69307e
commit e0c908d88f
26 changed files with 416 additions and 811 deletions
-1
View File
@@ -11,7 +11,6 @@ if($type <= 0 || $type > 8){
}
$db = DB::db();
$connect=$db->get();
increaseRefresh("빙의일람", 2);
+1 -4
View File
@@ -9,16 +9,13 @@ $userID = Session::getUserID();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect=$db->get();
increaseRefresh("세력도", 2);
TurnExecutionHelper::executeAllCommand();
$mapTheme = $gameStor->map_theme??'che';
$query = "select con,turntime from general where owner='{$userID}'";
$result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$me = MYDB_fetch_array($result);
$me = $db->queryFirstRow('SELECT con,turntime from general where owner=%i', $userID);
$con = checkLimit($me['con']);
if($con >= 2) { printLimitMsg($me['turntime']); exit(); }
-1
View File
@@ -42,7 +42,6 @@ $userID = Session::getUserID();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect=$db->get();
increaseRefresh("감찰부", 2);
//전투 추진을 위해 갱신
+5 -6
View File
@@ -9,7 +9,6 @@ $userID = Session::getUserID();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$nationStor = KVStorage::getStorage($db, 'nation_env');
increaseRefresh("내무부", 1);
@@ -18,6 +17,8 @@ $me = $db->queryFirstRow('SELECT no, nation, officer_level, con, turntime, belon
$nationID = $me['nation'];
$nation = $db->queryFirstRow('SELECT nation,level,name,color,type,gold,rice,bill,rate,scout,war,secretlimit,capital FROM nation WHERE nation = %i', $nationID);
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$con = checkLimit($me['con']);
if ($con >= 2) {
printLimitMsg($me['turntime']);
@@ -42,9 +43,7 @@ if ($me['officer_level'] >= 5) {
$read = "readonly";
}
$noticeKey = "nation_notice_{$nationID}";
$scoutKey = "nation_scout_msg_{$nationID}";
$nationStor->cacheValues([$noticeKey, $scoutKey]);
$nationStor->cacheValues(['notice', 'scout_msg']);
?>
<!DOCTYPE html>
@@ -56,8 +55,8 @@ $nationStor->cacheValues([$noticeKey, $scoutKey]);
<title><?=UniqueConst::$serverName?>: 내무부</title>
<script>
var editable = <?=(($me['officer_level']>=5||$permission==4)?'true':'false')?>;
var nationMsg = <?=Json::encode($nationStor->{$noticeKey}??'')?>;
var scoutmsg = <?=Json::encode($nationStor->{$scoutKey}??'')?>;
var nationMsg = <?=Json::encode($nationStor->notice??'')?>;
var scoutmsg = <?=Json::encode($nationStor->scout_msg??'')?>;
</script>
<?=WebUtil::printJS('../e_lib/jquery-3.3.1.min.js')?>
<?=WebUtil::printJS('../e_lib/bootstrap.bundle.min.js')?>
+1 -4
View File
@@ -15,13 +15,10 @@ $userID = Session::getUserID();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect=$db->get();
increaseRefresh("암행부", 1);
$query = "select no,nation,officer_level,con,turntime,belong,permission,penalty from general where owner='{$userID}'";
$result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect), "");
$me = MYDB_fetch_array($result);
$me = $db->queryFirstRow('SELECT no,nation,officer_level,con,turntime,belong,permission,penalty from general where owner=%i', $userID);
$nationLevel = $db->queryFirstField('SELECT level FROM nation WHERE nation=%i', $me['nation']);
+5 -18
View File
@@ -14,13 +14,9 @@ $session = Session::requireGameLogin()->setReadOnly();
$userID = Session::getUserID();
$db = DB::db();
$connect=$db->get();
increaseRefresh("세력도시", 1);
$query = "select no,nation,officer_level from general where owner='{$userID}'";
$result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect), "");
$me = MYDB_fetch_array($result);
$me = $db->queryFirstRow('SELECT no,nation,officer_level FROM general WHERE owner=%i', $userID);
$nationID = $me['nation'];
if ($me['officer_level'] == 0) {
@@ -191,21 +187,12 @@ foreach($cityList as $city){
<tr>
<td align=center id=bg1>장수</td>
<td colspan=11>";
$query = "select npc,name from general where city='{$city['city']}' and nation='{$me['nation']}'"; // 장수 목록
$genresult = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect), "");
$gencount = MYDB_num_rows($genresult);
if ($gencount == 0) {
$generalList = $db->query('SELECT npc, name FROM general WHERE city = %i AND nation = %i', $city['city'], $me['nation']);
if (!$generalList) {
echo "-";
}
for ($i=0; $i < $gencount; $i++) {
$general = MYDB_fetch_array($genresult);
if ($general['npc'] >= 2) {
echo "<font color=cyan>{$general['name']}, </font>";
} elseif ($general['npc'] == 1) {
echo "<font color=skyblue>{$general['name']}, </font>";
} else {
echo "{$general['name']}, ";
}
foreach($generalList as $general) {
echo getColoredName($general['name'], $general['npc']).', ';
}
echo "
</td>
+3 -5
View File
@@ -31,18 +31,16 @@ else if ($me['officer_level'] < 5 && $permission != 4) {
exit();
}
$nationStor = KVStorage::getStorage($db, 'nation_env');
$nationID = $me['nation'];
$noticeKey = "nation_notice_{$nationID}";
$scoutKey = "nation_scout_msg_{$nationID}";
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
if($btn == "국가방침 수정") {
$msg = mb_substr($msg, 0, 16384);
//$msg = StringUtil::
$nationStor->{$noticeKey} = WebUtil::htmlPurify($msg);
$nationStor->notice = WebUtil::htmlPurify($msg);
} elseif($btn == "임관 권유문 수정") {
$scoutmsg = mb_substr($scoutmsg, 0, 1000);
$nationStor->{$scoutKey} = WebUtil::htmlPurify($scoutmsg);
$nationStor->scout_msg = WebUtil::htmlPurify($scoutmsg);
} elseif($btn == "세율") {
$rate = Util::valueFit($rate, 5, 30);
$db->update('nation', [
+80 -86
View File
@@ -180,44 +180,31 @@ function cityInfo(General $generalObj)
return $templates->render('mainCityInfo', $city);
}
function myNationInfo()
function myNationInfo(General $generalObj)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
$userID = Session::getUserID();
$admin = $gameStor->getValues(['startyear', 'year']);
$query = "select no,nation from general where owner='{$userID}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$me = MYDB_fetch_array($result);
$nationID = $generalObj->getNationID();
$nation = $db->queryFirstRow('SELECT * FROM nation WHERE nation = %i', $nationID)??getNationStaticInfo(0);
$city = $db->queryFirstRow(
'SELECT COUNT(*) as cnt, SUM(pop) as totpop, SUM(pop_max) as maxpop from city where nation=%i',
$nationID
);
$general = $db->queryFirstRow('SELECT COUNT(*) as cnt, SUM(crew) as totcrew,SUM(leadership)*100 as maxcrew from general where nation=%i', $nationID);
$query = "select nation,name,color,power,gold,rice,bill,rate,scout,war,strategic_cmd_limit,surlimit,tech,level,type from nation where nation='{$me['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$nation = MYDB_fetch_array($result);
$topChiefs = Util::convertArrayToDict($db->query('SELECT officer_level, no, name, npc FROM general WHERE nation = %i AND officer_level >= 11', $nationID), 'officer_level');
$query = "select COUNT(*) as cnt, SUM(pop) as totpop, SUM(pop_max) as maxpop from city where nation='{$nation['nation']}'"; // 도시 이름 목록
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$city = MYDB_fetch_array($result);
$query = "select COUNT(*) as cnt, SUM(crew) as totcrew,SUM(leadership)*100 as maxcrew from general where nation='{$nation['nation']}'"; // 장수 목록
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$general = MYDB_fetch_array($result);
$query = "select name from general where nation='{$nation['nation']}' and officer_level='12'";
$genresult = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$level12 = MYDB_fetch_array($genresult);
$query = "select name from general where nation='{$nation['nation']}' and officer_level='11'";
$genresult = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$level11 = MYDB_fetch_array($genresult);
$level12Name = key_exists(12, $topChiefs)?getColoredName($topChiefs[12]['name'], $topChiefs[12]['npc']):'-';
$level11Name = key_exists(11, $topChiefs)?getColoredName($topChiefs[11]['name'], $topChiefs[11]['npc']):'-';
echo "<table width=498 class='tb_layout bg2 nation_info'>
<tr>
<td colspan=4 ";
if ($me['nation'] == 0) {
if (!$nationID) {
echo "style='color:white;background-color:000000;font-weight:bold;font-size:13px;text-align:center;'>【재 야】";
} else {
echo "style='color:" . newColor($nation['color']) . ";background-color:{$nation['color']};font-weight:bold;font-size:13px;text-align:center'>국가【 {$nation['name']}";
@@ -233,39 +220,35 @@ function myNationInfo()
</tr>
<tr>
<td width=68 class='bg1 center'><b>" . getOfficerLevelText(12, $nation['level']) . "</b></td>
<td width=178 class='center'>";
echo $level12 ? $level12['name'] : "-";
echo "</td>
<td width=178 class='center'>{$level12Name}</td>
<td width=68 class='bg1 center'><b>" . getOfficerLevelText(11, $nation['level']) . "</b></td>
<td width=178 class='center'>";
echo $level11 ? $level11['name'] : "-";
echo "</td>
<td width=178 class='center'>{$level11Name}</td>
</tr>
<tr>
<td class='bg1 center'><b>총주민</b></td>
<td class='center'>";
echo $me['nation'] == 0 ? "해당 없음" : "{$city['totpop']}/{$city['maxpop']}";
echo $nationID===0 ? "해당 없음" : "{$city['totpop']}/{$city['maxpop']}";
echo "</td>
<td class='bg1 center'><b>총병사</b></td>
<td class='center'>";
echo $me['nation'] == 0 ? "해당 없음" : "{$general['totcrew']}/{$general['maxcrew']}";
echo $nationID===0 ? "해당 없음" : "{$general['totcrew']}/{$general['maxcrew']}";
echo "</td>
</td>
</tr>
<tr>
<td class='bg1 center'><b>국 고</b></td>
<td class='center'>";
echo $me['nation'] == 0 ? "해당 없음" : "{$nation['gold']}";
echo $nationID===0 ? "해당 없음" : "{$nation['gold']}";
echo "</td>
<td class='bg1 center'><b>병 량</b></td>
<td class='center'>";
echo $me['nation'] == 0 ? "해당 없음" : "{$nation['rice']}";
echo $nationID===0 ? "해당 없음" : "{$nation['rice']}";
echo "</td>
</tr>
<tr>
<td class='bg1 center'><b>지급률</b></td>
<td class='center'>";
if ($me['nation'] == 0) {
if ($nationID===0) {
echo "해당 없음";
} else {
echo $nation['bill'] == 0 ? "0 %" : "{$nation['bill']} %";
@@ -274,7 +257,7 @@ function myNationInfo()
</td>
<td class='bg1 center'><b>세 율</b></td>
<td class='center'>";
if ($me['nation'] == 0) {
if ($nationID===0) {
echo "해당 없음";
} else {
echo $nation['rate'] == 0 ? "0 %" : "{$nation['rate']} %";
@@ -290,7 +273,7 @@ function myNationInfo()
$nation['tech'] = "$techCall / {$nation['tech']}";
if ($me['nation'] == 0) {
if ($nationID===0 == 0) {
$nation['strategic_cmd_limit'] = "<font color=white>해당 없음</font>";
$nation['surlimit'] = "<font color=white>해당 없음</font>";
$nation['scout'] = "<font color=white>해당 없음</font>";
@@ -328,11 +311,11 @@ function myNationInfo()
<tr>
<td style='text-align:center;' class='bg1'><b>속 령</b></td>
<td style='text-align:center;'>";
echo $me['nation'] == 0 ? "-" : "{$city['cnt']}";
echo $nationID===0 ? "-" : "{$city['cnt']}";
echo "</td>
<td style='text-align:center;' class='bg1'><b>장 수</b></td>
<td style='text-align:center;'>";
echo $me['nation'] == 0 ? "-" : "{$general['cnt']}";
echo $nationID===0 ? "-" : "{$general['cnt']}";
echo "</td>
</tr>
<tr>
@@ -340,7 +323,7 @@ function myNationInfo()
<td style='text-align:center;'>{$nation['power']}</td>
<td style='text-align:center;' class='bg1'><b>기술력</b></td>
<td style='text-align:center;'>";
echo $me['nation'] == 0 ? "-" : "{$nation['tech']}";
echo $nationID===0 ? "-" : "{$nation['tech']}";
echo "</td>
</tr>
<tr>
@@ -898,11 +881,10 @@ function onlinegen()
function nationMsg(General $general)
{
$db = DB::db();
$nationStor = KVStorage::getStorage($db, 'nation_env');
$nationID = $general->getNationID();
$noticeKey = "nation_notice_{$nationID}";
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
return $nationStor->{$noticeKey}??'';
return $nationStor->notice??'';
}
function banner()
@@ -1643,56 +1625,64 @@ function getAdmin()
return $gameStor->getAll();
}
function getCity($city, $sel = "*")
/** @return General[] */
function deleteNation(General $lord, bool $applyDB):array
{
$lordID = $lord->getID();
$nationID = $lord->getNationID();
DeleteConflict($nationID);
$db = DB::db();
$connect = $db->get();
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $nationID);
$nationName = $oldNation['name'];
$query = "select {$sel} from city where city='$city'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$city = MYDB_fetch_array($result);
return $city;
}
function deleteNation(General $general)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$nation = $general->getStaticNation();
$nationName = $nation['name'];
$nationID = $nation['nation'];
$logger = $general->getLogger();
$logger = $lord->getLogger();
$josaUn = JosaUtil::pick($nationName, '은');
$logger->pushGlobalHistoryLog("<R><b>【멸망】</b></><D><b>{$nationName}</b></>{$josaUn} <R>멸망</>했습니다.");
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $nationID);
$oldNationGenerals = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nationID);
$oldNation['generals'] = $oldNationGenerals;
$oldNationGeneralList = General::createGeneralObjListFromDB(
$db->queryFirstColumn(
'SELECT `no` FROM general WHERE nation=%i AND no != %i',
$nationID,
$lordID
),
['gold', 'rice', 'experience', 'explevel', 'dedication', 'dedlevel'], 1
);
$oldNationGeneralList[$lordID] = $lord;
$oldNation['generals'] = array_keys($oldNationGeneralList);
$oldNation['aux'] = Json::decode($oldNation['aux']);
$oldNation['msg'] = $nationStor->notice;
$oldNation['scout_msg'] = $nationStor->scout_msg;
$oldNation['aux'] += $nationStor->max_power;
$oldNation['history'] = getNationHistoryAll($nationID);
$general->setVar('belong', 0);
$general->setVar('troop', 0);
$general->setVar('officer_level', 0);
$general->setVar('officer_city', 0);
$general->setVar('nation', 0);
$general->setVar('makelimit', 12);
$josaYi = JosaUtil::pick($nationName, '이');
$destroyLog = "<D><b>{$nationName}</b></>{$josaYi} <R>멸망</>했습니다.";
$destroyHistoryLog = "<D><b>{$nationName}</b></>{$josaYi} <R>멸망</>";
// 전 장수 재야로
foreach($oldNationGeneralList as $general){
$general->setVar('belong', 0);
$general->setVar('troop', 0);
$general->setVar('officer_level', 0);
$general->setVar('officer_city', 0);
$general->setVar('nation', 0);
$general->setVar('permission', 'normal');
$logger = $general->getLogger();
$logger->pushGeneralActionLog($destroyLog, ActionLogger::PLAIN);
$logger->pushGeneralHistoryLog($destroyHistoryLog);
if($applyDB){
$general->applyDB($db);
}
}
// 전 장수 재야로 // 전 장수 소속 무소속으로
$db->update('general', [
'belong' => 0,
'troop' => 0,
'officer_level' => 0,
'officer_city' => 0,
'nation' => 0,
'makelimit' => 12,
'permission' => 'normal',
], 'nation=%i', $nationID);
// 도시 공백지로
$db->update('city', [
'nation' => 0,
@@ -1700,8 +1690,8 @@ function deleteNation(General $general)
], 'nation=%i', $nationID);
// 부대 삭제
$db->delete('troop', 'nation=%i', $nationID);
// 국가 삭제
// 국가 삭제
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => $nationID,
@@ -1713,6 +1703,11 @@ function deleteNation(General $general)
$db->delete('diplomacy', 'me = %i OR you = %i', $nationID, $nationID);
refreshNationStaticInfo();
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$nationStor->resetValues();
return $oldNationGeneralList;
}
function nextRuler(General $general)
@@ -1752,8 +1747,7 @@ function nextRuler(General $general)
if (!$candidate) {
DeleteConflict($general->getNationID());
deleteNation($general);
deleteNation($general, true);
return;
}
-1
View File
@@ -667,7 +667,6 @@ function getColoredName(string $name, int $npcType):string{
if($color === null){
return $name;
}
//TODO: font 폐기.
return "<span style='color:{$color}'>{$name}</span>";
}
+107 -438
View File
@@ -181,7 +181,7 @@ function updateQuaterly()
//천도 제한 해제, 관직 변경 제한 해제
$db->update('nation', [
'chief_set'=>0,
'chief_set' => 0,
], true);
//관직 변경 제한 해제
$db->update('city', [
@@ -323,11 +323,9 @@ function postUpdateMonthly()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
$admin = $gameStor->getValues(['startyear', 'year', 'month', 'scenario']);
$history = [];
$globalLogger = new ActionLogger(0, 0, $admin['year'], $admin['month']);
//도시 수 측정
$cityNations = [];
@@ -349,9 +347,9 @@ function postUpdateMonthly()
// 접속률
// 숙련도
// 명성,공헌
$nations = $db->query('SELECT
$nations = Util::convertArrayToDict($db->query('SELECT
A.nation,
A.gennum, A.aux,
A.gennum,
round((
round(((A.gold+A.rice)+(select sum(gold+rice) from general where nation=A.nation))/100)
+A.tech
@@ -368,34 +366,34 @@ function postUpdateMonthly()
as power,
(select sum(crew) from general where nation=A.nation) as totalCrew
from nation A
group by A.nation');
foreach ($nations as $nation) {
$genNum[$nation['nation']] = $nation['gennum'];
group by A.nation'), 'nation');
$maxPowerValues = KVStorage::getValuesFromInterNamespace($db, 'nation_env', 'max_power');
$aux = Json::decode($nation['aux']);
foreach ($nations as $nation) {
$nationID = $nation['nation'];
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$genNum[$nationID] = $nation['gennum'];
$powerValues = $maxPowerValues[$nationID]??[];
//약간의 랜덤치 부여 (95% ~ 105%)
$nation['power'] = Util::round($nation['power'] * (rand() % 101 + 950) / 1000);
$aux['maxPower'] = max($aux['maxPower'] ?? 0, $nation['power']);
$aux['maxCrew'] = max($aux['maxCrew'] ?? 0, Util::toInt($nation['totalCrew']));
$powerValues['maxPower'] = max($powerValues['maxPower'] ?? 0, $nation['power']);
$powerValues['maxCrew'] = max($powerValues['maxCrew'] ?? 0, Util::toInt($nation['totalCrew']));
if (count($cityNations[$nation['nation']] ?? []) > count($aux['maxCities'] ?? [])) {
$aux['maxCities'] = $cityNations[$nation['nation']];
if (count($cityNations[$nationID] ?? []) > count($powerValues['maxCities'] ?? [])) {
$powerValues['maxCities'] = $cityNations[$nationID];
}
$db->update('nation', [
'power' => $nation['power'],
'aux' => Json::encode($aux)
], 'nation=%i', $nation['nation']);
'power' => $nation['power']
], 'nation=%i', $nationID);
$nationStor->max_power = $powerValues;
}
// 전쟁기한 세팅
$query = "select me,you,dead,term from diplomacy where state='0'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$dipCount = MYDB_num_rows($result);
for ($i = 0; $i < $dipCount; $i++) {
$dip = MYDB_fetch_array($result);
foreach($db->query('SELECT me, you, dead, term FROM diplomacy WHERE state = 0') as $dip) {
$genCount = $genNum[$dip['me']];
// 25% 참여율일때 두당 10턴에 4000명 소모한다고 계산
// 4000 / 10 * 0.25 = 100
@@ -410,12 +408,7 @@ function postUpdateMonthly()
}
//개전국 로그
$query = "select me,you from diplomacy where state='1' and term<='1' and me<you";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$dipCount = MYDB_num_rows($result);
for ($i = 0; $i < $dipCount; $i++) {
$dip = MYDB_fetch_array($result);
foreach($db->query('SELECT me, you FROM diplomacy WHERE state = 1 AND term <= 1 AND me < you') as $dip){
$nation1 = getNationStaticInfo($dip['me']);
$name1 = $nation1['name'];
$nation2 = getNationStaticInfo($dip['you']);
@@ -423,47 +416,56 @@ function postUpdateMonthly()
$josaYi = JosaUtil::pick($name2, '이');
$josaWa = JosaUtil::pick($name1, '와');
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<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>전쟁</>을 시작합니다.");
}
//휴전국 로그
$query = "select A.me as me,A.you as you,A.term as term1,B.term as term2 from diplomacy A, diplomacy B where A.me=B.you and A.you=B.me and A.state='0' and A.me<A.you";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$dipCount = MYDB_num_rows($result);
for ($i = 0; $i < $dipCount; $i++) {
$dip = MYDB_fetch_array($result);
$stopWarList = [];
foreach($db->queryAllLists('SELECT me,you WHERE state=0 AND term <= 1 ORDER BY me desc, you desc') as [$me, $you]){
if($me < $you){
$key = "{$me}_{$you}";
}
else{
$key = "{$you}_{$me}";
}
if(!key_exists($key, $stopWarList)){
$stopWarList[$key] = true;
continue;
}
//양측 기간 모두 0이 되는 상황이면 휴전
if ($dip['term1'] <= 1 && $dip['term2'] <= 1) {
$nation1 = getNationStaticInfo($dip['me']);
$name1 = $nation1['name'];
$nation2 = getNationStaticInfo($dip['you']);
$name2 = $nation2['name'];
$nation1 = getNationStaticInfo($me);
$name1 = $nation1['name'];
$nation2 = getNationStaticInfo($you);
$name2 = $nation2['name'];
$josaWa = JosaUtil::pick($name1, '와');
$josaYi = JosaUtil::pick($name2, '이');
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<R><b>【휴전】</b></><D><b>$name1</b></>{$josaWa} <D><b>$name2</b></>{$josaYi} <S>휴전</>합니다.";
//기한 되면 휴전으로
$query = "update diplomacy set state='2',term='0' where (me='{$dip['me']}' and you='{$dip['you']}') or (me='{$dip['you']}' and you='{$dip['me']}')";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
}
$josaWa = JosaUtil::pick($name1, '와');
$josaYi = JosaUtil::pick($name2, '이');
$globalLogger->pushGlobalHistoryLog("<R><b>【휴전】</b></><D><b>$name1</b></>{$josaWa} <D><b>$name2</b></>{$josaYi} <S>휴전</>합니다.");
$db->update('diplomacy', [
'state'=>2,
'term'=>0,
], '(me=%i AND you=%i) OR (you=%i AND me=%i)', $me, $you, $me, $you);
}
pushWorldHistory($history, $admin['year'], $admin['month']);
//사상자 초기화
$query = "update diplomacy set dead=0 WHERE state != 0";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
//외교 기한-1
$query = "update diplomacy set term=term-1 where term!=0";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$globalLogger->flush();
//사상자 초기화, 외교 기한-1
$db->update('diplomacy', [
'dead'=>$db->sqleval('if(state!=0, 0, dead)'),
'term'=>$db->sqleval('greatest(0, term-1)'),
], true);
//불가침 끝나면 통상으로
$query = "update diplomacy set state='2' where state='7' and term='0'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$db->update('diploacy', [
'state'=>2,
], 'state = 7 AND term = 0');
//선포 끝나면 교전으로
$query = "update diplomacy set state='0',term='6' where state='1' and term='0'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
//3,4 기간 끝나면 통합
checkMerge();
//5,6 기간 끝나면 합병
checkSurrender();
$db->update('diploacy', [
'state'=>0,
'term'=>6,
], 'state = 1 AND term = 0');
//NOTE: diplomacy에서 3=>4 통합, 5=>6 합병이 있었음
//초반이후 방랑군 자동 해체
if ($admin['year'] >= $admin['startyear'] + 2) {
checkWander();
@@ -510,321 +512,6 @@ function checkWander()
}
}
function checkMerge()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
$mylog = [];
$youlog = [];
$history = [];
$admin = $gameStor->getValues(['year', 'month']);
$query = "select * from diplomacy where state='3' and term='0'";
$dipresult = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$dipcount = MYDB_num_rows($dipresult);
for ($i = 0; $i < $dipcount; $i++) {
$dip = MYDB_fetch_array($dipresult);
// 아국군주
$query = "select no,name,nation from general where nation='{$dip['me']}' and officer_level='12'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$me = MYDB_fetch_array($result);
// 상대군주
$query = "select no,name,nation,makenation from general where nation='{$dip['you']}' and officer_level='12'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$you = MYDB_fetch_array($result);
// 모국
$query = "select nation,name,surlimit,tech from nation where nation='{$you['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$younation = MYDB_fetch_array($result);
// 아국
$query = "select nation,name,gold,rice,surlimit,tech from nation where nation='{$me['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$mynation = MYDB_fetch_array($result);
//양국 NPC수
$query = "select no from general where nation='{$you['nation']}' and npc>=2";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$npccount = MYDB_num_rows($result);
//양국 NPC수
$query = "select no from general where nation='{$me['nation']}' and npc>=2";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$npccount2 = MYDB_num_rows($result);
//TODO: 로그 기록에 대한 쿼리는 한번만 할 수 있다.
//피항복국 장수들 역사 기록 및 로그 전달
$query = "select no,name,nation from general where nation='{$you['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$gencount = MYDB_num_rows($result);
$josaWa = JosaUtil::pick($mynation['name'], '와');
$genlog = ["<C>●</><D><b>{$mynation['name']}</b></>{$josaWa} 통합에 성공했습니다."];
for ($i = 0; $i < $gencount; $i++) {
$gen = MYDB_fetch_array($result);
pushGenLog($gen['no'], $genlog);
pushGeneralHistory($gen['no'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$mynation['name']}</b></>{$josaWa} <D><b>{$you['makenation']}</b></>로 통합에 성공"]);
}
//항복국 장수들 역사 기록 및 로그 전달
$query = "select no,name,nation from general where nation='{$me['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$gencount2 = MYDB_num_rows($result);
$josaWa = JosaUtil::pick($younation['name'], '와');
$genlog[0] = "<C>●</><D><b>{$younation['name']}</b></>{$josaWa} 통합에 성공했습니다.";
for ($i = 0; $i < $gencount2; $i++) {
$gen = MYDB_fetch_array($result);
pushGenLog($gen['no'], $genlog);
pushGeneralHistory($gen['no'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$younation['name']}</b></>{$josaWa} <D><b>{$you['makenation']}</b></>로 통합에 성공"]);
}
$josaRo = JosaUtil::pick($you['makenation'], '로');
$josaYi = JosaUtil::pick($younation['name'], '이');
$josaWa = JosaUtil::pick($mynation['name'], '와');
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【통합】</b></><D><b>{$mynation['name']}</b></>{$josaWa} <D><b>{$younation['name']}</b></>{$josaYi} <D><b>{$you['makenation']}</b></>{$josaRo} 통합하였습니다.";
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<D><b>【혼란】</b></>통합에 반대하는 세력들로 인해 <D><b>{$you['makenation']}</b></>에 혼란이 일고 있습니다.";
pushNationHistory($younation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$mynation['name']}</b></>과 <D><b>{$you['makenation']}</b></>로 통합"]);
$newGenCount = $gencount + $gencount2;
$newTech = ($younation['tech'] * $gencount + $mynation['tech'] * $gencount2) / $newGenCount;
// 국가 백업
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $me['nation']);
$oldNationGenerals = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $me['nation']);
$oldNation['generals'] = $oldNationGenerals;
$oldNation['aux'] = Json::decode($oldNation['aux']);
$oldNation['history'] = getNationHistoryAll($me['nation']);
// 자금 통합, 외교제한 5년, 기술유지
$db->update('nation', [
'name' => $you['makenation'],
'gold' => $db->sqleval('gold+%i', $mynation['gold']),
'rice' => $db->sqleval('rice+%i', $mynation['rice']),
'surlimit' => 24,
'tech' => $newTech,
'gennum' => $newGenCount
], 'nation=%i', $younation['nation']);
//국가 삭제
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => $me['nation'],
'data' => Json::encode($oldNation)
]);
$db->update('general', [
'nation' => 0,
'permission' => 'normal',
], 'nation=%i AND npc = 5', $me['nation']);
$query = "delete from nation where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$db->delete('nation_turn', 'nation_id=%i', $me['nation']);
// 아국 모든 도시들 상대국 소속으로
$query = "update city set nation='{$you['nation']}',conflict='{}' where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 아국 모든 장수들 일반으로 하고 상대국 소속으로, 수도로 이동
$query = "update general set belong=1,officer_level=1,officer_city=0,nation='{$you['nation']}' where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 공헌도0.9, 명성0.9
//TODO:experience General 객체로 이동
$query = "update general set dedication=dedication*0.9,experience=experience*0.9 where nation='{$you['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 부대도 모두 국가 소속 변경
$query = "update troop set nation='{$you['nation']}' where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 통합국 모든 도시 5% 감소
$query = "update city set pop=pop*0.95,agri=agri*0.95,comm=comm*0.95,secu=secu*0.95,trust=trust*0.95,def=def*0.95,wall=wall*0.95 where nation='{$you['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 외교 삭제
$query = "delete from diplomacy where me='{$me['nation']}' or you='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// NPC들 일부 하야 (양국중 큰쪽 장수수의 90~110%만큼)
$resignCount = 0;
if ($npccount >= $npccount2) {
$resignCount = Util::round($npccount * (rand() % 21 + 90) / 100);
} else {
$resignCount = Util::round($npccount2 * (rand() % 21 + 90) / 100);
}
$npcList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND npc>=2 AND npc != 5 ORDER BY rand() LIMIT %i', $you['nation'], $resignCount);
if ($npcList) {
$db->update('general_turn', [
'action' => 'che_하야',
'arg' => null,
'brief' => '하야',
], 'general_id IN %li AND turn_idx = 0');
}
pushGenLog($me['no'], $mylog);
pushGenLog($you['no'], $youlog);
pushWorldHistory($history, $admin['year'], $admin['month']);
$mylog = [];
$youlog = [];
$history = [];
refreshNationStaticInfo();
}
}
function checkSurrender()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
$admin = $gameStor->getValues(['year', 'month']);
$query = "select * from diplomacy where state='5' and term='0'";
$dipresult = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$dipcount = MYDB_num_rows($dipresult);
for ($i = 0; $i < $dipcount; $i++) {
$mylog = [];
$youlog = [];
$history = [];
$dip = MYDB_fetch_array($dipresult);
// 아국군주
$query = "select no,name,nation from general where nation='{$dip['me']}' and officer_level='12'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$me = MYDB_fetch_array($result);
// 상대군주
$query = "select no,name,nation,makenation from general where nation='{$dip['you']}' and officer_level='12'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$you = MYDB_fetch_array($result);
// 모국
$query = "select nation,name,surlimit,tech from nation where nation='{$you['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$younation = MYDB_fetch_array($result);
// 아국
$query = "select nation,name,gold,rice,surlimit,tech from nation where nation='{$me['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$mynation = MYDB_fetch_array($result);
//양국 NPC수
$query = "select no from general where nation='{$you['nation']}' and npc>=2 and npc != 5";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$npccount = MYDB_num_rows($result);
//양국 NPC수
$query = "select no from general where nation='{$me['nation']}' and npc>=2 and npc != 5";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$npccount2 = MYDB_num_rows($result);
//피항복국 장수들 역사 기록 및 로그 전달
$query = "select no,name,nation from general where nation='{$you['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$gencount = MYDB_num_rows($result);
$genlog = ["<C>●</><D><b>{$mynation['name']}</b></> 합병에 성공했습니다."];
for ($i = 0; $i < $gencount; $i++) {
$gen = MYDB_fetch_array($result);
pushGenLog($gen['no'], $genlog);
pushGeneralHistory($gen['no'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$mynation['name']}</b></> 합병에 성공"]);
}
$josaRo = JosaUtil::pick($younation['name'], '로');
//항복국 장수들 역사 기록 및 로그 전달
$query = "select no,name,nation from general where nation='{$me['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$gencount2 = MYDB_num_rows($result);
$genlog[0] = "<C>●</><D><b>{$younation['name']}</b></>{$josaRo} 항복하여 수도로 이동합니다.";
for ($i = 0; $i < $gencount2; $i++) {
$gen = MYDB_fetch_array($result);
pushGenLog($gen['no'], $genlog);
pushGeneralHistory($gen['no'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$mynation['name']}</b></>가 <D><b>{$younation['name']}</b></>{$josaRo} 항복"]);
}
$josaYi = JosaUtil::pick($mynation['name'], '이');
$josaWa = JosaUtil::pick($mynation['name'], '와');
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【투항】</b></><D><b>{$mynation['name']}</b></>{$josaYi} <D><b>{$younation['name']}</b></>{$josaRo} 항복하였습니다.";
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<D><b>【혼란】</b></>통합에 반대하는 세력들로 인해 <D><b>{$younation['name']}</b></>에 혼란이 일고 있습니다.";
pushNationHistory($younation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$mynation['name']}</b></>{$josaWa} 합병"]);
// 국가 백업
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $me['nation']);
$oldNationGenerals = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $me['nation']);
$oldNation['generals'] = $oldNationGenerals;
$oldNation['aux'] = Json::decode($oldNation['aux']);
$oldNation['history'] = getNationHistoryAll($me['nation']);
$newGenCount = $gencount + $gencount2;
$newTech = ($younation['tech'] * $gencount + $mynation['tech'] * $gencount2) / $newGenCount;
// 자금 통합, 외교제한 5년, 기술유지
$db->update('nation', [
'gold' => $db->sqleval('gold+%i', $mynation['gold']),
'rice' => $db->sqleval('rice+%i', $mynation['rice']),
'surlimit' => 24,
'tech' => $newTech,
'gennum' => $newGenCount
], 'nation=%i', $younation['nation']);
//합병 당한국 모든 도시 10%감소
$query = "update city set pop=pop*0.9,agri=agri*0.9,comm=comm*0.9,secu=secu*0.9,trust=trust*0.9,def=def*0.9,wall=wall*0.9 where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
//합병 시도국 모든 도시 5%감소
$query = "update city set pop=pop*0.95,agri=agri*0.95,comm=comm*0.95,secu=secu*0.95,trust=trust*0.95,def=def*0.95,wall=wall*0.95 where nation='{$you['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
//국가 삭제
$db->insert('ng_old_nations', [
'server_id' => UniqueConst::$serverID,
'nation' => $me['nation'],
'data' => Json::encode($oldNation)
]);
$db->update('general', [
'nation' => 0,
'permission' => 'normal',
], 'nation=%i AND npc = 5', $me['nation']);
$query = "delete from nation where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$db->delete('nation_turn', 'nation_id=%i', $me['nation']);
// 군주가 있는 위치 구함
$query = "select city from general where nation='{$you['nation']}' and officer_level='12'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$king = MYDB_fetch_array($result);
// 아국 모든 도시들 상대국 소속으로
$query = "update city set nation='{$you['nation']}',conflict='{}' where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 제의국 모든 장수들 공헌도0.95, 명성0.95
//TODO: experience를 General로
$query = "update general set dedication=dedication*0.95,experience=experience*0.95 where nation='{$you['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 아국 모든 장수들 일반으로 하고 상대국 소속으로, 수도로 이동, 공헌도1.1, 명성0.9
$query = "update general set belong=1,officer_level=1,officer_city=0,nation='{$you['nation']}',city='{$king['city']}',dedication=dedication*1.1,experience=experience*0.9 where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 부대도 모두 국가 소속 변경
$query = "update troop set nation='{$you['nation']}' where nation='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// 외교 삭제
$query = "delete from diplomacy where me='{$me['nation']}' or you='{$me['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
// NPC들 일부 하야 (양국중 큰쪽 장수수의 90~110%만큼)
$resignCount = 0;
if ($npccount >= $npccount2) {
$resignCount = Util::round($npccount * (rand() % 21 + 90) / 100);
} else {
$resignCount = Util::round($npccount2 * (rand() % 21 + 90) / 100);
}
$npcList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND npc>=2 AND npc != 5 ORDER BY rand() LIMIT %i', $you['nation'], $resignCount);
if ($npcList) {
$db->update('general_turn', [
'action' => 'che_하야',
'arg' => null,
'brief' => '하야',
], 'general_id IN %li AND turn_idx = 0');
}
pushGenLog($me['no'], $mylog);
pushGenLog($you['no'], $youlog);
pushWorldHistory($history, $admin['year'], $admin['month']);
refreshNationStaticInfo();
}
}
function updateNationState()
{
$db = DB::db();
@@ -864,7 +551,7 @@ function updateNationState()
$levelDiff = $nationlevel - $nation['level'];
$oldLevel = $nation['level'];
$nation['level'] = $nationlevel;
$updateVals = [
'level' => $nationlevel
];
@@ -949,10 +636,10 @@ function updateNationState()
}
foreach (Util::range($levelDiff) as $idx) {
if(!$uniqueLotteryWeightList){
if (!$uniqueLotteryWeightList) {
break;
}
}
/** @var General */
$winnerObj = Util::choiceRandomUsingWeightPair($uniqueLotteryWeightList);
unset($uniqueLotteryWeightList[$winnerObj->getID()]);
@@ -960,7 +647,6 @@ function updateNationState()
$winnerObj->applyDB($db);
}
}
}
$assemblerCnt = $assemblerCnts[$nation['nation']] ?? 0;
@@ -1250,27 +936,29 @@ function checkEmperior()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
$admin = $gameStor->getValues(['year', 'month', 'isunited']);
$query = "select nation,name from nation where level>0";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$count = MYDB_num_rows($result);
if ($count != 1 || $admin['isunited'] != 0) {
$admin = $gameStor->getValues(['year', 'month', 'isunited', 'conlimit']);
if ($admin['isunited'] != 0) {
return;
}
$nation = MYDB_fetch_array($result);
$remainNationCnt = $db->queryFirstField('SELECT count(*) FROM nation WHERE level > 0');
$count = $db->queryFirstField('SELECT count(city) FROM city WHERE nation=%i', $nation['nation']);
if (!$count) {
if ($remainNationCnt > 1) {
return;
}
$allcount = $db->queryFirstField('SELECT count(city) FROM city');
if ($count != $allcount) {
$nation = $db->queryFirstRow('SELECT * FROM nation WHERE level > 0 LIMIT 1');
$nationID = $nation['nation'];
$nationStor = KVStorage::getStorage($db, $nationID, 'nation_env');
$cityCnt = $db->queryFirstField('SELECT count(city) FROM city WHERE nation=%i', $nationID);
if (!$cityCnt) {
return;
}
if ($cityCnt != count(CityConst::all())) {
return;
}
@@ -1278,7 +966,8 @@ function checkEmperior()
$josaYi = JosaUtil::pick($nation['name'], '이');
pushNationHistory($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>{$josaYi} 전토를 통일"]);
$nationLogger = new ActionLogger(0, $nationID, $admin['year'], $admin['month']);
$nationLogger->pushNationalHistoryLog("<D><b>{$nation['name']}</b></>{$josaYi} 전토를 통일");
$gameStor->isunited = 2;
$gameStor->conlimit = $gameStor->conlimit * 100;
@@ -1287,26 +976,19 @@ function checkEmperior()
CheckHall($hallGeneralNo);
}
$query = "select nation,name,type,color,gold,rice,power,gennum from nation where nation='{$nation['nation']}'";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$nation = MYDB_fetch_array($result);
$query = "select SUM(pop) as totalpop,SUM(pop_max) as maxpop from city where nation='{$nation['nation']}'"; // 도시 이름 목록
$cityresult = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$city = MYDB_fetch_array($cityresult);
$pop = "{$city['totalpop']} / {$city['maxpop']}";
$poprate = round($city['totalpop'] / $city['maxpop'] * 100, 2);
$poprate .= " %";
[$totalPop, $totalMaxPop] = $db->queryFirstList('SELECT SUM(pop), SUM(pop_max) FROM city');
$pop = "{$totalPop} / {$totalMaxPop}";
$poprate = round($totalPop / $totalMaxPop * 100, 2). " %";
$chiefs = Util::convertArrayToDict(
$db->query(
'SELECT name,picture,belong,officer_level FROM general WHERE nation=%i AND officer_level >= 5',
'SELECT no,name,picture,belong,officer_level FROM general WHERE nation=%i AND officer_level >= 5',
$nation['nation']
),
'officer_level'
);
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $nation['nation']);
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $nation['nation']);
$oldNationGenerals = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nation['nation']);
$oldNation['generals'] = $oldNationGenerals;
@@ -1334,43 +1016,30 @@ function checkEmperior()
return "{$arr['name']}{$number}";
}, $eagles));
$log = ["<C>●</>{$admin['year']}{$admin['month']}월: <D><b>{$nation['name']}</b></>{$josaYi} 전토를 통일하였습니다."];
$query = "select no,name from general where nation='{$nation['nation']}' order by dedication desc";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$gencount = MYDB_num_rows($result);
$gen = '';
for ($i = 0; $i < $gencount; $i++) {
$general = MYDB_fetch_array($result);
$gen .= "{$general['name']}, ";
pushGenLog($general['no'], $log);
$rawGeneralList = $db->query('SELECT no, name, npc, owner FROM general WHERE nation=%i ORDER BY dedication DESC');
foreach ($rawGeneralList as $rawGeneral) {
$generalLogger = new ActionLogger($rawGeneral['no'], $nationID, $admin['year'], $admin['month']);
$generalLogger->pushGeneralActionLog("<D><b>{$nation['name']}</b></>{$josaYi} 전토를 통일하였습니다.", ActionLogger::YEAR_MONTH);
$generalLogger->flush();
}
$gen = join(', ', array_column($rawGeneral, 'name'));
$nation['type'] = getNationType($nation['type']);
$query = "select MAX(nation_count) as nc,MAX(gen_count) as gc from statistic";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$stat = MYDB_fetch_array($result);
$query = "select count(*) as cnt from general";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$gencount = MYDB_fetch_array($result);
$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 = "{$gencount['cnt']} / {$stat['gc']}";
$statGC = "{$genCnt} / {$stat['gc']}";
$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');
$query = "select nation_count,nation_name,nation_hist from statistic where nation_count='{$stat['nc']}' limit 0,1";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$statNation = MYDB_fetch_array($result);
$query = "select gen_count,personal_hist,special_hist,aux from statistic order by no desc limit 0,1";
$result = MYDB_query($query, $connect) or Error(__LINE__ . MYDB_error($connect), "");
$statGeneral = MYDB_fetch_array($result);
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $nation['nation']);
$oldNation = $nation;
$oldNation['generals'] = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nation['nation']);
$oldNation['aux'] = Json::decode($oldNation['aux']);
$oldNation['msg'] = $nationStor->notice;
$oldNation['scout_msg'] = $nationStor->scout_msg;
$oldNation['aux'] += $nationStor->max_power;
$oldNation['history'] = getNationHistoryAll($nation['nation']);
storeOldGenerals(0, $admin['year'], $admin['month']);
@@ -1393,7 +1062,7 @@ function checkEmperior()
])
]);
$nationHistory = JSON::encode(getNationHistoryAll($nation['nation']));
$nationHistory = getNationHistoryAll($nation['nation']);
$serverCnt = $db->queryFirstField('SELECT count(*) FROM ng_games');
$serverName = UniqueConst::$serverName;
@@ -1418,7 +1087,7 @@ function checkEmperior()
'month' => $admin['month'],
'power' => $nation['power'],
'gennum' => $nation['gennum'],
'citynum' => $allcount,
'citynum' => $cityCnt,
'pop' => $pop,
'poprate' => $poprate,
'gold' => $nation['gold'],
@@ -1442,7 +1111,7 @@ function checkEmperior()
'tiger' => $tigerstr,
'eagle' => $eaglestr,
'gen' => $gen,
'history' => $nationHistory,
'history' => JSON::encode($nationHistory),
'aux' => $statGeneral['aux']
]);
-28
View File
@@ -100,34 +100,6 @@ function getAuctionLogRecent(int $count) {
return join('<br>', array_reverse(getFormattedFileLogRecent(__DIR__."/logs/".UniqueConst::$serverID."/_auctionlog.txt", $count, 300)));
}
function pushOldNationStop(int $no, int $nationNo){
$logPrefixList = ['batres', 'gen', 'batlog'];
$result = [];
foreach($logPrefixList as $logPrefix){
$path = __DIR__."/logs/".UniqueConst::$serverID."/{$logPrefix}{$no}.txt";
if(file_exists($path)){
$fileLen = @filesize($path);
}
else{
$fileLen = 0;
}
$result[$logPrefix] = $fileLen;
}
$baseStopPath = __DIR__."/logs/".UniqueConst::$serverID."/stop{$no}.txt";
if(file_exists($baseStopPath)){
$oldValues = Json::decode(file_get_contents($baseStopPath));
}
else{
$oldValues = [];
}
$oldValues[$nationNo] = $result;
file_put_contents($baseStopPath, Json::encode($oldValues, Json::PRETTY));
}
//DB-based
function formatHistoryToHTML(array $history):string{
$result = [];
+1 -1
View File
@@ -307,7 +307,7 @@ else if($session->userGrade == 4){
</table>
<table class="tb_layout bg0" style="width:1000px;">
<tr>
<td width=498 style="border:none;"><?php myNationInfo(); ?></td>
<td width=498 style="border:none;"><?php myNationInfo($generalObj); ?></td>
<td width=498 style="border:none;"><?php generalInfo($generalObj); ?></td>
</tr>
<tr><td colspan=2><?=commandButton()?></td></tr>
+2 -6
View File
@@ -79,13 +79,9 @@ if ($gencount >= $admin['maxgeneral']) {
$nationList = $db->query('SELECT nation,`name`,color,scout FROM nation');
shuffle($nationList);
$nationList = Util::convertArrayToDict($nationList, 'nation');
$nationStor = KVStorage::getStorage($db, 'nation_env');
//NOTE: join 안할것임
$scoutMsgs = $nationStor->getValues(array_map(function($nationID){
return "nation_scout_msg_{$nationID}";
}, array_keys($nationList)));
foreach($scoutMsgs as $nationIDPack=>$scoutMsg){
$nationID = Util::toInt(Util::array_last(explode('_', $nationIDPack)));
$scoutMsgs = KVStorage::getValuesFromInterNamespace($db, 'nation_env', 'scout_msg');
foreach($scoutMsgs as $nationID=>$scoutMsg){
$nationList[$nationID]['scoutmsg'] = $scoutMsg;
}
+139 -165
View File
@@ -163,14 +163,6 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r
if(!$conquerCity){
return;
}
//XXX: 새 도시점령 코드 작성하기 전까지 유지
$rawAttackerCity = $db->queryFirstRow('SELECT * FROM city WHERE city = %i', $attackerGeneral->getCityID());
$rawAttackerNation = $db->queryFirstRow('SELECT nation,`level`,`name`,capital,gennum,tech,`type`,gold,rice FROM nation WHERE nation = %i', $attackerNationID);
if($defenderNationID !== 0){
$rawDefenderNation = $db->queryFirstRow('SELECT nation,`level`,`name`,capital,gennum,tech,`type`,gold,rice FROM nation WHERE nation = %i', $defenderNationID);
}
ConquerCity([
'startyear'=>$startYear,
@@ -178,7 +170,7 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r
'month'=>$month,
'city_rate'=>$cityRate,
'join_mode'=>$joinMode,
], $attacker->getRaw(), $city->getRaw(), $rawAttackerNation, $rawDefenderNation);
], $attacker->getGeneral(), $city->getRaw());
}
function extractBattleOrder(General $general){
@@ -476,198 +468,181 @@ function getConquerNation($city) : int {
return Util::array_first_key($conflict);
}
function ConquerCity($admin, $general, $city, $nation, $destnation) {
'@phan-var array<string,mixed> $city';
function ConquerCity(array $admin, General $general, array $city) {
$db = DB::db();
$connect=$db->get();
$alllog = [];
$log = [];
$history = [];
if($destnation['nation'] > 0) {
$destnationName = "<D><b>{$destnation['name']}</b></>의";
} else {
$destnationName = "공백지인";
}
$year = $admin['year'];
$month = $admin['month'];
$josaUl = JosaUtil::pick($city['name'], '을');
$josaYiNation = JosaUtil::pick($nation['name'], '이');
$josaYiGen = JosaUtil::pick($general['name'], '이');
$josaYiCity = JosaUtil::pick($city['name'], '이');
$alllog[] = "<C>●</>{$month}월:<Y>{$general['name']}</>{$josaYiGen} <G><b>{$city['name']}</b></> 공략에 <S>성공</>했습니다.";
$log[] = "<C>●</><G><b>{$city['name']}</b></> 공략에 <S>성공</>했습니다.";
$history[] = "<C>●</>{$year}{$month}월:<S><b>【지배】</b></><D><b>{$nation['name']}</b></>{$josaYiNation} <G><b>{$city['name']}</b></>{$josaUl} 지배했습니다.";
pushGeneralHistory($general['no'], ["<C>●</>{$year}{$month}월:<G><b>{$city['name']}</b></>{$josaUl} <S>함락</>시킴"]);
pushNationHistory($nation['nation'], ["<C>●</>{$year}{$month}월:<Y>{$general['name']}</>{$josaYiGen} {$destnationName} <G><b>{$city['name']}</b></>{$josaUl} <S>점령</>"]);
pushNationHistory($destnation['nation'], ["<C>●</>{$year}{$month}월:<D><b>{$nation['name']}</b></>의 <Y>{$general['name']}</>에 의해 <G><b>{$city['name']}</b></>{$josaYiCity} <span class='ev_highlight'>함락</span>"]);
$attackerID = $general->getID();
$attackerNationID = $general->getNationID();
$attackerGeneralName = $general->getName();
$attackerNationName = $general->getStaticNation()['name'];
$attackerLogger = $general->getLogger();
$citycount = $db->queryFirstField('SELECT count(city) FROM city WHERE nation = %i', $city['nation']);
$renewFront = false;
$cityID = $city['city'];
$cityName = $city['name'];
$defenderNationID = $city['nation'];
$defenderStaticNation = getNationStaticInfo($defenderNationID);
$defenderNationName = $defenderStaticNation['name'];
$defenderNationLogger = new ActionLogger(0, $defenderNationID, $year, $month);
if($defenderNationID) {
$defenderNationDecoration = "<D><b>{$defenderNationName}</b></>의";
} else {
$defenderNationDecoration = "공백지인";
}
$josaUl = JosaUtil::pick($cityName, '을');
$josaYiNation = JosaUtil::pick($attackerNationName, '이');
$josaYiGen = JosaUtil::pick($attackerGeneralName, '이');
$josaYiCity = JosaUtil::pick($cityName, '이');
$attackerLogger->pushGeneralActionLog("<G><b>{$cityName}</b></> 공략에 <S>성공</>했습니다.", ActionLogger::PLAIN);
$attackerLogger->pushGeneralHistoryLog("<G><b>{$cityName}</b></>{$josaUl} <S>점령</>");
$attackerLogger->pushGlobalActionLog("<Y>{$attackerGeneralName}</>{$josaYiGen} <G><b>{$cityName}</b></> 공략에 <S>성공</>했습니다.");
$attackerLogger->pushGlobalHistoryLog("<S><b>【지배】</b></><D><b>{$attackerNationName}</b></>{$josaYiNation} <G><b>{$cityName}</b></>{$josaUl} 지배했습니다.");
$attackerLogger->pushNationalHistoryLog("<Y>{$attackerGeneralName}</>{$josaYiGen} {$defenderNationDecoration} <G><b>{$cityName}</b></> {$josaUl} <S>점령</>");
$defenderNationLogger->pushNationalHistoryLog("<D><b>{$attackerNationName}</b></>의 <Y>{$general['name']}</>에 의해 <G><b>{$cityName}</b></>{$josaYiCity} <O>함락</>");
// 국가 멸망시
//TODO: 국가 멸망 코드를 별도로 작성
if($citycount == 1 && $city['nation'] != 0) {
$losenation = $destnation;
if($defenderNationID && $db->queryFirstField('SELECT count(city) FROM city WHERE nation = %i', $defenderNationID) === 1) {
$defenderNationLogger->flush();
unset($defenderNationLogger);
$josaYi = JosaUtil::pick($losenation['name'], '이');
$josaUl = JosaUtil::pick($losenation['name'], '을');
$history[] = "<C>●</>{$year}{$month}월:<R><b>【멸망】</b></><D><b>{$losenation['name']}</b></>{$josaYi} 멸망하였습니다.";
pushNationHistory($nation['nation'], ["<C>●</>{$year}{$month}월:<D><b>{$losenation['name']}</b></>{$josaUl} 정복"]);
$loseNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation = %i', $defenderNationID);
$lord = new General($db->queryFirstRow(
'SELECT %b FROM general WHERE nation = %i AND officer_level = %i LIMIT 1',
General::mergeQueryColumn(['gold', 'rice', 'experience', 'explevel', 'dedication', 'dedlevel'], 1),
$defenderNationID,
12
), null, $city, $loseNation, $year, $month, false);
$oldNationGenerals = deleteNation($lord, false);
$josaUl = JosaUtil::pick($defenderNationName, '을');
$attackerLogger->pushNationalHistoryLog("<D><b>{$defenderNationName}</b></>{$josaUl} 정복");
$loseGeneralGold = 0;
$loseGeneralRice = 0;
//멸망국 장수들 역사 기록 및 로그 전달
$josaYi = JosaUtil::pick($losenation['name'], '이');
$destroyLog = "<D><b>{$losenation['name']}</b></>{$josaYi} <R>멸망</>했습니다.";
$destroyHistoryLog = "<D><b>{$losenation['name']}</b></>{$josaYi} <R>멸망</>";
// 국가 백업
$oldNation = $db->queryFirstRow('SELECT * FROM nation WHERE nation=%i', $city['nation']);
$oldNationGenerals = $db->query('SELECT * FROM general WHERE nation=%i', $city['nation']);
$oldNation['generals'] = array_map(function($gen){
//다른 코드와는 다르게 공용으로 쓰므로 남겨둠
return $gen['no'];
}, $oldNationGenerals);
$oldNation['aux'] = Json::decode($oldNation['aux']);
$oldNation['history'] = getNationHistoryAll($city['nation']);
foreach($oldNationGenerals as $gen){
$oldGeneralObj = new General($gen, null, null, $oldNation, $year, $month, false);
$loseGold = intdiv($gen['gold'] * (rand()%30+20), 100);
$loseRice = intdiv($gen['rice'] * (rand()%30+20), 100);
$generalLogger = $oldGeneralObj->getLogger();
$generalLogger->pushGeneralHistoryLog($destroyHistoryLog);
$generalLogger->pushGeneralActionLog($destroyLog, ActionLogger::PLAIN);
$generalLogger->pushGeneralActionLog("도주하며 금<C>$loseGold</> 쌀<C>$loseRice</>을 분실했습니다.", ActionLogger::PLAIN);
$oldGeneralObj->increaseVar('gold', -$loseGold);
$oldGeneralObj->increaseVar('rice', -$loseRice);
$oldGeneralObj->addExperience(-$oldGeneralObj->getVar('experience')*0.1, false);
$oldGeneralObj->addDedication(-$oldGeneralObj->getVar('dedication')*0.5, false);
pushOldNationStop($gen['no'], $city['nation']);
foreach($oldNationGenerals as $oldGeneral){
$loseGold = intdiv($oldGeneral->getVar('gold') * (rand()%30+20), 100);
$loseRice = intdiv($oldGeneral->getVar('rice') * (rand()%30+20), 100);
$oldGeneral->getLogger()->pushGeneralActionLog(
"도주하며 금<C>$loseGold</> 쌀<C>$loseRice</>을 분실했습니다.",
ActionLogger::PLAIN
);
$oldGeneral->increaseVar('gold', -$loseGold);
$oldGeneral->increaseVar('rice', -$loseRice);
$oldGeneral->addExperience(-$oldGeneral->getVar('experience')*0.1, false);
$oldGeneral->addDedication(-$oldGeneral->getVar('dedication')*0.5, false);
$loseGeneralGold += $loseGold;
$loseGeneralRice += $loseRice;
$oldGeneralObj->applyDB($db);
$oldGeneral->applyDB($db);
//모두 등용장 발부
if($admin['join_mode'] != 'onlyRandom' && Util::randBool(0.5)) {
$msg = ScoutMessage::buildScoutMessage($general['no'], $gen['no']);
$msg = ScoutMessage::buildScoutMessage($attackerID, $oldGeneral->getID());
if($msg){
$msg->send(true);
}
}
//NPC인 경우 10% 확률로 임관(엔장, 인재, 의병)
if($admin['join_mode'] != 'onlyRandom' && $gen['npc'] >= 2 && $gen['npc'] <= 8 && $gen['npc'] != 5 && Util::randBool(0.1)) {
setGeneralCommand($gen['no'], [0], 'che_임관', ['destNationID'=>$nation['nation']]);
$npcType = $oldGeneral->getVar('npc');
if($admin['join_mode'] != 'onlyRandom' && 2 <= $npcType && $npcType <= 8 && $npcType != 5 && Util::randBool(0.1)) {
$cmd = buildGeneralCommandClass('che_임관', $oldGeneral, $admin, [
'destNationID'=>$attackerNationID
]);
if($cmd->hasFullConditionMet()){
_setGeneralCommand($cmd, [0]);
}
}
}
// 승전국 보상
$losenation['gold'] -= GameConst::$basegold;
$losenation['rice'] -= GameConst::$baserice;
if($losenation['gold'] < 0) { $losenation['gold'] = 0; }
if($losenation['rice'] < 0) { $losenation['rice'] = 0; }
$loseNationGold = Util::valueFit($loseNation['gold'] - GameConst::$basegold, 0);
$loseNationRice = Util::valueFit($loseNation['rice'] - GameConst::$baserice, 0);
$losenation['gold'] += $loseGeneralGold;
$losenation['rice'] += $loseGeneralRice;
$loseNationGold += $loseGeneralGold;
$loseNationRice += $loseGeneralRice;
$losenation['gold'] = intdiv($losenation['gold'], 2);
$losenation['rice'] = intdiv($losenation['gold'], 2);
$loseNationGold = intdiv($loseNationGold, 2);
$loseNationRice = intdiv($loseNationRice, 2);
// 기본량 제외 금쌀50% + 장수들 분실 금쌀50% 흡수
$query = "update nation set gold=gold+'{$losenation['gold']}',rice=rice+'{$losenation['rice']}' where nation='{$general['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$db->update('nation', [
'gold'=>$db->sqleval('gold + %i', $loseNationGold),
'rice'=>$db->sqleval('rice + %i', $loseNationRice),
], 'nation=%i', $attackerNationID);
//아국 수뇌부에게 로그 전달
$query = "select no,name,nation from general where nation='{$general['nation']}' and officer_level>='9'";
$result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$gencount = MYDB_num_rows($result);
$genlog[0] = "<C>●</><D><b>{$losenation['name']}</b></> 정복으로 금<C>{$losenation['gold']}</> 쌀<C>{$losenation['rice']}</>을 획득했습니다.";
for($i=0; $i < $gencount; $i++) {
$gen = MYDB_fetch_array($result);
pushGenLog($gen['no'], $genlog);
$loseNationGoldText = number_format($loseNationGold);
$loseNationRiceText = number_format($loseNationRice);
$resourceLog = "<D><b>{$defenderNationName}</b></> 정복으로 금<C>{$loseNationGoldText}</> 쌀<C>{$loseNationRiceText}</>을 획득했습니다.";
foreach($db->queryFirstColumn(
'SELECT no FROM general WHERE nation=%i AND officer_level>=5', $attackerNationID
) as $attackerChiefID
){
if($attackerChiefID == $attackerID){
$attackerLogger->pushGeneralActionLog($resourceLog, ActionLogger::PLAIN);
}
else{
$chiefLogger = new ActionLogger($attackerChiefID, $attackerNationID, $year, $month);
$chiefLogger->pushGeneralActionLog($resourceLog, ActionLogger::PLAIN);
$chiefLogger->flush();
}
}
//분쟁기록 모두 지움
DeleteConflict($city['nation']);
// 전 도시 공백지로
$query = "update city set nation='0',conflict='{}',term=0 where nation='{$city['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
// 전 장수 소속 무소속으로, 재야로, 부대 탈퇴
$db->update('general',[
'nation'=>0,
'belong'=>0,
'officer_level'=>0,
'officer_city'=>0,
'troop'=>0,
], 'nation=%i',$city['nation']);
// 부대도 삭제
$query = "delete from troop where nation='{$city['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
// 외교 삭제
$query = "delete from diplomacy where me='{$city['nation']}' or you='{$city['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$db->insert('ng_old_nations', [
'server_id'=>UniqueConst::$serverID,
'nation'=>$city['nation'],
'data'=>Json::encode($oldNation)
]);
// 국가 삭제
$query = "delete from nation where nation='{$city['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$db->delete('nation_turn', 'nation_id=%i', $city['nation']);
$renewFront = true;
// 멸망이 아니면
} else {
// 태수,군사,종사은 일반으로...
$db->update('general',[
'officer_level'=>1,
'officer_city'=>0,
], 'officer_city = %i',$city['city']);
], 'officer_city = %i',$cityID);
//수도였으면 긴급 천도
if(isset($destnation['capital']) && $destnation['capital'] == $city['city']) {
$minCity = findNextCapital($city['city'], $destnation['nation']);
if($defenderNationID && $defenderStaticNation == $cityID) {
$minCity = findNextCapital($cityID, $defenderNationID);
$minCityName = CityConst::byID($minCity)->name;
$josaYi = JosaUtil::pick($destnation['name'], '이');
$history[] = "<C>●</>{$year}{$month}월:<M><b>【긴급천도】</b></><D><b>{$destnation['name']}</b></>{$josaYi} 수도가 함락되어 <G><b>$minCityName</b></>으로 긴급천도하였습니다.";
$josaYi = JosaUtil::pick($defenderNationName, '이');
$attackerLogger->pushGlobalHistoryLog("<M><b>【긴급천도】</b></><D><b>{$defenderNationName}</b></>{$josaYi} 수도가 함락되어 <G><b>$minCityName</b></>으로 긴급천도하였습니다.");
$moveLog = "수도가 함락되어 <G><b>$minCityName</b></>으로 <M>긴급천도</>합니다.";
//아국 수뇌부에게 로그 전달
$query = "select no,name,nation from general where nation='{$destnation['nation']}' and officer_level>='5'";
$result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$gencount = MYDB_num_rows($result);
$genlog = ["<C>●</>수도가 함락되어 <G><b>$minCityName</b></>으로 <M>긴급천도</>합니다."];
for($i=0; $i < $gencount; $i++) {
$gen = MYDB_fetch_array($result);
pushGenLog($gen['no'], $genlog);
foreach($db->queryFirstColumn(
'SELECT no FROM general WHERE nation=%i AND officer_level>=5', $defenderNationID
) as $defenderChiefID
){
$chiefLogger = new ActionLogger($defenderChiefID, $defenderNationID, $year, $month);
$chiefLogger->pushGeneralActionLog($moveLog, ActionLogger::PLAIN);
$chiefLogger->flush();
}
//천도
$query = "update nation set capital='$minCity',gold=gold*0.5,rice=rice*0.5 where nation='{$destnation['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$db->update('nation', [
'capital'=>$minCity,
'gold'=>$db->sqleval('gold * 0.5'),
'rice'=>$db->sqleval('rice * 0.5'),
], 'nation=%i', $defenderNationID);
//보급도시로 만듬
$query = "update city set supply=1 where city='$minCity'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$db->update('city', [
'supply'=>1
], 'city=%i', $minCity);
//수뇌부 이동
$query = "update general set city='$minCity' where nation='{$destnation['nation']}' and officer_level>='5'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$db->update('general', [
'city'=>$minCity
], 'nation=%i AND officer_level>=5',$defenderNationID);
//장수 사기 감소
$query = "update general set atmos=atmos*0.8 where nation='{$destnation['nation']}'";
MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),"");
$db->update('general', [
'atmos'=>$db->sqleval('atmos*0.8')
], 'nation=%i',$defenderNationID);
refreshNationStaticInfo();
}
@@ -675,20 +650,23 @@ function ConquerCity($admin, $general, $city, $nation, $destnation) {
$conquerNation = getConquerNation($city);
if ($conquerNation == $general['nation']) {
if ($conquerNation == $attackerNationID) {
// 이동
$db->update('general', [
'city'=>$city['city']
'city'=>$cityID
], 'no=%i', $general['no']);
}
else{
$conquerNationName = $db->queryFirstField('SELECT `name` FROM nation WHERE nation=%i', $conquerNation);
$conquerNationName = getNationStaticInfo($conquerNation)['name'];
$conquerNationLogger = new ActionLogger(0, $conquerNation, $year, $month);
$josaUl = JosaUtil::pick($city['name'], '을');
$josaUl = JosaUtil::pick($cityName, '을');
$josaYi = JosaUtil::pick($conquerNationName, '이');
$history[] = "<C>●</>{$year}{$month}월:<Y><b>【분쟁협상】</b></><D><b>{$conquerNationName}</b></>{$josaYi} 영토분쟁에서 우위를 점하여 <G><b>{$city['name']}</b></>{$josaUl} 양도받았습니다.";
pushNationHistory($nation['nation'], ["<C>●</>{$year}{$month}월:<G><b>{$city['name']}</b></>{$josaUl} <D><b>{$conquerNationName}</b></>에 <Y>양도</>"]);
pushNationHistory($conquerNation, ["<C>●</>{$year}{$month}월:<D><b>{$nation['name']}</b></>에서 <G><b>{$city['name']}</b></>{$josaUl} <S>양도</> 받음"]);
$attackerLogger->pushGlobalHistoryLog(
"<Y><b>【분쟁협상】</b></><D><b>{$conquerNationName}</b></>{$josaYi} 영토분쟁에서 우위를 점하여 <G><b>{$cityName}</b></>{$josaUl} 양도받았습니다."
);
$conquerNationLogger->pushNationalHistoryLog("<D><b>{$attackerNationName}</b></>에서 <G><b>{$city['name']}</b></>{$josaUl} <S>양도</> 받음");
$attackerLogger->pushNationalHistoryLog("<G><b>{$city['name']}</b></>{$josaUl} <D><b>{$conquerNationName}</b></>에 <Y>양도</>");
}
$query = [
@@ -709,21 +687,19 @@ function ConquerCity($admin, $general, $city, $nation, $destnation) {
$query['wall'] = $db->sqleval('wall_max/2');
}
$db->update('city', $query, 'city=%i', (int)$city['city']);
$db->update('city', $query, 'city=%i', $cityID);
//전방설정
$nearNationsID = $db->queryFirstColumn(
'SELECT distinct(nation) FROM city WHERE nation != 0 AND city IN %li',
array_merge(array_keys(CityConst::byID($city['city'])->path), [$city['city']])
array_merge(array_keys(CityConst::byID($cityID)->path), [$cityID])
);
$nearNationsID[] = $conquerNation;
$nearNationsID = array_unique($nearNationsID);
foreach($nearNationsID as $nationNationID){
SetNationFront($nationNationID);
}
SetNationFront($conquerNation);
pushGenLog($general['no'], $log);
pushGeneralPublicRecord($alllog, $year, $month);
pushWorldHistory($history);
}
function findNextCapital(int $capitalID, int $nationID):int{
@@ -740,8 +716,6 @@ function findNextCapital(int $capitalID, int $nationID):int{
$cities[$row['city']] = $row['pop'];
};
foreach($distList as $dist=>$distSubList){
$maxCityPop = 0;
$minCity = 0;
+2 -6
View File
@@ -221,13 +221,9 @@ class che_임관 extends Command\GeneralCommand{
$nationList = $db->query('SELECT nation,`name`,color,scout,gennum FROM nation');
shuffle($nationList);
$nationList = Util::convertArrayToDict($nationList, 'nation');
$nationStor = KVStorage::getStorage($db, 'nation_env');
//NOTE: join 안할것임
$scoutMsgs = $nationStor->getValues(array_map(function($nationID){
return "nation_scout_msg_{$nationID}";
}, array_keys($nationList)));
foreach($scoutMsgs as $nationIDPack=>$scoutMsg){
$nationID = Util::toInt(Util::array_last(explode('_', $nationIDPack)));
$scoutMsgs = KVStorage::getValuesFromInterNamespace($db, 'nation_env', 'scout_msg');
foreach($scoutMsgs as $nationID=>$scoutMsg){
$nationList[$nationID]['scoutmsg'] = $scoutMsg;
}
+7 -7
View File
@@ -18,7 +18,6 @@ use function sammo\buildNationTypeClass;
use function sammo\refreshNationStaticInfo;
use function sammo\GetNationColors;
use function sammo\getAllNationStaticInfo;
use function sammo\DeleteConflict;
use function sammo\deleteNation;
@@ -87,19 +86,20 @@ class che_해산 extends Command\GeneralCommand{
$general->increaseVarWithLimit('gold', 0, 0, GameConst::$defaultGold);
$general->increaseVarWithLimit('rice', 0, 0, GameConst::$defaultRice);
DeleteConflict($nationID);
deleteNation($general);
refreshNationStaticInfo();
$logger = $general->getLogger();
$logger->pushGeneralActionLog("세력을 해산했습니다. <1>$date</>");
$logger->pushGlobalActionLog("<Y>{$generalName}</>{$josaYi} 세력을 해산했습니다.");
$logger->pushGeneralHistoryLog("<D><b>{$nationName}</b></>{$josaUl} 해산");
$general->setResultTurn(new LastTurn(static::getName(), $this->arg));
$oldNationGenerals = deleteNation($general, false);
foreach($oldNationGenerals as $oldGeneral){
$oldGeneral->setVar('makelimit', 12);
$oldGeneral->applyDB($db);
}
$general->applyDB($db);
return true;
+3 -2
View File
@@ -142,10 +142,11 @@ class che_천도 extends Command\NationCommand
$lastTurn = $this->getLastTurn();
$commandName = $this->getName();
$nationStor = \sammo\KVStorage::getStorage(DB::db(), 'nation_env');
$general = $this->getGeneral();
$nationID = $general->getNationID();
$nationStor->setValue("last천도Trial_{$nationID}", [$general->getVar('officer_level'), $general->getTurnTime()]);
$nationStor = \sammo\KVStorage::getStorage(DB::db(), $nationID, 'nation_env');
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTime()];
if ($lastTurn->getCommand() != $commandName || $lastTurn->getArg() !== $this->arg) {
$this->setResultTurn(new LastTurn(
+4 -4
View File
@@ -1648,19 +1648,19 @@ class GeneralAI
$db = DB::db();
$nationStor = KVStorage::getStorage($db, 'nation_env');
$nationStor = KVStorage::getStorage($db, $general->getNationID(), 'nation_env');
$turnTerm = $this->env['turnterm'];
//천도를 한턴 넣었다면 계속 넣는다.
if($lastTurn->getCommand() === '천도' && $lastTurn->getArg()['destCityID'] != $this->nation['capital']){
$cmd = buildNationCommandClass('che_천도', $this->general, $this->env, $lastTurn, $lastTurn->getArg());
if($cmd->hasFullConditionMet()){
$nationStor->setValue("last천도Trial_{$this->nation['nation']}", [$general->getVar('officer_level'), $general->getTurnTime()]);
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTime()];
return $cmd;
}
}
$lastTrial = $nationStor->getValue("last천도Trial_{$this->nation['nation']}");
$lastTrial = $nationStor->last천도Trial;
if($lastTrial){
[$lastTrialLevel, $lastTrialTurnTime] = $lastTrial;
$timeDiffSeconds = TimeUtil::DateIntervalToSeconds(
@@ -1776,7 +1776,7 @@ class GeneralAI
}
$nationStor->setValue("last천도Trial_{$this->nation['nation']}", [$general->getVar('officer_level'), $general->getTurnTime()]);
$nationStor->last천도Trial = [$general->getVar('officer_level'), $general->getTurnTime()];
return $cmd;
}
+23 -11
View File
@@ -15,18 +15,25 @@ class LastTurn{
$this->setSeq($seq);
}
static function fromRaw(?array $raw):self{
if(!$raw){
return new static();
}
$obj = new static(
$raw['command']??null,
$raw['arg']??null,
$raw['term']??null,
$raw['seq']??null
);
return $obj;
}
static function fromJson(?string $json):self{
if($json === null || $json === ''){
return new static();
}
$values = Json::decode($json);
$obj = new static(
$values['command']??null,
$values['arg']??null,
$values['term']??null,
$values['seq']??null
);
return $obj;
return static::fromRaw(Json::decode($json));
}
function setCommand(?string $command){
@@ -64,7 +71,7 @@ class LastTurn{
return $this->seq;
}
function toJson():string{
function toRaw():array{
$result = [
'command'=>$this->command
];
@@ -77,10 +84,15 @@ class LastTurn{
if($this->seq !== null){
$result['seq'] = $this->seq;
}
return Json::encode($result);
return $result;
}
function toJson():string{
return Json::encode($this->toRaw());
}
function duplicate():LastTurn{
return new static($this->command, $this->arg, $this->term);
return new static($this->command, $this->arg, $this->term, $this->seq);
}
}
-1
View File
@@ -123,7 +123,6 @@ class ResetHelper{
}
}
(KVStorage::getStorage($db, 'nation_env'))->resetValues();
$gameStor = KVStorage::getStorage($db, 'game_env');
$gameStor->resetValues();
$gameStor->next_season_idx = $seasonIdx;
+2 -3
View File
@@ -83,7 +83,7 @@ class Nation{
}
$db = DB::db();
$nationStor = KVStorage::getStorage($db, 'nation_env');
$nationStor = KVStorage::getStorage($db, $this->id, 'nation_env');
$otherNations = $db->queryFirstColumn('SELECT nation FROM nation');
$db->insert('nation', [
@@ -111,8 +111,7 @@ class Nation{
], 'city IN %li', $cities);
}
$scoutKey = "nation_scout_msg_{$this->id}";
$nationStor->{$scoutKey} = $this->infoText;
$nationStor->scout_msg = $this->infoText;
$diplomacy = [];
+4 -5
View File
@@ -246,9 +246,8 @@ WHERE turntime < %s ORDER BY turntime ASC, `no` ASC',
$hasNationTurn = false;
if($general->getVar('nation') != 0 && $general->getVar('officer_level') >= 5){
$nationStor = KVStorage::getStorage($db, 'nation_env');
$lastNationTurnKey = "turn_last_{$general->getVar('nation')}_{$general->getVar('officer_level')}";
$lastNationTurn = $nationStor->getValue($lastNationTurnKey);
$nationStor = KVStorage::getStorage($db, $general->getNationID(), 'nation_env');
$lastNationTurnKey = "turn_last_{$general->getVar('officer_level')}";
//수뇌 몇 없는데 매번 left join 하는건 낭비인것 같다.
$rawNationTurn = $db->queryFirstRow(
'SELECT action, arg FROM nation_turn WHERE nation_id = %i AND officer_level = %i AND turn_idx =0',
@@ -258,7 +257,7 @@ WHERE turntime < %s ORDER BY turntime ASC, `no` ASC',
$hasNationTurn = true;
$nationCommand = $rawNationTurn['action']??null;
$nationArg = Json::decode($rawNationTurn['arg']??null);
$lastNationTurn = LastTurn::fromJson($lastNationTurn);
$lastNationTurn = LastTurn::fromRaw($nationStor->getValue($lastNationTurnKey));
$nationCommandObj = buildNationCommandClass($nationCommand, $general, $env, $lastNationTurn, $nationArg);
}
@@ -279,7 +278,7 @@ WHERE turntime < %s ORDER BY turntime ASC, `no` ASC',
$resultNationTurn = $turnObj->processNationCommand(
$nationCommandObj
);
$nationStor->setValue($lastNationTurnKey, $resultNationTurn->toJson());
$nationStor->setValue($lastNationTurnKey, $resultNationTurn->toRaw());
}
if($ai){
+2 -6
View File
@@ -21,13 +21,9 @@ $gencount = $db->queryFirstField('SELECT count(`no`) FROM general WHERE npc<2');
$nationList = $db->query('SELECT nation,`name`,color,scout FROM nation');
shuffle($nationList);
$nationList = Util::convertArrayToDict($nationList, 'nation');
$nationStor = KVStorage::getStorage($db, 'nation_env');
//NOTE: join 안할것임
$scoutMsgs = $nationStor->getValues(array_map(function($nationID){
return "nation_scout_msg_{$nationID}";
}, array_keys($nationList)));
foreach($scoutMsgs as $nationIDPack=>$scoutMsg){
$nationID = Util::toInt(Util::array_last(explode('_', $nationIDPack)));
$scoutMsgs = KVStorage::getValuesFromInterNamespace($db, 'nation_env', 'scout_msg');
foreach($scoutMsgs as $nationID=>$scoutMsg){
$nationList[$nationID]['scoutmsg'] = $scoutMsg;
}
?>
+1
View File
@@ -4,6 +4,7 @@ DROP TABLE IF EXISTS `general_turn`;
#
DROP TABLE IF EXISTS nation;
DROP TABLE IF EXISTS `nation_turn`;
DROP TABLE IF EXISTS nation_env;
#
DROP TABLE IF EXISTS board;
+11
View File
@@ -587,6 +587,17 @@ CREATE TABLE IF NOT EXISTS `storage` (
COLLATE='utf8mb4_general_ci'
ENGINE=Aria;
CREATE TABLE IF NOT EXISTS `nation_env` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`namespace` INT(11) NOT NULL, #storage와 !
`key` VARCHAR(40) NOT NULL,
`value` LONGTEXT NOT NULL CHECK (json_valid(`value`)),
PRIMARY KEY (`id`),
UNIQUE INDEX `key` (`namespace`, `key`)
)
COLLATE='utf8mb4_general_ci'
ENGINE=Aria;
CREATE TABLE IF NOT EXISTS `betting` (
`general_id` INT(11) NOT NULL,
`bet0` INT(11) NOT NULL DEFAULT 0,
+13 -2
View File
@@ -11,7 +11,7 @@ class KVStorage{
static private $storageList = [];
static public function getStorage(\MeekroDB $db, string $storNamespace, string $tableName='storage'):self{
static public function getStorage(\MeekroDB $db, $storNamespace, string $tableName='storage'):self{
$obj_id = spl_object_hash($db);
$fullKey = $obj_id.','.$storNamespace.','.$tableName;
if(key_exists($fullKey, static::$storageList)){
@@ -22,12 +22,23 @@ class KVStorage{
return $obj;
}
public function __construct(\MeekroDB $db, string $storNamespace, string $tableName='storage'){
public function __construct(\MeekroDB $db, $storNamespace, string $tableName='storage'){
$this->db = $db;
$this->storNamespace = $storNamespace;
$this->tableName = $tableName;
}
public static function getValuesFromInterNamespace(\MeekroDB $db, string $tableName, $key):array{
$result = [];
foreach($db->queryAllLists(
'SELECT `namespace`, `value` FROM %b WHERE `key`=%s', $tableName, $key
) as [$namespaceName, $value])
{
$result[$namespaceName] = Json::decode($value);
}
return $result;
}
public function __get($key) {
return $this->getValue($key);
}