Browse Source

python优化

alex 1 year ago
parent
commit
2501df1b46

+ 1 - 0
.gitignore

@@ -10,3 +10,4 @@
 local.properties
 /yyyy_js/python-server/.idea
 /yyyy_js/python-server/*.properties
+/yyyy_js/python-server/*.log

+ 1 - 1
cli/src/main/cpp/cli.cpp

@@ -37,7 +37,7 @@ readFile(JNIEnv *env,
     char buffer[1024];
     // 将所有的buffer写到一个对象中
     while (fgets(buffer, sizeof(buffer), file)) {
-        printf("%s", buffer);
+//        printf("%s", buffer);
         buffers += buffer; // 使用 += 运算符追加内容
     }
     fclose(file);

+ 64 - 72
yyyy_js/assets/main/index.jsc

@@ -93,11 +93,7 @@ console.log = function (...args) {
     splitAndPrintString(combinedString, maxChunkSize);
 };
 
-function systemlog(...args){
-    originalConsoleLog(args);
-}
-
-const wsUrl = 'ws://192.168.137.1:9999';
+const wsUrl = 'ws://192.168.2.31:9999';
 let lws;
 let attempt = 1;
 
@@ -302,7 +298,7 @@ var totalProfit = 0;
 
 function dealMsg(msgType,data) {
     lws.send(`${msgType}:${JSON.stringify(data)}`);
-    return;
+
     switch(msgType){
         case "GameDataSynNotify"://进房间后同步已下注信息
             betInfoMap.clear();
@@ -408,13 +404,13 @@ function dealMsg(msgType,data) {
 }
 
 
-window.__require = function e(methodPath, cacheExports, exportKeyArray) {
-    function loadModule(a, s) {
-        if (!cacheExports[a]) {
-            if (!methodPath[a]) {
+window.__require = function e(t, n, o) {
+    function i(a, s) {
+        if (!n[a]) {
+            if (!t[a]) {
                 var c = a.split("/");
                 c = c[c.length - 1];
-                if (!methodPath[c]) {
+                if (!t[c]) {
                     var l = "function" == typeof __require && __require;
                     if (!s && l) return l(c, !0);
                     if (r) return r(c, !0);
@@ -422,17 +418,17 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                 }
                 a = c;
             }
-            var u = cacheExports[a] = {
+            var u = n[a] = {
                 exports: {}
             };
-            methodPath[a][0].call(u.exports, function (e) {
-                return loadModule(methodPath[a][1][e] || e);
-            }, u, u.exports, e, methodPath, cacheExports, exportKeyArray);
+            t[a][0].call(u.exports, function (e) {
+                return i(t[a][1][e] || e);
+            }, u, u.exports, e, t, n, o);
         }
-        return cacheExports[a].exports;
+        return n[a].exports;
     }
-    for (var r = "function" == typeof __require && __require, a = 0; a < exportKeyArray.length; a++) loadModule(exportKeyArray[a]);
-    return loadModule;
+    for (var r = "function" == typeof __require && __require, a = 0; a < o.length; a++) i(o[a]);
+    return i;
 }({
     1: [function (e, t) {
         var n = e("util/"), o = Array.prototype.slice, i = Object.prototype.hasOwnProperty, r = t.exports = u;
@@ -205892,7 +205888,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
             value: !0
         });
         n.WebSocketState = void 0;
-        var o, _NetworkConfig = e("./NetworkConfig"), r = e("../common/UI/LoadingManager"), a = e("../common/BJConfig"), s = e("../common/UI/PopupManager"), c = e("../common/SceneManager"), l = e("../common/BJTranslator"), u = e("../common/LangData"), d = e("../common/BJBasicConfig"), p = e("../common/BJDataManager"), h = e("../common/Utils"), f = e("../blackjack/BJDataHolder"), g = e("../common/BJConsoleLog"), m = function () { };
+        var o, i = e("./NetworkConfig"), r = e("../common/UI/LoadingManager"), a = e("../common/BJConfig"), s = e("../common/UI/PopupManager"), c = e("../common/SceneManager"), l = e("../common/BJTranslator"), u = e("../common/LangData"), d = e("../common/BJBasicConfig"), p = e("../common/BJDataManager"), h = e("../common/Utils"), f = e("../blackjack/BJDataHolder"), g = e("../common/BJConsoleLog"), m = function () { };
         (function (e) {
             e[e.CLOSED = 0] = "CLOSED";
             e[e.CLOSING = 1] = "CLOSING";
@@ -205960,18 +205956,18 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                     clearTimeout(n._pingAction);
                     clearTimeout(n._pongAction);
                     n._tryPong = 0;
-                    n._pingAction = setTimeout(n.ping, _NetworkConfig.default.PING_TIMEOUT_INTERVAL);
+                    n._pingAction = setTimeout(n.ping, i.default.PING_TIMEOUT_INTERVAL);
                 };
                 this.ping = function () {
                     if (n.ws) {
                         n.ws.send(n.pingMessageData);
-                        n._pongAction = setTimeout(n.pong, _NetworkConfig.default.PONG_TIMEOUT_INTERVAL);
+                        n._pongAction = setTimeout(n.pong, i.default.PONG_TIMEOUT_INTERVAL);
                     }
                 };
                 this.pong = function () {
                     n._tryPong++;
                     g.BJConsoleLog.log("pong try lost", n.url, n._tryPong);
-                    if (n._tryPong >= _NetworkConfig.default.PING_PONG_TRY_TIME) {
+                    if (n._tryPong >= i.default.PING_PONG_TRY_TIME) {
                         n._tryPong = 0;
                         g.BJConsoleLog.log("pong lost", n.url);
                         n.connect();
@@ -238891,7 +238887,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
         Object.defineProperty(n, "__esModule", {
             value: !0
         });
-        var a = e("./CustomScrollViewItem"), cc_decorator = cc._decorator, cc_ccclass = cc_decorator.ccclass, cc_property = cc_decorator.property, u = function (e) {
+        var a = e("./CustomScrollViewItem"), s = cc._decorator, c = s.ccclass, l = s.property, u = function (e) {
             i(t, e);
             function t() {
                 var t = null !== e && e.apply(this, arguments) || this;
@@ -239018,10 +239014,10 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
             t.prototype.resetContentPosition = function () {
                 cc.isValid(this.initPos) && this.content.setPosition(this.initPos);
             };
-            r([cc_property], t.prototype, "displayBuffer", void 0);
-            r([cc_property(cc.Mask)], t.prototype, "view", void 0);
-            r([cc_property(cc.Prefab)], t.prototype, "loadPrefab", void 0);
-            return r([cc_ccclass], t);
+            r([l], t.prototype, "displayBuffer", void 0);
+            r([l(cc.Mask)], t.prototype, "view", void 0);
+            r([l(cc.Prefab)], t.prototype, "loadPrefab", void 0);
+            return r([c], t);
         }(cc.ScrollView);
         n.default = u;
         cc._RF.pop();
@@ -288225,33 +288221,33 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                 });
             }
         };
-        HMFExtension.openPokerMasterGameWithRoomId = function (roomId, exitWhere) {
-            if (0 != roomId) {
+        HMFExtension.openPokerMasterGameWithRoomId = function (e, t) {
+            if (0 != e) {
                 var n = {
-                    roomId: roomId,
-                    exitWhere: exitWhere
+                    roomId: e,
+                    exitWhere: t
                 };
                 CurrentUserInfo.littleGameType = "pkm";
                 CurrentUserInfo.pkmGameParam = n;
                 cc.vv.loading.show();
-                CurrentUserInfo.user.wasUserInDiamondGame ? HMFHTTPClient.pokerMasterGameLogin(roomId).then(function (n) {
+                CurrentUserInfo.user.wasUserInDiamondGame ? HMFHTTPClient.pokerMasterGameLogin(e).then(function (n) {
                     cc.vv.loading.hide();
                     console.log(n);
                     if (0 == n.errorCode) {
-                        HMFAppSetting.pokerMasterExitWhere = exitWhere;
+                        HMFAppSetting.pokerMasterExitWhere = t;
                         cc.sys.localStorage.setItem("PokerMasterWs", n.data.gate_addr[0]);
                         cc.sys.localStorage.setItem("PokerMasterToken", n.data.token);
                         l.worldNet.initCommon(l.Enum.GameId.World);
                         l.getPokerMasterNet().initCommon(l.Enum.GameId.PokerMaster);
-                        l.roomManager.RequestJoinRoom(l.Enum.GameId.PokerMaster, roomId);
+                        l.roomManager.RequestJoinRoom(l.Enum.GameId.PokerMaster, e);
                     }
                 }, function () {
                     cc.vv.loading.hide();
                 }) : l.netWorkManager.onWpkSwitchNetConnect(!0, function () {
                     l.worldNet.initCommon(l.Enum.GameId.World);
-                    l.roomManager.setCurrentRoomID(roomId);
+                    l.roomManager.setCurrentRoomID(e);
                     l.getPokerMasterNet().initCommon(l.Enum.GameId.PokerMaster);
-                    l.roomManager.RequestJoinRoom(l.Enum.GameId.PokerMaster, roomId);
+                    l.roomManager.RequestJoinRoom(l.Enum.GameId.PokerMaster, e);
                 });
             }
         };
@@ -366802,19 +366798,19 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
         "../../../../scripts/common/MultiTableHelper": "MultiTableHelper",
         "../../components/lobby/cv": "cv"
     }],
-    NetWork: [function (moduleLoader, moduleKey, moduleInstance) {
+    NetWork: [function (e, t, n) {
         "use strict";
-        cc._RF.push(moduleKey, "e93a6atiglGeIIneILp46VP", "NetWork");
+        cc._RF.push(t, "e93a6atiglGeIIneILp46VP", "NetWork");
         var o = this && this.__decorate || function (e, t, n, o) {
             var i, r = arguments.length, a = r < 3 ? t : null === o ? o = Object.getOwnPropertyDescriptor(t, n) : o;
             if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a = Reflect.decorate(e, t, n, o); else for (var s = e.length - 1; s >= 0; s--) (i = e[s]) && (a = (r < 3 ? i(a) : r > 3 ? i(t, n, a) : i(t, n)) || a);
             return r > 3 && a && Object.defineProperty(t, n, a), a;
         };
-        Object.defineProperty(moduleInstance, "__esModule", {
+        Object.defineProperty(n, "__esModule", {
             value: !0
         });
-        moduleInstance.NetWork = void 0;
-        var i = moduleLoader("./ByteArray"), r = moduleLoader("../../components/game/cowboy/CowboyWsNetWork"), a = moduleLoader("../../components/lobby/cv"), s = moduleLoader("../plugg/aesHandler"), c = moduleLoader("../tools/HashMap"), l = moduleLoader("./BitHandler"), u = moduleLoader("../../components/game/pokerMaster/PokerMasterNetWork"), d = cc._decorator, p = d.ccclass, netWorkInstance = (d.property,
+        n.NetWork = void 0;
+        var i = e("./ByteArray"), r = e("../../components/game/cowboy/CowboyWsNetWork"), a = e("../../components/lobby/cv"), s = e("../plugg/aesHandler"), c = e("../tools/HashMap"), l = e("./BitHandler"), u = e("../../components/game/pokerMaster/PokerMasterNetWork"), d = cc._decorator, p = d.ccclass, h = (d.property,
             function () {
                 function e() {
                     this.wSocket = null;
@@ -366891,7 +366887,6 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                     }
                 };
                 e.prototype.sendMsg = function (e, t, n, o, i) {
-                    console.log(`====>>>>sendMsg `,e,t,n,o,i);
                     if (this.sendPackage(e, t, n, o, i)) {
                         a.default.LoadingView.addWebSocketMsg(i, t);
                         return !0;
@@ -366900,8 +366895,6 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                     return !1;
                 };
                 e.prototype.sendPackage = function (e, t, n, o, c) {
-                    console.log(`====>>>>sendPackage `,e,t,n,o,c);
-
                     var l, d = this.isEncrypt(c);
                     d && (l = s.aesHandler.EncryptBytes(e));
                     var p = new i.ByteArray();
@@ -366921,7 +366914,6 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                     return c == a.default.Enum.GameId.PokerMaster ? window.CurrentUserInfo.user.wasUserInDiamondGame ? u.PokerMasterNetWork.getInstance().send(p.getbuffer()) : this.send(p.getbuffer()) : c == a.default.Enum.GameId.CowBoy && window.CurrentUserInfo.user.wasUserInDiamondGame ? r.CowboyWsNetWork.getInstance().send(p.getbuffer()) : this.send(p.getbuffer());
                 };
                 e.prototype.send = function (e) {
-                    console.log(`====>>>>send `,e);
                     if (!this.wSocket) return !1;
                     if (this.wSocket.readyState == WebSocket.OPEN) {
                         this.wSocket.send(e);
@@ -367111,7 +367103,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                 var t;
                 return t = o([p], e);
             }());
-        moduleInstance.NetWork = netWorkInstance;
+        n.NetWork = h;
         cc._RF.pop();
     }, {
         "../../components/game/cowboy/CowboyWsNetWork": "CowboyWsNetWork",
@@ -380386,7 +380378,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                 this.registerMessage(e, t, s.default.Enum.GameId.PokerMaster);
             };
             t.prototype._sendNetMsg = function (e, t, n, o) {
-                console.log(`====>>>> pokermaster_proto-send-`, n + "-" + e + " = " + t);
+                console.log("pokermaster_proto-send-" + n + "-" + e + " = " + t);
                 var i = this.encodePB(e, t);
                 return this.sendMsg(i, n, o, s.default.Enum.SeverType.SeverType_Game, s.default.Enum.GameId.PokerMaster);
             };
@@ -381906,7 +381898,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
         "../../lobby/cv": "cv",
         "./PokerMasterRoomData": "PokerMasterRoomData"
     }],
-    PokerMasterHallSocket: [function (loadModule, t, n) {
+    PokerMasterHallSocket: [function (e, t, n) {
         "use strict";
         cc._RF.push(t, "713f3WdnDhJZppOA/4ZX1xA", "PokerMasterHallSocket");
         var o, i = this && this.__extends || (o = function (e, t) {
@@ -381928,7 +381920,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
             value: !0
         });
         n.PokerMasterHallSocket = void 0;
-        var r = loadModule("../../../../../pkw/Script/common/pb/pokermaster"), roomConfig = r.pokermaster_proto_hall, s = loadModule("../../lobby/cv"), c = loadModule("./PokerMasterDataMgr"), l = loadModule("../../../common/net/NetWorkProxy"), u = loadModule("./PokerMasterDef"), d = loadModule("./PokerMasterRoomData"), p = function (e) {
+        var r = e("../../../../../pkw/Script/common/pb/pokermaster"), roomConfig = r.pokermaster_proto_hall, s = e("../../lobby/cv"), c = e("./PokerMasterDataMgr"), l = e("../../../common/net/NetWorkProxy"), u = e("./PokerMasterDef"), d = e("./PokerMasterRoomData"), p = function (e) {
             i(t, e);
             function t() {
                 return null !== e && e.apply(this, arguments) || this;
@@ -382037,13 +382029,13 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
             t.prototype.requestJoinRoom = function (e) {
                 this._requestJoinRoom(e);
             };
-            t.prototype._requestJoinRoom = function (room_id) {
+            t.prototype._requestJoinRoom = function (e) {
                 console.log("Saad in join room request " + s.default.dataHandler.getUserData().m_bIsLoginGameServerSucc);
                 if (s.default.dataHandler.getUserData().m_bIsLoginGameServerSucc) {
                     var t = roomConfig.JoinRoomReq.create();
-                    t.roomid = room_id;
-                    console.log("saad sending join room msg with room id " + room_id);
-                    this._sendNetMsg("JoinRoomReq", t, roomConfig.CMD.JOIN_ROOM_REQ, room_id);
+                    t.roomid = e;
+                    console.log("saad sending join room msg with room id " + e);
+                    this._sendNetMsg("JoinRoomReq", t, roomConfig.CMD.JOIN_ROOM_REQ, e);
                 } else this.requestVerifyLogin();
             };
             t.prototype._handleJoinRoomResponse = function (e, t) {
@@ -382545,7 +382537,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
         "./PokerMasterDef": "PokerMasterDef",
         "./PokerMasterRoomData": "PokerMasterRoomData"
     }],
-    PokerMasterNetWork: [function (e, t, thisPokerMasterNetWork) {
+    PokerMasterNetWork: [function (e, t, n) {
         "use strict";
         cc._RF.push(t, "975ceEgFRxDG7lkqU+MeLCe", "PokerMasterNetWork");
         var o = this && this.__decorate || function (e, t, n, o) {
@@ -382553,10 +382545,10 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
             if ("object" == typeof Reflect && "function" == typeof Reflect.decorate) a = Reflect.decorate(e, t, n, o); else for (var s = e.length - 1; s >= 0; s--) (i = e[s]) && (a = (r < 3 ? i(a) : r > 3 ? i(t, n, a) : i(t, n)) || a);
             return r > 3 && a && Object.defineProperty(t, n, a), a;
         };
-        Object.defineProperty(thisPokerMasterNetWork, "__esModule", {
+        Object.defineProperty(n, "__esModule", {
             value: !0
         });
-        thisPokerMasterNetWork.PokerMasterNetWork = void 0;
+        n.PokerMasterNetWork = void 0;
         var i = e("../../lobby/cv"), r = cc._decorator, a = r.ccclass, s = (r.property,
             function () {
                 function e() {
@@ -382661,7 +382653,7 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                 var t;
                 return t = o([a], e);
             }());
-        thisPokerMasterNetWork.PokerMasterNetWork = s;
+        n.PokerMasterNetWork = s;
         cc._RF.pop();
     }, {
         "../../lobby/cv": "cv"
@@ -399388,23 +399380,23 @@ window.__require = function e(methodPath, cacheExports, exportKeyArray) {
                     }
                 }
             };
-            e.prototype.RequestJoinRoom = function (gameId, roomId, isQuickRoom, isNeedPassword, roomPassWord) {
+            e.prototype.RequestJoinRoom = function (e, t, n, i, r) {
                 var a = this;
-                void 0 === gameId && (gameId = this.current_gameId);
-                void 0 === roomId && (roomId = this.current_roomId);
-                void 0 === isQuickRoom && (isQuickRoom = this.isQuickRoom);
-                void 0 === isNeedPassword && (isNeedPassword = this.isNeedPassword);
-                void 0 === roomPassWord && (roomPassWord = this.roomPassWord);
-                if (!(gameId >= o.GameId.ZoomTexas && gameId <= o.GameId.ZoomTexasMax) || lobbyCv.default.dataHandler.getActivityData().haveAvatar()) {
+                void 0 === e && (e = this.current_gameId);
+                void 0 === t && (t = this.current_roomId);
+                void 0 === n && (n = this.isQuickRoom);
+                void 0 === i && (i = this.isNeedPassword);
+                void 0 === r && (r = this.roomPassWord);
+                if (!(e >= o.GameId.ZoomTexas && e <= o.GameId.ZoomTexasMax) || lobbyCv.default.dataHandler.getActivityData().haveAvatar()) {
                     (function () {
-                        a.setCurrentGameID(gameId);
-                        a.setCurrentRoomID(roomId);
-                        console.log("Saad setting room id " + roomId);
-                        a.setRoomPassWord(roomPassWord);
-                        a.setIsNeedPassword(isNeedPassword);
-                        a.setIsQuickRoom(isQuickRoom);
-                        a._checkShowLoadingByGameID(gameId);
-                        if (lobbyCv.default.netWork.isEncrypt(gameId) && !c.ecdhHandler.getInstance().ecdh_getNeedGenKeyState()) {
+                        a.setCurrentGameID(e);
+                        a.setCurrentRoomID(t);
+                        console.log("Saad setting room id " + t);
+                        a.setRoomPassWord(r);
+                        a.setIsNeedPassword(i);
+                        a.setIsQuickRoom(n);
+                        a._checkShowLoadingByGameID(e);
+                        if (lobbyCv.default.netWork.isEncrypt(e) && !c.ecdhHandler.getInstance().ecdh_getNeedGenKeyState()) {
                             var o = c.ecdhHandler.getInstance().ecdh_getClientPubX(), l = c.ecdhHandler.getInstance().ecdh_getClientPubY();
                             c.ecdhHandler.getInstance().ecdh_setNeedGenKeyState(!0);
                             lobbyCv.default.worldNet.RequestSetEcdhKey(0, o, l);

+ 91 - 0
yyyy_js/python-server/data_analysis/analysis2.py

@@ -0,0 +1,91 @@
+import json
+
+# 假设数据文件名为 'betting_data.txt',每行为一个时间戳和JSON数据
+file_path = '分析开奖记录.log'
+
+index = 0
+total_payout_by_bet_odd = 0
+total_payout_by_settle = 0
+bet_101 = 0
+bet_102 = 0
+options_pay_out = {}
+
+
+def process_settle(key, data):
+    global total_payout_by_settle, total_payout_by_bet_odd
+    player_settle = data["playerSettle"]
+    for player in player_settle:
+        total_payout_by_settle += player["totalWinAmount"]
+
+    other_players = data["otherPlayers"]
+    total_payout_by_settle += other_players["totalWinAmount"]
+
+    # 开奖结果
+    for result in data["optionResult"]:
+        if result["result"] == 1:
+            total_payout_by_bet_odd += options_pay_out[result["option"]]
+
+
+def compare_obb_and_settle(key, data):
+    global total_payout_by_settle, total_payout_by_bet_odd
+    diff_value = (total_payout_by_settle - total_payout_by_bet_odd) / 100
+    diff_value = round(diff_value, 2)
+    if diff_value != 0:
+        print(
+            f"{key} odd结果:{total_payout_by_bet_odd} 开奖结果:{total_payout_by_settle} 差值:{diff_value}¥ 数值不同不予计入")
+    else:
+        # print(f"{key} odd结果:{total_payout_by_bet_odd} 开奖结果:{total_payout_by_settle} 差值:{diff_value}¥")
+        pass
+
+
+def clear():
+    global bet_101, bet_102, total_payout_by_bet_odd, total_payout_by_settle
+    bet_101 = 0
+    bet_102 = 0
+    total_payout_by_bet_odd = 0
+    total_payout_by_settle = 0
+    options_pay_out.clear()
+
+
+def parse_data_from_file(file_path):
+    global index
+    with open(file_path, 'r', encoding='utf-8') as file:
+        for line in file:
+            # print(line)
+            line_strip = line.strip()
+            line_strip = line_strip.replace("'", '"')
+            line_strip = line_strip.replace("False", "false")
+            line_strip = line_strip.replace("True", "true")
+            timestamp = line_strip[:19]
+            json_data = line_strip[20:]
+            key = timestamp
+
+            data = json.loads(json_data)
+            if index % 2 == 0:
+                process_obb(key, data)
+            else:
+                process_settle(key, data)
+                compare_obb_and_settle(key, data)
+                clear()
+            index += 1
+
+
+def process_obb(key, data):
+    global total_payout_by_bet_odd, bet_101, bet_102
+    for item in data.values():
+        option_ = item["option"]
+        odds_ = item["odds"]
+        bet_ = item["total_bet"]
+        odds__bet_ = odds_ * bet_
+        options_pay_out[option_] = round(odds__bet_, 2)
+        if option_ == 101:
+            bet_101 = bet_
+        elif option_ == 102:
+            bet_102 = bet_
+        elif option_ == 103:
+            options_pay_out[option_] = bet_101 + bet_102
+
+
+# 开始解析文件
+if __name__ == '__main__':
+    parse_data_from_file(file_path)

+ 78 - 100
yyyy_js/python-server/pokermaster/PokerMasterDataProccesser.py

@@ -6,6 +6,9 @@ from itertools import product
 # 所有的下注选项
 OPTIONS = [101, 102, 103, 301, 302, 303, 304, 305]
 
+TIMES_LIMIT = 10
+autoOutEnter = 0
+
 
 # 下注选项
 class BetOption:
@@ -18,11 +21,22 @@ class BetOption:
         self.limitRed = limit
         self.total_bet = total_bet
 
+    def to_json(self):
+        return {'option': self.option, 'odds': self.odds, 'total_bet': self.total_bet}
+
     def __str__(self):
         return (f"BetOption(option={self.option}, odds={self.odds}, "
                 f"limitRed={self.limitRed}, totalBet={self.total_bet})")
 
 
+class BetOptionEncoder(json.JSONEncoder):
+    def default(self, obj):
+        if isinstance(obj, BetOption):
+            return obj.to_json()  # Use the to_json method defined in BetOption.
+        # Let the base class default method raise the TypeError
+        return json.JSONEncoder.default(self, obj)
+
+
 # 用户信息
 class User:
     # 对应option的下注金额
@@ -49,7 +63,7 @@ def init_round_option_info():
 
 
 # 用于存储User对象的用户信息和次数,key为用户ID,value为User对象
-round_user_betinfo = {}
+# round_user_betinfo = {}
 
 round_option_info = {}
 
@@ -64,6 +78,12 @@ banker_finance = 0
 DATA_SYN_NOTIFY_UID = -9999
 
 
+async def write_message_2_log_file(log):
+    with open("开奖记录.log", "a", encoding="utf-8") as f:
+        time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+        f.write(f"{time}:{log}\n")
+
+
 async def deal_message(message, broadcast_func):
     try:
         msg_type, data = parse_message(message)
@@ -76,7 +96,7 @@ async def deal_message(message, broadcast_func):
         elif msg_type == "KickNotify":
             await kickNotify(data, broadcast_func)
         elif msg_type == "GameRoundEndNotify":
-            await gameRoundEndNotify(data)
+            await gameRoundEndNotify(data, broadcast_func)
         elif msg_type == "MergeAutoBetNotify":
             await MergeAutoBetNotify(data)
         else:
@@ -85,47 +105,25 @@ async def deal_message(message, broadcast_func):
         logging.info(f"Received message: {message}")
 
 
-async def gameRoundEndNotify(data):
+async def judge_auto_out_and_int(broadcast_func):
+    global autoOutEnter, TIMES_LIMIT
+    autoOutEnter += 1
+    if autoOutEnter >= TIMES_LIMIT:
+        autoOutEnter = 0
+        await broadcast_func('''CMD:
+                    window.__require("PokerMasterHallSocket").PokerMasterHallSocket.getInstance().requestLeaveRoom();//立即退出
+                    setTimeout(function(){
+                        window.HMFExtension.openPokerMasterGameWithRoomId("716619","")
+                    },3000);//3秒后自动进入
+                ''')
+
+
+async def gameRoundEndNotify(data, broadcast_func):
     global banker_finance
-    time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-
-    print(f"{time}:收到结束下注GameRoundEndNotify")
-    # 开始结算
-    # 本轮收入
-    current_round_income = 0
-    # 本轮总下注金额
-    current_round_bet_amount = 0
-
-    for option in round_option_info.values():
-        current_round_bet_amount += option.total_bet
-        current_round_income = current_round_bet_amount
-
-    # 开奖结果
-    option_results = data["optionResult"]
-    win_option = [x["option"] for x in option_results if x["result"] == 1]
-    print(f"本轮中奖选项: {win_option}")
-    # 庄家结算
-    current_round_income = await bankerSettlement(current_round_income, option_results)
-    # 玩家结算
-    await playerSettlement(option_results)
-
-    await win_option_combo_analysis(current_round_bet_amount, win_option)
-
-    banker_finance += current_round_income
-    print(
-        f"庄家金币: {round(banker_finance / 100, 2)}¥    本轮总下注{round(current_round_bet_amount / 100, 2)}¥ 收入: {round(current_round_income / 100, 2)}¥")
-
-    # 格式化一下,避免数字位数导致各种缩进
-    with open("庄家盈亏记录.txt", "a", encoding="utf-8") as f:
-        finalxx = f"{time}:庄家金币: {banker_finance / 100}¥    本轮总下注{current_round_bet_amount / 100}¥ 收入: {current_round_income / 100}¥"
-        print(finalxx)
-        f.write(finalxx + "\n")
-    # 每把结束存储数据,然后清空数据
-    with open("用户记录.txt", "a", encoding="utf-8") as f:
-        # 将user_dict 转成json字符串
-        f.write(f"{time}:{json.dumps(round_user_betinfo, cls=UserEncoder)}\n")
-    round_user_betinfo.clear()
+    await write_message_2_log_file(json.dumps(round_option_info, cls=BetOptionEncoder))
+    await write_message_2_log_file(data)
     init_round_option_info()
+    await judge_auto_out_and_int(broadcast_func)
 
 
 #     计算所有组合的可能性及其赔付金额
@@ -185,54 +183,33 @@ async def bankerSettlement(current_round_income, option_results):
 
 
 #     玩家结算统计方法
-async def playerSettlement(option_results):
-    # 玩家结算
-    try:
-        for user in round_user_betinfo.values():
-            for option in user.betOptionAmounts:
-                open_result = next(filter(lambda x: x["option"] == option, option_results))
-                odds_rate = round_option_info[option].odds
-                if open_result is not None and open_result["result"] == 1:
-                    user.finance += user.betOptionAmounts[option] * odds_rate
-                else:
-                    user.finance -= user.betOptionAmounts[option]
-    except Exception as e:
-        pass
+# async def playerSettlement(option_results):
+#     # 玩家结算
+#     try:
+#         for user in round_user_betinfo.values():
+#             for option in user.betOptionAmounts:
+#                 open_result = next(filter(lambda x: x["option"] == option, option_results))
+#                 odds_rate = round_option_info[option].odds
+#                 if open_result is not None and open_result["result"] == 1:
+#                     user.finance += user.betOptionAmounts[option] * odds_rate
+#                 else:
+#                     user.finance -= user.betOptionAmounts[option]
+#     except Exception as e:
+#         pass
 
 
 async def kickNotify(data, broadcast_func):
     print(f"被踢下线了: {data}")
     await broadcast_func('''CMD:
-                setTimeout(function(){
-                    let btnDownNode = cc.find("Layer/PushNotice_panel/close_button");
-                    if (btnDownNode && btnDownNode.getComponent(cc.Button)) {
-                        btnDownNode.getComponent(cc.Button).clickEvents[0].emit([btnDownNode]);
-                    } else {
-                        console.error("节点未找到或节点上没有cc.Button组件");
-                    }
-                },3000);
-                
-                setTimeout(function(){
-                
-                   let btnDownNode = cc.find("Canvas/container/content/smallGame/createScrollView/view/cotent/row1/pokerNode/porkermaster/allHand");
-                    if (btnDownNode && btnDownNode.getComponent(cc.Button)) {
-                        btnDownNode.getComponent(cc.Button).clickEvents[0].emit([btnDownNode]);
-                    } else {
-                        console.error("没有找到扑克大师游戏节点");
-                    }
-                    
-                    // 点击扑克大师游戏线路1
-                    let pokerMasterGameLine1 = cc.find("Canvas/container/content/smallGame/New Node/listPokerMasterContent/main/view/content/item/main");
-                    if (pokerMasterGameLine1 && pokerMasterGameLine1.getComponent(cc.Button)) {
-                        pokerMasterGameLine1.getComponent(cc.Button).clickEvents[0].emit([pokerMasterGameLine1]);
-                    } else {
-                        console.error("未找到扑克大师游戏游戏节点1");
-                    }
-                },5000);
+                   setTimeout(function(){
+                        window.HMFExtension.openPokerMasterGameWithRoomId("716619","")
+                        lws.send("====>>>>被踢后3秒自动进入716619房间");
+                    },3000);//被踢后3秒后自动进入
             ''')
 
 
-def ShowOddsNotify(data):
+async def ShowOddsNotify(data):
+    # await write_message_2_log_file(data)
     option_odds = data["option_odds"]
     for optionInfo in option_odds:
         option_ = optionInfo["option"]
@@ -244,24 +221,25 @@ def ShowOddsNotify(data):
 
 
 async def gameDataSynNotify(data):
+    # await write_message_2_log_file(data)
     # print(f"同步游戏数据: {data}")
-    sync_user = User(1, DATA_SYN_NOTIFY_UID, 0)
+    # sync_user = User(1, DATA_SYN_NOTIFY_UID, 0)
     for optionInfo in data["optionInfo"]:
         option_ = optionInfo["option"]
         odds_ = optionInfo["odds"] / 100
 
         limit_red_ = optionInfo["limitRed"]
         total_bet_ = optionInfo["totalBet"]
-        sync_user.betAmount += total_bet_
+        # sync_user.betAmount += total_bet_
         # 打印信息
         print(f"同步下注选项: {option_}, 赔率: {odds_}, 限红: {limit_red_}, 总下注: {total_bet_}")
         round_option_info[option_] = BetOption(option_, odds_, limit_red_, total_bet_)
         # 虚拟用户,用来记录同步下来的下注数据,后续用于赔付
-        sync_user.betOptionAmounts[option_] = total_bet_
-        round_user_betinfo[DATA_SYN_NOTIFY_UID] = sync_user
+        # sync_user.betOptionAmounts[option_] = total_bet_
+        # round_user_betinfo[DATA_SYN_NOTIFY_UID] = sync_user
 
     # 同步的数据应该包含了所有的下注选项,所以这里直接清空,但是这样统计个人数据的时候,就会有点出入
-    round_user_betinfo.clear()
+    # round_user_betinfo.clear()
     print(f"同步后下注信息:", list(map(lambda x: str(x), round_option_info.values())))
 
 
@@ -279,22 +257,22 @@ async def betNotify(data):
     uid = data["uid"]
     option = data["detail"]["option"]
     bet_amount = data["detail"]["betAmount"]
-    # 获取用户信息
-    user = round_user_betinfo.get(uid)
-    if user is None:
-        # 如果用户信息不存在,创建一个新的User对象
-        user = User(0, "", 0)
-        round_user_betinfo[uid] = user
-    # 更新用户信息
-    user.bet_count += 1
-    user.uid = uid
-    user.betAmount += bet_amount
-    # 更新本轮下注选项的金额
-    user.betOptionAmounts[option] += bet_amount
+    # # # 获取用户信息
+    # # user = round_user_betinfo.get(uid)
+    # # if user is None:
+    # #     # 如果用户信息不存在,创建一个新的User对象
+    # #     user = User(0, "", 0)
+    # #     round_user_betinfo[uid] = user
+    # # # 更新用户信息
+    # # user.bet_count += 1
+    # # user.uid = uid
+    # # user.betAmount += bet_amount
+    # # # 更新本轮下注选项的金额
+    # user.betOptionAmounts[option] += bet_amount
     # 更新本轮全部选项的金额
     round_option_info[option].total_bet += bet_amount
-    print(f"用户{uid}下注次数: {user.bet_count}, 总金额: {user.betAmount}")
-    round_user_betinfo[uid] = user
+    # print(f"用户{uid}下注次数: {user.bet_count}, 总金额: {user.betAmount}")
+    # round_user_betinfo[uid] = user
 
 
 def parse_message(message):

+ 17 - 6
yyyy_js/python-server/pokermaster/WebServer.py

@@ -6,13 +6,23 @@ import websockets
 import logging
 import threading
 
-from pokermaster.PokerMasterDataProccesser import deal_message
+from pokermaster.PokerMasterDataProccesser import deal_message, write_message_2_log_file
 
 logging.basicConfig(level=logging.INFO)
 
 ip = "192.168.137.1"
 port = 9999
 
+
+# 从同目录下读取props.properties文件,获取配置(ip、port)信息
+with open("../props.properties", "r") as f:
+    props = f.readlines()
+    for prop in props:
+        if prop.startswith("ip"):
+            ip = prop.split("=")[1].strip()
+        if prop.startswith("port"):
+            port = prop.split("=")[1].strip()
+
 connected_clients = set()
 
 
@@ -20,9 +30,7 @@ async def echo(websocket, path):
     connected_clients.add(websocket)
     try:
         async for message in websocket:
-            # with open("ws.log", "a") as f:
-            #     time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
-            #     f.write(f"{time}:{message}\n")
+            # await write_message_2_log_file(message)
             await deal_message(message, broadcast)
             # print(f"Received message: {message}")
         await websocket.send("Server says: 你好,服务端收到,连接建立成功")
@@ -36,7 +44,10 @@ async def echo(websocket, path):
 
 async def broadcast(message):
     if connected_clients:
-        await asyncio.wait([client.send(message) for client in connected_clients])
+        # 将协程转换为Task对象,并收集到一个列表中
+        tasks = [asyncio.create_task(client.send(message)) for client in connected_clients]
+        # 等待所有任务完成
+        await asyncio.wait(tasks)
     else:
         print("No clients are connected.")
 
@@ -58,7 +69,7 @@ def start_cli(loop):
 
 
 def sendJsCommand(loop):
-    with open("script.js", "r", encoding="utf-8") as file:
+    with open("../script.js", "r", encoding="utf-8") as file:
         script_content = file.read()
     # 去除script中注释的行注释或者块注释
     script_content = re.sub(r"//.*?$", "", script_content, flags=re.MULTILINE)  # 去除行注释

+ 21 - 16
yyyy_js/python-server/script.js

@@ -185,39 +185,44 @@ function hookPokerMasterSocket(){
 function openPokerMasterGameWithRoomId(){
  // 确保HMFExtension已经加载和定义
     if (window.HMFExtension && typeof window.HMFExtension.openPokerMasterGameWithRoomId === "function") {
-        let originFunc = window.HMFExtension.openPokerMasterGameWithRoomId;
-        // 调用函数并传递roomId和exitWhere参数
-        var roomId = 716619; // 示例房间ID
-//        var exitWhere = "lobby"; // 示例退出位置
-//        window.HMFExtension.openPokerMasterGameWithRoomId=function(roomId, exitWhere){
-//            lws.send("====>>>>重写了openPokerMasterGameWithRoomId,看看房间号是什么东西:"+roomId);
-//            lws.send("====>>>>重写了openPokerMasterGameWithRoomId,看看房间号是什么东西:"+exitWhere);
-//            originFunc.call(window.HMFExtension,roomId,exitWhere);
-//        }
-        originFunc.call(window.HMFExtension,roomId,"");
+//        let originFunc = window.HMFExtension.openPokerMasterGameWithRoomId;
+//        // 调用函数并传递roomId和exitWhere参数
+//        var roomId = 716619; // 示例房间ID
+////        var exitWhere = "lobby"; // 示例退出位置
+////        window.HMFExtension.openPokerMasterGameWithRoomId=function(roomId, exitWhere){
+////            lws.send("====>>>>重写了openPokerMasterGameWithRoomId,看看房间号是什么东西:"+roomId);
+////            lws.send("====>>>>重写了openPokerMasterGameWithRoomId,看看房间号是什么东西:"+exitWhere);
+////            originFunc.call(window.HMFExtension,roomId,exitWhere);
+////        }
+//        originFunc.call(window.HMFExtension,roomId,"");
+        window.HMFExtension.openPokerMasterGameWithRoomId("716619","")
 
 //        setTimeout(function(){
 //            window.__require("PokerMasterHallSocket").PokerMasterHallSocket.getInstance().requestLeaveRoom();
-//        },16000);
+//        },10000);
     } else {
         console.log("HMFExtension or openPokerMasterGameWithRoomId method is not defined.");
     }
 }
-openPokerMasterGameWithRoomId();
+//openPokerMasterGameWithRoomId();
+window.HMFExtension.openPokerMasterGameWithRoomId("716619","")
+//window.__require("PokerMasterHallSocket").PokerMasterHallSocket.getInstance().requestLeaveRoom();
+
+//window.__require("PokerMasterHallSocket").PokerMasterHallSocket.getInstance().requestLeaveRoom();
 
 //function getData() {
 //    var t = {
-//        userId: 22542051,
+//        userId: 6002323,
 //        roomId: 716619,
-//        targetUserId: 5741489,
-//        playType: 0
+//        targetUserId: 2506189,
+//        playType:1
 //    };
 //    HMFHTTPClient.sendByPromise(new HMFRequest("/battle/getUserInfo", t)).then(function (data) {
 //        console.log("====>>>>获取到的数据:", data);
 //        lws.send("====>>>>获取到的数据:"+JSON.stringify(data));
 //    });
 //}
-
+//
 //getData();
 
 console.log("====>>>>远程脚本加载结束");