PokerMasterDataProccesser.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import datetime
  2. import json
  3. import logging
  4. from itertools import product
  5. # 所有的下注选项
  6. OPTIONS = [101, 102, 103, 301, 302, 303, 304, 305]
  7. # 下注选项
  8. class BetOption:
  9. def __init__(self, option, odds, limit, total_bet=0):
  10. self.option = option
  11. if odds == 0:
  12. self.odds = 1
  13. else:
  14. self.odds = odds
  15. self.limitRed = limit
  16. self.total_bet = total_bet
  17. def __str__(self):
  18. return (f"BetOption(option={self.option}, odds={self.odds}, "
  19. f"limitRed={self.limitRed}, totalBet={self.total_bet})")
  20. # 用户信息
  21. class User:
  22. # 对应option的下注金额
  23. def __init__(self, bet_count, uid, amount):
  24. self.bet_count = bet_count
  25. self.uid = uid
  26. self.betAmount = amount
  27. self.finance = 0
  28. self.betOptionAmounts = {option: 0 for option in OPTIONS}
  29. class UserEncoder(json.JSONEncoder):
  30. def default(self, obj):
  31. if isinstance(obj, User):
  32. return {"uid": obj.uid, "bet_count": obj.bet_count, "betAmount": obj.betAmount, "finance": obj.finance}
  33. # 让基类的 default 方法抛出 TypeError
  34. return json.JSONEncoder.default(self, obj)
  35. def init_round_option_info():
  36. global round_option_info
  37. round_option_info = {option: BetOption(option, 0, 0) for option in OPTIONS}
  38. # 用于存储User对象的用户信息和次数,key为用户ID,value为User对象
  39. round_user_betinfo = {}
  40. round_option_info = {}
  41. # 本轮选项赔率和下注金额
  42. init_round_option_info()
  43. # 庄家的钱
  44. banker_finance = 0
  45. # 虚拟一个用户,用来记录同步下来的下注数据,不然结算会异常,但是这样统计个人数据的时候,就会有点出入,
  46. # 没办法,因为会被定时踢出
  47. DATA_SYN_NOTIFY_UID = -9999
  48. async def deal_message(message, broadcast_func):
  49. try:
  50. msg_type, data = parse_message(message)
  51. if msg_type == "BetNotify":
  52. await betNotify(data)
  53. elif msg_type == "GameDataSynNotify":
  54. await gameDataSynNotify(data)
  55. elif msg_type == "ShowOddsNotify":
  56. await ShowOddsNotify(data)
  57. elif msg_type == "KickNotify":
  58. await kickNotify(data, broadcast_func)
  59. elif msg_type == "GameRoundEndNotify":
  60. await gameRoundEndNotify(data)
  61. elif msg_type == "MergeAutoBetNotify":
  62. await MergeAutoBetNotify(data)
  63. else:
  64. logging.info(f"Received message: {message}")
  65. except Exception as e:
  66. logging.info(f"Received message: {message}")
  67. async def gameRoundEndNotify(data):
  68. global banker_finance
  69. time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  70. print(f"{time}:收到结束下注GameRoundEndNotify")
  71. # 开始结算
  72. # 本轮收入
  73. current_round_income = 0
  74. # 本轮总下注金额
  75. current_round_bet_amount = 0
  76. for option in round_option_info.values():
  77. current_round_bet_amount += option.total_bet
  78. current_round_income = current_round_bet_amount
  79. # 开奖结果
  80. option_results = data["optionResult"]
  81. win_option = [x["option"] for x in option_results if x["result"] == 1]
  82. print(f"本轮中奖选项: {win_option}")
  83. # 庄家结算
  84. current_round_income = await bankerSettlement(current_round_income, option_results)
  85. # 玩家结算
  86. await playerSettlement(option_results)
  87. await win_option_combo_analysis(current_round_bet_amount, win_option)
  88. banker_finance += current_round_income
  89. print(
  90. f"庄家金币: {round(banker_finance / 100, 2)}¥ 本轮总下注{round(current_round_bet_amount / 100, 2)}¥ 收入: {round(current_round_income / 100, 2)}¥")
  91. # 格式化一下,避免数字位数导致各种缩进
  92. with open("庄家盈亏记录.txt", "a", encoding="utf-8") as f:
  93. finalxx = f"{time}:庄家金币: {banker_finance / 100}¥ 本轮总下注{current_round_bet_amount / 100}¥ 收入: {current_round_income / 100}¥"
  94. print(finalxx)
  95. f.write(finalxx + "\n")
  96. # 每把结束存储数据,然后清空数据
  97. with open("用户记录.txt", "a", encoding="utf-8") as f:
  98. # 将user_dict 转成json字符串
  99. f.write(f"{time}:{json.dumps(round_user_betinfo, cls=UserEncoder)}\n")
  100. round_user_betinfo.clear()
  101. init_round_option_info()
  102. # 计算所有组合的可能性及其赔付金额
  103. async def win_option_combo_analysis(current_round_bet_amount, win_option):
  104. # 统计所有结果的可能性
  105. try:
  106. win_npc = {key: value for key, value in round_option_info.items() if key in [101, 102, 103]}
  107. win_card = {key: value for key, value in round_option_info.items() if key in [301, 302, 303, 304, 305]}
  108. # 计算所有组合的可能性及其赔付金额
  109. combinations = list(product(win_npc.keys(), win_card.keys()))
  110. # 计算每个组合的赔付金额
  111. combination_payouts = []
  112. for npc_key, card_key in combinations:
  113. npc_info = win_npc[npc_key]
  114. card_info = win_card[card_key]
  115. payout = (npc_info.odds * npc_info.total_bet) + (card_info.odds * card_info.total_bet)
  116. combination_payouts.append({
  117. "combo": f"{npc_key}x{card_key}",
  118. "payout": payout,
  119. "open": npc_key in win_option and card_key in win_option
  120. })
  121. # 按赔付金额排序
  122. sorted_combinations = sorted(combination_payouts, key=lambda x: x["payout"], reverse=True)
  123. # 输出排序后的组合和对应的赔付金额
  124. with open("庄家盈亏记录.txt", "a", encoding="utf-8") as f:
  125. label = f"{'标记':<4} {'组合':<10} {'赔付':<15} {'收入':<10}\n"
  126. print(label)
  127. f.write(label)
  128. for item in sorted_combinations:
  129. combo_key = item["combo"]
  130. payout = item["payout"]
  131. income = round((current_round_bet_amount - payout) / 100, 2)
  132. badge = "√" if item["open"] else "×"
  133. combos = f"{badge:<4} {combo_key:<10} {round(payout / 100, 2):<15}¥ {income:<10}¥\n"
  134. print(combos)
  135. f.write(combos)
  136. except Exception as e:
  137. print(e)
  138. # 庄家结算统计方法
  139. async def bankerSettlement(current_round_income, option_results):
  140. for open_result in option_results:
  141. # 开奖结果
  142. option = open_result["option"]
  143. result = open_result["result"]
  144. # 这个是下注的选项信息
  145. option_info_option_ = round_option_info[option]
  146. odds_rate = option_info_option_.odds
  147. if result == 1: # 证明这个选项中奖了
  148. # 庄家结算
  149. final_out = option_info_option_.total_bet * odds_rate
  150. current_round_income -= final_out
  151. print(
  152. f"选项{option}中奖了, 赔率{odds_rate}, 该选项总下注{round(option_info_option_.total_bet / 100, 2)}¥, 赔付了{round(final_out / 100, 2)}¥")
  153. return current_round_income
  154. # 玩家结算统计方法
  155. async def playerSettlement(option_results):
  156. # 玩家结算
  157. try:
  158. for user in round_user_betinfo.values():
  159. for option in user.betOptionAmounts:
  160. open_result = next(filter(lambda x: x["option"] == option, option_results))
  161. odds_rate = round_option_info[option].odds
  162. if open_result is not None and open_result["result"] == 1:
  163. user.finance += user.betOptionAmounts[option] * odds_rate
  164. else:
  165. user.finance -= user.betOptionAmounts[option]
  166. except Exception as e:
  167. pass
  168. async def kickNotify(data, broadcast_func):
  169. print(f"被踢下线了: {data}")
  170. await broadcast_func('''CMD:
  171. setTimeout(function(){
  172. let btnDownNode = cc.find("Layer/PushNotice_panel/close_button");
  173. if (btnDownNode && btnDownNode.getComponent(cc.Button)) {
  174. btnDownNode.getComponent(cc.Button).clickEvents[0].emit([btnDownNode]);
  175. } else {
  176. console.error("节点未找到或节点上没有cc.Button组件");
  177. }
  178. },3000);
  179. setTimeout(function(){
  180. let btnDownNode = cc.find("Canvas/container/content/smallGame/createScrollView/view/cotent/row1/pokerNode/porkermaster/allHand");
  181. if (btnDownNode && btnDownNode.getComponent(cc.Button)) {
  182. btnDownNode.getComponent(cc.Button).clickEvents[0].emit([btnDownNode]);
  183. } else {
  184. console.error("没有找到扑克大师游戏节点");
  185. }
  186. // 点击扑克大师游戏线路1
  187. let pokerMasterGameLine1 = cc.find("Canvas/container/content/smallGame/New Node/listPokerMasterContent/main/view/content/item/main");
  188. if (pokerMasterGameLine1 && pokerMasterGameLine1.getComponent(cc.Button)) {
  189. pokerMasterGameLine1.getComponent(cc.Button).clickEvents[0].emit([pokerMasterGameLine1]);
  190. } else {
  191. console.error("未找到扑克大师游戏游戏节点1");
  192. }
  193. },5000);
  194. ''')
  195. def ShowOddsNotify(data):
  196. option_odds = data["option_odds"]
  197. for optionInfo in option_odds:
  198. option_ = optionInfo["option"]
  199. odds_ = optionInfo["odds"] / 100
  200. limit_red_ = optionInfo["limitRed"]
  201. # 打印信息
  202. print(f"选项: {option_}, 赔率: {odds_}, 限红: {limit_red_}, 总下注: {0}")
  203. round_option_info[option_] = BetOption(option_, odds_, limit_red_, 0)
  204. async def gameDataSynNotify(data):
  205. # print(f"同步游戏数据: {data}")
  206. sync_user = User(1, DATA_SYN_NOTIFY_UID, 0)
  207. for optionInfo in data["optionInfo"]:
  208. option_ = optionInfo["option"]
  209. odds_ = optionInfo["odds"] / 100
  210. limit_red_ = optionInfo["limitRed"]
  211. total_bet_ = optionInfo["totalBet"]
  212. sync_user.betAmount += total_bet_
  213. # 打印信息
  214. print(f"同步下注选项: {option_}, 赔率: {odds_}, 限红: {limit_red_}, 总下注: {total_bet_}")
  215. round_option_info[option_] = BetOption(option_, odds_, limit_red_, total_bet_)
  216. # 虚拟用户,用来记录同步下来的下注数据,后续用于赔付
  217. sync_user.betOptionAmounts[option_] = total_bet_
  218. round_user_betinfo[DATA_SYN_NOTIFY_UID] = sync_user
  219. # 同步的数据应该包含了所有的下注选项,所以这里直接清空,但是这样统计个人数据的时候,就会有点出入
  220. round_user_betinfo.clear()
  221. print(f"同步后下注信息:", list(map(lambda x: str(x), round_option_info.values())))
  222. async def MergeAutoBetNotify(data):
  223. print("收到合并通知")
  224. bet_notifys = data["notify"]
  225. for bet_notify in bet_notifys:
  226. await betNotify(bet_notify)
  227. async def betNotify(data):
  228. # {"uid":4174549,"detail":{"option":302,"betAmount":1000,"auto":false,"is_shot":false,"win_amt":0,"odds":0,"betGameCoin":0},"curCoin":767943,"selfBet":1000,"totalBet":67000,"curUsdt":0}
  229. # print(f"下注: {data}")
  230. # 获取用户ID
  231. uid = data["uid"]
  232. option = data["detail"]["option"]
  233. bet_amount = data["detail"]["betAmount"]
  234. # 获取用户信息
  235. user = round_user_betinfo.get(uid)
  236. if user is None:
  237. # 如果用户信息不存在,创建一个新的User对象
  238. user = User(0, "", 0)
  239. round_user_betinfo[uid] = user
  240. # 更新用户信息
  241. user.bet_count += 1
  242. user.uid = uid
  243. user.betAmount += bet_amount
  244. # 更新本轮下注选项的金额
  245. user.betOptionAmounts[option] += bet_amount
  246. # 更新本轮全部选项的金额
  247. round_option_info[option].total_bet += bet_amount
  248. print(f"用户{uid}下注次数: {user.bet_count}, 总金额: {user.betAmount}")
  249. round_user_betinfo[uid] = user
  250. def parse_message(message):
  251. # 分割消息类型和JSON字符串
  252. msg_type, json_str = message.split(':', 1)
  253. # 将JSON字符串转换为字典
  254. data = json.loads(json_str)
  255. # 返回解析结果
  256. return msg_type, data