파일 위치를 twe에서 hwe로 옮김.

This commit is contained in:
2018-04-01 01:23:44 +09:00
parent 1ddd26c8a1
commit 25ec9a2579
201 changed files with 0 additions and 0 deletions
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace sammo\Event;
abstract class Action{
//public abstract function __construct(...$args);
public abstract function run($env=null);
public static function build($actionArgs){
if(!is_array($actionArgs)){
throw new \InvalidArgumentException('action을 입력해야 합니다.');
}
$className = __NAMESPACE__.'\\Action\\'.$actionArgs[0];
if(!class_exists($className)){
throw new \InvalidArgumentException('존재하지 않는 Action입니다 :'.$actionArgs[0]);
}
$args = array_slice($actionArgs, 1);
$ref = new \ReflectionClass($className);
return $ref->newInstanceArgs($args);
}
}
+163
View File
@@ -0,0 +1,163 @@
<?php
namespace sammo\Event\Action;
use sammo\Util;
use sammo\DB;
//기존 시나리오에서 개시 1월에 내정을 깎는 것을 모사.
class ChangeCity extends \sammo\Event\Action{
const AVAILABLE_KEY = [
'pop'=>true,
'agri'=>true,
'comm'=>true,
'secu'=>true,
'rate'=>true,
'def'=>true,
'wall'=>true
];
const REGEXP_PERCENT = '/^(\d+(\.\d+)?)%$/';// 123.5% [1]=float
const REGEXP_MATH = '/^([\+\-\/\*])(\d+(\.\d+)?)$/'; //+30 [1]=기호, [2]=float
private $queries;
private $targetType = 'all';
private $targetArgs = [];
public function __construct($target = null, array $actions){
//values 포맷은 key, value로
if(!$target){
$this->targetType = 'all';
}
else if(is_string($target)){
$this->targetType = $target;
}
else if(is_array($target)){
$this->targetType = $target[0];
$this->targetArgs = array_slice($target, 1);
}
else{
throw new \InvalidArgumentException('올바르지 않은 targetType 입니다.');
}
$queries = [];
foreach($actions as $key => $value){
if(!key_exists($key, self::AVAILABLE_KEY)){
throw new \InvalidArgumentException('지원하지 않는 city 인자입니다 :'.$key);
}
if(!is_int($value) && !is_float($value) && !is_string($value)){
throw new \InvalidArgumentException('int, float, string이어야 합니다.');
}
if($key == 'rate'){
$queries['rate'] = $this->genSQLRate($value);
continue;
}
$queries[$key] = $this->genSQLGeneric($key, $value);
}
$this->queries = $queries;
}
private function genSQLRate($value){
//민심은 max값이 100으로 고정이므로 처리 방식이 다름.
if(is_float($value)){
if($value < 0){
throw new \InvalidArgumentException('음수를 곱할 수 없습니다.');
}
return DB::db()->sqleval('least(100, ROUND(`rate` * %d, 0))', $value);
}
if(is_int($value)){
return DB::db()->sqleval('%i', Util::valueFit($value, 0, 100));
}
$matches = null;
if(preg_match(self::REGEXP_PERCENT, $value, $matches)){
$value = round($matches[1], 0);
return DB::db()->sqleval('%i', Util::valueFit($value, 0, 100));
}
if(preg_match(self::REGEXP_MATH, $value, $matches)){
$op = $matches[1];
$value = $matches[2];
if($op == '/' && $value == 0){
throw new \InvalidArgumentException('0으로 나눌 수 없습니다.');
}
return DB::db()->sqleval('least(100, greatest(0, ROUND(`rate` %l %d, 0)))', $op, $value);
}
throw new \InvalidArgumentException('알 수 없는 패턴입니다.');
}
private function genSQLGeneric($key, $value){
$keyMax = $key.'2'; //comm, comm2
if(is_float($value)){
if($value < 0){
throw new \InvalidArgumentException('음수를 곱할 수 없습니다.');
}
return DB::db()->sqleval('least(%b, ROUND(%b * %d, 0))', $keyMax, $key, $value);
}
if(is_int($value)){
return DB::db()->sqleval('least(%b, %i)', $keyMax, max(0, $value));
}
$matches = null;
if(preg_match(self::REGEXP_PERCENT, $value, $matches)){
$value = round($matches[1], 0);
return DB::db()->sqleval('ROUND(%b * %d, 0)', $keyMax, $value/100);
}
if(preg_match(self::REGEXP_MATH, $value, $matches)){
$op = $matches[1];
$value = $matches[2];
if($op == '/' && $value == 0){
throw new \InvalidArgumentException('0으로 나눌 수 없습니다.');
}
return DB::db()->sqleval('least(%b, greatest(0, ROUND($b %l %d, 0)))', $keyMax, $key, $op, $value);
}
throw new \InvalidArgumentException('알 수 없는 패턴입니다.');
}
private function getTargetCities($env){
$targetType = $this->targetType;
if($targetType == 'all'){
return DB::db()->queryFirstColumn('SELECT city FROM city');
}
if($targetType == 'free'){
return DB::db()->queryFirstColumn('SELECT city FROM city WHERE nation = 0');
}
if($targetType == 'occupied'){
return DB::db()->queryFirstColumn('SELECT city FROM city WHERE nation != 0');
}
if($targetType == 'cities'){
if(is_numeric($this->targetArgs)){
return DB::db()->queryFirstColumn('SELECT city FROM city WHERE city IN (%ls)', $this->targetArgs);
}
else{
return DB::db()->queryFirstColumn('SELECT city FROM city WHERE name IN (%ls)', $this->targetArgs);
}
}
throw new \InvalidArgumentException('올바르지 않은 cond 입니다.');
}
public function run($env=null){
$cities = $this->getTargetCities($env);
DB::db()->update('city',
$this->queries
, 'city IN %li', $cities);
return [__CLASS__, DB::db()->affectedRows()];
}
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace sammo\Event\Action;
//기존 event_4.php
class CreateAdminNPC extends \sammo\Event\Action{
public function __construct(){
}
public function run($env=null){
return [__CLASS__, 'NYI'];
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace sammo\Event\Action;
//기존 event_3.php
class CreateManyNPC extends \sammo\Event\Action{
public function __construct($npcCount = 200){
}
public function run($env=null){
return [__CLASS__, 'NYI'];
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace sammo\Event\Action;
//1회용 event임을 의미함
class DeleteEvent extends \sammo\Event\Action{
public function __construct(){
}
public function run($env){
$eventID = \sammo\Util::array_get($env['currentEventID']);
if(!$eventID){
throw new \RuntimeException('currentEventID가 지정되지 않았습니다.');
//NOTE: 이걸 에러 내야할지 아닐지는 아직 판단 필요
}
$db = \sammo\DB::db();
$db->delete('event', 'id = %i', $eventID);
return [__CLASS__, $db->affectedRows()];
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace sammo\Event\Action;
use sammo\Util;
use sammo\DB;
/**
* 이민족 침입을 모사
*
* 양수 : 정해진 값. [절대값]
* 음수 : 합산(장수 등), 혹은 평균(기술 등)을 나누어 적용한 값 [상대값]
*
* event_1.php, 센 이민족 : npcEachCount = -0.5, specAvg = 195, specDist = 5, tech = 15000, dex = 450000
* event_2.php, 약한 이민족 : npcEachCount = -0.5, specAvg = 150, specDist = 20, tech = -1, dex = 0
* event_3.php, 엄청 약한 이민족 : npcEachCount = 100, specAvg = 50, specDist = 5, tech = 0, dex = 0
*/
class RaiseInvader extends \sammo\Event\Action{
private $npcEachCount;
private $specAvg;
private $specDist;
private $tech;
private $dex;
const INVADER_LIST = [
'강'=>63,
'저'=>64,
'흉노'=>65,
'남만'=>66,
'산월'=>67,
'오환'=>68,
'왜'=>69
];
public function __construct(
$npcEachCount = -0.5,
int $specAvg = 150,
int $specDist = 20,
int $tech = -1,
int $dex = 0
){
$this->npcEachCount = $npcEachCount;
$this->specAvg = $specAvg;
$this->specDist = $specDist;
$this->tech = $tech;
$this->dex = $dex;
if($specDist < 0){
throw new \InvalidArgumentException('specDist는 음수를 지원하지 않습니다.');
}
}
private function moveCapital(){
$cities = array_map(function ($value) {
return $value;
}, INVADER_LIST);
$db = DB::db();
foreach($db->queryFirstColumn('SELECT capital, nation from nation WHERE capital in %li', $cities) as $row){
list($oldCapital, $nation) = $row;
$newCapital = $db->queryFirstRow('SELECT city from city where nation=%i and city !=%i \
order by rand() limit 1', $nation, $oldCapital);
$db->update('nation', ['capital'=>$newCapital], 'nation=%i', $nation);
$db->update('general', ['city'=>$newCapital], 'nation=%i and city=%i', $nation, $city);
}
$generals = [];
foreach($db->query('SELECT gen1, gen2, gen3 from city where city in %li', $cities) as $city){
list($gen1, $gen2, $gen3) = $city;
if($gen1 != 0) $generals[]=$gen1;
if($gen2 != 0) $generals[]=$gen2;
if($gen3 != 0) $generals[]=$gen3;
}
$db->update('general', [
'level'=>1
], 'no in %li', $generals);
$db->update('city', [
'gen1'=>0,
'gen2'=>0,
'gen3'=>0,
'nation'=>0
], 'city in %li', $cities);
}
public function run($env=null){
$db = DB::db();
$npcEachCount = $this->npcEachCount;
if($npcEachCount < 0){
$npcEachCount =
$db->queryFirstField('SELECT count(no) from general where npc<5') / count(self::INVADER_LIST);
$npcEachCount /= -1 * $this->npcEachCount;
}
$specAvg = $this->specAvg;
if($specAvg < 0){
$specAvg = $db->queryFirstField('SELECT avg(sum(`leader` + `power` + `intel`)) from general where npc<5');
$specAvg /= -1 * $this->specAvg;
}
$tech = $this->tech;
if($tech < 0){
$tech = $db->queryFirstField("SELECT avg(tech) from nation where `level`>0");
$tech /= -1 * $this->tech;
}
$dex = $this->dex;
if($dex < 0){
$dex = $db->queryFirstField("SELECT avg(dex0 + dex10 + dex20 + dex30 + dex40)/5 from nation where `level`>0");
$dex /= -1 * $this->dex;
}
$this->moveCapital();
//TODO:국가를 만들고
//TODO:장수를 세팅하고
//TODO:외교를 설정한다.
//TODO: 시나리오 구현 후 마무리.
return [__CLASS__, 'NYI'];
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace sammo\Event\Action;
//이전 RegNPC 함수를 EventAction으로 재구성
class RegNPC extends \sammo\Event\Action{
private $npc;
public function __construct(
int $affinity,
string $name,
int $pictureID,
int $nationID,
string $locatedCity,
int $leadership,
int $power,
int $intel,
int $birth = 160,
int $death = 300,
string $ego = null,
string $char = null,
string $text = null
){
$this->npc = new \sammo\Scenario\NPC(
$affinity,
$name,
$pictureID,
$nationID,
$locatedCity,
$leadership,
$power,
$intel,
$birth,
$death,
$ego,
$char,
$text
);
}
public function run($env=null){
$result = $this->npc->build($env);
return [__CLASS__, $result];
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace sammo\Event;
abstract class Condition{
public abstract function eval($env=null);
public static function build($conditionChain){
if(is_bool($conditionChain)){
return new Condition\ConstBool($conditionChain);
}
if(!is_array($conditionChain)){
return $conditionChain;
}
$key = $conditionChain[0];
if(\array_key_exists(strtolower($key), Condition\Logic::AVAILABLE_LOGIC_NAME)){
//logic 단축 명령.
$ref = new \ReflectionClass('sammo\\Event\\Condition\\Logic');
return $ref->newInstanceArgs($conditionChain);
}
$className = 'sammo\\Event\\Condition\\'.$key;
if(class_exists($className)){
$args = [];
reset($conditionChain);
while (next($conditionChain) !== FALSE)
{
$args[] = static::build(current($conditionChain));
}
$ref = new \ReflectionClass($className);
return $ref->newInstanceArgs($args);
}
//array의 첫번째 값이 Condition이 아닌 경우에는 그냥 배열로 처리함.
return array_map(static::build, $conditionChain);
}
protected static function _eval($arg, $env=null){
if(is_bool($arg)){
return [
'value'=>$arg,
'chain'=>['boolean']
];
}
if($arg instanceof Condition){
return $arg->checkCondition($env);
}
throw new \InvalidArgumentException('평가 인자는 boolean이거나 Condition 클래스여야 합니다.');
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace sammo\Event\Condition;
class ConstBool extends \sammo\Event\Condition{
private $fixedResult = true;
public function __construct(bool $value){
$this->fixedResult = $value;
}
public function eval($env=null){
return [
'value'=>$this->fixedResult,
'chain'=>['ConstBool']
];
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace sammo\Event\Condition;
class Date extends sammo\Event\Condition{
const AVAILABLE_CMP = [
'=='=>true,
'!='=>true,
'<'=>true,
'>'=>true,
'<='=>true,
'>='=>true,
];
private $cmp;
private $year;
private $month;
//TODO:구현
public function __construct(string $cmp, int $year, int $month){
//Cmp('==', '!=', '<=', '>=', '<', '>'), Year, Month(Optional)
if(!array_key_exists($cmp, self::AVAILABLE_CMP)){
throw new \InvalidArgumentException('올바르지 않은 비교연산자입니다');
}
if($year === null && $month === null){
throw new \InvalidArgumentException('year과 month가 둘다 null일 수 없습니다.');
}
$this->cmp = $cmp;
$this->year = $year;
$this->month = $month;
}
public function eval(array $env=null){
if($env === null){
return [
'value'=>false,
'chain'=>[__CLASS__]
];
}
if($this->year !== null && !isset($env['year'])){
throw new \InvalidArgumentException('env에 year가 없습니다.');
}
if($this->month !== null && !isset($env['month'])){
throw new \InvalidArgumentException('env에 month가 없습니다.');
}
$lhs = [
$this->$year,
$this->month
];
$rhs = [
$this->year!==null?(int)$env['year']:null,
$this->month!==null?(int)$env['month']:null
];
$value = false;
switch($this->cmp){
case '==': $value = ($lhs == $rhs); break;
case '!=': $value = ($lhs != $rhs); break;
case '<=': $value = ($lhs <= $rhs); break;
case '>=': $value = ($lhs >= $rhs); break;
case '<': $value = ($lhs < $rhs); break;
case '>': $value = ($lhs > $rhs); break;
}
return [
'value'=>$value,
'chain'=>[__CLASS__]
];
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace sammo\Event\Condition;
class Interval extends sammo\Event\Condition{
//TODO:구현
public function __construct(...$args){
throw new \BadMethodCallException('Not Yet Implmented.');
//from Year, from Month, Interval, to Year, to Month
}
public function eval($env=null){
throw new \BadMethodCallException('Not Yet Implmented.');
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace sammo\Event\Condition;
class Logic extends sammo\Event\Condition{
private $mode = 'and';
private $conditions = [];
const AVAILABLE_LOGIC_NAME = [
'not'=>false,
'and'=>true,
'or'=>true,
'xor'=>true
];
public function __construct(string $mode, ...$conditions){
$mode = strtolower($mode);
if(!array_key_exists($mode, self::AVAILABLE_LOGIC_NAME)){
throw new \InvalidArgumentException('첫번째 인자는 not, and, or, xor 중 하나여야 합니다.');
}
if(!self::AVAILABLE_LOGIC_NAME[$mode] && count($conditions)>1){
throw new \InvalidArgumentException('조건을 하나만 받을 수 있습니다.');
}
$this->mode = $mode;
$this->conditions = $conditions;
}
public function eval($env=null){
switch($this->$mode){
case 'not':
return $this->logicNot($env);
case 'and':
return $this->logicAnd($env);
case 'or':
return $this->logicOr($env);
case 'xor':
return $this->logicXor($env);
}
throw new \InvalidArgumentException('올바르지 않은 mode.');
}
private function logicNot($env){
$sub = self::_eval($this->conditions[0], $env);
$result['value'] = !$result['value'];
$result['chain'][] = 'not';
return $result;
}
private function logicAnd($env){
$value = true;
$chain = [];
foreach($this->conditions as $cond){
$sub = self::_eval($cond, $env);
$chain[] = $sub['chain'];
if(!$sub['value']){
$result['value'] = false;
break;
}
}
return [
'value'=>$value,
'chain'=>[$chain, 'and']
];
}
private function logicOr($env){
$value = false;
$chain = [];
foreach($this->conditions as $cond){
$sub = self::_eval($cond, $env);
$chain[] = $sub['chain'];
if($sub['value']){
$result['value'] = true;
break;
}
}
return [
'value'=>$value,
'chain'=>[$chain, 'or']
];
}
private function logicXor($env){
$value = false;
$chain = [];
foreach($this->conditions as $cond){
$sub = self::_eval($cond, $env);
$chain[] = $sub['chain'];
$value ^= $sub['value'];
}
return [
'value'=>$value,
'chain'=>[$chain, 'xor']
];
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace sammo\Event;
/**
* 게임 내에서 매 월마다 EventHandler들을 점검하고, 이벤트를 일으키는 이벤트 엔진.
* 조건 방식이 '무식'하므로, 게임 내부에서 사용하지는 않고, 특수 시나리오를 구동하는데 사용.
* (예: 칠종칠금?)
*/
class Engine{
//TODO: 구현하라. 미래의 누군가. =P (메롱!)
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace sammo\Event;
class EventHandler{
private $condition = null;
private $actions = [];
public function __construct($rawCondition, $rawActions){
$this->condition = Condition::build($rawCondition);
foreach($rawActions as $rawAction){
$this->actions[] = Action::build($rawAction);
}
}
public function tryRunEvent(array $env=null){
$result = $this->condition->eval($env);
if(!$result['value']){
return $result;
}
$resultAction = [];
foreach($this->actions as $action){
$resultAction[] = $action->run();
}
$result['action'] = $resultAction;
return $result;
}
}