From d75f21035d2d747010efd234b5e7b3a42e0a41fd Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 21 Jan 2022 20:31:49 +0900 Subject: [PATCH 01/44] =?UTF-8?q?feat:=20ng=5Fbetting=20=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=B8=94=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sql/schema.sql | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/hwe/sql/schema.sql b/hwe/sql/schema.sql index 3e052ee0..4b0b002d 100644 --- a/hwe/sql/schema.sql +++ b/hwe/sql/schema.sql @@ -673,4 +673,21 @@ CREATE TABLE IF NOT EXISTS `user_record` ( ) DEFAULT CHARSET=utf8mb4 ENGINE=Aria -; \ No newline at end of file +; + +CREATE TABLE IF NOT EXISTS `ng_betting` ( + `id` INT(11) NOT NULL AUTO_INCREMENT, + `betting_id` INT(11) NOT NULL, + `general_id` INT(11) NOT NULL, + `user_id` INT(11) NULL DEFAULT NULL, + `betting_type` VARCHAR(100) NOT NULL COMMENT 'JSON', + `amount` INT(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE INDEX `by_general` (`general_id`, `betting_id`, `betting_type`), + UNIQUE INDEX `by_bet` (`betting_id`, `betting_type`, `general_id`), + INDEX `by_user` (`user_id`, `betting_id`, `betting_type`), + CONSTRAINT `type_json` CHECK (json_valid(`betting_type`)) +) +DEFAULT CHARSET=utf8mb4 +ENGINE=Aria +; -- 2.54.0 From 290e7ee05eed74da34cac1e5d77671b6f8e8778d Mon Sep 17 00:00:00 2001 From: hide_d Date: Mon, 24 Jan 2022 03:22:03 +0900 Subject: [PATCH 02/44] dep: DTO --- composer.json | 3 +- composer.lock | 65 ++- vendor/composer/InstalledVersions.php | 13 +- vendor/composer/autoload_psr4.php | 1 + vendor/composer/autoload_static.php | 5 + vendor/composer/installed.json | 66 +++ vendor/composer/installed.php | 13 +- vendor/composer/platform_check.php | 4 +- .../.github/CONTRIBUTING.md | 55 ++ .../data-transfer-object/.github/FUNDING.yml | 2 + .../.github/workflows/style.yml | 23 + .../.github/workflows/update-changelog.yml | 28 + .../.php-cs-fixer.dist.php | 41 ++ .../spatie/data-transfer-object/CHANGELOG.md | 248 +++++++++ vendor/spatie/data-transfer-object/LICENSE.md | 21 + vendor/spatie/data-transfer-object/README.md | 504 ++++++++++++++++++ .../spatie/data-transfer-object/composer.json | 44 ++ .../spatie/data-transfer-object/src/Arr.php | 98 ++++ .../src/Attributes/CastWith.php | 24 + .../src/Attributes/DefaultCast.php | 53 ++ .../src/Attributes/MapFrom.php | 14 + .../src/Attributes/MapTo.php | 14 + .../src/Attributes/Strict.php | 10 + .../data-transfer-object/src/Caster.php | 8 + .../src/Casters/ArrayCaster.php | 70 +++ .../src/Casters/DataTransferObjectCaster.php | 25 + .../src/DataTransferObject.php | 125 +++++ .../src/Exceptions/InvalidCasterClass.php | 18 + .../src/Exceptions/UnknownProperties.php | 15 + .../src/Exceptions/ValidationException.php | 27 + .../Reflection/DataTransferObjectClass.php | 84 +++ .../Reflection/DataTransferObjectProperty.php | 182 +++++++ .../src/Validation/ValidationResult.php | 31 ++ .../data-transfer-object/src/Validator.php | 10 + 34 files changed, 1936 insertions(+), 8 deletions(-) create mode 100644 vendor/spatie/data-transfer-object/.github/CONTRIBUTING.md create mode 100644 vendor/spatie/data-transfer-object/.github/FUNDING.yml create mode 100644 vendor/spatie/data-transfer-object/.github/workflows/style.yml create mode 100644 vendor/spatie/data-transfer-object/.github/workflows/update-changelog.yml create mode 100644 vendor/spatie/data-transfer-object/.php-cs-fixer.dist.php create mode 100644 vendor/spatie/data-transfer-object/CHANGELOG.md create mode 100644 vendor/spatie/data-transfer-object/LICENSE.md create mode 100644 vendor/spatie/data-transfer-object/README.md create mode 100644 vendor/spatie/data-transfer-object/composer.json create mode 100644 vendor/spatie/data-transfer-object/src/Arr.php create mode 100644 vendor/spatie/data-transfer-object/src/Attributes/CastWith.php create mode 100644 vendor/spatie/data-transfer-object/src/Attributes/DefaultCast.php create mode 100644 vendor/spatie/data-transfer-object/src/Attributes/MapFrom.php create mode 100644 vendor/spatie/data-transfer-object/src/Attributes/MapTo.php create mode 100644 vendor/spatie/data-transfer-object/src/Attributes/Strict.php create mode 100644 vendor/spatie/data-transfer-object/src/Caster.php create mode 100644 vendor/spatie/data-transfer-object/src/Casters/ArrayCaster.php create mode 100644 vendor/spatie/data-transfer-object/src/Casters/DataTransferObjectCaster.php create mode 100644 vendor/spatie/data-transfer-object/src/DataTransferObject.php create mode 100644 vendor/spatie/data-transfer-object/src/Exceptions/InvalidCasterClass.php create mode 100644 vendor/spatie/data-transfer-object/src/Exceptions/UnknownProperties.php create mode 100644 vendor/spatie/data-transfer-object/src/Exceptions/ValidationException.php create mode 100644 vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectClass.php create mode 100644 vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php create mode 100644 vendor/spatie/data-transfer-object/src/Validation/ValidationResult.php create mode 100644 vendor/spatie/data-transfer-object/src/Validator.php diff --git a/composer.json b/composer.json index 875d4bd8..b73c725d 100644 --- a/composer.json +++ b/composer.json @@ -29,7 +29,8 @@ "erusev/parsedown-extra": "^0.8.1", "nette/caching": "^3.0", "illuminate/database": "^8.61", - "illuminate/events": "^8.61" + "illuminate/events": "^8.61", + "spatie/data-transfer-object": "^3.7" }, "autoload": { "psr-4": { diff --git a/composer.lock b/composer.lock index 1679a960..251400a7 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "94cfbcb22b9f475e421ad5009391006f", + "content-hash": "1983b89436fd8017db508592ddf542e4", "packages": [ { "name": "brandonwamboldt/utilphp", @@ -2636,6 +2636,69 @@ }, "time": "2021-06-29T04:31:23+00:00" }, + { + "name": "spatie/data-transfer-object", + "version": "3.7.3", + "source": { + "type": "git", + "url": "https://github.com/spatie/data-transfer-object.git", + "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/data-transfer-object/zipball/341f72c77e0fce40ea2e0dcb212cb54dc27bbe72", + "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "illuminate/collections": "^8.36", + "jetbrains/phpstorm-attributes": "^1.0", + "larapack/dd": "^1.1", + "phpunit/phpunit": "^9.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "Spatie\\DataTransferObject\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brent Roose", + "email": "brent@spatie.be", + "homepage": "https://spatie.be", + "role": "Developer" + } + ], + "description": "Data transfer objects with batteries included", + "homepage": "https://github.com/spatie/data-transfer-object", + "keywords": [ + "data-transfer-object", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/data-transfer-object/issues", + "source": "https://github.com/spatie/data-transfer-object/tree/3.7.3" + }, + "funding": [ + { + "url": "https://spatie.be/open-source/support-us", + "type": "custom" + }, + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "time": "2021-12-30T20:31:10+00:00" + }, { "name": "symfony/console", "version": "v5.3.10", diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php index b54c107b..936da251 100644 --- a/vendor/composer/InstalledVersions.php +++ b/vendor/composer/InstalledVersions.php @@ -29,7 +29,7 @@ private static $installed = array ( 'aliases' => array ( ), - 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6', + 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd', 'name' => 'sammo-hid/sammo', ), 'versions' => @@ -450,7 +450,7 @@ private static $installed = array ( 'aliases' => array ( ), - 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6', + 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd', ), 'sergeytsalkov/meekrodb' => array ( @@ -461,6 +461,15 @@ private static $installed = array ( ), 'reference' => 'e30c240d54bc81f58c58507a9ed768032eb494a5', ), + 'spatie/data-transfer-object' => + array ( + 'pretty_version' => '3.7.3', + 'version' => '3.7.3.0', + 'aliases' => + array ( + ), + 'reference' => '341f72c77e0fce40ea2e0dcb212cb54dc27bbe72', + ), 'symfony/console' => array ( 'pretty_version' => 'v5.3.10', diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php index 6e758f8b..7576aec0 100644 --- a/vendor/composer/autoload_psr4.php +++ b/vendor/composer/autoload_psr4.php @@ -27,6 +27,7 @@ return array( 'Symfony\\Component\\String\\' => array($vendorDir . '/symfony/string'), 'Symfony\\Component\\Lock\\' => array($vendorDir . '/symfony/lock'), 'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'), + 'Spatie\\DataTransferObject\\' => array($vendorDir . '/spatie/data-transfer-object/src'), 'Sabre\\Event\\' => array($vendorDir . '/sabre/event/lib'), 'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'), 'Psr\\Log\\' => array($vendorDir . '/psr/log/Psr/Log'), diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php index 245fbae9..ce1a8b45 100644 --- a/vendor/composer/autoload_static.php +++ b/vendor/composer/autoload_static.php @@ -76,6 +76,7 @@ class ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a 'Symfony\\Component\\String\\' => 25, 'Symfony\\Component\\Lock\\' => 23, 'Symfony\\Component\\Console\\' => 26, + 'Spatie\\DataTransferObject\\' => 26, 'Sabre\\Event\\' => 12, ), 'P' => @@ -217,6 +218,10 @@ class ComposerStaticInit67b09c83b85c3bc0027caefe5bba171a array ( 0 => __DIR__ . '/..' . '/symfony/console', ), + 'Spatie\\DataTransferObject\\' => + array ( + 0 => __DIR__ . '/..' . '/spatie/data-transfer-object/src', + ), 'Sabre\\Event\\' => array ( 0 => __DIR__ . '/..' . '/sabre/event/lib', diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json index ad0ee3c1..35cec1c5 100644 --- a/vendor/composer/installed.json +++ b/vendor/composer/installed.json @@ -2722,6 +2722,72 @@ }, "install-path": "../sergeytsalkov/meekrodb" }, + { + "name": "spatie/data-transfer-object", + "version": "3.7.3", + "version_normalized": "3.7.3.0", + "source": { + "type": "git", + "url": "https://github.com/spatie/data-transfer-object.git", + "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/spatie/data-transfer-object/zipball/341f72c77e0fce40ea2e0dcb212cb54dc27bbe72", + "reference": "341f72c77e0fce40ea2e0dcb212cb54dc27bbe72", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "illuminate/collections": "^8.36", + "jetbrains/phpstorm-attributes": "^1.0", + "larapack/dd": "^1.1", + "phpunit/phpunit": "^9.0" + }, + "time": "2021-12-30T20:31:10+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Spatie\\DataTransferObject\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Brent Roose", + "email": "brent@spatie.be", + "homepage": "https://spatie.be", + "role": "Developer" + } + ], + "description": "Data transfer objects with batteries included", + "homepage": "https://github.com/spatie/data-transfer-object", + "keywords": [ + "data-transfer-object", + "spatie" + ], + "support": { + "issues": "https://github.com/spatie/data-transfer-object/issues", + "source": "https://github.com/spatie/data-transfer-object/tree/3.7.3" + }, + "funding": [ + { + "url": "https://spatie.be/open-source/support-us", + "type": "custom" + }, + { + "url": "https://github.com/spatie", + "type": "github" + } + ], + "install-path": "../spatie/data-transfer-object" + }, { "name": "symfony/console", "version": "v5.3.10", diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php index eb067000..c554846f 100644 --- a/vendor/composer/installed.php +++ b/vendor/composer/installed.php @@ -6,7 +6,7 @@ 'aliases' => array ( ), - 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6', + 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd', 'name' => 'sammo-hid/sammo', ), 'versions' => @@ -427,7 +427,7 @@ 'aliases' => array ( ), - 'reference' => '872755e57f84720a9c4c63d5455441f83c41f6c6', + 'reference' => 'd75f21035d2d747010efd234b5e7b3a42e0a41fd', ), 'sergeytsalkov/meekrodb' => array ( @@ -438,6 +438,15 @@ ), 'reference' => 'e30c240d54bc81f58c58507a9ed768032eb494a5', ), + 'spatie/data-transfer-object' => + array ( + 'pretty_version' => '3.7.3', + 'version' => '3.7.3.0', + 'aliases' => + array ( + ), + 'reference' => '341f72c77e0fce40ea2e0dcb212cb54dc27bbe72', + ), 'symfony/console' => array ( 'pretty_version' => 'v5.3.10', diff --git a/vendor/composer/platform_check.php b/vendor/composer/platform_check.php index 580fa960..adfb472f 100644 --- a/vendor/composer/platform_check.php +++ b/vendor/composer/platform_check.php @@ -4,8 +4,8 @@ $issues = array(); -if (!(PHP_VERSION_ID >= 70400)) { - $issues[] = 'Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' . PHP_VERSION . '.'; +if (!(PHP_VERSION_ID >= 80000)) { + $issues[] = 'Your Composer dependencies require a PHP version ">= 8.0.0". You are running ' . PHP_VERSION . '.'; } if ($issues) { diff --git a/vendor/spatie/data-transfer-object/.github/CONTRIBUTING.md b/vendor/spatie/data-transfer-object/.github/CONTRIBUTING.md new file mode 100644 index 00000000..b4ae1c4a --- /dev/null +++ b/vendor/spatie/data-transfer-object/.github/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/vendor/spatie/data-transfer-object/.github/FUNDING.yml b/vendor/spatie/data-transfer-object/.github/FUNDING.yml new file mode 100644 index 00000000..fe5143b5 --- /dev/null +++ b/vendor/spatie/data-transfer-object/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: spatie +custom: https://spatie.be/open-source/support-us diff --git a/vendor/spatie/data-transfer-object/.github/workflows/style.yml b/vendor/spatie/data-transfer-object/.github/workflows/style.yml new file mode 100644 index 00000000..502dbe70 --- /dev/null +++ b/vendor/spatie/data-transfer-object/.github/workflows/style.yml @@ -0,0 +1,23 @@ +name: Check & fix styling + +on: [push] + +jobs: + php-cs-fixer: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + with: + ref: ${{ github.head_ref }} + + - name: Run PHP CS Fixer + uses: docker://oskarstark/php-cs-fixer-ga + with: + args: --config=.php-cs-fixer.dist.php --allow-risky=yes + + - name: Commit changes + uses: stefanzweifel/git-auto-commit-action@v4 + with: + commit_message: Fix styling diff --git a/vendor/spatie/data-transfer-object/.github/workflows/update-changelog.yml b/vendor/spatie/data-transfer-object/.github/workflows/update-changelog.yml new file mode 100644 index 00000000..fa56639f --- /dev/null +++ b/vendor/spatie/data-transfer-object/.github/workflows/update-changelog.yml @@ -0,0 +1,28 @@ +name: "Update Changelog" + +on: + release: + types: [released] + +jobs: + update: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + with: + ref: main + + - name: Update Changelog + uses: stefanzweifel/changelog-updater-action@v1 + with: + latest-version: ${{ github.event.release.name }} + release-notes: ${{ github.event.release.body }} + + - name: Commit updated CHANGELOG + uses: stefanzweifel/git-auto-commit-action@v4 + with: + branch: main + commit_message: Update CHANGELOG + file_pattern: CHANGELOG.md diff --git a/vendor/spatie/data-transfer-object/.php-cs-fixer.dist.php b/vendor/spatie/data-transfer-object/.php-cs-fixer.dist.php new file mode 100644 index 00000000..b9a6b55a --- /dev/null +++ b/vendor/spatie/data-transfer-object/.php-cs-fixer.dist.php @@ -0,0 +1,41 @@ +notPath('docs/*') + ->notPath('vendor') + ->in([ + __DIR__.'/src', + __DIR__.'/tests', + ]) + ->name('*.php') + ->ignoreDotFiles(true) + ->ignoreVCS(true); + +return (new PhpCsFixer\Config()) + ->setRules([ + '@PSR12' => true, + 'array_syntax' => ['syntax' => 'short'], + 'ordered_imports' => ['sort_algorithm' => 'alpha'], + 'no_unused_imports' => true, + 'not_operator_with_successor_space' => true, + 'trailing_comma_in_multiline' => true, + 'phpdoc_scalar' => true, + 'unary_operator_spaces' => true, + 'binary_operator_spaces' => true, + 'logical_operators' => true, + 'blank_line_before_statement' => [ + 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], + ], + 'phpdoc_single_line_var_spacing' => true, + 'phpdoc_var_without_name' => true, + 'class_attributes_separation' => [ + 'elements' => [ + 'method' => 'one' + ], + ], + 'method_argument_space' => [ + 'on_multiline' => 'ensure_fully_multiline', + 'keep_multiple_spaces_after_comma' => true, + ], + ]) + ->setFinder($finder); diff --git a/vendor/spatie/data-transfer-object/CHANGELOG.md b/vendor/spatie/data-transfer-object/CHANGELOG.md new file mode 100644 index 00000000..f498a85b --- /dev/null +++ b/vendor/spatie/data-transfer-object/CHANGELOG.md @@ -0,0 +1,248 @@ +# Changelog + +All notable changes to `data-transfer-object` will be documented in this file + +## 3.7.2 - 2021-09-17 + +- `#[Strict]` is passed down the inheritance chain so children are strict when parent is strict (#239) + +## 3.7.1 - 2021-09-09 + +- Cast properties with self or parent type (#236) + +## 3.7.0 - 2021-08-26 + +- Add `#[MapTo]` support (#233) + +## 3.6.2 - 2021-08-25 + +- Correct behavior of Arr::forget with dot keys (#231) + +## 3.6.1 - 2021-08-17 + +- Fix array assignment bug with strict dto's (#225) + +## 3.6.0 - 2021-08-12 + +- Support mapped properties (#224) + +## 3.5.0 - 2021-08-11 + +- Support union types in casters (#210) + +## 3.4.0 - 2021-08-10 + +- Fix for an empty value being created when casting `ArrayAccess` objects (#216) +- Add logic exception when attempting to cast `ArrayAccess` objects that are not traversable (#216) +- Allow the `ArrayCaster` to retain values that are already instances of the `itemType` (#217) + +## 3.3.0 - 2021-06-01 + +- Expose DTO and validation error array in ValidationException (#213) + +## 3.2.0 - 2021-05-31 + +- Support generic casters (#199) +- Add `ArrayCaster` +- Add casting of objects that implement `ArrayAccess` to the `ArrayCaster` (#206) +- Fix for caster subclass check (#204) + +## 3.1.1 - 2021-04-26 + +- Make `DefaultCast` repeatable (#202) + +## 3.1.0 - 2021-04-21 + +- Add `DataTransferObject::clone(...$args)` + +## 3.0.4 - 2021-04-14 + +- Support union types (#185) +- Resolve default cast from parent classes (#189) +- Support default values (#191) + +## 3.0.3 - 2021-04-08 + +- Fix when nested DTO have casted field (#178) + +## 3.0.2 - 2021-04-02 + +- Allow valid DTOs to be passed to caster (#177) + +## 3.0.1 - 2021-04-02 + +- Fix for null values with casters + +## 3.0.0 - 2021-04-02 + +This package now focuses only on object creation by adding easy-to-use casting and data validation functionality. All runtime type checks are gone in favour of the improved type system in PHP 8. + +- Require `php:^8.0` +- Removed all runtime type checking functionality, you should use typed properties and a static analysis tool like Psalm or PhpStan +- Removed `Spatie\DataTransferObject\DataTransferObjectCollection` +- Removed `Spatie\DataTransferObject\FlexibleDataTransferObject`, all DTOs are now considered flexible +- Removed runtime immutable DTOs, you should use static analysis instead +- Added `Spatie\DataTransferObject\Validator` +- Added `Spatie\DataTransferObject\Validation\ValidationResult` +- Added `#[DefaultCast]` +- Added `#[CastWith]` +- Added `Spatie\DataTransferObject\Caster` +- Added `#[Strict]` + +## 2.8.3 - 2021-02-12 + +- Add support for using `collection` internally + +## 2.8.2 - 2021-02-11 + +This might be a breaking change, but it was required for a bugfix + +- Prevent DataTransferObjectCollection from iterating over array copy (#166) + +## 2.8.1 - 2021-02-10 + +- Fix for incorrect return type (#164) + +## 2.8.0 - 2021-01-27 + +- Allow the traversal of collections with string keys + +## 2.7.0 - 2021-01-21 + +- Cast nested collections (#117) + +## 2.6.0 - 2020-11-26 + +- Support PHP 8 + +## 2.5.0 - 2020-08-28 + +- Group type errors (#130) + +## 2.4.0 - 2020-08-28 + +- Support for `array` syntax (#136) + +## 2.3.0 - 2020-08-19 + +- Add PHPStan extension to support `checkUninitializedProperties: true` (#135) + +## 2.2.1 - 2020-05-13 + +- Validator for typed 7.4 properties (#109) + +## 2.2.0 - 2020-05-08 + +- Add support for typed properties to DTO casting in PHP 7.4 + +## 2.0.0 - 2020-04-28 + +- Bump minimum required PHP version to 7.4 +- Support for nested immutable DTOs (#86) + +## 1.13.3 - 2020-01-29 + +- Ignore static properties when serializing (#88) + +## 1.13.2 - 2020-01-08 + +- DataTransferObjectError::invalidType : get actual type before mutating $value for the error message (#81) + +## 1.13.1 - 2020-01-08 + +- Improve extendability of DTOs (#80) + +## 1.13.0 - 2020-01-08 + +- Ignore static properties (#82) +- Add `DataTransferObject::arrayOf` (#83) + +## 1.12.0 - 2019-12-19 + +- Improved performance by adding a cache (#79) +- Add `FlexibleDataTransferObject` which allows for unknown properties to be ignored + +## 1.11.0 - 2019-11-28 (#71) + +- Add `iterable` and `iterable<\Type>` support + +## 1.10.0 - 2019-10-16 + +- Allow a DTO to be constructed without an array (#68) + +## 1.9.1 - 2019-10-03 + +- Improve type error message + +## 1.9.0 - 2019-08-30 + +- Add DataTransferObjectCollection::items() + +## 1.8.0 - 2019-03-18 + +- Support immutability + +## 1.7.1 - 2019-02-11 + +- Fixes #47, allowing empty dto's to be cast to using an empty array. + +## 1.7.0 - 2019-02-04 + +- Nested array DTO casting supported. + +## 1.6.6 - 2018-12-04 + +- Properly support `float`. + +## 1.6.5 - 2018-11-20 + +- Fix uninitialised error with default value. + +## 1.6.4 - 2018-11-15 + +- Don't use `allValues` anymore. + +## 1.6.3 - 2018-11-14 + +- Support nested collections in collections +- Cleanup code + +## 1.6.2 - 2018-11-14 + +- Remove too much magic in nested array casting + +## 1.6.1 - 2018-11-14 + +- Support nested `toArray` in collections. + +## 1.6.0 - 2018-11-14 + +- Support nested `toArray`. + +## 1.5.1 - 2018-11-07 + +- Add strict type declarations + +## 1.5.0 - 2018-11-07 + +- Add auto casting of nested DTOs + +## 1.4.0 - 2018-11-05 + +- Rename to data-transfer-object + +## 1.2.0 - 2018-10-30 + +- Add uninitialized errors. + +## 1.1.1 - 2018-10-25 + +- Support instanceof on interfaces when type checking + +## 1.1.0 - 2018-10-24 + +- proper support for collections of value objects + +## 1.0.0 - 2018-10-24 + +- initial release diff --git a/vendor/spatie/data-transfer-object/LICENSE.md b/vendor/spatie/data-transfer-object/LICENSE.md new file mode 100644 index 00000000..59e5ec59 --- /dev/null +++ b/vendor/spatie/data-transfer-object/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Spatie bvba + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/spatie/data-transfer-object/README.md b/vendor/spatie/data-transfer-object/README.md new file mode 100644 index 00000000..e43ee4b6 --- /dev/null +++ b/vendor/spatie/data-transfer-object/README.md @@ -0,0 +1,504 @@ +# Data transfer objects with batteries included + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/data-transfer-object.svg?style=flat-square)](https://packagist.org/packages/spatie/data-transfer-object) +![Test](https://github.com/spatie/data-transfer-object/workflows/Test/badge.svg) +[![Total Downloads](https://img.shields.io/packagist/dt/spatie/data-transfer-object.svg?style=flat-square)](https://packagist.org/packages/spatie/data-transfer-object) + +## Installation + +You can install the package via composer: + +```bash +composer require spatie/data-transfer-object +``` + +* **Note**: v3 of this package only supports `php:^8.0`. If you're looking for the older version, check out [v2](https://github.com/spatie/data-transfer-object/tree/v2). + +## Support us + +[](https://spatie.be/github-ad-click/data-transfer-object) + +We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). + +We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). + +## Usage + +The goal of this package is to make constructing objects from arrays of (serialized) data as easy as possible. Here's what a DTO looks like: + +```php +use Spatie\DataTransferObject\DataTransferObject; + +class MyDTO extends DataTransferObject +{ + public OtherDTO $otherDTO; + + public OtherDTOCollection $collection; + + #[CastWith(ComplexObjectCaster::class)] + public ComplexObject $complexObject; + + public ComplexObjectWithCast $complexObjectWithCast; + + #[NumberBetween(1, 100)] + public int $a; + + #[MapFrom('address.city')] + public string $city; +} +``` + +You could construct this DTO like so: + +```php +$dto = new MyDTO( + a: 5, + collection: [ + ['id' => 1], + ['id' => 2], + ['id' => 3], + ], + complexObject: [ + 'name' => 'test', + ], + complexObjectWithCast: [ + 'name' => 'test', + ], + otherDTO: ['id' => 5], +); +``` + +Let's discuss all possibilities one by one. + +## Named arguments + +Constructing a DTO can be done with named arguments. It's also possible to still use the old array notation. This example is equivalent to the one above. + +```php +$dto = new MyDTO([ + 'a' => 5, + 'collection' => [ + ['id' => 1], + ['id' => 2], + ['id' => 3], + ], + 'complexObject' => [ + 'name' => 'test', + ], + 'complexObjectWithCast' => [ + 'name' => 'test', + ], + 'otherDTO' => ['id' => 5], +]); +``` + +## Value casts + +If a DTO has a property that is another DTO or a DTO collection, the package will take care of automatically casting arrays of data to those DTOs: + +```php +$dto = new MyDTO( + collection: [ // This will become an object of class OtherDTOCollection + ['id' => 1], + ['id' => 2], // Each item will be an instance of OtherDTO + ['id' => 3], + ], + otherDTO: ['id' => 5], // This data will be cast to OtherDTO +); +``` + +### Custom casters + +You can build your own caster classes, which will take whatever input they are given, and will cast that input to the desired result. + +Take a look at the `ComplexObject`: + +```php +class ComplexObject +{ + public string $name; +} +``` + +And its caster `ComplexObjectCaster`: + +```php +use Spatie\DataTransferObject\Caster; + +class ComplexObjectCaster implements Caster +{ + /** + * @param array|mixed $value + * + * @return mixed + */ + public function cast(mixed $value): ComplexObject + { + return new ComplexObject( + name: $value['name'] + ); + } +} +``` + +### Class-specific casters + +Instead of specifying which caster should be used for each property, you can also define that caster on the target class itself: + +```php +class MyDTO extends DataTransferObject +{ + public ComplexObjectWithCast $complexObjectWithCast; +} +``` + +```php +#[CastWith(ComplexObjectWithCastCaster::class)] +class ComplexObjectWithCast +{ + public string $name; +} +``` + +### Default casters + +It's possible to define default casters on a DTO class itself. These casters will be used whenever a property with a given type is encountered within the DTO class. + +```php +#[ + DefaultCast(DateTimeImmutable::class, DateTimeImmutableCaster::class), + DefaultCast(MyEnum::class, EnumCaster::class), +] +abstract class BaseDataTransferObject extends DataTransferObject +{ + public MyEnum $status; // EnumCaster will be used + + public DateTimeImmutable $date; // DateTimeImmutableCaster will be used +} +``` + +### Using custom caster arguments + +Any caster can be passed custom arguments, the built-in [`ArrayCaster` implementation](https://github.com/spatie/data-transfer-object/blob/master/src/Casters/ArrayCaster.php) is a good example of how this may be used. + +Using named arguments when passing input to your caster will help make your code more clear, but they are not required. + +For example: + +```php + /** @var \Spatie\DataTransferObject\Tests\Foo[] */ + #[CastWith(ArrayCaster::class, itemType: Foo::class)] + public array $collectionWithNamedArguments; + + /** @var \Spatie\DataTransferObject\Tests\Foo[] */ + #[CastWith(ArrayCaster::class, Foo::class)] + public array $collectionWithoutNamedArguments; +``` + +Note that the first argument passed to the caster constructor is always the array with type(s) of the value being casted. +All other arguments will be the ones passed as extra arguments in the `CastWith` attribute. + +## Validation + +This package doesn't offer any specific validation functionality, but it does give you a way to build your own validation attributes. For example, `NumberBetween` is a user-implemented validation attribute: + +```php +class MyDTO extends DataTransferObject +{ + #[NumberBetween(1, 100)] + public int $a; +} +``` + +It works like this under the hood: + +```php +#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)] +class NumberBetween implements Validator +{ + public function __construct( + private int $min, + private int $max + ) { + } + + public function validate(mixed $value): ValidationResult + { + if ($value < $this->min) { + return ValidationResult::invalid("Value should be greater than or equal to {$this->min}"); + } + + if ($value > $this->max) { + return ValidationResult::invalid("Value should be less than or equal to {$this->max}"); + } + + return ValidationResult::valid(); + } +} +``` + +## Mapping + +You can map a DTO property from a source property with a different name using the `#[MapFrom]` attribute. + +It works with a "dot" notation property name or an index. + +```php +class PostDTO extends DataTransferObject +{ + #[MapFrom('postTitle')] + public string $title; + + #[MapFrom('user.name')] + public string $author; +} + +$dto = new PostDTO([ + 'postTitle' => 'Hello world', + 'user' => [ + 'name' => 'John Doe' + ] +]); +``` + +```php +class UserDTO extends DataTransferObject +{ + + #[MapFrom(0)] + public string $firstName; + + #[MapFrom(1)] + public string $lastName; +} + +$dto = new UserDTO(['John', 'Doe']); +``` + +Sometimes you also want to map them during the transformation to Array. +A typical usecase would be transformation from camel case to snake case. +For that you can use the `#[MapTo]` attribute. + +```php +class UserDTO extends DataTransferObject +{ + + #[MapFrom(0)] + #[MapTo('first_name')] + public string $firstName; + + #[MapFrom(1)] + #[MapTo('last_name')] + public string $lastName; +} + +$dto = new UserDTO(['John', 'Doe']); +$dto->toArray() // ['first_name' => 'John', 'last_name'=> 'Doe']; +$dto->only('first_name')->toArray() // ['first_name' => 'John']; +``` + +## Strict DTOs + +The previous version of this package added the `FlexibleDataTransferObject` class which allowed you to ignore properties that didn't exist on the DTO. This behaviour has been changed, all DTOs are flexible now by default, but you can make them strict by using the `#[Strict]` attribute: + + +```php +class NonStrictDto extends DataTransferObject +{ + public string $name; +} + +// This works +new NonStrictDto( + name: 'name', + unknown: 'unknown' +); +``` + +```php +use \Spatie\DataTransferObject\Attributes\Strict; + +#[Strict] +class StrictDto extends DataTransferObject +{ + public string $name; +} + +// This throws a \Spatie\DataTransferObject\Exceptions\UnknownProperties exception +new StrictDto( + name: 'name', + unknown: 'unknown' +); +``` + +## Helper functions + +There are also some helper functions provided for working with multiple properties at once. + +```php +$postData->all(); + +$postData + ->only('title', 'body') + ->toArray(); + +$postData + ->except('author') + ->toArray(); +``` + +Note that `all()` will simply return all properties, while `toArray()` will cast nested DTOs to arrays as well. + +You can chain the `except()` and `only()` methods: + +```php +$postData + ->except('title') + ->except('body') + ->toArray(); +``` + +It's important to note that `except()` and `only()` are immutable, they won't change the original data transfer object. + +## Immutable DTOs and cloning + +This package doesn't force immutable objects since PHP doesn't support them, but you're always encouraged to keep your DTOs immutable. To help you, there's a `clone` method on every DTO which accepts data to override: + +```php +$clone = $original->clone(other: ['name' => 'a']); +``` + +Note that no data in `$original` is changed. + +## Collections of DTOs + +This version removes the `DataTransferObjectCollection` class. Instead you can use simple casters and your own collection classes. + +Here's an example of casting a collection of DTOs to an array of DTOs: + +```php +class Bar extends DataTransferObject +{ + /** @var \Spatie\DataTransferObject\Tests\Foo[] */ + #[CastWith(FooArrayCaster::class)] + public array $collectionOfFoo; +} + +class Foo extends DataTransferObject +{ + public string $name; +} +``` + +```php +class FooArrayCaster implements Caster +{ + public function cast(mixed $value): array + { + if (! is_array($value)) { + throw new Exception("Can only cast arrays to Foo"); + } + + return array_map( + fn (array $data) => new Foo(...$data), + $value + ); + } +} +``` + +If you don't want the redundant typehint, or want extended collection functionality; you could create your own collection classes using any collection implementation. In this example, we use Laravel's: + +```php +class Bar extends DataTransferObject +{ + #[CastWith(FooCollectionCaster::class)] + public CollectionOfFoo $collectionOfFoo; +} + +class Foo extends DataTransferObject +{ + public string $name; +} +``` + +```php +use Illuminate\Support\Collection; + +class CollectionOfFoo extends Collection +{ + // Add the correct return type here for static analyzers to know which type of array this is + public function offsetGet($key): Foo + { + return parent::offsetGet($key); + } +} +``` + +```php +class FooCollectionCaster implements Caster +{ + public function cast(mixed $value): CollectionOfFoo + { + return new CollectionOfFoo(array_map( + fn (array $data) => new Foo(...$data), + $value + )); + } +} +``` + +## Simple arrays of DTOs + +For a simple array of DTOs, or an object that implements PHP's built-in `ArrayAccess`, consider using the `ArrayCaster` which requires an item type to be provided: + +```php +class Bar extends DataTransferObject +{ + /** @var \Spatie\DataTransferObject\Tests\Foo[] */ + #[CastWith(ArrayCaster::class, itemType: Foo::class)] + public array $collectionOfFoo; +} +``` + +## Testing + +``` bash +composer test +``` + +### Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. + +## Contributing + +Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details. + +### Security + +If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker. + +## Postcardware + +You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. + +Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium. + +We publish all received postcards [on our company website](https://spatie.be/en/opensource/postcards). + +## External tools + +- [json2dto](https://json2dto.atymic.dev): a GUI to convert JSON objects to DTO classes (with nesting support). Also provides a [CLI tool](https://github.com/atymic/json2dto#cli-tool) for local usage. +- [Data Transfer Object Factory](https://github.com/anteris-dev/data-transfer-object-factory): Intelligently generates a DTO instance using the correct content for your properties based on its name and type. + +## Credits + +- [Brent Roose](https://github.com/brendt) +- [All Contributors](../../contributors) + +Our `Arr` class contains functions copied from Laravels `Arr` helper. + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/vendor/spatie/data-transfer-object/composer.json b/vendor/spatie/data-transfer-object/composer.json new file mode 100644 index 00000000..2bf0b517 --- /dev/null +++ b/vendor/spatie/data-transfer-object/composer.json @@ -0,0 +1,44 @@ +{ + "name": "spatie/data-transfer-object", + "description": "Data transfer objects with batteries included", + "keywords": [ + "spatie", + "data-transfer-object" + ], + "homepage": "https://github.com/spatie/data-transfer-object", + "license": "MIT", + "authors": [ + { + "name": "Brent Roose", + "email": "brent@spatie.be", + "homepage": "https://spatie.be", + "role": "Developer" + } + ], + "require": { + "php": "^8.0" + }, + "require-dev": { + "illuminate/collections": "^8.36", + "larapack/dd": "^1.1", + "phpunit/phpunit": "^9.0", + "jetbrains/phpstorm-attributes": "^1.0" + }, + "autoload": { + "psr-4": { + "Spatie\\DataTransferObject\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "Spatie\\DataTransferObject\\Tests\\": "tests" + } + }, + "scripts": { + "test": "vendor/bin/phpunit", + "test-coverage": "vendor/bin/phpunit --coverage-html coverage" + }, + "config": { + "sort-packages": true + } +} diff --git a/vendor/spatie/data-transfer-object/src/Arr.php b/vendor/spatie/data-transfer-object/src/Arr.php new file mode 100644 index 00000000..e3eb70ce --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Arr.php @@ -0,0 +1,98 @@ +offsetExists($key); + } + + return array_key_exists($key, $array); + } +} diff --git a/vendor/spatie/data-transfer-object/src/Attributes/CastWith.php b/vendor/spatie/data-transfer-object/src/Attributes/CastWith.php new file mode 100644 index 00000000..5fc46852 --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Attributes/CastWith.php @@ -0,0 +1,24 @@ +casterClass, Caster::class)) { + throw new InvalidCasterClass($this->casterClass); + } + + $this->args = $args; + } +} diff --git a/vendor/spatie/data-transfer-object/src/Attributes/DefaultCast.php b/vendor/spatie/data-transfer-object/src/Attributes/DefaultCast.php new file mode 100644 index 00000000..47cc76a9 --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Attributes/DefaultCast.php @@ -0,0 +1,53 @@ +getType(); + + /** @var \ReflectionNamedType[]|null $types */ + $types = match ($type::class) { + ReflectionNamedType::class => [$type], + ReflectionUnionType::class => $type->getTypes(), + default => null, + }; + + if (! $types) { + return false; + } + + foreach ($types as $type) { + if ($type->getName() !== $this->targetClass) { + continue; + } + + return true; + } + + return false; + } + + public function resolveCaster(): Caster + { + return new $this->casterClass(); + } +} diff --git a/vendor/spatie/data-transfer-object/src/Attributes/MapFrom.php b/vendor/spatie/data-transfer-object/src/Attributes/MapFrom.php new file mode 100644 index 00000000..96298b41 --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Attributes/MapFrom.php @@ -0,0 +1,14 @@ +types as $type) { + if ($type == 'array') { + return $this->mapInto( + destination: [], + items: $value + ); + } + + if (is_subclass_of($type, ArrayAccess::class)) { + return $this->mapInto( + destination: new $type(), + items: $value + ); + } + } + + throw new LogicException( + "Caster [ArrayCaster] may only be used to cast arrays or objects that implement ArrayAccess." + ); + } + + private function mapInto(array | ArrayAccess $destination, mixed $items): array | ArrayAccess + { + if ($destination instanceof ArrayAccess && ! is_subclass_of($destination, Traversable::class)) { + throw new LogicException( + "Caster [ArrayCaster] may only be used to cast ArrayAccess objects that are traversable." + ); + } + + foreach ($items as $key => $item) { + $destination[$key] = $this->castItem($item); + } + + return $destination; + } + + private function castItem(mixed $data) + { + if ($data instanceof $this->itemType) { + return $data; + } + + if (is_array($data)) { + return new $this->itemType(...$data); + } + + throw new LogicException( + "Caster [ArrayCaster] each item must be an array or an instance of the specified item type [{$this->itemType}]." + ); + } +} diff --git a/vendor/spatie/data-transfer-object/src/Casters/DataTransferObjectCaster.php b/vendor/spatie/data-transfer-object/src/Casters/DataTransferObjectCaster.php new file mode 100644 index 00000000..4f1913e9 --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Casters/DataTransferObjectCaster.php @@ -0,0 +1,25 @@ +classNames as $className) { + if ($value instanceof $className) { + return $value; + } + } + + return new $this->classNames[0](...$value); + } +} diff --git a/vendor/spatie/data-transfer-object/src/DataTransferObject.php b/vendor/spatie/data-transfer-object/src/DataTransferObject.php new file mode 100644 index 00000000..d1ecefff --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/DataTransferObject.php @@ -0,0 +1,125 @@ +getProperties() as $property) { + $property->setValue(Arr::get($args, $property->name) ?? $this->{$property->name} ?? null); + + $args = Arr::forget($args, $property->name); + } + + if ($class->isStrict() && count($args)) { + throw UnknownProperties::new(static::class, array_keys($args)); + } + + $class->validate(); + } + + public static function arrayOf(array $arrayOfParameters): array + { + return array_map( + fn (mixed $parameters) => new static($parameters), + $arrayOfParameters + ); + } + + public function all(): array + { + $data = []; + + $class = new ReflectionClass(static::class); + + $properties = $class->getProperties(ReflectionProperty::IS_PUBLIC); + + foreach ($properties as $property) { + if ($property->isStatic()) { + continue; + } + + $mapToAttribute = $property->getAttributes(MapTo::class); + $name = count($mapToAttribute) ? $mapToAttribute[0]->newInstance()->name : $property->getName(); + + $data[$name] = $property->getValue($this); + } + + return $data; + } + + public function only(string ...$keys): static + { + $dataTransferObject = clone $this; + + $dataTransferObject->onlyKeys = [...$this->onlyKeys, ...$keys]; + + return $dataTransferObject; + } + + public function except(string ...$keys): static + { + $dataTransferObject = clone $this; + + $dataTransferObject->exceptKeys = [...$this->exceptKeys, ...$keys]; + + return $dataTransferObject; + } + + public function clone(...$args): static + { + return new static(...array_merge($this->toArray(), $args)); + } + + public function toArray(): array + { + if (count($this->onlyKeys)) { + $array = Arr::only($this->all(), $this->onlyKeys); + } else { + $array = Arr::except($this->all(), $this->exceptKeys); + } + + $array = $this->parseArray($array); + + return $array; + } + + protected function parseArray(array $array): array + { + foreach ($array as $key => $value) { + if ($value instanceof DataTransferObject) { + $array[$key] = $value->toArray(); + + continue; + } + + if (! is_array($value)) { + continue; + } + + $array[$key] = $this->parseArray($value); + } + + return $array; + } +} diff --git a/vendor/spatie/data-transfer-object/src/Exceptions/InvalidCasterClass.php b/vendor/spatie/data-transfer-object/src/Exceptions/InvalidCasterClass.php new file mode 100644 index 00000000..7efebf41 --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Exceptions/InvalidCasterClass.php @@ -0,0 +1,18 @@ + $errorsForField) { + /** @var \Spatie\DataTransferObject\Validation\ValidationResult $errorForField */ + foreach ($errorsForField as $errorForField) { + $messages[] = "\t - `{$className}->{$fieldName}`: {$errorForField->message}"; + } + } + + parent::__construct("Validation errors:" . PHP_EOL . implode(PHP_EOL, $messages)); + } +} diff --git a/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectClass.php b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectClass.php new file mode 100644 index 00000000..dd35f859 --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectClass.php @@ -0,0 +1,84 @@ +reflectionClass = new ReflectionClass($dataTransferObject); + $this->dataTransferObject = $dataTransferObject; + } + + /** + * @return \Spatie\DataTransferObject\Reflection\DataTransferObjectProperty[] + */ + public function getProperties(): array + { + $publicProperties = array_filter( + $this->reflectionClass->getProperties(ReflectionProperty::IS_PUBLIC), + fn (ReflectionProperty $property) => ! $property->isStatic() + ); + + return array_map( + fn (ReflectionProperty $property) => new DataTransferObjectProperty( + $this->dataTransferObject, + $property + ), + $publicProperties + ); + } + + public function validate(): void + { + $validationErrors = []; + + foreach ($this->getProperties() as $property) { + $validators = $property->getValidators(); + + foreach ($validators as $validator) { + $result = $validator->validate($property->getValue()); + + if ($result->isValid) { + continue; + } + + $validationErrors[$property->name][] = $result; + } + } + + if (count($validationErrors)) { + throw new ValidationException($this->dataTransferObject, $validationErrors); + } + } + + public function isStrict(): bool + { + if (! isset($this->isStrict)) { + $attribute = null; + + $reflectionClass = $this->reflectionClass; + while ($attribute === null && $reflectionClass !== false) { + $attribute = $reflectionClass->getAttributes(Strict::class)[0] ?? null; + + $reflectionClass = $reflectionClass->getParentClass(); + } + + $this->isStrict = $attribute !== null; + } + + return $this->isStrict; + } +} diff --git a/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php new file mode 100644 index 00000000..abdf313d --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Reflection/DataTransferObjectProperty.php @@ -0,0 +1,182 @@ +dataTransferObject = $dataTransferObject; + $this->reflectionProperty = $reflectionProperty; + + $this->name = $this->resolveMappedProperty(); + + $this->caster = $this->resolveCaster(); + } + + public function setValue(mixed $value): void + { + if ($this->caster && $value !== null) { + $value = $this->caster->cast($value); + } + + $this->reflectionProperty->setValue($this->dataTransferObject, $value); + } + + /** + * @return \Spatie\DataTransferObject\Validator[] + */ + public function getValidators(): array + { + $attributes = $this->reflectionProperty->getAttributes( + Validator::class, + ReflectionAttribute::IS_INSTANCEOF + ); + + return array_map( + fn (ReflectionAttribute $attribute) => $attribute->newInstance(), + $attributes + ); + } + + public function getValue(): mixed + { + return $this->reflectionProperty->getValue($this->dataTransferObject); + } + + private function resolveCaster(): ?Caster + { + $attributes = $this->reflectionProperty->getAttributes(CastWith::class); + + if (! count($attributes)) { + $attributes = $this->resolveCasterFromType(); + } + + if (! count($attributes)) { + return $this->resolveCasterFromDefaults(); + } + + /** @var \Spatie\DataTransferObject\Attributes\CastWith $attribute */ + $attribute = $attributes[0]->newInstance(); + + return new $attribute->casterClass( + array_map(fn ($type) => $this->resolveTypeName($type), $this->extractTypes()), + ...$attribute->args + ); + } + + private function resolveCasterFromType(): array + { + foreach ($this->extractTypes() as $type) { + $name = $this->resolveTypeName($type); + + if (! class_exists($name)) { + continue; + } + + $reflectionClass = new ReflectionClass($name); + + do { + $attributes = $reflectionClass->getAttributes(CastWith::class); + + $reflectionClass = $reflectionClass->getParentClass(); + } while (! count($attributes) && $reflectionClass); + + if (count($attributes) > 0) { + return $attributes; + } + } + + return []; + } + + private function resolveCasterFromDefaults(): ?Caster + { + $defaultCastAttributes = []; + + $class = $this->reflectionProperty->getDeclaringClass(); + + do { + array_push($defaultCastAttributes, ...$class->getAttributes(DefaultCast::class)); + + $class = $class->getParentClass(); + } while ($class !== false); + + if (! count($defaultCastAttributes)) { + return null; + } + + foreach ($defaultCastAttributes as $defaultCastAttribute) { + /** @var \Spatie\DataTransferObject\Attributes\DefaultCast $defaultCast */ + $defaultCast = $defaultCastAttribute->newInstance(); + + if ($defaultCast->accepts($this->reflectionProperty)) { + return $defaultCast->resolveCaster(); + } + } + + return null; + } + + private function resolveMappedProperty(): string | int + { + $attributes = $this->reflectionProperty->getAttributes(MapFrom::class); + + if (! count($attributes)) { + return $this->reflectionProperty->name; + } + + return $attributes[0]->newInstance()->name; + } + + /** + * @return ReflectionNamedType[] + */ + private function extractTypes(): array + { + $type = $this->reflectionProperty->getType(); + + if (! $type) { + return []; + } + + return match ($type::class) { + ReflectionNamedType::class => [$type], + ReflectionUnionType::class => $type->getTypes(), + }; + } + + private function resolveTypeName(ReflectionType $type): string + { + return match ($type->getName()) { + 'self' => $this->dataTransferObject::class, + 'parent' => get_parent_class($this->dataTransferObject), + default => $type->getName(), + }; + } +} diff --git a/vendor/spatie/data-transfer-object/src/Validation/ValidationResult.php b/vendor/spatie/data-transfer-object/src/Validation/ValidationResult.php new file mode 100644 index 00000000..43d2eea3 --- /dev/null +++ b/vendor/spatie/data-transfer-object/src/Validation/ValidationResult.php @@ -0,0 +1,31 @@ + Date: Mon, 24 Jan 2022 03:22:57 +0900 Subject: [PATCH 03/44] =?UTF-8?q?feat(WIP):=20=EB=B2=A0=ED=8C=85=20?= =?UTF-8?q?=EA=B4=80=EB=A0=A8=20=EC=9E=91=EC=97=85=EC=A4=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/NationBetting/BetNation.php | 141 ++++++++++++++++++ .../API/NationBetting/GetBettingList.php | 70 +++++++++ hwe/sammo/DTO/BettingItem.php | 23 +++ hwe/sammo/DTO/NationBettingInfo.php | 36 +++++ hwe/v_nationBetting.php | 39 +++++ 5 files changed, 309 insertions(+) create mode 100644 hwe/sammo/API/NationBetting/BetNation.php create mode 100644 hwe/sammo/API/NationBetting/GetBettingList.php create mode 100644 hwe/sammo/DTO/BettingItem.php create mode 100644 hwe/sammo/DTO/NationBettingInfo.php create mode 100644 hwe/v_nationBetting.php diff --git a/hwe/sammo/API/NationBetting/BetNation.php b/hwe/sammo/API/NationBetting/BetNation.php new file mode 100644 index 00000000..e3bf85b4 --- /dev/null +++ b/hwe/sammo/API/NationBetting/BetNation.php @@ -0,0 +1,141 @@ +args); + $v->rule('required', [ + 'betting_id', + 'betting_type', + 'amount' + ]) + ->rule('integer', 'betting_id') + ->rule('integerArray', 'betting_type') + ->rule('integer', 'amount') + ->rule('min', 'amount', 1); + + if (!$v->validate()) { + return $v->errorStr(); + } + return null; + } + + public function getRequiredSessionMode(): int + { + return static::REQ_GAME_LOGIN | static::REQ_READ_ONLY; + } + + public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag) + { + $db = DB::db(); + + /** @var int */ + $bettingID = $this->arg['betting_id']; + /** @var int[] */ + $bettingType = $this->arg['betting_type']; + /** @var int[] */ + $amount = $this->args['amount']; + + $gameStor = KVStorage::getStorage($db, 'game_env'); + $nationBettingStor = KVStorage::getStorage($db, 'nation_betting'); + $rawBettingInfo = $nationBettingStor->getValue("id_{$bettingID}"); + if($rawBettingInfo === null){ + return '해당 베팅이 없습니다'; + } + + try{ + $bettingInfo = new NationBettingInfo($rawBettingInfo); + } + catch(\Error $e){ + return $e->getMessage(); + } + + if($bettingInfo->finished){ + return '이미 종료된 베팅입니다'; + } + + [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); + $yearMonth = Util::joinYearMonth($year, $month); + + + if($bettingInfo->closeYearMonth > $yearMonth){ + return '이미 마감된 베팅입니다'; + } + + if($bettingInfo->openYearMonth > $yearMonth){ + return '아직 시작되지 않은 베팅입니다'; + } + + if(count($bettingType) != $bettingInfo->selectCnt){ + return '필요한 선택 수를 채우지 못했습니다.'; + } + + + sort($bettingType);//NOTE: key로 바로 사용하므로 중요함 + $bettingTypeKey = Json::encode($bettingType); + $nations = getAllNationStaticInfo(); + + foreach($bettingType as $bettingNationID){ + if(!key_exists($bettingNationID, $nations)){ + return '존재하지 않는 국가를 선택했습니다.'; + } + } + + $general = General::createGeneralObjFromDB($session->generalID, ['gold', 'aux'], 1); + + if($bettingInfo->reqInheritancePoint){ + if($general->getInheritancePoint('previous') < $amount){ + return '유산포인트가 충분하지 않습니다.'; + } + } + else { + if($general->getVar('gold') < GameConst::$generalMinimumGold + $amount){ + return '금이 부족합니다.'; + } + } + + $userID = $session->userID; + + $bettingItem = new BettingItem([ + 'betting_id'=>$bettingID, + 'general_id'=>$session->generalID, + 'user_id'=>$userID, + 'betting_type'=>$bettingTypeKey, + 'amount'=>$amount + ]); + + if($bettingInfo->reqInheritancePoint){ + $general->increaseInheritancePoint('previous', -$amount); + } + else{ + $general->increaseVar('gold', -$amount); + } + $db->insert('ng_betting', $bettingItem->toArray()); + if(!$db->affected_rows){ + $general->flushUpdateValues(); + return '베팅을 실패했습니다.'; + } + $general->applyDB($db); + + return [ + 'result'=>true + ]; + } +} diff --git a/hwe/sammo/API/NationBetting/GetBettingList.php b/hwe/sammo/API/NationBetting/GetBettingList.php new file mode 100644 index 00000000..efb400d1 --- /dev/null +++ b/hwe/sammo/API/NationBetting/GetBettingList.php @@ -0,0 +1,70 @@ +userID; + + $me = $db->queryFirstRow('SELECT no,nation,officer_level,con,turntime,belong,penalty,permission FROM general WHERE owner=%i', $userID); + $con = checkLimit($me['con']); + if ($con >= 2) { + return "접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다. (다음 갱신 가능 시각 : {$me['turntime']})"; + } + + $bettingList = []; + foreach ($nationBettingStor->getAll() as $_key => $rawItem) { + $item = new NationBettingInfo($rawItem); + $bettingList[$item->id] = $rawItem; + $bettingList[$item->id]['totalAmount'] = 0; + } + + $bettingIDList = array_keys($bettingList); + // XXX: query cache만 믿고 sum을 하는 짓을 벌여도 되는가? + foreach ($db->queryAllLists( + 'SELECT betting_id, sum(amount) as total_amount FROM ng_betting WHERE betting_id IN %li GROUP BY betting_id', + $bettingIDList + ) as [$bettingID, $totalAmount]) { + if (!key_exists($bettingID, $bettingList)) { + continue; + } + $bettingList[$bettingID]['totalAmount'] = $totalAmount; + } + + [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); + + return [ + 'result' => false, + 'bettingList' => $bettingList, + 'year' => $year, + 'month' => $month, + ]; + } +} diff --git a/hwe/sammo/DTO/BettingItem.php b/hwe/sammo/DTO/BettingItem.php new file mode 100644 index 00000000..c37d8290 --- /dev/null +++ b/hwe/sammo/DTO/BettingItem.php @@ -0,0 +1,23 @@ +setReadOnly(); +$userID = Session::getUserID(); + +$db = DB::db(); +$gameStor = KVStorage::getStorage($db, 'game_env'); + +$generalID = $session->generalID; +?> + + + + + + + + <?= UniqueConst::$serverName ?>: 내무부 + [ + + ] + ], false) ?> + + + + + + + +
+ + + \ No newline at end of file -- 2.54.0 From 67a25e1ba21c1576848bf957d4fb2fd3bcfa4754 Mon Sep 17 00:00:00 2001 From: hide_d Date: Mon, 24 Jan 2022 05:40:38 +0900 Subject: [PATCH 04/44] =?UTF-8?q?feat:=20Global/GetNationList=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80=20-=20=EC=84=B8=EB=A0=A5=EC=9D=BC=EB=9E=8C=EC=9D=98?= =?UTF-8?q?=20=EB=8D=B0=EC=9D=B4=ED=84=B0=EC=99=80=20=EC=9B=90=EC=B9=99?= =?UTF-8?q?=EC=A0=81=EC=9C=BC=EB=A1=9C=20=EB=8F=99=EC=9D=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Global/GetNationList.php | 65 ++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 hwe/sammo/API/Global/GetNationList.php diff --git a/hwe/sammo/API/Global/GetNationList.php b/hwe/sammo/API/Global/GetNationList.php new file mode 100644 index 00000000..f3bd80aa --- /dev/null +++ b/hwe/sammo/API/Global/GetNationList.php @@ -0,0 +1,65 @@ + $lhs['power']; + }); + + $nations[0] = getNationStaticInfo(0); + + foreach ($db->query('SELECT npc,name,nation,officer_level,permission FROM `general` ORDER BY dedication DESC') as $general) { + $nationID = $general['nation']; + + $permission = $general['permission']; + if($permission != 'auditor' && $permission != 'ambassador'){ + unset($general['permission']); + } + + if($general['officer_level'] < 5){ + $general['officer_level'] = 1; + } + + if (!key_exists('generals', $nations[$nationID])) { + $nations[$nationID]['generals'] = []; + } + $nations[$nationID]['generals'][] = $general; + } + + foreach ($db->queryAllLists('SELECT city, name, nation FROM city') as [$cityID, $cityName, $nationID]) { + if (!key_exists('cities', $nations[$nationID])) { + $nations[$nationID]['cities'] = []; + } + $nations[$nationID]['cities'][$cityID] = $cityName; + } + + return [ + 'result' => true, + 'nations' => $nations, + ]; + } +} -- 2.54.0 From 2d645274cb401b79caaeaa1f5966a5320e19cc18 Mon Sep 17 00:00:00 2001 From: hide_d Date: Mon, 24 Jan 2022 05:41:24 +0900 Subject: [PATCH 05/44] =?UTF-8?q?feat(WIP):=20=EB=B2=A0=ED=8C=85=20?= =?UTF-8?q?=EC=83=81=EC=84=B8=20=EC=A0=95=EB=B3=B4=20=EB=B0=98=ED=99=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/NationBetting/BetNation.php | 6 +- .../API/NationBetting/GetBettingDetail.php | 98 +++++++++++++++++++ .../API/NationBetting/GetBettingList.php | 4 +- 3 files changed, 103 insertions(+), 5 deletions(-) create mode 100644 hwe/sammo/API/NationBetting/GetBettingDetail.php diff --git a/hwe/sammo/API/NationBetting/BetNation.php b/hwe/sammo/API/NationBetting/BetNation.php index e3bf85b4..40f3b6f4 100644 --- a/hwe/sammo/API/NationBetting/BetNation.php +++ b/hwe/sammo/API/NationBetting/BetNation.php @@ -1,6 +1,6 @@ increaseVar('gold', -$amount); } - $db->insert('ng_betting', $bettingItem->toArray()); + $db->insertUpdate('ng_betting', $bettingItem->toArray()); if(!$db->affected_rows){ $general->flushUpdateValues(); return '베팅을 실패했습니다.'; diff --git a/hwe/sammo/API/NationBetting/GetBettingDetail.php b/hwe/sammo/API/NationBetting/GetBettingDetail.php new file mode 100644 index 00000000..e3a4d5e8 --- /dev/null +++ b/hwe/sammo/API/NationBetting/GetBettingDetail.php @@ -0,0 +1,98 @@ +args); + $v->rule('required', [ + 'betting_id', + ]) + ->rule('integer', 'betting_id'); + + if (!$v->validate()) { + return $v->errorStr(); + } + return null; + } + + public function getRequiredSessionMode(): int + { + return static::REQ_GAME_LOGIN | static::REQ_READ_ONLY; + } + + public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag) + { + $db = DB::db(); + + increaseRefresh("국가베팅장", 1); + /** @var int */ + $bettingID = $this->arg['betting_id']; + + $gameStor = KVStorage::getStorage($db, 'game_env'); + $nationBettingStor = KVStorage::getStorage($db, 'nation_betting'); + $rawBettingInfo = $nationBettingStor->getValue("id_{$bettingID}"); + if($rawBettingInfo === null){ + return '해당 베팅이 없습니다'; + } + + try{ + $bettingInfo = new NationBettingInfo($rawBettingInfo); + } + catch(\Error $e){ + return $e->getMessage(); + } + + [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); + + $bettingDetail = []; + + foreach ($db->queryAllLists( + 'SELECT betting_type, sum(amount) as sum_amount FROM ng_betting WHERE betting_id = %i GROUP BY betting_type', + $bettingID + ) as [$bettingType, $amount]) { + $bettingDetail[] = [$bettingType, $amount]; + } + + [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); + + $myBetting = []; + foreach($db->queryAllLists( + 'SELECT betting_type, sum(amount) as sum_amount FROM ng_betting WHERE betting_id = %i AND user_id = %i GROUP BY betting_type', + $bettingID, $session->userID + ) as [$bettingType, $amount]){ + $myBetting[] = [$bettingType, $amount]; + } + + $general = General::createGeneralObjFromDB($session->generalID, ['gold', 'aux'], 1); + + if($bettingInfo->reqInheritancePoint){ + $remainPoint = $general->getInheritancePoint('previous'); + } + else{ + $remainPoint = $general->getVar('gold'); + } + + return [ + 'result' => false, + 'bettingInfo' => $rawBettingInfo, + 'bettingDetail' => $bettingDetail, + 'myBetting' => $myBetting, + 'remainPoint' => $remainPoint, + 'year' => $year, + 'month' => $month, + ]; + } +} diff --git a/hwe/sammo/API/NationBetting/GetBettingList.php b/hwe/sammo/API/NationBetting/GetBettingList.php index efb400d1..8f3bf0b2 100644 --- a/hwe/sammo/API/NationBetting/GetBettingList.php +++ b/hwe/sammo/API/NationBetting/GetBettingList.php @@ -1,6 +1,6 @@ Date: Mon, 24 Jan 2022 20:18:37 +0900 Subject: [PATCH 06/44] =?UTF-8?q?feat:=20event=20=ED=85=8C=EC=9D=B4?= =?UTF-8?q?=EB=B8=94=20=EC=A4=80=EB=B9=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sql/schema.sql | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/hwe/sql/schema.sql b/hwe/sql/schema.sql index 4b0b002d..85346286 100644 --- a/hwe/sql/schema.sql +++ b/hwe/sql/schema.sql @@ -507,9 +507,14 @@ ENGINE=Aria DEFAULT CHARSET=utf8mb4; CREATE TABLE `event` ( `id` INT(11) NOT NULL AUTO_INCREMENT, - `condition` MEDIUMTEXT NOT NULL CHECK (json_valid(`condition`)), - `action` MEDIUMTEXT NOT NULL CHECK (json_valid(`action`)), - PRIMARY KEY (`id`) + `target` ENUM('MONTH','OCCUPY_CITY','DESTROY_NATION') NOT NULL DEFAULT 'MONTH', + `priority` INT(11) NOT NULL DEFAULT '1000', + `condition` MEDIUMTEXT NOT NULL, + `action` MEDIUMTEXT NOT NULL, + PRIMARY KEY (`id`), + INDEX `target` (`target`, `priority`, `id`), + CONSTRAINT `condition` CHECK (json_valid(`condition`)), + CONSTRAINT `action` CHECK (json_valid(`action`)) ) DEFAULT CHARSET=utf8mb4 ENGINE=Aria; -- 2.54.0 From ef0360f4bac92c360fd2f87c45af7c3bac614112 Mon Sep 17 00:00:00 2001 From: hide_d Date: Mon, 24 Jan 2022 21:12:21 +0900 Subject: [PATCH 07/44] =?UTF-8?q?feat:=20=EB=8F=84=EC=8B=9C=20=EC=A0=90?= =?UTF-8?q?=EB=A0=B9,=20=EA=B5=AD=EA=B0=80=20=EB=A9=B8=EB=A7=9D=20?= =?UTF-8?q?=EC=8B=9C=20=ED=8A=B8=EB=A6=AC=EA=B1=B0=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/process_war.php | 331 ++++++++++++++----------- hwe/sammo/Command/General/che_해산.php | 26 +- hwe/sammo/TurnExecutionHelper.php | 8 +- 3 files changed, 212 insertions(+), 153 deletions(-) diff --git a/hwe/process_war.php b/hwe/process_war.php index e8cae199..fd82b726 100644 --- a/hwe/process_war.php +++ b/hwe/process_war.php @@ -1,28 +1,29 @@ getNationID(); $defenderNationID = $rawDefenderCity['nation']; - if($defenderNationID == 0){ + if ($defenderNationID == 0) { $rawDefenderNation = [ - 'nation'=>0, - 'name'=>'재야', - 'capital'=>0, - 'level'=>0, - 'gold'=>0, - 'rice'=>10000, - 'type'=>GameConst::$neutralNationType, - 'tech'=>0, - 'gennum'=>1 + 'nation' => 0, + 'name' => '재야', + 'capital' => 0, + 'level' => 0, + 'gold' => 0, + 'rice' => 10000, + 'type' => GameConst::$neutralNationType, + 'tech' => 0, + 'gennum' => 1 ]; - } - else{ + } else { $rawDefenderNation = $db->queryFirstRow('SELECT nation,`level`,`name`,capital,gennum,tech,`type`,gold,rice FROM nation WHERE nation = %i', $defenderNationID); } @@ -36,29 +37,29 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r $defenderIDList = $db->queryFirstColumn('SELECT no FROM general WHERE nation=%i AND city=%i AND nation!=0 and crew > 0 and rice>(crew/100) and train>=defence_train and atmos>=defence_train', $city->getVar('nation'), $city->getVar('city')); $defenderList = General::createGeneralObjListFromDB($defenderIDList, null, 2); - usort($defenderList, function(General $lhs, General $rhs){ - return -(extractBattleOrder($lhs) <=> extractBattleOrder($rhs)); + usort($defenderList, function (General $lhs, General $rhs) { + return - (extractBattleOrder($lhs) <=> extractBattleOrder($rhs)); }); $iterDefender = new \ArrayIterator($defenderList); $iterDefender->rewind(); - $getNextDefender = function(?WarUnit $prevDefender, bool $reqNext) use ($iterDefender, $rawDefenderNation, $rawDefenderCity, $db) { - if($prevDefender !== null){ + $getNextDefender = function (?WarUnit $prevDefender, bool $reqNext) use ($iterDefender, $rawDefenderNation, $rawDefenderCity, $db) { + if ($prevDefender !== null) { $prevDefender->applyDB($db); } - if(!$reqNext){ + if (!$reqNext) { return null; } - if(!$iterDefender->valid()){ + if (!$iterDefender->valid()) { return null; } $nextDefender = $iterDefender->current(); $nextDefender->setRawCity($rawDefenderCity); - if(extractBattleOrder($nextDefender) <= 0){ + if (extractBattleOrder($nextDefender) <= 0) { return null; } @@ -82,8 +83,8 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r $updateAttackerNation = []; $updateDefenderNation = []; - if($city->getVar('supply')){ - if($city->getPhase() > 0){ + if ($city->getVar('supply')) { + if ($city->getPhase() > 0) { $rice = $city->getKilled() / 100 * 0.8; $rice *= $city->getCrewType()->rice; $rice *= getTechCost($rawDefenderNation['tech']); @@ -91,12 +92,10 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r Util::setRound($rice); $updateDefenderNation['rice'] = max(0, $rawDefenderNation['rice'] - $rice); - } - else if($conquerCity){ - if($rawDefenderNation['capital'] == $rawDefenderCity['city']){ + } else if ($conquerCity) { + if ($rawDefenderNation['capital'] == $rawDefenderCity['city']) { $updateDefenderNation['rice'] = $rawDefenderNation['rice'] + 1000; - } - else{ + } else { $updateDefenderNation['rice'] = $rawDefenderNation['rice'] + 500; } } @@ -120,29 +119,29 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r $attackerGenCnt_eff = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc != 5', $rawAttackerNation['nation']); $defenderGenCnt_eff = $db->queryFirstField('SELECT count(no) FROM general WHERE nation=%i AND npc != 5', $rawDefenderNation['nation']); - if($attackerGenCnt_eff < GameConst::$initialNationGenLimit){ + if ($attackerGenCnt_eff < GameConst::$initialNationGenLimit) { $attackerGenCnt = GameConst::$initialNationGenLimit; $attackerGenCnt_eff = GameConst::$initialNationGenLimit; } - if($defenderGenCnt_eff < GameConst::$initialNationGenLimit){ + if ($defenderGenCnt_eff < GameConst::$initialNationGenLimit) { $defenderGenCnt = GameConst::$initialNationGenLimit; $defenderGenCnt_eff = GameConst::$initialNationGenLimit; } - if($attackerGenCnt != $attackerGenCnt_eff){ + if ($attackerGenCnt != $attackerGenCnt_eff) { $attackerIncTech *= $attackerGenCnt / $attackerGenCnt_eff; } - if($defenderGenCnt != $defenderGenCnt_eff){ + if ($defenderGenCnt != $defenderGenCnt_eff) { $defenderIncTech *= $defenderGenCnt / $defenderGenCnt_eff; } - if(TechLimit($startYear, $year, $rawAttackerNation['tech'])){ + if (TechLimit($startYear, $year, $rawAttackerNation['tech'])) { $attackerIncTech /= 4; } - if(TechLimit($startYear, $year, $rawDefenderNation['tech'])){ + if (TechLimit($startYear, $year, $rawDefenderNation['tech'])) { $defenderIncTech /= 4; } @@ -159,41 +158,42 @@ function processWar(General $attackerGeneral, array $rawAttackerNation, array $r $db->update('nation', $updateDefenderNation, 'nation=%i', $defenderNationID); $db->update('diplomacy', [ - 'dead'=>$db->sqleval('dead + %i', $attacker->getDead()) + 'dead' => $db->sqleval('dead + %i', $attacker->getDead()) ], 'me = %i and you = %i', $attackerNationID, $defenderNationID); $db->update('diplomacy', [ - 'dead'=>$db->sqleval('dead + %i', $attacker->getKilled()) + 'dead' => $db->sqleval('dead + %i', $attacker->getKilled()) ], 'me = %i and you = %i', $defenderNationID, $attackerNationID); - if(!$conquerCity){ + if (!$conquerCity) { return; } ConquerCity([ - 'startyear'=>$startYear, - 'year'=>$year, - 'month'=>$month, - 'city_rate'=>$cityRate, - 'join_mode'=>$joinMode, + 'startyear' => $startYear, + 'year' => $year, + 'month' => $month, + 'city_rate' => $cityRate, + 'join_mode' => $joinMode, ], $attacker->getGeneral(), $city->getRaw()); } -function extractBattleOrder(General $general){ - if($general->getVar('crew') == 0){ +function extractBattleOrder(General $general) +{ + if ($general->getVar('crew') == 0) { return 0; } - if($general->getVar('rice') <= $general->getVar('crew') / 100){ + if ($general->getVar('rice') <= $general->getVar('crew') / 100) { return 0; } $defence_train = $general->getVar('defence_train'); - if($general->getVar('train') < $defence_train){ + if ($general->getVar('train') < $defence_train) { return 0; } - if($general->getVar('atmos') < $defence_train){ + if ($general->getVar('atmos') < $defence_train) { return 0; } @@ -210,8 +210,8 @@ function processWar_NG( callable $getNextDefender, WarUnitCity $city, int $relYear -):bool{ - $templates = new \League\Plates\Engine(__DIR__.'/templates'); +): bool { + $templates = new \League\Plates\Engine(__DIR__ . '/templates'); $logger = $attacker->getLogger(); @@ -231,11 +231,11 @@ function processWar_NG( $logger->pushGlobalActionLog("{$attacker->getNationVar('name')}{$attacker->getName()}{$josaYi} {$city->getName()}{$josaRo} 진격합니다."); $logger->pushGeneralActionLog("{$city->getName()}{$josaRo} 진격합니다. <1>$date"); - for($currPhase = 0; $currPhase < $attacker->getMaxPhase(); $currPhase+=1){ - if($defender === null){ + for ($currPhase = 0; $currPhase < $attacker->getMaxPhase(); $currPhase += 1) { + if ($defender === null) { $defender = $city; - if($city->getNationVar('rice') <= 0 && $city->getVar('supply')){ + if ($city->getNationVar('rice') <= 0 && $city->getVar('supply')) { //병량 패퇴 $attacker->setOppose($defender); $defender->setOppose($attacker); @@ -256,7 +256,7 @@ function processWar_NG( } } - if($defender->getPhase() == 0){ + if ($defender->getPhase() == 0) { $defender->setPrePhase($currPhase); $attacker->addTrain(1); @@ -276,7 +276,7 @@ function processWar_NG( $attackerName = $attacker->getName(); $attackerCrewTypeName = $attacker->getCrewTypeName(); - if($defender instanceof WarUnitGeneral){ + if ($defender instanceof WarUnitGeneral) { $defenderName = $defender->getName(); $defenderCrewTypeName = $defender->getCrewTypeName(); @@ -291,8 +291,7 @@ function processWar_NG( $josaRo = JosaUtil::pick($defenderCrewTypeName, '로'); $josaUl = JosaUtil::pick($attackerCrewTypeName, '을'); $defender->getLogger()->pushGeneralActionLog("{$defenderCrewTypeName}{$josaRo} {$attackerName}의 {$attackerCrewTypeName}{$josaUl} 수비합니다."); - } - else{ + } else { $josaYi = JosaUtil::pick($attackerName, '이'); $josaRo = JosaUtil::pick($attackerCrewTypeName, '로'); $logger->pushGlobalActionLog("{$attackerName}{$josaYi} {$attackerCrewTypeName}{$josaRo} 성벽을 공격합니다."); @@ -324,16 +323,15 @@ function processWar_NG( $attackerHP = $attacker->getHP(); $defenderHP = $defender->getHP(); - if($deadAttacker > $attackerHP || $deadDefender > $defenderHP){ + if ($deadAttacker > $attackerHP || $deadDefender > $defenderHP) { $deadAttackerRatio = $deadAttacker / max(1, $attackerHP); $deadDefenderRatio = $deadDefender / max(1, $defenderHP); - if($deadDefenderRatio > $deadAttackerRatio){ + if ($deadDefenderRatio > $deadAttackerRatio) { //수비자가 더 병력 부족 $deadAttacker /= $deadDefenderRatio; $deadDefender = $defenderHP; - } - else{ + } else { //공격자가 더 병력 부족 $deadDefender /= $deadAttackerRatio; $deadAttacker = $attackerHP; @@ -351,7 +349,7 @@ function processWar_NG( $phaseNickname = $currPhase + 1; - if($deadAttacker > 0 || $deadDefender > 0){ + if ($deadAttacker > 0 || $deadDefender > 0) { $attacker->getLogger()->pushGeneralBattleDetailLog( "$phaseNickname : 【{$attacker->getName()}】 {$attacker->getHP()} (-$deadAttacker) VS {$defender->getHP()} (-$deadDefender) 【{$defender->getName()}】" ); @@ -365,7 +363,7 @@ function processWar_NG( $attacker->addPhase(); $defender->addPhase(); - if(!$attacker->continueWar($noRice)){ + if (!$attacker->continueWar($noRice)) { $attacker->logBattleResult(); $defender->logBattleResult(); @@ -377,10 +375,9 @@ function processWar_NG( $josaYi = JosaUtil::pick($attacker->getCrewTypeName(), '이'); $logger->pushGlobalActionLog("{$attacker->getName()}의 {$attacker->getCrewTypeName()}{$josaYi} 퇴각했습니다."); - if($noRice){ + if ($noRice) { $attacker->getLogger()->pushGeneralActionLog("군량 부족으로 퇴각합니다.", ActionLogger::PLAIN); - } - else{ + } else { $attacker->getLogger()->pushGeneralActionLog("퇴각했습니다.", ActionLogger::PLAIN); } $defender->getLogger()->pushGeneralActionLog("{$attacker->getName()}의 {$attacker->getCrewTypeName()}{$josaYi} 퇴각했습니다.", ActionLogger::PLAIN); @@ -388,7 +385,7 @@ function processWar_NG( break; } - if(!$defender->continueWar($noRice)){ + if (!$defender->continueWar($noRice)) { $attacker->logBattleResult(); $defender->logBattleResult(); @@ -399,7 +396,7 @@ function processWar_NG( $attacker->tryWound(); $defender->tryWound(); - if($defender === $city){ + if ($defender === $city) { $attacker->addLevelExp(1000); $conquerCity = true; break; @@ -407,33 +404,30 @@ function processWar_NG( $josaYi = JosaUtil::pick($defender->getCrewTypeName(), '이'); - if($noRice){ + if ($noRice) { $logger->pushGlobalActionLog("{$defender->getName()}의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다."); - $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.", ActionLogger::PLAIN); + $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}의 {$defender->getCrewTypeName()}{$josaYi} 패퇴했습니다.", ActionLogger::PLAIN); $defender->getLogger()->pushGeneralActionLog("군량 부족으로 패퇴합니다.", ActionLogger::PLAIN); - } - else{ + } else { $logger->pushGlobalActionLog("{$defender->getName()}의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다."); - $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다.", ActionLogger::PLAIN); + $attacker->getLogger()->pushGeneralActionLog("{$defender->getName()}의 {$defender->getCrewTypeName()}{$josaYi} 전멸했습니다.", ActionLogger::PLAIN); $defender->getLogger()->pushGeneralActionLog("전멸했습니다.", ActionLogger::PLAIN); } - if($currPhase + 1 == $attacker->getMaxPhase()){ + if ($currPhase + 1 == $attacker->getMaxPhase()) { break; } $defender->finishBattle(); $defender = ($getNextDefender)($defender, true); - if($defender !== null && !($defender instanceof WarUnitGeneral)){ + if ($defender !== null && !($defender instanceof WarUnitGeneral)) { throw new \RuntimeException('다음 수비자를 받아오는데 실패'); } - } - } - if($currPhase == $attacker->getMaxPhase()){ + if ($currPhase == $attacker->getMaxPhase()) { //마지막 페이즈의 전투 마무리 $attacker->logBattleResult(); $defender->logBattleResult(); @@ -445,9 +439,9 @@ function processWar_NG( $attacker->finishBattle(); $defender->finishBattle(); - if($defender instanceof WarUnitCity){ + if ($defender instanceof WarUnitCity) { $newConflict = $defender->addConflict(); - if($newConflict){ + if ($newConflict) { $nationName = $attacker->getNationVar('name'); $josaYi = JosaUtil::pick($nationName, '이'); $logger->pushGlobalHistoryLog("【분쟁】{$nationName}{$josaYi} {$defender->getName()} 공략에 가담하여 분쟁이 발생하고 있습니다."); @@ -459,33 +453,36 @@ function processWar_NG( return $conquerCity; } -function DeleteConflict($nation) { +function DeleteConflict($nation) +{ $db = DB::db(); - foreach($db->queryAllLists('SELECT city, conflict FROM city WHERE conflict!=%s', '{}') as list($cityID, $rawConflict)){ + foreach ($db->queryAllLists('SELECT city, conflict FROM city WHERE conflict!=%s', '{}') as list($cityID, $rawConflict)) { $conflict = Json::decode($rawConflict); - if(!$conflict || !is_array($conflict)){ + if (!$conflict || !is_array($conflict)) { continue; } - if(!key_exists($nation, $conflict)){ + if (!key_exists($nation, $conflict)) { continue; } unset($conflict[$nation]); $db->update('city', [ - 'conflict'=>Json::encode($conflict) + 'conflict' => Json::encode($conflict) ], 'city=%i', $cityID); } } -function getConquerNation($city) : int { +function getConquerNation($city): int +{ $conflict = Json::decode($city['conflict']); return Util::array_first_key($conflict); } -function ConquerCity(array $admin, General $general, array $city) { +function ConquerCity(array $admin, General $general, array $city) +{ $db = DB::db(); $year = $admin['year']; @@ -506,7 +503,7 @@ function ConquerCity(array $admin, General $general, array $city) { $defenderNationLogger = new ActionLogger(0, $defenderNationID, $year, $month); - if($defenderNationID) { + if ($defenderNationID) { $defenderNationDecoration = "{$defenderNationName}의"; } else { $defenderNationDecoration = "공백지인"; @@ -524,8 +521,29 @@ function ConquerCity(array $admin, General $general, array $city) { $defenderNationLogger->pushNationalHistoryLog("{$attackerNationName}{$attackerGeneralName}에 의해 {$cityName}{$josaYiCity} 함락"); + $gameStor = KVStorage::getStorage($db, 'game_env'); + + // 이벤트 핸들러 동작 + $e_env = null; + foreach (DB::db()->query('SELECT * FROM event WHERE target = "OCCUPY_CITY" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) { + if ($e_env === null) { + $e_env = $gameStor->getAll(false); + } + $eventID = $rawEvent['id']; + $cond = Json::decode($rawEvent['condition']); + $action = Json::decode($rawEvent['action']); + $event = new Event\EventHandler($cond, $action); + $e_env['currentEventID'] = $eventID; + + $event->tryRunEvent($e_env); + } + + if ($e_env !== null) { + $gameStor->resetCache(); + } + // 국가 멸망시 - if($defenderNationID && $db->queryFirstField('SELECT count(city) FROM city WHERE nation = %i', $defenderNationID) === 1) { + if ($defenderNationID && $db->queryFirstField('SELECT count(city) FROM city WHERE nation = %i', $defenderNationID) === 1) { $defenderNationLogger->flush(); unset($defenderNationLogger); @@ -545,17 +563,17 @@ function ConquerCity(array $admin, General $general, array $city) { $loseGeneralGold = 0; $loseGeneralRice = 0; - foreach($oldNationGenerals as $oldGeneral){ - $loseGold = intdiv($oldGeneral->getVar('gold') * (rand()%30+20), 100); - $loseRice = intdiv($oldGeneral->getVar('rice') * (rand()%30+20), 100); + foreach ($oldNationGenerals as $oldGeneral) { + $loseGold = intdiv($oldGeneral->getVar('gold') * (rand() % 30 + 20), 100); + $loseRice = intdiv($oldGeneral->getVar('rice') * (rand() % 30 + 20), 100); $oldGeneral->getLogger()->pushGeneralActionLog( "도주하며 금$loseGold 쌀$loseRice을 분실했습니다.", ActionLogger::PLAIN ); $oldGeneral->increaseVar('gold', -$loseGold); $oldGeneral->increaseVar('rice', -$loseRice); - $oldGeneral->addExperience(-$oldGeneral->getVar('experience')*0.1, false); - $oldGeneral->addDedication(-$oldGeneral->getVar('dedication')*0.5, false); + $oldGeneral->addExperience(-$oldGeneral->getVar('experience') * 0.1, false); + $oldGeneral->addDedication(-$oldGeneral->getVar('dedication') * 0.5, false); $loseGeneralGold += $loseGold; $loseGeneralRice += $loseRice; @@ -563,21 +581,21 @@ function ConquerCity(array $admin, General $general, array $city) { $oldGeneral->applyDB($db); //모두 등용장 발부 - if($admin['join_mode'] != 'onlyRandom' && Util::randBool(0.5)) { + if ($admin['join_mode'] != 'onlyRandom' && Util::randBool(0.5)) { $msg = ScoutMessage::buildScoutMessage($attackerID, $oldGeneral->getID()); - if($msg){ + if ($msg) { $msg->send(true); } } //NPC인 경우 일정 확률로 임관(엔장, 인재, 의병) $npcType = $oldGeneral->getNPCType(); - if($admin['join_mode'] != 'onlyRandom' && 2 <= $npcType && $npcType <= 8 && $npcType != 5 && Util::randBool(GameConst::$joinRuinedNPCProp)) { + if ($admin['join_mode'] != 'onlyRandom' && 2 <= $npcType && $npcType <= 8 && $npcType != 5 && Util::randBool(GameConst::$joinRuinedNPCProp)) { $cmd = buildGeneralCommandClass('che_임관', $oldGeneral, $admin, [ - 'destNationID'=>$attackerNationID + 'destNationID' => $attackerNationID ]); $joinTurn = Util::randRangeInt(0, 12); - if($joinTurn){ + if ($joinTurn) { _setGeneralCommand(buildGeneralCommandClass('che_견문', $oldGeneral, $admin), iterator_to_array(Util::range($joinTurn))); } _setGeneralCommand($cmd, [$joinTurn]); @@ -596,37 +614,56 @@ function ConquerCity(array $admin, General $general, array $city) { // 기본량 제외 금쌀50% + 장수들 분실 금쌀50% 흡수 $db->update('nation', [ - 'gold'=>$db->sqleval('gold + %i', $loseNationGold), - 'rice'=>$db->sqleval('rice + %i', $loseNationRice), + 'gold' => $db->sqleval('gold + %i', $loseNationGold), + 'rice' => $db->sqleval('rice + %i', $loseNationRice), ], 'nation=%i', $attackerNationID); //아국 수뇌부에게 로그 전달 $loseNationGoldText = number_format($loseNationGold); $loseNationRiceText = number_format($loseNationRice); $resourceLog = "{$defenderNationName} 정복으로 금{$loseNationGoldText} 쌀{$loseNationRiceText}을 획득했습니다."; - foreach($db->queryFirstColumn( - 'SELECT no FROM general WHERE nation=%i AND officer_level>=5', $attackerNationID - ) as $attackerChiefID - ){ - if($attackerChiefID == $attackerID){ + foreach ($db->queryFirstColumn( + 'SELECT no FROM general WHERE nation=%i AND officer_level>=5', + $attackerNationID + ) as $attackerChiefID) { + if ($attackerChiefID == $attackerID) { $attackerLogger->pushGeneralActionLog($resourceLog, ActionLogger::PLAIN); - } - else{ + } else { $chiefLogger = new ActionLogger($attackerChiefID, $attackerNationID, $year, $month); $chiefLogger->pushGeneralActionLog($resourceLog, ActionLogger::PLAIN); $chiefLogger->flush(); } } - // 멸망이 아니면 + + // 이벤트 핸들러 동작 + $e_env = null; + foreach (DB::db()->query('SELECT * FROM event WHERE target = "DESTROY_NATION" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) { + if ($e_env === null) { + $e_env = $gameStor->getAll(false); + } + $eventID = $rawEvent['id']; + $cond = Json::decode($rawEvent['condition']); + $action = Json::decode($rawEvent['action']); + $event = new Event\EventHandler($cond, $action); + $e_env['currentEventID'] = $eventID; + + $event->tryRunEvent($e_env); + } + + if ($e_env !== null) { + $gameStor->resetCache(); + } + + // 멸망이 아니면 } else { // 태수,군사,종사은 일반으로... - $db->update('general',[ - 'officer_level'=>1, - 'officer_city'=>0, - ], 'officer_city = %i',$cityID); + $db->update('general', [ + 'officer_level' => 1, + 'officer_city' => 0, + ], 'officer_city = %i', $cityID); //수도였으면 긴급 천도 - if($defenderNationID && $defenderStaticNation['capital'] == $cityID) { + if ($defenderNationID && $defenderStaticNation['capital'] == $cityID) { $minCity = findNextCapital($cityID, $defenderNationID); $minCityName = CityConst::byID($minCity)->name; @@ -636,10 +673,10 @@ function ConquerCity(array $admin, General $general, array $city) { $moveLog = "수도가 함락되어 $minCityName으로 긴급천도합니다."; //아국 수뇌부에게 로그 전달 - foreach($db->queryFirstColumn( - 'SELECT no FROM general WHERE nation=%i AND officer_level>=5', $defenderNationID - ) as $defenderChiefID - ){ + foreach ($db->queryFirstColumn( + 'SELECT no FROM general WHERE nation=%i AND officer_level>=5', + $defenderNationID + ) as $defenderChiefID) { $chiefLogger = new ActionLogger($defenderChiefID, $defenderNationID, $year, $month); $chiefLogger->pushGeneralActionLog($moveLog, ActionLogger::PLAIN); $chiefLogger->flush(); @@ -647,22 +684,22 @@ function ConquerCity(array $admin, General $general, array $city) { //천도 $db->update('nation', [ - 'capital'=>$minCity, - 'gold'=>$db->sqleval('gold * 0.5'), - 'rice'=>$db->sqleval('rice * 0.5'), + 'capital' => $minCity, + 'gold' => $db->sqleval('gold * 0.5'), + 'rice' => $db->sqleval('rice * 0.5'), ], 'nation=%i', $defenderNationID); //보급도시로 만듬 $db->update('city', [ - 'supply'=>1 + 'supply' => 1 ], 'city=%i', $minCity); //수뇌부 이동 $db->update('general', [ - 'city'=>$minCity - ], 'nation=%i AND officer_level>=5',$defenderNationID); + 'city' => $minCity + ], 'nation=%i AND officer_level>=5', $defenderNationID); //장수 사기 감소 $db->update('general', [ - 'atmos'=>$db->sqleval('atmos*0.8') - ], 'nation=%i',$defenderNationID); + 'atmos' => $db->sqleval('atmos*0.8') + ], 'nation=%i', $defenderNationID); refreshNationStaticInfo(); } @@ -673,10 +710,9 @@ function ConquerCity(array $admin, General $general, array $city) { if ($conquerNation == $attackerNationID) { // 이동 $db->update('general', [ - 'city'=>$cityID + 'city' => $cityID ], 'no=%i', $attackerID); - } - else{ + } else { $conquerNationName = getNationStaticInfo($conquerNation)['name']; $conquerNationLogger = new ActionLogger(0, $conquerNation, $year, $month); @@ -690,16 +726,16 @@ function ConquerCity(array $admin, General $general, array $city) { } $query = [ - 'supply'=>1, - 'term'=>0, - 'conflict'=>'{}', - 'agri'=>$db->sqleval('agri*0.7'), - 'comm'=>$db->sqleval('comm*0.7'), - 'secu'=>$db->sqleval('secu*0.7'), - 'nation'=>$conquerNation, - 'officer_set'=>0, + 'supply' => 1, + 'term' => 0, + 'conflict' => '{}', + 'agri' => $db->sqleval('agri*0.7'), + 'comm' => $db->sqleval('comm*0.7'), + 'secu' => $db->sqleval('secu*0.7'), + 'nation' => $conquerNation, + 'officer_set' => 0, ]; - if($city['level'] > 3) { + if ($city['level'] > 3) { $query['def'] = 1000; $query['wall'] = 1000; } else { @@ -717,45 +753,44 @@ function ConquerCity(array $admin, General $general, array $city) { $nearNationsID[] = $conquerNation; $nearNationsID = array_unique($nearNationsID); - foreach($nearNationsID as $nationNationID){ + foreach ($nearNationsID as $nationNationID) { SetNationFront($nationNationID); } } -function findNextCapital(int $capitalID, int $nationID):int{ +function findNextCapital(int $capitalID, int $nationID): int +{ $distList = searchDistance($capitalID, 99, true); $cities = []; - foreach( - DB::db()->query( + foreach (DB::db()->query( 'SELECT city, pop FROM city WHERE nation=%i and city!=%i', $nationID, $capitalID - ) as $row - ){ + ) as $row) { $cities[$row['city']] = $row['pop']; }; - foreach($distList as $dist=>$distSubList){ + foreach ($distList as $dist => $distSubList) { $maxCityPop = 0; $minCity = 0; - foreach($distSubList as $cityID){ - if(!key_exists($cityID, $cities)){ + foreach ($distSubList as $cityID) { + if (!key_exists($cityID, $cities)) { continue; } $cityPop = $cities[$cityID]; - if($cityPop < $maxCityPop){ + if ($cityPop < $maxCityPop) { continue; } $minCity = $cityID; $maxCityPop = $cityPop; } - if($minCity){ + if ($minCity) { return $minCity; } } throw new \RuntimeException('도시가 남지 않았는데 긴천을 시도하고 있습니다'); -} \ No newline at end of file +} diff --git a/hwe/sammo/Command/General/che_해산.php b/hwe/sammo/Command/General/che_해산.php index a4849548..a848e160 100644 --- a/hwe/sammo/Command/General/che_해산.php +++ b/hwe/sammo/Command/General/che_해산.php @@ -7,13 +7,17 @@ use \sammo\{ ActionLogger, GameConst, GameUnitConst, LastTurn, - Command + Command, + Json, + KVStorage }; use \sammo\Constraint\Constraint; use \sammo\Constraint\ConstraintHelper; use sammo\CityConst; +use sammo\Event\EventHandler; + use function sammo\refreshNationStaticInfo; use function sammo\deleteNation; use function sammo\tryRollbackInheritUniqueItem; @@ -98,6 +102,26 @@ class che_해산 extends Command\GeneralCommand{ tryRollbackInheritUniqueItem($general); $general->applyDB($db); + // 이벤트 핸들러 동작 + $gameStor = KVStorage::getStorage($db, 'game_env'); + $e_env = null; + foreach (DB::db()->query('SELECT * FROM event WHERE target = "DESTROY_NATION" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) { + if ($e_env === null) { + $e_env = $gameStor->getAll(false); + } + $eventID = $rawEvent['id']; + $cond = Json::decode($rawEvent['condition']); + $action = Json::decode($rawEvent['action']); + $event = new EventHandler($cond, $action); + $e_env['currentEventID'] = $eventID; + + $event->tryRunEvent($e_env); + } + + if ($e_env !== null) { + $gameStor->resetCache(); + } + return true; } diff --git a/hwe/sammo/TurnExecutionHelper.php b/hwe/sammo/TurnExecutionHelper.php index b13058bb..afe536d3 100644 --- a/hwe/sammo/TurnExecutionHelper.php +++ b/hwe/sammo/TurnExecutionHelper.php @@ -398,7 +398,7 @@ class TurnExecutionHelper // 1달마다 처리하는 것들, 벌점 감소 및 건국,전턴,합병 -1, 군량 소모 if (!preUpdateMonthly()) { - $gameStor->resetCache(true); + $gameStor->resetCache(); unlock(); throw new \RuntimeException('preUpdateMonthly() 처리 에러'); } @@ -435,7 +435,7 @@ class TurnExecutionHelper // 이벤트 핸들러 동작 $e_env = null; - foreach (DB::db()->query('SELECT * from event') as $rawEvent) { + foreach (DB::db()->query('SELECT * FROM event WHERE target = "MONTH" ORDER BY `priority` DESC, `id` ASC') as $rawEvent) { if ($e_env === null) { $e_env = $gameStor->getAll(false); } @@ -449,7 +449,7 @@ class TurnExecutionHelper } if ($e_env !== null) { - $gameStor->resetCache(true); + $gameStor->resetCache(); } postUpdateMonthly(); @@ -480,7 +480,7 @@ class TurnExecutionHelper //거래 처리 processAuction(); // 잡금 해제 - $gameStor->resetCache(true); + $gameStor->resetCache(); unlock(); } } -- 2.54.0 From eb09ed9a6d010be536a50ebc61f08815b269783a Mon Sep 17 00:00:00 2001 From: hide_d Date: Mon, 24 Jan 2022 21:37:47 +0900 Subject: [PATCH 08/44] =?UTF-8?q?feat:=20=EC=8B=9C=EB=82=98=EB=A6=AC?= =?UTF-8?q?=EC=98=A4=20event=20=ED=8F=AC=EB=A7=B7=EC=97=90=EC=84=9C=20targ?= =?UTF-8?q?et,=20priority=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Scenario.php | 94 +++++++++++++++++++-------------- hwe/scenario/scenario_0.json | 2 + hwe/scenario/scenario_1.json | 2 + hwe/scenario/scenario_1010.json | 4 +- hwe/scenario/scenario_1020.json | 4 +- hwe/scenario/scenario_1070.json | 4 +- hwe/scenario/scenario_2.json | 2 + hwe/scenario/scenario_2300.json | 2 + hwe/scenario/scenario_902.json | 3 ++ hwe/scenario/scenario_903.json | 2 + 10 files changed, 73 insertions(+), 46 deletions(-) diff --git a/hwe/sammo/Scenario.php b/hwe/sammo/Scenario.php index 18872702..8f1e28fc 100644 --- a/hwe/sammo/Scenario.php +++ b/hwe/sammo/Scenario.php @@ -19,7 +19,7 @@ class Scenario{ private $title; private $history; - + /** @var \sammo\Scenario\Nation[] */ private $nations; /** @var \sammo\Scenario\Nation[] */ @@ -52,7 +52,7 @@ class Scenario{ } list( - $affinity, $name, $picturePath, $nationName, $locatedCity, + $affinity, $name, $picturePath, $nationName, $locatedCity, $leadership, $strength, $intel, $officerLevel, $birth, $death, $ego, $char, $text ) = $rawGeneral; @@ -70,9 +70,9 @@ class Scenario{ $this->tmpGeneralQueue[$name] = $rawGeneral; $obj = (new Scenario\GeneralBuilder( - $name, + $name, false, - $picturePath, + $picturePath, $nationID )); if(!$initFull){ @@ -110,22 +110,22 @@ class Scenario{ $this->nations = []; $this->nations[0] = $neutralNation; $this->nationsInv = [$neutralNation->getName() => $neutralNation]; - + foreach (Util::array_get($data['nation'],[]) as $idx=>$rawNation) { list($name, $color, $gold, $rice, $infoText, $tech, $type, $nationLevel, $cities) = $rawNation; $nationID = $idx+1; - + $nation = new Scenario\Nation( - $nationID, - $name, - $color, - $gold, - $rice, - $infoText, - $tech, - $type, - $nationLevel, + $nationID, + $name, + $color, + $gold, + $rice, + $infoText, + $tech, + $type, + $nationLevel, $cities ); $this->nations[$nationID] = $nation; @@ -134,7 +134,7 @@ class Scenario{ $this->diplomacy = Util::array_get($data['diplomacy'], []); - + $this->generals = array_map(function($rawGeneral){ return $this->generateGeneral($rawGeneral, false, 2); }, Util::array_get($data['general'], [])); @@ -166,22 +166,22 @@ class Scenario{ $this->nations = []; $this->nations[0] = $neutralNation; $this->nationsInv = [$neutralNation->getName() => $neutralNation]; - + foreach (Util::array_get($data['nation'],[]) as $idx=>$rawNation) { list($name, $color, $gold, $rice, $infoText, $tech, $type, $nationLevel, $cities) = $rawNation; $nationID = $idx+1; - + $nation = new Scenario\Nation( - $nationID, - $name, - $color, - $gold, - $rice, - $infoText, - $tech, - $type, - $nationLevel, + $nationID, + $name, + $color, + $gold, + $rice, + $infoText, + $tech, + $type, + $nationLevel, $cities ); $this->nations[$nationID] = $nation; @@ -190,7 +190,7 @@ class Scenario{ $this->diplomacy = Util::array_get($data['diplomacy'], []); - + $this->generals = array_map(function($rawGeneral){ return $this->generateGeneral($rawGeneral, true, 2); }, Util::array_get($data['general'], [])); @@ -211,12 +211,22 @@ class Scenario{ $this->events = array_map(function($rawEvent){ //event는 여기서 풀지 않는다. 평가만 한다. - $cond = $rawEvent[0]; - $action = array_slice($rawEvent, 1); - + $target = $rawEvent[0]; + if(is_string($target)){ + throw new \RuntimeException("{$target}이 문자열이 아님"); + } + $priority = $rawEvent[1]; + if(is_int($priority)){ + throw new \RuntimeException("{$priority}가 정수가 아님"); + } + $cond = $rawEvent[2]; + $action = array_slice($rawEvent, 3); + new \sammo\Event\EventHandler($cond, $action); - + return [ + 'target' => $target, + 'priority' => $priority, 'cond' => $cond, 'action' => $action ]; @@ -310,7 +320,7 @@ class Scenario{ $this->initLite(); return $this->nations; } - + public function getMapTheme(){ return $this->gameConf['mapName']; } @@ -377,7 +387,7 @@ class Scenario{ private function buildGenerals($env){ $this->initFull(); - + try{ $text = \file_get_contents(ServConfig::getSharedIconPath('../hook/list.json?1')); $storedIcons = Json::decode($text); @@ -398,7 +408,7 @@ class Scenario{ } $rawGeneral = $this->tmpGeneralQueue[$general->getGeneralRawName()]; - $birth = $general->getBirthYear(); + $birth = $general->getBirthYear(); if(!key_exists($birth, $remainGenerals)){ $remainGenerals[$birth] = []; } @@ -432,13 +442,13 @@ class Scenario{ } $rawGeneral = $this->tmpGeneralQueue[$general->getGeneralRawName()]; - $birth = $general->getBirthYear(); + $birth = $general->getBirthYear(); if(!key_exists($birth, $remainGenerals)){ $remainGenerals[$birth] = []; } $remainGenerals[$birth][] = array_merge(['RegNeutralNPC'], $rawGeneral); } - + return $remainGenerals; } @@ -508,7 +518,7 @@ class Scenario{ $nation->build($env); } - + refreshNationStaticInfo(); CityHelper::flushCache(); @@ -519,6 +529,8 @@ class Scenario{ $actions[] = ['DeleteEvent']; $this->events[] = [ + 'target'=>'Month', + 'priority'=>1000, 'cond'=>['Date', '>=', $targetYear, '1'], 'action'=>$actions ]; @@ -540,6 +552,8 @@ class Scenario{ $events = array_map(function($rawEvent){ return [ + 'target'=>$rawEvent['target'], + 'priority'=>$rawEvent['priority'], 'condition'=>Json::encode($rawEvent['cond']), 'action'=>Json::encode($rawEvent['action']) ]; @@ -549,7 +563,7 @@ class Scenario{ $db->insert('event', $events); } - + pushGlobalHistoryLog($this->history, $env['year'], $env['month']); @@ -568,7 +582,7 @@ class Scenario{ foreach(glob(self::SCENARIO_PATH.'/scenario_*.json') as $scenarioPath){ $scenarioName = pathinfo(basename($scenarioPath), PATHINFO_FILENAME); $scenarioIdx = Util::array_last(explode('_', $scenarioName)); - + if(!is_numeric($scenarioIdx)){ continue; } diff --git a/hwe/scenario/scenario_0.json b/hwe/scenario/scenario_0.json index b47e808a..b32f4dc2 100644 --- a/hwe/scenario/scenario_0.json +++ b/hwe/scenario/scenario_0.json @@ -8,11 +8,13 @@ }, "events":[ [ + "month", 1000, ["or", ["Date", "==", null, 12], ["Date", "==", null, 6]], ["CreateManyNPC", 10, 10], ["DeleteEvent"] ], [ + "month", 1000, ["Date", "==", 181, 1], ["RaiseNPCNation"], ["DeleteEvent"] diff --git a/hwe/scenario/scenario_1.json b/hwe/scenario/scenario_1.json index b609f4c6..b54183d7 100644 --- a/hwe/scenario/scenario_1.json +++ b/hwe/scenario/scenario_1.json @@ -11,11 +11,13 @@ }, "events":[ [ + "month", 1000, ["or", ["Date", "==", null, 12], ["Date", "==", null, 6]], ["CreateManyNPC", 10, 10], ["DeleteEvent"] ], [ + "month", 1000, ["Date", "==", 181, 1], ["RaiseNPCNation"], ["DeleteEvent"] diff --git a/hwe/scenario/scenario_1010.json b/hwe/scenario/scenario_1010.json index 1a39d070..7162d196 100644 --- a/hwe/scenario/scenario_1010.json +++ b/hwe/scenario/scenario_1010.json @@ -12,7 +12,7 @@ ]], ["황건적", "#FFD700", 10000, 10000, "황건적", 500, "태평도", 2, [ "업","계교","진류","관도","정도","평원","복양","패","허창","초" - ]] + ]] ], "diplomacy":[ ], @@ -703,7 +703,7 @@ ], "history":[ "●184년 1월:【역사모드1】황건적의 난", - "●184년 1월:【황건적】전국 각지에서 황건적이 들고 일어서고 있습니다." + "●184년 1월:【황건적】전국 각지에서 황건적이 들고 일어서고 있습니다." ], "initialEvents":[ [ diff --git a/hwe/scenario/scenario_1020.json b/hwe/scenario/scenario_1020.json index d6ce37d6..5cdab1e2 100644 --- a/hwe/scenario/scenario_1020.json +++ b/hwe/scenario/scenario_1020.json @@ -20,7 +20,7 @@ "진류" ]], ["유언", "#483D8B", 10000, 10000, "익주 주자사 유언", 1000, "유가", 3, [ - "성도", "면죽", "자동", "강주" + "성도", "면죽", "자동", "강주" ]], ["원술", "#FFC0CB", 10000, 10000, "4세 5공 명문 혈통 원소의 사촌 원술", 1000, "병가", 2, [ "완" @@ -67,7 +67,7 @@ ["공주", "#800080", 10000, 10000, "공주", 1000, "도가", 3, [ "초" ]] - + ], "diplomacy":[ [1, 2, 1, 36], diff --git a/hwe/scenario/scenario_1070.json b/hwe/scenario/scenario_1070.json index d4aff9e3..5b84996f 100644 --- a/hwe/scenario/scenario_1070.json +++ b/hwe/scenario/scenario_1070.json @@ -8,8 +8,8 @@ }, "nation":[ ["조조", "#000080", 10000, 10000, "하북을 제패하고 대군을 이끌고 남하하는 조조", 1000, "병가", 6, [ - "허창", "역경", "계교", "관도", "호관", "정도", "호로", "사곡", "함곡", "사수", "서주", "계", - "북평", "진양", "남피", "평원", "하내", "업", "북해", "복양", "장안", "홍농", "낙양", "진류", + "허창", "역경", "계교", "관도", "호관", "정도", "호로", "사곡", "함곡", "사수", "서주", "계", + "북평", "진양", "남피", "평원", "하내", "업", "북해", "복양", "장안", "홍농", "낙양", "진류", "패", "초", "하비", "완", "여남", "수춘", "신야", "양양", "강릉", "장판" ]], ["손권", "#FF0000", 10000, 10000, "조조의 남하에 유비와 불가침으로 맞서는 손권", 1000, "덕가", 4, [ diff --git a/hwe/scenario/scenario_2.json b/hwe/scenario/scenario_2.json index 12f63c82..0b577eb9 100644 --- a/hwe/scenario/scenario_2.json +++ b/hwe/scenario/scenario_2.json @@ -15,11 +15,13 @@ }, "events":[ [ + "month", 1000, ["or", ["Date", "==", null, 12], ["Date", "==", null, 6]], ["CreateManyNPC", 10, 10], ["DeleteEvent"] ], [ + "month", 1000, ["Date", "==", 181, 1], ["RaiseNPCNation"], ["DeleteEvent"] diff --git a/hwe/scenario/scenario_2300.json b/hwe/scenario/scenario_2300.json index 0aac9133..05f52f65 100644 --- a/hwe/scenario/scenario_2300.json +++ b/hwe/scenario/scenario_2300.json @@ -99,11 +99,13 @@ ], "events":[ [ + "month", 1000, ["or", ["Date", "==", null, 12], ["Date", "==", null, 6]], ["CreateManyNPC", 10, 10], ["DeleteEvent"] ], [ + "month", 1000, ["Date", "==", 181, 1], ["RaiseNPCNation"], ["DeleteEvent"] diff --git a/hwe/scenario/scenario_902.json b/hwe/scenario/scenario_902.json index 987283e5..0ca1b5e0 100644 --- a/hwe/scenario/scenario_902.json +++ b/hwe/scenario/scenario_902.json @@ -59,11 +59,13 @@ }, "events":[ [ + "month", 1000, ["Date", "==", null, 12], ["CreateManyNPC", 10, 10], ["DeleteEvent"] ], [ + "month", 1000, ["Date", "==", 182, 1], ["ChangeCity", "occupied", { "trade":100 @@ -71,6 +73,7 @@ ["DeleteEvent"] ], [ + "month", 1000, ["Date", "==", 182, 7], ["ChangeCity", "occupied", { "trade":100 diff --git a/hwe/scenario/scenario_903.json b/hwe/scenario/scenario_903.json index f99a15af..ab39c555 100644 --- a/hwe/scenario/scenario_903.json +++ b/hwe/scenario/scenario_903.json @@ -11,11 +11,13 @@ ], "events": [ [ + "month", 1000, ["Date", "==", null, 12], ["CreateManyNPC", 100, 0], ["DeleteEvent"] ], [ + "month", 1000, ["Date", "==", 181, 12], ["ChangeCity", "occupied", { "pop": "+60000", -- 2.54.0 From 6014fc3ded38c936ac712948259bf922440c53d1 Mon Sep 17 00:00:00 2001 From: hide_d Date: Mon, 24 Jan 2022 21:55:59 +0900 Subject: [PATCH 09/44] =?UTF-8?q?feat:=20Event/Condition/RemainNation=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Event/Condition/RemainNation.php | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 hwe/sammo/Event/Condition/RemainNation.php diff --git a/hwe/sammo/Event/Condition/RemainNation.php b/hwe/sammo/Event/Condition/RemainNation.php new file mode 100644 index 00000000..5488aa85 --- /dev/null +++ b/hwe/sammo/Event/Condition/RemainNation.php @@ -0,0 +1,50 @@ +true, + '!='=>true, + '<'=>true, + '>'=>true, + '<='=>true, + '>='=>true, + ]; + + private $cmp; + private $cnt; + + public function __construct(string $cmp, int $cnt){ + //Cmp('==', '!=', '<=', '>=', '<', '>'), Cnt + if(!array_key_exists($cmp, self::AVAILABLE_CMP)){ + throw new \InvalidArgumentException('올바르지 않은 비교연산자입니다'); + } + + $this->cmp = $cmp; + $this->cnt = $cnt; + } + + public function eval($env=null){ + $lhs = count(getAllNationStaticInfo()); + $rhs = $this->cnt; + + $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__] + ]; + + } +} \ No newline at end of file -- 2.54.0 From f5dc1cd85e848aba97e0cdaffb74e4c920251775 Mon Sep 17 00:00:00 2001 From: hide_d Date: Tue, 25 Jan 2022 00:26:55 +0900 Subject: [PATCH 10/44] =?UTF-8?q?feat(WIP):=20=EC=9D=B4=EB=B2=A4=ED=8A=B8?= =?UTF-8?q?=20=EC=8B=9C=EB=82=98=EB=A6=AC=EC=98=A4=20=EC=A4=80=EB=B9=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Scenario.php | 4 +- hwe/scenario/scenario_904.json | 67 ++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) create mode 100644 hwe/scenario/scenario_904.json diff --git a/hwe/sammo/Scenario.php b/hwe/sammo/Scenario.php index 8f1e28fc..00578c40 100644 --- a/hwe/sammo/Scenario.php +++ b/hwe/sammo/Scenario.php @@ -212,11 +212,11 @@ class Scenario{ $this->events = array_map(function($rawEvent){ //event는 여기서 풀지 않는다. 평가만 한다. $target = $rawEvent[0]; - if(is_string($target)){ + if(!is_string($target)){ throw new \RuntimeException("{$target}이 문자열이 아님"); } $priority = $rawEvent[1]; - if(is_int($priority)){ + if(!is_int($priority)){ throw new \RuntimeException("{$priority}가 정수가 아님"); } $cond = $rawEvent[2]; diff --git a/hwe/scenario/scenario_904.json b/hwe/scenario/scenario_904.json new file mode 100644 index 00000000..d9a6f949 --- /dev/null +++ b/hwe/scenario/scenario_904.json @@ -0,0 +1,67 @@ +{ + "title":"【이벤트】 대리전", + "startYear":180, + "map":{ + "mapName":"miniche_b" + }, + "history":[ + "●180년 1월:【이벤트】NPC 군주 뒤에 플레이해보는 이벤트 깃수" + ], + "const": { + "joinRuinedNPCProp":0 + }, + "nation":[ + ["엄백호", "#800080", 10000, 10000, "엄백호", 0, "che_덕가", 2, ["건안"]], + ["맹획", "#A0522D", 10000, 10000, "맹획", 0, "che_덕가", 2, ["월수"]], + ["유표", "#E0FFFF", 10000, 10000, "유표", 0, "che_도가", 2, ["영릉"]], + ["올돌골", "#800000", 10000, 10000, "올돌골", 0, "che_도적", 2, ["남해"]], + ["동탁", "#A9A9A9", 10000, 10000, "동탁", 0, "che_도적", 2, ["안정"]], + ["유비", "#008000", 10000, 10000, "유비", 0, "che_명가", 2, ["평원"]], + ["유기", "#008080", 10000, 10000, "유기", 0, "che_명가", 2, ["강하"]], + ["유장", "#483D8B", 10000, 10000, "유장", 0, "che_묵가", 2, ["덕양"]], + ["조조", "#000080", 10000, 10000, "조조", 0, "che_법가", 2, ["진류"]], + ["원소", "#FF00FF", 10000, 10000, "원소", 0, "che_병가", 2, ["거록"]], + ["공손찬", "#87CEEB", 10000, 10000, "공손찬", 0, "che_병가", 2, ["계"]], + ["신라", "#FFA500", 10000, 10000, "신라", 0, "che_불가", 2, ["계림"]], + ["고구려", "#FF6347", 10000, 10000, "고구려", 0, "che_불가", 2, ["국내"]], + ["장로", "#20B2AA", 10000, 10000, "장로", 0, "che_오두미도", 2, ["상용"]], + ["도겸", "#00FF00", 10000, 10000, "도겸", 0, "che_오두미도", 2, ["하비"]], + ["손권", "#FF0000", 10000, 10000, "손권", 0, "che_유가", 2, ["오"]], + ["헌제", "#BA55D3", 10000, 10000, "헌제", 0, "che_유가", 2, ["홍농"]], + ["원술", "#FFC0CB", 10000, 10000, "원술", 0, "che_음양가", 2, ["여남"]], + ["마등", "#808000", 10000, 10000, "마등", 0, "che_종횡가", 2, ["무도"]], + ["목록대왕", "#7CFC00", 10000, 10000, "목록대왕", 0, "che_종횡가", 2, ["건녕"]], + ["장량", "#FFD700", 10000, 10000, "장량", 0, "che_태평도", 2, ["하내"]] + ], + "general":[ + [999, "엄백호", 1217, 1, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "맹획", 1108, 2, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "유표", 1293, 3, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "올돌골", 1241, 4, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "동탁", 1083, 5, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "유비", 1281, 6, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "유기", 1276, 7, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "유장", 1290, 8, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "조조", 1392, 9, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "원소", 1268, 10, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "공손찬", 1033, 11, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "석벌휴", null, 12, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "고남무", null, 13, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "장로", 1319, 14, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "도겸", 1074, 15, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "손권", 1169, 16, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "헌제", 1002, 17, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "원술", 1269, 18, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "마등", 1094, 19, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "목록대왕", 1110, 20, null, 85, 85, 85, 12, 150, 250, null, null], + [999, "장량", 1318, 21, null, 85, 85, 85, 12, 150, 250, null, null] + ], + "events":[ + [ + "month", 1000, + ["or", ["Date", "==", null, 12], ["Date", "==", null, 6]], + ["CreateManyNPC", 10, 10], + ["DeleteEvent"] + ] + ] +} \ No newline at end of file -- 2.54.0 From 41dd497d1b2667fb2f8662811dfb986bcbb9bc8a Mon Sep 17 00:00:00 2001 From: hide_d Date: Tue, 25 Jan 2022 00:44:44 +0900 Subject: [PATCH 11/44] =?UTF-8?q?fix:=20=EB=B4=89=EA=B8=89=20=EA=B3=84?= =?UTF-8?q?=EC=82=B0=EC=97=90=EC=84=9C=20=EB=B6=80=EB=8C=80=EC=9E=A5=20?= =?UTF-8?q?=EC=B2=98=EB=A6=AC=EB=A5=BC=20=ED=95=98=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EC=9D=80=20=EB=AC=B8=EC=A0=9C=20=EC=88=98=EC=A0=95=20-=20?= =?UTF-8?q?=EC=A0=84=EC=B2=B4=20=EC=A7=80=EC=B6=9C=20=EA=B3=84=EC=82=B0?= =?UTF-8?q?=EC=97=90=EB=A7=8C=20=EC=8B=A4=EC=88=98=20=EB=B0=9C=EC=83=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/GeneralAI.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hwe/sammo/GeneralAI.php b/hwe/sammo/GeneralAI.php index fd14f1b7..08189fb8 100644 --- a/hwe/sammo/GeneralAI.php +++ b/hwe/sammo/GeneralAI.php @@ -4137,7 +4137,7 @@ class GeneralAI $dedicationList = array_map(function (General $general) { return $general->getRaw(); }, array_filter($this->nationGenerals, function (General $rawGeneral) { - return $rawGeneral->getVar('officer_level') != 5; + return $rawGeneral->getVar('npc') != 5; })); $riceIncome = getRiceIncome($nation['nation'], $nation['level'], $nation['rate'], $nation['capital'], $nation['type'], $cityList); -- 2.54.0 From 8010b0f7da1b59a1b5770149358df8426ff9a224 Mon Sep 17 00:00:00 2001 From: hide_d Date: Tue, 25 Jan 2022 00:48:44 +0900 Subject: [PATCH 12/44] =?UTF-8?q?fix:=20N=EC=9E=A5=EB=A7=8C=20=EA=B1=B4?= =?UTF-8?q?=EA=B5=AD=ED=95=9C=20=EA=B2=BD=EC=9A=B0=EC=97=90=20CreateManyNP?= =?UTF-8?q?C=EA=B0=80=20=EB=8F=99=EC=9E=91=ED=95=98=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EB=8A=94=20=EB=B2=84=EA=B7=B8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Event/Action/CreateManyNPC.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hwe/sammo/Event/Action/CreateManyNPC.php b/hwe/sammo/Event/Action/CreateManyNPC.php index ae6e2b48..3c50b046 100644 --- a/hwe/sammo/Event/Action/CreateManyNPC.php +++ b/hwe/sammo/Event/Action/CreateManyNPC.php @@ -54,7 +54,7 @@ class CreateManyNPC extends \sammo\Event\Action{ $moreGenCnt = 0; if($this->fillCnt){ $db = DB::db(); - $nations = $db->queryFirstColumn('SELECT nation FROM general WHERE npc < 2 AND officer_level = 12'); + $nations = $db->queryFirstColumn('SELECT nation FROM general WHERE npc < 3 AND officer_level = 12'); $regGens = $db->queryFirstField('SELECT count(*) FROM general WHERE nation IN %li AND npc < 4', $nations); $moreGenCnt = count($nations) * $this->fillCnt - $regGens; } -- 2.54.0 From 5482af8ae7b8b000fe4358abc16fe163d65ba4af Mon Sep 17 00:00:00 2001 From: hide_d Date: Tue, 25 Jan 2022 00:58:11 +0900 Subject: [PATCH 13/44] =?UTF-8?q?fix:=20=EC=8B=9C=EB=82=98=EB=A6=AC?= =?UTF-8?q?=EC=98=A4=20=EB=AA=A8=EB=93=9C=EC=97=90=EC=84=9C=20=EC=8B=9C?= =?UTF-8?q?=EC=9E=91=EC=8B=9C=EC=A0=90=EA=B3=BC=20=EB=B4=89=EA=B8=89?= =?UTF-8?q?=EC=9B=94=EC=9D=B4=20=EA=B2=B9=EC=B9=98=EB=8A=94=20=EA=B2=BD?= =?UTF-8?q?=EC=9A=B0=20=EB=A9=88=EC=B6=94=EB=8A=94=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Scenario/GeneralBuilder.php | 1 + 1 file changed, 1 insertion(+) diff --git a/hwe/sammo/Scenario/GeneralBuilder.php b/hwe/sammo/Scenario/GeneralBuilder.php index 4fee435c..e6f52412 100644 --- a/hwe/sammo/Scenario/GeneralBuilder.php +++ b/hwe/sammo/Scenario/GeneralBuilder.php @@ -671,6 +671,7 @@ class GeneralBuilder{ 'intel'=>$this->intel, 'experience'=>$experience, 'dedication'=>$dedication, + 'dedlevel'=>1, 'officer_level'=>$officerLevel, 'gold'=>$this->gold, 'rice'=>$this->rice, -- 2.54.0 From 5762b4ca6dd13463e8c387fae9dbdbc326c67a9e Mon Sep 17 00:00:00 2001 From: hide_d Date: Tue, 25 Jan 2022 00:58:55 +0900 Subject: [PATCH 14/44] =?UTF-8?q?feat(WIP):=20=EC=9D=B4=EB=B2=A4=ED=8A=B8?= =?UTF-8?q?=20=EC=8B=9C=EB=82=98=EB=A6=AC=EC=98=A4=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EB=B6=88=EA=B0=80=EB=8A=A5=ED=95=9C=20=EC=BB=A4=EB=A7=A8?= =?UTF-8?q?=EB=93=9C=20=EC=A7=80=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/scenario/scenario_904.json | 126 +++++++++++++++++++++++++++------ 1 file changed, 104 insertions(+), 22 deletions(-) diff --git a/hwe/scenario/scenario_904.json b/hwe/scenario/scenario_904.json index d9a6f949..c81d6752 100644 --- a/hwe/scenario/scenario_904.json +++ b/hwe/scenario/scenario_904.json @@ -8,30 +8,112 @@ "●180년 1월:【이벤트】NPC 군주 뒤에 플레이해보는 이벤트 깃수" ], "const": { - "joinRuinedNPCProp":0 + "joinRuinedNPCProp":0, + "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_하야" + ] + }, + "availableChiefCommand": { + "휴식": [ + "휴식" + ], + "인사": [ + "che_발령", + "che_포상", + "che_몰수" + ], + "특수": [ + "che_초토화", + "che_천도", + "che_증축", + "che_감축" + ], + "전략": [ + "che_필사즉생", + "che_백성동원", + "che_수몰", + "che_허보", + "che_의병모집", + "che_이호경식", + "che_급습" + ], + "기타": [ + "che_피장파장", + "che_국기변경", + "che_국호변경" + ] + } }, "nation":[ - ["엄백호", "#800080", 10000, 10000, "엄백호", 0, "che_덕가", 2, ["건안"]], - ["맹획", "#A0522D", 10000, 10000, "맹획", 0, "che_덕가", 2, ["월수"]], - ["유표", "#E0FFFF", 10000, 10000, "유표", 0, "che_도가", 2, ["영릉"]], - ["올돌골", "#800000", 10000, 10000, "올돌골", 0, "che_도적", 2, ["남해"]], - ["동탁", "#A9A9A9", 10000, 10000, "동탁", 0, "che_도적", 2, ["안정"]], - ["유비", "#008000", 10000, 10000, "유비", 0, "che_명가", 2, ["평원"]], - ["유기", "#008080", 10000, 10000, "유기", 0, "che_명가", 2, ["강하"]], - ["유장", "#483D8B", 10000, 10000, "유장", 0, "che_묵가", 2, ["덕양"]], - ["조조", "#000080", 10000, 10000, "조조", 0, "che_법가", 2, ["진류"]], - ["원소", "#FF00FF", 10000, 10000, "원소", 0, "che_병가", 2, ["거록"]], - ["공손찬", "#87CEEB", 10000, 10000, "공손찬", 0, "che_병가", 2, ["계"]], - ["신라", "#FFA500", 10000, 10000, "신라", 0, "che_불가", 2, ["계림"]], - ["고구려", "#FF6347", 10000, 10000, "고구려", 0, "che_불가", 2, ["국내"]], - ["장로", "#20B2AA", 10000, 10000, "장로", 0, "che_오두미도", 2, ["상용"]], - ["도겸", "#00FF00", 10000, 10000, "도겸", 0, "che_오두미도", 2, ["하비"]], - ["손권", "#FF0000", 10000, 10000, "손권", 0, "che_유가", 2, ["오"]], - ["헌제", "#BA55D3", 10000, 10000, "헌제", 0, "che_유가", 2, ["홍농"]], - ["원술", "#FFC0CB", 10000, 10000, "원술", 0, "che_음양가", 2, ["여남"]], - ["마등", "#808000", 10000, 10000, "마등", 0, "che_종횡가", 2, ["무도"]], - ["목록대왕", "#7CFC00", 10000, 10000, "목록대왕", 0, "che_종횡가", 2, ["건녕"]], - ["장량", "#FFD700", 10000, 10000, "장량", 0, "che_태평도", 2, ["하내"]] + ["엄백호", "#800080", 10000, 10000, "엄백호", 500, "che_덕가", 1, ["건안"]], + ["맹획", "#A0522D", 10000, 10000, "맹획", 500, "che_덕가", 1, ["월수"]], + ["유표", "#E0FFFF", 10000, 10000, "유표", 500, "che_도가", 1, ["영릉"]], + ["올돌골", "#800000", 10000, 10000, "올돌골", 500, "che_도적", 1, ["남해"]], + ["동탁", "#A9A9A9", 10000, 10000, "동탁", 500, "che_도적", 1, ["안정"]], + ["유비", "#008000", 10000, 10000, "유비", 500, "che_명가", 1, ["평원"]], + ["유기", "#008080", 10000, 10000, "유기", 500, "che_명가", 1, ["강하"]], + ["유장", "#483D8B", 10000, 10000, "유장", 500, "che_묵가", 1, ["덕양"]], + ["조조", "#000080", 10000, 10000, "조조", 500, "che_법가", 1, ["진류"]], + ["원소", "#FF00FF", 10000, 10000, "원소", 500, "che_병가", 1, ["거록"]], + ["공손찬", "#87CEEB", 10000, 10000, "공손찬", 500, "che_병가", 1, ["계"]], + ["신라", "#FFA500", 10000, 10000, "신라", 500, "che_불가", 1, ["계림"]], + ["고구려", "#FF6347", 10000, 10000, "고구려", 500, "che_불가", 1, ["국내"]], + ["장로", "#20B2AA", 10000, 10000, "장로", 500, "che_오두미도", 1, ["상용"]], + ["도겸", "#00FF00", 10000, 10000, "도겸", 500, "che_오두미도", 1, ["하비"]], + ["손권", "#FF0000", 10000, 10000, "손권", 500, "che_유가", 1, ["오"]], + ["헌제", "#BA55D3", 10000, 10000, "헌제", 500, "che_유가", 1, ["홍농"]], + ["원술", "#FFC0CB", 10000, 10000, "원술", 500, "che_음양가", 1, ["여남"]], + ["마등", "#808000", 10000, 10000, "마등", 500, "che_종횡가", 1, ["무도"]], + ["목록대왕", "#7CFC00", 10000, 10000, "목록대왕", 500, "che_종횡가", 1, ["건녕"]], + ["장량", "#FFD700", 10000, 10000, "장량", 500, "che_태평도", 1, ["하내"]] ], "general":[ [999, "엄백호", 1217, 1, null, 85, 85, 85, 12, 150, 250, null, null], -- 2.54.0 From ee4a0fbe8358d3d8b60ec4ee2dfc631cd6bc848a Mon Sep 17 00:00:00 2001 From: hide_d Date: Wed, 26 Jan 2022 02:59:00 +0900 Subject: [PATCH 15/44] =?UTF-8?q?Feat(WIP):=20OpenNationBetting=20Action?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80=20-=20=EC=8B=9C=EB=82=98=EB=A6=AC?= =?UTF-8?q?=EC=98=A4=20event=EC=97=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Event/Action/FinishNationBetting.php | 39 ++++++++++ hwe/sammo/Event/Action/OpenNationBetting.php | 71 +++++++++++++++++++ hwe/scenario/scenario_904.json | 35 +++++++++ 3 files changed, 145 insertions(+) create mode 100644 hwe/sammo/Event/Action/FinishNationBetting.php create mode 100644 hwe/sammo/Event/Action/OpenNationBetting.php diff --git a/hwe/sammo/Event/Action/FinishNationBetting.php b/hwe/sammo/Event/Action/FinishNationBetting.php new file mode 100644 index 00000000..d33c847e --- /dev/null +++ b/hwe/sammo/Event/Action/FinishNationBetting.php @@ -0,0 +1,39 @@ +getValue("id_{$this->bettingID}"); + if($bettingInfoRaw === null){ + return [__CLASS__, true]; + } + $bettingInfo = new NationBettingInfo($bettingInfoRaw); + $bettingInfo->finished = true; + $nationBettingStor->setValue("id_{$this->bettingID}", $bettingInfo->toArray()); + + //TODO: 포인트를 배분해주어야 함 + //TODO: 이후 토너먼트 베팅 결과도 같이 처리할 것이므로, 별도의 함수나 모듈을 생성하여 처리! + + //NOTE: 완료되었음을 알릴 것인가? + + return [__CLASS__, false, 'NYI']; + } +} diff --git a/hwe/sammo/Event/Action/OpenNationBetting.php b/hwe/sammo/Event/Action/OpenNationBetting.php new file mode 100644 index 00000000..5fe6c5a7 --- /dev/null +++ b/hwe/sammo/Event/Action/OpenNationBetting.php @@ -0,0 +1,71 @@ +invalidateCacheValue('last_betting_id'); + $bettingID = ($gameStor->getValue('last_betting_id') ?? 0) + 1; + $gameStor->setValue('last_betting_id', $bettingID); + + $nationBettingStor = KVStorage::getStorage($db, 'nation_betting'); + [$year, $month] = [$env['year'], $env['month']]; + + if ($this->nationCnt == 1) { + $name = "천통국"; + } else { + $name = "최후 {$this->nationCnt}국"; + } + + + $openYearMonth = Util::joinYearMonth($year, $month); + $closeYearMonth = $openYearMonth + 24; + + $bettingInfo = new NationBettingInfo( + id: $bettingID, + name: "[{$year}년 {$month}월] {$name} 예상 베팅", + finished: false, + selectCnt: $this->nationCnt, + reqInheritancePoint: true, + openYearMonth: $openYearMonth, + closeYearMonth: $closeYearMonth, + ); + $nationBettingStor->setValue("id_{$bettingID}", $bettingInfo->toArray()); + + $db->insert('event', [ + 'target' => 'DESTROY_NATION', + 'priority' => 1000, + 'condition' => Json::encode( + ["RemainNation", $this->nationCnt], + ), + 'action' => Json::encode([ + ["FinishNationBetting", $bettingID], + ["DeleteEvent"], + ]), + ]); + $logger = new \sammo\ActionLogger(0, 0, $year, $month); + $logger->pushGlobalHistoryLog("【내기】천하통일을 염원하는 내기가 진행중입니다! 호사가의 참여를 기다립니다!"); + $logger->flush(); + + return [__CLASS__, true]; + } +} diff --git a/hwe/scenario/scenario_904.json b/hwe/scenario/scenario_904.json index c81d6752..c6ad8f3e 100644 --- a/hwe/scenario/scenario_904.json +++ b/hwe/scenario/scenario_904.json @@ -144,6 +144,41 @@ ["or", ["Date", "==", null, 12], ["Date", "==", null, 6]], ["CreateManyNPC", 10, 10], ["DeleteEvent"] + ], + [ + "month", 1000, + ["Date", "==", 181, 1], + ["OpenNationBetting", 4], + ["OpenNationBetting", 1], + ["DeleteEvent"] + ], + [ + "month", 1000, + ["and", + ["Date", ">=", 183, 1], + ["RemainNation", "<=", 16] + ], + ["OpenNationBetting", 4], + ["OpenNationBetting", 1], + ["DeleteEvent"] + ], + [ + "month", 1000, + ["and", + ["Date", ">=", 183, 1], + ["RemainNation", "<=", 8] + ], + ["OpenNationBetting", 1], + ["DeleteEvent"] + ], + [ + "month", 1000, + ["and", + ["Date", ">=", 183, 1], + ["RemainNation", "<=", 4] + ], + ["OpenNationBetting", 1], + ["DeleteEvent"] ] ] } \ No newline at end of file -- 2.54.0 From 8dabb6e76a4efc67dff993fd677e4eb90cc0fad0 Mon Sep 17 00:00:00 2001 From: hide_d Date: Wed, 26 Jan 2022 03:00:24 +0900 Subject: [PATCH 16/44] =?UTF-8?q?misc:=20OpenNationBetting=20TODO=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Event/Action/OpenNationBetting.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/hwe/sammo/Event/Action/OpenNationBetting.php b/hwe/sammo/Event/Action/OpenNationBetting.php index 5fe6c5a7..a333859d 100644 --- a/hwe/sammo/Event/Action/OpenNationBetting.php +++ b/hwe/sammo/Event/Action/OpenNationBetting.php @@ -51,6 +51,8 @@ class OpenNationBetting extends \sammo\Event\Action ); $nationBettingStor->setValue("id_{$bettingID}", $bettingInfo->toArray()); + //TODO: 초기에 부여할 포인트는 어디서 나는가? + $db->insert('event', [ 'target' => 'DESTROY_NATION', 'priority' => 1000, -- 2.54.0 From 466faf8179b7a349aa86144e1f2a129a6c24ae72 Mon Sep 17 00:00:00 2001 From: hide_d Date: Wed, 26 Jan 2022 03:01:06 +0900 Subject: [PATCH 17/44] =?UTF-8?q?fix:=20=EC=9D=B4=EB=B2=A4=ED=8A=B8=20?= =?UTF-8?q?=EC=A1=B0=EA=B1=B4=20=EC=98=A4=EB=A5=98=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Event/Action/OpenNationBetting.php | 2 +- hwe/sammo/Event/Action/RaiseInvader.php | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/hwe/sammo/Event/Action/OpenNationBetting.php b/hwe/sammo/Event/Action/OpenNationBetting.php index a333859d..d551c41d 100644 --- a/hwe/sammo/Event/Action/OpenNationBetting.php +++ b/hwe/sammo/Event/Action/OpenNationBetting.php @@ -57,7 +57,7 @@ class OpenNationBetting extends \sammo\Event\Action 'target' => 'DESTROY_NATION', 'priority' => 1000, 'condition' => Json::encode( - ["RemainNation", $this->nationCnt], + ["RemainNation", "<=", $this->nationCnt], ), 'action' => Json::encode([ ["FinishNationBetting", $bettingID], diff --git a/hwe/sammo/Event/Action/RaiseInvader.php b/hwe/sammo/Event/Action/RaiseInvader.php index 186c6174..6e48412b 100644 --- a/hwe/sammo/Event/Action/RaiseInvader.php +++ b/hwe/sammo/Event/Action/RaiseInvader.php @@ -204,12 +204,16 @@ class RaiseInvader extends \sammo\Event\Action $nationObj->postBuild($env); refreshNationStaticInfo(); $db->insert('event', [ + 'target' => 'month', + 'priority' => 1000, 'condition' => Json::encode(true), 'action' => Json::encode([["AutoDeleteInvader", $invaderNationID]]), ]); } $db->insert('event', [ + 'target' => 'month', + 'priority' => 1000, 'condition' => Json::encode(true), 'action' => Json::encode([["InvaderEnding"]]), ]); -- 2.54.0 From 3a2fdce3d9c187215cdd41df8b000f4c20c4d7c9 Mon Sep 17 00:00:00 2001 From: hide_d Date: Wed, 26 Jan 2022 03:05:33 +0900 Subject: [PATCH 18/44] =?UTF-8?q?feat(WIP):=20OpenNationBetting=EC=97=90?= =?UTF-8?q?=20=EB=B3=B4=EB=84=88=EC=8A=A4=20=EC=83=81=EA=B8=88=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Event/Action/OpenNationBetting.php | 17 ++++++++++++++--- hwe/scenario/scenario_904.json | 12 ++++++------ 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/hwe/sammo/Event/Action/OpenNationBetting.php b/hwe/sammo/Event/Action/OpenNationBetting.php index d551c41d..feea37d2 100644 --- a/hwe/sammo/Event/Action/OpenNationBetting.php +++ b/hwe/sammo/Event/Action/OpenNationBetting.php @@ -11,11 +11,14 @@ use sammo\KVStorage; class OpenNationBetting extends \sammo\Event\Action { - public function __construct(private int $nationCnt = 1) + public function __construct(private int $nationCnt = 1, private int $bonusPoint = 0) { if ($nationCnt < 1) { throw new \RuntimeException("1 미만의 숫자"); } + if ($bonusPoint < 0){ + throw new \RuntimeException("0 미만의 보너스 포인트"); + } } public function run(array $env) @@ -51,8 +54,6 @@ class OpenNationBetting extends \sammo\Event\Action ); $nationBettingStor->setValue("id_{$bettingID}", $bettingInfo->toArray()); - //TODO: 초기에 부여할 포인트는 어디서 나는가? - $db->insert('event', [ 'target' => 'DESTROY_NATION', 'priority' => 1000, @@ -64,6 +65,16 @@ class OpenNationBetting extends \sammo\Event\Action ["DeleteEvent"], ]), ]); + + if($this->bonusPoint > 0){ + $db->insert('ng_betting', [ + 'betting_id' => $bettingID, + 'general_id' => 0, + 'betting_type' => '0', + 'amount' => $this->bonusPoint + ]); + } + $logger = new \sammo\ActionLogger(0, 0, $year, $month); $logger->pushGlobalHistoryLog("【내기】천하통일을 염원하는 내기가 진행중입니다! 호사가의 참여를 기다립니다!"); $logger->flush(); diff --git a/hwe/scenario/scenario_904.json b/hwe/scenario/scenario_904.json index c6ad8f3e..05452c20 100644 --- a/hwe/scenario/scenario_904.json +++ b/hwe/scenario/scenario_904.json @@ -148,8 +148,8 @@ [ "month", 1000, ["Date", "==", 181, 1], - ["OpenNationBetting", 4], - ["OpenNationBetting", 1], + ["OpenNationBetting", 4, 1000], + ["OpenNationBetting", 1, 1000], ["DeleteEvent"] ], [ @@ -158,8 +158,8 @@ ["Date", ">=", 183, 1], ["RemainNation", "<=", 16] ], - ["OpenNationBetting", 4], - ["OpenNationBetting", 1], + ["OpenNationBetting", 4, 1000], + ["OpenNationBetting", 1, 1000], ["DeleteEvent"] ], [ @@ -168,7 +168,7 @@ ["Date", ">=", 183, 1], ["RemainNation", "<=", 8] ], - ["OpenNationBetting", 1], + ["OpenNationBetting", 1, 1000], ["DeleteEvent"] ], [ @@ -177,7 +177,7 @@ ["Date", ">=", 183, 1], ["RemainNation", "<=", 4] ], - ["OpenNationBetting", 1], + ["OpenNationBetting", 1, 1000], ["DeleteEvent"] ] ] -- 2.54.0 From f59449c15bc7463ea568965d3e96f57b8a6705f0 Mon Sep 17 00:00:00 2001 From: hide_d Date: Wed, 26 Jan 2022 23:10:55 +0900 Subject: [PATCH 19/44] =?UTF-8?q?feat(WIP):=20=EB=B2=A0=ED=8C=85=20?= =?UTF-8?q?=EA=B0=9C=EC=8B=9C=20=ED=83=80=EC=9E=85=20=EB=B3=80=EA=B2=BD=20?= =?UTF-8?q?-candidate=EB=A5=BC=20=EB=AF=B8=EB=A6=AC=20=EC=B6=94=EA=B0=80.?= =?UTF-8?q?=20-=EC=9D=B4=EB=A5=BC=20=ED=86=B5=ED=95=B4=20betting=EC=9D=84?= =?UTF-8?q?=20=EC=A4=91=EB=A6=BD=EC=A0=81=EC=9C=BC=EB=A1=9C=20=EC=9A=B4?= =?UTF-8?q?=EC=9A=A9=20=EA=B0=80=EB=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../BetNation.php => Betting/Bet.php} | 28 +++++----- .../GetBettingDetail.php | 8 +-- .../GetBettingList.php | 10 ++-- ...{NationBettingInfo.php => BettingInfo.php} | 9 +++- hwe/sammo/DTO/SelectItem.php | 15 ++++++ .../Event/Action/FinishNationBetting.php | 13 +++-- hwe/sammo/Event/Action/OpenNationBetting.php | 53 ++++++++++++++++--- 7 files changed, 101 insertions(+), 35 deletions(-) rename hwe/sammo/API/{NationBetting/BetNation.php => Betting/Bet.php} (82%) rename hwe/sammo/API/{NationBetting => Betting}/GetBettingDetail.php (91%) rename hwe/sammo/API/{NationBetting => Betting}/GetBettingList.php (87%) rename hwe/sammo/DTO/{NationBettingInfo.php => BettingInfo.php} (65%) create mode 100644 hwe/sammo/DTO/SelectItem.php diff --git a/hwe/sammo/API/NationBetting/BetNation.php b/hwe/sammo/API/Betting/Bet.php similarity index 82% rename from hwe/sammo/API/NationBetting/BetNation.php rename to hwe/sammo/API/Betting/Bet.php index 40f3b6f4..4fa82448 100644 --- a/hwe/sammo/API/NationBetting/BetNation.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -8,7 +8,7 @@ use sammo\DB; use Sammo\DTO\BettingItem; use sammo\Validator; use sammo\Json; -use sammo\DTO\NationBettingInfo; +use sammo\DTO\BettingInfo; use sammo\GameConst; use sammo\General; use sammo\KVStorage; @@ -54,14 +54,14 @@ class BetNation extends \sammo\BaseAPI $amount = $this->args['amount']; $gameStor = KVStorage::getStorage($db, 'game_env'); - $nationBettingStor = KVStorage::getStorage($db, 'nation_betting'); - $rawBettingInfo = $nationBettingStor->getValue("id_{$bettingID}"); + $bettingStor = KVStorage::getStorage($db, 'betting'); + $rawBettingInfo = $bettingStor->getValue("id_{$bettingID}"); if($rawBettingInfo === null){ return '해당 베팅이 없습니다'; } try{ - $bettingInfo = new NationBettingInfo($rawBettingInfo); + $bettingInfo = new BettingInfo($rawBettingInfo); } catch(\Error $e){ return $e->getMessage(); @@ -88,16 +88,20 @@ class BetNation extends \sammo\BaseAPI } - sort($bettingType);//NOTE: key로 바로 사용하므로 중요함 - $bettingTypeKey = Json::encode($bettingType); - $nations = getAllNationStaticInfo(); - - foreach($bettingType as $bettingNationID){ - if(!key_exists($bettingNationID, $nations)){ - return '존재하지 않는 국가를 선택했습니다.'; - } + $bettingType = array_unique($bettingType, SORT_NUMERIC);//NOTE: key로 바로 사용하므로 중요함 + if(count($bettingType) != $bettingInfo->selectCnt){ + return '중복된 값이 있습니다.'; } + if($bettingType[0] < 0){ + return '올바르지 않은 값이 있습니다.(0 미만)'; + } + + if(Util::array_last($bettingType) >= count($bettingInfo->candidates)){ + return '올바르지 않은 값이 있습니다.(초과)'; + } + + $bettingTypeKey = Json::encode($bettingType); $general = General::createGeneralObjFromDB($session->generalID, ['gold', 'aux'], 1); if($bettingInfo->reqInheritancePoint){ diff --git a/hwe/sammo/API/NationBetting/GetBettingDetail.php b/hwe/sammo/API/Betting/GetBettingDetail.php similarity index 91% rename from hwe/sammo/API/NationBetting/GetBettingDetail.php rename to hwe/sammo/API/Betting/GetBettingDetail.php index e3a4d5e8..1195fca1 100644 --- a/hwe/sammo/API/NationBetting/GetBettingDetail.php +++ b/hwe/sammo/API/Betting/GetBettingDetail.php @@ -5,7 +5,7 @@ namespace sammo\API\NationBetting; use sammo\Session; use DateTimeInterface; use sammo\DB; -use sammo\DTO\NationBettingInfo; +use sammo\DTO\BettingInfo; use sammo\General; use sammo\KVStorage; use sammo\Validator; @@ -42,14 +42,14 @@ class GetBettingDetail extends \sammo\BaseAPI $bettingID = $this->arg['betting_id']; $gameStor = KVStorage::getStorage($db, 'game_env'); - $nationBettingStor = KVStorage::getStorage($db, 'nation_betting'); - $rawBettingInfo = $nationBettingStor->getValue("id_{$bettingID}"); + $bettingStor = KVStorage::getStorage($db, 'betting'); + $rawBettingInfo = $bettingStor->getValue("id_{$bettingID}"); if($rawBettingInfo === null){ return '해당 베팅이 없습니다'; } try{ - $bettingInfo = new NationBettingInfo($rawBettingInfo); + $bettingInfo = new BettingInfo($rawBettingInfo); } catch(\Error $e){ return $e->getMessage(); diff --git a/hwe/sammo/API/NationBetting/GetBettingList.php b/hwe/sammo/API/Betting/GetBettingList.php similarity index 87% rename from hwe/sammo/API/NationBetting/GetBettingList.php rename to hwe/sammo/API/Betting/GetBettingList.php index 8f3bf0b2..0a80ae7b 100644 --- a/hwe/sammo/API/NationBetting/GetBettingList.php +++ b/hwe/sammo/API/Betting/GetBettingList.php @@ -5,7 +5,7 @@ namespace sammo\API\NationBetting; use sammo\Session; use DateTimeInterface; use sammo\DB; -use sammo\DTO\NationBettingInfo; +use sammo\DTO\BettingInfo; use sammo\KVStorage; use function sammo\checkLimit; @@ -27,10 +27,10 @@ class GetBettingList extends \sammo\BaseAPI { $db = DB::db(); - increaseRefresh("국가베팅장", 1); + increaseRefresh("베팅장", 1); $gameStor = KVStorage::getStorage($db, 'game_env'); - $nationBettingStor = KVStorage::getStorage($db, 'nation_betting'); + $bettingStor = KVStorage::getStorage($db, 'betting'); $userID = $session->userID; $me = $db->queryFirstRow('SELECT no,nation,officer_level,con,turntime,belong,penalty,permission FROM general WHERE owner=%i', $userID); @@ -40,8 +40,8 @@ class GetBettingList extends \sammo\BaseAPI } $bettingList = []; - foreach ($nationBettingStor->getAll() as $_key => $rawItem) { - $item = new NationBettingInfo($rawItem); + foreach ($bettingStor->getAll() as $_key => $rawItem) { + $item = new BettingInfo($rawItem); $bettingList[$item->id] = $rawItem; $bettingList[$item->id]['totalAmount'] = 0; } diff --git a/hwe/sammo/DTO/NationBettingInfo.php b/hwe/sammo/DTO/BettingInfo.php similarity index 65% rename from hwe/sammo/DTO/NationBettingInfo.php rename to hwe/sammo/DTO/BettingInfo.php index 2d10b293..984a8955 100644 --- a/hwe/sammo/DTO/NationBettingInfo.php +++ b/hwe/sammo/DTO/BettingInfo.php @@ -2,6 +2,8 @@ namespace sammo\DTO; +use Sammo\DTO\SelectItem; +use Spatie\DataTransferObject\Attributes\CastWith; use Spatie\DataTransferObject\Attributes\Strict; use Spatie\DataTransferObject\DataTransferObject; @@ -10,15 +12,20 @@ use Spatie\DataTransferObject\DataTransferObject; #[Strict] -class NationBettingInfo extends DataTransferObject +class BettingInfo extends DataTransferObject { public int $id; + public string $type; public string $name; public bool $finished; public int $selectCnt; public bool $reqInheritancePoint; public int $openYearMonth; public int $closeYearMonth; + + /** @var \sammo\DTO\SelectItem[] */ + #[CastWith(ArrayCaster::class, itemType: SelectItem::class)] + public array $candidates; } diff --git a/hwe/sammo/DTO/SelectItem.php b/hwe/sammo/DTO/SelectItem.php new file mode 100644 index 00000000..2ff8cffe --- /dev/null +++ b/hwe/sammo/DTO/SelectItem.php @@ -0,0 +1,15 @@ +getValue("id_{$this->bettingID}"); + $bettingStor = KVStorage::getStorage($db, 'betting'); + $bettingInfoRaw = $bettingStor->getValue("id_{$this->bettingID}"); if($bettingInfoRaw === null){ return [__CLASS__, true]; } - $bettingInfo = new NationBettingInfo($bettingInfoRaw); + $bettingInfo = new BettingInfo($bettingInfoRaw); + if($bettingInfo->type != 'nationBetting'){ + return [__CLASS__, false, 'invalid type', $bettingInfo->type]; + } $bettingInfo->finished = true; - $nationBettingStor->setValue("id_{$this->bettingID}", $bettingInfo->toArray()); + $bettingStor->setValue("id_{$this->bettingID}", $bettingInfo->toArray()); //TODO: 포인트를 배분해주어야 함 //TODO: 이후 토너먼트 베팅 결과도 같이 처리할 것이므로, 별도의 함수나 모듈을 생성하여 처리! diff --git a/hwe/sammo/Event/Action/OpenNationBetting.php b/hwe/sammo/Event/Action/OpenNationBetting.php index feea37d2..880cba06 100644 --- a/hwe/sammo/Event/Action/OpenNationBetting.php +++ b/hwe/sammo/Event/Action/OpenNationBetting.php @@ -5,10 +5,13 @@ namespace sammo\Event\Action; use \sammo\GameConst; use \sammo\Util; use \sammo\DB; -use sammo\DTO\NationBettingInfo; +use sammo\DTO\BettingInfo; +use Sammo\DTO\SelectItem; use sammo\Json; use sammo\KVStorage; +use function sammo\getAllNationStaticInfo; + class OpenNationBetting extends \sammo\Event\Action { public function __construct(private int $nationCnt = 1, private int $bonusPoint = 0) @@ -16,7 +19,7 @@ class OpenNationBetting extends \sammo\Event\Action if ($nationCnt < 1) { throw new \RuntimeException("1 미만의 숫자"); } - if ($bonusPoint < 0){ + if ($bonusPoint < 0) { throw new \RuntimeException("0 미만의 보너스 포인트"); } } @@ -30,7 +33,7 @@ class OpenNationBetting extends \sammo\Event\Action $bettingID = ($gameStor->getValue('last_betting_id') ?? 0) + 1; $gameStor->setValue('last_betting_id', $bettingID); - $nationBettingStor = KVStorage::getStorage($db, 'nation_betting'); + $bettingStor = KVStorage::getStorage($db, 'betting'); [$year, $month] = [$env['year'], $env['month']]; if ($this->nationCnt == 1) { @@ -43,16 +46,45 @@ class OpenNationBetting extends \sammo\Event\Action $openYearMonth = Util::joinYearMonth($year, $month); $closeYearMonth = $openYearMonth + 24; - $bettingInfo = new NationBettingInfo( + $citiesCnt = []; + foreach ($db->queryAllLists('SELECT nation, COUNT(*) AS cnt FROM city WHERE nation > 0 GROUP BY nation') as [$nationID, $cnt]) { + $citiesCnt[$nationID] = $cnt; + } + + /** @var \sammo\DTO\SelectItem[] */ + $candidates = []; + + foreach (getAllNationStaticInfo() as $nationRaw) { + $nationID = $nationRaw['nation']; + $cityCnt = $citiesCnt[$nationID] ?? 0; + $nationRaw['city_cnt'] = $cityCnt; + $info = [ + "국력: {$nationRaw['power']}", + "장수 수: {$nationRaw['gennum']}", + "도시 수: {$cityCnt}", + ]; + + //NOTE: 도시 정보도 추가? + $candidates[] = new SelectItem( + title: $nationRaw['name'], + info: join("
", $info), + isHtml: true, + aux: $nationRaw, + ); + } + + $bettingInfo = new BettingInfo( id: $bettingID, + type: 'bettingNation', name: "[{$year}년 {$month}월] {$name} 예상 베팅", finished: false, selectCnt: $this->nationCnt, reqInheritancePoint: true, openYearMonth: $openYearMonth, closeYearMonth: $closeYearMonth, + candidates: $candidates, ); - $nationBettingStor->setValue("id_{$bettingID}", $bettingInfo->toArray()); + $bettingStor->setValue("id_{$bettingID}", $bettingInfo->toArray()); $db->insert('event', [ 'target' => 'DESTROY_NATION', @@ -66,17 +98,22 @@ class OpenNationBetting extends \sammo\Event\Action ]), ]); - if($this->bonusPoint > 0){ + if ($this->bonusPoint > 0) { $db->insert('ng_betting', [ 'betting_id' => $bettingID, 'general_id' => 0, - 'betting_type' => '0', + 'betting_type' => '[-1]', 'amount' => $this->bonusPoint ]); } $logger = new \sammo\ActionLogger(0, 0, $year, $month); - $logger->pushGlobalHistoryLog("【내기】천하통일을 염원하는 내기가 진행중입니다! 호사가의 참여를 기다립니다!"); + if ($this->nationCnt > 1) { + $logger->pushGlobalHistoryLog("【내기】중원의 강자를 점치는 내기가 진행중입니다! 호사가의 참여를 기다립니다!"); + } else { + $logger->pushGlobalHistoryLog("【내기】천하통일 후보를 점치는 내기가 진행중입니다! 호사가의 참여를 기다립니다!"); + } + $logger->flush(); return [__CLASS__, true]; -- 2.54.0 From cf010e4e380de155a2779c36d1ec30d93fd837e7 Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 27 Jan 2022 03:30:43 +0900 Subject: [PATCH 20/44] =?UTF-8?q?fix:=20type=20react=EA=B0=80=20volar?= =?UTF-8?q?=EC=97=90=EC=84=9C=20=EB=AC=B8=EC=A0=9C=EB=A5=BC=20=EC=9D=BC?= =?UTF-8?q?=EC=9C=BC=ED=82=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/ts/@types/types__react/index.d.ts | 1 + package.json | 1 + 2 files changed, 2 insertions(+) create mode 100644 hwe/ts/@types/types__react/index.d.ts diff --git a/hwe/ts/@types/types__react/index.d.ts b/hwe/ts/@types/types__react/index.d.ts new file mode 100644 index 00000000..693da49f --- /dev/null +++ b/hwe/ts/@types/types__react/index.d.ts @@ -0,0 +1 @@ +export {} \ No newline at end of file diff --git a/package.json b/package.json index 79e82294..5fa1576b 100644 --- a/package.json +++ b/package.json @@ -64,6 +64,7 @@ "@types/jquery": "^3.5.11", "@types/lodash": "^4.14.178", "@types/node": "^17.0.4", + "@types/react": "file:hwe/ts/@types/types__react", "@typescript-eslint/eslint-plugin": "^5.8.0", "@typescript-eslint/parser": "^5.8.0", "@vue/compiler-sfc": "^3.2.26", -- 2.54.0 From 03dac8520b3b33c2c6ba64eea774321cdc93ae26 Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 27 Jan 2022 03:42:41 +0900 Subject: [PATCH 21/44] =?UTF-8?q?feat(WIP):=20=EA=B5=AD=EA=B0=80=20?= =?UTF-8?q?=EB=B2=A0=ED=8C=85=20'=EA=B8=B0=EB=8A=A5=EB=A7=8C'=20=EA=B5=AC?= =?UTF-8?q?=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/d_setting/templates/allButton.php.orig | 34 +- hwe/sammo/API/Betting/Bet.php | 45 +-- hwe/sammo/API/Betting/GetBettingDetail.php | 18 +- hwe/sammo/API/Betting/GetBettingList.php | 5 +- hwe/sammo/DTO/BettingInfo.php | 3 +- hwe/sammo/DTO/BettingItem.php | 12 +- hwe/sammo/DTO/SelectItem.php | 2 +- hwe/sammo/Event/Action/OpenNationBetting.php | 9 +- hwe/sammo/ResetHelper.php | 2 + hwe/scss/nationBetting.scss | 0 hwe/sql/reset.sql | 4 +- hwe/sql/schema.sql | 2 +- hwe/templates/allButton.php | 2 +- hwe/ts/PageNationBetting.vue | 315 +++++++++++++++++++ hwe/ts/SammoAPI.ts | 5 + hwe/ts/build_exports.json | 3 +- hwe/ts/components/MyToast.vue | 4 +- hwe/ts/v_nationBetting.ts | 12 + hwe/v_nationBetting.php | 2 +- 19 files changed, 420 insertions(+), 59 deletions(-) create mode 100644 hwe/scss/nationBetting.scss create mode 100644 hwe/ts/PageNationBetting.vue create mode 100644 hwe/ts/v_nationBetting.ts diff --git a/hwe/d_setting/templates/allButton.php.orig b/hwe/d_setting/templates/allButton.php.orig index e21f008b..f1bfd702 100644 --- a/hwe/d_setting/templates/allButton.php.orig +++ b/hwe/d_setting/templates/allButton.php.orig @@ -1,18 +1,16 @@ - +">세력도 +">세력일람 +">장수일람 +">명장일람 +">연감 +">명예의전당 +">왕조일람 +">천통국 베팅 +">삼모게시판 +">팁/강좌 +">삼국 일보 +">개인 열전 +">국가 열전 +">패치 내역 +">전투 시뮬레이터 +"> \ No newline at end of file diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index 4fa82448..f93066d1 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -1,11 +1,11 @@ args); $v->rule('required', [ - 'betting_id', - 'betting_type', + 'bettingID', + 'bettingType', 'amount' ]) - ->rule('integer', 'betting_id') - ->rule('integerArray', 'betting_type') + ->rule('integer', 'bettingID') + ->rule('integerArray', 'bettingType') ->rule('integer', 'amount') ->rule('min', 'amount', 1); @@ -47,10 +47,10 @@ class BetNation extends \sammo\BaseAPI $db = DB::db(); /** @var int */ - $bettingID = $this->arg['betting_id']; - /** @var int[] */ - $bettingType = $this->arg['betting_type']; + $bettingID = $this->args['bettingID']; /** @var int[] */ + $bettingType = $this->args['bettingType']; + /** @var int */ $amount = $this->args['amount']; $gameStor = KVStorage::getStorage($db, 'game_env'); @@ -75,7 +75,7 @@ class BetNation extends \sammo\BaseAPI $yearMonth = Util::joinYearMonth($year, $month); - if($bettingInfo->closeYearMonth > $yearMonth){ + if($bettingInfo->closeYearMonth <= $yearMonth){ return '이미 마감된 베팅입니다'; } @@ -102,15 +102,24 @@ class BetNation extends \sammo\BaseAPI } $bettingTypeKey = Json::encode($bettingType); - $general = General::createGeneralObjFromDB($session->generalID, ['gold', 'aux'], 1); + + $inheritStor = KVStorage::getStorage($db, "inheritance_{$session->userID}"); + + $prevBetAmount = $db->queryFirstField('SELECT sum(amount) FROM ng_betting WHERE betting_id = %i AND user_id = %i', $bettingID, $session->userID) ?? 0; + + if($prevBetAmount + $amount > 1000){ + return (1000 - $prevBetAmount).' 포인트까지만 베팅 가능합니다.'; + } if($bettingInfo->reqInheritancePoint){ - if($general->getInheritancePoint('previous') < $amount){ + $remainPoint = ($inheritStor->getValue('previous') ?? [0,0])[0]; + if($remainPoint < $amount){ return '유산포인트가 충분하지 않습니다.'; } } else { - if($general->getVar('gold') < GameConst::$generalMinimumGold + $amount){ + $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $session->generalID)??0; + if($remainPoint < GameConst::$generalMinimumGold + $amount){ return '금이 부족합니다.'; } } @@ -126,17 +135,17 @@ class BetNation extends \sammo\BaseAPI ]); if($bettingInfo->reqInheritancePoint){ - $general->increaseInheritancePoint('previous', -$amount); + $inheritStor->setValue('previous', [$remainPoint - $amount, null]); } else{ - $general->increaseVar('gold', -$amount); + $db->update('general', [ + 'gold' => $db->sqleval('gold - %i', $amount) + ], 'no = %i', $session->generalID); } $db->insertUpdate('ng_betting', $bettingItem->toArray()); if(!$db->affected_rows){ - $general->flushUpdateValues(); return '베팅을 실패했습니다.'; } - $general->applyDB($db); return [ 'result'=>true diff --git a/hwe/sammo/API/Betting/GetBettingDetail.php b/hwe/sammo/API/Betting/GetBettingDetail.php index 1195fca1..78e87507 100644 --- a/hwe/sammo/API/Betting/GetBettingDetail.php +++ b/hwe/sammo/API/Betting/GetBettingDetail.php @@ -1,6 +1,6 @@ arg['betting_id']; + $bettingID = $this->args['betting_id']; $gameStor = KVStorage::getStorage($db, 'game_env'); $bettingStor = KVStorage::getStorage($db, 'betting'); @@ -63,7 +64,7 @@ class GetBettingDetail extends \sammo\BaseAPI 'SELECT betting_type, sum(amount) as sum_amount FROM ng_betting WHERE betting_id = %i GROUP BY betting_type', $bettingID ) as [$bettingType, $amount]) { - $bettingDetail[] = [$bettingType, $amount]; + $bettingDetail[] = [$bettingType, Util::toInt($amount)]; } [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); @@ -73,20 +74,19 @@ class GetBettingDetail extends \sammo\BaseAPI 'SELECT betting_type, sum(amount) as sum_amount FROM ng_betting WHERE betting_id = %i AND user_id = %i GROUP BY betting_type', $bettingID, $session->userID ) as [$bettingType, $amount]){ - $myBetting[] = [$bettingType, $amount]; + $myBetting[] = [$bettingType, Util::toInt($amount)]; } - $general = General::createGeneralObjFromDB($session->generalID, ['gold', 'aux'], 1); - if($bettingInfo->reqInheritancePoint){ - $remainPoint = $general->getInheritancePoint('previous'); + $inheritStor = KVStorage::getStorage($db, "inheritance_{$session->userID}"); + $remainPoint = ($inheritStor->getValue('previous') ?? [0,0])[0]; } else{ - $remainPoint = $general->getVar('gold'); + $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $session->generalID)??0; } return [ - 'result' => false, + 'result' => true, 'bettingInfo' => $rawBettingInfo, 'bettingDetail' => $bettingDetail, 'myBetting' => $myBetting, diff --git a/hwe/sammo/API/Betting/GetBettingList.php b/hwe/sammo/API/Betting/GetBettingList.php index 0a80ae7b..df89dc55 100644 --- a/hwe/sammo/API/Betting/GetBettingList.php +++ b/hwe/sammo/API/Betting/GetBettingList.php @@ -1,6 +1,6 @@ getAll() as $_key => $rawItem) { $item = new BettingInfo($rawItem); + unset($rawItem['candidates']); $bettingList[$item->id] = $rawItem; $bettingList[$item->id]['totalAmount'] = 0; } @@ -61,7 +62,7 @@ class GetBettingList extends \sammo\BaseAPI [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); return [ - 'result' => false, + 'result' => true, 'bettingList' => $bettingList, 'year' => $year, 'month' => $month, diff --git a/hwe/sammo/DTO/BettingInfo.php b/hwe/sammo/DTO/BettingInfo.php index 984a8955..13fae86e 100644 --- a/hwe/sammo/DTO/BettingInfo.php +++ b/hwe/sammo/DTO/BettingInfo.php @@ -2,10 +2,11 @@ namespace sammo\DTO; -use Sammo\DTO\SelectItem; +use sammo\DTO\SelectItem; use Spatie\DataTransferObject\Attributes\CastWith; use Spatie\DataTransferObject\Attributes\Strict; use Spatie\DataTransferObject\DataTransferObject; +use Spatie\DataTransferObject\Casters\ArrayCaster; //https://json2dto.atymic.dev/ diff --git a/hwe/sammo/DTO/BettingItem.php b/hwe/sammo/DTO/BettingItem.php index c37d8290..d88426aa 100644 --- a/hwe/sammo/DTO/BettingItem.php +++ b/hwe/sammo/DTO/BettingItem.php @@ -1,8 +1,9 @@ $rhs['power']); + }); + + foreach ($nations as $nationRaw) { $nationID = $nationRaw['nation']; $cityCnt = $citiesCnt[$nationID] ?? 0; $nationRaw['city_cnt'] = $cityCnt; diff --git a/hwe/sammo/ResetHelper.php b/hwe/sammo/ResetHelper.php index 5c188c0c..d2638a54 100644 --- a/hwe/sammo/ResetHelper.php +++ b/hwe/sammo/ResetHelper.php @@ -133,6 +133,8 @@ class ResetHelper{ $gameStor = KVStorage::getStorage($db, 'game_env'); $gameStor->resetValues(); $gameStor->next_season_idx = $seasonIdx; + $bettingStor = KVStorage::getStorage($db, 'betting'); + $bettingStor->resetValues(); $lastExecuteStor = KVStorage::getStorage($db, 'next_execute'); $lastExecuteStor->resetValues(); diff --git a/hwe/scss/nationBetting.scss b/hwe/scss/nationBetting.scss new file mode 100644 index 00000000..e69de29b diff --git a/hwe/sql/reset.sql b/hwe/sql/reset.sql index a18f0f28..90015539 100644 --- a/hwe/sql/reset.sql +++ b/hwe/sql/reset.sql @@ -62,4 +62,6 @@ CREATE TABLE `reserved_open` ( INDEX `date` (`date`) ) DEFAULT CHARSET=utf8mb4 -ENGINE=Aria; \ No newline at end of file +ENGINE=Aria; + +DROP TABLE IF EXISTS ng_betting; \ No newline at end of file diff --git a/hwe/sql/schema.sql b/hwe/sql/schema.sql index 85346286..c7753c4c 100644 --- a/hwe/sql/schema.sql +++ b/hwe/sql/schema.sql @@ -680,7 +680,7 @@ DEFAULT CHARSET=utf8mb4 ENGINE=Aria ; -CREATE TABLE IF NOT EXISTS `ng_betting` ( +CREATE TABLE `ng_betting` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `betting_id` INT(11) NOT NULL, `general_id` INT(11) NOT NULL, diff --git a/hwe/templates/allButton.php b/hwe/templates/allButton.php index f398492f..f1bfd702 100644 --- a/hwe/templates/allButton.php +++ b/hwe/templates/allButton.php @@ -5,7 +5,7 @@ ">연감 ">명예의전당 ">왕조일람 -">접속량정보 +">천통국 베팅 ">삼모게시판 ">팁/강좌 ">삼국 일보 diff --git a/hwe/ts/PageNationBetting.vue b/hwe/ts/PageNationBetting.vue new file mode 100644 index 00000000..29313dbb --- /dev/null +++ b/hwe/ts/PageNationBetting.vue @@ -0,0 +1,315 @@ + + + \ No newline at end of file diff --git a/hwe/ts/SammoAPI.ts b/hwe/ts/SammoAPI.ts index f9fe713a..548c3da2 100644 --- a/hwe/ts/SammoAPI.ts +++ b/hwe/ts/SammoAPI.ts @@ -13,6 +13,11 @@ async function done{{ toast.title }} - {{ toast.content }} {{ toast.visible }} + {{ toast.content }} @@ -64,7 +64,7 @@ export default defineComponent({ doneMap.clear(); toasts.value.length = 0; - emit("update:modelValue", toasts); + emit("update:modelValue", toasts.value); } watch(props.modelValue, (values) => { diff --git a/hwe/ts/v_nationBetting.ts b/hwe/ts/v_nationBetting.ts new file mode 100644 index 00000000..a6269476 --- /dev/null +++ b/hwe/ts/v_nationBetting.ts @@ -0,0 +1,12 @@ +import "@scss/nationBetting.scss"; + +import { createApp } from 'vue' +import PageNationBetting from '@/PageNationBetting.vue'; +import BootstrapVue3 from 'bootstrap-vue-3'; +import { auto500px } from './util/auto500px'; + + + + +auto500px(); +createApp(PageNationBetting).use(BootstrapVue3).mount('#app'); \ No newline at end of file diff --git a/hwe/v_nationBetting.php b/hwe/v_nationBetting.php index 02a13850..a24f9a25 100644 --- a/hwe/v_nationBetting.php +++ b/hwe/v_nationBetting.php @@ -20,7 +20,7 @@ $generalID = $session->generalID; - <?= UniqueConst::$serverName ?>: 내무부 + <?= UniqueConst::$serverName ?>: 국가 베팅장 [ -- 2.54.0 From d6114132c8bbc0762106073fc612a1daa599b8cf Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 27 Jan 2022 03:55:55 +0900 Subject: [PATCH 22/44] =?UTF-8?q?fix:=20=ED=94=BC=EC=9E=A5=ED=8C=8C?= =?UTF-8?q?=EC=9E=A5=20=EC=8B=9C,=20=ED=84=B4=EC=9D=B4=2060=ED=84=B4?= =?UTF-8?q?=EC=9D=B4=20=EB=8A=98=EC=96=B4=EB=82=98=EB=8A=94=20=EA=B2=83?= =?UTF-8?q?=EC=9D=B4=20=EC=95=84=EB=8B=88=EB=9D=BC=2060=ED=84=B4=EC=9D=B4?= =?UTF-8?q?=20=EB=90=98=EB=8A=94=20=EB=B2=84=EA=B7=B8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Command/Nation/che_피장파장.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/hwe/sammo/Command/Nation/che_피장파장.php b/hwe/sammo/Command/Nation/che_피장파장.php index 5a050e31..06095d0b 100644 --- a/hwe/sammo/Command/Nation/che_피장파장.php +++ b/hwe/sammo/Command/Nation/che_피장파장.php @@ -230,7 +230,9 @@ class che_피장파장 extends Command\NationCommand $yearMonth = Util::joinYearMonth($env['year'], $env['month']); $nationStor->setValue($cmd->getNextExecuteKey(), $yearMonth + $this->getTargetPostReqTurn()); - $destNationStor->setValue($cmd->getNextExecuteKey(), $yearMonth + static::$delayCnt); + + $destDelay = max($destNationStor->getValue($cmd->getNextExecuteKey()) ?? 0, $yearMonth); + $destNationStor->setValue($cmd->getNextExecuteKey(), $destDelay + static::$delayCnt); $general->applyDB($db); -- 2.54.0 From 0f9a9f40cb0f8cf8e5b1f76854672eab20f2aefc Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 27 Jan 2022 04:01:11 +0900 Subject: [PATCH 23/44] =?UTF-8?q?game:=20=EC=9E=A5=EC=88=98=20=EC=83=9D?= =?UTF-8?q?=EC=84=B1=EC=8B=9C=20=EC=A2=85=EB=8A=A5=EC=9D=B4=20=EB=B6=80?= =?UTF-8?q?=EC=A1=B1=ED=95=98=EB=A9=B4=20=EA=B2=BD=EA=B3=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/ts/PageJoin.vue | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/hwe/ts/PageJoin.vue b/hwe/ts/PageJoin.vue index 8d8298cc..dd79678a 100644 --- a/hwe/ts/PageJoin.vue +++ b/hwe/ts/PageJoin.vue @@ -197,7 +197,7 @@ @@ -263,19 +263,19 @@
@@ -533,6 +533,13 @@ export default defineComponent({ async submitForm() { //검증은 언제 되어야 하는가? const args = clone(this.args); + const totalStat = args.leadership + args.strength + args.intel; + + if(totalStat < stats.total){ + if(!confirm(`설정한 능력치가 ${totalStat}으로, 실제 최대치인 ${stats.total}보다 적습니다.\r\n그래도 진행할까요?`)){ + return false; + } + } try { await SammoAPI.General.Join(args); } catch (e) { -- 2.54.0 From 319ae449fd1e9b5799ab3bcf33786c6d5581e575 Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 27 Jan 2022 04:12:09 +0900 Subject: [PATCH 24/44] =?UTF-8?q?fix:=20=EC=84=B8=EB=A0=A5=EC=9D=BC?= =?UTF-8?q?=EB=9E=8C=20=EB=B6=84=EC=84=9D=EC=97=90=EC=84=9C=20=EC=9E=90?= =?UTF-8?q?=EB=8F=99=EC=88=98=ED=96=89=ED=84=B4=EC=9D=84=20=EB=B0=98?= =?UTF-8?q?=EC=98=81=ED=95=98=EC=A7=80=20=EC=95=8A=EB=8A=94=20=EB=B2=84?= =?UTF-8?q?=EA=B7=B8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/a_kingdomList.php | 3 ++- hwe/ts/extKingdoms.ts | 15 +++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/hwe/a_kingdomList.php b/hwe/a_kingdomList.php index 38a38a89..c4977075 100644 --- a/hwe/a_kingdomList.php +++ b/hwe/a_kingdomList.php @@ -10,7 +10,7 @@ $userID = Session::getUserID(); $db = DB::db(); $gameStor = KVStorage::getStorage($db, 'game_env'); - +$gameStor->cacheValues(['killturn', 'autorun_user', 'turnterm']); increaseRefresh("세력일람", 2); $me = $db->queryFirstRow('SELECT con, turntime FROM general WHERE owner=%i', $userID); @@ -33,6 +33,7 @@ if ($con >= 2) { + getValues(['killturn', 'autorun_user', 'turnterm'])) ?> diff --git a/hwe/ts/extKingdoms.ts b/hwe/ts/extKingdoms.ts index c03b13ad..51b5d72d 100644 --- a/hwe/ts/extKingdoms.ts +++ b/hwe/ts/extKingdoms.ts @@ -3,6 +3,13 @@ import { unwrap } from '@util/unwrap'; import axios from 'axios'; import { setAxiosXMLHttpRequest } from '@util/setAxiosXMLHttpRequest'; +declare const killturn: number; +declare const autorun_user: undefined|null|{ + limit_minutes: number; + options: Record; +}; +declare const turnterm: number; + type KingdomGeneral = { html: JQuery, 장수명: string @@ -83,6 +90,10 @@ $(function () { } const runAnalysis = async function () { + let realKillturn = killturn; + if(autorun_user && autorun_user.limit_minutes){ + realKillturn -= autorun_user.limit_minutes / turnterm; + } const $content = $('#on_mover .content'); try { const response = await axios({ url: 'a_genList.php', method: 'get', responseType: 'text' }); @@ -197,7 +208,7 @@ $(function () { //const 종능 = val.통 + val.무 + val.지; console.log(val); if (종류명 != '무능' && 종류명 != '무지') { - if (val.삭턴 >= 80 && !val.NPC) { + if (val.삭턴 >= realKillturn && !val.NPC) { 전투유저장수 += 1; 통솔합 += val.통; @@ -214,7 +225,7 @@ $(function () { const $obj2 = $(''); $obj.html(val.장수명); - if (!val.NPC && val.삭턴 < 80) { + if (!val.NPC && val.삭턴 < realKillturn) { $obj.css('text-decoration', 'line-through'); 삭턴장수 += 1; } -- 2.54.0 From a8ba2872e1953a2969fce545b620314c3b3cde2a Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 27 Jan 2022 19:13:10 +0900 Subject: [PATCH 25/44] =?UTF-8?q?fix:=20=EB=B2=A0=ED=8C=85=20=EC=8B=9C=20k?= =?UTF-8?q?ey=20=EC=A0=95=EB=A0=AC=EC=9D=84=20=EC=88=AB=EC=9E=90=20?= =?UTF-8?q?=EC=A0=95=EB=A0=AC=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 2 +- hwe/ts/PageNationBetting.vue | 9 +++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index f93066d1..c5ffaec6 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -87,7 +87,7 @@ class Bet extends \sammo\BaseAPI return '필요한 선택 수를 채우지 못했습니다.'; } - + sort($bettingType, SORT_NUMERIC); $bettingType = array_unique($bettingType, SORT_NUMERIC);//NOTE: key로 바로 사용하므로 중요함 if(count($bettingType) != $bettingInfo->selectCnt){ return '중복된 값이 있습니다.'; diff --git a/hwe/ts/PageNationBetting.vue b/hwe/ts/PageNationBetting.vue index 29313dbb..877ecf7c 100644 --- a/hwe/ts/PageNationBetting.vue +++ b/hwe/ts/PageNationBetting.vue @@ -48,7 +48,9 @@ fontWeight: myBettings.has(betType) ? 'bold' : undefined }" >{{ getTypeStr(betType) }} -
{{ amount.toLocaleString() }}{{ myBettings.has(betType)?`(${myBettings.get(betType)?.toLocaleString()})`:'' }}
+
{{ amount.toLocaleString() }}{{ myBettings.has(betType) ? `(${myBettings.get(betType)?.toLocaleString()})` : '' }}
{{ (bettingAmount / amount).toFixed(2) }}배
@@ -178,9 +180,8 @@ function toggleCandidate(idx: number) { return; } - const typeArr = Array.from(choosedBetType.value.values()); - choosedBetTypeKey.value = JSON.stringify(typeArr.sort()); + choosedBetTypeKey.value = JSON.stringify(typeArr.sort((lhs, rhs) => lhs - rhs)); } async function loadBetting(bettingID: number) { @@ -236,7 +237,7 @@ async function loadBetting(bettingID: number) { choosedBetTypeKey.value = '[]'; myBettings.value.clear(); - for(const [betType, amount] of result.myBetting){ + for (const [betType, amount] of result.myBetting) { myBettings.value.set(betType, amount); } -- 2.54.0 From e6863539a0b8fc018e826f766a02943f967c1b2e Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 27 Jan 2022 20:02:05 +0900 Subject: [PATCH 26/44] =?UTF-8?q?game:=20npc=20=EC=83=89=EC=83=81=20?= =?UTF-8?q?=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/_admin2.php | 8 ++++---- hwe/_admin4.php | 11 ++++------- hwe/a_genList.php | 8 +------- hwe/a_kingdomList.php | 8 +------- hwe/b_betting.php | 31 ++++++------------------------- hwe/b_myGenInfo.php | 8 +------- hwe/b_tournament.php | 30 +++++------------------------- hwe/func_template.php | 31 ++++++++++++++++++++++++++----- hwe/func_tournament.php | 6 ++---- hwe/ts/common_legacy.ts | 11 ++++++++++- hwe/ts/select_npc.ts | 12 +++++++----- 11 files changed, 67 insertions(+), 97 deletions(-) diff --git a/hwe/_admin2.php b/hwe/_admin2.php index 87b2bb2b..2ccb1358 100644 --- a/hwe/_admin2.php +++ b/hwe/_admin2.php @@ -59,10 +59,10 @@ $db = DB::db(); if ($general['block'] > 0) { $style .= "background-color:red;"; } - if ($general['npc'] >= 2) { - $style .= "color:cyan;"; - } elseif ($general['npc'] == 1) { - $style .= "color:skyblue;"; + + $npcColor = getNPCColor($general['npc']); + if($npcColor !== null){ + $style .= "color:{$npcColor};"; } echo " diff --git a/hwe/_admin4.php b/hwe/_admin4.php index 2ef4c18f..39795c54 100644 --- a/hwe/_admin4.php +++ b/hwe/_admin4.php @@ -70,13 +70,10 @@ function colorBlockedName($general) if ($general['block'] > 0) { $style .= "background-color:red;"; } - if ($general['npc'] >= 2) { - $style .= "color:cyan;"; - } elseif ($general['npc'] == 1) { - $style .= "color:skyblue;"; - } - if ($general['con'] > $conlimit) { - $style .= "color:red;"; + + $npcColor = getNPCColor($general['npc']); + if($npcColor !== null){ + $style .= "color:{$npcColor};"; } echo " diff --git a/hwe/a_genList.php b/hwe/a_genList.php index b83e4e3b..750c1da5 100644 --- a/hwe/a_genList.php +++ b/hwe/a_genList.php @@ -155,13 +155,7 @@ if ($gameStor->isunited) { - if ($general['npc'] >= 2) { - $name = "{$general['name']}"; - } elseif ($general['npc'] == 1) { - $name = "{$general['name']}"; - } else { - $name = "{$general['name']}"; - } + $name = formatName($general['name'], $general['npc']); if (key_exists($general['owner'], $ownerNameList)) { $name = $name . '
(' . $ownerNameList[$general['owner']] . ')'; diff --git a/hwe/a_kingdomList.php b/hwe/a_kingdomList.php index c4977075..3c3f2e43 100644 --- a/hwe/a_kingdomList.php +++ b/hwe/a_kingdomList.php @@ -145,13 +145,7 @@ if ($con >= 2) { 장수 일람 : "; foreach ($generals as $general) { - if ($general['npc'] >= 2) { - echo "{$general['name']}, "; - } elseif ($general['npc'] == 1) { - echo "{$general['name']}, "; - } else { - echo "{$general['name']}, "; - } + echo formatName($general['name'], $general['npc']).', '; } echo " diff --git a/hwe/b_betting.php b/hwe/b_betting.php index 70285953..bed219ad 100644 --- a/hwe/b_betting.php +++ b/hwe/b_betting.php @@ -132,11 +132,8 @@ if ($str3) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + + $general['name'] = formatName($general['name'], $general['npc']); echo "{$general['name']}"; } @@ -162,11 +159,7 @@ if ($str3) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; @@ -208,11 +201,7 @@ if ($str3) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; @@ -254,11 +243,7 @@ if ($str3) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; @@ -300,11 +285,7 @@ if ($str3) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; diff --git a/hwe/b_myGenInfo.php b/hwe/b_myGenInfo.php index 015559e7..8d2a6c7d 100644 --- a/hwe/b_myGenInfo.php +++ b/hwe/b_myGenInfo.php @@ -146,13 +146,7 @@ if ($gameStor->isunited) { $intel = "{$general['intel']}"; } - if ($general['npc'] >= 2) { - $name = "{$general['name']}"; - } elseif ($general['npc'] == 1) { - $name = "{$general['name']}"; - } else { - $name = "{$general['name']}"; - } + $name = formatName($general['name'], $general['npc']); if (key_exists($general['owner'], $ownerNameList)) { $name = $name . '
(' . $ownerNameList[$general['owner']] . ')'; diff --git a/hwe/b_tournament.php b/hwe/b_tournament.php index cb4bc0d6..b486f61d 100644 --- a/hwe/b_tournament.php +++ b/hwe/b_tournament.php @@ -240,11 +240,7 @@ switch ($admin['tnmt_type']) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); echo "{$general['name']}"; } @@ -270,11 +266,7 @@ switch ($admin['tnmt_type']) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; @@ -316,11 +308,7 @@ switch ($admin['tnmt_type']) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; @@ -363,11 +351,7 @@ switch ($admin['tnmt_type']) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; @@ -409,11 +393,7 @@ switch ($admin['tnmt_type']) { if ($general['name'] == "") { $general['name'] = "-"; } - if ($general['npc'] >= 2) { - $general['name'] = "" . $general['name'] . ""; - } elseif ($general['npc'] == 1) { - $general['name'] = "" . $general['name'] . ""; - } + $general['name'] = formatName($general['name'], $general['npc']); if ($general['win'] > 0) { $line[$i] = ""; $cent[intdiv($i, 2)] = ""; diff --git a/hwe/func_template.php b/hwe/func_template.php index 6f264148..5ef56848 100644 --- a/hwe/func_template.php +++ b/hwe/func_template.php @@ -215,14 +215,35 @@ function formatLeadershipBonus(int $value): string return "+{$value}"; } +function getNPCColor(int $npc): ?string{ + if ($npc == 1) { + return 'skyblue'; + } + if ($npc == 4){ + return 'deepskyblue'; + } + if ($npc == 5){ + return 'darkcyan'; + } + if ($npc == 6){ + return 'mediumaquamarine'; + } + + if ($npc > 1) { + return 'cyan'; + } + + return null; +} + function formatName(string $name, int $npc): string { - if ($npc == 1) { - $name = "$name"; - } else if ($npc > 1) { - $name = "$name"; + $color = getNPCColor($npc); + if($color === null){ + return $name; } - return $name; + + return "$name"; } function getMapTheme(): string diff --git a/hwe/func_tournament.php b/hwe/func_tournament.php index d3d8c3cc..0fe0b0cc 100644 --- a/hwe/func_tournament.php +++ b/hwe/func_tournament.php @@ -261,10 +261,8 @@ function printRow($k, $npc, $name, $abil, $tgame, $win, $draw, $lose, $gd, $gl, $k += 1; if ($prmt > 0) { $name = "" . $name . ""; - } elseif ($npc >= 2) { - $name = "" . $name . ""; - } elseif ($npc == 1) { - $name = "" . $name . ""; + } else if($npc > 0){ + $name = formatName($name, $npc); } echo "$k$name$abil$tgame$win$draw$lose$gd$gl"; } diff --git a/hwe/ts/common_legacy.ts b/hwe/ts/common_legacy.ts index 3a6ecc3c..7773309b 100644 --- a/hwe/ts/common_legacy.ts +++ b/hwe/ts/common_legacy.ts @@ -79,7 +79,16 @@ function br2nl (text) { } */ -export function getNpcColor(npcType: number): 'cyan' | 'skyblue' | null { +export function getNpcColor(npcType: number): 'skyblue' | 'cyan' | 'deepskyblue' | 'darkcyan' | 'mediumaquamarine' | null { + if (npcType == 6){ + return 'mediumaquamarine'; + } + if (npcType == 5){ + return 'darkcyan'; + } + if (npcType == 4){ + return 'deepskyblue'; + } if (npcType >= 2) { return 'cyan'; } diff --git a/hwe/ts/select_npc.ts b/hwe/ts/select_npc.ts index 092eca73..0757c91c 100644 --- a/hwe/ts/select_npc.ts +++ b/hwe/ts/select_npc.ts @@ -306,10 +306,8 @@ function printGeneralList(value: GeneralListResponse) { if (general.reserved == 1) { general.userCSS = 'color:violet'; - } else if (general.npc >= 2) { - general.userCSS = 'color:cyan'; - } else if (general.npc == 1) { - general.userCSS = 'color:skyblue'; + } else if (general.npc > 0) { + general.userCSS = `color:${getNPCColor(general.npc)}`; } if (general.ownerName) { @@ -458,4 +456,8 @@ $(function ($) { _printGeneralList(); }) -}); \ No newline at end of file +}); + +function getNPCColor(npc: number) { + throw new Error('Function not implemented.'); +} -- 2.54.0 From 3611ee6cfe41cbedf73d650e21b7b48569f42c4e Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 28 Jan 2022 01:09:21 +0900 Subject: [PATCH 27/44] =?UTF-8?q?fix:=20volar=20error=20=EC=88=98=EC=A0=95?= =?UTF-8?q?=20-=20getNPCColor=20=EB=B0=98=ED=99=98=ED=98=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/ts/PageInheritPoint.vue | 2 +- hwe/ts/PageNPCControl.vue | 6 +++--- hwe/ts/PageNationStratFinan.vue | 2 +- hwe/ts/common_legacy.ts | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/hwe/ts/PageInheritPoint.vue b/hwe/ts/PageInheritPoint.vue index 9518c036..8be38a91 100644 --- a/hwe/ts/PageInheritPoint.vue +++ b/hwe/ts/PageInheritPoint.vue @@ -105,7 +105,7 @@ diff --git a/hwe/ts/PageNPCControl.vue b/hwe/ts/PageNPCControl.vue index 345cbc10..c489c59c 100644 --- a/hwe/ts/PageNPCControl.vue +++ b/hwe/ts/PageNPCControl.vue @@ -67,7 +67,7 @@ >유저전투장에게 주는 금입니다. 이보다 적으면 포상합니다.
0이면 유저전투장 긴급포상 금의 2배를 기준으로 하며, 그 수치는 현재 {{ - (calcPolicyValue("reqHumanWarUrgentGold") * 2).toLocaleString() + (calcPolicyValue("reqHumanWarUrgentGold") as number * 2).toLocaleString() }}입니다.
@@ -79,7 +79,7 @@ >유저전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다.
0이면 유저전투장 긴급포상 쌀의 2배를 기준으로 하며, 그 수치는 현재 {{ - (calcPolicyValue("reqHumanWarUrgentRice") * 2).toLocaleString() + (calcPolicyValue("reqHumanWarUrgentRice") as number * 2).toLocaleString() }}입니다. @@ -505,7 +505,7 @@ type SetterInfo = { }; declare const lastSetters: { - polcy: SetterInfo; + policy: SetterInfo; nation: SetterInfo; general: SetterInfo; }; diff --git a/hwe/ts/PageNationStratFinan.vue b/hwe/ts/PageNationStratFinan.vue index 10f4d5b8..8775cecf 100644 --- a/hwe/ts/PageNationStratFinan.vue +++ b/hwe/ts/PageNationStratFinan.vue @@ -44,7 +44,7 @@
Date: Fri, 28 Jan 2022 01:23:38 +0900 Subject: [PATCH 28/44] fix: template --- hwe/ts/PageNPCControl.vue | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/hwe/ts/PageNPCControl.vue b/hwe/ts/PageNPCControl.vue index c489c59c..039688bf 100644 --- a/hwe/ts/PageNPCControl.vue +++ b/hwe/ts/PageNPCControl.vue @@ -67,7 +67,7 @@ >유저전투장에게 주는 금입니다. 이보다 적으면 포상합니다.
0이면 유저전투장 긴급포상 금의 2배를 기준으로 하며, 그 수치는 현재 {{ - (calcPolicyValue("reqHumanWarUrgentGold") as number * 2).toLocaleString() + (calcPolicyValue("reqHumanWarUrgentGold") * 2).toLocaleString() }}입니다.
@@ -79,7 +79,7 @@ >유저전투장에게 주는 쌀입니다. 이보다 적으면 포상합니다.
0이면 유저전투장 긴급포상 쌀의 2배를 기준으로 하며, 그 수치는 현재 {{ - (calcPolicyValue("reqHumanWarUrgentRice") as number * 2).toLocaleString() + (calcPolicyValue("reqHumanWarUrgentRice") * 2).toLocaleString() }}입니다. -- 2.54.0 From 63f9c942beae08e1318ba05ed0297e27d2d6682b Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 28 Jan 2022 01:32:45 +0900 Subject: [PATCH 29/44] =?UTF-8?q?build:=20warning=20=EA=B8=B0=EC=A4=80=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD=20-=205MB,=203MB.......?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webpack.config.cjs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/webpack.config.cjs b/webpack.config.cjs index 6ebc5a89..f959cc52 100644 --- a/webpack.config.cjs +++ b/webpack.config.cjs @@ -89,6 +89,11 @@ module.exports = (env, argv) => { moduleIds: 'deterministic', }; + const performance = { + maxAssetSize: 5*1024*1024, + maxEntrypointSize: 3*1024*1024, + } + const ingame_vue = { name: `ingame_${versionTarget}_vue`, resolve: { @@ -200,6 +205,7 @@ module.exports = (env, argv) => { cacheDirectory, cacheLocation: path.resolve(cacheDirectory, `ingame_vue_${mode}`) }, + performance, }; const ingame = { name: `ingame_${versionTarget}`, @@ -275,6 +281,7 @@ module.exports = (env, argv) => { cacheDirectory, cacheLocation: path.resolve(cacheDirectory, `ingame_ts_${mode}`) }, + performance, }; const gateway = { name: `gateway`, @@ -355,6 +362,7 @@ module.exports = (env, argv) => { cacheDirectory, cacheLocation: path.resolve(cacheDirectory, `gateway_ts_${mode}`) }, + performance, }; if (env.WEBPACK_WATCH || !versionValue) { -- 2.54.0 From bb3526c1314796b7e137decfe5da6eca43c57f84 Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 28 Jan 2022 01:40:12 +0900 Subject: [PATCH 30/44] fix: NPCControl volar error --- hwe/ts/PageNPCControl.vue | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/hwe/ts/PageNPCControl.vue b/hwe/ts/PageNPCControl.vue index 039688bf..84ad30d6 100644 --- a/hwe/ts/PageNPCControl.vue +++ b/hwe/ts/PageNPCControl.vue @@ -472,7 +472,7 @@ import { ToastType, } from "@/defs"; import NumberInputWithInfo from "@/components/NumberInputWithInfo.vue"; -import { cloneDeep, isEqual, last } from "lodash"; +import { cloneDeep, isEqual, isNumber, last } from "lodash"; import { unwrap } from "@util/unwrap"; import { convertFormData } from "@util/convertFormData"; import axios from "axios"; @@ -592,14 +592,18 @@ export default defineComponent({ }, calcPolicyValue( title: keyof NationPolicy - ): NationPolicy[keyof NationPolicy] { + ): number { if (!(title in this.nationPolicy)) { throw `${title}이 NationPolicy key가 아님`; } - if (this.nationPolicy[title] == 0) { - return this.zeroPolicy[title]; + const policyValue = this.nationPolicy[title]; + if(!isNumber(policyValue)){ + throw `${title}에 해당하는 값이 number가 아님`; } - return this.nationPolicy[title]; + if (policyValue == 0) { + return this.zeroPolicy[title] as number; + } + return policyValue; }, resetNationPriority() { if (!confirm("초기 설정으로 되돌릴까요?")) { -- 2.54.0 From f42aab61e3fca229bb779df36bfaa0d8af426961 Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 28 Jan 2022 02:39:40 +0900 Subject: [PATCH 31/44] =?UTF-8?q?feat:=20=EA=B5=AD=EA=B0=80=20=EB=B2=A0?= =?UTF-8?q?=ED=8C=85=20ui?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/scss/nationBetting.scss | 62 +++++++++++++++++++++++ hwe/ts/PageNationBetting.vue | 96 +++++++++++++++++++++++++----------- 2 files changed, 128 insertions(+), 30 deletions(-) diff --git a/hwe/scss/nationBetting.scss b/hwe/scss/nationBetting.scss index e69de29b..50f4d698 100644 --- a/hwe/scss/nationBetting.scss +++ b/hwe/scss/nationBetting.scss @@ -0,0 +1,62 @@ +@import '@scss/common/bootstrap5.scss'; +@import "@scss/game_bg.scss"; +@import "@scss/util.scss"; + + +@include media-1000px { + #container { + width: 1000px; + margin: 0 auto; + position: relative; + } +} + +@include media-500px { + #container { + position: relative; + width: 500px; + margin: auto; + overflow-x: hidden; + } +} + +.bettingCandidate{ + border: gray 1px solid; + border-radius: 0.5em; + overflow: hidden; + cursor: pointer; + + .title{ + background-clip: padding-box; + text-align: center; + } + + .info{ + padding: 1ch; + } + + .pickRate{ + padding: 1ch; + } +} + +.bettingCandidate.picked{ + outline: white 1.5px solid; + border: white 1px solid; + .title{ + font-weight: bolder; + } +} + +.bettingList{ + margin-top: 1em; +} + +.bettingItem{ + margin: 0.25em; + cursor: pointer; + + &:hover{ + text-decoration: underline; + } +} \ No newline at end of file diff --git a/hwe/ts/PageNationBetting.vue b/hwe/ts/PageNationBetting.vue index 877ecf7c..04605196 100644 --- a/hwe/ts/PageNationBetting.vue +++ b/hwe/ts/PageNationBetting.vue @@ -4,7 +4,7 @@
로딩 중...
+
베팅 목록
()); -const choosedBetTypeKey = ref('[]'); +const pickedBetType = ref(new Set()); +const pickedBetTypeKey = ref('[]'); const betPoint = ref(0); const myBettings = ref(new Map()); @@ -166,22 +195,29 @@ function toggleCandidate(idx: number) { const selectCnt = bettingInfo.value.bettingInfo.selectCnt; if (selectCnt == 1) { - choosedBetTypeKey.value = JSON.stringify([idx]); + pickedBetType.value.clear(); + pickedBetType.value.add(idx); + pickedBetTypeKey.value = JSON.stringify([idx]); return; } - if (choosedBetType.value.has(idx)) { - choosedBetType.value.delete(idx); + if (pickedBetType.value.has(idx)) { + pickedBetType.value.delete(idx); } - else if (choosedBetType.value.size < selectCnt) { - choosedBetType.value.add(idx); + else if (pickedBetType.value.size < selectCnt) { + pickedBetType.value.add(idx); } else { + toasts.value.push({ + title: '오류', + type: 'warning', + content: `이미 ${selectCnt}개를 선택했습니다.`, + }) return; } - const typeArr = Array.from(choosedBetType.value.values()); - choosedBetTypeKey.value = JSON.stringify(typeArr.sort((lhs, rhs) => lhs - rhs)); + const typeArr = Array.from(pickedBetType.value.values()); + pickedBetTypeKey.value = JSON.stringify(typeArr.sort((lhs, rhs) => lhs - rhs)); } async function loadBetting(bettingID: number) { @@ -233,8 +269,8 @@ async function loadBetting(bettingID: number) { return rhsVal - lhsVal; }) - choosedBetType.value.clear(); - choosedBetTypeKey.value = '[]'; + pickedBetType.value.clear(); + pickedBetTypeKey.value = '[]'; myBettings.value.clear(); for (const [betType, amount] of result.myBetting) { @@ -261,7 +297,7 @@ async function submitBet(): Promise { } const bettingID = info.bettingInfo.id; - const bettingType = JSON.parse(choosedBetTypeKey.value); + const bettingType = JSON.parse(pickedBetTypeKey.value); const amount = betPoint.value; try { await SammoAPI.Betting.Bet({ -- 2.54.0 From 19bb9881ea9a0ec1d58e4106b63be08f43251917 Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 28 Jan 2022 02:43:58 +0900 Subject: [PATCH 32/44] =?UTF-8?q?fix:=20=EB=B2=A0=ED=8C=85=20=EA=B4=80?= =?UTF-8?q?=EB=A0=A8=20=EC=82=AC=EC=86=8C=ED=95=9C=20=EB=B2=84=EA=B7=B8=20?= =?UTF-8?q?=EC=88=98=EC=A0=95=20-=20=EB=B2=A0=ED=8C=85=EC=9D=B4=20?= =?UTF-8?q?=EC=97=86=EC=9D=84=20=EA=B2=BD=EC=9A=B0=20-=20=EB=B2=A0?= =?UTF-8?q?=ED=8C=85=20=EB=8F=99=EC=8B=9C=20=EC=8B=A0=EC=B2=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 2 +- hwe/sammo/API/Betting/GetBettingDetail.php | 1 - hwe/sammo/API/Betting/GetBettingList.php | 14 ++++++++++++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index c5ffaec6..40bb3d81 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -39,7 +39,7 @@ class Bet extends \sammo\BaseAPI public function getRequiredSessionMode(): int { - return static::REQ_GAME_LOGIN | static::REQ_READ_ONLY; + return static::REQ_GAME_LOGIN; } public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag) diff --git a/hwe/sammo/API/Betting/GetBettingDetail.php b/hwe/sammo/API/Betting/GetBettingDetail.php index 78e87507..99548309 100644 --- a/hwe/sammo/API/Betting/GetBettingDetail.php +++ b/hwe/sammo/API/Betting/GetBettingDetail.php @@ -38,7 +38,6 @@ class GetBettingDetail extends \sammo\BaseAPI { $db = DB::db(); - increaseRefresh("국가베팅장", 1); /** @var int */ $bettingID = $this->args['betting_id']; diff --git a/hwe/sammo/API/Betting/GetBettingList.php b/hwe/sammo/API/Betting/GetBettingList.php index df89dc55..57a25fbf 100644 --- a/hwe/sammo/API/Betting/GetBettingList.php +++ b/hwe/sammo/API/Betting/GetBettingList.php @@ -36,7 +36,7 @@ class GetBettingList extends \sammo\BaseAPI $me = $db->queryFirstRow('SELECT no,nation,officer_level,con,turntime,belong,penalty,permission FROM general WHERE owner=%i', $userID); $con = checkLimit($me['con']); if ($con >= 2) { - return "접속 제한중입니다. 1턴 이내에 너무 많은 갱신을 하셨습니다. (다음 갱신 가능 시각 : {$me['turntime']})"; + return "접속 제한중입니다."; } $bettingList = []; @@ -47,6 +47,17 @@ class GetBettingList extends \sammo\BaseAPI $bettingList[$item->id]['totalAmount'] = 0; } + [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); + + if(!$bettingList){ + return [ + 'result' => true, + 'bettingList' => $bettingList, + 'year' => $year, + 'month' => $month, + ]; + } + $bettingIDList = array_keys($bettingList); // XXX: query cache만 믿고 sum을 하는 짓을 벌여도 되는가? foreach ($db->queryAllLists( @@ -59,7 +70,6 @@ class GetBettingList extends \sammo\BaseAPI $bettingList[$bettingID]['totalAmount'] = $totalAmount; } - [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); return [ 'result' => true, -- 2.54.0 From 4d84396cf6852ad95b0fe8738a71c9fc783cdf9e Mon Sep 17 00:00:00 2001 From: Hide_D Date: Fri, 28 Jan 2022 14:02:12 +0900 Subject: [PATCH 33/44] =?UTF-8?q?fix:=20=EB=B2=A0=ED=8C=85=20=EC=88=9C?= =?UTF-8?q?=EC=84=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index 40bb3d81..3102eb89 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -134,6 +134,7 @@ class Bet extends \sammo\BaseAPI 'amount'=>$amount ]); + $db->insertUpdate('ng_betting', $bettingItem->toArray()); if($bettingInfo->reqInheritancePoint){ $inheritStor->setValue('previous', [$remainPoint - $amount, null]); } @@ -142,7 +143,6 @@ class Bet extends \sammo\BaseAPI 'gold' => $db->sqleval('gold - %i', $amount) ], 'no = %i', $session->generalID); } - $db->insertUpdate('ng_betting', $bettingItem->toArray()); if(!$db->affected_rows){ return '베팅을 실패했습니다.'; } -- 2.54.0 From 6fb4a1b2745c524ae15302d0f33c6b80a6b5d632 Mon Sep 17 00:00:00 2001 From: Hide_D Date: Fri, 28 Jan 2022 14:11:51 +0900 Subject: [PATCH 34/44] =?UTF-8?q?fix:=20=EB=B2=A0=ED=8C=85=EC=8B=9C=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20=ED=8F=AC=EC=9D=B8=ED=8A=B8=20=EB=B6=80?= =?UTF-8?q?=EC=97=AC=20=EB=B6=88=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index 3102eb89..91005cb5 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -134,7 +134,11 @@ class Bet extends \sammo\BaseAPI 'amount'=>$amount ]); - $db->insertUpdate('ng_betting', $bettingItem->toArray()); + $db->insertUpdate( + 'ng_betting', + $bettingItem->toArray(), + ['amount' => $db->sqleval('amount + %i', $amount)] + ); if($bettingInfo->reqInheritancePoint){ $inheritStor->setValue('previous', [$remainPoint - $amount, null]); } -- 2.54.0 From 3dcf5ce75f2166e1e158edcf99838cc7008edac6 Mon Sep 17 00:00:00 2001 From: Hide_D Date: Fri, 28 Jan 2022 14:12:42 +0900 Subject: [PATCH 35/44] =?UTF-8?q?Revert=20"fix:=20=EB=B2=A0=ED=8C=85?= =?UTF-8?q?=EC=8B=9C=20=EC=B6=94=EA=B0=80=20=ED=8F=AC=EC=9D=B8=ED=8A=B8=20?= =?UTF-8?q?=EB=B6=80=EC=97=AC=20=EB=B6=88=EA=B0=80"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 6fb4a1b2745c524ae15302d0f33c6b80a6b5d632. --- hwe/sammo/API/Betting/Bet.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index 91005cb5..3102eb89 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -134,11 +134,7 @@ class Bet extends \sammo\BaseAPI 'amount'=>$amount ]); - $db->insertUpdate( - 'ng_betting', - $bettingItem->toArray(), - ['amount' => $db->sqleval('amount + %i', $amount)] - ); + $db->insertUpdate('ng_betting', $bettingItem->toArray()); if($bettingInfo->reqInheritancePoint){ $inheritStor->setValue('previous', [$remainPoint - $amount, null]); } -- 2.54.0 From 3abbade1cbc65bd396d839a83973bb55b930980e Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 28 Jan 2022 14:19:37 +0900 Subject: [PATCH 36/44] =?UTF-8?q?fix:=20=EB=B2=A0=ED=8C=85=EC=8B=9C=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80=20=ED=8F=AC=EC=9D=B8=ED=8A=B8=20=EB=B6=80?= =?UTF-8?q?=EC=97=AC=20=EB=B6=88=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index 3102eb89..46bc53e7 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -134,8 +134,11 @@ class Bet extends \sammo\BaseAPI 'amount'=>$amount ]); - $db->insertUpdate('ng_betting', $bettingItem->toArray()); - if($bettingInfo->reqInheritancePoint){ + $db->insertUpdate( + 'ng_betting', + $bettingItem->toArray(), + ['amount' => $db->sqleval('amount + %i', $amount)] + ); if($bettingInfo->reqInheritancePoint){ $inheritStor->setValue('previous', [$remainPoint - $amount, null]); } else{ -- 2.54.0 From b0d6acbb4746cb8d3b5884895c621a5df4772b8c Mon Sep 17 00:00:00 2001 From: hide_d Date: Thu, 3 Feb 2022 23:28:38 +0900 Subject: [PATCH 37/44] =?UTF-8?q?feat:=20=EB=A9=94=EC=9D=B8=20=ED=8E=98?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=EC=97=90=20=ED=86=A0=EB=84=88=EB=A8=BC?= =?UTF-8?q?=ED=8A=B8=20=EA=B0=9C=EC=B5=9C=EA=B8=B0=EA=B0=84=20=ED=91=9C?= =?UTF-8?q?=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/b_betting.php | 2 +- hwe/b_tournament.php | 2 +- hwe/func_tournament.php | 62 ++++++++++++++++++++++------------------- hwe/index.php | 8 +++--- 4 files changed, 39 insertions(+), 35 deletions(-) diff --git a/hwe/b_betting.php b/hwe/b_betting.php index bed219ad..bbf065df 100644 --- a/hwe/b_betting.php +++ b/hwe/b_betting.php @@ -69,7 +69,7 @@ $str2 = getTournamentTime(); if ($str2) { $str2 = ', ' . $str2; } -$str3 = getTournamentTerm(); +$str3 = getTournamentTermText(); if ($str3) { $str3 = ', ' . $str3; } diff --git a/hwe/b_tournament.php b/hwe/b_tournament.php index b486f61d..a174cbfc 100644 --- a/hwe/b_tournament.php +++ b/hwe/b_tournament.php @@ -198,7 +198,7 @@ switch ($admin['tnmt_type']) { if ($str2) { $str2 = ', ' . $str2; } - $str3 = getTournamentTerm(); + $str3 = getTournamentTermText(); if ($str3) { $str3 = ', ' . $str3; } diff --git a/hwe/func_tournament.php b/hwe/func_tournament.php index 0fe0b0cc..80fd8744 100644 --- a/hwe/func_tournament.php +++ b/hwe/func_tournament.php @@ -164,40 +164,44 @@ function processTournament() $gameStor->tnmt_time = (new \DateTimeImmutable($admin['tnmt_time']))->add(new \DateInterval("PT{$second}S"))->format('Y-m-d H:i:s'); } -function getTournamentTerm() -{ +function getTournamentTerm(): ?int{ $db = DB::db(); $gameStor = KVStorage::getStorage($db, 'game_env'); $tnmt_auto = $gameStor->tnmt_auto; - - switch ($tnmt_auto) { - case 0: - $str = ''; - break; - case 1: - $str = "경기당 12분"; - break; - case 2: - $str = "경기당 7분"; - break; - case 3: - $str = "경기당 3분"; - break; - case 4: - $str = "경기당 1분"; - break; - case 5: - $str = "경기당 30초"; - break; - case 6: - $str = "경기당 15초"; - break; - case 7: - $str = "경기당 5초"; - break; + switch($tnmt_auto){ + case 0: return null; + case 1: return 12 * 60; + case 2: return 7 * 60; + case 3: return 3 * 60; + case 4: return 1 * 60; + case 5: return 30; + case 6: return 15; + case 7: return 5; } - return $str; + return null; +} + +function getTournamentTermText() +{ + $term = getTournamentTerm(); + + if($term === null){ + return '수동'; + } + + if($term % 60 === 0){ + $termMin = intdiv($term, 60); + return "경기당 {$termMin}분"; + } + + if($term > 60){ + $termSec = $term % 60; + $termMin = intdiv($term, 60); + return "경기당 {$termMin}분 {$termSec}초"; + } + + return "경기당 {$term}초"; } function getTournamentTime() diff --git a/hwe/index.php b/hwe/index.php index 67d4cb93..c7ece75b 100644 --- a/hwe/index.php +++ b/hwe/index.php @@ -149,14 +149,14 @@ if (!$otherTextInfo) {
- NPC수 : -
-
- NPC상성 : + NPC 수, 상성 : ,
NPC선택 :
+
+ 토너먼트 : +
기타 설정:
-- 2.54.0 From a25442efa78a4c0aa19ae72182134a56f58747b2 Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 4 Feb 2022 03:48:28 +0900 Subject: [PATCH 38/44] =?UTF-8?q?feat(WIP):=20=EB=B3=B4=EC=83=81=EC=9D=84?= =?UTF-8?q?=20=EC=9C=84=ED=95=9C=20Betting=20=EB=AA=A8=EB=93=88=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 33 +---- hwe/sammo/Betting.php | 235 ++++++++++++++++++++++++++++++++++ hwe/sammo/DTO/BettingInfo.php | 1 + 3 files changed, 240 insertions(+), 29 deletions(-) create mode 100644 hwe/sammo/Betting.php diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index 46bc53e7..36e343f1 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -4,13 +4,11 @@ namespace sammo\API\Betting; use sammo\Session; use DateTimeInterface; +use sammo\Betting; use sammo\DB; use sammo\DTO\BettingItem; use sammo\Validator; -use sammo\Json; -use sammo\DTO\BettingInfo; use sammo\GameConst; -use sammo\General; use sammo\KVStorage; use sammo\Util; @@ -54,18 +52,9 @@ class Bet extends \sammo\BaseAPI $amount = $this->args['amount']; $gameStor = KVStorage::getStorage($db, 'game_env'); - $bettingStor = KVStorage::getStorage($db, 'betting'); - $rawBettingInfo = $bettingStor->getValue("id_{$bettingID}"); - if($rawBettingInfo === null){ - return '해당 베팅이 없습니다'; - } - try{ - $bettingInfo = new BettingInfo($rawBettingInfo); - } - catch(\Error $e){ - return $e->getMessage(); - } + $bettingHelper = new Betting($bettingID); + $bettingInfo = $bettingHelper->getInfo(); if($bettingInfo->finished){ return '이미 종료된 베팅입니다'; @@ -87,21 +76,7 @@ class Bet extends \sammo\BaseAPI return '필요한 선택 수를 채우지 못했습니다.'; } - sort($bettingType, SORT_NUMERIC); - $bettingType = array_unique($bettingType, SORT_NUMERIC);//NOTE: key로 바로 사용하므로 중요함 - if(count($bettingType) != $bettingInfo->selectCnt){ - return '중복된 값이 있습니다.'; - } - - if($bettingType[0] < 0){ - return '올바르지 않은 값이 있습니다.(0 미만)'; - } - - if(Util::array_last($bettingType) >= count($bettingInfo->candidates)){ - return '올바르지 않은 값이 있습니다.(초과)'; - } - - $bettingTypeKey = Json::encode($bettingType); + $bettingTypeKey = $bettingHelper->convertBettingKey($bettingType); $inheritStor = KVStorage::getStorage($db, "inheritance_{$session->userID}"); diff --git a/hwe/sammo/Betting.php b/hwe/sammo/Betting.php new file mode 100644 index 00000000..7a345bf8 --- /dev/null +++ b/hwe/sammo/Betting.php @@ -0,0 +1,235 @@ +getValue("id_{$bettingID}"); + if ($rawBettingInfo === null) { + throw new \RuntimeException("해당 베팅이 없습니다: {$bettingID}"); + } + $this->info = new BettingInfo($rawBettingInfo); + } + + private function _convertBettingKey(array $bettingType): string + { + return Json::encode($bettingType); + } + + public function convertBettingKey(array $bettingType): string + { + $selectCnt = $this->info->selectCnt; + sort($bettingType, SORT_NUMERIC); + $bettingType = array_unique($bettingType, SORT_NUMERIC); //NOTE: key로 바로 사용하므로 중요함 + if (count($bettingType) != $selectCnt) { + throw new \InvalidArgumentException('중복된 값이 있습니다.'); + } + + if ($bettingType[0] < 0) { + throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(0 미만)'); + } + + if (Util::array_last($bettingType) >= count($this->info->candidates)) { + throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(초과)'); + } + + return $this->_convertBettingKey($bettingType); + } + + public function getInfo(): BettingInfo + { + return $this->info; + } + + /** @param int[] $result */ + private function _calcRewardExclusive(array $bettingType): array + { + $db = DB::db(); + $totalAmount = $db->queryFirstField('SELECT sum(amount) FROM ng_betting WHERE betting_id = %i'); + + if ($totalAmount == 0) { + return []; + } + + $winnerList = $db->queryAllLists( + 'SELECT general_id, user_id, amount WHERE betting_id = %i AND betting_type = %s', + $this->bettingID, + $this->_convertBettingKey($bettingType) + ); + + $subAmount = 0; + foreach ($winnerList as [,, $amount]) { + $subAmount += $amount; + } + + if ($subAmount == 0) { + return []; + } + + $multiplier = $totalAmount / $subAmount; + $selectCnt = $this->info->selectCnt; + + $result = []; + foreach ($winnerList as [$generalID, $userID, $amount]) { + $result[$generalID] = [ + 'generalID' => $generalID, + 'userID' => $userID, + 'amount' => $amount * $multiplier, + 'matchPoint' => $selectCnt, + ]; + } + return $result; + } + + + + /** @param int[] $winnerType */ + public function calcReward(array $winnerType): array + { + $selectCnt = $this->info->selectCnt; + if ($selectCnt == 1) { + return $this->_calcRewardExclusive($winnerType); + } + + if ($this->info->isExlusive) { + return $this->_calcRewardExclusive($winnerType); + } + //아래는 2개 이상, 복합 보상 옵션 + + $winnerTypeMap = []; + foreach ($winnerType as $typeVal) { + $winnerTypeMap[$typeVal] = $typeVal; + } + + $calcMatchPoint = function ($bettingType) use ($winnerTypeMap): int { + $result = 0; + foreach ($bettingType as $typeVal) { + if (key_exists($typeVal, $winnerTypeMap)) { + $result += 1; + } + } + return $result; + }; + + $totalAmount = 0; + $subAmount = []; + $subWinners = []; + + foreach (Util::range($selectCnt + 1) as $matchPoint) { + $subAmount[$matchPoint] = 0; + $subWinners[$matchPoint] = []; + } + + $db = DB::db(); + foreach ($db->queryAllLists( + 'SELECT general_id, user_id, amount, betting_type WHERE betting_id = %i', + $this->bettingID + ) as [$generalID, $userID, $amount, $bettingTypeKey]) { + $bettingType = Json::decode($bettingTypeKey); + $matchPoint = $calcMatchPoint($bettingType); + $totalAmount += $amount; + if ($generalID == 0) { + continue; + } + $subAmount[$matchPoint] += $amount; + $subWinners[$matchPoint][] = [ + 'generalID' => $generalID, + 'userID' => $userID, + 'amount' => $amount, + 'matchPoint' => $matchPoint, + ]; + } + + $remainRewardAmount = $totalAmount; + $rewardAmount = []; + foreach (Util::range($selectCnt, 0, -1) as $matchPoint) { + if (count($subWinners[$matchPoint]) == 0) { + continue; + } + if ($subAmount[$matchPoint] == 0) { + continue; + } + + $givenRewardAmount = $remainRewardAmount / 2; + $rewardAmount[$matchPoint] = $givenRewardAmount; + $remainRewardAmount -= $givenRewardAmount; // /2가 아니라 다른 값이 될 경우를 대비.. + } + + foreach (Util::range(1, $selectCnt) as $matchPoint) { + if (!key_exists($matchPoint, $rewardAmount)) { + continue; + } + $rewardAmount[$matchPoint] += $remainRewardAmount; + break; + } + + $result = []; + + foreach (Util::range($selectCnt + 1, 0, -1) as $matchPoint) { + if (!key_exists($matchPoint, $rewardAmount)) { + continue; + } + $subReward = $rewardAmount[$matchPoint]; + if ($subReward == 0) { + continue; + } + $multiplier = $subReward / $subAmount[$matchPoint]; + foreach ($subWinners[$matchPoint] as $subWinner) { + $subWinner['amount'] *= $multiplier; + $result[$subWinner['generalID']] = $subWinner; + } + } + + return $result; + } + + public function giveReward(array $winnerType) + { + $rewardList = $this->calcReward($winnerType); + + $db = DB::db(); + + if ($this->info->reqInheritancePoint) { + foreach ($rewardList as $rewardItem) { + if ($rewardItem['userID'] === null) { + continue; + } + $userID = $rewardItem['userID']; + $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}"); + $previousPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0]; + $previousPointText = number_format($previousPoint); + + $userLogger = new UserLogger($userID); + $amount = $rewardItem['amount']; + $amountText = number_format($amount); + $nextPoint = $previousPoint + $amount; + $nextPointText = number_format($nextPoint); + $userLogger->push("{$this->info->name} 베팅 보상으로 {$amountText} 포인트 획득.", "inheritPoint"); + $userLogger->push("포인트 {$previousPointText} => {$nextPointText}", "inheritPoint"); + $userLogger->flush(); + } + } else { + foreach (General::createGeneralObjListFromDB(Util::squeezeFromArray($rewardList, 'generalID'), ['gold', 'npc'], 1) as $gambler) { + $reward = Util::round($rewardList[$gambler->getID()]['amount']); + $gambler->increaseVar('gold', $reward); + if (($gambler->getNPCType() == 0) || ($gambler->getNPCType() == 1 && $gambler->getRankVar('betgold', 0) > 0)) { + $gambler->increaseRankVar('betwingold', $reward); + $gambler->increaseRankVar('betwin', 1); + } + $rewardText = number_format($reward); + $gambler->getLogger()->pushGeneralActionLog("{$this->info->name}의 베팅 보상으로 {$rewardText}의 금 획득!", ActionLogger::EVENT_PLAIN); + $gambler->applyDB($db); + } + } + } +} diff --git a/hwe/sammo/DTO/BettingInfo.php b/hwe/sammo/DTO/BettingInfo.php index 13fae86e..0ca1dd0d 100644 --- a/hwe/sammo/DTO/BettingInfo.php +++ b/hwe/sammo/DTO/BettingInfo.php @@ -20,6 +20,7 @@ class BettingInfo extends DataTransferObject public string $name; public bool $finished; public int $selectCnt; + public ?bool $isExlusive; public bool $reqInheritancePoint; public int $openYearMonth; public int $closeYearMonth; -- 2.54.0 From 33b80f77c78762dcb908c3c02885d4dd961537f0 Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 4 Feb 2022 03:50:39 +0900 Subject: [PATCH 39/44] =?UTF-8?q?feat(WIP):=20=EB=B2=A0=ED=8C=85=20?= =?UTF-8?q?=EB=B3=B4=EC=83=81=20=EB=88=84=EB=9D=BD=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Betting.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/hwe/sammo/Betting.php b/hwe/sammo/Betting.php index 7a345bf8..bac18948 100644 --- a/hwe/sammo/Betting.php +++ b/hwe/sammo/Betting.php @@ -8,7 +8,6 @@ class Betting { private BettingInfo $info; - private ?array $typeKeyCache = null; public function __construct(private $bettingID) { @@ -207,13 +206,17 @@ class Betting $userID = $rewardItem['userID']; $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}"); $previousPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0]; - $previousPointText = number_format($previousPoint); $userLogger = new UserLogger($userID); $amount = $rewardItem['amount']; - $amountText = number_format($amount); + $nextPoint = $previousPoint + $amount; + $inheritStor->setValue('previous', [$nextPoint, 0]); + + $amountText = number_format($amount); + $previousPointText = number_format($previousPoint); $nextPointText = number_format($nextPoint); + $userLogger->push("{$this->info->name} 베팅 보상으로 {$amountText} 포인트 획득.", "inheritPoint"); $userLogger->push("포인트 {$previousPointText} => {$nextPointText}", "inheritPoint"); $userLogger->flush(); -- 2.54.0 From 802d7fb78404eddb3970e403525bda4e9d46fb5a Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 4 Feb 2022 04:00:15 +0900 Subject: [PATCH 40/44] =?UTF-8?q?feat:=20=EB=B2=A0=ED=8C=85=20=EB=B3=B4?= =?UTF-8?q?=EC=83=81=20=EB=93=B1=EB=A1=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Betting.php | 14 +++++++++-- hwe/sammo/DTO/BettingInfo.php | 1 + .../Event/Action/FinishNationBetting.php | 24 ++++++++++++------- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/hwe/sammo/Betting.php b/hwe/sammo/Betting.php index bac18948..c1272b07 100644 --- a/hwe/sammo/Betting.php +++ b/hwe/sammo/Betting.php @@ -25,8 +25,7 @@ class Betting return Json::encode($bettingType); } - public function convertBettingKey(array $bettingType): string - { + public function purifyBettingKey(array $bettingType): array{ $selectCnt = $this->info->selectCnt; sort($bettingType, SORT_NUMERIC); $bettingType = array_unique($bettingType, SORT_NUMERIC); //NOTE: key로 바로 사용하므로 중요함 @@ -42,6 +41,12 @@ class Betting throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(초과)'); } + return $bettingType; + } + + public function convertBettingKey(array $bettingType): string + { + $bettingType = $this->purifyBettingKey($bettingType); return $this->_convertBettingKey($bettingType); } @@ -234,5 +239,10 @@ class Betting $gambler->applyDB($db); } } + + $this->info->finished = true; + $this->info->winner = $winnerType; + $bettingStor = KVStorage::getStorage($db, 'betting'); + $bettingStor->setValue("id_{$this->bettingID}", $this->info->toArray()); } } diff --git a/hwe/sammo/DTO/BettingInfo.php b/hwe/sammo/DTO/BettingInfo.php index 0ca1dd0d..81970429 100644 --- a/hwe/sammo/DTO/BettingInfo.php +++ b/hwe/sammo/DTO/BettingInfo.php @@ -28,6 +28,7 @@ class BettingInfo extends DataTransferObject /** @var \sammo\DTO\SelectItem[] */ #[CastWith(ArrayCaster::class, itemType: SelectItem::class)] public array $candidates; + public ?array $winner; } diff --git a/hwe/sammo/Event/Action/FinishNationBetting.php b/hwe/sammo/Event/Action/FinishNationBetting.php index abd7b01e..7e824494 100644 --- a/hwe/sammo/Event/Action/FinishNationBetting.php +++ b/hwe/sammo/Event/Action/FinishNationBetting.php @@ -2,6 +2,7 @@ namespace sammo\Event\Action; +use sammo\Betting; use \sammo\GameConst; use \sammo\Util; use \sammo\DB; @@ -18,25 +19,32 @@ class FinishNationBetting extends \sammo\Event\Action public function run(array $env) { $db = DB::db(); - [$year, $month] = [$env['year'], $env['month']]; $bettingStor = KVStorage::getStorage($db, 'betting'); $bettingInfoRaw = $bettingStor->getValue("id_{$this->bettingID}"); if($bettingInfoRaw === null){ return [__CLASS__, true]; } - $bettingInfo = new BettingInfo($bettingInfoRaw); + + try{ + $bettingHelper = new Betting($this->bettingID); + } + catch (\Exception $e){ + return [__CLASS__, false, $e->getMessage()]; + } + + $bettingInfo = $bettingHelper->getInfo(); if($bettingInfo->type != 'nationBetting'){ return [__CLASS__, false, 'invalid type', $bettingInfo->type]; } - $bettingInfo->finished = true; - $bettingStor->setValue("id_{$this->bettingID}", $bettingInfo->toArray()); - //TODO: 포인트를 배분해주어야 함 - //TODO: 이후 토너먼트 베팅 결과도 같이 처리할 것이므로, 별도의 함수나 모듈을 생성하여 처리! + $winnerNations = $bettingHelper->purifyBettingKey($db->queryFirstColumn('SELECT nation FROM nation WHERE level > 0')); + if(count($winnerNations) != $bettingInfo->selectCnt){ + return [__CLASS__, false, 'invalid winner cnt', $bettingInfo->selectCnt]; + } - //NOTE: 완료되었음을 알릴 것인가? + $bettingHelper->giveReward($winnerNations); - return [__CLASS__, false, 'NYI']; + return [__CLASS__, true]; } } -- 2.54.0 From 9fedb5174572b1bdf80cfd316509334e13fa79fa Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 4 Feb 2022 13:16:28 +0900 Subject: [PATCH 41/44] =?UTF-8?q?feat:=20=EB=B2=A0=ED=8C=85=EC=8B=9C=20?= =?UTF-8?q?=EC=9C=A0=EC=82=B0=ED=8F=AC=EC=9D=B8=ED=8A=B8=20=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EC=97=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 51 ++++++++++++++++++----------------- hwe/ts/PageNationBetting.vue | 8 ++++-- 2 files changed, 32 insertions(+), 27 deletions(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index 36e343f1..f232253d 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -10,10 +10,9 @@ use sammo\DTO\BettingItem; use sammo\Validator; use sammo\GameConst; use sammo\KVStorage; +use sammo\UserLogger; use sammo\Util; -use function sammo\getAllNationStaticInfo; - class Bet extends \sammo\BaseAPI { public function validateArgs(): ?string @@ -56,7 +55,7 @@ class Bet extends \sammo\BaseAPI $bettingHelper = new Betting($bettingID); $bettingInfo = $bettingHelper->getInfo(); - if($bettingInfo->finished){ + if ($bettingInfo->finished) { return '이미 종료된 베팅입니다'; } @@ -64,15 +63,15 @@ class Bet extends \sammo\BaseAPI $yearMonth = Util::joinYearMonth($year, $month); - if($bettingInfo->closeYearMonth <= $yearMonth){ + if ($bettingInfo->closeYearMonth <= $yearMonth) { return '이미 마감된 베팅입니다'; } - if($bettingInfo->openYearMonth > $yearMonth){ + if ($bettingInfo->openYearMonth > $yearMonth) { return '아직 시작되지 않은 베팅입니다'; } - if(count($bettingType) != $bettingInfo->selectCnt){ + if (count($bettingType) != $bettingInfo->selectCnt) { return '필요한 선택 수를 채우지 못했습니다.'; } @@ -82,19 +81,18 @@ class Bet extends \sammo\BaseAPI $prevBetAmount = $db->queryFirstField('SELECT sum(amount) FROM ng_betting WHERE betting_id = %i AND user_id = %i', $bettingID, $session->userID) ?? 0; - if($prevBetAmount + $amount > 1000){ - return (1000 - $prevBetAmount).' 포인트까지만 베팅 가능합니다.'; + if ($prevBetAmount + $amount > 1000) { + return (1000 - $prevBetAmount) . ' 포인트까지만 베팅 가능합니다.'; } - if($bettingInfo->reqInheritancePoint){ - $remainPoint = ($inheritStor->getValue('previous') ?? [0,0])[0]; - if($remainPoint < $amount){ + if ($bettingInfo->reqInheritancePoint) { + $remainPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0]; + if ($remainPoint < $amount) { return '유산포인트가 충분하지 않습니다.'; } - } - else { - $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $session->generalID)??0; - if($remainPoint < GameConst::$generalMinimumGold + $amount){ + } else { + $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $session->generalID) ?? 0; + if ($remainPoint < GameConst::$generalMinimumGold + $amount) { return '금이 부족합니다.'; } } @@ -102,31 +100,34 @@ class Bet extends \sammo\BaseAPI $userID = $session->userID; $bettingItem = new BettingItem([ - 'betting_id'=>$bettingID, - 'general_id'=>$session->generalID, - 'user_id'=>$userID, - 'betting_type'=>$bettingTypeKey, - 'amount'=>$amount + 'betting_id' => $bettingID, + 'general_id' => $session->generalID, + 'user_id' => $userID, + 'betting_type' => $bettingTypeKey, + 'amount' => $amount ]); $db->insertUpdate( 'ng_betting', $bettingItem->toArray(), ['amount' => $db->sqleval('amount + %i', $amount)] - ); if($bettingInfo->reqInheritancePoint){ + ); + if ($bettingInfo->reqInheritancePoint) { $inheritStor->setValue('previous', [$remainPoint - $amount, null]); - } - else{ + $userLogger = new UserLogger($userID); + $userLogger->push("{$amount} 포인트를 베팅에 사용", "inheritPoint"); + $userLogger->flush(); + } else { $db->update('general', [ 'gold' => $db->sqleval('gold - %i', $amount) ], 'no = %i', $session->generalID); } - if(!$db->affected_rows){ + if (!$db->affected_rows) { return '베팅을 실패했습니다.'; } return [ - 'result'=>true + 'result' => true ]; } } diff --git a/hwe/ts/PageNationBetting.vue b/hwe/ts/PageNationBetting.vue index 04605196..c3f0e479 100644 --- a/hwe/ts/PageNationBetting.vue +++ b/hwe/ts/PageNationBetting.vue @@ -78,8 +78,10 @@
{{ amount.toLocaleString() }}
{{ myBettings.has(betType) ? `(${myBettings.get(betType)?.toLocaleString()} -> ${((myBettings.get(betType)??0) * bettingAmount / amount).toLocaleString()})` : '' }}
-
{{ (bettingAmount / amount).toFixed(1) }}배
+ >{{ myBettings.has(betType) ? `(${myBettings.get(betType)?.toLocaleString()} -> ${((myBettings.get(betType) ?? 0) * bettingAmount / amount / ((info.isExclusive && info.selectCnt > 1) ? 1 : 2)).toLocaleString()})` : '' }}
+
{{ (bettingAmount / amount / ((info.isExclusive && info.selectCnt > 1) ? 1 : 2)).toFixed(1) }}배
@@ -130,10 +132,12 @@ type BettingInfo = { name: string; finished: boolean; selectCnt: number; + isExclusive?: boolean; reqInheritancePoint: boolean; openYearMonth: number; closeYearMonth: number; candidates: SelectItem[]; + winner?: number[]; } type BettingListResponse = ValidResponse & { -- 2.54.0 From e0bbe313a2236d58127e999d56292a37bc727d7a Mon Sep 17 00:00:00 2001 From: hide_d Date: Sat, 5 Feb 2022 02:56:45 +0900 Subject: [PATCH 42/44] =?UTF-8?q?fix:=20n=EC=B0=A8=20=ED=98=BC=ED=95=A9=20?= =?UTF-8?q?=EB=B2=A0=ED=8C=85=20=EB=B3=B4=EC=83=81=20=EC=88=98=EB=A0=B9?= =?UTF-8?q?=EC=9D=B4=20=ED=95=98=EB=82=98=EB=A7=8C=20=EB=90=98=EB=8A=94=20?= =?UTF-8?q?=EB=B2=84=EA=B7=B8=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/Betting.php | 70 ++++++++++++++----- .../Event/Action/FinishNationBetting.php | 40 +++++++---- hwe/sammo/Event/Action/OpenNationBetting.php | 2 +- hwe/ts/PageNationBetting.vue | 2 +- 4 files changed, 82 insertions(+), 32 deletions(-) diff --git a/hwe/sammo/Betting.php b/hwe/sammo/Betting.php index c1272b07..10623121 100644 --- a/hwe/sammo/Betting.php +++ b/hwe/sammo/Betting.php @@ -25,7 +25,8 @@ class Betting return Json::encode($bettingType); } - public function purifyBettingKey(array $bettingType): array{ + public function purifyBettingKey(array $bettingType): array + { $selectCnt = $this->info->selectCnt; sort($bettingType, SORT_NUMERIC); $bettingType = array_unique($bettingType, SORT_NUMERIC); //NOTE: key로 바로 사용하므로 중요함 @@ -34,11 +35,11 @@ class Betting } if ($bettingType[0] < 0) { - throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(0 미만)'); + throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(0 미만)' . print_r($bettingType, true)); } if (Util::array_last($bettingType) >= count($this->info->candidates)) { - throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(초과)'); + throw new \InvalidArgumentException('올바르지 않은 값이 있습니다.(초과)' . print_r($bettingType, true)); } return $bettingType; @@ -66,7 +67,7 @@ class Betting } $winnerList = $db->queryAllLists( - 'SELECT general_id, user_id, amount WHERE betting_id = %i AND betting_type = %s', + 'SELECT general_id, user_id, amount FROM ng_betting WHERE betting_id = %i AND betting_type = %s AND general_id > 0', $this->bettingID, $this->_convertBettingKey($bettingType) ); @@ -85,7 +86,7 @@ class Betting $result = []; foreach ($winnerList as [$generalID, $userID, $amount]) { - $result[$generalID] = [ + $result[] = [ 'generalID' => $generalID, 'userID' => $userID, 'amount' => $amount * $multiplier, @@ -136,7 +137,7 @@ class Betting $db = DB::db(); foreach ($db->queryAllLists( - 'SELECT general_id, user_id, amount, betting_type WHERE betting_id = %i', + 'SELECT general_id, user_id, amount, betting_type FROM ng_betting WHERE betting_id = %i', $this->bettingID ) as [$generalID, $userID, $amount, $bettingTypeKey]) { $bettingType = Json::decode($bettingTypeKey); @@ -169,7 +170,7 @@ class Betting $remainRewardAmount -= $givenRewardAmount; // /2가 아니라 다른 값이 될 경우를 대비.. } - foreach (Util::range(1, $selectCnt) as $matchPoint) { + foreach (Util::range(1, $selectCnt + 1) as $matchPoint) { if (!key_exists($matchPoint, $rewardAmount)) { continue; } @@ -190,7 +191,7 @@ class Betting $multiplier = $subReward / $subAmount[$matchPoint]; foreach ($subWinners[$matchPoint] as $subWinner) { $subWinner['amount'] *= $multiplier; - $result[$subWinner['generalID']] = $subWinner; + $result[] = $subWinner; } } @@ -200,43 +201,78 @@ class Betting public function giveReward(array $winnerType) { $rewardList = $this->calcReward($winnerType); + $selectCnt = $this->info->selectCnt; $db = DB::db(); if ($this->info->reqInheritancePoint) { + /** @var UserLogger[] */ + $loggers = []; foreach ($rewardList as $rewardItem) { if ($rewardItem['userID'] === null) { continue; } $userID = $rewardItem['userID']; - $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}"); - $previousPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0]; - - $userLogger = new UserLogger($userID); $amount = $rewardItem['amount']; + $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}"); + $previousPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0]; $nextPoint = $previousPoint + $amount; $inheritStor->setValue('previous', [$nextPoint, 0]); + $inheritStor->invalidateCacheValue('previous');//XXX: 실제로는 previous 값을 사용할 수 없도록 락을 걸어야 한다. $amountText = number_format($amount); $previousPointText = number_format($previousPoint); $nextPointText = number_format($nextPoint); - $userLogger->push("{$this->info->name} 베팅 보상으로 {$amountText} 포인트 획득.", "inheritPoint"); + $matchPoint = $rewardItem['matchPoint']; + + if ($matchPoint == $selectCnt) { + $partialText = '베팅 당첨'; + } else { + $partialText = "베팅 부분 당첨({$matchPoint}/{$selectCnt})"; + } + + if (key_exists($userID, $loggers)) { + $userLogger = $loggers[$userID]; + } else { + $userLogger = new UserLogger($userID); + $loggers[$userID] = $userLogger; + } + + [$year, $month] = Util::parseYearMonth($this->info->openYearMonth); + + $userLogger->push("{$this->info->name} {$partialText} 보상으로 {$amountText} 포인트 획득.", "inheritPoint"); $userLogger->push("포인트 {$previousPointText} => {$nextPointText}", "inheritPoint"); + } + + foreach ($loggers as $userLogger) { $userLogger->flush(); } + } else { - foreach (General::createGeneralObjListFromDB(Util::squeezeFromArray($rewardList, 'generalID'), ['gold', 'npc'], 1) as $gambler) { - $reward = Util::round($rewardList[$gambler->getID()]['amount']); + $generalList = General::createGeneralObjListFromDB(array_unique(Util::squeezeFromArray($rewardList, 'generalID')), ['gold', 'npc'], 1); + foreach ($rewardList as $rewardItem) { + $gambler = $generalList[$rewardItem['generalID']]; + $reward = Util::round($rewardItem['amount']); + $matchPoint = $rewardItem['matchPoint']; $gambler->increaseVar('gold', $reward); if (($gambler->getNPCType() == 0) || ($gambler->getNPCType() == 1 && $gambler->getRankVar('betgold', 0) > 0)) { $gambler->increaseRankVar('betwingold', $reward); $gambler->increaseRankVar('betwin', 1); } + + if ($matchPoint == $selectCnt) { + $partialText = '베팅 당첨'; + } else { + $partialText = "베팅 부분 당첨({$matchPoint}/{$selectCnt})"; + } $rewardText = number_format($reward); - $gambler->getLogger()->pushGeneralActionLog("{$this->info->name}의 베팅 보상으로 {$rewardText}의 금 획득!", ActionLogger::EVENT_PLAIN); - $gambler->applyDB($db); + $gambler->getLogger()->pushGeneralActionLog("{$this->info->name}의 {$partialText} 보상으로 {$rewardText}의 금 획득!", ActionLogger::EVENT_PLAIN); + } + + foreach ($generalList as $general) { + $general->applyDB($db); } } diff --git a/hwe/sammo/Event/Action/FinishNationBetting.php b/hwe/sammo/Event/Action/FinishNationBetting.php index 7e824494..6cecba38 100644 --- a/hwe/sammo/Event/Action/FinishNationBetting.php +++ b/hwe/sammo/Event/Action/FinishNationBetting.php @@ -2,6 +2,7 @@ namespace sammo\Event\Action; +use sammo\ActionLogger; use sammo\Betting; use \sammo\GameConst; use \sammo\Util; @@ -20,30 +21,43 @@ class FinishNationBetting extends \sammo\Event\Action { $db = DB::db(); - $bettingStor = KVStorage::getStorage($db, 'betting'); - $bettingInfoRaw = $bettingStor->getValue("id_{$this->bettingID}"); - if($bettingInfoRaw === null){ - return [__CLASS__, true]; - } - - try{ + try { $bettingHelper = new Betting($this->bettingID); - } - catch (\Exception $e){ + } catch (\Exception $e) { return [__CLASS__, false, $e->getMessage()]; } $bettingInfo = $bettingHelper->getInfo(); - if($bettingInfo->type != 'nationBetting'){ + if ($bettingInfo->type != 'bettingNation') { return [__CLASS__, false, 'invalid type', $bettingInfo->type]; } - $winnerNations = $bettingHelper->purifyBettingKey($db->queryFirstColumn('SELECT nation FROM nation WHERE level > 0')); - if(count($winnerNations) != $bettingInfo->selectCnt){ + $winnerNations = $db->queryFirstColumn('SELECT nation FROM nation WHERE level > 0'); + if (count($winnerNations) != $bettingInfo->selectCnt) { return [__CLASS__, false, 'invalid winner cnt', $bettingInfo->selectCnt]; } - $bettingHelper->giveReward($winnerNations); + //nation_id와 betting_type이 일치하지 않으므로 정렬 + $nationIDMap = []; + foreach ($bettingInfo->candidates as $idx => $candidate) { + $aux = $candidate->aux; + if (!$aux) { + return [__CLASS__, false, "invalid aux {$idx}:{$candidate->title}"]; + } + $nationID = $aux['nation']; + $nationIDMap[$nationID] = $idx; + } + + $winnerTypes = []; + foreach ($winnerNations as $winnerNationID) { + $winnerTypes[] = $nationIDMap[$winnerNationID]; + } + $winnerTypes = $bettingHelper->purifyBettingKey($winnerTypes); + + $bettingHelper->giveReward($winnerTypes); + $logger = new ActionLogger(0, 0, $env['year'], $env['month']); + [$year, $month] = Util::parseYearMonth($bettingInfo->openYearMonth); + $logger->pushGlobalHistoryLog("【내기】 {$year}년 {$month}월에 열렸던 {$bettingInfo->name} 내기의 결과가 나왔습니다!"); return [__CLASS__, true]; } diff --git a/hwe/sammo/Event/Action/OpenNationBetting.php b/hwe/sammo/Event/Action/OpenNationBetting.php index 6f097e77..8384d25c 100644 --- a/hwe/sammo/Event/Action/OpenNationBetting.php +++ b/hwe/sammo/Event/Action/OpenNationBetting.php @@ -81,7 +81,7 @@ class OpenNationBetting extends \sammo\Event\Action $bettingInfo = new BettingInfo( id: $bettingID, type: 'bettingNation', - name: "[{$year}년 {$month}월] {$name} 예상 베팅", + name: "{$name} 예상", finished: false, selectCnt: $this->nationCnt, reqInheritancePoint: true, diff --git a/hwe/ts/PageNationBetting.vue b/hwe/ts/PageNationBetting.vue index c3f0e479..51d03996 100644 --- a/hwe/ts/PageNationBetting.vue +++ b/hwe/ts/PageNationBetting.vue @@ -95,7 +95,7 @@ :key="info.id" @click="loadBetting(info.id)" > - {{ info.name }} + [{{ parseYearMonth(info.openYearMonth)[0] }}년 {{ parseYearMonth(info.openYearMonth)[1] }}월] {{ info.name }} (종료) Date: Sat, 5 Feb 2022 03:06:31 +0900 Subject: [PATCH 43/44] =?UTF-8?q?refac:=20=EB=B2=A0=ED=8C=85=20=EC=BD=94?= =?UTF-8?q?=EB=93=9C=EB=A5=BC=20=EB=AA=A8=EB=93=88=EB=A1=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/sammo/API/Betting/Bet.php | 78 ++--------------------------------- hwe/sammo/Betting.php | 77 ++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 74 deletions(-) diff --git a/hwe/sammo/API/Betting/Bet.php b/hwe/sammo/API/Betting/Bet.php index f232253d..492f34a3 100644 --- a/hwe/sammo/API/Betting/Bet.php +++ b/hwe/sammo/API/Betting/Bet.php @@ -41,8 +41,6 @@ class Bet extends \sammo\BaseAPI public function launch(Session $session, ?DateTimeInterface $modifiedSince, ?string $reqEtag) { - $db = DB::db(); - /** @var int */ $bettingID = $this->args['bettingID']; /** @var int[] */ @@ -50,80 +48,12 @@ class Bet extends \sammo\BaseAPI /** @var int */ $amount = $this->args['amount']; - $gameStor = KVStorage::getStorage($db, 'game_env'); - $bettingHelper = new Betting($bettingID); - $bettingInfo = $bettingHelper->getInfo(); - - if ($bettingInfo->finished) { - return '이미 종료된 베팅입니다'; + try{ + $bettingHelper->bet($session->generalID, $session->userID, $bettingType, $amount); } - - [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); - $yearMonth = Util::joinYearMonth($year, $month); - - - if ($bettingInfo->closeYearMonth <= $yearMonth) { - return '이미 마감된 베팅입니다'; - } - - if ($bettingInfo->openYearMonth > $yearMonth) { - return '아직 시작되지 않은 베팅입니다'; - } - - if (count($bettingType) != $bettingInfo->selectCnt) { - return '필요한 선택 수를 채우지 못했습니다.'; - } - - $bettingTypeKey = $bettingHelper->convertBettingKey($bettingType); - - $inheritStor = KVStorage::getStorage($db, "inheritance_{$session->userID}"); - - $prevBetAmount = $db->queryFirstField('SELECT sum(amount) FROM ng_betting WHERE betting_id = %i AND user_id = %i', $bettingID, $session->userID) ?? 0; - - if ($prevBetAmount + $amount > 1000) { - return (1000 - $prevBetAmount) . ' 포인트까지만 베팅 가능합니다.'; - } - - if ($bettingInfo->reqInheritancePoint) { - $remainPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0]; - if ($remainPoint < $amount) { - return '유산포인트가 충분하지 않습니다.'; - } - } else { - $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $session->generalID) ?? 0; - if ($remainPoint < GameConst::$generalMinimumGold + $amount) { - return '금이 부족합니다.'; - } - } - - $userID = $session->userID; - - $bettingItem = new BettingItem([ - 'betting_id' => $bettingID, - 'general_id' => $session->generalID, - 'user_id' => $userID, - 'betting_type' => $bettingTypeKey, - 'amount' => $amount - ]); - - $db->insertUpdate( - 'ng_betting', - $bettingItem->toArray(), - ['amount' => $db->sqleval('amount + %i', $amount)] - ); - if ($bettingInfo->reqInheritancePoint) { - $inheritStor->setValue('previous', [$remainPoint - $amount, null]); - $userLogger = new UserLogger($userID); - $userLogger->push("{$amount} 포인트를 베팅에 사용", "inheritPoint"); - $userLogger->flush(); - } else { - $db->update('general', [ - 'gold' => $db->sqleval('gold - %i', $amount) - ], 'no = %i', $session->generalID); - } - if (!$db->affected_rows) { - return '베팅을 실패했습니다.'; + catch(\Throwable $e){ + return $e->getMessage(); } return [ diff --git a/hwe/sammo/Betting.php b/hwe/sammo/Betting.php index 10623121..191fa9b0 100644 --- a/hwe/sammo/Betting.php +++ b/hwe/sammo/Betting.php @@ -3,6 +3,7 @@ namespace sammo; use sammo\DTO\BettingInfo; +use sammo\DTO\BettingItem; class Betting { @@ -56,6 +57,82 @@ class Betting return $this->info; } + public function bet(int $generalID, ?int $userID, array $bettingType, int $amount): void{ + $bettingInfo = $this->info; + + if ($bettingInfo->finished) { + throw new \RuntimeException('이미 종료된 베팅입니다'); + } + + if ($bettingInfo->finished) { + throw new \RuntimeException('이미 종료된 베팅입니다'); + } + $db = DB::db(); + $gameStor = KVStorage::getStorage($db, 'game_env'); + + [$year, $month] = $gameStor->getValuesAsArray(['year', 'month']); + $yearMonth = Util::joinYearMonth($year, $month); + + + if ($bettingInfo->closeYearMonth <= $yearMonth) { + throw new \RuntimeException('이미 마감된 베팅입니다'); + } + + if ($bettingInfo->openYearMonth > $yearMonth) { + throw new \RuntimeException('아직 시작되지 않은 베팅입니다'); + } + + if (count($bettingType) != $bettingInfo->selectCnt) { + throw new \RuntimeException('필요한 선택 수를 채우지 못했습니다.'); + } + + $bettingTypeKey = $this->convertBettingKey($bettingType); + + $inheritStor = KVStorage::getStorage($db, "inheritance_{$userID}"); + + $prevBetAmount = $db->queryFirstField('SELECT sum(amount) FROM ng_betting WHERE betting_id = %i AND user_id = %i', $this->bettingID, $userID) ?? 0; + + if ($prevBetAmount + $amount > 1000) { + throw new \RuntimeException((1000 - $prevBetAmount) . ' 포인트까지만 베팅 가능합니다.'); + } + + if ($bettingInfo->reqInheritancePoint) { + $remainPoint = ($inheritStor->getValue('previous') ?? [0, 0])[0]; + if ($remainPoint < $amount) { + throw new \RuntimeException('유산포인트가 충분하지 않습니다.'); + } + } else { + $remainPoint = $db->queryFirstField('SELECT gold FROM general WHERE no = %i', $generalID) ?? 0; + if ($remainPoint < GameConst::$generalMinimumGold + $amount) { + throw new \RuntimeException('금이 부족합니다.'); + } + } + + $bettingItem = new BettingItem([ + 'betting_id' => $this->bettingID, + 'general_id' => $generalID, + 'user_id' => $userID, + 'betting_type' => $bettingTypeKey, + 'amount' => $amount + ]); + + $db->insertUpdate( + 'ng_betting', + $bettingItem->toArray(), + ['amount' => $db->sqleval('amount + %i', $amount)] + ); + if ($bettingInfo->reqInheritancePoint) { + $inheritStor->setValue('previous', [$remainPoint - $amount, null]); + $userLogger = new UserLogger($userID); + $userLogger->push("{$amount} 포인트를 베팅에 사용", "inheritPoint"); + $userLogger->flush(); + } else { + $db->update('general', [ + 'gold' => $db->sqleval('gold - %i', $amount) + ], 'no = %i', $generalID); + } + } + /** @param int[] $result */ private function _calcRewardExclusive(array $bettingType): array { -- 2.54.0 From 405a61c1b5657eddb7ee6a0a72a58a1410e96cb4 Mon Sep 17 00:00:00 2001 From: hide_d Date: Sat, 5 Feb 2022 04:57:38 +0900 Subject: [PATCH 44/44] =?UTF-8?q?feat:=20=EB=B3=80=EA=B2=BD=EB=90=9C=20?= =?UTF-8?q?=EB=B2=A0=ED=8C=85=20=EB=B0=A9=EC=8B=9D=EC=97=90=20=EB=94=B0?= =?UTF-8?q?=EB=9D=BC=20=EA=B2=B0=EA=B3=BC=20=ED=91=9C=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hwe/ts/PageNationBetting.vue | 290 +----------------- hwe/ts/components/BettingDetail.vue | 436 ++++++++++++++++++++++++++++ hwe/ts/defs.ts | 22 ++ 3 files changed, 470 insertions(+), 278 deletions(-) create mode 100644 hwe/ts/components/BettingDetail.vue diff --git a/hwe/ts/PageNationBetting.vue b/hwe/ts/PageNationBetting.vue index 51d03996..909bd86d 100644 --- a/hwe/ts/PageNationBetting.vue +++ b/hwe/ts/PageNationBetting.vue @@ -2,90 +2,7 @@
-
- -
+
로딩 중...
베팅 목록
@@ -93,10 +10,12 @@ class="bettingItem" v-for="info of Object.values(bettingList).reverse()" :key="info.id" - @click="loadBetting(info.id)" + @click="targetBettingID = info.id" > [{{ parseYearMonth(info.openYearMonth)[0] }}년 {{ parseYearMonth(info.openYearMonth)[1] }}월] {{ info.name }} - (종료) + (종료) ({{ parseYearMonth(info.closeYearMonth)[0] }}년 {{ parseYearMonth(info.closeYearMonth)[1] }}월까지) @@ -112,33 +31,13 @@ import MyToast from "@/components/MyToast.vue"; import TopBackBar from "@/components/TopBackBar.vue"; import BottomBar from "@/components/BottomBar.vue"; -import { ToastType } from "@/defs"; +import { BettingInfo, ToastType } from "@/defs"; import { onMounted, ref } from "vue"; import { SammoAPI, ValidResponse } from "./SammoAPI"; -import { isString, sum } from "lodash"; +import { isString } from "lodash"; import { parseYearMonth } from "@/util/parseYearMonth"; import { joinYearMonth } from "./util/joinYearMonth"; - -type SelectItem = { - title: string; - info?: string; - isHtml?: boolean; - aux?: Record; -} - -type BettingInfo = { - id: number; - type: 'nationBetting', - name: string; - finished: boolean; - selectCnt: number; - isExclusive?: boolean; - reqInheritancePoint: boolean; - openYearMonth: number; - closeYearMonth: number; - candidates: SelectItem[]; - winner?: number[]; -} +import BettingDetail from "@/components/BettingDetail.vue"; type BettingListResponse = ValidResponse & { bettingList: Record>, @@ -146,187 +45,22 @@ type BettingListResponse = ValidResponse & { month: number, }; -type BettingDetailResponse = ValidResponse & { - bettingInfo: BettingInfo; - bettingDetail: [string, number][]; - myBetting: [string, number][]; - remainPoint: number; - year: number; - month: number; -} + const toasts = ref([]); const year = ref(); const month = ref(); const yearMonth = ref(); const bettingList = ref(); -const bettingInfo = ref(); -const bettingAmount = ref(0); -const pureBettingAmount = ref(0); -const partialBet = ref(new Map()); -const detailBet = ref<[string, number][]>([]); +const targetBettingID = ref(); -const typeMap = ref(new Map()); -function getTypeStr(type: string): string { - const typeResult = typeMap.value.get(type); - if (typeResult !== undefined) { - return typeResult; - } - const bettingSubTypes = JSON.parse(type) as number[]; - if (bettingSubTypes[0] < -1) { - return 'Invalid'; - } - const textBettingType = bettingSubTypes.map((idx) => { - return bettingInfo.value?.bettingInfo.candidates[idx].title; - }).join(', '); - typeMap.value.set(type, textBettingType); - return textBettingType; +function addToast(msg: ToastType){ + toasts.value.push(msg); } -const pickedBetType = ref(new Set()); -const pickedBetTypeKey = ref('[]'); - -const betPoint = ref(0); -const myBettings = ref(new Map()); - -function toggleCandidate(idx: number) { - if (bettingInfo.value === undefined) { - return; - } - const selectCnt = bettingInfo.value.bettingInfo.selectCnt; - - if (selectCnt == 1) { - pickedBetType.value.clear(); - pickedBetType.value.add(idx); - pickedBetTypeKey.value = JSON.stringify([idx]); - return; - } - - if (pickedBetType.value.has(idx)) { - pickedBetType.value.delete(idx); - } - else if (pickedBetType.value.size < selectCnt) { - pickedBetType.value.add(idx); - } - else { - toasts.value.push({ - title: '오류', - type: 'warning', - content: `이미 ${selectCnt}개를 선택했습니다.`, - }) - return; - } - - const typeArr = Array.from(pickedBetType.value.values()); - pickedBetTypeKey.value = JSON.stringify(typeArr.sort((lhs, rhs) => lhs - rhs)); -} - -async function loadBetting(bettingID: number) { - try { - const result = await SammoAPI.Betting.GetBettingDetail({ - betting_id: bettingID - }); - year.value = result.year; - month.value = result.month; - yearMonth.value = joinYearMonth(result.year, result.month); - bettingInfo.value = result; - - partialBet.value.clear(); - - const betSort = new Map(); - - - let _bettingAmount = 0; - let adminBettingAmount = 0; - for (const [bettingType, amount] of result.bettingDetail) { - console.log(amount, typeof (amount)); - let userBet = true; - const bettingSubTypes = JSON.parse(bettingType) as number[]; - for (const bettingSubType of bettingSubTypes) { - if (bettingSubType < 0) { - userBet = false; - continue; - } - const oldValue = partialBet.value.get(bettingSubType) ?? 0; - partialBet.value.set(bettingSubType, oldValue + amount); - } - - if (userBet) { - const oldValue = betSort.get(bettingType) ?? 0; - betSort.set(bettingType, oldValue + amount); - } - - _bettingAmount += amount; - if (!userBet) { - adminBettingAmount += amount; - } - } - console.log(_bettingAmount); - bettingAmount.value = _bettingAmount; - pureBettingAmount.value = _bettingAmount - adminBettingAmount; - - detailBet.value = Array.from(betSort.entries()); - detailBet.value.sort(([, lhsVal], [, rhsVal]) => { - return rhsVal - lhsVal; - }) - - pickedBetType.value.clear(); - pickedBetTypeKey.value = '[]'; - myBettings.value.clear(); - - for (const [betType, amount] of result.myBetting) { - myBettings.value.set(betType, amount); - } - - - } catch (e) { - if (isString(e)) { - toasts.value.push({ - title: "에러", - content: e, - type: "danger", - }); - } - console.error(e); - } -} - -async function submitBet(): Promise { - const info = bettingInfo.value; - if (info === undefined) { - return; - } - - const bettingID = info.bettingInfo.id; - const bettingType = JSON.parse(pickedBetTypeKey.value); - const amount = betPoint.value; - try { - await SammoAPI.Betting.Bet({ - bettingID, - bettingType, - amount, - }); - toasts.value.push({ - title: '완료', - content: '베팅했습니다', - type: 'success' - }); - await loadBetting(info.bettingInfo.id); - } catch (e) { - if (isString(e)) { - toasts.value.push({ - title: "에러", - content: e, - type: "danger", - }); - } - console.error(e); - } - -} console.log('시작!'); onMounted(async () => { diff --git a/hwe/ts/components/BettingDetail.vue b/hwe/ts/components/BettingDetail.vue new file mode 100644 index 00000000..caafdd1f --- /dev/null +++ b/hwe/ts/components/BettingDetail.vue @@ -0,0 +1,436 @@ + + + \ No newline at end of file diff --git a/hwe/ts/defs.ts b/hwe/ts/defs.ts index c5840288..173e5c22 100644 --- a/hwe/ts/defs.ts +++ b/hwe/ts/defs.ts @@ -223,3 +223,25 @@ export const diplomacyStateInfo: Record = { 2: { name: '통상' }, 7: { name: '불가침', color: 'green' }, } + + +export type SelectItem = { + title: string; + info?: string; + isHtml?: boolean; + aux?: Record; +} + +export type BettingInfo = { + id: number; + type: 'nationBetting', + name: string; + finished: boolean; + selectCnt: number; + isExclusive?: boolean; + reqInheritancePoint: boolean; + openYearMonth: number; + closeYearMonth: number; + candidates: SelectItem[]; + winner?: number[]; +} \ No newline at end of file -- 2.54.0