[mod] 先優化為Class

This commit is contained in:
建喵 2024-08-29 18:00:41 +08:00
parent e741029939
commit 735a0a6bb3
4 changed files with 515 additions and 112 deletions

367
.eslintrc.json Normal file
View File

@ -0,0 +1,367 @@
{
"env": {
"browser": true,
"es2021": true,
"jest": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended"
],
"overrides": [],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"react",
"@typescript-eslint",
"react-hooks"
],
"rules": {
"no-alert": 0, //使alert confirm prompt
"no-bitwise": 0, //使
"no-console": "off", //使console
"no-continue": 0, //使continue
"no-debugger": 2, //使debugger
"no-delete-var": 2, //var使delete
"no-div-regex": 1, //使/=foo/
"no-dupe-args": 2, //
"no-duplicate-case": 2, //switchcase
"no-else-return": "off", //ifreturn,else
"no-empty-label": "off", //使label
"no-eq-null": "off", //null使==!=
"no-extend-native": "off", //native
"no-extra-parens": "off", //
"no-extra-semi": 2, //
"no-floating-decimal": 2, //0 .5 3.
"no-implicit-coercion": "off", //
"no-inline-comments": 0, //
"no-invalid-this": 2, //this
"no-iterator": 2, //使__iterator__
"no-lonely-if": "off", //elseif
"no-mixed-requires": [
0,
false
], //
"no-mixed-spaces-and-tabs": "off", //tab
"no-multiple-empty-lines": [
1,
{
"max": 2
}
], //2
"no-nested-ternary": 0, //使
"no-new": "off", //使new
"no-new-require": 2, //使new require
"no-param-reassign": "off", //
"no-path-concat": 0, //node使__dirname__filename
"no-plusplus": 0, //使++--
"no-process-env": 0, //使process.env
"no-process-exit": 0, //使process.exit()
"no-redeclare": "off", //
"no-restricted-modules": 0, //使
"no-return-assign": "off", //return
"no-self-compare": 2, //
"no-sequences": 0, //使
"no-shadow": "off", //
"no-sync": 0, //nodejs
"no-ternary": 0, //使
"no-this-before-super": 0, //super()使thissuper
"no-throw-literal": 2, // throw "error";
"no-undef": "off", //
"no-undef-init": "off", //undefined
"no-undefined": "off", //使undefined
"no-unexpected-multiline": 2, //
"no-underscore-dangle": "off", //_
"no-unneeded-ternary": 2, // var isYes = answer === 1 ? true : false;
"no-unused-expressions": "off", //
"no-unused-vars": "off", //使
"no-use-before-define": "off", //使
"no-useless-call": "off", //callapply
"no-void": "off", //void
"no-var": 0, //varletconst
"no-warning-comments": "off", //
"no-array-constructor": "error", // 使
"no-caller": "error", // 使arguments.callerarguments.callee
"no-catch-shadow": "error", // catch
"no-class-assign": "error", //
"no-cond-assign": [
"error",
"except-parens"
], // 使
"no-constant-condition": "error", // 使 if(true) if(1)
"no-control-regex": "error", // 使
"no-dupe-keys": "error", // {a: 1, a: 1}
"no-empty": "error", //
"no-empty-character-class": "error", // []
"no-eval": "error", // 使eval
"no-ex-assign": "error", // catch
"no-extra-bind": "error", //
"no-extra-boolean-cast": "off", // bool
"no-fallthrough": "error", // switch穿
"no-func-assign": "error", //
"no-implied-eval": "error", // 使eval
"no-inner-declarations": "off", // 使
"no-invalid-regexp": "error", //
"no-irregular-whitespace": "error", //
"no-label-var": "error", // labelvar
"no-labels": "error", //
"no-lone-blocks": "error", //
"no-loop-func": "error", // 使
"no-multi-spaces": "error", //
"no-multi-str": "error", // \
"no-native-reassign": "error", // native
"no-negated-in-lhs": "error", // in !
"no-new-func": "error", // 使new Function
"no-new-object": "error", // 使new Object()
"no-new-wrappers": "error", // 使newnew String new Boolean new Number
"no-obj-calls": "error", // Math() JSON()
"no-octal": "error", // 使(0)
"no-octal-escape": "error", // 使
"no-proto": "error", // 使__proto__(__proto__)
"no-prototype-builtins": "off",
"no-regex-spaces": "error", // 使 /foo bar/
"no-script-url": "off", // 使javascript:void(0)
"no-shadow-restricted-names": "error", // 使
"no-spaced-func": "error", // ()
"no-sparse-arrays": "error", // [1,,2]
"no-trailing-spaces": [
"error",
{
"skipBlankLines": true
}
], // ( )
"no-unreachable": "error", //
"no-const-assign": "error", // const
"no-with": "error", // with
"comma-dangle": "off", //
"comma-spacing": "error", // 西
"curly": [
"error",
"multi-line"
], // 使 {}
"eqeqeq": "off", // 使
"indent": [
"off",
"tab",
{
"SwitchCase": 1
}
], // tab
"key-spacing": [
"error",
{
"beforeColon": false,
"afterColon": true
}
], //
"keyword-spacing": "off", //
"new-parens": "error", // new const person = new Person();
"quotes": [
"error",
"double",
{
"allowTemplateLiterals": true
}
], // ''
"semi": [
"error",
"always"
], //
"semi-spacing": [
0,
{
"before": false,
"after": true
}
], // 西
"space-before-blocks": [
"error",
"always"
], // {
// "space-before-function-paren": ["error", "never"], //
"space-infix-ops": "error", // a + b
"space-unary-ops": [
"error",
{
"words": true,
"nonwords": false
}
], // / new Foo 1++
// "spaced-comment": ["error", "always", { "markers": ["*!"] }], //
"strict": [
"error",
"global"
], // 使
"use-isnan": "error", // 使NaNisNaN()
"arrow-parens": 0, //
"arrow-spacing": 0, //=>/
"accessor-pairs": 0, //使getter/setter
"block-scoped-var": 0, //使var
"brace-style": "off", //
"callback-return": "off", //
"comma-style": [
"error",
"last"
], //
"complexity": [
0,
11
], //
"computed-property-spacing": [
0,
"never"
], //
"consistent-return": 0, //return
"consistent-this": "off", //this
"constructor-super": 0, //supersuper
"default-case": "off", //switchdefault
"dot-location": 0, //访
"dot-notation": [
0,
{
"allowKeywords": true
}
], //
"eol-last": 0, //
"func-names": 0, //
"func-style": [
0,
"declaration"
], //使/
"generator-star-spacing": 0, //*
"guard-for-in": 0, //for inif
"handle-callback-err": 0, //nodejs
"id-length": 0, //
"init-declarations": 0, //
"lines-around-comment": 0, ///
"max-depth": [
0,
4
], //
"max-len": [
0,
80,
4
], //
"max-nested-callbacks": [
0,
2
], //
"max-params": [
0,
3
], //3
"max-statements": [
0,
10
], //
"new-cap": "off", //使newnew
"newline-after-var": "off", //
"object-shorthand": 0, //
"one-var": "off", //
"operator-assignment": [
0,
"always"
], // += -=
"operator-linebreak": "off", //
"padded-blocks": 0, //
"prefer-spread": 0, //
"prefer-reflect": 0, //Reflect
"quote-props": "off", //
"radix": "off", //parseInt
"id-match": 0, //
"sort-vars": 0, //
"space-after-keywords": [
0,
"always"
], //
"space-before-function-paren": [
0,
"always"
], //
"space-in-parens": [
0,
"never"
], //
"space-return-throw-case": "off", //return throw case
"spaced-comment": 0, //
"valid-jsdoc": 0, //jsdoc
"valid-typeof": "error", //使typeof
"vars-on-top": "error", //var
"wrap-iife": [
"error",
"inside"
], //
"wrap-regex": 0, //
"yoda": [
"error",
"never"
], //
"linebreak-style": [
0,
"windows"
], //
"array-bracket-spacing": [
2,
"never"
], //
"react/react-in-jsx-scope": "off",
"camelcase": "off",
"block-spacing": "error",
"no-duplicate-imports": "error",
"require-yield": "off",
"prefer-const": "off",
"object-curly-spacing": [
"error",
"always"
],
"react/jsx-curly-spacing": [
"error",
"never"
],
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/prefer-namespace-keyword": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/explicit-function-return-type": [
"off",
{
"allowExpressions": true
}
],
"@typescript-eslint/typedef": [
"warn",
{
"arrayDestructuring": false,
"arrowParameter": false,
"objectDestructuring": false,
"memberVariableDeclaration": true,
"parameter": true,
"propertyDeclaration": true,
"variableDeclaration": false,
"variableDeclarationIgnoreFunction": true
}
]
},
"settings": {
"import/resolver": {
"typescript": {}
},
"react": {
"version": "detect"
}
}
}

106
src/api/slot/spin.ts Normal file
View File

@ -0,0 +1,106 @@
import { INetRequest } from "../../script/Engine/CatanEngine/NetManagerV2/Core/INetRequest";
import { INetResponse } from "../../script/Engine/CatanEngine/NetManagerV2/Core/INetResponse";
import { ClientData } from "../../shared/protocols/define/interface";
import { RpcSlot1SpinRequest, RpcSlot1SpinResponse } from "../../shared/protocols/Slot1Request";
import { RandomEx } from "../../Utils/Number/RandomEx";
export default class SlotBase {
protected temps: string[];
protected freeTemps: string[];
public *spin(clientData: ClientData, req: INetRequest<RpcSlot1SpinRequest>): IterableIterator<any> {
const data: RpcSlot1SpinRequest = req.Data
clientData.free = null;
const slotData: any = JSON.parse(this.temps[RandomEx.GetInt(0, this.temps.length)]);
let totalGet: number = 0;
if (slotData.line) {
totalGet += this.getLineGet(slotData.line);
}
if (slotData.scatter) {
totalGet += this.getScatterGet(slotData.scatter);
}
if (slotData.free) {
const count = slotData.free[1];
const { freeData, totalFreeGet } = this.getFree(count);
totalGet += totalFreeGet;
clientData.free = { count: 0, freeData };
}
if (totalGet) {
slotData.get = [[1, totalGet]];
}
clientData.money -= data.pay;
if (slotData.get) {
clientData.money += slotData.get[0][1];
}
slotData["pay"] = [[1, -data.pay]];
slotData["money"] = clientData.money;
const response: INetResponse<RpcSlot1SpinResponse> = {
Status: 0,
Method: req.Method,
Data: slotData,
IsValid: true
};
return response;
}
protected getFree(count: number) {
const freeData = [];
let totalFreeGet = 0;
for (let i: number = 0; i < count; i++) {
const slotData: any = JSON.parse(this.freeTemps[RandomEx.GetInt(0, this.freeTemps.length)]);
freeData.push(slotData);
if (slotData.line) {
totalFreeGet += this.getLineGet(slotData.line);
}
}
return { freeData, totalFreeGet }
}
getLineGet(lines: number[][]): number {
let totalGet: number = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
totalGet += line[2]
}
return totalGet;
}
getScatterGet(scatter: number[][]): number {
let totalGet: number = scatter[0][1];
return totalGet;
}
}
// // 原始的编码字符串
// // // {"slot":[4,4,1,12,14,9,10,1,6,4,8,9,1,14,10],"scatter":[[[2,7,12],100]],"pay":[[1,-100]],"get":[[1,100]],"money":9990624}
// // const encodedStr = 'H4sIAAAAAAAAA1WOMQ+CMBCF/0vnG9paRdkcSRwMjoahQjE1hZIWooTw371TSLS54d3ru7tvYpylE4vO97mJg+uztvbkNNq2WcVSAax2/rnIe/BDR5qj7UNDUipgtq3M62Rjz9KrUrBNgMMGSxbw2b1+gQIBQoJQcADBsdmhtaeGPMGLGZhutRujjbkxLq50Zz0uaJh4dJexuXm3wlY2mJIiX16kOdI5CQkeo5Wx/B/oKMp/oshZB2PQnPG9ARdrnfUWAQAA';
// // {"slot":[5,6,14,6,5,11,12,3,14,11,6,2,11,2,12],"line":[[[5,11,12,13,9],161,1500]],"pay":[[1,-100]],"get":[[1,1500]],"money":9991524}
// const encodedStr = 'H4sIAAAAAAAAA11Pu27DMAz8F84cQjlSEG9FpwAdinQMMqi2XKiQJcOykRqB/72kH0OrQTreEXenJxygfEIOabi6PIbhEpskTGt9vNRQEkIT0mODX30aO8EHplPfClRHBB9r9/Pm8wDlrdBIZ6QjFoSk77iYb5pGI4pB3mFVYSEjQ4NKHr7UfUaw0YYp+3x1LuS94Lud9nZkaGGn9jMFbsbVqjRGjtAIDx/q13VSCMFHt7Q3JMNWY02nAs9csLMT63rm4O/uY/Hcg2rfu0qS1y/zP1/EQDrm6u9q93/pxNZN7xyzM59fbBqv0msBAAA=';
// // 解码 Base64
// const decodedBytes = Buffer.from(encodedStr, 'base64');
// // 解压缩 zlib 数据
// gunzip(decodedBytes, (err, decompressedBytes) => {
// if (err) {
// console.error('解压缩失败:', err);
// return;
// }
// // 解析 JSON 数据
// try {
// const jsonData = JSON.parse(decompressedBytes.toString());
// console.log(JSON.stringify(jsonData, null, 4));
// } catch (parseErr) {
// console.error('JSON 解析失败:', parseErr);
// }
// });

View File

@ -1,86 +1,15 @@
import { INetRequest } from "../../script/Engine/CatanEngine/NetManagerV2/Core/INetRequest"; import SlotBase from "../slot/spin";
import { INetResponse } from "../../script/Engine/CatanEngine/NetManagerV2/Core/INetResponse";
import { ClientData } from "../../shared/protocols/define/interface";
import { RpcSlot1SpinRequest, RpcSlot1SpinResponse } from "../../shared/protocols/Slot1Request";
import { RandomEx } from "../../Utils/Number/RandomEx";
export default function* (clientData: ClientData, req: INetRequest<RpcSlot1SpinRequest>): IterableIterator<any> {
const data: RpcSlot1SpinRequest = req.Data
clientData.free = null;
// // 原始的编码字符串 export default class Slot1 extends SlotBase {
// // // {"slot":[4,4,1,12,14,9,10,1,6,4,8,9,1,14,10],"scatter":[[[2,7,12],100]],"pay":[[1,-100]],"get":[[1,100]],"money":9990624} protected temps: string[] = [
// // const encodedStr = 'H4sIAAAAAAAAA1WOMQ+CMBCF/0vnG9paRdkcSRwMjoahQjE1hZIWooTw371TSLS54d3ru7tvYpylE4vO97mJg+uztvbkNNq2WcVSAax2/rnIe/BDR5qj7UNDUipgtq3M62Rjz9KrUrBNgMMGSxbw2b1+gQIBQoJQcADBsdmhtaeGPMGLGZhutRujjbkxLq50Zz0uaJh4dJexuXm3wlY2mJIiX16kOdI5CQkeo5Wx/B/oKMp/oshZB2PQnPG9ARdrnfUWAQAA';
// // {"slot":[5,6,14,6,5,11,12,3,14,11,6,2,11,2,12],"line":[[[5,11,12,13,9],161,1500]],"pay":[[1,-100]],"get":[[1,1500]],"money":9991524}
// const encodedStr = 'H4sIAAAAAAAAA11Pu27DMAz8F84cQjlSEG9FpwAdinQMMqi2XKiQJcOykRqB/72kH0OrQTreEXenJxygfEIOabi6PIbhEpskTGt9vNRQEkIT0mODX30aO8EHplPfClRHBB9r9/Pm8wDlrdBIZ6QjFoSk77iYb5pGI4pB3mFVYSEjQ4NKHr7UfUaw0YYp+3x1LuS94Lud9nZkaGGn9jMFbsbVqjRGjtAIDx/q13VSCMFHt7Q3JMNWY02nAs9csLMT63rm4O/uY/Hcg2rfu0qS1y/zP1/EQDrm6u9q93/pxNZN7xyzM59fbBqv0msBAAA=';
// // 解码 Base64
// const decodedBytes = Buffer.from(encodedStr, 'base64');
// // 解压缩 zlib 数据
// gunzip(decodedBytes, (err, decompressedBytes) => {
// if (err) {
// console.error('解压缩失败:', err);
// return;
// }
// // 解析 JSON 数据
// try {
// const jsonData = JSON.parse(decompressedBytes.toString());
// console.log(JSON.stringify(jsonData, null, 4));
// } catch (parseErr) {
// console.error('JSON 解析失败:', parseErr);
// }
// });
const temps: string[] = [
`{"slot":[11,4,8,9,5,2,13,10,7,9,10,6,6,12,4],"line":[[[5,11,12],161,2000]]}`, `{"slot":[11,4,8,9,5,2,13,10,7,9,10,6,6,12,4],"line":[[[5,11,12],161,2000]]}`,
`{"slot":[9,6,2,5,4,14,10,9,13,10,4,5,5,2,2]}`, `{"slot":[9,6,2,5,4,14,10,9,13,10,4,5,5,2,2]}`,
`{"slot":[4,3,3,3,9,10,14,14,9,4,7,8,8,5,10],"free":[[1,2,3],3],"scatter":[[[1,2,3],3000]]}`, `{"slot":[4,3,3,3,9,10,14,14,9,4,7,8,8,5,10],"free":[[1,2,3],3],"scatter":[[[1,2,3],3000]]}`,
]; ];
const slotData: any = JSON.parse(temps[RandomEx.GetInt(0, temps.length)]); protected freeTemps: string[] = [
let totalGet: number = 0;
if (slotData.line) {
totalGet += getLineGet(slotData.line);
}
if (slotData.scatter) {
totalGet += getScatterGet(slotData.scatter);
}
if (slotData.free) {
const count = slotData.free[1];
const { freeData, totalFreeGet } = getFree(count);
totalGet += totalFreeGet;
clientData.free = { count: 0, freeData };
}
if (totalGet) {
slotData.get = [[1, totalGet]];
}
clientData.money -= data.pay;
if (slotData.get) {
clientData.money += slotData.get[0][1];
}
slotData["pay"] = [[1, -data.pay]];
slotData["money"] = clientData.money;
const response: INetResponse<RpcSlot1SpinResponse> = {
Status: 0,
Method: req.Method,
Data: slotData,
IsValid: true
};
return response;
}
function getFree(count: number) {
const freeData = [];
let totalFreeGet = 0;
const freeTemps: string[] = [
`{"slot":[13,9,5,14,4,9,4,12,12,11,4,14,8,7,6],"line":[[[10,6],195,300],[[10,6],213,300]]}`, `{"slot":[13,9,5,14,4,9,4,12,12,11,4,14,8,7,6],"line":[[[10,6],195,300],[[10,6],213,300]]}`,
`{"slot":[9,9,10,13,4,5,4,3,4,11,10,14,14,14,5]}`, `{"slot":[9,9,10,13,4,5,4,3,4,11,10,14,14,14,5]}`,
`{"slot":[12,6,8,12,11,7,12,11,5,5,11,5,3,10,9]}`, `{"slot":[12,6,8,12,11,7,12,11,5,5,11,5,3,10,9]}`,
@ -92,26 +21,4 @@ function getFree(count: number) {
`{"slot":[10,14,13,9,8,6,6,6,4,13,13,12,9,14,4],"line":[[[5,6,7],122,3000]]}`, `{"slot":[10,14,13,9,8,6,6,6,4,13,13,12,9,14,4],"line":[[[5,6,7],122,3000]]}`,
`{"slot":[11,13,9,8,5,8,5,5,13,9,14,9,12,4,7]}`, `{"slot":[11,13,9,8,5,8,5,5,13,9,14,9,12,4,7]}`,
]; ];
for (let i: number = 0; i < count; i++) {
const slotData: any = JSON.parse(freeTemps[RandomEx.GetInt(0, freeTemps.length)]);
freeData.push(slotData);
if (slotData.line) {
totalFreeGet += getLineGet(slotData.line);
}
}
return { freeData, totalFreeGet }
}
function getLineGet(lines: number[][]): number {
let totalGet: number = 0;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
totalGet += line[2]
}
return totalGet;
}
function getScatterGet(scatter: number[][]): number {
let totalGet: number = scatter[0][1];
return totalGet;
} }

View File

@ -58,33 +58,56 @@ export class NetConnector {
try { try {
// 动态导入文件 // 动态导入文件
const module = await import(`../../../../api/${req.Method.replace(".", "/")}`); const module = await import(`../../../../api/${req.Method.replace(".", "/")}`);
const isClass = typeof module.default === 'function' && module.default.prototype && Object.getOwnPropertyNames(module.default.prototype).includes('constructor');
// 调用导入模块中的处理函数 // 调用导入模块中的处理函数
if (module.default) { if (module.default) {
let AsyncFunction: () => IterableIterator<any> = function* (): IterableIterator<any> { if (isClass) {
const clientData: ClientData = NetConnector.clients.get(socket); const moduleClass = new module.default();
const response: INetResponse<any> = yield* module.default(clientData, req); let AsyncFunction: () => IterableIterator<any> = function* (): IterableIterator<any> {
if (response) { const clientData: ClientData = NetConnector.clients.get(socket);
NetConnector.Send(socket, response); const method: string = req.Method.split(".")[1];
} try {
}; const response: INetResponse<any> = yield* moduleClass[method](clientData, req);
CoroutineV2.Single(AsyncFunction()).Start(); if (response) {
NetConnector.Send(socket, response);
}
} catch (error) {
console.error(`Error handling request ${req.Method}: ${error.message}`);
NetConnector.sendError(socket, req);
}
};
CoroutineV2.Single(AsyncFunction()).Start();
} else {
let AsyncFunction: () => IterableIterator<any> = function* (): IterableIterator<any> {
const clientData: ClientData = NetConnector.clients.get(socket);
const response: INetResponse<any> = yield* module.default(clientData, req);
if (response) {
NetConnector.Send(socket, response);
}
};
CoroutineV2.Single(AsyncFunction()).Start();
}
} else { } else {
throw new Error(`Module for ${req.Method} does not export a default function.`); throw new Error(`Module for ${req.Method} does not export a default function.`);
} }
} catch (error) { } catch (error) {
console.error(`Error handling request ${req.Method}: ${error.message}`); console.error(`Error handling request ${req.Method}: ${error.message}`);
const response: INetResponse<any> = { NetConnector.sendError(socket, req);
Status: -1,
Method: req.Method,
Data: null,
IsValid: false
};
NetConnector.Send(socket, response);
} }
} }
} }
private static sendError(socket: WebSocket, req: INetRequest<any>) {
const response: INetResponse<any> = {
Status: -1,
Method: req.Method,
Data: null,
IsValid: false
};
NetConnector.Send(socket, response);
}
public static OnWebSocketClose() { public static OnWebSocketClose() {
console.log('Client disconnected'); console.log('Client disconnected');
} }