전략 사용 방식 변경

This commit is contained in:
2020-07-13 21:54:32 +09:00
parent 189db2a051
commit a09511defb
24 changed files with 4024 additions and 3910 deletions
+34 -1
View File
@@ -17,6 +17,7 @@ use \sammo\Constraint\ConstraintHelper;
abstract class BaseCommand{
static protected $actionName = 'CommandName';
static public $reqArg = false;
static protected $isLazyCalcReqTurn = false;
public function getCommandDetailTitle():string{
return $this->getName();
@@ -54,7 +55,6 @@ abstract class BaseCommand{
static protected $isInitStatic = true;
protected static function initStatic(){
}
public function __construct(General $generalObj, array $env, $arg = null){
@@ -271,6 +271,29 @@ abstract class BaseCommand{
return $this->logger;
}
abstract protected function getNextExecuteKey():string;
abstract public function getNextAvailable():?int;
abstract public function setNextAvailable(?int $yearMonth=null);
protected function testPostReqTurn():?array{
if(!$this->getPostReqTurn()){
return null;
}
$nextAvailable = $this->getNextAvailable();
if($nextAvailable === null){
return null;
}
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
$remainTurn = $nextAvailable - $yearMonth - $this->getPreReqTurn();
if($remainTurn <= 0){
return null;
}
return ['testPostReqTurn', "{$remainTurn}턴 더 기다려야 합니다"];
}
public function testPermissionToReserve():?string{
if($this->cachedPermissionToReserve){
return $this->reasonNoPermissionToReserve;
@@ -331,6 +354,11 @@ abstract class BaseCommand{
];
[$this->reasonConstraint, $this->reasonNotMinConditionMet] = Constraint::testAll($this->minConditionConstraints??[], $constraintInput, $this->env);
if($this->reasonNotMinConditionMet === null && !self::$isLazyCalcReqTurn){
[$this->reasonConstraint, $this->reasonNotMinConditionMet] = $this->testPostReqTurn();
}
$this->cachedMinConditionMet = true;
return $this->reasonNotMinConditionMet;
@@ -364,6 +392,11 @@ abstract class BaseCommand{
];
[$this->reasonConstraint, $this->reasonNotFullConditionMet] = Constraint::testAll($this->fullConditionConstraints??[], $constraintInput, $this->env);
if($this->reasonNotFullConditionMet === null){
[$this->reasonConstraint, $this->reasonNotFullConditionMet] = $this->testPostReqTurn();
}
$this->cachedFullConditionMet = true;
return $this->reasonNotFullConditionMet;
@@ -32,24 +32,6 @@ class che_전투특기초기화 extends Command\GeneralCommand{
}
protected function init(){
$general = $this->generalObj;
$env = $this->env;
$yearMonth = Util::joinYearMonth($env['year'], $env['month']);
$auxYearMonth = $general->getAuxVar('used_'.$this->getName())??-999;
if($yearMonth < $auxYearMonth + 60 - $this->getPreReqTurn()){
$this->minConditionConstraints=[
ConstraintHelper::AlwaysFail('초기화한 지 5년이 지나야합니다')
];
$this->fullConditionConstraints=[
ConstraintHelper::AlwaysFail('초기화한 지 5년이 지나야합니다')
];
return;
}
$this->minConditionConstraints=[
ConstraintHelper::ReqGeneralValue(static::$specialType, static::$specialText, '!=', 'None', '특기가 없습니다.'),
];
@@ -57,7 +39,6 @@ class che_전투특기초기화 extends Command\GeneralCommand{
$this->fullConditionConstraints=[
ConstraintHelper::ReqGeneralValue(static::$specialType, static::$specialText, '!=', 'None', '특기가 없습니다.')
];
}
public function getCommandDetailTitle():string{
@@ -82,7 +63,7 @@ class che_전투특기초기화 extends Command\GeneralCommand{
}
public function getPostReqTurn():int{
return 0;
return 60;
}
public function getTermString():string{
@@ -113,7 +94,6 @@ class che_전투특기초기화 extends Command\GeneralCommand{
$general->setVar(static::$specialType, 'None');
$general->setVar(static::$speicalAge, $general->getVar('age') + 1);
$general->setAuxVar('used_'.$this->getName(), $yearMonth);
$logger = $general->getLogger();
+35 -5
View File
@@ -1,6 +1,36 @@
<?php
namespace sammo\Command;
abstract class GeneralCommand extends BaseCommand{
<?php
namespace sammo\Command;
use \sammo\Util;
abstract class GeneralCommand extends BaseCommand{
protected function getNextExecuteKey():string{
$turnKey = static::$actionName;
$generalID = $this->getGeneral()->getID();
$executeKey = "next_execute_{$generalID}_{$turnKey}";
return $executeKey;
}
public function getNextAvailable():?int{
if($this->isArgValid && !$this->getPostReqTurn()){
return null;
}
$db = \sammo\DB::db();
$lastExecuteStor = \sammo\KVStorage::getStorage($db, 'next_execute');
return $lastExecuteStor->getValue($this->getNextExecuteKey());
}
public function setNextAvailable(?int $yearMonth=null){
if(!$this->getPostReqTurn()){
return;
}
if($yearMonth === null){
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']) + $this->getPostReqTurn();
}
$db = \sammo\DB::db();
$lastExecuteStor = \sammo\KVStorage::getStorage($db, 'next_execute');
$lastExecuteStor->setValue($this->getNextExecuteKey(), $yearMonth);
}
};
+251 -251
View File
@@ -1,251 +1,251 @@
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
Message,
MessageTarget
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_급습 extends Command\NationCommand
{
static protected $actionName = '급습';
static public $reqArg = true;
protected function argTest(): bool
{
if ($this->arg === null) {
return false;
}
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if (!key_exists('destNationID', $this->arg)) {
return false;
}
$destNationID = $this->arg['destNationID'];
if (!is_int($destNationID)) {
return false;
}
if ($destNationID < 1) {
return false;
}
$this->arg = [
'destNationID' => $destNationID
];
return true;
}
protected function init()
{
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(),
];
}
protected function initWithArg()
{
$this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyWithTerm(
1,
12,
'선포 12개월 이상인 상대국에만 가능합니다.'
),
ConstraintHelper::AvailableStrategicCommand(),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 0;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 16) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief(): string
{
$commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}";
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$destNation = $this->destNation;
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($destNationGeneralList as $destNationGeneralID) {
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush();
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$db->update('diplomacy', [
'term' => $db->sqleval('`term` - %i', 3),
], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectNationByMap.js'
];
}
public function getForm(): string
{
$generalObj = $this->generalObj;
$nationID = $generalObj->getNationID();
$nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach (getAllNationStaticInfo() as $destNation) {
if ($destNation['nation'] == $nationID) {
continue;
}
$testTurn->setArg(['destNationID' => $destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]);
if ($testCommand->hasFullConditionMet()) {
$destNation['availableCommand'] = true;
} else {
$destNation['availableCommand'] = false;
}
$nationList[] = $destNation;
}
ob_start();
?>
<?= \sammo\getMapHtml() ?><br>
선택된 국가에 급습을 발동합니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 급습 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach ($nationList as $nation) : ?>
<option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option>
<?php endforeach; ?>
<input type=button id="commonSubmit" value="<?= $this->getName() ?>">
<?php
return ob_get_clean();
}
}
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
Message,
MessageTarget
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_급습 extends Command\NationCommand
{
static protected $actionName = '급습';
static public $reqArg = true;
protected function argTest(): bool
{
if ($this->arg === null) {
return false;
}
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if (!key_exists('destNationID', $this->arg)) {
return false;
}
$destNationID = $this->arg['destNationID'];
if (!is_int($destNationID)) {
return false;
}
if ($destNationID < 1) {
return false;
}
$this->arg = [
'destNationID' => $destNationID
];
return true;
}
protected function init()
{
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
protected function initWithArg()
{
$this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyWithTerm(
1,
12,
'선포 12개월 이상인 상대국에만 가능합니다.'
),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 0;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 16) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief(): string
{
$commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}";
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$destNation = $this->destNation;
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($destNationGeneralList as $destNationGeneralID) {
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush();
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$db->update('diplomacy', [
'term' => $db->sqleval('`term` - %i', 3),
], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectNationByMap.js'
];
}
public function getForm(): string
{
$generalObj = $this->generalObj;
$nationID = $generalObj->getNationID();
$nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach (getAllNationStaticInfo() as $destNation) {
if ($destNation['nation'] == $nationID) {
continue;
}
$testTurn->setArg(['destNationID' => $destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]);
if ($testCommand->hasFullConditionMet()) {
$destNation['availableCommand'] = true;
} else {
$destNation['availableCommand'] = false;
}
$nationList[] = $destNation;
}
ob_start();
?>
<?= \sammo\getMapHtml() ?><br>
선택된 국가에 급습을 발동합니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 급습 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach ($nationList as $nation) : ?>
<option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option>
<?php endforeach; ?>
<input type=button id="commonSubmit" value="<?= $this->getName() ?>">
<?php
return ob_get_clean();
}
}
@@ -124,9 +124,18 @@ class che_물자원조 extends Command\NationCommand{
}
public function getPostReqTurn():int{
//NOTE: 자체 postReqTurn 사용
return 12;
}
public function getNextAvailable():?int{
return null;
}
public function setNextAvailable(?int $yearMonth=null){
return;
}
public function getBrief():string{
[$goldAmount, $riceAmount] = $this->arg['amountList'];
$goldAmountText = number_format($goldAmount);
+192 -195
View File
@@ -1,196 +1,193 @@
<?php
namespace sammo\Command\Nation;
use \sammo\{
DB, Util, JosaUtil,
General, DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
MessageTarget,
Message,
CityConst
};
use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
GetImageURL,
getNationStaticInfo
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action;
class che_백성동원 extends Command\NationCommand{
static protected $actionName = '백성동원';
static public $reqArg = true;
protected function argTest():bool{
if($this->arg === null){
return false;
}
if(!key_exists('destCityID', $this->arg)){
return false;
}
if(CityConst::byID($this->arg['destCityID']) === null){
return false;
}
$destCityID = $this->arg['destCityID'];
$this->arg = [
'destCityID'=>$destCityID,
];
return true;
}
protected function init(){
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand()
];
}
protected function initWithArg()
{
$this->setDestCity($this->arg['destCityID']);
$this->setDestNation($this->destCity['nation']);
$this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AllowDiplomacyStatus($this->generalObj->getNationID(), [
0, 1
], '전쟁중이 아닙니다.'),
ConstraintHelper::OccupiedDestCity(),
ConstraintHelper::AvailableStrategicCommand()
];
}
public function getCommandDetailTitle():string{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost():array{
return [0, 0];
}
public function getPreReqTurn():int{
return 0;
}
public function getPostReqTurn():int{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount*4)*10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief():string{
$commandName = $this->getName();
$destCityName = CityConst::byID($this->arg['destCityID'])->name;
return "{$destCityName}】에 {$commandName}";
}
public function run():bool{
if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$destCity = $this->destCity;
$destCityID = $destCity['city'];
$destCityName = $destCity['name'];
$nationID = $general->getNationID();
$nationName = $this->nation['name'];
$logger = $general->getLogger();
$logger->pushGeneralActionLog("백성동원 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach($targetGeneralList as $targetGeneralID){
$targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month);
$targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$targetLogger->flush();
}
$db->update('city', [
'def' => $db->sqleval('GREATEST(def_max * 0.8, def)'),
'wall' => $db->sqleval('GREATEST(wall_max * 0.8, wall)'),
], 'city=%i', $destCityID);
$josaYiNation = JosaUtil::pick($nationName, '이');
$logger->pushGeneralHistoryLog('<M>백성동원</>을 발동');
$logger->pushNationalHistoryLog("<L><b>【전략】</b></><D><b>{$nationName}</b></>{$josaYiNation} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다.");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectCityByMap.js'
];
}
public function getForm(): string
{
ob_start();
?>
<?=\sammo\getMapHtml()?><br>
선택된 도시에 백성을 동원해 성벽을 쌓습니다.<br>
아국 도시만 가능합니다.<br>
목록을 선택하거나 도시를 클릭하세요.<br>
<select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'>
<?=\sammo\optionsForCities()?><br>
</select> <input type=button id="commonSubmit" value="<?=$this->getName()?>"><br>
<br>
<?php
return ob_get_clean();
}
<?php
namespace sammo\Command\Nation;
use \sammo\{
DB, Util, JosaUtil,
General, DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
MessageTarget,
Message,
CityConst
};
use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
GetImageURL,
getNationStaticInfo
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action;
class che_백성동원 extends Command\NationCommand{
static protected $actionName = '백성동원';
static public $reqArg = true;
protected function argTest():bool{
if($this->arg === null){
return false;
}
if(!key_exists('destCityID', $this->arg)){
return false;
}
if(CityConst::byID($this->arg['destCityID']) === null){
return false;
}
$destCityID = $this->arg['destCityID'];
$this->arg = [
'destCityID'=>$destCityID,
];
return true;
}
protected function init(){
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn())
];
}
protected function initWithArg()
{
$this->setDestCity($this->arg['destCityID']);
$this->setDestNation($this->destCity['nation']);
$this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::OccupiedDestCity(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn())
];
}
public function getCommandDetailTitle():string{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost():array{
return [0, 0];
}
public function getPreReqTurn():int{
return 0;
}
public function getPostReqTurn():int{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount*4)*10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief():string{
$commandName = $this->getName();
$destCityName = CityConst::byID($this->arg['destCityID'])->name;
return "{$destCityName}】에 {$commandName}";
}
public function run():bool{
if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$destCity = $this->destCity;
$destCityID = $destCity['city'];
$destCityName = $destCity['name'];
$nationID = $general->getNationID();
$nationName = $this->nation['name'];
$logger = $general->getLogger();
$logger->pushGeneralActionLog("백성동원 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach($targetGeneralList as $targetGeneralID){
$targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month);
$targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$targetLogger->flush();
}
$db->update('city', [
'def' => $db->sqleval('GREATEST(def_max * 0.8, def)'),
'wall' => $db->sqleval('GREATEST(wall_max * 0.8, wall)'),
], 'city=%i', $destCityID);
$josaYiNation = JosaUtil::pick($nationName, '이');
$logger->pushGeneralHistoryLog('<M>백성동원</>을 발동');
$logger->pushNationalHistoryLog("<L><b>【전략】</b></><D><b>{$nationName}</b></>{$josaYiNation} <G><b>{$destCityName}</b></>에 <M>백성동원</>을 하였습니다.");
$db->update('nation', [
'strategic_cmd_limit' => 12
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectCityByMap.js'
];
}
public function getForm(): string
{
ob_start();
?>
<?=\sammo\getMapHtml()?><br>
선택된 도시에 백성을 동원해 성벽을 쌓습니다.<br>
아국 도시만 가능합니다.<br>
목록을 선택하거나 도시를 클릭하세요.<br>
<select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'>
<?=\sammo\optionsForCities()?><br>
</select> <input type=button id="commonSubmit" value="<?=$this->getName()?>"><br>
<br>
<?php
return ob_get_clean();
}
}
+3 -3
View File
@@ -60,7 +60,7 @@ class che_수몰 extends Command\NationCommand{
$this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
@@ -75,7 +75,7 @@ class che_수몰 extends Command\NationCommand{
ConstraintHelper::NotNeutralDestCity(),
ConstraintHelper::NotOccupiedDestCity(),
ConstraintHelper::BattleGroundCity(),
ConstraintHelper::AvailableStrategicCommand(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
@@ -179,7 +179,7 @@ class che_수몰 extends Command\NationCommand{
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>수몰</>을 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
'strategic_cmd_limit' => 12
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
+243 -243
View File
@@ -1,243 +1,243 @@
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
KVStorage
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
tryUniqueItemLottery
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_의병모집 extends Command\NationCommand
{
static protected $actionName = '의병모집';
protected function argTest(): bool
{
$this->arg = null;
return true;
}
protected function init()
{
$general = $this->generalObj;
$this->setNation(['strategic_cmd_limit']);
$this->setCity();
$env = $this->env;
$relYear = $env['year'] - $env['startyear'];
$this->fullConditionConstraints = [
ConstraintHelper::BeChief(),
ConstraintHelper::NotBeNeutral(),
ConstraintHelper::OccupiedCity(),
ConstraintHelper::AvailableStrategicCommand(),
ConstraintHelper::NotOpeningPart($relYear),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 2;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 10) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$genCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc < 2', $nationID);
$npcCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc = 3', $nationID);
$npcOtherCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation!=%i AND npc = 3', $nationID);
$genCount = Util::valueFit($genCount, 1);
$npcCount = Util::valueFit($npcCount, 1);
$npcOtherCountScore = Util::round(sqrt($npcOtherCount + 1)) - 1;
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$logger->pushGeneralHistoryLog("<M>{$commandName}</>{$josaUl} 발동");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$gameStor = KVStorage::getStorage($db, 'game_env'); //TODO: 차라리 env가 이거여야..?
$avgGenCnt = $db->queryFirstField('SELECT avg(gennum) FROM nation WHERE level > 0');
$createGenCnt = 5 + Util::round($avgGenCnt / 10);
$createGenIdx = $gameStor->npccount + 1;
$lastCreatGenIdx = $createGenIdx + $createGenCnt;
$pickTypeList = ['무' => 5, '지' => 5];
$avgGen = $db->queryFirstRow(
'SELECT avg(dedication) as ded,avg(experience) as exp,
avg(dex1+dex2+dex3+dex4) as dex_t, avg(age) as age, avg(dex5) as dex5
from general where nation=%i',
$nationID
);
$dexTotal = $avgGen['dex_t'];
for (; $createGenIdx <= $lastCreatGenIdx; $createGenIdx++) {
$pickType = Util::choiceRandomUsingWeight($pickTypeList);
$totalStat = GameConst::$defaultStatNPCMax * 2 + 10;
$minStat = 10;
$mainStat = GameConst::$defaultStatNPCMax - Util::randRangeInt(0, 10);
//TODO: defaultStatNPCTotal, defaultStatNPCMin 추가
$otherStat = $minStat + Util::randRangeInt(0, 5);
$subStat = $totalStat - $mainStat - $otherStat;
if ($subStat < $minStat) {
$subStat = $otherStat;
$otherStat = $minStat;
$mainStat = $totalStat - $subStat - $otherStat;
if ($mainStat) {
throw new \LogicException('기본 스탯 설정값이 잘못되어 있음');
}
}
if ($pickType == '무') {
$leadership = $subStat;
$strength = $mainStat;
$intel = $otherStat;
$dexVal = Util::choiceRandom([
[$dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8, $dexTotal / 8],
[$dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8],
[$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8],
]);
} else if ($pickType == '지') {
$leadership = $subStat;
$strength = $otherStat;
$intel = $mainStat;
$dexVal = [$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8];
} else {
$leadership = $otherStat;
$strength = $subStat;
$intel = $mainStat;
$dexVal = [$dexTotal / 4, $dexTotal / 4, $dexTotal / 4, $dexTotal / 4];
}
$leadership = Util::round($leadership);
$strength = Util::round($strength);
$intel = Util::round($intel);
$age = $avgGen['age'];
$newNPC = new \sammo\Scenario\NPC(
Util::randRangeInt(1, 150),
"의병장{$createGenIdx}",
null,
$nationID,
$general->getCityID(),
$leadership,
$strength,
$intel,
1,
$env['year'] - 20,
$env['year'] + 6,
null,
null
);
$newNPC->killturn = Util::randRangeInt(64, 70);
$newNPC->npc = 4;
$newNPC->setMoney(1000, 1000);
$newNPC->setExpDed($avgGen['exp'], $avgGen['ded']);
$newNPC->setDex(
$dexVal[0],
$dexVal[1],
$dexVal[2],
$dexVal[3],
$avgGen['dex5']
);
$newNPC->build($this->env);
}
$gameStor->npccount = $lastCreatGenIdx;
$db->update('nation', [
'gennum' => $db->sqleval('gennum + %i', $createGenCnt),
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db);
return true;
}
}
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
KVStorage
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
tryUniqueItemLottery
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_의병모집 extends Command\NationCommand
{
static protected $actionName = '의병모집';
protected function argTest(): bool
{
$this->arg = null;
return true;
}
protected function init()
{
$general = $this->generalObj;
$this->setNation(['strategic_cmd_limit']);
$this->setCity();
$env = $this->env;
$relYear = $env['year'] - $env['startyear'];
$this->fullConditionConstraints = [
ConstraintHelper::BeChief(),
ConstraintHelper::NotBeNeutral(),
ConstraintHelper::OccupiedCity(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
ConstraintHelper::NotOpeningPart($relYear),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 2;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 10) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$genCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc < 2', $nationID);
$npcCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc = 3', $nationID);
$npcOtherCount = $db->queryFirstField('SELECT count(no) FROM general WHERE nation!=%i AND npc = 3', $nationID);
$genCount = Util::valueFit($genCount, 1);
$npcCount = Util::valueFit($npcCount, 1);
$npcOtherCountScore = Util::round(sqrt($npcOtherCount + 1)) - 1;
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$logger->pushGeneralHistoryLog("<M>{$commandName}</>{$josaUl} 발동");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>{$commandName}</>{$josaUl} 발동");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$gameStor = KVStorage::getStorage($db, 'game_env'); //TODO: 차라리 env가 이거여야..?
$avgGenCnt = $db->queryFirstField('SELECT avg(gennum) FROM nation WHERE level > 0');
$createGenCnt = 5 + Util::round($avgGenCnt / 10);
$createGenIdx = $gameStor->npccount + 1;
$lastCreatGenIdx = $createGenIdx + $createGenCnt;
$pickTypeList = ['무' => 5, '지' => 5];
$avgGen = $db->queryFirstRow(
'SELECT avg(dedication) as ded,avg(experience) as exp,
avg(dex1+dex2+dex3+dex4) as dex_t, avg(age) as age, avg(dex5) as dex5
from general where nation=%i',
$nationID
);
$dexTotal = $avgGen['dex_t'];
for (; $createGenIdx <= $lastCreatGenIdx; $createGenIdx++) {
$pickType = Util::choiceRandomUsingWeight($pickTypeList);
$totalStat = GameConst::$defaultStatNPCMax * 2 + 10;
$minStat = 10;
$mainStat = GameConst::$defaultStatNPCMax - Util::randRangeInt(0, 10);
//TODO: defaultStatNPCTotal, defaultStatNPCMin 추가
$otherStat = $minStat + Util::randRangeInt(0, 5);
$subStat = $totalStat - $mainStat - $otherStat;
if ($subStat < $minStat) {
$subStat = $otherStat;
$otherStat = $minStat;
$mainStat = $totalStat - $subStat - $otherStat;
if ($mainStat) {
throw new \LogicException('기본 스탯 설정값이 잘못되어 있음');
}
}
if ($pickType == '무') {
$leadership = $subStat;
$strength = $mainStat;
$intel = $otherStat;
$dexVal = Util::choiceRandom([
[$dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8, $dexTotal / 8],
[$dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8, $dexTotal / 8],
[$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8],
]);
} else if ($pickType == '지') {
$leadership = $subStat;
$strength = $otherStat;
$intel = $mainStat;
$dexVal = [$dexTotal / 8, $dexTotal / 8, $dexTotal * 5 / 8, $dexTotal / 8];
} else {
$leadership = $otherStat;
$strength = $subStat;
$intel = $mainStat;
$dexVal = [$dexTotal / 4, $dexTotal / 4, $dexTotal / 4, $dexTotal / 4];
}
$leadership = Util::round($leadership);
$strength = Util::round($strength);
$intel = Util::round($intel);
$age = $avgGen['age'];
$newNPC = new \sammo\Scenario\NPC(
Util::randRangeInt(1, 150),
"의병장{$createGenIdx}",
null,
$nationID,
$general->getCityID(),
$leadership,
$strength,
$intel,
1,
$env['year'] - 20,
$env['year'] + 6,
null,
null
);
$newNPC->killturn = Util::randRangeInt(64, 70);
$newNPC->npc = 4;
$newNPC->setMoney(1000, 1000);
$newNPC->setExpDed($avgGen['exp'], $avgGen['ded']);
$newNPC->setDex(
$dexVal[0],
$dexVal[1],
$dexVal[2],
$dexVal[3],
$avgGen['dex5']
);
$newNPC->build($this->env);
}
$gameStor->npccount = $lastCreatGenIdx;
$db->update('nation', [
'gennum' => $db->sqleval('gennum + %i', $createGenCnt),
'strategic_cmd_limit' => 12
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db);
return true;
}
}
+250 -250
View File
@@ -1,250 +1,250 @@
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
Message,
MessageTarget
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_이호경식 extends Command\NationCommand
{
static protected $actionName = '이호경식';
static public $reqArg = true;
protected function argTest(): bool
{
if ($this->arg === null) {
return false;
}
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if (!key_exists('destNationID', $this->arg)) {
return false;
}
$destNationID = $this->arg['destNationID'];
if (!is_int($destNationID)) {
return false;
}
if ($destNationID < 1) {
return false;
}
$this->arg = [
'destNationID' => $destNationID
];
return true;
}
protected function init()
{
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(),
];
}
protected function initWithArg()
{
$this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.'
),
ConstraintHelper::AvailableStrategicCommand(),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 0;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 16) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief(): string
{
$commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}";
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$destNation = $this->destNation;
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($destNationGeneralList as $destNationGeneralID) {
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush();
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$db->update('diplomacy', [
'term' => $db->sqleval('IF(`state`=0, %i, `term`+ %i)', 3, 3),
'state' => 1,
], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectNationByMap.js'
];
}
public function getForm(): string
{
$generalObj = $this->generalObj;
$nationID = $generalObj->getNationID();
$nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach (getAllNationStaticInfo() as $destNation) {
if ($destNation['nation'] == $nationID) {
continue;
}
$testTurn->setArg(['destNationID' => $destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]);
if ($testCommand->hasFullConditionMet()) {
$destNation['availableCommand'] = true;
} else {
$destNation['availableCommand'] = false;
}
$nationList[] = $destNation;
}
ob_start();
?>
<?= \sammo\getMapHtml() ?><br>
선택된 국가에 이호경식을 발동합니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 이호경식 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach ($nationList as $nation) : ?>
<option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option>
<?php endforeach; ?>
<input type=button id="commonSubmit" value="<?= $this->getName() ?>">
<?php
return ob_get_clean();
}
}
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
Message,
MessageTarget
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_이호경식 extends Command\NationCommand
{
static protected $actionName = '이호경식';
static public $reqArg = true;
protected function argTest(): bool
{
if ($this->arg === null) {
return false;
}
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if (!key_exists('destNationID', $this->arg)) {
return false;
}
$destNationID = $this->arg['destNationID'];
if (!is_int($destNationID)) {
return false;
}
if ($destNationID < 1) {
return false;
}
$this->arg = [
'destNationID' => $destNationID
];
return true;
}
protected function init()
{
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
protected function initWithArg()
{
$this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.'
),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 0;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 16) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief(): string
{
$commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}";
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$destNation = $this->destNation;
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($nationGeneralList as $nationGeneralID) {
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($destNationGeneralList as $destNationGeneralID) {
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush();
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$db->update('nation', [
'strategic_cmd_limit' => 12
], 'nation=%i', $nationID);
$db->update('diplomacy', [
'term' => $db->sqleval('IF(`state`=0, %i, `term`+ %i)', 3, 3),
'state' => 1,
], '(me = %i AND you = %i) OR (you = %i AND me = %i)', $nationID, $destNationID, $nationID, $destNationID);
$this->setResultTurn(new LastTurn(static::getName(), $this->arg));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectNationByMap.js'
];
}
public function getForm(): string
{
$generalObj = $this->generalObj;
$nationID = $generalObj->getNationID();
$nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach (getAllNationStaticInfo() as $destNation) {
if ($destNation['nation'] == $nationID) {
continue;
}
$testTurn->setArg(['destNationID' => $destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID' => $destNation['nation']]);
if ($testCommand->hasFullConditionMet()) {
$destNation['availableCommand'] = true;
} else {
$destNation['availableCommand'] = false;
}
$nationList[] = $destNation;
}
ob_start();
?>
<?= \sammo\getMapHtml() ?><br>
선택된 국가에 이호경식을 발동합니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 이호경식 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach ($nationList as $nation) : ?>
<option value='<?= $nation['nation'] ?>' style='color:<?= $nation['color'] ?>;<?= $nation['availableCommand'] ? '' : 'background-color:red;' ?>'>【<?= $nation['name'] ?> 】</option>
<?php endforeach; ?>
<input type=button id="commonSubmit" value="<?= $this->getName() ?>">
<?php
return ob_get_clean();
}
}
@@ -95,9 +95,18 @@ class che_초토화 extends Command\NationCommand{
}
public function getPostReqTurn():int{
//NOTE: 자체 postReqTurn 사용
return 24;
}
public function getNextAvailable():?int{
return null;
}
public function setNextAvailable(?int $yearMonth=null){
return;
}
public function getCommandDetailTitle():string{
$name = $this->getName();
+256 -238
View File
@@ -1,239 +1,257 @@
<?php
namespace sammo\Command\Nation;
use \sammo\{
DB, Util, JosaUtil,
General, DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
Message, MessageTarget
};
use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_피장파장 extends Command\NationCommand{
static protected $actionName = '피장파장';
static public $reqArg = true;
static public $delayCnt = 60;
protected function argTest():bool{
if($this->arg === null){
return false;
}
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if(!key_exists('destNationID', $this->arg)){
return false;
}
$destNationID = $this->arg['destNationID'];
if(!is_int($destNationID)){
return false;
}
if($destNationID < 1){
return false;
}
$this->arg = [
'destNationID'=>$destNationID
];
return true;
}
protected function init(){
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(),
];
}
protected function initWithArg()
{
$this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.'
),
ConstraintHelper::AvailableStrategicCommand(),
];
}
public function getCommandDetailTitle():string{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost():array{
return [0, 0];
}
public function getPreReqTurn():int{
return 2;
}
public function getPostReqTurn():int{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount*2)*10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief():string{
$commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}";
}
public function run():bool{
if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$destNation = $this->destNation;
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach($nationGeneralList as $nationGeneralID){
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach($destNationGeneralList as $destNationGeneralID){
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush();
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$db->update('nation', [
'strategic_cmd_limit' => $db->sqleval('strategic_cmd_limit + %i', static::$delayCnt)
], 'nation = %i', $destNationID);
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectNationByMap.js'
];
}
public function getForm(): string
{
$generalObj = $this->generalObj;
$nationID = $generalObj->getNationID();
$nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach(getAllNationStaticInfo() as $destNation){
if($destNation['nation'] == $nationID){
continue;
}
$testTurn->setArg(['destNationID'=>$destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID'=>$destNation['nation']]);
if($testCommand->hasFullConditionMet()){
$destNation['availableCommand'] = true;
}
else{
$destNation['availableCommand'] = false;
}
$nationList[] = $destNation;
}
ob_start();
?>
<?=\sammo\getMapHtml()?><br>
선택된 국가에 피장파장을 발동합니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 피장파장 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach($nationList as $nation): ?>
<option
value='<?=$nation['nation']?>'
style='color:<?=$nation['color']?>;<?=$nation['availableCommand']?'':'background-color:red;'?>'
>【<?=$nation['name']?> 】</option>
<?php endforeach; ?>
<input type=button id="commonSubmit" value="<?=$this->getName()?>">
<?php
return ob_get_clean();
}
<?php
namespace sammo\Command\Nation;
use \sammo\{
DB, Util, JosaUtil,
General, DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
Message, MessageTarget
};
use function \sammo\{
buildNationCommandClass,
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
getAllNationStaticInfo,
getNationStaticInfo,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
class che_피장파장 extends Command\NationCommand{
static protected $actionName = '피장파장';
static public $reqArg = true;
static public $delayCnt = 60;
protected function argTest():bool{
if($this->arg === null){
return false;
}
//NOTE: 멸망 직전에 턴을 넣을 수 있으므로, 존재하지 않는 국가여도 argTest에서 바로 탈락시키지 않음
if(!key_exists('destNationID', $this->arg)){
return false;
}
$destNationID = $this->arg['destNationID'];
if(!is_int($destNationID)){
return false;
}
if($destNationID < 1){
return false;
}
$this->arg = [
'destNationID'=>$destNationID
];
return true;
}
protected function init(){
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation();
$this->minConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
];
}
protected function initWithArg()
{
$this->setDestNation($this->arg['destNationID'], null);
$this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::ExistsDestNation(),
ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.'
),
];
}
public function getCommandDetailTitle():string{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}";
}
public function getCost():array{
return [0, 0];
}
public function getPreReqTurn():int{
return 1;
}
public function getPostReqTurn():int{
return 0;
}
public function getBrief():string{
$commandName = $this->getName();
$destNationName = getNationStaticInfo($this->arg['destNationID'])['name'];
return "{$destNationName}】에 {$commandName}";
}
public function run():bool{
if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$env = $this->env;
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$nation = $this->nation;
$nationID = $nation['nation'];
$nationName = $nation['name'];
$destNation = $this->destNation;
$destNationID = $destNation['nation'];
$destNationName = $destNation['name'];
$josaYi = JosaUtil::pick($generalName, '이');
$josaYiNation = JosaUtil::pick($nationName, '이');
$commandName = $this->getName();
$josaUl = JosaUtil::pick($commandName, '을');
$logger = $general->getLogger();
$logger->pushGeneralActionLog("{$commandName} 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동하였습니다.";
$nationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach($nationGeneralList as $nationGeneralID){
$nationGeneralLogger = new ActionLogger($nationGeneralID, $nationID, $year, $month);
$nationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$nationGeneralLogger->flush();
}
$josaYiCommand = JosaUtil::pick($commandName, '이');
$broadcastMessage = "아국에 <M>{$commandName}</>{$josaYiCommand} 발동되었습니다.";
$destNationGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach($destNationGeneralList as $destNationGeneralID){
$destNationGeneralLogger = new ActionLogger($destNationGeneralID, $destNationID, $year, $month);
$destNationGeneralLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$destNationGeneralLogger->flush();
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog("<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국에 <M>{$commandName}</>{$josaUl} 발동");
$destNationLogger->flush();
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <D><b>{$destNationName}</b></>에 <M>{$commandName}</>{$josaUl} 발동");
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectNationByMap.js'
];
}
public function getForm(): string
{
$generalObj = $this->generalObj;
$nationID = $generalObj->getNationID();
$nationList = [];
$testTurn = new LastTurn($this->getName(), null, $this->getPreReqTurn());
foreach(getAllNationStaticInfo() as $destNation){
if($destNation['nation'] == $nationID){
continue;
}
$testTurn->setArg(['destNationID'=>$destNation['nation']]);
$testCommand = new static($generalObj, $this->env, $testTurn, ['destNationID'=>$destNation['nation']]);
if($testCommand->hasFullConditionMet()){
$destNation['availableCommand'] = true;
}
else{
$destNation['availableCommand'] = false;
}
$nationList[] = $destNation;
}
$availableCommandTypeList = [];
$currYearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']);
foreach(GameConst::$availableChiefCommand['전략'] as $commandType){
$cmd = buildNationCommandClass($commandType, $generalObj, $this->env, new LastTurn());
if($cmd->getName() == $this->getName()){
continue;
}
$cmdName = $cmd->getName();
$available = true;
$nextAvailable = $cmd->getNextAvailable();
if($nextAvailable !== null && $currYearMonth < $cmd->getNextAvailable() - $cmd->getPreReqTurn()){
$available = false;
}
$availableCommandTypeList[$commandType] = [$cmdName, $available];
}
ob_start();
?>
<?=\sammo\getMapHtml()?><br>
선택된 국가에 피장파장을 발동합니다.<br>
지정한 전략을 상대국이 <?=static::$delayCnt?>턴 동안 사용할 수 없게됩니다.<br>
선포, 전쟁중인 상대국에만 가능합니다.<br>
상대 국가를 목록에서 선택하세요.<br>
배경색은 현재 피장파장 불가능 국가는 <font color=red>붉은색</font>으로 표시됩니다.<br>
<select class='formInput' name="destNationID" id="destNationID" size='1' style='color:white;background-color:black;'>
<?php foreach($nationList as $nation): ?>
<option
value='<?=$nation['nation']?>'
style='color:<?=$nation['color']?>;<?=$nation['availableCommand']?'':'background-color:red;'?>'
>【<?=$nation['name']?> 】</option>
<?php endforeach; ?>
<select class='formInput' name="commandType" id="commandType" size='1' style='color:white;background-color:black;'>
<?php foreach($availableCommandTypeList as $commandType=>[$cmdName, $cmdAvailable]):
/** @var \sammo\Command\NationCommand $cmdObj */
?>
<option
value='<?=$commandType?>'
style='color:white;<?=$cmdAvailable?'':'background-color:red;'?>'
>【<?=$cmdName?> 】</option>
<?php endforeach; ?>
</select>
<input type=button id="commonSubmit" value="<?=$this->getName()?>">
<?php
return ob_get_clean();
}
}
+133 -133
View File
@@ -1,134 +1,134 @@
<?php
namespace sammo\Command\Nation;
use \sammo\{
DB, Util, JosaUtil,
General, DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
MessageTarget,
Message
};
use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action;
class che_필사즉생 extends Command\NationCommand{
static protected $actionName = '필사즉생';
protected function argTest():bool{
$this->arg = [];
return true;
}
protected function init(){
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AllowDiplomacyStatus($this->generalObj->getNationID(), [
0
], '전쟁중이 아닙니다.'),
ConstraintHelper::AvailableStrategicCommand()
];
}
public function getCommandDetailTitle():string{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost():array{
return [0, 0];
}
public function getPreReqTurn():int{
return 2;
}
public function getPostReqTurn():int{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount*8)*10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function run():bool{
if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$nationID = $general->getNationID();
$nationName = $this->nation['name'];
$logger = $general->getLogger();
$logger->pushGeneralActionLog("필사즉생 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach(General::createGeneralObjListFromDB($targetGeneralList, ['train', 'atmos'], 1) as $targetGeneral){
$targetGeneral->getLogger()->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
if($targetGeneral->getVar('train') < 100){
$targetGeneral->setVar('train', 100);
}
if($targetGeneral->getVar('atmos') < 100){
$targetGeneral->setVar('atmos', 100);
}
$targetGeneral->applyDB($db);
}
if($general->getVar('train') < 100){
$general->setVar('train', 100);
}
if($general->getVar('atmos') < 100){
$general->setVar('atmos', 100);
}
$logger->pushGeneralHistoryLog('<M>필사즉생</>을 발동');
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db);
return true;
}
<?php
namespace sammo\Command\Nation;
use \sammo\{
DB, Util, JosaUtil,
General, DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
MessageTarget,
Message
};
use function \sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
GetImageURL
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action;
class che_필사즉생 extends Command\NationCommand{
static protected $actionName = '필사즉생';
protected function argTest():bool{
$this->arg = [];
return true;
}
protected function init(){
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->fullConditionConstraints=[
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AllowDiplomacyStatus($this->generalObj->getNationID(), [
0
], '전쟁중이 아닙니다.'),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn())
];
}
public function getCommandDetailTitle():string{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn()+1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost():array{
return [0, 0];
}
public function getPreReqTurn():int{
return 2;
}
public function getPostReqTurn():int{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount*8)*10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function run():bool{
if(!$this->hasFullConditionMet()){
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$nationID = $general->getNationID();
$nationName = $this->nation['name'];
$logger = $general->getLogger();
$logger->pushGeneralActionLog("필사즉생 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach(General::createGeneralObjListFromDB($targetGeneralList, ['train', 'atmos'], 1) as $targetGeneral){
$targetGeneral->getLogger()->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
if($targetGeneral->getVar('train') < 100){
$targetGeneral->setVar('train', 100);
}
if($targetGeneral->getVar('atmos') < 100){
$targetGeneral->setVar('atmos', 100);
}
$targetGeneral->applyDB($db);
}
if($general->getVar('train') < 100){
$general->setVar('train', 100);
}
if($general->getVar('atmos') < 100){
$general->setVar('atmos', 100);
}
$logger->pushGeneralHistoryLog('<M>필사즉생</>을 발동');
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <M>필사즉생</>을 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db);
return true;
}
}
+239 -239
View File
@@ -1,239 +1,239 @@
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
MessageTarget,
Message,
CityConst
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
GetImageURL,
getNationStaticInfo
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action;
class che_허보 extends Command\NationCommand
{
static protected $actionName = '허보';
static public $reqArg = true;
protected function argTest(): bool
{
if ($this->arg === null) {
return false;
}
if (!key_exists('destCityID', $this->arg)) {
return false;
}
if (CityConst::byID($this->arg['destCityID']) === null) {
return false;
}
$destCityID = $this->arg['destCityID'];
$this->arg = [
'destCityID' => $destCityID,
];
return true;
}
protected function init()
{
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand(),
];
}
protected function initWithArg()
{
$this->setDestCity($this->arg['destCityID']);
$this->setDestNation($this->destCity['nation']);
$this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::NotNeutralDestCity(),
ConstraintHelper::NotOccupiedDestCity(),
ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.'
),
ConstraintHelper::AvailableStrategicCommand(),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 1;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 4) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief(): string
{
$commandName = $this->getName();
$destCityName = CityConst::byID($this->arg['destCityID'])->name;
return "{$destCityName}】에 {$commandName}";
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$destCity = $this->destCity;
$destCityID = $destCity['city'];
$destCityName = $destCity['name'];
$destNationID = $destCity['nation'];
$destNationName = getNationStaticInfo($destNationID)['name'];
$nationID = $general->getNationID();
$nationName = $this->nation['name'];
$logger = $general->getLogger();
$logger->pushGeneralActionLog("허보 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($targetGeneralList as $targetGeneralID) {
$targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month);
$targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$targetLogger->flush();
}
$destBroadcastMessage = "상대의 <M>허보</>에 당했다! <1>$date</>";
$destNationCityList = $db->queryFirstColumn('SELECT city FROM city WHERE nation = %i AND supply = 1', $destNationID);
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND city=%i', $destNationID, $destCityID);
foreach (General::createGeneralObjListFromDB($targetGeneralList) as $targetGeneralID => $targetGeneral) {
$targetLogger = $targetGeneral->getLogger();
$targetLogger->pushGeneralActionLog($destBroadcastMessage, ActionLogger::PLAIN);
$moveCityID = Util::choiceRandom($destNationCityList);
if ($moveCityID == $destCityID) {
//현재도시면 다시 랜덤 추첨
$moveCityID = Util::choiceRandom($destNationCityList);
}
$targetGeneral->setVar('city', $moveCityID);
$targetGeneral->applyDB($db);
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog(
"<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국의 <G><b>{$destCityName}</b></>에 <M>허보</>를 발동",
ActionLogger::PLAIN
);
$destNationLogger->flush();
$db->update('city', [
'def' => $db->sqleval('def * 0.2'),
'wall' => $db->sqleval('wall * 0.2'),
], 'city=%i', $destCityID);
$josaYiNation = JosaUtil::pick($nationName, '이');
$logger->pushGeneralHistoryLog("<G><b>{$destCityName}</b></>에 <M>허보</>를 발동");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectCityByMap.js'
];
}
public function getForm(): string
{
ob_start();
?>
<?= \sammo\getMapHtml() ?><br>
선택된 도시에 허보를 발동합니다.<br>
전쟁중인 상대국 도시만 가능합니다.<br>
목록을 선택하거나 도시를 클릭하세요.<br>
<select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'>
<?= \sammo\optionsForCities() ?><br>
</select> <input type=button id="commonSubmit" value="<?= $this->getName() ?>"><br>
<br>
<?php
return ob_get_clean();
}
}
<?php
namespace sammo\Command\Nation;
use\sammo\{
DB,
Util,
JosaUtil,
General,
DummyGeneral,
ActionLogger,
GameConst,
LastTurn,
GameUnitConst,
Command,
MessageTarget,
Message,
CityConst
};
use function\sammo\{
getDomesticExpLevelBonus,
CriticalRatioDomestic,
CriticalScoreEx,
GetImageURL,
getNationStaticInfo
};
use \sammo\Constraint\Constraint;
use \sammo\Constraint\ConstraintHelper;
use sammo\Event\Action;
class che_허보 extends Command\NationCommand
{
static protected $actionName = '허보';
static public $reqArg = true;
protected function argTest(): bool
{
if ($this->arg === null) {
return false;
}
if (!key_exists('destCityID', $this->arg)) {
return false;
}
if (CityConst::byID($this->arg['destCityID']) === null) {
return false;
}
$destCityID = $this->arg['destCityID'];
$this->arg = [
'destCityID' => $destCityID,
];
return true;
}
protected function init()
{
$general = $this->generalObj;
$env = $this->env;
$this->setCity();
$this->setNation(['strategic_cmd_limit']);
$this->minConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
protected function initWithArg()
{
$this->setDestCity($this->arg['destCityID']);
$this->setDestNation($this->destCity['nation']);
$this->fullConditionConstraints = [
ConstraintHelper::OccupiedCity(),
ConstraintHelper::BeChief(),
ConstraintHelper::NotNeutralDestCity(),
ConstraintHelper::NotOccupiedDestCity(),
ConstraintHelper::AllowDiplomacyBetweenStatus(
[0, 1],
'선포, 전쟁중인 상대국에게만 가능합니다.'
),
ConstraintHelper::AvailableStrategicCommand($this->getPreReqTurn()),
];
}
public function getCommandDetailTitle(): string
{
$name = $this->getName();
$reqTurn = $this->getPreReqTurn() + 1;
$postReqTurn = $this->getPostReqTurn();
return "{$name}/{$reqTurn}턴(전략$postReqTurn)";
}
public function getCost(): array
{
return [0, 0];
}
public function getPreReqTurn(): int
{
return 1;
}
public function getPostReqTurn(): int
{
$genCount = Util::valueFit($this->nation['gennum'], GameConst::$initialNationGenLimit);
$nextTerm = Util::round(sqrt($genCount * 4) * 10);
$nextTerm = $this->generalObj->onCalcStrategic($this->getName(), 'delay', $nextTerm);
return $nextTerm;
}
public function getBrief(): string
{
$commandName = $this->getName();
$destCityName = CityConst::byID($this->arg['destCityID'])->name;
return "{$destCityName}】에 {$commandName}";
}
public function run(): bool
{
if (!$this->hasFullConditionMet()) {
throw new \RuntimeException('불가능한 커맨드를 강제로 실행 시도');
}
$db = DB::db();
$general = $this->generalObj;
$generalID = $general->getID();
$generalName = $general->getName();
$date = $general->getTurnTime($general::TURNTIME_HM);
$year = $this->env['year'];
$month = $this->env['month'];
$destCity = $this->destCity;
$destCityID = $destCity['city'];
$destCityName = $destCity['name'];
$destNationID = $destCity['nation'];
$destNationName = getNationStaticInfo($destNationID)['name'];
$nationID = $general->getNationID();
$nationName = $this->nation['name'];
$logger = $general->getLogger();
$logger->pushGeneralActionLog("허보 발동! <1>$date</>");
$general->addExperience(5 * ($this->getPreReqTurn() + 1));
$general->addDedication(5 * ($this->getPreReqTurn() + 1));
$josaYi = JosaUtil::pick($generalName, '이');
$broadcastMessage = "<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동하였습니다.";
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND no != %i', $nationID, $generalID);
foreach ($targetGeneralList as $targetGeneralID) {
$targetLogger = new ActionLogger($targetGeneralID, $nationID, $year, $month);
$targetLogger->pushGeneralActionLog($broadcastMessage, ActionLogger::PLAIN);
$targetLogger->flush();
}
$destBroadcastMessage = "상대의 <M>허보</>에 당했다! <1>$date</>";
$destNationCityList = $db->queryFirstColumn('SELECT city FROM city WHERE nation = %i AND supply = 1', $destNationID);
$targetGeneralList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND city=%i', $destNationID, $destCityID);
foreach (General::createGeneralObjListFromDB($targetGeneralList) as $targetGeneralID => $targetGeneral) {
$targetLogger = $targetGeneral->getLogger();
$targetLogger->pushGeneralActionLog($destBroadcastMessage, ActionLogger::PLAIN);
$moveCityID = Util::choiceRandom($destNationCityList);
if ($moveCityID == $destCityID) {
//현재도시면 다시 랜덤 추첨
$moveCityID = Util::choiceRandom($destNationCityList);
}
$targetGeneral->setVar('city', $moveCityID);
$targetGeneral->applyDB($db);
}
$destNationLogger = new ActionLogger(0, $destNationID, $year, $month);
$destNationLogger->pushNationalHistoryLog(
"<D><b>{$nationName}</b></>의 <Y>{$generalName}</>{$josaYi} 아국의 <G><b>{$destCityName}</b></>에 <M>허보</>를 발동",
ActionLogger::PLAIN
);
$destNationLogger->flush();
$db->update('city', [
'def' => $db->sqleval('def * 0.2'),
'wall' => $db->sqleval('wall * 0.2'),
], 'city=%i', $destCityID);
$josaYiNation = JosaUtil::pick($nationName, '이');
$logger->pushGeneralHistoryLog("<G><b>{$destCityName}</b></>에 <M>허보</>를 발동");
$logger->pushNationalHistoryLog("<Y>{$generalName}</>{$josaYi} <G><b>{$destCityName}</b></>에 <M>허보</>를 발동");
$db->update('nation', [
'strategic_cmd_limit' => $this->getPostReqTurn()
], 'nation=%i', $nationID);
$this->setResultTurn(new LastTurn($this->getName(), $this->arg, 0));
$general->applyDB($db);
return true;
}
public function getJSFiles(): array
{
return [
'js/defaultSelectCityByMap.js'
];
}
public function getForm(): string
{
ob_start();
?>
<?= \sammo\getMapHtml() ?><br>
선택된 도시에 허보를 발동합니다.<br>
전쟁중인 상대국 도시만 가능합니다.<br>
목록을 선택하거나 도시를 클릭하세요.<br>
<select class='formInput' name="destCityID" id="destCityID" size='1' style='color:white;background-color:black;'>
<?= \sammo\optionsForCities() ?><br>
</select> <input type=button id="commonSubmit" value="<?= $this->getName() ?>"><br>
<br>
<?php
return ob_get_clean();
}
}
+57 -29
View File
@@ -1,30 +1,58 @@
<?php
namespace sammo\Command;
use \sammo\General;
use \sammo\LastTurn;
abstract class NationCommand extends BaseCommand{
protected $lastTurn;
protected $resultTurn;
public function __construct(General $generalObj, array $env, LastTurn $lastTurn, $arg = null){
$this->lastTurn = $lastTurn;
$this->resultTurn = $lastTurn->duplicate();
parent::__construct($generalObj, $env, $arg);
}
public function getLastTurn():LastTurn{
return $this->lastTurn;
}
public function setResultTurn(LastTurn $lastTurn){
$this->resultTurn = $lastTurn;
}
public function getResultTurn():LastTurn{
return $this->resultTurn;
}
<?php
namespace sammo\Command;
use \sammo\General;
use sammo\KVStorage;
use \sammo\LastTurn;
use \sammo\Util;
abstract class NationCommand extends BaseCommand{
protected $lastTurn;
protected $resultTurn;
public function __construct(General $generalObj, array $env, LastTurn $lastTurn, $arg = null){
$this->lastTurn = $lastTurn;
$this->resultTurn = $lastTurn->duplicate();
parent::__construct($generalObj, $env, $arg);
}
public function getLastTurn():LastTurn{
return $this->lastTurn;
}
public function setResultTurn(LastTurn $lastTurn){
$this->resultTurn = $lastTurn;
}
public function getResultTurn():LastTurn{
return $this->resultTurn;
}
protected function getNextExecuteKey():string{
$turnKey = static::$actionName;
$executeKey = "next_execute_{$turnKey}";
return $executeKey;
}
public function getNextAvailable():?int{
if($this->isArgValid && !$this->getPostReqTurn()){
return null;
}
$db = \sammo\DB::db();
$nationStor = \sammo\KVStorage::getStorage($db, $this->getNationID(), 'nation_env');
return $nationStor->getValue($this->getNextExecuteKey());
}
public function setNextAvailable(?int $yearMonth=null){
if(!$this->getPostReqTurn()){
return;
}
if($yearMonth === null){
$yearMonth = Util::joinYearMonth($this->env['year'], $this->env['month']) + $this->getPostReqTurn();
}
$db = \sammo\DB::db();
$nationStor = \sammo\KVStorage::getStorage($db, $this->getNationID(), 'nation_env');
$nationStor->setValue($this->getNextExecuteKey(), $yearMonth);
}
};
@@ -1,32 +1,32 @@
<?php
namespace sammo\Constraint;
class AvailableStrategicCommand extends Constraint{
const REQ_VALUES = Constraint::REQ_NATION;
public function checkInputValues(bool $throwExeception=true):bool{
if(!parent::checkInputValues($throwExeception) && !$throwExeception){
return false;
}
if(!key_exists('strategic_cmd_limit', $this->nation)){
if(!$throwExeception){return false; }
throw new \InvalidArgumentException("require strategic_cmd_limit in nation");
}
return true;
}
public function test():bool{
$this->checkInputValues();
$this->tested = true;
if($this->nation['strategic_cmd_limit'] == 0){
return true;
}
$this->reason = "전략기한이 남았습니다.";
return false;
}
<?php
namespace sammo\Constraint;
class AvailableStrategicCommand extends Constraint{
const REQ_VALUES = Constraint::REQ_NATION | Constraint::REQ_INT_ARG;
public function checkInputValues(bool $throwExeception=true):bool{
if(!parent::checkInputValues($throwExeception) && !$throwExeception){
return false;
}
if(!key_exists('strategic_cmd_limit', $this->nation)){
if(!$throwExeception){return false; }
throw new \InvalidArgumentException("require strategic_cmd_limit in nation");
}
return true;
}
public function test():bool{
$this->checkInputValues();
$this->tested = true;
if($this->nation['strategic_cmd_limit'] <= $this->arg){
return true;
}
$this->reason = "전략기한이 남았습니다.";
return false;
}
}
+273 -273
View File
@@ -1,274 +1,274 @@
<?php
namespace sammo\Constraint;
class ConstraintHelper{
static function AdhocCallback(callable $callback):array{
return [__FUNCTION__, $callback];
}
static function AllowDiplomacyStatus(int $nationID, array $allowList, string $errMsg):array{
return [__FUNCTION__, [$nationID, $allowList, $errMsg]];
}
static function AllowDiplomacyBetweenStatus(array $allowDipCodeList, string $errMsg):array{
return [__FUNCTION__, [$allowDipCodeList, $errMsg]];
}
static function AllowDiplomacyWithTerm(int $allowDipCode, int $allowMinTerm, string $errMsg):array{
return [__FUNCTION__, [$allowDipCode, $allowMinTerm, $errMsg]];
}
static function AllowJoinAction():array{
return [__FUNCTION__];
}
static function AllowJoinDestNation(int $relYear):array{
return [__FUNCTION__, $relYear];
}
static function AllowRebellion():array{
return [__FUNCTION__];
}
static function AllowWar():array{
return [__FUNCTION__];
}
static function AlwaysFail(string $failMessage):array{
return [__FUNCTION__, $failMessage];
}
static function AvailableRecruitCrewType(int $crewTypeID):array{
return [__FUNCTION__, $crewTypeID];
}
static function AvailableStrategicCommand():array{
return [__FUNCTION__];
}
static function BattleGroundCity():array{
return [__FUNCTION__];
}
static function BeChief():array{
return [__FUNCTION__];
}
static function BeLord():array{
return [__FUNCTION__];
}
static function BeNeutral():array{
return [__FUNCTION__];
}
static function BeOpeningPart(int $relYear):array{
return [__FUNCTION__, $relYear];
}
static function CheckNationNameDuplicate(string $nationName):array{
return [__FUNCTION__, $nationName];
}
static function ConstructableCity():array{
return [__FUNCTION__];
}
static function DifferentNationDestGeneral():array{
return [__FUNCTION__];
}
static function DifferentDestNation():array{
return [__FUNCTION__];
}
static function DisallowDiplomacyBetweenStatus(array $disallowList):array{
return [__FUNCTION__, $disallowList];
}
static function DisallowDiplomacyStatus(int $nationID, array $disallowList):array{
return [__FUNCTION__, [$nationID, $disallowList]];
}
static function ExistsAllowJoinNation(int $relYear, array $excludeNationList):array{
return [__FUNCTION__, [$relYear, $excludeNationList]];
}
static function ExistsDestGeneral():array{
return [__FUNCTION__];
}
static function ExistsDestNation():array{
return [__FUNCTION__];
}
static function FriendlyDestGeneral():array{
return [__FUNCTION__];
}
static function HasRoute():array{
return [__FUNCTION__];
}
static function HasRouteWithEnemy():array{
return [__FUNCTION__];
}
static function MustBeNPC():array{
return [__FUNCTION__];
}
static function MustBeTroopLeader():array{
return [__FUNCTION__];
}
static function NearCity(int $distance):array{
return [__FUNCTION__, $distance];
}
static function NearNation():array{
return [__FUNCTION__];
}
static function NotBeNeutral():array{
return [__FUNCTION__];
}
static function NotCapital(bool $ignoreOfficer=false):array{
return [__FUNCTION__, $ignoreOfficer];
}
static function NotChief():array{
return [__FUNCTION__];
}
static function NotLord():array{
return [__FUNCTION__];
}
static function NotNeutralDestCity():array{
return [__FUNCTION__];
}
static function NotOccupiedDestCity():array{
return [__FUNCTION__];
}
static function NotOpeningPart(int $relYear):array{
return [__FUNCTION__, $relYear];
}
static function NotSameDestCity():array{
return [__FUNCTION__];
}
static function NotWanderingNation():array{
return [__FUNCTION__];
}
static function OccupiedCity(bool $allowNeutral=false):array{
return [__FUNCTION__, $allowNeutral];
}
static function OccupiedDestCity():array{
return [__FUNCTION__];
}
static function RemainCityCapacity($key, string $actionName):array{
return [__FUNCTION__, [$key, $actionName]];
}
static function RemainCityTrust(string $actionName):array{
return [__FUNCTION__, $actionName];
}
static function ReqCityCapacity($key, string $keyNick, $reqVal):array{
return [__FUNCTION__, [$key, $keyNick, $reqVal]];
}
static function ReqCityTrust(float $minTrust):array{
return [__FUNCTION__, $minTrust];
}
static function ReqCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqDestCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqCityTrader(int $npcType):array{
return [__FUNCTION__, $npcType];
}
static function ReqDestNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqEnvValue($key, string $comp, $reqVal, string $failMessage):array{
return [__FUNCTION__, [$key, $comp, $reqVal, $failMessage]];
}
static function ReqGeneralAtmosMargin(int $maxAtmos):array{
return [__FUNCTION__, $maxAtmos];
}
static function ReqGeneralCrew():array{
return [__FUNCTION__];
}
static function ReqGeneralCrewMargin(int $crewTypeID):array{
return [__FUNCTION__, $crewTypeID];
}
static function ReqGeneralGold(int $reqGold):array{
return [__FUNCTION__, $reqGold];
}
static function ReqGeneralRice(int $reqRice):array{
return [__FUNCTION__, $reqRice];
}
static function ReqGeneralTrainMargin(int $maxTrain):array{
return [__FUNCTION__, $maxTrain];
}
static function ReqGeneralValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqNationGold(int $reqGold):array{
return [__FUNCTION__, $reqGold];
}
static function ReqNationRice(int $reqRice):array{
return [__FUNCTION__, $reqRice];
}
static function ReqNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqNationAuxValue($key, $defaultValue, string $comp, $reqVal, string $errMsg):array{
return [__FUNCTION__, [$key, $defaultValue, $comp, $reqVal, $errMsg]];
}
static function ReqTroopMembers():array{
return [__FUNCTION__];
}
static function SuppliedCity():array{
return [__FUNCTION__];
}
static function SuppliedDestCity():array{
return [__FUNCTION__];
}
static function WanderingNation():array{
return [__FUNCTION__];
}
<?php
namespace sammo\Constraint;
class ConstraintHelper{
static function AdhocCallback(callable $callback):array{
return [__FUNCTION__, $callback];
}
static function AllowDiplomacyStatus(int $nationID, array $allowList, string $errMsg):array{
return [__FUNCTION__, [$nationID, $allowList, $errMsg]];
}
static function AllowDiplomacyBetweenStatus(array $allowDipCodeList, string $errMsg):array{
return [__FUNCTION__, [$allowDipCodeList, $errMsg]];
}
static function AllowDiplomacyWithTerm(int $allowDipCode, int $allowMinTerm, string $errMsg):array{
return [__FUNCTION__, [$allowDipCode, $allowMinTerm, $errMsg]];
}
static function AllowJoinAction():array{
return [__FUNCTION__];
}
static function AllowJoinDestNation(int $relYear):array{
return [__FUNCTION__, $relYear];
}
static function AllowRebellion():array{
return [__FUNCTION__];
}
static function AllowWar():array{
return [__FUNCTION__];
}
static function AlwaysFail(string $failMessage):array{
return [__FUNCTION__, $failMessage];
}
static function AvailableRecruitCrewType(int $crewTypeID):array{
return [__FUNCTION__, $crewTypeID];
}
static function AvailableStrategicCommand(int $allowTurnCnt=0):array{
return [__FUNCTION__, $allowTurnCnt];
}
static function BattleGroundCity():array{
return [__FUNCTION__];
}
static function BeChief():array{
return [__FUNCTION__];
}
static function BeLord():array{
return [__FUNCTION__];
}
static function BeNeutral():array{
return [__FUNCTION__];
}
static function BeOpeningPart(int $relYear):array{
return [__FUNCTION__, $relYear];
}
static function CheckNationNameDuplicate(string $nationName):array{
return [__FUNCTION__, $nationName];
}
static function ConstructableCity():array{
return [__FUNCTION__];
}
static function DifferentNationDestGeneral():array{
return [__FUNCTION__];
}
static function DifferentDestNation():array{
return [__FUNCTION__];
}
static function DisallowDiplomacyBetweenStatus(array $disallowList):array{
return [__FUNCTION__, $disallowList];
}
static function DisallowDiplomacyStatus(int $nationID, array $disallowList):array{
return [__FUNCTION__, [$nationID, $disallowList]];
}
static function ExistsAllowJoinNation(int $relYear, array $excludeNationList):array{
return [__FUNCTION__, [$relYear, $excludeNationList]];
}
static function ExistsDestGeneral():array{
return [__FUNCTION__];
}
static function ExistsDestNation():array{
return [__FUNCTION__];
}
static function FriendlyDestGeneral():array{
return [__FUNCTION__];
}
static function HasRoute():array{
return [__FUNCTION__];
}
static function HasRouteWithEnemy():array{
return [__FUNCTION__];
}
static function MustBeNPC():array{
return [__FUNCTION__];
}
static function MustBeTroopLeader():array{
return [__FUNCTION__];
}
static function NearCity(int $distance):array{
return [__FUNCTION__, $distance];
}
static function NearNation():array{
return [__FUNCTION__];
}
static function NotBeNeutral():array{
return [__FUNCTION__];
}
static function NotCapital(bool $ignoreOfficer=false):array{
return [__FUNCTION__, $ignoreOfficer];
}
static function NotChief():array{
return [__FUNCTION__];
}
static function NotLord():array{
return [__FUNCTION__];
}
static function NotNeutralDestCity():array{
return [__FUNCTION__];
}
static function NotOccupiedDestCity():array{
return [__FUNCTION__];
}
static function NotOpeningPart(int $relYear):array{
return [__FUNCTION__, $relYear];
}
static function NotSameDestCity():array{
return [__FUNCTION__];
}
static function NotWanderingNation():array{
return [__FUNCTION__];
}
static function OccupiedCity(bool $allowNeutral=false):array{
return [__FUNCTION__, $allowNeutral];
}
static function OccupiedDestCity():array{
return [__FUNCTION__];
}
static function RemainCityCapacity($key, string $actionName):array{
return [__FUNCTION__, [$key, $actionName]];
}
static function RemainCityTrust(string $actionName):array{
return [__FUNCTION__, $actionName];
}
static function ReqCityCapacity($key, string $keyNick, $reqVal):array{
return [__FUNCTION__, [$key, $keyNick, $reqVal]];
}
static function ReqCityTrust(float $minTrust):array{
return [__FUNCTION__, $minTrust];
}
static function ReqCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqDestCityValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqCityTrader(int $npcType):array{
return [__FUNCTION__, $npcType];
}
static function ReqDestNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqEnvValue($key, string $comp, $reqVal, string $failMessage):array{
return [__FUNCTION__, [$key, $comp, $reqVal, $failMessage]];
}
static function ReqGeneralAtmosMargin(int $maxAtmos):array{
return [__FUNCTION__, $maxAtmos];
}
static function ReqGeneralCrew():array{
return [__FUNCTION__];
}
static function ReqGeneralCrewMargin(int $crewTypeID):array{
return [__FUNCTION__, $crewTypeID];
}
static function ReqGeneralGold(int $reqGold):array{
return [__FUNCTION__, $reqGold];
}
static function ReqGeneralRice(int $reqRice):array{
return [__FUNCTION__, $reqRice];
}
static function ReqGeneralTrainMargin(int $maxTrain):array{
return [__FUNCTION__, $maxTrain];
}
static function ReqGeneralValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqNationGold(int $reqGold):array{
return [__FUNCTION__, $reqGold];
}
static function ReqNationRice(int $reqRice):array{
return [__FUNCTION__, $reqRice];
}
static function ReqNationValue($key, string $keyNick, string $comp, $reqVal, ?string $errMsg=null):array{
return [__FUNCTION__, [$key, $keyNick, $comp, $reqVal, $errMsg]];
}
static function ReqNationAuxValue($key, $defaultValue, string $comp, $reqVal, string $errMsg):array{
return [__FUNCTION__, [$key, $defaultValue, $comp, $reqVal, $errMsg]];
}
static function ReqTroopMembers():array{
return [__FUNCTION__];
}
static function SuppliedCity():array{
return [__FUNCTION__];
}
static function SuppliedDestCity():array{
return [__FUNCTION__];
}
static function WanderingNation():array{
return [__FUNCTION__];
}
}
+280 -277
View File
@@ -1,278 +1,281 @@
<?php
namespace sammo;
class DiplomaticMessage extends Message{
const ACCEPTED = 1;
const DECLINED = -1;
const INVALID = 0;
const TYPE_NO_AGGRESSION = 'noAggression'; //불가침
const TYPE_CANCEL_NA = 'cancelNA'; //불가침 파기
const TYPE_STOP_WAR = 'stopWar'; //종전
protected $diplomaticType = '';
protected $diplomacyName = '';
protected $diplomacyDetail = '';
protected $validDiplomacy = true;
public function __construct(
string $msgType,
MessageTarget $src,
MessageTarget $dest,
string $msg,
\DateTime $date,
\DateTime $validUntil,
array $msgOption
)
{
if ($msgType !== self::MSGTYPE_DIPLOMACY){
throw new \InvalidArgumentException('DiplomaticMessage msgType');
}
$this->diplomaticType = Util::array_get($msgOption['action']);
switch($this->diplomaticType){
case self::TYPE_NO_AGGRESSION: $this->diplomacyName = '불가침'; break;
case self::TYPE_CANCEL_NA: $this->diplomacyName = '불가침 파기'; break;
case self::TYPE_STOP_WAR: $this->diplomacyName = '종전'; break;
default: throw new \RuntimeException('diplomaticType이 올바르지 않음');
}
parent::__construct(...func_get_args());
if(Util::array_get($msgOption['used'])){
$this->validDiplomacy = false;
}
if($this->validUntil < (new \DateTime())){
$this->validDiplomacy = false;
}
}
protected function checkDiplomaticMessageValidation(array $general){
if(!$this->validDiplomacy){
return [self::INVALID, '유효하지 않은 외교서신입니다.'];
}
if($this->mailbox !== $this->dest->nationID + static::MAILBOX_NATIONAL){
return [self::INVALID, '송신자가 외교서신을 처리할 수 없습니다.'];
}
$permission = checkSecretPermission($general, false);
if(!$general || $permission < 4){
return [self::INVALID, '해당 국가의 외교권자가 아닙니다.'];
}
return [self::ACCEPTED, ''];
}
protected function noAggression(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_불가침수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
'year'=>$this->msgOption['year'],
'month'=>$this->msgOption['month']
]);
$this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()];
}
$commandObj->run();
return [self::ACCEPTED, ''];
}
protected function cancelNA(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_불가침파기수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
]);
$this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()];
}
$commandObj->run();
return [self::ACCEPTED, ''];
}
protected function stopWar(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_종전수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
]);
$this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()];
}
$commandObj->run();
return [self::ACCEPTED, ''];
}
/**
* @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환
*/
public function agreeMessage(int $receiverID, string &$reason):int{
//NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등)
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$general = $db->queryFirstRow(
'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i',
$receiverID,
$this->dest->nationID
);
if($general){
$this->dest->generalID = $receiverID;
$this->dest->generalName = $general['name'];
}
list($result, $reason) = $this->checkDiplomaticMessageValidation($general);
if($result !== self::ACCEPTED){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 실패", ActionLogger::PLAIN);
if($result === self::DECLINED){
$this->_declineMessage();
}
return $result;
}
switch($this->diplomaticType){
case self::TYPE_NO_AGGRESSION:
list($result, $reason) = $this->noAggression();
break;
case self::TYPE_CANCEL_NA:
list($result, $reason) = $this->cancelNA();
break;
case self::TYPE_STOP_WAR:
list($result, $reason) = $this->stopWar();
break;
default:
throw new \RuntimeException('diplomaticType이 올바르지 않음');
}
if($result !== self::ACCEPTED){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog($reason, ActionLogger::PLAIN);
if($result === self::DECLINED){
$this->_declineMessage();
}
return $result;
}
$this->dest->generalID = $receiverID;
$this->dest->generalName = $general['name'];
$this->msgOption['used'] = true;
$this->validDiplomacy = false;
$josaYi = JosaUtil::pick($this->src->nationName, '이');
$newMsg = new Message(
self::MSGTYPE_NATIONAL,
$this->dest,
$this->src,
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id,
'silence'=>true,
'deletable' => false
]
);
$this->invalidate();
$newMsg->send();
$newMsg = new Message(
self::MSGTYPE_DIPLOMACY,
$this->dest,
$this->src,
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id,
'silence'=>true,
'deletable' => false
]
);
$newMsg->send();
return self::ACCEPTED;
}
protected function _declineMessage(){
$this->msgOption['used'] = true;
$this->invalidate();
$this->validDiplomacy = false;
return self::DECLINED;
}
public function declineMessage(int $receiverID, string &$reason):int{
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$general = $db->queryFirstRow(
'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i',
$receiverID,
$this->dest->nationID
);
list($result, $reason) = $this->checkDiplomaticMessageValidation($general);
if($result === self::INVALID){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 거절 불가.", ActionLogger::PLAIN);
return $result;
}
$josaYi = JosaUtil::pick($this->dest->nationName, '이');
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("<D>{$this->src->nationName}</>의 {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN);
(new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->nationName}</>{$josaYi} {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN);
$this->_declineMessage();
return self::DECLINED;
}
<?php
namespace sammo;
class DiplomaticMessage extends Message{
const ACCEPTED = 1;
const DECLINED = -1;
const INVALID = 0;
const TYPE_NO_AGGRESSION = 'noAggression'; //불가침
const TYPE_CANCEL_NA = 'cancelNA'; //불가침 파기
const TYPE_STOP_WAR = 'stopWar'; //종전
protected $diplomaticType = '';
protected $diplomacyName = '';
protected $diplomacyDetail = '';
protected $validDiplomacy = true;
public function __construct(
string $msgType,
MessageTarget $src,
MessageTarget $dest,
string $msg,
\DateTime $date,
\DateTime $validUntil,
array $msgOption
)
{
if ($msgType !== self::MSGTYPE_DIPLOMACY){
throw new \InvalidArgumentException('DiplomaticMessage msgType');
}
$this->diplomaticType = Util::array_get($msgOption['action']);
switch($this->diplomaticType){
case self::TYPE_NO_AGGRESSION: $this->diplomacyName = '불가침'; break;
case self::TYPE_CANCEL_NA: $this->diplomacyName = '불가침 파기'; break;
case self::TYPE_STOP_WAR: $this->diplomacyName = '종전'; break;
default: throw new \RuntimeException('diplomaticType이 올바르지 않음');
}
parent::__construct(...func_get_args());
if(Util::array_get($msgOption['used'])){
$this->validDiplomacy = false;
}
if($this->validUntil < (new \DateTime())){
$this->validDiplomacy = false;
}
}
protected function checkDiplomaticMessageValidation(array $general){
if(!$this->validDiplomacy){
return [self::INVALID, '유효하지 않은 외교서신입니다.'];
}
if($this->mailbox !== $this->dest->nationID + static::MAILBOX_NATIONAL){
return [self::INVALID, '송신자가 외교서신을 처리할 수 없습니다.'];
}
$permission = checkSecretPermission($general, false);
if(!$general || $permission < 4){
return [self::INVALID, '해당 국가의 외교권자가 아닙니다.'];
}
return [self::ACCEPTED, ''];
}
protected function noAggression(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_불가침수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
'year'=>$this->msgOption['year'],
'month'=>$this->msgOption['month']
]);
$this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()];
}
$commandObj->run();
$commandObj->setNextAvailable();
return [self::ACCEPTED, ''];
}
protected function cancelNA(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_불가침파기수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
]);
$this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()];
}
$commandObj->run();
$commandObj->setNextAvailable();
return [self::ACCEPTED, ''];
}
protected function stopWar(){
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$destGeneralObj = General::createGeneralObjFromDB($this->dest->generalID, ['picture', 'imgsvr', 'aux'], 1);
$commandObj = buildNationCommandClass('che_종전수락', $destGeneralObj, $gameStor->getAll(true), new LastTurn(), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
]);
$this->diplomacyDetail = $commandObj->getBrief();
if(!$commandObj->hasFullConditionMet()){
return [self::DECLINED, $commandObj->getFailString()];
}
$commandObj->run();
$commandObj->setNextAvailable();
return [self::ACCEPTED, ''];
}
/**
* @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환
*/
public function agreeMessage(int $receiverID, string &$reason):int{
//NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등)
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$general = $db->queryFirstRow(
'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i',
$receiverID,
$this->dest->nationID
);
if($general){
$this->dest->generalID = $receiverID;
$this->dest->generalName = $general['name'];
}
list($result, $reason) = $this->checkDiplomaticMessageValidation($general);
if($result !== self::ACCEPTED){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 실패", ActionLogger::PLAIN);
if($result === self::DECLINED){
$this->_declineMessage();
}
return $result;
}
switch($this->diplomaticType){
case self::TYPE_NO_AGGRESSION:
list($result, $reason) = $this->noAggression();
break;
case self::TYPE_CANCEL_NA:
list($result, $reason) = $this->cancelNA();
break;
case self::TYPE_STOP_WAR:
list($result, $reason) = $this->stopWar();
break;
default:
throw new \RuntimeException('diplomaticType이 올바르지 않음');
}
if($result !== self::ACCEPTED){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog($reason, ActionLogger::PLAIN);
if($result === self::DECLINED){
$this->_declineMessage();
}
return $result;
}
$this->dest->generalID = $receiverID;
$this->dest->generalName = $general['name'];
$this->msgOption['used'] = true;
$this->validDiplomacy = false;
$josaYi = JosaUtil::pick($this->src->nationName, '이');
$newMsg = new Message(
self::MSGTYPE_NATIONAL,
$this->dest,
$this->src,
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id,
'silence'=>true,
'deletable' => false
]
);
$this->invalidate();
$newMsg->send();
$newMsg = new Message(
self::MSGTYPE_DIPLOMACY,
$this->dest,
$this->src,
"【외교】{$year}{$month}월: {$this->src->nationName}{$josaYi} {$this->dest->nationName}에게 제안한 {$this->diplomacyDetail}",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id,
'silence'=>true,
'deletable' => false
]
);
$newMsg->send();
return self::ACCEPTED;
}
protected function _declineMessage(){
$this->msgOption['used'] = true;
$this->invalidate();
$this->validDiplomacy = false;
return self::DECLINED;
}
public function declineMessage(int $receiverID, string &$reason):int{
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
$general = $db->queryFirstRow(
'SELECT `name`, nation, `officer_level`, `permission`, `penalty`,belong FROM general WHERE `no`=%i AND nation=%i',
$receiverID,
$this->dest->nationID
);
list($result, $reason) = $this->checkDiplomaticMessageValidation($general);
if($result === self::INVALID){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} {$this->diplomacyName} 거절 불가.", ActionLogger::PLAIN);
return $result;
}
$josaYi = JosaUtil::pick($this->dest->nationName, '이');
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("<D>{$this->src->nationName}</>의 {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN);
(new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->nationName}</>{$josaYi} {$this->diplomacyName} 제안을 거절했습니다.", ActionLogger::PLAIN);
$this->_declineMessage();
return self::DECLINED;
}
}
+355 -355
View File
@@ -1,355 +1,355 @@
<?php
namespace sammo;
class GameConstBase
{
/** @var string 게임명 */
public static $title = "삼국지 모의전투 PHP HiDCHe";
/** @var string 코드 아래에 붙는 설명 코드 */
public static $banner = "KOEI의 이미지를 사용, 응용하였습니다 / 제작 : HideD(hided62@gmail.com) / <a href='https://sam.hided.net/wiki/hidche/credit' target='_blank' style='color:white;text-decoration: underline;'>Credit</a>";
/** @var string 사용중인 지도명 */
public static $mapName = 'che';
/** @var string 사용중인 유닛셋 */
public static $unitSet = 'che';
/** @var int 내정시 최하 민심 설정*/
public static $develrate = 50;
/** @var int 능력치 상승 경험치*/
public static $upgradeLimit = 30;
/** @var int 숙련도 제한치*/
public static $dexLimit = 1000000;
/** @var int 초기 징병 사기치*/
public static $defaultAtmosLow = 40;
/** @var int 초기 징병 훈련치*/
public static $defaultTrainLow = 40;
/** @var int 초기 모병 사기치*/
public static $defaultAtmosHigh = 70;
/** @var int 초기 모병 훈련치*/
public static $defaultTrainHigh = 70;
/** @var int 사기진작으로 올릴 수 있는 최대 사기치*/
public static $maxAtmosByCommand = 100;
/** @var int 훈련으로 올릴 수 있는 최대 사기치*/
public static $maxTrainByCommand = 100;
/** @var int 전투로 올릴 수 있는 최대 사기치*/
public static $maxAtmosByWar = 150;
/** @var int 전투로 올릴 수 훈련치*/
public static $maxTrainByWar = 110;
/** @var int 풀징병시 훈련 1회 상승량*/
public static $trainDelta = 30;
/** @var int 풀징병시 훈련 1회 상승량*/
public static $atmosDelta = 30;
/** @var float 훈련시 사기 감소율*/
public static $atmosSideEffectByTraining = 1;
/** @var float 사기시 훈련 감소율*/
public static $trainSideEffectByAtmosTurn = 1;
/** @var float 계략 기본 성공률*/
public static $sabotageDefaultProb = 0.35;
/** @var int 계략시 확률 가중치(수치가 클수록 변화가 적음 : (지력차/$firing + $basefiring)*/
public static $sabotageProbCoefByStat = 300;
/** @var int 계략시 최소 수치 감소량*/
public static $sabotageDamageMin = 100;
/** @var int 계략시 최대 수치 감소량*/
public static $sabotageDamageMax = 500;
/** @var string 기본 배경색깔 푸른색*/
public static $basecolor = "#000044";
/** @var string 기본 배경색깔 초록색*/
public static $basecolor2 = "#225500";
/** @var string 기본 배경색깔 붉은색*/
public static $basecolor3 = "#660000";
/** @var string 기본 배경색깔 검붉은색*/
public static $basecolor4 = "#330000";
/** @var int 페이즈당 표준 감소 병사 수*/
public static $armperphase = 500;
/** @var int 기본 국고*/
public static $basegold = 0;
/** @var int 기본 병량*/
public static $baserice = 2000;
/** @var int 최저 국고(긴급시) */
public static $minNationalGold = 0;
/** @var int 최저 병량(긴급시) */
public static $minNationalRice = 0;
/** @var float 군량 매매시 세율*/
public static $exchangeFee = 0.01;
/** @var float 성인 연령 */
public static $adultAge = 14;
/** @var float 명전 등록 가능 연령 */
public static $minPushHallAge = 40;
/** @var int 최대 계급 */
public static $maxDedLevel = 30;
/** @var int 최대 기술 레벨 */
public static $maxTechLevel = 12;
/** @var int 최대 하야 패널티 수 */
public static $maxBetrayCnt = 9;
/** @var int 최소 인구 증가량 */
public static $basePopIncreaseAmount = 5000;
/** @var int 증축시 인구 증가량 */
public static $expandCityPopIncreaseAmount = 100000;
/** @var int 증축시 내정 증가량 */
public static $expandCityDevelIncreaseAmount = 2000;
/** @var int 증축시 성벽 증가량 */
public static $expandCityWallIncreaseAmount = 2000;
/** @var int 증축시 최소 비용 */
public static $expandCityDefaultCost = 60000;
/** @var int 증축시 비용 계수 */
public static $expandCityCostCoef = 500;
/** @var int 징병 허용 최소 인구 */
public static $minAvailableRecruitPop = 30000;
/** @var int 초기 제한시 장수 제한 */
public static $initialNationGenLimitForRandInit = 3;
/** @var int 초기 제한시 장수 제한 */
public static $initialNationGenLimit = 10;
/** @var int 초기 최대 장수수 */
public static $defaultMaxGeneral = 500;
/** @var int 초기 최대 국가 수 */
public static $defaultMaxNation = 55;
/** @var int 초기 최대 천재 수 */
public static $defaultMaxGenius = 5;
/** @var int 초기 시작 년도. 실제 값은 시나리오에서 정해지므로 딱히 의미는 없음. */
public static $defaultStartYear = 180;
/** @var float 멸망한 NPC 장수의 임관 확률 */
public static $joinRuinedNPCProp = 0.1;
/** @var int 시작시 금 */
public static $defaultGold = 1000;
/** @var int 시작시 쌀 */
public static $defaultRice = 1000;
/** @var int 원조 계수 */
public static $coefAidAmount = 10000;
/** @var int 최대 개별 자원 금액 */
public static $maxResourceActionAmount = 10000;
/** @var int[] 포상/몰수 가이드 금액 */
public static $resourceActionAmountGuide = [
100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
1200, 1500, 2000, 2500, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000
];
public static $generalMinimumGold = 0;
public static $generalMinimumRice = 500;
/** @var int 최대 턴 */
public static $maxTurn = 30;
public static $maxChiefTurn = 12;
public static $statGradeLevel = 5;
/** @var int 초반 제한 기간 */
public static $openingPartYear = 3;
/** @var int 거병,임관 제한 기간 */
public static $joinActionLimit = 12;
/** @var array 선택 가능한 국가 성향 */
public static $availableNationType = [
'che_도적', 'che_명가', 'che_음양가', 'che_종횡가', 'che_불가', 'che_오두미도', 'che_태평도', 'che_도가',
'che_묵가', 'che_덕가', 'che_병가', 'che_유가', 'che_법가'
];
/** @var array 기본 국가 성향 */
public static $neutralNationType = 'che_중립';
/** @var string 기본 내정 특기 */
public static $defaultSpecialDomestic = 'None';
/** @var array 선택 가능한 장수 내정 특기 */
public static $availableSpecialDomestic = [
'che_경작', 'che_상재', 'che_발명', 'che_축성', 'che_수비', 'che_통찰', 'che_인덕', 'che_귀모',
];
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 내정 특기 */
public static $optionalSpecialDomestic = [
'None',
];
/** @var string 기본 전투 특기 */
public static $defaultSpecialWar = 'None';
/** @var array 선택 가능한 장수 전투 특기 */
public static $availableSpecialWar = [
'che_귀병', 'che_신산', 'che_환술', 'che_집중', 'che_신중', 'che_반계',
'che_보병', 'che_궁병', 'che_기병', 'che_공성',
'che_돌격', 'che_무쌍', 'che_견고', 'che_위압',
'che_저격', 'che_필살', 'che_징병', 'che_의술', 'che_격노', 'che_척사',
];
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 전투 특기 */
public static $optionalSpecialWar = [
'None',
];
/** @var string 기본 성향(공용) */
public static $neutralPersonality = 'None';
/** @var array 선택 가능한 성향 */
public static $availablePersonality = [
'che_안전', 'che_유지', 'che_재간', 'che_출세', 'che_할거', 'che_정복',
'che_패권', 'che_의협', 'che_대의', 'che_왕좌'
];
/** @var array 존재하는 모든 성향 */
public static $optionalPersonality = [
'che_은둔', 'None'
];
public static $allItems = [
'horse' => [
'che_명마_01_노기'=>0, 'che_명마_02_조랑'=>0, 'che_명마_03_노새'=>0,
'che_명마_04_나귀'=>0, 'che_명마_05_갈색마'=>0, 'che_명마_06_흑색마'=>0,
'che_명마_07_백마'=>2, 'che_명마_07_기주마'=>2,
'che_명마_08_양주마'=>2, 'che_명마_09_과하마'=>2,
'che_명마_10_대완마'=>2, 'che_명마_11_서량마'=>2,
'che_명마_12_사륜거'=>2, 'che_명마_13_절영'=>1, 'che_명마_13_적로'=>1,
'che_명마_14_적란마'=>1, 'che_명마_14_조황비전'=>1, 'che_명마_15_한혈마'=>1, 'che_명마_15_적토마'=>1,
],
'weapon' => [
'che_무기_01_단도'=>0, 'che_무기_02_단궁'=>0, 'che_무기_03_단극'=>0,
'che_무기_04_목검'=>0, 'che_무기_05_죽창'=>0, 'che_무기_06_소부'=>0,
'che_무기_07_동추'=>1, 'che_무기_07_철편'=>1, 'che_무기_07_철쇄'=>1, 'che_무기_07_맥궁'=>1,
'che_무기_08_유성추'=>1, 'che_무기_08_철질여골'=>1, 'che_무기_09_쌍철극'=>1, 'che_무기_09_동호비궁'=>1, 'che_무기_10_삼첨도'=>1, 'che_무기_10_대부'=>1, 'che_무기_11_고정도'=>1, 'che_무기_11_이광궁'=>1, 'che_무기_12_철척사모'=>1, 'che_무기_12_칠성검'=>1, 'che_무기_13_사모'=>1, 'che_무기_13_양유기궁'=>1,
'che_무기_14_언월도'=>1, 'che_무기_14_방천화극'=>1, 'che_무기_15_청홍검'=>1, 'che_무기_15_의천검'=>1
],
'book' => [
'che_서적_01_효경전'=>0, 'che_서적_02_회남자'=>0, 'che_서적_03_변도론'=>0,
'che_서적_04_건상역주'=>0, 'che_서적_05_여씨춘추'=>0, 'che_서적_06_사민월령'=>0,
'che_서적_07_위료자'=>1, 'che_서적_07_사마법'=>1, 'che_서적_07_한서'=>1, 'che_서적_07_논어'=>1,
'che_서적_08_전론'=>1, 'che_서적_08_사기'=>1, 'che_서적_09_장자'=>1, 'che_서적_09_역경'=>1,
'che_서적_10_시경'=>1, 'che_서적_10_구국론'=>1, 'che_서적_11_상군서'=>1, 'che_서적_11_춘추전'=>1,
'che_서적_12_산해경'=>1, 'che_서적_12_맹덕신서'=>1, 'che_서적_13_관자'=>1, 'che_서적_13_병법24편'=>1,
'che_서적_14_한비자'=>1, 'che_서적_14_오자병법'=>1, 'che_서적_15_노자'=>1, 'che_서적_15_손자병법'=>1,
],
'item' => [
'che_치료_환약'=>0, 'che_저격_수극'=>0, 'che_사기_탁주'=>0,
'che_훈련_청주'=>0, 'che_계략_이추'=>0, 'che_계략_향낭'=>0,
'che_치료_오석산'=>1, 'che_치료_무후행군'=>1, 'che_치료_도소연명'=>1,
'che_치료_칠엽청점'=>1, 'che_치료_정력견혈'=>1,
'che_훈련_과실주'=>1, 'che_훈련_이강주'=>1,
'che_사기_의적주'=>1, 'che_사기_두강주'=>1, 'che_사기_보령압주'=>1,
'che_훈련_철벽서'=>1, 'che_훈련_단결도'=>1, 'che_사기_춘화첩'=>1, 'che_사기_초선화'=>1,
'che_계략_육도'=>1, 'che_계략_삼략'=>1,
'che_의술_청낭서'=>1, 'che_의술_태평청령'=>1,
'che_회피_태평요술'=>1, 'che_회피_둔갑천서'=>1,
]
];
/** @var array 선택 가능한 커맨드 */
public static $availableGeneralCommand = [
''=>[
'휴식',
'che_요양'
],
'내정'=>[
'che_농지개간',
'che_상업투자',
'che_기술연구',
'che_수비강화',
'che_성벽보수',
'che_치안강화',
'che_정착장려',
'che_주민선정',
'che_물자조달',
],
'군사'=>[
'che_소집해제',
'che_첩보',
'che_징병',
'che_모병',
'che_훈련',
'che_사기진작',
'che_출병',
],
'인사'=>[
'che_이동',
'che_강행',
'che_인재탐색',
'che_등용',
'che_집합',
'che_귀환',
'che_임관',
'che_랜덤임관',
'che_장수대상임관',
],
'계략'=>[
'che_화계',
'che_파괴',
'che_탈취',
'che_선동',
],
'개인'=>[
'che_내정특기초기화',
'che_전투특기초기화',
'che_단련',
'che_숙련전환',
'che_견문',
'che_장비매매',
'che_군량매매',
'che_증여',
'che_헌납',
'che_하야',
'che_거병',
'che_건국',
'che_선양',
'che_방랑',
'che_해산',
'che_모반시도',
]
];
/** @var array 선택 가능한 커맨드 */
public static $availableChiefCommand = [
'휴식'=>[
'휴식',
],
'인사'=>[
'che_발령',
'che_포상',
'che_몰수',
],
'외교'=>[
'che_물자원조',
'che_불가침제의',
'che_선전포고',
'che_종전제의',
'che_불가침파기제의',
],
'특수'=>[
'che_초토화',
'che_천도',
'che_증축',
'che_감축',
],
'전략'=>[
'che_필사즉생',
'che_백성동원',
'che_수몰',
'che_허보',
'che_피장파장',
'che_의병모집',
'che_이호경식',
'che_급습',
],
'기타'=>[
'che_국기변경',
'che_국호변경',
]
];
public static $retirementYear = 80;
public static $randGenFirstName = [
'가', '간', '감', '강', '고', '공', '공손', '곽', '관', '괴', '교', '금', '노', '뇌', '능', '도', '동', '두',
'등', '마', '맹', '문', '미', '반', '방', '부', '비', '사', '사마', '서', '설', '성', '소', '손', '송', '순',
'신', '심', '악', '안', '양', '엄', '여', '염', '오', '왕', '요', '우', '원', '위', '유', '육', '윤', '이',
'장', '저', '전', '정', '제갈', '조', '종', '주', '진', '채', '태사', '하', '하후', '학', '한', '향', '허',
'호', '화', '황', '공손', '손', '왕', '유', '장', '조'
];
public static $randGenMiddleName = [''];
public static $randGenLastName = [
'가', '간', '강', '거', '건', '검', '견', '경', '공', '광', '권', '규', '녕', '단', '대', '도', '등', '람',
'량', '례', '로', '료', '모', '민', '박', '범', '보', '비', '사', '상', '색', '서', '소', '속', '송', '수',
'순', '습', '승', '양', '연', '영', '온', '옹', '완', '우', '웅', '월', '위', '유', '윤', '융', '이', '익',
'임', '정', '제', '조', '주', '준', '지', '찬', '책', '충', '탁', '택', '통', '패', '평', '포', '합', '해',
'혁', '현', '화', '환', '회', '횡', '후', '훈', '휴', '흠', '흥'
];
}
<?php
namespace sammo;
class GameConstBase
{
/** @var string 게임명 */
public static $title = "삼국지 모의전투 PHP HiDCHe";
/** @var string 코드 아래에 붙는 설명 코드 */
public static $banner = "KOEI의 이미지를 사용, 응용하였습니다 / 제작 : HideD(hided62@gmail.com) / <a href='https://sam.hided.net/wiki/hidche/credit' target='_blank' style='color:white;text-decoration: underline;'>Credit</a>";
/** @var string 사용중인 지도명 */
public static $mapName = 'che';
/** @var string 사용중인 유닛셋 */
public static $unitSet = 'che';
/** @var int 내정시 최하 민심 설정*/
public static $develrate = 50;
/** @var int 능력치 상승 경험치*/
public static $upgradeLimit = 30;
/** @var int 숙련도 제한치*/
public static $dexLimit = 1000000;
/** @var int 초기 징병 사기치*/
public static $defaultAtmosLow = 40;
/** @var int 초기 징병 훈련치*/
public static $defaultTrainLow = 40;
/** @var int 초기 모병 사기치*/
public static $defaultAtmosHigh = 70;
/** @var int 초기 모병 훈련치*/
public static $defaultTrainHigh = 70;
/** @var int 사기진작으로 올릴 수 있는 최대 사기치*/
public static $maxAtmosByCommand = 100;
/** @var int 훈련으로 올릴 수 있는 최대 사기치*/
public static $maxTrainByCommand = 100;
/** @var int 전투로 올릴 수 있는 최대 사기치*/
public static $maxAtmosByWar = 150;
/** @var int 전투로 올릴 수 훈련치*/
public static $maxTrainByWar = 110;
/** @var int 풀징병시 훈련 1회 상승량*/
public static $trainDelta = 30;
/** @var int 풀징병시 훈련 1회 상승량*/
public static $atmosDelta = 30;
/** @var float 훈련시 사기 감소율*/
public static $atmosSideEffectByTraining = 1;
/** @var float 사기시 훈련 감소율*/
public static $trainSideEffectByAtmosTurn = 1;
/** @var float 계략 기본 성공률*/
public static $sabotageDefaultProb = 0.35;
/** @var int 계략시 확률 가중치(수치가 클수록 변화가 적음 : (지력차/$firing + $basefiring)*/
public static $sabotageProbCoefByStat = 300;
/** @var int 계략시 최소 수치 감소량*/
public static $sabotageDamageMin = 100;
/** @var int 계략시 최대 수치 감소량*/
public static $sabotageDamageMax = 500;
/** @var string 기본 배경색깔 푸른색*/
public static $basecolor = "#000044";
/** @var string 기본 배경색깔 초록색*/
public static $basecolor2 = "#225500";
/** @var string 기본 배경색깔 붉은색*/
public static $basecolor3 = "#660000";
/** @var string 기본 배경색깔 검붉은색*/
public static $basecolor4 = "#330000";
/** @var int 페이즈당 표준 감소 병사 수*/
public static $armperphase = 500;
/** @var int 기본 국고*/
public static $basegold = 0;
/** @var int 기본 병량*/
public static $baserice = 2000;
/** @var int 최저 국고(긴급시) */
public static $minNationalGold = 0;
/** @var int 최저 병량(긴급시) */
public static $minNationalRice = 0;
/** @var float 군량 매매시 세율*/
public static $exchangeFee = 0.01;
/** @var float 성인 연령 */
public static $adultAge = 14;
/** @var float 명전 등록 가능 연령 */
public static $minPushHallAge = 40;
/** @var int 최대 계급 */
public static $maxDedLevel = 30;
/** @var int 최대 기술 레벨 */
public static $maxTechLevel = 12;
/** @var int 최대 하야 패널티 수 */
public static $maxBetrayCnt = 9;
/** @var int 최소 인구 증가량 */
public static $basePopIncreaseAmount = 5000;
/** @var int 증축시 인구 증가량 */
public static $expandCityPopIncreaseAmount = 100000;
/** @var int 증축시 내정 증가량 */
public static $expandCityDevelIncreaseAmount = 2000;
/** @var int 증축시 성벽 증가량 */
public static $expandCityWallIncreaseAmount = 2000;
/** @var int 증축시 최소 비용 */
public static $expandCityDefaultCost = 60000;
/** @var int 증축시 비용 계수 */
public static $expandCityCostCoef = 500;
/** @var int 징병 허용 최소 인구 */
public static $minAvailableRecruitPop = 30000;
/** @var int 초기 제한시 장수 제한 */
public static $initialNationGenLimitForRandInit = 3;
/** @var int 초기 제한시 장수 제한 */
public static $initialNationGenLimit = 10;
/** @var int 초기 최대 장수수 */
public static $defaultMaxGeneral = 500;
/** @var int 초기 최대 국가 수 */
public static $defaultMaxNation = 55;
/** @var int 초기 최대 천재 수 */
public static $defaultMaxGenius = 5;
/** @var int 초기 시작 년도. 실제 값은 시나리오에서 정해지므로 딱히 의미는 없음. */
public static $defaultStartYear = 180;
/** @var float 멸망한 NPC 장수의 임관 확률 */
public static $joinRuinedNPCProp = 0.1;
/** @var int 시작시 금 */
public static $defaultGold = 1000;
/** @var int 시작시 쌀 */
public static $defaultRice = 1000;
/** @var int 원조 계수 */
public static $coefAidAmount = 10000;
/** @var int 최대 개별 자원 금액 */
public static $maxResourceActionAmount = 10000;
/** @var int[] 포상/몰수 가이드 금액 */
public static $resourceActionAmountGuide = [
100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
1200, 1500, 2000, 2500, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000
];
public static $generalMinimumGold = 0;
public static $generalMinimumRice = 500;
/** @var int 최대 턴 */
public static $maxTurn = 30;
public static $maxChiefTurn = 12;
public static $statGradeLevel = 5;
/** @var int 초반 제한 기간 */
public static $openingPartYear = 3;
/** @var int 거병,임관 제한 기간 */
public static $joinActionLimit = 12;
/** @var array 선택 가능한 국가 성향 */
public static $availableNationType = [
'che_도적', 'che_명가', 'che_음양가', 'che_종횡가', 'che_불가', 'che_오두미도', 'che_태평도', 'che_도가',
'che_묵가', 'che_덕가', 'che_병가', 'che_유가', 'che_법가'
];
/** @var array 기본 국가 성향 */
public static $neutralNationType = 'che_중립';
/** @var string 기본 내정 특기 */
public static $defaultSpecialDomestic = 'None';
/** @var array 선택 가능한 장수 내정 특기 */
public static $availableSpecialDomestic = [
'che_경작', 'che_상재', 'che_발명', 'che_축성', 'che_수비', 'che_통찰', 'che_인덕', 'che_귀모',
];
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 내정 특기 */
public static $optionalSpecialDomestic = [
'None',
];
/** @var string 기본 전투 특기 */
public static $defaultSpecialWar = 'None';
/** @var array 선택 가능한 장수 전투 특기 */
public static $availableSpecialWar = [
'che_귀병', 'che_신산', 'che_환술', 'che_집중', 'che_신중', 'che_반계',
'che_보병', 'che_궁병', 'che_기병', 'che_공성',
'che_돌격', 'che_무쌍', 'che_견고', 'che_위압',
'che_저격', 'che_필살', 'che_징병', 'che_의술', 'che_격노', 'che_척사',
];
/** @var array 선택할 수 없으나 게임 내에 유효한 장수 전투 특기 */
public static $optionalSpecialWar = [
'None',
];
/** @var string 기본 성향(공용) */
public static $neutralPersonality = 'None';
/** @var array 선택 가능한 성향 */
public static $availablePersonality = [
'che_안전', 'che_유지', 'che_재간', 'che_출세', 'che_할거', 'che_정복',
'che_패권', 'che_의협', 'che_대의', 'che_왕좌'
];
/** @var array 존재하는 모든 성향 */
public static $optionalPersonality = [
'che_은둔', 'None'
];
public static $allItems = [
'horse' => [
'che_명마_01_노기'=>0, 'che_명마_02_조랑'=>0, 'che_명마_03_노새'=>0,
'che_명마_04_나귀'=>0, 'che_명마_05_갈색마'=>0, 'che_명마_06_흑색마'=>0,
'che_명마_07_백마'=>2, 'che_명마_07_기주마'=>2,
'che_명마_08_양주마'=>2, 'che_명마_09_과하마'=>2,
'che_명마_10_대완마'=>2, 'che_명마_11_서량마'=>2,
'che_명마_12_사륜거'=>2, 'che_명마_13_절영'=>1, 'che_명마_13_적로'=>1,
'che_명마_14_적란마'=>1, 'che_명마_14_조황비전'=>1, 'che_명마_15_한혈마'=>1, 'che_명마_15_적토마'=>1,
],
'weapon' => [
'che_무기_01_단도'=>0, 'che_무기_02_단궁'=>0, 'che_무기_03_단극'=>0,
'che_무기_04_목검'=>0, 'che_무기_05_죽창'=>0, 'che_무기_06_소부'=>0,
'che_무기_07_동추'=>1, 'che_무기_07_철편'=>1, 'che_무기_07_철쇄'=>1, 'che_무기_07_맥궁'=>1,
'che_무기_08_유성추'=>1, 'che_무기_08_철질여골'=>1, 'che_무기_09_쌍철극'=>1, 'che_무기_09_동호비궁'=>1, 'che_무기_10_삼첨도'=>1, 'che_무기_10_대부'=>1, 'che_무기_11_고정도'=>1, 'che_무기_11_이광궁'=>1, 'che_무기_12_철척사모'=>1, 'che_무기_12_칠성검'=>1, 'che_무기_13_사모'=>1, 'che_무기_13_양유기궁'=>1,
'che_무기_14_언월도'=>1, 'che_무기_14_방천화극'=>1, 'che_무기_15_청홍검'=>1, 'che_무기_15_의천검'=>1
],
'book' => [
'che_서적_01_효경전'=>0, 'che_서적_02_회남자'=>0, 'che_서적_03_변도론'=>0,
'che_서적_04_건상역주'=>0, 'che_서적_05_여씨춘추'=>0, 'che_서적_06_사민월령'=>0,
'che_서적_07_위료자'=>1, 'che_서적_07_사마법'=>1, 'che_서적_07_한서'=>1, 'che_서적_07_논어'=>1,
'che_서적_08_전론'=>1, 'che_서적_08_사기'=>1, 'che_서적_09_장자'=>1, 'che_서적_09_역경'=>1,
'che_서적_10_시경'=>1, 'che_서적_10_구국론'=>1, 'che_서적_11_상군서'=>1, 'che_서적_11_춘추전'=>1,
'che_서적_12_산해경'=>1, 'che_서적_12_맹덕신서'=>1, 'che_서적_13_관자'=>1, 'che_서적_13_병법24편'=>1,
'che_서적_14_한비자'=>1, 'che_서적_14_오자병법'=>1, 'che_서적_15_노자'=>1, 'che_서적_15_손자병법'=>1,
],
'item' => [
'che_치료_환약'=>0, 'che_저격_수극'=>0, 'che_사기_탁주'=>0,
'che_훈련_청주'=>0, 'che_계략_이추'=>0, 'che_계략_향낭'=>0,
'che_치료_오석산'=>1, 'che_치료_무후행군'=>1, 'che_치료_도소연명'=>1,
'che_치료_칠엽청점'=>1, 'che_치료_정력견혈'=>1,
'che_훈련_과실주'=>1, 'che_훈련_이강주'=>1,
'che_사기_의적주'=>1, 'che_사기_두강주'=>1, 'che_사기_보령압주'=>1,
'che_훈련_철벽서'=>1, 'che_훈련_단결도'=>1, 'che_사기_춘화첩'=>1, 'che_사기_초선화'=>1,
'che_계략_육도'=>1, 'che_계략_삼략'=>1,
'che_의술_청낭서'=>1, 'che_의술_태평청령'=>1,
'che_회피_태평요술'=>1, 'che_회피_둔갑천서'=>1,
]
];
/** @var array 선택 가능한 커맨드 */
public static $availableGeneralCommand = [
''=>[
'휴식',
'che_요양'
],
'내정'=>[
'che_농지개간',
'che_상업투자',
'che_기술연구',
'che_수비강화',
'che_성벽보수',
'che_치안강화',
'che_정착장려',
'che_주민선정',
'che_물자조달',
],
'군사'=>[
'che_소집해제',
'che_첩보',
'che_징병',
'che_모병',
'che_훈련',
'che_사기진작',
'che_출병',
],
'인사'=>[
'che_이동',
'che_강행',
'che_인재탐색',
'che_등용',
'che_집합',
'che_귀환',
'che_임관',
'che_랜덤임관',
'che_장수대상임관',
],
'계략'=>[
'che_화계',
'che_파괴',
'che_탈취',
'che_선동',
],
'개인'=>[
'che_내정특기초기화',
'che_전투특기초기화',
'che_단련',
'che_숙련전환',
'che_견문',
'che_장비매매',
'che_군량매매',
'che_증여',
'che_헌납',
'che_하야',
'che_거병',
'che_건국',
'che_선양',
'che_방랑',
'che_해산',
'che_모반시도',
]
];
/** @var array 선택 가능한 커맨드 */
public static $availableChiefCommand = [
'휴식'=>[
'휴식',
],
'인사'=>[
'che_발령',
'che_포상',
'che_몰수',
],
'외교'=>[
'che_물자원조',
'che_불가침제의',
'che_선전포고',
'che_종전제의',
'che_불가침파기제의',
],
'특수'=>[
'che_초토화',
'che_천도',
'che_증축',
'che_감축',
],
'전략'=>[
'che_피장파장',
'che_필사즉생',
'che_백성동원',
'che_수몰',
'che_허보',
'che_의병모집',
'che_이호경식',
'che_급습',
],
'기타'=>[
'che_국기변경',
'che_국호변경',
]
];
public static $retirementYear = 80;
public static $randGenFirstName = [
'가', '간', '감', '강', '고', '공', '공손', '곽', '관', '괴', '교', '금', '노', '뇌', '능', '도', '동', '두',
'등', '마', '맹', '문', '미', '반', '방', '부', '비', '사', '사마', '서', '설', '성', '소', '손', '송', '순',
'신', '심', '악', '안', '양', '엄', '여', '염', '오', '왕', '요', '우', '원', '위', '유', '육', '윤', '이',
'장', '저', '전', '정', '제갈', '조', '종', '주', '진', '채', '태사', '하', '하후', '학', '한', '향', '허',
'호', '화', '황', '공손', '손', '왕', '유', '장', '조'
];
public static $randGenMiddleName = [''];
public static $randGenLastName = [
'가', '간', '강', '거', '건', '검', '견', '경', '공', '광', '권', '규', '녕', '단', '대', '도', '등', '람',
'량', '례', '로', '료', '모', '민', '박', '범', '보', '비', '사', '상', '색', '서', '소', '속', '송', '수',
'순', '습', '승', '양', '연', '영', '온', '옹', '완', '우', '웅', '월', '위', '유', '윤', '융', '이', '익',
'임', '정', '제', '조', '주', '준', '지', '찬', '책', '충', '탁', '택', '통', '패', '평', '포', '합', '해',
'혁', '현', '화', '환', '회', '횡', '후', '훈', '휴', '흠', '흥'
];
}
+3
View File
@@ -132,6 +132,9 @@ class ResetHelper{
$gameStor->resetValues();
$gameStor->next_season_idx = $seasonIdx;
$lastExecuteStor = KVStorage::getStorage($db, 'next_execute');
$lastExecuteStor->resetValues();
return [
'result'=>true,
'serverID'=>$serverID,
+227 -226
View File
@@ -1,227 +1,228 @@
<?php
namespace sammo;
class ScoutMessage extends Message{
const ACCEPTED = 1;
const DECLINED = -1;
const INVALID = 0;
protected $validScout = true;
public function __construct(
string $msgType,
MessageTarget $src,
MessageTarget $dest,
string $msg,
\DateTime $date,
\DateTime $validUntil,
array $msgOption
)
{
if ($msgType !== self::MSGTYPE_PRIVATE){
throw new \InvalidArgumentException('DiplomaticMessage msgType');
}
if(Util::array_get($msgOption['action']) !== 'scout'){
throw new \InvalidArgumentException('Action !== scout');
}
parent::__construct(...func_get_args());
if(Util::array_get($msgOption['used'])){
$this->validScout = false;
}
if($this->validUntil <= new \DateTime()){
$this->validScout = false;
}
}
protected function checkScoutMessageValidation(int $receiverID){
if(!$this->validScout){
return [self::INVALID, '유효하지 않은 등용장입니다.'];
}
if($this->mailbox !== $this->dest->generalID){
return [self::INVALID, '송신자가 등용장을 처리할 수 없습니다.'];
}
if($this->mailbox !== $receiverID){
return [self::INVALID, '올바른 수신자가 아닙니다.'];
}
return [self::ACCEPTED, '성공'];
}
/**
* @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환
*/
public function agreeMessage(int $receiverID, string &$reason):int{
//NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등)
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중');
}
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$general = \sammo\General::createGeneralObjFromDB($receiverID, null, 2);
$logger = $general->getLogger();
list($result, $reason) = $this->checkScoutMessageValidation($receiverID);
if($result !== self::ACCEPTED){
$logger->pushGeneralActionLog("{$reason} 등용 수락 불가.");
if($result === self::DECLINED){
$this->_declineMessage();
}
return $result;
}
$commandObj = buildGeneralCommandClass('che_등용수락', $general, $gameStor->getAll(true), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
]);
if(!$commandObj->hasFullConditionMet()){
$logger->pushGeneralActionLog($commandObj->getFailString());
$reason = $commandObj->getFailString();
return self::DECLINED;
}
$commandObj->run();
//메시지 비 활성화
$this->msgOption['used'] = true;
$this->invalidate();
$this->validScout = false;
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$newMsg = new Message(
self::MSGTYPE_PRIVATE,
$this->src,
$this->dest,
"{$this->src->nationName}{$josaRo} 등용 제의 수락",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id
]
);
$newMsg->send(true);
return self::ACCEPTED;
}
protected function _declineMessage(){
$this->msgOption['used'] = true;
$this->invalidate();
$this->validScout = false;
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$newMsg = new Message(
self::MSGTYPE_PRIVATE,
$this->src,
$this->dest,
"{$this->src->nationName}{$josaRo} 등용 제의 거부",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id
]
);
$newMsg->send(true);
return self::DECLINED;
}
public function declineMessage(int $receiverID, string &$reason):int{
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
list($result, $reason) = $this->checkScoutMessageValidation($receiverID);
if($result === self::INVALID){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} 등용 취소 불가.", ActionLogger::PLAIN);
return $result;
}
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$josaYi = JosaUtil::pick($this->dest->generalName, '');
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$this->src->nationName}</>{$josaRo} 망명을 거부했습니다.", ActionLogger::PLAIN);
(new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->generalName}</>{$josaYi} 등용을 거부했습니다.", ActionLogger::PLAIN);
$this->_declineMessage();
return self::DECLINED;
}
public static function buildScoutMessage(int $srcGeneralID, int $destGeneralID, &$reason = null, \DateTime $date = null):?self{
if($srcGeneralID == $destGeneralID){
if($reason !== null){
$reason = '같은 장수에게 등용장을 보낼 수 없습니다';
}
return null;
}
$db = DB::db();
$srcGeneral = $db->queryFirstRow('SELECT `name`, nation FROM general WHERE `no`=%i', $srcGeneralID);
$destGeneral = $db->queryFirstRow('SELECT `name`, nation, `officer_level` FROM general WHERE `no`=%i', $destGeneralID);
if($date === null){
$date = new \DateTime();
}
if($destGeneral['officer_level'] == 12){
if($reason !== null){
$reason = '군주에게 등용장을 보낼 수 없습니다';
}
return null;
}
if(!$srcGeneral['nation']){
if($reason !== null){
$reason = '재야 상태일 때에는 등용장을 보낼 수 없습니다';
}
return null;
}
if($srcGeneral['nation'] === $destGeneral['nation']){
if($reason !== null){
$reason = '같은 소속의 장수에게 등용장을 보낼 수 없습니다';
}
return null;
}
$srcNationInfo = getNationStaticInfo($srcGeneral['nation']);
$destNationInfo = getNationStaticInfo($destGeneral['nation']);
$src = new MessageTarget(
$srcGeneralID,
$srcGeneral['name'],
$srcGeneral['nation'],
$srcNationInfo['name'],
$srcNationInfo['color']
);
$dest = new MessageTarget(
$destGeneralID,
$destGeneral['name'],
$destGeneral['nation'],
$destNationInfo['name'],
$destNationInfo['color']
);
$josaRo = JosaUtil::pick($src->nationName, '로');
$msg = "{$src->nationName}{$josaRo} 망명 권유 서신";
$validUntil = new \DateTime("9999-12-31 12:59:59");
$msgOption = [
'action'=>'scout'
];
return new ScoutMessage(Message::MSGTYPE_PRIVATE, $src, $dest, $msg, $date, $validUntil, $msgOption);
}
<?php
namespace sammo;
class ScoutMessage extends Message{
const ACCEPTED = 1;
const DECLINED = -1;
const INVALID = 0;
protected $validScout = true;
public function __construct(
string $msgType,
MessageTarget $src,
MessageTarget $dest,
string $msg,
\DateTime $date,
\DateTime $validUntil,
array $msgOption
)
{
if ($msgType !== self::MSGTYPE_PRIVATE){
throw new \InvalidArgumentException('DiplomaticMessage msgType');
}
if(Util::array_get($msgOption['action']) !== 'scout'){
throw new \InvalidArgumentException('Action !== scout');
}
parent::__construct(...func_get_args());
if(Util::array_get($msgOption['used'])){
$this->validScout = false;
}
if($this->validUntil <= new \DateTime()){
$this->validScout = false;
}
}
protected function checkScoutMessageValidation(int $receiverID){
if(!$this->validScout){
return [self::INVALID, '유효하지 않은 등용장입니다.'];
}
if($this->mailbox !== $this->dest->generalID){
return [self::INVALID, '송신자가 등용장을 처리할 수 없습니다.'];
}
if($this->mailbox !== $receiverID){
return [self::INVALID, '올바른 수신자가 아닙니다.'];
}
return [self::ACCEPTED, '성공'];
}
/**
* @return int 수행 결과 반환, ACCEPTED(등용장 소모), DECLINED(등용장 소모), INVALID 중 반환
*/
public function agreeMessage(int $receiverID, string &$reason):int{
//NOTE: 올바른 유저가 agreeMessage() 호출을 한건지는 외부에서 체크 필요(Session->userID 등)
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 수락 진행 중');
}
$gameStor = KVStorage::getStorage(DB::db(), 'game_env');
$general = \sammo\General::createGeneralObjFromDB($receiverID, null, 2);
$logger = $general->getLogger();
list($result, $reason) = $this->checkScoutMessageValidation($receiverID);
if($result !== self::ACCEPTED){
$logger->pushGeneralActionLog("{$reason} 등용 수락 불가.");
if($result === self::DECLINED){
$this->_declineMessage();
}
return $result;
}
$commandObj = buildGeneralCommandClass('che_등용수락', $general, $gameStor->getAll(true), [
'destNationID'=>$this->src->nationID,
'destGeneralID'=>$this->src->generalID,
]);
if(!$commandObj->hasFullConditionMet()){
$logger->pushGeneralActionLog($commandObj->getFailString());
$reason = $commandObj->getFailString();
return self::DECLINED;
}
$commandObj->run();
$commandObj->setNextAvailable();
//메시지 비 활성화
$this->msgOption['used'] = true;
$this->invalidate();
$this->validScout = false;
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$newMsg = new Message(
self::MSGTYPE_PRIVATE,
$this->src,
$this->dest,
"{$this->src->nationName}{$josaRo} 등용 제의 수락",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id
]
);
$newMsg->send(true);
return self::ACCEPTED;
}
protected function _declineMessage(){
$this->msgOption['used'] = true;
$this->invalidate();
$this->validScout = false;
$josaRo = JosaUtil::pick($this->src->nationName, '로');
$newMsg = new Message(
self::MSGTYPE_PRIVATE,
$this->src,
$this->dest,
"{$this->src->nationName}{$josaRo} 등용 제의 거부",
new \DateTime(),
new \DateTime('9999-12-31'),
[
'delete'=>$this->id
]
);
$newMsg->send(true);
return self::DECLINED;
}
public function declineMessage(int $receiverID, string &$reason):int{
if(!$this->id){
throw new \RuntimeException('전송되지 않은 메시지에 거절 진행 중');
}
$db = DB::db();
$gameStor = KVStorage::getStorage($db, 'game_env');
[$year, $month] = $gameStor->getValuesAsArray(['year', 'month']);
list($result, $reason) = $this->checkScoutMessageValidation($receiverID);
if($result === self::INVALID){
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$reason} 등용 취소 불가.", ActionLogger::PLAIN);
return $result;
}
$josaRo = JosaUtil::pick($this->src->nationName, '');
$josaYi = JosaUtil::pick($this->dest->generalName, '이');
(new ActionLogger($receiverID, 0, $year, $month))->pushGeneralActionLog("{$this->src->nationName}</>{$josaRo} 망명을 거부했습니다.", ActionLogger::PLAIN);
(new ActionLogger($this->src->generalID, 0, $year, $month))->pushGeneralActionLog("<Y>{$this->dest->generalName}</>{$josaYi} 등용을 거부했습니다.", ActionLogger::PLAIN);
$this->_declineMessage();
return self::DECLINED;
}
public static function buildScoutMessage(int $srcGeneralID, int $destGeneralID, &$reason = null, \DateTime $date = null):?self{
if($srcGeneralID == $destGeneralID){
if($reason !== null){
$reason = '같은 장수에게 등용장을 보낼 수 없습니다';
}
return null;
}
$db = DB::db();
$srcGeneral = $db->queryFirstRow('SELECT `name`, nation FROM general WHERE `no`=%i', $srcGeneralID);
$destGeneral = $db->queryFirstRow('SELECT `name`, nation, `officer_level` FROM general WHERE `no`=%i', $destGeneralID);
if($date === null){
$date = new \DateTime();
}
if($destGeneral['officer_level'] == 12){
if($reason !== null){
$reason = '군주에게 등용장을 보낼 수 없습니다';
}
return null;
}
if(!$srcGeneral['nation']){
if($reason !== null){
$reason = '재야 상태일 때에는 등용장을 보낼 수 없습니다';
}
return null;
}
if($srcGeneral['nation'] === $destGeneral['nation']){
if($reason !== null){
$reason = '같은 소속의 장수에게 등용장을 보낼 수 없습니다';
}
return null;
}
$srcNationInfo = getNationStaticInfo($srcGeneral['nation']);
$destNationInfo = getNationStaticInfo($destGeneral['nation']);
$src = new MessageTarget(
$srcGeneralID,
$srcGeneral['name'],
$srcGeneral['nation'],
$srcNationInfo['name'],
$srcNationInfo['color']
);
$dest = new MessageTarget(
$destGeneralID,
$destGeneral['name'],
$destGeneral['nation'],
$destNationInfo['name'],
$destNationInfo['color']
);
$josaRo = JosaUtil::pick($src->nationName, '로');
$msg = "{$src->nationName}{$josaRo} 망명 권유 서신";
$validUntil = new \DateTime("9999-12-31 12:59:59");
$msgOption = [
'action'=>'scout'
];
return new ScoutMessage(Message::MSGTYPE_PRIVATE, $src, $dest, $msg, $date, $validUntil, $msgOption);
}
}
+2
View File
@@ -85,6 +85,7 @@ class TurnExecutionHelper
$result = $commandObj->run();
if($result){
$commandObj->setNextAvailable();
break;
}
@@ -127,6 +128,7 @@ class TurnExecutionHelper
$result = $commandObj->run();
if($result){
$commandObj->setNextAvailable();
break;
}
$alt = $commandObj->getAlternativeCommand();