국기 변경 수정, 아이템 보상 추가

This commit is contained in:
2020-05-05 17:24:03 +09:00
parent 8b8f749006
commit a378ac8738
8 changed files with 1240 additions and 1045 deletions
+1 -1
View File
@@ -328,7 +328,7 @@ if ($admin['voteopen'] >= 2 || $isVoteAdmin) {
continue;
}
$per = round($nationVote[$nation['nation']][$k]??0 / $memCount * 100, 1);
$per = round(($nationVote[$nation['nation']][$k]??0) / $memCount * 100, 1);
if($i == $voteTypeCount-1){
$per = 100-$totalPer;
+322 -231
View File
@@ -1,4 +1,5 @@
<?php
namespace sammo;
use sammo\Event\Action;
@@ -88,7 +89,8 @@ function getAllNationStaticInfo()
return getNationStaticInfo(-1);
}
function GetImageURL($imgsvr, $filepath='') {
function GetImageURL($imgsvr, $filepath = '')
{
if ($imgsvr == 0) {
return ServConfig::getSharedIconPath($filepath);
} else {
@@ -100,7 +102,8 @@ function GetImageURL($imgsvr, $filepath='') {
* @param null|int $con 장수의 벌점
* @param null|int $conlimit 최대 벌점
*/
function checkLimit($con = null) {
function checkLimit($con = null)
{
$session = Session::getInstance();
if ($session->userGrade >= 4) {
return 0;
@@ -124,11 +127,13 @@ function checkLimit($con = null) {
}
}
function getBlockLevel() {
function getBlockLevel()
{
return DB::db()->queryFirstField('select block from general where no = %i', Session::getInstance()->generalID);
}
function getRandGenName() {
function getRandGenName()
{
$firstname = Util::choiceRandom(GameConst::$randGenFirstName);
$middlename = Util::choiceRandom(GameConst::$randGenMiddleName);
$lastname = Util::choiceRandom(GameConst::$randGenLastName);
@@ -138,7 +143,8 @@ function getRandGenName() {
function cityInfo(General $generalObj) {
function cityInfo(General $generalObj)
{
$db = DB::db();
// 도시 정보
@@ -174,7 +180,8 @@ function cityInfo(General $generalObj) {
return $templates->render('mainCityInfo', $city);
}
function myNationInfo() {
function myNationInfo()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
@@ -210,8 +217,11 @@ function myNationInfo() {
<tr>
<td colspan=4 ";
if($me['nation'] == 0) { 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']} "; }
if ($me['nation'] == 0) {
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']}";
}
echo "
</td>
@@ -223,22 +233,34 @@ 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'>";
echo $level12 ? $level12['name'] : "-";
echo "</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'>";
echo $level11 ? $level11['name'] : "-";
echo "</td>
</tr>
<tr>
<td class='bg1 center'><b>총주민</b></td>
<td class='center'>";echo $me['nation']==0?"해당 없음":"{$city['totpop']}/{$city['maxpop']}";echo "</td>
<td class='center'>";
echo $me['nation'] == 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 "</td>
<td class='center'>";
echo $me['nation'] == 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 "</td>
<td class='center'>";
echo $me['nation'] == 0 ? "해당 없음" : "{$nation['gold']}";
echo "</td>
<td class='bg1 center'><b>병 량</b></td>
<td class='center'>";echo $me['nation']==0?"해당 없음":"{$nation['rice']}";echo "</td>
<td class='center'>";
echo $me['nation'] == 0 ? "해당 없음" : "{$nation['rice']}";
echo "</td>
</tr>
<tr>
<td class='bg1 center'><b>지급률</b></td>
@@ -260,8 +282,11 @@ function myNationInfo() {
$techCall = getTechCall($nation['tech']);
if(TechLimit($admin['startyear'], $admin['year'], $nation['tech'])) { $nation['tech'] = "<font color=magenta>".floor($nation['tech'])."</font>"; }
else { $nation['tech'] = "<font color=limegreen>".floor($nation['tech'])."</font>"; }
if (TechLimit($admin['startyear'], $admin['year'], $nation['tech'])) {
$nation['tech'] = "<font color=magenta>" . floor($nation['tech']) . "</font>";
} else {
$nation['tech'] = "<font color=limegreen>" . floor($nation['tech']) . "</font>";
}
$nation['tech'] = "$techCall / {$nation['tech']}";
@@ -272,19 +297,29 @@ function myNationInfo() {
$nation['war'] = "<font color=white>해당 없음</font>";
$nation['power'] = "<font color=white>해당 없음</font>";
} else {
if($nation['strategic_cmd_limit'] != 0) { $nation['strategic_cmd_limit'] = "<font color=red>{$nation['strategic_cmd_limit']}턴</font>"; }
else { $nation['strategic_cmd_limit'] = "<font color=limegreen>가 능</font>"; }
if ($nation['strategic_cmd_limit'] != 0) {
$nation['strategic_cmd_limit'] = "<font color=red>{$nation['strategic_cmd_limit']}</font>";
} else {
$nation['strategic_cmd_limit'] = "<font color=limegreen>가 능</font>";
}
if($nation['surlimit'] != 0) { $nation['surlimit'] = "<font color=red>{$nation['surlimit']}턴</font>"; }
else { $nation['surlimit'] = "<font color=limegreen>가 능</font>"; }
if($nation['scout'] != 0) { $nation['scout'] = "<font color=red>금 지</font>"; }
else { $nation['scout'] = "<font color=limegreen>허 가</font>"; }
if($nation['war'] != 0) { $nation['war'] = "<font color=red>금 지</font>"; }
else { $nation['war'] = "<font color=limegreen>허 가</font>"; }
if ($nation['surlimit'] != 0) {
$nation['surlimit'] = "<font color=red>{$nation['surlimit']}</font>";
} else {
$nation['surlimit'] = "<font color=limegreen>가 능</font>";
}
if ($nation['scout'] != 0) {
$nation['scout'] = "<font color=red>금 지</font>";
} else {
$nation['scout'] = "<font color=limegreen>허 가</font>";
}
if ($nation['war'] != 0) {
$nation['war'] = "<font color=red>금 지</font>";
} else {
$nation['war'] = "<font color=limegreen>허 가</font>";
}
}
echo "
@@ -292,15 +327,21 @@ function myNationInfo() {
</tr>
<tr>
<td style='text-align:center;' class='bg1'><b>속 령</b></td>
<td style='text-align:center;'>";echo $me['nation']==0?"-":"{$city['cnt']}"; echo "</td>
<td style='text-align:center;'>";
echo $me['nation'] == 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 "</td>
<td style='text-align:center;'>";
echo $me['nation'] == 0 ? "-" : "{$general['cnt']}";
echo "</td>
</tr>
<tr>
<td style='text-align:center;' class='bg1'><b>국 력</b></td>
<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 "</td>
<td style='text-align:center;'>";
echo $me['nation'] == 0 ? "-" : "{$nation['tech']}";
echo "</td>
</tr>
<tr>
<td style='text-align:center;' class='bg1'><b>전 략</b></td>
@@ -318,21 +359,21 @@ function myNationInfo() {
";
}
function checkSecretMaxPermission($penalty){
function checkSecretMaxPermission($penalty)
{
$secretMax = 4;
if ($penalty['noTopSecret'] ?? false) {
$secretMax = 1;
}
else if($penalty['noChief']??false){
} else if ($penalty['noChief'] ?? false) {
$secretMax = 1;
}
else if($penalty['noAmbassador']??false){
} else if ($penalty['noAmbassador'] ?? false) {
$secretMax = 2;
}
return $secretMax;
}
function checkSecretPermission(array $me, $checkSecretLimit=true){
function checkSecretPermission(array $me, $checkSecretLimit = true)
{
if (!key_exists('penalty', $me) || !key_exists('permission', $me)) {
trigger_error('canAccessSecret() 함수에 필요한 인자가 부족');
}
@@ -358,20 +399,15 @@ function checkSecretPermission(array $me, $checkSecretLimit=true){
if ($me['officer_level'] == 12) {
$secretMin = 4;
}
else if($me['permission'] == 'ambassador'){
} else if ($me['permission'] == 'ambassador') {
$secretMin = 4;
}
else if($me['permission'] == 'auditor'){
} else if ($me['permission'] == 'auditor') {
$secretMin = 3;
}
else if($me['officer_level'] >= 5){
} else if ($me['officer_level'] >= 5) {
$secretMin = 2;
}
else if($me['officer_level'] > 1){
} else if ($me['officer_level'] > 1) {
$secretMin = 1;
}
else if($checkSecretLimit){
} else if ($checkSecretLimit) {
$db = DB::db();
$secretLimit = $db->queryFirstField('SELECT secretlimit FROM nation WHERE nation = %i', $me['nation']);
if ($me['belong'] >= $secretLimit) {
@@ -382,7 +418,8 @@ function checkSecretPermission(array $me, $checkSecretLimit=true){
return min($secretMin, $secretMax);
}
function addCommand($typename, $value, $valid = 1, $color=0) {
function addCommand($typename, $value, $valid = 1, $color = 0)
{
if ($valid == 1) {
switch ($color) {
case 0:
@@ -404,7 +441,8 @@ function addCommand($typename, $value, $valid = 1, $color=0) {
}
}
function commandGroup($typename, $type=0) {
function commandGroup($typename, $type = 0)
{
if ($type == 0) {
echo "
<optgroup label='{$typename}' style='color:skyblue;background-color:black;'>";
@@ -414,7 +452,8 @@ function commandGroup($typename, $type=0) {
}
}
function printCommandTable(General $generalObj) {
function printCommandTable(General $generalObj)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$userID = Session::getUserID();
@@ -430,8 +469,7 @@ function printCommandTable(General $generalObj) {
$getCompensateClassName = function ($value) {
if ($value > 0) {
return 'compensatePositive';
}
else if($value < 0){
} else if ($value < 0) {
return 'compensateNegative';
}
return 'compensateNeutral';
@@ -448,11 +486,7 @@ function printCommandTable(General $generalObj) {
continue;
}
?>
<option
class='commandBasic <?=$getCompensateClassName($commandObj->getCompensationStyle())?> <?=$commandObj->hasMinConditionMet()?'':'commandImpossible'?>'
value='<?=Util::getClassNameFromObj($commandObj)?>'
data-reqArg='<?=($commandObj::$reqArg)?'true':'false'?>'
><?=$commandObj->getCommandDetailTitle()?><?=$commandObj->hasMinConditionMet()?'':'(불가)'?></option>
<option class='commandBasic <?= $getCompensateClassName($commandObj->getCompensationStyle()) ?> <?= $commandObj->hasMinConditionMet() ? '' : 'commandImpossible' ?>' value='<?= Util::getClassNameFromObj($commandObj) ?>' data-reqArg='<?= ($commandObj::$reqArg) ? 'true' : 'false' ?>'><?= $commandObj->getCommandDetailTitle() ?><?= $commandObj->hasMinConditionMet() ? '' : '(불가)' ?></option>
<?php
}
@@ -466,7 +500,8 @@ function printCommandTable(General $generalObj) {
<?php
}
function chiefCommandTable(General $generalObj) {
function chiefCommandTable(General $generalObj)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$userID = Session::getUserID();
@@ -482,8 +517,7 @@ function chiefCommandTable(General $generalObj) {
$getCompensateClassName = function ($value) {
if ($value > 0) {
return 'compensatePositive';
}
else if($value < 0){
} else if ($value < 0) {
return 'compensateNegative';
}
return 'compensateNeutral';
@@ -500,11 +534,7 @@ function chiefCommandTable(General $generalObj) {
continue;
}
?>
<option
class='commandBasic <?=$getCompensateClassName($commandObj->getCompensationStyle())?> <?=$commandObj->hasMinConditionMet()?'':'commandImpossible'?>'
value='<?=Util::getClassNameFromObj($commandObj)?>'
data-reqArg='<?=($commandObj::$reqArg)?'true':'false'?>'
><?=$commandObj->getCommandDetailTitle()?><?=$commandObj->hasMinConditionMet()?'':'(불가)'?></option>
<option class='commandBasic <?= $getCompensateClassName($commandObj->getCompensationStyle()) ?> <?= $commandObj->hasMinConditionMet() ? '' : 'commandImpossible' ?>' value='<?= Util::getClassNameFromObj($commandObj) ?>' data-reqArg='<?= ($commandObj::$reqArg) ? 'true' : 'false' ?>'><?= $commandObj->getCommandDetailTitle() ?><?= $commandObj->hasMinConditionMet() ? '' : '(불가)' ?></option>
<?php
}
@@ -518,7 +548,8 @@ function chiefCommandTable(General $generalObj) {
<?php
}
function generalInfo(General $generalObj) {
function generalInfo(General $generalObj)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -536,16 +567,14 @@ function generalInfo(General $generalObj) {
if ($generalObj->getVar('troop') == 0) {
$troopInfo = '-';
}
else{
} else {
$troopCity = $db->queryFirstField('SELECT city FROM general WHERE no=%i', $generalObj->getVar('troop'));
$troopTurn = $db->queryFirstField('SELECT `brief` FROM general_turn WHERE general_id = %i AND turn_idx = 0', $generalObj->getVar('troop'));
$troopInfo = $db->queryFirstField('SELECT name FROM troop WHERE troop_leader = %i', $generalObj->getVar('troop'));
if ($troopTurn !== '집합') {
$troopInfo = "<strike style='color:gray;'>{$troopInfo}</strike>";
}
else if($troopCity != $generalObj->getCityID()){
} else if ($troopCity != $generalObj->getCityID()) {
$troopCityName = CityConst::byID($troopCity)->name;
$troopInfo = "<span style='color:orange;'>{$troopInfo}({$troopCityName})</span>";
}
@@ -572,20 +601,37 @@ function generalInfo(General $generalObj) {
$injury = $generalObj->getVar('injury');
if($injury > 60) { $color = "<font color=red>"; $injury = "위독"; }
elseif($injury > 40) { $color = "<font color=magenta>"; $injury = "심각"; }
elseif($injury > 20) { $color = "<font color=orange>"; $injury = "중상"; }
elseif($injury > 0) { $color = "<font color=yellow>"; $injury = "경상"; }
else { $color = "<font color=white>"; $injury = "건강"; }
if ($injury > 60) {
$color = "<font color=red>";
$injury = "위독";
} elseif ($injury > 40) {
$color = "<font color=magenta>";
$injury = "심각";
} elseif ($injury > 20) {
$color = "<font color=orange>";
$injury = "중상";
} elseif ($injury > 0) {
$color = "<font color=yellow>";
$injury = "경상";
} else {
$color = "<font color=white>";
$injury = "건강";
}
$remaining = (new \DateTimeImmutable($generalObj->getTurnTime()))->diff(new \DateTimeImmutable())->i;
if($nation['color'] == "") { $nation['color'] = "#000000"; }
if ($nation['color'] == "") {
$nation['color'] = "#000000";
}
$age = $generalObj->getVar('age');
if($age < GameConst::$retirementYear*0.75) {$age = "<font color=limegreen>{$age} 세</font>"; }
elseif($age < GameConst::$retirementYear) { $age = "<font color=yellow>{$age} 세</font>"; }
else { $age = "<font color=red>{$age} 세</font>"; }
if ($age < GameConst::$retirementYear * 0.75) {
$age = "<font color=limegreen>{$age} 세</font>";
} elseif ($age < GameConst::$retirementYear) {
$age = "<font color=yellow>{$age} 세</font>";
} else {
$age = "<font color=red>{$age} 세</font>";
}
$connectCnt = round($generalObj->getVar('connect'), -1);
$specialDomestic = $generalObj->getVar('special') === GameConst::$defaultSpecialDomestic
@@ -599,11 +645,9 @@ function generalInfo(General $generalObj) {
$atmosBonus = $generalObj->onCalcStat($generalObj, 'bonusAtmos', $atmos) - $atmos;
if ($atmosBonus > 0) {
$atmos = "<font color=cyan>{$atmos} (+{$atmosBonus})</font>";
}
else if($atmosBonus < 0){
} else if ($atmosBonus < 0) {
$atmos = "<font color=magenta>{$atmos} ({$atmosBonus})</font>";
}
else{
} else {
$atmos = "$atmos";
}
@@ -611,25 +655,24 @@ function generalInfo(General $generalObj) {
$trainBonus = $generalObj->onCalcStat($generalObj, 'bonusTrain', $train) - $train;
if ($trainBonus > 0) {
$train = "<font color=cyan>{$train} (+{$trainBonus})</font>";
}
else if($trainBonus < 0){
} else if ($trainBonus < 0) {
$train = "<font color=magenta>{$train} ({$trainBonus})</font>";
}
else{
} else {
$train = "$train";
}
if ($generalObj->getVar('defence_train') === 999) {
$defenceTrain = "<font color=red>수비 안함</font>";
}
else{
} else {
$defenceTrain = "<font color=limegreen>수비 함(훈사{$generalObj->getVar('defence_train')})</font>";
}
$crewType = $generalObj->getCrewTypeObj();
$weapImage = ServConfig::$gameImagePath . "/crewtype{$crewType->id}.png";
if($show_img_level < 2) { $weapImage = ServConfig::$sharedIconPath."/default.jpg"; };
if ($show_img_level < 2) {
$weapImage = ServConfig::$sharedIconPath . "/default.jpg";
};
$imagePath = GetImageURL(...$generalObj->getVars('imgsvr', 'picture'));
echo "<table width=498 class='tb_layout bg2'>
<tr>
@@ -704,7 +747,8 @@ function generalInfo(General $generalObj) {
</table>";
}
function generalInfo2(General $generalObj) {
function generalInfo2(General $generalObj)
{
$general = $generalObj->getRaw();
$winRate = round($generalObj->getRankVar('killnum') / max($generalObj->getRankVar('warnum'), 1) * 100, 2);
@@ -713,22 +757,18 @@ function generalInfo2(General $generalObj) {
$experienceBonus = $generalObj->onCalcStat($generalObj, 'experience', 10000) - 10000;
if ($experienceBonus > 0) {
$experience = "<font color=cyan>" . getHonor($general['experience']) . " ({$general['experience']})</font>";
}
else if($experienceBonus < 0){
} else if ($experienceBonus < 0) {
$experience = "<font color=magenta>" . getHonor($general['experience']) . " ({$general['experience']})</font>";
}
else{
} else {
$experience = getHonor($general['experience']) . " ({$general['experience']})";
}
$dedicationBonus = $generalObj->onCalcStat($generalObj, 'dedication', 10000) - 10000;
if ($dedicationBonus > 0) {
$dedication = "<font color=cyan>" . getHonor($general['dedication']) . " ({$general['dedication']})</font>";
}
else if($dedicationBonus < 0){
} else if ($dedicationBonus < 0) {
$dedication = "<font color=magenta>" . getHonor($general['dedication']) . " ({$general['dedication']})</font>";
}
else{
} else {
$dedication = getHonor($general['dedication']) . " ({$general['dedication']})";
}
@@ -738,11 +778,21 @@ function generalInfo2(General $generalObj) {
$dex4 = $general['dex4'] / GameConst::$dexLimit * 100;
$dex5 = $general['dex5'] / GameConst::$dexLimit * 100;
if($dex1 > 100) { $dex1 = 100; }
if($dex2 > 100) { $dex2 = 100; }
if($dex3 > 100) { $dex3 = 100; }
if($dex4 > 100) { $dex4 = 100; }
if($dex5 > 100) { $dex5 = 100; }
if ($dex1 > 100) {
$dex1 = 100;
}
if ($dex2 > 100) {
$dex2 = 100;
}
if ($dex3 > 100) {
$dex3 = 100;
}
if ($dex4 > 100) {
$dex4 = 100;
}
if ($dex5 > 100) {
$dex5 = 100;
}
$general['dex1_text'] = getDexCall($general['dex1']);
$general['dex2_text'] = getDexCall($general['dex2']);
@@ -824,11 +874,13 @@ function generalInfo2(General $generalObj) {
</table>";
}
function getOnlineNum() {
function getOnlineNum()
{
return KVStorage::getStorage(DB::db(), 'game_env')->online;
}
function onlinegen() {
function onlinegen()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -843,7 +895,8 @@ function onlinegen() {
return $onlinegen;
}
function nationMsg(General $general) {
function nationMsg(General $general)
{
$db = DB::db();
$msg = $db->queryFirstField(
'SELECT msg FROM nation WHERE nation = %i',
@@ -853,16 +906,19 @@ function nationMsg(General $general) {
return $msg ?: '';
}
function banner() {
function banner()
{
return sprintf(
'<font size=2>%s %s / %s</font>',
GameConst::$title,
VersionGit::$version,
GameConst::$banner);
GameConst::$banner
);
}
function addTurn($date, int $turnterm, int $turn=1, bool $withFraction=true) {
function addTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
{
$date = new \DateTime($date);
$target = $turnterm * $turn;
$date->add(new \DateInterval("PT{$target}M"));
@@ -872,7 +928,8 @@ function addTurn($date, int $turnterm, int $turn=1, bool $withFraction=true) {
return $date->format('Y-m-d H:i:s');
}
function subTurn($date, int $turnterm, int $turn=1, bool $withFraction=true) {
function subTurn($date, int $turnterm, int $turn = 1, bool $withFraction = true)
{
$date = new \DateTime($date);
$target = $turnterm * $turn;
$date->sub(new \DateInterval("PT{$target}M"));
@@ -882,7 +939,8 @@ function subTurn($date, int $turnterm, int $turn=1, bool $withFraction=true) {
return $date->format('Y-m-d H:i:s');
}
function cutTurn($date, int $turnterm, bool $withFraction=true) {
function cutTurn($date, int $turnterm, bool $withFraction = true)
{
$date = new \DateTime($date);
$baseDate = new \DateTime($date->format('Y-m-d'));
@@ -897,10 +955,10 @@ function cutTurn($date, int $turnterm, bool $withFraction=true) {
return $baseDate->format('Y-m-d H:i:s.u');
}
return $baseDate->format('Y-m-d H:i:s');
}
function cutDay($date, int $turnterm, bool $withFraction=true) {
function cutDay($date, int $turnterm, bool $withFraction = true)
{
$date = new \DateTime($date);
$baseDate = new \DateTime($date->format('Y-m-d'));
@@ -924,15 +982,15 @@ function cutDay($date, int $turnterm, bool $withFraction=true) {
$baseDate->add(new \DateInterval("PT{$diffMin}M"));
if ($withFraction) {
$dateTimeString = $baseDate->format('Y-m-d H:i:s.u');
}
else{
} else {
$dateTimeString = $baseDate->format('Y-m-d H:i:s');
}
return [$dateTimeString, $yearPulled, $newMonth];
}
function increaseRefresh($type="", $cnt=1) {
function increaseRefresh($type = "", $cnt = 1)
{
//FIXME: 로그인, 비로그인 시 처리가 명확하지 않음
$session = Session::getInstance();
$userID = $session->userID;
@@ -1005,11 +1063,13 @@ function increaseRefresh($type="", $cnt=1) {
$_SERVER['REMOTE_ADDR'],
$str
),
FILE_APPEND);
FILE_APPEND
);
}
}
function updateTraffic() {
function updateTraffic()
{
$online = getOnlineNum();
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1032,7 +1092,8 @@ function updateTraffic() {
$date = TimeUtil::now();
//일시|년|월|총갱신|접속자|최다갱신자
file_put_contents(__DIR__."/logs/".UniqueConst::$serverID."/_traffic.txt",
file_put_contents(
__DIR__ . "/logs/" . UniqueConst::$serverID . "/_traffic.txt",
Json::encode([
$date,
$admin['year'],
@@ -1040,11 +1101,13 @@ function updateTraffic() {
$admin['refresh'],
$online,
$user['name'] . "(" . $user['refresh'] . ")"
])."\n"
, FILE_APPEND);
]) . "\n",
FILE_APPEND
);
}
function CheckOverhead() {
function CheckOverhead()
{
//서버정보
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1058,11 +1121,13 @@ function CheckOverhead() {
}
}
function isLock() {
function isLock()
{
return DB::db()->queryFirstField("SELECT plock from plock limit 1") != 0;
}
function tryLock():bool{
function tryLock(): bool
{
//NOTE: 게임 로직과 관련한 모든 insert, update 함수들은 lock을 거칠것을 권장함.
$db = DB::db();
@@ -1075,7 +1140,8 @@ function tryLock():bool{
return $db->affectedRows() > 0;
}
function unlock():bool{
function unlock(): bool
{
// 풀림
$db = DB::db();
$db->update('plock', [
@@ -1085,7 +1151,8 @@ function unlock():bool{
return $db->affectedRows() > 0;
}
function timeover():bool {
function timeover(): bool
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1095,11 +1162,15 @@ function timeover():bool {
$t = min($turnterm, 5);
$term = $diff;
if($term >= $t || $term < 0) { return true; }
else { return false; }
if ($term >= $t || $term < 0) {
return true;
} else {
return false;
}
}
function checkDelay() {
function checkDelay()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1112,11 +1183,9 @@ function checkDelay() {
$term = $gameStor->turnterm;
if ($term >= 20) {
$threshold = 1;
}
else if($term >= 10){
} else if ($term >= 10) {
$threshold = 3;
}
else{
} else {
$threshold = 6;
}
//지연 해야할 밀린 턴 횟수
@@ -1139,7 +1208,8 @@ function checkDelay() {
}
}
function updateOnline() {
function updateOnline()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
@@ -1188,7 +1258,8 @@ function updateOnline() {
$gameStor->onlinenation = $onnationstr;
}
function addAge() {
function addAge()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1237,7 +1308,8 @@ function addAge() {
}
}
function turnDate($curtime) {
function turnDate($curtime)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$admin = $gameStor->getValues(['startyear', 'starttime', 'turnterm', 'year', 'month']);
@@ -1264,7 +1336,8 @@ function turnDate($curtime) {
}
function triggerTournament() {
function triggerTournament()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1274,12 +1347,15 @@ function triggerTournament() {
if ($admin['tournament'] == 0 && $admin['tnmt_trig'] > 0 && rand() % 100 < 40) {
$type = rand() % 5; // 0 : 전력전, 1 : 통솔전, 2 : 일기토, 3 : 설전
//전력전 40%, 통, 일, 설 각 20%
if($type > 3) { $type = 0; }
if ($type > 3) {
$type = 0;
}
startTournament($admin['tnmt_trig'], $type);
}
}
function CheckHall($no) {
function CheckHall($no)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1368,26 +1444,36 @@ function CheckHall($no) {
if ($valueType === 'natural') {
$value = $generalObj->getVar($typeName);
}
else if($valueType === 'rank'){
} else if ($valueType === 'rank') {
$value = $generalObj->getRankVar($typeName);
}
else if($valueType === 'calc'){
} else if ($valueType === 'calc') {
$value = $calcVar[$typeName];
}
//승률,살상률인데 10회 미만 전투시 스킵
if(($typeName === 'winrate' || $typeName === 'killrate') && $generalObj->getRankVar('warnum')<10) { continue; }
if (($typeName === 'winrate' || $typeName === 'killrate') && $generalObj->getRankVar('warnum') < 10) {
continue;
}
//토너승률인데 50회 미만시 스킵
if($typeName === 'ttrate' && $tt < 50) { continue; }
if ($typeName === 'ttrate' && $tt < 50) {
continue;
}
//토너승률인데 50회 미만시 스킵
if($typeName === 'tlrate' && $tl < 50) { continue; }
if ($typeName === 'tlrate' && $tl < 50) {
continue;
}
//토너승률인데 50회 미만시 스킵
if($typeName === 'tsrate' && $ts < 50) { continue; }
if ($typeName === 'tsrate' && $ts < 50) {
continue;
}
//토너승률인데 50회 미만시 스킵
if($typeName === 'tirate' && $ti < 50) { continue; }
if ($typeName === 'tirate' && $ti < 50) {
continue;
}
//수익률인데 1000미만시 스킵
if($typeName === 'betrate' && $generalObj->getRankVar('betgold') < 1000) { continue; }
if ($typeName === 'betrate' && $generalObj->getRankVar('betgold') < 1000) {
continue;
}
if ($value <= 0) {
continue;
@@ -1422,7 +1508,9 @@ function CheckHall($no) {
]);
if ($db->affectedRows() == 0) {
$db->update('ng_hall', [
$db->update(
'ng_hall',
[
'value' => $value,
'aux' => $jsonAux
],
@@ -1431,59 +1519,15 @@ function CheckHall($no) {
$scenarioIdx,
$no,
$idx,
$value);
$value
);
}
}
}
function tryUniqueItemLottery(General $general, string $acquireType='아이템'):bool{
function giveRandomUniqueItem(General $general, string $acquireType): bool
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
if($general->getVar('npc') >= 2){
return false;
}
if($general->getVar('npc') > 6){
return false;
}
foreach($general->getItems() as $item){
if(!$item){
continue;
}
if(!$item->isBuyable()){
return false;
}
}
$scenario = $gameStor->scenario;
$genCount = $db->queryFirstField('SELECT count(*) FROM general WHERE npc<2');
if ($scenario < 100) {
$prob = 1 / ($genCount * 5); // 5~6개월에 하나씩 등장
}
else {
$prob = 1 / $genCount; // 1~2개월에 하나씩 등장
}
if($acquireType == '투표'){
$prob = 1 / ($genCount * 0.7 / 3); // 투표율 70%, 투표 한번에 2~3개 등장
}
else if($acquireType == '랜덤 임관'){
$prob = 1 / ($genCount / 10/ 2); // 랜임시 2개(10%) 등장(200명중 20명 랜임시도?)
}
else if($acquireType == '건국'){
$prob = 1 / ($genCount / 10/ 4); // 건국시 4개(20%) 등장(200명시 20국 정도 됨)
}
$prob = Util::valueFit($prob, 1/3, 1);
if(!Util::randBool($prob)){
return false;
}
//아이템 습득 상황
$availableUnique = [];
@@ -1545,13 +1589,63 @@ function tryUniqueItemLottery(General $general, string $acquireType='아이템')
return true;
}
function getAdmin() {
function tryUniqueItemLottery(General $general, string $acquireType = '아이템'): bool
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
if ($general->getVar('npc') >= 2) {
return false;
}
if ($general->getVar('npc') > 6) {
return false;
}
foreach ($general->getItems() as $item) {
if (!$item) {
continue;
}
if (!$item->isBuyable()) {
return false;
}
}
$scenario = $gameStor->scenario;
$genCount = $db->queryFirstField('SELECT count(*) FROM general WHERE npc<2');
if ($scenario < 100) {
$prob = 1 / ($genCount * 5); // 5~6개월에 하나씩 등장
} else {
$prob = 1 / $genCount; // 1~2개월에 하나씩 등장
}
if ($acquireType == '투표') {
$prob = 1 / ($genCount * 0.7 / 3); // 투표율 70%, 투표 한번에 2~3개 등장
} else if ($acquireType == '랜덤 임관') {
$prob = 1 / ($genCount / 10 / 2); // 랜임시 2개(10%) 등장(200명중 20명 랜임시도?)
} else if ($acquireType == '건국') {
$prob = 1 / ($genCount / 10 / 4); // 건국시 4개(20%) 등장(200명시 20국 정도 됨)
}
$prob = Util::valueFit($prob, 1 / 3, 1);
if (!Util::randBool($prob)) {
return false;
}
return giveRandomUniqueItem($general, $acquireType);
}
function getAdmin()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
return $gameStor->getAll();
}
function getCity($city, $sel="*") {
function getCity($city, $sel = "*")
{
$db = DB::db();
$connect = $db->get();
@@ -1562,7 +1656,8 @@ function getCity($city, $sel="*") {
return $city;
}
function deleteNation(General $general) {
function deleteNation(General $general)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1621,7 +1716,8 @@ function deleteNation(General $general) {
refreshNationStaticInfo();
}
function nextRuler(General $general) {
function nextRuler(General $general)
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -1691,7 +1787,8 @@ function nextRuler(General $general) {
* @param $maxDist 검색하고자 하는 최대 거리
* @param $distForm 리턴 타입. true일 경우 $result[$dist] = [...$city] 이며, false일 경우 $result[$city] = $dist 임
*/
function searchDistance(int $from, int $maxDist=99, bool $distForm = false) {
function searchDistance(int $from, int $maxDist = 99, bool $distForm = false)
{
$queue = new \SplQueue();
$cities = [];
@@ -1726,8 +1823,7 @@ function searchDistance(int $from, int $maxDist=99, bool $distForm = false) {
if ($distForm) {
unset($distanceList[0]);
return $distanceList;
}
else{
} else {
return $cities;
}
}
@@ -1739,7 +1835,8 @@ function searchDistance(int $from, int $maxDist=99, bool $distForm = false) {
* @param array|null $linkNationList 경로에 해당하는 국가 리스트, null인 경우 제한 없음
* @return null|int 거리.
*/
function calcCityDistance(int $from, int $to, ?array $linkNationList):?int{
function calcCityDistance(int $from, int $to, ?array $linkNationList): ?int
{
$queue = new \SplQueue();
$cities = [];
@@ -1758,10 +1855,7 @@ function calcCityDistance(int $from, int $to, ?array $linkNationList):?int{
) as $cityID) {
$allowedCityList[$cityID] = $cityID;
}
}
else{
} else {
$allowedCityList = CityConst::all();
}
@@ -1795,7 +1889,6 @@ function calcCityDistance(int $from, int $to, ?array $linkNationList):?int{
continue;
}
$queue->enqueue([$connCityID, $dist + 1]);
}
}
@@ -1809,7 +1902,8 @@ function calcCityDistance(int $from, int $to, ?array $linkNationList):?int{
* @param $linkNationList 경로에 해당하는 국가 리스트
* @return array $dist=>[cityID, $nation] 배열 가장 앞이 가장 가까움
*/
function searchDistanceListToDest(int $from, int $to, array $linkNationList) {
function searchDistanceListToDest(int $from, int $to, array $linkNationList)
{
$queue = new \SplQueue();
$cities = [];
@@ -1860,7 +1954,6 @@ function searchDistanceListToDest(int $from, int $to, array $linkNationList) {
continue;
}
$queue->enqueue([$connCityID, $dist + 1]);
}
}
@@ -1872,7 +1965,8 @@ function searchDistanceListToDest(int $from, int $to, array $linkNationList) {
* @param $cityIDList 이동 가능한 도시 리스트.
* @return array [from][to] 로 표시되는 거리값
*/
function searchAllDistanceByCityList(array $cityIDList):array {
function searchAllDistanceByCityList(array $cityIDList): array
{
if (!$cityIDList) {
return [];
}
@@ -1923,21 +2017,22 @@ function searchAllDistanceByCityList(array $cityIDList):array {
* @param $suppliedCityOnly 보급된 도시만을 이용해 검색
* @return array [from][to] 로 표시되는 거리값
*/
function searchAllDistanceByNationList(array $linkNationList, bool $suppliedCityOnly=false):array {
function searchAllDistanceByNationList(array $linkNationList, bool $suppliedCityOnly = false): array
{
if (!$linkNationList) {
return [];
}
$db = DB::db();
if ($suppliedCityOnly) {
$cityIDList = $db->queryFirstColumn('SELECT city FROM city WHERE nation IN %li AND supply=1', $linkNationList);
}
else{
} else {
$cityIDList = $db->queryFirstColumn('SELECT city FROM city WHERE nation IN %li', $linkNationList);
}
return searchAllDistanceByCityList($cityIDList);
}
function isNeighbor(int $nation1, int $nation2, bool $includeNoSupply=true) {
function isNeighbor(int $nation1, int $nation2, bool $includeNoSupply = true)
{
if ($nation1 === $nation2) {
return false;
}
@@ -1947,8 +2042,7 @@ function isNeighbor(int $nation1, int $nation2, bool $includeNoSupply=true) {
if ($includeNoSupply) {
$supplySql = '';
}
else{
} else {
$supplySql = 'AND supply = 1';
}
@@ -1967,7 +2061,8 @@ function isNeighbor(int $nation1, int $nation2, bool $includeNoSupply=true) {
return false;
}
function SabotageInjury(array $cityGeneralList, string $reason):int{
function SabotageInjury(array $cityGeneralList, string $reason): int
{
$injuryCount = 0;
$josaRo = JosaUtil::pick($reason, '로');
$text = "<M>{$reason}</>{$josaRo} 인해 <R>부상</>을 당했습니다.";
@@ -1994,17 +2089,15 @@ function SabotageInjury(array $cityGeneralList, string $reason):int{
return $injuryCount;
}
function getRandTurn($term, ?\DateTimeInterface $baseDateTime = null) {
function getRandTurn($term, ?\DateTimeInterface $baseDateTime = null)
{
if ($baseDateTime === null) {
$baseDateTime = new \DateTimeImmutable();
}
else if($baseDateTime instanceof \DateTime){
} else if ($baseDateTime instanceof \DateTime) {
$baseDateTime = \DateTimeImmutable::createFromMutable($baseDateTime);
}
else if($baseDateTime instanceof \DateTimeImmutable){
} else if ($baseDateTime instanceof \DateTimeImmutable) {
//do Nothing
}
else{
} else {
throw new MustNotBeReachedException();
}
@@ -2018,11 +2111,9 @@ function getRandTurn2($term, ?\DateTimeInterface $baseDateTime = null)
{
if ($baseDateTime === null) {
$baseDateTime = new \DateTimeImmutable();
}
else if($baseDateTime instanceof \DateTime){
} else if ($baseDateTime instanceof \DateTime) {
$baseDateTime = \DateTimeImmutable::createFromMutable($baseDateTime);
}
else{
} else {
throw new MustNotBeReachedException();
}
$randSecond = Util::randRangeInt(0, 60 * $term - 1);
+134 -44
View File
@@ -1,4 +1,5 @@
<?php
namespace sammo;
use Monolog\Logger;
@@ -7,7 +8,8 @@ use Monolog\Logger;
* 게임 룰에 해당하는 함수 모음
*/
function getNationLevelList():array{
function getNationLevelList(): array
{
$table = [
0 => ['방랑군', 2, 0],
1 => ['호족', 2, 1],
@@ -21,7 +23,8 @@ function getNationLevelList():array{
return $table;
}
function getCityLevelList():array{
function getCityLevelList(): array
{
return [
1 => '수',
2 => '진',
@@ -35,8 +38,11 @@ function getCityLevelList():array{
}
//한국가의 전체 전방 설정
function SetNationFront($nationNo) {
if(!$nationNo) { return; }
function SetNationFront($nationNo)
{
if (!$nationNo) {
return;
}
// 도시소유 국가와 선포,교전중인 국가
$adj3 = [];
@@ -45,16 +51,16 @@ function SetNationFront($nationNo) {
$db = DB::db();
foreach ($db->queryFirstColumn(
'SELECT city FROM city JOIN diplomacy ON diplomacy.you = city.nation WHERE diplomacy.state = 0 AND me = %i'
, $nationNo
'SELECT city FROM city JOIN diplomacy ON diplomacy.you = city.nation WHERE diplomacy.state = 0 AND me = %i',
$nationNo
) as $city) {
foreach (CityConst::byID($city)->path as $adjKey => $adjVal) {
$adj3[$adjKey] = $adjVal;
}
};
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'
, $nationNo
'SELECT city FROM city JOIN diplomacy ON diplomacy.you = city.nation WHERE diplomacy.state = 1 AND diplomacy.term <= 5 AND me = %i',
$nationNo
) as $city) {
foreach (CityConst::byID($city)->path as $adjKey => $adjVal) {
$adj1[$adjKey] = $adjVal;
@@ -91,7 +97,8 @@ function SetNationFront($nationNo) {
}
}
function checkSupply() {
function checkSupply()
{
$db = DB::db();
$cities = [];
@@ -158,17 +165,18 @@ function checkSupply() {
'supply' => 1
], 'city IN %li', $supply);
}
}
function updateYearly() {
function updateYearly()
{
//통계
checkStatistic();
}
//관직 변경 해제
function updateQuaterly() {
function updateQuaterly()
{
$db = DB::db();
//천도 제한 해제, 관직 변경 제한 해제
@@ -191,14 +199,17 @@ function updateQuaterly() {
}
// 벌점 감소와 건국제한-1 전턴제한-1 외교제한-1, 1달마다 실행, 병사 있는 장수의 군량 감소, 수입비율 조정
function preUpdateMonthly() {
function preUpdateMonthly()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
//연감 월결산
$result = LogHistory();
if($result == false) { return false; }
if ($result == false) {
return false;
}
$admin = $gameStor->getValues(['startyear', 'year', 'month']);
@@ -305,8 +316,7 @@ EOD),
foreach ($spyInfo as $cityNo => $remainMonth) {
if ($remainMonth <= 1) {
unset($spyInfo[$cityNo]);
}
else{
} else {
$spyInfo[$cityNo] -= 1;
}
}
@@ -320,7 +330,8 @@ EOD),
}
// 외교 로그처리, 외교 상태 처리
function postUpdateMonthly() {
function postUpdateMonthly()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
@@ -487,7 +498,8 @@ function postUpdateMonthly() {
}
function checkWander() {
function checkWander()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -509,7 +521,8 @@ function checkWander() {
}
}
function checkMerge() {
function checkMerge()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
@@ -666,7 +679,8 @@ function checkMerge() {
}
}
function checkSurrender() {
function checkSurrender()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
@@ -822,19 +836,20 @@ function checkSurrender() {
}
}
function updateNationState() {
function updateNationState()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$history = array();
$admin = $gameStor->getValues(['year', 'month', 'fiction', 'startyear', 'show_img_level', 'turnterm', 'turntime']);
$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[$nationID] = $assemblerCnt;
};
foreach($db->query('SELECT nation,name,level,tech FROM nation') as $nation) {
foreach ($db->query('SELECT nation,name,level,tech,aux FROM nation') as $nation) {
//TODO: level이 진관수이소중대특 체계를 벗어날 수 있음
$citycount = $db->queryFirstField('SELECT count(*) FROM city WHERE nation=%i AND level>=4', $nation['nation']);
@@ -857,14 +872,23 @@ function updateNationState() {
}
if ($nationlevel > $nation['level']) {
$levelDiff = $nationlevel - $nation['level'];
$oldLevel = $nation['level'];
$nation['level'] = $nationlevel;
$updateVals = [
'level' => $nationlevel
];
switch ($nationlevel) {
case 7:
$josaUl = JosaUtil::pick(getNationLevel($nationlevel), '을');
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>{$josaUl} 자칭하였습니다.";
pushNationHistory($nation['nation'], ["<C>●</>{$admin['year']}{$admin['month']}월:<D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>{$josaUl} 자칭"]);
$auxVal = Json::decode($nation['aux']);
$auxVal['can_국기변경'] = 1;
$auxVal['can_국호변경'] = 1;
$updateVals['aux'] = Json::encode($auxVal);
break;
case 6:
$history[] = "<C>●</>{$admin['year']}{$admin['month']}월:<Y><b>【작위】</b></><D><b>{$nation['name']}</b></>의 군주가 <Y>" . getNationLevel($nationlevel) . "</>에 등극하였습니다.";
@@ -882,9 +906,7 @@ function updateNationState() {
break;
}
$db->update('nation', [
'level'=>$nation['level']
], 'nation=%i', $nation['nation']);
$db->update('nation', $updateVals, 'nation=%i', $nation['nation']);
$turnRows = [];
foreach (Util::range(getNationChiefLevel($nation['level']), 12) as $chiefLevel) {
@@ -900,6 +922,56 @@ function updateNationState() {
}
}
$db->insertIgnore('nation_turn', $turnRows);
if ($levelDiff) {
//유니크 아이템 하나 돌리자
$targetKillTurn = $admin['killturn'];
$targetKillTurn -= 24 * 60 / $admin['turnterm'];
$nationGenIDList = $db->queryFirstColumn(
'SELECT no FROM general WHERE nation = %i AND killturn >= %i AND npc < 2',
$nation['nation'],
$targetKillTurn
);
$nationGenList = General::createGeneralObjListFromDB($nationGenIDList, ['belong'], 2);
$uniqueLotteryWeightList = [];
foreach ($nationGenList as $nationGen) {
$hasUnique = false;
foreach ($nationGen->getItems() as $item) {
if (!$item->isBuyable()) {
$hasUnique = true;
break;
}
}
if ($hasUnique) {
continue;
}
$score = $nationGen->getVar('belong') + 5;
if ($nationGen->getVar('officer_level') == 12) {
$score += 200; //NOTE: 꼬우면 군주하세요.
} else if ($nationGen->getVar('officer_level') == 11) {
$score += 70;
} else if ($nationGen->getVar('officer_level') > 4) {
$score += 35;
}
$uniqueLotteryWeightList[$nationGen->getID()] = [$nationGen, $score];
}
foreach (Util::range($levelDiff) as $idx) {
if(!$uniqueLotteryWeightList){
break;
}
/** @var General */
$winnerObj = Util::choiceRandomUsingWeightPair($uniqueLotteryWeightList);
unset($uniqueLotteryWeightList[$winnerObj->getID()]);
giveRandomUniqueItem($winnerObj, '작위보상');
$winnerObj->applyDB($db);
}
}
}
$assemblerCnt = $assemblerCnts[$nation['nation']] ?? 0;
@@ -919,8 +991,19 @@ function updateNationState() {
while ($assemblerCnt < $maxAssemblerCnt) {
$lastAssemblerID += 1;
$npcObj = new Scenario\NPC(
999, sprintf('부대장%4d',$lastAssemblerID), null, $nation['nation'], null,
10, 10, 10, 1, $admin['year'] - 15, $admin['year'] + 15, '은둔', '척사'
999,
sprintf('부대장%4d', $lastAssemblerID),
null,
$nation['nation'],
null,
10,
10,
10,
1,
$admin['year'] - 15,
$admin['year'] + 15,
'은둔',
'척사'
);
$npcObj->killturn = 70;
$npcObj->gold = 0;
@@ -943,12 +1026,12 @@ function updateNationState() {
$gameStor->assembler_id = $lastAssemblerID;
}
}
}
pushWorldHistory($history, $admin['year'], $admin['month']);
}
function checkStatistic() {
function checkStatistic()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
@@ -982,7 +1065,8 @@ function checkStatistic() {
$avgNation = $db->queryFirstRow(
'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');
min(power) as minpower, max(power) as maxpower, avg(power) as avgpower from nation where level>0'
);
$auxData['nations']['avg'] = $avgNation;
$avgNation['mintech'] = floor($avgNation['mintech']);
@@ -997,7 +1081,8 @@ function checkStatistic() {
$nations = Util::convertArrayToDict(
$db->query(
'SELECT nation,name,type,power,gennum,gold+rice as goldrice from nation where level>0 order by power desc', 'nation'
'SELECT nation,name,type,power,gennum,gold+rice as goldrice from nation where level>0 order by power desc',
'nation'
),
'nation'
);
@@ -1038,7 +1123,9 @@ function checkStatistic() {
$nationHist = '';
foreach (GameConst::$availableNationType as $nationType) {
if(!Util::array_get($nationHists[$nationType])) { $nationHists[$nationType] = '-'; }
if (!Util::array_get($nationHists[$nationType])) {
$nationHists[$nationType] = '-';
}
$nationHist .= getNationType($nationType) . "({$nationHists[$nationType]}), ";
}
@@ -1063,8 +1150,7 @@ function checkStatistic() {
if ($general['npc'] < 2) {
$genCount += 1;
}
else{
} else {
$npcCount += 1;
}
@@ -1075,8 +1161,7 @@ function checkStatistic() {
foreach ($db->queryAllLists(
'SELECT crewtype, count(crewtype) AS cnt FROM general WHERE recent_war != NULL GROUP BY crewtype'
) as [$crewtype, $cnt]
){
) as [$crewtype, $cnt]) {
$crewtypeHists[$crewtype] = $cnt;
}
@@ -1127,11 +1212,11 @@ function checkStatistic() {
'etc' => $etc,
'aux' => Json::encode($auxData)
]);
}
function convForOldGeneral(array $general, int $year, int $month){
function convForOldGeneral(array $general, int $year, int $month)
{
$general['history'] = getGeneralHistoryAll($general['no']);
return [
'server_id' => UniqueConst::$serverID,
@@ -1144,7 +1229,8 @@ function convForOldGeneral(array $general, int $year, int $month){
];
}
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);
if (!$general) {
@@ -1158,7 +1244,8 @@ function storeOldGeneral(int $no, int $year, int $month){
);
}
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) {
$data = convForOldGeneral($general, $year, $month);
@@ -1170,7 +1257,8 @@ function storeOldGenerals(int $nation, int $year, int $month){
}
}
function checkEmperior() {
function checkEmperior()
{
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
$connect = $db->get();
@@ -1233,7 +1321,8 @@ function checkEmperior() {
$oldNationGenerals = $db->queryFirstColumn('SELECT `no` FROM general WHERE nation=%i', $nation['nation']);
$oldNation['generals'] = $oldNationGenerals;
$tigers = $db->query('SELECT value, name
$tigers = $db->query(
'SELECT value, name
FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no
WHERE rank_data.nation_id = %i AND rank_data.type = "warnum" AND value > 0 ORDER BY value DESC LIMIT 5',
$nation['nation']
@@ -1244,7 +1333,8 @@ function checkEmperior() {
return "{$arr['name']}{$number}";
}, $tigers));
$eagles = $db->query('SELECT value, name
$eagles = $db->query(
'SELECT value, name
FROM rank_data LEFT JOIN general ON rank_data.general_id = general.no
WHERE rank_data.nation_id = %i AND rank_data.type = "firenum" AND value > 0 ORDER BY value DESC LIMIT 7',
$nation['nation']
+8 -3
View File
@@ -11,7 +11,8 @@ use\sammo\{
GameConst,
GameUnitConst,
LastTurn,
Command
Command,
Json
};
@@ -79,7 +80,7 @@ class che_건국 extends Command\GeneralCommand
$env = $this->env;
$this->setCity();
$this->setNation(['gennum']);
$this->setNation(['gennum', 'aux']);
$relYear = $env['year'] - $env['startyear'];
@@ -173,6 +174,9 @@ class che_건국 extends Command\GeneralCommand
$general->addExperience($exp);
$general->addDedication($ded);
$aux = Json::decode($this->nation['aux'])??[];
$aux['can_국기변경'] = 1;
$db->update('city', [
'nation' => $general->getNationID(),
'conflict' => '{}'
@@ -183,7 +187,8 @@ class che_건국 extends Command\GeneralCommand
'color' => $colorType,
'level' => 1,
'type' => $nationType,
'capital' => $general->getCityID()
'capital' => $general->getCityID(),
'aux' => Json::encode($aux)
], 'nation=%i', $general->getNationID());
refreshNationStaticInfo();
+14 -5
View File
@@ -15,7 +15,8 @@ use\sammo\{
Command,
MessageTarget,
Message,
CityConst
CityConst,
Json,
};
use function\sammo\{
@@ -64,23 +65,27 @@ class che_국기변경 extends Command\NationCommand
$env = $this->env;
$this->setCity();
$this->setNation(['can_change_flag']);
$this->setNation(['aux']);
$actionName = $this->getName();
$this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::SuppliedCity(),
ConstraintHelper::ReqNationValue('can_change_flag', '국기색', '>', 0, '더이상 변경이 불가능합니다.')
ConstraintHelper::ReqNationAuxValue("can_{$actionName}", null, '>', 0, '더이상 변경이 불가능합니다.')
];
}
protected function initWithArg()
{
$actionName = $this->getName();
$this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::SuppliedCity(),
ConstraintHelper::ReqNationValue('can_change_flag', '국기색', '>', 0, '더이상 변경이 불가능합니다.')
ConstraintHelper::ReqNationAuxValue("can_{$actionName}", null, '>', 0, '더이상 변경이 불가능합니다.')
];
}
@@ -113,6 +118,7 @@ class che_국기변경 extends Command\NationCommand
}
$db = DB::db();
$actionName = $this->getName();
$general = $this->generalObj;
$generalID = $general->getID();
@@ -135,9 +141,12 @@ class che_국기변경 extends Command\NationCommand
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$aux = Json::decode($this->nation['aux']);
$aux["can_{$actionName}"] = 0;
$db->update('nation', [
'color'=>$color,
'can_change_flag' => $db->sqleval('can_change_flag - 1'),
'aux'=>Json::encode($aux)
], 'nation=%i', $nationID);
$logger->pushGeneralActionLog("<span style='color:{$color};'><b>국기</b></span>를 변경하였습니다 <1>$date</>");
+2 -1
View File
@@ -158,6 +158,7 @@ class General implements iAction{
return $this->itemObjs[$itemKey];
}
/** @return BaseItem[] */
function getItems():array{
return $this->itemObjs;
}
@@ -512,7 +513,7 @@ class General implements iAction{
}
function updateVar(string $key, $value){
if($this->raw[$key] === $value){
if(($this->raw[$key]??null) === $value){
return;
}
if(!key_exists($key, $this->updatedVar)){
+1 -1
View File
@@ -67,7 +67,7 @@ trait LazyVarUpdater{
}
function updateVar(string $key, $value){
if($this->raw[$key] === $value){
if(($this->raw[$key]??null) === $value){
return;
}
if(!key_exists($key, $this->updatedVar)){
-1
View File
@@ -116,7 +116,6 @@ CREATE TABLE `nation` (
`nation` INT(6) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(64) NOT NULL COLLATE 'utf8mb4_bin',
`color` CHAR(10) NOT NULL,
`can_change_flag` INT(1) NULL DEFAULT '1',
`onlinegen` TEXT NULL DEFAULT '',
`msg` TEXT NULL DEFAULT '',
`capital` INT(1) NULL DEFAULT '0',