유산 포인트 시스템, 추가 기수 대비 (#187)

- 유산 포인트
  - 기수 뒤로도 누적되는 포인트
  - 생존, 최대 임관년 수, 최대 연속 내정 성공, 병종 상성 우위 횟수, 전투 횟수, 계략 성공 횟수, 천통 기여(규모 상승, 천통 수뇌, 천통 군주), 숙련도, 토너먼트, 베팅 당첨
  - 유산 관리 페이지 제공

- 태수국
  - 181년 1월에 자동 생성되는 u장수국
  - 시간이 지나면 사실상 자동 소멸
  - 유저국과는 4칸 거리, 서로는 2칸 거리
  - 이 시스템으로 인해 m장 거병 차단

- NPC 원조시 불가침
  - 1년 세수만큼 받은 경우 24개월 불가침 제안
  - 최소 6개월
  - 불가침을 받지 않고 추가 원조한 경우 계속해서 기간 상승
  - 단, 불가침 수락 전에 선포를 할 수 있음

Reviewed-on: https://storage.hided.net/gitea/devsam/core/pulls/187
Co-authored-by: hide_d <hided62@gmail.com>
Co-committed-by: hide_d <hided62@gmail.com>
This commit was merged in pull request #187.
This commit is contained in:
2021-08-11 21:57:52 +09:00
parent b306601c72
commit b4d7acb827
44 changed files with 1377 additions and 142 deletions
+3
View File
@@ -28,6 +28,7 @@ class AutorunNationPolicy {
static $NPC몰수 = 'NPC몰수';
// 군주 행동
static $불가침제의 = '불가침제의';
static $선전포고 = '선전포고';
static $천도 = '천도';
@@ -35,6 +36,7 @@ class AutorunNationPolicy {
//실제 행동
static public $defaultPriority = [
'불가침제의',
'선전포고',
'천도',
@@ -106,6 +108,7 @@ class AutorunNationPolicy {
public $canNPC포상 = true;
public $canNPC몰수 = true;
public $can불가침제의 = true;
public $can선전포고 = true;
public $can천도 = true;
@@ -14,7 +14,8 @@ use function sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
tryUniqueItemLottery
tryUniqueItemLottery,
updateMaxDomesticCritical
};
use \sammo\Constraint\Constraint;
@@ -93,6 +94,13 @@ class che_기술연구 extends che_상업투자{
$exp = $score * 0.7;
$ded = $score * 1.0;
if($pick == 'success'){
updateMaxDomesticCritical($general, $score);
}
else{
$general->setAuxVar('max_domestic_critical', 0);
}
$scoreText = number_format($score, 0);
$josaUl = JosaUtil::pick(static::$actionName, '을');
+86 -81
View File
@@ -1,21 +1,22 @@
<?php
namespace sammo\Command\General;
use \sammo\{
DB, Util, JosaUtil, TimeUtil, Json,
General,
ActionLogger,
GameConst, GameUnitConst,
LastTurn,
Command
};
use \sammo\DB;
use \sammo\Util;
use \sammo\JosaUtil;
use \sammo\TimeUtil;
use \sammo\Json;
use \sammo\General;
use \sammo\ActionLogger;
use \sammo\GameConst;
use \sammo\GameUnitConst;
use \sammo\LastTurn;
use \sammo\Command;
use function \sammo\{
tryUniqueItemLottery,
getInvitationList,
getNationStaticInfo
};
use function \sammo\tryUniqueItemLottery;
use function \sammo\getInvitationList;
use function \sammo\getNationStaticInfo;
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
@@ -24,10 +25,12 @@ use sammo\MustNotBeReachedException;
class che_랜덤임관 extends Command\GeneralCommand{
class che_랜덤임관 extends Command\GeneralCommand
{
static protected $actionName = '랜덤임관';
protected function argTest():bool{
protected function argTest(): bool
{
$this->arg = null;
return true;
@@ -71,7 +74,7 @@ class che_랜덤임관 extends Command\GeneralCommand{
$relYear = $env['year'] - $env['startyear'];
$this->fullConditionConstraints=[
$this->fullConditionConstraints = [
ConstraintHelper::BeNeutral(),
ConstraintHelper::AllowJoinAction(),
];
@@ -83,28 +86,34 @@ class che_랜덤임관 extends Command\GeneralCommand{
*/
}
public function getCommandDetailTitle():string{
public function getCommandDetailTitle(): string
{
return '무작위 국가로 임관';
}
public function getBrief():string{
public function getBrief(): string
{
return '무작위 국가로 임관';
}
public function getCost():array{
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn():int{
public function getPreReqTurn(): int
{
return 0;
}
public function getPostReqTurn():int{
public function getPostReqTurn(): int
{
return 0;
}
public function run():bool{
if(!$this->hasFullConditionMet()){
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
@@ -126,108 +135,107 @@ class che_랜덤임관 extends Command\GeneralCommand{
$destNation = null;
if ($general->getNPCType() >= 2 && !$env['fiction'] && 1000 <= $env['scenario'] && $env['scenario'] < 2000) {
if($notIn){
if ($notIn) {
$nations = $db->query(
'SELECT nation.`name` as `name`,nation.nation as nation,scout,gennum,`affinity` FROM nation join general on general.nation = nation.nation and general.officer_level = 12 WHERE scout=0 and gennum<%i and nation.nation not in %li',
$relYear<3?GameConst::$initialNationGenLimit:GameConst::$defaultMaxGeneral,
$relYear < 3 ? GameConst::$initialNationGenLimit : GameConst::$defaultMaxGeneral,
$notIn
);
}
else{
} else {
$nations = $db->query(
'SELECT nation.`name` as `name`,nation.nation as nation,scout,gennum,`affinity` FROM nation join general on general.nation = nation.nation and general.officer_level = 12 WHERE scout=0 and gennum<%i',
$relYear<3?GameConst::$initialNationGenLimit:GameConst::$defaultMaxGeneral
$relYear < 3 ? GameConst::$initialNationGenLimit : GameConst::$defaultMaxGeneral
);
}
shuffle($nations);
$allGen = Util::arraySum($nations, 'gennum');
$maxScore = 1<<30;
$maxScore = 1 << 30;
$affinity = $general->getVar('affinity');
foreach($nations as $testNation){
foreach ($nations as $testNation) {
$affinity = abs($affinity - $testNation['affinity']);
$affinity = min($affinity, abs($affinity - 150));
$score = log($affinity + 1, 2);//0~
$score = log($affinity + 1, 2); //0~
//쉐킷쉐킷
$score += Util::randF();
$score += sqrt($testNation['gennum']/$allGen);
if($score < $maxScore){
$score += sqrt($testNation['gennum'] / $allGen);
if ($score < $maxScore) {
$maxScore = $score;
$destNation = $testNation;
}
}
}
else{
} else {
$onlyRandom = $env['join_mode'] == 'onlyRandom';
$genLimit = GameConst::$defaultMaxGeneral;
if($onlyRandom && TimeUtil::IsRangeMonth($env['init_year'], $env['init_month'], 1, $env['year'], $env['month'])){
if ($onlyRandom && TimeUtil::IsRangeMonth($env['init_year'], $env['init_month'], 1, $env['year'], $env['month'])) {
$genLimit = GameConst::$initialNationGenLimitForRandInit;
}
else if($relYear < 3){
} else if ($relYear < 3) {
$genLimit = GameConst::$initialNationGenLimit;
}
$generalsCnt = [];
if($notIn){
if ($notIn) {
$rawGeneralsCnt = $db->query(
'SELECT general.nation as nation, nation.gennum, nation.name, npc, count(*) as cnt FROM general JOIN nation ON general.nation = nation.nation WHERE npc < 4 AND nation.gennum < %i AND nation.scout=0 AND nation.nation NOT IN %li GROUP BY general.nation, general.npc',
'SELECT general.nation as nation, nation.gennum, nation.name, npc, count(*) as cnt FROM general JOIN nation ON general.nation = nation.nation WHERE npc != 9 AND nation.gennum < %i AND nation.scout=0 AND nation.nation NOT IN %li GROUP BY general.nation, general.npc',
$genLimit,
$notIn
);
}
else{
} else {
$rawGeneralsCnt = $db->query(
'SELECT general.nation as nation, nation.gennum, nation.name, npc, count(*) as cnt FROM general JOIN nation ON general.nation = nation.nation WHERE npc < 4 AND nation.gennum < %i AND nation.scout=0 GROUP BY general.nation, general.npc',
'SELECT general.nation as nation, nation.gennum, nation.name, npc, count(*) as cnt FROM general JOIN nation ON general.nation = nation.nation WHERE npc != 9 AND nation.gennum < %i AND nation.scout=0 GROUP BY general.nation, general.npc',
$genLimit
);
}
foreach($rawGeneralsCnt as $nation){
foreach ($rawGeneralsCnt as $nation) {
$nationID = $nation['nation'];
if(!\key_exists($nationID, $generalsCnt)){
if (!\key_exists($nationID, $generalsCnt)) {
$generalsCnt[$nationID] = [
'nation'=>$nationID,
'gennum'=>$nation['gennum'],
'name'=>$nation['name'],
'cnt'=>0,
'nation' => $nationID,
'gennum' => $nation['gennum'],
'name' => $nation['name'],
'cnt' => 0,
];
$generalsCnt[$nationID]['cnt'] = 0;
}
if($nation['npc'] <= 2){
if ($nation['npc'] <= 2) {
$calcCnt = $nation['cnt'];
}
else{
} else {
$calcCnt = $nation['cnt'] / 2;
}
if ($general->getNPCType() < 2 && Util::starts_with($nation['name'], 'ⓤ')) {
$calcCnt *= 100;
}
$generalsCnt[$nationID]['cnt'] += $calcCnt;
}
$randVals = [];
foreach($generalsCnt as $testNation){
$randVals[] = [$testNation, 1/$testNation['cnt']];
foreach ($generalsCnt as $testNation) {
$randVals[] = [$testNation, 1 / $testNation['cnt']];
}
if($randVals){
if ($randVals) {
$destNation = Util::choiceRandomUsingWeightPair($randVals);
}
}
$logger = $general->getLogger();
if(!$destNation){
if (!$destNation) {
//임관 가능한 국가가 없다!
$logger->pushGeneralActionLog("임관 가능한 국가가 없습니다. <1>$date</>");
$logger->pushGeneralActionLog("임관 가능한 국가가 없습니다. <1>$date</>");
$this->alternative = new che_요양($general, $this->env, null);
return false;
}
@@ -236,7 +244,7 @@ class che_랜덤임관 extends Command\GeneralCommand{
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$talkList = [
'어쩌다 보니',
@@ -257,10 +265,9 @@ class che_랜덤임관 extends Command\GeneralCommand{
$logger->pushGeneralHistoryLog("<D><b>{$destNationName}</b></>에 랜덤 임관");
$logger->pushGlobalActionLog("<Y>{$generalName}</>{$josaYi} {$randomTalk} <D><b>{$destNationName}</b></>에 <S>임관</>했습니다.");
if($gennum < GameConst::$initialNationGenLimit) {
if ($gennum < GameConst::$initialNationGenLimit) {
$exp = 700;
}
else {
} else {
$exp = 100;
}
@@ -268,22 +275,21 @@ class che_랜덤임관 extends Command\GeneralCommand{
$general->setVar('officer_level', 1);
$general->setVar('officer_city', 0);
$general->setVar('belong', 1);
if($this->destGeneralObj !== null){
if ($this->destGeneralObj !== null) {
$general->setVar('city', $this->destGeneralObj->getCityID());
}
else{
} else {
$targetCityID = $db->queryFirstField('SELECT city FROM general WHERE nation = %i AND officer_level=12', $destNationID);
$general->setVar('city', $targetCityID);
}
$db->update('nation', [
'gennum'=>$db->sqleval('gennum + 1')
'gennum' => $db->sqleval('gennum + 1')
], 'nation=%i', $destNationID);
$relYear = $env['year'] - $env['startyear'];
if($general->getNPCType() == 1 || $relYear >= 3){
$joinedNations = $general->getAuxVar('joinedNations')??[];
if ($general->getNPCType() == 1 || $relYear >= 3) {
$joinedNations = $general->getAuxVar('joinedNations') ?? [];
$joinedNations[] = $destNationID;
$general->setAuxVar('joinedNations', $joinedNations);
}
@@ -296,5 +302,4 @@ class che_랜덤임관 extends Command\GeneralCommand{
return true;
}
}
}
@@ -15,7 +15,8 @@ use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
tryUniqueItemLottery
tryUniqueItemLottery,
updateMaxDomesticCritical
};
use \sammo\Constraint\Constraint;
@@ -165,6 +166,13 @@ class che_상업투자 extends Command\GeneralCommand{
$exp = $score * 0.7;
$ded = $score * 1.0;
if($pick == 'success'){
updateMaxDomesticCritical($general, $score);
}
else{
$general->setAuxVar('max_domestic_critical', 0);
}
$scoreText = number_format($score, 0);
$josaUl = JosaUtil::pick(static::$actionName, '을');
@@ -203,6 +211,4 @@ class che_상업투자 extends Command\GeneralCommand{
return true;
}
}
+6 -1
View File
@@ -202,6 +202,8 @@ class che_임관 extends Command\GeneralCommand{
$nationList[$nationID]['scoutmsg'] = $scoutMsg;
}
$hiddenItems = [];
foreach($nationList as &$nation){
if($env['year'] < $env['startyear']+3 && $nation['gennum'] >= GameConst::$initialNationGenLimit){
$nation['availableJoin'] = false;
@@ -217,7 +219,9 @@ class che_임관 extends Command\GeneralCommand{
$nation['availableJoin'] = false;
}
if(Util::starts_with($nation['name'], 'ⓤ')){
$hiddenItems[$nation['nation']] = $nation['nation'];
}
}
unset($nation);
ob_start();
@@ -228,6 +232,7 @@ class che_임관 extends Command\GeneralCommand{
임관할 국가를 목록에서 선택하세요.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach($nationList as $nation): ?>
<?php if(key_exists($nation['nation'], $hiddenItems)){ continue; } ?>
<option
value='<?=$nation['nation']?>'
style='<?=$nation['availableJoin']?'':'background-color:red;'?>'
@@ -209,7 +209,10 @@ class che_장수대상임관 extends Command\GeneralCommand{
$nationList[$nationID]['scoutmsg'] = $scoutMsg;
}
$hiddenItems = [];
foreach($nationList as &$nation){
$nation['hideen'] = false;
if($env['year'] < $env['startyear']+3 && $nation['gennum'] >= GameConst::$initialNationGenLimit){
$nation['availableJoin'] = false;
}
@@ -224,7 +227,9 @@ class che_장수대상임관 extends Command\GeneralCommand{
$nation['availableJoin'] = false;
}
if(Util::starts_with($nation['name'], 'ⓤ')){
$hiddenItems[$nation['nation']] = $nation['nation'];
}
}
unset($nation);
ob_start();
@@ -235,6 +240,7 @@ class che_장수대상임관 extends Command\GeneralCommand{
임관할 국가를 목록에서 선택하세요.<br>
<select class='formInput' name="destGeneralID" id="destGeneralID" size='1' style='color:white;background-color:black;'>
<?php foreach($generalList as $targetGeneral): ?>
<?php if(key_exists($targetGeneral['nation'], $hiddenItems)){ continue; } ?>
<option value='<?=$targetGeneral['no']?>'><?=getColoredName($targetGeneral['name'],$targetGeneral['npc'])?>【<?=getNationStaticInfo($targetGeneral['nation'])['name']??'재야'?>】</option>
<?php endforeach; ?>
</select>
+10 -2
View File
@@ -15,7 +15,8 @@ use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
tryUniqueItemLottery
tryUniqueItemLottery,
updateMaxDomesticCritical
};
use \sammo\Constraint\Constraint;
@@ -150,6 +151,13 @@ class che_정착장려 extends Command\GeneralCommand{
$exp = $score * 0.7;
$ded = $score * 1.0;
if($pick == 'success'){
updateMaxDomesticCritical($general, $score);
}
else{
$general->setAuxVar('max_domestic_critical', 0);
}
$score *= 10;
$scoreText = number_format($score, 0);
@@ -187,5 +195,5 @@ class che_정착장려 extends Command\GeneralCommand{
return true;
}
}
@@ -15,7 +15,8 @@ use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
tryUniqueItemLottery
tryUniqueItemLottery,
updateMaxDomesticCritical
};
use \sammo\Constraint\Constraint;
@@ -150,6 +151,13 @@ class che_주민선정 extends Command\GeneralCommand{
$exp = $score * 0.7;
$ded = $score * 1.0;
if($pick == 'success'){
updateMaxDomesticCritical($general, $score);
}
else{
$general->setAuxVar('max_domestic_critical', 0);
}
$score /= 10;
$scoreText = number_format($score, 1);
+12 -8
View File
@@ -9,16 +9,17 @@ use \sammo\{
LastTurn,
GameUnitConst,
Command,
Json,
KVStorage,
StringUtil
};
use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo
};
use function \sammo\getDomesticExpLevelBonus;
use function \sammo\CriticalRatioDomestic;
use function \sammo\CriticalScoreEx;
use function \sammo\getAllNationStaticInfo;
use function \sammo\getNationStaticInfo;
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
@@ -223,7 +224,10 @@ class che_물자원조 extends Command\NationCommand{
$destNationLogger = new ActionLogger(0, $destChiefID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>{$josaRoSrc}부터 금<C>{$goldAmountText}</> 쌀<C>{$riceAmountText}</>을 지원 받음");
$destNationStor = KVStorage::getStorage(DB::db(), $destNationID, 'nation_env');
$destRecvAssist = $destNationStor->getValue('recv_assist')??[];
$destRecvAssist["n{$nationID}"] = [$nationID, ($destRecvAssist["n{$nationID}"][1]??0) + $goldAmount + $riceAmount];
$destNationStor->setValue('recv_assist', $destRecvAssist);
$db->update('nation', [
'gold'=>$db->sqleval('gold - %i', $goldAmount),
@@ -2,33 +2,31 @@
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
MessageTarget,
DiplomaticMessage,
Message,
};
use \sammo\DB;
use \sammo\Util;
use \sammo\JosaUtil;
use \sammo\General;
use \sammo\DummyGeneral;
use \sammo\ActionLogger;
use \sammo\GameConst;
use \sammo\LastTurn;
use \sammo\GameUnitConst;
use \sammo\Command;
use \sammo\MessageTarget;
use \sammo\DiplomaticMessage;
use \sammo\Message;
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo,
GetImageURL
};
use function \sammo\getDomesticExpLevelBonus;
use function \sammo\CriticalRatioDomestic;
use function \sammo\CriticalScoreEx;
use function \sammo\getAllNationStaticInfo;
use function \sammo\getNationStaticInfo;
use function \sammo\GetImageUR;
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Json;
use sammo\KVStorage;
class che_불가침수락 extends Command\NationCommand
{
@@ -191,6 +189,13 @@ class che_불가침수락 extends Command\NationCommand
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$destNationStor = KVStorage::getStorage(DB::db(), $destNationID, 'nation_env');
$destRecvAssist = $destNationStor->getValue('recv_assist')??[];
$destRespAssist = $destNationStor->getValue('resp_assist')??[];
$destRespAssist["n{$nationID}"] = [$nationID, $destRecvAssist["n{$nationID}"][1]??0];
$destNationStor->setValue('resp_assist', $destRespAssist);
$year = $this->arg['year'];
$month = $this->arg['month'];
@@ -50,6 +50,11 @@ class AllowJoinDestNation extends Constraint{
return false;
}
if($this->general['npc']??2 < 2 && \sammo\Util::starts_with($this->destNation['name'], 'ⓤ')){
$this->reason = "유저장은 태수국에 임관할 수 없습니다.";
return false;
}
$joinedNations = $this->general['auxVar']['joinedNations']??[];
if(in_array($this->destNation['nation'], $joinedNations)){
$this->reason = "이미 임관했었던 국가입니다.";
+282
View File
@@ -0,0 +1,282 @@
<?php
namespace sammo\Event\Action;
use InvalidArgumentException;
use sammo\ActionLogger;
use sammo\CityConst;
use sammo\DB;
use sammo\GameConst;
use sammo\Json;
use sammo\KVStorage;
use sammo\Scenario\GeneralBuilder;
use sammo\Scenario\Nation;
use sammo\UniqueConst;
use sammo\Util;
use function sammo\GetNationColors;
use function sammo\getNationStaticInfo;
use function sammo\pickGeneralFromPool;
use function sammo\refreshNationStaticInfo;
class RaiseNPCNation extends \sammo\Event\Action
{
public function __construct()
{
}
const CITY_KEYS = ['pop', 'agri', 'comm', 'secu', 'def', 'wall'];
const MIN_DIST_USERNATION = 4;
const MIN_DIST_NPCNATION = 2;
private function calcAvgNationCity(array $cities)
{
if (count($cities) == 0) {
throw new InvalidArgumentException();
}
$targetCities = [];
foreach ($cities as $city) {
if ($city['nation'] == 0) {
continue;
}
$citySum = 0;
foreach (static::CITY_KEYS as $key) {
if ($key === 'pop') {
continue;
}
$citySum += $city[$key];
}
$city['sum'] = $citySum;
$targetCities[] = $city;
}
$cityCnt = count($targetCities);
if ($cityCnt == 0) {
$target = Util::choiceRandom($cities);
$randCity = [];
foreach (static::CITY_KEYS as $key) {
$randCity[$key] = $target["{$key}_max"];
}
return $randCity;
}
usort($targetCities, function (array $lhs, array $rhs) {
return $lhs['sum'] <=> $rhs['sum'];
});
//최소, 최대 도시 몇개를 뺀다. 정렬은 신경쓰지 않는다.
if ($cityCnt >= 3) {
$reduceCnt = Util::valueFit(Util::round($cityCnt / 6, 0), 1);
foreach (Util::range($reduceCnt) as $_idx) {
array_pop($targetCities);
}
foreach (Util::range($reduceCnt) as $idx) {
$targetCities[$idx] = array_pop($targetCities);
}
$cityCnt -= $reduceCnt * 2;
}
$avgCity = [];
foreach ($targetCities as $city) {
foreach (static::CITY_KEYS as $key) {
$avgCity[$key] = ($avgCity[$key] ?? 0) + $city[$key];
}
}
foreach (static::CITY_KEYS as $key) {
$avgCity[$key] = Util::toInt($avgCity[$key] / $cityCnt);
}
return $avgCity;
}
public function calcAvgNationGeneralCnt(): int
{
$nationUsers = [];
foreach (\sammo\getAllNationStaticInfo() as $nation) {
if ($nation['level'] == 0) {
continue;
}
$nationUsers[] = $nation['gennum'];
}
$nationCnt = count($nationUsers);
if ($nationCnt == 0) {
return GameConst::$initialNationGenLimit;
}
sort($nationUsers);
if ($nationCnt >= 3) {
$reduceCnt = Util::valueFit(Util::round($nationCnt / 6, 0), 1);
foreach (Util::range($reduceCnt) as $_idx) {
array_pop($nationUsers);
}
foreach (Util::range($reduceCnt) as $idx) {
$nationUsers[$idx] = array_pop($nationUsers);
}
$nationCnt -= $reduceCnt * 2;
}
return Util::round(array_sum($nationUsers) / $nationCnt);
}
public function calcAvgTech(): int
{
$techSum = 0;
$nationCnt = 0;
foreach (\sammo\getAllNationStaticInfo() as $nation) {
if ($nation['level'] == 0) {
continue;
}
$techSum += $nation['tech'];
$nationCnt += 1;
}
if ($nationCnt == 0) {
return 0;
}
return Util::toInt($techSum / $nationCnt);
}
private function buildNation(int $nationID, int $tech, array $baseCity, array $avgCity, int $genCnt, $env)
{
$db = DB::db();
$targetCity = [
'trust' => 100
];
foreach (static::CITY_KEYS as $key) {
$targetCity[$key] = min($baseCity["{$key}_max"], $avgCity[$key]);
}
$pickTypeList = ['무' => 1, '지' => 1];
$cityID = $baseCity['city'];
$cityName = $baseCity['name'];
$nationName = "{$cityName}";
$color = Util::choiceRandom(GetNationColors());
$nationObj = new Nation($nationID, $nationName, $color, 0, 2000, "우리도 할 수 있다! {$cityName}", $tech, null, 2, [$cityName]);
$nationObj->build($env);
$ruler = (new GeneralBuilder("{$cityName}태수", false, null, $nationID))
->setOfficerLevel(12)
->setCityID($cityID)
->setNPCType(6)
->setGoldRice(1000, 1000)
->fillRandomStat($pickTypeList)
->setKillturn(240)
->fillRemainSpecAsZero($env);
$ruler->build($env);
$nationObj->addGeneral($ruler);
$birthYear = $env['year'] - 20;
$deadYearMin = $env['year'] + 10;
foreach (pickGeneralFromPool(DB::db(), 0, $genCnt - 1) as $pickedNPC) {
//대충 10년후부터 6년마다 절반?
$deadYear = $deadYearMin + Util::toInt(60 * (1 - log(Util::randRange(1, 1024), 2)/10));
$newNPC = $pickedNPC->getGeneralBuilder();
$newNPC->setNationID($nationID)
->setCityID($cityID)
->setNPCType(6)
->setGoldRice(1000, 1000)
->setLifeSpan($birthYear, $deadYear)
->fillRandomStat($pickTypeList)
->fillRemainSpecAsZero($env);
$newNPC->build($env);
$pickedNPC->occupyGeneralName();
$nationObj->addGeneral($newNPC);
}
$nationObj->postBuild($env);
$db->update('city', $targetCity, 'city = %i', $cityID);
refreshNationStaticInfo();
}
public function run(array $env)
{
$db = DB::db();
$allCities = $db->query('SELECT * FROM city WHERE 5 <= level AND level <= 6'); //소, 중 성만 선택
$emptyCities = [];
$occupiedCities = [];
$npcCities = [];
$avgCity = $this->calcAvgNationCity($allCities);
foreach ($allCities as $city) {
if ($city['nation'] == 0) {
$emptyCities[$city['city']] = $city;
} else {
$occupiedCities[$city['city']] = $city;
}
}
$avgGenCnt = $this->calcAvgNationGeneralCnt();
$serverID = UniqueConst::$serverID;
$lastNationID = max(
$db->queryFirstField("SELECT max(`nation`) FROM `nation`"),
$db->queryFirstField("SELECT max(`nation`) FROM `ng_old_nations` WHERE server_id = %s", $serverID),
);
$avgTech = $this->calcAvgTech();
Util::shuffle_assoc($emptyCities);
$occupiedCitiesID = array_keys($occupiedCities);
$npcCitiesID = [];
refreshNationStaticInfo();
foreach ($emptyCities as $emptyCity) {
$cityID = $emptyCity['city'];
$minDistance = 999;
foreach ($occupiedCitiesID as $targetCityID) {
$minDistance = min(\sammo\calcCityDistance($cityID, $targetCityID, null), $minDistance);
if ($minDistance < static::MIN_DIST_USERNATION) {
break;
}
}
if ($minDistance < static::MIN_DIST_USERNATION) {
continue;
}
$minDistance = 999;
foreach ($npcCitiesID as $targetCityID) {
$minDistance = min(\sammo\calcCityDistance($cityID, $targetCityID, null), $minDistance);
if ($minDistance < static::MIN_DIST_NPCNATION) {
break;
}
}
if ($minDistance < static::MIN_DIST_NPCNATION) {
continue;
}
//TODO: 거리 측정
$lastNationID += 1;
$this->buildNation($lastNationID, $avgTech, $emptyCity, $avgCity, $avgGenCnt, $env);
$npcCities[$cityID] = $emptyCity;
$npcCitiesID[] = $cityID;
}
if (count($npcCities) > 0) {
$logger = new ActionLogger(0, 0, $env['year'], $env['month']);
$logger->pushGlobalHistoryLog("<L><b>【공지】</b></>공백지에 임의의 국가가 생성되었습니다.");
$logger->flush();
}
return [__CLASS__, count($npcCities)];
}
}
+5 -1
View File
@@ -1,6 +1,8 @@
<?php
namespace sammo\Event\Condition;
use sammo\Event\Condition;
class Logic extends \sammo\Event\Condition{
private $mode = 'and';
@@ -24,7 +26,9 @@ class Logic extends \sammo\Event\Condition{
}
$this->mode = $mode;
$this->conditions = $conditions;
$this->conditions = array_map(function($condition){
return Condition::build($condition);
}, $conditions);
}
public function eval($env=null){
+207 -3
View File
@@ -50,6 +50,20 @@ class General implements iAction{
'occupied'=>1,
];
const INHERITANCE_KEY = [
'previous'=>[true, 1, '기존 포인트'],
'lived_month'=>[true, 1, '생존'],
'max_belong'=>[false, 10, '최대 임관년 수'],
'max_domestic_critical'=>[true, 1, '최대 연속 내정 성공'],
'snipe_combat'=>[true, 10, '병종 상성 우위 횟수'],
'combat'=>[['rank', 'warnum'], 5, '전투 횟수'],
'sabotage'=>[['rank', 'firenum'], 20, '계략 성공 횟수'],
'unifier'=>[true, 1, '천통 기여'],
'dex'=>[false, 0.001, '숙련도'],
'tournament'=>[true, 1, '토너먼트'],
'betting'=>[false, 10, '베팅 당첨'],
];
const TURNTIME_FULL_MS = -1;
const TURNTIME_FULL = 0;
const TURNTIME_HMS = 1;
@@ -539,6 +553,8 @@ class General implements iAction{
$generalName = $this->getName();
$this->mergeTotalInheritancePoint();
// 군주였으면 유지 이음
$officerLevel = $this->getVar('officer_level');
if($officerLevel == 12) {
@@ -592,6 +608,12 @@ class General implements iAction{
$generalName = $this->getName();
$ownerID = $this->getVar('owner');
if($ownerID){
$this->mergeTotalInheritancePoint();
resetInheritanceUser($ownerID);
}
$this->multiplyVarWithLimit('leadership', 0.85, 10);
$this->multiplyVarWithLimit('strength', 0.85, 10);
$this->multiplyVarWithLimit('intel', 0.85, 10);
@@ -919,19 +941,19 @@ class General implements iAction{
static public function mergeQueryColumn(?array $reqColumns=null, int $constructMode=2):array{
$minimumColumn = ['no', 'name', 'city', 'nation', 'officer_level', 'officer_city'];
$defaultEventColumn = [
'no', 'name', 'city', 'nation', 'officer_level', 'officer_city',
'no', 'name', 'owner', 'city', 'nation', 'officer_level', 'officer_city',
'special', 'special2', 'personal',
'horse', 'weapon', 'book', 'item', 'last_turn'
];
$fullColumn = [
'no', 'name', 'owner_name', 'picture', 'imgsvr', 'nation', 'city', 'troop', 'injury', 'affinity',
'no', 'name', 'owner', 'owner_name', 'picture', 'imgsvr', 'nation', 'city', 'troop', 'injury', 'affinity',
'leadership', 'leadership_exp', 'strength', 'strength_exp', 'intel', 'intel_exp', 'weapon', 'book', 'horse', 'item',
'experience', 'dedication', 'officer_level', 'officer_city', 'gold', 'rice', 'crew', 'crewtype', 'train', 'atmos', 'turntime',
'makelimit', 'killturn', 'block', 'dedlevel', 'explevel', 'age', 'startage', 'belong',
'personal', 'special', 'special2', 'defence_train', 'tnmt', 'npc', 'npc_org', 'deadyear', 'npcmsg',
'dex1', 'dex2', 'dex3', 'dex4', 'dex5', 'betray',
'recent_war', 'last_turn', 'myset',
'specage', 'specage2', 'con', 'connect', 'owner', 'aux', 'lastrefresh',
'specage', 'specage2', 'con', 'connect', 'aux', 'lastrefresh',
];
if($reqColumns === null){
@@ -1141,4 +1163,186 @@ class General implements iAction{
}
return $result;
}
/**
* @return int|float
*/
public function getInheritancePoint(string $key, &$aux=null, bool $forceCalc=false){
$inheritType = static::INHERITANCE_KEY[$key]??null;
if($inheritType === null){
throw new \OutOfRangeException("{$key}는 유산 타입이 아님");
}
$ownerID = $this->getVar('owner');
if(!$ownerID){
return 0;
}
if($this->getVar('npc') != 0){
return 0;
}
[$storeType, $multiplier, ] = $inheritType;
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
if($storeType === true || ($gameStor->isunited != 0 && !$forceCalc)){
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}");
[$value, $aux] = $inheritStor->getValue($key);
return $value;
}
if(is_array($storeType)){
[$storSubType, $storSubKey] = $storeType;
if($storSubType === 'rank'){
return $this->getRankVar($storSubKey) * $multiplier;
}
if($storSubType === 'raw'){
return $this->getVar($storSubKey) * $multiplier;
}
if($storSubType === 'aux'){
return ($this->getAuxVar($storSubKey)??0) * $multiplier;
}
throw new \InvalidArgumentException("{$storSubType}은 참조 할 수 없는 유산 세부키임");
}
if($storeType !== false){
throw new \InvalidArgumentException("{$storeType}은 올바르지 않은 유산 키임");
}
$extractFn = function(){ return [0, null];};
switch($key){
case 'dex':
$extractFn = function() use ($multiplier){
$totalDex = 0;
foreach(array_keys(GameUnitConst::allType()) as $armType){
$totalDex += $this->getVar("dex{$armType}");
}
return [$totalDex * $multiplier, null];
};
break;
case 'betting':
$extractFn = function() use ($multiplier){
$betWin = $this->getRankVar('betwin');
$betWinRate = $this->getRankVar('betwingold')/max(1, $this->getRankVar('betgold'));
return [$betWin * $multiplier * pow($betWinRate, 2), null];
};
break;
case 'max_belong':
$extractFn = function() use ($multiplier){
$maxBelong = max($this->getVar('belong'), $this->getAuxVar('max_belong')??0);
return [$maxBelong * $multiplier, null];
};
break;
default:
throw new \InvalidArgumentException("{$key}는 유산 추출기를 보유하고 있지 않음");
}
[$value, $aux] = ($extractFn)();
return $value;
}
public function setInheritancePoint(string $key, $value, $aux=null){
if(!is_int($value) && !is_float($value)){
throw new \InvalidArgumentException("{$value}는 숫자가 아님");
}
$inheritType = static::INHERITANCE_KEY[$key]??null;
if($inheritType === null){
throw new \OutOfRangeException("{$key}는 유산 타입이 아님");
}
[$storeType, $multiplier, ] = $inheritType;
if($storeType !== true){
throw new \InvalidArgumentException("{$key}는 직접 저장형 유산 포인트가 아님");
}
if($multiplier != 1 && $value != 0){
throw new \InvalidArgumentException("{$key}는 1:1 유산 포인트가 아님");
}
$ownerID = $this->getVar('owner');
if(!$ownerID){
return;
}
if($this->getVar('npc') != 0){
return;
}
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
if($gameStor->isunited != 0){
return;
}
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}");
$inheritStor->setValue($key, [$value, $aux]);
}
public function increaseInheritancePoint(string $key, $value, $aux=null){
if(!is_int($value) && !is_float($value)){
throw new \InvalidArgumentException("{$value}는 숫자가 아님");
}
$inheritType = static::INHERITANCE_KEY[$key]??null;
if($inheritType === null){
throw new \OutOfRangeException("{$key}는 유산 타입이 아님");
}
[$storeType, $multiplier, ] = $inheritType;
if($storeType !== true){
throw new \InvalidArgumentException("{$key}는 직접 저장형 유산 포인트가 아님");
}
$ownerID = $this->getVar('owner');
if(!$ownerID){
return;
}
if($this->getVar('npc') != 0){
return;
}
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
if($gameStor->isunited != 0){
return;
}
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}");
[$oldValue, $oldAux] = $inheritStor->getValue($key)??[0, null];
if($oldAux !== $aux){
$oldValue = 0;
}
$newValue = $oldValue + $value * $multiplier;
$inheritStor->setValue($key, [$newValue, $aux]);
}
public function mergeTotalInheritancePoint(){
$ownerID = $this->getVar('owner');
if(!$ownerID){
return;
}
if($this->getVar('npc') != 0){
return;
}
$inheritStor = KVStorage::getStorage(DB::db(), "inheritance_{$ownerID}");
$inheritStor->cacheAll();
foreach(static::INHERITANCE_KEY as $key=>[$storType, ,]){
$aux = null;
$point = $this->getInheritancePoint($key, $aux, true);
if($storType === true){
continue;
}
$inheritStor->setValue($key, [$point, $aux]);
}
$oldInheritStor = KVStorage::getStorage(DB::db(), "inheritance_result");
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$serverID = UniqueConst::$serverID;
$year = $gameStor->year;
$month = $gameStor->month;
$oldInheritStor->setValue("{$serverID}_{$ownerID}_{$this->getID()}_{$year}_{$month}", $inheritStor->getAll(true));
}
}
+86 -2
View File
@@ -1712,6 +1712,88 @@ class GeneralAI
return $cmd;
}
// 군주 행동
protected function do불가침제의(LastTurn $lastTurn): ?NationCommand
{
$general = $this->general;
if($general->getVar('officer_level') < 12){
return null;
}
$nation = $this->nation;
$nationID = $nation['nation'];
$nationStor = KVStorage::getStorage(DB::db(), $nationID, 'nation_env');
$recvAssist = $nationStor->getValue('recv_assist')??[];
$respAssist = $nationStor->getValue('resp_assist')??[];
$respAssistTry = $nationStor->getValue('resp_assist_try')??[];
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
$candidateList = [];
foreach($recvAssist as [$candNationID, $amount]){
$amount -= $respAssist["n{$candNationID}"][1]??0;
if($amount <= 0){
continue;
}
if(key_exists($candNationID, $this->warTargetNation)){
continue;
}
if(($respAssistTry["n{$candNationID}"][1]??0) >= $yearMonth - 8){
continue;
}
$candidateList[$candNationID] = $amount;
}
if(!$candidateList){
return null;
}
$cityList = $this->supplyCities;
if (!$cityList) {
return null;
}
$goldIncome = getGoldIncome($nation['nation'], $nation['level'], 15, $nation['capital'], $nation['type'], $cityList);
$riceIncome = getRiceIncome($nation['nation'], $nation['level'], 15, $nation['capital'], $nation['type'], $cityList);
$wallIncome = getWallIncome($nation['nation'], $nation['level'], 15, $nation['capital'], $nation['type'], $cityList);
$income = $goldIncome + $riceIncome + $wallIncome;
arsort($candidateList);
$destNationID = null;
$diplomatMonth = 0;
foreach($candidateList as $candNationID => $amount){
if($amount * 4 < $income){
break;
}
$destNationID = $candNationID;
$diplomatMonth = 24 * $amount / $income;
break;
}
if($destNationID === null){
return null;
}
[$targetYear, $targetMonth] = Util::parseYearMonth($yearMonth + $diplomatMonth);
$cmd = buildNationCommandClass('che_불가침제의', $this->general, $this->env, $lastTurn, [
'destNationID' => $destNationID,
'year' => $targetYear,
'month' => $targetMonth,
]);
if(!$cmd->hasFullConditionMet()){
return null;
}
$respAssistTry["n{$destNationID}"] = [$destNationID, $yearMonth];
$nationStor->setValue('resp_assist_try', $respAssistTry);
return $cmd;
}
// 군주 행동
protected function do선전포고(LastTurn $lastTurn): ?NationCommand
@@ -3067,6 +3149,9 @@ class GeneralAI
if($general->getVar('makelimit')){
return null;
}
if($general->getNPCType() > 2){
return null;
}
if(!$this->generalPolicy->can건국){
return null;
}
@@ -3167,8 +3252,7 @@ class GeneralAI
return null;
}
if (Util::randBool(pow(1 / $nationCnt / pow($notFullNationCnt, 3), 1 / 4))) {
//국가가 1개일 경우에는 '임관하지 않음'
if (Util::randBool(pow(1 / ($nationCnt + 1) / pow($notFullNationCnt, 3), 1 / 4))) {
return null;
}
}
+4 -1
View File
@@ -76,7 +76,10 @@ class Nation{
$capital = 0;
}
if(strpos($this->type, '_') === FALSE){
if($this->type === null){
$type = Util::choiceRandom(GameConst::$availableNationType);
}
else if(strpos($this->type, '_') === FALSE){
$type = 'che_'.$this->type;
}
else{
+2
View File
@@ -257,6 +257,8 @@ class TurnExecutionHelper
$autorunMode = false;
$ai = null;
$general->increaseInheritancePoint('lived_month', 1);
$turnObj->preprocessCommand($env);
$generalCommandObj = $general->getReservedTurn(0, $env);